ACL.php 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593
  1. <?php
  2. Lib::loadClass('Core_AclHelper');
  3. Lib::loadClass('AntAclBase');
  4. Lib::loadClass('RefConfig');
  5. Lib::loadClass('InstanceConfig');
  6. class ACL {
  7. /**
  8. * Ids List of Proces Init for given tabel (skip filters)
  9. */
  10. public static function getTableProcesInitIds($idTable) {
  11. $procesInitList = self::getTableProcesInitList($idTable);
  12. return array_keys($procesInitList);
  13. }
  14. /**
  15. * List of Proces Init for given table (skip filters)
  16. */
  17. public static function getTableProcesInitList($idTable) {
  18. $tableProcesInitList = array();
  19. $sqlIdProcesListSql = "
  20. select tpv.`ID_PROCES`
  21. from `CRM_PROCES_idx_TABLE_TO_PROCES_VIEW` tpv
  22. where tpv.`ID_TABLE`='{$idTable}'
  23. ";
  24. $fetchTableProcesInitListSql = "
  25. -- time ~0.07 -- no goto and return
  26. select p.`ID`, p.`DESC`
  27. from `CRM_PROCES` p
  28. where p.`ID` in(
  29. select i.`idx_PROCES_INIT_ID`
  30. from `CRM_PROCES_idx` i
  31. where i.`ID_PROCES` in({$sqlIdProcesListSql})
  32. )
  33. and p.`TYPE`='PROCES_INIT'
  34. order by p.`SORT_PRIO`
  35. ";
  36. /*
  37. SELECT p.`ID` , p.`DESC`
  38. FROM `CRM_PROCES` p
  39. WHERE p.`ID`
  40. IN (
  41. SELECT i.`idx_PROCES_INIT_ID`
  42. FROM `CRM_PROCES_idx` i
  43. WHERE i.`ID_PROCES`
  44. IN (
  45. SELECT tpv.`ID_PROCES`
  46. FROM `CRM_PROCES_idx_TABLE_TO_PROCES_VIEW` tpv
  47. WHERE tpv.`ID_TABLE` = '13051'
  48. )
  49. )
  50. AND p.`TYPE` = 'PROCES_INIT'
  51. order by p.`SORT_PRIO`
  52. */
  53. $fetchTableProcesInitListSql = "
  54. -- time ~0.15s
  55. select p.`ID`, p.`DESC`
  56. from `CRM_PROCES` p
  57. where p.`ID` in(
  58. select i.`idx_PROCES_INIT_ID`
  59. from `CRM_PROCES_idx` i
  60. where i.`ID_PROCES` in({$sqlIdProcesListSql})
  61. union
  62. select ig.`idx_PROCES_INIT_ID`
  63. from `CRM_PROCES_idx` i
  64. join `CRM_PROCES_idx` ig on(ig.`ID_PROCES`=i.`idx_PROCES_WITH_GROUPS_ID`)
  65. where i.`ID_PROCES` in({$sqlIdProcesListSql})
  66. )
  67. and p.`TYPE`='PROCES_INIT'
  68. order by p.`SORT_PRIO`
  69. ";
  70. $fetchTableProcesInitListSql = "
  71. -- time ~0.14
  72. select p.`ID`, p.`DESC`
  73. from `CRM_PROCES` p
  74. where p.`ID` in(
  75. select i.`idx_PROCES_INIT_ID`
  76. from `CRM_PROCES_idx` i
  77. where i.`ID_PROCES` in({$sqlIdProcesListSql})
  78. or i.`ID_PROCES` in(
  79. select ig.`idx_PROCES_WITH_GROUPS_ID`
  80. from `CRM_PROCES_idx` ig
  81. where ig.`ID_PROCES` in({$sqlIdProcesListSql})
  82. )
  83. )
  84. and p.`TYPE`='PROCES_INIT'
  85. order by p.`SORT_PRIO`
  86. ";
  87. return array_map(function ($row) {
  88. return $row['DESC'];
  89. }, DB::getPDO()->fetchAllByKey($fetchTableProcesInitListSql, 'ID'));
  90. }
  91. public static function getProcesInitMapTreeOnlyIds($ids) {
  92. $mapTree = array();
  93. $map = self::getProcesInitMapOnlyIds($ids);
  94. foreach ($map as $row) {
  95. if ('PROCES_INIT' == $row['TYPE']) {
  96. $mapTree[ $row['ID_PROCES'] ] = array();
  97. }
  98. }
  99. foreach ($map as $row) {
  100. if ('GOTO_AND_RETURN' == $row['TYPE']) {
  101. $mapTree[ $row['idx_MAIN_PROCES_INIT_ID'] ][ $row['ID_PROCES'] ] = array();
  102. }
  103. }
  104. foreach ($map as $row) {
  105. if ('GOTO_AND_RETURN_LVL2' == $row['TYPE']) {
  106. $mapTree[ $row['idx_MAIN_PROCES_INIT_ID'] ][ $row['idx_GOTO_LVL2_INIT_ID'] ][ $row['ID_PROCES'] ] = true;
  107. }
  108. }
  109. return $mapTree;
  110. }
  111. public static function getProcesInitMapOnlyIds($ids) {
  112. $map = array();
  113. $sqlIds = V::filter($ids, array('V', 'filterPositiveInteger'));
  114. $sqlIds = implode(',', $sqlIds);
  115. if (empty($sqlIds)) return $map;
  116. $sql = "
  117. select i.`ID_PROCES`
  118. , i.`PARENT_ID`
  119. , i.`TYPE`
  120. , i.`idx_PROCES_INIT_ID`
  121. , i.`idx_MAIN_PROCES_INIT_ID`
  122. , i.`idx_PROCES_WITH_GROUPS_ID`
  123. , IF(i.`TYPE`='GOTO_AND_RETURN_LVL2'
  124. , (select ig.`idx_PROCES_INIT_ID`
  125. from `CRM_PROCES_idx` ig
  126. where ig.`ID_PROCES`=i.`PARENT_ID`
  127. limit 1)
  128. , 0
  129. ) as idx_GOTO_LVL2_INIT_ID
  130. from `CRM_PROCES_idx` i
  131. where i.`ID_PROCES` in({$sqlIds})
  132. and i.`idx_MAIN_PROCES_INIT_ID` in({$sqlIds})
  133. ";
  134. return DB::getPDO()->fetchAll($sql);
  135. }
  136. public static function canGroupViewProces($idGroup, $idProcesInit) {
  137. $isAllowed = false;
  138. $idProcesInit = (int)$idProcesInit;
  139. if (!$idProcesInit) return false;
  140. $checkProcesAccessSql = "
  141. select count(*) as cnt
  142. from `CRM_PROCES_idx_GROUP_to_INIT_VIEW` giv
  143. where giv.`ID_GROUP` = '{$idGroup}'
  144. and giv.`ID_PROCES_INIT` = '{$idProcesInit}'
  145. ";
  146. return ( DB::getPDO()->fetchValue($checkProcesAccessSql) > 0 );
  147. }
  148. public static function getStorageByNamespace($namespace, $forceTblAclInit = false) {
  149. Lib::loadClass('Core_AclHelper');
  150. Lib::loadClass('SchemaFactory');
  151. $ns = Core_AclHelper::parseNamespaceUrl($namespace);
  152. DBG::log($ns, 'array', "parseNamespaceUrl({$namespace})");
  153. if ('default_db' == $ns['prefix']) {
  154. $acl = User::getAcl()->getObjectAcl($ns['prefix'], $ns['name']);
  155. } else if ('objects' == $ns['prefix']) {
  156. $acl = SchemaFactory::loadDefaultObject($ns['name']);
  157. } else if ('default_objects' == $ns['prefix']) {
  158. $acl = SchemaFactory::loadDefaultObject($ns['name']);
  159. } else if ('default_db__x3A__' == substr($ns['prefix'], 0, 17)) {
  160. $rootTableName = strtolower(substr($ns['prefix'], 17));
  161. $acl = SchemaFactory::loadTableObject($rootTableName, $ns['name']);
  162. } else {
  163. throw new HttpException("Not Implemented", 501);
  164. }
  165. $acl->init($forceTblAclInit);
  166. return $acl;
  167. }
  168. public static function getBaseNamespace($namespace) {
  169. // map SystemObjects__x3A__{parent}/{name} to default_objects/{name}
  170. if ('SystemObjects/' === substr($namespace, 0, strlen('SystemObjects/'))) {
  171. $exNs = explode('/', $namespace);
  172. if (3 === count($exNs)) {
  173. return "default_objects/{$exNs[2]}";
  174. }
  175. }
  176. return $namespace;
  177. }
  178. public static function getAclByNamespace($namespace, $forceTblAclInit = false) {
  179. $namespace = ACL::getBaseNamespace($namespace);
  180. return Core_AclHelper::getAclByNamespace($namespace, $forceTblAclInit);
  181. }
  182. public static function getAclByTypeName($typeName, $forceTblAclInit = false) {
  183. return Core_AclHelper::getAclByNamespace(str_replace(':', '/', $typeName), $forceTblAclInit);
  184. }
  185. public static function getNamespaceFromId($idZasob) {
  186. $sqlIdZasob = DB::getPDO()->quote($idZasob, PDO::PARAM_INT);
  187. $zasob = DB::getPDO()->fetchFirst("
  188. select z.ID, z.DESC, z.PARENT_ID
  189. from CRM_LISTA_ZASOBOW z
  190. where z.ID = {$sqlIdZasob}
  191. and z.`TYPE` = 'TABELA'
  192. and z.A_STATUS != 'DELETED'
  193. ");
  194. if (!$zasob) throw new Exception("Object not exists '{$idZasob}'");
  195. if ($zasob['PARENT_ID'] != DB::getPDO()->getZasobId()) {
  196. throw new Exception("TODO: getNamespaceFromId for remote database");
  197. }
  198. return ('default_db/' === substr($zasob['DESC'], 0, strlen('default_db/')))
  199. ? $zasob['DESC']
  200. : "default_db/{$zasob['DESC']}"
  201. ;
  202. }
  203. public static function parseNamespaceUrl($namespace) {// returns assoc array: [ 'name', 'url', 'prefix', 'sourceName' ]
  204. return Core_AclHelper::parseNamespaceUrl($namespace);
  205. }
  206. public static function getRefTable($rootObjectNamespace, $childName) { // TODO: mv to RefConfig
  207. static $cacheRefTables = array();
  208. DBG::log("DBG get ref table ({$rootObjectNamespace}, {$childName}) ...");
  209. $rootObjectNamespace = ACL::getBaseNamespace($rootObjectNamespace);
  210. $cacheKey = "{$rootObjectNamespace}/{$childName}";
  211. if (array_key_exists($cacheKey, $cacheRefTables)) return $cacheRefTables[$cacheKey];
  212. $rootAcl = self::getAclByNamespace($rootObjectNamespace);
  213. $refConfig = RefConfig::fetch($rootObjectNamespace, $childName);
  214. // TODO: CASE: Obj: A, B not installed, Ref: A->B; Install A / cannot install Ref A->B / require install B first / then go back and reinstall A
  215. // TODO: What if primaryKey type != int ?
  216. // TODO: require 2 pass for Install every object - first install all base Obj, then reinstall fixes Ref config
  217. // \--- TODO: or split Reinstall obj action to: 1. Reinstall base Obj and 2. Install Ref tables
  218. if ('view' === $refConfig->source) {
  219. $refTableName = "CRM__#REF_TABLE__{$refConfig->id}_VIEW"; // view created by ACL::generateRefSelectSqlByFlatRelationCache
  220. if ('WAITING' == $refConfig->status) {
  221. if (!($rootAcl instanceof AntAclBase)) throw new Exception("Ref allowed only for AntAcl objects");
  222. $fieldInfo = $rootAcl->_getField($childName);
  223. $typeField = Type_Field::build($fieldInfo);
  224. RefConfig::installRefView($rootObjectNamespace, $childName, $typeField, $refConfig);
  225. $refConfig = RefConfig::fetch($rootObjectNamespace, $childName);
  226. }
  227. } else if ('backRef' === $refConfig->source) {
  228. $refTableName = "CRM__#REF_TABLE__{$refConfig->id}_VIEW"; // view created by ACL::generateRefSelectSqlByFlatRelationCache
  229. if ('WAITING' == $refConfig->status) {
  230. throw new Exception("Install backRef view for '{$rootObjectNamespace}' to '{$childName}'");
  231. // if (!($rootAcl instanceof AntAclBase)) throw new Exception("Ref allowed only for AntAcl objects");
  232. // $fieldInfo = $rootAcl->_getField($childName);
  233. // $typeField = Type_Field::build($fieldInfo);
  234. // RefConfig::installRefView($rootObjectNamespace, $childName, $typeField, $refConfig);
  235. // $refConfig = RefConfig::fetch($rootObjectNamespace, $childName);
  236. }
  237. } else if ('table' === $refConfig->source) {
  238. $refTableName = "CRM__#REF_TABLE__{$refConfig->id}";
  239. if ('WAITING' == $refConfig->status) {
  240. RefConfig::createRefTable($rootObjectNamespace, $childName);
  241. $refConfig = RefConfig::fetch($rootObjectNamespace, $childName);
  242. }
  243. } else {
  244. throw new Exception("Not Implemented ref SOURCE = '{$refConfig->source}'");
  245. }
  246. if ('0' === (string)$refConfig->version) {
  247. DBG::log($refConfig, 'array', "BUG RefConfig VERSION = 0 (ID: {$refConfig->version})");
  248. throw new Exception("Wystąpiły błędy w konfiguracji tabeli powiązań - zainstaluj ponownie obiekt");
  249. }
  250. if ($refConfig->version < RefConfig::$REF_TABLE_VERSION) {
  251. if (1 == $refConfig->version) {
  252. RefConfig::createRefTable($rootObjectNamespace, $childName);
  253. $refConfig = RefConfig::fetch($rootObjectNamespace, $childName);
  254. }
  255. }
  256. if ($refConfig->version < RefConfig::$REF_TABLE_VERSION) throw new Exception("TODO: ref table {$refConfig->id} require upgrade - field '{$childName}' in object '{$rootObjectNamespace}'");
  257. $cacheRefTables[$cacheKey] = $refTableName;
  258. return $refTableName;
  259. }
  260. public static function getRefSource($rootObjectNamespace, $childName) { // CRM_REF_CONFIG
  261. $rootObjectNamespace = ACL::getBaseNamespace($rootObjectNamespace);
  262. $refConfig = RefConfig::fetch($rootObjectNamespace, $childName);
  263. return $refConfig->source;
  264. }
  265. public static function decodeAppInfoJson($appInfoJsonString) {
  266. $appInfo = @json_decode($appInfoJsonString, $assoc = true);
  267. if (null == $appInfo && 0 !== json_last_error()) throw new Exception("Parsing Json failed: " . json_last_error());
  268. return $appInfo;
  269. }
  270. public static function generateRefSelectSqlByFlatRelationCache($rootObjectNamespace, $childName) { // CRM_REF_CONFIG
  271. $appInfo = DB::getPDO()->fetchValue("
  272. select f.appInfo
  273. from `CRM_#CACHE_ACL_OBJECT_FIELD` f
  274. where f.objectNamespace = '{$rootObjectNamespace}'
  275. and f.fieldNamespace = '{$childName}'
  276. ");
  277. if (!$appInfo) throw new Exception("Missing app:info for field '{$rootObjectNamespace}/{$childName}'");
  278. $appInfo = ACL::decodeAppInfoJson($appInfo);
  279. if (empty($appInfo)) throw new Exception("Empty app:info for field '{$rootObjectNamespace}/{$childName}'");
  280. DBG::log(['$appInfo'=>$appInfo, '$rootObjectNamespace'=>$rootObjectNamespace, '$childName'=>$childName], 'array', "\$appInfo");
  281. $rootAcl = self::getAclByNamespace($rootObjectNamespace);
  282. $childXsdType = $rootAcl->getXsdFieldType($childName);
  283. list($typePrefix, $childNamespace) = explode(':', $childXsdType, 2);
  284. switch ($typePrefix) {
  285. case 'ref_uri': $childAcl = self::getAclByNamespace($childNamespace); break;
  286. case 'ref': $childAcl = self::getAclByTypeName($childNamespace); break;
  287. default: throw new Exception("Expected ref type for field '{$childName}' in object '{$rootObjectNamespace}'");
  288. }
  289. $lastActionDateField = "NULL"; // , IF(l.A_RECORD_UPDATE_DATE > r.A_RECORD_UPDATE_DATE, l.A_RECORD_UPDATE_DATE, r.A_RECORD_UPDATE_DATE) as A_LAST_ACTION_DATE
  290. $rootPrimaryKeyField = $rootAcl->getPrimaryKeyField();
  291. $childPrimaryKeyField = $childAcl->getPrimaryKeyField();
  292. $rootTableName = $rootAcl->getRootTableName();
  293. $childTableName = $childAcl->getRootTableName();
  294. // '$appInfo' => [
  295. // 'flat_relation_cache' => [
  296. // 'source' => [
  297. // '@name' => 'ID',
  298. // '@xpath' => 'default_db__x3A__CRM_WSKAZNIK:CRM_WSKAZNIK/ID_PROCES',
  299. // ),
  300. // ),
  301. // ),
  302. // '$rootObjectNamespace' => 'default_db/CRM_PROCES/PROCES',
  303. // '$childName' => 'default_db__x3A__CRM_WSKAZNIK:CRM_WSKAZNIK',
  304. // '$appInfo' => [
  305. // 'flat_relation_cache' => [
  306. // 'source' => [
  307. // '@name' => 'ID',
  308. // '@xpath' => 'default_db__x3A__CRM_PROCES:PROCES/PARENT_ID',
  309. // ),
  310. // ),
  311. // ),
  312. // '$rootObjectNamespace' => 'default_db/CRM_PROCES/PROCES',
  313. // '$childName' => 'default_db__x3A__CRM_PROCES:PROCES',
  314. $appInfoRootFieldName = null;
  315. $appInfoChildFieldName = null;
  316. {
  317. if (empty($appInfo['flat_relation_cache']['source']['@name'])) throw new Exception("Missing flat_relation_cache/source/@name");
  318. if (empty($appInfo['flat_relation_cache']['source']['@xpath'])) throw new Exception("Missing flat_relation_cache/source/@xpath");
  319. $appInfoName = $appInfo['flat_relation_cache']['source']['@name'];
  320. $appInfoXpath = $appInfo['flat_relation_cache']['source']['@xpath'];
  321. // $rootNs = $rootAcl->getNamespace()
  322. if ("{$childName}/" === substr($appInfoXpath, 0, strlen("{$childName}/"))) {
  323. $appInfoRootFieldName = substr($appInfoXpath, strlen("{$childName}/"));
  324. $appInfoChildFieldName = $appInfoName;
  325. } else {
  326. throw new Exception("TODO parse flat_relation_cache");
  327. }
  328. }
  329. if (!$appInfoRootFieldName || !$appInfoChildFieldName) throw new Exception("Error Processing flat_relation_cache");
  330. $sqlWhereFromRestrictions = [];
  331. DBG::log(['root'=>$rootAcl->getFields(), 'child'=>$childAcl->getFields()], 'array', "rootAcl and childAcl fields - xsdRestrictions");
  332. if ($rootAcl instanceof AntAclBase && $childAcl instanceof AntAclBase) {
  333. $rootLocalFieldsWithRestrictions = array_filter($rootAcl->getFields(), function ($field) {
  334. if (!$field['isLocal']) return false;
  335. if (empty($field['xsdRestrictions'])) return false;
  336. if ('[]' == $field['xsdRestrictions']) return false;
  337. return true;
  338. });
  339. $childLocalFieldsWithRestrictions = array_filter($childAcl->getFields(), function ($field) {
  340. if (!$field['isLocal']) return false;
  341. if (empty($field['xsdRestrictions'])) return false;
  342. if ('[]' == $field['xsdRestrictions']) return false;
  343. return true;
  344. });
  345. DBG::log(['root'=>$rootLocalFieldsWithRestrictions, 'child'=>$childLocalFieldsWithRestrictions], 'array', "root and child fields with xsdRestrictions");
  346. if (!empty($rootLocalFieldsWithRestrictions)) {
  347. $sqlTablePrefix = 'root';
  348. $sqlWhereFromRestrictions = array_reduce(
  349. array_map(function ($field) use ($sqlTablePrefix) {
  350. $sqlRestrictions = [];
  351. // 'xsdRestrictions' => '{"enumeration":{"PROCES":"PROCES"}}',
  352. $restrictions = @json_decode($field['xsdRestrictions'], $assoc = true);
  353. if (!empty($restrictions)) {
  354. if (!empty($restrictions['enumeration'])) {
  355. $sqlRestrictions[] = "{$sqlTablePrefix}.`{$field['fieldNamespace']}` in (" . implode(",", array_map([DB::getPDO(), 'quote'], array_keys($restrictions['enumeration']))) . ")";
  356. }
  357. }
  358. return $sqlRestrictions;
  359. }, $rootLocalFieldsWithRestrictions),
  360. function ($ret, $cur) {
  361. return array_merge($ret, array_filter($cur, ['V', 'filterNotEmpty']));
  362. },
  363. $sqlWhereFromRestrictions
  364. );
  365. }
  366. if (!empty($childLocalFieldsWithRestrictions)) {
  367. $sqlTablePrefix = 'child';
  368. $sqlWhereFromRestrictions = array_reduce(
  369. array_map(function ($field) use ($sqlTablePrefix) {
  370. $sqlRestrictions = [];
  371. // 'xsdRestrictions' => '{"enumeration":{"PROCES":"PROCES"}}',
  372. $restrictions = @json_decode($field['xsdRestrictions'], $assoc = true);
  373. if (!empty($restrictions)) {
  374. if (!empty($restrictions['enumeration'])) {
  375. $sqlRestrictions[] = "{$sqlTablePrefix}.`{$field['fieldNamespace']}` in (" . implode(",", array_map([DB::getPDO(), 'quote'], array_keys($restrictions['enumeration']))) . ")";
  376. }
  377. }
  378. return $sqlRestrictions;
  379. }, $childLocalFieldsWithRestrictions),
  380. function ($ret, $cur) {
  381. return array_merge($ret, array_filter($cur, ['V', 'filterNotEmpty']));
  382. },
  383. $sqlWhereFromRestrictions
  384. );
  385. }
  386. }
  387. $sqlWhereFromRestrictions = (!empty($sqlWhereFromRestrictions)) ? implode(" and ", $sqlWhereFromRestrictions) : "1=1";
  388. $sqlChildFieldName = $childAcl->getSqlFieldName($appInfoRootFieldName);
  389. $sql = "
  390. select root.{$rootPrimaryKeyField} as PRIMARY_KEY
  391. , child.{$childPrimaryKeyField} as REMOTE_PRIMARY_KEY
  392. , '' as REMOTE_TYPENAME
  393. , 'WAITING' as A_STATUS
  394. , 0 as TRANSACTION_ID
  395. , {$lastActionDateField} as A_LAST_ACTION_DATE
  396. from `{$rootTableName}` root
  397. join `{$childTableName}` child on(child.{$sqlChildFieldName} = root.{$appInfoChildFieldName})
  398. where {$sqlWhereFromRestrictions}
  399. ";
  400. DBG::log($sql, 'sql', "generateRefSelectSqlByFlatRelationCache");
  401. return $sql;
  402. }
  403. public static function getBackRefList($namespace) {
  404. if (!$namespace) throw new Exception("Missing namespace");
  405. $nsParts = explode('/', $namespace);
  406. $typeName = array_pop($nsParts);
  407. $typeName = implode("__x3A__", $nsParts) . ":{$typeName}";
  408. return DB::getPDO()->fetchAll("
  409. select c.ROOT_OBJECT_NS as namespace
  410. , i.id as idInstance
  411. from CRM_REF_CONFIG c
  412. join CRM_INSTANCE_CONFIG i on ( i.namespace = c.ROOT_OBJECT_NS )
  413. where ( c.CHILD_NAME = :type_name or c.CHILD_NAME = :namespace )
  414. and c.A_STATUS = 'NORMAL'
  415. ", [
  416. ':type_name' => $typeName,
  417. ':namespace' => $namespace,
  418. ]);
  419. }
  420. public static function fetchRefs($namespace, $childNamespace, $primaryKey, $params = []) { // TODO: $params: limit, total
  421. if (!$namespace) throw new Exception("Missing namespace");
  422. if (!$childNamespace) throw new Exception("Missing child namespace");
  423. if (!$primaryKey) throw new Exception("Missing primary key");
  424. throw new Exception("TODO: fetch refs from '{$namespace}' where primaryKey = '{$primaryKey}'");
  425. }
  426. public static function fetchBackRefs($namespace, $primaryKey, $parentNamespace, $params = []) { // TODO: $params: limit, total
  427. if (!$namespace) throw new Exception("Missing namespace");
  428. if (!$parentNamespace) throw new Exception("Missing parent namespace");
  429. if (!$primaryKey) throw new Exception("Missing primary key");
  430. $typeName = Api_WfsNs::typeName($namespace);
  431. $refTable = ACL::getRefTable($parentNamespace, $typeName);
  432. if (V::get('total', false, $params)) {
  433. return DB::getPDO()->fetchValue(" select count(*) as cnt from `{$refTable}` where REMOTE_PRIMARY_KEY = :primary_key and A_STATUS not in ('DELETED') ", [ ':primary_key' => $primaryKey ]);
  434. }
  435. throw new Exception("TODO: fetch back refs from '{$namespace}' where primaryKey({$primaryKey}) by refTable({$refTable})");
  436. }
  437. public static function generateIsInstanceFunctionBody($namespace, $item = null) {
  438. if (!$item) $item = SchemaFactory::loadDefaultObject('SystemObject')->getItem($namespace, [ 'propertyName' => '*,field' ]);
  439. if (!in_array( $item['_type'], [ 'AntAcl' ] )) return null;
  440. $sqlFunBody = " RETURN 1; ";
  441. $localFieldsWithRestrictions = array_filter($item['field'], function ($field) {
  442. if (!$field['isLocal']) return false;
  443. if (empty($field['xsdRestrictions'])) return false;
  444. if ('[]' == $field['xsdRestrictions']) return false;
  445. return true;
  446. });
  447. // TODO: get fields with minOccurs > 1 (may require select by ref)
  448. $sqlTablePrefix = 'root';
  449. $sqlWhereFromRestrictions = (!empty($localFieldsWithRestrictions))
  450. ? array_reduce(
  451. array_map(function ($field) use ($sqlTablePrefix) {
  452. $sqlRestrictions = [];
  453. // 'xsdRestrictions' => '{"enumeration":{"PROCES":"PROCES"}}',
  454. $restrictions = @json_decode($field['xsdRestrictions'], $assoc = true);
  455. if (!empty($restrictions)) {
  456. if (!empty($restrictions['enumeration'])) {
  457. $sqlRestrictions[] = "{$sqlTablePrefix}.`{$field['fieldNamespace']}` in (" . implode(",", array_map([DB::getPDO(), 'quote'], array_keys($restrictions['enumeration']))) . ")";
  458. }
  459. }
  460. return $sqlRestrictions;
  461. }, $localFieldsWithRestrictions),
  462. function ($ret, $cur) {
  463. return array_merge($ret, array_filter($cur, ['V', 'filterNotEmpty']));
  464. },
  465. []
  466. )
  467. : '';
  468. DBG::nicePrint($localFieldsWithRestrictions, "\$localFieldsWithRestrictions");
  469. DBG::nicePrint($sqlWhereFromRestrictions, "\$sqlWhereFromRestrictions");
  470. $sqlWhereFromRestrictions = (!empty($sqlWhereFromRestrictions)) ? implode(" and ", $sqlWhereFromRestrictions) : "1=1";
  471. $pkField = 'ID'; // TODO: primaryKeyField into SystemObject structure
  472. $rootTableName = $item['_rootTableName'];
  473. $sqlFunBody = (!empty($sqlWhereFromRestrictions))
  474. ? " RETURN IF(
  475. (select count(1) as cnt from `{$rootTableName}` root where root.`{$pkField}` = pk and {$sqlWhereFromRestrictions}) > 0
  476. , 1, 0)
  477. "
  478. : " RETURN 1; ";
  479. return $sqlFunBody;
  480. }
  481. public static function getInstanceId($namespace) {
  482. return InstanceConfig::getInstanceConfig($namespace)['id'];
  483. }
  484. public static function getInstanceConfig($namespace) { // @returns { id, namespace, rootNamespace, idInstanceBase, _createdAt }
  485. return InstanceConfig::getInstanceConfig($namespace);
  486. }
  487. public static function getInstanceTable($namespace) { // @returns tableName with struct { pk, idInstance, _createdAt }
  488. return InstanceConfig::getInstanceTable($namespace);
  489. }
  490. public static function getRootNamespace($namespace) { // TODO: works only for relative urls! - mv to Acl->getRootNamespace
  491. Lib::loadClass('SchemaFactory');
  492. try {
  493. $objectItem = SchemaFactory::loadDefaultObject('SystemObject')->getItem($namespace);
  494. } catch (Exception $e) {
  495. throw new Exception("Object not installed '{$namespace}'");
  496. }
  497. if (!$objectItem['isStructInstalled']) throw new Exception("Object structure not installed '{$namespace}'");
  498. if ($objectItem['idDatabase'] != DB::getPDO()->getZasobId()) {
  499. if ('StorageAcl' === $objectItem['_type']) {
  500. DBG::log("getRootNamespace...");
  501. return $objectItem['namespace'];
  502. }
  503. else {
  504. throw new Exception("Only default_db supported"); // TODO: support more Sources
  505. }
  506. }
  507. return "default_db/{$objectItem['_rootTableName']}";
  508. }
  509. public static function getNamespaceSiblings($namespace) {
  510. return InstanceConfig::getNamespaceSiblings($namespace);
  511. }
  512. public static function getFeatureNamespaces($namespace, $pk) {
  513. return InstanceConfig::getFeatureNamespaces($namespace, $pk);
  514. }
  515. // @params $from - ( ACL | tableName | namespace | etc... - only ACL)
  516. public static function query($from, $prefix = 't') {
  517. Lib::loadClass('AclQueryBuilder');
  518. $query = new AclQueryBuilder();
  519. $query->from($from, $prefix);
  520. return $query;
  521. }
  522. /**
  523. * @param mixed $object - Core_AclBase or string - namespace
  524. * @return Core_AclFields
  525. */
  526. public static function getObjectFields($object) {
  527. // TODO: try to get structure from `CRM_#CACHE_ACL_OBJECT_FIELD`
  528. // if ($object is instance Core_AclBase) {
  529. // if ($object->isStructInstalled) then get structure from `CRM_#CACHE_ACL_OBJECT_FIELD` and put into Core_AclFields
  530. // else get from $object->getFields() and put into Core_AclFields
  531. }
  532. public static function canUserReadObject($idUser, $aclOrIdZasob) {
  533. throw new Exception("TODO: canUserReadObjec({$idUser}, {$aclOrIdZasob})");
  534. }
  535. public static function canUserCreateObject($idUser, $aclOrIdZasob) {
  536. throw new Exception("TODO: canUserCreateObjec({$idUser}, {$aclOrIdZasob})");
  537. }
  538. public static function canUserWriteObject($idUser, $aclOrIdZasob) {
  539. throw new Exception("TODO: canUserWriteObjec({$idUser}, {$aclOrIdZasob})");
  540. }
  541. public static function canUserReadObjectField($idUser, $aclOrIdZasob, $fieldNameOrXPath) {
  542. throw new Exception("TODO: canUserReadObjectFiel({$idUser}, {$aclOrIdZasob}, {$fieldNameOrXPath})");
  543. }
  544. public static function canUserCreateObjectField($idUser, $aclOrIdZasob, $fieldNameOrXPath) {
  545. throw new Exception("TODO: canUserCreateObjectFiel({$idUser}, {$aclOrIdZasob}, {$fieldNameOrXPath})");
  546. }
  547. public static function canUserWriteObjectField($idUser, $aclOrIdZasob, $fieldNameOrXPath) {
  548. throw new Exception("TODO: canUserWriteObjectFiel({$idUser}, {$aclOrIdZasob}, {$fieldNameOrXPath})");
  549. }
  550. // TODO: replace below:
  551. // AclBase->canCreateField
  552. // AclBase->canReadField
  553. // AclBase->canReadObjectField
  554. // AclBase->canWriteField
  555. // AclBase->canWriteObjectField
  556. // AclBase->canWriteRecord
  557. // AclBase->canReadRecord
  558. }