ViewTableAjax.php 67 KB

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