ACL.php 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580
  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. static function getRefConfig($rootObjectNamespace, $childName) { // @return Type_RefConfig or throws Exception
  207. return RefConfig::getRefConfig($rootObjectNamespace, $childName);
  208. }
  209. public static function getRefTable($rootObjectNamespace, $childName) { // TODO: RMME - use getRefConfig
  210. static $cacheRefTables = array();
  211. DBG::log("DBG get ref table ({$rootObjectNamespace}, {$childName}) ...");
  212. $rootObjectNamespace = ACL::getBaseNamespace($rootObjectNamespace);
  213. $cacheKey = "{$rootObjectNamespace}/{$childName}";
  214. if (array_key_exists($cacheKey, $cacheRefTables)) return $cacheRefTables[$cacheKey];
  215. $rootAcl = self::getAclByNamespace($rootObjectNamespace);
  216. // $item = SchemaFactory::loadDefaultObject('SystemObject')->getItem($rootObjectNamespace, [ 'propertyName' => '*,field' ]);
  217. if (!($rootAcl instanceof AntAclBase)) throw new Exception("Ref allowed only for AntAcl objects");
  218. $refConfig = RefConfig::getRefConfig($rootObjectNamespace, $childName);
  219. $cacheRefTables[$cacheKey] = $refConfig->tableName;
  220. return $cacheRefTables[$cacheKey];
  221. }
  222. public static function getRefSource($rootObjectNamespace, $childName) { // CRM_REF_CONFIG
  223. $rootObjectNamespace = ACL::getBaseNamespace($rootObjectNamespace);
  224. $refConfig = RefConfig::fetch($rootObjectNamespace, $childName);
  225. return $refConfig->source;
  226. }
  227. static function addRef($namespace, $remoteTypeName, $pk, $remotePk) {
  228. self::addListRef($namespace, $remoteTypeName, $pk, [ $remotePk ]);
  229. }
  230. static function addListRef($namespace, $remoteTypeName, $pk, $listRemotePk) {
  231. // $refTable = ACL::getRefTable($namespace, $remoteTypeName); // TODO: RefConfig::fetch($namespace, $remoteTypeName);
  232. $refConfig = RefConfig::getRefConfig($namespace, $remoteTypeName);
  233. if ('table' !== $refConfig->source) throw new HttpException("Not implemented ref source type", 501);
  234. $refTable = $refConfig->tableName;
  235. foreach ($listRemotePk as $remotePk) {
  236. DB::getPDO()->insertIgnore($refTable, [ 'PRIMARY_KEY' => $pk, 'REMOTE_PRIMARY_KEY' => $remotePk ]);
  237. }
  238. $refLogTable = RefConfig::getRefEventLogTable($namespace, $remoteTypeName);
  239. foreach ($listRemotePk as $remotePk) {
  240. DB::getPDO()->insert($refLogTable, [
  241. 'PRIMARY_KEY' => $pk,
  242. 'REMOTE_PRIMARY_KEY' => $remotePk,
  243. 'REMOTE_TYPENAME' => $remoteTypeName,
  244. 'A_STATUS' => "NORMAL",
  245. // 'TRANSACTION_ID' => 0,
  246. ]);
  247. }
  248. }
  249. static function removeRef($namespace, $remoteTypeName, $pk, $remotePk) {
  250. self::removeListRef($namespace, $remoteTypeName, $pk, [ $remotePk ]);
  251. }
  252. static function removeListRef($namepace, $remoteTypeName, $pk, $listRemotePk) {
  253. // $refTable = ACL::getRefTable($namepace, $remoteTypeName); // TODO: RefConfig::fetch($namepace, $remoteTypeName);
  254. $refConfig = RefConfig::getRefConfig($namespace, $remoteTypeName);
  255. if ('table' !== $refConfig->source) throw new HttpException("Not implemented ref source type", 501);
  256. $refTable = $refConfig->tableName;
  257. foreach ($listRemotePk as $remotePk) {
  258. DB::getPDO()->execSql(" delete from `{$refTable}` where PRIMARY_KEY = :pk and REMOTE_PRIMARY_KEY = :remote_pk ", [
  259. ':pk' => $pk,
  260. ':remote_pk' => $remotePk
  261. ]);
  262. }
  263. $refLogTable = RefConfig::getRefEventLogTable($namepace, $remoteTypeName);
  264. foreach ($listRemotePk as $remotePk) {
  265. DB::getPDO()->insert($refLogTable, [
  266. 'PRIMARY_KEY' => $pk,
  267. 'REMOTE_PRIMARY_KEY' => $remotePk,
  268. 'REMOTE_TYPENAME' => $remoteTypeName,
  269. 'A_STATUS' => "DELETED",
  270. // 'TRANSACTION_ID' => 0,
  271. ]);
  272. }
  273. }
  274. public static function decodeAppInfoJson($appInfoJsonString) {
  275. $appInfo = @json_decode($appInfoJsonString, $assoc = true);
  276. if (null == $appInfo && 0 !== json_last_error()) throw new Exception("Parsing Json failed: " . json_last_error());
  277. return $appInfo;
  278. }
  279. public static function generateRefSelectSqlByFlatRelationCache($rootObjectNamespace, $childName) { // CRM_REF_CONFIG
  280. $appInfo = DB::getPDO()->fetchValue("
  281. select f.appInfo
  282. from `CRM_#CACHE_ACL_OBJECT_FIELD` f
  283. where f.objectNamespace = :objectNamespace
  284. and f.fieldNamespace = :fieldNamespace
  285. ", [
  286. ':objectNamespace' => $rootObjectNamespace,
  287. ':fieldNamespace' => $childName,
  288. ]);
  289. if (!$appInfo) throw new Exception("Missing app:info for field '{$rootObjectNamespace}/{$childName}'");
  290. $appInfo = ACL::decodeAppInfoJson($appInfo);
  291. if (empty($appInfo)) throw new Exception("Empty app:info for field '{$rootObjectNamespace}/{$childName}'");
  292. DBG::log(['$appInfo'=>$appInfo, '$rootObjectNamespace'=>$rootObjectNamespace, '$childName'=>$childName], 'array', "\$appInfo");
  293. $rootAcl = self::getAclByNamespace($rootObjectNamespace);
  294. $childXsdType = $rootAcl->getXsdFieldType($childName);
  295. list($typePrefix, $childNamespace) = explode(':', $childXsdType, 2);
  296. switch ($typePrefix) {
  297. case 'ref_uri': $childAcl = self::getAclByNamespace($childNamespace); break;
  298. case 'ref': $childAcl = self::getAclByTypeName($childNamespace); break;
  299. default: throw new Exception("Expected ref type for field '{$childName}' in object '{$rootObjectNamespace}'");
  300. }
  301. $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
  302. $rootPrimaryKeyField = $rootAcl->getPrimaryKeyField();
  303. $childPrimaryKeyField = $childAcl->getPrimaryKeyField();
  304. $rootTableName = $rootAcl->getRootTableName();
  305. $childTableName = $childAcl->getRootTableName();
  306. // '$appInfo' => [
  307. // 'flat_relation_cache' => [
  308. // 'source' => [
  309. // '@name' => 'ID',
  310. // '@xpath' => 'default_db__x3A__CRM_WSKAZNIK:CRM_WSKAZNIK/ID_PROCES',
  311. // ),
  312. // ),
  313. // ),
  314. // '$rootObjectNamespace' => 'default_db/CRM_PROCES/PROCES',
  315. // '$childName' => 'default_db__x3A__CRM_WSKAZNIK:CRM_WSKAZNIK',
  316. // '$appInfo' => [
  317. // 'flat_relation_cache' => [
  318. // 'source' => [
  319. // '@name' => 'ID',
  320. // '@xpath' => 'default_db__x3A__CRM_PROCES:PROCES/PARENT_ID',
  321. // ),
  322. // ),
  323. // ),
  324. // '$rootObjectNamespace' => 'default_db/CRM_PROCES/PROCES',
  325. // '$childName' => 'default_db__x3A__CRM_PROCES:PROCES',
  326. $appInfoRootFieldName = null;
  327. $appInfoChildFieldName = null;
  328. {
  329. if (empty($appInfo['flat_relation_cache']['source']['@name'])) throw new Exception("Missing flat_relation_cache/source/@name");
  330. if (empty($appInfo['flat_relation_cache']['source']['@xpath'])) throw new Exception("Missing flat_relation_cache/source/@xpath");
  331. $appInfoName = $appInfo['flat_relation_cache']['source']['@name'];
  332. $appInfoXpath = $appInfo['flat_relation_cache']['source']['@xpath'];
  333. // $rootNs = $rootAcl->getNamespace()
  334. if ("{$childName}/" === substr($appInfoXpath, 0, strlen("{$childName}/"))) {
  335. $appInfoRootFieldName = substr($appInfoXpath, strlen("{$childName}/"));
  336. $appInfoChildFieldName = $appInfoName;
  337. } else {
  338. throw new Exception("TODO parse flat_relation_cache");
  339. }
  340. }
  341. if (!$appInfoRootFieldName || !$appInfoChildFieldName) throw new Exception("Error Processing flat_relation_cache");
  342. $sqlWhereFromRestrictions = [];
  343. DBG::log(['root'=>$rootAcl->getFields(), 'child'=>$childAcl->getFields()], 'array', "rootAcl and childAcl fields - xsdRestrictions");
  344. if ($rootAcl instanceof AntAclBase && $childAcl instanceof AntAclBase) {
  345. $rootLocalFieldsWithRestrictions = array_filter($rootAcl->getFields(), function ($field) {
  346. if (!$field['isLocal']) return false;
  347. if (empty($field['xsdRestrictions'])) return false;
  348. if ('[]' == $field['xsdRestrictions']) return false;
  349. return true;
  350. });
  351. $childLocalFieldsWithRestrictions = array_filter($childAcl->getFields(), function ($field) {
  352. if (!$field['isLocal']) return false;
  353. if (empty($field['xsdRestrictions'])) return false;
  354. if ('[]' == $field['xsdRestrictions']) return false;
  355. return true;
  356. });
  357. DBG::log(['root'=>$rootLocalFieldsWithRestrictions, 'child'=>$childLocalFieldsWithRestrictions], 'array', "root and child fields with xsdRestrictions");
  358. if (!empty($rootLocalFieldsWithRestrictions)) {
  359. $sqlTablePrefix = 'root';
  360. $sqlWhereFromRestrictions = array_reduce(
  361. array_map(function ($field) use ($sqlTablePrefix) {
  362. $sqlRestrictions = [];
  363. // 'xsdRestrictions' => '{"enumeration":{"PROCES":"PROCES"}}',
  364. $restrictions = @json_decode($field['xsdRestrictions'], $assoc = true);
  365. if (!empty($restrictions)) {
  366. if (!empty($restrictions['enumeration'])) {
  367. $sqlRestrictions[] = "{$sqlTablePrefix}.`{$field['fieldNamespace']}` in (" . implode(",", array_map([DB::getPDO(), 'quote'], array_keys($restrictions['enumeration']))) . ")";
  368. }
  369. }
  370. return $sqlRestrictions;
  371. }, $rootLocalFieldsWithRestrictions),
  372. function ($ret, $cur) {
  373. return array_merge($ret, array_filter($cur, ['V', 'filterNotEmpty']));
  374. },
  375. $sqlWhereFromRestrictions
  376. );
  377. }
  378. if (!empty($childLocalFieldsWithRestrictions)) {
  379. $sqlTablePrefix = 'child';
  380. $sqlWhereFromRestrictions = array_reduce(
  381. array_map(function ($field) use ($sqlTablePrefix) {
  382. $sqlRestrictions = [];
  383. // 'xsdRestrictions' => '{"enumeration":{"PROCES":"PROCES"}}',
  384. $restrictions = @json_decode($field['xsdRestrictions'], $assoc = true);
  385. if (!empty($restrictions)) {
  386. if (!empty($restrictions['enumeration'])) {
  387. $sqlRestrictions[] = "{$sqlTablePrefix}.`{$field['fieldNamespace']}` in (" . implode(",", array_map([DB::getPDO(), 'quote'], array_keys($restrictions['enumeration']))) . ")";
  388. }
  389. }
  390. return $sqlRestrictions;
  391. }, $childLocalFieldsWithRestrictions),
  392. function ($ret, $cur) {
  393. return array_merge($ret, array_filter($cur, ['V', 'filterNotEmpty']));
  394. },
  395. $sqlWhereFromRestrictions
  396. );
  397. }
  398. }
  399. $sqlWhereFromRestrictions = (!empty($sqlWhereFromRestrictions)) ? implode(" and ", $sqlWhereFromRestrictions) : "1=1";
  400. $sqlChildFieldName = $childAcl->getSqlFieldName($appInfoRootFieldName);
  401. $sql = "
  402. select root.{$rootPrimaryKeyField} as PRIMARY_KEY
  403. , child.{$childPrimaryKeyField} as REMOTE_PRIMARY_KEY
  404. , '' as REMOTE_TYPENAME
  405. , 'WAITING' as A_STATUS
  406. , 0 as TRANSACTION_ID
  407. , {$lastActionDateField} as A_LAST_ACTION_DATE
  408. from `{$rootTableName}` root
  409. join `{$childTableName}` child on(child.{$sqlChildFieldName} = root.{$appInfoChildFieldName})
  410. where {$sqlWhereFromRestrictions}
  411. ";
  412. DBG::log($sql, 'sql', "generateRefSelectSqlByFlatRelationCache");
  413. return $sql;
  414. }
  415. public static function getBackRefList($namespace) {
  416. if (!$namespace) throw new Exception("Missing namespace");
  417. return DB::getPDO()->fetchAll("
  418. select c.ROOT_OBJECT_NS as namespace
  419. , i.id as idInstance
  420. from CRM_REF_CONFIG c
  421. join CRM_INSTANCE_CONFIG i on ( i.namespace = c.ROOT_OBJECT_NS )
  422. where ( c.CHILD_NS = :namespace )
  423. and c.A_STATUS = 'NORMAL'
  424. ", [
  425. ':namespace' => $namespace,
  426. ]);
  427. }
  428. public static function getRefList($namespace) {
  429. if (!$namespace) throw new Exception("Missing namespace");
  430. return DB::getPDO()->fetchAll("
  431. select c.CHILD_NS as namespace
  432. , i.id as idInstance
  433. from CRM_REF_CONFIG c
  434. join CRM_INSTANCE_CONFIG i on ( i.namespace = c.CHILD_NS )
  435. where ( c.ROOT_OBJECT_NS = :namespace )
  436. and c.A_STATUS = 'NORMAL'
  437. ", [
  438. ':namespace' => $namespace,
  439. ]);
  440. }
  441. public static function fetchRefs($namespace, $primaryKey, $childNamespace, $params = []) { // TODO: $params: limit, total
  442. if (!$namespace) throw new Exception("Missing namespace");
  443. if (!$childNamespace) throw new Exception("Missing child namespace");
  444. if (!$primaryKey) throw new Exception("Missing primary key");
  445. $childTypeName = Api_WfsNs::toTypeName($childNamespace);
  446. $refConf = ACL::getRefConfig($namespace, $childTypeName);
  447. $refTable = $refConf->tableName; // ACL::getRefTable($namespace, $childTypeName);
  448. if (V::get('total', false, $params)) {
  449. return (int)DB::getPDO()->fetchValue("
  450. select count( DISTINCT REMOTE_PRIMARY_KEY ) as cnt
  451. from `{$refTable}`
  452. where PRIMARY_KEY = :primary_key
  453. and A_STATUS not in ('DELETED')
  454. ", [ ':primary_key' => $primaryKey ]);
  455. }
  456. return DB::getPDO()->fetchValuesList("
  457. select REMOTE_PRIMARY_KEY
  458. from `{$refConf->tableName}`
  459. where PRIMARY_KEY = :primaryKey
  460. and A_STATUS not in ('DELETED')
  461. group by REMOTE_PRIMARY_KEY
  462. ", [ ':primaryKey' => $primaryKey ]);
  463. // TODO: order by SORT_PRIO
  464. }
  465. public static function fetchBackRefs($namespace, $primaryKey, $parentNamespace, $params = []) { // TODO: $params: limit, total
  466. if (!$namespace) throw new Exception("Missing namespace");
  467. if (!$parentNamespace) throw new Exception("Missing parent namespace");
  468. if (!$primaryKey) throw new Exception("Missing primary key");
  469. $typeName = Api_WfsNs::typeName($namespace);
  470. $refTable = ACL::getRefTable($parentNamespace, $typeName);
  471. if (V::get('total', false, $params)) {
  472. 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 ]);
  473. }
  474. throw new Exception("TODO: fetch back refs from '{$namespace}' where primaryKey({$primaryKey}) by refTable({$refTable})");
  475. }
  476. static function generateSqlWhereFromFieldsWithRestrictions($fieldsRestrictions, $sqlTablePrefix = 't') {
  477. return InstanceConfig::generateSqlWhereFromFieldsWithRestrictions($fieldsRestrictions, $sqlTablePrefix);
  478. }
  479. static function generateSqlWhereFromFieldRestrictions($fields, $sqlTablePrefix = 't') {
  480. return InstanceConfig::generateSqlWhereFromFieldRestrictions($fields, $sqlTablePrefix);
  481. }
  482. static function getInstanceId($namespace) { // @return int
  483. return InstanceConfig::getInstanceId($namespace);
  484. }
  485. static function getInstanceConfig($namespace) { // @return Type_InstanceConfig
  486. return InstanceConfig::getInstanceConfig($namespace);
  487. }
  488. static function getInstanceTable($namespace) { // @return tableName with struct { pk, idInstance, _createdAt }
  489. return InstanceConfig::getInstanceTable($namespace);
  490. }
  491. static function getInstanceNamespaceById($idInstance) {
  492. return InstanceConfig::getInstanceNamespaceById($idInstance);
  493. }
  494. static function getRootNamespace($namespace) { // TODO: works only for relative urls! - mv to Acl->getRootNamespace
  495. return InstanceConfig::getRootNamespace($namespace);
  496. }
  497. static function getNamespaceSiblings($namespace) {
  498. return InstanceConfig::getNamespaceSiblings($namespace);
  499. }
  500. static function getFeatureNamespaces($namespace, $pk) {
  501. return InstanceConfig::getFeatureNamespaces($namespace, $pk);
  502. }
  503. // @params $from - ( ACL | tableName | namespace | etc... - only ACL)
  504. public static function query($from, $prefix = 't') {
  505. Lib::loadClass('AclQueryBuilder');
  506. $query = new AclQueryBuilder();
  507. $query->from($from, $prefix);
  508. return $query;
  509. }
  510. /**
  511. * @param mixed $object - Core_AclBase or string - namespace
  512. * @return Core_AclFields
  513. */
  514. public static function getObjectFields($object) {
  515. // TODO: try to get structure from `CRM_#CACHE_ACL_OBJECT_FIELD`
  516. // if ($object is instance Core_AclBase) {
  517. // if ($object->isStructInstalled) then get structure from `CRM_#CACHE_ACL_OBJECT_FIELD` and put into Core_AclFields
  518. // else get from $object->getFields() and put into Core_AclFields
  519. }
  520. public static function canUserReadObject($idUser, $aclOrIdZasob) {
  521. throw new Exception("TODO: canUserReadObjec({$idUser}, {$aclOrIdZasob})");
  522. }
  523. public static function canUserCreateObject($idUser, $aclOrIdZasob) {
  524. throw new Exception("TODO: canUserCreateObjec({$idUser}, {$aclOrIdZasob})");
  525. }
  526. public static function canUserWriteObject($idUser, $aclOrIdZasob) {
  527. throw new Exception("TODO: canUserWriteObjec({$idUser}, {$aclOrIdZasob})");
  528. }
  529. public static function canUserReadObjectField($idUser, $aclOrIdZasob, $fieldNameOrXPath) {
  530. throw new Exception("TODO: canUserReadObjectFiel({$idUser}, {$aclOrIdZasob}, {$fieldNameOrXPath})");
  531. }
  532. public static function canUserCreateObjectField($idUser, $aclOrIdZasob, $fieldNameOrXPath) {
  533. throw new Exception("TODO: canUserCreateObjectFiel({$idUser}, {$aclOrIdZasob}, {$fieldNameOrXPath})");
  534. }
  535. public static function canUserWriteObjectField($idUser, $aclOrIdZasob, $fieldNameOrXPath) {
  536. throw new Exception("TODO: canUserWriteObjectFiel({$idUser}, {$aclOrIdZasob}, {$fieldNameOrXPath})");
  537. }
  538. // TODO: replace below:
  539. // AclBase->canCreateField
  540. // AclBase->canReadField
  541. // AclBase->canReadObjectField
  542. // AclBase->canWriteField
  543. // AclBase->canWriteObjectField
  544. // AclBase->canWriteRecord
  545. // AclBase->canReadRecord
  546. }