SystemObjectFieldStorageAcl.php 23 KB

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