ViewObject.php 47 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117
  1. <?php
  2. Lib::loadClass('RouteBase');
  3. Lib::loadClass('ProcesHelper');
  4. Lib::loadClass('TableAjax');
  5. // Lib::loadClass('Request');
  6. Lib::loadClass('Response');
  7. Lib::loadClass('UI');
  8. Lib::loadClass('Api_WfsNs');
  9. Lib::loadClass('Core_AclHelper');
  10. Lib::loadClass('Route_UrlAction');
  11. Lib::loadClass('Router');
  12. Lib::loadClass('Typespecial');
  13. Lib::loadClass('UserProfile');
  14. Lib::loadClass('P5');
  15. Lib::loadClass('Route_ViewTableAjax');
  16. class Route_ViewObject extends Route_ViewTableAjax {
  17. public function getTableAjaxWidget($acl) {
  18. $syncUrl = Request::getPathUri() . 'index.php?_route=ViewObject&namespace=' . $acl->getNamespace();
  19. $tbl = new TableAjax($acl);
  20. $tbl->showProcesInit(false); // TODO: activate when ready
  21. $tblLabel = $acl->getNamespace();
  22. if ('default_db' == $acl->getSourceName()) {
  23. $tblLabel = array();
  24. DBG::nicePrint($acl->getID(), '$acl->getID()');
  25. $zasobObj = ProcesHelper::getZasobTableInfo($acl->getID());
  26. DBG::nicePrint($zasobObj, '$zasobObj');
  27. $sqlId = $acl->getID();
  28. if (!$sqlId) throw new Exception("Missing zasob id!");
  29. $zasobItem = DB::getPDO()->fetchFirst("
  30. select z.ID, z.`DESC`, z.DESC_PL, z.OPIS
  31. from CRM_LISTA_ZASOBOW z
  32. where z.ID = {$sqlId}
  33. and z.`TYPE` = 'TABELA'
  34. ");
  35. DBG::nicePrint($zasobItem, '$zasobItem');
  36. // if (!$zasobObj) throw new Exception("Zasob TABELA ID=" . $acl->getID() . " nie istnieje");
  37. // if (!empty($zasobObj->DESC_PL)) $tblLabel []= $zasobObj->DESC_PL;
  38. // if (!empty($zasobObj->OPIS)) $tblLabel []= $zasobObj->OPIS;
  39. if (!$zasobItem) throw new Exception("Zasob TABELA ID=" . $acl->getID() . " nie istnieje");
  40. if (!empty($zasobItem['DESC_PL'])) $tblLabel []= $zasobItem['DESC_PL'];
  41. if (!empty($zasobItem['OPIS'])) $tblLabel []= $zasobItem['OPIS'];
  42. $tblLabel = implode(" - ", $tblLabel);
  43. }
  44. $tbl->setSyncUrl($syncUrl);
  45. $tbl->setLabel($tblLabel);
  46. $tbl->addRowFunction('edit');
  47. $tbl->addRowFunction('hist');
  48. $tbl->addRowFunction('files');
  49. $tbl->addRowFunction('cp');
  50. $tbl->addRowFunction('msgs');
  51. return $tbl;
  52. }
  53. public function defaultAction() {
  54. UI::gora();
  55. UI::menu();
  56. try {
  57. $namespace = V::get('namespace', '', $_GET, 'word');
  58. if (!$namespace) {
  59. $typeName = V::get('typeName', '', $_GET, 'word');
  60. if (!$typeName) throw new Exception("Wrong param typeName");
  61. $namespace = Api_WfsNs::getBaseWfsUri() . '/' . str_replace(':', '/', $typeName);
  62. }
  63. $acl = P5::getAclByNamespace($namespace, $forceTblAclInit = ('1' == V::get('_force', '', $_GET)));
  64. $forceFilterInit = array();
  65. $filterInit = new stdClass();
  66. $filterInit->currSortCol = $acl->getPrimaryKeyField();
  67. $filterInit->currSortFlip = 'desc';
  68. foreach ($_GET as $k => $v) {
  69. if (strlen($k) > 3 && substr($k, 0, 2) == 'f_' && !empty($v)) {// filter prefix
  70. $filterInit->$k = $v;
  71. }
  72. else if (strlen($k) > 4 && substr($k, 0, 3) == 'sf_' && !empty($v)) {// special filter prefix
  73. $filterInit->$k = $v;
  74. }
  75. else if (strlen($k) > 4 && substr($k, 0, 3) == 'ff_' && !empty($v)) {// force filter prefix
  76. $fldName = substr($k, 3);
  77. $forceFilterInit[$fldName] = $v;
  78. }
  79. }
  80. $tbl = $this->getTableAjaxWidget($acl);
  81. $tbl->setFilterInit($filterInit);
  82. if (!empty($forceFilterInit)) $tbl->setForceFilterInit($forceFilterInit);
  83. if (V::get('DBG_INST', '', $_GET)) { // TODO: TEST namespace
  84. $siblings = ACL::getNamespaceSiblings($namespace);
  85. DBG::nicePrint($siblings, '$siblings');
  86. $filtrInstance = V::get('f_instance', [], $_POST, 'array');
  87. DBG::nicePrint($filtrInstance, '$filtrInstance');
  88. $sibling = 'default_db/CRM_PROCES/PROCES_INIT'; DBG::nicePrint(array_merge(['type'=>"radio", 'name'=>"f_instance[{$sibling}]", 'value'=>'YES'], ('YES' === V::get($sibling, '', $filtrInstance)) ? ['checked' => "checked"] : []), "merge {$sibling} YES");
  89. $sibling = 'default_db/CRM_PROCES/PROCES_INIT'; DBG::nicePrint(array_merge(['type'=>"radio", 'name'=>"f_instance[{$sibling}]", 'value'=>'NO'], ('NO' === V::get($sibling, '', $filtrInstance)) ? ['checked' => "checked"] : []), "merge {$sibling} NO");
  90. $_ = array(UI, 'h');
  91. echo $_('form', ['method' => "POST", 'style' => "width:600px; border:1px solid #ddd; border-radius:2px"], [
  92. $_('div', ['style' => "background-color:#ddd"], "Test Filtr instancji"),
  93. $_('div', ['style' => "padding:8px"], array_map(function ($sibling) use ($filtrInstance, $_) {
  94. return $_('div', [], [
  95. $_('label', ['style' => "margin:0 8px"], [
  96. $_('input', array_merge(['type'=>"radio", 'name'=>"f_instance[{$sibling}]", 'value'=>'YES'], ('YES' === V::get($sibling, '', $filtrInstance)) ? ['checked' => "checked"] : [])),
  97. " TAK "
  98. ]),
  99. $_('label', ['style' => "margin:0 8px"], [
  100. $_('input', array_merge(['type'=>"radio", 'name'=>"f_instance[{$sibling}]", 'value'=>'NO'], ('NO' === V::get($sibling, '', $filtrInstance)) ? ['checked' => "checked"] : [])),
  101. " NIE "
  102. ]),
  103. $_('label', ['style' => "margin:0 8px"], [
  104. $_('input', ['type'=>"radio", 'name'=>"f_instance[{$sibling}]", 'value'=>'x']),
  105. " pomiń "
  106. ]),
  107. // $_('button', ['onClick'=>"this.form.f_instance['{$sibling}'].value = ''; return false"], "odznacz"),
  108. $_('button', ['onClick'=>"console.log(this.form.elements['f_instance[{$sibling}]']); this.form.elements['f_instance[{$sibling}]'].value = 'x'; return false"], "odznacz"),
  109. " - {$sibling}"
  110. ]);
  111. }, $siblings)),
  112. $_('div', [], [
  113. $_('input', ['type'=>"hidden", 'name'=>'_route', 'value'=>"ViewObject"]),
  114. $_('input', ['type'=>"hidden", 'name'=>'namespace', 'value'=>$namespace]),
  115. $_('input', ['type'=>"submit", 'value'=>"Filtruj - TEST"]),
  116. ]),
  117. ]);
  118. DBG::nicePrint($_POST, '$_POST');
  119. {
  120. $args = $_POST;
  121. $fIsInstance = [];
  122. $fIsNotInstance = [];
  123. if (!empty($args['f_instance'])) {
  124. foreach ($args['f_instance'] as $inst => $selected) {
  125. if ('YES' === $selected) {
  126. $fIsInstance[] = $inst;
  127. } else if ('NO' === $selected) {
  128. $fIsNotInstance[] = $inst;
  129. }
  130. }
  131. }
  132. }
  133. $items = $acl->getItems([
  134. // TODO: 'propertyName' => "*,@instance",
  135. 'f_is_instance' => $fIsInstance,
  136. 'f_is_not_instance' => $fIsNotInstance,
  137. '@instances' => '1',
  138. 'limit' => 10
  139. ]);
  140. $rootNamespace = $acl->getRootNamespace();
  141. DBG::nicePrint($rootNamespace, '$rootNamespace');
  142. $jsRenderFunName = 'render_dropdown_instances_' . substr(md5(time()), 0, 6);
  143. DBG::nicePrint($jsRenderFunName, '$jsRenderFunName');
  144. UI::table([
  145. 'rows' => array_map(function($row) use ($namespace, $siblings, $rootNamespace, $jsRenderFunName) {
  146. return [
  147. 'ID' => $row['ID'],
  148. 'DESC' => $row['DESC'],
  149. 'TYPE' => $row['TYPE'],
  150. 'instances' => UI::h('div', ['class'=>"p5UI__dropdown-wrap"], [
  151. UI::h('button', [
  152. // 'onClick' => "p5UI__dropdown(event, this, 'left bottom')",
  153. 'onClick' => "p5UI__dropdown(event, this, 'left bottom', {$jsRenderFunName}({$row['ID']}))",
  154. 'class' => "btn btn-xs btn-default p5UI__dropdown-btn"
  155. ], [
  156. '<i class="glyphicon glyphicon-menu-hamburger"></i>',
  157. " ustal instancje"
  158. ]),
  159. UI::h('div', ['class' => "p5UI__dropdown-content"]
  160. , array_merge(
  161. [
  162. UI::h('input', ['type' => "text", 'placeholder' => "Search..", 'class' => "p5UI__dropdown-input", 'onkeyup' => "p5_ViewObject_instances_filterInput(this)"], null),
  163. ]
  164. , array_map(function ($sibling) use ($row, $namespace, $rootNamespace) {
  165. return UI::h('div', ['label'=>$sibling, 'style'=>"padding:4px 0"], [
  166. UI::h('button', array_merge(['class' => "btn btn-xs btn-default",
  167. 'style' => "margin:0 4px 0 0",
  168. 'title' => "Ustaw instancje '{$sibling}'",
  169. 'onClick' => "return p5_ViewObject_instance_set(this, '{$row['ID']}', '{$sibling}', 'yes')"],
  170. (in_array($sibling, explode(',', $row['@instances']))) ? ['disabled' => "disabled"] : []
  171. ), "+"),
  172. UI::h('button', ['class' => "btn btn-xs btn-default",
  173. 'style' => "margin:0 4px 0 0",
  174. 'title' => "Usuń instancje '{$sibling}'",
  175. 'onClick' => "return p5_ViewObject_instance_set(this, '{$row['ID']}', '{$sibling}', 'no')"], "-"),
  176. UI::h('span', [], substr($sibling, strlen($rootNamespace) + 1)),
  177. ]);
  178. }, $siblings)
  179. )
  180. )
  181. ]),
  182. 'instancesList' => implode(', ', ACL::getFeatureNamespaces($namespace, $row['ID'])),
  183. ];
  184. }, $items)
  185. ]);
  186. echo UI::h('style', ['type' => "text/css"], "
  187. .p5UI__dropdown-content { min-width:400px; border:1px solid #ccc; background-color: #fff; box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2) }
  188. .p5UI__dropdown-content .p5UI__dropdown-item { display:block; color:#000; padding:4px; text-decoration:none }
  189. .p5UI__dropdown-content .p5UI__dropdown-item:hover { background-color:#ebebeb }
  190. ");
  191. echo UI::h('script', ['src'=>"static/vendor.js", 'type'=>"text/javascript"]);
  192. $jsArgs = [
  193. 'SET_INSTANCE_URL' => $this->getLink('setInstanceAjax'),
  194. 'NAMESPACE' => $namespace,
  195. 'DBG' => DBG::isActive() ? 'true' : 'false',
  196. ];
  197. UI::inlineJS(__FILE__ . '.instancesDropdown.js', [
  198. 'JS_GLOBAL_FUNCTION_NAME' => $jsRenderFunName,
  199. 'NAMESPACE' => $namespace,
  200. 'SET_INSTANCE_URL' => $this->getLink('setInstanceAjax'),
  201. 'DBG' => DBG::isActive() ? 1 : 0,
  202. 'INITIAL_DROPDOWN_DATA' => [
  203. // 'allowed_instances' => $siblings,
  204. 'allowed_instances' => array_map(function ($sibling) use ($rootNamespace) {
  205. return [
  206. 'namespace' => $sibling,
  207. 'label' => substr($sibling, strlen($rootNamespace) + 1)
  208. ];
  209. }, $siblings),
  210. 'items' => array_map(function($row) use ($namespace, $siblings, $rootNamespace, $jsRenderFunName) {
  211. return [
  212. 'pk' => $row['ID'], // TODO: $primaryKeyField
  213. 'instances' => explode(',', $row['@instances']),
  214. ];
  215. }, $items)
  216. ],
  217. ]);
  218. echo UI::h('script', [], "
  219. var SET_INSTANCE_URL = '{$jsArgs['SET_INSTANCE_URL']}'
  220. var NAMESPACE = '{$jsArgs['NAMESPACE']}'
  221. function p5_ViewObject_instance_set(n, pk, sibling, toConnect) {
  222. console.log('p5_ViewObject_instance_set pk('+pk+'), sibling('+sibling+'), toConnect('+toConnect+'), n', n);
  223. window.fetch(SET_INSTANCE_URL, {
  224. method: 'POST',
  225. headers: { 'Content-Type': 'application/json' },
  226. credentials: 'same-origin',
  227. body: JSON.stringify({
  228. namespace: NAMESPACE,
  229. primaryKey: pk,
  230. instance: sibling,
  231. toConnect: toConnect,
  232. })
  233. }).then(function (response) {
  234. return response.json()
  235. }).then(function (response) {
  236. p5UI__notifyAjaxCallback(response)
  237. console.log(response) // TODO: render list
  238. })
  239. }
  240. ");
  241. echo UI::h('script', [], "
  242. function p5_ViewObject_instances_filterInput(n) {
  243. var input, filter, ul, li, a, i, div;
  244. input = n // .id-myInput
  245. filter = input.value.toUpperCase()
  246. div = n.parentNode // .id-myDropdown
  247. a = div.getElementsByTagName('div')
  248. for (i = 0; i < a.length; i++) {
  249. if (a[i].getAttribute('label') && a[i].getAttribute('label').toUpperCase().indexOf(filter) > -1) {
  250. a[i].style.display = 'block'
  251. } else {
  252. a[i].style.display = 'none'
  253. }
  254. }
  255. }
  256. ");
  257. echo '<hr style="margin-top:300px">';
  258. exit;
  259. }
  260. echo $tbl->render();
  261. if (DBG::isActive() && V::get('DBG_ACL', '', $_GET)) {// test load perms
  262. Lib::loadClass('DebugExecutionTime');
  263. $dbgExecTime = new DebugExecutionTime();
  264. $dbgExecTime->activate();
  265. $dbgExecTime->log('start');
  266. UI::startContainer(['style'=>'border:1px solid red']);
  267. UI::tag('p', null, "TEST - load perms from db");
  268. $idTable = $acl->getID();
  269. UI::tag('p', null, "DBG idTable({$idTable})");
  270. if ($idTable > 0) {
  271. $dbgExecTime->log('before sql');
  272. $aclTableRows = DB::getPDO()->fetchAll("select * from `CRM_PROCES_idx_TABLE_TO_PROCES_PERMS_VIEW` where ID_TABLE = {$idTable}");
  273. $dbgExecTime->log('after sql', ['sql']);
  274. UI::table(['caption' => "from CRM_PROCES_idx_TABLE_TO_PROCES_PERMS_VIEW", 'rows' => $aclTableRows]);
  275. $csvIdProces = array();
  276. foreach ($aclTableRows as $row) {
  277. if (!in_array($row['ID_PROCES'], $csvIdProces)) $csvIdProces[] = $row['ID_PROCES'];
  278. }
  279. }
  280. $tableName = $acl->getName();
  281. $databaseName = DB::getPDO()->getDatabaseName();
  282. UI::table([
  283. 'caption' => "Cell to process",
  284. 'rows' => array_map(
  285. function ($row) use ($aclTableRows, $idTable) {
  286. $row['proces'] = array();
  287. $row['id_zasob'] = 0;
  288. $row['PERM_R'] = 0;
  289. $row['PERM_W'] = 0;
  290. $row['PERM_X'] = 0;
  291. $row['PERM_C'] = 0;
  292. $row['PERM_S'] = 0;
  293. $row['PERM_O'] = 0;
  294. $row['PERM_V'] = 0;
  295. $row['PERM_E'] = 0;
  296. foreach ($aclTableRows as $aclInfo) {
  297. if (strtolower($aclInfo['CELL_NAME']) == strtolower($row['COLUMN_NAME'])) {
  298. $row['proces'][] = $aclInfo['ID_PROCES'];
  299. $row['id_zasob'] = $aclInfo['ID_CELL'];
  300. $row['PERM_R'] += $aclInfo['PERM_R'];
  301. $row['PERM_W'] += $aclInfo['PERM_W'];
  302. $row['PERM_X'] += $aclInfo['PERM_X'];
  303. $row['PERM_C'] += $aclInfo['PERM_C'];
  304. $row['PERM_S'] += $aclInfo['PERM_S'];
  305. $row['PERM_O'] += $aclInfo['PERM_O'];
  306. $row['PERM_V'] += $aclInfo['PERM_V'];
  307. $row['PERM_E'] += $aclInfo['PERM_E'];
  308. }
  309. }
  310. $row['proces'] = (empty($row['proces']))
  311. ? "<i style=\"color:red\">Brak</i>"
  312. : implode(", ", $row['proces']);
  313. if (!$row['id_zasob']) $row['id_zasob'] = DB::getPDO()->fetchValue("select ID from CRM_LISTA_ZASOBOW where `DESC` = '{$row['COLUMN_NAME']}' and PARENT_ID = {$idTable} limit 1");
  314. return $row;
  315. }, DB::getPDO()->fetchAll("
  316. select t.TABLE_NAME, t.COLUMN_NAME, t.DATA_TYPE, t.COLUMN_TYPE
  317. from `information_schema`.`COLUMNS` t
  318. where t.TABLE_SCHEMA = '{$databaseName}'
  319. and t.TABLE_NAME like '{$tableName}'
  320. ")
  321. )
  322. ]);
  323. if (!empty($csvIdProces)) {
  324. $csvIdProces = implode(",", $csvIdProces);
  325. UI::tag('p', null, "DBG csvIdProces({$csvIdProces})");
  326. $userLogin = User::getLogin();
  327. $dbgExecTime->log('before sql');
  328. $rows = DB::getPDO()->fetchAll("select ID_PROCES from `CRM_PROCES_idx_USER_to_PROCES_VIEW` where ADM_ACCOUNT = '{$userLogin}' and ID_PROCES in({$csvIdProces}) group by ID_PROCES");
  329. $dbgExecTime->log('after sql', ['sql']);
  330. UI::table(['caption' => "from CRM_PROCES_idx_USER_to_PROCES_VIEW", 'rows' => $rows]);
  331. $userIdProces = array(); foreach ($rows as $row) $userIdProces[] = $row['ID_PROCES'];
  332. $userTablePerms = array();
  333. foreach ($aclTableRows as $row) {
  334. if (!in_array($row['ID_PROCES'], $userIdProces)) continue;
  335. if (array_key_exists($row['CELL_NAME'], $userTablePerms)) {
  336. $userTablePerms[ $row['CELL_NAME'] ][ 'PERM_R' ] += $row['PERM_R'];
  337. $userTablePerms[ $row['CELL_NAME'] ][ 'PERM_W' ] += $row['PERM_W'];
  338. $userTablePerms[ $row['CELL_NAME'] ][ 'PERM_X' ] += $row['PERM_X'];
  339. $userTablePerms[ $row['CELL_NAME'] ][ 'PERM_C' ] += $row['PERM_C'];
  340. $userTablePerms[ $row['CELL_NAME'] ][ 'PERM_S' ] += $row['PERM_S'];
  341. $userTablePerms[ $row['CELL_NAME'] ][ 'PERM_O' ] += $row['PERM_O'];
  342. $userTablePerms[ $row['CELL_NAME'] ][ 'PERM_V' ] += $row['PERM_V'];
  343. $userTablePerms[ $row['CELL_NAME'] ][ 'PERM_E' ] += $row['PERM_E'];
  344. } else {
  345. $userTablePerms[ $row['CELL_NAME'] ] = $row;
  346. unset($userTablePerms[ $row['CELL_NAME'] ][ 'TABLE_DESCRIPTION' ]);
  347. unset($userTablePerms[ $row['CELL_NAME'] ][ 'ID_PROCES' ]);
  348. unset($userTablePerms[ $row['CELL_NAME'] ][ 'FORM_TREAT' ]);
  349. }
  350. }
  351. UI::table(['caption' => "\$userTablePerms", 'rows' => $userTablePerms]);
  352. } else UI::alert('warning', "brak \$csvIdProces");
  353. $dbgExecTime->printDebug();
  354. UI::endContainer();
  355. }
  356. } catch (Exception $e) {
  357. UI::startContainer();
  358. UI::alert('danger', "<strong>Wystąpiły błędy!</strong> " . $e->getMessage());
  359. UI::endContainer();
  360. DBG::log($e);
  361. }
  362. UI::dol();
  363. }
  364. public function setInstanceAjaxAction() {
  365. Response::sendTryCatchJson(array($this, 'setInstanceAjax'), $args = 'JSON_FROM_REQUEST_BODY');
  366. }
  367. public function setInstanceAjax($args) {
  368. // namespace => default_db/CRM_PROCES/PROCES_INIT
  369. // primaryKey => 6
  370. // instance => default_db/CRM_PROCES/PROCES_TREE
  371. // toConnect => yes
  372. if (empty($args['namespace'])) throw new Exception("Missing namespace");
  373. if (empty($args['primaryKey'])) throw new Exception("Missing primaryKey");
  374. if (empty($args['instance'])) throw new Exception("Missing instance");
  375. if (empty($args['toConnect'])) throw new Exception("Missing toConnect");
  376. if (!in_array($args['toConnect'], ['yes', 'no'])) throw new Exception("Wrong param toConnect");
  377. $idInstance = ACL::getInstanceId($args['instance']);
  378. $instanceTable = ACL::getInstanceTable($args['namespace']);
  379. switch ($args['toConnect']) {
  380. case 'yes': {
  381. // TODO: _HIST info - waiting
  382. $ret = DB::getPDO()->execSql("
  383. insert into `{$instanceTable}` (`pk`, `idInstance`)
  384. values ( :pk , :idInstance )
  385. ", [
  386. 'pk' => $args['primaryKey'],
  387. 'idInstance' => $idInstance,
  388. ]);
  389. // TODO: _HIST info - mark as done
  390. } break;
  391. case 'no': {
  392. // TODO: _HIST info - waiting
  393. $ret = DB::getPDO()->execSql("
  394. delete from `{$instanceTable}`
  395. where `pk` = :pk
  396. and `idInstance` = :idInstance
  397. ", [
  398. 'pk' => $args['primaryKey'],
  399. 'idInstance' => $idInstance,
  400. ]);
  401. // TODO: _HIST info - mark as done
  402. } break;
  403. }
  404. return [
  405. 'type' => 'success',
  406. 'msg' => "Wprowadzono zmiany ({$ret})",
  407. // TODO: 'data' => all instances for pk
  408. ];
  409. }
  410. public function rmUserTableFilterAjaxAction() {
  411. Response::sendTryCatchJson(array($this, 'rmUserTableFilterAjax'), $args = 'JSON_FROM_REQUEST_BODY');
  412. }
  413. public function rmUserTableFilterAjax($args) {
  414. $namespace = V::get('namespace', '', $args);
  415. $filtrName = V::get('filtrName', '', $args);
  416. if (!$namespace) throw new Exception("Missing namespace");
  417. if (!$filtrName) throw new Exception("Missing filtrName");
  418. $userFltrConfKey = "tableColFilters__" . User::getLogin();
  419. $currentFilters = DB::getPDO()->fetchValue(" select CONF_VAL from CRM_CONFIG where CONF_KEY = '{$userFltrConfKey}' ");
  420. if (!$currentFilters) return [
  421. 'type' => 'warning',
  422. 'msg' => "Brak filtrów w bazie",
  423. ];
  424. $currentFilters = json_decode($currentFilters, 'assoc');
  425. unset($currentFilters[$namespace][$filtrName]);
  426. $affeced = DB::getPDO()->update('CRM_CONFIG', 'CONF_KEY', $userFltrConfKey, [
  427. 'CONF_VAL' => json_encode($currentFilters)
  428. ]);
  429. return [
  430. 'type' => 'success',
  431. 'msg' => 'Zapisano nowy filtr',
  432. 'data' => $currentFilters[$namespace]
  433. ];
  434. }
  435. public function addUserTableFilterAjaxAction() {
  436. Response::sendTryCatchJson(array($this, 'addUserTableFilterAjax'), $args = 'JSON_FROM_REQUEST_BODY');
  437. }
  438. public function addUserTableFilterAjax($args) {
  439. $namespace = V::get('namespace', '', $args);
  440. $filtrName = V::get('filtrName', '', $args);
  441. $visibleCols = V::get('visibleCols', '', $args);
  442. if (!$namespace) throw new Exception("Missing namespace");
  443. if (!$filtrName) throw new Exception("Missing filtrName");
  444. if (!$visibleCols) throw new Exception("Missing visibleCols");
  445. $userFltrConfKey = "tableColFilters__" . User::getLogin();
  446. $currentFilters = DB::getPDO()->fetchValue(" select CONF_VAL from CRM_CONFIG where CONF_KEY = '{$userFltrConfKey}' ");
  447. $currentFilters = ($currentFilters) ? json_decode($currentFilters, 'assoc') : [];
  448. $currentFilters[$namespace][$filtrName] = $visibleCols;
  449. $sqlFltr = json_encode($currentFilters);
  450. DB::getPDO()->execSql("
  451. insert into CRM_CONFIG (CONF_KEY, CONF_VAL)
  452. values ('$userFltrConfKey', '{$sqlFltr}')
  453. on duplicate key update CONF_VAL = '{$sqlFltr}'
  454. ");
  455. return [
  456. 'type' => 'success',
  457. 'msg' => 'Zapisano nowy filtr',
  458. 'data' => $currentFilters[$namespace]
  459. ];
  460. }
  461. public function getUserTableFilterAjaxAction() {
  462. Response::sendTryCatchJson(array($this, 'getUserTableFilterAjax'), $args = 'JSON_FROM_REQUEST_BODY');
  463. }
  464. public function getUserTableFilterAjax($args) {
  465. $namespace = V::get('namespace', '', $args);
  466. if (!$namespace) throw new Exception("Missing namespace");
  467. $userFltrConfKey = "tableColFilters__" . User::getLogin();
  468. $currentFilters = DB::getPDO()->fetchValue(" select CONF_VAL from CRM_CONFIG where CONF_KEY = '{$userFltrConfKey}' ");
  469. $currentFilters = ($currentFilters) ? json_decode($currentFilters, 'assoc') : [];
  470. return [
  471. 'type' => 'success',
  472. 'msg' => 'Odczytano filtry użytkownika',
  473. 'data' => (!empty($currentFilters[$namespace])) ? $currentFilters[$namespace] : []
  474. ];
  475. }
  476. public function revertFromHistAjaxAction() {
  477. Response::sendTryCatchJson(array($this, 'revertFromHistAjax'));
  478. }
  479. public function revertFromHistAjax() {
  480. $typeName = V::get('typeName', '', $_REQUEST, 'word');
  481. if (!$typeName) throw new Exception("Wrong param typeName");
  482. // TODO: use namespace from url
  483. // $namespace = V::get('namespace', '', $_GET, 'word');
  484. // if (!$namespace) {
  485. // $typeName = V::get('typeName', '', $_GET, 'word');
  486. // if (!$typeName) throw new Exception("Wrong param typeName");
  487. // $namespace = Api_WfsNs::getBaseWfsUri() . '/' . str_replace(':', '/', $typeName);
  488. // }
  489. // $acl = Core_AclHelper::getAclByNamespace($namespace, $forceTblAclInit = ('1' == V::get('_force', '', $_GET)));
  490. $id = V::get('ID', '', $_REQUEST, 'word');
  491. if (!$id) throw new Exception("Wrong param ID");
  492. $idHist = V::get('idHist', '', $_REQUEST, 'word');
  493. if (!$idHist) throw new Exception("Wrong param idHist");
  494. $fieldName = V::get('fieldName', '', $_REQUEST, 'word');
  495. if (!$fieldName) throw new Exception("Wrong param fieldName");
  496. $acl = Core_AclHelper::getAclByTypeName($typeName);
  497. $item = $acl->getItem($id);
  498. if (!$item) throw new HttpException("Item not found", 404);
  499. if (!$acl->canWriteObjectField($fieldName, $record)) throw new Exception("Missing perm Write for field {$fieldName}");
  500. $histItem = $acl->getHistItem($id, $idHist);
  501. if (!$histItem) throw new HttpException("Hist Item not found", 404);
  502. $histValue = V::get($fieldName, 'N/S;', $histItem);
  503. if ('N/S;' == $histValue) throw new Exception("Missing field value in hist[{$idHist}] for field({$fieldName}) from item[{$id}]");
  504. if ($acl->isGeomField($fieldName)) {
  505. $wktType = strtoupper($acl->getGeomFieldType($fieldName));
  506. if (!$wktType) throw new Exception("Wrong geometry type for field {$fieldName}");
  507. if ($wktType != strtoupper(substr($histValue, 0, strlen($wktType)))) throw new Exception("Wrong geometry type for field {$fieldName} in hist value");
  508. $coords = trim(substr($histValue, strlen($wktType)), '()');
  509. $wktValue = $acl->convertGmlCoordsToWkt($wktType, $coords, ['cs'=>' ', 'ts'=>',']);
  510. if (!$wktValue) throw new Exception("BUG in hist record");
  511. $sqlObj = array();
  512. $sqlObj['ID'] = $id;
  513. $sqlObj[$fieldName] = "GeomFromText('{$wktValue}')";
  514. $affected = DB::getDB()->UPDATE_OBJ($acl->getName(), (object)$sqlObj);
  515. if (0 == $affected) throw new AlertInfoException("Nie wprowadzono żadnych zmian");
  516. else if ($affected < 0) throw new Exception("Wystąpiły błędy podczas aktualizacji rekordu [{$id}]");
  517. $jsonResponse = array();
  518. $jsonResponse['type'] = 'success';
  519. $jsonResponse['msg'] = "Zaktualizowano dane na podstawie wcześniejszej wartości dla rekordu [{$id}]";
  520. $jsonResponse['actions'] = array();
  521. $jsonResponse['actions'][] = ['jsFunction'=>'TableAjax__HIST_Route', 'args'=>[$id]];
  522. return $jsonResponse;
  523. } else {
  524. throw new HttpException("Not implemented - update from hist only for the geom field", 501);
  525. }
  526. throw new Exception("BUG: update field '{$fieldName}' in item[{$id}] from hist[{$idHist}]", 501);
  527. }
  528. public function removeTheGeomAjaxAction() {
  529. Response::sendTryCatchJson(array($this, 'removeTheGeomAjax'), $args = 'JSON_FROM_REQUEST_BODY');
  530. }
  531. public function removeTheGeomAjax($args) {
  532. $namespace = V::get('namespace', '', $args, 'word');
  533. if (!$namespace) throw new HttpException("Bad Request - missing namespace", 400);
  534. $acl = Core_AclHelper::getAclByNamespace($namespace, $forceTblAclInit = ('1' == V::get('_force', '', $_GET)));
  535. $primaryKeyField = $acl->getPrimaryKeyField();
  536. $primaryKey = V::get($primaryKeyField, 0, $args, 'int');
  537. $geomFieldName = 'the_geom';
  538. $response = new stdClass();
  539. if ($primaryKey <= 0) throw new HttpException("Bad Request - Wrong param ID", 400);
  540. $record = $acl->getItem($primaryKey);
  541. if (!$record) throw new HttpException("Nie odnaleziono rekordu nr {$primaryKey}", 404);
  542. if (!$acl->canWriteObjectField($geomFieldName, $record)) throw new HttpException("Brak dostępu do zapisu dla pola {$geomFieldName}", 403);
  543. if (empty($record->{$geomFieldName})) {
  544. $response->type = 'info';
  545. $response->msg = "Rekord nie jest powiązany z żadnym obiektem na mapie";
  546. $response->record = $record;
  547. return $response;
  548. }
  549. $itemPatch = array();
  550. $itemPatch[$geomFieldName] = "NULL";
  551. $itemPatch[$primaryKeyField] = $primaryKey;
  552. $response = new stdClass();
  553. try {
  554. $affected = $acl->updateItem($itemPatch);
  555. if ($affected > 0) {
  556. $response->type = 'success';
  557. $response->msg = "Usunięto obiekt z mapy dla rekordu {$primaryKey}";// Rekord zapisany pomyślnie
  558. } else if ($affected == 0) {
  559. $response->type = 'info';
  560. $response->msg = "Nie wprowadzono żadnych zmian";
  561. }
  562. $response->record = $acl->getItem($primaryKey);
  563. }
  564. catch (Exception $e) {
  565. $response->type = 'error';
  566. $response->msg = $e->getMessage();
  567. }
  568. return $response;
  569. }
  570. public function moreFunctionsCellAjaxAction() {
  571. Response::sendTryCatchJson(array($this, 'moreFunctionsCell'), $args = $_GET);
  572. }
  573. public function moreFunctionsCell($args) {// ajax task 'MORE_FUNCTIONS_CELL'
  574. $id = V::get('ID', 0, $args, 'int');
  575. if ($id <= 0) throw new HttpException("404", 404);
  576. $namespace = V::get('namespace', '', $args, 'word');
  577. if (!$namespace) throw new HttpException("Bad Request - missing namespace", 400);
  578. $acl = Core_AclHelper::getAclByNamespace($namespace, $forceTblAclInit = ('1' == V::get('_force', '', $args)));
  579. $response = new stdClass();
  580. $response->type = 'success';
  581. $response->msg = 'Funkcje';
  582. $response->rowFunctions = Core_AclHelper::getMoreFunctionsCell($acl, array('primary_key' => $id));
  583. return $response;
  584. }
  585. public function editFormAction() {// namespace, _hash, _primaryKey
  586. $args = $_REQUEST;
  587. $id = V::get('_primaryKey', 0, $args, 'int');
  588. if ($id <= 0) throw new HttpException("Bad Request - missing primaryKey", 400);
  589. $namespace = V::get('namespace', '', $args, 'word');
  590. if (!$namespace) throw new HttpException("Bad Request - missing namespace", 400);
  591. $acl = Core_AclHelper::getAclByNamespace($namespace);
  592. $tbl = $this->getTableAjaxWidget($acl);
  593. $tbl->sendAjaxEdit($id, $args);
  594. }
  595. public function editSaveAjaxAction() {
  596. Response::sendTryCatchJson(array($this, 'editSaveAjax'), $args = 'JSON_FROM_REQUEST_BODY');
  597. }
  598. public function editSaveAjax($args) {
  599. $namespace = V::get('namespace', '', $args, 'word');
  600. if (!$namespace) throw new HttpException("Bad Request - missing namespace", 400);
  601. $acl = Core_AclHelper::getAclByNamespace($namespace);
  602. $primaryKeyField = $acl->getPrimaryKeyField();
  603. $primaryKey = V::get('primaryKey', 0, $args, 'int');
  604. if (empty($primaryKey)) throw new HttpException("Bad Request - missing primaryKey!", 400);
  605. $item = $acl->getItem($primaryKey);
  606. if (!$item) throw new HttpException("Item not exists!", 404);
  607. $itemFromUser = $acl->convertObjectFromUserInput($args['form'], $type = 'array_by_id', $prefix = 'f');
  608. $response = new stdClass();
  609. $response->primaryKey = $primaryKey;
  610. try {
  611. $itemFromUser[$primaryKeyField] = $primaryKey;
  612. $affected = $acl->updateItem($itemFromUser);
  613. if ($affected > 0) {
  614. $response->type = 'success';
  615. $response->msg = "Rekord zapisany pomyślnie";//"Record saved successfully";
  616. } else if ($affected == 0) {
  617. $response->type = 'info';
  618. $response->msg = "Nie wprowadzono żadnych zmian";
  619. }
  620. $response->record = $acl->getItem($primaryKey);
  621. $rowFunList = Core_AclHelper::getMoreFunctionsCell($acl, array('primary_key'=>$primaryKey, 'record'=>$response->record));
  622. if (!empty($rowFunList)) $response->rowFunctions = $rowFunList;
  623. }
  624. catch (Exception $e) {
  625. $response->type = 'error';
  626. $response->msg = "Wystąpiły błędy!";
  627. $response->msg .= $e->getMessage();
  628. }
  629. return $response;
  630. }
  631. public function typeSpecialCellAction() {
  632. Response::sendTryCatchJson(array($this, 'typeSpecialCell'), $args = $_REQUEST);
  633. }
  634. public function typeSpecialCell($args) {
  635. $namespace = V::get('namespace', '', $args, 'word');
  636. if (!$namespace) throw new HttpException("Bad Request - missing namespace", 400);
  637. $acl = Core_AclHelper::getAclByNamespace($namespace);
  638. $id = V::get('ID', 0, $args, 'int');
  639. $fieldName = V::get('col', '', $args);
  640. if ($id <= 0 || empty($fieldName)) throw new HttpException("Bad Request - missing id or col", 400);
  641. $col = $fieldName;// TODO: RM $col
  642. $jsonData = new stdClass();
  643. $idField = $acl->getFieldIdByName($fieldName);
  644. if (!$idField) throw new Exception("Wrong field");
  645. $item = $acl->getItem($id);
  646. if (!$acl->canReadObjectField($fieldName, $item)) throw new Exception("Brak dostępu");
  647. $typeSpecial = Typespecial::getInstance($idField, $fieldName);
  648. if ($typeSpecial) {
  649. $jsonData->data = $typeSpecial->getReturnData($acl->getID(), $id, $fieldName, '');
  650. $jsonData->namespace = 'default_db/' . V::get('tbl_name', '', $jsonData->data);
  651. }
  652. return $jsonData;
  653. }
  654. /**
  655. * @param $_GET['namespace'] = AclNamespace
  656. * @param $_GET['format'] = 'csv' | 'html'
  657. * @param $_GET['flds'] = csv - coma separated field names
  658. * @param $_GET['sortCol'] = FieldName
  659. * @param $_GET['sortDir'] = SortDir ('desc' | 'asc')
  660. * @param $_GET['f_{$fieldName}'] = filter
  661. * @param $_GET['sf_{$fieldName}'] = force filter
  662. */
  663. public function exportAction() {
  664. $args = $_GET;
  665. $namespace = V::get('namespace', '', $args, 'word');
  666. if (!$namespace) throw new HttpException("Bad Request - missing namespace", 400);
  667. $acl = Core_AclHelper::getAclByNamespace($namespace);
  668. $exportLimit = 10000;
  669. $params = array();
  670. $params['limit'] = $exportLimit;
  671. // $params['limitstart'] = 0;
  672. $params['order_by'] = V::get('sortCol', '', $args);
  673. $params['order_dir'] = V::get('sortDir', '', $args);
  674. $params['cols'] = array($acl->getPrimaryKeyField());
  675. $toExportFields = explode(',', V::get('flds', '', $_GET));
  676. if (empty($toExportFields)) throw new Exception("Nie wybrano żandych pól do exportu.");
  677. $allowedExportFieldList = Core_AclHelper::getExportFieldList($acl);
  678. foreach ($toExportFields as $fieldName) {
  679. if ($fieldName == $acl->getPrimaryKeyField()) continue;
  680. if (!in_array($fieldName, $allowedExportFieldList)) throw new Exception("Brak uprawnień do exportu pola '{$fieldName}'");
  681. $params['cols'][] = $fieldName;
  682. }
  683. $labels = array();
  684. foreach ($toExportFields as $fieldName) {
  685. $labels[ $fieldName ] = $acl->getFieldLabel($fieldName);
  686. }
  687. foreach ($args as $k => $v) {
  688. if (strlen($k) > 3 && substr($k, 0, 2) == 'f_' && strlen($v) > 0) {// filter prefix
  689. $params[$k] = $v;
  690. }
  691. else if (strlen($k) > 4 && substr($k, 0, 3) == 'sf_' && strlen($v) > 0) {// special filter prefix
  692. $params[$k] = $v;
  693. }
  694. }
  695. $total = $acl->getTotal($params);
  696. // if ($total > $exportLimit) $params['limit'] = $exportLimit;
  697. $items = $acl->getItems($params);
  698. $format = V::get('format', 'html', $_GET);
  699. if ('html' == $format) {
  700. UI::gora();
  701. UI::startTag('table', ['class'=>'table table-bordered table-hover']);
  702. UI::startTag('thead');
  703. UI::startTag('tr');
  704. foreach ($labels as $fldName => $label) {
  705. UI::tag('th', [], $label);
  706. }
  707. UI::endTag('tr');
  708. UI::endTag('thead');
  709. UI::startTag('tbody');
  710. foreach ($items as $item) :
  711. UI::startTag('tr');
  712. foreach ($labels as $fldName => $label) :
  713. UI::tag('td', [], $item->{$fldName});
  714. endforeach;
  715. UI::endTag('tr');
  716. endforeach;
  717. UI::endTag('tbody');
  718. UI::endTag('table');
  719. UI::dol();
  720. }
  721. else if ('csv' == $format) {
  722. $csvFileName = "Tabela-" . $acl->getName() . "-" . date("Y-m-d_H_s");
  723. header('Content-Type: text/csv; charset=utf-8');
  724. header("Content-Disposition: attachment; filename={$csvFileName}.csv");
  725. $csvSeparator = ';';
  726. $labelsLine = array();
  727. foreach ($labels as $fldName => $label) {
  728. $labelsLine[] = '"' . addslashes($label) . '"';
  729. }
  730. echo implode($csvSeparator, $labelsLine) . "\n";
  731. foreach ($items as $item) {
  732. $itemLine = array();
  733. foreach ($labels as $fldName => $label) {
  734. $itemLine[] = '"' . addslashes($item->{$fldName}) . '"';
  735. }
  736. echo implode($csvSeparator, $itemLine) . "\n";
  737. }
  738. }
  739. else {
  740. die("Nieobsługiwany format danych.");
  741. }
  742. }
  743. public function loadDataAjaxAction() {
  744. // $tbl = $this->getTableAjaxWidget($acl);
  745. Response::sendTryCatchJson(array($this, 'loadDataAjax'), $args = $_GET);
  746. }
  747. public function loadDataAjax($args) {
  748. $namespace = V::get('namespace', '', $args, 'word');
  749. if (!$namespace) throw new HttpException("Bad Request - missing namespace", 400);
  750. $acl = P5::getAclByNamespace($namespace);
  751. $uiConf = [
  752. 'pageSize' => 10
  753. ];
  754. $DBG = ('1' == V::get('DBG', '', $args));
  755. $pageSize = V::get('pageSize', $uiConf['pageSize'], $args, 'int');
  756. $page = V::get('page', 0, $args, 'int');
  757. $currSortCol = V::get('currSortCol', '', $args);
  758. $currSortFlip = V::get('currSortFlip', '', $args);
  759. if ($page > 0) {
  760. $page -= 1;
  761. }
  762. $params = array();
  763. $params['limit'] = $pageSize;
  764. $params['limitstart'] = $page * $params['limit'];
  765. $params['order_by'] = ($currSortCol)? $currSortCol : '';
  766. $params['order_dir'] = $currSortFlip;
  767. $filters = new stdClass();
  768. $filters->currSortCol = $currSortCol;
  769. $filters->currSortFlip = $currSortFlip;
  770. foreach ($args as $k => $v) {
  771. if (strlen($k) > 3 && substr($k, 0, 2) == 'f_' && strlen($v) > 0) {// filter prefix
  772. $params[$k] = $v;
  773. $filters->{$k} = $v;
  774. }
  775. else if (strlen($k) > 4 && substr($k, 0, 3) == 'sf_' && strlen($v) > 0) {// special filter prefix
  776. $params[$k] = $v;
  777. $filters->{$k} = $v;
  778. }
  779. }
  780. // TODO: $this->setFilters($filters);
  781. $vCols = $acl->getVirtualFieldListByIdZasob();
  782. if (!empty($vCols)) {
  783. if($DBG){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">vCols (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($vCols);echo'</pre>';}
  784. }
  785. $visibleCols = $acl->getVisibleFieldListByIdZasob();
  786. if($DBG){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">visibleCols (F.' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($visibleCols);echo'</pre>';}
  787. $jsonData = new stdClass();
  788. $jsonData->page = $page + 1;
  789. $jsonData->pageSize = $pageSize;
  790. $jsonData->filters = $filters;
  791. $jsonData->cols = new stdClass();
  792. $jsonData->uniqueCol = $acl->getPrimaryKeyField();
  793. $ind = 0;
  794. foreach ($visibleCols as $fieldID => $col) {
  795. $ind++;
  796. $columnConfig = (object)array('index'=>$ind);
  797. if (in_array($col, array('A_STATUS','A_STATUS_CURRENT','A_SERVICES_STATUS_CURRENT'))) {
  798. $columnConfig->format = '<div class="cell-A_STATUS-{0}">{0}</div>';
  799. }
  800. else if (in_array($col, array('Status'))) {
  801. // Ahmes problems Status colors
  802. $columnConfig->format = '<div class="cell-Status-{0}">{0}</div>';
  803. }
  804. else if ($acl->isGeomField($col)) {
  805. $columnConfig->type = 'geom';
  806. }
  807. if ('' !== ($label = $acl->getFieldLabel($col))) {
  808. $columnConfig->friendly = $label;
  809. }
  810. $colType = $acl->getFieldType($col);
  811. if ($colType) {// @see MarkTableAjaxFilterColType
  812. if($DBG){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">field('.$col.') $colType (F.' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($colType);echo'</pre>';}
  813. if ($colType['type'] == 'date') {
  814. //$columnConfig->type = 'date';// TODO: require datetimepicker
  815. }
  816. if (!empty($colType['simpleType'])) $columnConfig->type = $colType['simpleType'];
  817. } else {// typespecial - no type
  818. $columnConfig->type = 'special';
  819. }
  820. $columnConfig->xsdType = $acl->getXsdFieldType($col);
  821. if ($columnConfig->xsdType) {
  822. $ex = explode(":", $columnConfig->xsdType);
  823. switch ($ex[0]) {
  824. case 'ref':
  825. case 'alias_ref':
  826. if (3 != count($ex)) throw new HttpException("Schema Error for field({$col}) xsdType({$columnConfig->xsdType})", 500);
  827. $columnConfig->type = 'ref';
  828. $columnConfig->xsdRefUri = Api_WfsNs::getNsUri($ex[1]);
  829. $columnConfig->xsdRefType = $ex[2];
  830. $columnConfig->xsdRefNsPrefix = $ex[1];
  831. break;
  832. case 'xsd':
  833. switch ($ex[1]) {
  834. case 'string': $columnConfig->type = 'string'; break;
  835. case 'ind': $columnConfig->type = 'number'; break;// TODO: bug 'ind'?
  836. }
  837. break;
  838. case 'p5':
  839. switch ($ex[1]) {
  840. case 'alias': {
  841. $format = $acl->getXsdFieldParam($col, 'format');
  842. if ($format) $columnConfig->format = $format;
  843. } break;
  844. case 'string': {
  845. $columnConfig->type = 'p5:string';
  846. $columnConfig->formatByValue = $acl->getXsdFieldParam($col, 'formatByValue');
  847. } break;
  848. }
  849. break;
  850. }
  851. }
  852. $typeSpecial = Typespecial::getInstance($fieldID, $col);
  853. if ($typeSpecial) {
  854. if($DBG){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">typeSpecial (F.' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($typeSpecial);echo'</pre>';}
  855. $columnConfig->_tsRetId = $typeSpecial->getReturnId();
  856. if ($columnConfig->_tsRetId == 0) {
  857. $tsParamOut = V::get('param_out', null, $typeSpecial);
  858. if ($tsParamOut) {
  859. $tsFormat = V::get('format', null, $tsParamOut);
  860. $tsValues = V::get('values', null, $tsParamOut);
  861. $tsAliases = V::get('alias', null, $tsParamOut);
  862. if (false !== strpos($tsFormat, '<a') && !empty($tsValues) && !empty($tsAliases)) {
  863. $tsAliasMap = array();
  864. /* [values] => Array([ID] => 1467), [alias] => Array([1467] => ID) */
  865. $bugTsColsNotVisible = array();
  866. foreach ($tsValues as $kVarName => $vIdZasob) {
  867. if (array_key_exists($vIdZasob, $tsAliases)) {
  868. $tsAliasMap[$kVarName] = $tsAliases[$vIdZasob];
  869. } else {
  870. $bugTsColsNotVisible[] = "noAliasFor {$vIdZasob}";
  871. }
  872. if (!array_key_exists($vIdZasob, $visibleCols)) {
  873. $bugTsColsNotVisible[] = $vIdZasob;
  874. }
  875. }
  876. if (empty($bugTsColsNotVisible)) {
  877. $tsSimpleLink = new stdClass();
  878. $tsSimpleLink->format = $tsFormat;
  879. $tsSimpleLink->aliasMap = $tsAliasMap;
  880. $columnConfig->_tsSimpleLink = $tsSimpleLink;
  881. $columnConfig->type = 'simpleLink';
  882. } else {
  883. $columnConfig->_tsSimpleLinkBug = $bugTsColsNotVisible;
  884. }
  885. }
  886. }
  887. }
  888. }
  889. if ($columnConfig->xsdType) {// fix fields type p5:typeSpecialSimpleLink (previously defined by Typespecial)
  890. switch ($columnConfig->xsdType) {
  891. case 'p5:typeSpecialSimpleLink': {
  892. $columnConfig->type = 'simpleLink';
  893. $columnConfig->_tsRetId = 0;
  894. $columnConfig->_tsSimpleLink = new stdClass();
  895. $columnConfig->_tsSimpleLink->format = $acl->getXsdFieldParam($col, 'format');
  896. $columnConfig->_tsSimpleLink->aliasMap = $acl->getXsdFieldParam($col, 'aliasMap');
  897. } break;
  898. }
  899. }
  900. // @see ajaxHiddenColsSave
  901. if (UserProfile::isHiddenColumn($acl->getID(), $fieldID)) {
  902. $columnConfig->hidden = true;
  903. }
  904. $columnConfig->description = $acl->getFieldOpis($col);
  905. $jsonData->cols->{$col} = $columnConfig;
  906. }
  907. $jsonData->rows = array();
  908. $jsonData->total = $acl->getTotal($params);
  909. if($DBG){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">get_total (F.' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($jsonData->total);echo'</pre>';}
  910. $items = $acl->getItems($params);
  911. foreach ($items as $idx => $item) $items[$idx] = (array)$item;
  912. if($DBG){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">items (F.' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($items);echo'</pre>';}
  913. // TODO: add virtual data by Typespecial
  914. if (!empty($vCols) && !empty($items)) {
  915. foreach ($vCols as $vColID => $vCol) {
  916. $colType = $acl->getFieldTypeById($vColID);
  917. if ($colType) continue;// pomin Typespecial dla realnych komorek w bazie danych
  918. $typeSpecial = Typespecial::getInstance($vColID, $vCol);
  919. if ($typeSpecial) {
  920. $columnConfig = V::get($vCol, null, $jsonData->cols);
  921. if ($columnConfig && !empty($columnConfig->_tsSimpleLink)) {
  922. // pomin simple link values - mved to js render
  923. } else {
  924. if($DBG){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">Typespecial('.$vColID.') (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($typeSpecial);echo'</pre>';}
  925. $ids = array_keys($items);
  926. $specialValues = $typeSpecial->getValuesByIds($this->_zasobID, $ids);
  927. if($DBG){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">Typespecial('.$vCol.') specialValues (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($specialValues);echo'</pre>';}
  928. if (!empty($specialValues)) foreach ($specialValues as $kItemID => $vValues) {
  929. $tsValue = implode('<br>', $vValues);
  930. if($DBG){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">Item['.$kItemID.'].'.$vCol.' specialValues (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($items[$kItemID]);echo'</pre>';}
  931. if (!empty($items[$kItemID][$vCol]) && !empty($tsValue)) {
  932. $items[$kItemID][$vCol] .= ": {$tsValue}";
  933. } else {
  934. $items[$kItemID][$vCol] = $tsValue;
  935. }
  936. }
  937. }
  938. }
  939. }
  940. }
  941. {
  942. if(V::get('DBG', '', $_GET)){$jsonData->__DBG__ = [];}
  943. $p5Alias = [];
  944. foreach ((array)$jsonData->cols as $fieldName => $conf) {
  945. if ('p5:alias' == V::get('xsdType', '', $conf)) {
  946. if(V::get('DBG', '', $_GET)){$jsonData->__DBG__[$fieldName] = $conf;}
  947. $aliasType = $acl->getXsdFieldParam($fieldName, 'type');// 'type' => 'sql_table_alias',
  948. if ('sql_table_alias' == $aliasType) {
  949. $p5Alias[$fieldName] = (array)$conf;
  950. $p5Alias[$fieldName]['type'] = 'sql_table_alias';
  951. $p5Alias[$fieldName]['local_join_key'] = $acl->getXsdFieldParam($fieldName, 'local_join_key');// 'local_join_key' => 'ID',
  952. $p5Alias[$fieldName]['remote_table_name'] = $acl->getXsdFieldParam($fieldName, 'remote_table_name');// 'remote_table_name' => 'CRM_LISTA_ZASOBOW_ORDERS_summary_view',
  953. $p5Alias[$fieldName]['remote_join_key'] = $acl->getXsdFieldParam($fieldName, 'remote_join_key');// 'remote_join_key' => 'ID',
  954. $p5Alias[$fieldName]['remote_column_value'] = $acl->getXsdFieldParam($fieldName, 'remote_column_value');// 'remote_column_value' => 'SUM_POS',
  955. } else if ('sql_query_alias' == $aliasType) {
  956. $p5Alias[$fieldName] = (array)$conf;
  957. $p5Alias[$fieldName]['type'] = 'sql_query_alias';
  958. $p5Alias[$fieldName]['local_join_key'] = $acl->getXsdFieldParam($fieldName, 'local_join_key');
  959. $p5Alias[$fieldName]['join_query_format'] = $acl->getXsdFieldParam($fieldName, 'join_query_format');
  960. }
  961. }
  962. }
  963. if(V::get('DBG', '', $_GET)){$jsonData->__DBG__['$p5Alias'] = $p5Alias;}
  964. if(V::get('DBG', '', $_GET)){$jsonData->__DBG__['$aliasValuesRaw'] = [];}
  965. if ($p5Alias) {
  966. $sqlLocalTableName = $acl->getRootTableName();
  967. $primaryKeyField = $acl->getPrimaryKeyField();
  968. foreach ($p5Alias as $fieldName => $conf) {
  969. $aliasValuesRaw = [];
  970. if ('sql_table_alias' == $conf['type']) {
  971. $localKeys = [];
  972. $localKeyName = V::get('local_join_key', '', $conf);
  973. if ($localKeyName) {
  974. if (!array_key_exists($localKeyName, $localKeys)) {
  975. $localKeys[$localKeyName] = [];
  976. foreach ($items as $item) {
  977. $keyLocal = V::get($localKeyName, 0, $item);
  978. if ($keyLocal) $localKeys[$localKeyName][] = DB::getPDO()->quote($keyLocal, PDO::PARAM_STR);
  979. }
  980. }
  981. if(V::get('DBG', '', $_GET)){$jsonData->__DBG__['$localKeys'] = $localKeys;}
  982. if (!empty($localKeys[$localKeyName])) {
  983. $sqlRemoteTable = V::get('remote_table_name', '', $conf);
  984. $sqlRemoteValueFieldName = V::get('remote_column_value', '', $conf);
  985. $sqlRemoteKeyName = V::get('remote_join_key', '', $conf);
  986. $sqlLocalKeyName = $acl->getSqlFieldName($localKeyName);
  987. $aliasValuesRaw = DB::getPDO()->fetchAllByKey("
  988. select r.{$sqlRemoteKeyName} as {$sqlLocalKeyName}, r.{$sqlRemoteValueFieldName} as remote_value
  989. from {$sqlRemoteTable} r
  990. where r.{$sqlRemoteKeyName} in(" . implode(",", $localKeys[$localKeyName]) . ")
  991. ", $sqlLocalKeyName);
  992. if(V::get('DBG', '', $_GET)){$jsonData->__DBG__['$aliasValuesRaw'][$fieldName] = $aliasValuesRaw;}
  993. }
  994. }
  995. } else if ('sql_query_alias' == $conf['type']) {
  996. $localKeys = [];
  997. $localKeyName = V::get('local_join_key', '', $conf);
  998. $sqlFormat = V::get('join_query_format', '', $conf);
  999. if ($localKeyName && $sqlFormat) {
  1000. if (!array_key_exists($localKeyName, $localKeys)) {
  1001. $localKeys[$localKeyName] = [];
  1002. foreach ($items as $item) {
  1003. $keyLocal = V::get($localKeyName, 0, $item);
  1004. if ($keyLocal) $localKeys[$localKeyName][] = DB::getPDO()->quote($keyLocal, PDO::PARAM_STR);
  1005. }
  1006. }
  1007. }
  1008. if (!empty($localKeys[$localKeyName])) {
  1009. $sql = str_replace('{sql_in_local_join_key}', implode(",", $localKeys[$localKeyName]), $sqlFormat);
  1010. $sqlLocalKeyName = $acl->getSqlFieldName($localKeyName);
  1011. $aliasValuesRaw = DB::getPDO()->fetchAllByKey($sql, $sqlLocalKeyName);
  1012. }
  1013. }
  1014. DBG::log($aliasValuesRaw, 'array', '$aliasValuesRaw');
  1015. if (!empty($aliasValuesRaw)) {
  1016. if(V::get('DBG_P5', '', $_GET)){echo '{ "$aliasValuesRaw": '.json_encode($aliasValuesRaw).', "dbg": [' . "\n";}
  1017. array_walk($items, function (&$item) use ($fieldName, $sqlLocalKeyName, $aliasValuesRaw) {
  1018. $sqlValue = V::get($sqlLocalKeyName, null, $item);
  1019. if(V::get('DBG_P5', '', $_GET)){echo '{ "sqlValue": "'.$sqlValue.'", "remote_value": "'.$aliasValuesRaw[$sqlValue]['remote_value'].'", "item": '.json_encode($item) . '},' . "\n";}
  1020. if ($sqlValue !== null && array_key_exists($sqlValue, $aliasValuesRaw)) {
  1021. if(V::get('DBG_P5', '', $_GET)){echo '{ "TODO_update_value": "'.$aliasValuesRaw[$sqlValue]['remote_value'].'"},' . "\n";}
  1022. $item[$fieldName] = $aliasValuesRaw[$sqlValue]['remote_value'];
  1023. if(V::get('DBG_P5', '', $_GET)){echo '{ "TODO_updated_value": "'.$item[$fieldName].'"},' . "\n";}
  1024. }
  1025. });
  1026. if(V::get('DBG_P5', '', $_GET)){echo "\n".'{}]}';die();}
  1027. }
  1028. }
  1029. }
  1030. }
  1031. foreach ($items as $item) {
  1032. // TODO: hide items without 'R'
  1033. foreach ($visibleCols as $fieldName) {
  1034. // TODO: ID default 'R'
  1035. if (!$acl->canReadObjectField($fieldName, $item)) $item[$fieldName] = '*****';
  1036. // null => empty string
  1037. if (!isset($item[$fieldName]) || (!$item[$fieldName] && $item[$fieldName] !== '0')) {
  1038. if($DBG){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">isEmptyString['.$fieldName.'] (F.' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($item[$fieldName]);echo'</pre>';}
  1039. $item[$fieldName] = '';
  1040. }
  1041. }
  1042. $jsonData->rows[] = $item;
  1043. }
  1044. $jsonData->type = 'success';
  1045. $jsonData->msg = 'pobrano nowe dane';
  1046. return $jsonData;
  1047. }
  1048. }