SystemObjectFieldStorageAcl.php 22 KB

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