Typespecial.php 55 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387
  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. var fldExportNode = document.getElementById('f' + i)
  762. if (fldExportNode) {
  763. // console.log('--- onItemAdd jQuery(#f' + i + ').val(', curSel.exports[i], '): fieldExport.is(input:',fieldExport.is('input'),'select:',fieldExport.is('select'),'textarea:',fieldExport.is('textarea'),')', fieldExport);
  764. switch (fldExportNode.tagName) {
  765. case 'INPUT': jQuery('#f' + i).val(curSel.exports[i]); break;
  766. case 'SELECT': /* TODO: add option and select //jQuery('#f' + i).val(curSel.exports[i]); */; break;
  767. case 'TEXTAREA': jQuery('#f' + i).val(curSel.exports[i]); break;
  768. }
  769. }
  770. }
  771. }
  772. }
  773. },
  774. score: function(query) {
  775. // console.log('Typespecial({$fName})::score: q(', query, ')');
  776. var score = this.getScoreFunction(query);
  777. return function(item) {
  778. var retScore = 0, lName = ('' + item.name).toLowerCase(), lQuery = query.toLowerCase();
  779. if (query.search(' ') > -1) {
  780. retScore = score(item);
  781. }
  782. else {
  783. if (lQuery + ':' == lName.substr(0, lQuery.length + 1)) {
  784. retScore = 100;
  785. } else if (lName.search(lQuery) > -1) {
  786. retScore = 90 - lName.search(lQuery);
  787. } else {
  788. retScore = 0;
  789. }
  790. }
  791. // console.log('Typespecial({$fName})::score: q(', lQuery, ') , retScore(', retScore, '), score(', score(item), '), item.name(', item.name, ') item.id:', item.id);
  792. return retScore;
  793. };
  794. },
  795. load: function(query, callback) {
  796. // if (!query.length) return callback();
  797. $.ajax({
  798. url: '{$ajaxDataUrlBase}',
  799. data: 'q=' + encodeURIComponent(query),
  800. type: 'POST',
  801. error: function() {
  802. callback();
  803. },
  804. success: function(res) {
  805. var i, prefix, prefixLen;
  806. for (i in res) {
  807. prefix = '' + res[i].id;
  808. prefixLen = prefix.length;
  809. if (prefixLen > 0 && prefix !== res[i].name.substr(0, prefixLen)) {
  810. res[i].name = res[i].id + ': ' + res[i].name;
  811. }
  812. res[i]['\$order'] = 1 + (parseInt(i) || 0);// set order from request
  813. }
  814. // console.log('Typespecial({$fName})::res',res);
  815. callback(res);
  816. }
  817. });
  818. }
  819. });
  820. })()
  821. " . '</script>';
  822. return $out;
  823. }
  824. public function _getValues($query) {
  825. $rows = array();
  826. $db = DB::getDB();// TODO: get from DB by zasoby ID
  827. DBG::log(['msg'=>"session", $_SESSION['Typespecial_Cache']['sqlTablesInfo']]);
  828. DBG::log(['msg'=>"this", $this]);
  829. $query = trim($query);
  830. $sqlWhereAdd = "";
  831. if (!empty($query)) {
  832. Lib::loadClass('SqlQueryWhereBuilder');
  833. $queryWhereBuilder = new SqlQueryWhereBuilder();
  834. $qArr = $queryWhereBuilder->splitQueryToWords($query);
  835. DBG::log(['msg'=>"qArr", $qArr]);
  836. if (!empty($qArr)) {
  837. $sqlWhereAnd = array();
  838. foreach ($qArr as $q) {
  839. $sqlSearchWord = DB::getPDO()->quote(
  840. (is_numeric($q)) ? "{$q}%" : "%{$q}%",
  841. PDO::PARAM_STR
  842. );
  843. $sqlWhereOr = array();
  844. foreach ($this->param_out->alias as $fldID => $fldName) {
  845. if (false === strpos($this->param_out->format, "{{$fldName}}")) continue;
  846. $tblInfo = V::get($fldID, null, $_SESSION['Typespecial_Cache']['sqlTablesInfo']);
  847. if ($tblInfo) {
  848. $sqlWhereOr[] = "`t_{$tblInfo->tbl_id}`.`{$fldName}` like {$sqlSearchWord}";
  849. }
  850. }
  851. if (!empty($sqlWhereOr)) {
  852. $sqlWhereAnd[] = "(" . implode(" or ", $sqlWhereOr) . ")";
  853. }
  854. }
  855. if (!empty($sqlWhereAnd)) {
  856. $sqlWhereAdd = " and (" . implode(" and ", $sqlWhereAnd) . ")";
  857. }
  858. }
  859. }
  860. DBG::log(['msg'=>"this", $this]);
  861. Lib::loadClass('ACL');
  862. Lib::loadClass('AclQueryFeatures');
  863. try {
  864. $andSql = array_map(
  865. function ($tableName, $idTable) {
  866. $tableAcl = User::getAcl()->getObjectAcl('default_db', $tableName);
  867. return ACL::query($tableAcl, "t_{$idTable}")
  868. ->where( (new AclQueryFeatures($tableAcl, $params = []))->parseSpecialFilterAccess() )
  869. ->generateWhereSql()
  870. ;
  871. },
  872. $this->tblAliasList, array_keys($this->tblAliasList)
  873. );
  874. $andSql = array_filter($andSql, ['V', 'filterNotEmpty']);
  875. if (!empty($andSql)) $sqlWhereAdd .= "\n" . " and " . implode(" and ", $andSql);
  876. } catch (Exception $e) {
  877. DBG::log($e);
  878. return [];
  879. }
  880. $sqlLimit = V::get('limit', 0, $this->sqlQuery, 'int');
  881. $sqlLimit = ($sqlLimit > 0) ? $sqlLimit : 20;
  882. $histRows = array();
  883. {
  884. if (empty($query)) {
  885. if (V::get('TEST_SORT', '', $_GET)) echo '{' . "\n";
  886. if (V::get('TEST_SORT', '', $_GET)) echo '"this": ' . json_encode($this) . ",";
  887. if (!empty($this->fldID) && is_numeric($this->fldID)) {
  888. $fldName = $this->param_out->alias[ $this->param_out->retID ];
  889. $zasobCellInfo = DB::getPDO()->fetchFirst("
  890. select z.`DESC` as fldName, t.`DESC` as tblName
  891. from CRM_LISTA_ZASOBOW z
  892. join CRM_LISTA_ZASOBOW t on(t.ID = z.PARENT_ID)
  893. where z.ID = '{$this->fldID}'
  894. and z.`TYPE` = 'KOMORKA'
  895. and t.`TYPE` = 'TABELA'
  896. ");
  897. if (!empty($zasobCellInfo)) {
  898. $fldName = $zasobCellInfo['fldName'];
  899. $tblName = $zasobCellInfo['tblName'];
  900. if (V::get('TEST_SORT', '', $_GET)) echo '"field_name": "'.$fldName.'",';
  901. if (V::get('TEST_SORT', '', $_GET)) echo '"table_name": "'.$tblName.'",';
  902. $userLogin = V::get('TEST_SORT_LOGIN', User::getLogin(), $_REQUEST);
  903. try {
  904. $histRows = DB::getPDO()->fetchAll("
  905. select h.`{$fldName}`
  906. , count(1) as cnt
  907. from `{$tblName}_HIST` h
  908. where h.A_RECORD_UPDATE_AUTHOR = '{$userLogin}'
  909. and h.`{$fldName}` != 'N/S;'
  910. and h.`{$fldName}` != ''
  911. and h.`{$fldName}` != '0'
  912. and h.`{$fldName}` IS NOT NULL
  913. and h.`{$fldName}` != 'NULL'
  914. group by h.`{$fldName}`
  915. order by cnt desc
  916. limit 10
  917. ");
  918. } catch (Exception $e) {
  919. if (V::get('TEST_SORT', '', $_GET)) echo '"Exception": ' . json_encode($e) . ',';
  920. }
  921. if (V::get('TEST_SORT', '', $_GET)) echo '"hist_rows_stats": ' . json_encode($histRows) . ',';
  922. }
  923. }
  924. }
  925. }
  926. $rawRows = DB::getPDO()->fetchAll("
  927. select " . implode("\n\t\t,", $this->sqlQuery->select) . "
  928. from " . implode(", ", $this->sqlQuery->from) . "
  929. where {$this->sqlQuery->where}
  930. {$sqlWhereAdd}
  931. limit {$sqlLimit}
  932. ");
  933. foreach ($rawRows as $r) {
  934. $retID = V::get("f_{$this->param_out->retID}", '', $r);
  935. $rows[$retID] = (object)$r;
  936. }
  937. if (!empty($histRows)) {
  938. $sordedRows = array();
  939. $orderIndex = 1000;
  940. foreach ($histRows as $histRow) {
  941. $retValue = $histRow[$fldName];
  942. if (array_key_exists($retValue, $rows)) {
  943. $sordedRows[$retValue] = $rows[$retValue];
  944. $sordedRows[$retValue]->{'$order'} = $orderIndex--;
  945. unset($rows[$retValue]);
  946. } else {
  947. try {
  948. $sordedRows[$retValue] = (object)DB::getPDO()->fetchFirst("
  949. select " . implode("\n\t\t,", $this->sqlQuery->select) . "
  950. from " . implode(", ", $this->sqlQuery->from) . "
  951. where {$this->sqlQuery->where}
  952. {$sqlWhereAdd}
  953. having `f_{$this->param_out->retID}` = '{$retValue}'
  954. ");
  955. if (V::get('TEST_SORT', '', $_GET)) echo '"test_fetch_'.$retValue.'":' . json_encode($sordedRows[$retValue]) . ",";
  956. if (!empty($sordedRows[$retValue])) {
  957. $sordedRows[$retValue]->{'$order'} = $orderIndex--;
  958. }
  959. } catch (Exception $e) {
  960. DBG::log($e);
  961. }
  962. }
  963. }
  964. foreach ($rows as $key => $val) {
  965. $sordedRows[$key] = $val;
  966. }
  967. $rows = $sordedRows;
  968. }
  969. if (V::get('TEST_SORT', '', $_GET)) echo '"rows":' . json_encode($rows) . ",";
  970. if (V::get('TEST_SORT', '', $_GET)) die('"end":"end"' . "\n" . '}');
  971. DBG::log(['msg'=>"rows", $rows]);
  972. return $rows;
  973. }
  974. public function getValues($query) {
  975. $rows = $this->_getValues($query);
  976. DBG::log(['msg'=>"param_out", $this->param_out]);
  977. {// convert param_out
  978. $format = $this->param_out->format;
  979. foreach ($this->param_out->values as $kFldName => $vFldID) {
  980. $format = str_replace("{{$kFldName}}", "{f_{$vFldID}}", $format);
  981. }
  982. DBG::log(['msg'=>"format", $format]);
  983. }
  984. $rows_out = array();
  985. foreach ($rows as $ind => $r) {
  986. $row_out = $format;
  987. foreach ($r as $kFldName => $vVal) {
  988. $row_out = str_replace("{{$kFldName}}", "{$vVal}", $row_out);
  989. }
  990. $rows_out[$ind] = $row_out;
  991. }
  992. DBG::log(['msg'=>"rows_out", $rows_out]);
  993. return $rows_out;
  994. }
  995. public function getValuesWithExports($query) {
  996. $rows = $this->_getValues($query);
  997. DBG::log(['msg'=>"param_out", $this->param_out]);
  998. {// convert param_out
  999. $format = $this->param_out->format;
  1000. foreach ($this->param_out->values as $kFldName => $vFldID) {
  1001. $format = str_replace("{{$kFldName}}", "{f_{$vFldID}}", $format);
  1002. }
  1003. DBG::log(['msg'=>"format", $format]);
  1004. }
  1005. $retObjList = array();
  1006. foreach ($rows as $ind => $r) {
  1007. $vObj = new stdClass();
  1008. $vObj->id = $ind;
  1009. $vObj->param_out = $format;
  1010. foreach ($r as $kFldName => $vVal) {
  1011. $vObj->param_out = str_replace("{{$kFldName}}", "{$vVal}", $vObj->param_out);
  1012. }
  1013. if (!empty($this->param_out->exports)) {
  1014. $vObj->exports = array();
  1015. foreach ($this->param_out->exports as $kExportID => $vExportOut) {
  1016. $vObj->exports[$kExportID] = new stdClass();
  1017. foreach ($this->param_out->values as $kFldName => $vFldID) {
  1018. $vExportOut = str_replace("{{$kFldName}}", "{f_{$vFldID}}", $vExportOut);
  1019. }
  1020. foreach ($r as $kFldName => $vVal) {
  1021. $vExportOut = str_replace("{{$kFldName}}", "{$vVal}", $vExportOut);
  1022. }
  1023. $vObj->exports[$kExportID] = $vExportOut;
  1024. }
  1025. }
  1026. if (!empty($r->{'$order'})) {
  1027. $vObj->{'$order'} = $r->{'$order'};
  1028. }
  1029. $retObjList[$ind] = $vObj;
  1030. }
  1031. DBG::log(['msg'=>"retObjList", $retObjList]);
  1032. return $retObjList;
  1033. }
  1034. public function getEditSelectedValuesByIds($tblId, $rowId, $fieldName, $fieldValue = '') {
  1035. $rows = array();
  1036. $db = DB::getDB();// TODO: get from DB by zasoby ID
  1037. 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
  1038. 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
  1039. 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
  1040. 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
  1041. $retFldName = '';
  1042. $sqlWhereAdd = array();
  1043. $tblFound = null;
  1044. foreach ($_SESSION['Typespecial_Cache']['sqlTablesInfo'] as $vTblInfo) {
  1045. if ($vTblInfo->tbl_id == $tblId) {
  1046. $tblFound = $vTblInfo;
  1047. break;
  1048. }
  1049. }
  1050. if (!$tblFound) {
  1051. $tblFound = (object)DB::getPDO()->fetchFirst("
  1052. select z.`ID` as tbl_id
  1053. , z.`PARENT_ID` as db_id
  1054. , z.`DESC` as tbl_name
  1055. from `CRM_LISTA_ZASOBOW` as z
  1056. where z.`ID`={$tblId}
  1057. ");
  1058. 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
  1059. }
  1060. if (!$tblFound) {
  1061. 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
  1062. return false;
  1063. }
  1064. //echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">$vTblInfo (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($vTblInfo);echo'</pre>';
  1065. $sqlFrom = $this->sqlQuery->from;
  1066. $sqlSelect = $this->sqlQuery->select;
  1067. if ($this->param_out->retID > 0) {
  1068. $sqlWhereAdd[] = "`tr_{$tblId}`.`ID`={$rowId}";
  1069. if (array_key_exists($this->param_out->retID, $_SESSION['Typespecial_Cache']['sqlTablesInfo'])) {
  1070. $retTblId = $_SESSION['Typespecial_Cache']['sqlTablesInfo'][$this->param_out->retID]->tbl_id;
  1071. $retName = $this->param_out->alias[$this->param_out->retID];
  1072. $sqlWhereAdd[] = "`t_{$retTblId}`.`{$retName}`=`tr_{$tblId}`.`{$fieldName}`";
  1073. } else {
  1074. return false;
  1075. }
  1076. $sqlSelect[] = "`tr_{$tblId}`.`ID`";
  1077. $sqlFrom[] = "`{$tblFound->tbl_name}` as tr_{$tblFound->tbl_id}";
  1078. $retFldName = "f_{$this->param_out->retID}";
  1079. $foundInSelect = false;
  1080. foreach ($sqlSelect as $vSelectStr) {
  1081. if (false !== strpos($vSelectStr, $retFldName)) {
  1082. $foundInSelect = true;
  1083. }
  1084. }
  1085. if (!$foundInSelect) $retFldName = '';
  1086. }
  1087. else {// if no retID then TYPESPECIAL is link
  1088. $sqlWhereAdd[] = "`t_{$tblId}`.`ID`={$rowId}";
  1089. $sqlSelect[] = "`t_{$tblId}`.`ID`";
  1090. }
  1091. $sqlWhereAdd = (!empty($sqlWhereAdd))? " and " . implode(" and ", $sqlWhereAdd) : "";
  1092. $sqlLimit = V::get('limit', 0, $this->sqlQuery, 'int');
  1093. if ($sqlLimit <= 0) {
  1094. $sqlLimit = 20;
  1095. }
  1096. $sqlLimit = "limit {$sqlLimit}";
  1097. $sqlFrom = implode(", ", $sqlFrom);
  1098. $sql = "select " . implode("\n\t\t,", $sqlSelect) . "
  1099. from {$sqlFrom}
  1100. where {$this->sqlQuery->where}
  1101. {$sqlWhereAdd}
  1102. {$sqlLimit}
  1103. ";
  1104. 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>';}
  1105. $res = $db->query($sql);
  1106. while ($r = $db->fetch($res)) {
  1107. $rows[] = $r;
  1108. }
  1109. 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>';}
  1110. 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>';}
  1111. {// convert param_out
  1112. $format = $this->param_out->format;
  1113. foreach ($this->param_out->values as $kFldName => $vFldID) {
  1114. $format = str_replace("{{$kFldName}}", "{f_{$vFldID}}", $format);
  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;">format (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($format);echo'</pre>';}
  1117. }
  1118. 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>';}
  1119. $rowsOut = array();
  1120. foreach ($rows as $r) {
  1121. $rowOut = $format;
  1122. foreach ($r as $kFldName => $vVal) {
  1123. $rowOut = str_replace("{{$kFldName}}", "{$vVal}", $rowOut);
  1124. }
  1125. if ($retFldName) {
  1126. $rowsOut[$r->{$retFldName}] = $rowOut;
  1127. } else {
  1128. $rowsOut[] = $rowOut;
  1129. }
  1130. }
  1131. 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>';}
  1132. return $rowsOut;
  1133. }
  1134. public function getValuesByIds($tblId, $ids) {
  1135. $rows = array();
  1136. $db = DB::getDB();// TODO: get from DB by zasoby ID
  1137. 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
  1138. 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
  1139. 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
  1140. $sqlWhereAdd = array();
  1141. $tblFound = null;
  1142. foreach ($_SESSION['Typespecial_Cache']['sqlTablesInfo'] as $vTblInfo) {
  1143. if ($vTblInfo->tbl_id == $tblId) {
  1144. $tblFound = $vTblInfo;
  1145. break;
  1146. }
  1147. }
  1148. if (!$tblFound) {
  1149. return false;
  1150. }
  1151. $sqlWhereAdd[] = "`t_{$tblId}`.`ID` in(" . implode(",", $ids) . ")";
  1152. $sqlWhereAdd = (!empty($sqlWhereAdd))? " and " . implode(" and ", $sqlWhereAdd) : "";
  1153. $sqlLimit = V::get('limit', 0, $this->sqlQuery, 'int');
  1154. if ($sqlLimit <= 0) {
  1155. $sqlLimit = 20;
  1156. }
  1157. $sqlLimit = "limit {$sqlLimit}";
  1158. $sql = "select " . implode("\n\t\t,", $this->sqlQuery->select) . "
  1159. , `t_{$tblId}`.`ID`
  1160. from " . implode(", ", $this->sqlQuery->from) . "
  1161. where {$this->sqlQuery->where}
  1162. {$sqlWhereAdd}
  1163. {$sqlLimit}
  1164. ";
  1165. 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>';}
  1166. $res = $db->query($sql);
  1167. while ($r = $db->fetch($res)) {
  1168. $rows[$r->ID][] = $r;
  1169. }
  1170. 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>';}
  1171. 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>';}
  1172. {// convert param_out
  1173. $format = $this->param_out->format;
  1174. foreach ($this->param_out->values as $kFldName => $vFldID) {
  1175. $format = str_replace("{{$kFldName}}", "{f_{$vFldID}}", $format);
  1176. }
  1177. 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>';}
  1178. }
  1179. $rowsOut = array();
  1180. foreach ($rows as $id => $vRows) {
  1181. foreach ($vRows as $r) {
  1182. $rowOut = $format;
  1183. foreach ($r as $kFldName => $vVal) {
  1184. $rowOut = str_replace("{{$kFldName}}", "{$vVal}", $rowOut);
  1185. }
  1186. $rowsOut[$id][] = $rowOut;
  1187. }
  1188. }
  1189. 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>';}
  1190. return $rowsOut;
  1191. }
  1192. public function getTblAliasList() {
  1193. return $this->tblAliasList;
  1194. }
  1195. public static function getCache() {
  1196. if (!array_key_exists('Typespecial_Cache', $_SESSION)) {
  1197. $_SESSION['Typespecial_Cache'] = array();
  1198. }
  1199. return $_SESSION['Typespecial_Cache'];
  1200. }
  1201. private function saveCache() {
  1202. 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>';}
  1203. $typeSpecialID = $_SESSION['Typespecial_Cache']['map'][$this->fldID];
  1204. $_SESSION['Typespecial_Cache'][$typeSpecialID] = array('param_out'=>$this->param_out, 'sqlQuery'=>$this->sqlQuery, 'tblAliasList'=>$this->tblAliasList);
  1205. }
  1206. public static function getInstance($fieldID, $colName) {
  1207. // DBG::log("Typespecial::getInstance({$fieldID}, {$colName})");
  1208. if (!empty($colName)) {
  1209. Lib::loadClass('Config');
  1210. $LIB_CLASS_NAME_PREFIX = Config::get('LIB_CLASS_NAME_PREFIX');
  1211. if (!empty($LIB_CLASS_NAME_PREFIX)) {
  1212. $clsName = "{$LIB_CLASS_NAME_PREFIX}_TypespecialVariable";
  1213. if (Lib::tryLoadClass($clsName)) {
  1214. //$typeSpecial = $clsName::getInstance($fieldID, $colName);
  1215. $typeSpecial = call_user_func(array($clsName, 'getInstance'), $fieldID, $colName);
  1216. if ($typeSpecial) {
  1217. return $typeSpecial;
  1218. }
  1219. }
  1220. }
  1221. Lib::loadClass('TypespecialVariable');
  1222. $typeSpecial = TypespecialVariable::getInstance($fieldID, $colName);
  1223. // DBG::log($typeSpecial, 'array', "TypespecialVariable::getInstance({$fieldID}, {$colName})");
  1224. if ($typeSpecial) {
  1225. return $typeSpecial;
  1226. }
  1227. }
  1228. $cache = self::getCache();
  1229. $map = V::get('map', '', $cache);
  1230. if (!empty($map) && array_key_exists($fieldID, $map)) {
  1231. $typespecialID = $map[$fieldID];
  1232. if (array_key_exists($typespecialID, $cache)) {
  1233. $typeSpecial = new Typespecial($fieldID, $colName, $cache[$typespecialID]);
  1234. if ($typeSpecial->validate()) {
  1235. return $typeSpecial;
  1236. }
  1237. }
  1238. }
  1239. return null;
  1240. }
  1241. public function getReturnId() {
  1242. if (!isset($this->param_out)) return null;
  1243. if (!isset($this->param_out->retID)) return null;
  1244. return $this->param_out->retID;
  1245. }
  1246. public function getReturnData($tblId, $rowId, $fieldName) {
  1247. if (!isset($this->param_out)) return null;
  1248. if (!isset($this->param_out->retID)) return null;
  1249. if ($this->param_out->retID <= 0) return null;
  1250. $retData = new stdClass();
  1251. $retData->tbl_id = 0;
  1252. $retData->fld_name = null;
  1253. $retData->tbl_name = null;
  1254. $retData->tbl_label = null;
  1255. $spValues = $this->getEditSelectedValuesByIds($tblId, $rowId, $fieldName, '');
  1256. 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>';}
  1257. if (empty($spValues)) return null;
  1258. $itemsJson = array();
  1259. foreach ($spValues as $kID => $val) {
  1260. $itemJson = new stdClass();
  1261. $itemJson->id = $kID;
  1262. $itemJson->label = $val;
  1263. $itemsJson[] = $itemJson;
  1264. }
  1265. if (empty($itemsJson)) return null;
  1266. $retData->items = $itemsJson;
  1267. $db = DB::getDB();
  1268. $sql = "select z.`ID`
  1269. , z.`DESC` as fld_name
  1270. , tbl.`ID` as tbl_id
  1271. , tbl.`DESC` as tbl_name
  1272. , tbl.`DESC_PL` as tbl_label
  1273. from `CRM_LISTA_ZASOBOW` as z
  1274. join `CRM_LISTA_ZASOBOW` tbl on (tbl.`ID`=z.`PARENT_ID`)
  1275. where
  1276. z.`ID`='{$this->param_out->retID}'
  1277. and z.`TYPE`='KOMORKA'
  1278. and tbl.`TYPE`='TABELA'
  1279. ";
  1280. 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>';}
  1281. $res = $db->query($sql);
  1282. if ($r = $db->fetch($res)) {
  1283. $retData->fld_name = $r->fld_name;
  1284. $retData->tbl_id = $r->tbl_id;
  1285. $retData->tbl_name = $r->tbl_name;
  1286. $retData->tbl_label = $r->tbl_label;
  1287. }
  1288. 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>';}
  1289. if ($retData->tbl_id > 0) {
  1290. return $retData;
  1291. }
  1292. return null;
  1293. }
  1294. }