Storage.php 63 KB

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