SystemObjectFieldStorageAcl.php 23 KB

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