SystemObjectStorageAcl.php 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515
  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. UNIQUE KEY `idZasob` (idZasob),
  100. UNIQUE KEY `namespace` (namespace),
  101. KEY `isObjectActive` (isObjectActive)
  102. ) ENGINE=MyISAM DEFAULT CHARSET=latin2
  103. ");
  104. DB::getPDO()->execSql(" update `{$this->_rootTableName}` set hasStruct = 0 ");
  105. $idDefDB = DB::getPDO()->getZasobId();
  106. $sourceStorage = SchemaFactory::loadDefaultObject('SystemSource');
  107. foreach ($sourceStorage->getItems([ 'f_hasConfig' => 1 ]) as $source) {
  108. if ('default_objects' == $source['nsPrefix']) {
  109. $clsFiles = array_map(function ($clsFile) {
  110. return substr($clsFile, strlen(APP_PATH_LIB . "/Schema/"), -1 * strlen('StorageAcl.php'));
  111. // return str_replace('/', '_', substr($clsFile, strlen(APP_PATH_LIB . "/Schema/"), -1 * strlen('StorageAcl.php')));
  112. }, array_merge(
  113. glob(APP_PATH_LIB . "/Schema/*StorageAcl.php", GLOB_NOSORT),
  114. glob(APP_PATH_LIB . "/Schema/*/*StorageAcl.php", GLOB_NOSORT)
  115. ));
  116. DBG::log($clsFiles, 'array', "DBG glob default_objects");
  117. foreach ($clsFiles as $clsName) {
  118. try {
  119. $acl = SchemaFactory::loadDefaultObject($clsName);
  120. $namespace = $acl->getNamespace();
  121. DB::getPDO()->insertOrUpdate($this->_rootTableName, [
  122. 'namespace' => $namespace,
  123. 'idDatabase' => $source['idZasob'],
  124. '_type' => "StorageAcl",
  125. '_rootTableName' => $acl->getRootTableName(),
  126. 'hasStruct' => 1
  127. ]);
  128. } catch (Exception $e) {
  129. UI::alert('danger', $e->getMessage());
  130. }
  131. }
  132. DB::getPDO()->execSql("
  133. insert into `{$this->_rootTableName}` (namespace, idZasob, idDatabase, description, hasStruct)
  134. select concat('{$source['nsPrefix']}/', t.`DESC`)
  135. , t.ID as idZasob
  136. , '{$source['idZasob']}' as idDatabase
  137. , t.`OPIS` as description
  138. , 1 as hasStruct
  139. from CRM_LISTA_ZASOBOW t
  140. where t.`TYPE` = 'TABELA'
  141. and t.A_STATUS in('NORMAL', 'WAITING')
  142. and t.PARENT_ID = {$source['idZasob']}
  143. and t.`DESC` not like '%/%'
  144. on duplicate key update idZasob = t.ID
  145. , hasStruct = 1
  146. ");
  147. }
  148. else {
  149. try {
  150. $dbName = DB::getPDO($source['idZasob'])->getDatabaseName();
  151. $dbType = DB::getPDO($source['idZasob'])->getType();
  152. if ('mysql' == $dbType) {
  153. UI::alert('warning', "TODO: { id: {$source['idZasob']}, nsPrefix: '{$source['nsPrefix']}', dbName: '{$dbName}', dbType: '{$dbType}'} ...");
  154. // TODO: if another DB split select and insert
  155. DB::getPDO()->execSql("
  156. insert into `{$this->_rootTableName}` (namespace, idDatabase, _rootTableName, _type, description)
  157. select concat('{$source['nsPrefix']}/', t.TABLE_NAME) as namespace
  158. , '{$source['idZasob']}' as idDatabase
  159. , t.TABLE_NAME as _rootTableName
  160. , 'TableAcl' as _type
  161. , t.TABLE_COMMENT as description
  162. from INFORMATION_SCHEMA.TABLES t
  163. where t.TABLE_SCHEMA = '{$dbName}'
  164. on duplicate key update _rootTableName = t.TABLE_NAME
  165. ");
  166. DB::getPDO()->execSql("
  167. insert into `{$this->_rootTableName}` (namespace, idZasob, idDatabase, description, hasStruct)
  168. select IF(t.`DESC` like 'default_db/%',
  169. t.`DESC`,
  170. concat('{$source['nsPrefix']}/', t.`DESC`)
  171. ) as namespace
  172. , t.ID as idZasob
  173. , '{$source['idZasob']}' as idDatabase
  174. , t.`OPIS` as description
  175. , 1 as hasStruct
  176. from CRM_LISTA_ZASOBOW t
  177. where t.`TYPE` = 'TABELA'
  178. and t.A_STATUS in('NORMAL', 'WAITING')
  179. and t.PARENT_ID = {$source['idZasob']}
  180. on duplicate key update idZasob = t.ID
  181. , hasStruct = 1
  182. ");
  183. // } else if ('pgsql' == $dbType) {// TODO: use pgsql @see Storage Pgsql getTables from information_schema
  184. } else {
  185. UI::alert('warning', "TODO: { id: {$source['idZasob']}, nsPrefix: '{$source['nsPrefix']}', dbName: '{$dbName}', dbType: <b>'{$dbType}'</b>} ...");
  186. }
  187. } catch (Exception $e) {
  188. UI::alert('danger', "Error source '{$source['idZasob']}' " . $e->getMessage());
  189. continue;
  190. }
  191. }
  192. }
  193. // Ant objects in: SE/schema/ant-object/
  194. foreach (glob(APP_PATH_SCHEMA . "/ant-object/*/*/build.xml", GLOB_NOSORT) as $file) {
  195. // SE/schema/ant-object/default_db.test_perms/TestPermsAnt/build.xml
  196. $file = substr($file, strlen(APP_PATH_SCHEMA . '/ant-object/'), -1 * strlen('/build.xml'));
  197. DBG::nicePrint($file, '$file');
  198. list($partSource, $name) = explode('/', $file);
  199. list($sourceName, $rootTableName) = explode('.', $partSource);
  200. DBG::nicePrint([$sourceName, $rootTableName, $name], '[$lowerSource, $rootTableName, $name]');
  201. // $clsName = substr(basename($file), 0, -1 * strlen('StorageAcl.php'));
  202. try {
  203. Lib::loadClass('AntAclBase');
  204. $acl = AntAclBase::buildInstance(0, [
  205. 'source' => $sourceName,
  206. 'rootTableName' => $rootTableName,
  207. 'name' => $name
  208. ]);
  209. // $acl = SchemaFactory::loadDefaultObject($clsName);
  210. // $namespace = $acl->getNamespace();
  211. // $name = $acl->getName();
  212. $idDatabase = DB::getPDO($sourceName)->getZasobId();
  213. $namespace = "{$sourceName}/{$rootTableName}/{$name}";
  214. DB::getPDO()->insertOrUpdate($this->_rootTableName, [
  215. 'namespace' => $namespace,
  216. 'idDatabase' => $idDatabase,
  217. '_type' => "AntAcl",
  218. '_rootTableName' => $rootTableName,
  219. 'hasStruct' => 1
  220. ]);
  221. } catch (Exception $e) {
  222. UI::alert('danger', $e->getMessage());
  223. }
  224. }
  225. if ($activeProject = Config::getProjectPath()) {
  226. $baseAntObjectPath = "{$activeProject}/schema/ant-object";
  227. DBG::nicePrint($baseAntObjectPath, "\$baseAntObjectPath");
  228. foreach (glob("{$baseAntObjectPath}/*/*/build.xml", GLOB_NOSORT) as $file) {
  229. // SE/schema/ant-object/default_db.test_perms/TestPermsAnt/build.xml
  230. $file = substr($file, strlen("{$baseAntObjectPath}/"), -1 * strlen('/build.xml'));
  231. DBG::nicePrint($file, '$file');
  232. list($partSource, $name) = explode('/', $file);
  233. list($sourceName, $rootTableName) = explode('.', $partSource);
  234. DBG::nicePrint([$sourceName, $rootTableName, $name], '[$lowerSource, $rootTableName, $name]');
  235. // $clsName = substr(basename($file), 0, -1 * strlen('StorageAcl.php'));
  236. try {
  237. Lib::loadClass('AntAclBase');
  238. $acl = AntAclBase::buildInstance(0, [
  239. 'source' => $sourceName,
  240. 'rootTableName' => $rootTableName,
  241. 'name' => $name
  242. ]);
  243. // $acl = SchemaFactory::loadDefaultObject($clsName);
  244. // $namespace = $acl->getNamespace();
  245. // $name = $acl->getName();
  246. $idDatabase = DB::getPDO($sourceName)->getZasobId();
  247. $namespace = "{$sourceName}/{$rootTableName}/{$name}";
  248. DB::getPDO()->insertOrUpdate($this->_rootTableName, [
  249. 'namespace' => $namespace,
  250. 'idDatabase' => $idDatabase,
  251. '_type' => "AntAcl",
  252. '_rootTableName' => $rootTableName,
  253. 'hasStruct' => 1
  254. ]);
  255. } catch (Exception $e) {
  256. UI::alert('danger', $e->getMessage());
  257. }
  258. }
  259. }
  260. // Fix objects AntAcl which struct is not installed
  261. $listAntAclObjectsToFix = DB::getPDO()->fetchAll("
  262. select t.*
  263. from `CRM_#CACHE_ACL_OBJECT` t
  264. where t._type = 'AntAcl'
  265. and t.idZasob is not NULL
  266. and t.hasStruct = 1
  267. and t.isStructInstalled = 0
  268. ");
  269. if (!empty($listAntAclObjectsToFix)) {
  270. UI::alert('info', "Fix AntAcl objects which is not installed (total: ".count($listAntAclObjectsToFix).")");
  271. foreach ($listAntAclObjectsToFix as $antAclInfo) {
  272. $namespace = $antAclInfo['namespace'];
  273. DBG::nicePrint($antAclInfo, "\$antAclInfo ({$namespace})");
  274. $zasobyStruct = DB::getPDO()->fetchAll("
  275. select z.ID, z.`DESC`
  276. from `CRM_LISTA_ZASOBOW` z
  277. where z.PARENT_ID = :parent_id
  278. and z.`TYPE` = 'KOMORKA'
  279. ", [ ':parent_id' => $antAclInfo['idZasob'] ]);
  280. DBG::nicePrint($zasobyStruct, "\$zasobyStruct ({$namespace})");
  281. ob_start();
  282. Lib::loadClass('Schema_SystemObjectFieldStorageAcl');
  283. $objFieldAcl = new Schema_SystemObjectFieldStorageAcl();
  284. $objFieldAcl->updateCache($namespace);
  285. $reinstallLog = ob_get_clean();
  286. // DBG::nicePrint($reinstallLog, "\$reinstallLog ({$namespace})");
  287. $fieldCacheStruct = DB::getPDO()->fetchAll("
  288. select t.namespace, t.fieldNamespace
  289. from `CRM_#CACHE_ACL_OBJECT_FIELD` t
  290. where t.objectNamespace = :namespace
  291. and t.idZasob is NULL
  292. ", [ ':namespace' => $namespace ]);
  293. DBG::nicePrint($fieldCacheStruct, "\$fieldCacheStruct ({$namespace})");
  294. $fieldsToFix = [];
  295. foreach ($fieldCacheStruct as $cacheField) {
  296. $fieldName = $cacheField['fieldNamespace'];
  297. foreach ($zasobyStruct as $fieldZasob) {
  298. if ($fieldZasob['DESC'] === $fieldName) {
  299. $fieldsToFix[] = [
  300. 'idZasob' => $fieldZasob['ID'],
  301. 'namespace' => $cacheField['namespace'],
  302. ];
  303. }
  304. }
  305. }
  306. DBG::nicePrint($fieldsToFix, "\$fieldsToFix ({$namespace})");
  307. foreach ($fieldsToFix as $fixField) {
  308. $affected = SchemaFactory::loadDefaultObject('SystemObjectField')->updateItem([
  309. 'namespace' => $fixField['namespace'],
  310. 'idZasob' => $fixField['idZasob']
  311. ]);
  312. if (!$affected) UI::alert('warning', "field ({$fixField['namespace']}) update idZasob failed");
  313. }
  314. $affected = SchemaFactory::loadDefaultObject('SystemObject')->updateItem([
  315. 'namespace' => $namespace,
  316. 'isObjectActive' => 1
  317. ]);
  318. ($affected)
  319. ? UI::alert('success', "object ({$namespace}) activated")
  320. : UI::alert('warning', "object ({$namespace}) activation failed");
  321. }
  322. }
  323. // // foreach ... DB::getPDO($idDatabase)->fetchAll(select real _rootTableName)
  324. // foreach (Core_AclHelper::getCustomAclList() as $typeName) {
  325. // $ns = Core_AclHelper::parseTypeName($typeName);
  326. // $namespace = str_replace('__x3A__', '/', $ns['prefix']) . "/{$ns['name']}";
  327. // $sqlNs = DB::getPDO()->quote($namespace, PDO::PARAM_STR);
  328. // $idZasob = DB::getPDO()->fetchValue(" select ID from CRM_LISTA_ZASOBOW where `DESC` = {$sqlNs} and `TYPE` = 'TABELA' and A_STATUS in('WAITING', 'NORMAL') ");
  329. // if (!$idZasob) {
  330. // DBG::nicePrint($ns, "TODO: insert zasob PARENT_ID = ?");
  331. // }
  332. // }
  333. }
  334. public function _parseWhere($params = []) {
  335. $sqlWhere = [];
  336. DBG::log($params, 'array', "SystemObject::_parseWhere");
  337. if (!empty($params['#refFrom'])) {
  338. // '#refFrom' => [
  339. // 'namespace' => 'default_objects/SystemSource',
  340. // 'primaryKey' => $sourceItem['idZasob']
  341. // ]
  342. if (empty($params['#refFrom']['namespace'])) throw new Exception("Missing refFrom/namespace");
  343. if (empty($params['#refFrom']['primaryKey'])) throw new Exception("Missing refFrom/primaryKey");
  344. if ('default_objects/SystemSource' != $params['#refFrom']['namespace']) throw new Exception("Unsupported refFrom/namespace '{$params['#refFrom']['namespace']}'");
  345. $sqlWhere[] = "t.idDatabase = " . DB::getPDO()->quote($params['#refFrom']['primaryKey'], PDO::PARAM_INT);
  346. }
  347. {
  348. $filterParams = [];
  349. $xsdFields = $this->getXsdTypes();
  350. foreach ($params as $k => $v) {
  351. if ('f_' != substr($k, 0, 2)) continue;
  352. $fieldName = substr($k, 2);
  353. if (!array_key_exists($fieldName, $xsdFields)) {
  354. // TODO: check query by xpath or use different param prefix
  355. throw new Exception("Field '{$fieldName}' not found in '{$this->_namespace}'");
  356. }
  357. if ('p5:www_link' == $xsdFields[$fieldName]) {
  358. continue;
  359. }
  360. $filterParams[$fieldName] = $v;
  361. }
  362. }
  363. if (!empty($filterParams)) {
  364. DBG::log($filterParams, 'array', "SystemObject::_parseWhere TODO \$filterParams");
  365. foreach ($filterParams as $fieldName => $value) {
  366. if (is_array($value)) {
  367. DBG::log($value, 'array', "TODO SystemObject::_parseWhere array value for \$filterParams[{$fieldName}]");
  368. } else if (is_scalar($value)) {
  369. if ('=' == substr($value, 0, 1)) {
  370. $sqlWhere[] = "t.{$fieldName} = " . DB::getPDO()->quote(substr($value, 1), PDO::PARAM_STR);
  371. } else {
  372. $sqlWhere[] = "t.{$fieldName} like " . DB::getPDO()->quote("%{$value}%", PDO::PARAM_STR);
  373. }
  374. } else {
  375. DBG::log($value, 'array', "BUG SystemObject::_parseWhere unknown type for \$filterParams[{$fieldName}]");
  376. }
  377. }
  378. }
  379. return (!empty($sqlWhere)) ? "where " . implode(" and ", $sqlWhere) : '';
  380. }
  381. public function getTotal($params = []) {
  382. $sqlWhere = $this->_parseWhere($params);
  383. return DB::getPDO()->fetchValue("
  384. select count(1) as cnt
  385. from `{$this->_rootTableName}` t
  386. {$sqlWhere}
  387. ");
  388. }
  389. public function clearGetItemCache($pk = null) {
  390. if (!$this->_cache) return;
  391. if (!$pk) $this->_cache = [];
  392. else if (array_key_exists($pk, $this->_cache)) unset($this->_cache[$pk]);
  393. }
  394. public function getItem($pk, $params = []) {
  395. // TODO: ceche query for: $pk = 'default_db/CRM_PROCES/PROCES', $params = [ 'propertyName' => "*,field" ]
  396. if (!$this->_cache) $this->_cache = [];
  397. if (1 === count($params) && "*,field" === V::get('propertyName', '', $params)) {
  398. if (array_key_exists($pk, $this->_cache)) return $this->_cache[$pk];
  399. $this->_cache[$pk] = $this->_fetchItem($pk, $params);
  400. } else {
  401. return $this->_fetchItem($pk, $params);
  402. }
  403. return $this->_cache[$pk];
  404. }
  405. public function _fetchItem($pk, $params = []) {
  406. if (!$pk) throw new Exception("Missing primary key '{$this->_namespace}'");
  407. $pkField = $this->getSqlPrimaryKeyField();
  408. if (!$pkField) throw new Exception("Missing primary key field defined in '{$this->_namespace}'");
  409. $sqlPk = DB::getPDO()->quote($pk, PDO::PARAM_STR);
  410. $item = DB::getPDO()->fetchFirst("
  411. select t.*
  412. from `{$this->_rootTableName}` t
  413. where t.`{$pkField}` = {$sqlPk}
  414. ");
  415. if (!$item) throw new Exception("Item '{$pk}' not exists - type '{$this->_namespace}'");
  416. return $this->buildFeatureFromSqlRow($item, $params);
  417. }
  418. public function getItems($params = []) {
  419. $sqlWhere = $this->_parseWhere($params);
  420. $currSortCol = V::get('order_by', 'idZasob', $params);
  421. $currSortFlip = strtolower(V::get('order_dir', 'desc', $params));
  422. // TODO: validate $currSortCol is in field list
  423. // TODO: validate $currSortFlip ('asc' or 'desc')
  424. $xsdFields = $this->getXsdTypes();
  425. if (!array_key_exists($currSortCol, $xsdFields)) throw new Exception("Field '{$currSortCol}' not found in '{$this->_namespace}'");
  426. if (!in_array($currSortFlip, ['asc', 'desc'])) throw new Exception("Sort dir not allowed");
  427. $sqlOrderBy = "order by t.`{$currSortCol}` {$currSortFlip}";
  428. $limit = V::get('limit', 0, $params, 'int');
  429. $limit = ($limit < 0) ? 0 : $limit;
  430. $offset = V::get('limitstart', 0, $params, 'int');
  431. $offset = ($offset < 0) ? 0 : $offset;
  432. $sqlLimit = ($limit > 0)
  433. ? "limit {$limit} offset {$offset}"
  434. : '';
  435. Lib::loadClass('AclQueryItems');
  436. $query = new AclQueryItems($this);
  437. $query->setParams($params);
  438. $query->setSource('default_db');
  439. $query->setRawSql("
  440. select t.*
  441. from `{$this->_rootTableName}` t
  442. {$sqlWhere}
  443. {$sqlOrderBy}
  444. {$sqlLimit}
  445. ");
  446. return $query->fetchAll();
  447. }
  448. public function buildFeatureFromSqlRow($item, $params = []) {
  449. DBG::log($params, 'array', "buildFeatureFromSqlRow... '{$item['namespace']}'");
  450. $exNs = explode('/', $item['namespace']);
  451. $item['name'] = array_pop($exNs);
  452. $item['nsPrefix'] = implode('__x3A__', $exNs);
  453. $item['typeName'] = implode('__x3A__', $exNs) . ':' . $item['name'];
  454. $item['reinstallLink'] = Router::getRoute('Storage_AclReinstall')->getLink('', [ 'namespace' => $item['namespace'] ]);
  455. if (!empty($params['propertyName'])) {
  456. if (is_string($params['propertyName'])) $params['propertyName'] = explode(',', $params['propertyName']);
  457. if (!is_array($params['propertyName'])) throw new Exception("Wrong param propertyName - expected array or string");
  458. foreach ($params['propertyName'] as $fetchField) {
  459. if ('*' == $fetchField) continue;
  460. if ('field' == $fetchField) {
  461. $item['field'] = SchemaFactory::loadDefaultObject('SystemObjectField')->getItems([
  462. '__backRef' => [
  463. 'namespace' => 'default_objects/SystemObject',
  464. 'primaryKey' => $item['namespace']
  465. ]
  466. ]);
  467. }
  468. }
  469. }
  470. return $item;
  471. }
  472. public function updateItem($itemPatch) { // @required [ 'namespace' => ... ] (primaryKey)
  473. $pkField = $this->getPrimaryKeyField();
  474. $pk = V::get($pkField, null, $itemPatch);
  475. if (null === $pk) throw new Exception("BUG missing primary key field for '{$this->_namespace}' updateItem");
  476. $this->clearGetItemCache($pk);
  477. DBG::log(['updateItem $itemPatch', $itemPatch]);
  478. unset($itemPatch[$pkField]);
  479. if (empty($itemPatch)) return 0;
  480. foreach ($itemPatch as $fieldName => $value) {
  481. if ('isStructInstalled' == $fieldName) continue;
  482. if ('isObjectActive' == $fieldName) continue;
  483. throw new Exception("Update field '{$fieldName}' not allowed for '{$this->_namespace}'");
  484. }
  485. return DB::getPDO()->update($this->_rootTableName, $pkField, $pk, $itemPatch);
  486. }
  487. }