SystemObjectFieldStorageAcl.php 21 KB

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