SystemObjectStorageAcl.php 22 KB

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