SystemObjectFieldStorageAcl.php 23 KB

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