ACL.php 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816
  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 = "
  19. select tpv.`ID_PROCES`
  20. from `CRM_PROCES_idx_TABLE_TO_PROCES_VIEW` tpv
  21. where tpv.`ID_TABLE`='{$idTable}'
  22. ";
  23. $fetchTableProcesInitListSql = "
  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. ";
  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 = "
  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. ";
  69. $fetchTableProcesInitListSql = "
  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. ";
  86. return array_map(function ($row) {
  87. return $row['DESC'];
  88. }, DB::getPDO()->fetchAllByKey($fetchTableProcesInitListSql, 'ID'));
  89. }
  90. public static function getProcesInitMapTreeOnlyIds($ids) {
  91. $mapTree = array();
  92. $map = self::getProcesInitMapOnlyIds($ids);
  93. foreach ($map as $row) {
  94. if ('PROCES_INIT' == $row['TYPE']) {
  95. $mapTree[ $row['ID_PROCES'] ] = array();
  96. }
  97. }
  98. foreach ($map as $row) {
  99. if ('GOTO_AND_RETURN' == $row['TYPE']) {
  100. $mapTree[ $row['idx_MAIN_PROCES_INIT_ID'] ][ $row['ID_PROCES'] ] = array();
  101. }
  102. }
  103. foreach ($map as $row) {
  104. if ('GOTO_AND_RETURN_LVL2' == $row['TYPE']) {
  105. $mapTree[ $row['idx_MAIN_PROCES_INIT_ID'] ][ $row['idx_GOTO_LVL2_INIT_ID'] ][ $row['ID_PROCES'] ] = true;
  106. }
  107. }
  108. return $mapTree;
  109. }
  110. public static function getProcesInitMapOnlyIds($ids) {
  111. $map = array();
  112. $sqlIds = V::filter($ids, array('V', 'filterPositiveInteger'));
  113. $sqlIds = implode(',', $sqlIds);
  114. if (empty($sqlIds)) return $map;
  115. $sql = "
  116. select i.`ID_PROCES`
  117. , i.`PARENT_ID`
  118. , i.`TYPE`
  119. , i.`idx_PROCES_INIT_ID`
  120. , i.`idx_MAIN_PROCES_INIT_ID`
  121. , i.`idx_PROCES_WITH_GROUPS_ID`
  122. , IF(i.`TYPE`='GOTO_AND_RETURN_LVL2'
  123. , (select ig.`idx_PROCES_INIT_ID`
  124. from `CRM_PROCES_idx` ig
  125. where ig.`ID_PROCES`=i.`PARENT_ID`
  126. limit 1)
  127. , 0
  128. ) as idx_GOTO_LVL2_INIT_ID
  129. from `CRM_PROCES_idx` i
  130. where i.`ID_PROCES` in({$sqlIds})
  131. and i.`idx_MAIN_PROCES_INIT_ID` in({$sqlIds})
  132. ";
  133. return DB::getPDO()->fetchAll($sql);
  134. }
  135. public static function canGroupViewProces($idGroup, $idProcesInit) {
  136. $isAllowed = false;
  137. $idProcesInit = (int)$idProcesInit;
  138. if (!$idProcesInit) return false;
  139. $checkProcesAccessSql = "
  140. select count(*) as cnt
  141. from `CRM_PROCES_idx_GROUP_to_INIT_VIEW` giv
  142. where giv.`ID_GROUP` = '{$idGroup}'
  143. and giv.`ID_PROCES_INIT` = '{$idProcesInit}'
  144. ";
  145. return ( DB::getPDO()->fetchValue($checkProcesAccessSql) > 0 );
  146. }
  147. public static function getStorageByNamespace($namespace, $forceTblAclInit = false) {
  148. Lib::loadClass('Core_AclHelper');
  149. Lib::loadClass('SchemaFactory');
  150. $ns = Core_AclHelper::parseNamespaceUrl($namespace);
  151. DBG::log($ns, 'array', "parseNamespaceUrl({$namespace})");
  152. if ('default_db' == $ns['prefix']) {
  153. $acl = User::getAcl()->getObjectAcl($ns['prefix'], $ns['name']);
  154. } else if ('objects' == $ns['prefix']) {
  155. $acl = SchemaFactory::loadDefaultObject($ns['name']);
  156. } else if ('default_objects' == $ns['prefix']) {
  157. $acl = SchemaFactory::loadDefaultObject($ns['name']);
  158. } else if ('default_db__x3A__' == substr($ns['prefix'], 0, 17)) {
  159. $rootTableName = strtolower(substr($ns['prefix'], 17));
  160. $acl = SchemaFactory::loadTableObject($rootTableName, $ns['name']);
  161. } else {
  162. throw new HttpException("Not Implemented", 501);
  163. }
  164. $acl->init($forceTblAclInit);
  165. return $acl;
  166. }
  167. public static function getBaseNamespace($namespace) {
  168. // map SystemObjects__x3A__{parent}/{name} to default_objects/{name}
  169. if ('SystemObjects/' === substr($namespace, 0, strlen('SystemObjects/'))) {
  170. $exNs = explode('/', $namespace);
  171. if (3 === count($exNs)) {
  172. return "default_objects/{$exNs[2]}";
  173. }
  174. }
  175. return $namespace;
  176. }
  177. public static function getAclByNamespace($namespace, $forceTblAclInit = false) {
  178. $namespace = ACL::getBaseNamespace($namespace);
  179. return Core_AclHelper::getAclByNamespace($namespace, $forceTblAclInit);
  180. }
  181. public static function getAclByTypeName($typeName, $forceTblAclInit = false) {
  182. return Core_AclHelper::getAclByNamespace(str_replace(':', '/', $typeName), $forceTblAclInit);
  183. }
  184. public static function getNamespaceFromId($idZasob) {
  185. $sqlIdZasob = DB::getPDO()->quote($idZasob, PDO::PARAM_INT);
  186. $zasob = DB::getPDO()->fetchFirst("
  187. select z.ID, z.DESC, z.PARENT_ID
  188. from CRM_LISTA_ZASOBOW z
  189. where z.ID = {$sqlIdZasob}
  190. and z.`TYPE` = 'TABELA'
  191. and z.A_STATUS != 'DELETED'
  192. ");
  193. if (!$zasob) throw new Exception("Object not exists '{$idZasob}'");
  194. if ($zasob['PARENT_ID'] != DB::getPDO()->getZasobId()) {
  195. throw new Exception("TODO: getNamespaceFromId for remote database");
  196. }
  197. return ('default_db/' === substr($zasob['DESC'], 0, strlen('default_db/')))
  198. ? $zasob['DESC']
  199. : "default_db/{$zasob['DESC']}"
  200. ;
  201. }
  202. public static function parseNamespaceUrl($namespace) {// returns assoc array: [ 'name', 'url', 'prefix', 'sourceName' ]
  203. return Core_AclHelper::parseNamespaceUrl($namespace);
  204. }
  205. public static function getRefTable($rootObjectNamespace, $childName) { // CRM_REF_CONFIG
  206. static $cacheRefTables = array();
  207. if ($recurseCounter > 1) throw new Exception("BUG loop in ref config (SOURCE = 'backRef') for ns({$rootObjectNamespace}) child({$childName})");
  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. ) ENGINE=MyISAM DEFAULT CHARSET=latin2 COMMENT='{$rootObjectNamespace} #REF $childName ({$childNamespace})';
  240. ");
  241. $refInfo['A_STATUS'] = "NORMAL";
  242. $refInfo['VERSION'] = self::$REF_TABLE_VERSION;
  243. $affected = DB::getPDO()->update("CRM_REF_CONFIG", 'ID', $refInfo['ID'], [
  244. 'A_STATUS' => $refInfo['A_STATUS'],
  245. 'VERSION' => $refInfo['VERSION']
  246. ]);
  247. }
  248. } else {
  249. throw new Exception("Not Implemented ref SOURCE = '{$refInfo['SOURCE']}'");
  250. }
  251. if ($refInfo['VERSION'] < self::$REF_TABLE_VERSION) throw new Exception("TODO: ref table {$refInfo['ID']} require upgrade - field '{$childName}' in object '{$rootObjectNamespace}'");
  252. $cacheRefTables[$cacheKey] = $refTableName;
  253. return $refTableName;
  254. }
  255. public static function getRefSource($rootObjectNamespace, $childName) { // CRM_REF_CONFIG
  256. $rootObjectNamespace = ACL::getBaseNamespace($rootObjectNamespace);
  257. $refInfo = self::getRefConfig($rootObjectNamespace, $childName);
  258. return V::get('SOURCE', 'table', $refInfo);
  259. }
  260. public static function decodeAppInfoJson($appInfoJsonString) {
  261. $appInfo = @json_decode($appInfoJsonString, $assoc = true);
  262. if (null == $appInfo && 0 !== json_last_error()) throw new Exception("Parsing Json failed: " . json_last_error());
  263. return $appInfo;
  264. }
  265. public static function generateRefSelectSqlByBackRef($rootObjectNamespace, $childName) { // TODO: mv to generateRefSelectSqlByFlatRelationCache
  266. // TODO: generate view which is select from {replaced(pk, remote pk) on ref table from backRef}
  267. // {
  268. // DBG::nicePrint($refInfo, "\$refInfo");
  269. // DBG::nicePrint($rootObjectNamespace, "\$rootObjectNamespace");
  270. // DBG::nicePrint($childName, "\$childName");
  271. // DBG::nicePrint($childNamespace, "\$childNamespace");
  272. // $replacedObjNs = Api_WfsNs::namespaceFromTypeName($childName);
  273. // $replacedChildName = Api_WfsNs::typeName($rootObjectNamespace);
  274. // DBG::nicePrint($replacedObjNs, "\$replacedObjNs");
  275. // DBG::nicePrint($replacedChildName, "\$replacedChildName");
  276. // return ACL::getRefTable($replacedObjNs, $replacedChildName, 1);
  277. // throw new Exception("Not Implemented ref SOURCE = '{$refInfo['SOURCE']}'");
  278. // }
  279. $childNs = Api_WfsNs::namespaceFromTypeName($childName);
  280. $rootTypeName = Api_WfsNs::typeName($rootObjectNamespace);
  281. $backRefTable = ACL::getRefTable($childNs, $rootTypeName);
  282. DBG::nicePrint($backRefTable, "ACL::getRefTable({$childNs}, {$rootTypeName})");
  283. // TODO: check if ref_config is not backRef to avoid loop // $refInfo = self::getRefConfig($fieldNs, $item['typeName'], $item['typeName']);
  284. $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
  285. $sql = "
  286. select backRef.REMOTE_PRIMARY_KEY as PRIMARY_KEY
  287. , backRef.PRIMARY_KEY as REMOTE_PRIMARY_KEY
  288. , backRef.REMOTE_TYPENAME as REMOTE_TYPENAME
  289. , backRef.A_STATUS as A_STATUS
  290. , 0 as TRANSACTION_ID
  291. , {$lastActionDateField} as A_LAST_ACTION_DATE
  292. from `{$backRefTable}` backRef
  293. ";
  294. DBG::log($sql, 'sql', "generateRefSelectSqlByBackRef");
  295. return $sql;
  296. }
  297. public static function generateRefSelectSqlByFlatRelationCache($rootObjectNamespace, $childName) { // CRM_REF_CONFIG
  298. $appInfo = DB::getPDO()->fetchValue("
  299. select f.appInfo
  300. from `CRM_#CACHE_ACL_OBJECT_FIELD` f
  301. where f.objectNamespace = '{$rootObjectNamespace}'
  302. and f.fieldNamespace = '{$childName}'
  303. ");
  304. if (!$appInfo) throw new Exception("Missing app:info for field '{$rootObjectNamespace}/{$childName}'");
  305. $appInfo = ACL::decodeAppInfoJson($appInfo);
  306. if (empty($appInfo)) throw new Exception("Empty app:info for field '{$rootObjectNamespace}/{$childName}'");
  307. DBG::log(['$appInfo'=>$appInfo, '$rootObjectNamespace'=>$rootObjectNamespace, '$childName'=>$childName], 'array', "\$appInfo");
  308. $rootAcl = self::getAclByNamespace($rootObjectNamespace);
  309. $childXsdType = $rootAcl->getXsdFieldType($childName);
  310. list($typePrefix, $childNamespace) = explode(':', $childXsdType, 2);
  311. switch ($typePrefix) {
  312. case 'ref_uri': $childAcl = self::getAclByNamespace($childNamespace); break;
  313. case 'ref': $childAcl = self::getAclByTypeName($childNamespace); break;
  314. default: throw new Exception("Expected ref type for field '{$childName}' in object '{$rootObjectNamespace}'");
  315. }
  316. $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
  317. $rootPrimaryKeyField = $rootAcl->getPrimaryKeyField();
  318. $childPrimaryKeyField = $childAcl->getPrimaryKeyField();
  319. $rootTableName = $rootAcl->getRootTableName();
  320. $childTableName = $childAcl->getRootTableName();
  321. // '$appInfo' => [
  322. // 'flat_relation_cache' => [
  323. // 'source' => [
  324. // '@name' => 'ID',
  325. // '@xpath' => 'default_db__x3A__CRM_WSKAZNIK:CRM_WSKAZNIK/ID_PROCES',
  326. // ),
  327. // ),
  328. // ),
  329. // '$rootObjectNamespace' => 'default_db/CRM_PROCES/PROCES',
  330. // '$childName' => 'default_db__x3A__CRM_WSKAZNIK:CRM_WSKAZNIK',
  331. // '$appInfo' => [
  332. // 'flat_relation_cache' => [
  333. // 'source' => [
  334. // '@name' => 'ID',
  335. // '@xpath' => 'default_db__x3A__CRM_PROCES:PROCES/PARENT_ID',
  336. // ),
  337. // ),
  338. // ),
  339. // '$rootObjectNamespace' => 'default_db/CRM_PROCES/PROCES',
  340. // '$childName' => 'default_db__x3A__CRM_PROCES:PROCES',
  341. $appInfoRootFieldName = null;
  342. $appInfoChildFieldName = null;
  343. {
  344. if (empty($appInfo['flat_relation_cache']['source']['@name'])) throw new Exception("Missing flat_relation_cache/source/@name");
  345. if (empty($appInfo['flat_relation_cache']['source']['@xpath'])) throw new Exception("Missing flat_relation_cache/source/@xpath");
  346. $appInfoName = $appInfo['flat_relation_cache']['source']['@name'];
  347. $appInfoXpath = $appInfo['flat_relation_cache']['source']['@xpath'];
  348. // $rootNs = $rootAcl->getNamespace()
  349. if ("{$childName}/" === substr($appInfoXpath, 0, strlen("{$childName}/"))) {
  350. $appInfoRootFieldName = substr($appInfoXpath, strlen("{$childName}/"));
  351. $appInfoChildFieldName = $appInfoName;
  352. } else {
  353. throw new Exception("TODO parse flat_relation_cache");
  354. }
  355. }
  356. if (!$appInfoRootFieldName || !$appInfoChildFieldName) throw new Exception("Error Processing flat_relation_cache");
  357. $sqlWhereFromRestrictions = [];
  358. DBG::log(['root'=>$rootAcl->getFields(), 'child'=>$childAcl->getFields()], 'array', "rootAcl and childAcl fields - xsdRestrictions");
  359. if ($rootAcl instanceof AntAclBase && $childAcl instanceof AntAclBase) {
  360. $rootLocalFieldsWithRestrictions = array_filter($rootAcl->getFields(), function ($field) {
  361. if (!$field['isLocal']) return false;
  362. if (empty($field['xsdRestrictions'])) return false;
  363. if ('[]' == $field['xsdRestrictions']) return false;
  364. return true;
  365. });
  366. $childLocalFieldsWithRestrictions = array_filter($childAcl->getFields(), function ($field) {
  367. if (!$field['isLocal']) return false;
  368. if (empty($field['xsdRestrictions'])) return false;
  369. if ('[]' == $field['xsdRestrictions']) return false;
  370. return true;
  371. });
  372. DBG::log(['root'=>$rootLocalFieldsWithRestrictions, 'child'=>$childLocalFieldsWithRestrictions], 'array', "root and child fields with xsdRestrictions");
  373. if (!empty($rootLocalFieldsWithRestrictions)) {
  374. $sqlTablePrefix = 'root';
  375. $sqlWhereFromRestrictions = array_reduce(
  376. array_map(function ($field) use ($sqlTablePrefix) {
  377. $sqlRestrictions = [];
  378. // 'xsdRestrictions' => '{"enumeration":{"PROCES":"PROCES"}}',
  379. $restrictions = @json_decode($field['xsdRestrictions'], $assoc = true);
  380. if (!empty($restrictions)) {
  381. if (!empty($restrictions['enumeration'])) {
  382. $sqlRestrictions[] = "{$sqlTablePrefix}.`{$field['fieldNamespace']}` in (" . implode(",", array_map([DB::getPDO(), 'quote'], array_keys($restrictions['enumeration']))) . ")";
  383. }
  384. }
  385. return $sqlRestrictions;
  386. }, $rootLocalFieldsWithRestrictions),
  387. function ($ret, $cur) {
  388. return array_merge($ret, array_filter($cur, ['V', 'filterNotEmpty']));
  389. },
  390. $sqlWhereFromRestrictions
  391. );
  392. }
  393. if (!empty($childLocalFieldsWithRestrictions)) {
  394. $sqlTablePrefix = 'child';
  395. $sqlWhereFromRestrictions = array_reduce(
  396. array_map(function ($field) use ($sqlTablePrefix) {
  397. $sqlRestrictions = [];
  398. // 'xsdRestrictions' => '{"enumeration":{"PROCES":"PROCES"}}',
  399. $restrictions = @json_decode($field['xsdRestrictions'], $assoc = true);
  400. if (!empty($restrictions)) {
  401. if (!empty($restrictions['enumeration'])) {
  402. $sqlRestrictions[] = "{$sqlTablePrefix}.`{$field['fieldNamespace']}` in (" . implode(",", array_map([DB::getPDO(), 'quote'], array_keys($restrictions['enumeration']))) . ")";
  403. }
  404. }
  405. return $sqlRestrictions;
  406. }, $childLocalFieldsWithRestrictions),
  407. function ($ret, $cur) {
  408. return array_merge($ret, array_filter($cur, ['V', 'filterNotEmpty']));
  409. },
  410. $sqlWhereFromRestrictions
  411. );
  412. }
  413. }
  414. $sqlWhereFromRestrictions = (!empty($sqlWhereFromRestrictions)) ? implode(" and ", $sqlWhereFromRestrictions) : "1=1";
  415. $sqlChildFieldName = $childAcl->getSqlFieldName($appInfoRootFieldName);
  416. $sql = "
  417. select root.{$rootPrimaryKeyField} as PRIMARY_KEY
  418. , child.{$childPrimaryKeyField} as REMOTE_PRIMARY_KEY
  419. , '' as REMOTE_TYPENAME
  420. , 'WAITING' as A_STATUS
  421. , 0 as TRANSACTION_ID
  422. , {$lastActionDateField} as A_LAST_ACTION_DATE
  423. from `{$rootTableName}` root
  424. join `{$childTableName}` child on(child.{$sqlChildFieldName} = root.{$appInfoChildFieldName})
  425. where {$sqlWhereFromRestrictions}
  426. ";
  427. DBG::log($sql, 'sql', "generateRefSelectSqlByFlatRelationCache");
  428. return $sql;
  429. }
  430. public static function setRefSource($rootObjectNamespace, $childName, $source, $viewSelectSql = null) { // CRM_REF_CONFIG
  431. if (!in_array($source, ['view', 'table', 'backRef'])) throw new Exception("Wrong param source - expected 'table', 'view' or 'backRef'");
  432. if ('view' === $source && !$viewSelectSql) throw new Exception("Missing create view sql");
  433. $refInfo = self::getRefConfig($rootObjectNamespace, $childName);
  434. if (true) { // if ($source != $refInfo['SOURCE']) {
  435. if ('view' === $source) {
  436. $refTableName = "CRM__#REF_TABLE__{$refInfo['ID']}_VIEW";
  437. DB::getPDO()->execSql(" CREATE OR REPLACE DEFINER=`root`@`localhost` SQL SECURITY DEFINER VIEW `{$refTableName}` AS {$viewSelectSql} ");
  438. }
  439. if ('backRef' === $source) {
  440. $refTableName = "CRM__#REF_TABLE__{$refInfo['ID']}_VIEW";
  441. DB::getPDO()->execSql(" CREATE OR REPLACE DEFINER=`root`@`localhost` SQL SECURITY DEFINER VIEW `{$refTableName}` AS {$viewSelectSql} ");
  442. }
  443. $affected = DB::getPDO()->update("CRM_REF_CONFIG", 'ID', $refInfo['ID'], [
  444. 'SOURCE' => $source,
  445. ]);
  446. }
  447. }
  448. public static function getRefConfig($rootObjectNamespace, $childName, $childNamespace = null) { // CRM_REF_CONFIG
  449. $rootObjectNamespace = ACL::getBaseNamespace($rootObjectNamespace);
  450. if (!$childNamespace) {
  451. $rootAcl = self::getAclByNamespace($rootObjectNamespace);
  452. $childXsdType = $rootAcl->getXsdFieldType($childName);
  453. list($typePrefix, $childNamespace) = explode(':', $childXsdType, 2);
  454. DBG::log(['$childXsdType' => $childXsdType, '$typePrefix' => $typePrefix, '$childNamespace' => $childNamespace], 'array', "DBG get ref table ...");
  455. switch ($typePrefix) {
  456. case 'ref_uri': $childAcl = self::getAclByNamespace($childNamespace); break;
  457. case 'ref': $childAcl = self::getAclByTypeName($childNamespace); break;
  458. default: throw new Exception("Expected ref type for field '{$childName}' in object '{$rootObjectNamespace}'");
  459. }
  460. }
  461. $refInfo = [];// define $refInfo = [ ID, A_STATUS, VERSION ]
  462. try {// check that ref config table exists
  463. $sqlRootTableNs = DB::getPDO()->quote($rootObjectNamespace, PDO::PARAM_STR);
  464. $sqlChildName = DB::getPDO()->quote($childName, PDO::PARAM_STR);
  465. $sqlChildNamespace = DB::getPDO()->quote($childNamespace, PDO::PARAM_STR);
  466. $refInfo = DB::getPDO()->fetchFirst("
  467. select c.ID, c.A_STATUS, c.VERSION, c.SOURCE
  468. from `CRM_REF_CONFIG` c
  469. where c.ROOT_OBJECT_NS = {$sqlRootTableNs}
  470. and c.CHILD_NAME = {$sqlChildName}
  471. and c.CHILD_NS = {$sqlChildNamespace}
  472. ");
  473. } catch (Exception $e) {
  474. DB::getPDO()->execSql("
  475. CREATE TABLE IF NOT EXISTS `CRM_REF_CONFIG` (
  476. `ID` INT NOT NULL AUTO_INCREMENT
  477. , `ROOT_OBJECT_NS` VARCHAR(255) NOT NULL
  478. , `CHILD_NAME` VARCHAR(255) NOT NULL
  479. , `CHILD_NS` VARCHAR(255) NOT NULL
  480. , `A_STATUS` enum('WAITING', 'NORMAL', 'DELETED') NOT NULL DEFAULT 'WAITING'
  481. , `VERSION` int(11) NOT NULL DEFAULT 0
  482. , `A_LAST_ACTION_DATE` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
  483. , PRIMARY KEY (`ID`)
  484. ) ENGINE = MyISAM DEFAULT CHARSET=latin2;
  485. ");
  486. try {
  487. DB::getPDO()->execSql(" ALTER TABLE `CRM_REF_CONFIG` ADD `SOURCE` enum('table', 'view') not null default 'table' ");
  488. } catch (Exception $e) {
  489. DBG::log($e);
  490. }
  491. }
  492. try {
  493. DB::getPDO()->execSql(" ALTER TABLE `CRM_REF_CONFIG` CHANGE `SOURCE` `SOURCE` enum('table', 'view', 'backRef') not null default 'table' ");
  494. } catch (Exception $e) {
  495. DBG::log($e);
  496. }
  497. if (empty($refInfo)) {
  498. $refInfo = [ 'ID' => 0, 'A_STATUS' => 'WAITING', 'VERSION' => 0, 'SOURCE' => 'table' ];
  499. $refInfo['ID'] = DB::getPDO()->insert("CRM_REF_CONFIG", [
  500. 'ROOT_OBJECT_NS' => $rootObjectNamespace,
  501. 'CHILD_NAME' => $childName,
  502. 'CHILD_NS' => $childNamespace
  503. ]);
  504. }
  505. // { // TODO: fix source if ref for `SystemObjects__x3A__*` and defined flat_relation_cache - move to AclReinstall?
  506. // if ('SystemObjects__x3A__' === substr($childNamespace, 0, strlen('SystemObjects__x3A__'))) {
  507. // if ('table' === $refInfo['SOURCE']) {
  508. // $toUpdate = [
  509. // 'SOURCE' => 'view',
  510. // 'A_STATUS' => 'WAITING',
  511. // ];
  512. // DB::getPDO()->update('CRM_REF_CONFIG', 'ID', $refInfo['ID'], $toUpdate);
  513. // $refInfo = array_merge($refInfo, $toUpdate);
  514. // }
  515. // }
  516. // }
  517. if (!$refInfo['ID']) throw new Exception("Ref table not found in ref config table for field '{$childName}' in object '{$rootObjectNamespace}'");
  518. return $refInfo;
  519. }
  520. public static function getBackRefList($namespace) {
  521. if (!$namespace) throw new Exception("Missing namespace");
  522. $nsParts = explode('/', $namespace);
  523. $typeName = array_pop($nsParts);
  524. $typeName = implode("__x3A__", $nsParts) . ":{$typeName}";
  525. return DB::getPDO()->fetchAll("
  526. select c.ROOT_OBJECT_NS as namespace
  527. , i.id as idInstance
  528. from CRM_REF_CONFIG c
  529. join CRM_INSTANCE_CONFIG i on ( i.namespace = c.ROOT_OBJECT_NS )
  530. where ( c.CHILD_NAME = :type_name or c.CHILD_NAME = :namespace )
  531. and c.A_STATUS = 'NORMAL'
  532. ", [
  533. ':type_name' => $typeName,
  534. ':namespace' => $namespace,
  535. ]);
  536. }
  537. public static function getChildRefFullList($namespace) {
  538. $namespace = ACL::getBaseNamespace($namespace);
  539. if (!$namespace) throw new Exception("Missing namespace");
  540. return DB::getPDO()->fetchAll("
  541. select c.CHILD_NAME as namespace
  542. , c.A_STATUS
  543. , c.ID
  544. , c.SOURCE
  545. from CRM_REF_CONFIG c
  546. where c.ROOT_OBJECT_NS = :namespace
  547. -- and c.A_STATUS = 'NORMAL'
  548. ", [
  549. ':namespace' => $namespace,
  550. ]);
  551. }
  552. public static function updateChildRefSource($id, $source) {
  553. if (!$id) throw new Exception("Missing id");
  554. if (!in_array($source, ['view', 'table', 'backRef'])) throw new Exception("Wrong source");
  555. return DB::getPDO()->update('CRM_REF_CONFIG', 'ID', $id, [
  556. 'SOURCE' => $source
  557. ]);
  558. }
  559. public static function fetchRefs($namespace, $childNamespace, $primaryKey, $params = []) { // TODO: $params: limit, total
  560. if (!$namespace) throw new Exception("Missing namespace");
  561. if (!$childNamespace) throw new Exception("Missing child namespace");
  562. if (!$primaryKey) throw new Exception("Missing primary key");
  563. throw new Exception("TODO: fetch refs from '{$namespace}' where primaryKey = '{$primaryKey}'");
  564. }
  565. public static function fetchBackRefs($namespace, $primaryKey, $parentNamespace, $params = []) { // TODO: $params: limit, total
  566. if (!$namespace) throw new Exception("Missing namespace");
  567. if (!$parentNamespace) throw new Exception("Missing parent namespace");
  568. if (!$primaryKey) throw new Exception("Missing primary key");
  569. $typeName = Api_WfsNs::typeName($namespace);
  570. $refTable = ACL::getRefTable($parentNamespace, $typeName);
  571. if (V::get('total', false, $params)) {
  572. 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 ]);
  573. }
  574. throw new Exception("TODO: fetch back refs from '{$namespace}' where primaryKey({$primaryKey}) by refTable({$refTable})");
  575. }
  576. public static function generateIsInstanceFunctionBody($namespace, $item = null) {
  577. if (!$item) $item = SchemaFactory::loadDefaultObject('SystemObject')->getItem($namespace, [ 'propertyName' => '*,field' ]);
  578. if (!in_array( $item['_type'], [ 'AntAcl' ] )) return null;
  579. $sqlFunBody = " RETURN 1; ";
  580. $localFieldsWithRestrictions = array_filter($item['field'], function ($field) {
  581. if (!$field['isLocal']) return false;
  582. if (empty($field['xsdRestrictions'])) return false;
  583. if ('[]' == $field['xsdRestrictions']) return false;
  584. return true;
  585. });
  586. // TODO: get fields with minOccurs > 1 (may require select by ref)
  587. $sqlTablePrefix = 'root';
  588. $sqlWhereFromRestrictions = (!empty($localFieldsWithRestrictions))
  589. ? array_reduce(
  590. array_map(function ($field) use ($sqlTablePrefix) {
  591. $sqlRestrictions = [];
  592. // 'xsdRestrictions' => '{"enumeration":{"PROCES":"PROCES"}}',
  593. $restrictions = @json_decode($field['xsdRestrictions'], $assoc = true);
  594. if (!empty($restrictions)) {
  595. if (!empty($restrictions['enumeration'])) {
  596. $sqlRestrictions[] = "{$sqlTablePrefix}.`{$field['fieldNamespace']}` in (" . implode(",", array_map([DB::getPDO(), 'quote'], array_keys($restrictions['enumeration']))) . ")";
  597. }
  598. }
  599. return $sqlRestrictions;
  600. }, $localFieldsWithRestrictions),
  601. function ($ret, $cur) {
  602. return array_merge($ret, array_filter($cur, ['V', 'filterNotEmpty']));
  603. },
  604. []
  605. )
  606. : '';
  607. DBG::nicePrint($localFieldsWithRestrictions, "\$localFieldsWithRestrictions");
  608. DBG::nicePrint($sqlWhereFromRestrictions, "\$sqlWhereFromRestrictions");
  609. $sqlWhereFromRestrictions = (!empty($sqlWhereFromRestrictions)) ? implode(" and ", $sqlWhereFromRestrictions) : "1=1";
  610. $pkField = 'ID'; // TODO: primaryKeyField into SystemObject structure
  611. $rootTableName = $item['_rootTableName'];
  612. $sqlFunBody = (!empty($sqlWhereFromRestrictions))
  613. ? " RETURN IF(
  614. (select count(1) as cnt from `{$rootTableName}` root where root.`{$pkField}` = pk and {$sqlWhereFromRestrictions}) > 0
  615. , 1, 0)
  616. "
  617. : " RETURN 1; ";
  618. return $sqlFunBody;
  619. }
  620. public static function getInstanceId($namespace) {
  621. $conf = self::getInstanceConfig($namespace);
  622. return $conf['id'];
  623. }
  624. public static function getInstanceConfig($namespace) { // @returns { id, namespace, rootNamespace, idInstanceBase, _createdAt }
  625. try {
  626. $conf = self::fetchInstanceConfig($namespace);
  627. } catch (Exception $e) {
  628. DB::getPDO()->execSql("
  629. create table if not exists `CRM_INSTANCE_CONFIG` (
  630. `id` int(11) not null AUTO_INCREMENT,
  631. `namespace` varchar(255) NOT NULL DEFAULT '',
  632. `rootNamespace` varchar(255) NOT NULL DEFAULT '',
  633. `idInstanceBase` int(11) NOT NULL DEFAULT 0,
  634. `_createdAt` datetime NOT NULL,
  635. UNIQUE KEY `namespace` (`namespace`),
  636. KEY `rootNamespace` (`rootNamespace`),
  637. PRIMARY KEY (`id`)
  638. ) ENGINE=MyISAM DEFAULT CHARSET=latin2
  639. ");
  640. // TODO:?: `_tableInstalled` tinyint(1) not null default 0,
  641. $conf = self::fetchInstanceConfig($namespace);
  642. }
  643. if (!$conf) {
  644. $id = DB::getPDO()->insert("CRM_INSTANCE_CONFIG", [
  645. 'namespace' => $namespace,
  646. 'rootNamespace' => self::getRootNamespace($namespace),
  647. '_createdAt' => 'NOW()',
  648. ]);
  649. $conf = self::fetchInstanceConfig($namespace);
  650. }
  651. if (!$conf) throw new Exception("Instance not found in config table '{$namespace}'");
  652. return $conf;
  653. }
  654. public static function fetchInstanceConfig($namespace) {
  655. return DB::getPDO()->fetchFirst("
  656. select c.*
  657. from `CRM_INSTANCE_CONFIG` c
  658. where c.namespace = '{$namespace}'
  659. ");
  660. }
  661. public static function getRootNamespace($namespace) { // TODO: works only for relative urls! - mv to Acl->getRootNamespace
  662. Lib::loadClass('SchemaFactory');
  663. try {
  664. $objectItem = SchemaFactory::loadDefaultObject('SystemObject')->getItem($namespace);
  665. } catch (Exception $e) {
  666. throw new Exception("Object not installed '{$namespace}'");
  667. }
  668. if (!$objectItem['isStructInstalled']) throw new Exception("Object structure not installed '{$namespace}'");
  669. if ($objectItem['idDatabase'] != DB::getPDO()->getZasobId()) {
  670. if ('StorageAcl' === $objectItem['_type']) {
  671. DBG::log("getRootNamespace...");
  672. return $objectItem['namespace'];
  673. }
  674. else {
  675. throw new Exception("Only default_db supported"); // TODO: support more Sources
  676. }
  677. }
  678. return "default_db/{$objectItem['_rootTableName']}";
  679. }
  680. public static function getNamespaceSiblings($namespace) {
  681. return array_map(function ($row) {
  682. return $row['namespace'];
  683. }, DB::getPDO()->fetchAll("
  684. select s.namespace
  685. from CRM_INSTANCE_CONFIG c
  686. join CRM_INSTANCE_CONFIG s on ( s.rootNamespace = c.rootNamespace and s.namespace != c.rootNamespace )
  687. where c.namespace = :namespace
  688. ", [
  689. 'namespace' => $namespace
  690. ]));
  691. }
  692. public static function getFeatureNamespaces($namespace, $pk) {
  693. $instanceTable = self::getInstanceTable($namespace);
  694. return array_map(function ($row) {
  695. return $row['namespace'];
  696. }, DB::getPDO()->fetchAll("
  697. select c.namespace
  698. from `{$instanceTable}` i
  699. join `CRM_INSTANCE_CONFIG` c on ( c.id = i.idInstance )
  700. where i.pk = :pk
  701. ", [
  702. 'pk' => $pk,
  703. ]));
  704. }
  705. public static function getInstanceTable($namespace) { // @returns tableName with struct { pk, idInstance, _createdAt }
  706. $conf = self::getInstanceConfig($namespace);
  707. if (!empty($conf['idInstanceBase'])) return "CRM__#INSTANCE_TABLE__{$conf['idInstanceBase']}";
  708. $rootNs = $conf['rootNamespace'];
  709. $rootConf = self::getInstanceConfig($rootNs);
  710. $instanceTableName = "CRM__#INSTANCE_TABLE__{$rootConf['id']}";
  711. if (!empty($rootConf['idInstance'])) {
  712. $affected = DB::getPDO()->update("CRM_INSTANCE_CONFIG", 'rootNamespace', $rootNs, [
  713. 'idInstanceBase' => $rootConf['id']
  714. ]);
  715. return $instanceTableName;
  716. }
  717. // TODO: fetch primaryKeyType - TODO: store primaryKey and primaryKeyType in SystemObject item
  718. $pkType = 'int';
  719. DB::getPDO()->exec("
  720. CREATE TABLE IF NOT EXISTS `{$instanceTableName}` (
  721. `pk` int(11) NOT NULL COMMENT 'primary key'
  722. , `idInstance` int(11) NOT NULL
  723. , `_createdAt` datetime NOT NULL
  724. , KEY `pk` (`pk`)
  725. , KEY `idInstance` (`idInstance`)
  726. ) ENGINE=MyISAM DEFAULT CHARSET=latin2 COMMENT='{$rootNs} #INSTANCE';
  727. ");
  728. $affected = DB::getPDO()->update("CRM_INSTANCE_CONFIG", 'rootNamespace', $rootNs, [
  729. 'idInstanceBase' => $rootConf['id']
  730. ]);
  731. return $instanceTableName;
  732. }
  733. // @params $from - ( ACL | tableName | namespace | etc... - only ACL)
  734. public static function query($from, $prefix = 't') {
  735. Lib::loadClass('AclQueryBuilder');
  736. $query = new AclQueryBuilder();
  737. $query->from($from, $prefix);
  738. return $query;
  739. }
  740. /**
  741. * @param mixed $object - Core_AclBase or string - namespace
  742. * @return Core_AclFields
  743. */
  744. public static function getObjectFields($object) {
  745. // TODO: try to get structure from `CRM_#CACHE_ACL_OBJECT_FIELD`
  746. // if ($object is instance Core_AclBase) {
  747. // if ($object->isStructInstalled) then get structure from `CRM_#CACHE_ACL_OBJECT_FIELD` and put into Core_AclFields
  748. // else get from $object->getFields() and put into Core_AclFields
  749. }
  750. public static function canUserReadObject($idUser, $aclOrIdZasob) {
  751. throw new Exception("TODO: canUserReadObjec({$idUser}, {$aclOrIdZasob})");
  752. }
  753. public static function canUserCreateObject($idUser, $aclOrIdZasob) {
  754. throw new Exception("TODO: canUserCreateObjec({$idUser}, {$aclOrIdZasob})");
  755. }
  756. public static function canUserWriteObject($idUser, $aclOrIdZasob) {
  757. throw new Exception("TODO: canUserWriteObjec({$idUser}, {$aclOrIdZasob})");
  758. }
  759. public static function canUserReadObjectField($idUser, $aclOrIdZasob, $fieldNameOrXPath) {
  760. throw new Exception("TODO: canUserReadObjectFiel({$idUser}, {$aclOrIdZasob}, {$fieldNameOrXPath})");
  761. }
  762. public static function canUserCreateObjectField($idUser, $aclOrIdZasob, $fieldNameOrXPath) {
  763. throw new Exception("TODO: canUserCreateObjectFiel({$idUser}, {$aclOrIdZasob}, {$fieldNameOrXPath})");
  764. }
  765. public static function canUserWriteObjectField($idUser, $aclOrIdZasob, $fieldNameOrXPath) {
  766. throw new Exception("TODO: canUserWriteObjectFiel({$idUser}, {$aclOrIdZasob}, {$fieldNameOrXPath})");
  767. }
  768. // TODO: replace below:
  769. // AclBase->canCreateField
  770. // AclBase->canReadField
  771. // AclBase->canReadObjectField
  772. // AclBase->canWriteField
  773. // AclBase->canWriteObjectField
  774. // AclBase->canWriteRecord
  775. // AclBase->canReadRecord
  776. }