ACL.php 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703
  1. <?php
  2. Lib::loadClass('Core_AclHelper');
  3. Lib::loadClass('AntAclBase');
  4. Lib::loadClass('RefConfig');
  5. class ACL {
  6. public static $REF_TABLE_VERSION = 2;
  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) { // CRM_REF_CONFIG
  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. $childXsdType = $rootAcl->getXsdFieldType($childName);
  214. list($typePrefix, $childNamespace) = explode(':', $childXsdType, 2);
  215. DBG::log(['$childXsdType' => $childXsdType, '$typePrefix' => $typePrefix, '$childNamespace' => $childNamespace], 'array', "DBG get ref table ...");
  216. switch ($typePrefix) {
  217. case 'ref_uri': $childAcl = self::getAclByNamespace($childNamespace); break;
  218. case 'ref': $childAcl = self::getAclByTypeName($childNamespace); break;
  219. default: throw new Exception("Expected ref type for field '{$childName}' in object '{$rootObjectNamespace}'");
  220. }
  221. $refInfo = self::getRefConfig($rootObjectNamespace, $childName, $childNamespace);
  222. if ('view' === $refInfo['SOURCE']) {
  223. $refTableName = "CRM__#REF_TABLE__{$refInfo['ID']}_VIEW"; // view created by ACL::generateRefSelectSqlByFlatRelationCache
  224. } else if ('backRef' === $refInfo['SOURCE']) {
  225. $refTableName = "CRM__#REF_TABLE__{$refInfo['ID']}_VIEW"; // view created by ACL::generateRefSelectSqlByFlatRelationCache
  226. } else if ('table' === $refInfo['SOURCE']) {
  227. $refTableName = "CRM__#REF_TABLE__{$refInfo['ID']}";
  228. if ('WAITING' == $refInfo['A_STATUS']) {
  229. DB::getPDO()->execSql("
  230. CREATE TABLE IF NOT EXISTS `{$refTableName}` (
  231. `PRIMARY_KEY` int(11) NOT NULL
  232. , `REMOTE_PRIMARY_KEY` int(11) NOT NULL
  233. , `REMOTE_TYPENAME` varchar(255) NOT NULL DEFAULT ''
  234. , `A_STATUS` enum('WAITING', 'NORMAL', 'DELETED') NOT NULL DEFAULT 'WAITING'
  235. , `TRANSACTION_ID` int(11) NOT NULL
  236. , `A_LAST_ACTION_DATE` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
  237. , KEY `PRIMARY_KEY` (`PRIMARY_KEY`)
  238. , KEY `REMOTE_PRIMARY_KEY` (`REMOTE_PRIMARY_KEY`)
  239. , KEY `TRANSACTION_ID` (`TRANSACTION_ID`)
  240. ) ENGINE=MyISAM DEFAULT CHARSET=latin2 COMMENT='{$rootObjectNamespace} #REF $childName ({$childNamespace})';
  241. ");
  242. $refInfo['A_STATUS'] = "NORMAL";
  243. $refInfo['VERSION'] = self::$REF_TABLE_VERSION;
  244. $affected = DB::getPDO()->update("CRM_REF_CONFIG", 'ID', $refInfo['ID'], [
  245. 'A_STATUS' => $refInfo['A_STATUS'],
  246. 'VERSION' => $refInfo['VERSION']
  247. ]);
  248. }
  249. } else {
  250. throw new Exception("Not Implemented ref SOURCE = '{$refInfo['SOURCE']}'");
  251. }
  252. if ('0' === (string)$refInfo['VERSION']) {
  253. DBG::log($refInfo, 'array', "BUG RefConfig VERSION = 0 (ID: {$refInfo['VERSION']})");
  254. throw new Exception("Wystąpiły błędy w konfiguracji tabeli powiązań - zainstaluj ponownie obiekt");
  255. }
  256. if ($refInfo['VERSION'] < self::$REF_TABLE_VERSION) {
  257. if (1 == $refInfo['VERSION']) $refInfo = self::upgradeRefConfigFrom1to2($refInfo);
  258. }
  259. if ($refInfo['VERSION'] < self::$REF_TABLE_VERSION) throw new Exception("TODO: ref table {$refInfo['ID']} require upgrade - field '{$childName}' in object '{$rootObjectNamespace}'");
  260. $cacheRefTables[$cacheKey] = $refTableName;
  261. return $refTableName;
  262. }
  263. public static function getRefSource($rootObjectNamespace, $childName) { // CRM_REF_CONFIG
  264. $rootObjectNamespace = ACL::getBaseNamespace($rootObjectNamespace);
  265. $refInfo = self::getRefConfig($rootObjectNamespace, $childName);
  266. return V::get('SOURCE', 'table', $refInfo);
  267. }
  268. public static function decodeAppInfoJson($appInfoJsonString) {
  269. $appInfo = @json_decode($appInfoJsonString, $assoc = true);
  270. if (null == $appInfo && 0 !== json_last_error()) throw new Exception("Parsing Json failed: " . json_last_error());
  271. return $appInfo;
  272. }
  273. public static function generateRefSelectSqlByFlatRelationCache($rootObjectNamespace, $childName) { // CRM_REF_CONFIG
  274. $appInfo = DB::getPDO()->fetchValue("
  275. select f.appInfo
  276. from `CRM_#CACHE_ACL_OBJECT_FIELD` f
  277. where f.objectNamespace = '{$rootObjectNamespace}'
  278. and f.fieldNamespace = '{$childName}'
  279. ");
  280. if (!$appInfo) throw new Exception("Missing app:info for field '{$rootObjectNamespace}/{$childName}'");
  281. $appInfo = ACL::decodeAppInfoJson($appInfo);
  282. if (empty($appInfo)) throw new Exception("Empty app:info for field '{$rootObjectNamespace}/{$childName}'");
  283. DBG::log(['$appInfo'=>$appInfo, '$rootObjectNamespace'=>$rootObjectNamespace, '$childName'=>$childName], 'array', "\$appInfo");
  284. $rootAcl = self::getAclByNamespace($rootObjectNamespace);
  285. $childXsdType = $rootAcl->getXsdFieldType($childName);
  286. list($typePrefix, $childNamespace) = explode(':', $childXsdType, 2);
  287. switch ($typePrefix) {
  288. case 'ref_uri': $childAcl = self::getAclByNamespace($childNamespace); break;
  289. case 'ref': $childAcl = self::getAclByTypeName($childNamespace); break;
  290. default: throw new Exception("Expected ref type for field '{$childName}' in object '{$rootObjectNamespace}'");
  291. }
  292. $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
  293. $rootPrimaryKeyField = $rootAcl->getPrimaryKeyField();
  294. $childPrimaryKeyField = $childAcl->getPrimaryKeyField();
  295. $rootTableName = $rootAcl->getRootTableName();
  296. $childTableName = $childAcl->getRootTableName();
  297. // '$appInfo' => [
  298. // 'flat_relation_cache' => [
  299. // 'source' => [
  300. // '@name' => 'ID',
  301. // '@xpath' => 'default_db__x3A__CRM_WSKAZNIK:CRM_WSKAZNIK/ID_PROCES',
  302. // ),
  303. // ),
  304. // ),
  305. // '$rootObjectNamespace' => 'default_db/CRM_PROCES/PROCES',
  306. // '$childName' => 'default_db__x3A__CRM_WSKAZNIK:CRM_WSKAZNIK',
  307. // '$appInfo' => [
  308. // 'flat_relation_cache' => [
  309. // 'source' => [
  310. // '@name' => 'ID',
  311. // '@xpath' => 'default_db__x3A__CRM_PROCES:PROCES/PARENT_ID',
  312. // ),
  313. // ),
  314. // ),
  315. // '$rootObjectNamespace' => 'default_db/CRM_PROCES/PROCES',
  316. // '$childName' => 'default_db__x3A__CRM_PROCES:PROCES',
  317. $appInfoRootFieldName = null;
  318. $appInfoChildFieldName = null;
  319. {
  320. if (empty($appInfo['flat_relation_cache']['source']['@name'])) throw new Exception("Missing flat_relation_cache/source/@name");
  321. if (empty($appInfo['flat_relation_cache']['source']['@xpath'])) throw new Exception("Missing flat_relation_cache/source/@xpath");
  322. $appInfoName = $appInfo['flat_relation_cache']['source']['@name'];
  323. $appInfoXpath = $appInfo['flat_relation_cache']['source']['@xpath'];
  324. // $rootNs = $rootAcl->getNamespace()
  325. if ("{$childName}/" === substr($appInfoXpath, 0, strlen("{$childName}/"))) {
  326. $appInfoRootFieldName = substr($appInfoXpath, strlen("{$childName}/"));
  327. $appInfoChildFieldName = $appInfoName;
  328. } else {
  329. throw new Exception("TODO parse flat_relation_cache");
  330. }
  331. }
  332. if (!$appInfoRootFieldName || !$appInfoChildFieldName) throw new Exception("Error Processing flat_relation_cache");
  333. $sqlWhereFromRestrictions = [];
  334. DBG::log(['root'=>$rootAcl->getFields(), 'child'=>$childAcl->getFields()], 'array', "rootAcl and childAcl fields - xsdRestrictions");
  335. if ($rootAcl instanceof AntAclBase && $childAcl instanceof AntAclBase) {
  336. $rootLocalFieldsWithRestrictions = array_filter($rootAcl->getFields(), function ($field) {
  337. if (!$field['isLocal']) return false;
  338. if (empty($field['xsdRestrictions'])) return false;
  339. if ('[]' == $field['xsdRestrictions']) return false;
  340. return true;
  341. });
  342. $childLocalFieldsWithRestrictions = array_filter($childAcl->getFields(), function ($field) {
  343. if (!$field['isLocal']) return false;
  344. if (empty($field['xsdRestrictions'])) return false;
  345. if ('[]' == $field['xsdRestrictions']) return false;
  346. return true;
  347. });
  348. DBG::log(['root'=>$rootLocalFieldsWithRestrictions, 'child'=>$childLocalFieldsWithRestrictions], 'array', "root and child fields with xsdRestrictions");
  349. if (!empty($rootLocalFieldsWithRestrictions)) {
  350. $sqlTablePrefix = 'root';
  351. $sqlWhereFromRestrictions = array_reduce(
  352. array_map(function ($field) use ($sqlTablePrefix) {
  353. $sqlRestrictions = [];
  354. // 'xsdRestrictions' => '{"enumeration":{"PROCES":"PROCES"}}',
  355. $restrictions = @json_decode($field['xsdRestrictions'], $assoc = true);
  356. if (!empty($restrictions)) {
  357. if (!empty($restrictions['enumeration'])) {
  358. $sqlRestrictions[] = "{$sqlTablePrefix}.`{$field['fieldNamespace']}` in (" . implode(",", array_map([DB::getPDO(), 'quote'], array_keys($restrictions['enumeration']))) . ")";
  359. }
  360. }
  361. return $sqlRestrictions;
  362. }, $rootLocalFieldsWithRestrictions),
  363. function ($ret, $cur) {
  364. return array_merge($ret, array_filter($cur, ['V', 'filterNotEmpty']));
  365. },
  366. $sqlWhereFromRestrictions
  367. );
  368. }
  369. if (!empty($childLocalFieldsWithRestrictions)) {
  370. $sqlTablePrefix = 'child';
  371. $sqlWhereFromRestrictions = array_reduce(
  372. array_map(function ($field) use ($sqlTablePrefix) {
  373. $sqlRestrictions = [];
  374. // 'xsdRestrictions' => '{"enumeration":{"PROCES":"PROCES"}}',
  375. $restrictions = @json_decode($field['xsdRestrictions'], $assoc = true);
  376. if (!empty($restrictions)) {
  377. if (!empty($restrictions['enumeration'])) {
  378. $sqlRestrictions[] = "{$sqlTablePrefix}.`{$field['fieldNamespace']}` in (" . implode(",", array_map([DB::getPDO(), 'quote'], array_keys($restrictions['enumeration']))) . ")";
  379. }
  380. }
  381. return $sqlRestrictions;
  382. }, $childLocalFieldsWithRestrictions),
  383. function ($ret, $cur) {
  384. return array_merge($ret, array_filter($cur, ['V', 'filterNotEmpty']));
  385. },
  386. $sqlWhereFromRestrictions
  387. );
  388. }
  389. }
  390. $sqlWhereFromRestrictions = (!empty($sqlWhereFromRestrictions)) ? implode(" and ", $sqlWhereFromRestrictions) : "1=1";
  391. $sqlChildFieldName = $childAcl->getSqlFieldName($appInfoRootFieldName);
  392. $sql = "
  393. select root.{$rootPrimaryKeyField} as PRIMARY_KEY
  394. , child.{$childPrimaryKeyField} as REMOTE_PRIMARY_KEY
  395. , '' as REMOTE_TYPENAME
  396. , 'WAITING' as A_STATUS
  397. , 0 as TRANSACTION_ID
  398. , {$lastActionDateField} as A_LAST_ACTION_DATE
  399. from `{$rootTableName}` root
  400. join `{$childTableName}` child on(child.{$sqlChildFieldName} = root.{$appInfoChildFieldName})
  401. where {$sqlWhereFromRestrictions}
  402. ";
  403. DBG::log($sql, 'sql', "generateRefSelectSqlByFlatRelationCache");
  404. return $sql;
  405. }
  406. public static function getRefConfig($rootObjectNamespace, $childName, $childNamespace = null) { // CRM_REF_CONFIG
  407. $refConfig = RefConfig::fetch($rootObjectNamespace, $childName, $childNamespace)->toArray();
  408. return [
  409. 'ID' => $refConfig['id'],
  410. 'A_STATUS' => $refConfig['status'],
  411. 'VERSION' => $refConfig['version'],
  412. 'SOURCE' => $refConfig['source']
  413. ];
  414. }
  415. public static function upgradeRefConfigFrom1to2($refInfo) {
  416. if (1 == $refInfo['VERSION']) {
  417. if ('table' === $refInfo['SOURCE'] && 'NORMAL' == $refInfo['A_STATUS']) {
  418. $refTableName = "CRM__#REF_TABLE__{$refInfo['ID']}";
  419. try {
  420. DB::getPDO()->execSql(" CREATE INDEX `TRANSACTION_ID` ON `{$refTableName}` (`TRANSACTION_ID`) ");
  421. } catch (Exception $e) {
  422. DBG::log($e);
  423. }
  424. }
  425. $affected = DB::getPDO()->update("CRM_REF_CONFIG", 'ID', $refInfo['ID'], [
  426. 'VERSION' => 2
  427. ]);
  428. }
  429. return array_merge($refInfo, [
  430. 'VERSION' => 2
  431. ]);
  432. }
  433. public static function getBackRefList($namespace) {
  434. if (!$namespace) throw new Exception("Missing namespace");
  435. $nsParts = explode('/', $namespace);
  436. $typeName = array_pop($nsParts);
  437. $typeName = implode("__x3A__", $nsParts) . ":{$typeName}";
  438. return DB::getPDO()->fetchAll("
  439. select c.ROOT_OBJECT_NS as namespace
  440. , i.id as idInstance
  441. from CRM_REF_CONFIG c
  442. join CRM_INSTANCE_CONFIG i on ( i.namespace = c.ROOT_OBJECT_NS )
  443. where ( c.CHILD_NAME = :type_name or c.CHILD_NAME = :namespace )
  444. and c.A_STATUS = 'NORMAL'
  445. ", [
  446. ':type_name' => $typeName,
  447. ':namespace' => $namespace,
  448. ]);
  449. }
  450. public static function fetchRefs($namespace, $childNamespace, $primaryKey, $params = []) { // TODO: $params: limit, total
  451. if (!$namespace) throw new Exception("Missing namespace");
  452. if (!$childNamespace) throw new Exception("Missing child namespace");
  453. if (!$primaryKey) throw new Exception("Missing primary key");
  454. throw new Exception("TODO: fetch refs from '{$namespace}' where primaryKey = '{$primaryKey}'");
  455. }
  456. public static function fetchBackRefs($namespace, $primaryKey, $parentNamespace, $params = []) { // TODO: $params: limit, total
  457. if (!$namespace) throw new Exception("Missing namespace");
  458. if (!$parentNamespace) throw new Exception("Missing parent namespace");
  459. if (!$primaryKey) throw new Exception("Missing primary key");
  460. $typeName = Api_WfsNs::typeName($namespace);
  461. $refTable = ACL::getRefTable($parentNamespace, $typeName);
  462. if (V::get('total', false, $params)) {
  463. 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 ]);
  464. }
  465. throw new Exception("TODO: fetch back refs from '{$namespace}' where primaryKey({$primaryKey}) by refTable({$refTable})");
  466. }
  467. public static function generateIsInstanceFunctionBody($namespace, $item = null) {
  468. if (!$item) $item = SchemaFactory::loadDefaultObject('SystemObject')->getItem($namespace, [ 'propertyName' => '*,field' ]);
  469. if (!in_array( $item['_type'], [ 'AntAcl' ] )) return null;
  470. $sqlFunBody = " RETURN 1; ";
  471. $localFieldsWithRestrictions = array_filter($item['field'], function ($field) {
  472. if (!$field['isLocal']) return false;
  473. if (empty($field['xsdRestrictions'])) return false;
  474. if ('[]' == $field['xsdRestrictions']) return false;
  475. return true;
  476. });
  477. // TODO: get fields with minOccurs > 1 (may require select by ref)
  478. $sqlTablePrefix = 'root';
  479. $sqlWhereFromRestrictions = (!empty($localFieldsWithRestrictions))
  480. ? array_reduce(
  481. array_map(function ($field) use ($sqlTablePrefix) {
  482. $sqlRestrictions = [];
  483. // 'xsdRestrictions' => '{"enumeration":{"PROCES":"PROCES"}}',
  484. $restrictions = @json_decode($field['xsdRestrictions'], $assoc = true);
  485. if (!empty($restrictions)) {
  486. if (!empty($restrictions['enumeration'])) {
  487. $sqlRestrictions[] = "{$sqlTablePrefix}.`{$field['fieldNamespace']}` in (" . implode(",", array_map([DB::getPDO(), 'quote'], array_keys($restrictions['enumeration']))) . ")";
  488. }
  489. }
  490. return $sqlRestrictions;
  491. }, $localFieldsWithRestrictions),
  492. function ($ret, $cur) {
  493. return array_merge($ret, array_filter($cur, ['V', 'filterNotEmpty']));
  494. },
  495. []
  496. )
  497. : '';
  498. DBG::nicePrint($localFieldsWithRestrictions, "\$localFieldsWithRestrictions");
  499. DBG::nicePrint($sqlWhereFromRestrictions, "\$sqlWhereFromRestrictions");
  500. $sqlWhereFromRestrictions = (!empty($sqlWhereFromRestrictions)) ? implode(" and ", $sqlWhereFromRestrictions) : "1=1";
  501. $pkField = 'ID'; // TODO: primaryKeyField into SystemObject structure
  502. $rootTableName = $item['_rootTableName'];
  503. $sqlFunBody = (!empty($sqlWhereFromRestrictions))
  504. ? " RETURN IF(
  505. (select count(1) as cnt from `{$rootTableName}` root where root.`{$pkField}` = pk and {$sqlWhereFromRestrictions}) > 0
  506. , 1, 0)
  507. "
  508. : " RETURN 1; ";
  509. return $sqlFunBody;
  510. }
  511. public static function getInstanceId($namespace) {
  512. $conf = self::getInstanceConfig($namespace);
  513. return $conf['id'];
  514. }
  515. public static function getInstanceConfig($namespace) { // @returns { id, namespace, rootNamespace, idInstanceBase, _createdAt }
  516. try {
  517. $conf = self::fetchInstanceConfig($namespace);
  518. } catch (Exception $e) {
  519. DB::getPDO()->execSql("
  520. create table if not exists `CRM_INSTANCE_CONFIG` (
  521. `id` int(11) not null AUTO_INCREMENT,
  522. `namespace` varchar(255) NOT NULL DEFAULT '',
  523. `rootNamespace` varchar(255) NOT NULL DEFAULT '',
  524. `idInstanceBase` int(11) NOT NULL DEFAULT 0,
  525. `_createdAt` datetime NOT NULL,
  526. UNIQUE KEY `namespace` (`namespace`),
  527. KEY `rootNamespace` (`rootNamespace`),
  528. PRIMARY KEY (`id`)
  529. ) ENGINE=MyISAM DEFAULT CHARSET=latin2
  530. ");
  531. // TODO:?: `_tableInstalled` tinyint(1) not null default 0,
  532. $conf = self::fetchInstanceConfig($namespace);
  533. }
  534. if (!$conf) {
  535. $id = DB::getPDO()->insert("CRM_INSTANCE_CONFIG", [
  536. 'namespace' => $namespace,
  537. 'rootNamespace' => self::getRootNamespace($namespace),
  538. '_createdAt' => 'NOW()',
  539. ]);
  540. $conf = self::fetchInstanceConfig($namespace);
  541. }
  542. if (!$conf) throw new Exception("Instance not found in config table '{$namespace}'");
  543. return $conf;
  544. }
  545. public static function fetchInstanceConfig($namespace) {
  546. return DB::getPDO()->fetchFirst("
  547. select c.*
  548. from `CRM_INSTANCE_CONFIG` c
  549. where c.namespace = '{$namespace}'
  550. ");
  551. }
  552. public static function getRootNamespace($namespace) { // TODO: works only for relative urls! - mv to Acl->getRootNamespace
  553. Lib::loadClass('SchemaFactory');
  554. try {
  555. $objectItem = SchemaFactory::loadDefaultObject('SystemObject')->getItem($namespace);
  556. } catch (Exception $e) {
  557. throw new Exception("Object not installed '{$namespace}'");
  558. }
  559. if (!$objectItem['isStructInstalled']) throw new Exception("Object structure not installed '{$namespace}'");
  560. if ($objectItem['idDatabase'] != DB::getPDO()->getZasobId()) {
  561. if ('StorageAcl' === $objectItem['_type']) {
  562. DBG::log("getRootNamespace...");
  563. return $objectItem['namespace'];
  564. }
  565. else {
  566. throw new Exception("Only default_db supported"); // TODO: support more Sources
  567. }
  568. }
  569. return "default_db/{$objectItem['_rootTableName']}";
  570. }
  571. public static function getNamespaceSiblings($namespace) {
  572. return array_map(function ($row) {
  573. return $row['namespace'];
  574. }, DB::getPDO()->fetchAll("
  575. select s.namespace
  576. from CRM_INSTANCE_CONFIG c
  577. join CRM_INSTANCE_CONFIG s on ( s.rootNamespace = c.rootNamespace and s.namespace != c.rootNamespace )
  578. where c.namespace = :namespace
  579. ", [
  580. 'namespace' => $namespace
  581. ]));
  582. }
  583. public static function getFeatureNamespaces($namespace, $pk) {
  584. $instanceTable = self::getInstanceTable($namespace);
  585. return array_map(function ($row) {
  586. return $row['namespace'];
  587. }, DB::getPDO()->fetchAll("
  588. select c.namespace
  589. from `{$instanceTable}` i
  590. join `CRM_INSTANCE_CONFIG` c on ( c.id = i.idInstance )
  591. where i.pk = :pk
  592. ", [
  593. 'pk' => $pk,
  594. ]));
  595. }
  596. public static function getInstanceTable($namespace) { // @returns tableName with struct { pk, idInstance, _createdAt }
  597. $conf = self::getInstanceConfig($namespace);
  598. if (!empty($conf['idInstanceBase'])) return "CRM__#INSTANCE_TABLE__{$conf['idInstanceBase']}";
  599. $rootNs = $conf['rootNamespace'];
  600. $rootConf = self::getInstanceConfig($rootNs);
  601. $instanceTableName = "CRM__#INSTANCE_TABLE__{$rootConf['id']}";
  602. if (!empty($rootConf['idInstance'])) {
  603. $affected = DB::getPDO()->update("CRM_INSTANCE_CONFIG", 'rootNamespace', $rootNs, [
  604. 'idInstanceBase' => $rootConf['id']
  605. ]);
  606. return $instanceTableName;
  607. }
  608. // TODO: fetch primaryKeyType - TODO: store primaryKey and primaryKeyType in SystemObject item
  609. $pkType = 'int';
  610. DB::getPDO()->exec("
  611. CREATE TABLE IF NOT EXISTS `{$instanceTableName}` (
  612. `pk` int(11) NOT NULL COMMENT 'primary key'
  613. , `idInstance` int(11) NOT NULL
  614. , `_createdAt` datetime NOT NULL
  615. , KEY `pk` (`pk`)
  616. , KEY `idInstance` (`idInstance`)
  617. ) ENGINE=MyISAM DEFAULT CHARSET=latin2 COMMENT='{$rootNs} #INSTANCE';
  618. ");
  619. $affected = DB::getPDO()->update("CRM_INSTANCE_CONFIG", 'rootNamespace', $rootNs, [
  620. 'idInstanceBase' => $rootConf['id']
  621. ]);
  622. return $instanceTableName;
  623. }
  624. // @params $from - ( ACL | tableName | namespace | etc... - only ACL)
  625. public static function query($from, $prefix = 't') {
  626. Lib::loadClass('AclQueryBuilder');
  627. $query = new AclQueryBuilder();
  628. $query->from($from, $prefix);
  629. return $query;
  630. }
  631. /**
  632. * @param mixed $object - Core_AclBase or string - namespace
  633. * @return Core_AclFields
  634. */
  635. public static function getObjectFields($object) {
  636. // TODO: try to get structure from `CRM_#CACHE_ACL_OBJECT_FIELD`
  637. // if ($object is instance Core_AclBase) {
  638. // if ($object->isStructInstalled) then get structure from `CRM_#CACHE_ACL_OBJECT_FIELD` and put into Core_AclFields
  639. // else get from $object->getFields() and put into Core_AclFields
  640. }
  641. public static function canUserReadObject($idUser, $aclOrIdZasob) {
  642. throw new Exception("TODO: canUserReadObjec({$idUser}, {$aclOrIdZasob})");
  643. }
  644. public static function canUserCreateObject($idUser, $aclOrIdZasob) {
  645. throw new Exception("TODO: canUserCreateObjec({$idUser}, {$aclOrIdZasob})");
  646. }
  647. public static function canUserWriteObject($idUser, $aclOrIdZasob) {
  648. throw new Exception("TODO: canUserWriteObjec({$idUser}, {$aclOrIdZasob})");
  649. }
  650. public static function canUserReadObjectField($idUser, $aclOrIdZasob, $fieldNameOrXPath) {
  651. throw new Exception("TODO: canUserReadObjectFiel({$idUser}, {$aclOrIdZasob}, {$fieldNameOrXPath})");
  652. }
  653. public static function canUserCreateObjectField($idUser, $aclOrIdZasob, $fieldNameOrXPath) {
  654. throw new Exception("TODO: canUserCreateObjectFiel({$idUser}, {$aclOrIdZasob}, {$fieldNameOrXPath})");
  655. }
  656. public static function canUserWriteObjectField($idUser, $aclOrIdZasob, $fieldNameOrXPath) {
  657. throw new Exception("TODO: canUserWriteObjectFiel({$idUser}, {$aclOrIdZasob}, {$fieldNameOrXPath})");
  658. }
  659. // TODO: replace below:
  660. // AclBase->canCreateField
  661. // AclBase->canReadField
  662. // AclBase->canReadObjectField
  663. // AclBase->canWriteField
  664. // AclBase->canWriteObjectField
  665. // AclBase->canWriteRecord
  666. // AclBase->canReadRecord
  667. }