Typespecial.php 55 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385
  1. <?php
  2. Lib::loadClass('TypespecialBase');
  3. /**
  4. * Zasoby:
  5. * DATABASE
  6. * TABLE
  7. * KOMORKA
  8. * TYPESPECIAL
  9. * PARAM_IN
  10. * PARAM_OUT
  11. * DANE ALIAS do komórki z innej tabeli
  12. * PARAM_WHERE
  13. *
  14. * example:
  15. * TYPESPECIAL 'id_project'
  16. * PARAM_IN ALIAS_ID -> 1260 -> IN7_DZIENNIK_KORESP.ID_PROJECT
  17. * PARAM_OUT
  18. * DANE ALIAS do komórki z innej tabeli
  19. *
  20. *** TODO: new struct, TODO: remove above
  21. * TYPESPECIAL
  22. * PARAM_OUT format: dla PARAM_IN = vcol pokzać listę, a dla PARAM_IN = col i perm W pokazać select/search
  23. * PARAM_IN alias do komórki dla której ma się pokazać PARAM_OUT
  24. * DANE alias do komórki/zmiennej z danymi do podstawienia
  25. * PARAM_WHERE sql params - join tables
  26. *
  27. * $_SESSION['Typespecial_Cache'] = array(
  28. * map = array(
  29. * fieldID => typesiecialID
  30. * ),
  31. * typesiecialID => Typespecial Data
  32. * )
  33. *
  34. * Typespecial types:
  35. * - typespecial function for form fields in edit, create
  36. * - typespecial view function for virtual fields
  37. *
  38. * $_SESSION['USERS2_MARKETING_COLUMN']['RELATIVEDB']['SRC_COLUMN']['INTERNET_STATUS']="temp_USERS2_INTERNET_STATUS";
  39. * $_SESSION['USERS2_MARKETING_COLUMN']['RELATIVEDB']['TRG_COLUMN']['INTERNET_STATUS']="temp_USERS2_INTERNET_STATUS.USERS2_INTERNET_STATUS";
  40. * $_SESSION['USERS2_MARKETING_COLUMN']['RELATIVEDB']['TRG_COLUMN_NAME']['INTERNET_STATUS']="temp_USERS2_INTERNET_STATUS.USERS2_INTERNET_STATUS";
  41. * $_SESSION['USERS2_MARKETING_COLUMN']['RELATIVEDB']['JOINQUERY']['temp_USERS2_INTERNET_STATUS']="LEFT JOIN temp_USERS2_INTERNET_STATUS as temp_USERS2_INTERNET_STATUS on temp_USERS2_INTERNET_STATUS.S_ADDRESS_STREET=USERS2_MARKETING.S_ADDRESS_STREET ";
  42. *
  43. * used `CRM_LISTA_ZASOBOW`.`TYPE`:
  44. 'TYPESPECIAL'
  45. 'PARAM_IN'
  46. 'PARAM_OUT'
  47. 'PARAM_WHERE'
  48. 'SQL_LIKE' => "`fld` LIKE '{param}'"
  49. 'SQL_LIKE_PR' => "`fld` LIKE '%{param}%'"
  50. 'SQL_NOT_LIKE' => "`fld` NOT LIKE '{param}'"
  51. 'SQL_EQUAL' => "`fld`='{param}'"
  52. 'SQL_NOT_EQUAL' => "`fld`!='{param}'"
  53. 'SQL_IS_EMPTY' => "`fld`=''"
  54. 'SQL_IS_NOT_EMPTY' => "`fld`!=''"
  55. 'SQL_IS_NULL' => "`fld` IS NULL"
  56. 'SQL_IS_NOT_NULL' => "`fld` IS NOT NULL"
  57. 'SQL_IN' => "`fld` IN({params})"
  58. 'SQL_NOT_IN' => "`fld` NOT IN({params})"
  59. 'SQL_BETWEEN' => "`fld` BETWEEN {params1} AND {params2}"
  60. 'SQL_NOT_BETWEEN' => "`fld` NOT BETWEEN {params1} AND {params2}"
  61. *
  62. *
  63. 'TYPESPECIAL','PARAM_IN','PARAM_OUT','PARAM_WHERE','SQL_LIKE','SQL_LIKE_PR','SQL_NOT_LIKE','SQL_EQUAL','SQL_NOT_EQUAL','SQL_IS_EMPTY','SQL_IS_NOT_EMPTY','SQL_IS_NULL','SQL_IS_NOT_NULL','SQL_IN','SQL_NOT_IN','SQL_BETWEEN','SQL_NOT_BETWEEN'
  64. 'KONTO-KSIEGOWE-OLD','KONTO-KSIEGOWE-ZESPOL','KONTO-KSIEGOWE','KONTO-KSIEGOWE-GRUPA','DANE','WYNIK_ZAPYTANIA','NARZEDZIE','PLIK','ZASOB_PLIKOW','TABELA','KOMORKA','BAZA_DANYCH','DATABASE_MYSQL','TRIGGER','SERWER','SERWER_PORT','DOKUMENTY','MAGAZYN','SEGREGATOR','POMIESZCZENIE','MATERIAL_REKLAMOWY','DZIAL','STANOWISKO','INNE','CZYNNOSC','PODMIOT','ALARM-SATEL','DOSTEP-ZAMEK','DOSTEP-KLUCZ','NOTATKA','URZADZENIE','TELBOX','SZAFA','REJESTRATOR','KAMERA','PIECZATKA','URL','URL_REQUEST_RESPOND','TYPESPECIAL','PARAM_IN','PARAM_OUT','PARAM_WHERE','SQL_LIKE','SQL_LIKE_PR','SQL_NOT_LIKE','SQL_EQUAL','SQL_NOT_EQUAL','SQL_IS_EMPTY','SQL_IS_NOT_EMPTY','SQL_IS_NULL','SQL_IS_NOT_NULL','SQL_IN','SQL_NOT_IN','SQL_BETWEEN','SQL_NOT_BETWEEN',''
  65. */
  66. class Typespecial extends TypespecialBase {
  67. public $fldID;
  68. public $param_out;
  69. public $filters;
  70. public $fldAliasList;
  71. public $tblAliasList;
  72. public $sqlQuery;
  73. private $_fldName;// @use getFieldName()
  74. public function __construct($fldID, $fldName = '', $cacheData = array()) {
  75. $this->fldID = $fldID;
  76. $this->param_out = V::get('param_out', null, $cacheData);
  77. $this->sqlQuery = V::get('sqlQuery', null, $cacheData);
  78. if (empty($this->sqlQuery->from) && !empty($this->sqlQuery->form)) {
  79. $this->sqlQuery->from = $this->sqlQuery->form;
  80. unset($this->sqlQuery->form);
  81. }
  82. $this->tblAliasList = V::get('tblAliasList', null, $cacheData);
  83. if(V::get('DBG_TS', 0, $_GET) > 3){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">Typespecial cacheData (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($cacheData);echo'</pre>';}
  84. $this->_fldName = $fldName;
  85. }
  86. public function validate() {
  87. // TODO: validate cache data
  88. // TODO: check if has parse errors
  89. // TODO: try to run sql and check if has error
  90. return true;
  91. }
  92. /**
  93. * @returns virtual fields id list
  94. */
  95. public static function initFields($fieldIds) {
  96. if (empty($fieldIds)) {
  97. return;
  98. }
  99. $db = DB::getDB();
  100. $typeSpecials = array();
  101. $sql = "select z.`ID`
  102. , z.`ALIAS_ID` as fieldID
  103. , zpp.`ID` as TYPE_ID
  104. from `CRM_LISTA_ZASOBOW` as z
  105. join `CRM_LISTA_ZASOBOW` as zp on(zp.`ID`=z.`PARENT_ID`)
  106. join `CRM_LISTA_ZASOBOW` as zpp on(zpp.`ID`=zp.`PARENT_ID`)
  107. where zpp.`TYPE`='TYPESPECIAL'
  108. and zpp.`A_STATUS` in('WAITING','NORMAL')
  109. and zp.`TYPE`='PARAM_OUT'
  110. and z.`TYPE`='PARAM_IN'
  111. and z.`ALIAS_ID` in(" . implode(",", $fieldIds) . ")
  112. ";
  113. if(V::get('DBG_TS', 0, $_GET) > 0){echo'<pre style="max-height:200px;overflow:auto;border:1px solid orange;text-align:left;">sql (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($sql);echo'</pre>';}
  114. $res = $db->query($sql);
  115. while ($r = $db->fetch($res)) {
  116. $r->params_out = array();
  117. $r->filters = array();
  118. $typeSpecials[$r->TYPE_ID] = $r;
  119. $typeSpecials_2[$r->fieldID] = $r;
  120. $_SESSION['Typespecial_Cache']['map'][$r->fieldID] = $r->TYPE_ID;
  121. $_SESSION['Typespecial_Cache']['map_param_out'][$r->fieldID] = $r->TYPE_ID;
  122. }
  123. if(V::get('DBG_TS', 0, $_GET) > 0){echo'<pre style="max-height:200px;overflow:auto;border:1px solid orange;text-align:left;">typeSpecials (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($typeSpecials);echo'</pre>';}
  124. if(V::get('DBG_TS', 0, $_GET) > 0){echo'<pre style="max-height:200px;overflow:auto;border:1px solid blue;text-align:left;">typeSpecials_2 (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($typeSpecials_2);echo'</pre>';}
  125. if (empty($typeSpecials)) {
  126. return;
  127. }
  128. $sql = "select z.`ID`
  129. , z.`ALIAS_ID`
  130. , z.`TYPE`
  131. , z.`DESC`
  132. , za.`DESC` as ALIAS_DESC
  133. , za.`PARENT_ID` as ALIAS_PARENT_ID
  134. , zp.`ID` as PARAM_ID
  135. , zp.`ALIAS_ID` as ALIAS_ID_RETURN
  136. , zp.`DESC` as PARAM_DESC
  137. , zp.`PARENT_ID` as TYPE_ID
  138. , zp.`TYPE` as TYPE_TYPE
  139. , za.`TYPE` as ALIAS_TYPE
  140. from `CRM_LISTA_ZASOBOW` as z
  141. join `CRM_LISTA_ZASOBOW` as zp on(zp.`ID`=z.`PARENT_ID`)
  142. left join `CRM_LISTA_ZASOBOW` as za on(za.`ID`=z.`ALIAS_ID`)
  143. where zp.`TYPE` in('PARAM_OUT', 'PARAM_WHERE')
  144. and z.`TYPE` not in('PARAM_IN')
  145. and zp.`PARENT_ID` in(" . implode(",", array_keys($typeSpecials)) . ")
  146. ";
  147. if(V::get('DBG_TS', 0, $_GET) > 0){echo'<pre style="max-height:200px;overflow:auto;border:1px solid orange;text-align:left;">sql (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($sql);echo'</pre>';}
  148. $res = $db->query($sql);
  149. while ($r = $db->fetch($res)) {
  150. if ($r->TYPE_TYPE == 'PARAM_OUT') {
  151. $typeSpecials[$r->TYPE_ID]->params_out[$r->PARAM_ID][] = $r;
  152. }
  153. else {
  154. if (!array_key_exists($r->PARAM_ID, $typeSpecials[$r->TYPE_ID]->filters)) {
  155. /*
  156. (
  157. [ID] => 4526
  158. [ALIAS_ID] => 1123
  159. [TYPE] => DANE
  160. [DESC] => IN
  161. [ALIAS_DESC] => A_STATUS
  162. [PARAM_ID] => 4531
  163. [ALIAS_ID_RETURN] => 0
  164. [PARAM_DESC] => AND
  165. [TYPE_ID] => 4519
  166. [TYPE_TYPE] => PARAM_WHERE
  167. )
  168. */
  169. $typeSpecials[$r->TYPE_ID]->filters[$r->PARAM_ID] = new stdClass();
  170. $typeSpecials[$r->TYPE_ID]->filters[$r->PARAM_ID]->filtersByID = array();
  171. $typeSpecials[$r->TYPE_ID]->filters[$r->PARAM_ID]->treeFlat = array();
  172. $typeSpecials[$r->TYPE_ID]->filters[$r->PARAM_ID]->ID = $r->PARAM_ID;
  173. $typeSpecials[$r->TYPE_ID]->filters[$r->PARAM_ID]->ALIAS_ID = $r->ALIAS_ID_RETURN;
  174. $typeSpecials[$r->TYPE_ID]->filters[$r->PARAM_ID]->PARAM_DESC = $r->PARAM_DESC;
  175. $typeSpecials[$r->TYPE_ID]->filters[$r->PARAM_ID]->FLTR_ID = $r->ID;
  176. }
  177. $param = new stdClass();
  178. $param->ID = $r->ID;
  179. $param->PARENT_ID = 0;
  180. $param->ALIAS_ID = $r->ALIAS_ID;
  181. $param->ALIAS_PARENT_ID = $r->ALIAS_PARENT_ID;
  182. $param->ALIAS_TYPE = $r->ALIAS_TYPE;
  183. $param->TYPE = $r->TYPE;
  184. $param->DESC = $r->DESC;
  185. $param->ALIAS_DESC = $r->ALIAS_DESC;
  186. $typeSpecials[$r->TYPE_ID]->filters[$r->PARAM_ID]->filtersByID[$r->ID] = $param;
  187. }
  188. }
  189. if(V::get('DBG_TS', 0, $_GET) > 0){echo'<pre style="max-height:200px;overflow:auto;border:1px solid orange;text-align:left;">typeSpecials (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($typeSpecials);echo'</pre>';}
  190. $typeSpecialsByField = array();// table, db info
  191. $aliasesMap = array();
  192. $filtersByField = array();// filters info
  193. // create sql by params, filters
  194. /*
  195. [ID] => 4527
  196. [ALIAS_ID] => 0
  197. [TYPE] => DANE
  198. [DESC] => NORMAL
  199. [ALIAS_DESC] =>
  200. [PARAM_ID] => 4526
  201. [PARAM_DESC] => IN
  202. [TYPE_ID] => 4519
  203. [TYPE_TYPE] => DANE
  204. */
  205. foreach ($typeSpecials as $kTypeID => $vType) {
  206. $typeSpecialsByField[$vType->fieldID] = new Typespecial($vType->fieldID);
  207. $params = $vType->params_out;
  208. foreach ($params as $kParamID => $vParams) {
  209. $vParam = reset($vParams);
  210. $typeSpecialsByField[$vType->fieldID]->param_out = new stdClass();
  211. $typeSpecialsByField[$vType->fieldID]->param_out->format = $vParam->PARAM_DESC;
  212. $typeSpecialsByField[$vType->fieldID]->param_out->retID = $vParam->ALIAS_ID_RETURN;
  213. $typeSpecialsByField[$vType->fieldID]->param_out->values = array();
  214. $typeSpecialsByField[$vType->fieldID]->param_out->alias = array();
  215. $typeSpecialsByField[$vType->fieldID]->param_out->exports = array();
  216. }
  217. foreach ($params as $kParamID => $vParams) {
  218. foreach ($vParams as $vParam) {
  219. if ($vParam->TYPE == 'PARAM_EXPORT') {
  220. $typeSpecialsByField[$vType->fieldID]->param_out->exports[$vParam->ALIAS_ID] = $vParam->DESC;
  221. } else {
  222. $typeSpecialsByField[$vType->fieldID]->param_out->values[$vParam->DESC] = $vParam->ALIAS_ID;
  223. $typeSpecialsByField[$vType->fieldID]->param_out->alias[$vParam->ALIAS_ID] = $vParam->ALIAS_DESC;
  224. }
  225. }
  226. }
  227. foreach ($typeSpecialsByField[$vType->fieldID]->param_out->alias as $kParam => $vParam) {
  228. $aliasesMap[$kParam] = $vParam;
  229. }
  230. $filters = $vType->filters;
  231. foreach ($filters as $kFilterID => $vFilters) {
  232. $typeSpecialsByField[$vType->fieldID]->filters[$kFilterID] = $vFilters;
  233. }
  234. }
  235. {// fetch filters recursive
  236. if(V::get('DBG_TS', 0, $_GET) > 0){echo'<pre style="max-height:200px;overflow:auto;border:1px solid orange;text-align:left;">typeSpecialsByField update by filtersTodoIds (F.' . __FUNCTION__ . ':' . __LINE__ . '): '."\n";}
  237. $filtersTodoIds = array();
  238. foreach ($typeSpecialsByField as $kFldID => $vType) {
  239. if (!empty($vType->filters)) {
  240. foreach ($vType->filters as $kFltrID => $vFltr) {
  241. foreach ($vFltr->filtersByID as $kId => $v) {
  242. $filtersTodoIds[$kId] = array('type' => $kFldID, 'filter' => $kFltrID);
  243. }
  244. }
  245. }
  246. }
  247. if(V::get('DBG_TS', 0, $_GET) > 0){echo "filtersTodoIds: [" . implode(",", array_keys($filtersTodoIds)) . "]\n";}
  248. $deepLimit = 3;
  249. for ($i = 0; $i < $deepLimit; $i++) {
  250. if(V::get('DBG_TS', 0, $_GET) > 0){echo "loop i({$i}) filtersTodoIds[" . implode(",", array_keys($filtersTodoIds)) . "] \n";}
  251. if (empty($filtersTodoIds)) {
  252. break;
  253. }
  254. $newFiltersTodoIds = array();
  255. $sql = "select z.`ID`
  256. , z.`ALIAS_ID`
  257. , z.`TYPE`
  258. , z.`DESC`
  259. , z.`PARENT_ID`
  260. , za.`DESC` as ALIAS_DESC
  261. , za.`TYPE` as ALIAS_TYPE
  262. , za.`PARENT_ID` as ALIAS_PARENT_ID
  263. from `CRM_LISTA_ZASOBOW` as z
  264. left join `CRM_LISTA_ZASOBOW` as za on(za.`ID`=z.`ALIAS_ID`)
  265. where
  266. z.`PARENT_ID` in(" . implode(",", array_keys($filtersTodoIds)) . ")
  267. ";
  268. if(V::get('DBG_TS', 0, $_GET) > 0){echo'<pre style="max-height:200px;overflow:auto;border:1px solid orange;text-align:left;display:none">sql (F.' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($sql);echo'</pre>';}
  269. $res = $db->query($sql);
  270. while ($r = $db->fetch($res)) {
  271. $fltr = $filtersTodoIds[$r->PARENT_ID];
  272. if(V::get('DBG_TS', 0, $_GET) > 0){echo "\tr: {" . json_encode($r) . "}\n";}
  273. if(V::get('DBG_TS', 0, $_GET) > 0){echo "\t\tfltr: {" . json_encode($fltr) . "}\n";}
  274. $typeSpecialsByField[$fltr['type']]->filters[$fltr['filter']]->filtersByID[$r->ID] = $r;
  275. $newFiltersTodoIds[$r->ID] = array('type' => $fltr['type'], 'filter' => $fltr['filter']);
  276. if ($r->ALIAS_ID > 0) {
  277. $aliasesMap[$r->ALIAS_ID] = $r->ALIAS_DESC;
  278. }
  279. }
  280. $filtersTodoIds = $newFiltersTodoIds;
  281. }
  282. if(V::get('DBG_TS', 0, $_GET) > 0){echo '</pre>';}
  283. }
  284. foreach ($typeSpecialsByField as $kFieldID => $vType) {
  285. $vType->filters = Typespecial::convertFilters($vType->filters);
  286. }
  287. if(V::get('DBG_TS', 0, $_GET) > 0){echo'<pre style="max-height:200px;overflow:auto;border:1px solid orange;text-align:left;">typeSpecialsByField (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($typeSpecialsByField);echo'</pre>';}
  288. if(V::get('DBG_TS', 0, $_GET) > 0){echo'<pre style="max-height:200px;overflow:auto;border:1px solid orange;text-align:left;">aliasesMap (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($aliasesMap);echo'</pre>';}
  289. $sqlTables = array();
  290. if (!isset($_SESSION['Typespecial_Cache']['sqlTablesInfo'])) $_SESSION['Typespecial_Cache']['sqlTablesInfo'] = array();
  291. $sql = "select z.`ID`
  292. , z.`PARENT_ID`
  293. , z.`ALIAS_ID`
  294. , z.`TYPE`
  295. , z.`DESC`
  296. , zp.`ID` as TBL_ID
  297. , zp.`PARENT_ID` as DB_ID
  298. , zp.`DESC` as TBL_NAME
  299. -- , zpp.`ID` as DB_ID
  300. -- , zpp.`DESC` as DB_DESC
  301. from `CRM_LISTA_ZASOBOW` as z
  302. join `CRM_LISTA_ZASOBOW` as zp on(zp.`ID`=z.`PARENT_ID`)
  303. -- join `CRM_LISTA_ZASOBOW` as zpp on(zpp.`ID`=zp.`PARENT_ID`)
  304. where zp.`TYPE`='TABELA'
  305. and z.`TYPE`='KOMORKA'
  306. -- and zpp.`TYPE` in('DATABASE', 'DATABASE_MYSQL')
  307. and z.`ID` in(" . implode(",", array_keys($aliasesMap)) . ")
  308. ";
  309. if(V::get('DBG_TS', 0, $_GET) > 0){echo'<pre style="max-height:200px;overflow:auto;border:1px solid orange;text-align:left;">sql (C.' . __CLASS__ . ':C.' . __CLASS__ . ':F.' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($sql);echo'</pre>';}
  310. $res = $db->query($sql);
  311. while ($r = $db->fetch($res)) {
  312. $_SESSION['Typespecial_Cache']['sqlTablesInfo'][$r->ID] = (object)array('tbl_id'=>$r->TBL_ID, 'db_id'=>$r->DB_ID, 'tbl_name'=>$r->TBL_NAME);
  313. }
  314. if(V::get('DBG_TS', 0, $_GET) > 0){echo'<pre style="max-height:200px;overflow:auto;border:1px solid orange;text-align:left;">sqlTablesInfo (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($_SESSION['Typespecial_Cache']['sqlTablesInfo']);echo'</pre>';}
  315. if(V::get('DBG_TS', 0, $_GET) > 0){echo'<pre style="max-height:200px;overflow:auto;border:1px solid orange;text-align:left">typeSpecialsByField update by sqlTablesInfo (F.' . __FUNCTION__ . ':' . __LINE__ . '): '."\n";}
  316. foreach ($typeSpecialsByField as $kFieldID => $vType) {
  317. if(V::get('DBG_TS', 0, $_GET) > 0){ echo "loop: {$kFieldID}\n";}
  318. $vType->fldAliasList = array();// [tblID][fldID] = fldName
  319. $vType->tblAliasList = array();
  320. foreach ($vType->param_out->values as $kName => $vZasobID) {
  321. if(V::get('DBG_TS', 0, $_GET) > 0){ echo "\t value: {$kName}=>{$vZasobID} (" . (array_key_exists($vZasobID, $_SESSION['Typespecial_Cache']['sqlTablesInfo'])) . ") \n";}
  322. if (array_key_exists($vZasobID, $_SESSION['Typespecial_Cache']['sqlTablesInfo'])) {
  323. $vTbl = $_SESSION['Typespecial_Cache']['sqlTablesInfo'][$vZasobID];
  324. if(V::get('DBG_TS', 0, $_GET) > 0){ echo "\t\t tbl({$vTbl->tbl_id}:{$vTbl->tbl_name}), db({$vTbl->db_id}) (info: " . '<b style="display:none">' . json_encode($vTbl) . '</b>' . ") \n";}
  325. $vType->fldAliasList[$vTbl->tbl_id][$vZasobID] = $aliasesMap[$vZasobID];
  326. $vType->tblAliasList[$vTbl->tbl_id] = $vTbl->tbl_name;
  327. }
  328. }
  329. // TODO: add tblAliasList, fldAliasList by filters (PARAM_WHERE)
  330. if (!empty($vType->filters)) foreach ($vType->filters as $kFltr => $vFltrs) {
  331. foreach ($vFltrs->filtersByID as $kFltrId => $vFltr) {
  332. if ($vFltr->ALIAS_ID > 0) {
  333. $vZasobID = $vFltr->ALIAS_ID;
  334. if (array_key_exists($vZasobID, $_SESSION['Typespecial_Cache']['sqlTablesInfo'])) {
  335. $vTbl = $_SESSION['Typespecial_Cache']['sqlTablesInfo'][$vZasobID];
  336. if(V::get('DBG_TS', 0, $_GET) > 0){ echo "\t\t filters tbl({$vTbl->tbl_id}:{$vTbl->tbl_name}), db({$vTbl->db_id}) (info: " . '<b style="display:none">' . json_encode($vTbl) . '</b>' . ") \n";}
  337. if (!empty($aliasesMap[$vZasobID])) {
  338. $vType->fldAliasList[$vTbl->tbl_id][$vZasobID] = $aliasesMap[$vZasobID];
  339. }
  340. $vType->tblAliasList[$vTbl->tbl_id] = $vTbl->tbl_name;
  341. }
  342. }
  343. }
  344. }
  345. }
  346. if(V::get('DBG_TS', 0, $_GET) > 0){echo'</pre>';}
  347. if(V::get('DBG_TS', 0, $_GET) > 0){echo'<pre style="max-height:300px;overflow:auto;border:1px solid orange;text-align:left;">typeSpecialsByField-2 (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($typeSpecialsByField);echo'</pre>';}
  348. foreach ($typeSpecialsByField as $kFieldID => $vType) {
  349. $vType->buildSqlQuery();
  350. }
  351. if(V::get('DBG_TS', 0, $_GET) > 0){echo'<pre style="max-height:300px;overflow:auto;border:1px solid orange;text-align:left;">typeSpecialsByField-3 (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($typeSpecialsByField);echo'</pre>';}
  352. foreach ($typeSpecialsByField as $kFieldID => $vType) {
  353. $vType->saveCache();
  354. }
  355. return array_keys($typeSpecialsByField);
  356. }
  357. public static function convertFilters($filters) {
  358. if (empty($filters)) {
  359. return $filters;
  360. }
  361. foreach ($filters as $kFltrID => $vFltrRoot) {
  362. foreach ($vFltrRoot->filtersByID as $vFltr) {
  363. $vFltrRoot->treeFlat[$vFltr->PARENT_ID][] = $vFltr->ID;
  364. }
  365. }
  366. if(V::get('DBG_TS', 0, $_GET) > 0){ echo'<pre style="max-height:200px;overflow:auto;border:1px solid orange;text-align:left;">filters (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($filters);echo'</pre>';}
  367. return $filters;
  368. }
  369. private function buildSqlWhere($fltrRoot, $fltr) {
  370. if(V::get('DBG_TS', 0, $_GET) > 0){echo "buildSqlWhere({$fltr->ID}) {" . json_encode($fltr) . "}\n";}
  371. if (in_array($fltr->TYPE, array('SQL_IN', 'SQL_NOT_IN'))) {
  372. $sqlValues = array();
  373. foreach ($fltrRoot->treeFlat[$fltr->ID] as $vFltrID) {
  374. $vFltr = $fltrRoot->filtersByID[$vFltrID];
  375. $sqlValues[] = "'{$vFltr->DESC}'";
  376. }
  377. if (!empty($sqlValues)) {
  378. $sqlSign = 'in';
  379. if ($fltr->TYPE == 'SQL_NOT_IN') {
  380. $sqlSign = 'not in';
  381. }
  382. return "`t_{$fltr->ALIAS_PARENT_ID}`.`{$fltr->ALIAS_DESC}` {$sqlSign}(" . implode(", ", $sqlValues) . ")";
  383. } else {
  384. return null;// TODO: add parse error - use in validate
  385. }
  386. }
  387. else if ($fltr->TYPE == 'SQL_EQUAL') {
  388. if(V::get('DBG_TS', 0, $_GET) > 0){print_r($fltrRoot);echo "\n";}
  389. $sqlValues = array();
  390. if (count($fltrRoot->treeFlat[$fltr->ID]) == 1) {
  391. if(V::get('DBG_TS', 0, $_GET) > 0){echo "\nTODO: SQL_EQUAL count(" . count($fltrRoot->treeFlat[$fltr->ID]) . ") < 2\n";}
  392. foreach ($fltrRoot->filtersByID as $vFltr) {
  393. if(V::get('DBG_TS', 0, $_GET) > 0){echo "\nTODO: [" . reset($fltrRoot->treeFlat[0]) . "] vFltr=";print_r($vFltr);}
  394. if ($vFltr->ALIAS_ID > 0) {
  395. $sqlValues[] = "`t_{$vFltr->ALIAS_PARENT_ID}`.`{$vFltr->ALIAS_DESC}`";
  396. } else if (!empty($vFltr->DESC)) {
  397. $sqlValues[] = "'{$vFltr->DESC}'";
  398. }
  399. }
  400. }
  401. else {
  402. foreach ($fltrRoot->treeFlat[$fltr->ID] as $vFltrID) {
  403. $vFltr = $fltrRoot->filtersByID[$vFltrID];
  404. // TODO: $vFltr->TYPE == 'PARAM_IN' - use like {fltr_name} and add to special fields in sql to generate by given data
  405. $sqlValues[] = "`t_{$vFltr->ALIAS_PARENT_ID}`.`{$vFltr->ALIAS_DESC}`";
  406. }
  407. }
  408. if (count($sqlValues) == 2) {
  409. return "{$sqlValues[0]}={$sqlValues[1]}";
  410. } else if (count($sqlValues) > 2) {// TODO: multiple '='
  411. if(V::get('DBG_TS', 0, $_GET) > 0){echo "\nTODO: SQL_EQUAL count(sqlValues) > 2\n";}
  412. return null;
  413. } else {
  414. if(V::get('DBG_TS', 0, $_GET) > 0){echo "\nTODO: SQL_EQUAL count(sqlValues) < 2\n";}
  415. return null;// TODO: add parse error - use in validate
  416. }
  417. }
  418. else if ($fltr->TYPE == 'SQL_LIKE') {
  419. if(V::get('DBG_TS', 0, $_GET) > 0){echo "\nTODO: SQL_LIKE\n";print_r($fltrRoot);echo "\n";}
  420. $fltrs = array();
  421. $fltrs[] = $fltr;
  422. foreach ($fltrRoot->treeFlat[$fltr->ID] as $vFltrID) {
  423. $vFltr = $fltrRoot->filtersByID[$vFltrID];
  424. $fltrs[] = $vFltr;
  425. }
  426. if (count($fltrs) == 2) {
  427. if(V::get('DBG_TS', 0, $_GET) > 0){echo "\nTODO: SQL_LIKE count(fltrs) == 1; fltrs = ";print_r($fltrs);echo"\n";}
  428. $sqlValues = array();
  429. foreach ($fltrs as $vFltr) {
  430. if ($vFltr->ALIAS_TYPE == 'KOMORKA') {
  431. $sqlValues[] = "`t_{$vFltr->ALIAS_PARENT_ID}`.`{$vFltr->ALIAS_DESC}`";
  432. } else if ($vFltr->ALIAS_TYPE == 'VARIABLE') {
  433. switch ($vFltr->ALIAS_DESC) {
  434. case 'ADM_COMPANY':
  435. $sqlValues[] = "'{$_SESSION['ADM_COMPANY']}'";
  436. break;
  437. default:
  438. }
  439. } else {
  440. if(V::get('DBG_TS', 0, $_GET) > 0){echo "\nTODO: SQL_LIKE unknown ALIAS_DESC ($vFltr->ALIAS_DESC) \n";}
  441. }
  442. }
  443. if (count($sqlValues) == 2) {
  444. $sql = "{$sqlValues[0]} LIKE {$sqlValues[1]}";
  445. if(V::get('DBG_TS', 0, $_GET) > 0){echo "\nTODO: SQL_LIKE count(sqlValues) == 2; return {$sql}\n";}
  446. return $sql;
  447. } else {
  448. if(V::get('DBG_TS', 0, $_GET) > 0){echo "\nTODO: SQL_LIKE count(sqlValues) != 2\n";}
  449. return null;// TODO: add parse error - use in validate
  450. }
  451. } else {
  452. if(V::get('DBG_TS', 0, $_GET) > 0){echo "\nTODO: SQL_LIKE count(fltrs) != 2\n";}
  453. return null;// TODO: add parse error - use in validate
  454. }
  455. }
  456. return null;// TODO: add parse error - use in validate
  457. }
  458. /**
  459. * Create sql query by given filters
  460. *
  461. * @requires before $this->convertFilters();
  462. * @uses $this->filters
  463. * @uses $this->fldAliasList
  464. * @uses $this->buildSqlWhere($vFltrRoot, $fltr);
  465. */
  466. public function buildSqlQuery() {
  467. $this->sqlQuery = new stdClass();
  468. $this->sqlQuery->select = array();
  469. $this->sqlQuery->from = array();
  470. $this->sqlQuery->where = '';
  471. $this->sqlQuery->orderBy = '';
  472. $this->sqlQuery->limit = '';
  473. foreach ($this->fldAliasList as $kTblID => $vFields) {
  474. $this->sqlQuery->from[] = "`{$this->tblAliasList[$kTblID]}` as t_{$kTblID}";
  475. foreach ($vFields as $kFldID => $vFldName) {
  476. $this->sqlQuery->select[] = "`t_{$kTblID}`.`{$vFldName}` as f_{$kFldID}";
  477. }
  478. }
  479. if(V::get('DBG_TS', 0, $_GET) > 0){echo'<pre style="max-height:200px;overflow:auto;border:1px solid orange;text-align:left;">buildSqlWhere by filters (F.' . __FUNCTION__ . ':' . __LINE__ . '): '."\n";}
  480. $sql_where_and = array();
  481. if (!empty($this->filters)) {
  482. foreach ($this->filters as $kFltrID => $vFltrRoot) {
  483. foreach ($vFltrRoot->treeFlat[0] as $fltrID) {
  484. $fltr = $vFltrRoot->filtersByID[$fltrID];//$vFltrRoot->FLTR_ID];
  485. if(V::get('DBG_TS', 0, $_GET) > 0){echo "kFltrID: {$kFltrID} fltrID({$fltr->ID})\n";}
  486. $sqlPart = $this->buildSqlWhere($vFltrRoot, $fltr);
  487. if ($sqlPart) {
  488. $sql_where_and[] = $sqlPart;
  489. }
  490. }
  491. }
  492. }
  493. if(V::get('DBG_TS', 0, $_GET) > 0){echo'</pre>';}
  494. $sql_where = (!empty($sql_where_and))? implode("\n and ", $sql_where_and) : "1=1";
  495. $this->sqlQuery->where = $sql_where;
  496. }
  497. public function getFieldName() {
  498. if (empty($this->_fldName)) {
  499. $db = DB::getDB();
  500. $sql = "select z.`DESC` from `CRM_LISTA_ZASOBOW` as z where z.`ID`='{$this->fldID}' ";
  501. $res = $db->query($sql);
  502. if ($r = $db->fetch($res)) {
  503. $this->_fldName = $r->DESC;
  504. }
  505. }
  506. return $this->_fldName;
  507. }
  508. /*
  509. * TODO: RMME - use Typeahead plugin
  510. */
  511. public function showFormItem__OLD($tblID, $fName, $selValue = '', $params = array(), $record = null) {
  512. $out = '';
  513. //if(V::get('DBG_TS', 0, $_GET) > 1){echo'<pre style="max-height:200px;overflow:auto;border:1px solid orange;text-align:left;">showFormItem (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r(array('tblID'=>$tblID,'fName'=>$fName,'selValue'=>$selValue));echo'</pre>';}
  514. // TODO: set value = $selValue to typespecial search field to load data from ajax?
  515. $tsValue = V::get('typespecialValue', '', $params);
  516. if (!empty($selValue) && !empty($tsValue)) {
  517. $tsValue = "{$selValue}: {$tsValue}";
  518. }
  519. $out = '<div class="input-prepend">
  520. <span class="add-on"><i class="glyphicon glyphicon-search"></i></span>
  521. <input class="span3" id="typeahead-' . $fName . '" type="search" placeholder="Search..." autocomplete="off" value="' . $tsValue . '">
  522. </div>
  523. <script>' . "
  524. jQuery('#typeahead-{$fName}').typeahead({
  525. source: function (query, process) {
  526. return $.ajax({
  527. dataType: 'json',
  528. url: 'index-ajax.php?_cls=TableAjax&_zasobID={$tblID}&_task=TYPESPECIAL&fldID={$this->fldID}',
  529. data: 'q=' + query,
  530. type: 'POST',
  531. success: function (json) {
  532. process(json);
  533. }
  534. });
  535. },
  536. updater: function (item) {
  537. console.log('selected item: '+item);
  538. var itemID = item.split(':')[0];
  539. console.log('selected id: '+itemID);
  540. jQuery('#{$fName}').val(itemID);
  541. return item;
  542. },
  543. matcher: function(item) {
  544. var queryArr = [];
  545. var words = this.query.split(' ');
  546. $.each(words, function(ind, word) {
  547. word = $.trim(word);
  548. if (word != '') {
  549. queryArr.push(word);
  550. }
  551. });
  552. var found = false;
  553. $.each(queryArr, function(ind, word) {
  554. //console.log('item(' + item + ') word(' + word + ') found(' + (item.toLowerCase().indexOf(word.toLowerCase())) + ')');
  555. if (-1 !== item.toLowerCase().indexOf(word.toLowerCase())) {
  556. found = true;
  557. }
  558. });
  559. return found;
  560. },
  561. sorter: function (items) {
  562. var bestFound = []
  563. , oneFound = []
  564. , notFound = []
  565. , item;
  566. var queryArr = [];
  567. var words = this.query.split(' ');
  568. $.each(words, function(ind, word) {
  569. word = $.trim(word);
  570. if (word != '') {
  571. queryArr.push(word);
  572. }
  573. });
  574. var found = 0;
  575. while (item = items.shift()) {
  576. found = 0;
  577. $.each(queryArr, function(ind, word) {
  578. //console.log('item(' + item + ') word(' + word + ') found(' + (item.toLowerCase().indexOf(word.toLowerCase())) + ')');
  579. if (-1 !== item.toLowerCase().indexOf(word.toLowerCase())) {
  580. found++;
  581. }
  582. });
  583. if (found > 1) {
  584. bestFound.push(item);
  585. } else if (found == 1) {
  586. oneFound.push(item);
  587. } else {
  588. notFound.push(item);
  589. }
  590. }
  591. return bestFound.concat(oneFound, notFound)
  592. },
  593. items: 20 // The max number of items to display in the dropdown.
  594. });
  595. " . '</script>
  596. ';
  597. return $out;
  598. }
  599. public function hGetFormItem($acl, $fieldNamespace, $tblID, $fName, $selValue = '', $params = array(), $record = null) {
  600. $jsonAllowCreate = 'true';
  601. switch ($this->getFieldName()) {
  602. case 'L_APPOITMENT_USER':
  603. case 'T_TELBOX_NEIGHBOUR_IN_ID':
  604. case 'CRM_LISTA_ZASOBOW_ID':
  605. case 'ID_ZASOB':
  606. case 'ID_BILLING_USERS':
  607. case 'ID_PROJECT':
  608. case 'ID_DEVICE':
  609. $jsonAllowCreate = 'false';
  610. break;
  611. }
  612. if (array_key_exists('allowCreate', $params)) $jsonAllowCreate = ($params['allowCreate'])? 'true' : 'false';
  613. $tsValue = V::get('typespecialValue', '', $params);
  614. if (!empty($selValue) && !empty($tsValue)) {
  615. // $tsValue = "{$selValue}: {$tsValue}"; // TODO: only in TypespecialVariable - skip in Typespecial
  616. }
  617. $options = [];
  618. if (!empty($selValue)) {
  619. $tsSelectedItemLabel = (!empty($tsValue))? $tsValue : $selValue;
  620. //$out .= '<option value="' . $selValue . '" selected="selected" typespecial="'.$tsSelectedItemLabel.'">' . $tsSelectedItemLabel . '</option>';
  621. {// fix prefix
  622. $prefix = "{$selValue}";
  623. $prefixLen = strlen($prefix);
  624. if (strlen($tsSelectedItemLabel) > $prefixLen && $prefix != substr($tsSelectedItemLabel, 0, $prefixLen)) {
  625. if (' ' == substr($tsSelectedItemLabel, 0, 1)) {
  626. $tsSelectedItemLabel = "{$prefix}{$tsSelectedItemLabel}";
  627. } else {
  628. $tsSelectedItemLabel = "{$prefix}: {$tsSelectedItemLabel}";
  629. }
  630. }
  631. }
  632. // $out .= '<option value="' . $selValue . '" selected="selected">' . $tsSelectedItemLabel . '</option>';
  633. $options[] = [
  634. 'id' => $selValue,
  635. 'name' => $tsSelectedItemLabel,
  636. ];
  637. }
  638. DBG::log(['$selValue'=>$selValue, '$tsValue'=>$tsValue, '$options'=>$options], 'array', "DBG TS selected value");
  639. return [ 'P5UI__Typespecial', array_filter([
  640. 'idField' => $this->fldID,
  641. 'fieldNamespace' => $fieldNamespace,
  642. 'fieldName' => $fName,
  643. 'frmFldName' => V::get('formFieldName', $fName, $params),
  644. 'create' => $jsonAllowCreate,
  645. 'ajaxDataUrlBase' => V::get('ajaxDataUrlBase', "index-ajax.php?_cls=TableAjax&_zasobID={$tblID}&_task=TYPESPECIAL&fldID={$this->fldID}", $params),
  646. 'options' => $options,
  647. 'selected' => $selValue,
  648. 'type' => "Typespecial",
  649. 'preload' => true,
  650. ], function ($value) { return null !== $value; }),
  651. (!empty($options))
  652. ? [ [ 'option', [ 'value' => $options[0]['id'] ], $options[0]['name'] ] ]
  653. : []
  654. ];
  655. }
  656. public function showFormItem($tblID, $fName, $selValue = '', $params = array(), $record = null) {
  657. $out = '';
  658. $jsonAllowCreate = 'true';
  659. switch ($this->getFieldName()) {
  660. case 'L_APPOITMENT_USER':
  661. case 'T_TELBOX_NEIGHBOUR_IN_ID':
  662. case 'CRM_LISTA_ZASOBOW_ID':
  663. case 'ID_ZASOB':
  664. case 'ID_BILLING_USERS':
  665. case 'ID_PROJECT':
  666. case 'ID_DEVICE':
  667. $jsonAllowCreate = 'false';
  668. break;
  669. default:
  670. $jsonAllowCreate = 'true';
  671. }
  672. $tsValue = V::get('typespecialValue', '', $params);
  673. if (!empty($selValue) && !empty($tsValue)) {
  674. //$tsValue = "{$selValue}: {$tsValue}";
  675. }
  676. $optionsJson = 'null';
  677. $out .= '<div class="typepsecial">';
  678. $out .= '<select id="ts-' . $fName . '">';
  679. if (!empty($selValue)) {
  680. $tsSelectedItemLabel = (!empty($tsValue))? $tsValue : $selValue;
  681. //$out .= '<option value="' . $selValue . '" selected="selected" typespecial="'.$tsSelectedItemLabel.'">' . $tsSelectedItemLabel . '</option>';
  682. {// fix prefix
  683. $prefix = "{$selValue}";
  684. $prefixLen = strlen($prefix);
  685. if (strlen($tsSelectedItemLabel) > $prefixLen && $prefix != substr($tsSelectedItemLabel, 0, $prefixLen)) {
  686. if (' ' == substr($tsSelectedItemLabel, 0, 1)) {
  687. $tsSelectedItemLabel = "{$prefix}{$tsSelectedItemLabel}";
  688. } else {
  689. $tsSelectedItemLabel = "{$prefix}: {$tsSelectedItemLabel}";
  690. }
  691. }
  692. }
  693. $out .= '<option value="' . $selValue . '" selected="selected">' . $tsSelectedItemLabel . '</option>';
  694. $optionsJson = new stdClass();
  695. $optionsJson->id = $selValue;
  696. $optionsJson->name = $tsSelectedItemLabel;
  697. $optionsJson = array($optionsJson);
  698. $optionsJson = json_encode($optionsJson);
  699. }
  700. $out .= '</select>';
  701. $out .= '</div>';
  702. $ajaxDataUrlBase = "index-ajax.php?_cls=TableAjax&_zasobID={$tblID}&_task=TYPESPECIAL&fldID={$this->fldID}";
  703. $ajaxDataUrlBase = V::get('ajaxDataUrlBase', $ajaxDataUrlBase, $params);
  704. $frmFldName = V::get('formFieldName', $fName, $params);
  705. $out .= '<script>' . "
  706. (function(){
  707. var fldNode=jQuery('#{$fName}'), tsNode=jQuery('#ts-{$fName}');
  708. if (!fldNode && !tsNode) {
  709. return;
  710. }
  711. fldNode.attr('name', '');
  712. fldNode.hide();
  713. if (fldNode.parent().hasClass('show-last-value')) {
  714. fldNode.parent().hide();
  715. }
  716. tsNode.attr('name', '{$frmFldName}');
  717. tsNode.attr('tabindex', fldNode.attr('tabindex'));
  718. tsNode.selectize({
  719. theme: 'typespecial',
  720. valueField: 'id',
  721. labelField: 'id',
  722. searchField: 'name',
  723. // sortField: 'name',
  724. create: {$jsonAllowCreate},
  725. delimiter: ';',
  726. dataAttr: 'typespecial',
  727. preload: true,
  728. options: {$optionsJson},
  729. render: {
  730. item: function(item, escape) {
  731. //console.log('item', item);
  732. //var name = formatName(item);
  733. return '<div>' +
  734. '<span class=\"name\">' + escape(item.name || item.id) + '</span>' +
  735. '</div>';
  736. },
  737. option: function(item, escape) {
  738. //console.log('--- render.option item(',item,') this:',this);
  739. return '<div>' +
  740. '<span class=\"title\">' +
  741. escape(item.name || item.id) +
  742. '</span>' +
  743. '</div>';
  744. }
  745. },
  746. onItemAdd: function(value, item) {// Invoked when an item is selected.
  747. var curSel = this.options[value] || null, fieldExport;
  748. //console.log('--- onItemAdd val(',value,'/',item.data('name'),'/',item,') this:curSel:',curSel);
  749. if (curSel && curSel.exports) {
  750. for (var i in curSel.exports) {
  751. fieldExport = jQuery('#ts-f' + i);
  752. if (fieldExport.length) {
  753. //console.log('--- onItemAdd fieldExport.selectize(',fieldExport.selectize,')', fieldExport);
  754. if (fieldExport.get(0).selectize) {
  755. fieldExport.get(0).selectize.addOption({id:curSel.exports[i], name:curSel.exports[i]});
  756. fieldExport.get(0).selectize.setValue(curSel.exports[i]);
  757. } else {
  758. //jQuery('#f' + i).val(curSel.exports[i]);
  759. }
  760. } else {
  761. //console.log('--- onItemAdd jQuery(#f' + i + ').val(', curSel.exports[i], '): fieldExport.is(input:',fieldExport.is('input'),'/select:',fieldExport.is('select'),')', fieldExport);
  762. fieldExport = jQuery('#f' + i);
  763. if (fieldExport.is('input')) {
  764. jQuery('#f' + i).val(curSel.exports[i]);
  765. } else if (fieldExport.is('select')) {
  766. //TODO: add option and select //jQuery('#f' + i).val(curSel.exports[i]);
  767. }
  768. }
  769. }
  770. }
  771. },
  772. score: function(query) {
  773. // console.log('Typespecial({$fName})::score: q(', query, ')');
  774. var score = this.getScoreFunction(query);
  775. return function(item) {
  776. var retScore = 0, lName = ('' + item.name).toLowerCase(), lQuery = query.toLowerCase();
  777. if (query.search(' ') > -1) {
  778. retScore = score(item);
  779. }
  780. else {
  781. if (lQuery + ':' == lName.substr(0, lQuery.length + 1)) {
  782. retScore = 100;
  783. } else if (lName.search(lQuery) > -1) {
  784. retScore = 90 - lName.search(lQuery);
  785. } else {
  786. retScore = 0;
  787. }
  788. }
  789. // console.log('Typespecial({$fName})::score: q(', lQuery, ') , retScore(', retScore, '), score(', score(item), '), item.name(', item.name, ') item.id:', item.id);
  790. return retScore;
  791. };
  792. },
  793. load: function(query, callback) {
  794. //if (!query.length) return callback();
  795. $.ajax({
  796. url: '{$ajaxDataUrlBase}',
  797. data: 'q=' + encodeURIComponent(query),
  798. type: 'POST',
  799. error: function() {
  800. callback();
  801. },
  802. success: function(res) {
  803. var i, prefix, prefixLen;
  804. for (i in res) {
  805. prefix = '' + res[i].id;
  806. prefixLen = prefix.length;
  807. if (prefixLen > 0 && prefix !== res[i].name.substr(0, prefixLen)) {
  808. res[i].name = res[i].id + ': ' + res[i].name;
  809. }
  810. res[i]['\$order'] = 1 + (parseInt(i) || 0);// set order from request
  811. }
  812. // console.log('Typespecial({$fName})::res',res);
  813. callback(res);
  814. }
  815. });
  816. }
  817. });
  818. })()
  819. " . '</script>';
  820. return $out;
  821. }
  822. public function _getValues($query) {
  823. $rows = array();
  824. $db = DB::getDB();// TODO: get from DB by zasoby ID
  825. DBG::log(['msg'=>"session", $_SESSION['Typespecial_Cache']['sqlTablesInfo']]);
  826. DBG::log(['msg'=>"this", $this]);
  827. $query = trim($query);
  828. $sqlWhereAdd = "";
  829. if (!empty($query)) {
  830. Lib::loadClass('SqlQueryWhereBuilder');
  831. $queryWhereBuilder = new SqlQueryWhereBuilder();
  832. $qArr = $queryWhereBuilder->splitQueryToWords($query);
  833. DBG::log(['msg'=>"qArr", $qArr]);
  834. if (!empty($qArr)) {
  835. $sqlWhereAnd = array();
  836. foreach ($qArr as $q) {
  837. $sqlSearchWord = DB::getPDO()->quote(
  838. (is_numeric($q)) ? "{$q}%" : "%{$q}%",
  839. PDO::PARAM_STR
  840. );
  841. $sqlWhereOr = array();
  842. foreach ($this->param_out->alias as $fldID => $fldName) {
  843. if (false === strpos($this->param_out->format, "{{$fldName}}")) continue;
  844. $tblInfo = V::get($fldID, null, $_SESSION['Typespecial_Cache']['sqlTablesInfo']);
  845. if ($tblInfo) {
  846. $sqlWhereOr[] = "`t_{$tblInfo->tbl_id}`.`{$fldName}` like {$sqlSearchWord}";
  847. }
  848. }
  849. if (!empty($sqlWhereOr)) {
  850. $sqlWhereAnd[] = "(" . implode(" or ", $sqlWhereOr) . ")";
  851. }
  852. }
  853. if (!empty($sqlWhereAnd)) {
  854. $sqlWhereAdd = " and (" . implode(" and ", $sqlWhereAnd) . ")";
  855. }
  856. }
  857. }
  858. DBG::log(['msg'=>"this", $this]);
  859. Lib::loadClass('ACL');
  860. Lib::loadClass('AclQueryFeatures');
  861. try {
  862. $andSql = array_map(
  863. function ($tableName, $idTable) {
  864. $tableAcl = User::getAcl()->getObjectAcl('default_db', $tableName);
  865. return ACL::query($tableAcl, "t_{$idTable}")
  866. ->where( (new AclQueryFeatures($tableAcl, $params = []))->parseSpecialFilterAccess() )
  867. ->generateWhereSql()
  868. ;
  869. },
  870. $this->tblAliasList, array_keys($this->tblAliasList)
  871. );
  872. $andSql = array_filter($andSql, ['V', 'filterNotEmpty']);
  873. if (!empty($andSql)) $sqlWhereAdd .= "\n" . " and " . implode(" and ", $andSql);
  874. } catch (Exception $e) {
  875. DBG::log($e);
  876. return [];
  877. }
  878. $sqlLimit = V::get('limit', 0, $this->sqlQuery, 'int');
  879. $sqlLimit = ($sqlLimit > 0) ? $sqlLimit : 20;
  880. $histRows = array();
  881. {
  882. if (empty($query)) {
  883. if (V::get('TEST_SORT', '', $_GET)) echo '{' . "\n";
  884. if (V::get('TEST_SORT', '', $_GET)) echo '"this": ' . json_encode($this) . ",";
  885. if (!empty($this->fldID) && is_numeric($this->fldID)) {
  886. $fldName = $this->param_out->alias[ $this->param_out->retID ];
  887. $zasobCellInfo = DB::getPDO()->fetchFirst("
  888. select z.`DESC` as fldName, t.`DESC` as tblName
  889. from CRM_LISTA_ZASOBOW z
  890. join CRM_LISTA_ZASOBOW t on(t.ID = z.PARENT_ID)
  891. where z.ID = '{$this->fldID}'
  892. and z.`TYPE` = 'KOMORKA'
  893. and t.`TYPE` = 'TABELA'
  894. ");
  895. if (!empty($zasobCellInfo)) {
  896. $fldName = $zasobCellInfo['fldName'];
  897. $tblName = $zasobCellInfo['tblName'];
  898. if (V::get('TEST_SORT', '', $_GET)) echo '"field_name": "'.$fldName.'",';
  899. if (V::get('TEST_SORT', '', $_GET)) echo '"table_name": "'.$tblName.'",';
  900. $userLogin = V::get('TEST_SORT_LOGIN', User::getLogin(), $_REQUEST);
  901. try {
  902. $histRows = DB::getPDO()->fetchAll("
  903. select h.`{$fldName}`
  904. , count(1) as cnt
  905. from `{$tblName}_HIST` h
  906. where h.A_RECORD_UPDATE_AUTHOR = '{$userLogin}'
  907. and h.`{$fldName}` != 'N/S;'
  908. and h.`{$fldName}` != ''
  909. and h.`{$fldName}` != '0'
  910. and h.`{$fldName}` IS NOT NULL
  911. and h.`{$fldName}` != 'NULL'
  912. group by h.`{$fldName}`
  913. order by cnt desc
  914. limit 10
  915. ");
  916. } catch (Exception $e) {
  917. if (V::get('TEST_SORT', '', $_GET)) echo '"Exception": ' . json_encode($e) . ',';
  918. }
  919. if (V::get('TEST_SORT', '', $_GET)) echo '"hist_rows_stats": ' . json_encode($histRows) . ',';
  920. }
  921. }
  922. }
  923. }
  924. $rawRows = DB::getPDO()->fetchAll("
  925. select " . implode("\n\t\t,", $this->sqlQuery->select) . "
  926. from " . implode(", ", $this->sqlQuery->from) . "
  927. where {$this->sqlQuery->where}
  928. {$sqlWhereAdd}
  929. limit {$sqlLimit}
  930. ");
  931. foreach ($rawRows as $r) {
  932. $retID = V::get("f_{$this->param_out->retID}", '', $r);
  933. $rows[$retID] = (object)$r;
  934. }
  935. if (!empty($histRows)) {
  936. $sordedRows = array();
  937. $orderIndex = 1000;
  938. foreach ($histRows as $histRow) {
  939. $retValue = $histRow[$fldName];
  940. if (array_key_exists($retValue, $rows)) {
  941. $sordedRows[$retValue] = $rows[$retValue];
  942. $sordedRows[$retValue]->{'$order'} = $orderIndex--;
  943. unset($rows[$retValue]);
  944. } else {
  945. try {
  946. $sordedRows[$retValue] = (object)DB::getPDO()->fetchFirst("
  947. select " . implode("\n\t\t,", $this->sqlQuery->select) . "
  948. from " . implode(", ", $this->sqlQuery->from) . "
  949. where {$this->sqlQuery->where}
  950. {$sqlWhereAdd}
  951. having `f_{$this->param_out->retID}` = '{$retValue}'
  952. ");
  953. if (V::get('TEST_SORT', '', $_GET)) echo '"test_fetch_'.$retValue.'":' . json_encode($sordedRows[$retValue]) . ",";
  954. if (!empty($sordedRows[$retValue])) {
  955. $sordedRows[$retValue]->{'$order'} = $orderIndex--;
  956. }
  957. } catch (Exception $e) {
  958. DBG::log($e);
  959. }
  960. }
  961. }
  962. foreach ($rows as $key => $val) {
  963. $sordedRows[$key] = $val;
  964. }
  965. $rows = $sordedRows;
  966. }
  967. if (V::get('TEST_SORT', '', $_GET)) echo '"rows":' . json_encode($rows) . ",";
  968. if (V::get('TEST_SORT', '', $_GET)) die('"end":"end"' . "\n" . '}');
  969. DBG::log(['msg'=>"rows", $rows]);
  970. return $rows;
  971. }
  972. public function getValues($query) {
  973. $rows = $this->_getValues($query);
  974. DBG::log(['msg'=>"param_out", $this->param_out]);
  975. {// convert param_out
  976. $format = $this->param_out->format;
  977. foreach ($this->param_out->values as $kFldName => $vFldID) {
  978. $format = str_replace("{{$kFldName}}", "{f_{$vFldID}}", $format);
  979. }
  980. DBG::log(['msg'=>"format", $format]);
  981. }
  982. $rows_out = array();
  983. foreach ($rows as $ind => $r) {
  984. $row_out = $format;
  985. foreach ($r as $kFldName => $vVal) {
  986. $row_out = str_replace("{{$kFldName}}", "{$vVal}", $row_out);
  987. }
  988. $rows_out[$ind] = $row_out;
  989. }
  990. DBG::log(['msg'=>"rows_out", $rows_out]);
  991. return $rows_out;
  992. }
  993. public function getValuesWithExports($query) {
  994. $rows = $this->_getValues($query);
  995. DBG::log(['msg'=>"param_out", $this->param_out]);
  996. {// convert param_out
  997. $format = $this->param_out->format;
  998. foreach ($this->param_out->values as $kFldName => $vFldID) {
  999. $format = str_replace("{{$kFldName}}", "{f_{$vFldID}}", $format);
  1000. }
  1001. DBG::log(['msg'=>"format", $format]);
  1002. }
  1003. $retObjList = array();
  1004. foreach ($rows as $ind => $r) {
  1005. $vObj = new stdClass();
  1006. $vObj->id = $ind;
  1007. $vObj->param_out = $format;
  1008. foreach ($r as $kFldName => $vVal) {
  1009. $vObj->param_out = str_replace("{{$kFldName}}", "{$vVal}", $vObj->param_out);
  1010. }
  1011. if (!empty($this->param_out->exports)) {
  1012. $vObj->exports = array();
  1013. foreach ($this->param_out->exports as $kExportID => $vExportOut) {
  1014. $vObj->exports[$kExportID] = new stdClass();
  1015. foreach ($this->param_out->values as $kFldName => $vFldID) {
  1016. $vExportOut = str_replace("{{$kFldName}}", "{f_{$vFldID}}", $vExportOut);
  1017. }
  1018. foreach ($r as $kFldName => $vVal) {
  1019. $vExportOut = str_replace("{{$kFldName}}", "{$vVal}", $vExportOut);
  1020. }
  1021. $vObj->exports[$kExportID] = $vExportOut;
  1022. }
  1023. }
  1024. if (!empty($r->{'$order'})) {
  1025. $vObj->{'$order'} = $r->{'$order'};
  1026. }
  1027. $retObjList[$ind] = $vObj;
  1028. }
  1029. DBG::log(['msg'=>"retObjList", $retObjList]);
  1030. return $retObjList;
  1031. }
  1032. public function getEditSelectedValuesByIds($tblId, $rowId, $fieldName, $fieldValue = '') {
  1033. $rows = array();
  1034. $db = DB::getDB();// TODO: get from DB by zasoby ID
  1035. if(V::get('DBG_TS', 0, $_GET) > 1){echo'<pre style="max-height:200px;overflow:auto;border:1px solid orange;text-align:left;">args (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r(array('tblId'=>$tblId, 'rowId'=>$rowId, 'fieldName'=>$fieldName, 'fieldValue'=>$fieldValue));echo'</pre>';}// TODO: RMME
  1036. if(V::get('DBG_TS', 0, $_GET) > 1){echo'<pre style="max-height:200px;overflow:auto;border:1px solid orange;text-align:left;">sqlTablesInfo (tblId:'.$tblId.') (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($_SESSION['Typespecial_Cache']['sqlTablesInfo']);echo'</pre>';}// TODO: RMME
  1037. if(V::get('DBG_TS', 0, $_GET) > 1){echo'<pre style="max-height:200px;overflow:auto;border:1px solid orange;text-align:left;">this->tblAliasList (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($this->tblAliasList);echo'</pre>';}// TODO: RMME
  1038. if(V::get('DBG_TS', 0, $_GET) > 1){echo'<pre style="max-height:200px;overflow:auto;border:1px solid orange;text-align:left;">this (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($this);echo'</pre>';}// TODO: RMME
  1039. $retFldName = '';
  1040. $sqlWhereAdd = array();
  1041. $tblFound = null;
  1042. foreach ($_SESSION['Typespecial_Cache']['sqlTablesInfo'] as $vTblInfo) {
  1043. if ($vTblInfo->tbl_id == $tblId) {
  1044. $tblFound = $vTblInfo;
  1045. break;
  1046. }
  1047. }
  1048. if (!$tblFound) {
  1049. $tblFound = (object)DB::getPDO()->fetchFirst("
  1050. select z.`ID` as tbl_id
  1051. , z.`PARENT_ID` as db_id
  1052. , z.`DESC` as tbl_name
  1053. from `CRM_LISTA_ZASOBOW` as z
  1054. where z.`ID`={$tblId}
  1055. ");
  1056. if(V::get('DBG_TS', 0, $_GET) > 1){echo'<pre style="max-height:200px;overflow:auto;border:1px solid orange;text-align:left;">Found 2 tblFound ('.$tblId.') (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($tblFound);echo'</pre>';}// TODO: RMME
  1057. }
  1058. if (!$tblFound) {
  1059. if(V::get('DBG_TS', 0, $_GET) > 1){echo'<pre style="max-height:200px;overflow:auto;border:1px solid orange;text-align:left;">No tblFound! ('.$tblId.') (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($_SESSION['Typespecial_Cache']['sqlTablesInfo']);echo'</pre>';}// TODO: RMME
  1060. return false;
  1061. }
  1062. //echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">$vTblInfo (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($vTblInfo);echo'</pre>';
  1063. $sqlFrom = $this->sqlQuery->from;
  1064. $sqlSelect = $this->sqlQuery->select;
  1065. if ($this->param_out->retID > 0) {
  1066. $sqlWhereAdd[] = "`tr_{$tblId}`.`ID`={$rowId}";
  1067. if (array_key_exists($this->param_out->retID, $_SESSION['Typespecial_Cache']['sqlTablesInfo'])) {
  1068. $retTblId = $_SESSION['Typespecial_Cache']['sqlTablesInfo'][$this->param_out->retID]->tbl_id;
  1069. $retName = $this->param_out->alias[$this->param_out->retID];
  1070. $sqlWhereAdd[] = "`t_{$retTblId}`.`{$retName}`=`tr_{$tblId}`.`{$fieldName}`";
  1071. } else {
  1072. return false;
  1073. }
  1074. $sqlSelect[] = "`tr_{$tblId}`.`ID`";
  1075. $sqlFrom[] = "`{$tblFound->tbl_name}` as tr_{$tblFound->tbl_id}";
  1076. $retFldName = "f_{$this->param_out->retID}";
  1077. $foundInSelect = false;
  1078. foreach ($sqlSelect as $vSelectStr) {
  1079. if (false !== strpos($vSelectStr, $retFldName)) {
  1080. $foundInSelect = true;
  1081. }
  1082. }
  1083. if (!$foundInSelect) $retFldName = '';
  1084. }
  1085. else {// if no retID then TYPESPECIAL is link
  1086. $sqlWhereAdd[] = "`t_{$tblId}`.`ID`={$rowId}";
  1087. $sqlSelect[] = "`t_{$tblId}`.`ID`";
  1088. }
  1089. $sqlWhereAdd = (!empty($sqlWhereAdd))? " and " . implode(" and ", $sqlWhereAdd) : "";
  1090. $sqlLimit = V::get('limit', 0, $this->sqlQuery, 'int');
  1091. if ($sqlLimit <= 0) {
  1092. $sqlLimit = 20;
  1093. }
  1094. $sqlLimit = "limit {$sqlLimit}";
  1095. $sqlFrom = implode(", ", $sqlFrom);
  1096. $sql = "select " . implode("\n\t\t,", $sqlSelect) . "
  1097. from {$sqlFrom}
  1098. where {$this->sqlQuery->where}
  1099. {$sqlWhereAdd}
  1100. {$sqlLimit}
  1101. ";
  1102. if(V::get('DBG_TS', 0, $_GET) > 0){echo'<pre style="max-height:200px;overflow:auto;border:1px solid orange;text-align:left;">sql (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($sql);echo'</pre>';}
  1103. $res = $db->query($sql);
  1104. while ($r = $db->fetch($res)) {
  1105. $rows[] = $r;
  1106. }
  1107. if(V::get('DBG_TS', 0, $_GET) > 0){echo'<pre style="max-height:200px;overflow:auto;border:1px solid orange;text-align:left;">rows (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($rows);echo'</pre>';}
  1108. if(V::get('DBG_TS', 0, $_GET) > 0){echo'<pre style="max-height:200px;overflow:auto;border:1px solid orange;text-align:left;">param_out (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($this->param_out);echo'</pre>';}
  1109. {// convert param_out
  1110. $format = $this->param_out->format;
  1111. foreach ($this->param_out->values as $kFldName => $vFldID) {
  1112. $format = str_replace("{{$kFldName}}", "{f_{$vFldID}}", $format);
  1113. }
  1114. if(V::get('DBG_TS', 0, $_GET) > 0){echo'<pre style="max-height:200px;overflow:auto;border:1px solid orange;text-align:left;">format (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($format);echo'</pre>';}
  1115. }
  1116. if(V::get('DBG_TS', 0, $_GET) > 0){echo'<pre style="max-height:200px;overflow:auto;border:1px solid orange;text-align:left;">retFldName:'.$retFldName.' (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($rows);echo'</pre>';}
  1117. $rowsOut = array();
  1118. foreach ($rows as $r) {
  1119. $rowOut = $format;
  1120. foreach ($r as $kFldName => $vVal) {
  1121. $rowOut = str_replace("{{$kFldName}}", "{$vVal}", $rowOut);
  1122. }
  1123. if ($retFldName) {
  1124. $rowsOut[$r->{$retFldName}] = $rowOut;
  1125. } else {
  1126. $rowsOut[] = $rowOut;
  1127. }
  1128. }
  1129. if(V::get('DBG_TS', 0, $_GET) > 0){echo'<pre style="max-height:200px;overflow:auto;border:1px solid orange;text-align:left;">rowsOut (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($rowsOut);echo'</pre>';}
  1130. return $rowsOut;
  1131. }
  1132. public function getValuesByIds($tblId, $ids) {
  1133. $rows = array();
  1134. $db = DB::getDB();// TODO: get from DB by zasoby ID
  1135. if(V::get('DBG_TS', 0, $_GET) > 1){echo'<pre style="max-height:200px;overflow:auto;border:1px solid orange;text-align:left;">sqlTablesInfo (tblId:'.$tblId.') (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($_SESSION['Typespecial_Cache']['sqlTablesInfo']);echo'</pre>';}// TODO: RMME
  1136. if(V::get('DBG_TS', 0, $_GET) > 1){echo'<pre style="max-height:200px;overflow:auto;border:1px solid orange;text-align:left;">this->tblAliasList (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($this->tblAliasList);echo'</pre>';}// TODO: RMME
  1137. if(V::get('DBG_TS', 0, $_GET) > 1){echo'<pre style="max-height:200px;overflow:auto;border:1px solid orange;text-align:left;">this (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($this);echo'</pre>';}// TODO: RMME
  1138. $sqlWhereAdd = array();
  1139. $tblFound = null;
  1140. foreach ($_SESSION['Typespecial_Cache']['sqlTablesInfo'] as $vTblInfo) {
  1141. if ($vTblInfo->tbl_id == $tblId) {
  1142. $tblFound = $vTblInfo;
  1143. break;
  1144. }
  1145. }
  1146. if (!$tblFound) {
  1147. return false;
  1148. }
  1149. $sqlWhereAdd[] = "`t_{$tblId}`.`ID` in(" . implode(",", $ids) . ")";
  1150. $sqlWhereAdd = (!empty($sqlWhereAdd))? " and " . implode(" and ", $sqlWhereAdd) : "";
  1151. $sqlLimit = V::get('limit', 0, $this->sqlQuery, 'int');
  1152. if ($sqlLimit <= 0) {
  1153. $sqlLimit = 20;
  1154. }
  1155. $sqlLimit = "limit {$sqlLimit}";
  1156. $sql = "select " . implode("\n\t\t,", $this->sqlQuery->select) . "
  1157. , `t_{$tblId}`.`ID`
  1158. from " . implode(", ", $this->sqlQuery->from) . "
  1159. where {$this->sqlQuery->where}
  1160. {$sqlWhereAdd}
  1161. {$sqlLimit}
  1162. ";
  1163. if(V::get('DBG_TS', 0, $_GET) > 0){echo'<pre style="max-height:200px;overflow:auto;border:1px solid orange;text-align:left;">sql (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($sql);echo'</pre>';}
  1164. $res = $db->query($sql);
  1165. while ($r = $db->fetch($res)) {
  1166. $rows[$r->ID][] = $r;
  1167. }
  1168. if(V::get('DBG_TS', 0, $_GET) > 0){echo'<pre style="max-height:200px;overflow:auto;border:1px solid orange;text-align:left;">rows (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($rows);echo'</pre>';}
  1169. if(V::get('DBG_TS', 0, $_GET) > 0){echo'<pre style="max-height:200px;overflow:auto;border:1px solid orange;text-align:left;">param_out (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($this->param_out);echo'</pre>';}
  1170. {// convert param_out
  1171. $format = $this->param_out->format;
  1172. foreach ($this->param_out->values as $kFldName => $vFldID) {
  1173. $format = str_replace("{{$kFldName}}", "{f_{$vFldID}}", $format);
  1174. }
  1175. if(V::get('DBG_TS', 0, $_GET) > 0){echo'<pre style="max-height:200px;overflow:auto;border:1px solid orange;text-align:left;">format (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($format);echo'</pre>';}
  1176. }
  1177. $rowsOut = array();
  1178. foreach ($rows as $id => $vRows) {
  1179. foreach ($vRows as $r) {
  1180. $rowOut = $format;
  1181. foreach ($r as $kFldName => $vVal) {
  1182. $rowOut = str_replace("{{$kFldName}}", "{$vVal}", $rowOut);
  1183. }
  1184. $rowsOut[$id][] = $rowOut;
  1185. }
  1186. }
  1187. if(V::get('DBG_TS', 0, $_GET) > 0){echo'<pre style="max-height:200px;overflow:auto;border:1px solid orange;text-align:left;">rowsOut (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($rowsOut);echo'</pre>';}
  1188. return $rowsOut;
  1189. }
  1190. public function getTblAliasList() {
  1191. return $this->tblAliasList;
  1192. }
  1193. public static function getCache() {
  1194. if (!array_key_exists('Typespecial_Cache', $_SESSION)) {
  1195. $_SESSION['Typespecial_Cache'] = array();
  1196. }
  1197. return $_SESSION['Typespecial_Cache'];
  1198. }
  1199. private function saveCache() {
  1200. if(V::get('DBG_TS', 0, $_GET) > 3){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">Typespecial_Cache (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($_SESSION['Typespecial_Cache']);echo'</pre>';}
  1201. $typeSpecialID = $_SESSION['Typespecial_Cache']['map'][$this->fldID];
  1202. $_SESSION['Typespecial_Cache'][$typeSpecialID] = array('param_out'=>$this->param_out, 'sqlQuery'=>$this->sqlQuery, 'tblAliasList'=>$this->tblAliasList);
  1203. }
  1204. public static function getInstance($fieldID, $colName) {
  1205. // DBG::log("Typespecial::getInstance({$fieldID}, {$colName})");
  1206. if (!empty($colName)) {
  1207. Lib::loadClass('Config');
  1208. $LIB_CLASS_NAME_PREFIX = Config::get('LIB_CLASS_NAME_PREFIX');
  1209. if (!empty($LIB_CLASS_NAME_PREFIX)) {
  1210. $clsName = "{$LIB_CLASS_NAME_PREFIX}_TypespecialVariable";
  1211. if (Lib::tryLoadClass($clsName)) {
  1212. //$typeSpecial = $clsName::getInstance($fieldID, $colName);
  1213. $typeSpecial = call_user_func(array($clsName, 'getInstance'), $fieldID, $colName);
  1214. if ($typeSpecial) {
  1215. return $typeSpecial;
  1216. }
  1217. }
  1218. }
  1219. Lib::loadClass('TypespecialVariable');
  1220. $typeSpecial = TypespecialVariable::getInstance($fieldID, $colName);
  1221. // DBG::log($typeSpecial, 'array', "TypespecialVariable::getInstance({$fieldID}, {$colName})");
  1222. if ($typeSpecial) {
  1223. return $typeSpecial;
  1224. }
  1225. }
  1226. $cache = self::getCache();
  1227. $map = V::get('map', '', $cache);
  1228. if (!empty($map) && array_key_exists($fieldID, $map)) {
  1229. $typespecialID = $map[$fieldID];
  1230. if (array_key_exists($typespecialID, $cache)) {
  1231. $typeSpecial = new Typespecial($fieldID, $colName, $cache[$typespecialID]);
  1232. if ($typeSpecial->validate()) {
  1233. return $typeSpecial;
  1234. }
  1235. }
  1236. }
  1237. return null;
  1238. }
  1239. public function getReturnId() {
  1240. if (!isset($this->param_out)) return null;
  1241. if (!isset($this->param_out->retID)) return null;
  1242. return $this->param_out->retID;
  1243. }
  1244. public function getReturnData($tblId, $rowId, $fieldName) {
  1245. if (!isset($this->param_out)) return null;
  1246. if (!isset($this->param_out->retID)) return null;
  1247. if ($this->param_out->retID <= 0) return null;
  1248. $retData = new stdClass();
  1249. $retData->tbl_id = 0;
  1250. $retData->fld_name = null;
  1251. $retData->tbl_name = null;
  1252. $retData->tbl_label = null;
  1253. $spValues = $this->getEditSelectedValuesByIds($tblId, $rowId, $fieldName, '');
  1254. if(V::get('DBG_TS', 0, $_GET) > 1){echo'<pre style="max-height:200px;overflow:auto;border:1px solid orange;text-align:left;">getEditSelectedValuesByIds (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($spValues);echo'</pre>';}
  1255. if (empty($spValues)) return null;
  1256. $itemsJson = array();
  1257. foreach ($spValues as $kID => $val) {
  1258. $itemJson = new stdClass();
  1259. $itemJson->id = $kID;
  1260. $itemJson->label = $val;
  1261. $itemsJson[] = $itemJson;
  1262. }
  1263. if (empty($itemsJson)) return null;
  1264. $retData->items = $itemsJson;
  1265. $db = DB::getDB();
  1266. $sql = "select z.`ID`
  1267. , z.`DESC` as fld_name
  1268. , tbl.`ID` as tbl_id
  1269. , tbl.`DESC` as tbl_name
  1270. , tbl.`DESC_PL` as tbl_label
  1271. from `CRM_LISTA_ZASOBOW` as z
  1272. join `CRM_LISTA_ZASOBOW` tbl on (tbl.`ID`=z.`PARENT_ID`)
  1273. where
  1274. z.`ID`='{$this->param_out->retID}'
  1275. and z.`TYPE`='KOMORKA'
  1276. and tbl.`TYPE`='TABELA'
  1277. ";
  1278. if(V::get('DBG_TS', 0, $_GET) > 2){echo'<pre style="max-height:200px;overflow:auto;border:1px solid orange;text-align:left;">sql (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($sql);echo'</pre>';}
  1279. $res = $db->query($sql);
  1280. if ($r = $db->fetch($res)) {
  1281. $retData->fld_name = $r->fld_name;
  1282. $retData->tbl_id = $r->tbl_id;
  1283. $retData->tbl_name = $r->tbl_name;
  1284. $retData->tbl_label = $r->tbl_label;
  1285. }
  1286. if(V::get('DBG_TS', 0, $_GET) > 1){echo'<pre style="max-height:200px;overflow:auto;border:1px solid orange;text-align:left;">retData (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($retData);echo'</pre>';}
  1287. if ($retData->tbl_id > 0) {
  1288. return $retData;
  1289. }
  1290. return null;
  1291. }
  1292. }