Storage.php 68 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762
  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::nicePrint($sourceItem, '$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. $objectStorage->updateCache();
  516. UI::alert('info', "Lista obiketów zaktualizowana");
  517. }
  518. if ('1' == V::get('refreshObjectList', '', $_POST)) {
  519. $objectStorage->updateCache();
  520. UI::alert('info', "Lista obiketów zaktualizowana");
  521. }
  522. UI::table([
  523. 'caption' => "Obiekty w bazie '{$sourceItem['name']}' " .
  524. UI::hButtonPost('<i class="glyphicon glyphicon-refresh"></i>' . " odśwież", [
  525. 'class' => "btn btn-xs btn-link",
  526. 'data' => [
  527. 'refreshObjectList' => '1'
  528. ]
  529. ]),
  530. 'rows' => array_map(function ($item) use ($idStorage) {
  531. $addToZasobyLink = $this->getLink('addTableToZasoby', ['idStorage' => $idStorage, 'tblName' => $item['name']]);
  532. return [
  533. 'nazwa' => $item['name'],
  534. '_type' => $item['_type'], // TODO: editable?
  535. 'Nr zasobu' => ($item['idZasob'] > 0)
  536. ? $item['idZasob']
  537. : UI::h('button', [
  538. 'class' => "btn btn-xs btn-primary",
  539. 'onClick' => "return p5UI__ButtonAjax(this, 'p5UIBtnAjax:Storage:addTableToZasoby', { href: '{$addToZasobyLink}' })"
  540. ], "Dodaj do Zasobów"),
  541. // 'opis' => $item['description'],
  542. 'active?' => ($item['isActive']) ? '<span class="label label-success">TAK</span>' : '<span class="text text-muted">nie</span>',
  543. 'struktura' => UI::h('a', [ 'href' => $this->getLink('tableStruct', [ 'idStorage' => $idStorage, 'table' => $item['name'] ]) ], "struktura"),
  544. 'raw info' => UI::h('a', [ 'href' => $this->getLink('rawInfo', [ 'idStorage' => $idStorage, 'table' => $item['name'] ]) ], "raw info"),
  545. // 'xsd' => UI::h('a', [ 'href' => $this->getLink('xsd', [ 'idStorage' => $idStorage ]) ], "xsd"),
  546. ];
  547. }, $objectStorage->getItems([
  548. '#refFrom' => [
  549. 'namespace' => 'default_objects/SystemSource',
  550. 'primaryKey' => $sourceItem['idZasob']
  551. ]
  552. ]))
  553. ]);
  554. echo UI::h('script', [], "
  555. jQuery(document).on('p5UIBtnAjax:Storage:addTableToZasoby:click', function(e, n, payload) {
  556. console.log('event p5UIBtnAjax:Storage:addTableToZasoby:click', n, payload);
  557. });
  558. jQuery(document).on('p5UIBtnAjax:Storage:addTableToZasoby:ajaxLoaded', function(e, n, payload) {
  559. console.log('event p5UIBtnAjax:Storage:addTableToZasoby:ajaxLoaded', n, payload);
  560. if ('success' == payload.type && payload.body && payload.body.id > 0) {
  561. jQuery(n).parents('td').text(payload.body.id);
  562. }
  563. jQuery.notify(payload.msg, payload.type);
  564. });
  565. ");
  566. return;
  567. echo '<hr>';
  568. $storagePdo = DB::getStorage($idStorage);
  569. $viewRealList = $storagePdo->getViewList();
  570. $tableRealList = $storagePdo->getTableList();
  571. $tableZasobList = array();
  572. foreach (DB::getPDO()->fetchAllByKey("
  573. select z.ID, z.`DESC`, z.A_STATUS
  574. from CRM_LISTA_ZASOBOW z
  575. where z.PARENT_ID = '{$idStorage}'
  576. ", $key = 'DESC') as $ind => $row) {
  577. $tableZasobList[strtolower($ind)] = $row;
  578. }
  579. $emptyItem = array();
  580. $emptyItem['nazwa'] = '';
  581. $emptyItem['type'] = '';
  582. $emptyItem['id_zasob'] = '';
  583. $emptyItem['struktura'] = '';
  584. $emptyItem['objectTest'] = '';
  585. $emptyItem['xsd'] = '';
  586. $emptyItem['isHist'] = '';
  587. $emptyItem['uwagi'] = '';
  588. $tableList = array();
  589. foreach ($tableRealList as $row) {
  590. $tblName = $row['table_name'];
  591. $tblItem = V::cloneArray($emptyItem);
  592. $tblItem['nazwa'] = $tblName;
  593. $tblItem['type'] = $row['table_type'];
  594. $tblItem['struktura'] = '<a href="index.php?_route=Storage&_task=tableStruct&idStorage=' . $idStorage . '&table=' . $tblName . '">' . "struct" . '</a>';
  595. $tblItem['xsd'] = '<a href="index.php?_route=Storage&_task=tableXsd&idStorage=' . $idStorage . '&table=' . $tblName . '" target="_blank">' . "xsd" . '</a>';
  596. $tblItem['objectTest'] = '<a href="index.php?_route=Storage&_task=objectTest&idStorage=' . $idStorage . '&table=' . $tblName . '">' . "objectTest" . '</a>';
  597. $tblItem['isHist'] = ('_hist' == substr($tblName, -5));
  598. $tblItem['uwagi'] = '';
  599. $tblZasob = V::get($tblName, '', $tableZasobList);
  600. if ($tblZasob) {
  601. $tableZasobList[$tblName]['_checked'] = true;
  602. $tblItem['id_zasob'] = $tblZasob['ID'];
  603. } else {
  604. $tblItem['uwagi'] .= 'TODO: ADD ZASOB';
  605. $ajaxAddZasobLink = Request::getPathUri() . "index.php?_route=Storage&_task=addTableToZasoby&idStorage={$idStorage}&tblName={$tblName}";
  606. $onClick = "return p5UI__ButtonAjax(this, 'p5UIBtnAjax:Storage:addTableToZasoby', { href: '{$ajaxAddZasobLink}' })";
  607. $tblItem['id_zasob'] = '<a onclick="'.$onClick.'" class="btn btn-xs btn-primary" href="#">TODO: ADD ZASOB</a>';
  608. }
  609. $tableList[] = $tblItem;
  610. }
  611. foreach ($viewRealList as $row) {
  612. $tblName = $row['table_name'];
  613. $tblItem = V::cloneArray($emptyItem);
  614. $tblItem['nazwa'] = $tblName;
  615. $tblItem['type'] = $row['table_type'];
  616. $tblItem['struktura'] = '<a href="index.php?_route=Storage&_task=tableStruct&idStorage=' . $idStorage . '&table=' . $tblName . '">' . "struct" . '</a>';
  617. $tblItem['uwagi'] = '';
  618. $tblZasob = V::get($tblName, '', $tableZasobList);
  619. if ($tblZasob) {
  620. $tableZasobList[$tblName]['_checked'] = true;
  621. $tblItem['id_zasob'] = $tblZasob['ID'];
  622. } else {
  623. $tblItem['uwagi'] .= 'TODO: ADD ZASOB';
  624. $tblItem['id_zasob'] = 'TODO: ADD ZASOB';
  625. }
  626. $tableList[] = $tblItem;
  627. }
  628. foreach ($tableZasobList as $tblName => $row) {
  629. if (!$row['_checked']) {
  630. $tblItem = V::cloneArray($emptyItem);
  631. $tblItem['nazwa'] = $tblName;
  632. $tblItem['id_zasob'] = $row['ID'];
  633. $tblItem['type'] = 'unknown';
  634. $tblItem['uwagi'] = 'TODO: nie istnieje w bazie danych';
  635. $tableList[] = $tblItem;
  636. }
  637. }
  638. usort($tableList, function($rowA, $rowB) {
  639. $a = $rowA['nazwa']; $b = $rowB['nazwa'];
  640. if ($a == $b) return 0;
  641. $a1 = substr($a, 0, 1); $b1 = substr($b, 0, 1);
  642. if (('_' == $a1 || '_' == $b1) && $a1 != $b1) {
  643. return ($a1 < $b1) ? 1 : -1;
  644. }
  645. return ($a < $b) ? -1 : 1;
  646. });
  647. DBG::table("tableList", $tableList, __CLASS__, __FUNCTION__, __LINE__);
  648. ?>
  649. <script>
  650. jQuery(document).on('p5UIBtnAjax:Storage:addTableToZasoby:click', function(e, n, payload) {
  651. console.log('event p5UIBtnAjax:Storage:addTableToZasoby:click', n, payload);
  652. });
  653. jQuery(document).on('p5UIBtnAjax:Storage:addTableToZasoby:ajaxLoaded', function(e, n, payload) {
  654. console.log('event p5UIBtnAjax:Storage:addTableToZasoby:ajaxLoaded', n, payload);
  655. if ('success' == payload.type && payload.body && payload.body.id > 0) {
  656. jQuery(n).parents('td').text(payload.body.id);
  657. }
  658. jQuery.notify(payload.msg, payload.type);
  659. });
  660. </script>
  661. <?php
  662. } catch (Exception $e) {
  663. UI::alert('danger', "Error #" . $e->getCode() . "|" . $e->getLine() . ": " . $e->getMessage());
  664. }
  665. UI::endContainer();
  666. UI::dol();
  667. }
  668. public function rawInfoAction() {
  669. UI::gora();
  670. UI::menu();
  671. $this->navView();
  672. try {
  673. $idStorage = V::get('idStorage', 0, $_REQUEST, 'int');
  674. if (empty($idStorage)) throw new Exception("Missing id storage");
  675. $storageList = $this->getStorageList();
  676. if (empty($storageList)) throw new Exception("No storage defined");
  677. if (!array_key_exists($idStorage, $storageList)) throw new Exception("Storage not exists");
  678. $storagePdo = DB::getStorage($idStorage);
  679. $rawInfo = $storagePdo->getTableListWithInfo();
  680. DBG::table("rawInfo", $rawInfo, __CLASS__, __FUNCTION__, __LINE__);
  681. } catch (Exception $e) {
  682. UI::alert('danger', "Error #" . $e->getCode() . "|" . $e->getLine() . ": " . $e->getMessage());
  683. }
  684. UI::dol();
  685. }
  686. public function tableStructAction() {
  687. UI::gora();
  688. UI::menu();
  689. $this->navView();
  690. try {
  691. $idStorage = V::get('idStorage', 0, $_REQUEST, 'int');
  692. if (empty($idStorage)) throw new Exception("Missing id storage");
  693. $storageList = $this->getStorageList();
  694. if (empty($storageList)) throw new Exception("No storage defined");
  695. if (!array_key_exists($idStorage, $storageList)) throw new Exception("Storage not exists");
  696. $tblName = V::get('table', '', $_REQUEST, 'word');
  697. if (empty($tblName)) throw new Exception("No table name");
  698. $storagePdo = DB::getStorage($idStorage);
  699. $tblStruct = $storagePdo->getTableStruct($tblName);
  700. $idTable = $this->fetchTableId($idStorage, $tblName);
  701. if ($idTable <= 0) {
  702. UI::alert('warning', "Zasob tabela '{$tblName}' nie istnieje");// TODO: add p5UI btn
  703. DBG::table("tblStruct", $tblStruct, __CLASS__, __FUNCTION__, __LINE__);
  704. throw new Exception("Zasob tabela '{$tblName}' nie istnieje");
  705. }
  706. $cellZasobList = array();
  707. foreach (DB::getPDO()->fetchAllByKey("
  708. select z.ID, z.`DESC`, z.`TYPE` as ZASOB_TYPE, z.A_STATUS
  709. from CRM_LISTA_ZASOBOW z
  710. where z.PARENT_ID = '{$idTable}'
  711. ", $key = 'DESC') as $ind => $row) {
  712. $cellZasobList[strtolower($ind)] = $row;
  713. }
  714. $emptyItem = array();
  715. $emptyItem['name'] = '';
  716. $emptyItem['id_zasob'] = '';
  717. $emptyItem['zasob_type'] = '';
  718. $emptyItem['uwagi'] = '';
  719. $emptyItem['type'] = '';
  720. $emptyItem['is_nullable'] = '';
  721. $emptyItem['default_value'] = '';
  722. $emptyItem['default_is_null'] = '';
  723. $emptyItem['max_length'] = '';
  724. $emptyItem['num_precision'] = '';
  725. $emptyItem['num_scale'] = '';
  726. $emptyItem['char_encoding'] = '';
  727. $emptyItem['char_collation'] = '';
  728. $emptyItem['extra'] = '';
  729. $emptyItem['raw_storage_type'] = '';
  730. $tableList = array();
  731. foreach ($tblStruct as $row) {
  732. $cellName = $row['name'];
  733. $tblItem = V::cloneArray($emptyItem);
  734. $tblItem['name'] = $cellName;
  735. foreach ($row as $fldName => $fldVal) {
  736. if (array_key_exists($fldName, $tblItem)) $tblItem[$fldName] = $fldVal;
  737. }
  738. $tblItem['uwagi'] = '';
  739. $lowerCellName = strtolower($cellName);
  740. $tblZasob = V::get($lowerCellName, '', $cellZasobList);
  741. if ($tblZasob) {
  742. $cellZasobList[$lowerCellName]['_checked'] = true;
  743. $tblItem['id_zasob'] = $tblZasob['ID'];
  744. $tblItem['zasob_type'] = $tblZasob['ZASOB_TYPE'];
  745. } else {
  746. $tblItem['uwagi'] .= '!Zasob';//'TODO: ADD ZASOB';
  747. $ajaxAddZasobLink = Request::getPathUri() . "index.php?_route=Storage&_task=addCellToZasoby&idStorage={$idStorage}&tblName={$tblName}&cellName={$cellName}";
  748. $onClick = "return p5UI__ButtonAjax(this, 'p5UIBtnAjax:Storage:addCellToZasoby', { href: '{$ajaxAddZasobLink}' })";
  749. $tblItem['id_zasob'] = '<a onclick="'.$onClick.'" class="btn btn-xs btn-primary" href="#">TODO: ADD ZASOB</a>';
  750. }
  751. $tableList[] = $tblItem;
  752. }
  753. foreach ($cellZasobList as $cellName => $row) {
  754. if ('URL_ACTION' == $row['ZASOB_TYPE']) continue;
  755. if (!$row['_checked']) {
  756. $tblItem = V::cloneArray($emptyItem);
  757. $tblItem['name'] = $cellName;
  758. $tblItem['id_zasob'] = $row['ID'];
  759. $tblItem['zasob_type'] = $row['ZASOB_TYPE'];
  760. $tblItem['uwagi'] = '!DB';//'TODO: nie istnieje w bazie danych';
  761. $tableList[] = $tblItem;
  762. }
  763. }
  764. usort($tableList, function($rowA, $rowB) {
  765. $a = $rowA['name']; $b = $rowB['name'];
  766. if ('ID' == $a) return -1;
  767. if ('ID' == $b) return 1;
  768. if ($a == $b) return 0;
  769. $a1 = substr($a, 0, 1); $b1 = substr($b, 0, 1);
  770. if (('_' == $a1 || '_' == $b1) && $a1 != $b1) {
  771. return ($a1 < $b1) ? 1 : -1;
  772. }
  773. return ($a < $b) ? -1 : 1;
  774. });
  775. UI::table([
  776. 'caption' => UI::h('span', [], [
  777. "Komórki [{$idTable}] ",
  778. UI::h('a', [
  779. 'href' => "index.php?_route=ViewTableAjax&namespace=default_db/{$tblName}",
  780. 'class' => "btn btn-md btn-link"
  781. ], "Przeglądaj tabelę"),
  782. UI::h('a', [
  783. 'href' => "procesy5.php?task=CRM_LISTA_ZASOBOW&filtr_id={$idTable}&filtr_ids=%2B&filtr_ob=%2B",
  784. 'class' => "btn btn-md btn-link",
  785. 'title' => "Struktura aktualnie przeglądanej tabeli"
  786. ], "Zasoby"),
  787. UI::h('a', [
  788. 'href' => "index.php?FUNCTION_INIT=PROCES_MENU&HEADER_NOT_INIT=YES&_task=PROCES_FOR_TABLE&tblId={$idTable}",
  789. 'class' => "btn btn-md btn-link",
  790. 'title' => "Procesy dla aktualnie przeglądanej tabeli"
  791. ], "Procesy"),
  792. ]),
  793. 'cols' => array_keys($emptyItem),
  794. 'rows' => $tableList
  795. ]);
  796. echo UI::h('script', [], "
  797. jQuery(document).on('p5UIBtnAjax:Storage:addCellToZasoby:click', function(e, n, payload) {
  798. console.log('event p5UIBtnAjax:Storage:addCellToZasoby:click', n, payload);
  799. });
  800. jQuery(document).on('p5UIBtnAjax:Storage:addCellToZasoby:ajaxLoaded', function(e, n, payload) {
  801. console.log('event p5UIBtnAjax:Storage:addCellToZasoby:ajaxLoaded', n, payload);
  802. if ('success' == payload.type && payload.body && payload.body.id > 0) {
  803. var cellUwagiJQNode = jQuery(n).parents('td').next('td');
  804. cellUwagiJQNode.text(cellUwagiJQNode.text().replace('!Zasob', ''))
  805. jQuery(n).parents('td').text(payload.body.id);
  806. jQuery(n).remove();
  807. }
  808. jQuery.notify(payload.msg, payload.type);
  809. });
  810. ");
  811. $ajaxAddZasobLink = Request::getPathUri() . "index.php?_route=Storage&_task=addGeomEtykietaCells&idStorage={$idStorage}&tblName={$tblName}";
  812. $onClick = "return p5UI__ButtonAjax(this, 'p5UIBtnAjax:Storage:addGeomEtykietaCells', { href: '{$ajaxAddZasobLink}' })";
  813. UI::tag('a', ['onclick'=>$onClick, 'class'=>"btn btn-xs btn-default", 'href'=>"#"], "Dodaj komórki etykiet", true);
  814. echo "<i>(<code>`etykieta_x`</code>, <code>`etykieta_y`</code>, <code>`etykieta_obrot`</code>)</i>";
  815. echo UI::h('script', [], "
  816. jQuery(document).on('p5UIBtnAjax:Storage:addGeomEtykietaCells:ajaxLoaded', function(e, n, payload) {
  817. console.log('event p5UIBtnAjax:Storage:addGeomEtykietaCells:ajaxLoaded', n, payload);
  818. if ('success' == payload.type && payload.body && payload.body.id > 0) {
  819. var cellUwagiJQNode = jQuery(n).parents('td').next('td');
  820. cellUwagiJQNode.text(cellUwagiJQNode.text().replace('!Zasob', ''))
  821. jQuery(n).parents('td').text(payload.body.id);
  822. jQuery(n).remove();
  823. }
  824. jQuery.notify(payload.msg, payload.type);
  825. });
  826. ");
  827. $tableActions = array_filter($cellZasobList, function ($row) {
  828. return ('URL_ACTION' == $row['ZASOB_TYPE']);
  829. });
  830. UI::table([
  831. 'caption' => "tableActions",
  832. // 'cols' => array_keys($emptyItem),
  833. 'rows' => array_map(function ($item) {
  834. $sqlIdAction = DB::getPDO()->quote($item['ID'], PDO::PARAM_INT);
  835. $args = DB::getPDO()->fetchAll("
  836. select z.`DESC`
  837. , a.ID as ALIAS_ID, a.`DESC` as ALIAS_DESC, a.OPIS as ALIAS_OPIS
  838. from CRM_LISTA_ZASOBOW z
  839. left join CRM_LISTA_ZASOBOW a on(a.ID = z.ALIAS_ID)
  840. where z.PARENT_ID = {$sqlIdAction}
  841. and z.`TYPE` = 'PARAM_IN'
  842. ");
  843. $definitionArgs = DB::getPDO()->fetchAll("
  844. select p.ID, p.`DESC`
  845. from CRM_LISTA_ZASOBOW z
  846. join CRM_LISTA_ZASOBOW d on(d.ID = z.ALIAS_ID)
  847. left join CRM_LISTA_ZASOBOW p on(p.PARENT_ID = d.ID)
  848. where z.ID = {$sqlIdAction}
  849. and p.`TYPE` = 'PARAM_IN'
  850. ");
  851. $flatDefinitionArgs = implode(";", array_map(function ($arg) {
  852. return "{$arg['ID']}={$arg['DESC']}";
  853. }, $definitionArgs));
  854. return [
  855. 'label' => DB::getPDO()->fetchValue(" select z.OPIS from CRM_LISTA_ZASOBOW z where z.ID = {$sqlIdAction} ") . " " .
  856. UI::h('i', [
  857. 'class' => "glyphicon glyphicon-pencil",
  858. 'style' => "cursor:pointer",
  859. 'onClick' => "return Storage__tableStruct__editActionLabel(this, {$sqlIdAction})"], ''),
  860. 'args' => implode("<br>&", array_map(function ($item) {
  861. return (NULL === $item['ALIAS_ID'])
  862. ? $item['DESC']
  863. : "{$item['DESC']}=" . '{$row["' . $item['ALIAS_DESC'] . '"]}';// TODO: add rmParam btn
  864. }, $args)) . " " .
  865. UI::h('i', [
  866. 'class' => "glyphicon glyphicon-plus-sign",
  867. 'style' => "cursor:pointer",
  868. 'title' => "Dodaj PARAM_IN",
  869. 'onClick' => "return Storage__tableStruct__addParamAction(this, {$sqlIdAction}, '{$flatDefinitionArgs}')"], ''),
  870. // 'args_info' => '<pre>' . var_export($args, true) . '</pre>',
  871. 'ID' => $item['ID'],
  872. 'DESC' => $item['DESC'],
  873. 'A_STATUS' => $item['A_STATUS'],
  874. 'definition args' => implode("", array_map(function ($item) {
  875. return '<div style="white-space:nowrap">' . "[{$item['ID']}] {$item['DESC']}" . '</div>';
  876. }, $definitionArgs)),
  877. ];
  878. }, $tableActions)
  879. ]);
  880. echo UI::h('button', [
  881. 'onClick'=>"Storage__tableStruct__addAction()",
  882. 'class'=>"btn btn-xs btn-default"
  883. ], "Dodaj Akcję");
  884. echo UI::h('link', ['rel'=>"stylesheet", 'type'=>"text/css", 'href'=>"static/sweetalert2.min.css"]);
  885. echo UI::h('script', ['src'=>"static/sweetalert2.min.js"]);
  886. echo UI::h('style', [], "
  887. .swal2-radio.p5-swal-radio-as-list { text-align:left }
  888. .swal2-radio.p5-swal-radio-as-list > label { display:block; margin-left:20px }
  889. ");
  890. UI::inlineJS(__FILE__ . '.tableActions.js', [
  891. 'ID_STORAGE' => $idStorage,
  892. 'TABLE_NAME' => $tblName,
  893. 'FETCH_URL' => Request::getPathUri() . 'index.php?_route=Storage&_task=fetchActionListAjax',
  894. 'ADD_ACTION_URL' => Request::getPathUri() . 'index.php?_route=Storage&_task=addActionAjax'
  895. ]);
  896. echo '<hr>';
  897. $ajaxAddBaseProcesLink = Request::getPathUri() . "index.php?_route=Storage&_task=addBaseProces&idStorage={$idStorage}&tblName={$tblName}";
  898. $onClick = "return p5UI__ButtonAjax(this, 'p5UIBtnAjax:Storage:addBaseProces', { href: '{$ajaxAddBaseProcesLink}' })";
  899. UI::tag('a', ['onclick'=>$onClick, 'class'=>"btn btn-xs btn-default", 'href'=>"#"], "Dodaj podstawowy proces dla tabeli '{$tblName}' - read only", true);
  900. echo UI::h('script', [], "
  901. jQuery(document).on('p5UIBtnAjax:Storage:addBaseProces:ajaxLoaded', function(e, n, payload) {
  902. jQuery.notify(payload.msg, payload.type);
  903. });
  904. ");
  905. } catch (Exception $e) {
  906. UI::alert('danger', "Error #" . $e->getCode() . "|" . $e->getLine() . ": " . $e->getMessage());
  907. }
  908. UI::dol();
  909. }
  910. public function fetchActionListAjaxAction() {
  911. Response::sendTryCatchJson(array($this, 'fetchActionListAjax'), $args = 'JSON_FROM_REQUEST_BODY');
  912. }
  913. public function fetchActionListAjax($args) {
  914. return [
  915. 'type' => 'success',
  916. '__args' => $args,
  917. 'options' => DB::getPDO()->fetchAll("
  918. select z.ID, z.`DESC`, z.OPIS
  919. from CRM_LISTA_ZASOBOW z
  920. where z.`TYPE` = 'URL_ACTION'
  921. and z.A_STATUS != 'DELETED'
  922. and z.ALIAS_ID = 0
  923. ")
  924. ];
  925. }
  926. public function addActionAjaxAction() {
  927. Response::sendTryCatchJson(array($this, 'addActionAjax'), $args = 'JSON_FROM_REQUEST_BODY');
  928. }
  929. public function addActionAjax($args) {
  930. $idStorage = V::get('idStorage', 0, $args, 'int');
  931. if ($idStorage <= 0) throw new Exception("Missing id storage");
  932. $idAction = V::get('idAction', 0, $args, 'int');
  933. if ($idAction <= 0) throw new Exception("Missing id action");
  934. $storageList = $this->getStorageList();
  935. if (empty($storageList)) throw new Exception("No storage defined");
  936. if (!array_key_exists($idStorage, $storageList)) throw new Exception("Storage not exists");
  937. $tblName = V::get('table', '', $args, 'word');
  938. if (empty($tblName)) throw new Exception("No table name");
  939. $storagePdo = DB::getStorage($idStorage);
  940. // $tblStruct = $storagePdo->getTableStruct($tblName);
  941. $idTable = $this->fetchTableId($idStorage, $tblName);
  942. if ($idTable <= 0) throw new Exception("Zasob tabela '{$tblName}' nie istnieje");
  943. $action = DB::getPDO()->fetchFirst("
  944. select z.ID, z.`DESC`, z.OPIS
  945. from CRM_LISTA_ZASOBOW z
  946. where z.ID = {$idAction}
  947. ");
  948. if (empty($action)) throw new Exception("Action '{$idAction}' not exists");
  949. $idInsertedAction = DB::getPDO()->insert('CRM_LISTA_ZASOBOW', [
  950. 'PARENT_ID' => $idTable,
  951. 'ALIAS_ID' => $idAction,
  952. 'TYPE' => 'URL_ACTION',
  953. 'DESC' => $action['DESC'],
  954. 'OPIS' => V::get('OPIS', $action['DESC'], $action),
  955. ]);
  956. if (!$idInsertedAction) throw new Exception("Nie udało się dodać akcji");
  957. try {
  958. DB::getPDO()->insert('CRM_LISTA_ZASOBOW_HIST', [
  959. 'ID_USERS2' => $idInsertedAction,
  960. 'PARENT_ID' => $idTable,
  961. 'ALIAS_ID' => $idAction,
  962. 'TYPE' => 'URL_ACTION',
  963. 'DESC' => $action['DESC'],
  964. 'OPIS' => V::get('OPIS', $action['DESC'], $action),
  965. ]);
  966. } catch (Exception $e) {
  967. DBG::log($e);
  968. }
  969. return [
  970. 'type' => 'success',
  971. 'msg' => "Dodano akcję - rekord nr {$idInsertedAction}",
  972. '__DBG__' => [
  973. '$args' => $args,
  974. '$idStorage' => $idStorage,
  975. '$tblName' => $tblName,
  976. // '$tblStruct' => $tblStruct,
  977. '$idTable' => $idTable,
  978. '$action' => $action,
  979. ]
  980. ];
  981. }
  982. public function addBaseProcesAction() {
  983. Response::sendTryCatchJson(array($this, 'addBaseProces'), $_REQUEST);
  984. }
  985. public function addBaseProces($args) {
  986. $return = [
  987. 'type' => 'error',
  988. 'msg' => 'todo: F.' . __FUNCTION__ . ' L.' . __LINE__,
  989. ];
  990. $idStorage = V::get('idStorage', 0, $args, 'int');
  991. if ($idStorage <= 0) throw new HttpException("Missing idStorage", 400);
  992. $storage = DB::getStorage($idStorage);
  993. $tblName = V::get('tblName', 0, $args, 'word');
  994. if (empty($tblName)) throw new HttpException("Missing tblName", 400);
  995. $tableStruct = $storage->getTableStruct($tblName);
  996. $return['$tableStruct'] = $tableStruct;
  997. $idTable = $this->fetchTableId($idStorage, $tblName);
  998. if ($idTable <= 0) {
  999. UI::alert('warning', "Zasob tabela '{$tblName}' nie istnieje");// TODO: add p5UI btn
  1000. DBG::table("tblStruct", $tblStruct, __CLASS__, __FUNCTION__, __LINE__);
  1001. throw new Exception("Zasob tabela '{$tblName}' nie istnieje");
  1002. }
  1003. $cellZasobList = array();
  1004. foreach (DB::getPDO()->fetchAllByKey("
  1005. select z.ID, z.`DESC`, z.A_STATUS
  1006. from CRM_LISTA_ZASOBOW z
  1007. where z.PARENT_ID = '{$idTable}'
  1008. ", $key = 'DESC') as $ind => $row) {
  1009. $cellZasobList[strtolower($ind)] = $row;
  1010. }
  1011. $return['$cellZasobList'] = $cellZasobList;
  1012. $idProces = DB::getDB()->ADD_NEW_OBJ('CRM_PROCES', (object)[
  1013. 'TYPE' => 'PROCES_INIT',
  1014. 'DESC' => "Proces dla tabeli '{$tblName}'",
  1015. ]);
  1016. if (!$idProces) throw new Exception("DB ERROR - nie udało się dodać procesu");
  1017. foreach ($cellZasobList as $loverName => $row) {
  1018. DB::getDB()->ADD_NEW_OBJ('CRM_WSKAZNIK', (object)[
  1019. 'ID_PROCES' => $idProces,
  1020. 'ID_ZASOB' => $row['ID'],
  1021. 'TYP' => 'P',
  1022. 'ID_PRZYPADEK' => 2
  1023. ]);
  1024. }
  1025. $return['type'] = 'success';
  1026. $return['msg'] = "Utworzono proces {{$idProces}}";
  1027. return $return;
  1028. }
  1029. public function addGeomEtykietaCellsAction() {
  1030. Response::sendTryCatchJson(array($this, 'addGeomEtykietaCells'), $_REQUEST);
  1031. }
  1032. public function addGeomEtykietaCells($args) {
  1033. $return = [
  1034. 'type' => 'error',
  1035. 'msg' => 'todo: F.' . __FUNCTION__ . ' L.' . __LINE__,
  1036. ];
  1037. $return['_DBG_request'] = $args;
  1038. // idStorage: "36"
  1039. // tblName: "test_geom_linestring"
  1040. $idStorage = V::get('idStorage', 0, $args, 'int');
  1041. if ($idStorage <= 0) throw new HttpException("Missing idStorage", 400);
  1042. $storage = DB::getStorage($idStorage);
  1043. $tblName = V::get('tblName', 0, $args, 'word');
  1044. if (empty($tblName)) throw new HttpException("Missing tblName", 400);
  1045. $tableStruct = $storage->getTableStruct($tblName);
  1046. $return['_DBG_$tableStruct'] = $tableStruct;
  1047. if ('mysql' == DB::getPDO($idStorage)->getType()) {
  1048. $dbName = DB::getPDO($idStorage)->getDatabaseName();
  1049. $fixedTableName = DB::getPDO($idStorage)->fetchValue("
  1050. select t.TABLE_NAME
  1051. from `information_schema`.`TABLES` t
  1052. where t.TABLE_SCHEMA = '{$dbName}'
  1053. and t.TABLE_NAME LIKE '{$tblName}'
  1054. ");
  1055. $return['_DBG_sql_fix__$tblName'] = "
  1056. select t.TABLE_NAME
  1057. from `information_schema`.`TABLES` t
  1058. where t.TABLE_SCHEMA = '{$dbName}'
  1059. and t.TABLE_NAME LIKE '{$tblName}'
  1060. ";
  1061. if (empty($fixedTableName)) return $return;
  1062. if (empty($fixedTableName)) throw new HttpException("Database Error", 500);
  1063. $return['_DBG_$fixedTableName'] = $fixedTableName;
  1064. $tblName = $fixedTableName;
  1065. }
  1066. $return['_DBG_$tableStruct'] = $tableStruct;
  1067. $return['_DBG_has_field__etykieta_x'] = (null != V::geti('etykieta_x', null, $tableStruct));
  1068. $return['_DBG_has_field__etykieta_y'] = (null != V::geti('etykieta_y', null, $tableStruct));
  1069. $return['_DBG_has_field__etykieta_obrot'] = (null != V::geti('etykieta_obrot', null, $tableStruct));
  1070. if (!V::geti('etykieta_x', null, $tableStruct)) {
  1071. try {
  1072. DB::getPDO($idStorage)->exec("ALTER TABLE `{$tblName}_HIST` ADD `etykieta_x` varchar(16) DEFAULT 'N/S;'");
  1073. } catch (Exception $e) {
  1074. $return['__DBG_hist_errors__etykieta_x'] = $e->getMessage();
  1075. }
  1076. DB::getPDO($idStorage)->exec("ALTER TABLE `{$tblName}` ADD `etykieta_x` decimal(16,10) DEFAULT NULL COMMENT 'przesuniecie etykiety elementu w GIS'");
  1077. }
  1078. if (!V::geti('etykieta_y', null, $tableStruct)) {
  1079. try {
  1080. DB::getPDO($idStorage)->exec("ALTER TABLE `{$tblName}_HIST` ADD `etykieta_y` varchar(16) DEFAULT 'N/S;'");
  1081. } catch (Exception $e) {
  1082. $return['__DBG_hist_errors__etykieta_y'] = $e->getMessage();
  1083. }
  1084. DB::getPDO($idStorage)->exec("ALTER TABLE `{$tblName}` ADD `etykieta_y` decimal(16,10) DEFAULT NULL COMMENT 'przesuniecie etykiety elementu w GIS'");
  1085. }
  1086. if (!V::geti('etykieta_obrot', null, $tableStruct)) {
  1087. try {
  1088. DB::getPDO($idStorage)->exec("ALTER TABLE `{$tblName}_HIST` ADD `etykieta_obrot` varchar(16) DEFAULT 'N/S;'");
  1089. } catch (Exception $e) {
  1090. $return['__DBG_hist_errors__etykieta_obrot'] = $e->getMessage();
  1091. }
  1092. DB::getPDO($idStorage)->exec("ALTER TABLE `{$tblName}` ADD `etykieta_obrot` decimal(16,10) DEFAULT NULL");
  1093. }
  1094. return $return;
  1095. }
  1096. public function xsdAction() {
  1097. $idStorage = V::get('idStorage', 0, $_REQUEST, 'int');
  1098. $storage = DB::getStorage($idStorage);
  1099. $tableRealList = $storage->getTableList();
  1100. $srvName = $_SERVER['SERVER_NAME'];
  1101. $storageZasobId = $storage->getZasobId();
  1102. $objNs = "p5_{$storageZasobId}_{$tblName}";
  1103. $objNsUri = "https://biuro.biall-net.pl/api/{$storageZasobId}/{$tblName}";
  1104. $p5TypePrefix = "p5Type";
  1105. $p5TypeNsUri = "http://biuro.biall-net.pl/p5/schema/types";
  1106. $p5TypeNsLocation = "http://biuro.biall-net.pl/p5/schema/types.xsd";
  1107. header('Content-type: text/plain; charset=utf-8');// TODO: test
  1108. //header('Content-type: application/xml; charset=utf-8');
  1109. $xmlWriter = new XMLWriter();
  1110. $xmlWriter->openUri('php://output');
  1111. $xmlWriter->setIndent(true);
  1112. if (!$xmlWriter) throw new HttpException("Error no XMLWriter", 404);
  1113. $xmlWriter->startDocument('1.0', 'UTF-8');
  1114. $xmlWriter->startElement('xs:schema');
  1115. $xmlWriter->writeAttribute('xmlns:xs', 'http://www.w3.org/2001/XMLSchema');
  1116. $xmlWriter->writeAttribute('xmlns:vc', 'http://www.w3.org/2007/XMLSchema-versioning');
  1117. $xmlWriter->writeAttribute("xmlns:{$p5TypePrefix}", $p5TypeNsUri);
  1118. $xmlWriter->writeAttribute('elementFormDefault', 'qualified');
  1119. $xmlWriter->writeAttribute('targetNamespace', $objNsUri);
  1120. $xmlWriter->writeAttribute('vc:minVersion', '1.1');
  1121. $xmlWriter->startElement('xs:import');
  1122. $xmlWriter->writeAttribute('namespace', $p5TypeNsUri);
  1123. $xmlWriter->writeAttribute('schemaLocation', $p5TypeNsLocation);
  1124. $xmlWriter->endElement();// xs:import
  1125. foreach ($tableRealList as $tbl) {
  1126. $tblName = $tbl['table_name'];
  1127. $this->tableXsdViewXmlWriter($xmlWriter, $idStorage, $tblName);
  1128. }
  1129. $xmlWriter->endElement();// xs:schema
  1130. $xmlWriter->endDocument();
  1131. }
  1132. public function tableXsdAction() {
  1133. $idStorage = V::get('idStorage', '', $_GET);
  1134. $tblName = V::get('table', '', $_GET, 'word');
  1135. if (empty($tblName)) die("Wrong table name");
  1136. header('Content-type: text/plain; charset=utf-8');// TODO: test
  1137. $storage = DB::getStorage($idStorage);
  1138. $storageZasobId = $storage->getZasobId();
  1139. $objNs = "p5_{$storageZasobId}_{$tblName}";
  1140. $objNsUri = "https://biuro.biall-net.pl/api/{$storageZasobId}/{$tblName}";
  1141. $p5TypePrefix = "p5Type";
  1142. $p5TypeNsUri = "http://biuro.biall-net.pl/p5/schema/types";
  1143. $p5TypeNsLocation = "http://biuro.biall-net.pl/p5/schema/types.xsd";
  1144. //header('Content-type: application/xml; charset=utf-8');
  1145. $xmlWriter = new XMLWriter();
  1146. $xmlWriter->openUri('php://output');
  1147. $xmlWriter->setIndent(true);
  1148. if (!$xmlWriter) throw new HttpException("Error no XMLWriter", 404);
  1149. $xmlWriter->startDocument('1.0', 'UTF-8');
  1150. $xmlWriter->startElement('xs:schema');
  1151. $xmlWriter->writeAttribute('xmlns:xs', 'http://www.w3.org/2001/XMLSchema');
  1152. $xmlWriter->writeAttribute('xmlns:vc', 'http://www.w3.org/2007/XMLSchema-versioning');
  1153. $xmlWriter->writeAttribute("xmlns:{$p5TypePrefix}", $p5TypeNsUri);
  1154. $xmlWriter->writeAttribute('elementFormDefault', 'qualified');
  1155. $xmlWriter->writeAttribute('targetNamespace', $objNsUri);
  1156. $xmlWriter->writeAttribute('vc:minVersion', '1.1');
  1157. $xmlWriter->startElement('xs:import');
  1158. $xmlWriter->writeAttribute('namespace', $p5TypeNsUri);
  1159. $xmlWriter->writeAttribute('schemaLocation', $p5TypeNsLocation);
  1160. $xmlWriter->endElement();// xs:import
  1161. $this->tableXsdViewXmlWriter($xmlWriter, $idStorage, $tblName);
  1162. $xmlWriter->endElement();// xs:schema
  1163. $xmlWriter->endDocument();
  1164. }
  1165. public function tableXsdViewXmlWriter(&$xmlWriter, $idStorage, $tblName) {
  1166. $storage = DB::getStorage($idStorage);
  1167. $schema = Schema_TableFactory::build($tblName, $idStorage, $_SERVER['SERVER_NAME']);
  1168. $struct = $schema->getStruct();
  1169. DBG::_('DBG', '>1', "struct", $struct, __CLASS__, __FUNCTION__, __LINE__);
  1170. $typeName = "{$tblName}Type";
  1171. $xmlWriter->startElement('xs:complexType');
  1172. $xmlWriter->writeAttribute('name', $typeName);
  1173. $xmlWriter->startElement('xs:sequence');
  1174. foreach ($struct as $field) {
  1175. $xmlWriter->startElement('xs:element');
  1176. $xmlWriter->writeAttribute('name', $field['name']);
  1177. $xmlWriter->writeAttribute('minOccurs', 0);// TODO: set minOccurs by default, etc.
  1178. if ($field['is_nullable']) $xmlWriter->writeAttribute('nillable', 'true');
  1179. if (null !== $field['default_value']) {
  1180. $xmlWriter->writeAttribute('default', $field['default_value']);
  1181. } else if (null === $field['default_value'] && $field['is_nullable']) {
  1182. $xmlWriter->writeAttribute('default', $field['default_value']);
  1183. } else {
  1184. // TODO: Schema BUG?
  1185. }
  1186. if (empty($field['p5_restrictions'])) {
  1187. $xmlWriter->writeAttribute('type', "p5Type:{$field['p5_type']}");
  1188. } else {
  1189. $xmlWriter->startElement('xs:simpleType');
  1190. $xmlWriter->writeAttribute('base', "p5Type:{$field['p5_type']}");
  1191. $xmlWriter->startElement('xs:restriction');
  1192. if (!empty($field['p5_restrictions']['enumeration'])) {
  1193. foreach ($field['p5_restrictions']['enumeration'] as $enumValue) {
  1194. $xmlWriter->startElement('xs:enumeration');
  1195. $xmlWriter->writeAttribute('value', $enumValue);
  1196. $xmlWriter->endElement();// xs:enumeration
  1197. }
  1198. } else {
  1199. // TODO: another restrictions...
  1200. }
  1201. $xmlWriter->endElement();// xs:restriction
  1202. $xmlWriter->endElement();// xs:simpleType
  1203. }
  1204. $xmlWriter->endElement();// xs:element
  1205. }
  1206. $xmlWriter->endElement();// xs:sequence
  1207. $xmlWriter->endElement();// xs:complexType
  1208. return;
  1209. // <xs:element maxOccurs="1" minOccurs="0" name="{$fldName}" nillable="true" type="xs:integer"/>
  1210. $pKeyField = 'ID';//$storageObject->getPrimaryKeyFieldName();
  1211. //DBG::_(true, true, "struct", $struct, __CLASS__, __FUNCTION__, __LINE__);
  1212. foreach ($struct as $field) {
  1213. $fldName = $vField->getName();
  1214. $fldType = $vField->getType();
  1215. $xsdType = $fldType->getTypeForXsd();
  1216. if ($fldType->hasDefault()) {
  1217. $fldDefault = $fldType->getDefault();
  1218. if (!empty($fldDefault) || '0' === $fldDefault) {
  1219. $elNode->setAttribute('default', $fldDefault);
  1220. }
  1221. }
  1222. $fldRestrictions = $fldType->getRestrictions();
  1223. if (empty($fldRestrictions)) {
  1224. $elNode->setAttribute('type', "{$p5TypePrefix}:{$xsdType}");
  1225. } else {
  1226. $sType = $dom->createElementNS('http://www.w3.org/2001/XMLSchema', 'xs:simpleType');
  1227. $elNode->appendChild($sType);
  1228. $sTypeRes = $dom->createElementNS('http://www.w3.org/2001/XMLSchema', 'xs:restriction');
  1229. $sType->appendChild($sTypeRes);
  1230. $sTypeRes->setAttribute('base', "{$p5TypePrefix}:{$xsdType}");
  1231. $enumList = $fldType->getEnumeration();
  1232. if (empty($enumList)) {
  1233. foreach ($fldRestrictions as $restricionName => $restrictionValue) {
  1234. if ('maxLength' == $restricionName) {
  1235. $sTypeResMaxLength = $dom->createElementNS('http://www.w3.org/2001/XMLSchema', 'xs:maxLength');
  1236. $sTypeRes->appendChild($sTypeResMaxLength);
  1237. $sTypeResMaxLength->setAttribute('value', $restrictionValue);
  1238. } else if ('minLength' == $restricionName) {
  1239. $sTypeResMinLength = $dom->createElementNS('http://www.w3.org/2001/XMLSchema', 'xs:minLength');
  1240. $sTypeRes->appendChild($sTypeResMinLength);
  1241. $sTypeResMinLength->setAttribute('value', $restrictionValue);
  1242. } else if ('pattern' == $restricionName) {
  1243. $sTypeResPattern = $dom->createElementNS('http://www.w3.org/2001/XMLSchema', 'xs:pattern');
  1244. $sTypeRes->appendChild($sTypeResPattern);
  1245. $sTypeResPattern->setAttribute('value', $restrictionValue);
  1246. } else if ('fractionDigits' == $restricionName) {
  1247. $sTypeResFractionDigits = $dom->createElementNS('http://www.w3.org/2001/XMLSchema', 'xs:fractionDigits');
  1248. $sTypeRes->appendChild($sTypeResFractionDigits);
  1249. $sTypeResFractionDigits->setAttribute('value', $restrictionValue);
  1250. } else if ('totalDigits' == $restricionName) {
  1251. $sTypeResTotalDigits = $dom->createElementNS('http://www.w3.org/2001/XMLSchema', 'xs:totalDigits');
  1252. $sTypeRes->appendChild($sTypeResTotalDigits);
  1253. $sTypeResTotalDigits->setAttribute('value', $restrictionValue);
  1254. } else if ('maxExclusive' == $restricionName) {
  1255. $sTypeResMaxExclusive = $dom->createElementNS('http://www.w3.org/2001/XMLSchema', 'xs:maxExclusive');
  1256. $sTypeRes->appendChild($sTypeResMaxExclusive);
  1257. $sTypeResMaxExclusive->setAttribute('value', $restrictionValue);
  1258. } else if ('minExclusive' == $restricionName) {
  1259. $sTypeResMinExclusive = $dom->createElementNS('http://www.w3.org/2001/XMLSchema', 'xs:minExclusive');
  1260. $sTypeRes->appendChild($sTypeResMinExclusive);
  1261. $sTypeResMinExclusive->setAttribute('value', $restrictionValue);
  1262. } else if ('maxInclusive' == $restricionName) {
  1263. $sTypeResMaxInclusive = $dom->createElementNS('http://www.w3.org/2001/XMLSchema', 'xs:maxInclusive');
  1264. $sTypeRes->appendChild($sTypeResMaxInclusive);
  1265. $sTypeResMaxInclusive->setAttribute('value', $restrictionValue);
  1266. } else if ('minInclusive' == $restricionName) {
  1267. $sTypeResMinInclusive = $dom->createElementNS('http://www.w3.org/2001/XMLSchema', 'xs:minInclusive');
  1268. $sTypeRes->appendChild($sTypeResMinInclusive);
  1269. $sTypeResMinInclusive->setAttribute('value', $restrictionValue);
  1270. }
  1271. /* TODO: xsd restrictions:
  1272. enumeration Defines a list of acceptable values
  1273. fractionDigits Specifies the maximum number of decimal places allowed. Must be equal to or greater than zero
  1274. length Specifies the exact number of characters or list items allowed. Must be equal to or greater than zero
  1275. maxExclusive Specifies the upper bounds for numeric values (the value must be less than this value)
  1276. maxInclusive Specifies the upper bounds for numeric values (the value must be less than or equal to this value)
  1277. maxLength Specifies the maximum number of characters or list items allowed. Must be equal to or greater than zero
  1278. minExclusive Specifies the lower bounds for numeric values (the value must be greater than this value)
  1279. minInclusive Specifies the lower bounds for numeric values (the value must be greater than or equal to this value)
  1280. minLength Specifies the minimum number of characters or list items allowed. Must be equal to or greater than zero
  1281. pattern Defines the exact sequence of characters that are acceptable
  1282. totalDigits Specifies the exact number of digits allowed. Must be greater than zero
  1283. whiteSpace Specifies how white space (line feeds, tabs, spaces, and carriage returns) is handled
  1284. */
  1285. }
  1286. } else {
  1287. foreach ($enumList as $enumValue) {
  1288. $sTypeResEnum = $dom->createElementNS('http://www.w3.org/2001/XMLSchema', 'xs:enumeration');
  1289. $sTypeRes->appendChild($sTypeResEnum);
  1290. $sTypeResEnum->setAttribute('value', $enumValue);
  1291. }
  1292. }
  1293. }
  1294. }
  1295. $elNode = $dom->createElementNS('http://www.w3.org/2001/XMLSchema', 'xs:element');
  1296. $rootNode->appendChild($elNode);
  1297. $elNode->setAttribute('name', $tblName);
  1298. $elNode->setAttribute('type', "{$objNs}:{$typeName}");
  1299. header('Content-type: application/xml');
  1300. echo $dom->saveXML();
  1301. exit;
  1302. }
  1303. public function navView() {
  1304. $backLabel = 'back';
  1305. $backLink = 'index.php?_route=Storage';
  1306. $backDisabled = true;
  1307. $currentLabel = 'Storage';
  1308. $currentLink = 'index.php?_route=Storage';
  1309. if ($task = V::get('_task', '', $_REQUEST)) {
  1310. $currentLink = "index.php?_route=Storage&_task={$task}";
  1311. $backDisabled = false;
  1312. $idStorage = V::get('idStorage', 0, $_REQUEST, 'int');
  1313. $tblName = V::get('table', '', $_REQUEST, 'word');
  1314. $objName = V::get('object', '', $_REQUEST, 'word');
  1315. switch ($task) {
  1316. case 'tableList':
  1317. case 'viewList':
  1318. case 'rawInfo':
  1319. $backLabel = 'Storage';
  1320. $backLink = 'index.php?_route=Storage';
  1321. $currentLink = "index.php?_route=Storage&_task={$task}&idStorage={$idStorage}";
  1322. break;
  1323. case 'tableStruct':
  1324. $backLabel = "Tabele [{$idStorage}]";
  1325. $backLink = "index.php?_route=Storage&_task=tableList&idStorage={$idStorage}";
  1326. $currentLink = "index.php?_route=Storage&_task={$task}&idStorage={$idStorage}&table={$tblName}";
  1327. break;
  1328. case 'objectStruct': break;
  1329. case 'coreObjectStruct':
  1330. $backLabel = "Obiekty podstawowe";
  1331. $backLink = "index.php?_route=Storage&_task=coreObjectList";
  1332. $currentLink = "index.php?_route=Storage&_task={$task}&object={$objName}";
  1333. break;
  1334. }
  1335. switch ($task) {
  1336. case 'tableList': $currentLabel = "Tabele [{$idStorage}]"; break;
  1337. case 'viewList': $currentLabel = "Widoki [{$idStorage}]"; break;
  1338. case 'rawInfo': $currentLabel = "Raw info [{$idStorage}]"; break;
  1339. case 'tableStruct': $currentLabel = "Struktura tabeli '{$tblName}'"; break;
  1340. case 'coreObjectList': $currentLabel = "Obiekty podstawowe"; break;
  1341. case 'coreObjectStruct': $currentLabel = "Obiekt '{$objName}'"; break;
  1342. case 'objectList': $currentLabel = "Obiekty z aktualnej domeny"; break;// TODO: domain from $_GET
  1343. }
  1344. }
  1345. UI::startTag('nav', ['class'=>"navbar navbar-default navbar-static-top", 'style'=>"z-index:999"]);
  1346. UI::startTag('div', ['class'=>"container-fluid"]);
  1347. UI::startTag('div', ['class'=>"navbar-left"]);
  1348. UI::startTag('ul', ['class'=>"nav navbar-nav navbar-center"]);
  1349. UI::startTag('li');
  1350. UI::tag('a', ['href'=>$backLink, 'class'=>"btn" . ($backDisabled ? ' disabled' : '')], '<i class="glyphicon glyphicon-chevron-left"></i> ' . $backLabel);
  1351. UI::endTag('li');
  1352. UI::endTag('ul');
  1353. UI::endTag('div');
  1354. UI::startTag('div', ['class'=>"navbar-left"]);
  1355. UI::startTag('ul', ['class'=>"nav navbar-nav navbar-center"]);
  1356. UI::startTag('li');
  1357. UI::tag('a', ['href'=>$currentLink, 'class'=>"btn"], $currentLabel);
  1358. UI::endTag('li');
  1359. UI::endTag('ul');
  1360. UI::endTag('div');
  1361. UI::startTag('div', ['class'=>"navbar-right"]);
  1362. // <ul class="nav navbar-nav navbar-right">
  1363. // <li><a href="#">Link</a></li>
  1364. // <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>
  1365. // <ul class="dropdown-menu">
  1366. // <li><a href="#">Action</a></li>
  1367. // <li><a href="#">Another action</a></li>
  1368. // <li><a href="#">Something else here</a></li>
  1369. // <li role="separator" class="divider"></li>
  1370. // <li><a href="#">Separated link</a></li>
  1371. // </ul>
  1372. // </li>
  1373. // </ul>
  1374. UI::endTag('div');
  1375. UI::endTag('div');// .container-fluid
  1376. UI::endTag('nav');
  1377. }
  1378. public function getStorageList() {
  1379. $storageList = array();
  1380. $sth = DB::getPDO()->prepare("
  1381. select z.ID, z.`DESC`, z.`TYPE`
  1382. from CRM_LISTA_ZASOBOW z
  1383. where z.TYPE in('BAZA_DANYCH','DATABASE_MYSQL','DATABASE_POSTGRESQL')
  1384. ");
  1385. $sth->execute();
  1386. $rows = $sth->fetchAll();
  1387. foreach ($rows as $row) {
  1388. $storageList[$row['ID']] = $row;
  1389. }
  1390. return $storageList;
  1391. }
  1392. public function addTableToZasobyAction() {// sends JSON
  1393. $response = new stdClass();
  1394. try {
  1395. $idStorage = V::get('storageId', '', $_GET);
  1396. $tblName = V::get('tblName', '', $_GET, 'word');
  1397. if (empty($tblName)) throw new HttpException("Wrong table name");
  1398. $storage = DB::getStorage($idStorage);
  1399. $sqlTableName = DB::getPDO($idStorage)->quote($tblName, PDO::PARAM_STR);
  1400. $dbName = DB::getPDO($idStorage)->getDatabaseName();
  1401. $rootTableName = DB::getPDO($idStorage)->fetchValue("
  1402. select t.TABLE_NAME
  1403. from `information_schema`.`TABLES` t
  1404. where t.TABLE_SCHEMA = '{$dbName}'
  1405. and t.TABLE_NAME LIKE {$sqlTableName}
  1406. ");
  1407. if (!$rootTableName) throw new Exception("Table '{$tblName}' not exists!");
  1408. $tableStruct = $storage->getTableStruct($tblName);
  1409. $zasobStorageId = $storage->getZasobId();
  1410. if (!is_numeric($zasobStorageId)) throw new HttpException("Storage id is not set in config file");
  1411. $foundZasobItem = null;
  1412. {
  1413. $rows = DB::getPDO()->fetchAll("
  1414. select z.`ID`, z.`DESC`
  1415. from `CRM_LISTA_ZASOBOW` z
  1416. where z.`PARENT_ID`='{$zasobStorageId}'
  1417. and z.`DESC`='{$tblName}'
  1418. and z.`A_STATUS` in('NORMAL','WAITING')
  1419. ");
  1420. if (!empty($rows)) {
  1421. $foundZasobItem = $rows[0]['ID'];
  1422. }
  1423. }
  1424. if ($foundZasobItem > 0) {
  1425. $response->_replaceButtonNode = "[{$foundZasobItem}]";
  1426. throw new AlertInfoException("Zasob tabela '{$tblName}' już istnieje - nr '{$foundZasobItem}'");
  1427. }
  1428. try {
  1429. $acl = User::getAcl()->getObjectAcl('default_db', 'crm_lista_zasobow');
  1430. } catch (Exception $e) {
  1431. throw new Exception("Brak dostępu do tabeli Zasoby");
  1432. }
  1433. $item = array();
  1434. $item['PARENT_ID'] = $zasobStorageId;
  1435. $item['TYPE'] = 'TABELA';
  1436. $item['DESC'] = $rootTableName;
  1437. $item['DESC_PL'] = $tblName;
  1438. if (DBG::isActive()) $response->_itemToCreate = $item;
  1439. $createdId = $acl->addItem($item);
  1440. if (!$createdId) throw new Exception("Nie udało się utworzyć nowego rekordu!");
  1441. $response->id = $createdId;
  1442. $response->record = $acl->getItem($createdId);
  1443. $response->_replaceButtonNode = "[{$createdId}]";
  1444. throw new AlertSuccessException("Utworzono pomyślnie rekord nr {$createdId}");
  1445. } catch (AlertSuccessException $e) {
  1446. $response->type = 'success';
  1447. $response->msg = $e->getMessage();
  1448. } catch (AlertInfoException $e) {
  1449. $response->type = 'info';
  1450. $response->msg = $e->getMessage();
  1451. } catch (Exception $e) {
  1452. $response->type = 'error';
  1453. $response->msg = $e->getMessage();
  1454. }
  1455. Response::sendJsonExit($response);
  1456. }
  1457. public function addCellToZasobyAction() {// sends JSON
  1458. $response = new stdClass();
  1459. try {
  1460. $idStorage = V::get('storageId', '', $_GET);
  1461. $tblName = V::get('tblName', '', $_GET, 'word');
  1462. $cellName = V::get('cellName', '', $_GET, 'word');
  1463. if (empty($tblName)) throw new HttpException("Wrong table name");
  1464. if (empty($tblName)) throw new HttpException("Wrong cell name");
  1465. $storage = DB::getStorage($idStorage);
  1466. $tableStruct = $storage->getTableStruct($tblName);
  1467. $zasobStorageId = $storage->getZasobId();
  1468. if (!is_numeric($zasobStorageId)) throw new HttpException("Storage id is not set in config file");
  1469. $idTable = $this->fetchTableId($zasobStorageId, $tblName);
  1470. if ($idTable <= 0) throw new Exception("Zasob tabela '{$tblName}' nie istnieje");
  1471. try {
  1472. $acl = User::getAcl()->getObjectAcl('default_db', 'crm_lista_zasobow');
  1473. } catch (Exception $e) {
  1474. throw new Exception("Brak dostępu do tabeli Zasoby");
  1475. }
  1476. $item = array();
  1477. $item['PARENT_ID'] = $idTable;
  1478. $item['TYPE'] = 'KOMORKA';
  1479. $item['DESC'] = $cellName;
  1480. $item['DESC_PL'] = $cellName;
  1481. if (DBG::isActive()) $response->_itemToCreate = $item;
  1482. $createdId = $acl->addItem($item);
  1483. if (!$createdId) throw new Exception("Nie udało się utworzyć nowego rekordu!");
  1484. $response->id = $createdId;
  1485. $response->record = $acl->getItem($createdId);
  1486. $response->_replaceButtonNode = "[{$createdId}]";
  1487. throw new AlertSuccessException("Utworzono pomyślnie rekord nr {$createdId}");
  1488. } catch (AlertSuccessException $e) {
  1489. $response->type = 'success';
  1490. $response->msg = $e->getMessage();
  1491. } catch (AlertInfoException $e) {
  1492. $response->type = 'info';
  1493. $response->msg = $e->getMessage();
  1494. } catch (Exception $e) {
  1495. $response->type = 'error';
  1496. $response->msg = $e->getMessage();
  1497. }
  1498. Response::sendJsonExit($response);
  1499. }
  1500. public function fetchTableId($idZasobStorage, $tblName) {
  1501. $rows = DB::getPDO()->fetchAll("
  1502. select z.`ID`, z.`DESC`
  1503. from `CRM_LISTA_ZASOBOW` z
  1504. where z.`PARENT_ID`='{$idZasobStorage}'
  1505. and z.`DESC`='{$tblName}'
  1506. and z.`A_STATUS` in('NORMAL','WAITING')
  1507. ");
  1508. if (!empty($rows)) return (int)$rows[0]['ID'];
  1509. return null;
  1510. }
  1511. public function systemObjectsStructAction() {
  1512. UI::gora();
  1513. UI::menu();
  1514. $this->navView();
  1515. try {
  1516. throw new Exception("TODO: F." . __FUNCTION__ . ' L.' . __LINE__);
  1517. // $coreObjlist = OBJXSD::getSystemObjectsStruct();
  1518. // $objectList = array();
  1519. // foreach ($coreObjlist as $objName) {
  1520. // $objItem = array();
  1521. // $objItem['name'] = $objName;
  1522. // $objItem['struktura'] = '<a href="index.php?_route=Storage&_task=systemObjectsStruct&object=' . $objName . '">' . "struct" . '</a>';
  1523. // // $objItem['label'] = "";// TODO: read from json
  1524. // $objectList[] = $objItem;
  1525. // }
  1526. // usort($objectList, function($rowA, $rowB) {
  1527. // $a = $rowA['nazwa']; $b = $rowB['nazwa'];
  1528. // if ($a == $b) return 0;
  1529. // return ($a < $b) ? -1 : 1;
  1530. // });
  1531. //
  1532. // DBG::table("objectList", $objectList, __CLASS__, __FUNCTION__, __LINE__);
  1533. } catch (Exception $e) {
  1534. UI::alert('danger', "Error #" . $e->getCode() . "|" . $e->getLine() . ": " . $e->getMessage());
  1535. }
  1536. UI::dol();
  1537. }
  1538. public function systemObjectsAction() {// TableAjax view: index.php?_route=ViewTableAjax&namespace=default_objects/SystemObject
  1539. UI::gora();
  1540. UI::menu();
  1541. $this->navView();
  1542. try {
  1543. Lib::loadClass('Schema_SystemObjectStorageAcl');
  1544. $acl = new Schema_SystemObjectStorageAcl();
  1545. UI::table([
  1546. 'rows' => array_map(
  1547. function ($item) {
  1548. $exNs = explode('/', $item['namespace']);
  1549. $name = array_pop($exNs);
  1550. $typeName = implode('__x3A__', $exNs) . ':' . $name;
  1551. return [
  1552. 'ns' => $item['namespace'],
  1553. 'nazwa' => $name,
  1554. 'edit' => '<a href="index.php?_route=ViewTableAjax&namespace=' . $item['namespace'] . '">edit</a>',
  1555. 'wfs Describe' => '<a href="wfs-data.php/default_db/?SERVICE=WFS&VERSION=1.0.0&SRSNAME=EPSG:3003&REQUEST=DescribeFeatureType&TYPENAME=' . $typeName . '">DescribeFeatureType</a>',
  1556. 'wfs getFeature' => '<a href="wfs-data.php/default_db/?SERVICE=WFS&VERSION=1.0.0&SRSNAME=EPSG:3003&REQUEST=GetFeature&TYPENAME=' . $typeName . '&MAXFEATURES=10">GetFeature</a> (max:10)'
  1557. ];
  1558. }
  1559. , $acl->getItems([
  1560. 'order_by' => 'namespace',
  1561. 'order_dir' => 'asc'
  1562. ])
  1563. )
  1564. ]);
  1565. } catch (Exception $e) {
  1566. UI::alert('danger', "Error #" . $e->getCode() . "|" . $e->getLine() . ": " . $e->getMessage());
  1567. DBG::log($e);
  1568. }
  1569. UI::dol();
  1570. }
  1571. public function objectReinstallAction() {
  1572. UI::gora();
  1573. UI::startContainer();
  1574. try {
  1575. $namespace = V::get('namespace', '', $_GET);
  1576. if (empty($namespace)) throw new Exception("Missing param namespace");
  1577. Lib::loadClass('Schema_SystemObjectStorageAcl');
  1578. $acl = new Schema_SystemObjectStorageAcl();
  1579. $items = $acl->getItems([
  1580. 'f_namespace' => "={$namespace}",
  1581. ]);
  1582. if (empty($items)) throw new Exception("SystemObject '{$namespace}' not found");
  1583. $item = reset($items);
  1584. if (empty($item)) throw new Exception("SystemObject '{$namespace}' not found");
  1585. DBG::log($item, 'array', '$item');
  1586. switch ($item['_type']) {
  1587. case 'AntAcl': $this->reinstallAntAcl($item); break;
  1588. default: throw new Exception("TODO: Not Implemented type '{$item['_type']}'");
  1589. }
  1590. } catch (Exception $e) {
  1591. UI::alert('danger', "Error #" . $e->getCode() . "|" . $e->getLine() . ": " . $e->getMessage());
  1592. DBG::log($e);
  1593. }
  1594. UI::endContainer();
  1595. UI::dol();
  1596. }
  1597. public function reinstallAntAcl($item) {
  1598. Lib::loadClass('AntAclBase');
  1599. $exNs = explode('/', $item['namespace']);
  1600. $name = array_pop($exNs);
  1601. $antAclPath = APP_PATH_SCHEMA . DS . 'ant-object' . DS . implode('.', $exNs) . DS . $name;
  1602. if (!file_exists("{$antAclPath}/build.xml")) throw new Exception("Ant build file not exists");
  1603. DBG::log($antAclPath, 'string', '$antAclPath');
  1604. $antBin = APP_PATH_WWW . DS . 'stuff' . DS . 'dita-ot-2.3.3' . DS . 'bin' . DS . 'ant';
  1605. $cmd = "cd {$antAclPath} && {$antBin} DescribeFeatureType 2>&1";
  1606. V::exec($cmd, $out, $ret);
  1607. DBG::log($out, 'array', "DescribeFeatureType ret({$ret})");
  1608. $outputType = 'XML';
  1609. $html = []; $startRead = false;
  1610. foreach ($out as $line) {
  1611. // $line = " [echo] OUTPUT__TYPE__XML"
  1612. if ('[echo]' == substr(trim($line), 0, 6)) {
  1613. $line = trim(substr(trim($line), 7));
  1614. }
  1615. if (!$startRead) {
  1616. if ('OUTPUT__TYPE__XML' == $line) $outputType = 'XML';
  1617. if ('OUTPUT__TYPE__HTML' == $line) $outputType = 'HTML';
  1618. if ('OUTPUT__START' == $line) {
  1619. $startRead = true;
  1620. continue;
  1621. }
  1622. } else {
  1623. if ('<!DOCTYPE' == substr($line, 0, strlen('<!DOCTYPE'))) continue;
  1624. if ('OUTPUT__END' == $line) {
  1625. break;
  1626. }
  1627. $html[]= $line;
  1628. }
  1629. }
  1630. if (empty($html)) UI::alert('danger', "Empty output!");
  1631. else {
  1632. if ('XML' == $outputType) {
  1633. echo UI::h('pre', [], htmlspecialchars(implode("\n", $html)));
  1634. } else if ('HTML' == $outputType) {
  1635. echo UI::h('div', ['class'=>"container", 'style'=>"padding:12px; border:1px solid #ddd"], $html);
  1636. }
  1637. }
  1638. }
  1639. }