SystemObjectFieldStorageAcl.php 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614
  1. <?php
  2. Lib::loadClass('Core_AclSimpleSchemaBase');
  3. Lib::loadClass('ParseOgcFilter');
  4. Lib::loadClass('Router');
  5. class Schema_SystemObjectFieldStorageAcl extends Core_AclSimpleSchemaBase {
  6. public $_simpleSchema = [
  7. 'root' => [
  8. '@namespace' => 'default_objects/SystemObjectField',
  9. '@primaryKey' => 'namespace',
  10. 'idZasob' => [ '@type' => 'xsd:integer' ],
  11. 'idDatabase' => [ '@type' => 'xsd:integer' ],
  12. '_rootTableName' => [ '@type' => 'xsd:string' ],
  13. 'namespace' => [ '@type' => 'xsd:string' ],
  14. 'objectNamespace' => [ '@type' => 'xsd:string' ],
  15. 'fieldNamespace' => [ '@type' => 'xsd:string' ],
  16. 'xsdType' => [ '@type' => 'xsd:string' ],
  17. 'xsdRestrictions' => [ '@type' => 'xsd:string' ],
  18. 'appInfo' => [ '@type' => 'xsd:string' ],
  19. 'minOccurs' => [ '@type' => 'xsd:string' ],
  20. 'maxOccurs' => [ '@type' => 'xsd:string' ], // '0..unbounded',
  21. 'isActive' => [ '@type' => 'xsd:integer' ], // installed
  22. 'description' => [ '@type' => 'xsd:string' ],
  23. 'isLocal' => [ '@type' => 'xsd:integer', '@comment' => "is in _rootTableName" ],
  24. 'sortPrio' => [ '@type' => 'xsd:integer' ],
  25. // 'A_RECORD_CREATE_AUTHOR' => [ '@type' => 'xsd:string' , '@label' => 'autor' ],
  26. // 'A_RECORD_CREATE_DATE' => [ '@type' => 'xsd:date' , '@label' => 'utworzono' ],
  27. // 'A_RECORD_UPDATE_AUTHOR' => [ '@type' => 'xsd:string' , '@label' => 'zaktualizował' ],
  28. // 'A_RECORD_UPDATE_DATE' => [ '@type' => 'xsd:date', '@label' => 'zaktualizowano' ],
  29. ]
  30. ];
  31. // public $_rootTableName = 'CRM_LISTA_ZASOBOW';
  32. public $_rootTableName = 'CRM_#CACHE_ACL_OBJECT_FIELD';
  33. public $_enumRootTableName = 'CRM_#CACHE_ACL_OBJECT_FIELD_enum';
  34. public $_version = '3';
  35. public function __construct($simpleSchema = null) {
  36. parent::__construct($simpleSchema);
  37. $version = (int)DB::getPDO()->fetchValue(" select CONF_VAL from CRM_CONFIG where CONF_KEY='Schema_SystemObjectFieldStorageAcl__version' ");
  38. if ($version < $this->_version) {
  39. DBG::log("UPDATE Schema_SystemObjectFieldStorageAcl__version");
  40. DB::getPDO()->execSql("
  41. create table if not exists `{$this->_rootTableName}` (
  42. `namespace` varchar(255) DEFAULT '',
  43. `fieldNamespace` varchar(255) DEFAULT '',
  44. `idZasob` int(11) DEFAULT NULL,
  45. `idDatabase` int(11) NOT NULL,
  46. `_rootTableName` varchar(255) DEFAULT '',
  47. `objectNamespace` varchar(255) DEFAULT '',
  48. `xsdType` varchar(255) DEFAULT '',
  49. `xsdRestrictions` varchar(1000) DEFAULT '',
  50. `appInfo` varchar(1000) DEFAULT '',
  51. `minOccurs` int(11) DEFAULT '0',
  52. `maxOccurs` varchar(11) DEFAULT '1' COMMENT '0..unbounded',
  53. `isActive` tinyint(1) NOT NULL DEFAULT 0 COMMENT 'installed',
  54. `description` varchar(255) DEFAULT '',
  55. `isLocal` tinyint(1) NOT NULL DEFAULT 0 COMMENT 'is in _rootTableName',
  56. `sortPrio` int(11) NOT NULL DEFAULT 0,
  57. UNIQUE KEY `idZasob` (idZasob),
  58. PRIMARY KEY (`namespace`),
  59. KEY `isActive` (isActive)
  60. ) ENGINE=MyISAM DEFAULT CHARSET=latin2
  61. ");
  62. try {
  63. DB::getPDO()->execSql(" ALTER TABLE `{$this->_rootTableName}` ADD `appInfo` VARCHAR(1000) NOT NULL DEFAULT '' AFTER `xsdRestrictions` ");
  64. } catch (Exception $e) {
  65. DBG::log($e);
  66. }
  67. try {
  68. DB::getPDO()->execSql(" ALTER TABLE `{$this->_rootTableName}` ADD `isLocal` tinyint(1) NOT NULL DEFAULT 0 COMMENT 'is in _rootTableName' AFTER `description` ");
  69. } catch (Exception $e) {
  70. DBG::log($e);
  71. }
  72. try {
  73. DB::getPDO()->execSql(" ALTER TABLE `{$this->_rootTableName}` ADD `sortPrio` int(11) NOT NULL DEFAULT 0 AFTER `isLocal` ");
  74. DB::getPDO()->execSql("
  75. UPDATE `{$this->_rootTableName}`
  76. SET sortPrio = idZasob
  77. WHERE idZasob > 0
  78. ");
  79. DB::getPDO()->execSql("
  80. UPDATE `{$this->_rootTableName}` c
  81. LEFT JOIN `CRM_LISTA_ZASOBOW` z on ( z.ID = c.idZasob )
  82. SET c.sortPrio = z.SORT_PRIO
  83. WHERE c.idZasob > 0
  84. and z.ID is not null
  85. ");
  86. } catch (Exception $e) {
  87. DBG::log($e);
  88. }
  89. DB::getPDO()->execSql("
  90. create table if not exists `{$this->_enumRootTableName}` (
  91. `namespace` varchar(255) DEFAULT '' COMMENT 'concat obj ns / field ns / value',
  92. `fieldNamespace` varchar(255) DEFAULT '',
  93. `objectNamespace` varchar(255) DEFAULT '',
  94. `value` varchar(255) DEFAULT '',
  95. `label` varchar(255) DEFAULT '',
  96. `isActive` tinyint(1) NOT NULL DEFAULT 0 COMMENT 'installed',
  97. `sortPrio` tinyint NOT NULL DEFAULT 0,
  98. KEY `objectNamespace` (`objectNamespace`),
  99. KEY `fieldNamespace` (`fieldNamespace`),
  100. KEY `isActive` (isActive),
  101. UNIQUE `enum_uniq_value` (`objectNamespace`, `fieldNamespace`, `value`, `isActive`)
  102. ) ENGINE=MyISAM DEFAULT CHARSET=latin2
  103. ");
  104. try {
  105. DB::getPDO()->execSql(" DELETE from `{$this->_enumRootTableName}` where isActive = 0 ");
  106. DB::getPDO()->execSql(" ALTER TABLE `{$this->_enumRootTableName}` ADD UNIQUE `enum_uniq_value` (`objectNamespace`, `fieldNamespace`, `value`, `isActive`) ");
  107. } catch (Exception $e) {
  108. DBG::log($e);
  109. }
  110. try {
  111. DB::getPDO()->execSql(" ALTER TABLE `{$this->_enumRootTableName}` ADD `sortPrio` tinyint NOT NULL DEFAULT 0 ");
  112. } catch (Exception $e) {
  113. DBG::log($e);
  114. }
  115. DB::getPDO()->execSql(" REPLACE INTO CRM_CONFIG (`CONF_KEY`,`CONF_VAL`) VALUES ('Schema_SystemObjectFieldStorageAcl__version', '{$this->_version}') ");
  116. }
  117. }
  118. public static function getAntAclXsdBasePath($typeName) {
  119. if (!$typeName) throw new Exception("Missing typeName");
  120. $antAclPath = null;
  121. if ($activeProject = Config::getProjectPath()) {
  122. $tryProjectSchemaPath = "{$activeProject}/schema/ant-object/" . str_replace(['__x3A__', ':'], ['.', '/'], $typeName);
  123. if (file_exists($tryProjectSchemaPath)) {
  124. $antAclPath = $tryProjectSchemaPath;
  125. }
  126. }
  127. if (!$antAclPath) {
  128. $antAclPath = APP_PATH_SCHEMA . DS . 'ant-object' . DS . str_replace(['__x3A__', ':'], ['.', '/'], $typeName);
  129. }
  130. return $antAclPath;
  131. }
  132. public function updateCache($namespace = null) {
  133. DBG::log("SystemObjectField::updateCache({$namespace})...");
  134. if (!$namespace) return;
  135. DB::getPDO()->update($this->_rootTableName, 'objectNamespace', $namespace, ['isActive' => 0]);
  136. DB::getPDO()->update("{$this->_enumRootTableName}", 'objectNamespace', $namespace, ['isActive' => 0]);
  137. if (!$namespace) throw new Exception("Missing namespace '{$namespace}'");
  138. $objectItem = SchemaFactory::loadDefaultObject('SystemObject')->getItem($namespace);
  139. DBG::nicePrint($objectItem, '$objectItem');
  140. DBG::log($objectItem, 'array', '$objectItem');
  141. switch ($objectItem['_type']) {
  142. case 'AntAcl': $this->updateCacheAntAcl($objectItem); break;
  143. case 'TableAcl': $this->updateCacheTableAcl($objectItem); break;
  144. case 'StorageAcl': $this->updateCacheStorageAcl($objectItem); break;
  145. default: throw new Exception("TODO: Not Implemented type '{$objectItem['_type']}'");
  146. }
  147. // TODO: mv from methods: SchemaFactory::loadDefaultObject('SystemObject')->updateItem([
  148. // 'namespace' => $item['namespace'],
  149. // 'isStructInstalled' => 1
  150. // ]);
  151. $dbName = DB::getPDO()->getDatabaseName();
  152. DB::getPDO()->execSql("
  153. update `{$this->_rootTableName}` t
  154. set t.isLocal = IF(
  155. ( select c.COLUMN_NAME
  156. from information_schema.COLUMNS c
  157. where c.COLUMN_NAME = t.fieldNamespace
  158. and c.TABLE_SCHEMA = '{$dbName}'
  159. and c.TABLE_NAME = '{$objectItem['_rootTableName']}'
  160. limit 1
  161. ) is null
  162. , 0, 1)
  163. where t.objectNamespace = '{$objectItem['namespace']}'
  164. and t._rootTableName = '{$objectItem['_rootTableName']}'
  165. ");
  166. DB::getPDO()->execSql("
  167. UPDATE `{$this->_rootTableName}` t
  168. LEFT JOIN `CRM_LISTA_ZASOBOW` z on ( z.ID = t.idZasob )
  169. SET t.sortPrio = IF(z.ID is not null, z.SORT_PRIO, 0)
  170. WHERE t.objectNamespace = '{$objectItem['namespace']}'
  171. ");
  172. }
  173. public function updateCacheAntAcl($item) {
  174. Lib::loadClass('AntAclBase');
  175. $antAclPath = Schema_SystemObjectFieldStorageAcl::getAntAclXsdBasePath($item['typeName']);
  176. DBG::log(['typeName'=>$item['typeName'], 'antAclPath'=>$antAclPath], 'array', "AntAcl build.xml path");
  177. if (!file_exists("{$antAclPath}/build.xml")) throw new Exception("Ant build file not exists");
  178. Lib::loadClass('XML');
  179. $xsdType = XML::getXsdTypeFromXsdSchema("{$antAclPath}/{$item['name']}.xsd", $namespace = $item['namespace'], $name = $item['name']);
  180. DBG::nicePrint($xsdType, '$xsdType');
  181. if (empty($xsdType['struct'])) throw new Exception("Field list not found for '{$item['namespace']}'");
  182. foreach ($xsdType['struct'] as $fieldName => $x) {
  183. $listEnum = [];
  184. if (!empty($x['restrictions']['enumeration'])) {
  185. $listEnum = $x['restrictions']['enumeration'];
  186. unset($x['restrictions']['enumeration']);
  187. }
  188. DB::getPDO()->insertOrUpdate($this->_rootTableName, [
  189. 'namespace' => "{$item['namespace']}/{$fieldName}",
  190. 'objectNamespace' => $item['namespace'],
  191. 'idDatabase' => $item['idDatabase'],
  192. '_rootTableName' => $item['_rootTableName'],
  193. 'fieldNamespace' => $fieldName,
  194. 'xsdType' => $x['type'],
  195. 'xsdRestrictions' => json_encode($x['restrictions']),
  196. 'appInfo' => json_encode($x['appInfo']),
  197. 'minOccurs' => $x['minOccurs'],
  198. 'maxOccurs' => $x['maxOccurs'],
  199. 'isActive' => 1
  200. ]);
  201. if (!empty($listEnum)) {
  202. DBG::nicePrint($listEnum, '$listEnum');
  203. $sortPrio = count($listEnum);
  204. foreach ($listEnum as $value => $label) {
  205. DB::getPDO()->insertOrUpdate("{$this->_enumRootTableName}", [
  206. 'namespace' => "{$item['namespace']}/{$fieldName}/@{$value}",
  207. 'fieldNamespace' => $fieldName,
  208. 'objectNamespace' => $item['namespace'],
  209. 'value' => $value,
  210. 'label' => $label,
  211. 'isActive' => 1,
  212. 'sortPrio' => $sortPrio--
  213. ]);
  214. }
  215. }
  216. }
  217. SchemaFactory::loadDefaultObject('SystemObject')->updateItem([
  218. 'namespace' => $item['namespace'],
  219. 'isStructInstalled' => 1,
  220. 'primaryKey' => $xsdType['primaryKey'],
  221. ]);
  222. DB::getPDO()->execSql("
  223. DELETE from `{$this->_enumRootTableName}`
  224. where isActive = 0
  225. and objectNamespace = :objectNamespace
  226. ", [
  227. ':objectNamespace' => $item['namespace'],
  228. ]);
  229. $zasobTableName = substr($item['objectNamespace'], strlen('default_db/'));
  230. $zasobTableName = (false !== strpos($zasobTableName, '/'))
  231. ? $item['objectNamespace']
  232. : $zasobTableName;
  233. DB::getPDO()->execSql("
  234. update `{$this->_rootTableName}` t
  235. join CRM_LISTA_ZASOBOW zp on(zp.PARENT_ID = {$item['idDatabase']} and zp.`DESC` = '{$zasobTableName}')
  236. join CRM_LISTA_ZASOBOW z on(z.PARENT_ID = zp.ID and z.`DESC` = t.fieldNamespace)
  237. set t.idZasob = z.ID
  238. where t.objectNamespace = '{$item['namespace']}'
  239. ");
  240. UI::alert('success', "Gotowe");
  241. {// TODO: DBG
  242. $schema = XML::readXmlFileToArray("{$antAclPath}/{$item['name']}.xsd");
  243. DBG::nicePrint($schema, '$schema');
  244. Lib::loadClass('Core_XmlWriter');
  245. ob_start();
  246. $xmlWriter = new Core_XmlWriter();
  247. $xmlWriter->openUri('php://output');
  248. $xmlWriter->setIndent(true);
  249. $xmlWriter->startDocument('1.0','UTF-8');
  250. $xmlWriter->h($schema[0], $schema[1], $schema[2]);
  251. $xmlWriter->endDocument();
  252. echo UI::h('pre', ['style' => 'max-height:400px; overflow:scroll'], htmlspecialchars(ob_get_clean()));
  253. }
  254. }
  255. public function updateCacheStorageAcl($item) {
  256. Lib::loadClass('SchemaFactory');
  257. $aclName = substr($item['namespace'], strlen('default_objects/'));
  258. DBG::log($aclName, 'array', "\$aclName");
  259. $fvAcl = SchemaFactory::loadDefaultObject($aclName);
  260. DBG::log($fvAcl->getFields(), 'array', "\$fvAcl->getFields()");
  261. foreach ($fvAcl->getFields() as $field) {
  262. // 'name' => 'id',
  263. // 'perms' => '',
  264. // 'idZasob' => 10000,
  265. // 'xsdType' => 'xsd:integer',
  266. // 'label' => 'id',
  267. $fieldName = $field['name'];
  268. $xsdType = $field['xsdType'];
  269. DB::getPDO()->insertOrUpdate($this->_rootTableName, [
  270. 'namespace' => "{$item['namespace']}/{$fieldName}",
  271. 'objectNamespace' => $item['namespace'],
  272. 'idDatabase' => $item['idDatabase'],
  273. '_rootTableName' => $item['_rootTableName'],
  274. 'fieldNamespace' => $fieldName,
  275. 'xsdType' => $xsdType,
  276. // 'xsdRestrictions' => '',
  277. // 'appInfo' => '',
  278. // 'minOccurs' => '',
  279. // 'maxOccurs' => '',
  280. 'isActive' => 1
  281. ]);
  282. $listEnum = [];
  283. if (!empty($listEnum)) {
  284. DBG::nicePrint($listEnum, '$listEnum');
  285. foreach ($listEnum as $value => $label) {
  286. DB::getPDO()->insertOrUpdate("{$this->_enumRootTableName}", [
  287. 'namespace' => "{$item['namespace']}/{$fieldName}/@{$value}",
  288. 'fieldNamespace' => $fieldName,
  289. 'objectNamespace' => $item['namespace'],
  290. 'value' => $value,
  291. 'label' => $label,
  292. 'isActive' => 1
  293. ]);
  294. }
  295. }
  296. }
  297. SchemaFactory::loadDefaultObject('SystemObject')->updateItem([
  298. 'namespace' => $item['namespace'],
  299. 'isStructInstalled' => 1
  300. ]);
  301. // $zasobTableName = substr($item['objectNamespace'], strlen('default_db/'));
  302. // $zasobTableName = (false !== strpos($zasobTableName, '/'))
  303. // ? $item['objectNamespace']
  304. // : $zasobTableName;
  305. // DB::getPDO()->execSql("
  306. // update `{$this->_rootTableName}` t
  307. // join CRM_LISTA_ZASOBOW zp on(zp.PARENT_ID = {$item['idDatabase']} and zp.`DESC` = '{$zasobTableName}')
  308. // join CRM_LISTA_ZASOBOW z on(z.PARENT_ID = zp.ID and z.`DESC` = t.fieldNamespace)
  309. // set t.idZasob = z.ID
  310. // where t.objectNamespace = '{$item['namespace']}'
  311. // ");
  312. }
  313. public function updateCacheTableAcl($item) {
  314. // TODO: xsdType - convert mysql type to xsdType, xsdRestrictions
  315. $xsdInfo = [];
  316. Lib::loadClass('SchemaHelper');
  317. $dbName = DB::getPDO()->getDatabaseName();
  318. $mysqlTypes = DB::getPDO()->fetchAll("
  319. select c.COLUMN_NAME, c.COLUMN_TYPE, c.DATA_TYPE, c.IS_NULLABLE, c.CHARACTER_MAXIMUM_LENGTH, c.NUMERIC_PRECISION, c.NUMERIC_SCALE
  320. from `information_schema`.`COLUMNS` c
  321. where c.TABLE_SCHEMA = '{$dbName}'
  322. and c.TABLE_NAME = '{$item['_rootTableName']}'
  323. ");
  324. foreach ($mysqlTypes as $mysqlType) {
  325. $xsdInfo[ $mysqlType['COLUMN_NAME'] ] = SchemaHelper::convertMysqlTypeToSchemaXsd($mysqlType);
  326. }
  327. DBG::nicePrint($xsdInfo, '$xsdInfo');
  328. foreach ($xsdInfo as $fieldName => $x) {
  329. $listEnum = [];
  330. if (!empty($x['restrictions']['enumeration'])) {
  331. $listEnum = $x['restrictions']['enumeration'];
  332. unset($x['restrictions']['enumeration']);
  333. }
  334. DB::getPDO()->insertOrUpdate($this->_rootTableName, [
  335. 'namespace' => "{$item['namespace']}/{$fieldName}",
  336. 'fieldNamespace' => $fieldName,
  337. 'isActive' => 1,
  338. 'idDatabase' => $item['idDatabase'],
  339. '_rootTableName' => $item['_rootTableName'],
  340. 'objectNamespace' => $item['namespace'],
  341. 'xsdType' => $x['type'],
  342. 'xsdRestrictions' => json_encode($x['restrictions']),
  343. 'appInfo' => json_encode([]),
  344. ]);
  345. if (!empty($listEnum)) {
  346. DBG::nicePrint($listEnum, '$listEnum');
  347. foreach ($listEnum as $value => $label) {
  348. DB::getPDO()->insertOrUpdate("{$this->_enumRootTableName}", [
  349. 'namespace' => "{$item['namespace']}/{$fieldName}/@{$value}",
  350. 'fieldNamespace' => $fieldName,
  351. 'objectNamespace' => $item['namespace'],
  352. 'value' => $value,
  353. 'label' => $label,
  354. 'isActive' => 1
  355. ]);
  356. }
  357. }
  358. }
  359. SchemaFactory::loadDefaultObject('SystemObject')->updateItem([
  360. 'namespace' => $item['namespace'],
  361. 'isStructInstalled' => 1
  362. ]);
  363. $zasobTableName = substr($item['namespace'], strlen('default_db/'));
  364. $zasobTableName = (false !== strpos($zasobTableName, '/'))
  365. ? $item['namespace']
  366. : $zasobTableName;
  367. DB::getPDO()->execSql("
  368. update `{$this->_rootTableName}` t
  369. join CRM_LISTA_ZASOBOW zp on(zp.PARENT_ID = {$item['idDatabase']} and zp.`DESC` = '{$zasobTableName}' and zp.PARENT_ID = {$item['idDatabase']})
  370. join CRM_LISTA_ZASOBOW z on(z.PARENT_ID = zp.ID and z.`DESC` = t.fieldNamespace)
  371. set t.idZasob = z.ID
  372. where t.objectNamespace = '{$item['namespace']}'
  373. ");
  374. $struct = $this->getItems([
  375. '__backRef' => [
  376. 'namespace' => 'default_objects/SystemObject',
  377. 'primaryKey' => $item['namespace']
  378. ]
  379. ]);
  380. DBG::nicePrint($struct, '$struct');
  381. {// TODO: DBG
  382. $schema = ['xsd:schema', [
  383. 'xmlns:xsd' => "http://www.w3.org/2001/XMLSchema",
  384. 'xmlns:gml' => "http://www.opengis.net/gml",
  385. 'xmlns:p5' => "https://biuro.biall-net.pl/wfs",
  386. 'xmlns:default_db' => "https://biuro.biall-net.pl/wfs/default_db",
  387. 'xmlns:default_objects' => "https://biuro.biall-net.pl/wfs/default_objects",
  388. 'elementFormDefault' => "qualified",
  389. 'version' => "1.0.0",
  390. ], []];
  391. Lib::loadClass('Api_WfsNs');
  392. $tnsUri = Api_WfsNs::getNsUri($item['nsPrefix']);
  393. $schema[1]['xmlns:' . Api_WfsNs::getNsPrefix($tnsUri)] = $tnsUri;
  394. $schema[1]['targetNamespace'] = $tnsUri;
  395. $schema[2][] = ['xsd:import', ['namespace'=>"http://www.opengis.net/gml", 'schemaLocation'=>"https://biuro.biall-net.pl/dev-pl/se-master/schema/gml/2.1.2/feature.xsd"], null];
  396. $schema[2][] = ['xsd:complexType', [ 'name'=> $item['name'] . "Type" ], [
  397. [ 'xsd:complexContent', [], [
  398. [ 'xsd:extension', ['base'=>"gml:AbstractFeatureType"], [
  399. [ 'xsd:sequence', [], array_map(function ($field) {
  400. $attrs = [
  401. 'name' => $field['fieldNamespace'],
  402. // <xsd:element minOccurs="1" maxOccurs="1" name="ID" type="xsd:integer" nillable="true"/>
  403. 'minOccurs' => $field['minOccurs'],
  404. 'maxOccurs' => $field['maxOccurs'],
  405. ];
  406. $childrens = null;
  407. $restrictions = [];
  408. foreach ($this->getXsdRestrictionsValue($field) as $k => $v) {
  409. if ('enumeration' == $k) {
  410. foreach ($v as $enumValue) {
  411. $restrictions[] = [ 'xsd:enumeration', [ 'value' => $enumValue ], null ];
  412. }
  413. } else if ('maxLength' == $k) {
  414. $restrictions[] = [ 'xsd:maxLength', [ 'value' => $v ], null ];
  415. } else if ('totalDigits' == $k) {
  416. $restrictions[] = [ 'xsd:totalDigits', [ 'value' => $v ], null ];
  417. } else if ('fractionDigits' == $k) {
  418. $restrictions[] = [ 'xsd:fractionDigits', [ 'value' => $v ], null ];
  419. } else if ('nillable' == $k) {
  420. if ($v) $attrs['nillable'] = "true";
  421. } else {
  422. DBG::log(['TODO' => $k, $v]);
  423. }
  424. }
  425. if (!empty($restrictions)) {
  426. $childrens = [
  427. [ 'xsd:simpleType', [], [
  428. [ 'xsd:restriction', [ 'base' => $field['xsdType'] ], $restrictions ]
  429. ] ]
  430. ];
  431. } else {
  432. $attrs['type'] = $field['xsdType'];
  433. }
  434. return [ 'xsd:element', $attrs, $childrens ];
  435. }, $struct) ]
  436. ] ]
  437. ] ]
  438. ] ];
  439. $schema[2][] = ['xsd:element', [ 'name' => $item['name'], 'type' => "{$item['nsPrefix']}:{$item['name']}Type", 'substitutionGroup' => "gml:_Feature" ], null];
  440. DBG::nicePrint($schema, '$schema');
  441. Lib::loadClass('Core_XmlWriter');
  442. ob_start();
  443. $xmlWriter = new Core_XmlWriter();
  444. $xmlWriter->openUri('php://output');
  445. $xmlWriter->setIndent(true);
  446. $xmlWriter->startDocument('1.0','UTF-8');
  447. $xmlWriter->h($schema[0], $schema[1], $schema[2]);
  448. $xmlWriter->endDocument();
  449. echo UI::h('pre', ['style' => 'max-height:400px; overflow:scroll'], htmlspecialchars(ob_get_clean()));
  450. }
  451. }
  452. public function _parseWhere($params = []) {
  453. $sqlWhere = [];
  454. DBG::log($params, 'array', "SystemObject::_parseWhere");
  455. if (!empty($params['__backRef'])) {
  456. // '__backRef' => [
  457. // 'namespace' => 'default_objects/SystemObject',
  458. // 'primaryKey' => 'default_db/TEST_PERMS',
  459. // ),
  460. if (empty($params['__backRef']['namespace'])) throw new Exception("Missing refFrom/namespace");
  461. if (empty($params['__backRef']['primaryKey'])) throw new Exception("Missing refFrom/primaryKey");
  462. if ('default_objects/SystemObject' != $params['__backRef']['namespace']) throw new Exception("Unsupported refFrom/namespace '{$params['__backRef']['namespace']}'");
  463. $sqlWhere[] = "t.objectNamespace = " . DB::getPDO()->quote($params['__backRef']['primaryKey'], PDO::PARAM_INT);
  464. }
  465. {
  466. $filterParams = [];
  467. $xsdFields = $this->getXsdTypes();
  468. DBG::log($xsdFields);
  469. foreach ($params as $k => $v) {
  470. if ('f_' != substr($k, 0, 2)) continue;
  471. $fieldName = substr($k, 2);
  472. if (!array_key_exists($fieldName, $xsdFields)) {
  473. // TODO: check query by xpath or use different param prefix
  474. throw new Exception("Field '{$fieldName}' not found in '{$this->_namespace}'");
  475. }
  476. if ('p5:' == substr($xsdFields[$fieldName], 0, 3)) {
  477. continue;
  478. }
  479. $filterParams[$fieldName] = $v;
  480. }
  481. }
  482. if (!empty($filterParams)) {
  483. DBG::log($filterParams, 'array', "SystemObject::_parseWhere TODO \$filterParams");
  484. foreach ($filterParams as $fieldName => $value) {
  485. if (is_array($value)) {
  486. DBG::log($value, 'array', "TODO SystemObject::_parseWhere array value for \$filterParams[{$fieldName}]");
  487. } else if (is_scalar($value)) {
  488. if ('=' == substr($value, 0, 1)) {
  489. $sqlWhere[] = "t.{$fieldName} = " . DB::getPDO()->quote(substr($value, 1), PDO::PARAM_STR);
  490. } else {
  491. $sqlWhere[] = "t.{$fieldName} like " . DB::getPDO()->quote("%{$value}%", PDO::PARAM_STR);
  492. }
  493. } else {
  494. DBG::log($value, 'array', "BUG SystemObject::_parseWhere unknown type for \$filterParams[{$fieldName}]");
  495. }
  496. }
  497. }
  498. return (!empty($sqlWhere)) ? "where " . implode(" and ", $sqlWhere) : '';
  499. }
  500. public function getTotal($params = []) {
  501. $sqlWhere = $this->_parseWhere($params);
  502. return DB::getPDO()->fetchValue("
  503. select count(1) as cnt
  504. from `{$this->_rootTableName}` t
  505. {$sqlWhere}
  506. ");
  507. }
  508. public function getItem($pk, $params = []) {
  509. if (!$pk) throw new Exception("Missing primary key '{$this->_namespace}'");
  510. $pkField = $this->getSqlPrimaryKeyField();
  511. if (!$pkField) throw new Exception("Missing primary key field defined in '{$this->_namespace}'");
  512. $sqlPk = DB::getPDO()->quote($pk, PDO::PARAM_STR);
  513. $item = DB::getPDO()->fetchFirst("
  514. select t.*
  515. from `{$this->_rootTableName}` t
  516. where t.`{$pkField}` = {$sqlPk}
  517. ");
  518. if (!$item) throw new Exception("Item '{$pk}' not exists - type '{$this->_namespace}'");
  519. return $this->buildFeatureFromSqlRow($item, $params);
  520. }
  521. public function getItems($params = []) {
  522. $sqlWhere = $this->_parseWhere($params);
  523. $currSortCol = V::get('order_by', 'idZasob', $params);
  524. $currSortFlip = strtolower(V::get('order_dir', 'desc', $params));
  525. // TODO: validate $currSortCol is in field list
  526. // TODO: validate $currSortFlip ('asc' or 'desc')
  527. $xsdFields = $this->getXsdTypes();
  528. if (!array_key_exists($currSortCol, $xsdFields)) throw new Exception("Field '{$currSortCol}' not found in '{$this->_namespace}'");
  529. if (!in_array($currSortFlip, ['asc', 'desc'])) throw new Exception("Sort dir not allowed");
  530. $sqlOrderBy = "order by t.`{$currSortCol}` {$currSortFlip}";
  531. $limit = V::get('limit', 0, $params, 'int');
  532. $limit = ($limit < 0) ? 0 : $limit;
  533. $offset = V::get('limitstart', 0, $params, 'int');
  534. $offset = ($offset < 0) ? 0 : $offset;
  535. $sqlLimit = ($limit > 0)
  536. ? "limit {$limit} offset {$offset}"
  537. : '';
  538. return array_map(array($this, 'buildFeatureFromSqlRow'), DB::getPDO()->fetchAll("
  539. select t.*
  540. from `{$this->_rootTableName}` t
  541. {$sqlWhere}
  542. {$sqlOrderBy}
  543. {$sqlLimit}
  544. "));
  545. }
  546. public function getXsdRestrictionsValue($item) {
  547. $xsdRestrictions = @json_decode($item['xsdRestrictions'], $assoc = true);
  548. if (empty($xsdRestrictions)) $xsdRestrictions = [];
  549. if (array_key_exists('__DBG__', $xsdRestrictions)) unset($xsdRestrictions['__DBG__']);
  550. return $xsdRestrictions;
  551. }
  552. public function buildFeatureFromSqlRow($item) {
  553. if ('p5:enum' == V::get('xsdType', '', $item)) {
  554. $xsdRestrictions = @json_decode($item['xsdRestrictions'], $assoc = true);
  555. $xsdRestrictions['enumeration'] = [];
  556. foreach (DB::getPDO()->fetchAll("
  557. select t.value, t.label
  558. from `{$this->_enumRootTableName}` t
  559. where t.objectNamespace = '{$item['objectNamespace']}'
  560. and t.fieldNamespace = '{$item['fieldNamespace']}'
  561. and t.isActive = 1
  562. order by sortPrio DESC
  563. ") as $enum) {
  564. $xsdRestrictions['enumeration'][ $enum['value'] ] = $enum['label'];
  565. }
  566. $item['xsdRestrictions'] = json_encode($xsdRestrictions);
  567. }
  568. return $item;
  569. }
  570. public function updateItem($itemPatch) {
  571. SchemaFactory::loadDefaultObject('SystemObject')->clearGetItemCache();
  572. $pkField = $this->getPrimaryKeyField();
  573. $pk = V::get($pkField, null, $itemPatch);
  574. if (null === $pk) throw new Exception("BUG missing primary key field for '{$this->_namespace}' updateItem");
  575. DBG::log(['updateItem $itemPatch', $itemPatch]);
  576. unset($itemPatch[$pkField]);
  577. if (empty($itemPatch)) return 0;
  578. foreach ($itemPatch as $fieldName => $value) {
  579. if ('idZasob' == $fieldName) continue;
  580. throw new Exception("Update field '{$fieldName}' not allowed for '{$this->_namespace}'");
  581. }
  582. return DB::getPDO()->update($this->_rootTableName, $pkField, $pk, $itemPatch);
  583. }
  584. }