ViewTableAjax.php 66 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605
  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. $mergedNears = [];
  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. }
  647. if ($lastNear) {
  648. if (Geometry::samePoint($lastNear->b, $near->a)) $lastNear->b = $near->b;
  649. else $mergedNears[] = $lastNear;
  650. }
  651. $lastNear = $near;
  652. }
  653. if ($lastNear) $mergedNears[] = $lastNear;
  654. foreach ($mergedNears as $near) {
  655. $a = Geometry::closedPointOnLine($near->a, $line);
  656. $b = Geometry::closedPointOnLine($near->b, $line);
  657. $array[] = ['i' => ($i - 1) . '.k' . $ki . 'a', 'x' => $a->x, 'y' => $a->y, 'desc' => 'Kolizja (II) start'];
  658. $array[] = ['i' => ($i - 1) . '.k' . $ki++ . 'b', 'x' => $b->x, 'y' => $b->y, 'desc' => 'Kolizja (II) stop'];
  659. }
  660. if (($distance = $line->length()) > $minDistance) {
  661. $parts = ceil($distance / $minDistance);
  662. $deltaX = ($line->b->x - $line->a->x) / $parts;
  663. $deltaY = ($line->b->y - $line->a->y) / $parts;
  664. for ($j = 1; $j < $parts; $j++) {
  665. $array[] = ['i' => ($i - 1) . "." . $j, 'x' => ($line->a->x + $j * $deltaX), 'y' => ($line->a->y + $j * $deltaY), 'desc' => 'Pośredni'];
  666. }
  667. }
  668. $array[] = ['i' => $i, 'x' => $line->b->x, 'y' => $line->b->y, 'desc' => 'Punkt'];
  669. $i++;
  670. }
  671. $csv = implode("\n", array_map(function ($item) {
  672. try {
  673. $z = EpsgConversion::GetZByPuwg2000($item['x'], $item['y']);
  674. } catch (Exception $e) {
  675. $z = 0;
  676. }
  677. return $item['i'] . "," . round($item['y'], 3) . "," . round($item['x'], 3) . "," . round($z, 3) . "," . $item['desc'];
  678. }, $array));
  679. Response::sendCsv($csv, "{$table}.{$id}");
  680. }
  681. public function moreFunctionsCellAjaxAction() {
  682. Response::sendTryCatchJson(array($this, 'moreFunctionsCell'), $args = $_GET);
  683. }
  684. public function moreFunctionsCell($args) {// ajax task 'MORE_FUNCTIONS_CELL'
  685. $id = V::get('ID', 0, $args, 'int');
  686. if ($id <= 0) throw new HttpException("404", 404);
  687. $namespace = V::get('namespace', '', $args, 'word');
  688. if (!$namespace) throw new HttpException("Bad Request - missing namespace", 400);
  689. $acl = Core_AclHelper::getAclByNamespace($namespace, $forceTblAclInit = ('1' == V::get('_force', '', $args)));
  690. $response = new stdClass();
  691. $response->type = 'success';
  692. $response->msg = 'Funkcje';
  693. $response->rowFunctions = Core_AclHelper::getMoreFunctionsCell($acl, array('primary_key' => $id));
  694. return $response;
  695. }
  696. public function createFormAction() {// TODO: move to createFormJsonAction
  697. try {
  698. $args = $_REQUEST;
  699. $namespace = V::get('namespace', '', $args, 'word');
  700. if (!$namespace) throw new HttpException("Bad Request - missing namespace", 400);
  701. $acl = Core_AclHelper::getAclByNamespace($namespace);
  702. $tbl = $this->getTableAjaxWidget($acl);
  703. $tbl->sendAjaxCreate();
  704. } catch (Exception $e) {
  705. DBG::log($e);
  706. throw $e;
  707. }
  708. }
  709. public function createFormJsonAction() {
  710. Response::sendTryCatchJson(array($this, 'createFormJson'), $args = $_REQUEST);
  711. }
  712. public function createFormJson($args) { // namespace, _hash, _primaryKey
  713. $namespace = V::get('namespace', '', $args, 'word');
  714. if (!$namespace) throw new HttpException("Bad Request - missing namespace", 400);
  715. $acl = Core_AclHelper::getAclByNamespace($namespace);
  716. $tbl = $this->getTableAjaxWidget($acl);
  717. if (!Core_AclHelper::hasCreatePerms($acl)) {
  718. return [
  719. 'type' => "success",
  720. 'msg' => "Dodaj nowy rekord",
  721. 'body' => [
  722. 'reactNode' => [ 'div', [ 'class' => "alert alert-danger" ], "Brak uprawnień do utworzenia nowego rekordu." ]
  723. ],
  724. ];
  725. // throw new Exception("Brak uprawnień do utworzenia nowego rekordu.");
  726. }
  727. $fieldsList = array();
  728. foreach ($acl->getFieldListByIdZasob() as $kID => $fieldName) {
  729. if ($fieldName == 'ID') continue;
  730. $field['name'] = $fieldName;
  731. $field['opis'] = $acl->getFieldOpis($fieldName);
  732. $field['label'] = $acl->getFieldLabel($fieldName);
  733. if (empty($field['label'])) $field['label'] = str_replace('_', ' ', $fieldName);
  734. $fieldsList[$kID] = $field;
  735. }
  736. $cols = array();
  737. $forceFilterInit = array();
  738. $defaultAclGroup = User::getDefaultAclGroup();
  739. if ($defaultAclGroup) {
  740. $forceFilterInit['A_ADM_COMPANY'] = $defaultAclGroup;
  741. $forceFilterInit['A_CLASSIFIED'] = $defaultAclGroup;
  742. }
  743. foreach ($_GET as $k => $v) { // TODO: read from $args ?
  744. if (strlen($k) > 4 && substr($k, 0, 3) == 'ff_' && !empty($v)) {// force filter prefix
  745. $fldName = substr($k, 3);
  746. $forceFilterInit[$fldName] = $v;
  747. }
  748. }
  749. DBG::log($forceFilterInit, 'array', "\$forceFilterInit");
  750. foreach ($fieldsList as $kID => $field) {
  751. $defaultValue = '';
  752. if (!empty($forceFilterInit[$field['name']])) {
  753. $defaultValue = $forceFilterInit[$field['name']];
  754. }
  755. $cols[$kID] = V::get("f{$kID}", $defaultValue, $_POST);
  756. }
  757. DBG::log($cols, 'array', "\$cols - field values");
  758. $tsValues = array();
  759. $featureFunctions = [
  760. // 'edit' => [ 'href' => '#EDIT/{0}', 'ico' => 'glyphicon glyphicon-pencil', 'title' => "Edytuj rekord"],
  761. 'hist' => [ 'href' => '#HIST/{0}', 'ico' => 'glyphicon glyphicon-book', 'title' => "Historia" ],
  762. 'files' => [ 'href' => '#FILES/{0}', 'ico' => 'glyphicon glyphicon-folder-open', 'title' => "Pliki" ],
  763. // 'cp' => [ 'href' => '#', 'ico' => 'glyphicon glyphicon-plus-sign', 'title' => "Kopiuj rekord", 'onclick' => 'return tableAjaxCopy({0});' ],
  764. 'msgs' => [ 'href' => "index.php?_route=TableMsgs&_task=tableRow&idTable=".$acl->getID()."&idRow={0}", 'ico' => 'glyphicon glyphicon-envelope', 'title' => "Wiadomości" ],
  765. ];
  766. $jsFields = [];
  767. $tabindex = 0;
  768. foreach ($fieldsList as $kID => $vCol) {
  769. $fieldName = $vCol['name'];
  770. $fieldLabel = str_replace('<br>', ' ', $vCol['label']);
  771. DBG::log(['$fieldName'=>$fieldName, 'canCreate'=>$acl->canCreateField($fieldName)], 'array', "form field");
  772. if ($acl->canCreateField($fieldName)) {
  773. DBG::log("editFormJson::field({$fieldName})");
  774. $fieldParams = [ 'appendBack' => true, 'tabindex' => (++$tabindex), 'maxGrid' => 8 ];
  775. if (!empty($tsValues[$kID])) $fieldParams['typespecialValue'] = $tsValues[$kID];
  776. $jsFields[] = [ 'div', [ 'class' => "form-group" ], [
  777. [ 'label', [ 'class' => "control-label", 'for' => "f{$kID}" ], [
  778. [ 'span', [ 'style' => ['padding-right'=>'4px'] ], $fieldLabel ],
  779. [ '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}" ] ],
  780. ] ],
  781. [ 'div', [ 'class' => "" ], [
  782. UI::hGetFormItem($acl, $fieldName, 'C', $kID, "f{$kID}", $cols[$kID], $fieldParams),
  783. ] ]
  784. ] ];
  785. // } else {
  786. // $jsFields[] = [ 'div', [ 'class' => "form-group" ], [
  787. // "TODO: SKIP field ({$fieldName}) - ! canWriteObjectField && ! canReadObjectField"
  788. // ]];
  789. }
  790. }
  791. $jsFields[] = [ 'div', [ 'class' => "form-group" ], [
  792. [ 'div', [ 'class' => "" ], [
  793. ['button', [ 'type' => "submit", 'class' => "btn btn-primary", 'tabindex' => ++$tabindex ], "Zapisz" ]
  794. ] ]
  795. ] ];
  796. $tblLabel = $acl->getNamespace();
  797. if ('default_db' == $acl->getSourceName()) {
  798. $tblLabel = array();
  799. $zasobObj = ProcesHelper::getZasobTableInfo($acl->getID());
  800. if (!$zasobObj) throw new Exception("Zasob TABELA ID=" . $acl->getID() . " nie istnieje");
  801. if (!empty($zasobObj->DESC_PL)) $tblLabel []= $zasobObj->DESC_PL;
  802. if (!empty($zasobObj->OPIS)) $tblLabel []= $zasobObj->OPIS;
  803. $tblLabel = implode(" - ", $tblLabel);
  804. }
  805. $syncUrl = Request::getPathUri() . 'index.php?_route=ViewTableAjax&namespace=' . $acl->getNamespace();
  806. $jsGui = [
  807. 'reactNode' => [ 'div', [ 'class' => "container AjaxFrmHorizontalEdit", 'style' => [ "max-width" => "940px" ] ], [
  808. [ 'h4', [ 'style' => [ "padding-bottom" => "3px", "border-bottom" => "1px solid #ddd" ] ], [
  809. "Dodaj nowy rekord",
  810. ] ],
  811. [ 'P5UI__FeatureCreateForm', [
  812. 'class' => "", 'action' => "", 'method' => "post",
  813. 'id' => "CREATE_FRM_{$this->_htmlID}", // TODO: rm - use React nodes // TODO: $this->_htmlID not exists!
  814. 'ajaxSaveUrl' => "{$syncUrl}&_task=createSaveAjax", // TODO:? &_hash={$this->_htmlID}
  815. 'ajaxSaveLegacyUrl' => "{$syncUrl}&_task=createSaveLegacy", // TODO: Legacy RM
  816. 'namespace' => $acl->getNamespace(),
  817. 'tableLabelHtml' => $tblLabel,
  818. '_htmlID' => $acl->getName(),
  819. ], [
  820. [ 'fieldset', [ 'style' => [ "padding-bottom" => "100px" ] ], $jsFields ] // fieldset
  821. ] ] // form
  822. ] ] // .container
  823. ];
  824. return [
  825. 'type' => "success",
  826. 'msg' => "Dodaj nowy rekord",
  827. 'body' => $jsGui, // TODO: action for GUI: array to render by function h, js to trigger
  828. ];
  829. }
  830. public function createSaveAjaxAction() {
  831. Response::sendTryCatchJson(array($this, 'createSaveAjax'), $args = 'JSON_FROM_REQUEST_BODY');
  832. }
  833. public function createSaveAjax($args) {
  834. throw new Exception("TODO: ...");
  835. }
  836. public function createSaveLegacyAction() { // TODO: Legacy RM
  837. $args = [
  838. 'namespace' => V::get('namespace', '', $_GET),
  839. 'body' => Request::getRequestJson(),
  840. ];
  841. DBG::log($args, 'array', 'createSaveLegacyAction');
  842. Response::sendTryCatchJson(array($this, 'createSaveLegacy'), $args);
  843. }
  844. public function createSaveLegacy($args) { // TODO: Legacy RM
  845. $namespace = V::get('namespace', '', $args, 'word');
  846. if (!$namespace) throw new HttpException("Bad Request - missing namespace", 400);
  847. $body = V::get('body', null, $args);
  848. if (!$body) throw new HttpException("Bad Request - missing body", 400);
  849. $acl = Core_AclHelper::getAclByNamespace($namespace);
  850. $tbl = $this->getTableAjaxWidget($acl);
  851. DBG::log($args, 'array', "ajaxCreateSave");
  852. $createdId = null;
  853. try {
  854. $item = $acl->convertObjectFromUserInput($body, $type = 'array_by_id', $prefix = 'f');
  855. $createdId = $acl->addItem($item);
  856. if ($createdId) {
  857. return [
  858. 'type' => 'success',
  859. 'msg' => "Utworzono pomyślnie rekord nr {$createdId}",
  860. 'id' => $createdId,
  861. 'record' => $acl->buildQuery([])->getItem($createdId),
  862. ];
  863. }
  864. else {
  865. return [
  866. 'type' => 'error',
  867. 'msg' => "Nie udało się utworzyć nowego rekordu!",
  868. ];
  869. }
  870. }
  871. catch (Exception $e) {
  872. return [
  873. 'type' => 'error',
  874. 'msg' => $e->getMessage(),
  875. ];
  876. }
  877. }
  878. public function editFormAction() { // TODO: not used - moved to editFormJsonAction
  879. try {
  880. $args = $_REQUEST;
  881. $id = V::get('_primaryKey', 0, $args, 'int');
  882. if ($id <= 0) throw new HttpException("Bad Request - missing primaryKey", 400);
  883. $namespace = V::get('namespace', '', $args, 'word');
  884. if (!$namespace) throw new HttpException("Bad Request - missing namespace", 400);
  885. $acl = Core_AclHelper::getAclByNamespace($namespace);
  886. $tbl = $this->getTableAjaxWidget($acl);
  887. $tbl->sendAjaxEdit($id, $args);
  888. } catch (Exception $e) {
  889. DBG::log($e);
  890. throw $e;
  891. }
  892. }
  893. public function editFormJsonAction() {
  894. Response::sendTryCatchJson(array($this, 'editFormJson'), $args = $_REQUEST);
  895. }
  896. public function editFormJson($args) { // namespace, _hash, _primaryKey
  897. $id = V::get('_primaryKey', 0, $args, 'int');
  898. if ($id <= 0) throw new HttpException("Bad Request - missing primaryKey", 400);
  899. $namespace = V::get('namespace', '', $args, 'word');
  900. if (!$namespace) throw new HttpException("Bad Request - missing namespace", 400);
  901. $acl = Core_AclHelper::getAclByNamespace($namespace);
  902. $tbl = $this->getTableAjaxWidget($acl);
  903. $record = $acl->buildQuery([])->getItem($id);
  904. if (!$acl->canWriteRecord($record) && !$acl->hasPermSuperWrite()) {
  905. return [
  906. 'type' => "success",
  907. 'msg' => "Edycja rekordu nr {$id}",
  908. 'body' => [
  909. 'reactNode' => [ 'div', [ 'class' => "alert alert-danger" ], "Brak dostępu do rekordu" ]
  910. ],
  911. ];
  912. // throw new Exception("Brak dostępu do rekordu");
  913. }
  914. $fieldsList = array();
  915. foreach ($acl->getFieldListByIdZasob() as $kID => $fieldName) {
  916. if ($fieldName == 'ID') continue;
  917. $field['name'] = $fieldName;
  918. $field['opis'] = $acl->getFieldOpis($fieldName);
  919. $field['label'] = $acl->getFieldLabel($fieldName);
  920. if (empty($field['label'])) $field['label'] = str_replace('_', ' ', $fieldName);
  921. $fieldsList[$kID] = $field;
  922. }
  923. $cols = array();
  924. foreach ($fieldsList as $kID => $field) {
  925. $cols[$kID] = '';
  926. if ($acl->canReadObjectField($field['name'], $record)) {
  927. $cols[$kID] = V::get($field['name'], '', $record);
  928. } else {
  929. $cols[$kID] = '*****';
  930. }
  931. $cols[$kID] = V::get("f{$kID}", $cols[$kID], $_POST);
  932. }
  933. $tsValues = array();
  934. if (!empty($fieldsList)) {
  935. foreach ($fieldsList as $vColID => $vCol) {
  936. $typeSpecial = Typespecial::getInstance($vColID, $vCol['name']);
  937. if ($typeSpecial) {
  938. $colValue = V::get($vCol['name'], '', $record);
  939. $specialValues = $typeSpecial->getEditSelectedValuesByIds($acl->getID(), $record['ID'], $vCol['name'], $colValue);
  940. if (!empty($specialValues)) {
  941. $tsValues[$vColID] = implode('<br>', $specialValues);
  942. }
  943. }
  944. }
  945. }
  946. DBG::log($tsValues, 'array', "editFormJson::tsValues");
  947. foreach ($tsValues as $idx => $value) {
  948. if ('<' === substr($value, 0, 1)) {
  949. // $tsValues[$idx] = UI::convertHtmlToArray($value); // TODO: ...
  950. $tsValues[$idx] = [ 'P5UI__RawHtml', [ 'rawHtml' => $tsValues[$idx] ] ];
  951. }
  952. }
  953. DBG::log($tsValues, 'array', "editFormJson::tsValues parsed");
  954. $featureFunctions = [
  955. // 'edit' => [ 'href' => '#EDIT/{0}', 'ico' => 'glyphicon glyphicon-pencil', 'title' => "Edytuj rekord"],
  956. 'hist' => [ 'href' => '#HIST/{0}', 'ico' => 'glyphicon glyphicon-book', 'title' => "Historia" ],
  957. 'files' => [ 'href' => '#FILES/{0}', 'ico' => 'glyphicon glyphicon-folder-open', 'title' => "Pliki" ],
  958. // 'cp' => [ 'href' => '#', 'ico' => 'glyphicon glyphicon-plus-sign', 'title' => "Kopiuj rekord", 'onclick' => 'return tableAjaxCopy({0});' ],
  959. 'msgs' => [ 'href' => "index.php?_route=TableMsgs&_task=tableRow&idTable=".$acl->getID()."&idRow={0}", 'ico' => 'glyphicon glyphicon-envelope', 'title' => "Wiadomości" ],
  960. ];
  961. $rowFunctionsOut = [ 'P5UI__FeatureRowFunctions', [
  962. 'id' => $record[ $acl->getPrimaryKeyField() ],
  963. 'functions' => $featureFunctions,
  964. 'showLabels' => true,
  965. 'viewMoreDropdown' => [
  966. 'primaryKey' => $record['ID'],
  967. 'uri' => $this->getLink('moreFunctionsCellAjax', [ 'namespace' => $acl->getNamespace(), 'ID' => $record['ID'] ]),
  968. ],
  969. ] ]; // TODO: $this->_showRowFunctions($record['ID'], array('edit', 'cp'), true);
  970. $jsFields = [];
  971. $tabindex = 0;
  972. foreach ($fieldsList as $kID => $vCol) {
  973. $fieldName = $vCol['name'];
  974. $fieldLabel = str_replace('<br>', ' ', $vCol['label']);
  975. DBG::log(['$fieldName'=>$fieldName, '$record'=>$record, 'canWrite'=>$acl->canWriteObjectField($fieldName, $record), 'canRead'=>$acl->canReadObjectField($fieldName, $record)], 'array', "form field");
  976. if ($acl->canWriteObjectField($fieldName, $record)) {
  977. DBG::log("editFormJson::field({$fieldName})");
  978. $fieldParams = [ 'appendBack' => true, 'tabindex' => (++$tabindex), 'maxGrid' => 8 ];
  979. if (!empty($tsValues[$kID])) $fieldParams['typespecialValue'] = $tsValues[$kID];
  980. $jsFields[] = [ 'div', [ 'class' => "form-group" ], [
  981. [ 'label', [ 'class' => "control-label", 'for' => "f{$kID}" ], [
  982. [ 'span', [ 'style' => ['padding-right'=>'4px'] ], $fieldLabel ],
  983. [ '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}" ] ],
  984. ] ],
  985. [ 'div', [ 'class' => "" ], [
  986. UI::hGetFormItem($acl, $fieldName, 'W', $kID, "f{$kID}", $cols[$kID], $fieldParams, $record),
  987. ] ]
  988. ] ];
  989. } else if ($acl->canReadObjectField($fieldName, $record)) {
  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. ['p', [ 'style' => [ 'margin-top' => '5px' ] ], [
  997. (!empty($tsValues[$kID]))
  998. ? $tsValues[$kID]
  999. : V::get($fieldName, '', $record)
  1000. ] ],
  1001. ] ]
  1002. ] ];
  1003. // } else {
  1004. // $jsFields[] = [ 'div', [ 'class' => "form-group" ], [
  1005. // "TODO: SKIP field ({$fieldName}) - ! canWriteObjectField && ! canReadObjectField"
  1006. // ]];
  1007. }
  1008. }
  1009. $jsFields[] = [ 'div', [ 'class' => "form-group" ], [
  1010. [ 'div', [ 'class' => "" ], [
  1011. ['button', [ 'type' => "submit", 'class' => "btn btn-primary", 'tabindex' => ++$tabindex ], "Zapisz" ]
  1012. ] ]
  1013. ] ];
  1014. $tblLabel = $acl->getNamespace();
  1015. if ('default_db' == $acl->getSourceName()) {
  1016. $tblLabel = array();
  1017. $zasobObj = ProcesHelper::getZasobTableInfo($acl->getID());
  1018. if (!$zasobObj) throw new Exception("Zasob TABELA ID=" . $acl->getID() . " nie istnieje");
  1019. if (!empty($zasobObj->DESC_PL)) $tblLabel []= $zasobObj->DESC_PL;
  1020. if (!empty($zasobObj->OPIS)) $tblLabel []= $zasobObj->OPIS;
  1021. $tblLabel = implode(" - ", $tblLabel);
  1022. }
  1023. $syncUrl = Request::getPathUri() . 'index.php?_route=ViewTableAjax&namespace=' . $acl->getNamespace();
  1024. $jsGui = [
  1025. 'reactNode' => [ 'div', [ 'class' => "container AjaxFrmHorizontalEdit", 'style' => [ "max-width" => "940px" ] ], [
  1026. [ 'h4', [ 'style' => [ "padding-bottom" => "3px", "border-bottom" => "1px solid #ddd" ] ], [
  1027. "Edycja rekordu Nr {$record['ID']}",
  1028. [ 'small', [ 'class' => "pull-right valign-btns-bottom" ], [ $rowFunctionsOut ] ],
  1029. ] ],
  1030. [ 'P5UI__FeatureEditForm', [
  1031. 'class' => "", 'action' => "", 'method' => "post",
  1032. 'id' => "EDIT_FRM_{$this->_htmlID}", // TODO: rm - use React nodes // TODO: $this->_htmlID not exists!
  1033. 'ajaxSaveUrl' => "{$syncUrl}&_task=editSaveAjax", // TODO:? &_hash={$this->_htmlID}
  1034. 'namespace' => $acl->getNamespace(),
  1035. 'idRecord' => $record['ID'],
  1036. 'tableLabelHtml' => $tblLabel,
  1037. ], [
  1038. [ 'fieldset', [ 'style' => [ "padding-bottom" => "100px" ] ], $jsFields ] // fieldset
  1039. ] ] // form
  1040. ] ] // .container
  1041. ];
  1042. return [
  1043. 'type' => "success",
  1044. 'msg' => "Edycja rekordu nr {$id}",
  1045. 'body' => $jsGui, // TODO: action for GUI: array to render by function h, js to trigger
  1046. ];
  1047. }
  1048. public function editSaveAjaxAction() {
  1049. Response::sendTryCatchJson(array($this, 'editSaveAjax'), $args = 'JSON_FROM_REQUEST_BODY');
  1050. }
  1051. public function editSaveAjax($args) {
  1052. $namespace = V::get('namespace', '', $args, 'word');
  1053. if (!$namespace) throw new HttpException("Bad Request - missing namespace", 400);
  1054. $acl = Core_AclHelper::getAclByNamespace($namespace);
  1055. $primaryKeyField = $acl->getPrimaryKeyField();
  1056. $primaryKey = V::get('primaryKey', 0, $args, 'int');
  1057. if (empty($primaryKey)) throw new HttpException("Bad Request - missing primaryKey!", 400);
  1058. $item = $acl->getItem($primaryKey);
  1059. if (!$item) throw new HttpException("Item not exists!", 404);
  1060. $itemFromUser = $acl->convertObjectFromUserInput($args['form'], $type = 'array_by_id', $prefix = 'f');
  1061. $response = new stdClass();
  1062. $response->primaryKey = $primaryKey;
  1063. try {
  1064. $itemFromUser[$primaryKeyField] = $primaryKey;
  1065. $affected = $acl->updateItem($itemFromUser);
  1066. if ($affected > 0) {
  1067. $response->type = 'success';
  1068. $response->msg = "Rekord zapisany pomyślnie";//"Record saved successfully";
  1069. } else if ($affected == 0) {
  1070. $response->type = 'info';
  1071. $response->msg = "Nie wprowadzono żadnych zmian";
  1072. }
  1073. $response->record = $acl->getItem($primaryKey);
  1074. $rowFunList = Core_AclHelper::getMoreFunctionsCell($acl, array('primary_key'=>$primaryKey, 'record'=>$response->record));
  1075. if (!empty($rowFunList)) $response->rowFunctions = $rowFunList;
  1076. }
  1077. catch (Exception $e) {
  1078. $response->type = 'error';
  1079. $response->msg = "Wystąpiły błędy!";
  1080. $response->msg .= $e->getMessage();
  1081. }
  1082. return $response;
  1083. }
  1084. public function typeSpecialCellAction() {
  1085. Response::sendTryCatchJson(array($this, 'typeSpecialCell'), $args = $_REQUEST);
  1086. }
  1087. public function typeSpecialCell($args) {
  1088. $namespace = V::get('namespace', '', $args, 'word');
  1089. if (!$namespace) throw new HttpException("Bad Request - missing namespace", 400);
  1090. $acl = Core_AclHelper::getAclByNamespace($namespace);
  1091. $id = V::get('ID', 0, $args, 'int');
  1092. $fieldName = V::get('col', '', $args);
  1093. if ($id <= 0 || empty($fieldName)) throw new HttpException("Bad Request - missing id or col", 400);
  1094. $col = $fieldName;// TODO: RM $col
  1095. $jsonData = new stdClass();
  1096. $idField = $acl->getFieldIdByName($fieldName);
  1097. if (!$idField) throw new Exception("Wrong field");
  1098. $item = $acl->getItem($id);
  1099. if (!$acl->canReadObjectField($fieldName, $item)) throw new Exception("Brak dostępu");
  1100. $typeSpecial = Typespecial::getInstance($idField, $fieldName);
  1101. if ($typeSpecial) {
  1102. $jsonData->data = $typeSpecial->getReturnData($acl->getID(), $id, $fieldName, '');
  1103. $jsonData->namespace = 'default_db/' . V::get('tbl_name', '', $jsonData->data);
  1104. }
  1105. return $jsonData;
  1106. }
  1107. public function typespecialAction() { Response::sendTryCatchJson(array($this, 'typespecial'), $args = $_REQUEST); }
  1108. public function typespecial($args) { // @required idField, @optional: q (query), selected (selected value), idRecord (fetch value for given record)
  1109. $idField = V::get('idField', 0, $args, 'int');
  1110. if (!$idField) throw new HttpException("Bad Request - missing idField", 400);
  1111. $query = V::get('q', '', $_REQUEST);
  1112. DBG::log("\$query({$query})");
  1113. $cellInfo = DB::getPDO()->fetchFirst("
  1114. select *
  1115. from CRM_PROCES_idx_TABLES_INFO_VIEW
  1116. where ID_CELL = :id
  1117. ", [ ':id' => $idField ]);
  1118. DBG::log($cellInfo, 'array', "cell info");
  1119. if (!$cellInfo) throw new HttpException("Bad Request - wrong idField", 400);
  1120. // 'ID_CELL' => '24310',
  1121. // 'CELL_NAME' => 'L_APPOITMENT_USER',
  1122. // 'CELL_LABEL' => 'Osoba odpowiedzialna',
  1123. // 'CELL_DESCRIPTION' => '',
  1124. // 'CELL_SORT_PRIO' => '3',
  1125. // 'ID_TABLE' => '13051',
  1126. // 'TABLE_NAME' => 'TEST_PERMS',
  1127. // 'TABLE_LABEL' => 'Test permy',
  1128. // 'TABLE_DESCRIPTION' => '',
  1129. // 'ID_DATABASE' => '36',
  1130. $namespace = (false !== strpos($cellInfo['TABLE_NAME'], '/')) ? $cellInfo['TABLE_NAME'] : "default_db/{$cellInfo['TABLE_NAME']}";
  1131. if (!$namespace) throw new HttpException("Bad Request - wrong idField, cannot find namespace", 400);
  1132. $acl = Core_AclHelper::getAclByNamespace($namespace);
  1133. $fieldName = $cellInfo['CELL_NAME'];
  1134. $jsonData = array();
  1135. $typeSpecial = Typespecial::getInstance($idField, $fieldName);
  1136. if ($typeSpecial) {
  1137. // if (idRecord or selected) { // TODO
  1138. // $jsonData->data = $typeSpecial->getReturnData($acl->getID(), $id, $fieldName, '');
  1139. // $jsonData->namespace = 'default_db/' . V::get('tbl_name', '', $jsonData->data);
  1140. $rawRows = null;
  1141. $rows = $typeSpecial->getValuesWithExports($query);
  1142. DBG::log($rows, 'array', "\$rows({$query})");
  1143. foreach ($rows as $kID => $vItem) {
  1144. $itemJson = new stdClass();
  1145. $itemJson->id = $vItem->id;
  1146. $itemJson->name = $vItem->param_out;
  1147. if (!empty($vItem->exports)) {
  1148. $itemJson->exports = $vItem->exports;
  1149. }
  1150. if (!empty($vItem->{'$order'})) {
  1151. $itemJson->{'$order'} = $vItem->{'$order'};
  1152. }
  1153. $jsonData[] = $itemJson;
  1154. }
  1155. }
  1156. return $jsonData;
  1157. }
  1158. /**
  1159. * @param $_GET['namespace'] = AclNamespace
  1160. * @param $_GET['format'] = 'csv' | 'html'
  1161. * @param $_GET['flds'] = csv - coma separated field names
  1162. * @param $_GET['sortCol'] = FieldName
  1163. * @param $_GET['sortDir'] = SortDir ('desc' | 'asc')
  1164. * @param $_GET['f_{$fieldName}'] = filter
  1165. * @param $_GET['sf_{$fieldName}'] = force filter
  1166. */
  1167. public function exportAction() {
  1168. $args = $_GET;
  1169. $namespace = V::get('namespace', '', $args, 'word');
  1170. if (!$namespace) throw new HttpException("Bad Request - missing namespace", 400);
  1171. $acl = Core_AclHelper::getAclByNamespace($namespace);
  1172. $exportLimit = 10000;
  1173. $params = array();
  1174. $params['limit'] = $exportLimit;
  1175. // $params['limitstart'] = 0;
  1176. $params['order_by'] = V::get('sortCol', '', $args);
  1177. $params['order_dir'] = V::get('sortDir', '', $args);
  1178. $params['cols'] = array($acl->getPrimaryKeyField());
  1179. $toExportFields = explode(',', V::get('flds', '', $_GET));
  1180. if (empty($toExportFields)) throw new Exception("Nie wybrano żandych pól do exportu.");
  1181. $allowedExportFieldList = Core_AclHelper::getExportFieldList($acl);
  1182. foreach ($toExportFields as $fieldName) {
  1183. if ($fieldName == $acl->getPrimaryKeyField()) continue;
  1184. if (!in_array($fieldName, $allowedExportFieldList)) throw new Exception("Brak uprawnień do exportu pola '{$fieldName}'");
  1185. $params['cols'][] = $fieldName;
  1186. }
  1187. $labels = array();
  1188. foreach ($toExportFields as $fieldName) {
  1189. $labels[ $fieldName ] = $acl->getFieldLabel($fieldName);
  1190. }
  1191. foreach ($args as $k => $v) {
  1192. if (strlen($k) > 3 && substr($k, 0, 2) == 'f_' && strlen($v) > 0) {// filter prefix
  1193. $params[$k] = $v;
  1194. }
  1195. else if (strlen($k) > 4 && substr($k, 0, 3) == 'sf_' && strlen($v) > 0) {// special filter prefix
  1196. $params[$k] = $v;
  1197. }
  1198. }
  1199. try {
  1200. $queryFeatures = $acl->buildQuery($params);
  1201. $total = $queryFeatures->getTotal();
  1202. $listItems = $queryFeatures->getItems();
  1203. $primaryKeyField = $acl->getPrimaryKeyField();
  1204. $items = []; foreach ($listItems as $item) $items[ $item[$primaryKeyField] ] = $item;
  1205. } catch (Exception $e) {
  1206. DBG::log($e);
  1207. throw $e;
  1208. }
  1209. $format = V::get('format', 'html', $_GET);
  1210. switch ($format) {
  1211. case 'html': {
  1212. UI::gora();
  1213. echo UI::h('table', ['class'=>'table table-bordered table-hover'], [
  1214. UI::h('thead', [], [
  1215. UI::h('tr', [], array_map(function ($label) {
  1216. return UI::h('th', [], $label);
  1217. }, $labels))
  1218. ]),
  1219. UI::h('tbody', [], array_map(function ($item) use($labels) {
  1220. return UI::h('tr', [], array_map(function ($fieldName) use ($item) {
  1221. return UI::h('td', [], V::get($fieldName, '', $item));
  1222. }, array_keys($labels)));
  1223. }, $items)),
  1224. ]);
  1225. UI::dol();
  1226. exit;
  1227. }
  1228. case 'csv_cp1250':
  1229. case 'csv': {
  1230. $csvFileName = "Tabela-" . $acl->getName() . "-" . date("Y-m-d_H_s");
  1231. header('Content-Type: text/csv; charset=utf-8');
  1232. header("Content-Disposition: attachment; filename={$csvFileName}.csv");
  1233. $csvSeparator = ';';
  1234. $csvHeader = implode($csvSeparator, array_map(function ($label) use ($item) {
  1235. return '"' . addslashes($label) . '"';
  1236. }, array_values($labels)));
  1237. $csvRows = implode("\r\n", array_map(function ($item) use ($labels, $csvSeparator) {
  1238. return implode($csvSeparator, array_map(function ($fieldName) use ($item) {
  1239. return '"' . addslashes(V::get($fieldName, '', $item)) . '"';
  1240. }, array_keys($labels)));
  1241. }, $items));
  1242. switch ($format) {
  1243. case 'csv': echo $csvHeader . "\n" . $csvRows; exit;
  1244. case 'csv_cp1250': echo iconv('utf-8', 'Windows-1250//IGNORE', $csvHeader) . "\r\n" . iconv('utf-8', 'Windows-1250//IGNORE', $csvRows); exit;
  1245. die("Nieobsługiwane kodowanie danych csv.");
  1246. }
  1247. exit;
  1248. }
  1249. }
  1250. die("Nieobsługiwany format danych.");
  1251. }
  1252. public function loadDataAjaxAction() {
  1253. $namespace = V::get('namespace', '', $_REQUEST, 'word');
  1254. if (!$namespace) throw new HttpException("Bad Request - missing namespace", 400);
  1255. $acl = Core_AclHelper::getAclByNamespace($namespace);
  1256. $backRefFilter = [
  1257. 'namespace' => V::get('backRefNS', '', $_REQUEST),
  1258. 'primaryKey' => V::get('backRefPK', '', $_REQUEST),
  1259. 'fieldName' => V::get('backRefField', '', $_REQUEST),
  1260. ];
  1261. $childRefFilter = [
  1262. 'namespace' => V::get('childRefNS', '', $_GET),
  1263. 'primaryKey' => V::get('childRefPK', '', $_GET),
  1264. ];
  1265. $tbl = $this->getTableAjaxWidget($acl, $backRefFilter, $childRefFilter);
  1266. Response::sendTryCatchJson(array($tbl, 'ajaxData'), $args = $_GET);
  1267. }
  1268. public function uploadFilesAjaxAction() {
  1269. Response::sendTryCatchJson([$this, 'uploadFilesAjax'], $args = $_POST);
  1270. }
  1271. public function uploadFilesAjax($args) {
  1272. DBG::log($_FILES, 'array', "\$_FILES");
  1273. DBG::log($args, 'array', "\$args");
  1274. $namespace = V::get('namespace', '', $args, 'word');
  1275. if (!$namespace) throw new Exception("Missing namespace");
  1276. $primaryKey = V::get('primaryKey', '', $args, 'int');
  1277. if ($primaryKey <= 0) throw new Exception("Missing primaryKey");
  1278. if (empty($_FILES)) throw new Exception("Missing files");
  1279. $acl = Core_AclHelper::getAclByNamespace($namespace, $forceTblAclInit = ('1' == V::get('_force', '', $_GET)));
  1280. Lib::loadClass('FileUploader');
  1281. Lib::loadClass('FoldersConfig');
  1282. // $dbID = $acl->getDB();
  1283. // $db = DB::getDB($dbID);
  1284. // if (!$db) throw new HttpException("No DB ({$dbID})", 406);
  1285. $record = $acl->buildQuery([])->getItem($primaryKey);
  1286. DBG::log($record, 'array', "\$record");
  1287. if (!$record) throw new HttpException("No item ID({$primaryKey})", 404);
  1288. if (!$acl->canReadRecord($record)) throw new Exception("Brak uprawnień do odczytu");
  1289. if (!$acl->canWriteRecord($record)) throw new Exception("Brak uprawnień do zapisu");
  1290. $rootTableName = $acl->getRootTableName();
  1291. $confTblName = "{$rootTableName}_COLUMN";
  1292. $folderConfAll = FoldersConfig::getRawData();
  1293. if (!FoldersConfig::hasConfig($confTblName)) throw new HttpException("Brak danych konfiguracyjnych ({$rootTableName})", 404);
  1294. $folderConf = FoldersConfig::getAll($confTblName);
  1295. DBG::log($folderConf, 'array', "\$folderConf");
  1296. $uploader = new FileUploader($confTblName, (object)$record);
  1297. if (!$uploader->setConfig($folderConf)) throw new HttpException("Błąd danych konfiguracyjnych ({$rootTableName})", 404);
  1298. $uploader->findFolder();
  1299. DBG::log($uploader, 'array', "\$uploader");
  1300. // $errorMsg = '';
  1301. // if (!empty($args['SCANS_COLUMN_ADD'])) {
  1302. // $uploaded = $uploader->tryMoveFromScanAjax($errorMsg);
  1303. // }
  1304. // else {
  1305. // $uploaded = $uploader->tryUploadAjax($errorMsg);
  1306. // }
  1307. $destPath = $uploader->getDestLocalPath($show_if_not_found = true);
  1308. DBG::log($destPath, 'array', "\$destPath");
  1309. if (!file_exists($destPath)) {
  1310. if (!$uploader->tryCreateDestFolder($destPath)) throw new Exception("Wystąpił błąd podczas tworzenie katalogu dla rekordu '{$primaryKey}'");
  1311. }
  1312. $generateSafeFileName = function($destPath, $fileName) {
  1313. if (!file_exists("{$destPath}/{$fileName}")) return $fileName;
  1314. $infoPath = pathinfo($fileName);
  1315. // pathinfo('/path/t1/t2/fileName.ext') = [
  1316. // [dirname] => /path/t1/t2
  1317. // [basename] => fileName.ext
  1318. // [extension] => ext
  1319. // [filename] => fileName
  1320. // ]
  1321. return $infoPath['filename'] . "--" . date("Y-m-d_H-i-s") . "." . $infoPath['extension'];
  1322. };
  1323. $moveActions = array_map(function ($file) use ($destPath, $generateSafeFileName) {
  1324. $safeName = $generateSafeFileName($destPath, $file['name']);
  1325. return [
  1326. $file['tmp_name'],
  1327. "{$destPath}/{$safeName}",
  1328. $safeName,
  1329. ];
  1330. }, $_FILES);
  1331. DBG::log($moveActions, 'array', "\$moveActions"); // [ [ srcPath, descPath ] ]
  1332. $errorMsgs = [];
  1333. $pkField = $acl->getSqlPrimaryKeyField();
  1334. foreach ($moveActions as $fileMoveAction) {
  1335. if (!move_uploaded_file($fileMoveAction[0], $fileMoveAction[1])) {
  1336. $errorMsgs[] = "Nie udało się wgrać pliku '{$fileMoveAction[2]}'";
  1337. } else {
  1338. try {
  1339. $affected = DB::getPDO($acl->getDB())->update($rootTableName, $pkField, $primaryKey, [
  1340. 'M_DIST_FILES' => "Wrano plik '{$fileMoveAction[2]}'",
  1341. 'A_RECORD_UPDATE_AUTHOR' => User::getLogin(),
  1342. 'A_RECORD_UPDATE_DATE' => 'NOW()',
  1343. ]);
  1344. if ($affected) {
  1345. DB::getPDO($acl->getDB())->insert("{$rootTableName}_HIST", [
  1346. 'ID_USERS2' => $primaryKey,
  1347. 'M_DIST_FILES' => "Wrano plik '{$fileMoveAction[2]}'",
  1348. 'A_RECORD_UPDATE_AUTHOR' => User::getLogin(),
  1349. 'A_RECORD_UPDATE_DATE' => 'NOW()',
  1350. ]);
  1351. }
  1352. } catch (Exception $e) {
  1353. DBG::log($e);
  1354. $errorMsgs[] = $e->getMessage();
  1355. }
  1356. }
  1357. }
  1358. if (!empty($errorMsgs)) {
  1359. return [
  1360. 'type' => "error",
  1361. 'msg' => "Wystąpiły błędy podczas wgrywania plików dla '{$primaryKey}'",
  1362. 'errors' => $errorMsgs,
  1363. ];
  1364. }
  1365. return [
  1366. 'type' => "success",
  1367. 'msg' => "Wgrano nowe pliki dla '{$primaryKey}'",
  1368. ];
  1369. }
  1370. public function removeFileAjaxAction() {
  1371. Response::sendTryCatchJson([$this, 'removeFileAjax'], $args = $_REQUEST);
  1372. }
  1373. public function removeFileAjax($args) { // ajaxFileRemove
  1374. $namespace = V::get('namespace', '', $args, 'word');
  1375. if (!$namespace) throw new Exception("Missing namespace");
  1376. $id = V::get('ID', 0, $args, 'int');
  1377. if ($id <= 0) throw new Exception("Missing ID");
  1378. $filename = V::get('filename', '', $args);
  1379. if (empty($filename)) throw new Exception("Nie wybrano pliku do usunięcia");
  1380. $acl = Core_AclHelper::getAclByNamespace($namespace, $forceTblAclInit = ('1' == V::get('_force', '', $_GET)));
  1381. $dbID = $acl->getDB();
  1382. $db = DB::getPDO($dbID);
  1383. if (!$db) throw new HttpException("No DB ({$dbID})", 406);
  1384. $record = $acl->buildQuery([])->getItem($id);
  1385. if (!$record) throw new HttpException("No item ID({$id})", 404);
  1386. if (!$acl->canReadRecord($record)) throw new Exception("Brak uprawnień do odczytu");
  1387. if (!$acl->canWriteRecord($record)) throw new Exception("Brak uprawnień do zapisu");
  1388. Lib::loadClass('FileUploader');
  1389. Lib::loadClass('FoldersConfig');
  1390. $tblName = $acl->getName();
  1391. $confTblName = "{$tblName}_COLUMN";
  1392. $folderConfAll = FoldersConfig::getRawData();
  1393. if (!FoldersConfig::hasConfig($confTblName)) throw new HttpException("Brak danych konfiguracyjnych ({$tblName})", 404);
  1394. $folderConf = FoldersConfig::getAll($confTblName);
  1395. $uploader = new FileUploader($confTblName, (object)$record);
  1396. if (!$uploader->setConfig($folderConf)) throw new HttpException("Błąd danych konfiguracyjnych ({$tblName})", 404);
  1397. $uploader->findFolder();
  1398. $errorMsg = '';
  1399. $removed = $uploader->tryRemoveFromAjax($filename, $errorMsg);
  1400. if (!$removed) throw new Exception($errorMsg);
  1401. // $affected = DB::getPDO($acl->getDB())->update();
  1402. $rootTableName = $acl->getRootTableName();
  1403. $pkField = $acl->getSqlPrimaryKeyField();
  1404. $primaryKey = $id;
  1405. try {
  1406. $affected = DB::getPDO($acl->getDB())->update($rootTableName, $pkField, $primaryKey, [
  1407. 'M_DIST_FILES' => "Usunięto plik '{$filename}'",
  1408. 'A_RECORD_UPDATE_AUTHOR' => User::getLogin(),
  1409. 'A_RECORD_UPDATE_DATE' => 'NOW()',
  1410. ]);
  1411. if ($affected) {
  1412. DB::getPDO($acl->getDB())->insert("{$rootTableName}_HIST", [
  1413. 'ID_USERS2' => $primaryKey,
  1414. 'M_DIST_FILES' => "Usunięto plik '{$filename}'",
  1415. 'A_RECORD_UPDATE_AUTHOR' => User::getLogin(),
  1416. 'A_RECORD_UPDATE_DATE' => 'NOW()',
  1417. ]);
  1418. }
  1419. } catch (Exception $e) {
  1420. DBG::log($e);
  1421. }
  1422. return [
  1423. 'type' => 'success',
  1424. 'msg' => 'Plik został usunięty',
  1425. ];
  1426. }
  1427. public function procesInitFiltrAjaxAction() {
  1428. Response::sendTryCatchJson([$this, 'procesInitFiltrAjax'], $args = $_GET);
  1429. }
  1430. public function procesInitFiltrAjax($args) { // ajaxFileRemove
  1431. $namespace = V::get('namespace', '', $args, 'word');
  1432. if (!$namespace) throw new Exception("Missing namespace");
  1433. $acl = Core_AclHelper::getAclByNamespace($namespace, $forceTblAclInit = ('1' == V::get('_force', '', $_GET)));
  1434. $pInitList = User::getAcl()->getTableProcesInitList($acl->getID());
  1435. DBG::log($pInitList, 'array', "\$pInitList");
  1436. if (!empty($pInitList)) {
  1437. $procesIds = array_keys($pInitList);
  1438. $mapTree = ACL::getProcesInitMapTreeOnlyIds($procesIds);
  1439. DBG::log($mapTree, 'array', "\$mapTree");
  1440. DBG::log($pInitList, 'array', "\$pInitList");
  1441. $pInitListSelected = User::getAcl()->getPermsFiltrProcesId();
  1442. return [
  1443. 'type' => 'success',
  1444. 'msg' => 'ok',
  1445. 'pInitData' => [
  1446. 'pInitList' => $pInitList,
  1447. 'mapTree' => $mapTree,
  1448. 'pInitListSelected' => $pInitListSelected,
  1449. ],
  1450. ];
  1451. }
  1452. return [
  1453. 'type' => 'success'
  1454. ];
  1455. }
  1456. public function tableToolsAjaxAction() {
  1457. Response::sendTryCatchJson([$this, 'tableToolsAjax'], $args = $_GET);
  1458. }
  1459. public function tableToolsAjax($args) { // ajaxFileRemove
  1460. $namespace = V::get('namespace', '', $args, 'word');
  1461. if (!$namespace) throw new Exception("Missing namespace");
  1462. $acl = Core_AclHelper::getAclByNamespace($namespace, $forceTblAclInit = ('1' == V::get('_force', '', $_GET)));
  1463. $listUrlFunctions = Route_UrlAction::getTableFunctions($acl->getID(), $idRecord = 0, $acl->getName(), User::getLogin());
  1464. DBG::log($listUrlFunctions, 'array', "\$listUrlFunctions");
  1465. $listUrlFunctions = array_map(function ($urlFunction) use ($namespace) {
  1466. if ('index.php?' === substr($urlFunction['baseLink'], 0, strlen('index.php?'))) $urlFunction['baseLink'] .= "&_fromNamespace={$namespace}";
  1467. return $urlFunction;
  1468. }, $listUrlFunctions);
  1469. return [
  1470. 'type' => "success",
  1471. 'msg' => 'ok',
  1472. 'body' => [
  1473. 'tableTools' => array_values(array_map(function ($urlFunction) {
  1474. return [
  1475. 'url' => $urlFunction['baseLink'],
  1476. 'label' => $urlFunction['label'],
  1477. // TODO: $urlFunction['link_target'] // "_blank"
  1478. // ? $urlFunction['name']
  1479. ];
  1480. }, array_filter($listUrlFunctions, function ($urlFunction) {
  1481. return empty($urlFunction['cell_id_params']);
  1482. }))),
  1483. ],
  1484. ];
  1485. }
  1486. function executeRowFunctionAction() { UI::layout([ $this, 'executeRowFunction' ]); }
  1487. function executeRowFunction() {
  1488. $namespace = V::get('namespace', '', $_GET);
  1489. $name = V::get('name', '', $_GET);
  1490. $pk = V::get('pk', '', $_GET);
  1491. if (!$namespace) throw new Exception("Missing namespace");
  1492. if (!$name) throw new Exception("Missing name");
  1493. if (!$pk) throw new Exception("Missing pk");
  1494. $acl = ACL::getAclByNamespace($namespace);
  1495. if (!method_exists($acl, 'executeGuiRowFunction')) throw new Exception("Function executeGuiRowFunction not defined for '{$namespace}'");
  1496. $acl->executeGuiRowFunction($name, $pk);
  1497. }
  1498. }