SystemObjectFieldStorageAcl.php 23 KB

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