SystemObjectStorageAcl.php 16 KB

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