SystemObjectFieldStorageAcl.php 20 KB

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