SystemObjectFieldStorageAcl.php 22 KB

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