SystemObjectFieldStorageAcl.php 21 KB

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