Storage.php 66 KB

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