SystemObjectStorageAcl.php 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526
  1. <?php
  2. Lib::loadClass('Core_AclSimpleSchemaBase');
  3. Lib::loadClass('ParseOgcFilter');
  4. Lib::loadClass('Router');
  5. class Schema_SystemObjectStorageAcl extends Core_AclSimpleSchemaBase {
  6. public $_simpleSchema = [
  7. 'root' => [
  8. '@namespace' => 'default_objects/SystemObject',
  9. '@primaryKey' => 'namespace',
  10. 'idZasob' => [ '@type' => 'xsd:integer' ],
  11. 'idDatabase' => [ '@type' => 'xsd:integer' ],
  12. 'namespace' => [ '@type' => 'xsd:string' ],
  13. '_rootTableName' => [ '@type' => 'xsd:string' ],
  14. '_type' => [ '@type' => 'xsd:string' ],
  15. 'hasStruct' => [ '@type' => 'xsd:integer' ], // 0 - removed, old, 1 - has config, structure
  16. 'isStructInstalled' => [ '@type' => 'xsd:integer' ], // installed
  17. 'isObjectActive' => [ '@type' => 'xsd:integer' ], // (0,1) - admin settings with restrictions: (hasStruct, isStructInstalled, all fields installed and with idZasob)
  18. 'description' => [ '@type' => 'xsd:string' ],
  19. 'name' => [ '@type' => 'p5:string' ],
  20. 'typeName' => [ '@type' => 'p5:string' ],
  21. 'nsPrefix' => [ '@type' => 'p5:string' ],
  22. 'reinstallLink' => [ '@type' => 'p5:www_link' ],
  23. // 'A_RECORD_CREATE_AUTHOR' => [ '@type' => 'xsd:string' , '@label' => 'autor' ],
  24. // 'A_RECORD_CREATE_DATE' => [ '@type' => 'xsd:date' , '@label' => 'utworzono' ],
  25. // 'A_RECORD_UPDATE_AUTHOR' => [ '@type' => 'xsd:string' , '@label' => 'zaktualizował' ],
  26. // 'A_RECORD_UPDATE_DATE' => [ '@type' => 'xsd:date', '@label' => 'zaktualizowano' ],
  27. 'field' => [ '@ref' => 'default_objects/SystemObjectField', '@maxOccurs' => 'unbounded' ]
  28. ]
  29. ];
  30. // public $_rootTableName = 'CRM_LISTA_ZASOBOW';
  31. public $_rootTableName = 'CRM_#CACHE_ACL_OBJECT';
  32. public $_version = '1';
  33. // public function __construct($simpleSchema = null) {
  34. // parent::__construct($simpleSchema);
  35. // self::updateCacheIfNeeded(array($this, 'updateCache'));
  36. // }
  37. // public static function updateCacheIfNeeded($updateCallback) {
  38. // static $_cacheUpdated = null;
  39. // if (null !== $_cacheUpdated) return;
  40. // $conf = DB::getPDO()->fetchFirst("
  41. // select (select CONF_VAL from CRM_CONFIG where CONF_KEY = 'SystemObject__last_cache_update_date') as lastCacheUpdate
  42. // , (select CONF_VAL from CRM_CONFIG where CONF_KEY = 'SystemObject__force_cache_update') as forceCacheUpdate
  43. // , (select CONF_VAL from CRM_CONFIG where CONF_KEY = 'SystemObject__schema_version') as schemaVersion
  44. // , (select CONF_VAL from CRM_CONFIG where CONF_KEY = 'tbl_indexer_CRM_PROCES_last_exec_end') as lastProcesIndexer
  45. // , (
  46. // select IF('N/S;' = A_RECORD_UPDATE_DATE or A_RECORD_UPDATE_DATE is null or '' = A_RECORD_UPDATE_DATE, A_RECORD_CREATE_DATE, A_RECORD_UPDATE_DATE) as lastUpdateDate
  47. // from CRM_LISTA_ZASOBOW_HIST
  48. // order by ID DESC
  49. // limit 1
  50. // ) as lastZasobyUpdate
  51. // ");
  52. // if ($conf['lastZasobyUpdate']) {// fix date format - convert to Mysql date time format '2002-05-30 09:00:00'
  53. // if (preg_match('/^\d\d\d\d\-\d\d\-\d\d\-\d\d:\d\d$/', $conf['lastZasobyUpdate'])) { // 'Y-m-d-H:i'
  54. // $conf['lastZasobyUpdate'] = substr($conf['lastZasobyUpdate'], 0, 10) . " " . substr($conf['lastZasobyUpdate'], 11) . ":00";
  55. // } else if (preg_match('/^\d\d\d\d\-\d\d\-\d\d\-\d\d:\d\d:\d\d$/', $conf['lastZasobyUpdate'])) { // 'Y-m-d-H:i:s'
  56. // $conf['lastZasobyUpdate'] = substr($conf['lastZasobyUpdate'], 0, 10) . " " . substr($conf['lastZasobyUpdate'], 11);
  57. // } else if (preg_match('/^\d\d\d\d\-\d\d\-\d\d\ \d\d:\d\d:\d\d$/', $conf['lastZasobyUpdate'])) {
  58. // $conf['lastZasobyUpdate'] = substr($conf['lastZasobyUpdate'], 0, 10) . " " . substr($conf['lastZasobyUpdate'], 11);
  59. // }
  60. // }
  61. // // $lastProcesIndexer = DB::getPDO()->fetchValue(" select CONF_VAL from CRM_CONFIG where CONF_KEY = 'tbl_indexer_CRM_PROCES_last_exec_end' ");
  62. // $updateReason = null;
  63. // if ('1' == $conf['forceCacheUpdate']) $updateReason = 'forceCacheUpdate = 1';
  64. // if (!$conf['lastCacheUpdate']) $updateReason = '!lastCacheUpdate';
  65. // if (!$conf['schemaVersion']) $updateReason = '!schemaVersion';
  66. // else if ($conf['schemaVersion'] < $this->_version) $updateReason = 'schemaVersion < ' . $this->_version;
  67. // if ($conf['lastCacheUpdate'] && $conf['lastZasobyUpdate'] && $conf['lastCacheUpdate'] < $conf['lastZasobyUpdate']) $updateReason = 'lastZasobyUpdate';
  68. // if ($updateReason) {
  69. // DBG::simpleLog('schema', "SystemObject: update cache reason '{$updateReason}' '" . json_encode($conf) . "'");
  70. // call_user_func($updateCallback);
  71. // }
  72. // DB::getPDO()->execSql("
  73. // insert into CRM_CONFIG (CONF_KEY, CONF_VAL)
  74. // values('SystemObject__last_cache_update_date', NOW())
  75. // on duplicate key update CONF_VAL = NOW()
  76. // ");
  77. // DB::getPDO()->execSql("
  78. // insert into CRM_CONFIG (CONF_KEY, CONF_VAL)
  79. // values('SystemObject__schema_version', {$this->_version})
  80. // on duplicate key update CONF_VAL = {$this->_version}
  81. // ");
  82. // if ('1' == $conf['forceCacheUpdate']) DB::getPDO()->execSql(" update CRM_CONFIG set CONF_VAL = '0' where CONF_KEY = 'SystemObject__force_cache_update' ");
  83. // $_cacheUpdated = true;
  84. // }
  85. public function updateCache($idDatabase = null) {
  86. DBG::simpleLog('schema', "SystemObject::updateCache...");
  87. // DB::getPDO()->execSql(" drop table if exists `{$this->_rootTableName}` "); // TODO: DBG
  88. DB::getPDO()->execSql("
  89. create table if not exists `{$this->_rootTableName}` (
  90. `idZasob` int(11) DEFAULT NULL,
  91. `idDatabase` int(11) NOT NULL,
  92. `namespace` varchar(255) DEFAULT '',
  93. `_rootTableName` varchar(255) DEFAULT '',
  94. `_type` varchar(255) DEFAULT '',
  95. `hasStruct` tinyint(1) NOT NULL DEFAULT 0 COMMENT 'has structure',
  96. `isStructInstalled` tinyint(1) NOT NULL DEFAULT 0 COMMENT 'has installed structure',
  97. `isObjectActive` tinyint(1) NOT NULL DEFAULT 0 COMMENT 'object is active',
  98. `description` varchar(255) DEFAULT '',
  99. `primaryKey` varchar(255) DEFAULT '',
  100. UNIQUE KEY `idZasob` (idZasob),
  101. UNIQUE KEY `namespace` (namespace),
  102. KEY `isObjectActive` (isObjectActive)
  103. ) ENGINE=MyISAM DEFAULT CHARSET=latin2
  104. ");
  105. try {
  106. DB::getPDO()->execSql(" ALTER TABLE `{$this->_rootTableName}` ADD `primaryKey` VARCHAR(255) NOT NULL DEFAULT '' AFTER `description` ");
  107. } catch (Exception $e) {
  108. DBG::log($e);
  109. }
  110. DB::getPDO()->execSql(" update `{$this->_rootTableName}` set hasStruct = 0 ");
  111. $idDefDB = DB::getPDO()->getZasobId();
  112. $sourceStorage = SchemaFactory::loadDefaultObject('SystemSource');
  113. foreach ($sourceStorage->getItems([ 'f_hasConfig' => 1 ]) as $source) {
  114. if ('default_objects' == $source['nsPrefix']) {
  115. $clsFiles = array_map(function ($clsFile) {
  116. return substr($clsFile, strlen(APP_PATH_LIB . "/Schema/"), -1 * strlen('StorageAcl.php'));
  117. // return str_replace('/', '_', substr($clsFile, strlen(APP_PATH_LIB . "/Schema/"), -1 * strlen('StorageAcl.php')));
  118. }, array_merge(
  119. glob(APP_PATH_LIB . "/Schema/*StorageAcl.php", GLOB_NOSORT),
  120. glob(APP_PATH_LIB . "/Schema/*/*StorageAcl.php", GLOB_NOSORT)
  121. ));
  122. DBG::log($clsFiles, 'array', "DBG glob default_objects");
  123. foreach ($clsFiles as $clsName) {
  124. try {
  125. $acl = SchemaFactory::loadDefaultObject($clsName);
  126. $namespace = $acl->getNamespace();
  127. DB::getPDO()->insertOrUpdate($this->_rootTableName, [
  128. 'namespace' => $namespace,
  129. 'idDatabase' => $source['idZasob'],
  130. '_type' => "StorageAcl",
  131. '_rootTableName' => $acl->getRootTableName(),
  132. 'hasStruct' => 1
  133. ]);
  134. } catch (Exception $e) {
  135. UI::alert('danger', $e->getMessage());
  136. }
  137. }
  138. DB::getPDO()->execSql("
  139. insert into `{$this->_rootTableName}` (namespace, idZasob, idDatabase, description, hasStruct)
  140. select concat('{$source['nsPrefix']}/', t.`DESC`)
  141. , t.ID as idZasob
  142. , '{$source['idZasob']}' as idDatabase
  143. , t.`OPIS` as description
  144. , 1 as hasStruct
  145. from CRM_LISTA_ZASOBOW t
  146. where t.`TYPE` = 'TABELA'
  147. and t.A_STATUS in('NORMAL', 'WAITING')
  148. and t.PARENT_ID = {$source['idZasob']}
  149. and t.`DESC` not like '%/%'
  150. on duplicate key update idZasob = t.ID
  151. , hasStruct = 1
  152. ");
  153. }
  154. else {
  155. try {
  156. $dbName = DB::getPDO($source['idZasob'])->getDatabaseName();
  157. $dbType = DB::getPDO($source['idZasob'])->getType();
  158. if ('mysql' == $dbType) {
  159. UI::alert('warning', "TODO: { id: {$source['idZasob']}, nsPrefix: '{$source['nsPrefix']}', dbName: '{$dbName}', dbType: '{$dbType}'} ...");
  160. // TODO: if another DB split select and insert
  161. DB::getPDO()->execSql("
  162. insert into `{$this->_rootTableName}` (namespace, idDatabase, _rootTableName, _type, description)
  163. select concat('{$source['nsPrefix']}/', t.TABLE_NAME) as namespace
  164. , '{$source['idZasob']}' as idDatabase
  165. , t.TABLE_NAME as _rootTableName
  166. , 'TableAcl' as _type
  167. , t.TABLE_COMMENT as description
  168. from INFORMATION_SCHEMA.TABLES t
  169. where t.TABLE_SCHEMA = '{$dbName}'
  170. and t.TABLE_NAME not like '%#%'
  171. on duplicate key update _rootTableName = t.TABLE_NAME
  172. ");
  173. DB::getPDO()->execSql("
  174. insert into `{$this->_rootTableName}` (namespace, idZasob, idDatabase, description, hasStruct)
  175. select IF(t.`DESC` like 'default_db/%',
  176. t.`DESC`,
  177. concat('{$source['nsPrefix']}/', t.`DESC`)
  178. ) as namespace
  179. , t.ID as idZasob
  180. , '{$source['idZasob']}' as idDatabase
  181. , t.`OPIS` as description
  182. , 1 as hasStruct
  183. from CRM_LISTA_ZASOBOW t
  184. where t.`TYPE` = 'TABELA'
  185. and t.A_STATUS in('NORMAL', 'WAITING')
  186. and t.PARENT_ID = {$source['idZasob']}
  187. on duplicate key update idZasob = t.ID
  188. , hasStruct = 1
  189. ");
  190. // } else if ('pgsql' == $dbType) {// TODO: use pgsql @see Storage Pgsql getTables from information_schema
  191. } else {
  192. UI::alert('warning', "TODO: { id: {$source['idZasob']}, nsPrefix: '{$source['nsPrefix']}', dbName: '{$dbName}', dbType: <b>'{$dbType}'</b>} ...");
  193. }
  194. } catch (Exception $e) {
  195. UI::alert('danger', "Error source '{$source['idZasob']}' " . $e->getMessage());
  196. continue;
  197. }
  198. }
  199. }
  200. // Ant objects in: SE/schema/ant-object/
  201. foreach (glob(APP_PATH_SCHEMA . "/ant-object/*/*/build.xml", GLOB_NOSORT) as $buildXmlPath) {
  202. // SE/schema/ant-object/default_db.test_perms/TestPermsAnt/build.xml
  203. $file = substr($buildXmlPath, strlen(APP_PATH_SCHEMA . '/ant-object/'), -1 * strlen('/build.xml'));
  204. DBG::nicePrint($file, "file({$file})");
  205. list($partSource, $name) = explode('/', $file);
  206. list($sourceName, $rootTableName) = explode('.', $partSource);
  207. DBG::nicePrint([$sourceName, $rootTableName], "\$name='{$name}' - [\$lowerSource, \$rootTableName]");
  208. // $clsName = substr(basename($file), 0, -1 * strlen('StorageAcl.php'));
  209. try {
  210. // Lib::loadClass('AntAclBase');
  211. // $acl = AntAclBase::buildInstance(0, [
  212. // 'source' => $sourceName,
  213. // 'rootTableName' => $rootTableName,
  214. // 'name' => $name
  215. // ]);
  216. // $acl = SchemaFactory::loadDefaultObject($clsName);
  217. // $namespace = $acl->getNamespace();
  218. // $name = $acl->getName();
  219. $idDatabase = DB::getPDO($sourceName)->getZasobId();
  220. $namespace = "{$sourceName}/{$rootTableName}/{$name}";
  221. DB::getPDO()->insertOrUpdate($this->_rootTableName, [
  222. 'namespace' => $namespace,
  223. 'idDatabase' => $idDatabase,
  224. '_type' => "AntAcl",
  225. '_rootTableName' => $rootTableName,
  226. 'hasStruct' => 1
  227. ]);
  228. } catch (Exception $e) {
  229. UI::alert('danger', $e->getMessage());
  230. }
  231. }
  232. if ($activeProject = Config::getProjectPath()) {
  233. $baseAntObjectPath = "{$activeProject}/schema/ant-object";
  234. DBG::nicePrint($baseAntObjectPath, "\$baseAntObjectPath");
  235. foreach (glob("{$baseAntObjectPath}/*/*/build.xml", GLOB_NOSORT) as $file) {
  236. // SE/schema/ant-object/default_db.test_perms/TestPermsAnt/build.xml
  237. $file = substr($file, strlen("{$baseAntObjectPath}/"), -1 * strlen('/build.xml'));
  238. DBG::nicePrint($file, '$file');
  239. list($partSource, $name) = explode('/', $file);
  240. list($sourceName, $rootTableName) = explode('.', $partSource);
  241. DBG::nicePrint([$sourceName, $rootTableName, $name], '[$lowerSource, $rootTableName, $name]');
  242. // $clsName = substr(basename($file), 0, -1 * strlen('StorageAcl.php'));
  243. try {
  244. // Lib::loadClass('AntAclBase');
  245. // $acl = AntAclBase::buildInstance(0, [
  246. // 'source' => $sourceName,
  247. // 'rootTableName' => $rootTableName,
  248. // 'name' => $name
  249. // ]);
  250. // $acl = SchemaFactory::loadDefaultObject($clsName);
  251. // $namespace = $acl->getNamespace();
  252. // $name = $acl->getName();
  253. $idDatabase = DB::getPDO($sourceName)->getZasobId();
  254. $namespace = "{$sourceName}/{$rootTableName}/{$name}";
  255. DB::getPDO()->insertOrUpdate($this->_rootTableName, [
  256. 'namespace' => $namespace,
  257. 'idDatabase' => $idDatabase,
  258. '_type' => "AntAcl",
  259. '_rootTableName' => $rootTableName,
  260. 'hasStruct' => 1
  261. ]);
  262. } catch (Exception $e) {
  263. UI::alert('danger', $e->getMessage());
  264. }
  265. }
  266. }
  267. // Fix objects AntAcl which struct is not installed
  268. $listAntAclObjectsToFix = DB::getPDO()->fetchAll("
  269. select t.*
  270. from `CRM_#CACHE_ACL_OBJECT` t
  271. where t._type = 'AntAcl'
  272. and t.idZasob is not NULL
  273. and t.hasStruct = 1
  274. and t.isStructInstalled = 0
  275. ");
  276. if (!empty($listAntAclObjectsToFix)) {
  277. UI::alert('info', "Fix AntAcl objects which is not installed (total: ".count($listAntAclObjectsToFix).")");
  278. foreach ($listAntAclObjectsToFix as $antAclInfo) {
  279. $namespace = $antAclInfo['namespace'];
  280. DBG::nicePrint($antAclInfo, "\$antAclInfo ({$namespace})");
  281. $zasobyStruct = DB::getPDO()->fetchAll("
  282. select z.ID, z.`DESC`
  283. from `CRM_LISTA_ZASOBOW` z
  284. where z.PARENT_ID = :parent_id
  285. and z.`TYPE` = 'KOMORKA'
  286. and z.A_STATUS not in ('DELETED')
  287. ", [ ':parent_id' => $antAclInfo['idZasob'] ]);
  288. DBG::nicePrint($zasobyStruct, "\$zasobyStruct ({$namespace})");
  289. ob_start();
  290. {
  291. Lib::loadClass('Schema_SystemObjectFieldStorageAcl');
  292. $objFieldAcl = new Schema_SystemObjectFieldStorageAcl();
  293. $objFieldAcl->updateCache($namespace);
  294. $reinstallLog = ob_get_clean();
  295. }
  296. // DBG::nicePrint($reinstallLog, "\$reinstallLog ({$namespace})");
  297. $fieldCacheStruct = DB::getPDO()->fetchAll("
  298. select t.namespace, t.fieldNamespace
  299. from `CRM_#CACHE_ACL_OBJECT_FIELD` t
  300. where t.objectNamespace = :namespace
  301. and t.idZasob is NULL
  302. ", [ ':namespace' => $namespace ]);
  303. DBG::nicePrint($fieldCacheStruct, "\$fieldCacheStruct ({$namespace})");
  304. $fieldsToFix = [];
  305. foreach ($fieldCacheStruct as $cacheField) {
  306. $fieldName = $cacheField['fieldNamespace'];
  307. foreach ($zasobyStruct as $fieldZasob) {
  308. if ($fieldZasob['DESC'] === $fieldName) {
  309. $fieldsToFix[] = [
  310. 'idZasob' => $fieldZasob['ID'],
  311. 'namespace' => $cacheField['namespace'],
  312. ];
  313. }
  314. }
  315. }
  316. DBG::nicePrint($fieldsToFix, "\$fieldsToFix ({$namespace})");
  317. foreach ($fieldsToFix as $fixField) {
  318. $affected = SchemaFactory::loadDefaultObject('SystemObjectField')->updateItem([
  319. 'namespace' => $fixField['namespace'],
  320. 'idZasob' => $fixField['idZasob']
  321. ]);
  322. if (!$affected) UI::alert('warning', "field ({$fixField['namespace']}) update idZasob failed");
  323. }
  324. $affected = SchemaFactory::loadDefaultObject('SystemObject')->updateItem([
  325. 'namespace' => $namespace,
  326. 'isObjectActive' => 1
  327. ]);
  328. ($affected)
  329. ? UI::alert('success', "object ({$namespace}) activated")
  330. : UI::alert('warning', "object ({$namespace}) activation failed");
  331. }
  332. }
  333. // // foreach ... DB::getPDO($idDatabase)->fetchAll(select real _rootTableName)
  334. // foreach (Core_AclHelper::getCustomAclList() as $typeName) {
  335. // $ns = Core_AclHelper::parseTypeName($typeName);
  336. // $namespace = str_replace('__x3A__', '/', $ns['prefix']) . "/{$ns['name']}";
  337. // $sqlNs = DB::getPDO()->quote($namespace, PDO::PARAM_STR);
  338. // $idZasob = DB::getPDO()->fetchValue(" select ID from CRM_LISTA_ZASOBOW where `DESC` = {$sqlNs} and `TYPE` = 'TABELA' and A_STATUS in('WAITING', 'NORMAL') ");
  339. // if (!$idZasob) {
  340. // DBG::nicePrint($ns, "TODO: insert zasob PARENT_ID = ?");
  341. // }
  342. // }
  343. }
  344. public function _parseWhere($params = []) {
  345. $sqlWhere = [];
  346. DBG::log($params, 'array', "SystemObject::_parseWhere");
  347. if (!empty($params['#refFrom'])) {
  348. // '#refFrom' => [
  349. // 'namespace' => 'default_objects/SystemSource',
  350. // 'primaryKey' => $sourceItem['idZasob']
  351. // ]
  352. if (empty($params['#refFrom']['namespace'])) throw new Exception("Missing refFrom/namespace");
  353. if (empty($params['#refFrom']['primaryKey'])) throw new Exception("Missing refFrom/primaryKey");
  354. if ('default_objects/SystemSource' != $params['#refFrom']['namespace']) throw new Exception("Unsupported refFrom/namespace '{$params['#refFrom']['namespace']}'");
  355. $sqlWhere[] = "t.idDatabase = " . DB::getPDO()->quote($params['#refFrom']['primaryKey'], PDO::PARAM_INT);
  356. }
  357. {
  358. $filterParams = [];
  359. $xsdFields = $this->getXsdTypes();
  360. foreach ($params as $k => $v) {
  361. if ('f_' != substr($k, 0, 2)) continue;
  362. $fieldName = substr($k, 2);
  363. if (!array_key_exists($fieldName, $xsdFields)) {
  364. // TODO: check query by xpath or use different param prefix
  365. throw new Exception("Field '{$fieldName}' not found in '{$this->_namespace}'");
  366. }
  367. if ('p5:www_link' == $xsdFields[$fieldName]) {
  368. continue;
  369. }
  370. $filterParams[$fieldName] = $v;
  371. }
  372. }
  373. if (!empty($filterParams)) {
  374. DBG::log($filterParams, 'array', "SystemObject::_parseWhere TODO \$filterParams");
  375. foreach ($filterParams as $fieldName => $value) {
  376. if (is_array($value)) {
  377. DBG::log($value, 'array', "TODO SystemObject::_parseWhere array value for \$filterParams[{$fieldName}]");
  378. } else if (is_scalar($value)) {
  379. if ('=' == substr($value, 0, 1)) {
  380. $sqlWhere[] = "t.{$fieldName} = " . DB::getPDO()->quote(substr($value, 1), PDO::PARAM_STR);
  381. } else {
  382. $sqlWhere[] = "t.{$fieldName} like " . DB::getPDO()->quote("%{$value}%", PDO::PARAM_STR);
  383. }
  384. } else {
  385. DBG::log($value, 'array', "BUG SystemObject::_parseWhere unknown type for \$filterParams[{$fieldName}]");
  386. }
  387. }
  388. }
  389. return (!empty($sqlWhere)) ? "where " . implode(" and ", $sqlWhere) : '';
  390. }
  391. public function getTotal($params = []) {
  392. $sqlWhere = $this->_parseWhere($params);
  393. return DB::getPDO()->fetchValue("
  394. select count(1) as cnt
  395. from `{$this->_rootTableName}` t
  396. {$sqlWhere}
  397. ");
  398. }
  399. public function clearGetItemCache($pk = null) {
  400. if (!$this->_cache) return;
  401. if (!$pk) $this->_cache = [];
  402. else if (array_key_exists($pk, $this->_cache)) unset($this->_cache[$pk]);
  403. }
  404. public function getItem($pk, $params = []) {
  405. // TODO: ceche query for: $pk = 'default_db/CRM_PROCES/PROCES', $params = [ 'propertyName' => "*,field" ]
  406. if (!$this->_cache) $this->_cache = [];
  407. if (1 === count($params) && "*,field" === V::get('propertyName', '', $params)) {
  408. if (array_key_exists($pk, $this->_cache)) return $this->_cache[$pk];
  409. $this->_cache[$pk] = $this->_fetchItem($pk, $params);
  410. } else {
  411. return $this->_fetchItem($pk, $params);
  412. }
  413. return $this->_cache[$pk];
  414. }
  415. public function _fetchItem($pk, $params = []) {
  416. if (!$pk) throw new Exception("Missing primary key '{$this->_namespace}'");
  417. $pkField = $this->getSqlPrimaryKeyField();
  418. if (!$pkField) throw new Exception("Missing primary key field defined in '{$this->_namespace}'");
  419. $sqlPk = DB::getPDO()->quote($pk, PDO::PARAM_STR);
  420. $item = DB::getPDO()->fetchFirst("
  421. select t.*
  422. from `{$this->_rootTableName}` t
  423. where t.`{$pkField}` = {$sqlPk}
  424. ");
  425. if (!$item) throw new Exception("Item '{$pk}' not exists - type '{$this->_namespace}'");
  426. return $this->buildFeatureFromSqlRow($item, $params);
  427. }
  428. public function getItems($params = []) {
  429. $sqlWhere = $this->_parseWhere($params);
  430. $currSortCol = V::get('order_by', 'idZasob', $params);
  431. $currSortFlip = strtolower(V::get('order_dir', 'desc', $params));
  432. // TODO: validate $currSortCol is in field list
  433. // TODO: validate $currSortFlip ('asc' or 'desc')
  434. $xsdFields = $this->getXsdTypes();
  435. if (!array_key_exists($currSortCol, $xsdFields)) throw new Exception("Field '{$currSortCol}' not found in '{$this->_namespace}'");
  436. if (!in_array($currSortFlip, ['asc', 'desc'])) throw new Exception("Sort dir not allowed");
  437. $sqlOrderBy = "order by t.`{$currSortCol}` {$currSortFlip}";
  438. $limit = V::get('limit', 0, $params, 'int');
  439. $limit = ($limit < 0) ? 0 : $limit;
  440. $offset = V::get('limitstart', 0, $params, 'int');
  441. $offset = ($offset < 0) ? 0 : $offset;
  442. $sqlLimit = ($limit > 0)
  443. ? "limit {$limit} offset {$offset}"
  444. : '';
  445. Lib::loadClass('AclQueryItems');
  446. $query = new AclQueryItems($this);
  447. $query->setParams($params);
  448. $query->setSource('default_db');
  449. $query->setRawSql("
  450. select t.*
  451. from `{$this->_rootTableName}` t
  452. {$sqlWhere}
  453. {$sqlOrderBy}
  454. {$sqlLimit}
  455. ");
  456. return $query->fetchAll();
  457. }
  458. public function buildFeatureFromSqlRow($item, $params = []) {
  459. DBG::log($params, 'array', "buildFeatureFromSqlRow... '{$item['namespace']}'");
  460. $exNs = explode('/', $item['namespace']);
  461. $item['name'] = array_pop($exNs);
  462. $item['nsPrefix'] = implode('__x3A__', $exNs);
  463. $item['typeName'] = implode('__x3A__', $exNs) . ':' . $item['name'];
  464. $item['reinstallLink'] = Router::getRoute('Storage_AclReinstall')->getLink('', [ 'namespace' => $item['namespace'] ]);
  465. if (!empty($params['propertyName'])) {
  466. if (is_string($params['propertyName'])) $params['propertyName'] = explode(',', $params['propertyName']);
  467. if (!is_array($params['propertyName'])) throw new Exception("Wrong param propertyName - expected array or string");
  468. foreach ($params['propertyName'] as $fetchField) {
  469. if ('*' == $fetchField) continue;
  470. if ('field' == $fetchField) {
  471. $item['field'] = SchemaFactory::loadDefaultObject('SystemObjectField')->getItems([
  472. '__backRef' => [
  473. 'namespace' => 'default_objects/SystemObject',
  474. 'primaryKey' => $item['namespace']
  475. ]
  476. ]);
  477. }
  478. }
  479. }
  480. return $item;
  481. }
  482. public function updateItem($itemPatch) { // @required [ 'namespace' => ... ] (primaryKey)
  483. $pkField = $this->getPrimaryKeyField();
  484. $pk = V::get($pkField, null, $itemPatch);
  485. if (null === $pk) throw new Exception("BUG missing primary key field for '{$this->_namespace}' updateItem");
  486. $this->clearGetItemCache($pk);
  487. DBG::log(['updateItem $itemPatch', $itemPatch]);
  488. unset($itemPatch[$pkField]);
  489. if (empty($itemPatch)) return 0;
  490. foreach ($itemPatch as $fieldName => $value) {
  491. if ('isStructInstalled' == $fieldName) continue;
  492. if ('isObjectActive' == $fieldName) continue;
  493. if ('primaryKey' == $fieldName) continue;
  494. throw new Exception("Update field '{$fieldName}' not allowed for '{$this->_namespace}'");
  495. }
  496. return DB::getPDO()->update($this->_rootTableName, $pkField, $pk, $itemPatch);
  497. }
  498. }