ViewTableAjax.php 66 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618
  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. class Route_ViewTableAjax extends RouteBase {
  15. public function getTableAjaxWidget($acl, $backRefFilter = [], $childRefFilter = []) {
  16. $syncUrl = $this->getLink('', [ 'namespace' => $acl->getNamespace() ]);
  17. $tbl = new TableAjax($acl);
  18. $tbl->setRootUrl($syncUrl);
  19. if (!empty($backRefFilter['namespace']) && !empty($backRefFilter['primaryKey'])) {
  20. $tbl->setBackRefFilter($backRefFilter);
  21. $syncUrl = $this->getLink('', [
  22. 'namespace' => $acl->getNamespace(),
  23. 'backRefNS' => $backRefFilter['namespace'],
  24. 'backRefPK' => $backRefFilter['primaryKey'],
  25. 'backRefField' => $backRefFilter['fieldName'],
  26. ]);
  27. }
  28. if (!empty($childRefFilter['namespace']) && !empty($childRefFilter['primaryKey'])) {
  29. $tbl->setChildRefFilter($childRefFilter);
  30. $syncUrl = $this->getLink('', [
  31. 'namespace' => $acl->getNamespace(),
  32. 'childRefNS' => $childRefFilter['namespace'],
  33. 'childRefPK' => $childRefFilter['primaryKey'],
  34. ]);
  35. }
  36. $tblLabel = $acl->getNamespace();
  37. if ('default_db' == $acl->getSourceName()) {
  38. $tblLabel = array();
  39. $zasobObj = ProcesHelper::getZasobTableInfo($acl->getID());
  40. if (!$zasobObj) throw new Exception("Zasob TABELA ID=" . $acl->getID() . " nie istnieje");
  41. if (!empty($zasobObj->DESC_PL)) $tblLabel[] = $zasobObj->DESC_PL;
  42. if (!empty($zasobObj->OPIS)) $tblLabel[] = $zasobObj->OPIS;
  43. $tblLabel = implode(" - ", $tblLabel);
  44. }
  45. $tbl->setSyncUrl($syncUrl);
  46. $tbl->showProcesInitFiltr = $this->getLink("procesInitFiltrAjax", [ 'namespace' => $acl->getNamespace() ]);
  47. $tbl->showTableTools = $this->getLink("tableToolsAjax", [ 'namespace' => $acl->getNamespace() ]);
  48. $tbl->useUserTableFilter = $this->getLink("getUserTableFilterAjax");
  49. $tbl->setLabel($tblLabel);
  50. if (method_exists($acl, 'getGuiRowFunctions')) {
  51. foreach ($acl->getGuiRowFunctions() as $funKey => $funParams) {
  52. $tbl->addRowFunction($funKey, $funParams);
  53. }
  54. } else {
  55. $tbl->addRowFunction('edit');
  56. $tbl->addRowFunction('hist');
  57. $tbl->addRowFunction('files');
  58. $tbl->addRowFunction('cp');
  59. $tbl->addRowFunction('msgs');
  60. }
  61. return $tbl;
  62. }
  63. public function defaultAction() {
  64. UI::gora();
  65. UI::menu();
  66. try {
  67. $namespace = V::get('namespace', '', $_GET, 'word');
  68. if (!$namespace) {
  69. $typeName = V::get('typeName', '', $_GET, 'word');
  70. if (!$typeName) throw new Exception("Wrong param typeName");
  71. $namespace = Api_WfsNs::getBaseWfsUri() . '/' . str_replace(':', '/', $typeName);
  72. }
  73. $acl = Core_AclHelper::getAclByNamespace($namespace, $forceTblAclInit = ('1' == V::get('_force', '', $_GET)));
  74. $forceFilterInit = array();
  75. $filterInit = new stdClass();
  76. $filterInit->currSortCol = $acl->getPrimaryKeyField();
  77. $filterInit->currSortFlip = 'desc';
  78. foreach ($_REQUEST as $k => $v) {
  79. if (strlen($k) > 3 && substr($k, 0, 2) == 'f_' && !empty($v)) {// filter prefix
  80. $filterInit->$k = $v;
  81. }
  82. else if (strlen($k) > 4 && substr($k, 0, 3) == 'sf_' && !empty($v)) {// special filter prefix
  83. $filterInit->$k = $v;
  84. }
  85. else if (strlen($k) > 4 && substr($k, 0, 3) == 'ff_' && !empty($v)) {// force filter prefix
  86. $fldName = substr($k, 3);
  87. $forceFilterInit[$fldName] = $v;
  88. }
  89. }
  90. $backRefFilter = [
  91. 'namespace' => V::get('backRefNS', '', $_GET),
  92. 'primaryKey' => V::get('backRefPK', '', $_GET),
  93. 'fieldName' => V::get('backRefField', '', $_GET),
  94. ];
  95. $childRefFilter = [
  96. 'namespace' => V::get('childRefNS', '', $_GET),
  97. 'primaryKey' => V::get('childRefPK', '', $_GET),
  98. ];
  99. $tbl = $this->getTableAjaxWidget($acl, $backRefFilter, $childRefFilter);
  100. $tbl->setFilterInit($filterInit);
  101. if (!empty($forceFilterInit)) $tbl->setForceFilterInit($forceFilterInit);
  102. if (V::get('DBG_INST', '', $_GET)) { // TODO: TEST namespace
  103. $siblings = ACL::getNamespaceSiblings($namespace);
  104. DBG::nicePrint($siblings, '$siblings');
  105. $filtrInstance = V::get('f_instance', [], $_POST, 'array');
  106. DBG::nicePrint($filtrInstance, '$filtrInstance');
  107. $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");
  108. $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");
  109. $_ = array(UI, 'h');
  110. echo $_('form', ['method' => "POST", 'style' => "width:600px; border:1px solid #ddd; border-radius:2px"], [
  111. $_('div', ['style' => "background-color:#ddd"], "Test Filtr instancji"),
  112. $_('div', ['style' => "padding:8px"], array_map(function ($sibling) use ($filtrInstance, $_) {
  113. return $_('div', [], [
  114. $_('label', ['style' => "margin:0 8px"], [
  115. $_('input', array_merge(['type'=>"radio", 'name'=>"f_instance[{$sibling}]", 'value'=>'YES'], ('YES' === V::get($sibling, '', $filtrInstance)) ? ['checked' => "checked"] : [])),
  116. " TAK "
  117. ]),
  118. $_('label', ['style' => "margin:0 8px"], [
  119. $_('input', array_merge(['type'=>"radio", 'name'=>"f_instance[{$sibling}]", 'value'=>'NO'], ('NO' === V::get($sibling, '', $filtrInstance)) ? ['checked' => "checked"] : [])),
  120. " NIE "
  121. ]),
  122. $_('label', ['style' => "margin:0 8px"], [
  123. $_('input', ['type'=>"radio", 'name'=>"f_instance[{$sibling}]", 'value'=>'x']),
  124. " pomiń "
  125. ]),
  126. // $_('button', ['onClick'=>"this.form.f_instance['{$sibling}'].value = ''; return false"], "odznacz"),
  127. $_('button', ['onClick'=>"console.log(this.form.elements['f_instance[{$sibling}]']); this.form.elements['f_instance[{$sibling}]'].value = 'x'; return false"], "odznacz"),
  128. " - {$sibling}"
  129. ]);
  130. }, $siblings)),
  131. $_('div', [], [
  132. $_('input', ['type'=>"hidden", 'name'=>'_route', 'value'=>"ViewObject"]),
  133. $_('input', ['type'=>"hidden", 'name'=>'namespace', 'value'=>$namespace]),
  134. $_('input', ['type'=>"submit", 'value'=>"Filtruj - TEST"]),
  135. ]),
  136. ]);
  137. DBG::nicePrint($_POST, '$_POST');
  138. {
  139. $args = $_POST;
  140. $fIsInstance = [];
  141. $fIsNotInstance = [];
  142. if (!empty($args['f_instance'])) {
  143. foreach ($args['f_instance'] as $inst => $selected) {
  144. if ('YES' === $selected) {
  145. $fIsInstance[] = $inst;
  146. } else if ('NO' === $selected) {
  147. $fIsNotInstance[] = $inst;
  148. }
  149. }
  150. }
  151. }
  152. $queryFeatures = $acl->buildQuery([
  153. // TODO: 'propertyName' => "*,@instance",
  154. 'f_is_instance' => $fIsInstance,
  155. 'f_is_not_instance' => $fIsNotInstance,
  156. '@instances' => '1',
  157. 'limit' => 10
  158. ]);
  159. // $total = $queryFeatures->getTotal();
  160. $items = $queryFeatures->getItems();
  161. $rootNamespace = $acl->getRootNamespace();
  162. DBG::nicePrint($rootNamespace, '$rootNamespace');
  163. $jsRenderFunName = 'render_dropdown_instances_' . substr(md5(time()), 0, 6);
  164. DBG::nicePrint($jsRenderFunName, '$jsRenderFunName');
  165. UI::table([
  166. 'rows' => array_map(function($row) use ($namespace, $siblings, $rootNamespace, $jsRenderFunName) {
  167. return [
  168. 'ID' => $row['ID'],
  169. 'DESC' => $row['DESC'],
  170. 'TYPE' => $row['TYPE'],
  171. 'Typ' => UI::h('div', ['class'=>"p5UI__dropdown-wrap"], [
  172. UI::h('button', [
  173. // 'onClick' => "p5UI__dropdown(event, this, 'left bottom')",
  174. 'onClick' => "p5UI__dropdown(event, this, 'left bottom', {$jsRenderFunName}({$row['ID']}))",
  175. 'class' => "btn btn-xs btn-default p5UI__dropdown-btn"
  176. ], [
  177. UI::h('i', ['class' => "glyphicon glyphicon-tags", 'title' => "Ustaw typ danych (instancje)"]),
  178. ]),
  179. UI::h('div', ['class' => "p5UI__dropdown-content"]
  180. , array_merge(
  181. [
  182. UI::h('input', ['type' => "text", 'placeholder' => "Search..", 'class' => "p5UI__dropdown-input", 'onkeyup' => "p5_ViewObject_instances_filterInput(this)"], null),
  183. ]
  184. , array_map(function ($sibling) use ($row, $namespace, $rootNamespace) {
  185. return UI::h('div', ['label'=>$sibling, 'style'=>"padding:4px 0"], [
  186. UI::h('button', array_merge(['class' => "btn btn-xs btn-default",
  187. 'style' => "margin:0 4px 0 0",
  188. 'title' => "Ustaw instancje '{$sibling}'",
  189. 'onClick' => "return p5_ViewObject_instance_set(this, '{$row['ID']}', '{$sibling}', 'yes')"],
  190. (in_array($sibling, explode(',', $row['@instances']))) ? ['disabled' => "disabled"] : []
  191. ), "+"),
  192. UI::h('button', ['class' => "btn btn-xs btn-default",
  193. 'style' => "margin:0 4px 0 0",
  194. 'title' => "Usuń instancje '{$sibling}'",
  195. 'onClick' => "return p5_ViewObject_instance_set(this, '{$row['ID']}', '{$sibling}', 'no')"], "-"),
  196. UI::h('span', [], substr($sibling, strlen($rootNamespace) + 1)),
  197. ]);
  198. }, $siblings)
  199. )
  200. )
  201. ]),
  202. 'instancesList' => implode(', ', ACL::getFeatureNamespaces($namespace, $row['ID'])),
  203. ];
  204. }, $items)
  205. ]);
  206. echo UI::h('style', ['type' => "text/css"], "
  207. .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) }
  208. .p5UI__dropdown-content .p5UI__dropdown-item { display:block; color:#000; padding:4px; text-decoration:none }
  209. .p5UI__dropdown-content .p5UI__dropdown-item:hover { background-color:#ebebeb }
  210. ");
  211. echo UI::h('script', ['src'=>"static/vendor.js", 'type'=>"text/javascript"]);
  212. $jsArgs = [
  213. 'SET_INSTANCE_URL' => $this->getLink('setInstanceAjax'),
  214. 'NAMESPACE' => $namespace,
  215. 'DBG' => DBG::isActive() ? 'true' : 'false',
  216. ];
  217. UI::inlineJS(__FILE__ . '.instancesDropdown.js', [
  218. 'JS_GLOBAL_FUNCTION_NAME' => $jsRenderFunName,
  219. 'NAMESPACE' => $namespace,
  220. 'SET_INSTANCE_URL' => $this->getLink('setInstanceAjax'),
  221. 'DBG' => DBG::isActive() ? 1 : 0,
  222. 'INITIAL_DROPDOWN_DATA' => [
  223. // 'allowed_instances' => $siblings,
  224. 'allowed_instances' => array_map(function ($sibling) use ($rootNamespace) {
  225. return [
  226. 'namespace' => $sibling,
  227. 'label' => substr($sibling, strlen($rootNamespace) + 1)
  228. ];
  229. }, $siblings),
  230. 'items' => array_map(function($row) use ($namespace, $siblings, $rootNamespace, $jsRenderFunName) {
  231. return [
  232. 'pk' => $row['ID'], // TODO: $primaryKeyField
  233. 'instances' => explode(',', $row['@instances']),
  234. ];
  235. }, $items)
  236. ],
  237. ]);
  238. echo UI::h('script', [], "
  239. var SET_INSTANCE_URL = '{$jsArgs['SET_INSTANCE_URL']}'
  240. var NAMESPACE = '{$jsArgs['NAMESPACE']}'
  241. function p5_ViewObject_instance_set(n, pk, sibling, toConnect) {
  242. console.log('p5_ViewObject_instance_set pk('+pk+'), sibling('+sibling+'), toConnect('+toConnect+'), n', n);
  243. window.fetch(SET_INSTANCE_URL, {
  244. method: 'POST',
  245. headers: { 'Content-Type': 'application/json' },
  246. credentials: 'same-origin',
  247. body: JSON.stringify({
  248. namespace: NAMESPACE,
  249. primaryKey: pk,
  250. instance: sibling,
  251. toConnect: toConnect,
  252. })
  253. }).then(function (response) {
  254. return response.json()
  255. }).then(function (response) {
  256. p5UI__notifyAjaxCallback(response)
  257. console.log(response) // TODO: render list
  258. })
  259. }
  260. ");
  261. echo UI::h('script', [], "
  262. function p5_ViewObject_instances_filterInput(n) {
  263. var input, filter, ul, li, a, i, div;
  264. input = n // .id-myInput
  265. filter = input.value.toUpperCase()
  266. div = n.parentNode // .id-myDropdown
  267. a = div.getElementsByTagName('div')
  268. for (i = 0; i < a.length; i++) {
  269. if (a[i].getAttribute('label') && a[i].getAttribute('label').toUpperCase().indexOf(filter) > -1) {
  270. a[i].style.display = 'block'
  271. } else {
  272. a[i].style.display = 'none'
  273. }
  274. }
  275. }
  276. ");
  277. echo '<hr style="margin-top:300px">';
  278. exit;
  279. }
  280. echo $tbl->render();
  281. if (DBG::isActive() && V::get('DBG_ACL', '', $_GET)) {// test load perms
  282. Lib::loadClass('DebugExecutionTime');
  283. $dbgExecTime = new DebugExecutionTime();
  284. $dbgExecTime->activate();
  285. $dbgExecTime->log('start');
  286. UI::startContainer(['style'=>'border:1px solid red']);
  287. UI::tag('p', null, "TEST - load perms from db");
  288. $idTable = $acl->getID();
  289. UI::tag('p', null, "DBG idTable({$idTable})");
  290. if ($idTable > 0) {
  291. $dbgExecTime->log('before sql');
  292. $aclTableRows = DB::getPDO()->fetchAll("select * from `CRM_PROCES_idx_TABLE_TO_PROCES_PERMS_VIEW` where ID_TABLE = {$idTable}");
  293. $dbgExecTime->log('after sql', ['sql']);
  294. UI::table(['caption' => "from CRM_PROCES_idx_TABLE_TO_PROCES_PERMS_VIEW", 'rows' => $aclTableRows]);
  295. $csvIdProces = array();
  296. foreach ($aclTableRows as $row) {
  297. if (!in_array($row['ID_PROCES'], $csvIdProces)) $csvIdProces[] = $row['ID_PROCES'];
  298. }
  299. }
  300. $tableName = $acl->getName();
  301. $databaseName = DB::getPDO()->getDatabaseName();
  302. UI::table([
  303. 'caption' => "Cell to process",
  304. 'rows' => array_map(
  305. function ($row) use ($aclTableRows, $idTable) {
  306. $row['proces'] = array();
  307. $row['id_zasob'] = 0;
  308. $row['PERM_R'] = 0;
  309. $row['PERM_W'] = 0;
  310. $row['PERM_X'] = 0;
  311. $row['PERM_C'] = 0;
  312. $row['PERM_S'] = 0;
  313. $row['PERM_O'] = 0;
  314. $row['PERM_V'] = 0;
  315. $row['PERM_E'] = 0;
  316. foreach ($aclTableRows as $aclInfo) {
  317. if (strtolower($aclInfo['CELL_NAME']) == strtolower($row['COLUMN_NAME'])) {
  318. $row['proces'][] = $aclInfo['ID_PROCES'];
  319. $row['id_zasob'] = $aclInfo['ID_CELL'];
  320. $row['PERM_R'] += $aclInfo['PERM_R'];
  321. $row['PERM_W'] += $aclInfo['PERM_W'];
  322. $row['PERM_X'] += $aclInfo['PERM_X'];
  323. $row['PERM_C'] += $aclInfo['PERM_C'];
  324. $row['PERM_S'] += $aclInfo['PERM_S'];
  325. $row['PERM_O'] += $aclInfo['PERM_O'];
  326. $row['PERM_V'] += $aclInfo['PERM_V'];
  327. $row['PERM_E'] += $aclInfo['PERM_E'];
  328. }
  329. }
  330. $row['proces'] = (empty($row['proces']))
  331. ? "<i style=\"color:red\">Brak</i>"
  332. : implode(", ", $row['proces']);
  333. 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");
  334. return $row;
  335. }, DB::getPDO()->fetchAll("
  336. select t.TABLE_NAME, t.COLUMN_NAME, t.DATA_TYPE, t.COLUMN_TYPE
  337. from `information_schema`.`COLUMNS` t
  338. where t.TABLE_SCHEMA = '{$databaseName}'
  339. and t.TABLE_NAME like '{$tableName}'
  340. ")
  341. )
  342. ]);
  343. if (!empty($csvIdProces)) {
  344. $csvIdProces = implode(",", $csvIdProces);
  345. UI::tag('p', null, "DBG csvIdProces({$csvIdProces})");
  346. $userLogin = User::getLogin();
  347. $dbgExecTime->log('before sql');
  348. $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");
  349. $dbgExecTime->log('after sql', ['sql']);
  350. UI::table(['caption' => "from CRM_PROCES_idx_USER_to_PROCES_VIEW", 'rows' => $rows]);
  351. $userIdProces = array(); foreach ($rows as $row) $userIdProces[] = $row['ID_PROCES'];
  352. $userTablePerms = array();
  353. foreach ($aclTableRows as $row) {
  354. if (!in_array($row['ID_PROCES'], $userIdProces)) continue;
  355. if (array_key_exists($row['CELL_NAME'], $userTablePerms)) {
  356. $userTablePerms[ $row['CELL_NAME'] ][ 'PERM_R' ] += $row['PERM_R'];
  357. $userTablePerms[ $row['CELL_NAME'] ][ 'PERM_W' ] += $row['PERM_W'];
  358. $userTablePerms[ $row['CELL_NAME'] ][ 'PERM_X' ] += $row['PERM_X'];
  359. $userTablePerms[ $row['CELL_NAME'] ][ 'PERM_C' ] += $row['PERM_C'];
  360. $userTablePerms[ $row['CELL_NAME'] ][ 'PERM_S' ] += $row['PERM_S'];
  361. $userTablePerms[ $row['CELL_NAME'] ][ 'PERM_O' ] += $row['PERM_O'];
  362. $userTablePerms[ $row['CELL_NAME'] ][ 'PERM_V' ] += $row['PERM_V'];
  363. $userTablePerms[ $row['CELL_NAME'] ][ 'PERM_E' ] += $row['PERM_E'];
  364. } else {
  365. $userTablePerms[ $row['CELL_NAME'] ] = $row;
  366. unset($userTablePerms[ $row['CELL_NAME'] ][ 'TABLE_DESCRIPTION' ]);
  367. unset($userTablePerms[ $row['CELL_NAME'] ][ 'ID_PROCES' ]);
  368. unset($userTablePerms[ $row['CELL_NAME'] ][ 'FORM_TREAT' ]);
  369. }
  370. }
  371. UI::table(['caption' => "\$userTablePerms", 'rows' => $userTablePerms]);
  372. } else UI::alert('warning', "brak \$csvIdProces");
  373. $dbgExecTime->printDebug();
  374. UI::endContainer();
  375. }
  376. } catch (Exception $e) {
  377. UI::startContainer();
  378. UI::alert('danger', "<strong>Wystąpiły błędy!</strong> " . $e->getMessage());
  379. UI::endContainer();
  380. DBG::log($e);
  381. }
  382. UI::dol();
  383. }
  384. public function setInstanceAjaxAction() {
  385. Response::sendTryCatchJson(array($this, 'setInstanceAjax'), $args = 'JSON_FROM_REQUEST_BODY');
  386. }
  387. public function setInstanceAjax($args) {
  388. // namespace => default_db/CRM_PROCES/PROCES_INIT
  389. // primaryKey => 6
  390. // instance => default_db/CRM_PROCES/PROCES_TREE
  391. // toConnect => yes
  392. if (empty($args['namespace'])) throw new Exception("Missing namespace");
  393. if (empty($args['primaryKey'])) throw new Exception("Missing primaryKey");
  394. if (empty($args['instance'])) throw new Exception("Missing instance");
  395. if (empty($args['toConnect'])) throw new Exception("Missing toConnect");
  396. if (!in_array($args['toConnect'], ['yes', 'no'])) throw new Exception("Wrong param toConnect");
  397. $idInstance = ACL::getInstanceId($args['instance']);
  398. throw new Exception("TODO: check instance config"); // if 'view' then set instance is not allowed
  399. // $instanceTable = ACL::getInstanceTable($args['namespace']);
  400. // switch ($args['toConnect']) {
  401. // case 'yes': {
  402. // // TODO: _HIST info - waiting
  403. // $ret = DB::getPDO()->execSql("
  404. // insert into `{$instanceTable}` (`pk`, `idInstance`)
  405. // values ( :pk , :idInstance )
  406. // ", [
  407. // 'pk' => $args['primaryKey'],
  408. // 'idInstance' => $idInstance,
  409. // ]);
  410. // // TODO: _HIST info - mark as done
  411. // } break;
  412. // case 'no': {
  413. // // TODO: _HIST info - waiting
  414. // $ret = DB::getPDO()->execSql("
  415. // delete from `{$instanceTable}`
  416. // where `pk` = :pk
  417. // and `idInstance` = :idInstance
  418. // ", [
  419. // 'pk' => $args['primaryKey'],
  420. // 'idInstance' => $idInstance,
  421. // ]);
  422. // // TODO: _HIST info - mark as done
  423. // } break;
  424. // }
  425. // return [
  426. // 'type' => 'success',
  427. // 'msg' => "Wprowadzono zmiany ({$ret})",
  428. // // TODO: 'data' => all instances for pk
  429. // ];
  430. }
  431. public function rmUserTableFilterAjaxAction() {
  432. Response::sendTryCatchJson(array($this, 'rmUserTableFilterAjax'), $args = 'JSON_FROM_REQUEST_BODY');
  433. }
  434. public function rmUserTableFilterAjax($args) {
  435. $namespace = V::get('namespace', '', $args);
  436. $filtrName = V::get('filtrName', '', $args);
  437. if (!$namespace) throw new Exception("Missing namespace");
  438. if (!$filtrName) throw new Exception("Missing filtrName");
  439. $userFltrConfKey = "tableColFilters__" . User::getLogin();
  440. $currentFilters = DB::getPDO()->fetchValue(" select CONF_VAL from CRM_CONFIG where CONF_KEY = '{$userFltrConfKey}' ");
  441. if (!$currentFilters) return [
  442. 'type' => 'warning',
  443. 'msg' => "Brak filtrów w bazie",
  444. ];
  445. $currentFilters = json_decode($currentFilters, 'assoc');
  446. unset($currentFilters[$namespace][$filtrName]);
  447. $affeced = DB::getPDO()->update('CRM_CONFIG', 'CONF_KEY', $userFltrConfKey, [
  448. 'CONF_VAL' => json_encode($currentFilters)
  449. ]);
  450. return [
  451. 'type' => 'success',
  452. 'msg' => 'Zapisano nowy filtr',
  453. 'data' => $currentFilters[$namespace]
  454. ];
  455. }
  456. public function addUserTableFilterAjaxAction() {
  457. Response::sendTryCatchJson(array($this, 'addUserTableFilterAjax'), $args = 'JSON_FROM_REQUEST_BODY');
  458. }
  459. public function addUserTableFilterAjax($args) {
  460. $namespace = V::get('namespace', '', $args);
  461. $filtrName = V::get('filtrName', '', $args);
  462. $visibleCols = V::get('visibleCols', '', $args);
  463. if (!$namespace) throw new Exception("Missing namespace");
  464. if (!$filtrName) throw new Exception("Missing filtrName");
  465. if (!$visibleCols) throw new Exception("Missing visibleCols");
  466. $userFltrConfKey = "tableColFilters__" . User::getLogin();
  467. $currentFilters = DB::getPDO()->fetchValue(" select CONF_VAL from CRM_CONFIG where CONF_KEY = '{$userFltrConfKey}' ");
  468. $currentFilters = ($currentFilters) ? json_decode($currentFilters, 'assoc') : [];
  469. $currentFilters[$namespace][$filtrName] = $visibleCols;
  470. $sqlFltr = json_encode($currentFilters);
  471. DB::getPDO()->execSql("
  472. insert into CRM_CONFIG (CONF_KEY, CONF_VAL)
  473. values ('$userFltrConfKey', '{$sqlFltr}')
  474. on duplicate key update CONF_VAL = '{$sqlFltr}'
  475. ");
  476. return [
  477. 'type' => 'success',
  478. 'msg' => 'Zapisano nowy filtr',
  479. 'data' => $currentFilters[$namespace]
  480. ];
  481. }
  482. public function getUserTableFilterAjaxAction() {
  483. Response::sendTryCatchJson(array($this, 'getUserTableFilterAjax'), $args = 'JSON_FROM_REQUEST_BODY');
  484. }
  485. public function getUserTableFilterAjax($args) {
  486. $namespace = V::get('namespace', '', $args);
  487. if (!$namespace) throw new Exception("Missing namespace");
  488. $userFltrConfKey = "tableColFilters__" . User::getLogin();
  489. $currentFilters = DB::getPDO()->fetchValue(" select CONF_VAL from CRM_CONFIG where CONF_KEY = '{$userFltrConfKey}' ");
  490. $currentFilters = ($currentFilters) ? json_decode($currentFilters, 'assoc') : [];
  491. return [
  492. 'type' => 'success',
  493. 'msg' => 'Odczytano filtry użytkownika',
  494. 'data' => (!empty($currentFilters[$namespace])) ? $currentFilters[$namespace] : []
  495. ];
  496. }
  497. public function revertFromHistAjaxAction() {
  498. Response::sendTryCatchJson(array($this, 'revertFromHistAjax'));
  499. }
  500. public function revertFromHistAjax() {
  501. $typeName = V::get('typeName', '', $_REQUEST, 'word');
  502. if (!$typeName) throw new Exception("Wrong param typeName");
  503. // TODO: use namespace from url
  504. // $namespace = V::get('namespace', '', $_GET, 'word');
  505. // if (!$namespace) {
  506. // $typeName = V::get('typeName', '', $_GET, 'word');
  507. // if (!$typeName) throw new Exception("Wrong param typeName");
  508. // $namespace = Api_WfsNs::getBaseWfsUri() . '/' . str_replace(':', '/', $typeName);
  509. // }
  510. // $acl = Core_AclHelper::getAclByNamespace($namespace, $forceTblAclInit = ('1' == V::get('_force', '', $_GET)));
  511. $id = V::get('ID', '', $_REQUEST, 'word');
  512. if (!$id) throw new Exception("Wrong param ID");
  513. $idHist = V::get('idHist', '', $_REQUEST, 'word');
  514. if (!$idHist) throw new Exception("Wrong param idHist");
  515. $fieldName = V::get('fieldName', '', $_REQUEST, 'word');
  516. if (!$fieldName) throw new Exception("Wrong param fieldName");
  517. $acl = Core_AclHelper::getAclByTypeName($typeName);
  518. $item = $acl->getItem($id);
  519. if (!$item) throw new HttpException("Item not found", 404);
  520. if (!$acl->canWriteObjectField($fieldName, $record)) throw new Exception("Missing perm Write for field {$fieldName}");
  521. $histItem = $acl->getHistItem($id, $idHist);
  522. if (!$histItem) throw new HttpException("Hist Item not found", 404);
  523. $histValue = V::get($fieldName, 'N/S;', $histItem);
  524. if ('N/S;' == $histValue) throw new Exception("Missing field value in hist[{$idHist}] for field({$fieldName}) from item[{$id}]");
  525. if ($acl->isGeomField($fieldName)) {
  526. $wktType = strtoupper($acl->getGeomFieldType($fieldName));
  527. if (!$wktType) throw new Exception("Wrong geometry type for field {$fieldName}");
  528. if ($wktType != strtoupper(substr($histValue, 0, strlen($wktType)))) throw new Exception("Wrong geometry type for field {$fieldName} in hist value");
  529. $coords = trim(substr($histValue, strlen($wktType)), '()');
  530. $wktValue = $acl->convertGmlCoordsToWkt($wktType, $coords, ['cs'=>' ', 'ts'=>',']);
  531. if (!$wktValue) throw new Exception("BUG in hist record");
  532. $sqlObj = array();
  533. $sqlObj['ID'] = $id;
  534. $sqlObj[$fieldName] = "GeomFromText('{$wktValue}')";
  535. $affected = DB::getDB()->UPDATE_OBJ($acl->getName(), (object)$sqlObj);
  536. if (0 == $affected) throw new AlertInfoException("Nie wprowadzono żadnych zmian");
  537. else if ($affected < 0) throw new Exception("Wystąpiły błędy podczas aktualizacji rekordu [{$id}]");
  538. $jsonResponse = array();
  539. $jsonResponse['type'] = 'success';
  540. $jsonResponse['msg'] = "Zaktualizowano dane na podstawie wcześniejszej wartości dla rekordu [{$id}]";
  541. $jsonResponse['actions'] = array();
  542. $jsonResponse['actions'][] = ['jsFunction'=>'TableAjax__HIST_Route', 'args'=>[$id]];
  543. return $jsonResponse;
  544. } else {
  545. throw new HttpException("Not implemented - update from hist only for the geom field", 501);
  546. }
  547. throw new Exception("BUG: update field '{$fieldName}' in item[{$id}] from hist[{$idHist}]", 501);
  548. }
  549. public function removeTheGeomAjaxAction() {
  550. Response::sendTryCatchJson(array($this, 'removeTheGeomAjax'), $args = 'JSON_FROM_REQUEST_BODY');
  551. }
  552. public function removeTheGeomAjax($args) {
  553. $namespace = V::get('namespace', '', $args, 'word');
  554. if (!$namespace) throw new HttpException("Bad Request - missing namespace", 400);
  555. $acl = Core_AclHelper::getAclByNamespace($namespace, $forceTblAclInit = ('1' == V::get('_force', '', $_GET)));
  556. $primaryKeyField = $acl->getPrimaryKeyField();
  557. $primaryKey = V::get($primaryKeyField, 0, $args, 'int');
  558. $geomFieldName = 'the_geom';
  559. $response = new stdClass();
  560. if ($primaryKey <= 0) throw new HttpException("Bad Request - Wrong param ID", 400);
  561. $record = $acl->getItem($primaryKey);
  562. if (!$record) throw new HttpException("Nie odnaleziono rekordu nr {$primaryKey}", 404);
  563. if (!$acl->canWriteObjectField($geomFieldName, $record)) throw new HttpException("Brak dostępu do zapisu dla pola {$geomFieldName}", 403);
  564. if (empty($record->{$geomFieldName})) {
  565. $response->type = 'info';
  566. $response->msg = "Rekord nie jest powiązany z żadnym obiektem na mapie";
  567. $response->record = $record;
  568. return $response;
  569. }
  570. $itemPatch = array();
  571. $itemPatch[$geomFieldName] = "NULL";
  572. $itemPatch[$primaryKeyField] = $primaryKey;
  573. $response = new stdClass();
  574. try {
  575. $affected = $acl->updateItem($itemPatch);
  576. if ($affected > 0) {
  577. $response->type = 'success';
  578. $response->msg = "Usunięto obiekt z mapy dla rekordu {$primaryKey}";// Rekord zapisany pomyślnie
  579. } else if ($affected == 0) {
  580. $response->type = 'info';
  581. $response->msg = "Nie wprowadzono żadnych zmian";
  582. }
  583. $response->record = $acl->getItem($primaryKey);
  584. }
  585. catch (Exception $e) {
  586. $response->type = 'error';
  587. $response->msg = $e->getMessage();
  588. }
  589. return $response;
  590. }
  591. public function getCsvTheGeomAjaxAction() {
  592. try {
  593. self::getCsvTheGeomAjax();
  594. } catch (Exception $e) {
  595. SE_Layout::gora();
  596. SE_Layout::menu();
  597. SE_Layout::alert('danger', $e->getMessage());
  598. ?>
  599. <div style="text-align: center;">
  600. <a href="<?=$_SERVER['HTTP_REFERER']?>" class="btn btn-primary" style="width: 80px;">Powrót</a>
  601. </div>
  602. <?php
  603. SE_Layout::dol();
  604. }
  605. }
  606. public function getCsvTheGeomAjax($minDistance = 10, $nearDistance = 1) {
  607. Lib::loadClass('EpsgConversion');
  608. Lib::loadClass('Geometry');
  609. $namespace = V::get('namespace', '', $_GET, 'word');
  610. $acl = Core_AclHelper::getAclByNamespace($namespace);
  611. $table = $acl->getRootTableName();
  612. $id = V::get('id', 0, $_GET, 'int');
  613. $query_points = "select st_astext(`the_geom`) as `the_geom` from `{$table}` where `ID` = {$id}";
  614. $result_points = DB::getPDO()->fetchValue($query_points);
  615. $points = Geometry::objectFromText($result_points, 'Wgs84ToPuwg2000')->points();
  616. $lines = Geometry::pointsToLines($points);
  617. $i = 1;
  618. $array = [['i' => $i++, 'x' => $points[0]->x, 'y' => $points[0]->y, 'desc' => 'Punkt']];
  619. foreach ($lines as $line) {
  620. $polygon_asText = Geometry::lineToRectangle($line, $nearDistance)->asText('Puwg2000ToWgs84');
  621. $query_nears = "select st_astext(`the_geom`) as `the_geom` from `rurociagi_obce_wsg84` where st_intersects(st_geomfromtext('{$polygon_asText}'), `the_geom`)";
  622. $results_nears = DB::getPDO()->fetchAll($query_nears);
  623. $nears = [];
  624. foreach ($results_nears as $result_nears) {
  625. $nears = array_merge($nears, Geometry::pointsToLines(Geometry::objectFromText($result_nears['the_geom'], 'Wgs84ToPuwg2000')->points()));
  626. }
  627. $nears = array_filter($nears, function ($near) use ($line, $nearDistance) {
  628. return Geometry::distance($line, $near) <= $nearDistance;
  629. });
  630. $ki = 1;
  631. $lastNear = null;
  632. $nearsOnLine = [];
  633. foreach ($nears as $near) {
  634. if ($crossPoints = Geometry::crossPoint($line, $near)) {
  635. switch (count($crossPoints)) {
  636. case 1:
  637. $array[] = ['i' => ($i - 1) . '.k' . $ki++, 'x' => $crossPoints[0]->x, 'y' => $crossPoints[0]->y, 'desc' => 'Kolizja (X)'];
  638. break;
  639. case 2:
  640. $array[] = ['i' => ($i - 1) . '.k' . $ki . 'a', 'x' => $crossPoint->x, 'y' => $crossPoint->y, 'desc' => 'Kolizja (I) start'];
  641. $array[] = ['i' => ($i - 1) . '.k' . $ki++ . 'b', 'x' => $crossPoint->x, 'y' => $crossPoint->y, 'desc' => 'Kolizja (I) stop'];
  642. break;
  643. default:
  644. throw new Exception(__CLASS__ . "::" . __FUNCTION__ . ' - unknown error');
  645. }
  646. } else $crossPoints = [];
  647. $nearOnLine = Geometry::line(Geometry::closedPointOnLine($near->a, $line), Geometry::closedPointOnLine($near->b, $line));
  648. if ($nearOnLine->length() < 1) {
  649. $break = false;
  650. foreach ($crossPoints as $crossPoint) {
  651. if (Geometry::distance($crossPoint, $nearOnLine) == 0) {
  652. $break = true;
  653. break;
  654. }
  655. }
  656. if ($break) continue;
  657. }
  658. if ($lastNearOnLine) {
  659. if (Geometry::distance($lastNearOnLine->b, $nearOnLine->a) < 1) $lastNearOnLine->b = $nearOnLine->b;
  660. else $nearsOnLine[] = $lastNearOnLine;
  661. }
  662. $lastNearOnLine = $nearOnLine;
  663. }
  664. if ($lastNearOnLine) $nearsOnLine[] = $lastNearOnLine;
  665. foreach ($nearsOnLine as $nearOnLine) {
  666. $array[] = ['i' => ($i - 1) . '.k' . $ki . 'a', 'x' => $nearOnLine->a->x, 'y' => $nearOnLine->a->y, 'desc' => 'Kolizja (II) start'];
  667. $array[] = ['i' => ($i - 1) . '.k' . $ki++ . 'b', 'x' => $nearOnLine->b->x, 'y' => $nearOnLine->b->y, 'desc' => 'Kolizja (II) stop'];
  668. }
  669. if (($distance = $line->length()) > $minDistance) {
  670. $parts = ceil($distance / $minDistance);
  671. $deltaX = ($line->b->x - $line->a->x) / $parts;
  672. $deltaY = ($line->b->y - $line->a->y) / $parts;
  673. for ($j = 1; $j < $parts; $j++) {
  674. $array[] = ['i' => ($i - 1) . "." . $j, 'x' => ($line->a->x + $j * $deltaX), 'y' => ($line->a->y + $j * $deltaY), 'desc' => 'Pośredni'];
  675. }
  676. }
  677. $array[] = ['i' => $i, 'x' => $line->b->x, 'y' => $line->b->y, 'desc' => 'Punkt'];
  678. $i++;
  679. }
  680. $csv = implode("\n", array_map(function ($item) {
  681. try {
  682. $z = EpsgConversion::GetZByPuwg2000($item['x'], $item['y']);
  683. } catch (Exception $e) {
  684. $z = 0;
  685. }
  686. return $item['i'] . "," . round($item['y'], 3) . "," . round($item['x'], 3) . "," . round($z, 3) . "," . $item['desc'];
  687. }, $array));
  688. // echo "<pre>{$csv}</pre>";
  689. Response::sendCsv($csv, "{$table}.{$id}");
  690. }
  691. public function moreFunctionsCellAjaxAction() {
  692. Response::sendTryCatchJson(array($this, 'moreFunctionsCell'), $args = $_GET);
  693. }
  694. public function moreFunctionsCell($args) {// ajax task 'MORE_FUNCTIONS_CELL'
  695. $id = V::get('ID', 0, $args, 'int');
  696. if ($id <= 0) throw new HttpException("404", 404);
  697. $namespace = V::get('namespace', '', $args, 'word');
  698. if (!$namespace) throw new HttpException("Bad Request - missing namespace", 400);
  699. $acl = Core_AclHelper::getAclByNamespace($namespace, $forceTblAclInit = ('1' == V::get('_force', '', $args)));
  700. $response = new stdClass();
  701. $response->type = 'success';
  702. $response->msg = 'Funkcje';
  703. $response->rowFunctions = Core_AclHelper::getMoreFunctionsCell($acl, array('primary_key' => $id));
  704. return $response;
  705. }
  706. public function createFormAction() {// TODO: move to createFormJsonAction
  707. try {
  708. $args = $_REQUEST;
  709. $namespace = V::get('namespace', '', $args, 'word');
  710. if (!$namespace) throw new HttpException("Bad Request - missing namespace", 400);
  711. $acl = Core_AclHelper::getAclByNamespace($namespace);
  712. $tbl = $this->getTableAjaxWidget($acl);
  713. $tbl->sendAjaxCreate();
  714. } catch (Exception $e) {
  715. DBG::log($e);
  716. throw $e;
  717. }
  718. }
  719. public function createFormJsonAction() {
  720. Response::sendTryCatchJson(array($this, 'createFormJson'), $args = $_REQUEST);
  721. }
  722. public function createFormJson($args) { // namespace, _hash, _primaryKey
  723. $namespace = V::get('namespace', '', $args, 'word');
  724. if (!$namespace) throw new HttpException("Bad Request - missing namespace", 400);
  725. $acl = Core_AclHelper::getAclByNamespace($namespace);
  726. $tbl = $this->getTableAjaxWidget($acl);
  727. if (!Core_AclHelper::hasCreatePerms($acl)) {
  728. return [
  729. 'type' => "success",
  730. 'msg' => "Dodaj nowy rekord",
  731. 'body' => [
  732. 'reactNode' => [ 'div', [ 'class' => "alert alert-danger" ], "Brak uprawnień do utworzenia nowego rekordu." ]
  733. ],
  734. ];
  735. // throw new Exception("Brak uprawnień do utworzenia nowego rekordu.");
  736. }
  737. $fieldsList = array();
  738. foreach ($acl->getFieldListByIdZasob() as $kID => $fieldName) {
  739. if ($fieldName == 'ID') continue;
  740. $field['name'] = $fieldName;
  741. $field['opis'] = $acl->getFieldOpis($fieldName);
  742. $field['label'] = $acl->getFieldLabel($fieldName);
  743. if (empty($field['label'])) $field['label'] = str_replace('_', ' ', $fieldName);
  744. $fieldsList[$kID] = $field;
  745. }
  746. $cols = array();
  747. $forceFilterInit = array();
  748. $defaultAclGroup = User::getDefaultAclGroup();
  749. if ($defaultAclGroup) {
  750. $forceFilterInit['A_ADM_COMPANY'] = $defaultAclGroup;
  751. $forceFilterInit['A_CLASSIFIED'] = $defaultAclGroup;
  752. }
  753. foreach ($_GET as $k => $v) { // TODO: read from $args ?
  754. if (strlen($k) > 4 && substr($k, 0, 3) == 'ff_' && !empty($v)) {// force filter prefix
  755. $fldName = substr($k, 3);
  756. $forceFilterInit[$fldName] = $v;
  757. }
  758. }
  759. DBG::log($forceFilterInit, 'array', "\$forceFilterInit");
  760. foreach ($fieldsList as $kID => $field) {
  761. $defaultValue = '';
  762. if (!empty($forceFilterInit[$field['name']])) {
  763. $defaultValue = $forceFilterInit[$field['name']];
  764. }
  765. $cols[$kID] = V::get("f{$kID}", $defaultValue, $_POST);
  766. }
  767. DBG::log($cols, 'array', "\$cols - field values");
  768. $tsValues = array();
  769. $featureFunctions = [
  770. // 'edit' => [ 'href' => '#EDIT/{0}', 'ico' => 'glyphicon glyphicon-pencil', 'title' => "Edytuj rekord"],
  771. 'hist' => [ 'href' => '#HIST/{0}', 'ico' => 'glyphicon glyphicon-book', 'title' => "Historia" ],
  772. 'files' => [ 'href' => '#FILES/{0}', 'ico' => 'glyphicon glyphicon-folder-open', 'title' => "Pliki" ],
  773. // 'cp' => [ 'href' => '#', 'ico' => 'glyphicon glyphicon-plus-sign', 'title' => "Kopiuj rekord", 'onclick' => 'return tableAjaxCopy({0});' ],
  774. 'msgs' => [ 'href' => "index.php?_route=TableMsgs&_task=tableRow&idTable=".$acl->getID()."&idRow={0}", 'ico' => 'glyphicon glyphicon-envelope', 'title' => "Wiadomości" ],
  775. ];
  776. $jsFields = [];
  777. $tabindex = 0;
  778. foreach ($fieldsList as $kID => $vCol) {
  779. $fieldName = $vCol['name'];
  780. $fieldLabel = str_replace('<br>', ' ', $vCol['label']);
  781. DBG::log(['$fieldName'=>$fieldName, 'canCreate'=>$acl->canCreateField($fieldName)], 'array', "form field");
  782. if ($acl->canCreateField($fieldName)) {
  783. DBG::log("editFormJson::field({$fieldName})");
  784. $fieldParams = [ 'appendBack' => true, 'tabindex' => (++$tabindex), 'maxGrid' => 8 ];
  785. if (!empty($tsValues[$kID])) $fieldParams['typespecialValue'] = $tsValues[$kID];
  786. $jsFields[] = [ 'div', [ 'class' => "form-group" ], [
  787. [ 'label', [ 'class' => "control-label", 'for' => "f{$kID}" ], [
  788. [ 'span', [ 'style' => ['padding-right'=>'4px'] ], $fieldLabel ],
  789. [ 'i', [ 'class' => "glyphicon glyphicon-info-sign frm-help", 'data-toggle' => "popover", 'data-trigger' => "hover", 'title' => "", 'data-content' => htmlspecialchars($vCol['opis']), 'data-original-title' => "[{$kID}] {$fieldName}" ] ],
  790. ] ],
  791. [ 'div', [ 'class' => "" ], [
  792. UI::hGetFormItem($acl, $fieldName, 'C', $kID, "f{$kID}", $cols[$kID], $fieldParams),
  793. ] ]
  794. ] ];
  795. // } else {
  796. // $jsFields[] = [ 'div', [ 'class' => "form-group" ], [
  797. // "TODO: SKIP field ({$fieldName}) - ! canWriteObjectField && ! canReadObjectField"
  798. // ]];
  799. }
  800. }
  801. $jsFields[] = [ 'div', [ 'class' => "form-group" ], [
  802. [ 'div', [ 'class' => "" ], [
  803. ['button', [ 'type' => "submit", 'class' => "btn btn-primary", 'tabindex' => ++$tabindex ], "Zapisz" ]
  804. ] ]
  805. ] ];
  806. $tblLabel = $acl->getNamespace();
  807. if ('default_db' == $acl->getSourceName()) {
  808. $tblLabel = array();
  809. $zasobObj = ProcesHelper::getZasobTableInfo($acl->getID());
  810. if (!$zasobObj) throw new Exception("Zasob TABELA ID=" . $acl->getID() . " nie istnieje");
  811. if (!empty($zasobObj->DESC_PL)) $tblLabel []= $zasobObj->DESC_PL;
  812. if (!empty($zasobObj->OPIS)) $tblLabel []= $zasobObj->OPIS;
  813. $tblLabel = implode(" - ", $tblLabel);
  814. }
  815. $syncUrl = Request::getPathUri() . 'index.php?_route=ViewTableAjax&namespace=' . $acl->getNamespace();
  816. $jsGui = [
  817. 'reactNode' => [ 'div', [ 'class' => "container AjaxFrmHorizontalEdit", 'style' => [ "max-width" => "940px" ] ], [
  818. [ 'h4', [ 'style' => [ "padding-bottom" => "3px", "border-bottom" => "1px solid #ddd" ] ], [
  819. "Dodaj nowy rekord",
  820. ] ],
  821. [ 'P5UI__FeatureCreateForm', [
  822. 'class' => "", 'action' => "", 'method' => "post",
  823. 'id' => "CREATE_FRM_{$this->_htmlID}", // TODO: rm - use React nodes // TODO: $this->_htmlID not exists!
  824. 'ajaxSaveUrl' => "{$syncUrl}&_task=createSaveAjax", // TODO:? &_hash={$this->_htmlID}
  825. 'ajaxSaveLegacyUrl' => "{$syncUrl}&_task=createSaveLegacy", // TODO: Legacy RM
  826. 'namespace' => $acl->getNamespace(),
  827. 'tableLabelHtml' => $tblLabel,
  828. '_htmlID' => $acl->getName(),
  829. ], [
  830. [ 'fieldset', [ 'style' => [ "padding-bottom" => "100px" ] ], $jsFields ] // fieldset
  831. ] ] // form
  832. ] ] // .container
  833. ];
  834. return [
  835. 'type' => "success",
  836. 'msg' => "Dodaj nowy rekord",
  837. 'body' => $jsGui, // TODO: action for GUI: array to render by function h, js to trigger
  838. ];
  839. }
  840. public function createSaveAjaxAction() {
  841. Response::sendTryCatchJson(array($this, 'createSaveAjax'), $args = 'JSON_FROM_REQUEST_BODY');
  842. }
  843. public function createSaveAjax($args) {
  844. throw new Exception("TODO: ...");
  845. }
  846. public function createSaveLegacyAction() { // TODO: Legacy RM
  847. $args = [
  848. 'namespace' => V::get('namespace', '', $_GET),
  849. 'body' => Request::getRequestJson(),
  850. ];
  851. DBG::log($args, 'array', 'createSaveLegacyAction');
  852. Response::sendTryCatchJson(array($this, 'createSaveLegacy'), $args);
  853. }
  854. public function createSaveLegacy($args) { // TODO: Legacy RM
  855. $namespace = V::get('namespace', '', $args, 'word');
  856. if (!$namespace) throw new HttpException("Bad Request - missing namespace", 400);
  857. $body = V::get('body', null, $args);
  858. if (!$body) throw new HttpException("Bad Request - missing body", 400);
  859. $acl = Core_AclHelper::getAclByNamespace($namespace);
  860. $tbl = $this->getTableAjaxWidget($acl);
  861. DBG::log($args, 'array', "ajaxCreateSave");
  862. $createdId = null;
  863. try {
  864. $item = $acl->convertObjectFromUserInput($body, $type = 'array_by_id', $prefix = 'f');
  865. $createdId = $acl->addItem($item);
  866. if ($createdId) {
  867. return [
  868. 'type' => 'success',
  869. 'msg' => "Utworzono pomyślnie rekord nr {$createdId}",
  870. 'id' => $createdId,
  871. 'record' => $acl->buildQuery([])->getItem($createdId),
  872. ];
  873. }
  874. else {
  875. return [
  876. 'type' => 'error',
  877. 'msg' => "Nie udało się utworzyć nowego rekordu!",
  878. ];
  879. }
  880. }
  881. catch (Exception $e) {
  882. return [
  883. 'type' => 'error',
  884. 'msg' => $e->getMessage(),
  885. ];
  886. }
  887. }
  888. public function editFormAction() { // TODO: not used - moved to editFormJsonAction
  889. try {
  890. $args = $_REQUEST;
  891. $id = V::get('_primaryKey', 0, $args, 'int');
  892. if ($id <= 0) throw new HttpException("Bad Request - missing primaryKey", 400);
  893. $namespace = V::get('namespace', '', $args, 'word');
  894. if (!$namespace) throw new HttpException("Bad Request - missing namespace", 400);
  895. $acl = Core_AclHelper::getAclByNamespace($namespace);
  896. $tbl = $this->getTableAjaxWidget($acl);
  897. $tbl->sendAjaxEdit($id, $args);
  898. } catch (Exception $e) {
  899. DBG::log($e);
  900. throw $e;
  901. }
  902. }
  903. public function editFormJsonAction() {
  904. Response::sendTryCatchJson(array($this, 'editFormJson'), $args = $_REQUEST);
  905. }
  906. public function editFormJson($args) { // namespace, _hash, _primaryKey
  907. $id = V::get('_primaryKey', 0, $args, 'int');
  908. if ($id <= 0) throw new HttpException("Bad Request - missing primaryKey", 400);
  909. $namespace = V::get('namespace', '', $args, 'word');
  910. if (!$namespace) throw new HttpException("Bad Request - missing namespace", 400);
  911. $acl = Core_AclHelper::getAclByNamespace($namespace);
  912. $tbl = $this->getTableAjaxWidget($acl);
  913. $record = $acl->buildQuery([])->getItem($id);
  914. if (!$acl->canWriteRecord($record) && !$acl->hasPermSuperWrite()) {
  915. return [
  916. 'type' => "success",
  917. 'msg' => "Edycja rekordu nr {$id}",
  918. 'body' => [
  919. 'reactNode' => [ 'div', [ 'class' => "alert alert-danger" ], "Brak dostępu do rekordu" ]
  920. ],
  921. ];
  922. // throw new Exception("Brak dostępu do rekordu");
  923. }
  924. $fieldsList = array();
  925. foreach ($acl->getFieldListByIdZasob() as $kID => $fieldName) {
  926. if ($fieldName == 'ID') continue;
  927. $field['name'] = $fieldName;
  928. $field['opis'] = $acl->getFieldOpis($fieldName);
  929. $field['label'] = $acl->getFieldLabel($fieldName);
  930. if (empty($field['label'])) $field['label'] = str_replace('_', ' ', $fieldName);
  931. $fieldsList[$kID] = $field;
  932. }
  933. $cols = array();
  934. foreach ($fieldsList as $kID => $field) {
  935. $cols[$kID] = '';
  936. if ($acl->canReadObjectField($field['name'], $record)) {
  937. $cols[$kID] = V::get($field['name'], '', $record);
  938. } else {
  939. $cols[$kID] = '*****';
  940. }
  941. $cols[$kID] = V::get("f{$kID}", $cols[$kID], $_POST);
  942. }
  943. $tsValues = array();
  944. if (!empty($fieldsList)) {
  945. foreach ($fieldsList as $vColID => $vCol) {
  946. $typeSpecial = Typespecial::getInstance($vColID, $vCol['name']);
  947. if ($typeSpecial) {
  948. $colValue = V::get($vCol['name'], '', $record);
  949. $specialValues = $typeSpecial->getEditSelectedValuesByIds($acl->getID(), $record['ID'], $vCol['name'], $colValue);
  950. if (!empty($specialValues)) {
  951. $tsValues[$vColID] = implode('<br>', $specialValues);
  952. }
  953. }
  954. }
  955. }
  956. DBG::log($tsValues, 'array', "editFormJson::tsValues");
  957. foreach ($tsValues as $idx => $value) {
  958. if ('<' === substr($value, 0, 1)) {
  959. // $tsValues[$idx] = UI::convertHtmlToArray($value); // TODO: ...
  960. $tsValues[$idx] = [ 'P5UI__RawHtml', [ 'rawHtml' => $tsValues[$idx] ] ];
  961. }
  962. }
  963. DBG::log($tsValues, 'array', "editFormJson::tsValues parsed");
  964. $featureFunctions = [
  965. // 'edit' => [ 'href' => '#EDIT/{0}', 'ico' => 'glyphicon glyphicon-pencil', 'title' => "Edytuj rekord"],
  966. 'hist' => [ 'href' => '#HIST/{0}', 'ico' => 'glyphicon glyphicon-book', 'title' => "Historia" ],
  967. 'files' => [ 'href' => '#FILES/{0}', 'ico' => 'glyphicon glyphicon-folder-open', 'title' => "Pliki" ],
  968. // 'cp' => [ 'href' => '#', 'ico' => 'glyphicon glyphicon-plus-sign', 'title' => "Kopiuj rekord", 'onclick' => 'return tableAjaxCopy({0});' ],
  969. 'msgs' => [ 'href' => "index.php?_route=TableMsgs&_task=tableRow&idTable=".$acl->getID()."&idRow={0}", 'ico' => 'glyphicon glyphicon-envelope', 'title' => "Wiadomości" ],
  970. ];
  971. $rowFunctionsOut = [ 'P5UI__FeatureRowFunctions', [
  972. 'id' => $record[ $acl->getPrimaryKeyField() ],
  973. 'functions' => $featureFunctions,
  974. 'showLabels' => true,
  975. 'viewMoreDropdown' => [
  976. 'primaryKey' => $record['ID'],
  977. 'uri' => $this->getLink('moreFunctionsCellAjax', [ 'namespace' => $acl->getNamespace(), 'ID' => $record['ID'] ]),
  978. ],
  979. ] ]; // TODO: $this->_showRowFunctions($record['ID'], array('edit', 'cp'), true);
  980. $jsFields = [];
  981. $tabindex = 0;
  982. foreach ($fieldsList as $kID => $vCol) {
  983. $fieldName = $vCol['name'];
  984. $fieldLabel = str_replace('<br>', ' ', $vCol['label']);
  985. DBG::log(['$fieldName'=>$fieldName, '$record'=>$record, 'canWrite'=>$acl->canWriteObjectField($fieldName, $record), 'canRead'=>$acl->canReadObjectField($fieldName, $record)], 'array', "form field");
  986. if ($acl->canWriteObjectField($fieldName, $record)) {
  987. DBG::log("editFormJson::field({$fieldName})");
  988. $fieldParams = [ 'appendBack' => true, 'tabindex' => (++$tabindex), 'maxGrid' => 8 ];
  989. if (!empty($tsValues[$kID])) $fieldParams['typespecialValue'] = $tsValues[$kID];
  990. $jsFields[] = [ 'div', [ 'class' => "form-group" ], [
  991. [ 'label', [ 'class' => "control-label", 'for' => "f{$kID}" ], [
  992. [ 'span', [ 'style' => ['padding-right'=>'4px'] ], $fieldLabel ],
  993. [ 'i', [ 'class' => "glyphicon glyphicon-info-sign frm-help", 'data-toggle' => "popover", 'data-trigger' => "hover", 'title' => "", 'data-content' => htmlspecialchars($vCol['opis']), 'data-original-title' => "[{$kID}] {$fieldName}" ] ],
  994. ] ],
  995. [ 'div', [ 'class' => "" ], [
  996. UI::hGetFormItem($acl, $fieldName, 'W', $kID, "f{$kID}", $cols[$kID], $fieldParams, $record),
  997. ] ]
  998. ] ];
  999. } else if ($acl->canReadObjectField($fieldName, $record)) {
  1000. $jsFields[] = [ 'div', [ 'class' => "form-group" ], [
  1001. [ 'label', [ 'class' => "control-label", 'for' => "f{$kID}" ], [
  1002. [ 'span', [ 'style' => ['padding-right'=>'4px'] ], $fieldLabel ],
  1003. [ 'i', [ 'class' => "glyphicon glyphicon-info-sign frm-help", 'data-toggle' => "popover", 'data-trigger' => "hover", 'title' => "", 'data-content' => htmlspecialchars($vCol['opis']), 'data-original-title' => "[{$kID}] {$fieldName}" ] ],
  1004. ] ],
  1005. [ 'div', [ 'class' => "" ], [
  1006. ['p', [ 'style' => [ 'margin-top' => '5px' ] ], [
  1007. (!empty($tsValues[$kID]))
  1008. ? $tsValues[$kID]
  1009. : V::get($fieldName, '', $record)
  1010. ] ],
  1011. ] ]
  1012. ] ];
  1013. // } else {
  1014. // $jsFields[] = [ 'div', [ 'class' => "form-group" ], [
  1015. // "TODO: SKIP field ({$fieldName}) - ! canWriteObjectField && ! canReadObjectField"
  1016. // ]];
  1017. }
  1018. }
  1019. $jsFields[] = [ 'div', [ 'class' => "form-group" ], [
  1020. [ 'div', [ 'class' => "" ], [
  1021. ['button', [ 'type' => "submit", 'class' => "btn btn-primary", 'tabindex' => ++$tabindex ], "Zapisz" ]
  1022. ] ]
  1023. ] ];
  1024. $tblLabel = $acl->getNamespace();
  1025. if ('default_db' == $acl->getSourceName()) {
  1026. $tblLabel = array();
  1027. $zasobObj = ProcesHelper::getZasobTableInfo($acl->getID());
  1028. if (!$zasobObj) throw new Exception("Zasob TABELA ID=" . $acl->getID() . " nie istnieje");
  1029. if (!empty($zasobObj->DESC_PL)) $tblLabel []= $zasobObj->DESC_PL;
  1030. if (!empty($zasobObj->OPIS)) $tblLabel []= $zasobObj->OPIS;
  1031. $tblLabel = implode(" - ", $tblLabel);
  1032. }
  1033. $syncUrl = Request::getPathUri() . 'index.php?_route=ViewTableAjax&namespace=' . $acl->getNamespace();
  1034. $jsGui = [
  1035. 'reactNode' => [ 'div', [ 'class' => "container AjaxFrmHorizontalEdit", 'style' => [ "max-width" => "940px" ] ], [
  1036. [ 'h4', [ 'style' => [ "padding-bottom" => "3px", "border-bottom" => "1px solid #ddd" ] ], [
  1037. "Edycja rekordu Nr {$record['ID']}",
  1038. [ 'small', [ 'class' => "pull-right valign-btns-bottom" ], [ $rowFunctionsOut ] ],
  1039. ] ],
  1040. [ 'P5UI__FeatureEditForm', [
  1041. 'class' => "", 'action' => "", 'method' => "post",
  1042. 'id' => "EDIT_FRM_{$this->_htmlID}", // TODO: rm - use React nodes // TODO: $this->_htmlID not exists!
  1043. 'ajaxSaveUrl' => "{$syncUrl}&_task=editSaveAjax", // TODO:? &_hash={$this->_htmlID}
  1044. 'namespace' => $acl->getNamespace(),
  1045. 'idRecord' => $record['ID'],
  1046. 'tableLabelHtml' => $tblLabel,
  1047. ], [
  1048. [ 'fieldset', [ 'style' => [ "padding-bottom" => "100px" ] ], $jsFields ] // fieldset
  1049. ] ] // form
  1050. ] ] // .container
  1051. ];
  1052. return [
  1053. 'type' => "success",
  1054. 'msg' => "Edycja rekordu nr {$id}",
  1055. 'body' => $jsGui, // TODO: action for GUI: array to render by function h, js to trigger
  1056. ];
  1057. }
  1058. public function editSaveAjaxAction() {
  1059. Response::sendTryCatchJson(array($this, 'editSaveAjax'), $args = 'JSON_FROM_REQUEST_BODY');
  1060. }
  1061. public function editSaveAjax($args) {
  1062. $namespace = V::get('namespace', '', $args, 'word');
  1063. if (!$namespace) throw new HttpException("Bad Request - missing namespace", 400);
  1064. $acl = Core_AclHelper::getAclByNamespace($namespace);
  1065. $primaryKeyField = $acl->getPrimaryKeyField();
  1066. $primaryKey = V::get('primaryKey', 0, $args, 'int');
  1067. if (empty($primaryKey)) throw new HttpException("Bad Request - missing primaryKey!", 400);
  1068. $item = $acl->getItem($primaryKey);
  1069. if (!$item) throw new HttpException("Item not exists!", 404);
  1070. $itemFromUser = $acl->convertObjectFromUserInput($args['form'], $type = 'array_by_id', $prefix = 'f');
  1071. $response = new stdClass();
  1072. $response->primaryKey = $primaryKey;
  1073. try {
  1074. $itemFromUser[$primaryKeyField] = $primaryKey;
  1075. $affected = $acl->updateItem($itemFromUser);
  1076. if ($affected > 0) {
  1077. $response->type = 'success';
  1078. $response->msg = "Rekord zapisany pomyślnie";//"Record saved successfully";
  1079. } else if ($affected == 0) {
  1080. $response->type = 'info';
  1081. $response->msg = "Nie wprowadzono żadnych zmian";
  1082. }
  1083. $response->record = $acl->getItem($primaryKey);
  1084. $rowFunList = Core_AclHelper::getMoreFunctionsCell($acl, array('primary_key'=>$primaryKey, 'record'=>$response->record));
  1085. if (!empty($rowFunList)) $response->rowFunctions = $rowFunList;
  1086. }
  1087. catch (Exception $e) {
  1088. $response->type = 'error';
  1089. $response->msg = "Wystąpiły błędy!";
  1090. $response->msg .= $e->getMessage();
  1091. }
  1092. return $response;
  1093. }
  1094. public function typeSpecialCellAction() {
  1095. Response::sendTryCatchJson(array($this, 'typeSpecialCell'), $args = $_REQUEST);
  1096. }
  1097. public function typeSpecialCell($args) {
  1098. $namespace = V::get('namespace', '', $args, 'word');
  1099. if (!$namespace) throw new HttpException("Bad Request - missing namespace", 400);
  1100. $acl = Core_AclHelper::getAclByNamespace($namespace);
  1101. $id = V::get('ID', 0, $args, 'int');
  1102. $fieldName = V::get('col', '', $args);
  1103. if ($id <= 0 || empty($fieldName)) throw new HttpException("Bad Request - missing id or col", 400);
  1104. $col = $fieldName;// TODO: RM $col
  1105. $jsonData = new stdClass();
  1106. $idField = $acl->getFieldIdByName($fieldName);
  1107. if (!$idField) throw new Exception("Wrong field");
  1108. $item = $acl->getItem($id);
  1109. if (!$acl->canReadObjectField($fieldName, $item)) throw new Exception("Brak dostępu");
  1110. $typeSpecial = Typespecial::getInstance($idField, $fieldName);
  1111. if ($typeSpecial) {
  1112. $jsonData->data = $typeSpecial->getReturnData($acl->getID(), $id, $fieldName, '');
  1113. $jsonData->namespace = 'default_db/' . V::get('tbl_name', '', $jsonData->data);
  1114. }
  1115. return $jsonData;
  1116. }
  1117. public function typespecialAction() { Response::sendTryCatchJson(array($this, 'typespecial'), $args = $_REQUEST); }
  1118. public function typespecial($args) { // @required idField, @optional: q (query), selected (selected value), idRecord (fetch value for given record)
  1119. $idField = V::get('idField', 0, $args, 'int');
  1120. if (!$idField) throw new HttpException("Bad Request - missing idField", 400);
  1121. $query = V::get('q', '', $_REQUEST);
  1122. DBG::log("\$query({$query})");
  1123. $cellInfo = DB::getPDO()->fetchFirst("
  1124. select *
  1125. from CRM_PROCES_idx_TABLES_INFO_VIEW
  1126. where ID_CELL = :id
  1127. ", [ ':id' => $idField ]);
  1128. DBG::log($cellInfo, 'array', "cell info");
  1129. if (!$cellInfo) throw new HttpException("Bad Request - wrong idField", 400);
  1130. // 'ID_CELL' => '24310',
  1131. // 'CELL_NAME' => 'L_APPOITMENT_USER',
  1132. // 'CELL_LABEL' => 'Osoba odpowiedzialna',
  1133. // 'CELL_DESCRIPTION' => '',
  1134. // 'CELL_SORT_PRIO' => '3',
  1135. // 'ID_TABLE' => '13051',
  1136. // 'TABLE_NAME' => 'TEST_PERMS',
  1137. // 'TABLE_LABEL' => 'Test permy',
  1138. // 'TABLE_DESCRIPTION' => '',
  1139. // 'ID_DATABASE' => '36',
  1140. $namespace = (false !== strpos($cellInfo['TABLE_NAME'], '/')) ? $cellInfo['TABLE_NAME'] : "default_db/{$cellInfo['TABLE_NAME']}";
  1141. if (!$namespace) throw new HttpException("Bad Request - wrong idField, cannot find namespace", 400);
  1142. $acl = Core_AclHelper::getAclByNamespace($namespace);
  1143. $fieldName = $cellInfo['CELL_NAME'];
  1144. $jsonData = array();
  1145. $typeSpecial = Typespecial::getInstance($idField, $fieldName);
  1146. if ($typeSpecial) {
  1147. // if (idRecord or selected) { // TODO
  1148. // $jsonData->data = $typeSpecial->getReturnData($acl->getID(), $id, $fieldName, '');
  1149. // $jsonData->namespace = 'default_db/' . V::get('tbl_name', '', $jsonData->data);
  1150. $rawRows = null;
  1151. $rows = $typeSpecial->getValuesWithExports($query);
  1152. DBG::log($rows, 'array', "\$rows({$query})");
  1153. foreach ($rows as $kID => $vItem) {
  1154. $itemJson = new stdClass();
  1155. $itemJson->id = $vItem->id;
  1156. $itemJson->name = $vItem->param_out;
  1157. if (!empty($vItem->exports)) {
  1158. $itemJson->exports = $vItem->exports;
  1159. }
  1160. if (!empty($vItem->{'$order'})) {
  1161. $itemJson->{'$order'} = $vItem->{'$order'};
  1162. }
  1163. $jsonData[] = $itemJson;
  1164. }
  1165. }
  1166. return $jsonData;
  1167. }
  1168. /**
  1169. * @param $_GET['namespace'] = AclNamespace
  1170. * @param $_GET['format'] = 'csv' | 'html'
  1171. * @param $_GET['flds'] = csv - coma separated field names
  1172. * @param $_GET['sortCol'] = FieldName
  1173. * @param $_GET['sortDir'] = SortDir ('desc' | 'asc')
  1174. * @param $_GET['f_{$fieldName}'] = filter
  1175. * @param $_GET['sf_{$fieldName}'] = force filter
  1176. */
  1177. public function exportAction() {
  1178. $args = $_GET;
  1179. $namespace = V::get('namespace', '', $args, 'word');
  1180. if (!$namespace) throw new HttpException("Bad Request - missing namespace", 400);
  1181. $acl = Core_AclHelper::getAclByNamespace($namespace);
  1182. $exportLimit = 10000;
  1183. $params = array();
  1184. $params['limit'] = $exportLimit;
  1185. // $params['limitstart'] = 0;
  1186. $params['order_by'] = V::get('sortCol', '', $args);
  1187. $params['order_dir'] = V::get('sortDir', '', $args);
  1188. $params['cols'] = array($acl->getPrimaryKeyField());
  1189. $toExportFields = explode(',', V::get('flds', '', $_GET));
  1190. if (empty($toExportFields)) throw new Exception("Nie wybrano żandych pól do exportu.");
  1191. $allowedExportFieldList = Core_AclHelper::getExportFieldList($acl);
  1192. foreach ($toExportFields as $fieldName) {
  1193. if ($fieldName == $acl->getPrimaryKeyField()) continue;
  1194. if (!in_array($fieldName, $allowedExportFieldList)) throw new Exception("Brak uprawnień do exportu pola '{$fieldName}'");
  1195. $params['cols'][] = $fieldName;
  1196. }
  1197. $labels = array();
  1198. foreach ($toExportFields as $fieldName) {
  1199. $labels[ $fieldName ] = $acl->getFieldLabel($fieldName);
  1200. }
  1201. foreach ($args as $k => $v) {
  1202. if (strlen($k) > 3 && substr($k, 0, 2) == 'f_' && strlen($v) > 0) {// filter prefix
  1203. $params[$k] = $v;
  1204. }
  1205. else if (strlen($k) > 4 && substr($k, 0, 3) == 'sf_' && strlen($v) > 0) {// special filter prefix
  1206. $params[$k] = $v;
  1207. }
  1208. }
  1209. try {
  1210. $queryFeatures = $acl->buildQuery($params);
  1211. $total = $queryFeatures->getTotal();
  1212. $listItems = $queryFeatures->getItems();
  1213. $primaryKeyField = $acl->getPrimaryKeyField();
  1214. $items = []; foreach ($listItems as $item) $items[ $item[$primaryKeyField] ] = $item;
  1215. } catch (Exception $e) {
  1216. DBG::log($e);
  1217. throw $e;
  1218. }
  1219. $format = V::get('format', 'html', $_GET);
  1220. switch ($format) {
  1221. case 'html': {
  1222. UI::gora();
  1223. echo UI::h('table', ['class'=>'table table-bordered table-hover'], [
  1224. UI::h('thead', [], [
  1225. UI::h('tr', [], array_map(function ($label) {
  1226. return UI::h('th', [], $label);
  1227. }, $labels))
  1228. ]),
  1229. UI::h('tbody', [], array_map(function ($item) use($labels) {
  1230. return UI::h('tr', [], array_map(function ($fieldName) use ($item) {
  1231. return UI::h('td', [], V::get($fieldName, '', $item));
  1232. }, array_keys($labels)));
  1233. }, $items)),
  1234. ]);
  1235. UI::dol();
  1236. exit;
  1237. }
  1238. case 'csv_cp1250':
  1239. case 'csv': {
  1240. $csvFileName = "Tabela-" . $acl->getName() . "-" . date("Y-m-d_H_s");
  1241. header('Content-Type: text/csv; charset=utf-8');
  1242. header("Content-Disposition: attachment; filename={$csvFileName}.csv");
  1243. $csvSeparator = ';';
  1244. $csvHeader = implode($csvSeparator, array_map(function ($label) use ($item) {
  1245. return '"' . addslashes($label) . '"';
  1246. }, array_values($labels)));
  1247. $csvRows = implode("\r\n", array_map(function ($item) use ($labels, $csvSeparator) {
  1248. return implode($csvSeparator, array_map(function ($fieldName) use ($item) {
  1249. return '"' . addslashes(V::get($fieldName, '', $item)) . '"';
  1250. }, array_keys($labels)));
  1251. }, $items));
  1252. switch ($format) {
  1253. case 'csv': echo $csvHeader . "\n" . $csvRows; exit;
  1254. case 'csv_cp1250': echo iconv('utf-8', 'Windows-1250//IGNORE', $csvHeader) . "\r\n" . iconv('utf-8', 'Windows-1250//IGNORE', $csvRows); exit;
  1255. die("Nieobsługiwane kodowanie danych csv.");
  1256. }
  1257. exit;
  1258. }
  1259. }
  1260. die("Nieobsługiwany format danych.");
  1261. }
  1262. public function loadDataAjaxAction() {
  1263. $namespace = V::get('namespace', '', $_REQUEST, 'word');
  1264. if (!$namespace) throw new HttpException("Bad Request - missing namespace", 400);
  1265. $acl = Core_AclHelper::getAclByNamespace($namespace);
  1266. $backRefFilter = [
  1267. 'namespace' => V::get('backRefNS', '', $_REQUEST),
  1268. 'primaryKey' => V::get('backRefPK', '', $_REQUEST),
  1269. 'fieldName' => V::get('backRefField', '', $_REQUEST),
  1270. ];
  1271. $childRefFilter = [
  1272. 'namespace' => V::get('childRefNS', '', $_GET),
  1273. 'primaryKey' => V::get('childRefPK', '', $_GET),
  1274. ];
  1275. $tbl = $this->getTableAjaxWidget($acl, $backRefFilter, $childRefFilter);
  1276. Response::sendTryCatchJson(array($tbl, 'ajaxData'), $args = $_GET);
  1277. }
  1278. public function uploadFilesAjaxAction() {
  1279. Response::sendTryCatchJson([$this, 'uploadFilesAjax'], $args = $_POST);
  1280. }
  1281. public function uploadFilesAjax($args) {
  1282. DBG::log($_FILES, 'array', "\$_FILES");
  1283. DBG::log($args, 'array', "\$args");
  1284. $namespace = V::get('namespace', '', $args, 'word');
  1285. if (!$namespace) throw new Exception("Missing namespace");
  1286. $primaryKey = V::get('primaryKey', '', $args, 'int');
  1287. if ($primaryKey <= 0) throw new Exception("Missing primaryKey");
  1288. if (empty($_FILES)) throw new Exception("Missing files");
  1289. $acl = Core_AclHelper::getAclByNamespace($namespace, $forceTblAclInit = ('1' == V::get('_force', '', $_GET)));
  1290. Lib::loadClass('FileUploader');
  1291. Lib::loadClass('FoldersConfig');
  1292. // $dbID = $acl->getDB();
  1293. // $db = DB::getDB($dbID);
  1294. // if (!$db) throw new HttpException("No DB ({$dbID})", 406);
  1295. $record = $acl->buildQuery([])->getItem($primaryKey);
  1296. DBG::log($record, 'array', "\$record");
  1297. if (!$record) throw new HttpException("No item ID({$primaryKey})", 404);
  1298. if (!$acl->canReadRecord($record)) throw new Exception("Brak uprawnień do odczytu");
  1299. if (!$acl->canWriteRecord($record)) throw new Exception("Brak uprawnień do zapisu");
  1300. $rootTableName = $acl->getRootTableName();
  1301. $confTblName = "{$rootTableName}_COLUMN";
  1302. $folderConfAll = FoldersConfig::getRawData();
  1303. if (!FoldersConfig::hasConfig($confTblName)) throw new HttpException("Brak danych konfiguracyjnych ({$rootTableName})", 404);
  1304. $folderConf = FoldersConfig::getAll($confTblName);
  1305. DBG::log($folderConf, 'array', "\$folderConf");
  1306. $uploader = new FileUploader($confTblName, (object)$record);
  1307. if (!$uploader->setConfig($folderConf)) throw new HttpException("Błąd danych konfiguracyjnych ({$rootTableName})", 404);
  1308. $uploader->findFolder();
  1309. DBG::log($uploader, 'array', "\$uploader");
  1310. // $errorMsg = '';
  1311. // if (!empty($args['SCANS_COLUMN_ADD'])) {
  1312. // $uploaded = $uploader->tryMoveFromScanAjax($errorMsg);
  1313. // }
  1314. // else {
  1315. // $uploaded = $uploader->tryUploadAjax($errorMsg);
  1316. // }
  1317. $destPath = $uploader->getDestLocalPath($show_if_not_found = true);
  1318. DBG::log($destPath, 'array', "\$destPath");
  1319. if (!file_exists($destPath)) {
  1320. if (!$uploader->tryCreateDestFolder($destPath)) throw new Exception("Wystąpił błąd podczas tworzenie katalogu dla rekordu '{$primaryKey}'");
  1321. }
  1322. $generateSafeFileName = function($destPath, $fileName) {
  1323. if (!file_exists("{$destPath}/{$fileName}")) return $fileName;
  1324. $infoPath = pathinfo($fileName);
  1325. // pathinfo('/path/t1/t2/fileName.ext') = [
  1326. // [dirname] => /path/t1/t2
  1327. // [basename] => fileName.ext
  1328. // [extension] => ext
  1329. // [filename] => fileName
  1330. // ]
  1331. return $infoPath['filename'] . "--" . date("Y-m-d_H-i-s") . "." . $infoPath['extension'];
  1332. };
  1333. $moveActions = array_map(function ($file) use ($destPath, $generateSafeFileName) {
  1334. $safeName = $generateSafeFileName($destPath, $file['name']);
  1335. return [
  1336. $file['tmp_name'],
  1337. "{$destPath}/{$safeName}",
  1338. $safeName,
  1339. ];
  1340. }, $_FILES);
  1341. DBG::log($moveActions, 'array', "\$moveActions"); // [ [ srcPath, descPath ] ]
  1342. $errorMsgs = [];
  1343. $pkField = $acl->getSqlPrimaryKeyField();
  1344. foreach ($moveActions as $fileMoveAction) {
  1345. if (!move_uploaded_file($fileMoveAction[0], $fileMoveAction[1])) {
  1346. $errorMsgs[] = "Nie udało się wgrać pliku '{$fileMoveAction[2]}'";
  1347. } else {
  1348. try {
  1349. $affected = DB::getPDO($acl->getDB())->update($rootTableName, $pkField, $primaryKey, [
  1350. 'M_DIST_FILES' => "Wrano plik '{$fileMoveAction[2]}'",
  1351. 'A_RECORD_UPDATE_AUTHOR' => User::getLogin(),
  1352. 'A_RECORD_UPDATE_DATE' => 'NOW()',
  1353. ]);
  1354. if ($affected) {
  1355. DB::getPDO($acl->getDB())->insert("{$rootTableName}_HIST", [
  1356. 'ID_USERS2' => $primaryKey,
  1357. 'M_DIST_FILES' => "Wrano plik '{$fileMoveAction[2]}'",
  1358. 'A_RECORD_UPDATE_AUTHOR' => User::getLogin(),
  1359. 'A_RECORD_UPDATE_DATE' => 'NOW()',
  1360. ]);
  1361. }
  1362. } catch (Exception $e) {
  1363. DBG::log($e);
  1364. $errorMsgs[] = $e->getMessage();
  1365. }
  1366. }
  1367. }
  1368. if (!empty($errorMsgs)) {
  1369. return [
  1370. 'type' => "error",
  1371. 'msg' => "Wystąpiły błędy podczas wgrywania plików dla '{$primaryKey}'",
  1372. 'errors' => $errorMsgs,
  1373. ];
  1374. }
  1375. return [
  1376. 'type' => "success",
  1377. 'msg' => "Wgrano nowe pliki dla '{$primaryKey}'",
  1378. ];
  1379. }
  1380. public function removeFileAjaxAction() {
  1381. Response::sendTryCatchJson([$this, 'removeFileAjax'], $args = $_REQUEST);
  1382. }
  1383. public function removeFileAjax($args) { // ajaxFileRemove
  1384. $namespace = V::get('namespace', '', $args, 'word');
  1385. if (!$namespace) throw new Exception("Missing namespace");
  1386. $id = V::get('ID', 0, $args, 'int');
  1387. if ($id <= 0) throw new Exception("Missing ID");
  1388. $filename = V::get('filename', '', $args);
  1389. if (empty($filename)) throw new Exception("Nie wybrano pliku do usunięcia");
  1390. $acl = Core_AclHelper::getAclByNamespace($namespace, $forceTblAclInit = ('1' == V::get('_force', '', $_GET)));
  1391. $dbID = $acl->getDB();
  1392. $db = DB::getPDO($dbID);
  1393. if (!$db) throw new HttpException("No DB ({$dbID})", 406);
  1394. $record = $acl->buildQuery([])->getItem($id);
  1395. if (!$record) throw new HttpException("No item ID({$id})", 404);
  1396. if (!$acl->canReadRecord($record)) throw new Exception("Brak uprawnień do odczytu");
  1397. if (!$acl->canWriteRecord($record)) throw new Exception("Brak uprawnień do zapisu");
  1398. Lib::loadClass('FileUploader');
  1399. Lib::loadClass('FoldersConfig');
  1400. $tblName = $acl->getName();
  1401. $confTblName = "{$tblName}_COLUMN";
  1402. $folderConfAll = FoldersConfig::getRawData();
  1403. if (!FoldersConfig::hasConfig($confTblName)) throw new HttpException("Brak danych konfiguracyjnych ({$tblName})", 404);
  1404. $folderConf = FoldersConfig::getAll($confTblName);
  1405. $uploader = new FileUploader($confTblName, (object)$record);
  1406. if (!$uploader->setConfig($folderConf)) throw new HttpException("Błąd danych konfiguracyjnych ({$tblName})", 404);
  1407. $uploader->findFolder();
  1408. $errorMsg = '';
  1409. $removed = $uploader->tryRemoveFromAjax($filename, $errorMsg);
  1410. if (!$removed) throw new Exception($errorMsg);
  1411. // $affected = DB::getPDO($acl->getDB())->update();
  1412. $rootTableName = $acl->getRootTableName();
  1413. $pkField = $acl->getSqlPrimaryKeyField();
  1414. $primaryKey = $id;
  1415. try {
  1416. $affected = DB::getPDO($acl->getDB())->update($rootTableName, $pkField, $primaryKey, [
  1417. 'M_DIST_FILES' => "Usunięto plik '{$filename}'",
  1418. 'A_RECORD_UPDATE_AUTHOR' => User::getLogin(),
  1419. 'A_RECORD_UPDATE_DATE' => 'NOW()',
  1420. ]);
  1421. if ($affected) {
  1422. DB::getPDO($acl->getDB())->insert("{$rootTableName}_HIST", [
  1423. 'ID_USERS2' => $primaryKey,
  1424. 'M_DIST_FILES' => "Usunięto plik '{$filename}'",
  1425. 'A_RECORD_UPDATE_AUTHOR' => User::getLogin(),
  1426. 'A_RECORD_UPDATE_DATE' => 'NOW()',
  1427. ]);
  1428. }
  1429. } catch (Exception $e) {
  1430. DBG::log($e);
  1431. }
  1432. return [
  1433. 'type' => 'success',
  1434. 'msg' => 'Plik został usunięty',
  1435. ];
  1436. }
  1437. public function procesInitFiltrAjaxAction() {
  1438. Response::sendTryCatchJson([$this, 'procesInitFiltrAjax'], $args = $_GET);
  1439. }
  1440. public function procesInitFiltrAjax($args) { // ajaxFileRemove
  1441. $namespace = V::get('namespace', '', $args, 'word');
  1442. if (!$namespace) throw new Exception("Missing namespace");
  1443. $acl = Core_AclHelper::getAclByNamespace($namespace, $forceTblAclInit = ('1' == V::get('_force', '', $_GET)));
  1444. $pInitList = User::getAcl()->getTableProcesInitList($acl->getID());
  1445. DBG::log($pInitList, 'array', "\$pInitList");
  1446. if (!empty($pInitList)) {
  1447. $procesIds = array_keys($pInitList);
  1448. $mapTree = ACL::getProcesInitMapTreeOnlyIds($procesIds);
  1449. DBG::log($mapTree, 'array', "\$mapTree");
  1450. DBG::log($pInitList, 'array', "\$pInitList");
  1451. $pInitListSelected = User::getAcl()->getPermsFiltrProcesId();
  1452. return [
  1453. 'type' => 'success',
  1454. 'msg' => 'ok',
  1455. 'pInitData' => [
  1456. 'pInitList' => $pInitList,
  1457. 'mapTree' => $mapTree,
  1458. 'pInitListSelected' => $pInitListSelected,
  1459. ],
  1460. ];
  1461. }
  1462. return [
  1463. 'type' => 'success'
  1464. ];
  1465. }
  1466. public function tableToolsAjaxAction() {
  1467. Response::sendTryCatchJson([$this, 'tableToolsAjax'], $args = $_GET);
  1468. }
  1469. public function tableToolsAjax($args) { // ajaxFileRemove
  1470. $namespace = V::get('namespace', '', $args, 'word');
  1471. if (!$namespace) throw new Exception("Missing namespace");
  1472. $acl = Core_AclHelper::getAclByNamespace($namespace, $forceTblAclInit = ('1' == V::get('_force', '', $_GET)));
  1473. $listUrlFunctions = Route_UrlAction::getTableFunctions($acl->getID(), $idRecord = 0, $acl->getName(), User::getLogin());
  1474. DBG::log($listUrlFunctions, 'array', "\$listUrlFunctions");
  1475. $listUrlFunctions = array_map(function ($urlFunction) use ($namespace) {
  1476. if ('index.php?' === substr($urlFunction['baseLink'], 0, strlen('index.php?'))) $urlFunction['baseLink'] .= "&_fromNamespace={$namespace}";
  1477. return $urlFunction;
  1478. }, $listUrlFunctions);
  1479. return [
  1480. 'type' => "success",
  1481. 'msg' => 'ok',
  1482. 'body' => [
  1483. 'tableTools' => array_values(array_map(function ($urlFunction) {
  1484. return [
  1485. 'url' => $urlFunction['baseLink'],
  1486. 'label' => $urlFunction['label'],
  1487. // TODO: $urlFunction['link_target'] // "_blank"
  1488. // ? $urlFunction['name']
  1489. ];
  1490. }, array_filter($listUrlFunctions, function ($urlFunction) {
  1491. return empty($urlFunction['cell_id_params']);
  1492. }))),
  1493. ],
  1494. ];
  1495. }
  1496. function executeRowFunctionAction() { UI::layout([ $this, 'executeRowFunction' ]); }
  1497. function executeRowFunction() {
  1498. $namespace = V::get('namespace', '', $_GET);
  1499. $name = V::get('name', '', $_GET);
  1500. $pk = V::get('pk', '', $_GET);
  1501. if (!$namespace) throw new Exception("Missing namespace");
  1502. if (!$name) throw new Exception("Missing name");
  1503. if (!$pk) throw new Exception("Missing pk");
  1504. $acl = ACL::getAclByNamespace($namespace);
  1505. if (!method_exists($acl, 'executeGuiRowFunction')) throw new Exception("Function executeGuiRowFunction not defined for '{$namespace}'");
  1506. $acl->executeGuiRowFunction($name, $pk);
  1507. }
  1508. }