SystemObjectFieldStorageAcl.php 22 KB

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