SystemObjectFieldStorageAcl.php 24 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. 'minOccurs' => [ '@type' => 'xsd:string' ],
  19. 'maxOccurs' => [ '@type' => 'xsd:string' ], // '0..unbounded',
  20. 'isActive' => [ '@type' => 'xsd:integer' ], // installed
  21. 'description' => [ '@type' => 'xsd:string' ],
  22. // 'A_RECORD_CREATE_AUTHOR' => [ '@type' => 'xsd:string' , '@label' => 'autor' ],
  23. // 'A_RECORD_CREATE_DATE' => [ '@type' => 'xsd:date' , '@label' => 'utworzono' ],
  24. // 'A_RECORD_UPDATE_AUTHOR' => [ '@type' => 'xsd:string' , '@label' => 'zaktualizował' ],
  25. // 'A_RECORD_UPDATE_DATE' => [ '@type' => 'xsd:date', '@label' => 'zaktualizowano' ],
  26. ]
  27. ];
  28. // public $_rootTableName = 'CRM_LISTA_ZASOBOW';
  29. public $_rootTableName = 'CRM_#CACHE_ACL_OBJECT_FIELD';
  30. public $_version = '1';
  31. public function updateCache($namespace = null) {
  32. DBG::simpleLog('schema', "SystemObjectField::updateCache({$namespace})...");
  33. // DB::getPDO()->execSql(" drop table if exists `{$this->_rootTableName}` "); // TODO: DBG
  34. DB::getPDO()->execSql("
  35. create table if not exists `{$this->_rootTableName}` (
  36. `namespace` varchar(255) DEFAULT '',
  37. `fieldNamespace` varchar(255) DEFAULT '',
  38. `idZasob` int(11) DEFAULT NULL,
  39. `idDatabase` int(11) NOT NULL,
  40. `_rootTableName` varchar(255) DEFAULT '',
  41. `objectNamespace` varchar(255) DEFAULT '',
  42. `xsdType` varchar(255) DEFAULT '',
  43. `xsdRestrictions` varchar(1000) DEFAULT '',
  44. `minOccurs` int(11) DEFAULT '0',
  45. `maxOccurs` varchar(11) DEFAULT '1' COMMENT '0..unbounded',
  46. `isActive` tinyint(1) NOT NULL DEFAULT 0 COMMENT 'installed',
  47. `description` varchar(255) DEFAULT '',
  48. UNIQUE KEY `idZasob` (idZasob),
  49. PRIMARY KEY (`namespace`),
  50. KEY `isActive` (isActive)
  51. ) ENGINE=MyISAM DEFAULT CHARSET=latin2
  52. ");
  53. // DB::getPDO()->execSql(" drop table if exists `{$this->_rootTableName}_enum` ");// TODO: DBG
  54. DB::getPDO()->execSql("
  55. create table if not exists `{$this->_rootTableName}_enum` (
  56. `namespace` varchar(255) DEFAULT '' COMMENT 'concat obj ns / field ns / value',
  57. `fieldNamespace` varchar(255) DEFAULT '',
  58. `objectNamespace` varchar(255) DEFAULT '',
  59. `value` varchar(255) DEFAULT '',
  60. `label` varchar(255) DEFAULT '',
  61. `isActive` tinyint(1) NOT NULL DEFAULT 0 COMMENT 'installed',
  62. KEY `objectNamespace` (`objectNamespace`),
  63. KEY `fieldNamespace` (`fieldNamespace`),
  64. KEY `isActive` (isActive)
  65. ) ENGINE=MyISAM DEFAULT CHARSET=latin2
  66. ");
  67. DB::getPDO()->update($this->_rootTableName, 'objectNamespace', $namespace, ['isActive' => 0]);
  68. DB::getPDO()->update("{$this->_rootTableName}_enum", 'objectNamespace', $namespace, ['isActive' => 0]);
  69. $sysObjectStorage = SchemaFactory::loadDefaultObject('SystemObject');
  70. if (!$namespace) throw new Exception("Missing namespace '{$namespace}'");
  71. $objectItem = $sysObjectStorage->getItem($namespace);
  72. DBG::nicePrint($objectItem, '$objectItem');
  73. DBG::log($objectItem, 'array', '$objectItem');
  74. switch ($objectItem['_type']) {
  75. case 'AntAcl': $this->updateCacheAntAcl($objectItem); break;
  76. case 'TableAcl': $this->updateCacheTableAcl($objectItem); break;
  77. default: throw new Exception("TODO: Not Implemented type '{$objectItem['_type']}'");
  78. }
  79. // TODO: mv from methods: SchemaFactory::loadDefaultObject('SystemObject')->updateItem([
  80. // 'namespace' => $item['namespace'],
  81. // 'isStructInstalled' => 1
  82. // ]);
  83. }
  84. public function updateCacheAntAcl($item) {
  85. Lib::loadClass('AntAclBase');
  86. $antAclPath = APP_PATH_SCHEMA . DS . 'ant-object' . DS . str_replace(['__x3A__', ':'], ['.', '/'], $item['typeName']);
  87. if (!file_exists("{$antAclPath}/build.xml")) throw new Exception("Ant build file not exists");
  88. // if (file_exists("{$antAclPath}/{$item['name']}.xsd")) {
  89. // DBG::log("{$antAclPath}/{$item['name']}.xsd", 'string', 'xsd file exists');
  90. // $outputType = 'XML';
  91. // $antOutput = file_get_contents("{$antAclPath}/{$item['name']}.xsd");
  92. // } else {
  93. // DBG::log($antAclPath, 'string', '$antAclPath');
  94. // $antBin = APP_PATH_WWW . DS . 'stuff' . DS . 'dita-ot-2.3.3' . DS . 'bin' . DS . 'ant';
  95. // $cmd = "cd {$antAclPath} && {$antBin} DescribeFeatureType 2>&1";
  96. // V::exec($cmd, $out, $ret);
  97. // DBG::log($out, 'array', "DescribeFeatureType ret({$ret})");
  98. // $outputType = 'XML';
  99. // $antOutput = []; $startRead = false;
  100. // foreach ($out as $line) {
  101. // // $line = " [echo] OUTPUT__TYPE__XML"
  102. // if ('[echo]' == substr(trim($line), 0, 6)) {
  103. // $line = trim(substr(trim($line), 7));
  104. // }
  105. //
  106. // if (!$startRead) {
  107. // if ('OUTPUT__TYPE__XML' == $line) $outputType = 'XML';
  108. // if ('OUTPUT__TYPE__HTML' == $line) $outputType = 'HTML';
  109. // if ('OUTPUT__START' == $line) {
  110. // $startRead = true;
  111. // continue;
  112. // }
  113. // } else {
  114. // if ('<!DOCTYPE' == substr($line, 0, strlen('<!DOCTYPE'))) continue;
  115. // if ('OUTPUT__END' == $line) {
  116. // break;
  117. // }
  118. // $antOutput[]= $line;
  119. // }
  120. // }
  121. // if (!empty($antOutput)) $antOutput = implode("\n", $antOutput);
  122. // }
  123. // if (empty($antOutput)) UI::alert('danger', "Empty output!");
  124. // else {
  125. // echo UI::h('p', [], "Ant Schema:");
  126. // if ('XML' == $outputType) {
  127. // echo UI::h('pre', ['style' => 'max-height:400px; overflow:scroll'], htmlspecialchars($antOutput));
  128. // } else if ('HTML' == $outputType) {
  129. // echo UI::h('div', ['class'=>"container", 'style'=>"padding:12px; border:1px solid #ddd"], $antOutput);
  130. // }
  131. // }
  132. Lib::loadClass('XML');
  133. $schema = XML::readXmlFileToArray("{$antAclPath}/{$item['name']}.xsd");
  134. if (empty($schema)) throw new Exception("Missing schema file for '{$item['namespace']}'");
  135. $xsdType = [ // find xsd:element with @name = $item['name']
  136. 'nsPrefix' => null,
  137. 'name' => null,
  138. 'nsUri' => null,
  139. 'targetNsUri' => V::get('targetNamespace', '', $schema[1])
  140. ];
  141. if (!$xsdType['targetNsUri']) throw new Exception("Missing schema target namespace declaration '{$item['name']}'");
  142. foreach ($schema[2] as $n) {
  143. if ('xsd:element' != $n[0]) continue;
  144. if ($item['name'] != V::get('name', '', $n[1])) continue;
  145. list($xsdType['nsPrefix'], $xsdType['name']) = explode(':', V::get('type', '', $n[1]));
  146. }
  147. if (!$xsdType['nsPrefix'] || !$xsdType['name']) throw new Exception("Missing schema root element name = '{$item['name']}'");
  148. $xsdType['nsUri'] = V::get("xmlns:{$xsdType['nsPrefix']}", '', $schema[1]);// find xmlns:default_objects = "https://biuro.biall-net.pl/wfs/default_objects"
  149. if (!$xsdType['nsUri']) throw new Exception("Missing schema root element namespace declaration = '{$item['name']}'");
  150. if ($xsdType['nsUri'] != $xsdType['targetNsUri']) throw new Exception("TODO: type ns is not the same as targetNamespace '{$item['name']}'");// TODO
  151. foreach ($schema[2] as $n) {
  152. if ('xsd:complexType' != $n[0]) continue;
  153. if ($xsdType['name'] != V::get('name', '', $n[1])) continue;
  154. DBG::nicePrint($n, 'TODO: parse complexType');
  155. // complexType/complexContent/extension[base=...]/sequence/element
  156. if ($n[2][0][0] != 'xsd:complexContent') throw new Exception("Error Parsing Schema - expected 'complexType/complexContent'");
  157. if ($n[2][0][2][0][0] != 'xsd:extension') throw new Exception("Error Parsing Schema - expected 'complexType/complexContent/extension'");
  158. $xsdType['extensionBase'] = V::get('base', '', $n[2][0][2][0][1]);
  159. if ($n[2][0][2][0][2][0][0] != 'xsd:sequence') throw new Exception("Error Parsing Schema - expected 'complexType/complexContent/extension/sequence'");
  160. foreach ($n[2][0][2][0][2][0][2] as $f) {
  161. if ($f[0] !== 'xsd:element') {
  162. DBG::log($n, 'array', "Schema xsd parse error - Not implemented node type '{$f[0]}'");
  163. continue;
  164. }
  165. $fieldName = XML::findElementName($schema, $f); // V::get('name', '', $f[1]);
  166. if (!$fieldName) throw new Exception("Error Parsing Schema - expected 'element[@name]'");
  167. if ('__' === substr($fieldName, 0, 2)) continue;
  168. if (!V::get('type', '', $f[1]) && !V::get('ref', '', $f[1]) && empty($f[2])) {
  169. UI::alert('danger', "Skipping not implemented field structure '{$fieldName}'");
  170. continue;
  171. }
  172. $xsdType['struct'][$fieldName] = [
  173. 'type' => XML::findElementType($schema, $f),
  174. 'minOccurs' => V::get('minOccurs', 0, $f[1], 'int'),
  175. 'maxOccurs' => V::get('maxOccurs', '1', $f[1]),
  176. 'restrictions' => XML::findElementRestrictions($schema, $f),
  177. ];
  178. }
  179. }
  180. DBG::nicePrint($xsdType, '$xsdType');
  181. if (empty($xsdType['struct'])) throw new Exception("Field list not found for '{$item['namespace']}'");
  182. foreach ($xsdType['struct'] as $fieldName => $x) {
  183. $listEnum = [];
  184. if (!empty($x['restrictions']['enumeration'])) {
  185. $listEnum = $x['restrictions']['enumeration'];
  186. unset($x['restrictions']['enumeration']);
  187. }
  188. DB::getPDO()->insertOrUpdate($this->_rootTableName, [
  189. 'namespace' => "{$item['namespace']}/{$fieldName}",
  190. 'objectNamespace' => $item['namespace'],
  191. 'idDatabase' => $item['idDatabase'],
  192. '_rootTableName' => $item['_rootTableName'],
  193. 'fieldNamespace' => $fieldName,
  194. 'xsdType' => $x['type'],
  195. 'xsdRestrictions' => json_encode($x['restrictions']),
  196. 'minOccurs' => $x['minOccurs'],
  197. 'maxOccurs' => $x['maxOccurs'],
  198. 'isActive' => 1
  199. ]);
  200. if (!empty($listEnum)) {
  201. DBG::nicePrint($listEnum, '$listEnum');
  202. foreach ($listEnum as $value => $label) {
  203. DB::getPDO()->insertOrUpdate("{$this->_rootTableName}_enum", [
  204. 'namespace' => "{$item['namespace']}/{$fieldName}/@{$value}",
  205. 'fieldNamespace' => $fieldName,
  206. 'objectNamespace' => $item['namespace'],
  207. 'value' => $value,
  208. 'label' => $label,
  209. 'isActive' => 1
  210. ]);
  211. }
  212. }
  213. }
  214. SchemaFactory::loadDefaultObject('SystemObject')->updateItem([
  215. 'namespace' => $item['namespace'],
  216. 'isStructInstalled' => 1
  217. ]);
  218. $zasobTableName = substr($item['objectNamespace'], strlen('default_db/'));
  219. $zasobTableName = (false !== strpos($zasobTableName, '/'))
  220. ? $item['objectNamespace']
  221. : $zasobTableName;
  222. DB::getPDO()->execSql("
  223. update `{$this->_rootTableName}` t
  224. join CRM_LISTA_ZASOBOW zp on(zp.PARENT_ID = {$item['idDatabase']} and zp.`DESC` = '{$zasobTableName}')
  225. join CRM_LISTA_ZASOBOW z on(z.PARENT_ID = zp.ID and z.`DESC` = t.fieldNamespace)
  226. set t.idZasob = z.ID
  227. where t.objectNamespace = '{$item['namespace']}'
  228. ");
  229. {// TODO: DBG
  230. DBG::nicePrint($schema, '$schema');
  231. Lib::loadClass('Core_XmlWriter');
  232. ob_start();
  233. $xmlWriter = new Core_XmlWriter();
  234. $xmlWriter->openUri('php://output');
  235. $xmlWriter->setIndent(true);
  236. $xmlWriter->startDocument('1.0','UTF-8');
  237. $xmlWriter->h($schema[0], $schema[1], $schema[2]);
  238. $xmlWriter->endDocument();
  239. echo UI::h('pre', ['style' => 'max-height:400px; overflow:scroll'], htmlspecialchars(ob_get_clean()));
  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. ]);
  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. $pkField = $this->getPrimaryKeyField();
  499. $pk = V::get($pkField, null, $itemPatch);
  500. if (null === $pk) throw new Exception("BUG missing primary key field for '{$this->_namespace}' updateItem");
  501. DBG::log(['updateItem $itemPatch', $itemPatch]);
  502. unset($itemPatch[$pkField]);
  503. if (empty($itemPatch)) return 0;
  504. foreach ($itemPatch as $fieldName => $value) {
  505. if ('idZasob' == $fieldName) continue;
  506. throw new Exception("Update field '{$fieldName}' not allowed for '{$this->_namespace}'");
  507. }
  508. return DB::getPDO()->update($this->_rootTableName, $pkField, $pk, $itemPatch);
  509. }
  510. }