Storage.php 91 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277
  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 aclUsageAction() {
  821. UI::gora();
  822. UI::menu();
  823. UI::startContainer();
  824. try {
  825. $namespace = V::get('namespace', '', $_GET, 'word');
  826. if (!$namespace) {
  827. $typeName = V::get('typeName', '', $_GET, 'word');
  828. if (!$typeName) throw new Exception("Wrong param typeName");
  829. $namespace = Api_WfsNs::getBaseWfsUri() . '/' . str_replace(':', '/', $typeName);
  830. }
  831. $acl = Core_AclHelper::getAclByNamespace($namespace, $forceTblAclInit = ('1' == V::get('_force', '', $_GET)));
  832. $tableName = $acl->getName();
  833. $idTable = $acl->getID();
  834. UI::tag('h2', [], "Uprawnienia tabeli '{$tableName}'");
  835. UI::tag('p', [], "ID Zasobu [{$idTable}]");
  836. if ($idTable > 0) {
  837. $aclTableRows = DB::getPDO()->fetchAll("select * from `CRM_PROCES_idx_TABLE_TO_PROCES_PERMS_VIEW` where ID_TABLE = {$idTable}");
  838. UI::startTag('details');
  839. echo UI::h('summary', ['style'=>"cursor:pointer"], "Wszystkie powiązania komórek z procesami - szczegóły");
  840. UI::table([
  841. 'rows' => array_map(function ($row) {
  842. $splitPos = strpos($row['TABLE_DESCRIPTION'], ' ', 20);
  843. if ($splitPos > 30) $splitPos = 20;
  844. $row['TABLE_DESCRIPTION'] = UI::h('details', [], [
  845. UI::h('summary', [ 'style' => "white-space:nowrap" ], substr($row['TABLE_DESCRIPTION'], 0, $splitPos)),
  846. UI::h('p', [], substr($row['TABLE_DESCRIPTION'], $splitPos)),
  847. ]);
  848. return $row;
  849. }, $aclTableRows)
  850. ]);
  851. UI::endTag('details');
  852. $csvIdProces = array();
  853. foreach ($aclTableRows as $row) {
  854. if (!in_array($row['ID_PROCES'], $csvIdProces)) $csvIdProces[] = $row['ID_PROCES'];
  855. }
  856. }
  857. $databaseName = DB::getPDO()->getDatabaseName();
  858. UI::table([
  859. 'caption' => "Powiązania komórek z procesem",
  860. 'rows' => array_map(
  861. function ($row) use ($aclTableRows, $idTable) {
  862. $fieldName = $row['COLUMN_NAME'];
  863. $item = [];
  864. $item['name'] = $fieldName;
  865. $item['typ'] = UI::h('details', [], [
  866. UI::h('summary', ['style'=>"cursor:pointer"], $row['DATA_TYPE']),
  867. UI::h('p', [], $row['COLUMN_TYPE']),
  868. ]);
  869. $item['w procesie'] = array();
  870. $item['id_zasob'] = 0;
  871. $item['PERM_R'] = 0;
  872. $item['PERM_W'] = 0;
  873. $item['PERM_X'] = 0;
  874. $item['PERM_C'] = 0;
  875. $item['PERM_S'] = 0;
  876. $item['PERM_O'] = 0;
  877. $item['PERM_V'] = 0;
  878. $item['PERM_E'] = 0;
  879. foreach ($aclTableRows as $aclInfo) {
  880. if (strtolower($aclInfo['CELL_NAME']) == strtolower($row['COLUMN_NAME'])) {
  881. $item['w procesie'][] = $aclInfo['ID_PROCES'];
  882. $item['id_zasob'] = $aclInfo['ID_CELL'];
  883. $item['PERM_R'] += $aclInfo['PERM_R'];
  884. $item['PERM_W'] += $aclInfo['PERM_W'];
  885. $item['PERM_X'] += $aclInfo['PERM_X'];
  886. $item['PERM_C'] += $aclInfo['PERM_C'];
  887. $item['PERM_S'] += $aclInfo['PERM_S'];
  888. $item['PERM_O'] += $aclInfo['PERM_O'];
  889. $item['PERM_V'] += $aclInfo['PERM_V'];
  890. $item['PERM_E'] += $aclInfo['PERM_E'];
  891. }
  892. }
  893. $item['w procesie'] = (empty($item['w procesie']))
  894. ? "<i style=\"color:red\">Brak</i>"
  895. : UI::h('span', ['style'=>"white-space:nowrap"], implode(", ", $item['w procesie']));
  896. if (!$item['id_zasob']) $item['id_zasob'] = DB::getPDO()->fetchValue("select ID from CRM_LISTA_ZASOBOW where `DESC` = '{$fieldName}' and PARENT_ID = {$idTable} limit 1");
  897. $item['id_zasob'] = ($item['id_zasob']) ? $item['id_zasob'] : UI::h('i', ['style'=>"color:silver"], "Brak");
  898. return $item;
  899. }, DB::getPDO()->fetchAll("
  900. select t.COLUMN_NAME, t.DATA_TYPE, t.COLUMN_TYPE
  901. from `information_schema`.`COLUMNS` t
  902. where t.TABLE_SCHEMA = '{$databaseName}'
  903. and t.TABLE_NAME like '{$tableName}'
  904. ")
  905. )
  906. ]);
  907. if (!empty($csvIdProces)) {
  908. $userLogin = User::getLogin();
  909. $csvIdProces = implode(",", $csvIdProces);
  910. UI::tag('h4', ['style'=>"margin-top:40px"], "Procesy dla '{$userLogin}': [{$csvIdProces}] <small><i>(z tabeli CRM_PROCES_idx_USER_to_PROCES_VIEW)</i></small>");
  911. $rows = DB::getPDO()->fetchAll("
  912. select ID_PROCES
  913. from `CRM_PROCES_idx_USER_to_PROCES_VIEW`
  914. where ADM_ACCOUNT = '{$userLogin}'
  915. and ID_PROCES in({$csvIdProces})
  916. group by ID_PROCES
  917. ");
  918. $userIdProces = array(); foreach ($rows as $row) $userIdProces[] = $row['ID_PROCES'];
  919. $userTablePerms = array();
  920. foreach ($aclTableRows as $row) {
  921. if (!in_array($row['ID_PROCES'], $userIdProces)) continue;
  922. if (array_key_exists($row['CELL_NAME'], $userTablePerms)) {
  923. $userTablePerms[ $row['CELL_NAME'] ]['w procesie'] .= ",{$row['ID_PROCES']}";
  924. $userTablePerms[ $row['CELL_NAME'] ][ 'PERM_R' ] += $row['PERM_R'];
  925. $userTablePerms[ $row['CELL_NAME'] ][ 'PERM_W' ] += $row['PERM_W'];
  926. $userTablePerms[ $row['CELL_NAME'] ][ 'PERM_X' ] += $row['PERM_X'];
  927. $userTablePerms[ $row['CELL_NAME'] ][ 'PERM_C' ] += $row['PERM_C'];
  928. $userTablePerms[ $row['CELL_NAME'] ][ 'PERM_S' ] += $row['PERM_S'];
  929. $userTablePerms[ $row['CELL_NAME'] ][ 'PERM_O' ] += $row['PERM_O'];
  930. $userTablePerms[ $row['CELL_NAME'] ][ 'PERM_V' ] += $row['PERM_V'];
  931. $userTablePerms[ $row['CELL_NAME'] ][ 'PERM_E' ] += $row['PERM_E'];
  932. } else {
  933. $userTablePerms[ $row['CELL_NAME'] ] = [
  934. 'fieldName' => $row['CELL_NAME'],
  935. 'zasob' => $row['ID_CELL'],
  936. 'w procesie' => "{$row['ID_PROCES']}",
  937. 'PERM_R' => $row['PERM_R'],
  938. 'PERM_W' => $row['PERM_W'],
  939. 'PERM_X' => $row['PERM_X'],
  940. 'PERM_C' => $row['PERM_C'],
  941. 'PERM_S' => $row['PERM_S'],
  942. 'PERM_O' => $row['PERM_O'],
  943. 'PERM_V' => $row['PERM_V'],
  944. 'PERM_E' => $row['PERM_E'],
  945. ];
  946. }
  947. }
  948. UI::table([
  949. 'caption' => "Uprawniena dla usera '{$userLogin}'",
  950. 'rows' => $userTablePerms
  951. ]);
  952. } else UI::alert('warning', "brak \$csvIdProces");
  953. } catch (Exception $e) {
  954. UI::alert('danger', $e->getMessage());
  955. DBG::log($e);
  956. }
  957. UI::endContainer();
  958. UI::dol();
  959. }
  960. public function tableStructAction() {
  961. UI::gora();
  962. UI::menu();
  963. $this->navView();
  964. try {
  965. $idStorage = V::get('idStorage', 0, $_REQUEST, 'int');
  966. if (empty($idStorage)) throw new Exception("Missing id storage");
  967. $storageList = $this->getStorageList();
  968. if (empty($storageList)) throw new Exception("No storage defined");
  969. if (!array_key_exists($idStorage, $storageList)) throw new Exception("Storage not exists");
  970. $tblName = V::get('table', '', $_REQUEST, 'word');
  971. if (empty($tblName)) throw new Exception("No table name");
  972. $storagePdo = DB::getStorage($idStorage);
  973. $tblStruct = $storagePdo->getTableStruct($tblName);
  974. $idTable = $this->fetchTableId($idStorage, $tblName);
  975. if ($idTable <= 0) {
  976. UI::alert('warning', "Zasob tabela '{$tblName}' nie istnieje");// TODO: add p5UI btn
  977. DBG::table("tblStruct", $tblStruct, __CLASS__, __FUNCTION__, __LINE__);
  978. throw new Exception("Zasob tabela '{$tblName}' nie istnieje");
  979. }
  980. $cellZasobList = array();
  981. foreach (DB::getPDO()->fetchAllByKey("
  982. select z.ID, z.`DESC`, z.`TYPE` as ZASOB_TYPE, z.A_STATUS
  983. from CRM_LISTA_ZASOBOW z
  984. where z.PARENT_ID = '{$idTable}'
  985. ", $key = 'DESC') as $ind => $row) {
  986. $cellZasobList[strtolower($ind)] = $row;
  987. }
  988. $emptyItem = array();
  989. $emptyItem['name'] = '';
  990. $emptyItem['id_zasob'] = '';
  991. $emptyItem['zasob_type'] = '';
  992. $emptyItem['uwagi'] = '';
  993. $emptyItem['type'] = '';
  994. $emptyItem['is_nullable'] = '';
  995. $emptyItem['default_value'] = '';
  996. $emptyItem['default_is_null'] = '';
  997. $emptyItem['max_length'] = '';
  998. $emptyItem['num_precision'] = '';
  999. $emptyItem['num_scale'] = '';
  1000. $emptyItem['char_encoding'] = '';
  1001. $emptyItem['char_collation'] = '';
  1002. $emptyItem['extra'] = '';
  1003. $emptyItem['raw_storage_type'] = '';
  1004. $tableList = array();
  1005. foreach ($tblStruct as $row) {
  1006. $cellName = $row['name'];
  1007. $tblItem = V::cloneArray($emptyItem);
  1008. $tblItem['name'] = $cellName;
  1009. foreach ($row as $fldName => $fldVal) {
  1010. if (array_key_exists($fldName, $tblItem)) $tblItem[$fldName] = $fldVal;
  1011. }
  1012. $tblItem['uwagi'] = '';
  1013. $lowerCellName = strtolower($cellName);
  1014. $tblZasob = V::get($lowerCellName, '', $cellZasobList);
  1015. if ($tblZasob) {
  1016. $cellZasobList[$lowerCellName]['_checked'] = true;
  1017. $tblItem['id_zasob'] = $tblZasob['ID'];
  1018. $tblItem['zasob_type'] = $tblZasob['ZASOB_TYPE'];
  1019. } else {
  1020. $tblItem['uwagi'] .= '!Zasob';//'TODO: ADD ZASOB';
  1021. $ajaxAddZasobLink = Request::getPathUri() . "index.php?_route=Storage&_task=addCellToZasoby&idStorage={$idStorage}&tblName={$tblName}&cellName={$cellName}";
  1022. $onClick = "return p5UI__ButtonAjax(this, 'p5UIBtnAjax:Storage:addCellToZasoby', { href: '{$ajaxAddZasobLink}' })";
  1023. $tblItem['id_zasob'] = '<a onclick="'.$onClick.'" class="btn btn-xs btn-primary" href="#">TODO: ADD ZASOB</a>';
  1024. }
  1025. $tableList[] = $tblItem;
  1026. }
  1027. foreach ($cellZasobList as $cellName => $row) {
  1028. if ('URL_ACTION' == $row['ZASOB_TYPE']) continue;
  1029. if (!$row['_checked']) {
  1030. $tblItem = V::cloneArray($emptyItem);
  1031. $tblItem['name'] = $cellName;
  1032. $tblItem['id_zasob'] = $row['ID'];
  1033. $tblItem['zasob_type'] = $row['ZASOB_TYPE'];
  1034. $tblItem['uwagi'] = '!DB';//'TODO: nie istnieje w bazie danych';
  1035. $tableList[] = $tblItem;
  1036. }
  1037. }
  1038. usort($tableList, function($rowA, $rowB) {
  1039. $a = $rowA['name']; $b = $rowB['name'];
  1040. if ('ID' == $a) return -1;
  1041. if ('ID' == $b) return 1;
  1042. if ($a == $b) return 0;
  1043. $a1 = substr($a, 0, 1); $b1 = substr($b, 0, 1);
  1044. if (('_' == $a1 || '_' == $b1) && $a1 != $b1) {
  1045. return ($a1 < $b1) ? 1 : -1;
  1046. }
  1047. return ($a < $b) ? -1 : 1;
  1048. });
  1049. UI::table([
  1050. 'caption' => UI::h('span', [], [
  1051. "Komórki [{$idTable}] ",
  1052. UI::h('a', [
  1053. 'href' => "index.php?_route=ViewTableAjax&namespace=default_db/{$tblName}",
  1054. 'class' => "btn btn-md btn-link"
  1055. ], "Przeglądaj tabelę"),
  1056. UI::h('a', [
  1057. 'href' => "procesy5.php?task=CRM_LISTA_ZASOBOW&filtr_id={$idTable}&filtr_ids=%2B&filtr_ob=%2B",
  1058. 'class' => "btn btn-md btn-link",
  1059. 'title' => "Struktura aktualnie przeglądanej tabeli"
  1060. ], "Zasoby"),
  1061. UI::h('a', [
  1062. 'href' => "index.php?FUNCTION_INIT=PROCES_MENU&HEADER_NOT_INIT=YES&_task=PROCES_FOR_TABLE&tblId={$idTable}",
  1063. 'class' => "btn btn-md btn-link",
  1064. 'title' => "Procesy dla aktualnie przeglądanej tabeli"
  1065. ], "Procesy"),
  1066. UI::h('a', [
  1067. 'href' => $this->getLink('aclUsage', [ 'namespace' => "default_db/{$tblName}" ]),
  1068. 'class' => "btn btn-md btn-link",
  1069. 'title' => "Uprawnienia - analiza użycia komórek w procesach"
  1070. ], "Uprawnienia (analiza użycia)"),
  1071. ]),
  1072. 'cols' => array_keys($emptyItem),
  1073. 'rows' => $tableList
  1074. ]);
  1075. echo UI::h('script', [], "
  1076. jQuery(document).on('p5UIBtnAjax:Storage:addCellToZasoby:click', function(e, n, payload) {
  1077. console.log('event p5UIBtnAjax:Storage:addCellToZasoby:click', n, payload);
  1078. });
  1079. jQuery(document).on('p5UIBtnAjax:Storage:addCellToZasoby:ajaxLoaded', function(e, n, payload) {
  1080. console.log('event p5UIBtnAjax:Storage:addCellToZasoby:ajaxLoaded', n, payload);
  1081. if ('success' == payload.type && payload.body && payload.body.id > 0) {
  1082. var cellUwagiJQNode = jQuery(n).parents('td').next('td');
  1083. cellUwagiJQNode.text(cellUwagiJQNode.text().replace('!Zasob', ''))
  1084. jQuery(n).parents('td').text(payload.body.id);
  1085. jQuery(n).remove();
  1086. }
  1087. jQuery.notify(payload.msg, payload.type);
  1088. });
  1089. ");
  1090. $ajaxAddZasobLink = Request::getPathUri() . "index.php?_route=Storage&_task=addGeomEtykietaCells&idStorage={$idStorage}&tblName={$tblName}";
  1091. $onClick = "return p5UI__ButtonAjax(this, 'p5UIBtnAjax:Storage:addGeomEtykietaCells', { href: '{$ajaxAddZasobLink}' })";
  1092. UI::tag('a', ['onclick'=>$onClick, 'class'=>"btn btn-xs btn-default", 'href'=>"#"], "Dodaj komórki etykiet", true);
  1093. echo "<i>(<code>`etykieta_x`</code>, <code>`etykieta_y`</code>, <code>`etykieta_obrot`</code>)</i>";
  1094. echo UI::h('script', [], "
  1095. jQuery(document).on('p5UIBtnAjax:Storage:addGeomEtykietaCells:ajaxLoaded', function(e, n, payload) {
  1096. console.log('event p5UIBtnAjax:Storage:addGeomEtykietaCells:ajaxLoaded', n, payload);
  1097. if ('success' == payload.type && payload.body && payload.body.id > 0) {
  1098. var cellUwagiJQNode = jQuery(n).parents('td').next('td');
  1099. cellUwagiJQNode.text(cellUwagiJQNode.text().replace('!Zasob', ''))
  1100. jQuery(n).parents('td').text(payload.body.id);
  1101. jQuery(n).remove();
  1102. }
  1103. jQuery.notify(payload.msg, payload.type);
  1104. });
  1105. ");
  1106. $tableActions = array_filter($cellZasobList, function ($row) {
  1107. return ('URL_ACTION' == $row['ZASOB_TYPE']);
  1108. });
  1109. UI::table([
  1110. 'caption' => "tableActions",
  1111. // 'cols' => array_keys($emptyItem),
  1112. 'rows' => array_map(function ($item) {
  1113. $sqlIdAction = DB::getPDO()->quote($item['ID'], PDO::PARAM_INT);
  1114. $args = DB::getPDO()->fetchAll("
  1115. select z.`DESC`
  1116. , a.ID as ALIAS_ID, a.`DESC` as ALIAS_DESC, a.OPIS as ALIAS_OPIS
  1117. from CRM_LISTA_ZASOBOW z
  1118. left join CRM_LISTA_ZASOBOW a on(a.ID = z.ALIAS_ID)
  1119. where z.PARENT_ID = {$sqlIdAction}
  1120. and z.`TYPE` = 'PARAM_IN'
  1121. ");
  1122. $definitionArgs = DB::getPDO()->fetchAll("
  1123. select p.ID, p.`DESC`
  1124. from CRM_LISTA_ZASOBOW z
  1125. join CRM_LISTA_ZASOBOW d on(d.ID = z.ALIAS_ID)
  1126. left join CRM_LISTA_ZASOBOW p on(p.PARENT_ID = d.ID)
  1127. where z.ID = {$sqlIdAction}
  1128. and p.`TYPE` = 'PARAM_IN'
  1129. ");
  1130. $flatDefinitionArgs = implode(";", array_map(function ($arg) {
  1131. return "{$arg['ID']}={$arg['DESC']}";
  1132. }, $definitionArgs));
  1133. return [
  1134. 'label' => DB::getPDO()->fetchValue(" select z.OPIS from CRM_LISTA_ZASOBOW z where z.ID = {$sqlIdAction} ") . " " .
  1135. UI::h('i', [
  1136. 'class' => "glyphicon glyphicon-pencil",
  1137. 'style' => "cursor:pointer",
  1138. 'onClick' => "return Storage__tableStruct__editActionLabel(this, {$sqlIdAction})"], ''),
  1139. 'args' => implode("<br>&", array_map(function ($item) {
  1140. return (NULL === $item['ALIAS_ID'])
  1141. ? $item['DESC']
  1142. : "{$item['DESC']}=" . '{$row["' . $item['ALIAS_DESC'] . '"]}';// TODO: add rmParam btn
  1143. }, $args)) . " " .
  1144. UI::h('i', [
  1145. 'class' => "glyphicon glyphicon-plus-sign",
  1146. 'style' => "cursor:pointer",
  1147. 'title' => "Dodaj PARAM_IN",
  1148. 'onClick' => "return Storage__tableStruct__addParamAction(this, {$sqlIdAction}, '{$flatDefinitionArgs}')"], ''),
  1149. // 'args_info' => '<pre>' . var_export($args, true) . '</pre>',
  1150. 'ID' => $item['ID'],
  1151. 'DESC' => $item['DESC'],
  1152. 'A_STATUS' => $item['A_STATUS'],
  1153. 'definition args' => implode("", array_map(function ($item) {
  1154. return '<div style="white-space:nowrap">' . "[{$item['ID']}] {$item['DESC']}" . '</div>';
  1155. }, $definitionArgs)),
  1156. ];
  1157. }, $tableActions)
  1158. ]);
  1159. echo UI::h('button', [
  1160. 'onClick'=>"Storage__tableStruct__addAction()",
  1161. 'class'=>"btn btn-xs btn-default"
  1162. ], "Dodaj Akcję");
  1163. echo UI::h('link', ['rel'=>"stylesheet", 'type'=>"text/css", 'href'=>"static/sweetalert2.min.css"]);
  1164. echo UI::h('script', ['src'=>"static/sweetalert2.min.js"]);
  1165. echo UI::h('style', [], "
  1166. .swal2-radio.p5-swal-radio-as-list { text-align:left }
  1167. .swal2-radio.p5-swal-radio-as-list > label { display:block; margin-left:20px }
  1168. ");
  1169. UI::inlineJS(__FILE__ . '.tableActions.js', [
  1170. 'ID_STORAGE' => $idStorage,
  1171. 'TABLE_NAME' => $tblName,
  1172. 'FETCH_URL' => Request::getPathUri() . 'index.php?_route=Storage&_task=fetchActionListAjax',
  1173. 'ADD_ACTION_URL' => Request::getPathUri() . 'index.php?_route=Storage&_task=addActionAjax'
  1174. ]);
  1175. echo '<hr>';
  1176. $ajaxAddBaseProcesLink = Request::getPathUri() . "index.php?_route=Storage&_task=addTableBaseProces&idStorage={$idStorage}&tblName={$tblName}";
  1177. $onClick = "return p5UI__ButtonAjax(this, 'p5UIBtnAjax:Storage:addTableBaseProces', { href: '{$ajaxAddBaseProcesLink}' })";
  1178. UI::tag('a', ['onclick'=>$onClick, 'class'=>"btn btn-xs btn-default", 'href'=>"#"], "Dodaj podstawowy proces dla tabeli '{$tblName}' - read only", true);
  1179. echo UI::h('script', [], "
  1180. jQuery(document).on('p5UIBtnAjax:Storage:addTableBaseProces:ajaxLoaded', function(e, n, payload) {
  1181. jQuery.notify(payload.msg, payload.type);
  1182. });
  1183. ");
  1184. } catch (Exception $e) {
  1185. UI::alert('danger', "Error #" . $e->getCode() . "|" . $e->getLine() . ": " . $e->getMessage());
  1186. }
  1187. UI::dol();
  1188. }
  1189. public function fetchActionListAjaxAction() {
  1190. Response::sendTryCatchJson(array($this, 'fetchActionListAjax'), $args = 'JSON_FROM_REQUEST_BODY');
  1191. }
  1192. public function fetchActionListAjax($args) {
  1193. return [
  1194. 'type' => 'success',
  1195. '__args' => $args,
  1196. 'options' => DB::getPDO()->fetchAll("
  1197. select z.ID, z.`DESC`, z.OPIS
  1198. from CRM_LISTA_ZASOBOW z
  1199. where z.`TYPE` = 'URL_ACTION'
  1200. and z.A_STATUS != 'DELETED'
  1201. and z.ALIAS_ID = 0
  1202. ")
  1203. ];
  1204. }
  1205. public function addActionAjaxAction() {
  1206. Response::sendTryCatchJson(array($this, 'addActionAjax'), $args = 'JSON_FROM_REQUEST_BODY');
  1207. }
  1208. public function addActionAjax($args) {
  1209. $idStorage = V::get('idStorage', 0, $args, 'int');
  1210. if ($idStorage <= 0) throw new Exception("Missing id storage");
  1211. $idAction = V::get('idAction', 0, $args, 'int');
  1212. if ($idAction <= 0) throw new Exception("Missing id action");
  1213. $storageList = $this->getStorageList();
  1214. if (empty($storageList)) throw new Exception("No storage defined");
  1215. if (!array_key_exists($idStorage, $storageList)) throw new Exception("Storage not exists");
  1216. $tblName = V::get('table', '', $args, 'word');
  1217. if (empty($tblName)) throw new Exception("No table name");
  1218. $storagePdo = DB::getStorage($idStorage);
  1219. // $tblStruct = $storagePdo->getTableStruct($tblName);
  1220. $idTable = $this->fetchTableId($idStorage, $tblName);
  1221. if ($idTable <= 0) throw new Exception("Zasob tabela '{$tblName}' nie istnieje");
  1222. $action = DB::getPDO()->fetchFirst("
  1223. select z.ID, z.`DESC`, z.OPIS
  1224. from CRM_LISTA_ZASOBOW z
  1225. where z.ID = {$idAction}
  1226. ");
  1227. if (empty($action)) throw new Exception("Action '{$idAction}' not exists");
  1228. $idInsertedAction = DB::getPDO()->insert('CRM_LISTA_ZASOBOW', [
  1229. 'PARENT_ID' => $idTable,
  1230. 'ALIAS_ID' => $idAction,
  1231. 'TYPE' => 'URL_ACTION',
  1232. 'DESC' => $action['DESC'],
  1233. 'OPIS' => V::get('OPIS', $action['DESC'], $action),
  1234. ]);
  1235. if (!$idInsertedAction) throw new Exception("Nie udało się dodać akcji");
  1236. try {
  1237. DB::getPDO()->insert('CRM_LISTA_ZASOBOW_HIST', [
  1238. 'ID_USERS2' => $idInsertedAction,
  1239. 'PARENT_ID' => $idTable,
  1240. 'ALIAS_ID' => $idAction,
  1241. 'TYPE' => 'URL_ACTION',
  1242. 'DESC' => $action['DESC'],
  1243. 'OPIS' => V::get('OPIS', $action['DESC'], $action),
  1244. ]);
  1245. } catch (Exception $e) {
  1246. DBG::log($e);
  1247. }
  1248. return [
  1249. 'type' => 'success',
  1250. 'msg' => "Dodano akcję - rekord nr {$idInsertedAction}",
  1251. '__DBG__' => [
  1252. '$args' => $args,
  1253. '$idStorage' => $idStorage,
  1254. '$tblName' => $tblName,
  1255. // '$tblStruct' => $tblStruct,
  1256. '$idTable' => $idTable,
  1257. '$action' => $action,
  1258. ]
  1259. ];
  1260. }
  1261. public function addTableBaseProcesAction() {
  1262. Response::sendTryCatchJson(array($this, 'addTableBaseProces'), $_REQUEST);
  1263. }
  1264. public function addTableBaseProces($args) {
  1265. $return = [
  1266. 'type' => 'error',
  1267. 'msg' => 'todo: F.' . __FUNCTION__ . ' L.' . __LINE__,
  1268. ];
  1269. $idStorage = V::get('idStorage', 0, $args, 'int');
  1270. if ($idStorage <= 0) throw new HttpException("Missing idStorage", 400);
  1271. $storage = DB::getStorage($idStorage);
  1272. $tblName = V::get('tblName', 0, $args, 'word');
  1273. if (empty($tblName)) throw new HttpException("Missing tblName", 400);
  1274. $tableStruct = $storage->getTableStruct($tblName);
  1275. $return['$tableStruct'] = $tableStruct;
  1276. $idTable = $this->fetchTableId($idStorage, $tblName);
  1277. if ($idTable <= 0) {
  1278. UI::alert('warning', "Zasob tabela '{$tblName}' nie istnieje");// TODO: add p5UI btn
  1279. DBG::table("tblStruct", $tblStruct, __CLASS__, __FUNCTION__, __LINE__);
  1280. throw new Exception("Zasob tabela '{$tblName}' nie istnieje");
  1281. }
  1282. $cellZasobList = array();
  1283. foreach (DB::getPDO()->fetchAllByKey("
  1284. select z.ID, z.`DESC`, z.A_STATUS
  1285. from CRM_LISTA_ZASOBOW z
  1286. where z.PARENT_ID = '{$idTable}'
  1287. ", $key = 'DESC') as $ind => $row) {
  1288. $cellZasobList[strtolower($ind)] = $row;
  1289. }
  1290. $return['$cellZasobList'] = $cellZasobList;
  1291. $idProces = DB::getDB()->ADD_NEW_OBJ('CRM_PROCES', (object)[
  1292. 'TYPE' => 'PROCES_INIT',
  1293. 'DESC' => "Proces dla tabeli '{$tblName}'",
  1294. ]);
  1295. if (!$idProces) throw new Exception("DB ERROR - nie udało się dodać procesu");
  1296. foreach ($cellZasobList as $loverName => $row) {
  1297. DB::getDB()->ADD_NEW_OBJ('CRM_WSKAZNIK', (object)[
  1298. 'ID_PROCES' => $idProces,
  1299. 'ID_ZASOB' => $row['ID'],
  1300. 'TYP' => 'P',
  1301. 'ID_PRZYPADEK' => 2
  1302. ]);
  1303. }
  1304. $return['type'] = 'success';
  1305. $return['msg'] = "Utworzono proces {{$idProces}}";
  1306. return $return;
  1307. }
  1308. public function addObjectBaseProcesAjaxAction() {
  1309. Response::sendTryCatchJson(array($this, 'addObjectBaseProcesAjax'), $_REQUEST);
  1310. }
  1311. public function addObjectBaseProcesAjax($args) {
  1312. $return = [
  1313. 'type' => 'error',
  1314. 'msg' => 'todo: F.' . __FUNCTION__ . ' L.' . __LINE__,
  1315. ];
  1316. $namespace = V::get('namespace', 0, $args);
  1317. if (empty($namespace)) throw new HttpException("Missing namespace", 400);
  1318. $item = SchemaFactory::loadDefaultObject('SystemObject')->getItem($namespace, [ 'propertyName' => '*,field' ]);
  1319. DBG::log($item, 'array', "TODO: addObjectBaseProcesAjax for \$item");
  1320. throw new HttpException("TODO: addObjectBaseProcesAjax('{$namespace}')", 400); // TODO: ...
  1321. // $return['$tableStruct'] = $tableStruct;
  1322. //
  1323. // $idTable = $this->fetchTableId($idStorage, $tblName);
  1324. // if ($idTable <= 0) {
  1325. // UI::alert('warning', "Zasob tabela '{$tblName}' nie istnieje");// TODO: add p5UI btn
  1326. // DBG::table("tblStruct", $tblStruct, __CLASS__, __FUNCTION__, __LINE__);
  1327. // throw new Exception("Zasob tabela '{$tblName}' nie istnieje");
  1328. // }
  1329. // $cellZasobList = array();
  1330. // foreach (DB::getPDO()->fetchAllByKey("
  1331. // select z.ID, z.`DESC`, z.A_STATUS
  1332. // from CRM_LISTA_ZASOBOW z
  1333. // where z.PARENT_ID = '{$idTable}'
  1334. // ", $key = 'DESC') as $ind => $row) {
  1335. // $cellZasobList[strtolower($ind)] = $row;
  1336. // }
  1337. //
  1338. // $return['$cellZasobList'] = $cellZasobList;
  1339. // TODO: ACL::modify('default_db/CRM_PROCES/CRM_PROCES_INIT', [ 'ref:...' => $namespace ]);
  1340. $idProces = DB::getDB()->ADD_NEW_OBJ('CRM_PROCES', (object)[
  1341. 'TYPE' => 'PROCES_INIT',
  1342. 'DESC' => "Proces dla obiektu '{$namespace}'",
  1343. ]);
  1344. if (!$idProces) throw new Exception("DB ERROR - nie udało się dodać procesu");
  1345. // TODO: add wskaznik do $item['idZasob']
  1346. // foreach ($cellZasobList as $loverName => $row) {
  1347. // DB::getDB()->ADD_NEW_OBJ('CRM_WSKAZNIK', (object)[
  1348. // 'ID_PROCES' => $idProces,
  1349. // 'ID_ZASOB' => $row['ID'],
  1350. // 'TYP' => 'P',
  1351. // 'ID_PRZYPADEK' => 2
  1352. // ]);
  1353. // }
  1354. // $return['type'] = 'success';
  1355. // $return['msg'] = "Utworzono proces {{$idProces}}";
  1356. // return $return;
  1357. }
  1358. public function addGeomEtykietaCellsAction() {
  1359. Response::sendTryCatchJson(array($this, 'addGeomEtykietaCells'), $_REQUEST);
  1360. }
  1361. public function addGeomEtykietaCells($args) {
  1362. $return = [
  1363. 'type' => 'error',
  1364. 'msg' => 'todo: F.' . __FUNCTION__ . ' L.' . __LINE__,
  1365. ];
  1366. $return['_DBG_request'] = $args;
  1367. // idStorage: "36"
  1368. // tblName: "test_geom_linestring"
  1369. $idStorage = V::get('idStorage', 0, $args, 'int');
  1370. if ($idStorage <= 0) throw new HttpException("Missing idStorage", 400);
  1371. $storage = DB::getStorage($idStorage);
  1372. $tblName = V::get('tblName', 0, $args, 'word');
  1373. if (empty($tblName)) throw new HttpException("Missing tblName", 400);
  1374. $tableStruct = $storage->getTableStruct($tblName);
  1375. $return['_DBG_$tableStruct'] = $tableStruct;
  1376. if ('mysql' == DB::getPDO($idStorage)->getType()) {
  1377. $dbName = DB::getPDO($idStorage)->getDatabaseName();
  1378. $fixedTableName = DB::getPDO($idStorage)->fetchValue("
  1379. select t.TABLE_NAME
  1380. from `information_schema`.`TABLES` t
  1381. where t.TABLE_SCHEMA = '{$dbName}'
  1382. and t.TABLE_NAME LIKE '{$tblName}'
  1383. ");
  1384. $return['_DBG_sql_fix__$tblName'] = "
  1385. select t.TABLE_NAME
  1386. from `information_schema`.`TABLES` t
  1387. where t.TABLE_SCHEMA = '{$dbName}'
  1388. and t.TABLE_NAME LIKE '{$tblName}'
  1389. ";
  1390. if (empty($fixedTableName)) return $return;
  1391. if (empty($fixedTableName)) throw new HttpException("Database Error", 500);
  1392. $return['_DBG_$fixedTableName'] = $fixedTableName;
  1393. $tblName = $fixedTableName;
  1394. }
  1395. $return['_DBG_$tableStruct'] = $tableStruct;
  1396. $return['_DBG_has_field__etykieta_x'] = (null != V::geti('etykieta_x', null, $tableStruct));
  1397. $return['_DBG_has_field__etykieta_y'] = (null != V::geti('etykieta_y', null, $tableStruct));
  1398. $return['_DBG_has_field__etykieta_obrot'] = (null != V::geti('etykieta_obrot', null, $tableStruct));
  1399. if (!V::geti('etykieta_x', null, $tableStruct)) {
  1400. try {
  1401. DB::getPDO($idStorage)->exec("ALTER TABLE `{$tblName}_HIST` ADD `etykieta_x` varchar(16) DEFAULT 'N/S;'");
  1402. } catch (Exception $e) {
  1403. $return['__DBG_hist_errors__etykieta_x'] = $e->getMessage();
  1404. }
  1405. DB::getPDO($idStorage)->exec("ALTER TABLE `{$tblName}` ADD `etykieta_x` decimal(16,10) DEFAULT NULL COMMENT 'przesuniecie etykiety elementu w GIS'");
  1406. }
  1407. if (!V::geti('etykieta_y', null, $tableStruct)) {
  1408. try {
  1409. DB::getPDO($idStorage)->exec("ALTER TABLE `{$tblName}_HIST` ADD `etykieta_y` varchar(16) DEFAULT 'N/S;'");
  1410. } catch (Exception $e) {
  1411. $return['__DBG_hist_errors__etykieta_y'] = $e->getMessage();
  1412. }
  1413. DB::getPDO($idStorage)->exec("ALTER TABLE `{$tblName}` ADD `etykieta_y` decimal(16,10) DEFAULT NULL COMMENT 'przesuniecie etykiety elementu w GIS'");
  1414. }
  1415. if (!V::geti('etykieta_obrot', null, $tableStruct)) {
  1416. try {
  1417. DB::getPDO($idStorage)->exec("ALTER TABLE `{$tblName}_HIST` ADD `etykieta_obrot` varchar(16) DEFAULT 'N/S;'");
  1418. } catch (Exception $e) {
  1419. $return['__DBG_hist_errors__etykieta_obrot'] = $e->getMessage();
  1420. }
  1421. DB::getPDO($idStorage)->exec("ALTER TABLE `{$tblName}` ADD `etykieta_obrot` decimal(16,10) DEFAULT NULL");
  1422. }
  1423. return $return;
  1424. }
  1425. public function xsdAction() {
  1426. $idStorage = V::get('idStorage', 0, $_REQUEST, 'int');
  1427. $storage = DB::getStorage($idStorage);
  1428. $tableRealList = $storage->getTableList();
  1429. $srvName = $_SERVER['SERVER_NAME'];
  1430. $storageZasobId = $storage->getZasobId();
  1431. $objNs = "p5_{$storageZasobId}_{$tblName}";
  1432. $objNsUri = "https://biuro.biall-net.pl/api/{$storageZasobId}/{$tblName}";
  1433. $p5TypePrefix = "p5Type";
  1434. $p5TypeNsUri = "http://biuro.biall-net.pl/p5/schema/types";
  1435. $p5TypeNsLocation = "http://biuro.biall-net.pl/p5/schema/types.xsd";
  1436. header('Content-type: text/plain; charset=utf-8');// TODO: test
  1437. //header('Content-type: application/xml; charset=utf-8');
  1438. $xmlWriter = new XMLWriter();
  1439. $xmlWriter->openUri('php://output');
  1440. $xmlWriter->setIndent(true);
  1441. if (!$xmlWriter) throw new HttpException("Error no XMLWriter", 404);
  1442. $xmlWriter->startDocument('1.0', 'UTF-8');
  1443. $xmlWriter->startElement('xs:schema');
  1444. $xmlWriter->writeAttribute('xmlns:xs', 'http://www.w3.org/2001/XMLSchema');
  1445. $xmlWriter->writeAttribute('xmlns:vc', 'http://www.w3.org/2007/XMLSchema-versioning');
  1446. $xmlWriter->writeAttribute("xmlns:{$p5TypePrefix}", $p5TypeNsUri);
  1447. $xmlWriter->writeAttribute('elementFormDefault', 'qualified');
  1448. $xmlWriter->writeAttribute('targetNamespace', $objNsUri);
  1449. $xmlWriter->writeAttribute('vc:minVersion', '1.1');
  1450. $xmlWriter->startElement('xs:import');
  1451. $xmlWriter->writeAttribute('namespace', $p5TypeNsUri);
  1452. $xmlWriter->writeAttribute('schemaLocation', $p5TypeNsLocation);
  1453. $xmlWriter->endElement();// xs:import
  1454. foreach ($tableRealList as $tbl) {
  1455. $tblName = $tbl['table_name'];
  1456. $this->tableXsdViewXmlWriter($xmlWriter, $idStorage, $tblName);
  1457. }
  1458. $xmlWriter->endElement();// xs:schema
  1459. $xmlWriter->endDocument();
  1460. }
  1461. public function tableXsdAction() {
  1462. $idStorage = V::get('idStorage', '', $_GET);
  1463. $tblName = V::get('table', '', $_GET, 'word');
  1464. if (empty($tblName)) die("Wrong table name");
  1465. header('Content-type: text/plain; charset=utf-8');// TODO: test
  1466. $storage = DB::getStorage($idStorage);
  1467. $storageZasobId = $storage->getZasobId();
  1468. $objNs = "p5_{$storageZasobId}_{$tblName}";
  1469. $objNsUri = "https://biuro.biall-net.pl/api/{$storageZasobId}/{$tblName}";
  1470. $p5TypePrefix = "p5Type";
  1471. $p5TypeNsUri = "http://biuro.biall-net.pl/p5/schema/types";
  1472. $p5TypeNsLocation = "http://biuro.biall-net.pl/p5/schema/types.xsd";
  1473. //header('Content-type: application/xml; charset=utf-8');
  1474. $xmlWriter = new XMLWriter();
  1475. $xmlWriter->openUri('php://output');
  1476. $xmlWriter->setIndent(true);
  1477. if (!$xmlWriter) throw new HttpException("Error no XMLWriter", 404);
  1478. $xmlWriter->startDocument('1.0', 'UTF-8');
  1479. $xmlWriter->startElement('xs:schema');
  1480. $xmlWriter->writeAttribute('xmlns:xs', 'http://www.w3.org/2001/XMLSchema');
  1481. $xmlWriter->writeAttribute('xmlns:vc', 'http://www.w3.org/2007/XMLSchema-versioning');
  1482. $xmlWriter->writeAttribute("xmlns:{$p5TypePrefix}", $p5TypeNsUri);
  1483. $xmlWriter->writeAttribute('elementFormDefault', 'qualified');
  1484. $xmlWriter->writeAttribute('targetNamespace', $objNsUri);
  1485. $xmlWriter->writeAttribute('vc:minVersion', '1.1');
  1486. $xmlWriter->startElement('xs:import');
  1487. $xmlWriter->writeAttribute('namespace', $p5TypeNsUri);
  1488. $xmlWriter->writeAttribute('schemaLocation', $p5TypeNsLocation);
  1489. $xmlWriter->endElement();// xs:import
  1490. $this->tableXsdViewXmlWriter($xmlWriter, $idStorage, $tblName);
  1491. $xmlWriter->endElement();// xs:schema
  1492. $xmlWriter->endDocument();
  1493. }
  1494. public function tableXsdViewXmlWriter(&$xmlWriter, $idStorage, $tblName) {
  1495. $storage = DB::getStorage($idStorage);
  1496. $schema = Schema_TableFactory::build($tblName, $idStorage, $_SERVER['SERVER_NAME']);
  1497. $struct = $schema->getStruct();
  1498. DBG::_('DBG', '>1', "struct", $struct, __CLASS__, __FUNCTION__, __LINE__);
  1499. $typeName = "{$tblName}Type";
  1500. $xmlWriter->startElement('xs:complexType');
  1501. $xmlWriter->writeAttribute('name', $typeName);
  1502. $xmlWriter->startElement('xs:sequence');
  1503. foreach ($struct as $field) {
  1504. $xmlWriter->startElement('xs:element');
  1505. $xmlWriter->writeAttribute('name', $field['name']);
  1506. $xmlWriter->writeAttribute('minOccurs', 0);// TODO: set minOccurs by default, etc.
  1507. if ($field['is_nullable']) $xmlWriter->writeAttribute('nillable', 'true');
  1508. if (null !== $field['default_value']) {
  1509. $xmlWriter->writeAttribute('default', $field['default_value']);
  1510. } else if (null === $field['default_value'] && $field['is_nullable']) {
  1511. $xmlWriter->writeAttribute('default', $field['default_value']);
  1512. } else {
  1513. // TODO: Schema BUG?
  1514. }
  1515. if (empty($field['p5_restrictions'])) {
  1516. $xmlWriter->writeAttribute('type', "p5Type:{$field['p5_type']}");
  1517. } else {
  1518. $xmlWriter->startElement('xs:simpleType');
  1519. $xmlWriter->writeAttribute('base', "p5Type:{$field['p5_type']}");
  1520. $xmlWriter->startElement('xs:restriction');
  1521. if (!empty($field['p5_restrictions']['enumeration'])) {
  1522. foreach ($field['p5_restrictions']['enumeration'] as $enumValue) {
  1523. $xmlWriter->startElement('xs:enumeration');
  1524. $xmlWriter->writeAttribute('value', $enumValue);
  1525. $xmlWriter->endElement();// xs:enumeration
  1526. }
  1527. } else {
  1528. // TODO: another restrictions...
  1529. }
  1530. $xmlWriter->endElement();// xs:restriction
  1531. $xmlWriter->endElement();// xs:simpleType
  1532. }
  1533. $xmlWriter->endElement();// xs:element
  1534. }
  1535. $xmlWriter->endElement();// xs:sequence
  1536. $xmlWriter->endElement();// xs:complexType
  1537. return;
  1538. // <xs:element maxOccurs="1" minOccurs="0" name="{$fldName}" nillable="true" type="xs:integer"/>
  1539. $pKeyField = 'ID';//$storageObject->getPrimaryKeyFieldName();
  1540. //DBG::_(true, true, "struct", $struct, __CLASS__, __FUNCTION__, __LINE__);
  1541. foreach ($struct as $field) {
  1542. $fldName = $vField->getName();
  1543. $fldType = $vField->getType();
  1544. $xsdType = $fldType->getTypeForXsd();
  1545. if ($fldType->hasDefault()) {
  1546. $fldDefault = $fldType->getDefault();
  1547. if (!empty($fldDefault) || '0' === $fldDefault) {
  1548. $elNode->setAttribute('default', $fldDefault);
  1549. }
  1550. }
  1551. $fldRestrictions = $fldType->getRestrictions();
  1552. if (empty($fldRestrictions)) {
  1553. $elNode->setAttribute('type', "{$p5TypePrefix}:{$xsdType}");
  1554. } else {
  1555. $sType = $dom->createElementNS('http://www.w3.org/2001/XMLSchema', 'xs:simpleType');
  1556. $elNode->appendChild($sType);
  1557. $sTypeRes = $dom->createElementNS('http://www.w3.org/2001/XMLSchema', 'xs:restriction');
  1558. $sType->appendChild($sTypeRes);
  1559. $sTypeRes->setAttribute('base', "{$p5TypePrefix}:{$xsdType}");
  1560. $enumList = $fldType->getEnumeration();
  1561. if (empty($enumList)) {
  1562. foreach ($fldRestrictions as $restricionName => $restrictionValue) {
  1563. if ('maxLength' == $restricionName) {
  1564. $sTypeResMaxLength = $dom->createElementNS('http://www.w3.org/2001/XMLSchema', 'xs:maxLength');
  1565. $sTypeRes->appendChild($sTypeResMaxLength);
  1566. $sTypeResMaxLength->setAttribute('value', $restrictionValue);
  1567. } else if ('minLength' == $restricionName) {
  1568. $sTypeResMinLength = $dom->createElementNS('http://www.w3.org/2001/XMLSchema', 'xs:minLength');
  1569. $sTypeRes->appendChild($sTypeResMinLength);
  1570. $sTypeResMinLength->setAttribute('value', $restrictionValue);
  1571. } else if ('pattern' == $restricionName) {
  1572. $sTypeResPattern = $dom->createElementNS('http://www.w3.org/2001/XMLSchema', 'xs:pattern');
  1573. $sTypeRes->appendChild($sTypeResPattern);
  1574. $sTypeResPattern->setAttribute('value', $restrictionValue);
  1575. } else if ('fractionDigits' == $restricionName) {
  1576. $sTypeResFractionDigits = $dom->createElementNS('http://www.w3.org/2001/XMLSchema', 'xs:fractionDigits');
  1577. $sTypeRes->appendChild($sTypeResFractionDigits);
  1578. $sTypeResFractionDigits->setAttribute('value', $restrictionValue);
  1579. } else if ('totalDigits' == $restricionName) {
  1580. $sTypeResTotalDigits = $dom->createElementNS('http://www.w3.org/2001/XMLSchema', 'xs:totalDigits');
  1581. $sTypeRes->appendChild($sTypeResTotalDigits);
  1582. $sTypeResTotalDigits->setAttribute('value', $restrictionValue);
  1583. } else if ('maxExclusive' == $restricionName) {
  1584. $sTypeResMaxExclusive = $dom->createElementNS('http://www.w3.org/2001/XMLSchema', 'xs:maxExclusive');
  1585. $sTypeRes->appendChild($sTypeResMaxExclusive);
  1586. $sTypeResMaxExclusive->setAttribute('value', $restrictionValue);
  1587. } else if ('minExclusive' == $restricionName) {
  1588. $sTypeResMinExclusive = $dom->createElementNS('http://www.w3.org/2001/XMLSchema', 'xs:minExclusive');
  1589. $sTypeRes->appendChild($sTypeResMinExclusive);
  1590. $sTypeResMinExclusive->setAttribute('value', $restrictionValue);
  1591. } else if ('maxInclusive' == $restricionName) {
  1592. $sTypeResMaxInclusive = $dom->createElementNS('http://www.w3.org/2001/XMLSchema', 'xs:maxInclusive');
  1593. $sTypeRes->appendChild($sTypeResMaxInclusive);
  1594. $sTypeResMaxInclusive->setAttribute('value', $restrictionValue);
  1595. } else if ('minInclusive' == $restricionName) {
  1596. $sTypeResMinInclusive = $dom->createElementNS('http://www.w3.org/2001/XMLSchema', 'xs:minInclusive');
  1597. $sTypeRes->appendChild($sTypeResMinInclusive);
  1598. $sTypeResMinInclusive->setAttribute('value', $restrictionValue);
  1599. }
  1600. /* TODO: xsd restrictions:
  1601. enumeration Defines a list of acceptable values
  1602. fractionDigits Specifies the maximum number of decimal places allowed. Must be equal to or greater than zero
  1603. length Specifies the exact number of characters or list items allowed. Must be equal to or greater than zero
  1604. maxExclusive Specifies the upper bounds for numeric values (the value must be less than this value)
  1605. maxInclusive Specifies the upper bounds for numeric values (the value must be less than or equal to this value)
  1606. maxLength Specifies the maximum number of characters or list items allowed. Must be equal to or greater than zero
  1607. minExclusive Specifies the lower bounds for numeric values (the value must be greater than this value)
  1608. minInclusive Specifies the lower bounds for numeric values (the value must be greater than or equal to this value)
  1609. minLength Specifies the minimum number of characters or list items allowed. Must be equal to or greater than zero
  1610. pattern Defines the exact sequence of characters that are acceptable
  1611. totalDigits Specifies the exact number of digits allowed. Must be greater than zero
  1612. whiteSpace Specifies how white space (line feeds, tabs, spaces, and carriage returns) is handled
  1613. */
  1614. }
  1615. } else {
  1616. foreach ($enumList as $enumValue) {
  1617. $sTypeResEnum = $dom->createElementNS('http://www.w3.org/2001/XMLSchema', 'xs:enumeration');
  1618. $sTypeRes->appendChild($sTypeResEnum);
  1619. $sTypeResEnum->setAttribute('value', $enumValue);
  1620. }
  1621. }
  1622. }
  1623. }
  1624. $elNode = $dom->createElementNS('http://www.w3.org/2001/XMLSchema', 'xs:element');
  1625. $rootNode->appendChild($elNode);
  1626. $elNode->setAttribute('name', $tblName);
  1627. $elNode->setAttribute('type', "{$objNs}:{$typeName}");
  1628. header('Content-type: application/xml');
  1629. echo $dom->saveXML();
  1630. exit;
  1631. }
  1632. public function navView() {
  1633. $backLabel = 'back';
  1634. $backLink = 'index.php?_route=Storage';
  1635. $backDisabled = true;
  1636. $currentLabel = 'Storage';
  1637. $currentLink = 'index.php?_route=Storage';
  1638. if ($task = V::get('_task', '', $_REQUEST)) {
  1639. $currentLink = "index.php?_route=Storage&_task={$task}";
  1640. $backDisabled = false;
  1641. $idStorage = V::get('idStorage', 0, $_REQUEST, 'int');
  1642. $tblName = V::get('table', '', $_REQUEST, 'word');
  1643. $objName = V::get('object', '', $_REQUEST, 'word');
  1644. $namespace = V::get('namespace', '', $_REQUEST, 'word');
  1645. switch ($task) {
  1646. case 'obejctList':
  1647. case 'tableList':
  1648. case 'viewList':
  1649. case 'rawInfo':
  1650. $backLabel = 'Storage';
  1651. $backLink = $this->getLink();
  1652. $currentLink = $this->getLink($task, ['idStorage' => $idStorage]);
  1653. break;
  1654. case 'tableStruct':
  1655. $backLabel = "Tabele [{$idStorage}]";
  1656. $backLink = $this->getLink('tableList', ['idStorage' => $idStorage]);
  1657. $currentLink = $this->getLink($task, ['idStorage' => $idStorage, 'table' => $tblName]);
  1658. break;
  1659. case 'objectStruct':
  1660. $backLabel = "Obiekty [{$idStorage}]";
  1661. $backLink = $this->getLink('tableList', ['idStorage' => $idStorage]);// TODO: mv tableList to objectList
  1662. $currentLink = $this->getLink($task, ['idStorage' => $idStorage, 'namespace' => $namespace]);
  1663. break;
  1664. case 'coreObjectStruct':
  1665. $backLabel = "Obiekty podstawowe";
  1666. $backLink = $this->getLink('coreObjectList', ['idStorage' => $idStorage]);
  1667. $currentLink = $this->getLink($task, ['idStorage' => $idStorage, 'object' => $objName]);
  1668. break;
  1669. }
  1670. switch ($task) {
  1671. case 'tableList': $currentLabel = "Tabele [{$idStorage}]"; break;
  1672. case 'viewList': $currentLabel = "Widoki [{$idStorage}]"; break;
  1673. case 'rawInfo': $currentLabel = "Raw info [{$idStorage}]"; break;
  1674. case 'tableStruct': $currentLabel = "Struktura tabeli '{$tblName}'"; break;
  1675. case 'objectStruct': $currentLabel = "Obiekt '{$namespace}'"; break;
  1676. case 'coreObjectList': $currentLabel = "Obiekty podstawowe"; break;
  1677. case 'coreObjectStruct': $currentLabel = "Obiekt '{$objName}'"; break;
  1678. case 'objectList': $currentLabel = "Obiekty z aktualnej domeny"; break;// TODO: domain from $_GET
  1679. }
  1680. }
  1681. echo UI::h('nav', ['class'=>"navbar navbar-default navbar-static-top", 'style'=>"z-index:999"], [
  1682. UI::h('div', ['class'=>"container-fluid"], [
  1683. UI::h('div', ['class'=>"navbar-left"], [
  1684. UI::h('ul', ['class'=>"nav navbar-nav navbar-center"], [
  1685. UI::h('li', [], [
  1686. UI::h('a', ['href'=>$backLink, 'class'=>"btn" . ($backDisabled ? ' disabled' : '')], '<i class="glyphicon glyphicon-chevron-left"></i> ' . $backLabel)
  1687. ])
  1688. ])
  1689. ]),
  1690. UI::h('div', ['class'=>"navbar-left"], [
  1691. UI::h('ul', ['class'=>"nav navbar-nav navbar-center"], [
  1692. UI::h('li', [], [
  1693. UI::h('a', ['href'=>$currentLink, 'class'=>"btn"], $currentLabel)
  1694. ])
  1695. ])
  1696. ]),
  1697. UI::h('div', ['class'=>"navbar-right"], [
  1698. // <ul class="nav navbar-nav navbar-right">
  1699. // <li><a href="#">Link</a></li>
  1700. // <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>
  1701. // <ul class="dropdown-menu">
  1702. // <li><a href="#">Action</a></li>
  1703. // <li><a href="#">Another action</a></li>
  1704. // <li><a href="#">Something else here</a></li>
  1705. // <li role="separator" class="divider"></li>
  1706. // <li><a href="#">Separated link</a></li>
  1707. // </ul>
  1708. // </li>
  1709. // </ul>
  1710. ])
  1711. ])
  1712. ]);
  1713. }
  1714. public function getStorageList() {
  1715. $storageList = array();
  1716. $sth = DB::getPDO()->prepare("
  1717. select z.ID, z.`DESC`, z.`TYPE`
  1718. from CRM_LISTA_ZASOBOW z
  1719. where z.TYPE in('BAZA_DANYCH','DATABASE_MYSQL','DATABASE_POSTGRESQL')
  1720. ");
  1721. $sth->execute();
  1722. $rows = $sth->fetchAll();
  1723. foreach ($rows as $row) {
  1724. $storageList[$row['ID']] = $row;
  1725. }
  1726. return $storageList;
  1727. }
  1728. public function addAclObjectToZasobyAction() {// sends JSON
  1729. $response = new stdClass();
  1730. try {
  1731. $idStorage = V::get('idStorage', '', $_GET);
  1732. $namespace = V::get('namespace', '', $_GET);
  1733. if (empty($idStorage)) throw new HttpException("Missing idStorage param");
  1734. if (empty($namespace)) throw new HttpException("Missing namespace param");
  1735. $objectStorage = SchemaFactory::loadDefaultObject('SystemObject');
  1736. $items = $objectStorage->getItems([
  1737. 'f_namespace' => "={$namespace}",
  1738. ]);
  1739. if (empty($items)) throw new Exception("SystemObject '{$namespace}' not found");
  1740. $objectItem = reset($items);
  1741. if (empty($objectItem)) throw new Exception("SystemObject '{$namespace}' not found");
  1742. DBG::log($objectItem, 'array', 'object acl $objectItem');
  1743. if ($objectItem['idZasob'] > 0) {
  1744. // TODO: check if realy exists? @see SchemaFactory::loadDefaultObject('SystemObject')::updateCache()
  1745. $response->_replaceButtonNode = "[{$objectItem['idZasob']}]";
  1746. throw new AlertInfoException("Zasob '{$objectItem['namespace']}' już istnieje - nr '{$objectItem['idZasob']}'");
  1747. }
  1748. $idZasobFound = 0;
  1749. switch ($objectItem['_type']) {
  1750. case 'TableAcl': $idZasobFound = DB::getPDO()->fetchValue(" select ID from CRM_LISTA_ZASOBOW where PARENT_ID = {$objectItem['idDatabase']} and `DESC` = '{$objectItem['name']}' "); break;
  1751. case 'AntAcl': $idZasobFound = DB::getPDO()->fetchValue(" select ID from CRM_LISTA_ZASOBOW where PARENT_ID = {$objectItem['idDatabase']} and `DESC` = '{$objectItem['namespace']}' "); break;
  1752. default: throw new Exception("Not implemented acl type '{$objectItem['_type']}'");
  1753. }
  1754. if ($idZasobFound > 0) {
  1755. DB::getPDO()->update($objectStorage->_rootTableName, 'namespace', $objectItem['namespace'], [
  1756. 'idZasob' => $idZasobFound
  1757. ]);
  1758. $response->id = $idZasobFound;
  1759. throw new AlertSuccessException("Zasob '{$objectItem['namespace']}' już istnieje - nr '{$idZasobFound}' - cache zaktualizowany");
  1760. }
  1761. try {
  1762. $acl = User::getAcl()->getObjectAcl('default_db', 'crm_lista_zasobow');
  1763. } catch (Exception $e) {
  1764. DBG::log($e);
  1765. throw new Exception("Brak dostępu do tabeli Zasoby");
  1766. }
  1767. if (empty($objectItem['idDatabase'])) throw new Exception("Missing database id");
  1768. if ($idStorage != $objectItem['idDatabase']) throw new Exception("Database id must be the same");
  1769. if (empty($objectItem['_rootTableName'])) throw new Exception("Missing root table name");
  1770. switch ($objectItem['_type']) {
  1771. case 'TableAcl':
  1772. $newZasobItem = [
  1773. 'PARENT_ID' => $objectItem['idDatabase'],
  1774. 'TYPE' => 'TABELA',
  1775. 'DESC' => $objectItem['_rootTableName'],
  1776. 'DESC_PL' => $objectItem['name'],
  1777. ];
  1778. break;
  1779. case 'AntAcl':
  1780. $newZasobItem = [
  1781. 'PARENT_ID' => $objectItem['idDatabase'],
  1782. 'TYPE' => 'TABELA',
  1783. 'DESC' => $objectItem['namespace'],
  1784. 'DESC_PL' => $objectItem['name'],
  1785. ];
  1786. break;
  1787. default: throw new Exception("Not implemented acl type '{$objectItem['_type']}'");
  1788. }
  1789. $idCreated = $acl->addItem($newZasobItem);
  1790. if (!$idCreated) throw new Exception("Nie udało się utworzyć nowego rekordu!");
  1791. try {
  1792. DB::getPDO()->update($objectStorage->_rootTableName, 'namespace', $objectItem['namespace'], [
  1793. 'idZasob' => $idCreated
  1794. ]);
  1795. } catch (Exception $e) {
  1796. DBG::log($e);
  1797. }
  1798. $response->id = $idCreated;
  1799. $response->record = $acl->getItem($idCreated);
  1800. $response->_replaceButtonNode = "[{$idCreated}]";
  1801. throw new AlertSuccessException("Utworzono pomyślnie rekord nr {$idCreated}");
  1802. } catch (AlertSuccessException $e) {
  1803. $response->type = 'success';
  1804. $response->msg = $e->getMessage();
  1805. } catch (AlertInfoException $e) {
  1806. $response->type = 'info';
  1807. $response->msg = $e->getMessage();
  1808. } catch (Exception $e) {
  1809. $response->type = 'error';
  1810. $response->msg = $e->getMessage();
  1811. DBG::log($e);
  1812. }
  1813. Response::sendJsonExit($response);
  1814. }
  1815. public function addAclObjectToZasobyAjaxAction() {
  1816. DBG::log($_REQUEST, 'array', '$_REQUEST');
  1817. Response::sendTryCatchJson(array($this, 'addAclObjectToZasobyAjax'), $_REQUEST);
  1818. }
  1819. public function addAclObjectToZasobyAjax($args) {
  1820. $namespace = V::get('namespace', '', $args);
  1821. if (empty($namespace)) throw new HttpException("Missing namespace");
  1822. $idStorage = V::get('idStorage', '', $args);
  1823. if (empty($idStorage)) throw new HttpException("Missing idStorage");
  1824. $objectStorage = SchemaFactory::loadDefaultObject('SystemObject');
  1825. $items = $objectStorage->getItems([
  1826. 'f_namespace' => "={$namespace}",
  1827. ]);
  1828. if (empty($items)) throw new Exception("SystemObject '{$namespace}' not found");
  1829. $objectItem = reset($items);
  1830. if (empty($objectItem)) throw new Exception("SystemObject '{$namespace}' not found");
  1831. DBG::log($objectItem, 'array', 'object acl $objectItem');
  1832. if ($objectItem['idZasob'] > 0) {
  1833. // TODO: check if realy exists? @see SchemaFactory::loadDefaultObject('SystemObject')::updateCache()
  1834. return [
  1835. 'type' => 'info',
  1836. 'msg' => "Zasob '{$objectItem['namespace']}' już istnieje - nr '{$objectItem['idZasob']}'",
  1837. 'body' => [
  1838. 'id' => $objectItem['idZasob'],
  1839. 'record' => $acl->getItem($objectItem['idZasob']),
  1840. '_replaceButtonNode' => "[{$objectItem['idZasob']}]",
  1841. ]
  1842. ];
  1843. }
  1844. $idZasobFound = 0;
  1845. switch ($objectItem['_type']) {
  1846. case 'TableAcl': $idZasobFound = DB::getPDO()->fetchValue(" select ID from CRM_LISTA_ZASOBOW where PARENT_ID = {$objectItem['idDatabase']} and `DESC` = '{$objectItem['name']}' "); break;
  1847. case 'AntAcl': $idZasobFound = DB::getPDO()->fetchValue(" select ID from CRM_LISTA_ZASOBOW where PARENT_ID = {$objectItem['idDatabase']} and `DESC` = '{$objectItem['namespace']}' "); break;
  1848. default: throw new Exception("Not implemented acl type '{$objectItem['_type']}'");
  1849. }
  1850. if ($idZasobFound > 0) {
  1851. DB::getPDO()->update($objectStorage->_rootTableName, 'namespace', $objectItem['namespace'], [
  1852. 'idZasob' => $idZasobFound
  1853. ]);
  1854. return [
  1855. 'type' => 'info',
  1856. 'msg' => "Zasob '{$objectItem['namespace']}' już istnieje - nr '{$idZasobFound}' - cache zaktualizowany",
  1857. 'body' => [
  1858. 'id' => $idZasobFound,
  1859. 'record' => $acl->getItem($idZasobFound),
  1860. '_replaceButtonNode' => "[{$idZasobFound}]",
  1861. ]
  1862. ];
  1863. }
  1864. try {
  1865. $acl = User::getAcl()->getObjectAcl('default_db', 'crm_lista_zasobow');
  1866. } catch (Exception $e) {
  1867. DBG::log($e);
  1868. throw new Exception("Brak dostępu do tabeli Zasoby");
  1869. }
  1870. if (empty($objectItem['idDatabase'])) throw new Exception("Missing database id");
  1871. if ($idStorage != $objectItem['idDatabase']) throw new Exception("Database id must be the same");
  1872. if (empty($objectItem['_rootTableName'])) throw new Exception("Missing root table name");
  1873. switch ($objectItem['_type']) {
  1874. case 'TableAcl':
  1875. $newZasobItem = [
  1876. 'PARENT_ID' => $objectItem['idDatabase'],
  1877. 'TYPE' => 'TABELA',
  1878. 'DESC' => $objectItem['_rootTableName'],
  1879. 'DESC_PL' => $objectItem['name'],
  1880. ];
  1881. break;
  1882. case 'AntAcl':
  1883. $newZasobItem = [
  1884. 'PARENT_ID' => $objectItem['idDatabase'],
  1885. 'TYPE' => 'TABELA',
  1886. 'DESC' => $objectItem['namespace'],
  1887. 'DESC_PL' => $objectItem['name'],
  1888. ];
  1889. break;
  1890. default: throw new Exception("Not implemented acl type '{$objectItem['_type']}'");
  1891. }
  1892. $idCreated = $acl->addItem($newZasobItem);
  1893. if (!$idCreated) throw new Exception("Nie udało się utworzyć nowego rekordu!");
  1894. try {
  1895. DB::getPDO()->update($objectStorage->_rootTableName, 'namespace', $objectItem['namespace'], [
  1896. 'idZasob' => $idCreated
  1897. ]);
  1898. } catch (Exception $e) {
  1899. DBG::log($e);
  1900. }
  1901. return [
  1902. 'type' => 'success',
  1903. 'msg' => "Utworzono pomyślnie rekord nr {$idCreated}",
  1904. 'body' => [
  1905. 'id' => $idCreated,
  1906. 'record' => $acl->getItem($idCreated),
  1907. '_replaceButtonNode' => "[{$idCreated}]",
  1908. ]
  1909. ];
  1910. }
  1911. public function addFieldToZasobyAjaxAction() {
  1912. DBG::log($_REQUEST, 'array', '$_REQUEST');
  1913. Response::sendTryCatchJson(array($this, 'addFieldToZasobyAjax'), $_REQUEST);
  1914. }
  1915. public function addFieldToZasobyAjax($args) {
  1916. $namespace = V::get('namespace', '', $args);
  1917. if (empty($namespace)) throw new HttpException("Missing namespace");
  1918. $fieldNamespace = V::get('fieldNamespace', '', $args);
  1919. if (empty($fieldNamespace)) throw new HttpException("Missing fieldNamespace");
  1920. $fieldItem = SchemaFactory::loadDefaultObject('SystemObjectField')->getItem($fieldNamespace);
  1921. if (!$fieldItem) throw new HttpException("Field not found '{$fieldNamespace}'", 404);
  1922. DBG::log($fieldItem, 'array', "\$fieldItem");
  1923. if ($fieldItem['idZasob'] > 0) throw (new AlertSuccessException("Field already added to Zasoby '{$fieldItem['idZasob']}'"))->setBody([ 'id' => $fieldItem['idZasob'] ]);
  1924. $objectItem = SchemaFactory::loadDefaultObject('SystemObject')->getItem($namespace);
  1925. if (!$objectItem) throw new HttpException("Object not found '{$namespace}'", 404);
  1926. DBG::log($objectItem, 'array', "\$objectItem");
  1927. if (!$objectItem['idZasob']) throw new Exception("Missing Object idZasob");
  1928. $zasobItem = DB::getPDO()->fetchFirst("
  1929. select zField.ID, zField.`DESC`, zField.`TYPE`, zField.PARENT_ID
  1930. from CRM_LISTA_ZASOBOW as zField
  1931. join CRM_LISTA_ZASOBOW as zTable on(zTable.ID = zField.PARENT_ID)
  1932. where zTable.`ID` = '{$objectItem['idZasob']}'
  1933. and zTable.`TYPE` = 'TABELA'
  1934. and zField.`DESC` = '{$fieldItem['fieldNamespace']}'
  1935. and zField.`TYPE` = 'KOMORKA'
  1936. ");
  1937. if ($zasobItem) {
  1938. SchemaFactory::loadDefaultObject('SystemObjectField')->updateItem([
  1939. 'namespace' => $fieldItem['namespace'],
  1940. 'idZasob' => $zasobItem['ID']
  1941. ]);
  1942. throw (new AlertSuccessException("Zasob już istnieje"))->setBody([ 'id' => $zasobItem['ID'] ]);
  1943. }
  1944. $newFieldItem = [
  1945. 'PARENT_ID' => $objectItem['idZasob'],
  1946. 'TYPE' => 'KOMORKA',
  1947. 'DESC' => $fieldItem['fieldNamespace'],
  1948. 'DESC_PL' => $fieldItem['fieldNamespace'],
  1949. ];
  1950. DBG::log($newFieldItem, 'array', "add new field item");
  1951. try {
  1952. $acl = User::getAcl()->getObjectAcl('default_db', 'crm_lista_zasobow');
  1953. } catch (Exception $e) {
  1954. throw new Exception("Brak dostępu do tabeli Zasoby");
  1955. }
  1956. $createdId = $acl->addItem($newFieldItem);
  1957. if (!$createdId) throw new Exception("Nie udało się utworzyć nowego rekordu!");
  1958. SchemaFactory::loadDefaultObject('SystemObjectField')->updateItem([
  1959. 'namespace' => $fieldItem['namespace'],
  1960. 'idZasob' => $createdId
  1961. ]);
  1962. throw (new AlertSuccessException("Utworzono pomyślnie rekord nr {$createdId}"))->setBody([ 'id' => $createdId ]);
  1963. }
  1964. public function addCellToZasobyAction() {// sends JSON
  1965. $response = new stdClass();
  1966. try {
  1967. $idStorage = V::get('storageId', '', $_GET);
  1968. $tblName = V::get('tblName', '', $_GET, 'word');
  1969. $cellName = V::get('cellName', '', $_GET, 'word');
  1970. if (empty($tblName)) throw new HttpException("Wrong table name");
  1971. if (empty($tblName)) throw new HttpException("Wrong cell name");
  1972. $storage = DB::getStorage($idStorage);
  1973. $tableStruct = $storage->getTableStruct($tblName);
  1974. $zasobStorageId = $storage->getZasobId();
  1975. if (!is_numeric($zasobStorageId)) throw new HttpException("Storage id is not set in config file");
  1976. $idTable = $this->fetchTableId($zasobStorageId, $tblName);
  1977. if ($idTable <= 0) throw new Exception("Zasob tabela '{$tblName}' nie istnieje");
  1978. try {
  1979. $acl = User::getAcl()->getObjectAcl('default_db', 'crm_lista_zasobow');
  1980. } catch (Exception $e) {
  1981. throw new Exception("Brak dostępu do tabeli Zasoby");
  1982. }
  1983. $item = array();
  1984. $item['PARENT_ID'] = $idTable;
  1985. $item['TYPE'] = 'KOMORKA';
  1986. $item['DESC'] = $cellName;
  1987. $item['DESC_PL'] = $cellName;
  1988. if (DBG::isActive()) $response->_itemToCreate = $item;
  1989. $createdId = $acl->addItem($item);
  1990. if (!$createdId) throw new Exception("Nie udało się utworzyć nowego rekordu!");
  1991. $response->id = $createdId;
  1992. $response->record = $acl->getItem($createdId);
  1993. $response->_replaceButtonNode = "[{$createdId}]";
  1994. throw new AlertSuccessException("Utworzono pomyślnie rekord nr {$createdId}");
  1995. } catch (AlertSuccessException $e) {
  1996. $response->type = 'success';
  1997. $response->msg = $e->getMessage();
  1998. } catch (AlertInfoException $e) {
  1999. $response->type = 'info';
  2000. $response->msg = $e->getMessage();
  2001. } catch (Exception $e) {
  2002. $response->type = 'error';
  2003. $response->msg = $e->getMessage();
  2004. }
  2005. Response::sendJsonExit($response);
  2006. }
  2007. public function fetchTableId($idZasobStorage, $tblName) {
  2008. $rows = DB::getPDO()->fetchAll("
  2009. select z.`ID`, z.`DESC`
  2010. from `CRM_LISTA_ZASOBOW` z
  2011. where z.`PARENT_ID`='{$idZasobStorage}'
  2012. and z.`DESC`='{$tblName}'
  2013. and z.`A_STATUS` in('NORMAL','WAITING')
  2014. ");
  2015. if (!empty($rows)) return (int)$rows[0]['ID'];
  2016. return null;
  2017. }
  2018. public function systemObjectsStructAction() {
  2019. UI::gora();
  2020. UI::menu();
  2021. $this->navView();
  2022. try {
  2023. throw new Exception("TODO: F." . __FUNCTION__ . ' L.' . __LINE__);
  2024. // $coreObjlist = OBJXSD::getSystemObjectsStruct();
  2025. // $objectList = array();
  2026. // foreach ($coreObjlist as $objName) {
  2027. // $objItem = array();
  2028. // $objItem['name'] = $objName;
  2029. // $objItem['struktura'] = '<a href="index.php?_route=Storage&_task=systemObjectsStruct&object=' . $objName . '">' . "struct" . '</a>';
  2030. // // $objItem['label'] = "";// TODO: read from json
  2031. // $objectList[] = $objItem;
  2032. // }
  2033. // usort($objectList, function($rowA, $rowB) {
  2034. // $a = $rowA['nazwa']; $b = $rowB['nazwa'];
  2035. // if ($a == $b) return 0;
  2036. // return ($a < $b) ? -1 : 1;
  2037. // });
  2038. //
  2039. // DBG::table("objectList", $objectList, __CLASS__, __FUNCTION__, __LINE__);
  2040. } catch (Exception $e) {
  2041. UI::alert('danger', "Error #" . $e->getCode() . "|" . $e->getLine() . ": " . $e->getMessage());
  2042. }
  2043. UI::dol();
  2044. }
  2045. public function systemObjectsAction() {// TableAjax view: index.php?_route=ViewTableAjax&namespace=default_objects/SystemObject
  2046. UI::gora();
  2047. UI::menu();
  2048. $this->navView();
  2049. try {
  2050. Lib::loadClass('Schema_SystemObjectStorageAcl');
  2051. $acl = new Schema_SystemObjectStorageAcl();
  2052. UI::table([
  2053. 'rows' => array_map(
  2054. function ($item) {
  2055. return [
  2056. 'ns' => $item['namespace'],
  2057. 'nazwa' => $item['name'],
  2058. 'type' => $item['_type'],
  2059. 'edit' => '<a href="index.php?_route=ViewTableAjax&namespace=' . $item['namespace'] . '">edit</a>',
  2060. '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>',
  2061. '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)'
  2062. ];
  2063. }
  2064. , $acl->getItems([
  2065. 'order_by' => 'namespace',
  2066. 'order_dir' => 'asc'
  2067. ])
  2068. )
  2069. ]);
  2070. } catch (Exception $e) {
  2071. UI::alert('danger', "Error #" . $e->getCode() . "|" . $e->getLine() . ": " . $e->getMessage());
  2072. DBG::log($e);
  2073. }
  2074. UI::dol();
  2075. }
  2076. public function objectReinstallAction() {
  2077. UI::gora();
  2078. UI::startContainer();
  2079. try {
  2080. $namespace = V::get('namespace', '', $_GET);
  2081. if (empty($namespace)) throw new Exception("Missing param namespace");
  2082. echo UI::h('h3', [], $namespace);
  2083. Lib::loadClass('Schema_SystemObjectFieldStorageAcl');
  2084. $objFieldAcl = new Schema_SystemObjectFieldStorageAcl();
  2085. $objFieldAcl->updateCache($namespace);
  2086. {
  2087. DBG::nicePrint([
  2088. 'idInstance' => ACL::getInstanceId($namespace),
  2089. 'rootInstance' => ACL::getRootNamespace($namespace),
  2090. 'conf' => ACL::fetchInstanceConfig($namespace),
  2091. 'table' => ACL::getInstanceTable($namespace),
  2092. ], "dbg");
  2093. throw new Exception("TODO...");
  2094. }
  2095. } catch (Exception $e) {
  2096. UI::alert('danger', "Error #" . $e->getCode() . "|" . $e->getLine() . ": " . $e->getMessage());
  2097. DBG::log($e);
  2098. }
  2099. UI::endContainer();
  2100. UI::dol();
  2101. }
  2102. public function activateObjectAjaxAction() {
  2103. DBG::log($_REQUEST, 'array', '$_REQUEST');
  2104. Response::sendTryCatchJson(array($this, 'activateObjectAjax'), $_REQUEST);
  2105. }
  2106. public function activateObjectAjax($args) {
  2107. $namespace = V::get('namespace', '', $args);
  2108. if (empty($namespace)) throw new Exception("Missing param namespace");
  2109. $item = SchemaFactory::loadDefaultObject('SystemObject')->getItem($namespace, [ 'propertyName' => '*,field' ]);
  2110. if (empty($item)) throw new HttpException("Namespace not found", 404);
  2111. DBG::log($item, 'array', "TODO: activateObjectAjax \$item");
  2112. if ($item['isObjectActive']) throw new AlertSuccessException("Namespace '{$namespace}' already active");
  2113. if (!$item['hasStruct']) throw new Exception("Missing struct for namespace '{$namespace}'");
  2114. if (!$item['isStructInstalled']) throw new Exception("Namespace struct not installed '{$namespace}'");
  2115. $activeFields = array_filter($item['field'], function ($field) {
  2116. if (!$field['isActive']) return false;
  2117. if (!$field['idZasob']) return false;
  2118. return true;
  2119. });
  2120. if (empty($activeFields)) throw new Exception("Missing active fields for namespace '{$namespace}'");
  2121. $affected = SchemaFactory::loadDefaultObject('SystemObject')->updateItem([
  2122. 'namespace' => $item['namespace'],
  2123. 'isObjectActive' => 1
  2124. ]);
  2125. if ($affected < 0) throw new Exception("Nie udało się aktywować obiektu '{$namespace}'");
  2126. return [
  2127. 'type' => "success",
  2128. 'msg' => "Aktywowano obiekt '{$namespace}'",
  2129. 'body' => [
  2130. 'isObjectActive' => 1
  2131. ]
  2132. ];
  2133. }
  2134. }