SystemObjectFieldStorageAcl.php 22 KB

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