| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813 |
- <?php
- // @requires $_SERVER['SERVER_NAME']
- Lib::loadClass('RouteBase');
- Lib::loadClass('Schema_TableFactory');
- Lib::loadClass('Response');
- Lib::loadClass('UI');
- Lib::loadClass('OBJ');
- Lib::loadClass('SchemaFactory');
- /*
- # Storage:
- - [x] view available storage (from Zasoby - type 'BAZA_DANYCH', 'DATABASE_MYSQL', ...)
- - [x] check config for connection
- - [x] add cells to Zasoby
- - [ ] create cells in Storage
- - [x] use PDO
- */
- class Route_Storage extends RouteBase {
- public function handleAuth() {
- if (!User::logged()) {
- User::authByRequest();
- }
- }
- public function defaultAction() {
- UI::gora();
- UI::menu();
- $this->navView();
- UI::startContainer();
- try {
- $sourceStorage = SchemaFactory::loadDefaultObject('SystemSource');
- try {
- $sourceStorage->getTotal();
- } catch (Exception $e) {
- UI::alert('warning', $e->getMessage());
- $sourceStorage->updateCache();
- UI::alert('info', "Lista dostępnych baz danych zaktualizowana");
- }
- if ('1' == V::get('refreshSourceList', '', $_POST)) {
- $sourceStorage->updateCache();
- UI::alert('info', "Lista dostępnych baz danych zaktualizowana");
- }
- UI::table([
- 'caption' => "Bazy danych " .
- UI::hButtonPost('<i class="glyphicon glyphicon-refresh"></i>' . " odśwież", [
- 'class' => "btn btn-xs btn-link",
- 'data' => [
- 'refreshSourceList' => '1'
- ]
- ]),
- 'rows' => array_merge(
- array_map(function ($item) {
- return [
- 'Nr zasobu' => $item['idZasob'],
- 'nazwa' => $item['name'],
- 'opis' => $item['description'],
- 'config?' => ($item['hasConfig']) ? '<span class="label label-success">TAK</span>' : '<span class="text text-muted">brak</span>',
- 'obiekty' => UI::h('a', [ 'href' => $this->getLink('tableList', [ 'idStorage' => $item['idZasob'] ]) ], "obiekty"),
- 'raw info' => UI::h('a', [ 'href' => $this->getLink('rawInfo', [ 'idStorage' => $item['idZasob'] ]) ], "raw info"),
- 'xsd' => UI::h('a', [ 'href' => $this->getLink('xsd', [ 'idStorage' => $item['idZasob'] ]) ], "xsd"),
- ];
- }, $sourceStorage->getItems())
- , [
- [
- 'Nr zasobu' => '',
- 'nazwa' => "Obiekty",
- 'opis' => "SystemObjects",
- 'config?' => '<span class="text text-muted">brak</span>',
- 'obiekty' => UI::h('a', [ 'href' => $this->getLink('systemObjects') ], "obiekty"),
- ],
- [
- 'Nr zasobu' => '',
- 'nazwa' => "Obiekty Test",
- 'opis' => "Obiekty podstawowe (test json)",
- 'config?' => '<span class="text text-muted">brak</span>',
- 'obiekty' => UI::h('a', [ 'href' => $this->getLink('coreObjectList') ], "obiekty"),
- 'raw info' => UI::h('a', [ 'href' => $this->getLink('coreObjectParseAll') ], "raw info"),
- ],
- [
- 'Nr zasobu' => '',
- 'nazwa' => "Obiekty Test",
- 'opis' => "Obiekty dla domeny '" . str_replace(array(".", "-"), '_', $_SERVER['SERVER_NAME']) . "' (test json)",
- 'config?' => '<span class="text text-muted">brak</span>',
- 'obiekty' => UI::h('a', [ 'href' => $this->getLink('objectList') ], "obiekty"),
- // 'raw info' => UI::h('a', [ 'href' => $this->getLink('objectRawInfo') ], "raw info"),
- ],
- ]
- )
- ]);
- // $sourceStorage = SchemaFactory::loadDefaultObject('SystemObject');
- // $sourceStorage->updateCache();
- } catch (Exception $e) {
- UI::alert('danger', "Error #" . $e->getCode() . "|" . $e->getLine() . ": " . $e->getMessage());
- }
- UI::endContainer();
- UI::dol();
- }
- public function checkObjectInstallAjaxAction() {
- $response = array();
- try {
- $objectName = V::get('object', '', $_REQUEST, 'word');
- if (empty($objectName)) throw new Exception("Missing Object name");
- $response['object'] = $objectName;
- $json = OBJ::getCoreObjectFromFile($objectName);
- OBJ::checkInstall($json);
- $response['type'] = 'success';
- $response['msg'] = "OK - object installed";
- } catch (Exception $e) {
- $response['type'] = 'error';
- $response['msg'] = $e->getMessage();
- $response['code'] = $e->getCode();
- $response['line'] = $e->getLine();
- }
- Response::sendJsonExit($response);
- }
- public function coreObjectStructAction() {
- UI::gora();
- UI::menu();
- $this->navView();
- try {
- $objectName = V::get('object', '', $_REQUEST, 'word');
- if (empty($objectName)) throw new Exception("Missing Object name");
- $json = OBJ::getCoreObjectFromFile($objectName);
- $label = OBJ::getLabel($json);
- $parentList = OBJ::getParentList($json);
- $linksParentList = array(); foreach ($parentList as $parentName) {
- $parentLink = '<a href="index.php?_route=Storage&_task=coreObjectStruct&object=' . str_replace('/', '-', $parentName) . '">' . $parentName . '</a>';
- array_unshift($linksParentList, $parentLink);
- }
- $ajaxCheckInstall = Request::getPathUri() . "index.php?_route=Storage&_task=checkObjectInstallAjax&object={$objectName}";
- $onClick = "return p5UI__ButtonAjax(this, 'p5UIBtnAjax:Storage:checkObjectInstallAjax', { href: '{$ajaxCheckInstall}' })";
- $btnCheckInstall = '<a onclick="'.$onClick.'" href="#" title="check install db tables"><i class="glyphicon glyphicon-cog"></i></a>';
- UI::startContainer();
- UI::tag('h1', [], "Obiekt <code>{$label}</code> <small>{$btnCheckInstall}</small>");
- if (!empty($parentList)) {
- UI::startTag('ol', ['class'=>"breadcrumb"]);
- UI::tag('li', [], "Dziedziczy z:");
- foreach ($linksParentList as $parentLink) {
- UI::tag('li', [], $parentLink);
- }
- // <!-- <li class="active">Data</li> -->
- UI::endTag('ol');
- // <!-- <p> implode(", ", $parentList);</p> -->
- }
- // TODO: UI::table(['rows'=>array_map()]);
- ?>
- <table class="table table-bordered table-hovered">
- <caption>Struktura:</caption>
- <thead>
- <tr>
- <th>nazwa</th>
- <th>typ</th>
- <th>label</th>
- <th>json</th>
- </tr>
- </thead>
- <tbody>
- <?php foreach (OBJ::getFields($json) as $fieldName => $field) : ?>
- <tr>
- <td><?php echo $fieldName; ?></td>
- <td><?php echo $field['type']; ?></td>
- <td><?php echo $field['label']; ?></td>
- <td><?php echo json_encode($field); ?></td>
- </tr>
- <?php endforeach; ?>
- </tbody>
- </table>
- <a href="index.php?_route=Storage&_task=coreObjectConnect&object=<?php echo $objectName; ?>" class="btn btn-primary">Przypisz rekordy do klasy</a>
- <?php
- $mainTable = OBJ::getMainTableName($json);
- $sqlFields = OBJ::getTableFields($json);
- $this->showTableWidget($mainTable, $sqlFields);
- ?>
- </div>
- <script>
- jQuery(document).on('p5UIBtnAjax:Storage:checkObjectInstallAjax:click', function(e, n, payload) {
- console.log('event p5UIBtnAjax:Storage:checkObjectInstallAjax:click', n, payload);
- });
- jQuery(document).on('p5UIBtnAjax:Storage:checkObjectInstallAjax:ajaxLoaded', function(e, n, payload) {
- console.log('event p5UIBtnAjax:Storage:checkObjectInstallAjax:ajaxLoaded', n, payload);
- if ('success' == payload.type) {
- // jQuery(n).parents('td').text(payload.body.id);
- }
- jQuery.notify(payload.msg, payload.type);
- });
- </script>
- <?php
- DBG::_(true, true, "json", $json, __CLASS__, __FUNCTION__, __LINE__);
- } catch (Exception $e) {
- UI::alert('danger', "Error #" . $e->getCode() . "|" . $e->getLine() . ": " . $e->getMessage());
- }
- UI::dol();
- }
- public function coreObjectConnectAction() {
- UI::gora();
- UI::menu();
- $this->navView();
- try {
- $objectName = V::get('object', '', $_REQUEST, 'word');
- if (empty($objectName)) throw new Exception("Missing Object name");
- $json = OBJ::getCoreObjectFromFile($objectName);
- $label = OBJ::getLabel($json);
- $parentList = OBJ::getParentList($json);
- $linksParentList = array(); foreach ($parentList as $parentName) {
- $parentLink = '<a href="index.php?_route=Storage&_task=coreObjectStruct&object=' . str_replace('/', '-', $parentName) . '">' . $parentName . '</a>';
- array_unshift($linksParentList, $parentLink);
- }
- $ajaxCheckInstall = Request::getPathUri() . "index.php?_route=Storage&_task=checkObjectInstallAjax&object={$objectName}";
- $onClick = "return p5UI__ButtonAjax(this, 'p5UIBtnAjax:Storage:checkObjectInstallAjax', { href: '{$ajaxCheckInstall}' })";
- $btnCheckInstall = '<a onclick="'.$onClick.'" href="#" title="check install db tables"><i class="glyphicon glyphicon-cog"></i></a>';
- ?>
- <div class="container">
- <h1>Obiekt <code><?php echo $label; ?></code> <small><?php echo $btnCheckInstall; ?></small></h1>
- <?php if (!empty($parentList)) : ?>
- <ol class="breadcrumb">
- <li>Dziedziczy z:</li>
- <?php foreach ($linksParentList as $parentLink) : ?>
- <li><?php echo $parentLink; ?></li>
- <?php endforeach; ?>
- <!-- <li class="active">Data</li> -->
- </ol>
- <!-- <p> <?php echo implode(", ", $parentList); ?></p> -->
- <?php endif; ?>
- <?php
- $tableOne = array();
- $tableOne['caption'] = 'Klasy';
- $tableOne['rows'] = array();
- $parentList = OBJ::getParentList($json);
- $tableOne['rows'][] = array('__primary_key' => $objectName, 'name' => $objectName);
- $linksParentList = array(); foreach ($parentList as $parentName) {
- // $parentLink = '<a href="index.php?_route=Storage&_task=coreObjectStruct&object=' . str_replace('/', '-', $parentName) . '">' . $parentName . '</a>';
- // array_unshift($linksParentList, $parentLink);
- $tableOne['rows'][] = array('__primary_key' => $parentName, 'name' => $parentName);
- }
- $tableTwo = array();
- $tableTwo['caption'] = 'Rekordy w tabeli głównej';
- $mainTable = OBJ::getMainTableName($json);
- $sqlFields = OBJ::getTableFields($json);
- $tableTwo['rows'] = $this->getTableRows($mainTable, $sqlFields);
- foreach ($tableTwo['rows'] as $idx => $row) {
- // $tableTwo['rows'][] = array('__primary_key' => $objectName, 'name' => $objectName);
- $tableTwo['rows'][$idx]['__primary_key'] = $row['ID'];
- }
- echo '<hr>';
- // TODO: filter connected rows
- // TODO: filter not connected rows
- // TODO: action connect rows - args(schema, rows_primary_key_list)
- // TODO: action un connect rows - args(schema, rows_primary_key_list)
- $this->showConnectSchemaToTableWidget(compact('tableOne', 'tableTwo'));
- ?>
- </div>
- <script>
- jQuery(document).on('p5UIBtnAjax:Storage:checkObjectInstallAjax:click', function(e, n, payload) {
- console.log('event p5UIBtnAjax:Storage:checkObjectInstallAjax:click', n, payload);
- });
- jQuery(document).on('p5UIBtnAjax:Storage:checkObjectInstallAjax:ajaxLoaded', function(e, n, payload) {
- console.log('event p5UIBtnAjax:Storage:checkObjectInstallAjax:ajaxLoaded', n, payload);
- if ('success' == payload.type) {
- // jQuery(n).parents('td').text(payload.body.id);
- }
- jQuery.notify(payload.msg, payload.type);
- });
- </script>
- <?php
- DBG::_(true, true, "json", $json, __CLASS__, __FUNCTION__, __LINE__);
- } catch (Exception $e) {
- UI::alert('danger', "Error #" . $e->getCode() . "|" . $e->getLine() . ": " . $e->getMessage());
- }
- UI::dol();
- }
- public function showConnectSchemaToTableWidget($params) {
- if (empty($params['tableOne'])) throw new Exception("Missing tableOne in Connect widget");
- if (empty($params['tableTwo'])) throw new Exception("Missing tableTwo in Connect widget");
- $tableOne = $params['tableOne'];
- $tableTwo = $params['tableTwo'];
- // TODO: add p5BtnAjax to table filters button
- // TODO: add p5BtnAjax to conn button
- $jsEventNamespace = 'ConnectTableWidget' . time();
- $htmlIdWrap = "{$jsEventNamespace}-wrap";
- $stateLogId = "{$jsEventNamespace}-state-log";
- $stateSelectedTotalId = "{$jsEventNamespace}-state-selected";
- $stateClearSelectedBtnId = "{$jsEventNamespace}-state-clear-selected-btn";
- foreach ($tableOne['rows'] as $idx => $r) {
- $tableOne['rows'][$idx]['@onClick'] = "return p5UI__Clickable(this, '{$jsEventNamespace}:tableOne', { primary_key: '{$r['__primary_key']}' });";
- }
- foreach ($tableTwo['rows'] as $idx => $r) {
- $tableTwo['rows'][$idx]['@onClick'] = "return p5UI__Clickable(this, '{$jsEventNamespace}:tableTwo', { primary_key: '{$r['__primary_key']}' });";
- }
- $tableOne['hidden_cols'] = $tableTwo['hidden_cols'] = array('__primary_key', '@onClick', '__html_id');
- $tableTwo['__html_id'] = "{$jsEventNamespace}-table-two";
- ?>
- <div id="<?php echo $htmlIdWrap; ?>">
- <?php UI::table($tableOne); ?>
- <div class="btn-group">
- <button class="btn btn-default" title="Wybierz rekordy wg instancji"><i class="glyphicon glyphicon-question-sign"></i></button>
- <button class="btn btn-default conn-btn-filter-yes">Przypisani</button>
- <button class="btn btn-default conn-btn-filter-no active">Nieprzypisani</button>
- <button class="btn btn-default conn-btn-filter-clear" title="Wszystkie"><i class="glyphicon glyphicon-remove"></i></button>
- </div>
- <div class="btn-group">
- <span style="padding-left:30px;">Zaznaczono
- <span class="conn-selected-total">0</span>
- <button class="conn-btn-clear-selected btn btn-link"
- onClick="return p5UI__Clickable(this, '<?php echo $jsEventNamespace; ?>:clearSelection', {});"
- style="display:none"><i class="glyphicon glyphicon-remove" style="color:red"></i></button>
- </span>
- </div>
- <?php UI::jsAjaxTable($tableTwo); ?>
- <pre class="conn-log"></pre>
- </div>
- <script>
- (function(){
- var state = {
- selectedTableOne: null,
- selectedTableTwo: [],
- filterSelected: 'no'
- }
- var props = {
- jsEventNamespace: '<?php echo $jsEventNamespace; ?>',
- htmlIdWrap: '<?php echo $htmlIdWrap; ?>',
- tableTwoId: '#<?php echo $tableTwo['__html_id']; ?>',
- stateSelectedTotalId: '#<?php echo $stateSelectedTotalId; ?>',
- stateClearSelectedBtnId: '#<?php echo $stateClearSelectedBtnId; ?>',
- stateLogId: '#<?php echo $stateLogId; ?>'
- }
- var wrap = jQuery('#' + props.htmlIdWrap);
- var jqNodes = {
- wrap: wrap,
- filter_yes: wrap.find('.conn-btn-filter-yes'),
- filter_no: wrap.find('.conn-btn-filter-no'),
- filter_clear: wrap.find('.conn-btn-filter-clear'),
- total_selected: wrap.find('.conn-selected-total'),
- btn_clear_selected: wrap.find('.conn-btn-clear-selected'),
- state_log: wrap.find('.conn-log')
- }
- function render() {
- jqNodes['total_selected'].text(state.selectedTableTwo.length);
- if (state.selectedTableTwo.length > 0) {
- jQuery(props.stateClearSelectedBtnId).show();
- } else {
- jQuery(props.stateClearSelectedBtnId).hide();
- }
- jqNodes['state_log'].text(JSON.stringify(state));
- switch (state.filterSelected) {
- case 'yes':
- jqNodes['filter_yes'].addClass('active');
- jqNodes['filter_no'].removeClass('active');
- jqNodes['filter_clear'].removeClass('active');
- break;
- case 'no':
- jqNodes['filter_yes'].removeClass('active');
- jqNodes['filter_no'].addClass('active');
- jqNodes['filter_clear'].removeClass('active');
- break;
- case 'clear':
- jqNodes['filter_yes'].removeClass('active');
- jqNodes['filter_no'].removeClass('active');
- jqNodes['filter_clear'].addClass('active');
- break;
- }
- }
- function action__selectTableOneRow(pk) {
- state.selectedTableOne = pk;
- render();
- }
- function action__unselectTableOneRow() {
- state.selectedTableOne = null;
- render();
- }
- function action__selectTableTwoRow(pk) {
- var idx = state.selectedTableTwo.indexOf(pk);
- if (-1 === idx) state.selectedTableTwo.push(pk);
- else console.log("Error selectedTableTwo - should be not set");
- render();
- }
- function action__unselectTableTwoRow(pk) {
- var idx = state.selectedTableTwo.indexOf(pk);
- if (-1 === idx) state.selectedTableTwo.push(pk);
- else state.selectedTableTwo.splice(idx, 1);
- render();
- }
- function action__clearSelection() {
- state.selectedTableTwo = [];
- jQuery(props.tableTwoId).find('tbody').children('.info').removeClass('info');
- render();
- }
- function action__filterSet(fltr) {
- state.filterSelected = fltr;
- render();
- // TODO: ajax load tableTwo based on filter
- }
- jQuery(document).on(props.jsEventNamespace + ':tableOne:click', function(e, n, payload) {
- var n$ = jQuery(n);
- console.log('event '+props.jsEventNamespace+':tableOne:click', n, payload);
- jQuery.notify('tableOne row clicked [' + payload.props.primary_key + ']', 'info');
- if (n$.hasClass('info')) {
- n$.removeClass('info');
- action__unselectTableOneRow();
- } else {
- n$.parent().children('.info').removeClass('info');
- n$.addClass('info');
- action__selectTableOneRow(payload.props.primary_key);
- }
- });
- jQuery(document).on(props.jsEventNamespace + ':tableTwo:click', function(e, n, payload) {
- var n$ = jQuery(n);
- console.log('event '+props.jsEventNamespace+':tableTwo:click', n, payload);
- jQuery.notify('tableTwo row clicked [' + payload.props.primary_key + ']', 'info');
- if (n$.hasClass('info')) {
- n$.removeClass('info');
- action__unselectTableTwoRow(payload.props.primary_key);
- } else {
- n$.addClass('info');
- action__selectTableTwoRow(payload.props.primary_key);
- }
- });
- jQuery(document).on(props.jsEventNamespace + ':clearSelection:click', function(e, n, payload) {
- action__clearSelection();
- });
- jqNodes['filter_yes'].on('click', function(e) {
- action__filterSet('yes');
- });
- jqNodes['filter_no'].on('click', function(e) {
- action__filterSet('no');
- });
- jqNodes['filter_clear'].on('click', function(e) {
- action__filterSet('clear');
- });
- })();
- </script>
- <?php
- }
- public function getTableRows($tblName, $fields) {
- $sqlFields = array();
- foreach ($fields as $fldName) {
- $sqlFields[] = "t.`{$fldName}`";
- }
- $sqlFields = (!empty($sqlFields))? implode(", ", $sqlFields) : "t.*";
- $rows = DB::getPDO()->fetchAll("
- select {$sqlFields}
- from `{$tblName}` t
- where 1=1
- limit 10
- ");
- return $rows;
- }
- public function showTableWidget($tblName, $fields) {
- $rows = $this->getTableRows($tblName, $fields);
- UI::table(array('caption' => "table({$tblName})", 'rows' => $rows));
- }
- public function coreObjectParseAllAction() {
- UI::gora();
- UI::menu();
- $this->navView();
- try {
- OBJ::parseAll();
- } catch (Exception $e) {
- UI::alert('danger', "Error #" . $e->getCode() . "|" . $e->getLine() . ": " . $e->getMessage());
- }
- UI::dol();
- }
- public function coreObjectListAction() {
- UI::gora();
- UI::menu();
- $this->navView();
- try {
- $coreObjlist = OBJ::getCoreObjectList();
- $objectList = array();
- foreach ($coreObjlist as $objName) {
- $objItem = array();
- $objItem['name'] = $objName;
- $objItem['struktura'] = '<a href="index.php?_route=Storage&_task=coreObjectStruct&object=' . $objName . '">' . "struct" . '</a>';
- // $objItem['label'] = "";// TODO: read from json
- $objectList[] = $objItem;
- }
- usort($objectList, function($rowA, $rowB) {
- $a = $rowA['nazwa']; $b = $rowB['nazwa'];
- if ($a == $b) return 0;
- return ($a < $b) ? -1 : 1;
- });
- DBG::table("objectList", $objectList, __CLASS__, __FUNCTION__, __LINE__);
- } catch (Exception $e) {
- UI::alert('danger', "Error #" . $e->getCode() . "|" . $e->getLine() . ": " . $e->getMessage());
- }
- UI::dol();
- }
- public function objectListAction() {
- UI::gora();
- UI::menu();
- try {
- } catch (Exception $e) {
- UI::alert('danger', "Error #" . $e->getCode() . "|" . $e->getLine() . ": " . $e->getMessage());
- }
- UI::dol();
- }
- public function tableListAction() {
- UI::gora();
- UI::menu();
- $this->navView();
- UI::startContainer();
- try {
- $idStorage = V::get('idStorage', 0, $_REQUEST, 'int');
- if (empty($idStorage)) throw new Exception("Missing id storage");
- $sourceStorage = SchemaFactory::loadDefaultObject('SystemSource');
- $sourceItem = $sourceStorage->getItem($idStorage);
- if (!$sourceItem) throw new Exception("Storage id='{$idStorage}' not exists");
- DBG::log($sourceItem, 'array', '$sourceItem');
- // TODO: fetch SystemObject childrens from $sourceItem:
- // 1. 'SystemSource' -> getItems([ 'cols' => 'SystemObject/*', 'featureId' => $sourceItem['idZasob'] ])
- // 2. 'SystemObject' -> getItems([ 'refFrom' => $sourceItem['idZasob'] ])
- // 'default_objects' => _task=systemObjects
- $objectStorage = SchemaFactory::loadDefaultObject('SystemObject');
- try {
- $objectStorage->getTotal();
- } catch (Exception $e) {
- UI::alert('warning', $e->getMessage());
- DBG::log($e);
- $objectStorage->updateCache();
- UI::alert('info', "Lista obiketów zaktualizowana");
- }
- if ('1' == V::get('refreshObjectList', '', $_POST)) {
- $objectStorage->updateCache();
- UI::alert('info', "Lista obiketów zaktualizowana");
- }
- UI::table([
- 'caption' => "Obiekty w bazie '{$sourceItem['name']}' " .
- UI::hButtonPost('<i class="glyphicon glyphicon-refresh"></i>' . " odśwież", [
- 'class' => "btn btn-xs btn-link",
- 'data' => [
- 'refreshObjectList' => '1'
- ]
- ]),
- 'rows' => array_map(function ($item) use ($idStorage) {
- $addToZasobyLink = $this->getLink('addAclObjectToZasoby', ['idStorage' => $idStorage, 'namespace' => $item['namespace']]);
- return [
- 'namespace' => '<span style="color:#888">' . substr($item['namespace'], 0, strlen($item['namespace']) - strlen($item['name'])) . '</span>' .
- '<span>' . $item['name'] . '</span>',
- '_type' => $item['_type'], // TODO: editable?
- 'Nr zasobu' => ($item['idZasob'] > 0)
- ? $item['idZasob']
- : UI::h('button', [
- 'class' => "btn btn-xs btn-primary",
- 'onClick' => "return p5UI__ButtonAjax(this, 'p5UIBtnAjax:Storage:addAclObjectToZasoby', { href: '{$addToZasobyLink}' })"
- ], "Dodaj do Zasobów"),
- // 'opis' => $item['description'],
- 'active?' => ($item['isActive']) ? '<span class="label label-success">TAK</span>' : '<span class="text text-muted">nie</span>',
- 'struktura' => UI::h('a', [ 'href' => $this->getLink('tableStruct', [ 'idStorage' => $idStorage, 'table' => $item['name'] ]) ], "struktura"),
- 'struktura OBJ' => UI::h('a', [ 'href' => $this->getLink('objectStruct', [ 'idStorage' => $idStorage, 'namespace' => $item['namespace'] ]) ], "obj struct"),
- 'raw info' => UI::h('a', [ 'href' => $this->getLink('rawInfo', [ 'idStorage' => $idStorage, 'table' => $item['name'] ]) ], "raw info"),
- 'reinstall' => UI::h('a', [ 'href' => $item['reinstallLink'] ], "reinstall"),
- // 'xsd' => UI::h('a', [ 'href' => $this->getLink('xsd', [ 'idStorage' => $idStorage ]) ], "xsd"),
- ];
- }, $objectStorage->getItems([
- '#refFrom' => [
- 'namespace' => 'default_objects/SystemSource',
- 'primaryKey' => $sourceItem['idZasob']
- ],
- 'order_by' => 'namespace',
- 'order_dir' => 'asc'
- ]))
- ]);
- echo UI::h('script', [], "
- jQuery(document).on('p5UIBtnAjax:Storage:addAclObjectToZasoby:click', function(e, n, payload) {
- console.log('event p5UIBtnAjax:Storage:addAclObjectToZasoby:click', n, payload);
- });
- jQuery(document).on('p5UIBtnAjax:Storage:addAclObjectToZasoby:ajaxLoaded', function(e, n, payload) {
- console.log('event p5UIBtnAjax:Storage:addAclObjectToZasoby:ajaxLoaded', n, payload);
- if ('success' == payload.type && payload.body && payload.body.id > 0) {
- jQuery(n).parents('td').text(payload.body.id);
- }
- jQuery.notify(payload.msg, payload.type);
- });
- ");
- } catch (Exception $e) {
- UI::alert('danger', "Error #" . $e->getCode() . "|" . $e->getLine() . ": " . $e->getMessage());
- DBG::log($e);
- }
- UI::endContainer();
- UI::dol();
- }
- public function rawInfoAction() {
- UI::gora();
- UI::menu();
- $this->navView();
- try {
- $idStorage = V::get('idStorage', 0, $_REQUEST, 'int');
- if (empty($idStorage)) throw new Exception("Missing id storage");
- $storageList = $this->getStorageList();
- if (empty($storageList)) throw new Exception("No storage defined");
- if (!array_key_exists($idStorage, $storageList)) throw new Exception("Storage not exists");
- $storagePdo = DB::getStorage($idStorage);
- $rawInfo = $storagePdo->getTableListWithInfo();
- DBG::table("rawInfo", $rawInfo, __CLASS__, __FUNCTION__, __LINE__);
- } catch (Exception $e) {
- UI::alert('danger', "Error #" . $e->getCode() . "|" . $e->getLine() . ": " . $e->getMessage());
- }
- UI::dol();
- }
- public function objectStructAction() {
- UI::gora();
- UI::menu();
- $this->navView();
- try {
- $namespace = V::get('namespace', '', $_GET);
- if (empty($namespace)) throw new Exception("Missing param namespace");
- $item = $this->getObjectAclRow($namespace);
- DBG::nicePrint($item, '$item');
- // DBG::log($item, 'array', '$item');
- switch ($item['_type']) {
- case 'TableAcl': $this->structTableAclView($item); break;
- default: throw new Exception("Not implemented struct view for '{$namespace}'");
- }
- } catch (Exception $e) {
- UI::alert('danger', "Error #" . $e->getCode() . "|" . $e->getLine() . ": " . $e->getMessage());
- DBG::log($e);
- }
- UI::dol();
- }
- public function structTableAclView($item) {
- UI::table([
- 'caption' => UI::h('h3', [], "Struktura obiektu '{$item['namespace']}'"),
- 'rows' => array_map(function ($field) {
- return $field;
- }, $this->getObjectFields($item))
- ]);
- }
- public function getObjectFields($namespace) {
- Lib::loadClass('Schema_SystemObjectFieldStorageAcl');
- $acl = new Schema_SystemObjectFieldStorageAcl();
- $items = $acl->getItems([
- '#refFrom' => [
- 'namespace' => 'default_objects/SystemObject',
- 'primaryKey' => $namespace
- ],
- 'order_by' => 'namespace',
- 'order_dir' => 'asc'
- ]);
- if (empty($items)) throw new Exception("SystemObject '{$namespace}' not found");
- $item = reset($items);
- if (empty($item)) throw new Exception("SystemObject '{$namespace}' not found");
- return $item;
- }
- public function tableStructAction() {
- UI::gora();
- UI::menu();
- $this->navView();
- try {
- $idStorage = V::get('idStorage', 0, $_REQUEST, 'int');
- if (empty($idStorage)) throw new Exception("Missing id storage");
- $storageList = $this->getStorageList();
- if (empty($storageList)) throw new Exception("No storage defined");
- if (!array_key_exists($idStorage, $storageList)) throw new Exception("Storage not exists");
- $tblName = V::get('table', '', $_REQUEST, 'word');
- if (empty($tblName)) throw new Exception("No table name");
- $storagePdo = DB::getStorage($idStorage);
- $tblStruct = $storagePdo->getTableStruct($tblName);
- $idTable = $this->fetchTableId($idStorage, $tblName);
- if ($idTable <= 0) {
- UI::alert('warning', "Zasob tabela '{$tblName}' nie istnieje");// TODO: add p5UI btn
- DBG::table("tblStruct", $tblStruct, __CLASS__, __FUNCTION__, __LINE__);
- throw new Exception("Zasob tabela '{$tblName}' nie istnieje");
- }
- $cellZasobList = array();
- foreach (DB::getPDO()->fetchAllByKey("
- select z.ID, z.`DESC`, z.`TYPE` as ZASOB_TYPE, z.A_STATUS
- from CRM_LISTA_ZASOBOW z
- where z.PARENT_ID = '{$idTable}'
- ", $key = 'DESC') as $ind => $row) {
- $cellZasobList[strtolower($ind)] = $row;
- }
- $emptyItem = array();
- $emptyItem['name'] = '';
- $emptyItem['id_zasob'] = '';
- $emptyItem['zasob_type'] = '';
- $emptyItem['uwagi'] = '';
- $emptyItem['type'] = '';
- $emptyItem['is_nullable'] = '';
- $emptyItem['default_value'] = '';
- $emptyItem['default_is_null'] = '';
- $emptyItem['max_length'] = '';
- $emptyItem['num_precision'] = '';
- $emptyItem['num_scale'] = '';
- $emptyItem['char_encoding'] = '';
- $emptyItem['char_collation'] = '';
- $emptyItem['extra'] = '';
- $emptyItem['raw_storage_type'] = '';
- $tableList = array();
- foreach ($tblStruct as $row) {
- $cellName = $row['name'];
- $tblItem = V::cloneArray($emptyItem);
- $tblItem['name'] = $cellName;
- foreach ($row as $fldName => $fldVal) {
- if (array_key_exists($fldName, $tblItem)) $tblItem[$fldName] = $fldVal;
- }
- $tblItem['uwagi'] = '';
- $lowerCellName = strtolower($cellName);
- $tblZasob = V::get($lowerCellName, '', $cellZasobList);
- if ($tblZasob) {
- $cellZasobList[$lowerCellName]['_checked'] = true;
- $tblItem['id_zasob'] = $tblZasob['ID'];
- $tblItem['zasob_type'] = $tblZasob['ZASOB_TYPE'];
- } else {
- $tblItem['uwagi'] .= '!Zasob';//'TODO: ADD ZASOB';
- $ajaxAddZasobLink = Request::getPathUri() . "index.php?_route=Storage&_task=addCellToZasoby&idStorage={$idStorage}&tblName={$tblName}&cellName={$cellName}";
- $onClick = "return p5UI__ButtonAjax(this, 'p5UIBtnAjax:Storage:addCellToZasoby', { href: '{$ajaxAddZasobLink}' })";
- $tblItem['id_zasob'] = '<a onclick="'.$onClick.'" class="btn btn-xs btn-primary" href="#">TODO: ADD ZASOB</a>';
- }
- $tableList[] = $tblItem;
- }
- foreach ($cellZasobList as $cellName => $row) {
- if ('URL_ACTION' == $row['ZASOB_TYPE']) continue;
- if (!$row['_checked']) {
- $tblItem = V::cloneArray($emptyItem);
- $tblItem['name'] = $cellName;
- $tblItem['id_zasob'] = $row['ID'];
- $tblItem['zasob_type'] = $row['ZASOB_TYPE'];
- $tblItem['uwagi'] = '!DB';//'TODO: nie istnieje w bazie danych';
- $tableList[] = $tblItem;
- }
- }
- usort($tableList, function($rowA, $rowB) {
- $a = $rowA['name']; $b = $rowB['name'];
- if ('ID' == $a) return -1;
- if ('ID' == $b) return 1;
- if ($a == $b) return 0;
- $a1 = substr($a, 0, 1); $b1 = substr($b, 0, 1);
- if (('_' == $a1 || '_' == $b1) && $a1 != $b1) {
- return ($a1 < $b1) ? 1 : -1;
- }
- return ($a < $b) ? -1 : 1;
- });
- UI::table([
- 'caption' => UI::h('span', [], [
- "Komórki [{$idTable}] ",
- UI::h('a', [
- 'href' => "index.php?_route=ViewTableAjax&namespace=default_db/{$tblName}",
- 'class' => "btn btn-md btn-link"
- ], "Przeglądaj tabelę"),
- UI::h('a', [
- 'href' => "procesy5.php?task=CRM_LISTA_ZASOBOW&filtr_id={$idTable}&filtr_ids=%2B&filtr_ob=%2B",
- 'class' => "btn btn-md btn-link",
- 'title' => "Struktura aktualnie przeglądanej tabeli"
- ], "Zasoby"),
- UI::h('a', [
- 'href' => "index.php?FUNCTION_INIT=PROCES_MENU&HEADER_NOT_INIT=YES&_task=PROCES_FOR_TABLE&tblId={$idTable}",
- 'class' => "btn btn-md btn-link",
- 'title' => "Procesy dla aktualnie przeglądanej tabeli"
- ], "Procesy"),
- ]),
- 'cols' => array_keys($emptyItem),
- 'rows' => $tableList
- ]);
- echo UI::h('script', [], "
- jQuery(document).on('p5UIBtnAjax:Storage:addCellToZasoby:click', function(e, n, payload) {
- console.log('event p5UIBtnAjax:Storage:addCellToZasoby:click', n, payload);
- });
- jQuery(document).on('p5UIBtnAjax:Storage:addCellToZasoby:ajaxLoaded', function(e, n, payload) {
- console.log('event p5UIBtnAjax:Storage:addCellToZasoby:ajaxLoaded', n, payload);
- if ('success' == payload.type && payload.body && payload.body.id > 0) {
- var cellUwagiJQNode = jQuery(n).parents('td').next('td');
- cellUwagiJQNode.text(cellUwagiJQNode.text().replace('!Zasob', ''))
- jQuery(n).parents('td').text(payload.body.id);
- jQuery(n).remove();
- }
- jQuery.notify(payload.msg, payload.type);
- });
- ");
- $ajaxAddZasobLink = Request::getPathUri() . "index.php?_route=Storage&_task=addGeomEtykietaCells&idStorage={$idStorage}&tblName={$tblName}";
- $onClick = "return p5UI__ButtonAjax(this, 'p5UIBtnAjax:Storage:addGeomEtykietaCells', { href: '{$ajaxAddZasobLink}' })";
- UI::tag('a', ['onclick'=>$onClick, 'class'=>"btn btn-xs btn-default", 'href'=>"#"], "Dodaj komórki etykiet", true);
- echo "<i>(<code>`etykieta_x`</code>, <code>`etykieta_y`</code>, <code>`etykieta_obrot`</code>)</i>";
- echo UI::h('script', [], "
- jQuery(document).on('p5UIBtnAjax:Storage:addGeomEtykietaCells:ajaxLoaded', function(e, n, payload) {
- console.log('event p5UIBtnAjax:Storage:addGeomEtykietaCells:ajaxLoaded', n, payload);
- if ('success' == payload.type && payload.body && payload.body.id > 0) {
- var cellUwagiJQNode = jQuery(n).parents('td').next('td');
- cellUwagiJQNode.text(cellUwagiJQNode.text().replace('!Zasob', ''))
- jQuery(n).parents('td').text(payload.body.id);
- jQuery(n).remove();
- }
- jQuery.notify(payload.msg, payload.type);
- });
- ");
- $tableActions = array_filter($cellZasobList, function ($row) {
- return ('URL_ACTION' == $row['ZASOB_TYPE']);
- });
- UI::table([
- 'caption' => "tableActions",
- // 'cols' => array_keys($emptyItem),
- 'rows' => array_map(function ($item) {
- $sqlIdAction = DB::getPDO()->quote($item['ID'], PDO::PARAM_INT);
- $args = DB::getPDO()->fetchAll("
- select z.`DESC`
- , a.ID as ALIAS_ID, a.`DESC` as ALIAS_DESC, a.OPIS as ALIAS_OPIS
- from CRM_LISTA_ZASOBOW z
- left join CRM_LISTA_ZASOBOW a on(a.ID = z.ALIAS_ID)
- where z.PARENT_ID = {$sqlIdAction}
- and z.`TYPE` = 'PARAM_IN'
- ");
- $definitionArgs = DB::getPDO()->fetchAll("
- select p.ID, p.`DESC`
- from CRM_LISTA_ZASOBOW z
- join CRM_LISTA_ZASOBOW d on(d.ID = z.ALIAS_ID)
- left join CRM_LISTA_ZASOBOW p on(p.PARENT_ID = d.ID)
- where z.ID = {$sqlIdAction}
- and p.`TYPE` = 'PARAM_IN'
- ");
- $flatDefinitionArgs = implode(";", array_map(function ($arg) {
- return "{$arg['ID']}={$arg['DESC']}";
- }, $definitionArgs));
- return [
- 'label' => DB::getPDO()->fetchValue(" select z.OPIS from CRM_LISTA_ZASOBOW z where z.ID = {$sqlIdAction} ") . " " .
- UI::h('i', [
- 'class' => "glyphicon glyphicon-pencil",
- 'style' => "cursor:pointer",
- 'onClick' => "return Storage__tableStruct__editActionLabel(this, {$sqlIdAction})"], ''),
- 'args' => implode("<br>&", array_map(function ($item) {
- return (NULL === $item['ALIAS_ID'])
- ? $item['DESC']
- : "{$item['DESC']}=" . '{$row["' . $item['ALIAS_DESC'] . '"]}';// TODO: add rmParam btn
- }, $args)) . " " .
- UI::h('i', [
- 'class' => "glyphicon glyphicon-plus-sign",
- 'style' => "cursor:pointer",
- 'title' => "Dodaj PARAM_IN",
- 'onClick' => "return Storage__tableStruct__addParamAction(this, {$sqlIdAction}, '{$flatDefinitionArgs}')"], ''),
- // 'args_info' => '<pre>' . var_export($args, true) . '</pre>',
- 'ID' => $item['ID'],
- 'DESC' => $item['DESC'],
- 'A_STATUS' => $item['A_STATUS'],
- 'definition args' => implode("", array_map(function ($item) {
- return '<div style="white-space:nowrap">' . "[{$item['ID']}] {$item['DESC']}" . '</div>';
- }, $definitionArgs)),
- ];
- }, $tableActions)
- ]);
- echo UI::h('button', [
- 'onClick'=>"Storage__tableStruct__addAction()",
- 'class'=>"btn btn-xs btn-default"
- ], "Dodaj Akcję");
- echo UI::h('link', ['rel'=>"stylesheet", 'type'=>"text/css", 'href'=>"static/sweetalert2.min.css"]);
- echo UI::h('script', ['src'=>"static/sweetalert2.min.js"]);
- echo UI::h('style', [], "
- .swal2-radio.p5-swal-radio-as-list { text-align:left }
- .swal2-radio.p5-swal-radio-as-list > label { display:block; margin-left:20px }
- ");
- UI::inlineJS(__FILE__ . '.tableActions.js', [
- 'ID_STORAGE' => $idStorage,
- 'TABLE_NAME' => $tblName,
- 'FETCH_URL' => Request::getPathUri() . 'index.php?_route=Storage&_task=fetchActionListAjax',
- 'ADD_ACTION_URL' => Request::getPathUri() . 'index.php?_route=Storage&_task=addActionAjax'
- ]);
- echo '<hr>';
- $ajaxAddBaseProcesLink = Request::getPathUri() . "index.php?_route=Storage&_task=addBaseProces&idStorage={$idStorage}&tblName={$tblName}";
- $onClick = "return p5UI__ButtonAjax(this, 'p5UIBtnAjax:Storage:addBaseProces', { href: '{$ajaxAddBaseProcesLink}' })";
- UI::tag('a', ['onclick'=>$onClick, 'class'=>"btn btn-xs btn-default", 'href'=>"#"], "Dodaj podstawowy proces dla tabeli '{$tblName}' - read only", true);
- echo UI::h('script', [], "
- jQuery(document).on('p5UIBtnAjax:Storage:addBaseProces:ajaxLoaded', function(e, n, payload) {
- jQuery.notify(payload.msg, payload.type);
- });
- ");
- } catch (Exception $e) {
- UI::alert('danger', "Error #" . $e->getCode() . "|" . $e->getLine() . ": " . $e->getMessage());
- }
- UI::dol();
- }
- public function fetchActionListAjaxAction() {
- Response::sendTryCatchJson(array($this, 'fetchActionListAjax'), $args = 'JSON_FROM_REQUEST_BODY');
- }
- public function fetchActionListAjax($args) {
- return [
- 'type' => 'success',
- '__args' => $args,
- 'options' => DB::getPDO()->fetchAll("
- select z.ID, z.`DESC`, z.OPIS
- from CRM_LISTA_ZASOBOW z
- where z.`TYPE` = 'URL_ACTION'
- and z.A_STATUS != 'DELETED'
- and z.ALIAS_ID = 0
- ")
- ];
- }
- public function addActionAjaxAction() {
- Response::sendTryCatchJson(array($this, 'addActionAjax'), $args = 'JSON_FROM_REQUEST_BODY');
- }
- public function addActionAjax($args) {
- $idStorage = V::get('idStorage', 0, $args, 'int');
- if ($idStorage <= 0) throw new Exception("Missing id storage");
- $idAction = V::get('idAction', 0, $args, 'int');
- if ($idAction <= 0) throw new Exception("Missing id action");
- $storageList = $this->getStorageList();
- if (empty($storageList)) throw new Exception("No storage defined");
- if (!array_key_exists($idStorage, $storageList)) throw new Exception("Storage not exists");
- $tblName = V::get('table', '', $args, 'word');
- if (empty($tblName)) throw new Exception("No table name");
- $storagePdo = DB::getStorage($idStorage);
- // $tblStruct = $storagePdo->getTableStruct($tblName);
- $idTable = $this->fetchTableId($idStorage, $tblName);
- if ($idTable <= 0) throw new Exception("Zasob tabela '{$tblName}' nie istnieje");
- $action = DB::getPDO()->fetchFirst("
- select z.ID, z.`DESC`, z.OPIS
- from CRM_LISTA_ZASOBOW z
- where z.ID = {$idAction}
- ");
- if (empty($action)) throw new Exception("Action '{$idAction}' not exists");
- $idInsertedAction = DB::getPDO()->insert('CRM_LISTA_ZASOBOW', [
- 'PARENT_ID' => $idTable,
- 'ALIAS_ID' => $idAction,
- 'TYPE' => 'URL_ACTION',
- 'DESC' => $action['DESC'],
- 'OPIS' => V::get('OPIS', $action['DESC'], $action),
- ]);
- if (!$idInsertedAction) throw new Exception("Nie udało się dodać akcji");
- try {
- DB::getPDO()->insert('CRM_LISTA_ZASOBOW_HIST', [
- 'ID_USERS2' => $idInsertedAction,
- 'PARENT_ID' => $idTable,
- 'ALIAS_ID' => $idAction,
- 'TYPE' => 'URL_ACTION',
- 'DESC' => $action['DESC'],
- 'OPIS' => V::get('OPIS', $action['DESC'], $action),
- ]);
- } catch (Exception $e) {
- DBG::log($e);
- }
- return [
- 'type' => 'success',
- 'msg' => "Dodano akcję - rekord nr {$idInsertedAction}",
- '__DBG__' => [
- '$args' => $args,
- '$idStorage' => $idStorage,
- '$tblName' => $tblName,
- // '$tblStruct' => $tblStruct,
- '$idTable' => $idTable,
- '$action' => $action,
- ]
- ];
- }
- public function addBaseProcesAction() {
- Response::sendTryCatchJson(array($this, 'addBaseProces'), $_REQUEST);
- }
- public function addBaseProces($args) {
- $return = [
- 'type' => 'error',
- 'msg' => 'todo: F.' . __FUNCTION__ . ' L.' . __LINE__,
- ];
- $idStorage = V::get('idStorage', 0, $args, 'int');
- if ($idStorage <= 0) throw new HttpException("Missing idStorage", 400);
- $storage = DB::getStorage($idStorage);
- $tblName = V::get('tblName', 0, $args, 'word');
- if (empty($tblName)) throw new HttpException("Missing tblName", 400);
- $tableStruct = $storage->getTableStruct($tblName);
- $return['$tableStruct'] = $tableStruct;
- $idTable = $this->fetchTableId($idStorage, $tblName);
- if ($idTable <= 0) {
- UI::alert('warning', "Zasob tabela '{$tblName}' nie istnieje");// TODO: add p5UI btn
- DBG::table("tblStruct", $tblStruct, __CLASS__, __FUNCTION__, __LINE__);
- throw new Exception("Zasob tabela '{$tblName}' nie istnieje");
- }
- $cellZasobList = array();
- foreach (DB::getPDO()->fetchAllByKey("
- select z.ID, z.`DESC`, z.A_STATUS
- from CRM_LISTA_ZASOBOW z
- where z.PARENT_ID = '{$idTable}'
- ", $key = 'DESC') as $ind => $row) {
- $cellZasobList[strtolower($ind)] = $row;
- }
- $return['$cellZasobList'] = $cellZasobList;
- $idProces = DB::getDB()->ADD_NEW_OBJ('CRM_PROCES', (object)[
- 'TYPE' => 'PROCES_INIT',
- 'DESC' => "Proces dla tabeli '{$tblName}'",
- ]);
- if (!$idProces) throw new Exception("DB ERROR - nie udało się dodać procesu");
- foreach ($cellZasobList as $loverName => $row) {
- DB::getDB()->ADD_NEW_OBJ('CRM_WSKAZNIK', (object)[
- 'ID_PROCES' => $idProces,
- 'ID_ZASOB' => $row['ID'],
- 'TYP' => 'P',
- 'ID_PRZYPADEK' => 2
- ]);
- }
- $return['type'] = 'success';
- $return['msg'] = "Utworzono proces {{$idProces}}";
- return $return;
- }
- public function addGeomEtykietaCellsAction() {
- Response::sendTryCatchJson(array($this, 'addGeomEtykietaCells'), $_REQUEST);
- }
- public function addGeomEtykietaCells($args) {
- $return = [
- 'type' => 'error',
- 'msg' => 'todo: F.' . __FUNCTION__ . ' L.' . __LINE__,
- ];
- $return['_DBG_request'] = $args;
- // idStorage: "36"
- // tblName: "test_geom_linestring"
- $idStorage = V::get('idStorage', 0, $args, 'int');
- if ($idStorage <= 0) throw new HttpException("Missing idStorage", 400);
- $storage = DB::getStorage($idStorage);
- $tblName = V::get('tblName', 0, $args, 'word');
- if (empty($tblName)) throw new HttpException("Missing tblName", 400);
- $tableStruct = $storage->getTableStruct($tblName);
- $return['_DBG_$tableStruct'] = $tableStruct;
- if ('mysql' == DB::getPDO($idStorage)->getType()) {
- $dbName = DB::getPDO($idStorage)->getDatabaseName();
- $fixedTableName = DB::getPDO($idStorage)->fetchValue("
- select t.TABLE_NAME
- from `information_schema`.`TABLES` t
- where t.TABLE_SCHEMA = '{$dbName}'
- and t.TABLE_NAME LIKE '{$tblName}'
- ");
- $return['_DBG_sql_fix__$tblName'] = "
- select t.TABLE_NAME
- from `information_schema`.`TABLES` t
- where t.TABLE_SCHEMA = '{$dbName}'
- and t.TABLE_NAME LIKE '{$tblName}'
- ";
- if (empty($fixedTableName)) return $return;
- if (empty($fixedTableName)) throw new HttpException("Database Error", 500);
- $return['_DBG_$fixedTableName'] = $fixedTableName;
- $tblName = $fixedTableName;
- }
- $return['_DBG_$tableStruct'] = $tableStruct;
- $return['_DBG_has_field__etykieta_x'] = (null != V::geti('etykieta_x', null, $tableStruct));
- $return['_DBG_has_field__etykieta_y'] = (null != V::geti('etykieta_y', null, $tableStruct));
- $return['_DBG_has_field__etykieta_obrot'] = (null != V::geti('etykieta_obrot', null, $tableStruct));
- if (!V::geti('etykieta_x', null, $tableStruct)) {
- try {
- DB::getPDO($idStorage)->exec("ALTER TABLE `{$tblName}_HIST` ADD `etykieta_x` varchar(16) DEFAULT 'N/S;'");
- } catch (Exception $e) {
- $return['__DBG_hist_errors__etykieta_x'] = $e->getMessage();
- }
- DB::getPDO($idStorage)->exec("ALTER TABLE `{$tblName}` ADD `etykieta_x` decimal(16,10) DEFAULT NULL COMMENT 'przesuniecie etykiety elementu w GIS'");
- }
- if (!V::geti('etykieta_y', null, $tableStruct)) {
- try {
- DB::getPDO($idStorage)->exec("ALTER TABLE `{$tblName}_HIST` ADD `etykieta_y` varchar(16) DEFAULT 'N/S;'");
- } catch (Exception $e) {
- $return['__DBG_hist_errors__etykieta_y'] = $e->getMessage();
- }
- DB::getPDO($idStorage)->exec("ALTER TABLE `{$tblName}` ADD `etykieta_y` decimal(16,10) DEFAULT NULL COMMENT 'przesuniecie etykiety elementu w GIS'");
- }
- if (!V::geti('etykieta_obrot', null, $tableStruct)) {
- try {
- DB::getPDO($idStorage)->exec("ALTER TABLE `{$tblName}_HIST` ADD `etykieta_obrot` varchar(16) DEFAULT 'N/S;'");
- } catch (Exception $e) {
- $return['__DBG_hist_errors__etykieta_obrot'] = $e->getMessage();
- }
- DB::getPDO($idStorage)->exec("ALTER TABLE `{$tblName}` ADD `etykieta_obrot` decimal(16,10) DEFAULT NULL");
- }
- return $return;
- }
- public function xsdAction() {
- $idStorage = V::get('idStorage', 0, $_REQUEST, 'int');
- $storage = DB::getStorage($idStorage);
- $tableRealList = $storage->getTableList();
- $srvName = $_SERVER['SERVER_NAME'];
- $storageZasobId = $storage->getZasobId();
- $objNs = "p5_{$storageZasobId}_{$tblName}";
- $objNsUri = "https://biuro.biall-net.pl/api/{$storageZasobId}/{$tblName}";
- $p5TypePrefix = "p5Type";
- $p5TypeNsUri = "http://biuro.biall-net.pl/p5/schema/types";
- $p5TypeNsLocation = "http://biuro.biall-net.pl/p5/schema/types.xsd";
- header('Content-type: text/plain; charset=utf-8');// TODO: test
- //header('Content-type: application/xml; charset=utf-8');
- $xmlWriter = new XMLWriter();
- $xmlWriter->openUri('php://output');
- $xmlWriter->setIndent(true);
- if (!$xmlWriter) throw new HttpException("Error no XMLWriter", 404);
- $xmlWriter->startDocument('1.0', 'UTF-8');
- $xmlWriter->startElement('xs:schema');
- $xmlWriter->writeAttribute('xmlns:xs', 'http://www.w3.org/2001/XMLSchema');
- $xmlWriter->writeAttribute('xmlns:vc', 'http://www.w3.org/2007/XMLSchema-versioning');
- $xmlWriter->writeAttribute("xmlns:{$p5TypePrefix}", $p5TypeNsUri);
- $xmlWriter->writeAttribute('elementFormDefault', 'qualified');
- $xmlWriter->writeAttribute('targetNamespace', $objNsUri);
- $xmlWriter->writeAttribute('vc:minVersion', '1.1');
- $xmlWriter->startElement('xs:import');
- $xmlWriter->writeAttribute('namespace', $p5TypeNsUri);
- $xmlWriter->writeAttribute('schemaLocation', $p5TypeNsLocation);
- $xmlWriter->endElement();// xs:import
- foreach ($tableRealList as $tbl) {
- $tblName = $tbl['table_name'];
- $this->tableXsdViewXmlWriter($xmlWriter, $idStorage, $tblName);
- }
- $xmlWriter->endElement();// xs:schema
- $xmlWriter->endDocument();
- }
- public function tableXsdAction() {
- $idStorage = V::get('idStorage', '', $_GET);
- $tblName = V::get('table', '', $_GET, 'word');
- if (empty($tblName)) die("Wrong table name");
- header('Content-type: text/plain; charset=utf-8');// TODO: test
- $storage = DB::getStorage($idStorage);
- $storageZasobId = $storage->getZasobId();
- $objNs = "p5_{$storageZasobId}_{$tblName}";
- $objNsUri = "https://biuro.biall-net.pl/api/{$storageZasobId}/{$tblName}";
- $p5TypePrefix = "p5Type";
- $p5TypeNsUri = "http://biuro.biall-net.pl/p5/schema/types";
- $p5TypeNsLocation = "http://biuro.biall-net.pl/p5/schema/types.xsd";
- //header('Content-type: application/xml; charset=utf-8');
- $xmlWriter = new XMLWriter();
- $xmlWriter->openUri('php://output');
- $xmlWriter->setIndent(true);
- if (!$xmlWriter) throw new HttpException("Error no XMLWriter", 404);
- $xmlWriter->startDocument('1.0', 'UTF-8');
- $xmlWriter->startElement('xs:schema');
- $xmlWriter->writeAttribute('xmlns:xs', 'http://www.w3.org/2001/XMLSchema');
- $xmlWriter->writeAttribute('xmlns:vc', 'http://www.w3.org/2007/XMLSchema-versioning');
- $xmlWriter->writeAttribute("xmlns:{$p5TypePrefix}", $p5TypeNsUri);
- $xmlWriter->writeAttribute('elementFormDefault', 'qualified');
- $xmlWriter->writeAttribute('targetNamespace', $objNsUri);
- $xmlWriter->writeAttribute('vc:minVersion', '1.1');
- $xmlWriter->startElement('xs:import');
- $xmlWriter->writeAttribute('namespace', $p5TypeNsUri);
- $xmlWriter->writeAttribute('schemaLocation', $p5TypeNsLocation);
- $xmlWriter->endElement();// xs:import
- $this->tableXsdViewXmlWriter($xmlWriter, $idStorage, $tblName);
- $xmlWriter->endElement();// xs:schema
- $xmlWriter->endDocument();
- }
- public function tableXsdViewXmlWriter(&$xmlWriter, $idStorage, $tblName) {
- $storage = DB::getStorage($idStorage);
- $schema = Schema_TableFactory::build($tblName, $idStorage, $_SERVER['SERVER_NAME']);
- $struct = $schema->getStruct();
- DBG::_('DBG', '>1', "struct", $struct, __CLASS__, __FUNCTION__, __LINE__);
- $typeName = "{$tblName}Type";
- $xmlWriter->startElement('xs:complexType');
- $xmlWriter->writeAttribute('name', $typeName);
- $xmlWriter->startElement('xs:sequence');
- foreach ($struct as $field) {
- $xmlWriter->startElement('xs:element');
- $xmlWriter->writeAttribute('name', $field['name']);
- $xmlWriter->writeAttribute('minOccurs', 0);// TODO: set minOccurs by default, etc.
- if ($field['is_nullable']) $xmlWriter->writeAttribute('nillable', 'true');
- if (null !== $field['default_value']) {
- $xmlWriter->writeAttribute('default', $field['default_value']);
- } else if (null === $field['default_value'] && $field['is_nullable']) {
- $xmlWriter->writeAttribute('default', $field['default_value']);
- } else {
- // TODO: Schema BUG?
- }
- if (empty($field['p5_restrictions'])) {
- $xmlWriter->writeAttribute('type', "p5Type:{$field['p5_type']}");
- } else {
- $xmlWriter->startElement('xs:simpleType');
- $xmlWriter->writeAttribute('base', "p5Type:{$field['p5_type']}");
- $xmlWriter->startElement('xs:restriction');
- if (!empty($field['p5_restrictions']['enumeration'])) {
- foreach ($field['p5_restrictions']['enumeration'] as $enumValue) {
- $xmlWriter->startElement('xs:enumeration');
- $xmlWriter->writeAttribute('value', $enumValue);
- $xmlWriter->endElement();// xs:enumeration
- }
- } else {
- // TODO: another restrictions...
- }
- $xmlWriter->endElement();// xs:restriction
- $xmlWriter->endElement();// xs:simpleType
- }
- $xmlWriter->endElement();// xs:element
- }
- $xmlWriter->endElement();// xs:sequence
- $xmlWriter->endElement();// xs:complexType
- return;
- // <xs:element maxOccurs="1" minOccurs="0" name="{$fldName}" nillable="true" type="xs:integer"/>
- $pKeyField = 'ID';//$storageObject->getPrimaryKeyFieldName();
- //DBG::_(true, true, "struct", $struct, __CLASS__, __FUNCTION__, __LINE__);
- foreach ($struct as $field) {
- $fldName = $vField->getName();
- $fldType = $vField->getType();
- $xsdType = $fldType->getTypeForXsd();
- if ($fldType->hasDefault()) {
- $fldDefault = $fldType->getDefault();
- if (!empty($fldDefault) || '0' === $fldDefault) {
- $elNode->setAttribute('default', $fldDefault);
- }
- }
- $fldRestrictions = $fldType->getRestrictions();
- if (empty($fldRestrictions)) {
- $elNode->setAttribute('type', "{$p5TypePrefix}:{$xsdType}");
- } else {
- $sType = $dom->createElementNS('http://www.w3.org/2001/XMLSchema', 'xs:simpleType');
- $elNode->appendChild($sType);
- $sTypeRes = $dom->createElementNS('http://www.w3.org/2001/XMLSchema', 'xs:restriction');
- $sType->appendChild($sTypeRes);
- $sTypeRes->setAttribute('base', "{$p5TypePrefix}:{$xsdType}");
- $enumList = $fldType->getEnumeration();
- if (empty($enumList)) {
- foreach ($fldRestrictions as $restricionName => $restrictionValue) {
- if ('maxLength' == $restricionName) {
- $sTypeResMaxLength = $dom->createElementNS('http://www.w3.org/2001/XMLSchema', 'xs:maxLength');
- $sTypeRes->appendChild($sTypeResMaxLength);
- $sTypeResMaxLength->setAttribute('value', $restrictionValue);
- } else if ('minLength' == $restricionName) {
- $sTypeResMinLength = $dom->createElementNS('http://www.w3.org/2001/XMLSchema', 'xs:minLength');
- $sTypeRes->appendChild($sTypeResMinLength);
- $sTypeResMinLength->setAttribute('value', $restrictionValue);
- } else if ('pattern' == $restricionName) {
- $sTypeResPattern = $dom->createElementNS('http://www.w3.org/2001/XMLSchema', 'xs:pattern');
- $sTypeRes->appendChild($sTypeResPattern);
- $sTypeResPattern->setAttribute('value', $restrictionValue);
- } else if ('fractionDigits' == $restricionName) {
- $sTypeResFractionDigits = $dom->createElementNS('http://www.w3.org/2001/XMLSchema', 'xs:fractionDigits');
- $sTypeRes->appendChild($sTypeResFractionDigits);
- $sTypeResFractionDigits->setAttribute('value', $restrictionValue);
- } else if ('totalDigits' == $restricionName) {
- $sTypeResTotalDigits = $dom->createElementNS('http://www.w3.org/2001/XMLSchema', 'xs:totalDigits');
- $sTypeRes->appendChild($sTypeResTotalDigits);
- $sTypeResTotalDigits->setAttribute('value', $restrictionValue);
- } else if ('maxExclusive' == $restricionName) {
- $sTypeResMaxExclusive = $dom->createElementNS('http://www.w3.org/2001/XMLSchema', 'xs:maxExclusive');
- $sTypeRes->appendChild($sTypeResMaxExclusive);
- $sTypeResMaxExclusive->setAttribute('value', $restrictionValue);
- } else if ('minExclusive' == $restricionName) {
- $sTypeResMinExclusive = $dom->createElementNS('http://www.w3.org/2001/XMLSchema', 'xs:minExclusive');
- $sTypeRes->appendChild($sTypeResMinExclusive);
- $sTypeResMinExclusive->setAttribute('value', $restrictionValue);
- } else if ('maxInclusive' == $restricionName) {
- $sTypeResMaxInclusive = $dom->createElementNS('http://www.w3.org/2001/XMLSchema', 'xs:maxInclusive');
- $sTypeRes->appendChild($sTypeResMaxInclusive);
- $sTypeResMaxInclusive->setAttribute('value', $restrictionValue);
- } else if ('minInclusive' == $restricionName) {
- $sTypeResMinInclusive = $dom->createElementNS('http://www.w3.org/2001/XMLSchema', 'xs:minInclusive');
- $sTypeRes->appendChild($sTypeResMinInclusive);
- $sTypeResMinInclusive->setAttribute('value', $restrictionValue);
- }
- /* TODO: xsd restrictions:
- enumeration Defines a list of acceptable values
- fractionDigits Specifies the maximum number of decimal places allowed. Must be equal to or greater than zero
- length Specifies the exact number of characters or list items allowed. Must be equal to or greater than zero
- maxExclusive Specifies the upper bounds for numeric values (the value must be less than this value)
- maxInclusive Specifies the upper bounds for numeric values (the value must be less than or equal to this value)
- maxLength Specifies the maximum number of characters or list items allowed. Must be equal to or greater than zero
- minExclusive Specifies the lower bounds for numeric values (the value must be greater than this value)
- minInclusive Specifies the lower bounds for numeric values (the value must be greater than or equal to this value)
- minLength Specifies the minimum number of characters or list items allowed. Must be equal to or greater than zero
- pattern Defines the exact sequence of characters that are acceptable
- totalDigits Specifies the exact number of digits allowed. Must be greater than zero
- whiteSpace Specifies how white space (line feeds, tabs, spaces, and carriage returns) is handled
- */
- }
- } else {
- foreach ($enumList as $enumValue) {
- $sTypeResEnum = $dom->createElementNS('http://www.w3.org/2001/XMLSchema', 'xs:enumeration');
- $sTypeRes->appendChild($sTypeResEnum);
- $sTypeResEnum->setAttribute('value', $enumValue);
- }
- }
- }
- }
- $elNode = $dom->createElementNS('http://www.w3.org/2001/XMLSchema', 'xs:element');
- $rootNode->appendChild($elNode);
- $elNode->setAttribute('name', $tblName);
- $elNode->setAttribute('type', "{$objNs}:{$typeName}");
- header('Content-type: application/xml');
- echo $dom->saveXML();
- exit;
- }
- public function navView() {
- $backLabel = 'back';
- $backLink = 'index.php?_route=Storage';
- $backDisabled = true;
- $currentLabel = 'Storage';
- $currentLink = 'index.php?_route=Storage';
- if ($task = V::get('_task', '', $_REQUEST)) {
- $currentLink = "index.php?_route=Storage&_task={$task}";
- $backDisabled = false;
- $idStorage = V::get('idStorage', 0, $_REQUEST, 'int');
- $tblName = V::get('table', '', $_REQUEST, 'word');
- $objName = V::get('object', '', $_REQUEST, 'word');
- $namespace = V::get('namespace', '', $_REQUEST, 'word');
- switch ($task) {
- case 'obejctList':
- case 'tableList':
- case 'viewList':
- case 'rawInfo':
- $backLabel = 'Storage';
- $backLink = $this->getLink();
- $currentLink = $this->getLink($task, ['idStorage' => $idStorage]);
- break;
- case 'tableStruct':
- $backLabel = "Tabele [{$idStorage}]";
- $backLink = $this->getLink('tableList', ['idStorage' => $idStorage]);
- $currentLink = $this->getLink($task, ['idStorage' => $idStorage, 'table' => $tblName]);
- break;
- case 'objectStruct':
- $backLabel = "Obiekty [{$idStorage}]";
- $backLink = $this->getLink('tableList', ['idStorage' => $idStorage]);// TODO: mv tableList to objectList
- $currentLink = $this->getLink($task, ['idStorage' => $idStorage, 'namespace' => $namespace]);
- break;
- case 'coreObjectStruct':
- $backLabel = "Obiekty podstawowe";
- $backLink = $this->getLink('coreObjectList', ['idStorage' => $idStorage]);
- $currentLink = $this->getLink($task, ['idStorage' => $idStorage, 'object' => $objName]);
- break;
- }
- switch ($task) {
- case 'tableList': $currentLabel = "Tabele [{$idStorage}]"; break;
- case 'viewList': $currentLabel = "Widoki [{$idStorage}]"; break;
- case 'rawInfo': $currentLabel = "Raw info [{$idStorage}]"; break;
- case 'tableStruct': $currentLabel = "Struktura tabeli '{$tblName}'"; break;
- case 'objectStruct': $currentLabel = "Obiekt '{$namespace}'"; break;
- case 'coreObjectList': $currentLabel = "Obiekty podstawowe"; break;
- case 'coreObjectStruct': $currentLabel = "Obiekt '{$objName}'"; break;
- case 'objectList': $currentLabel = "Obiekty z aktualnej domeny"; break;// TODO: domain from $_GET
- }
- }
- echo UI::h('nav', ['class'=>"navbar navbar-default navbar-static-top", 'style'=>"z-index:999"], [
- UI::h('div', ['class'=>"container-fluid"], [
- UI::h('div', ['class'=>"navbar-left"], [
- UI::h('ul', ['class'=>"nav navbar-nav navbar-center"], [
- UI::h('li', [], [
- UI::h('a', ['href'=>$backLink, 'class'=>"btn" . ($backDisabled ? ' disabled' : '')], '<i class="glyphicon glyphicon-chevron-left"></i> ' . $backLabel)
- ])
- ])
- ]),
- UI::h('div', ['class'=>"navbar-left"], [
- UI::h('ul', ['class'=>"nav navbar-nav navbar-center"], [
- UI::h('li', [], [
- UI::h('a', ['href'=>$currentLink, 'class'=>"btn"], $currentLabel)
- ])
- ])
- ]),
- UI::h('div', ['class'=>"navbar-right"], [
- // <ul class="nav navbar-nav navbar-right">
- // <li><a href="#">Link</a></li>
- // <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>
- // <ul class="dropdown-menu">
- // <li><a href="#">Action</a></li>
- // <li><a href="#">Another action</a></li>
- // <li><a href="#">Something else here</a></li>
- // <li role="separator" class="divider"></li>
- // <li><a href="#">Separated link</a></li>
- // </ul>
- // </li>
- // </ul>
- ])
- ])
- ]);
- }
- public function getStorageList() {
- $storageList = array();
- $sth = DB::getPDO()->prepare("
- select z.ID, z.`DESC`, z.`TYPE`
- from CRM_LISTA_ZASOBOW z
- where z.TYPE in('BAZA_DANYCH','DATABASE_MYSQL','DATABASE_POSTGRESQL')
- ");
- $sth->execute();
- $rows = $sth->fetchAll();
- foreach ($rows as $row) {
- $storageList[$row['ID']] = $row;
- }
- return $storageList;
- }
- public function addAclObjectToZasobyAction() {// sends JSON
- $response = new stdClass();
- try {
- $idStorage = V::get('idStorage', '', $_GET);
- $namespace = V::get('namespace', '', $_GET);
- if (empty($idStorage)) throw new HttpException("Missing idStorage param");
- if (empty($namespace)) throw new HttpException("Missing namespace param");
- $objectStorage = SchemaFactory::loadDefaultObject('SystemObject');
- $items = $objectStorage->getItems([
- 'f_namespace' => "={$namespace}",
- ]);
- if (empty($items)) throw new Exception("SystemObject '{$namespace}' not found");
- $objectItem = reset($items);
- if (empty($objectItem)) throw new Exception("SystemObject '{$namespace}' not found");
- DBG::log($objectItem, 'array', 'object acl $objectItem');
- if ($objectItem['idZasob'] > 0) {
- // TODO: check if realy exists? @see SchemaFactory::loadDefaultObject('SystemObject')::updateCache()
- $response->_replaceButtonNode = "[{$objectItem['idZasob']}]";
- throw new AlertInfoException("Zasob '{$objectItem['namespace']}' już istnieje - nr '{$objectItem['idZasob']}'");
- }
- $idZasobFound = 0;
- switch ($objectItem['_type']) {
- case 'TableAcl': $idZasobFound = DB::getPDO()->fetchValue(" select ID from CRM_LISTA_ZASOBOW where PARENT_ID = {$objectItem['idDatabase']} and `DESC` = '{$objectItem['name']}' "); break;
- case 'AntAcl': $idZasobFound = DB::getPDO()->fetchValue(" select ID from CRM_LISTA_ZASOBOW where PARENT_ID = {$objectItem['idDatabase']} and `DESC` = '{$objectItem['namespace']}' "); break;
- default: throw new Exception("Not implemented acl type '{$objectItem['_type']}'");
- }
- if ($idZasobFound > 0) {
- DB::getPDO()->update($objectStorage->_rootTableName, 'namespace', $objectItem['namespace'], [
- 'idZasob' => $idZasobFound
- ]);
- $response->id = $idZasobFound;
- throw new AlertSuccessException("Zasob '{$objectItem['namespace']}' już istnieje - nr '{$idZasobFound}' - cache zaktualizowany");
- }
- try {
- $acl = User::getAcl()->getObjectAcl('default_db', 'crm_lista_zasobow');
- } catch (Exception $e) {
- DBG::log($e);
- throw new Exception("Brak dostępu do tabeli Zasoby");
- }
- if (empty($objectItem['idDatabase'])) throw new Exception("Missing database id");
- if ($idStorage != $objectItem['idDatabase']) throw new Exception("Database id must be the same");
- if (empty($objectItem['_rootTableName'])) throw new Exception("Missing root table name");
- switch ($objectItem['_type']) {
- case 'TableAcl':
- $newZasobItem = [
- 'PARENT_ID' => $objectItem['idDatabase'],
- 'TYPE' => 'TABELA',
- 'DESC' => $objectItem['_rootTableName'],
- 'DESC_PL' => $objectItem['name'],
- ];
- break;
- case 'AntAcl':
- $newZasobItem = [
- 'PARENT_ID' => $objectItem['idDatabase'],
- 'TYPE' => 'TABELA',
- 'DESC' => $objectItem['namespace'],
- 'DESC_PL' => $objectItem['name'],
- ];
- break;
- default: throw new Exception("Not implemented acl type '{$objectItem['_type']}'");
- }
- $idCreated = $acl->addItem($newZasobItem);
- if (!$idCreated) throw new Exception("Nie udało się utworzyć nowego rekordu!");
- try {
- DB::getPDO()->update($objectStorage->_rootTableName, 'namespace', $objectItem['namespace'], [
- 'idZasob' => $idCreated
- ]);
- } catch (Exception $e) {
- DBG::log($e);
- }
- $response->id = $idCreated;
- $response->record = $acl->getItem($idCreated);
- $response->_replaceButtonNode = "[{$idCreated}]";
- throw new AlertSuccessException("Utworzono pomyślnie rekord nr {$idCreated}");
- } catch (AlertSuccessException $e) {
- $response->type = 'success';
- $response->msg = $e->getMessage();
- } catch (AlertInfoException $e) {
- $response->type = 'info';
- $response->msg = $e->getMessage();
- } catch (Exception $e) {
- $response->type = 'error';
- $response->msg = $e->getMessage();
- DBG::log($e);
- }
- Response::sendJsonExit($response);
- }
- public function addCellToZasobyAction() {// sends JSON
- $response = new stdClass();
- try {
- $idStorage = V::get('storageId', '', $_GET);
- $tblName = V::get('tblName', '', $_GET, 'word');
- $cellName = V::get('cellName', '', $_GET, 'word');
- if (empty($tblName)) throw new HttpException("Wrong table name");
- if (empty($tblName)) throw new HttpException("Wrong cell name");
- $storage = DB::getStorage($idStorage);
- $tableStruct = $storage->getTableStruct($tblName);
- $zasobStorageId = $storage->getZasobId();
- if (!is_numeric($zasobStorageId)) throw new HttpException("Storage id is not set in config file");
- $idTable = $this->fetchTableId($zasobStorageId, $tblName);
- if ($idTable <= 0) throw new Exception("Zasob tabela '{$tblName}' nie istnieje");
- try {
- $acl = User::getAcl()->getObjectAcl('default_db', 'crm_lista_zasobow');
- } catch (Exception $e) {
- throw new Exception("Brak dostępu do tabeli Zasoby");
- }
- $item = array();
- $item['PARENT_ID'] = $idTable;
- $item['TYPE'] = 'KOMORKA';
- $item['DESC'] = $cellName;
- $item['DESC_PL'] = $cellName;
- if (DBG::isActive()) $response->_itemToCreate = $item;
- $createdId = $acl->addItem($item);
- if (!$createdId) throw new Exception("Nie udało się utworzyć nowego rekordu!");
- $response->id = $createdId;
- $response->record = $acl->getItem($createdId);
- $response->_replaceButtonNode = "[{$createdId}]";
- throw new AlertSuccessException("Utworzono pomyślnie rekord nr {$createdId}");
- } catch (AlertSuccessException $e) {
- $response->type = 'success';
- $response->msg = $e->getMessage();
- } catch (AlertInfoException $e) {
- $response->type = 'info';
- $response->msg = $e->getMessage();
- } catch (Exception $e) {
- $response->type = 'error';
- $response->msg = $e->getMessage();
- }
- Response::sendJsonExit($response);
- }
- public function fetchTableId($idZasobStorage, $tblName) {
- $rows = DB::getPDO()->fetchAll("
- select z.`ID`, z.`DESC`
- from `CRM_LISTA_ZASOBOW` z
- where z.`PARENT_ID`='{$idZasobStorage}'
- and z.`DESC`='{$tblName}'
- and z.`A_STATUS` in('NORMAL','WAITING')
- ");
- if (!empty($rows)) return (int)$rows[0]['ID'];
- return null;
- }
- public function systemObjectsStructAction() {
- UI::gora();
- UI::menu();
- $this->navView();
- try {
- throw new Exception("TODO: F." . __FUNCTION__ . ' L.' . __LINE__);
- // $coreObjlist = OBJXSD::getSystemObjectsStruct();
- // $objectList = array();
- // foreach ($coreObjlist as $objName) {
- // $objItem = array();
- // $objItem['name'] = $objName;
- // $objItem['struktura'] = '<a href="index.php?_route=Storage&_task=systemObjectsStruct&object=' . $objName . '">' . "struct" . '</a>';
- // // $objItem['label'] = "";// TODO: read from json
- // $objectList[] = $objItem;
- // }
- // usort($objectList, function($rowA, $rowB) {
- // $a = $rowA['nazwa']; $b = $rowB['nazwa'];
- // if ($a == $b) return 0;
- // return ($a < $b) ? -1 : 1;
- // });
- //
- // DBG::table("objectList", $objectList, __CLASS__, __FUNCTION__, __LINE__);
- } catch (Exception $e) {
- UI::alert('danger', "Error #" . $e->getCode() . "|" . $e->getLine() . ": " . $e->getMessage());
- }
- UI::dol();
- }
- public function systemObjectsAction() {// TableAjax view: index.php?_route=ViewTableAjax&namespace=default_objects/SystemObject
- UI::gora();
- UI::menu();
- $this->navView();
- try {
- Lib::loadClass('Schema_SystemObjectStorageAcl');
- $acl = new Schema_SystemObjectStorageAcl();
- UI::table([
- 'rows' => array_map(
- function ($item) {
- return [
- 'ns' => $item['namespace'],
- 'nazwa' => $item['name'],
- 'type' => $item['_type'],
- 'edit' => '<a href="index.php?_route=ViewTableAjax&namespace=' . $item['namespace'] . '">edit</a>',
- '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>',
- '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)'
- ];
- }
- , $acl->getItems([
- 'order_by' => 'namespace',
- 'order_dir' => 'asc'
- ])
- )
- ]);
- } catch (Exception $e) {
- UI::alert('danger', "Error #" . $e->getCode() . "|" . $e->getLine() . ": " . $e->getMessage());
- DBG::log($e);
- }
- UI::dol();
- }
- public function getObjectAclRow($namespace) {
- Lib::loadClass('Schema_SystemObjectStorageAcl');
- $acl = new Schema_SystemObjectStorageAcl();
- $items = $acl->getItems([
- 'f_namespace' => "={$namespace}",
- ]);
- if (empty($items)) throw new Exception("SystemObject '{$namespace}' not found");
- $item = reset($items);
- if (empty($item)) throw new Exception("SystemObject '{$namespace}' not found");
- return $item;
- }
- public function objectReinstallAction() {
- UI::gora();
- UI::startContainer();
- try {
- $namespace = V::get('namespace', '', $_GET);
- if (empty($namespace)) throw new Exception("Missing param namespace");
- $item = $this->getObjectAclRow($namespace);
- DBG::log($item, 'array', '$item');
- switch ($item['_type']) {
- case 'AntAcl': $this->reinstallAntAcl($item); break;
- default: throw new Exception("TODO: Not Implemented type '{$item['_type']}'");
- }
- } catch (Exception $e) {
- UI::alert('danger', "Error #" . $e->getCode() . "|" . $e->getLine() . ": " . $e->getMessage());
- DBG::log($e);
- }
- UI::endContainer();
- UI::dol();
- }
- public function reinstallAntAcl($item) {
- Lib::loadClass('AntAclBase');
- $antAclPath = APP_PATH_SCHEMA . DS . 'ant-object' . DS . str_replace(['__x3A__', ':'], ['.', '/'], $item['typeName']);
- if (!file_exists("{$antAclPath}/build.xml")) throw new Exception("Ant build file not exists");
- if (file_exists("{$antAclPath}/{$item['name']}.xsd")) {
- DBG::log("{$antAclPath}/{$item['name']}.xsd", 'string', 'xsd file exists');
- $outputType = 'XML';
- $antOutput = file_get_contents("{$antAclPath}/{$item['name']}.xsd");
- } else {
- DBG::log($antAclPath, 'string', '$antAclPath');
- $antBin = APP_PATH_WWW . DS . 'stuff' . DS . 'dita-ot-2.3.3' . DS . 'bin' . DS . 'ant';
- $cmd = "cd {$antAclPath} && {$antBin} DescribeFeatureType 2>&1";
- V::exec($cmd, $out, $ret);
- DBG::log($out, 'array', "DescribeFeatureType ret({$ret})");
- $outputType = 'XML';
- $antOutput = []; $startRead = false;
- foreach ($out as $line) {
- // $line = " [echo] OUTPUT__TYPE__XML"
- if ('[echo]' == substr(trim($line), 0, 6)) {
- $line = trim(substr(trim($line), 7));
- }
- if (!$startRead) {
- if ('OUTPUT__TYPE__XML' == $line) $outputType = 'XML';
- if ('OUTPUT__TYPE__HTML' == $line) $outputType = 'HTML';
- if ('OUTPUT__START' == $line) {
- $startRead = true;
- continue;
- }
- } else {
- if ('<!DOCTYPE' == substr($line, 0, strlen('<!DOCTYPE'))) continue;
- if ('OUTPUT__END' == $line) {
- break;
- }
- $antOutput[]= $line;
- }
- }
- if (!empty($antOutput)) $antOutput = implode("\n", $antOutput);
- }
- if (empty($antOutput)) UI::alert('danger', "Empty output!");
- else {
- echo UI::h('p', [], "Ant Schema:");
- if ('XML' == $outputType) {
- echo UI::h('pre', ['style' => 'max-height:400px; overflow:scroll'], htmlspecialchars($antOutput));
- } else if ('HTML' == $outputType) {
- echo UI::h('div', ['class'=>"container", 'style'=>"padding:12px; border:1px solid #ddd"], $antOutput);
- }
- }
- Lib::loadClass('XML');
- $schema = XML::readXmlFileToArray("{$antAclPath}/{$item['name']}.xsd");
- if (empty($schema)) throw new Exception("Missing schema");
- $xsdType = [ // find xsd:element with @name = $item['name']
- 'nsPrefix' => null,
- 'name' => null,
- 'nsUri' => null,
- 'targetNsUri' => V::get('targetNamespace', '', $schema[1])
- ];
- if (!$xsdType['targetNsUri']) throw new Exception("Missing schema target namespace declaration '{$item['name']}'");
- foreach ($schema[2] as $n) {
- if ('xsd:element' != $n[0]) continue;
- if ($item['name'] != V::get('name', '', $n[1])) continue;
- list($xsdType['nsPrefix'], $xsdType['name']) = explode(':', V::get('type', '', $n[1]));
- }
- if (!$xsdType['nsPrefix'] || !$xsdType['name']) throw new Exception("Missing schema root element name = '{$item['name']}'");
- $xsdType['nsUri'] = V::get("xmlns:{$xsdType['nsPrefix']}", '', $schema[1]);// find xmlns:default_objects = "https://biuro.biall-net.pl/wfs/default_objects"
- if (!$xsdType['nsUri']) throw new Exception("Missing schema root element namespace declaration = '{$item['name']}'");
- if ($xsdType['nsUri'] != $xsdType['targetNsUri']) throw new Exception("TODO: type ns is not the same as targetNamespace '{$item['name']}'");// TODO
- foreach ($schema[2] as $n) {
- if ('xsd:complexType' != $n[0]) continue;
- if ($xsdType['name'] != V::get('name', '', $n[1])) continue;
- DBG::nicePrint($n, 'TODO: parse complexType');
- // complexType/complexContent/extension[base=...]/sequence/element
- if ($n[2][0][0] != 'xsd:complexContent') throw new Exception("Error Parsing Schema - expected 'complexType/complexContent'");
- if ($n[2][0][2][0][0] != 'xsd:extension') throw new Exception("Error Parsing Schema - expected 'complexType/complexContent/extension'");
- $xsdType['extensionBase'] = V::get('base', '', $n[2][0][2][0][1]);
- if ($n[2][0][2][0][2][0][0] != 'xsd:sequence') throw new Exception("Error Parsing Schema - expected 'complexType/complexContent/extension/sequence'");
- foreach ($n[2][0][2][0][2][0][2] as $f) {
- if ($f[0] !== 'xsd:element') {
- DBG::log($n, 'array', "Schema xsd parse error - Not implemented node type '{$f[0]}'");
- continue;
- }
- $fieldName = V::get('name', '', $f[1]);
- if (!$fieldName) throw new Exception("Error Parsing Schema - expected 'element[@name]'");
- $xsdType['struct'][$fieldName] = [
- 'type' => V::get('type', '', $f[1]),
- 'ref' => V::get('ref', '', $f[1]),
- 'minOccurs' => V::get('minOccurs', 0, $f[1], 'int'),
- 'maxOccurs' => V::get('maxOccurs', '1', $f[1]),
- ];
- }
- }
- DBG::nicePrint($xsdType, '$xsdType');
- // TODO: insert fields $xsdType['struct'] by 'SystemObjectField'
- // getStorage('SystemObjectField')->update(['isActive' => 0], ['#refFrom' => ['ns' => 'SystemObject', 'pk' => $item['namespace']]]) // TODO: update pk in SysObj schema
- // getStorage('SystemObjectField')->insertOrUpdate([ 'isActive' => 1, ... , '@insert' => [], '@update' => [] ])
- {
- DBG::nicePrint($schema, '$schema');
- Lib::loadClass('Core_XmlWriter');
- ob_start();
- $xmlWriter = new Core_XmlWriter();
- $xmlWriter->openUri('php://output');
- $xmlWriter->setIndent(true);
- $xmlWriter->startDocument('1.0','UTF-8');
- $xmlWriter->h($schema[0], $schema[1], $schema[2]);
- $xmlWriter->endDocument();
- echo UI::h('pre', ['style' => 'max-height:400px; overflow:scroll'], htmlspecialchars(ob_get_clean()));
- }
- }
- }
|