SystemObjectFieldStorageAcl.php 21 KB

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