UserAcl.php 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631
  1. <?php
  2. Lib::loadClass('DB');
  3. Lib::loadClass('UsersHelper');
  4. Lib::loadClass('ProcesHelper');
  5. Lib::loadClass('TableAcl');
  6. Lib::loadClass('SchemaReader');
  7. Lib::loadClass('SchemaFactory');
  8. Lib::loadClass('DBG');
  9. class UserAcl {
  10. public $_user_id;
  11. public $_use_cache = false;
  12. public $_session_id = false;
  13. /**
  14. * User groups (cached)
  15. */
  16. public $_groups = array();
  17. public $_proces_ids = array();
  18. public $_proces_tree_flat = array();
  19. public $_proces_used_ids = array();
  20. public $_proces_used_map = array();
  21. public $_proces_init_used_ids = array();
  22. function __construct($user_id, $use_cache = false, $session_id = null) {
  23. $this->_user_id = $user_id;
  24. $this->_use_cache = $use_cache;
  25. $this->_session_id = (null !== $session_id) ? $session_id : session_id();
  26. DBG::simpleLog('auth', "UserAcl::__construct {{$user_id}, {$this->_session_id}}");
  27. // try {
  28. // throw new Exception("Error Processing Request");
  29. // } catch (Exception $e) {
  30. // DBG::simpleLog('auth', "UserAcl::__construct {{$user_id}, {$this->_session_id}} trace:" . "\n" . $e->getTraceAsString());
  31. // }
  32. $this->_cache_init();
  33. }
  34. function fetchGroups() {
  35. if ($this->_user_id < 0) return false;
  36. if (!empty($this->_groups)) {
  37. return $this->_groups;
  38. }
  39. $this->_groups = $this->_cache_read('_groups');
  40. if ($this->_groups != null) {
  41. return $this->_groups;
  42. }
  43. $this->_groups = array();
  44. $this->_groups = UsersHelper::get_group_by_user($this->_user_id);
  45. $this->_cache_save('_groups', $this->_groups);
  46. return $this->_groups;
  47. }
  48. function getProcesIds() {
  49. if (!empty($this->_proces_ids)) return $this->_proces_ids;
  50. $groups = $this->fetchGroups();
  51. if (empty($groups)) {
  52. return false;
  53. }
  54. $this->_proces_ids = DB::getPDO()->fetchValuesList("
  55. select p.`ID`
  56. from `CRM_PROCES` as p
  57. left join `CRM_WSKAZNIK` as w on ( p.`ID` = w.`ID_PROCES` )
  58. where
  59. w.`ID_ZASOB` in ( " . implode(",", array_keys($groups)) . " )
  60. and w.`A_STATUS` in ( 'NORMAL', 'WAITING' )
  61. and p.`A_STATUS` in ( 'NORMAL', 'WAITING' )
  62. ");
  63. return $this->_proces_ids;
  64. }
  65. function getProcesTree() {
  66. if (!empty($this->_proces_tree_flat)) return $this->_proces_tree_flat;
  67. $listItems = DB::getPDO()->fetchAll("
  68. select p.`ID`, p.`PARENT_ID`
  69. from `CRM_PROCES` as p
  70. where p.`A_STATUS` in ( 'WAITING', 'NORMAL' )
  71. union
  72. select p.`IF_TRUE_GOTO` as ID, p.`ID` as PARENT_ID
  73. from `CRM_PROCES` as p
  74. where p.`A_STATUS` in ( 'WAITING', 'NORMAL' )
  75. and p.IF_TRUE_GOTO > 0
  76. and p.IF_TRUE_GOTO_FLAG = 'GOTO_AND_RETURN'
  77. ");
  78. // union select '83','122' union select p.`ID` as ID, p.`IF_TRUE_GOTO` as PARENT_ID from `CRM_PROCES` as p where p.`A_STATUS` in('WAITING','NORMAL') and p.IF_TRUE_GOTO>0
  79. //union select '83','122'
  80. //union select '83','2025'
  81. $this->_proces_tree_flat = [];
  82. foreach ($listItems as $item) {
  83. $this->_proces_tree_flat[$item['PARENT_ID']][] = $item['ID'];
  84. }
  85. return $this->_proces_tree_flat;
  86. }
  87. function _cache_init() {
  88. if (!$this->_use_cache) return;
  89. if (!isset($_SESSION['UserAcl_cache'])) {
  90. $_SESSION['UserAcl_cache'] = array();
  91. }
  92. else {
  93. $user_id = V::get('_user_id', 0, $_SESSION['UserAcl_cache'], 'int');
  94. if ($user_id > 0) {
  95. if ($user_id != $this->_user_id) {
  96. // clean cache if another user
  97. $_SESSION['UserAcl_cache'] = array();
  98. }
  99. }
  100. }
  101. }
  102. function _cache_clear() {
  103. if (!$this->_use_cache) return;
  104. $_SESSION['UserAcl_cache'] = array();
  105. }
  106. /**
  107. * Read data from cache.
  108. */
  109. function _cache_read($key) {
  110. if (!$this->_use_cache) return null;
  111. if (array_key_exists($key, $_SESSION['UserAcl_cache'])) {
  112. return $_SESSION['UserAcl_cache'][$key];
  113. }
  114. return null;
  115. }
  116. /**
  117. * Save data in cache.
  118. */
  119. function _cache_save($key, $value) {
  120. if (!$this->_use_cache) return;
  121. if ($key == 'foundTables') {
  122. $tblIds = array();
  123. foreach ($value as $idTable => $tableConfig) {
  124. $tblIds[] = $idTable;
  125. TableAcl::buildInstance($idTable, $tableConfig);
  126. }
  127. $value = $tblIds;
  128. }
  129. $_SESSION['UserAcl_cache'][$key] = $value;
  130. }
  131. public function getUrls() {// @require _fetchPerms
  132. static $_userUrls = null;
  133. if (null !== $_userUrls) return $_userUrls;
  134. $_userUrls = [];
  135. $filterIdProces = $this->getFilterIdProces();
  136. $userUrlAction = SchemaFactory::loadDefaultObject('UserUrlAction');
  137. $userUrlAction->setIdUser($this->_user_id);
  138. $userUrlAction->setIdProcesFilter($filterIdProces);
  139. foreach ($userUrlAction->getItems() as $url) {
  140. $_userUrls[ $url['ID_URL'] ] = $url['opis'];
  141. }
  142. return $_userUrls;
  143. }
  144. public function getObjectAcl($sourceName, $objName) {// TODO: rename $sourceName to $prefix (xml namespace - @see Core_AclHelper)
  145. if (empty($objName)) throw new Exception("Missing object name", 400);
  146. if ('default_db' == $sourceName) {
  147. $zasobTblInfo = ProcesHelper::getZasobTableInfoByUri("{$sourceName}/{$objName}");
  148. if (!$zasobTblInfo) throw new HttpException("Object not Found '{$objName}'", 404);
  149. if (!$this->hasTableAcl($zasobTblInfo->ID)) throw new HttpException("Access Denied for '{$sourceName}/{$objName}'", 403);
  150. return $this->getTableAcl($zasobTblInfo->ID);
  151. } else if ('objects' == $sourceName) {
  152. return SchemaFactory::loadDefaultObject($objName);
  153. } else if ('default_objects' == $sourceName) {
  154. return SchemaFactory::loadDefaultObject($objName);
  155. } else if ('default_db__x3A__' == substr($sourceName, 0, 17)) {
  156. $rootTableName = strtolower(substr($sourceName, 17));
  157. return SchemaFactory::loadTableObject($rootTableName, $objName);
  158. } else if ('zasob_' == substr($sourceName, 0, strlen('zasob_'))) {
  159. $idDatabase = strtolower(substr($sourceName, strlen('zasob_')));
  160. // return SchemaFactory::loadTableObject($rootTableName, $objName);
  161. if (!is_numeric($idDatabase)) throw new HttpException("Not Implemented - Database({$idDatabase})", 501);
  162. $remoteDB = DB::getPDO($idDatabase); // TODO: may throw Exception 'Config file not exists ...'
  163. DBG::log($remoteDB, 'array', "\$remoteDB");
  164. $dbType = $remoteDB->getType();
  165. switch ($dbType) {
  166. case 'mysql': {
  167. // throw new HttpException("Not Implemented - TODO idDatabase({$idDatabase}) type({$dbType})", 501);
  168. $zasobTblInfo = ProcesHelper::getZasobTableInfoByUri("{$sourceName}/{$objName}");
  169. DBG::log($zasobTblInfo, 'array', "\$zasobTblInfo");
  170. if (!$zasobTblInfo) throw new HttpException("Object not Found '{$objName}'", 404);
  171. if (!$this->hasTableAcl($zasobTblInfo->ID)) throw new HttpException("Access Denied for '{$sourceName}/{$objName}'", 403);
  172. return $this->getTableAcl($zasobTblInfo->ID);
  173. }
  174. case 'pgsql': {
  175. $zasobTblInfo = ProcesHelper::getZasobTableInfoByUri("{$sourceName}/{$objName}");
  176. DBG::log($zasobTblInfo, 'array', "\$zasobTblInfo");
  177. if (!$zasobTblInfo) throw new HttpException("Object not Found '{$objName}'", 404);
  178. if (!$this->hasTableAcl($zasobTblInfo->ID)) throw new HttpException("Access Denied for '{$sourceName}/{$objName}'", 403);
  179. return $this->getTableAcl($zasobTblInfo->ID);
  180. // throw new HttpException("Not Implemented - TODO idDatabase({$idDatabase}) type({$dbType})", 501);
  181. }
  182. default: throw new HttpException("Not Implemented - TODO idDatabase({$idDatabase}) type({$dbType})", 501);
  183. }
  184. }
  185. throw new HttpException("Not Implemented", 501);
  186. }
  187. public function getTablesAcl() {// TODO: read from `CRM_PROCES_idx_TABLE_TO_USER_VIEW`
  188. $tbls = array();
  189. $tblIds = $this->_cache_read('foundTables');
  190. foreach ($tblIds as $vTableID) {
  191. $tbls[$vTableID] = TableAcl::getInstance($vTableID);
  192. }
  193. return $tbls;
  194. }
  195. public function hasTableAcl($tableID) {// TODO: read from `CRM_PROCES_idx_TABLE_TO_USER_VIEW`
  196. $tbls = $this->_cache_read('foundTables');
  197. return (is_array($tbls) && in_array($tableID, $tbls));
  198. }
  199. public function getTableAcl($tableID) {
  200. $tblAcl = TableAcl::getInstance($tableID);
  201. if (!$tblAcl) throw new Exception("Brak obiektu nr [{$tableID}]!");
  202. $tblAcl->init();
  203. return $tblAcl;
  204. }
  205. /**
  206. * Check if perms are only for one proces.
  207. * @returns int or false
  208. */
  209. public function getPermsFiltrProcesId() {// TODO: RMME mved to getFilterIdProces
  210. return $this->getFilterIdProces();
  211. }
  212. public function getFilterIdProces() {
  213. $procesID = $this->_cache_read('permsByProcesID');
  214. return ($procesID > 0)? $procesID : false;
  215. }
  216. public function fetchAllPerms($force = false) {
  217. $this->_fetchPerms('All', $force);
  218. }
  219. public function fetchProcesPerms($procesID, $force = false) {
  220. $this->_fetchPerms($procesID, $force);
  221. }
  222. /**
  223. * @param $type - 'All', $procesID
  224. */
  225. private function _fetchPerms($type, $force = false) {
  226. $procesID = 0;// if 0 - All, alse perms by procesID
  227. $foundTbls = array();
  228. if ($force) {
  229. $this->_cache_clear();
  230. }
  231. $schemaReader = new SchemaReader();
  232. if ($type == 'All') {
  233. $procesID = 0;// if 0 - All, alse perms by procesID
  234. $schemaReader->getAll();
  235. } else if (is_numeric($type) && $type > 0) {
  236. $procesID = (int)$type;
  237. }
  238. {// fetch from schema files in SE/schema/process/*.ini.php
  239. if ($schemaReader->hasProcessConfigs()) {
  240. foreach ($schemaReader->getProcessConfigs() as $process) {
  241. DBG::_('DBG_SCH', '1', "process", $process, __CLASS__, __FUNCTION__, __LINE__ );
  242. if ($process->hasAccess()) {
  243. $tables = $process->getTables();
  244. DBG::_('DBG_SCH', '1', "tables", $tables, __CLASS__, __FUNCTION__, __LINE__ );
  245. foreach ($tables as $vTable) {
  246. $tblUri = $vTable->getUri();
  247. $zasobTblInfo = ProcesHelper::getZasobTableInfoByUri($tblUri);
  248. DBG::_('DBG_SCH', '1', "table(" . $vTable->getLabel() . ")", $zasobTblInfo, __CLASS__, __FUNCTION__, __LINE__ );
  249. if ($zasobTblInfo) {
  250. $idTable = $zasobTblInfo->ID;
  251. if (!array_key_exists($idTable, $foundTbls)) {
  252. $tableConfig = array();
  253. $tableConfig['ID_TABLE'] = $idTable;
  254. $tableConfig['db'] = $zasobTblInfo->P__ID;
  255. $tableConfig['name'] = $zasobTblInfo->DESC;
  256. $tableConfig['label'] = $zasobTblInfo->DESC_PL;
  257. $tableConfig['opis'] = $zasobTblInfo->OPIS;
  258. $foundTbls[$idTable] = $tableConfig;
  259. }
  260. $tableAcl = TableAcl::buildInstance($idTable, $foundTbls[$idTable]);
  261. $fieldsConfig = array();
  262. $fldsInfo = ProcesHelper::getZasobTableFieldsInfo($idTable);
  263. foreach ($vTable->getFields() as $field) {
  264. $fldInfo = V::get($field->getName(), null, $fldsInfo);
  265. if ($fldInfo) {
  266. if (!array_key_exists($fldInfo->ID, $fieldsConfig)) {
  267. $fieldsConfig[$fldInfo->ID] = array();
  268. $fieldsConfig[$fldInfo->ID]['ID_CELL'] = $fldInfo->ID;
  269. $fieldsConfig[$fldInfo->ID]['CELL_NAME'] = $fldInfo->DESC;
  270. $fieldsConfig[$fldInfo->ID]['CELL_DESC'] = $fldInfo->OPIS;
  271. $fieldsConfig[$fldInfo->ID]['SORT_PRIO'] = $fldInfo->SORT_PRIO;
  272. $fieldsConfig[$fldInfo->ID]['CELL_LABEL'] = $fldInfo->DESC_PL;
  273. $fieldsConfig[$fldInfo->ID]['FORM_TREAT'] = '';
  274. //$tableAcl->addField($fldInfo->ID, $fldInfo->DESC, $fldInfo->OPIS, $fldInfo->SORT_PRIO, $fldInfo->DESC_PL);
  275. }
  276. // TODO: $field->getPerms() -> PERM_R, PERM_W, ... etc.?
  277. $fieldsConfig[$fldInfo->ID]['FORM_TREAT'] .= $field->getPerms();//$tableAcl->setFieldPerms($fldInfo->ID, $field->getPerms());
  278. }
  279. }
  280. $tableAcl->initFieldsFromConfig($fieldsConfig);
  281. DBG::_('DBG_SCH', '1', "fieldsConfig({$idTable})", $fieldsConfig, __CLASS__, __FUNCTION__, __LINE__);
  282. $tableAcl->save();
  283. DBG::_('DBG_SCH', '1', "tableAcl({$idTable})", $tableAcl, __CLASS__, __FUNCTION__, __LINE__);
  284. }
  285. }
  286. }
  287. }
  288. } else {
  289. DBG::_('DBG_SCH', '1', "NO \$schemaReader->hasProcessConfigs()", null, __CLASS__, __FUNCTION__, __LINE__);
  290. }
  291. DBG::_('DBG_SCH', '1', "foundTbls", $foundTbls, __CLASS__, __FUNCTION__, __LINE__);
  292. }// fetch from schema files
  293. $this->setFilterIdProces($procesID);//$this->_cache_save('permsByProcesID', $procesID);
  294. $filterIdProces = $this->getFilterIdProces();
  295. $userConfigStorage = SchemaFactory::loadDefaultObject('UserConfig');// TODO:? UserSession
  296. $userConfigStorage->setIdUser($this->_user_id);
  297. $userConfigStorage->setIdProcesFilter($filterIdProces);
  298. $userConf = $userConfigStorage->getItem(1);// TODO:? session_id() or 'api'
  299. DBG::simpleLog('auth', "UserAcl::fetchPerms UserConf: " . str_replace('"', '', json_encode($userConf)));
  300. // 'lastLogin' => [ '@type' => 'xsd:dateTime', '@confKey' => 'auth_user_{ID_USER}' ],// TODO: store last login time
  301. // 'lastAuthCacheUpdate' => [ '@type' => 'xsd:dateTime', '@confKey' => 'acl_user_{ID_USER}_cache_update' ],
  302. $userObject = SchemaFactory::loadDefaultObject('UserObject');
  303. $userObject->setIdUser($this->_user_id);
  304. $userObject->setIdProcesFilter($filterIdProces);
  305. $userUrlAction = SchemaFactory::loadDefaultObject('UserUrlAction');
  306. $userUrlAction->setIdUser($this->_user_id);
  307. $userUrlAction->setIdProcesFilter($filterIdProces);
  308. // DB cache
  309. // TODO: session garbage collector. CRM_CONFIG: last_proces_update, user_last_req_date, last_user_acl_cache_update
  310. $lastProcesIndexer = DB::getPDO()->fetchValue(" select CONF_VAL from CRM_CONFIG where CONF_KEY = 'tbl_indexer_CRM_PROCES_last_exec_end' ");
  311. DBG::simpleLog('auth', "UserAcl::fetchPerms lastProcesIndexer: '{$lastProcesIndexer}'");
  312. if ($userConf['lastAuthCacheUpdate'] > $lastProcesIndexer) {
  313. DBG::simpleLog('auth', "UserAcl::fetchPerms skip update cache");
  314. } else {
  315. DBG::simpleLog('auth', "UserAcl::fetchPerms update cache");
  316. $userObject->updateCacheFeatures();
  317. $userUrlAction->updateCacheFeatures();
  318. $userConfigStorage->updateItem([
  319. 'ID_USER' => $this->_user_id,
  320. 'ID_PROCES' => $filterIdProces,
  321. 'lastAuthCacheUpdate' => 'NOW()'
  322. ]);
  323. }
  324. $userAccessForTables = array_map(function ($tableConfig) {
  325. $sourceNs = substr($tableConfig['namespace'], 0, strpos($tableConfig['namespace'], '/'));
  326. return array_merge($tableConfig, [
  327. '_sourceNamespace' => $sourceNs,
  328. ]);
  329. }, $userObject->getItems());
  330. DBG::simpleLog('auth', "UserAcl::fetchPerms fetched " . count($userAccessForTables) . " tables");
  331. DBG::_('DBG_SCH', '1', "userAccessForTables", $userAccessForTables, __CLASS__, __FUNCTION__, __LINE__ );
  332. foreach ($userAccessForTables as $tableConfig) {
  333. unset($tableConfig['ID']);
  334. $idTable = $tableConfig['ID_TABLE'];
  335. if (!array_key_exists($idTable, $foundTbls)) {
  336. $foundTbls[$idTable] = $tableConfig;
  337. }
  338. }
  339. $this->_cache_save('foundTables', $foundTbls);
  340. // use cache for UserUrlAction turned OFF @see getUrls()
  341. // $userAccessForUrls = $userUrlAction->getItems();
  342. // DBG::logAuth($userAccessForUrls, "_fetchPerms \$userAccessForUrls");
  343. // DBG::_('DBG_SCH', '2', "userAccessForUrls", $userAccessForUrls, __CLASS__, __FUNCTION__, __LINE__ );
  344. // $foundUrls = array();
  345. // foreach ($userAccessForUrls as $vUrlConfig) {
  346. // $foundUrls[$vUrlConfig['ID_URL']] = $vUrlConfig['opis'];
  347. // }
  348. // $this->_cache_save('foundUrls', $foundUrls);
  349. }
  350. public function setFilterIdProces($procesID) {
  351. $this->_cache_save('permsByProcesID', $procesID);
  352. }
  353. public function getPermsForTable($idTable) { // @returns [ permInfo group by ID_CELL ]; permInfo = [ ID_CELL, CELL_NAME, SORT_PRIO, PERM_R, PERM_W, PERM_... ]
  354. $sqlIdProcesListSql = $this->getUsedUserProcesIdsSql();
  355. if (!$sqlIdProcesListSql) return [];
  356. $tableCellToProcesSql = "
  357. select z.`ID` as `ID_CELL`
  358. , z.`DESC` as `CELL_NAME`
  359. , z.`DESC_PL` as `CELL_LABEL`
  360. , z.`OPIS` as `CELL_DESC`
  361. , z.`SORT_PRIO` as `SORT_PRIO`
  362. , zp.`ID` as `ID_TABLE`
  363. -- , zp.`DESC` as `TABLE_NAME`
  364. -- , wsk.`ID_PROCES` as `ID_PROCES`
  365. , sum(IF(przyp.`FORM_TREAT` & 2, 1, 0)) as PERM_R
  366. , sum(IF(przyp.`FORM_TREAT` & 4, 1, 0)) as PERM_W
  367. , sum(IF(przyp.`FORM_TREAT` & 8, 1, 0)) as PERM_X
  368. , sum(IF(przyp.`FORM_TREAT` & 16, 1, 0)) as PERM_C
  369. , sum(IF(przyp.`FORM_TREAT` & 32, 1, 0)) as PERM_S
  370. , sum(IF(przyp.`FORM_TREAT` & 64, 1, 0)) as PERM_O
  371. , sum(IF(przyp.`FORM_TREAT` & 128, 1, 0)) as PERM_V
  372. , sum(IF(przyp.`FORM_TREAT` & 256, 1, 0)) as PERM_E
  373. from `CRM_LISTA_ZASOBOW` z
  374. join `CRM_LISTA_ZASOBOW` zp on(zp.`ID`=z.`PARENT_ID` and zp.`TYPE`='TABELA' and zp.`A_STATUS` in('WAITING','NORMAL'))
  375. join `CRM_WSKAZNIK` wsk on(wsk.`ID_ZASOB`=z.`ID` and wsk.`A_STATUS` in('WAITING','NORMAL'))
  376. join `CRM_PROCES` p on(p.`ID`=wsk.`ID_PROCES` and p.`A_STATUS` in('WAITING','NORMAL'))
  377. join `CRM_PRZYPADEK` as przyp on (przyp.`ID`=wsk.`ID_PRZYPADEK`)
  378. where z.`TYPE`='KOMORKA'
  379. and z.`A_STATUS` in('WAITING','NORMAL')
  380. and zp.`ID`='{$idTable}'
  381. and wsk.`ID_PROCES` in({$sqlIdProcesListSql})
  382. -- group by z.`ID`, wsk.`ID_PROCES`
  383. group by z.`ID`
  384. order by z.`SORT_PRIO`
  385. ";
  386. $userPermsForTable = array();
  387. foreach (DB::getPDO()->fetchAll($tableCellToProcesSql) as $h) {
  388. $idCell = $h['ID_CELL'];
  389. $userPermsForTable[$idCell] = $h;
  390. }
  391. return $userPermsForTable;
  392. }
  393. public function getUsedUserGroupIds() {
  394. $idUserGroupList = User::getGroupsIds();// TODO:? $this->_user_id
  395. // TODO: acl filtr by group ids
  396. return $idUserGroupList;
  397. }
  398. public function getUsedUserProcesIdsSql() {
  399. $filterIdProces = $this->getFilterIdProces();
  400. if ($filterIdProces > 0) {
  401. return "
  402. select i.`ID_PROCES`
  403. from `CRM_PROCES_idx` i
  404. where i.`idx_MAIN_PROCES_INIT_ID`='{$filterIdProces}'
  405. ";
  406. }
  407. $idUserGroupList = $this->getUsedUserGroupIds();
  408. if (empty($idUserGroupList)) return null;
  409. $sqlIdUserGroupList = implode(",", $idUserGroupList);
  410. return "
  411. select gi.`ID_PROCES`
  412. from `CRM_PROCES_idx_GROUP_to_PROCES` gi
  413. where gi.`ID_GROUP` in({$sqlIdUserGroupList})
  414. ";
  415. }
  416. public function getProcesMaxUpdateDate($idProcesInit) {
  417. return DB::getPDO()->fetchValue("
  418. select max(p.`A_RECORD_UPDATE_DATE`) as max_update_date
  419. from `CRM_PROCES` as p
  420. where p.`ID` in(
  421. select i.`ID_PROCES`
  422. from `CRM_PROCES_idx` i
  423. where i.`idx_PROCES_INIT_ID`='{$idProcesInit}'
  424. )
  425. ");
  426. }
  427. /**
  428. * Ids List of Proces Init for user (skip filters)
  429. */
  430. public function getUserProcesInitIds() {
  431. $procesInitList = $this->getUserProcesInitList();
  432. return array_keys($procesInitList);
  433. }
  434. /**
  435. * List of Proces Init for user (skip filters)
  436. */
  437. public function getUserProcesInitList() {// TODO: read from CRM_PROCES_idx_GROUP_to_INIT_VIEW?
  438. $idUserGroupList = $this->fetchGroups();
  439. if (empty($idUserGroupList)) return [];
  440. $sqlIdUserGroupList = implode(",", array_keys($idUserGroupList));
  441. $sqlIdProcesListSql = "
  442. select gi.`ID_PROCES`
  443. from `CRM_PROCES_idx_GROUP_to_PROCES` gi
  444. where gi.`ID_GROUP` in({$sqlIdUserGroupList})
  445. ";
  446. $sqlFetchUserProcesInitList = "
  447. select p.`ID`, p.`DESC`
  448. from `CRM_PROCES_idx` i
  449. join `CRM_PROCES` p on(p.`ID`=i.`idx_PROCES_INIT_ID`)
  450. where i.`ID_PROCES` in({$sqlIdProcesListSql})
  451. group by p.`ID`
  452. order by p.`SORT_PRIO`
  453. ";
  454. return array_map(function ($row) {
  455. return $row['DESC'];
  456. }, DB::getPDO()->fetchAllByKey($sqlFetchUserProcesInitList, 'ID'));
  457. }
  458. /**
  459. * Ids List of Proces Init for user (use filters)
  460. */
  461. function getUsedUserProcesInitIds() {
  462. $usedProcesInitList = $this->getUsedUserProcesInitList();
  463. return array_keys($usedProcesInitList);
  464. }
  465. /**
  466. * List of Proces Init for user (use filters)
  467. */
  468. function getUsedUserProcesInitList() {
  469. $filterIdProces = $this->getFilterIdProces();
  470. if ($filterIdProces > 0) return $filterIdProces;
  471. $sqlIdProcesListSql = $this->getUsedUserProcesIdsSql();
  472. if (!$sqlIdProcesListSql) return [];
  473. $listItems = DB::getPDO()->fetchAll("
  474. select p.`ID`, p.`DESC`
  475. from `CRM_PROCES` p
  476. where p.`ID` in ( {$sqlIdProcesListSql} )
  477. and p.`TYPE` = 'PROCES_INIT'
  478. order by p.`SORT_PRIO`
  479. ");
  480. $usedProcesInitList = array();
  481. foreach ($listItems as $item) {
  482. $usedProcesInitList[$item['ID']] = $item['DESC'];
  483. }
  484. return $usedProcesInitList;
  485. }
  486. /**
  487. * Ids List of Proces Init for given tabel (skip filters)
  488. */
  489. public function getTableProcesInitIds($idTable) {
  490. $procesInitList = $this->getTableProcesInitList($idTable);
  491. return array_keys($procesInitList);
  492. }
  493. /**
  494. * List of Proces Init for given table (skip filters)
  495. */
  496. public function getTableProcesInitList($idTable) {
  497. $tableProcesInitList = ACL::getTableProcesInitList($idTable);
  498. if (!empty($tableProcesInitList)) {
  499. $filteredTableProcesInitList = array();
  500. $procesIds = array_keys($tableProcesInitList);
  501. if (empty($procesIds)) {
  502. DBG::log("BUG empty \$procesIds for table {$idTable}");
  503. return [];
  504. }
  505. $sqlProcesIds = implode(",", $procesIds);
  506. $userLogin = User::getLogin();
  507. $groupIds = User::getGroupsIds();
  508. if (empty($procesIds)) {
  509. DBG::log("BUG empty User Group Ids");
  510. return [];
  511. }
  512. $sqlGroupIds = implode(",", $groupIds);
  513. // $sql = " -- slow
  514. // select uiv.`ID_PROCES_INIT`, uiv.`DESC`
  515. // from `CRM_PROCES_idx_USER_to_INIT_VIEW` uiv
  516. // where uiv.`ADM_ACCOUNT`='{$userLogin}'
  517. // and uiv.`ID_PROCES_INIT` in({$sqlProcesIds})
  518. // group by uiv.`ID_PROCES_INIT`
  519. // ";
  520. $sql = "
  521. select ugiv.`ID_PROCES_INIT`, ugiv.`DESC`
  522. from `CRM_PROCES_idx_GROUP_to_INIT_VIEW` ugiv
  523. where ugiv.`ID_GROUP` in({$sqlGroupIds})
  524. and ugiv.`ID_PROCES_INIT` in({$sqlProcesIds})
  525. ";
  526. foreach (DB::getPDO()->fetchAll($sql) as $row) {
  527. $filteredTableProcesInitList[$row['ID_PROCES_INIT']] = $row['DESC'];
  528. }
  529. $tableProcesInitList = $filteredTableProcesInitList;
  530. DBG::log($filteredTableProcesInitList, 'array', "tableProcesInitList({$idTable}):filteredTableProcesInitList");
  531. }
  532. return $tableProcesInitList;
  533. }
  534. function canExecuteProcesInit($idProcesInit) {
  535. $isAllowed = false;
  536. $idProcesInit = (int)$idProcesInit;
  537. if (!$idProcesInit) return false;
  538. $idUserGroupList = $this->fetchGroups();
  539. $sqlIdUserGroupList = implode(",", array_keys($idUserGroupList));
  540. $isAlowed = DB::getPDO()->fetchValue("
  541. select count(*) as cnt
  542. from `CRM_PROCES_idx_GROUP_to_PROCES` gi
  543. join `CRM_PROCES` p on ( p.`ID` = gi.`ID_PROCES` and p.`TYPE` = 'PROCES_INIT' )
  544. where gi.`ID_GROUP` in ( {$sqlIdUserGroupList} )
  545. and gi.`ID_PROCES` = :id_proces_init
  546. ", [
  547. ':id_proces_init' => $idProcesInit,
  548. ]);
  549. return ($isAlowed > 0);
  550. }
  551. function canViewProces($idProcesInit) {
  552. $isAllowed = false;
  553. $idProcesInit = (int)$idProcesInit;
  554. if (!$idProcesInit) return false;
  555. $idUserGroupList = $this->fetchGroups();
  556. $sqlIdUserGroupList = implode(",", array_keys($idUserGroupList));
  557. $isAllowed = DB::getPDO()->fetchValue("
  558. select count(*) as cnt
  559. from `CRM_PROCES_idx_GROUP_to_PROCES_PERM` gi
  560. join `CRM_PROCES` p on ( p.`ID` = gi.`ID_PROCES` )
  561. where gi.`ID_GROUP` in ( {$sqlIdUserGroupList} )
  562. and gi.`ID_PROCES` = :id_proces_init
  563. ", [
  564. ':id_proces_init' => $idProcesInit,
  565. ]);
  566. // -- and gi.`HAS_PERM_R` = 1 -- TODO allow only with defined perm 'R'
  567. return ($isAllowed > 0);
  568. }
  569. }