SystemObjectStorageAcl.php 23 KB

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