SystemObjectStorageAcl.php 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373
  1. <?php
  2. Lib::loadClass('Core_AclSimpleSchemaBase');
  3. Lib::loadClass('ParseOgcFilter');
  4. class Schema_SystemObjectStorageAcl extends Core_AclSimpleSchemaBase {
  5. public $_simpleSchema = [
  6. 'root' => [
  7. '@namespace' => 'default_objects/SystemObject',
  8. '@primaryKey' => 'idZasob',
  9. 'idZasob' => [ '@type' => 'xsd:integer' ],
  10. 'idDatabase' => [ '@type' => 'xsd:integer' ],
  11. 'nsPrefix' => [ '@type' => 'xsd:string' ],
  12. 'name' => [ '@type' => 'xsd:string' ],
  13. '_rootTableName' => [ '@type' => 'xsd:string' ],
  14. '_type' => [ '@type' => 'xsd:string' ],
  15. 'isActive' => [ '@type' => 'xsd:integer' ], // installed
  16. 'description' => [ '@type' => 'xsd:string' ],
  17. // 'A_RECORD_CREATE_AUTHOR' => [ '@type' => 'xsd:string' , '@label' => 'autor' ],
  18. // 'A_RECORD_CREATE_DATE' => [ '@type' => 'xsd:date' , '@label' => 'utworzono' ],
  19. // 'A_RECORD_UPDATE_AUTHOR' => [ '@type' => 'xsd:string' , '@label' => 'zaktualizował' ],
  20. // 'A_RECORD_UPDATE_DATE' => [ '@type' => 'xsd:date', '@label' => 'zaktualizowano' ],
  21. ]
  22. // 'root' => [
  23. // '@namespace' => 'default_objects/SystemObject',
  24. // '@primaryKey' => 'ID',
  25. // 'ID' => [ '@type' => 'xsd:integer' ],
  26. // 'namespace' => [ '@type' => 'xsd:string' ],
  27. // 'typeName' => [ '@type' => 'xsd:string' ],
  28. // 'tabela' => [ '@type' => 'xsd:string', '@alias' => 'DESC' ],
  29. // 'nazwa' => [ '@type' => 'xsd:string', '@alias' => 'DESC' ],
  30. // 'opis' => [ '@type' => 'xsd:string', '@alias' => 'OPIS' ],
  31. // 'id_zasob' => [ '@type' => 'xsd:integer' ],
  32. // 'autor' => [ '@type' => 'xsd:string' , '@alias' => 'A_RECORD_CREATE_AUTHOR' ],
  33. // 'utworzono' => [ '@type' => 'xsd:date' , '@alias' => 'A_RECORD_CREATE_DATE' ],
  34. // 'zaktualizował' => [ '@type' => 'xsd:string' , '@alias' => 'A_RECORD_UPDATE_AUTHOR' ],
  35. // 'zaktualizowano' => [ '@type' => 'xsd:date', '@alias' => 'A_RECORD_UPDATE_DATE' ]
  36. // ]
  37. ];
  38. // public $_rootTableName = 'CRM_LISTA_ZASOBOW';
  39. public $_rootTableName = 'CRM_#CACHE_ACL_OBJECT';
  40. public $_version = '1';
  41. // public function __construct($simpleSchema = null) {
  42. // parent::__construct($simpleSchema);
  43. // self::updateCacheIfNeeded(array($this, 'updateCache'));
  44. // }
  45. // public static function updateCacheIfNeeded($updateCallback) {
  46. // static $_cacheUpdated = null;
  47. // if (null !== $_cacheUpdated) return;
  48. // $conf = DB::getPDO()->fetchFirst("
  49. // select (select CONF_VAL from CRM_CONFIG where CONF_KEY = 'SystemObject__last_cache_update_date') as lastCacheUpdate
  50. // , (select CONF_VAL from CRM_CONFIG where CONF_KEY = 'SystemObject__force_cache_update') as forceCacheUpdate
  51. // , (select CONF_VAL from CRM_CONFIG where CONF_KEY = 'SystemObject__schema_version') as schemaVersion
  52. // , (select CONF_VAL from CRM_CONFIG where CONF_KEY = 'tbl_indexer_CRM_PROCES_last_exec_end') as lastProcesIndexer
  53. // , (
  54. // 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
  55. // from CRM_LISTA_ZASOBOW_HIST
  56. // order by ID DESC
  57. // limit 1
  58. // ) as lastZasobyUpdate
  59. // ");
  60. // if ($conf['lastZasobyUpdate']) {// fix date format - convert to Mysql date time format '2002-05-30 09:00:00'
  61. // if (preg_match('/^\d\d\d\d\-\d\d\-\d\d\-\d\d:\d\d$/', $conf['lastZasobyUpdate'])) { // 'Y-m-d-H:i'
  62. // $conf['lastZasobyUpdate'] = substr($conf['lastZasobyUpdate'], 0, 10) . " " . substr($conf['lastZasobyUpdate'], 11) . ":00";
  63. // } 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'
  64. // $conf['lastZasobyUpdate'] = substr($conf['lastZasobyUpdate'], 0, 10) . " " . substr($conf['lastZasobyUpdate'], 11);
  65. // } else if (preg_match('/^\d\d\d\d\-\d\d\-\d\d\ \d\d:\d\d:\d\d$/', $conf['lastZasobyUpdate'])) {
  66. // $conf['lastZasobyUpdate'] = substr($conf['lastZasobyUpdate'], 0, 10) . " " . substr($conf['lastZasobyUpdate'], 11);
  67. // }
  68. // }
  69. // // $lastProcesIndexer = DB::getPDO()->fetchValue(" select CONF_VAL from CRM_CONFIG where CONF_KEY = 'tbl_indexer_CRM_PROCES_last_exec_end' ");
  70. // $updateReason = null;
  71. // if ('1' == $conf['forceCacheUpdate']) $updateReason = 'forceCacheUpdate = 1';
  72. // if (!$conf['lastCacheUpdate']) $updateReason = '!lastCacheUpdate';
  73. // if (!$conf['schemaVersion']) $updateReason = '!schemaVersion';
  74. // else if ($conf['schemaVersion'] < $this->_version) $updateReason = 'schemaVersion < ' . $this->_version;
  75. // if ($conf['lastCacheUpdate'] && $conf['lastZasobyUpdate'] && $conf['lastCacheUpdate'] < $conf['lastZasobyUpdate']) $updateReason = 'lastZasobyUpdate';
  76. // if ($updateReason) {
  77. // DBG::simpleLog('schema', "SystemObject: update cache reason '{$updateReason}' '" . json_encode($conf) . "'");
  78. // call_user_func($updateCallback);
  79. // }
  80. // DB::getPDO()->execSql("
  81. // insert into CRM_CONFIG (CONF_KEY, CONF_VAL)
  82. // values('SystemObject__last_cache_update_date', NOW())
  83. // on duplicate key update CONF_VAL = NOW()
  84. // ");
  85. // DB::getPDO()->execSql("
  86. // insert into CRM_CONFIG (CONF_KEY, CONF_VAL)
  87. // values('SystemObject__schema_version', {$this->_version})
  88. // on duplicate key update CONF_VAL = {$this->_version}
  89. // ");
  90. // if ('1' == $conf['forceCacheUpdate']) DB::getPDO()->execSql(" update CRM_CONFIG set CONF_VAL = '0' where CONF_KEY = 'SystemObject__force_cache_update' ");
  91. // $_cacheUpdated = true;
  92. // }
  93. public function updateCache($idDatabase = null) {
  94. DBG::simpleLog('schema', "SystemObject::updateCache...");
  95. DB::getPDO()->execSql(" drop table if exists `{$this->_rootTableName}` "); // TODO: DBG
  96. DB::getPDO()->execSql("
  97. create table if not exists `{$this->_rootTableName}` (
  98. `idZasob` int(11) DEFAULT NULL,
  99. `idDatabase` int(11) NOT NULL,
  100. `nsPrefix` varchar(255) DEFAULT '',
  101. `name` varchar(255) DEFAULT '',
  102. `_rootTableName` varchar(255) DEFAULT '',
  103. `_type` varchar(255) DEFAULT '',
  104. `isActive` tinyint(1) NOT NULL DEFAULT 0 COMMENT 'installed',
  105. `description` varchar(255) DEFAULT '',
  106. UNIQUE KEY `idZasob` (idZasob),
  107. UNIQUE KEY `typeName` (nsPrefix, name),
  108. KEY `isActive` (isActive)
  109. ) ENGINE=MyISAM DEFAULT CHARSET=latin2
  110. ");
  111. $idDefDB = DB::getPDO()->getZasobId();
  112. $sourceStorage = SchemaFactory::loadDefaultObject('SystemSource');
  113. foreach ($sourceStorage->getItems([ 'f_hasConfig' => 1 ]) as $source) {
  114. if ('default_objects' == $source['nsPrefix']) {
  115. foreach (glob(APP_PATH_LIB . "/Schema/*StorageAcl.php", GLOB_NOSORT) as $file) {
  116. $clsName = substr(basename($file), 0, -1 * strlen('StorageAcl.php'));
  117. try {
  118. $acl = SchemaFactory::loadDefaultObject($clsName);
  119. $namespace = $acl->getNamespace();
  120. $name = $acl->getName();
  121. DB::getPDO()->execSql("
  122. insert ignore into `{$this->_rootTableName}` (nsPrefix, idDatabase, _type, name, description, isActive)
  123. values (
  124. '{$source['nsPrefix']}'
  125. , '{$source['idZasob']}'
  126. , 'StorageAcl'
  127. , '{$name}'
  128. , ''
  129. , '1'
  130. )
  131. ");
  132. } catch (Exception $e) {
  133. UI::alert('danger', $e->getMessage());
  134. }
  135. }
  136. DB::getPDO()->execSql("
  137. insert into `{$this->_rootTableName}` (idZasob, nsPrefix, idDatabase, name, description, isActive)
  138. select t.ID as idZasob
  139. , '{$source['nsPrefix']}' as nsPrefix
  140. , '{$source['idZasob']}' as idDatabase
  141. , t.`DESC` as name
  142. , t.`OPIS` as description
  143. , 1 as isActive
  144. from CRM_LISTA_ZASOBOW t
  145. where t.`TYPE` = 'TABELA'
  146. and t.A_STATUS in('NORMAL', 'WAITING')
  147. and t.PARENT_ID = {$source['idZasob']}
  148. and t.`DESC` not like '%/%'
  149. on duplicate key update idZasob = t.ID
  150. , isActive = 1
  151. ");
  152. }
  153. else {
  154. try {
  155. $dbName = DB::getPDO($source['idZasob'])->getDatabaseName();
  156. $dbType = DB::getPDO($source['idZasob'])->getType();
  157. if ('mysql' == $dbType) {
  158. UI::alert('warning', "TODO: { id: {$source['idZasob']}, nsPrefix: '{$source['nsPrefix']}', dbName: '{$dbName}', dbType: '{$dbType}'} ...");
  159. // TODO: if another DB split select and insert
  160. DB::getPDO()->execSql("
  161. insert into `{$this->_rootTableName}` (idDatabase, nsPrefix, name, _rootTableName, _type, description)
  162. select '{$source['idZasob']}' as idDatabase
  163. , '{$source['nsPrefix']}' as nsPrefix
  164. , t.TABLE_NAME as name
  165. , t.TABLE_NAME as _rootTableName
  166. , 'TableAcl' as _type
  167. , t.TABLE_COMMENT as description
  168. from INFORMATION_SCHEMA.TABLES t
  169. where t.TABLE_SCHEMA = '{$dbName}'
  170. on duplicate key update _rootTableName = t.TABLE_NAME
  171. ");
  172. DB::getPDO()->execSql("
  173. insert into `{$this->_rootTableName}` (idZasob, nsPrefix, idDatabase, name, description, isActive)
  174. select t.ID as idZasob
  175. , '{$source['nsPrefix']}' as nsPrefix
  176. , '{$source['idZasob']}' as idDatabase
  177. , t.`DESC` as name
  178. , t.`OPIS` as description
  179. , 1 as isActive
  180. from CRM_LISTA_ZASOBOW t
  181. where t.`TYPE` = 'TABELA'
  182. and t.A_STATUS in('NORMAL', 'WAITING')
  183. and t.PARENT_ID = {$source['idZasob']}
  184. on duplicate key update idZasob = t.ID
  185. , isActive = 1
  186. ");
  187. // } else if ('pgsql' == $dbType) {// TODO: use pgsql @see Storage Pgsql getTables from information_schema
  188. } else {
  189. UI::alert('warning', "TODO: { id: {$source['idZasob']}, nsPrefix: '{$source['nsPrefix']}', dbName: '{$dbName}', dbType: <b>'{$dbType}'</b>} ...");
  190. }
  191. } catch (Exception $e) {
  192. UI::alert('danger', "Error source '{$source['idZasob']}' " . $e->getMessage());
  193. continue;
  194. }
  195. }
  196. }
  197. // // foreach ... DB::getPDO($idDatabase)->fetchAll(select real _rootTableName)
  198. // foreach (Core_AclHelper::getAclList() as $typeName) {
  199. // $ns = Core_AclHelper::parseTypeName($typeName);
  200. // $namespace = str_replace('__x3A__', '/', $ns['prefix']) . "/{$ns['name']}";
  201. // $sqlNs = DB::getPDO()->quote($namespace, PDO::PARAM_STR);
  202. // $idZasob = DB::getPDO()->fetchValue(" select ID from CRM_LISTA_ZASOBOW where `DESC` = {$sqlNs} and `TYPE` = 'TABELA' and A_STATUS in('WAITING', 'NORMAL') ");
  203. // if (!$idZasob) {
  204. // DBG::nicePrint($ns, "TODO: insert zasob PARENT_ID = ?");
  205. // }
  206. // }
  207. }
  208. public function _parseWhere($params = []) {
  209. $sqlWhere = [];
  210. if (!empty($params['#refFrom'])) {
  211. // '#refFrom' => [
  212. // 'namespace' => 'default_objects/SystemSource',
  213. // 'primaryKey' => $sourceItem['idZasob']
  214. // ]
  215. if (empty($params['#refFrom']['namespace'])) throw new Exception("Missing refFrom/namespace");
  216. if (empty($params['#refFrom']['primaryKey'])) throw new Exception("Missing refFrom/primaryKey");
  217. if ('default_objects/SystemSource' != $params['#refFrom']['namespace']) throw new Exception("Unsupported refFrom/namespace '{$params['#refFrom']['namespace']}'");
  218. $sqlWhere[] = "idDatabase = " . DB::getPDO()->quote($params['#refFrom']['primaryKey'], PDO::PARAM_INT);
  219. }
  220. return (!empty($sqlWhere)) ? "where " . implode(" and ", $sqlWhere) : '';
  221. }
  222. public function getTotal($params = []) {
  223. $sqlWhere = $this->_parseWhere($params);
  224. return DB::getPDO()->fetchValue("
  225. select count(1) as cnt
  226. from `{$this->_rootTableName}` t
  227. {$sqlWhere}
  228. ");
  229. }
  230. public function getItems($params = []) {
  231. $sqlWhere = $this->_parseWhere($params);
  232. return DB::getPDO()->fetchAll("
  233. select t.*
  234. from `{$this->_rootTableName}` t
  235. {$sqlWhere}
  236. ");
  237. $items = $this->_getAllItems();
  238. $currSortCol = V::get('order_by', 'ID', $params);
  239. $currSortFlip = strtolower(V::get('order_dir', 'desc', $params));
  240. // TODO: validate $currSortCol is in field list
  241. // TODO: validate $currSortFlip ('asc' or 'desc')
  242. $aliasMap = array();
  243. foreach ($this->_simpleSchema['root'] as $key => $field) {
  244. if ('@' === substr($key, 0, 1)) continue;
  245. $aliasMap[ $key ] = $key;// (!empty($field['@alias'])) ? $field['@alias'] : $key;
  246. }
  247. // TODO: if (!array_key_exists($currSortCol, $aliasMap)) throw new Exception("field name not allowed to sort");
  248. $currSortCol = (array_key_exists($currSortCol, $aliasMap)) ? $aliasMap[$currSortCol] : null;
  249. if (!empty($currSortCol) && ('asc' == $currSortFlip || 'desc' == $currSortFlip)) {
  250. usort($items, function ($itemA, $itemB) use ($currSortCol, $currSortFlip) {
  251. $a = strtolower(V::get($currSortCol, '', $itemA));
  252. $b = strtolower(V::get($currSortCol, '', $itemB));
  253. if ($a == $b) return 0;
  254. else if ('asc' == $currSortFlip) return ($a < $b) ? -1 : 1;
  255. else if ('desc' == $currSortFlip) return ($a > $b) ? -1 : 1;
  256. throw new Exception("BUG - Wrong sort param - order dir");
  257. });
  258. }
  259. $limit = V::get('limit', 0, $params);
  260. $limit = ($limit < 0) ? 0 : $limit;
  261. $offset = V::get('limitstart', 0, $params);
  262. $offset = ($offset < 0) ? 0 : $offset;
  263. return array_slice($items, $offset, ($limit > 0) ? $limit : null, $preserve_keys = true);
  264. }
  265. public function _generateUniqueKeyFromNamespace($namespace) {
  266. return str_replace('/', '__x3A__', $namespace);
  267. }
  268. public function _getAllItems($params = []) {
  269. static $_cacheAllItems = null;
  270. if (null !== $_cacheAllItems) return $_cacheAllItems;
  271. $idMainDatabase = DB::getPDO()->getZasobId();
  272. $listFromZasoby = array_map(
  273. function ($row) {
  274. $row['ID'] = $row['id_zasob'];
  275. if (false !== strpos($row['tabela'], '/')) {
  276. $ns = Core_AclHelper::parseNamespaceUrl($row['tabela']);
  277. $row['namespace'] = "{$row['tabela']}";
  278. $row['typeName'] = "{$ns['prefix']}:{$ns['name']}";
  279. $row['nazwa'] = $ns['name'];
  280. } else {
  281. $row['namespace'] = "default_db/{$row['tabela']}";
  282. $row['typeName'] = "default_db:{$row['tabela']}";
  283. // $row['ID'] = $this->_generateUniqueKeyFromNamespace($row['namespace']);
  284. }
  285. return $row;
  286. }
  287. , DB::getPDO()->fetchAll("
  288. select z.ID as id_zasob
  289. , z.`DESC` as tabela
  290. , IF(z.`DESC_PL` != '', z.`DESC_PL`, z.`DESC`) as nazwa
  291. , z.`OPIS` as opis
  292. , z.A_RECORD_CREATE_AUTHOR as `autor`
  293. , z.A_RECORD_CREATE_DATE as `utworzono`
  294. , z.A_RECORD_UPDATE_AUTHOR as `zaktualizował`
  295. , z.A_RECORD_UPDATE_DATE as `zaktualizowano`
  296. from `CRM_LISTA_ZASOBOW` z
  297. where z.PARENT_ID = {$idMainDatabase}
  298. and z.`TYPE` = 'TABELA'
  299. and z.`A_STATUS` not in('DELETED', 'OFF_HARD', 'OFF_SOFT')
  300. ")
  301. );
  302. $notRawTables = array_filter(
  303. array_map(
  304. function ($item) {
  305. return $item['typeName'];
  306. }
  307. , $listFromZasoby
  308. )
  309. , function ($typeName) {
  310. return 'default_db:' !== substr($typeName, 0, strlen('default_db:'));
  311. }
  312. );
  313. $_cacheAllItems = array_filter(
  314. array_merge(
  315. $listFromZasoby
  316. , array_map(
  317. function ($typeName) {
  318. list($prefix, $objectName) = explode(':', $typeName);
  319. $namespace = str_replace([':', '__x3A__'], '/', $typeName);
  320. $id = 0;
  321. if ('objects' == $prefix) {
  322. $id = SchemaFactory::loadDefaultObject($objectName)->getID();
  323. } else if ('default_objects' == $prefix) {
  324. $id = SchemaFactory::loadDefaultObject($objectName)->getID();
  325. } else if ('default_db__x3A__' == substr($prefix, 0, 17)) {
  326. $rootTableName = strtolower(substr($prefix, 17));
  327. $id = SchemaFactory::loadTableObject($rootTableName, $objectName)->getID();
  328. }
  329. if (!$id) $id = $this->_generateUniqueKeyFromNamespace($namespace);
  330. return [
  331. 'ID' => $id,
  332. 'id_zasob' => $id,
  333. 'namespace' => $namespace,
  334. 'typeName' => $typeName,
  335. 'tabela' => '', // TODO: $acl->getRootTableName(),
  336. 'nazwa' => substr($typeName, strrpos($typeName, ':') + 1),
  337. 'opis' => '...',
  338. 'autor' => '',
  339. 'utworzono' => '',
  340. 'zaktualizował' => '',
  341. 'zaktualizowano' => ''
  342. ];
  343. }
  344. , array_filter(Core_AclHelper::getAclList(), function ($typeName) use ($notRawTables) { return !in_array($typeName, $notRawTables); })
  345. )
  346. )
  347. , function ($item) use ($params) {
  348. return true;
  349. }
  350. );
  351. return $_cacheAllItems;
  352. }
  353. }