SystemObjectStorageAcl.php 18 KB

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