SystemObjectFieldStorageAcl.php 21 KB

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