ViewTableAjax.php 59 KB

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