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('' . " 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']) ? 'TAK' : 'brak',
'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' => "Narzędzia systemowe",
'opis' => "SystemObjects",
'config?' => 'n/d',
'obiekty' => UI::h('a', [ 'href' => Router::getRoute('Storage_Tools')->getLink() ], "narzędzia"),
],
[
'Nr zasobu' => '',
'nazwa' => '' . "Obiekty" . '',
'opis' => '' . "SystemObjects" . '',
'config?' => 'brak',
'obiekty' => UI::h('a', [ 'href' => $this->getLink('systemObjects') ], "obiekty"),
],
[
'Nr zasobu' => '',
'nazwa' => '' . "Obiekty Test" . '',
'opis' => '' . "Obiekty podstawowe (test json)" . '',
'config?' => 'brak',
'obiekty' => UI::h('a', [ 'href' => Router::getRoute('Storage_TestObj')->getLink('coreObjectList') ], "obiekty"),
'raw info' => UI::h('a', [ 'href' => Router::getRoute('Storage_TestObj')->getLink('coreObjectParseAll') ], "raw info"),
],
[
'Nr zasobu' => '',
'nazwa' => '' . "Obiekty Test" . '',
'opis' => '' . "Obiekty dla domeny '" . str_replace(array(".", "-"), '_', $_SERVER['SERVER_NAME']) . "' (test json)" . '',
'config?' => 'brak',
'obiekty' => UI::h('a', [ 'href' => Router::getRoute('Storage_TestObj')->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 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 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");
}
{
echo UI::h('style', ['type' => "text/css"], "
.p5UI__dropdown-content { min-width:300px; padding:8px; background-color: #f6f6f6; box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2) }
.p5UI__dropdown-content a { display:block; color:#000; padding:8px; text-decoration:none }
.p5UI__dropdown-content a:hover { background-color:#ebebeb }
");
echo UI::h('script', [], "
function p5_Storage_actions_filterInput(n) {
var input, filter, ul, li, a, i, div;
input = n // .id-myInput
filter = input.value.toUpperCase()
div = n.parentNode // .id-myDropdown
a = div.getElementsByTagName('a')
for (i = 0; i < a.length; i++) {
if (a[i].innerHTML.toUpperCase().indexOf(filter) > -1) {
a[i].style.display = ''
} else {
a[i].style.display = 'none'
}
}
}
");
}
$thisGetLink = array($this, 'getLink');
UI::table([
'caption' => "Obiekty w bazie '{$sourceItem['name']}' " .
UI::hButtonPost('' . " odśwież", [
'class' => "btn btn-xs btn-link",
'data' => [
'refreshObjectList' => '1'
]
]),
'rows' => array_map(function ($item) use ($idStorage, $thisGetLink) {
$typeName = $item['typeName']; // $typeName = Api_WfsNs::typeName($item['namespace']);
return [
'namespace' => '' . substr($item['namespace'], 0, strlen($item['namespace']) - strlen($item['name'])) . '' .
'' . $item['name'] . '',
'_type' => $item['_type'], // TODO: editable?
'Nr zasobu' => ($item['idZasob'] > 0)
? $item['idZasob']
: UI::hButtonAjax("Dodaj do zasobów", 'addAclObjectToZasobyAjax', [
'class' => "btn btn-xs btn-primary",
'href' => $this->getLink('addAclObjectToZasobyAjax'),
'data' => [
'idStorage' => $idStorage,
'namespace' => $item['namespace'],
]
]),
// 'opis' => $item['description'],
'hasStruct' => ($item['hasStruct']) ? 'TAK' : 'nie',
'installed' => $item['isStructInstalled'] ? 'TAK' : 'nie',
'active?' => $item['isObjectActive'] ? 'TAK' : 'nie',
'menu' => UI::h('div', ['class'=>"p5UI__dropdown-wrap"], [
UI::h('button', ['onClick' => "p5UI__dropdown(event, this, 'left bottom')", 'class' => "btn btn-xs btn-default p5UI__dropdown-btn"], [
'',
" menu"
]),
UI::h('div', ['class' => "p5UI__dropdown-content"], [
UI::h('input', ['type' => "text", 'placeholder' => "Search..", 'class' => "p5UI__dropdown-input", 'onkeyup' => "p5_Storage_actions_filterInput(this)"], null),
UI::h('a', [ 'href' => Router::getRoute('Storage_AclStruct')->getLink('', [ 'namespace' => $item['namespace'] ]) ], "struktura"),
UI::h('a', [ 'href' => $item['reinstallLink'] ], "reinstall"),
UI::h('a', [ 'href' => $this->getLink('rawInfo', [ 'idStorage' => $idStorage, 'table' => $item['name'] ]) ], "raw info"),
UI::h('a', [ 'href' => Router::getRoute('ViewTableAjax')->getLink('', ['namespace' => $item['namespace']]) ], "view table"),
UI::h('a', [ 'href' => Router::getRoute('ViewObject')->getLink('', ['namespace' => $item['namespace']]) ], "view object"),
// 'xsd' => UI::h('a', [ 'href' => $this->getLink('xsd', [ 'idStorage' => $idStorage ]) ], "xsd"),
UI::h('a', [ 'href' => "wfs-data.php/default_db/?SERVICE=WFS&VERSION=1.0.0&SRSNAME=EPSG:3003&REQUEST=DescribeFeatureType&TYPENAME={$typeName}" ], "wfs DescribeFeatureType"),
UI::h('a', [ 'href' => "wfs-data.php/default_db/?SERVICE=WFS&VERSION=1.0.0&SRSNAME=EPSG:3003&REQUEST=DescribeFeatureTypeAdvanced&TYPENAME={$typeName}" ], "wfs DescribeFeatureTypeAdvanced"),
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)"),
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)"),
UI::h('a', [ 'href' => "wfs-data.php/default_db/?SERVICE=WFS&VERSION=1.0.0&SRSNAME=EPSG:3003&REQUEST=GetFeature&TYPENAME={$typeName}&MAXFEATURES=3&resolve=all&resolveDepth=3" ], "wfs GetFeature (max: 3, resolveDepth: 3)"),
])
]),
];
}, $objectStorage->getItems([
'#refFrom' => [
'namespace' => 'default_objects/SystemSource',
'primaryKey' => $sourceItem['idZasob']
],
'order_by' => 'namespace',
'order_dir' => 'asc'
]))
]);
UI::hButtonAjaxOnResponse('addAclObjectToZasobyAjax', /* payload, n */ "
if (!payload.type) return false
if ('success' === payload.type || 'info' === payload.type) {
if (payload.body && payload.body.id && payload.body.id > 0) {
n.parentNode.replaceChild(document.createTextNode(payload.body.id), n)
} else {
console.log('TODO: addAclObjectToZasobyAjax unknown response', payload);
}
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 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 addTableBaseProcesAction() {
Response::sendTryCatchJson(array($this, 'addTableBaseProces'), $_REQUEST);
}
public function addTableBaseProces($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 addObjectBaseProcesAjaxAction() {
Response::sendTryCatchJson(array($this, 'addObjectBaseProcesAjax'), $_REQUEST);
}
public function addObjectBaseProcesAjax($args) {
$return = [
'type' => 'error',
'msg' => 'todo: F.' . __FUNCTION__ . ' L.' . __LINE__,
];
$namespace = V::get('namespace', 0, $args);
if (empty($namespace)) throw new HttpException("Missing namespace", 400);
$item = SchemaFactory::loadDefaultObject('SystemObject')->getItem($namespace, [ 'propertyName' => '*,field' ]);
DBG::log($item, 'array', "TODO: addObjectBaseProcesAjax for \$item");
if (!$item['idZasob']) throw new Exception("Missing id zasob for object '{$namespace}'");
if (!$item['idDatabase']) throw new Exception("Missing id database for object '{$namespace}'");
if (!$item['_rootTableName']) throw new Exception("Missing root table name for object '{$namespace}'");
if ('AntAcl' != $item['_type']) throw new Exception("Not implemented type '{$item['_type']}' for namespace '{$namespace}' - only AntAcl supported");
if (!$item['hasStruct']) throw new Exception("Missing structure for object '{$namespace}'");
if (!$item['isStructInstalled']) throw new Exception("Structure not installed for object '{$namespace}'");
if (!$item['isObjectActive']) throw new Exception("Object is not active '{$namespace}'");
$fieldsWithIdZasob = array_filter($item['field'], function ($field) {
if (!$field['idZasob']) return false;
return true;
});
if (empty($fieldsWithIdZasob)) throw new Exception("Missing fields with id zasob in object '{$namespace}'");
$idProces = DB::getDB()->ADD_NEW_OBJ('CRM_PROCES', (object)[
'TYPE' => 'PROCES_INIT',
'DESC' => "TODO: Proces dla obiektu '{$namespace}'",
]);
if (!$idProces) throw new Exception("DB ERROR - nie udało się dodać procesu");
array_map(function ($field) use ($idProces) {
DB::getDB()->ADD_NEW_OBJ('CRM_WSKAZNIK', (object)[
'ID_PROCES' => $idProces,
'ID_ZASOB' => $field['idZasob'],
'TYP' => 'P',
'ID_PRZYPADEK' => 2
]);
}, $fieldsWithIdZasob);
$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');
$foreignKeys = [];
{
$dbName = DB::getPDO($idStorage)->getDatabaseName();
if ('mysql' === DB::getPDO($idStorage)->getType()) {
$foreignKeys = DB::getPDO($idStorage)->fetchAll("
SELECT i.TABLE_SCHEMA, i.TABLE_NAME, i.CONSTRAINT_TYPE, i.CONSTRAINT_NAME, k.COLUMN_NAME, k.REFERENCED_TABLE_NAME, k.REFERENCED_COLUMN_NAME
FROM information_schema.TABLE_CONSTRAINTS i
LEFT JOIN information_schema.KEY_COLUMN_USAGE k ON i.CONSTRAINT_NAME = k.CONSTRAINT_NAME
WHERE i.TABLE_SCHEMA = :db_name
and i.TABLE_NAME = :tbl_name
and i.CONSTRAINT_TYPE = 'FOREIGN KEY'
ORDER BY i.TABLE_NAME
", [
':db_name' => $dbName,
':tbl_name' => $tblName,
]);
// if ('CRM_WSKAZNIK' === $tblName) { // @example: CRM_WSKAZNIK.ID_ZASOB => CRM_LISTA_ZASOBOW.ID
// $foreignKeys = [
// [ 'TABLE_SCHEMA' => "SES_USERS2"
// , 'TABLE_NAME' => "CRM_WSKAZNIK"
// , 'CONSTRAINT_TYPE' => "FOREIGN KEY"
// , 'CONSTRAINT_NAME' => "zasob"
// , 'COLUMN_NAME' => "ID_ZASOB"
// , 'REFERENCED_TABLE_NAME' => "CRM_LISTA_ZASOBOW"
// , 'REFERENCED_COLUMN_NAME' => "ID"
// ]
// ];
// }
// $xmlWriter->writeComment("\$foreignKeys: " . var_export($foreignKeys, true));
// TABLE_SCHEMA, TABLE_NAME, CONSTRAINT_TYPE, CONSTRAINT_NAME, COLUMN_NAME, REFERENCED_TABLE_NAME, REFERENCED_COLUMN_NAME
// * * FOREIGN KEY * * * *
}
}
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
}
if (!empty($foreignKeys)) {
foreach ($foreignKeys as $key) {
$xmlWriter->startElement('xs:element');
$refPrefix = (DB::getPDO()->getZasobId() === $idStorage) ? 'p5_default_db' : "p5_zasob_{$idStorage}";
$xmlWriter->writeAttribute('ref', "{$refPrefix}:{$key['REFERENCED_TABLE_NAME']}");
$xmlWriter->startElement('xs:annotation');
$xmlWriter->startElement('xs:appinfo');
$xmlWriter->startElement('system_cache__appinfo:flat_relation_cache');
$xmlWriter->writeAttribute("system_cache__appinfo:name", $key['COLUMN_NAME']);
$xmlWriter->writeAttribute("system_cache__appinfo:xpath", "{$refPrefix}:{$key['REFERENCED_TABLE_NAME']}/{$key['REFERENCED_COLUMN_NAME']}");
$xmlWriter->endElement();// system_cache__appinfo:flat_relation_cache
$xmlWriter->endElement();// xs:appinfo
$xmlWriter->endElement();// xs:annotation
$xmlWriter->endElement();// xs:element
}
}
$xmlWriter->endElement();// xs:sequence
$xmlWriter->endElement();// xs:complexType
return;
//