SystemObjectFieldStorageAcl.php 21 KB

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