SystemObjectStorageAcl.php 23 KB

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