SystemObjectStorageAcl.php 18 KB

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