Storage.php 69 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765
  1. <?php
  2. // @requires $_SERVER['SERVER_NAME']
  3. Lib::loadClass('RouteBase');
  4. Lib::loadClass('Schema_TableFactory');
  5. Lib::loadClass('Response');
  6. Lib::loadClass('UI');
  7. Lib::loadClass('OBJ');
  8. Lib::loadClass('SchemaFactory');
  9. /*
  10. # Storage:
  11. - [x] view available storage (from Zasoby - type 'BAZA_DANYCH', 'DATABASE_MYSQL', ...)
  12. - [x] check config for connection
  13. - [x] add cells to Zasoby
  14. - [ ] create cells in Storage
  15. - [x] use PDO
  16. */
  17. class Route_Storage extends RouteBase {
  18. public function handleAuth() {
  19. if (!User::logged()) {
  20. User::authByRequest();
  21. }
  22. }
  23. public function defaultAction() {
  24. UI::gora();
  25. UI::menu();
  26. $this->navView();
  27. UI::startContainer();
  28. try {
  29. $sourceStorage = SchemaFactory::loadDefaultObject('SystemSource');
  30. try {
  31. $sourceStorage->getTotal();
  32. } catch (Exception $e) {
  33. UI::alert('warning', $e->getMessage());
  34. $sourceStorage->updateCache();
  35. UI::alert('info', "Lista dostępnych baz danych zaktualizowana");
  36. }
  37. if ('1' == V::get('refreshSourceList', '', $_POST)) {
  38. $sourceStorage->updateCache();
  39. UI::alert('info', "Lista dostępnych baz danych zaktualizowana");
  40. }
  41. UI::table([
  42. 'caption' => "Bazy danych " .
  43. UI::hButtonPost('<i class="glyphicon glyphicon-refresh"></i>' . " odśwież", [
  44. 'class' => "btn btn-xs btn-link",
  45. 'data' => [
  46. 'refreshSourceList' => '1'
  47. ]
  48. ]),
  49. 'rows' => array_merge(
  50. array_map(function ($item) {
  51. return [
  52. 'Nr zasobu' => $item['idZasob'],
  53. 'nazwa' => $item['name'],
  54. 'opis' => $item['description'],
  55. 'config?' => ($item['hasConfig']) ? '<span class="label label-success">TAK</span>' : '<span class="text text-muted">brak</span>',
  56. 'obiekty' => UI::h('a', [ 'href' => $this->getLink('tableList', [ 'idStorage' => $item['idZasob'] ]) ], "obiekty"),
  57. 'raw info' => UI::h('a', [ 'href' => $this->getLink('rawInfo', [ 'idStorage' => $item['idZasob'] ]) ], "raw info"),
  58. 'xsd' => UI::h('a', [ 'href' => $this->getLink('xsd', [ 'idStorage' => $item['idZasob'] ]) ], "xsd"),
  59. ];
  60. }, $sourceStorage->getItems())
  61. , [
  62. [
  63. 'Nr zasobu' => '',
  64. 'nazwa' => "Obiekty",
  65. 'opis' => "SystemObjects",
  66. 'config?' => '<span class="text text-muted">brak</span>',
  67. 'obiekty' => UI::h('a', [ 'href' => $this->getLink('systemObjects') ], "obiekty"),
  68. ],
  69. [
  70. 'Nr zasobu' => '',
  71. 'nazwa' => "Obiekty Test",
  72. 'opis' => "Obiekty podstawowe (test json)",
  73. 'config?' => '<span class="text text-muted">brak</span>',
  74. 'obiekty' => UI::h('a', [ 'href' => $this->getLink('coreObjectList') ], "obiekty"),
  75. 'raw info' => UI::h('a', [ 'href' => $this->getLink('coreObjectParseAll') ], "raw info"),
  76. ],
  77. [
  78. 'Nr zasobu' => '',
  79. 'nazwa' => "Obiekty Test",
  80. 'opis' => "Obiekty dla domeny '" . str_replace(array(".", "-"), '_', $_SERVER['SERVER_NAME']) . "' (test json)",
  81. 'config?' => '<span class="text text-muted">brak</span>',
  82. 'obiekty' => UI::h('a', [ 'href' => $this->getLink('objectList') ], "obiekty"),
  83. // 'raw info' => UI::h('a', [ 'href' => $this->getLink('objectRawInfo') ], "raw info"),
  84. ],
  85. ]
  86. )
  87. ]);
  88. // $sourceStorage = SchemaFactory::loadDefaultObject('SystemObject');
  89. // $sourceStorage->updateCache();
  90. } catch (Exception $e) {
  91. UI::alert('danger', "Error #" . $e->getCode() . "|" . $e->getLine() . ": " . $e->getMessage());
  92. }
  93. UI::endContainer();
  94. UI::dol();
  95. }
  96. public function checkObjectInstallAjaxAction() {
  97. $response = array();
  98. try {
  99. $objectName = V::get('object', '', $_REQUEST, 'word');
  100. if (empty($objectName)) throw new Exception("Missing Object name");
  101. $response['object'] = $objectName;
  102. $json = OBJ::getCoreObjectFromFile($objectName);
  103. OBJ::checkInstall($json);
  104. $response['type'] = 'success';
  105. $response['msg'] = "OK - object installed";
  106. } catch (Exception $e) {
  107. $response['type'] = 'error';
  108. $response['msg'] = $e->getMessage();
  109. $response['code'] = $e->getCode();
  110. $response['line'] = $e->getLine();
  111. }
  112. Response::sendJsonExit($response);
  113. }
  114. public function coreObjectStructAction() {
  115. UI::gora();
  116. UI::menu();
  117. $this->navView();
  118. try {
  119. $objectName = V::get('object', '', $_REQUEST, 'word');
  120. if (empty($objectName)) throw new Exception("Missing Object name");
  121. $json = OBJ::getCoreObjectFromFile($objectName);
  122. $label = OBJ::getLabel($json);
  123. $parentList = OBJ::getParentList($json);
  124. $linksParentList = array(); foreach ($parentList as $parentName) {
  125. $parentLink = '<a href="index.php?_route=Storage&_task=coreObjectStruct&object=' . str_replace('/', '-', $parentName) . '">' . $parentName . '</a>';
  126. array_unshift($linksParentList, $parentLink);
  127. }
  128. $ajaxCheckInstall = Request::getPathUri() . "index.php?_route=Storage&_task=checkObjectInstallAjax&object={$objectName}";
  129. $onClick = "return p5UI__ButtonAjax(this, 'p5UIBtnAjax:Storage:checkObjectInstallAjax', { href: '{$ajaxCheckInstall}' })";
  130. $btnCheckInstall = '<a onclick="'.$onClick.'" href="#" title="check install db tables"><i class="glyphicon glyphicon-cog"></i></a>';
  131. UI::startContainer();
  132. UI::tag('h1', [], "Obiekt <code>{$label}</code> <small>{$btnCheckInstall}</small>");
  133. if (!empty($parentList)) {
  134. UI::startTag('ol', ['class'=>"breadcrumb"]);
  135. UI::tag('li', [], "Dziedziczy z:");
  136. foreach ($linksParentList as $parentLink) {
  137. UI::tag('li', [], $parentLink);
  138. }
  139. // <!-- <li class="active">Data</li> -->
  140. UI::endTag('ol');
  141. // <!-- <p> implode(", ", $parentList);</p> -->
  142. }
  143. // TODO: UI::table(['rows'=>array_map()]);
  144. ?>
  145. <table class="table table-bordered table-hovered">
  146. <caption>Struktura:</caption>
  147. <thead>
  148. <tr>
  149. <th>nazwa</th>
  150. <th>typ</th>
  151. <th>label</th>
  152. <th>json</th>
  153. </tr>
  154. </thead>
  155. <tbody>
  156. <?php foreach (OBJ::getFields($json) as $fieldName => $field) : ?>
  157. <tr>
  158. <td><?php echo $fieldName; ?></td>
  159. <td><?php echo $field['type']; ?></td>
  160. <td><?php echo $field['label']; ?></td>
  161. <td><?php echo json_encode($field); ?></td>
  162. </tr>
  163. <?php endforeach; ?>
  164. </tbody>
  165. </table>
  166. <a href="index.php?_route=Storage&_task=coreObjectConnect&object=<?php echo $objectName; ?>" class="btn btn-primary">Przypisz rekordy do klasy</a>
  167. <?php
  168. $mainTable = OBJ::getMainTableName($json);
  169. $sqlFields = OBJ::getTableFields($json);
  170. $this->showTableWidget($mainTable, $sqlFields);
  171. ?>
  172. </div>
  173. <script>
  174. jQuery(document).on('p5UIBtnAjax:Storage:checkObjectInstallAjax:click', function(e, n, payload) {
  175. console.log('event p5UIBtnAjax:Storage:checkObjectInstallAjax:click', n, payload);
  176. });
  177. jQuery(document).on('p5UIBtnAjax:Storage:checkObjectInstallAjax:ajaxLoaded', function(e, n, payload) {
  178. console.log('event p5UIBtnAjax:Storage:checkObjectInstallAjax:ajaxLoaded', n, payload);
  179. if ('success' == payload.type) {
  180. // jQuery(n).parents('td').text(payload.body.id);
  181. }
  182. jQuery.notify(payload.msg, payload.type);
  183. });
  184. </script>
  185. <?php
  186. DBG::_(true, true, "json", $json, __CLASS__, __FUNCTION__, __LINE__);
  187. } catch (Exception $e) {
  188. UI::alert('danger', "Error #" . $e->getCode() . "|" . $e->getLine() . ": " . $e->getMessage());
  189. }
  190. UI::dol();
  191. }
  192. public function coreObjectConnectAction() {
  193. UI::gora();
  194. UI::menu();
  195. $this->navView();
  196. try {
  197. $objectName = V::get('object', '', $_REQUEST, 'word');
  198. if (empty($objectName)) throw new Exception("Missing Object name");
  199. $json = OBJ::getCoreObjectFromFile($objectName);
  200. $label = OBJ::getLabel($json);
  201. $parentList = OBJ::getParentList($json);
  202. $linksParentList = array(); foreach ($parentList as $parentName) {
  203. $parentLink = '<a href="index.php?_route=Storage&_task=coreObjectStruct&object=' . str_replace('/', '-', $parentName) . '">' . $parentName . '</a>';
  204. array_unshift($linksParentList, $parentLink);
  205. }
  206. $ajaxCheckInstall = Request::getPathUri() . "index.php?_route=Storage&_task=checkObjectInstallAjax&object={$objectName}";
  207. $onClick = "return p5UI__ButtonAjax(this, 'p5UIBtnAjax:Storage:checkObjectInstallAjax', { href: '{$ajaxCheckInstall}' })";
  208. $btnCheckInstall = '<a onclick="'.$onClick.'" href="#" title="check install db tables"><i class="glyphicon glyphicon-cog"></i></a>';
  209. ?>
  210. <div class="container">
  211. <h1>Obiekt <code><?php echo $label; ?></code> <small><?php echo $btnCheckInstall; ?></small></h1>
  212. <?php if (!empty($parentList)) : ?>
  213. <ol class="breadcrumb">
  214. <li>Dziedziczy z:</li>
  215. <?php foreach ($linksParentList as $parentLink) : ?>
  216. <li><?php echo $parentLink; ?></li>
  217. <?php endforeach; ?>
  218. <!-- <li class="active">Data</li> -->
  219. </ol>
  220. <!-- <p> <?php echo implode(", ", $parentList); ?></p> -->
  221. <?php endif; ?>
  222. <?php
  223. $tableOne = array();
  224. $tableOne['caption'] = 'Klasy';
  225. $tableOne['rows'] = array();
  226. $parentList = OBJ::getParentList($json);
  227. $tableOne['rows'][] = array('__primary_key' => $objectName, 'name' => $objectName);
  228. $linksParentList = array(); foreach ($parentList as $parentName) {
  229. // $parentLink = '<a href="index.php?_route=Storage&_task=coreObjectStruct&object=' . str_replace('/', '-', $parentName) . '">' . $parentName . '</a>';
  230. // array_unshift($linksParentList, $parentLink);
  231. $tableOne['rows'][] = array('__primary_key' => $parentName, 'name' => $parentName);
  232. }
  233. $tableTwo = array();
  234. $tableTwo['caption'] = 'Rekordy w tabeli głównej';
  235. $mainTable = OBJ::getMainTableName($json);
  236. $sqlFields = OBJ::getTableFields($json);
  237. $tableTwo['rows'] = $this->getTableRows($mainTable, $sqlFields);
  238. foreach ($tableTwo['rows'] as $idx => $row) {
  239. // $tableTwo['rows'][] = array('__primary_key' => $objectName, 'name' => $objectName);
  240. $tableTwo['rows'][$idx]['__primary_key'] = $row['ID'];
  241. }
  242. echo '<hr>';
  243. // TODO: filter connected rows
  244. // TODO: filter not connected rows
  245. // TODO: action connect rows - args(schema, rows_primary_key_list)
  246. // TODO: action un connect rows - args(schema, rows_primary_key_list)
  247. $this->showConnectSchemaToTableWidget(compact('tableOne', 'tableTwo'));
  248. ?>
  249. </div>
  250. <script>
  251. jQuery(document).on('p5UIBtnAjax:Storage:checkObjectInstallAjax:click', function(e, n, payload) {
  252. console.log('event p5UIBtnAjax:Storage:checkObjectInstallAjax:click', n, payload);
  253. });
  254. jQuery(document).on('p5UIBtnAjax:Storage:checkObjectInstallAjax:ajaxLoaded', function(e, n, payload) {
  255. console.log('event p5UIBtnAjax:Storage:checkObjectInstallAjax:ajaxLoaded', n, payload);
  256. if ('success' == payload.type) {
  257. // jQuery(n).parents('td').text(payload.body.id);
  258. }
  259. jQuery.notify(payload.msg, payload.type);
  260. });
  261. </script>
  262. <?php
  263. DBG::_(true, true, "json", $json, __CLASS__, __FUNCTION__, __LINE__);
  264. } catch (Exception $e) {
  265. UI::alert('danger', "Error #" . $e->getCode() . "|" . $e->getLine() . ": " . $e->getMessage());
  266. }
  267. UI::dol();
  268. }
  269. public function showConnectSchemaToTableWidget($params) {
  270. if (empty($params['tableOne'])) throw new Exception("Missing tableOne in Connect widget");
  271. if (empty($params['tableTwo'])) throw new Exception("Missing tableTwo in Connect widget");
  272. $tableOne = $params['tableOne'];
  273. $tableTwo = $params['tableTwo'];
  274. // TODO: add p5BtnAjax to table filters button
  275. // TODO: add p5BtnAjax to conn button
  276. $jsEventNamespace = 'ConnectTableWidget' . time();
  277. $htmlIdWrap = "{$jsEventNamespace}-wrap";
  278. $stateLogId = "{$jsEventNamespace}-state-log";
  279. $stateSelectedTotalId = "{$jsEventNamespace}-state-selected";
  280. $stateClearSelectedBtnId = "{$jsEventNamespace}-state-clear-selected-btn";
  281. foreach ($tableOne['rows'] as $idx => $r) {
  282. $tableOne['rows'][$idx]['@onClick'] = "return p5UI__Clickable(this, '{$jsEventNamespace}:tableOne', { primary_key: '{$r['__primary_key']}' });";
  283. }
  284. foreach ($tableTwo['rows'] as $idx => $r) {
  285. $tableTwo['rows'][$idx]['@onClick'] = "return p5UI__Clickable(this, '{$jsEventNamespace}:tableTwo', { primary_key: '{$r['__primary_key']}' });";
  286. }
  287. $tableOne['hidden_cols'] = $tableTwo['hidden_cols'] = array('__primary_key', '@onClick', '__html_id');
  288. $tableTwo['__html_id'] = "{$jsEventNamespace}-table-two";
  289. ?>
  290. <div id="<?php echo $htmlIdWrap; ?>">
  291. <?php UI::table($tableOne); ?>
  292. <div class="btn-group">
  293. <button class="btn btn-default" title="Wybierz rekordy wg instancji"><i class="glyphicon glyphicon-question-sign"></i></button>
  294. <button class="btn btn-default conn-btn-filter-yes">Przypisani</button>
  295. <button class="btn btn-default conn-btn-filter-no active">Nieprzypisani</button>
  296. <button class="btn btn-default conn-btn-filter-clear" title="Wszystkie"><i class="glyphicon glyphicon-remove"></i></button>
  297. </div>
  298. <div class="btn-group">
  299. <span style="padding-left:30px;">Zaznaczono
  300. <span class="conn-selected-total">0</span>
  301. <button class="conn-btn-clear-selected btn btn-link"
  302. onClick="return p5UI__Clickable(this, '<?php echo $jsEventNamespace; ?>:clearSelection', {});"
  303. style="display:none"><i class="glyphicon glyphicon-remove" style="color:red"></i></button>
  304. </span>
  305. </div>
  306. <?php UI::jsAjaxTable($tableTwo); ?>
  307. <pre class="conn-log"></pre>
  308. </div>
  309. <script>
  310. (function(){
  311. var state = {
  312. selectedTableOne: null,
  313. selectedTableTwo: [],
  314. filterSelected: 'no'
  315. }
  316. var props = {
  317. jsEventNamespace: '<?php echo $jsEventNamespace; ?>',
  318. htmlIdWrap: '<?php echo $htmlIdWrap; ?>',
  319. tableTwoId: '#<?php echo $tableTwo['__html_id']; ?>',
  320. stateSelectedTotalId: '#<?php echo $stateSelectedTotalId; ?>',
  321. stateClearSelectedBtnId: '#<?php echo $stateClearSelectedBtnId; ?>',
  322. stateLogId: '#<?php echo $stateLogId; ?>'
  323. }
  324. var wrap = jQuery('#' + props.htmlIdWrap);
  325. var jqNodes = {
  326. wrap: wrap,
  327. filter_yes: wrap.find('.conn-btn-filter-yes'),
  328. filter_no: wrap.find('.conn-btn-filter-no'),
  329. filter_clear: wrap.find('.conn-btn-filter-clear'),
  330. total_selected: wrap.find('.conn-selected-total'),
  331. btn_clear_selected: wrap.find('.conn-btn-clear-selected'),
  332. state_log: wrap.find('.conn-log')
  333. }
  334. function render() {
  335. jqNodes['total_selected'].text(state.selectedTableTwo.length);
  336. if (state.selectedTableTwo.length > 0) {
  337. jQuery(props.stateClearSelectedBtnId).show();
  338. } else {
  339. jQuery(props.stateClearSelectedBtnId).hide();
  340. }
  341. jqNodes['state_log'].text(JSON.stringify(state));
  342. switch (state.filterSelected) {
  343. case 'yes':
  344. jqNodes['filter_yes'].addClass('active');
  345. jqNodes['filter_no'].removeClass('active');
  346. jqNodes['filter_clear'].removeClass('active');
  347. break;
  348. case 'no':
  349. jqNodes['filter_yes'].removeClass('active');
  350. jqNodes['filter_no'].addClass('active');
  351. jqNodes['filter_clear'].removeClass('active');
  352. break;
  353. case 'clear':
  354. jqNodes['filter_yes'].removeClass('active');
  355. jqNodes['filter_no'].removeClass('active');
  356. jqNodes['filter_clear'].addClass('active');
  357. break;
  358. }
  359. }
  360. function action__selectTableOneRow(pk) {
  361. state.selectedTableOne = pk;
  362. render();
  363. }
  364. function action__unselectTableOneRow() {
  365. state.selectedTableOne = null;
  366. render();
  367. }
  368. function action__selectTableTwoRow(pk) {
  369. var idx = state.selectedTableTwo.indexOf(pk);
  370. if (-1 === idx) state.selectedTableTwo.push(pk);
  371. else console.log("Error selectedTableTwo - should be not set");
  372. render();
  373. }
  374. function action__unselectTableTwoRow(pk) {
  375. var idx = state.selectedTableTwo.indexOf(pk);
  376. if (-1 === idx) state.selectedTableTwo.push(pk);
  377. else state.selectedTableTwo.splice(idx, 1);
  378. render();
  379. }
  380. function action__clearSelection() {
  381. state.selectedTableTwo = [];
  382. jQuery(props.tableTwoId).find('tbody').children('.info').removeClass('info');
  383. render();
  384. }
  385. function action__filterSet(fltr) {
  386. state.filterSelected = fltr;
  387. render();
  388. // TODO: ajax load tableTwo based on filter
  389. }
  390. jQuery(document).on(props.jsEventNamespace + ':tableOne:click', function(e, n, payload) {
  391. var n$ = jQuery(n);
  392. console.log('event '+props.jsEventNamespace+':tableOne:click', n, payload);
  393. jQuery.notify('tableOne row clicked [' + payload.props.primary_key + ']', 'info');
  394. if (n$.hasClass('info')) {
  395. n$.removeClass('info');
  396. action__unselectTableOneRow();
  397. } else {
  398. n$.parent().children('.info').removeClass('info');
  399. n$.addClass('info');
  400. action__selectTableOneRow(payload.props.primary_key);
  401. }
  402. });
  403. jQuery(document).on(props.jsEventNamespace + ':tableTwo:click', function(e, n, payload) {
  404. var n$ = jQuery(n);
  405. console.log('event '+props.jsEventNamespace+':tableTwo:click', n, payload);
  406. jQuery.notify('tableTwo row clicked [' + payload.props.primary_key + ']', 'info');
  407. if (n$.hasClass('info')) {
  408. n$.removeClass('info');
  409. action__unselectTableTwoRow(payload.props.primary_key);
  410. } else {
  411. n$.addClass('info');
  412. action__selectTableTwoRow(payload.props.primary_key);
  413. }
  414. });
  415. jQuery(document).on(props.jsEventNamespace + ':clearSelection:click', function(e, n, payload) {
  416. action__clearSelection();
  417. });
  418. jqNodes['filter_yes'].on('click', function(e) {
  419. action__filterSet('yes');
  420. });
  421. jqNodes['filter_no'].on('click', function(e) {
  422. action__filterSet('no');
  423. });
  424. jqNodes['filter_clear'].on('click', function(e) {
  425. action__filterSet('clear');
  426. });
  427. })();
  428. </script>
  429. <?php
  430. }
  431. public function getTableRows($tblName, $fields) {
  432. $sqlFields = array();
  433. foreach ($fields as $fldName) {
  434. $sqlFields[] = "t.`{$fldName}`";
  435. }
  436. $sqlFields = (!empty($sqlFields))? implode(", ", $sqlFields) : "t.*";
  437. $rows = DB::getPDO()->fetchAll("
  438. select {$sqlFields}
  439. from `{$tblName}` t
  440. where 1=1
  441. limit 10
  442. ");
  443. return $rows;
  444. }
  445. public function showTableWidget($tblName, $fields) {
  446. $rows = $this->getTableRows($tblName, $fields);
  447. UI::table(array('caption' => "table({$tblName})", 'rows' => $rows));
  448. }
  449. public function coreObjectParseAllAction() {
  450. UI::gora();
  451. UI::menu();
  452. $this->navView();
  453. try {
  454. OBJ::parseAll();
  455. } catch (Exception $e) {
  456. UI::alert('danger', "Error #" . $e->getCode() . "|" . $e->getLine() . ": " . $e->getMessage());
  457. }
  458. UI::dol();
  459. }
  460. public function coreObjectListAction() {
  461. UI::gora();
  462. UI::menu();
  463. $this->navView();
  464. try {
  465. $coreObjlist = OBJ::getCoreObjectList();
  466. $objectList = array();
  467. foreach ($coreObjlist as $objName) {
  468. $objItem = array();
  469. $objItem['name'] = $objName;
  470. $objItem['struktura'] = '<a href="index.php?_route=Storage&_task=coreObjectStruct&object=' . $objName . '">' . "struct" . '</a>';
  471. // $objItem['label'] = "";// TODO: read from json
  472. $objectList[] = $objItem;
  473. }
  474. usort($objectList, function($rowA, $rowB) {
  475. $a = $rowA['nazwa']; $b = $rowB['nazwa'];
  476. if ($a == $b) return 0;
  477. return ($a < $b) ? -1 : 1;
  478. });
  479. DBG::table("objectList", $objectList, __CLASS__, __FUNCTION__, __LINE__);
  480. } catch (Exception $e) {
  481. UI::alert('danger', "Error #" . $e->getCode() . "|" . $e->getLine() . ": " . $e->getMessage());
  482. }
  483. UI::dol();
  484. }
  485. public function objectListAction() {
  486. UI::gora();
  487. UI::menu();
  488. try {
  489. } catch (Exception $e) {
  490. UI::alert('danger', "Error #" . $e->getCode() . "|" . $e->getLine() . ": " . $e->getMessage());
  491. }
  492. UI::dol();
  493. }
  494. public function tableListAction() {
  495. UI::gora();
  496. UI::menu();
  497. $this->navView();
  498. UI::startContainer();
  499. try {
  500. $idStorage = V::get('idStorage', 0, $_REQUEST, 'int');
  501. if (empty($idStorage)) throw new Exception("Missing id storage");
  502. $sourceStorage = SchemaFactory::loadDefaultObject('SystemSource');
  503. $sourceItem = $sourceStorage->getItem($idStorage);
  504. if (!$sourceItem) throw new Exception("Storage id='{$idStorage}' not exists");
  505. DBG::log($sourceItem, 'array', '$sourceItem');
  506. // TODO: fetch SystemObject childrens from $sourceItem:
  507. // 1. 'SystemSource' -> getItems([ 'cols' => 'SystemObject/*', 'featureId' => $sourceItem['idZasob'] ])
  508. // 2. 'SystemObject' -> getItems([ 'refFrom' => $sourceItem['idZasob'] ])
  509. // 'default_objects' => _task=systemObjects
  510. $objectStorage = SchemaFactory::loadDefaultObject('SystemObject');
  511. try {
  512. $objectStorage->getTotal();
  513. } catch (Exception $e) {
  514. UI::alert('warning', $e->getMessage());
  515. DBG::log($e);
  516. $objectStorage->updateCache();
  517. UI::alert('info', "Lista obiketów zaktualizowana");
  518. }
  519. if ('1' == V::get('refreshObjectList', '', $_POST)) {
  520. $objectStorage->updateCache();
  521. UI::alert('info', "Lista obiketów zaktualizowana");
  522. }
  523. UI::table([
  524. 'caption' => "Obiekty w bazie '{$sourceItem['name']}' " .
  525. UI::hButtonPost('<i class="glyphicon glyphicon-refresh"></i>' . " odśwież", [
  526. 'class' => "btn btn-xs btn-link",
  527. 'data' => [
  528. 'refreshObjectList' => '1'
  529. ]
  530. ]),
  531. 'rows' => array_map(function ($item) use ($idStorage) {
  532. $addToZasobyLink = $this->getLink('addAclObjectToZasoby', ['idStorage' => $idStorage, 'namespace' => $item['namespace']]);
  533. return [
  534. 'namespace' => '<span style="color:#888">' . substr($item['namespace'], 0, strlen($item['namespace']) - strlen($item['name'])) . '</span>' .
  535. '<span>' . $item['name'] . '</span>',
  536. '_type' => $item['_type'], // TODO: editable?
  537. 'Nr zasobu' => ($item['idZasob'] > 0)
  538. ? $item['idZasob']
  539. : UI::h('button', [
  540. 'class' => "btn btn-xs btn-primary",
  541. 'onClick' => "return p5UI__ButtonAjax(this, 'p5UIBtnAjax:Storage:addAclObjectToZasoby', { href: '{$addToZasobyLink}' })"
  542. ], "Dodaj do Zasobów"),
  543. // 'opis' => $item['description'],
  544. 'active?' => ($item['isActive']) ? '<span class="label label-success">TAK</span>' : '<span class="text text-muted">nie</span>',
  545. 'struktura' => UI::h('a', [ 'href' => $this->getLink('tableStruct', [ 'idStorage' => $idStorage, 'table' => $item['name'] ]) ], "struktura"),
  546. 'struktura OBJ' => UI::h('a', [ 'href' => $this->getLink('objectStruct', [ 'idStorage' => $idStorage, 'namespace' => $item['namespace'] ]) ], "obj struct"),
  547. 'raw info' => UI::h('a', [ 'href' => $this->getLink('rawInfo', [ 'idStorage' => $idStorage, 'table' => $item['name'] ]) ], "raw info"),
  548. 'reinstall' => UI::h('a', [ 'href' => $item['reinstallLink'] ], "reinstall"),
  549. 'view table' => UI::h('a', [ 'href' => Router::getRoute('ViewTableAjax')->getLink('', ['namespace' => $item['namespace']]) ], "view table"),
  550. 'view object' => UI::h('a', [ 'href' => Router::getRoute('ViewObject')->getLink('', ['namespace' => $item['namespace']]) ], "view object"),
  551. // 'xsd' => UI::h('a', [ 'href' => $this->getLink('xsd', [ 'idStorage' => $idStorage ]) ], "xsd"),
  552. ];
  553. }, $objectStorage->getItems([
  554. '#refFrom' => [
  555. 'namespace' => 'default_objects/SystemSource',
  556. 'primaryKey' => $sourceItem['idZasob']
  557. ],
  558. 'order_by' => 'namespace',
  559. 'order_dir' => 'asc'
  560. ]))
  561. ]);
  562. echo UI::h('script', [], "
  563. jQuery(document).on('p5UIBtnAjax:Storage:addAclObjectToZasoby:click', function(e, n, payload) {
  564. console.log('event p5UIBtnAjax:Storage:addAclObjectToZasoby:click', n, payload);
  565. });
  566. jQuery(document).on('p5UIBtnAjax:Storage:addAclObjectToZasoby:ajaxLoaded', function(e, n, payload) {
  567. console.log('event p5UIBtnAjax:Storage:addAclObjectToZasoby:ajaxLoaded', n, payload);
  568. if ('success' == payload.type && payload.body && payload.body.id > 0) {
  569. jQuery(n).parents('td').text(payload.body.id);
  570. }
  571. jQuery.notify(payload.msg, payload.type);
  572. });
  573. ");
  574. } catch (Exception $e) {
  575. UI::alert('danger', "Error #" . $e->getCode() . "|" . $e->getLine() . ": " . $e->getMessage());
  576. DBG::log($e);
  577. }
  578. UI::endContainer();
  579. UI::dol();
  580. }
  581. public function rawInfoAction() {
  582. UI::gora();
  583. UI::menu();
  584. $this->navView();
  585. try {
  586. $idStorage = V::get('idStorage', 0, $_REQUEST, 'int');
  587. if (empty($idStorage)) throw new Exception("Missing id storage");
  588. $storageList = $this->getStorageList();
  589. if (empty($storageList)) throw new Exception("No storage defined");
  590. if (!array_key_exists($idStorage, $storageList)) throw new Exception("Storage not exists");
  591. $storagePdo = DB::getStorage($idStorage);
  592. $rawInfo = $storagePdo->getTableListWithInfo();
  593. DBG::table("rawInfo", $rawInfo, __CLASS__, __FUNCTION__, __LINE__);
  594. } catch (Exception $e) {
  595. UI::alert('danger', "Error #" . $e->getCode() . "|" . $e->getLine() . ": " . $e->getMessage());
  596. }
  597. UI::dol();
  598. }
  599. public function objectStructAction() {
  600. UI::gora();
  601. UI::menu();
  602. $this->navView();
  603. UI::startTag('div', [ 'class' => 'container-fluid' ]);
  604. try {
  605. $namespace = V::get('namespace', '', $_GET);
  606. if (empty($namespace)) throw new Exception("Missing param namespace");
  607. $item = SchemaFactory::loadDefaultObject('SystemObject')->getItem($namespace, [ 'propertyName' => '*,field' ]);
  608. DBG::nicePrint($item, '$item');
  609. usort($item['field'], function ($a, $b) {
  610. if ($a['fieldNamespace'] > $b['fieldNamespace']) return 1;
  611. if ($a['fieldNamespace'] < $b['fieldNamespace']) return -1;
  612. return 0;
  613. });
  614. echo ($item['idZasob'] > 0)
  615. ? UI::h('h3', [], "Nr zasobu {$item['idZasob']}")
  616. : UI::h('h3', [], "Nr zasobu ???");// TODO: UI::hButtonAjax(...)
  617. UI::table([
  618. 'caption' => UI::h('h3', [], "Struktura obiektu '{$item['namespace']}'"),
  619. 'rows' => array_map(function ($field) {
  620. $tblItem = []; foreach ($field as $k => $v) $tblItem[$k] = $v;
  621. $tblItem['namespace'] = UI::h('span', [], [
  622. UI::h('span', ['style' => "color:#aaa"], substr($field['namespace'], 0, strlen($field['objectNamespace']) + 1)),
  623. UI::h('span', ['style' => "color:#000"], substr($field['namespace'], strlen($field['objectNamespace']) + 1)),
  624. ]);
  625. $tblItem['idZasob'] = ($field['idZasob'] > 0)
  626. ? $field['idZasob']
  627. : UI::hButtonAjax("+ do zasobów", 'addFieldToZasoby', [
  628. 'class' => "btn btn-xs btn-primary",
  629. 'href' => Request::getPathUri() . "index.php?_route=Storage&_task=addFieldToZasoby",
  630. 'data' => [
  631. 'namespace' => $field['namespace'],
  632. ]
  633. ]);
  634. unset($tblItem['objectNamespace']);
  635. unset($tblItem['fieldNamespace']);
  636. return $tblItem;
  637. }, $item['field'])
  638. ]);
  639. UI::hButtonAjaxOnResponse('addFieldToZasoby', "
  640. if (!payload.type) return false
  641. console.log('TODO: addFieldToZasoby response', payload);
  642. if (payload.data && payload.data.id && payload.data.id > 0) { // if ('success' == payload.type) {
  643. n.parentNode.replaceChild(document.createTextNode(payload.data.id), n)
  644. } else {
  645. console.log('TODO: addFieldToZasoby unknown response', payload);
  646. }
  647. ");
  648. } catch (Exception $e) {
  649. UI::alert('danger', "Error #" . $e->getCode() . "|" . $e->getLine() . ": " . $e->getMessage());
  650. DBG::log($e);
  651. }
  652. UI::endTag('div'); // .container-fluid
  653. UI::dol();
  654. }
  655. public function tableStructAction() {
  656. UI::gora();
  657. UI::menu();
  658. $this->navView();
  659. try {
  660. $idStorage = V::get('idStorage', 0, $_REQUEST, 'int');
  661. if (empty($idStorage)) throw new Exception("Missing id storage");
  662. $storageList = $this->getStorageList();
  663. if (empty($storageList)) throw new Exception("No storage defined");
  664. if (!array_key_exists($idStorage, $storageList)) throw new Exception("Storage not exists");
  665. $tblName = V::get('table', '', $_REQUEST, 'word');
  666. if (empty($tblName)) throw new Exception("No table name");
  667. $storagePdo = DB::getStorage($idStorage);
  668. $tblStruct = $storagePdo->getTableStruct($tblName);
  669. $idTable = $this->fetchTableId($idStorage, $tblName);
  670. if ($idTable <= 0) {
  671. UI::alert('warning', "Zasob tabela '{$tblName}' nie istnieje");// TODO: add p5UI btn
  672. DBG::table("tblStruct", $tblStruct, __CLASS__, __FUNCTION__, __LINE__);
  673. throw new Exception("Zasob tabela '{$tblName}' nie istnieje");
  674. }
  675. $cellZasobList = array();
  676. foreach (DB::getPDO()->fetchAllByKey("
  677. select z.ID, z.`DESC`, z.`TYPE` as ZASOB_TYPE, z.A_STATUS
  678. from CRM_LISTA_ZASOBOW z
  679. where z.PARENT_ID = '{$idTable}'
  680. ", $key = 'DESC') as $ind => $row) {
  681. $cellZasobList[strtolower($ind)] = $row;
  682. }
  683. $emptyItem = array();
  684. $emptyItem['name'] = '';
  685. $emptyItem['id_zasob'] = '';
  686. $emptyItem['zasob_type'] = '';
  687. $emptyItem['uwagi'] = '';
  688. $emptyItem['type'] = '';
  689. $emptyItem['is_nullable'] = '';
  690. $emptyItem['default_value'] = '';
  691. $emptyItem['default_is_null'] = '';
  692. $emptyItem['max_length'] = '';
  693. $emptyItem['num_precision'] = '';
  694. $emptyItem['num_scale'] = '';
  695. $emptyItem['char_encoding'] = '';
  696. $emptyItem['char_collation'] = '';
  697. $emptyItem['extra'] = '';
  698. $emptyItem['raw_storage_type'] = '';
  699. $tableList = array();
  700. foreach ($tblStruct as $row) {
  701. $cellName = $row['name'];
  702. $tblItem = V::cloneArray($emptyItem);
  703. $tblItem['name'] = $cellName;
  704. foreach ($row as $fldName => $fldVal) {
  705. if (array_key_exists($fldName, $tblItem)) $tblItem[$fldName] = $fldVal;
  706. }
  707. $tblItem['uwagi'] = '';
  708. $lowerCellName = strtolower($cellName);
  709. $tblZasob = V::get($lowerCellName, '', $cellZasobList);
  710. if ($tblZasob) {
  711. $cellZasobList[$lowerCellName]['_checked'] = true;
  712. $tblItem['id_zasob'] = $tblZasob['ID'];
  713. $tblItem['zasob_type'] = $tblZasob['ZASOB_TYPE'];
  714. } else {
  715. $tblItem['uwagi'] .= '!Zasob';//'TODO: ADD ZASOB';
  716. $ajaxAddZasobLink = Request::getPathUri() . "index.php?_route=Storage&_task=addCellToZasoby&idStorage={$idStorage}&tblName={$tblName}&cellName={$cellName}";
  717. $onClick = "return p5UI__ButtonAjax(this, 'p5UIBtnAjax:Storage:addCellToZasoby', { href: '{$ajaxAddZasobLink}' })";
  718. $tblItem['id_zasob'] = '<a onclick="'.$onClick.'" class="btn btn-xs btn-primary" href="#">TODO: ADD ZASOB</a>';
  719. }
  720. $tableList[] = $tblItem;
  721. }
  722. foreach ($cellZasobList as $cellName => $row) {
  723. if ('URL_ACTION' == $row['ZASOB_TYPE']) continue;
  724. if (!$row['_checked']) {
  725. $tblItem = V::cloneArray($emptyItem);
  726. $tblItem['name'] = $cellName;
  727. $tblItem['id_zasob'] = $row['ID'];
  728. $tblItem['zasob_type'] = $row['ZASOB_TYPE'];
  729. $tblItem['uwagi'] = '!DB';//'TODO: nie istnieje w bazie danych';
  730. $tableList[] = $tblItem;
  731. }
  732. }
  733. usort($tableList, function($rowA, $rowB) {
  734. $a = $rowA['name']; $b = $rowB['name'];
  735. if ('ID' == $a) return -1;
  736. if ('ID' == $b) return 1;
  737. if ($a == $b) return 0;
  738. $a1 = substr($a, 0, 1); $b1 = substr($b, 0, 1);
  739. if (('_' == $a1 || '_' == $b1) && $a1 != $b1) {
  740. return ($a1 < $b1) ? 1 : -1;
  741. }
  742. return ($a < $b) ? -1 : 1;
  743. });
  744. UI::table([
  745. 'caption' => UI::h('span', [], [
  746. "Komórki [{$idTable}] ",
  747. UI::h('a', [
  748. 'href' => "index.php?_route=ViewTableAjax&namespace=default_db/{$tblName}",
  749. 'class' => "btn btn-md btn-link"
  750. ], "Przeglądaj tabelę"),
  751. UI::h('a', [
  752. 'href' => "procesy5.php?task=CRM_LISTA_ZASOBOW&filtr_id={$idTable}&filtr_ids=%2B&filtr_ob=%2B",
  753. 'class' => "btn btn-md btn-link",
  754. 'title' => "Struktura aktualnie przeglądanej tabeli"
  755. ], "Zasoby"),
  756. UI::h('a', [
  757. 'href' => "index.php?FUNCTION_INIT=PROCES_MENU&HEADER_NOT_INIT=YES&_task=PROCES_FOR_TABLE&tblId={$idTable}",
  758. 'class' => "btn btn-md btn-link",
  759. 'title' => "Procesy dla aktualnie przeglądanej tabeli"
  760. ], "Procesy"),
  761. ]),
  762. 'cols' => array_keys($emptyItem),
  763. 'rows' => $tableList
  764. ]);
  765. echo UI::h('script', [], "
  766. jQuery(document).on('p5UIBtnAjax:Storage:addCellToZasoby:click', function(e, n, payload) {
  767. console.log('event p5UIBtnAjax:Storage:addCellToZasoby:click', n, payload);
  768. });
  769. jQuery(document).on('p5UIBtnAjax:Storage:addCellToZasoby:ajaxLoaded', function(e, n, payload) {
  770. console.log('event p5UIBtnAjax:Storage:addCellToZasoby:ajaxLoaded', n, payload);
  771. if ('success' == payload.type && payload.body && payload.body.id > 0) {
  772. var cellUwagiJQNode = jQuery(n).parents('td').next('td');
  773. cellUwagiJQNode.text(cellUwagiJQNode.text().replace('!Zasob', ''))
  774. jQuery(n).parents('td').text(payload.body.id);
  775. jQuery(n).remove();
  776. }
  777. jQuery.notify(payload.msg, payload.type);
  778. });
  779. ");
  780. $ajaxAddZasobLink = Request::getPathUri() . "index.php?_route=Storage&_task=addGeomEtykietaCells&idStorage={$idStorage}&tblName={$tblName}";
  781. $onClick = "return p5UI__ButtonAjax(this, 'p5UIBtnAjax:Storage:addGeomEtykietaCells', { href: '{$ajaxAddZasobLink}' })";
  782. UI::tag('a', ['onclick'=>$onClick, 'class'=>"btn btn-xs btn-default", 'href'=>"#"], "Dodaj komórki etykiet", true);
  783. echo "<i>(<code>`etykieta_x`</code>, <code>`etykieta_y`</code>, <code>`etykieta_obrot`</code>)</i>";
  784. echo UI::h('script', [], "
  785. jQuery(document).on('p5UIBtnAjax:Storage:addGeomEtykietaCells:ajaxLoaded', function(e, n, payload) {
  786. console.log('event p5UIBtnAjax:Storage:addGeomEtykietaCells:ajaxLoaded', n, payload);
  787. if ('success' == payload.type && payload.body && payload.body.id > 0) {
  788. var cellUwagiJQNode = jQuery(n).parents('td').next('td');
  789. cellUwagiJQNode.text(cellUwagiJQNode.text().replace('!Zasob', ''))
  790. jQuery(n).parents('td').text(payload.body.id);
  791. jQuery(n).remove();
  792. }
  793. jQuery.notify(payload.msg, payload.type);
  794. });
  795. ");
  796. $tableActions = array_filter($cellZasobList, function ($row) {
  797. return ('URL_ACTION' == $row['ZASOB_TYPE']);
  798. });
  799. UI::table([
  800. 'caption' => "tableActions",
  801. // 'cols' => array_keys($emptyItem),
  802. 'rows' => array_map(function ($item) {
  803. $sqlIdAction = DB::getPDO()->quote($item['ID'], PDO::PARAM_INT);
  804. $args = DB::getPDO()->fetchAll("
  805. select z.`DESC`
  806. , a.ID as ALIAS_ID, a.`DESC` as ALIAS_DESC, a.OPIS as ALIAS_OPIS
  807. from CRM_LISTA_ZASOBOW z
  808. left join CRM_LISTA_ZASOBOW a on(a.ID = z.ALIAS_ID)
  809. where z.PARENT_ID = {$sqlIdAction}
  810. and z.`TYPE` = 'PARAM_IN'
  811. ");
  812. $definitionArgs = DB::getPDO()->fetchAll("
  813. select p.ID, p.`DESC`
  814. from CRM_LISTA_ZASOBOW z
  815. join CRM_LISTA_ZASOBOW d on(d.ID = z.ALIAS_ID)
  816. left join CRM_LISTA_ZASOBOW p on(p.PARENT_ID = d.ID)
  817. where z.ID = {$sqlIdAction}
  818. and p.`TYPE` = 'PARAM_IN'
  819. ");
  820. $flatDefinitionArgs = implode(";", array_map(function ($arg) {
  821. return "{$arg['ID']}={$arg['DESC']}";
  822. }, $definitionArgs));
  823. return [
  824. 'label' => DB::getPDO()->fetchValue(" select z.OPIS from CRM_LISTA_ZASOBOW z where z.ID = {$sqlIdAction} ") . " " .
  825. UI::h('i', [
  826. 'class' => "glyphicon glyphicon-pencil",
  827. 'style' => "cursor:pointer",
  828. 'onClick' => "return Storage__tableStruct__editActionLabel(this, {$sqlIdAction})"], ''),
  829. 'args' => implode("<br>&", array_map(function ($item) {
  830. return (NULL === $item['ALIAS_ID'])
  831. ? $item['DESC']
  832. : "{$item['DESC']}=" . '{$row["' . $item['ALIAS_DESC'] . '"]}';// TODO: add rmParam btn
  833. }, $args)) . " " .
  834. UI::h('i', [
  835. 'class' => "glyphicon glyphicon-plus-sign",
  836. 'style' => "cursor:pointer",
  837. 'title' => "Dodaj PARAM_IN",
  838. 'onClick' => "return Storage__tableStruct__addParamAction(this, {$sqlIdAction}, '{$flatDefinitionArgs}')"], ''),
  839. // 'args_info' => '<pre>' . var_export($args, true) . '</pre>',
  840. 'ID' => $item['ID'],
  841. 'DESC' => $item['DESC'],
  842. 'A_STATUS' => $item['A_STATUS'],
  843. 'definition args' => implode("", array_map(function ($item) {
  844. return '<div style="white-space:nowrap">' . "[{$item['ID']}] {$item['DESC']}" . '</div>';
  845. }, $definitionArgs)),
  846. ];
  847. }, $tableActions)
  848. ]);
  849. echo UI::h('button', [
  850. 'onClick'=>"Storage__tableStruct__addAction()",
  851. 'class'=>"btn btn-xs btn-default"
  852. ], "Dodaj Akcję");
  853. echo UI::h('link', ['rel'=>"stylesheet", 'type'=>"text/css", 'href'=>"static/sweetalert2.min.css"]);
  854. echo UI::h('script', ['src'=>"static/sweetalert2.min.js"]);
  855. echo UI::h('style', [], "
  856. .swal2-radio.p5-swal-radio-as-list { text-align:left }
  857. .swal2-radio.p5-swal-radio-as-list > label { display:block; margin-left:20px }
  858. ");
  859. UI::inlineJS(__FILE__ . '.tableActions.js', [
  860. 'ID_STORAGE' => $idStorage,
  861. 'TABLE_NAME' => $tblName,
  862. 'FETCH_URL' => Request::getPathUri() . 'index.php?_route=Storage&_task=fetchActionListAjax',
  863. 'ADD_ACTION_URL' => Request::getPathUri() . 'index.php?_route=Storage&_task=addActionAjax'
  864. ]);
  865. echo '<hr>';
  866. $ajaxAddBaseProcesLink = Request::getPathUri() . "index.php?_route=Storage&_task=addBaseProces&idStorage={$idStorage}&tblName={$tblName}";
  867. $onClick = "return p5UI__ButtonAjax(this, 'p5UIBtnAjax:Storage:addBaseProces', { href: '{$ajaxAddBaseProcesLink}' })";
  868. UI::tag('a', ['onclick'=>$onClick, 'class'=>"btn btn-xs btn-default", 'href'=>"#"], "Dodaj podstawowy proces dla tabeli '{$tblName}' - read only", true);
  869. echo UI::h('script', [], "
  870. jQuery(document).on('p5UIBtnAjax:Storage:addBaseProces:ajaxLoaded', function(e, n, payload) {
  871. jQuery.notify(payload.msg, payload.type);
  872. });
  873. ");
  874. } catch (Exception $e) {
  875. UI::alert('danger', "Error #" . $e->getCode() . "|" . $e->getLine() . ": " . $e->getMessage());
  876. }
  877. UI::dol();
  878. }
  879. public function fetchActionListAjaxAction() {
  880. Response::sendTryCatchJson(array($this, 'fetchActionListAjax'), $args = 'JSON_FROM_REQUEST_BODY');
  881. }
  882. public function fetchActionListAjax($args) {
  883. return [
  884. 'type' => 'success',
  885. '__args' => $args,
  886. 'options' => DB::getPDO()->fetchAll("
  887. select z.ID, z.`DESC`, z.OPIS
  888. from CRM_LISTA_ZASOBOW z
  889. where z.`TYPE` = 'URL_ACTION'
  890. and z.A_STATUS != 'DELETED'
  891. and z.ALIAS_ID = 0
  892. ")
  893. ];
  894. }
  895. public function addActionAjaxAction() {
  896. Response::sendTryCatchJson(array($this, 'addActionAjax'), $args = 'JSON_FROM_REQUEST_BODY');
  897. }
  898. public function addActionAjax($args) {
  899. $idStorage = V::get('idStorage', 0, $args, 'int');
  900. if ($idStorage <= 0) throw new Exception("Missing id storage");
  901. $idAction = V::get('idAction', 0, $args, 'int');
  902. if ($idAction <= 0) throw new Exception("Missing id action");
  903. $storageList = $this->getStorageList();
  904. if (empty($storageList)) throw new Exception("No storage defined");
  905. if (!array_key_exists($idStorage, $storageList)) throw new Exception("Storage not exists");
  906. $tblName = V::get('table', '', $args, 'word');
  907. if (empty($tblName)) throw new Exception("No table name");
  908. $storagePdo = DB::getStorage($idStorage);
  909. // $tblStruct = $storagePdo->getTableStruct($tblName);
  910. $idTable = $this->fetchTableId($idStorage, $tblName);
  911. if ($idTable <= 0) throw new Exception("Zasob tabela '{$tblName}' nie istnieje");
  912. $action = DB::getPDO()->fetchFirst("
  913. select z.ID, z.`DESC`, z.OPIS
  914. from CRM_LISTA_ZASOBOW z
  915. where z.ID = {$idAction}
  916. ");
  917. if (empty($action)) throw new Exception("Action '{$idAction}' not exists");
  918. $idInsertedAction = DB::getPDO()->insert('CRM_LISTA_ZASOBOW', [
  919. 'PARENT_ID' => $idTable,
  920. 'ALIAS_ID' => $idAction,
  921. 'TYPE' => 'URL_ACTION',
  922. 'DESC' => $action['DESC'],
  923. 'OPIS' => V::get('OPIS', $action['DESC'], $action),
  924. ]);
  925. if (!$idInsertedAction) throw new Exception("Nie udało się dodać akcji");
  926. try {
  927. DB::getPDO()->insert('CRM_LISTA_ZASOBOW_HIST', [
  928. 'ID_USERS2' => $idInsertedAction,
  929. 'PARENT_ID' => $idTable,
  930. 'ALIAS_ID' => $idAction,
  931. 'TYPE' => 'URL_ACTION',
  932. 'DESC' => $action['DESC'],
  933. 'OPIS' => V::get('OPIS', $action['DESC'], $action),
  934. ]);
  935. } catch (Exception $e) {
  936. DBG::log($e);
  937. }
  938. return [
  939. 'type' => 'success',
  940. 'msg' => "Dodano akcję - rekord nr {$idInsertedAction}",
  941. '__DBG__' => [
  942. '$args' => $args,
  943. '$idStorage' => $idStorage,
  944. '$tblName' => $tblName,
  945. // '$tblStruct' => $tblStruct,
  946. '$idTable' => $idTable,
  947. '$action' => $action,
  948. ]
  949. ];
  950. }
  951. public function addBaseProcesAction() {
  952. Response::sendTryCatchJson(array($this, 'addBaseProces'), $_REQUEST);
  953. }
  954. public function addBaseProces($args) {
  955. $return = [
  956. 'type' => 'error',
  957. 'msg' => 'todo: F.' . __FUNCTION__ . ' L.' . __LINE__,
  958. ];
  959. $idStorage = V::get('idStorage', 0, $args, 'int');
  960. if ($idStorage <= 0) throw new HttpException("Missing idStorage", 400);
  961. $storage = DB::getStorage($idStorage);
  962. $tblName = V::get('tblName', 0, $args, 'word');
  963. if (empty($tblName)) throw new HttpException("Missing tblName", 400);
  964. $tableStruct = $storage->getTableStruct($tblName);
  965. $return['$tableStruct'] = $tableStruct;
  966. $idTable = $this->fetchTableId($idStorage, $tblName);
  967. if ($idTable <= 0) {
  968. UI::alert('warning', "Zasob tabela '{$tblName}' nie istnieje");// TODO: add p5UI btn
  969. DBG::table("tblStruct", $tblStruct, __CLASS__, __FUNCTION__, __LINE__);
  970. throw new Exception("Zasob tabela '{$tblName}' nie istnieje");
  971. }
  972. $cellZasobList = array();
  973. foreach (DB::getPDO()->fetchAllByKey("
  974. select z.ID, z.`DESC`, z.A_STATUS
  975. from CRM_LISTA_ZASOBOW z
  976. where z.PARENT_ID = '{$idTable}'
  977. ", $key = 'DESC') as $ind => $row) {
  978. $cellZasobList[strtolower($ind)] = $row;
  979. }
  980. $return['$cellZasobList'] = $cellZasobList;
  981. $idProces = DB::getDB()->ADD_NEW_OBJ('CRM_PROCES', (object)[
  982. 'TYPE' => 'PROCES_INIT',
  983. 'DESC' => "Proces dla tabeli '{$tblName}'",
  984. ]);
  985. if (!$idProces) throw new Exception("DB ERROR - nie udało się dodać procesu");
  986. foreach ($cellZasobList as $loverName => $row) {
  987. DB::getDB()->ADD_NEW_OBJ('CRM_WSKAZNIK', (object)[
  988. 'ID_PROCES' => $idProces,
  989. 'ID_ZASOB' => $row['ID'],
  990. 'TYP' => 'P',
  991. 'ID_PRZYPADEK' => 2
  992. ]);
  993. }
  994. $return['type'] = 'success';
  995. $return['msg'] = "Utworzono proces {{$idProces}}";
  996. return $return;
  997. }
  998. public function addGeomEtykietaCellsAction() {
  999. Response::sendTryCatchJson(array($this, 'addGeomEtykietaCells'), $_REQUEST);
  1000. }
  1001. public function addGeomEtykietaCells($args) {
  1002. $return = [
  1003. 'type' => 'error',
  1004. 'msg' => 'todo: F.' . __FUNCTION__ . ' L.' . __LINE__,
  1005. ];
  1006. $return['_DBG_request'] = $args;
  1007. // idStorage: "36"
  1008. // tblName: "test_geom_linestring"
  1009. $idStorage = V::get('idStorage', 0, $args, 'int');
  1010. if ($idStorage <= 0) throw new HttpException("Missing idStorage", 400);
  1011. $storage = DB::getStorage($idStorage);
  1012. $tblName = V::get('tblName', 0, $args, 'word');
  1013. if (empty($tblName)) throw new HttpException("Missing tblName", 400);
  1014. $tableStruct = $storage->getTableStruct($tblName);
  1015. $return['_DBG_$tableStruct'] = $tableStruct;
  1016. if ('mysql' == DB::getPDO($idStorage)->getType()) {
  1017. $dbName = DB::getPDO($idStorage)->getDatabaseName();
  1018. $fixedTableName = DB::getPDO($idStorage)->fetchValue("
  1019. select t.TABLE_NAME
  1020. from `information_schema`.`TABLES` t
  1021. where t.TABLE_SCHEMA = '{$dbName}'
  1022. and t.TABLE_NAME LIKE '{$tblName}'
  1023. ");
  1024. $return['_DBG_sql_fix__$tblName'] = "
  1025. select t.TABLE_NAME
  1026. from `information_schema`.`TABLES` t
  1027. where t.TABLE_SCHEMA = '{$dbName}'
  1028. and t.TABLE_NAME LIKE '{$tblName}'
  1029. ";
  1030. if (empty($fixedTableName)) return $return;
  1031. if (empty($fixedTableName)) throw new HttpException("Database Error", 500);
  1032. $return['_DBG_$fixedTableName'] = $fixedTableName;
  1033. $tblName = $fixedTableName;
  1034. }
  1035. $return['_DBG_$tableStruct'] = $tableStruct;
  1036. $return['_DBG_has_field__etykieta_x'] = (null != V::geti('etykieta_x', null, $tableStruct));
  1037. $return['_DBG_has_field__etykieta_y'] = (null != V::geti('etykieta_y', null, $tableStruct));
  1038. $return['_DBG_has_field__etykieta_obrot'] = (null != V::geti('etykieta_obrot', null, $tableStruct));
  1039. if (!V::geti('etykieta_x', null, $tableStruct)) {
  1040. try {
  1041. DB::getPDO($idStorage)->exec("ALTER TABLE `{$tblName}_HIST` ADD `etykieta_x` varchar(16) DEFAULT 'N/S;'");
  1042. } catch (Exception $e) {
  1043. $return['__DBG_hist_errors__etykieta_x'] = $e->getMessage();
  1044. }
  1045. DB::getPDO($idStorage)->exec("ALTER TABLE `{$tblName}` ADD `etykieta_x` decimal(16,10) DEFAULT NULL COMMENT 'przesuniecie etykiety elementu w GIS'");
  1046. }
  1047. if (!V::geti('etykieta_y', null, $tableStruct)) {
  1048. try {
  1049. DB::getPDO($idStorage)->exec("ALTER TABLE `{$tblName}_HIST` ADD `etykieta_y` varchar(16) DEFAULT 'N/S;'");
  1050. } catch (Exception $e) {
  1051. $return['__DBG_hist_errors__etykieta_y'] = $e->getMessage();
  1052. }
  1053. DB::getPDO($idStorage)->exec("ALTER TABLE `{$tblName}` ADD `etykieta_y` decimal(16,10) DEFAULT NULL COMMENT 'przesuniecie etykiety elementu w GIS'");
  1054. }
  1055. if (!V::geti('etykieta_obrot', null, $tableStruct)) {
  1056. try {
  1057. DB::getPDO($idStorage)->exec("ALTER TABLE `{$tblName}_HIST` ADD `etykieta_obrot` varchar(16) DEFAULT 'N/S;'");
  1058. } catch (Exception $e) {
  1059. $return['__DBG_hist_errors__etykieta_obrot'] = $e->getMessage();
  1060. }
  1061. DB::getPDO($idStorage)->exec("ALTER TABLE `{$tblName}` ADD `etykieta_obrot` decimal(16,10) DEFAULT NULL");
  1062. }
  1063. return $return;
  1064. }
  1065. public function xsdAction() {
  1066. $idStorage = V::get('idStorage', 0, $_REQUEST, 'int');
  1067. $storage = DB::getStorage($idStorage);
  1068. $tableRealList = $storage->getTableList();
  1069. $srvName = $_SERVER['SERVER_NAME'];
  1070. $storageZasobId = $storage->getZasobId();
  1071. $objNs = "p5_{$storageZasobId}_{$tblName}";
  1072. $objNsUri = "https://biuro.biall-net.pl/api/{$storageZasobId}/{$tblName}";
  1073. $p5TypePrefix = "p5Type";
  1074. $p5TypeNsUri = "http://biuro.biall-net.pl/p5/schema/types";
  1075. $p5TypeNsLocation = "http://biuro.biall-net.pl/p5/schema/types.xsd";
  1076. header('Content-type: text/plain; charset=utf-8');// TODO: test
  1077. //header('Content-type: application/xml; charset=utf-8');
  1078. $xmlWriter = new XMLWriter();
  1079. $xmlWriter->openUri('php://output');
  1080. $xmlWriter->setIndent(true);
  1081. if (!$xmlWriter) throw new HttpException("Error no XMLWriter", 404);
  1082. $xmlWriter->startDocument('1.0', 'UTF-8');
  1083. $xmlWriter->startElement('xs:schema');
  1084. $xmlWriter->writeAttribute('xmlns:xs', 'http://www.w3.org/2001/XMLSchema');
  1085. $xmlWriter->writeAttribute('xmlns:vc', 'http://www.w3.org/2007/XMLSchema-versioning');
  1086. $xmlWriter->writeAttribute("xmlns:{$p5TypePrefix}", $p5TypeNsUri);
  1087. $xmlWriter->writeAttribute('elementFormDefault', 'qualified');
  1088. $xmlWriter->writeAttribute('targetNamespace', $objNsUri);
  1089. $xmlWriter->writeAttribute('vc:minVersion', '1.1');
  1090. $xmlWriter->startElement('xs:import');
  1091. $xmlWriter->writeAttribute('namespace', $p5TypeNsUri);
  1092. $xmlWriter->writeAttribute('schemaLocation', $p5TypeNsLocation);
  1093. $xmlWriter->endElement();// xs:import
  1094. foreach ($tableRealList as $tbl) {
  1095. $tblName = $tbl['table_name'];
  1096. $this->tableXsdViewXmlWriter($xmlWriter, $idStorage, $tblName);
  1097. }
  1098. $xmlWriter->endElement();// xs:schema
  1099. $xmlWriter->endDocument();
  1100. }
  1101. public function tableXsdAction() {
  1102. $idStorage = V::get('idStorage', '', $_GET);
  1103. $tblName = V::get('table', '', $_GET, 'word');
  1104. if (empty($tblName)) die("Wrong table name");
  1105. header('Content-type: text/plain; charset=utf-8');// TODO: test
  1106. $storage = DB::getStorage($idStorage);
  1107. $storageZasobId = $storage->getZasobId();
  1108. $objNs = "p5_{$storageZasobId}_{$tblName}";
  1109. $objNsUri = "https://biuro.biall-net.pl/api/{$storageZasobId}/{$tblName}";
  1110. $p5TypePrefix = "p5Type";
  1111. $p5TypeNsUri = "http://biuro.biall-net.pl/p5/schema/types";
  1112. $p5TypeNsLocation = "http://biuro.biall-net.pl/p5/schema/types.xsd";
  1113. //header('Content-type: application/xml; charset=utf-8');
  1114. $xmlWriter = new XMLWriter();
  1115. $xmlWriter->openUri('php://output');
  1116. $xmlWriter->setIndent(true);
  1117. if (!$xmlWriter) throw new HttpException("Error no XMLWriter", 404);
  1118. $xmlWriter->startDocument('1.0', 'UTF-8');
  1119. $xmlWriter->startElement('xs:schema');
  1120. $xmlWriter->writeAttribute('xmlns:xs', 'http://www.w3.org/2001/XMLSchema');
  1121. $xmlWriter->writeAttribute('xmlns:vc', 'http://www.w3.org/2007/XMLSchema-versioning');
  1122. $xmlWriter->writeAttribute("xmlns:{$p5TypePrefix}", $p5TypeNsUri);
  1123. $xmlWriter->writeAttribute('elementFormDefault', 'qualified');
  1124. $xmlWriter->writeAttribute('targetNamespace', $objNsUri);
  1125. $xmlWriter->writeAttribute('vc:minVersion', '1.1');
  1126. $xmlWriter->startElement('xs:import');
  1127. $xmlWriter->writeAttribute('namespace', $p5TypeNsUri);
  1128. $xmlWriter->writeAttribute('schemaLocation', $p5TypeNsLocation);
  1129. $xmlWriter->endElement();// xs:import
  1130. $this->tableXsdViewXmlWriter($xmlWriter, $idStorage, $tblName);
  1131. $xmlWriter->endElement();// xs:schema
  1132. $xmlWriter->endDocument();
  1133. }
  1134. public function tableXsdViewXmlWriter(&$xmlWriter, $idStorage, $tblName) {
  1135. $storage = DB::getStorage($idStorage);
  1136. $schema = Schema_TableFactory::build($tblName, $idStorage, $_SERVER['SERVER_NAME']);
  1137. $struct = $schema->getStruct();
  1138. DBG::_('DBG', '>1', "struct", $struct, __CLASS__, __FUNCTION__, __LINE__);
  1139. $typeName = "{$tblName}Type";
  1140. $xmlWriter->startElement('xs:complexType');
  1141. $xmlWriter->writeAttribute('name', $typeName);
  1142. $xmlWriter->startElement('xs:sequence');
  1143. foreach ($struct as $field) {
  1144. $xmlWriter->startElement('xs:element');
  1145. $xmlWriter->writeAttribute('name', $field['name']);
  1146. $xmlWriter->writeAttribute('minOccurs', 0);// TODO: set minOccurs by default, etc.
  1147. if ($field['is_nullable']) $xmlWriter->writeAttribute('nillable', 'true');
  1148. if (null !== $field['default_value']) {
  1149. $xmlWriter->writeAttribute('default', $field['default_value']);
  1150. } else if (null === $field['default_value'] && $field['is_nullable']) {
  1151. $xmlWriter->writeAttribute('default', $field['default_value']);
  1152. } else {
  1153. // TODO: Schema BUG?
  1154. }
  1155. if (empty($field['p5_restrictions'])) {
  1156. $xmlWriter->writeAttribute('type', "p5Type:{$field['p5_type']}");
  1157. } else {
  1158. $xmlWriter->startElement('xs:simpleType');
  1159. $xmlWriter->writeAttribute('base', "p5Type:{$field['p5_type']}");
  1160. $xmlWriter->startElement('xs:restriction');
  1161. if (!empty($field['p5_restrictions']['enumeration'])) {
  1162. foreach ($field['p5_restrictions']['enumeration'] as $enumValue) {
  1163. $xmlWriter->startElement('xs:enumeration');
  1164. $xmlWriter->writeAttribute('value', $enumValue);
  1165. $xmlWriter->endElement();// xs:enumeration
  1166. }
  1167. } else {
  1168. // TODO: another restrictions...
  1169. }
  1170. $xmlWriter->endElement();// xs:restriction
  1171. $xmlWriter->endElement();// xs:simpleType
  1172. }
  1173. $xmlWriter->endElement();// xs:element
  1174. }
  1175. $xmlWriter->endElement();// xs:sequence
  1176. $xmlWriter->endElement();// xs:complexType
  1177. return;
  1178. // <xs:element maxOccurs="1" minOccurs="0" name="{$fldName}" nillable="true" type="xs:integer"/>
  1179. $pKeyField = 'ID';//$storageObject->getPrimaryKeyFieldName();
  1180. //DBG::_(true, true, "struct", $struct, __CLASS__, __FUNCTION__, __LINE__);
  1181. foreach ($struct as $field) {
  1182. $fldName = $vField->getName();
  1183. $fldType = $vField->getType();
  1184. $xsdType = $fldType->getTypeForXsd();
  1185. if ($fldType->hasDefault()) {
  1186. $fldDefault = $fldType->getDefault();
  1187. if (!empty($fldDefault) || '0' === $fldDefault) {
  1188. $elNode->setAttribute('default', $fldDefault);
  1189. }
  1190. }
  1191. $fldRestrictions = $fldType->getRestrictions();
  1192. if (empty($fldRestrictions)) {
  1193. $elNode->setAttribute('type', "{$p5TypePrefix}:{$xsdType}");
  1194. } else {
  1195. $sType = $dom->createElementNS('http://www.w3.org/2001/XMLSchema', 'xs:simpleType');
  1196. $elNode->appendChild($sType);
  1197. $sTypeRes = $dom->createElementNS('http://www.w3.org/2001/XMLSchema', 'xs:restriction');
  1198. $sType->appendChild($sTypeRes);
  1199. $sTypeRes->setAttribute('base', "{$p5TypePrefix}:{$xsdType}");
  1200. $enumList = $fldType->getEnumeration();
  1201. if (empty($enumList)) {
  1202. foreach ($fldRestrictions as $restricionName => $restrictionValue) {
  1203. if ('maxLength' == $restricionName) {
  1204. $sTypeResMaxLength = $dom->createElementNS('http://www.w3.org/2001/XMLSchema', 'xs:maxLength');
  1205. $sTypeRes->appendChild($sTypeResMaxLength);
  1206. $sTypeResMaxLength->setAttribute('value', $restrictionValue);
  1207. } else if ('minLength' == $restricionName) {
  1208. $sTypeResMinLength = $dom->createElementNS('http://www.w3.org/2001/XMLSchema', 'xs:minLength');
  1209. $sTypeRes->appendChild($sTypeResMinLength);
  1210. $sTypeResMinLength->setAttribute('value', $restrictionValue);
  1211. } else if ('pattern' == $restricionName) {
  1212. $sTypeResPattern = $dom->createElementNS('http://www.w3.org/2001/XMLSchema', 'xs:pattern');
  1213. $sTypeRes->appendChild($sTypeResPattern);
  1214. $sTypeResPattern->setAttribute('value', $restrictionValue);
  1215. } else if ('fractionDigits' == $restricionName) {
  1216. $sTypeResFractionDigits = $dom->createElementNS('http://www.w3.org/2001/XMLSchema', 'xs:fractionDigits');
  1217. $sTypeRes->appendChild($sTypeResFractionDigits);
  1218. $sTypeResFractionDigits->setAttribute('value', $restrictionValue);
  1219. } else if ('totalDigits' == $restricionName) {
  1220. $sTypeResTotalDigits = $dom->createElementNS('http://www.w3.org/2001/XMLSchema', 'xs:totalDigits');
  1221. $sTypeRes->appendChild($sTypeResTotalDigits);
  1222. $sTypeResTotalDigits->setAttribute('value', $restrictionValue);
  1223. } else if ('maxExclusive' == $restricionName) {
  1224. $sTypeResMaxExclusive = $dom->createElementNS('http://www.w3.org/2001/XMLSchema', 'xs:maxExclusive');
  1225. $sTypeRes->appendChild($sTypeResMaxExclusive);
  1226. $sTypeResMaxExclusive->setAttribute('value', $restrictionValue);
  1227. } else if ('minExclusive' == $restricionName) {
  1228. $sTypeResMinExclusive = $dom->createElementNS('http://www.w3.org/2001/XMLSchema', 'xs:minExclusive');
  1229. $sTypeRes->appendChild($sTypeResMinExclusive);
  1230. $sTypeResMinExclusive->setAttribute('value', $restrictionValue);
  1231. } else if ('maxInclusive' == $restricionName) {
  1232. $sTypeResMaxInclusive = $dom->createElementNS('http://www.w3.org/2001/XMLSchema', 'xs:maxInclusive');
  1233. $sTypeRes->appendChild($sTypeResMaxInclusive);
  1234. $sTypeResMaxInclusive->setAttribute('value', $restrictionValue);
  1235. } else if ('minInclusive' == $restricionName) {
  1236. $sTypeResMinInclusive = $dom->createElementNS('http://www.w3.org/2001/XMLSchema', 'xs:minInclusive');
  1237. $sTypeRes->appendChild($sTypeResMinInclusive);
  1238. $sTypeResMinInclusive->setAttribute('value', $restrictionValue);
  1239. }
  1240. /* TODO: xsd restrictions:
  1241. enumeration Defines a list of acceptable values
  1242. fractionDigits Specifies the maximum number of decimal places allowed. Must be equal to or greater than zero
  1243. length Specifies the exact number of characters or list items allowed. Must be equal to or greater than zero
  1244. maxExclusive Specifies the upper bounds for numeric values (the value must be less than this value)
  1245. maxInclusive Specifies the upper bounds for numeric values (the value must be less than or equal to this value)
  1246. maxLength Specifies the maximum number of characters or list items allowed. Must be equal to or greater than zero
  1247. minExclusive Specifies the lower bounds for numeric values (the value must be greater than this value)
  1248. minInclusive Specifies the lower bounds for numeric values (the value must be greater than or equal to this value)
  1249. minLength Specifies the minimum number of characters or list items allowed. Must be equal to or greater than zero
  1250. pattern Defines the exact sequence of characters that are acceptable
  1251. totalDigits Specifies the exact number of digits allowed. Must be greater than zero
  1252. whiteSpace Specifies how white space (line feeds, tabs, spaces, and carriage returns) is handled
  1253. */
  1254. }
  1255. } else {
  1256. foreach ($enumList as $enumValue) {
  1257. $sTypeResEnum = $dom->createElementNS('http://www.w3.org/2001/XMLSchema', 'xs:enumeration');
  1258. $sTypeRes->appendChild($sTypeResEnum);
  1259. $sTypeResEnum->setAttribute('value', $enumValue);
  1260. }
  1261. }
  1262. }
  1263. }
  1264. $elNode = $dom->createElementNS('http://www.w3.org/2001/XMLSchema', 'xs:element');
  1265. $rootNode->appendChild($elNode);
  1266. $elNode->setAttribute('name', $tblName);
  1267. $elNode->setAttribute('type', "{$objNs}:{$typeName}");
  1268. header('Content-type: application/xml');
  1269. echo $dom->saveXML();
  1270. exit;
  1271. }
  1272. public function navView() {
  1273. $backLabel = 'back';
  1274. $backLink = 'index.php?_route=Storage';
  1275. $backDisabled = true;
  1276. $currentLabel = 'Storage';
  1277. $currentLink = 'index.php?_route=Storage';
  1278. if ($task = V::get('_task', '', $_REQUEST)) {
  1279. $currentLink = "index.php?_route=Storage&_task={$task}";
  1280. $backDisabled = false;
  1281. $idStorage = V::get('idStorage', 0, $_REQUEST, 'int');
  1282. $tblName = V::get('table', '', $_REQUEST, 'word');
  1283. $objName = V::get('object', '', $_REQUEST, 'word');
  1284. $namespace = V::get('namespace', '', $_REQUEST, 'word');
  1285. switch ($task) {
  1286. case 'obejctList':
  1287. case 'tableList':
  1288. case 'viewList':
  1289. case 'rawInfo':
  1290. $backLabel = 'Storage';
  1291. $backLink = $this->getLink();
  1292. $currentLink = $this->getLink($task, ['idStorage' => $idStorage]);
  1293. break;
  1294. case 'tableStruct':
  1295. $backLabel = "Tabele [{$idStorage}]";
  1296. $backLink = $this->getLink('tableList', ['idStorage' => $idStorage]);
  1297. $currentLink = $this->getLink($task, ['idStorage' => $idStorage, 'table' => $tblName]);
  1298. break;
  1299. case 'objectStruct':
  1300. $backLabel = "Obiekty [{$idStorage}]";
  1301. $backLink = $this->getLink('tableList', ['idStorage' => $idStorage]);// TODO: mv tableList to objectList
  1302. $currentLink = $this->getLink($task, ['idStorage' => $idStorage, 'namespace' => $namespace]);
  1303. break;
  1304. case 'coreObjectStruct':
  1305. $backLabel = "Obiekty podstawowe";
  1306. $backLink = $this->getLink('coreObjectList', ['idStorage' => $idStorage]);
  1307. $currentLink = $this->getLink($task, ['idStorage' => $idStorage, 'object' => $objName]);
  1308. break;
  1309. }
  1310. switch ($task) {
  1311. case 'tableList': $currentLabel = "Tabele [{$idStorage}]"; break;
  1312. case 'viewList': $currentLabel = "Widoki [{$idStorage}]"; break;
  1313. case 'rawInfo': $currentLabel = "Raw info [{$idStorage}]"; break;
  1314. case 'tableStruct': $currentLabel = "Struktura tabeli '{$tblName}'"; break;
  1315. case 'objectStruct': $currentLabel = "Obiekt '{$namespace}'"; break;
  1316. case 'coreObjectList': $currentLabel = "Obiekty podstawowe"; break;
  1317. case 'coreObjectStruct': $currentLabel = "Obiekt '{$objName}'"; break;
  1318. case 'objectList': $currentLabel = "Obiekty z aktualnej domeny"; break;// TODO: domain from $_GET
  1319. }
  1320. }
  1321. echo UI::h('nav', ['class'=>"navbar navbar-default navbar-static-top", 'style'=>"z-index:999"], [
  1322. UI::h('div', ['class'=>"container-fluid"], [
  1323. UI::h('div', ['class'=>"navbar-left"], [
  1324. UI::h('ul', ['class'=>"nav navbar-nav navbar-center"], [
  1325. UI::h('li', [], [
  1326. UI::h('a', ['href'=>$backLink, 'class'=>"btn" . ($backDisabled ? ' disabled' : '')], '<i class="glyphicon glyphicon-chevron-left"></i> ' . $backLabel)
  1327. ])
  1328. ])
  1329. ]),
  1330. UI::h('div', ['class'=>"navbar-left"], [
  1331. UI::h('ul', ['class'=>"nav navbar-nav navbar-center"], [
  1332. UI::h('li', [], [
  1333. UI::h('a', ['href'=>$currentLink, 'class'=>"btn"], $currentLabel)
  1334. ])
  1335. ])
  1336. ]),
  1337. UI::h('div', ['class'=>"navbar-right"], [
  1338. // <ul class="nav navbar-nav navbar-right">
  1339. // <li><a href="#">Link</a></li>
  1340. // <li class="dropdown"><a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false">Dropdown <span class="caret"></span></a>
  1341. // <ul class="dropdown-menu">
  1342. // <li><a href="#">Action</a></li>
  1343. // <li><a href="#">Another action</a></li>
  1344. // <li><a href="#">Something else here</a></li>
  1345. // <li role="separator" class="divider"></li>
  1346. // <li><a href="#">Separated link</a></li>
  1347. // </ul>
  1348. // </li>
  1349. // </ul>
  1350. ])
  1351. ])
  1352. ]);
  1353. }
  1354. public function getStorageList() {
  1355. $storageList = array();
  1356. $sth = DB::getPDO()->prepare("
  1357. select z.ID, z.`DESC`, z.`TYPE`
  1358. from CRM_LISTA_ZASOBOW z
  1359. where z.TYPE in('BAZA_DANYCH','DATABASE_MYSQL','DATABASE_POSTGRESQL')
  1360. ");
  1361. $sth->execute();
  1362. $rows = $sth->fetchAll();
  1363. foreach ($rows as $row) {
  1364. $storageList[$row['ID']] = $row;
  1365. }
  1366. return $storageList;
  1367. }
  1368. public function addAclObjectToZasobyAction() {// sends JSON
  1369. $response = new stdClass();
  1370. try {
  1371. $idStorage = V::get('idStorage', '', $_GET);
  1372. $namespace = V::get('namespace', '', $_GET);
  1373. if (empty($idStorage)) throw new HttpException("Missing idStorage param");
  1374. if (empty($namespace)) throw new HttpException("Missing namespace param");
  1375. $objectStorage = SchemaFactory::loadDefaultObject('SystemObject');
  1376. $items = $objectStorage->getItems([
  1377. 'f_namespace' => "={$namespace}",
  1378. ]);
  1379. if (empty($items)) throw new Exception("SystemObject '{$namespace}' not found");
  1380. $objectItem = reset($items);
  1381. if (empty($objectItem)) throw new Exception("SystemObject '{$namespace}' not found");
  1382. DBG::log($objectItem, 'array', 'object acl $objectItem');
  1383. if ($objectItem['idZasob'] > 0) {
  1384. // TODO: check if realy exists? @see SchemaFactory::loadDefaultObject('SystemObject')::updateCache()
  1385. $response->_replaceButtonNode = "[{$objectItem['idZasob']}]";
  1386. throw new AlertInfoException("Zasob '{$objectItem['namespace']}' już istnieje - nr '{$objectItem['idZasob']}'");
  1387. }
  1388. $idZasobFound = 0;
  1389. switch ($objectItem['_type']) {
  1390. case 'TableAcl': $idZasobFound = DB::getPDO()->fetchValue(" select ID from CRM_LISTA_ZASOBOW where PARENT_ID = {$objectItem['idDatabase']} and `DESC` = '{$objectItem['name']}' "); break;
  1391. case 'AntAcl': $idZasobFound = DB::getPDO()->fetchValue(" select ID from CRM_LISTA_ZASOBOW where PARENT_ID = {$objectItem['idDatabase']} and `DESC` = '{$objectItem['namespace']}' "); break;
  1392. default: throw new Exception("Not implemented acl type '{$objectItem['_type']}'");
  1393. }
  1394. if ($idZasobFound > 0) {
  1395. DB::getPDO()->update($objectStorage->_rootTableName, 'namespace', $objectItem['namespace'], [
  1396. 'idZasob' => $idZasobFound
  1397. ]);
  1398. $response->id = $idZasobFound;
  1399. throw new AlertSuccessException("Zasob '{$objectItem['namespace']}' już istnieje - nr '{$idZasobFound}' - cache zaktualizowany");
  1400. }
  1401. try {
  1402. $acl = User::getAcl()->getObjectAcl('default_db', 'crm_lista_zasobow');
  1403. } catch (Exception $e) {
  1404. DBG::log($e);
  1405. throw new Exception("Brak dostępu do tabeli Zasoby");
  1406. }
  1407. if (empty($objectItem['idDatabase'])) throw new Exception("Missing database id");
  1408. if ($idStorage != $objectItem['idDatabase']) throw new Exception("Database id must be the same");
  1409. if (empty($objectItem['_rootTableName'])) throw new Exception("Missing root table name");
  1410. switch ($objectItem['_type']) {
  1411. case 'TableAcl':
  1412. $newZasobItem = [
  1413. 'PARENT_ID' => $objectItem['idDatabase'],
  1414. 'TYPE' => 'TABELA',
  1415. 'DESC' => $objectItem['_rootTableName'],
  1416. 'DESC_PL' => $objectItem['name'],
  1417. ];
  1418. break;
  1419. case 'AntAcl':
  1420. $newZasobItem = [
  1421. 'PARENT_ID' => $objectItem['idDatabase'],
  1422. 'TYPE' => 'TABELA',
  1423. 'DESC' => $objectItem['namespace'],
  1424. 'DESC_PL' => $objectItem['name'],
  1425. ];
  1426. break;
  1427. default: throw new Exception("Not implemented acl type '{$objectItem['_type']}'");
  1428. }
  1429. $idCreated = $acl->addItem($newZasobItem);
  1430. if (!$idCreated) throw new Exception("Nie udało się utworzyć nowego rekordu!");
  1431. try {
  1432. DB::getPDO()->update($objectStorage->_rootTableName, 'namespace', $objectItem['namespace'], [
  1433. 'idZasob' => $idCreated
  1434. ]);
  1435. } catch (Exception $e) {
  1436. DBG::log($e);
  1437. }
  1438. $response->id = $idCreated;
  1439. $response->record = $acl->getItem($idCreated);
  1440. $response->_replaceButtonNode = "[{$idCreated}]";
  1441. throw new AlertSuccessException("Utworzono pomyślnie rekord nr {$idCreated}");
  1442. } catch (AlertSuccessException $e) {
  1443. $response->type = 'success';
  1444. $response->msg = $e->getMessage();
  1445. } catch (AlertInfoException $e) {
  1446. $response->type = 'info';
  1447. $response->msg = $e->getMessage();
  1448. } catch (Exception $e) {
  1449. $response->type = 'error';
  1450. $response->msg = $e->getMessage();
  1451. DBG::log($e);
  1452. }
  1453. Response::sendJsonExit($response);
  1454. }
  1455. public function addFieldToZasobyAction() {
  1456. DBG::log($_REQUEST, 'array', '$_REQUEST');
  1457. Response::sendTryCatchJson(array($this, 'addFieldToZasoby'), $_REQUEST);
  1458. }
  1459. public function addFieldToZasoby($args) {
  1460. $namespace = V::get('namespace', '', $args);
  1461. if (empty($namespace)) throw new HttpException("Missing namespace");
  1462. $fieldItem = SchemaFactory::loadDefaultObject('SystemObjectField')->getItem($namespace);
  1463. $zasobTableName = substr($fieldItem['objectNamespace'], strlen('default_db/'));
  1464. $zasobTableName = (false !== strpos($zasobTableName, '/'))
  1465. ? $fieldItem['objectNamespace']
  1466. : $zasobTableName;
  1467. $zasobItem = DB::getPDO()->fetchFirst("
  1468. select zField.ID, zField.`DESC`, zField.`TYPE`, zField.PARENT_ID
  1469. from CRM_LISTA_ZASOBOW as zField
  1470. join CRM_LISTA_ZASOBOW as zTable on(zTable.ID = zField.PARENT_ID)
  1471. where zTable.PARENT_ID = {$fieldItem['idDatabase']}
  1472. and zTable.`DESC` = '{$zasobTableName}'
  1473. and zTable.`TYPE` = 'TABELA'
  1474. and zField.`DESC` = '{$fieldItem['fieldNamespace']}'
  1475. and zField.`TYPE` = 'KOMORKA'
  1476. ");
  1477. if ($zasobItem) {
  1478. SchemaFactory::loadDefaultObject('SystemObjectField')->updateItem([
  1479. 'namespace' => $namespace,
  1480. 'idZasob' => $zasobItem['ID']
  1481. ]);
  1482. return [
  1483. 'type' => 'success',
  1484. 'msg' => "Zasob już istnieje",
  1485. 'data' => [
  1486. 'id' => $zasobItem['ID']
  1487. ],
  1488. '__DBG__' => [
  1489. $zasobItem,
  1490. $fieldItem,
  1491. $args,
  1492. ]
  1493. ];
  1494. }
  1495. return [
  1496. 'type' => 'success',
  1497. 'msg' => "TODO: addFieldToZasoby",
  1498. 'data' => [
  1499. 'id' => 123
  1500. ],
  1501. '__DBG__' => [
  1502. $zasobItem,
  1503. $fieldItem,
  1504. $args,
  1505. ]
  1506. ];
  1507. // throw new Exception("TODO: F.addFieldToZasoby");
  1508. return [
  1509. 'type' => 'success',
  1510. 'msg' => "TODO: addFieldToZasoby",
  1511. 'data' => [
  1512. 'id' => 123
  1513. ],
  1514. '__DBG__args' => $args
  1515. ];
  1516. }
  1517. public function addCellToZasobyAction() {// sends JSON
  1518. $response = new stdClass();
  1519. try {
  1520. $idStorage = V::get('storageId', '', $_GET);
  1521. $tblName = V::get('tblName', '', $_GET, 'word');
  1522. $cellName = V::get('cellName', '', $_GET, 'word');
  1523. if (empty($tblName)) throw new HttpException("Wrong table name");
  1524. if (empty($tblName)) throw new HttpException("Wrong cell name");
  1525. $storage = DB::getStorage($idStorage);
  1526. $tableStruct = $storage->getTableStruct($tblName);
  1527. $zasobStorageId = $storage->getZasobId();
  1528. if (!is_numeric($zasobStorageId)) throw new HttpException("Storage id is not set in config file");
  1529. $idTable = $this->fetchTableId($zasobStorageId, $tblName);
  1530. if ($idTable <= 0) throw new Exception("Zasob tabela '{$tblName}' nie istnieje");
  1531. try {
  1532. $acl = User::getAcl()->getObjectAcl('default_db', 'crm_lista_zasobow');
  1533. } catch (Exception $e) {
  1534. throw new Exception("Brak dostępu do tabeli Zasoby");
  1535. }
  1536. $item = array();
  1537. $item['PARENT_ID'] = $idTable;
  1538. $item['TYPE'] = 'KOMORKA';
  1539. $item['DESC'] = $cellName;
  1540. $item['DESC_PL'] = $cellName;
  1541. if (DBG::isActive()) $response->_itemToCreate = $item;
  1542. $createdId = $acl->addItem($item);
  1543. if (!$createdId) throw new Exception("Nie udało się utworzyć nowego rekordu!");
  1544. $response->id = $createdId;
  1545. $response->record = $acl->getItem($createdId);
  1546. $response->_replaceButtonNode = "[{$createdId}]";
  1547. throw new AlertSuccessException("Utworzono pomyślnie rekord nr {$createdId}");
  1548. } catch (AlertSuccessException $e) {
  1549. $response->type = 'success';
  1550. $response->msg = $e->getMessage();
  1551. } catch (AlertInfoException $e) {
  1552. $response->type = 'info';
  1553. $response->msg = $e->getMessage();
  1554. } catch (Exception $e) {
  1555. $response->type = 'error';
  1556. $response->msg = $e->getMessage();
  1557. }
  1558. Response::sendJsonExit($response);
  1559. }
  1560. public function fetchTableId($idZasobStorage, $tblName) {
  1561. $rows = DB::getPDO()->fetchAll("
  1562. select z.`ID`, z.`DESC`
  1563. from `CRM_LISTA_ZASOBOW` z
  1564. where z.`PARENT_ID`='{$idZasobStorage}'
  1565. and z.`DESC`='{$tblName}'
  1566. and z.`A_STATUS` in('NORMAL','WAITING')
  1567. ");
  1568. if (!empty($rows)) return (int)$rows[0]['ID'];
  1569. return null;
  1570. }
  1571. public function systemObjectsStructAction() {
  1572. UI::gora();
  1573. UI::menu();
  1574. $this->navView();
  1575. try {
  1576. throw new Exception("TODO: F." . __FUNCTION__ . ' L.' . __LINE__);
  1577. // $coreObjlist = OBJXSD::getSystemObjectsStruct();
  1578. // $objectList = array();
  1579. // foreach ($coreObjlist as $objName) {
  1580. // $objItem = array();
  1581. // $objItem['name'] = $objName;
  1582. // $objItem['struktura'] = '<a href="index.php?_route=Storage&_task=systemObjectsStruct&object=' . $objName . '">' . "struct" . '</a>';
  1583. // // $objItem['label'] = "";// TODO: read from json
  1584. // $objectList[] = $objItem;
  1585. // }
  1586. // usort($objectList, function($rowA, $rowB) {
  1587. // $a = $rowA['nazwa']; $b = $rowB['nazwa'];
  1588. // if ($a == $b) return 0;
  1589. // return ($a < $b) ? -1 : 1;
  1590. // });
  1591. //
  1592. // DBG::table("objectList", $objectList, __CLASS__, __FUNCTION__, __LINE__);
  1593. } catch (Exception $e) {
  1594. UI::alert('danger', "Error #" . $e->getCode() . "|" . $e->getLine() . ": " . $e->getMessage());
  1595. }
  1596. UI::dol();
  1597. }
  1598. public function systemObjectsAction() {// TableAjax view: index.php?_route=ViewTableAjax&namespace=default_objects/SystemObject
  1599. UI::gora();
  1600. UI::menu();
  1601. $this->navView();
  1602. try {
  1603. Lib::loadClass('Schema_SystemObjectStorageAcl');
  1604. $acl = new Schema_SystemObjectStorageAcl();
  1605. UI::table([
  1606. 'rows' => array_map(
  1607. function ($item) {
  1608. return [
  1609. 'ns' => $item['namespace'],
  1610. 'nazwa' => $item['name'],
  1611. 'type' => $item['_type'],
  1612. 'edit' => '<a href="index.php?_route=ViewTableAjax&namespace=' . $item['namespace'] . '">edit</a>',
  1613. 'wfs Describe' => '<a href="wfs-data.php/default_db/?SERVICE=WFS&VERSION=1.0.0&SRSNAME=EPSG:3003&REQUEST=DescribeFeatureType&TYPENAME=' . $item['typeName'] . '">DescribeFeatureType</a>',
  1614. 'wfs getFeature' => '<a href="wfs-data.php/default_db/?SERVICE=WFS&VERSION=1.0.0&SRSNAME=EPSG:3003&REQUEST=GetFeature&TYPENAME=' . $item['typeName'] . '&MAXFEATURES=10">GetFeature</a> (max:10)'
  1615. ];
  1616. }
  1617. , $acl->getItems([
  1618. 'order_by' => 'namespace',
  1619. 'order_dir' => 'asc'
  1620. ])
  1621. )
  1622. ]);
  1623. } catch (Exception $e) {
  1624. UI::alert('danger', "Error #" . $e->getCode() . "|" . $e->getLine() . ": " . $e->getMessage());
  1625. DBG::log($e);
  1626. }
  1627. UI::dol();
  1628. }
  1629. public function objectReinstallAction() {
  1630. UI::gora();
  1631. UI::startContainer();
  1632. try {
  1633. $namespace = V::get('namespace', '', $_GET);
  1634. if (empty($namespace)) throw new Exception("Missing param namespace");
  1635. echo UI::h('h3', [], $namespace);
  1636. Lib::loadClass('Schema_SystemObjectFieldStorageAcl');
  1637. $objFieldAcl = new Schema_SystemObjectFieldStorageAcl();
  1638. $objFieldAcl->updateCache($namespace);
  1639. } catch (Exception $e) {
  1640. UI::alert('danger', "Error #" . $e->getCode() . "|" . $e->getLine() . ": " . $e->getMessage());
  1641. DBG::log($e);
  1642. }
  1643. UI::endContainer();
  1644. UI::dol();
  1645. }
  1646. }