SystemObjectFieldStorageAcl.php 23 KB

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