ViewTableAjax.php 63 KB

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