Storage.php 85 KB

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