ViewObject.php 47 KB

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