SystemObjectStorageAcl.php 23 KB

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