ACL.php 24 KB

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