SystemObjectStorageAcl.php 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479
  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. // Fix objects AntAcl which struct is not installed
  226. $listAntAclObjectsToFix = DB::getPDO()->fetchAll("
  227. select t.*
  228. from `CRM_#CACHE_ACL_OBJECT` t
  229. where t._type = 'AntAcl'
  230. and t.idZasob is not NULL
  231. and t.hasStruct = 1
  232. and t.isStructInstalled = 0
  233. ");
  234. if (!empty($listAntAclObjectsToFix)) {
  235. UI::alert('info', "Fix AntAcl objects which is not installed (total: ".count($listAntAclObjectsToFix).")");
  236. foreach ($listAntAclObjectsToFix as $antAclInfo) {
  237. $namespace = $antAclInfo['namespace'];
  238. DBG::nicePrint($antAclInfo, "\$antAclInfo ({$namespace})");
  239. $zasobyStruct = DB::getPDO()->fetchAll("
  240. select z.ID, z.`DESC`
  241. from `CRM_LISTA_ZASOBOW` z
  242. where z.PARENT_ID = :parent_id
  243. and z.`TYPE` = 'KOMORKA'
  244. ", [ ':parent_id' => $antAclInfo['idZasob'] ]);
  245. DBG::nicePrint($zasobyStruct, "\$zasobyStruct ({$namespace})");
  246. ob_start();
  247. Lib::loadClass('Schema_SystemObjectFieldStorageAcl');
  248. $objFieldAcl = new Schema_SystemObjectFieldStorageAcl();
  249. $objFieldAcl->updateCache($namespace);
  250. $reinstallLog = ob_get_clean();
  251. // DBG::nicePrint($reinstallLog, "\$reinstallLog ({$namespace})");
  252. $fieldCacheStruct = DB::getPDO()->fetchAll("
  253. select t.namespace, t.fieldNamespace
  254. from `CRM_#CACHE_ACL_OBJECT_FIELD` t
  255. where t.objectNamespace = :namespace
  256. and t.idZasob is NULL
  257. ", [ ':namespace' => $namespace ]);
  258. DBG::nicePrint($fieldCacheStruct, "\$fieldCacheStruct ({$namespace})");
  259. $fieldsToFix = [];
  260. foreach ($fieldCacheStruct as $cacheField) {
  261. $fieldName = $cacheField['fieldNamespace'];
  262. foreach ($zasobyStruct as $fieldZasob) {
  263. if ($fieldZasob['DESC'] === $fieldName) {
  264. $fieldsToFix[] = [
  265. 'idZasob' => $fieldZasob['ID'],
  266. 'namespace' => $cacheField['namespace'],
  267. ];
  268. }
  269. }
  270. }
  271. DBG::nicePrint($fieldsToFix, "\$fieldsToFix ({$namespace})");
  272. foreach ($fieldsToFix as $fixField) {
  273. $affected = SchemaFactory::loadDefaultObject('SystemObjectField')->updateItem([
  274. 'namespace' => $fixField['namespace'],
  275. 'idZasob' => $fixField['idZasob']
  276. ]);
  277. if (!$affected) UI::alert('warning', "field ({$fixField['namespace']}) update idZasob failed");
  278. }
  279. $affected = SchemaFactory::loadDefaultObject('SystemObject')->updateItem([
  280. 'namespace' => $namespace,
  281. 'isObjectActive' => 1
  282. ]);
  283. ($affected)
  284. ? UI::alert('success', "object ({$namespace}) activated")
  285. : UI::alert('warning', "object ({$namespace}) activation failed");
  286. }
  287. }
  288. // // foreach ... DB::getPDO($idDatabase)->fetchAll(select real _rootTableName)
  289. // foreach (Core_AclHelper::getCustomAclList() as $typeName) {
  290. // $ns = Core_AclHelper::parseTypeName($typeName);
  291. // $namespace = str_replace('__x3A__', '/', $ns['prefix']) . "/{$ns['name']}";
  292. // $sqlNs = DB::getPDO()->quote($namespace, PDO::PARAM_STR);
  293. // $idZasob = DB::getPDO()->fetchValue(" select ID from CRM_LISTA_ZASOBOW where `DESC` = {$sqlNs} and `TYPE` = 'TABELA' and A_STATUS in('WAITING', 'NORMAL') ");
  294. // if (!$idZasob) {
  295. // DBG::nicePrint($ns, "TODO: insert zasob PARENT_ID = ?");
  296. // }
  297. // }
  298. }
  299. public function _parseWhere($params = []) {
  300. $sqlWhere = [];
  301. DBG::log($params, 'array', "SystemObject::_parseWhere");
  302. if (!empty($params['#refFrom'])) {
  303. // '#refFrom' => [
  304. // 'namespace' => 'default_objects/SystemSource',
  305. // 'primaryKey' => $sourceItem['idZasob']
  306. // ]
  307. if (empty($params['#refFrom']['namespace'])) throw new Exception("Missing refFrom/namespace");
  308. if (empty($params['#refFrom']['primaryKey'])) throw new Exception("Missing refFrom/primaryKey");
  309. if ('default_objects/SystemSource' != $params['#refFrom']['namespace']) throw new Exception("Unsupported refFrom/namespace '{$params['#refFrom']['namespace']}'");
  310. $sqlWhere[] = "t.idDatabase = " . DB::getPDO()->quote($params['#refFrom']['primaryKey'], PDO::PARAM_INT);
  311. }
  312. {
  313. $filterParams = [];
  314. $xsdFields = $this->getXsdTypes();
  315. foreach ($params as $k => $v) {
  316. if ('f_' != substr($k, 0, 2)) continue;
  317. $fieldName = substr($k, 2);
  318. if (!array_key_exists($fieldName, $xsdFields)) {
  319. // TODO: check query by xpath or use different param prefix
  320. throw new Exception("Field '{$fieldName}' not found in '{$this->_namespace}'");
  321. }
  322. if ('p5:www_link' == $xsdFields[$fieldName]) {
  323. continue;
  324. }
  325. $filterParams[$fieldName] = $v;
  326. }
  327. }
  328. if (!empty($filterParams)) {
  329. DBG::log($filterParams, 'array', "SystemObject::_parseWhere TODO \$filterParams");
  330. foreach ($filterParams as $fieldName => $value) {
  331. if (is_array($value)) {
  332. DBG::log($value, 'array', "TODO SystemObject::_parseWhere array value for \$filterParams[{$fieldName}]");
  333. } else if (is_scalar($value)) {
  334. if ('=' == substr($value, 0, 1)) {
  335. $sqlWhere[] = "t.{$fieldName} = " . DB::getPDO()->quote(substr($value, 1), PDO::PARAM_STR);
  336. } else {
  337. $sqlWhere[] = "t.{$fieldName} like " . DB::getPDO()->quote("%{$value}%", PDO::PARAM_STR);
  338. }
  339. } else {
  340. DBG::log($value, 'array', "BUG SystemObject::_parseWhere unknown type for \$filterParams[{$fieldName}]");
  341. }
  342. }
  343. }
  344. return (!empty($sqlWhere)) ? "where " . implode(" and ", $sqlWhere) : '';
  345. }
  346. public function getTotal($params = []) {
  347. $sqlWhere = $this->_parseWhere($params);
  348. return DB::getPDO()->fetchValue("
  349. select count(1) as cnt
  350. from `{$this->_rootTableName}` t
  351. {$sqlWhere}
  352. ");
  353. }
  354. public function clearGetItemCache($pk = null) {
  355. if (!$this->_cache) return;
  356. if (!$pk) $this->_cache = [];
  357. else if (array_key_exists($pk, $this->_cache)) unset($this->_cache[$pk]);
  358. }
  359. public function getItem($pk, $params = []) {
  360. // TODO: ceche query for: $pk = 'default_db/CRM_PROCES/PROCES', $params = [ 'propertyName' => "*,field" ]
  361. if (!$this->_cache) $this->_cache = [];
  362. if (1 === count($params) && "*,field" === V::get('propertyName', '', $params)) {
  363. if (array_key_exists($pk, $this->_cache)) return $this->_cache[$pk];
  364. $this->_cache[$pk] = $this->_fetchItem($pk, $params);
  365. } else {
  366. return $this->_fetchItem($pk, $params);
  367. }
  368. return $this->_cache[$pk];
  369. }
  370. public function _fetchItem($pk, $params = []) {
  371. if (!$pk) throw new Exception("Missing primary key '{$this->_namespace}'");
  372. $pkField = $this->getSqlPrimaryKeyField();
  373. if (!$pkField) throw new Exception("Missing primary key field defined in '{$this->_namespace}'");
  374. $sqlPk = DB::getPDO()->quote($pk, PDO::PARAM_STR);
  375. $item = DB::getPDO()->fetchFirst("
  376. select t.*
  377. from `{$this->_rootTableName}` t
  378. where t.`{$pkField}` = {$sqlPk}
  379. ");
  380. if (!$item) throw new Exception("Item '{$pk}' not exists - type '{$this->_namespace}'");
  381. return $this->buildFeatureFromSqlRow($item, $params);
  382. }
  383. public function getItems($params = []) {
  384. $sqlWhere = $this->_parseWhere($params);
  385. $currSortCol = V::get('order_by', 'idZasob', $params);
  386. $currSortFlip = strtolower(V::get('order_dir', 'desc', $params));
  387. // TODO: validate $currSortCol is in field list
  388. // TODO: validate $currSortFlip ('asc' or 'desc')
  389. $xsdFields = $this->getXsdTypes();
  390. if (!array_key_exists($currSortCol, $xsdFields)) throw new Exception("Field '{$currSortCol}' not found in '{$this->_namespace}'");
  391. if (!in_array($currSortFlip, ['asc', 'desc'])) throw new Exception("Sort dir not allowed");
  392. $sqlOrderBy = "order by t.`{$currSortCol}` {$currSortFlip}";
  393. $limit = V::get('limit', 0, $params, 'int');
  394. $limit = ($limit < 0) ? 0 : $limit;
  395. $offset = V::get('limitstart', 0, $params, 'int');
  396. $offset = ($offset < 0) ? 0 : $offset;
  397. $sqlLimit = ($limit > 0)
  398. ? "limit {$limit} offset {$offset}"
  399. : '';
  400. Lib::loadClass('AclQueryItems');
  401. $query = new AclQueryItems($this);
  402. $query->setParams($params);
  403. $query->setSource('default_db');
  404. $query->setRawSql("
  405. select t.*
  406. from `{$this->_rootTableName}` t
  407. {$sqlWhere}
  408. {$sqlOrderBy}
  409. {$sqlLimit}
  410. ");
  411. return $query->fetchAll();
  412. }
  413. public function buildFeatureFromSqlRow($item, $params = []) {
  414. DBG::log($params, 'array', "buildFeatureFromSqlRow... '{$item['namespace']}'");
  415. $exNs = explode('/', $item['namespace']);
  416. $item['name'] = array_pop($exNs);
  417. $item['nsPrefix'] = implode('__x3A__', $exNs);
  418. $item['typeName'] = implode('__x3A__', $exNs) . ':' . $item['name'];
  419. $item['reinstallLink'] = Router::getRoute('Storage_AclReinstall')->getLink('', [ 'namespace' => $item['namespace'] ]);
  420. if (!empty($params['propertyName'])) {
  421. if (is_string($params['propertyName'])) $params['propertyName'] = explode(',', $params['propertyName']);
  422. if (!is_array($params['propertyName'])) throw new Exception("Wrong param propertyName - expected array or string");
  423. foreach ($params['propertyName'] as $fetchField) {
  424. if ('*' == $fetchField) continue;
  425. if ('field' == $fetchField) {
  426. $item['field'] = SchemaFactory::loadDefaultObject('SystemObjectField')->getItems([
  427. '__backRef' => [
  428. 'namespace' => 'default_objects/SystemObject',
  429. 'primaryKey' => $item['namespace']
  430. ]
  431. ]);
  432. }
  433. }
  434. }
  435. return $item;
  436. }
  437. public function updateItem($itemPatch) { // @required [ 'namespace' => ... ] (primaryKey)
  438. $pkField = $this->getPrimaryKeyField();
  439. $pk = V::get($pkField, null, $itemPatch);
  440. if (null === $pk) throw new Exception("BUG missing primary key field for '{$this->_namespace}' updateItem");
  441. $this->clearGetItemCache($pk);
  442. DBG::log(['updateItem $itemPatch', $itemPatch]);
  443. unset($itemPatch[$pkField]);
  444. if (empty($itemPatch)) return 0;
  445. foreach ($itemPatch as $fieldName => $value) {
  446. if ('isStructInstalled' == $fieldName) continue;
  447. if ('isObjectActive' == $fieldName) continue;
  448. throw new Exception("Update field '{$fieldName}' not allowed for '{$this->_namespace}'");
  449. }
  450. return DB::getPDO()->update($this->_rootTableName, $pkField, $pk, $itemPatch);
  451. }
  452. }