userrightsprofile.class.inc.php 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870
  1. <?php
  2. // Copyright (C) 2010 Combodo SARL
  3. //
  4. // This program is free software; you can redistribute it and/or modify
  5. // it under the terms of the GNU General Public License as published by
  6. // the Free Software Foundation; version 3 of the License.
  7. //
  8. // This program is distributed in the hope that it will be useful,
  9. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. // GNU General Public License for more details.
  12. //
  13. // You should have received a copy of the GNU General Public License
  14. // along with this program; if not, write to the Free Software
  15. // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
  16. /**
  17. * UserRightsProfile
  18. * User management Module, basing the right on profiles and a matrix (similar to UserRightsMatrix, but profiles and other decorations have been added)
  19. *
  20. * @author Erwan Taloc <erwan.taloc@combodo.com>
  21. * @author Romain Quetiez <romain.quetiez@combodo.com>
  22. * @author Denis Flaven <denis.flaven@combodo.com>
  23. * @license http://www.opensource.org/licenses/gpl-3.0.html LGPL
  24. */
  25. define('ADMIN_PROFILE_NAME', 'Administrator');
  26. define('PORTAL_PROFILE_NAME', 'Portal user');
  27. class UserRightsBaseClassGUI extends cmdbAbstractObject
  28. {
  29. // Whenever something changes, reload the privileges
  30. protected function AfterInsert()
  31. {
  32. UserRights::FlushPrivileges();
  33. }
  34. protected function AfterUpdate()
  35. {
  36. UserRights::FlushPrivileges();
  37. }
  38. protected function AfterDelete()
  39. {
  40. UserRights::FlushPrivileges();
  41. }
  42. }
  43. class URP_Profiles extends UserRightsBaseClassGUI
  44. {
  45. public static function Init()
  46. {
  47. $aParams = array
  48. (
  49. "category" => "addon/userrights",
  50. "key_type" => "autoincrement",
  51. "name_attcode" => "name",
  52. "state_attcode" => "",
  53. "reconc_keys" => array(),
  54. "db_table" => "priv_urp_profiles",
  55. "db_key_field" => "id",
  56. "db_finalclass_field" => "",
  57. "display_template" => "",
  58. );
  59. MetaModel::Init_Params($aParams);
  60. //MetaModel::Init_InheritAttributes();
  61. MetaModel::Init_AddAttribute(new AttributeString("name", array("allowed_values"=>null, "sql"=>"name", "default_value"=>null, "is_null_allowed"=>false, "depends_on"=>array())));
  62. MetaModel::Init_AddAttribute(new AttributeString("description", array("allowed_values"=>null, "sql"=>"description", "default_value"=>null, "is_null_allowed"=>false, "depends_on"=>array())));
  63. MetaModel::Init_AddAttribute(new AttributeLinkedSetIndirect("user_list", array("linked_class"=>"URP_UserProfile", "ext_key_to_me"=>"profileid", "ext_key_to_remote"=>"userid", "allowed_values"=>null, "count_min"=>1, "count_max"=>0, "depends_on"=>array())));
  64. // Display lists
  65. MetaModel::Init_SetZListItems('details', array('name', 'description', 'user_list')); // Attributes to be displayed for the complete details
  66. MetaModel::Init_SetZListItems('list', array('description')); // Attributes to be displayed for a list
  67. // Search criteria
  68. MetaModel::Init_SetZListItems('standard_search', array('name')); // Criteria of the std search form
  69. MetaModel::Init_SetZListItems('advanced_search', array('name')); // Criteria of the advanced search form
  70. }
  71. protected static $m_aCacheProfiles = null;
  72. public static function DoCreateProfile($sName, $sDescription)
  73. {
  74. if (is_null(self::$m_aCacheProfiles))
  75. {
  76. self::$m_aCacheProfiles = array();
  77. $oFilterAll = new DBObjectSearch('URP_Profiles');
  78. $oSet = new DBObjectSet($oFilterAll);
  79. while ($oProfile = $oSet->Fetch())
  80. {
  81. self::$m_aCacheProfiles[$oProfile->Get('name')] = $oProfile->GetKey();
  82. }
  83. }
  84. $sCacheKey = $sName;
  85. if (isset(self::$m_aCacheProfiles[$sCacheKey]))
  86. {
  87. return self::$m_aCacheProfiles[$sCacheKey];
  88. }
  89. $oNewObj = MetaModel::NewObject("URP_Profiles");
  90. $oNewObj->Set('name', $sName);
  91. $oNewObj->Set('description', $sDescription);
  92. $iId = $oNewObj->DBInsertNoReload();
  93. self::$m_aCacheProfiles[$sCacheKey] = $iId;
  94. return $iId;
  95. }
  96. function GetGrantAsHtml($oUserRights, $sClass, $sAction)
  97. {
  98. $bGrant = $oUserRights->GetProfileActionGrant($this->GetKey(), $sClass, $sAction);
  99. if (is_null($bGrant))
  100. {
  101. return '<span style="background-color: #ffdddd;">'.Dict::S('UI:UserManagement:ActionAllowed:No').'</span>';
  102. }
  103. elseif ($bGrant)
  104. {
  105. return '<span style="background-color: #ddffdd;">'.Dict::S('UI:UserManagement:ActionAllowed:Yes').'</span>';
  106. }
  107. else
  108. {
  109. return '<span style="background-color: #ffdddd;">'.Dict::S('UI:UserManagement:ActionAllowed:No').'</span>';
  110. }
  111. }
  112. function DoShowGrantSumary($oPage)
  113. {
  114. if ($this->GetRawName() == "Administrator")
  115. {
  116. // Looks dirty, but ok that's THE ONE
  117. $oPage->p(Dict::S('UI:UserManagement:AdminProfile+'));
  118. return;
  119. }
  120. // Note: for sure, we assume that the instance is derived from UserRightsProfile
  121. $oUserRights = UserRights::GetModuleInstance();
  122. $aDisplayData = array();
  123. foreach (MetaModel::GetClasses('bizmodel') as $sClass)
  124. {
  125. // Skip non instantiable classes
  126. if (MetaModel::IsAbstract($sClass)) continue;
  127. $aStimuli = array();
  128. foreach (MetaModel::EnumStimuli($sClass) as $sStimulusCode => $oStimulus)
  129. {
  130. $bGrant = $oUserRights->GetClassStimulusGrant($this->GetKey(), $sClass, $sStimulusCode);
  131. if ($bGrant === true)
  132. {
  133. $aStimuli[] = '<span title="'.$sStimulusCode.': '.htmlentities($oStimulus->GetDescription(), ENT_QUOTES, 'UTF-8').'">'.htmlentities($oStimulus->GetLabel(), ENT_QUOTES, 'UTF-8').'</span>';
  134. }
  135. }
  136. $sStimuli = implode(', ', $aStimuli);
  137. $aDisplayData[] = array(
  138. 'class' => MetaModel::GetName($sClass),
  139. 'read' => $this->GetGrantAsHtml($oUserRights, $sClass, 'r'),
  140. 'bulkread' => $this->GetGrantAsHtml($oUserRights, $sClass, 'br'),
  141. 'write' => $this->GetGrantAsHtml($oUserRights, $sClass, 'w'),
  142. 'bulkwrite' => $this->GetGrantAsHtml($oUserRights, $sClass, 'bw'),
  143. 'delete' => $this->GetGrantAsHtml($oUserRights, $sClass, 'd'),
  144. 'bulkdelete' => $this->GetGrantAsHtml($oUserRights, $sClass, 'bd'),
  145. 'stimuli' => $sStimuli,
  146. );
  147. }
  148. $aDisplayConfig = array();
  149. $aDisplayConfig['class'] = array('label' => Dict::S('UI:UserManagement:Class'), 'description' => Dict::S('UI:UserManagement:Class+'));
  150. $aDisplayConfig['read'] = array('label' => Dict::S('UI:UserManagement:Action:Read'), 'description' => Dict::S('UI:UserManagement:Action:Read+'));
  151. $aDisplayConfig['bulkread'] = array('label' => Dict::S('UI:UserManagement:Action:BulkRead'), 'description' => Dict::S('UI:UserManagement:Action:BulkRead+'));
  152. $aDisplayConfig['write'] = array('label' => Dict::S('UI:UserManagement:Action:Modify'), 'description' => Dict::S('UI:UserManagement:Action:Modify+'));
  153. $aDisplayConfig['bulkwrite'] = array('label' => Dict::S('UI:UserManagement:Action:BulkModify'), 'description' => Dict::S('UI:UserManagement:Action:BulkModify+'));
  154. $aDisplayConfig['delete'] = array('label' => Dict::S('UI:UserManagement:Action:Delete'), 'description' => Dict::S('UI:UserManagement:Action:Delete+'));
  155. $aDisplayConfig['bulkdelete'] = array('label' => Dict::S('UI:UserManagement:Action:BulkDelete'), 'description' => Dict::S('UI:UserManagement:Action:BulkDelete+'));
  156. $aDisplayConfig['stimuli'] = array('label' => Dict::S('UI:UserManagement:Action:Stimuli'), 'description' => Dict::S('UI:UserManagement:Action:Stimuli+'));
  157. $oPage->table($aDisplayConfig, $aDisplayData);
  158. }
  159. function DisplayBareRelations(WebPage $oPage, $bEditMode = false)
  160. {
  161. parent::DisplayBareRelations($oPage, $bEditMode);
  162. if (!$bEditMode)
  163. {
  164. $oPage->SetCurrentTab(Dict::S('UI:UserManagement:GrantMatrix'));
  165. $this->DoShowGrantSumary($oPage);
  166. }
  167. }
  168. public static function GetReadOnlyAttributes()
  169. {
  170. return array('name', 'description');
  171. }
  172. // returns an array of id => array of column => php value(so-called "real value")
  173. public static function GetPredefinedObjects()
  174. {
  175. return ProfilesConfig::GetProfilesValues();
  176. }
  177. // Before deleting a profile,
  178. // preserve DB integrity by deleting links to users
  179. protected function OnDelete()
  180. {
  181. // Note: this may break the rule that says: "a user must have at least ONE profile" !
  182. $oLnkSet = $this->Get('user_list');
  183. while($oLnk = $oLnkSet->Fetch())
  184. {
  185. $oLnk->DBDelete();
  186. }
  187. }
  188. }
  189. class URP_UserProfile extends UserRightsBaseClassGUI
  190. {
  191. public static function Init()
  192. {
  193. $aParams = array
  194. (
  195. "category" => "addon/userrights",
  196. "key_type" => "autoincrement",
  197. "name_attcode" => "userid",
  198. "state_attcode" => "",
  199. "reconc_keys" => array(),
  200. "db_table" => "priv_urp_userprofile",
  201. "db_key_field" => "id",
  202. "db_finalclass_field" => "",
  203. "display_template" => "",
  204. );
  205. MetaModel::Init_Params($aParams);
  206. //MetaModel::Init_InheritAttributes();
  207. MetaModel::Init_AddAttribute(new AttributeExternalKey("userid", array("targetclass"=>"User", "jointype"=> "", "allowed_values"=>null, "sql"=>"userid", "is_null_allowed"=>false, "on_target_delete"=>DEL_AUTO, "depends_on"=>array())));
  208. MetaModel::Init_AddAttribute(new AttributeExternalField("userlogin", array("allowed_values"=>null, "extkey_attcode"=> 'userid', "target_attcode"=>"login")));
  209. MetaModel::Init_AddAttribute(new AttributeExternalKey("profileid", array("targetclass"=>"URP_Profiles", "jointype"=> "", "allowed_values"=>null, "sql"=>"profileid", "is_null_allowed"=>false, "on_target_delete"=>DEL_AUTO, "depends_on"=>array())));
  210. MetaModel::Init_AddAttribute(new AttributeExternalField("profile", array("allowed_values"=>null, "extkey_attcode"=> 'profileid', "target_attcode"=>"name")));
  211. MetaModel::Init_AddAttribute(new AttributeString("reason", array("allowed_values"=>null, "sql"=>"description", "default_value"=>null, "is_null_allowed"=>true, "depends_on"=>array())));
  212. // Display lists
  213. MetaModel::Init_SetZListItems('details', array('userid', 'profileid', 'reason')); // Attributes to be displayed for the complete details
  214. MetaModel::Init_SetZListItems('list', array('userid', 'profileid', 'reason')); // Attributes to be displayed for a list
  215. // Search criteria
  216. MetaModel::Init_SetZListItems('standard_search', array('userid', 'profileid')); // Criteria of the std search form
  217. MetaModel::Init_SetZListItems('advanced_search', array('userid', 'profileid')); // Criteria of the advanced search form
  218. }
  219. public function GetName()
  220. {
  221. return Dict::Format('UI:UserManagement:LinkBetween_User_And_Profile', $this->Get('userlogin'), $this->Get('profile'));
  222. }
  223. }
  224. class URP_UserOrg extends UserRightsBaseClassGUI
  225. {
  226. public static function Init()
  227. {
  228. $aParams = array
  229. (
  230. "category" => "addon/userrights",
  231. "key_type" => "autoincrement",
  232. "name_attcode" => "userid",
  233. "state_attcode" => "",
  234. "reconc_keys" => array(),
  235. "db_table" => "priv_urp_userorg",
  236. "db_key_field" => "id",
  237. "db_finalclass_field" => "",
  238. "display_template" => "",
  239. );
  240. MetaModel::Init_Params($aParams);
  241. //MetaModel::Init_InheritAttributes();
  242. MetaModel::Init_AddAttribute(new AttributeExternalKey("userid", array("targetclass"=>"User", "jointype"=> "", "allowed_values"=>null, "sql"=>"userid", "is_null_allowed"=>false, "on_target_delete"=>DEL_AUTO, "depends_on"=>array())));
  243. MetaModel::Init_AddAttribute(new AttributeExternalField("userlogin", array("allowed_values"=>null, "extkey_attcode"=> 'userid', "target_attcode"=>"login")));
  244. MetaModel::Init_AddAttribute(new AttributeExternalKey("allowed_org_id", array("targetclass"=>"Organization", "jointype"=> "", "allowed_values"=>null, "sql"=>"allowed_org_id", "is_null_allowed"=>false, "on_target_delete"=>DEL_AUTO, "depends_on"=>array())));
  245. MetaModel::Init_AddAttribute(new AttributeExternalField("allowed_org_name", array("allowed_values"=>null, "extkey_attcode"=> 'allowed_org_id', "target_attcode"=>"name")));
  246. MetaModel::Init_AddAttribute(new AttributeString("reason", array("allowed_values"=>null, "sql"=>"reason", "default_value"=>null, "is_null_allowed"=>true, "depends_on"=>array())));
  247. // Display lists
  248. MetaModel::Init_SetZListItems('details', array('userid', 'allowed_org_id', 'reason')); // Attributes to be displayed for the complete details
  249. MetaModel::Init_SetZListItems('list', array('allowed_org_id', 'reason')); // Attributes to be displayed for a list
  250. // Search criteria
  251. MetaModel::Init_SetZListItems('standard_search', array('userid', 'allowed_org_id')); // Criteria of the std search form
  252. MetaModel::Init_SetZListItems('advanced_search', array('userid', 'allowed_org_id')); // Criteria of the advanced search form
  253. }
  254. public function GetName()
  255. {
  256. return Dict::Format('UI:UserManagement:LinkBetween_User_And_Org', $this->Get('userlogin'), $this->Get('allowed_org_name'));
  257. }
  258. }
  259. class UserRightsProfile extends UserRightsAddOnAPI
  260. {
  261. static public $m_aActionCodes = array(
  262. UR_ACTION_READ => 'r',
  263. UR_ACTION_MODIFY => 'w',
  264. UR_ACTION_DELETE => 'd',
  265. UR_ACTION_BULK_READ => 'br',
  266. UR_ACTION_BULK_MODIFY => 'bw',
  267. UR_ACTION_BULK_DELETE => 'bd',
  268. );
  269. // Installation: create the very first user
  270. public function CreateAdministrator($sAdminUser, $sAdminPwd, $sLanguage = 'EN US')
  271. {
  272. // Create a change to record the history of the User object
  273. $oChange = MetaModel::NewObject("CMDBChange");
  274. $oChange->Set("date", time());
  275. $oChange->Set("userinfo", "Initialization");
  276. $iChangeId = $oChange->DBInsert();
  277. $iContactId = 0;
  278. // Support drastic data model changes: no organization class (or not writable)!
  279. if (MetaModel::IsValidClass('Organization') && !MetaModel::IsAbstract('Organization'))
  280. {
  281. $oOrg = new Organization();
  282. $oOrg->Set('name', 'My Company/Department');
  283. $oOrg->Set('code', 'SOMECODE');
  284. $iOrgId = $oOrg->DBInsertTrackedNoReload($oChange, true /* skip security */);
  285. // Support drastic data model changes: no Person class (or not writable)!
  286. if (MetaModel::IsValidClass('Person') && !MetaModel::IsAbstract('Person'))
  287. {
  288. $oContact = new Person();
  289. $oContact->Set('name', 'My last name');
  290. $oContact->Set('first_name', 'My first name');
  291. if (MetaModel::IsValidAttCode('Person', 'org_id'))
  292. {
  293. $oContact->Set('org_id', $iOrgId);
  294. }
  295. if (MetaModel::IsValidAttCode('Person', 'phone'))
  296. {
  297. $oContact->Set('phone', '+00 000 000 000');
  298. }
  299. $oContact->Set('email', 'my.email@foo.org');
  300. $iContactId = $oContact->DBInsertTrackedNoReload($oChange, true /* skip security */);
  301. }
  302. }
  303. $oUser = new UserLocal();
  304. $oUser->Set('login', $sAdminUser);
  305. $oUser->Set('password', $sAdminPwd);
  306. if (MetaModel::IsValidAttCode('UserLocal', 'contactid') && ($iContactId != 0))
  307. {
  308. $oUser->Set('contactid', $iContactId);
  309. }
  310. $oUser->Set('language', $sLanguage); // Language was chosen during the installation
  311. // Add this user to the very specific 'admin' profile
  312. $oAdminProfile = MetaModel::GetObjectFromOQL("SELECT URP_Profiles WHERE name = :name", array('name' => ADMIN_PROFILE_NAME), true /*all data*/);
  313. if (is_object($oAdminProfile))
  314. {
  315. $oUserProfile = new URP_UserProfile();
  316. //$oUserProfile->Set('userid', $iUserId);
  317. $oUserProfile->Set('profileid', $oAdminProfile->GetKey());
  318. $oUserProfile->Set('reason', 'By definition, the administrator must have the administrator profile');
  319. //$oUserProfile->DBInsertTrackedNoReload($oChange, true /* skip security */);
  320. $oSet = DBObjectSet::FromObject($oUserProfile);
  321. $oUser->Set('profile_list', $oSet);
  322. }
  323. $iUserId = $oUser->DBInsertTrackedNoReload($oChange, true /* skip security */);
  324. return true;
  325. }
  326. public function Init()
  327. {
  328. }
  329. protected $m_aAdmins = array(); // id -> bool, true if the user has the well-known admin profile
  330. protected $m_aPortalUsers = array(); // id -> bool, true if the user has the well-known portal user profile
  331. protected $m_aProfiles; // id -> object
  332. protected $m_aUserProfiles = array(); // userid,profileid -> object
  333. protected $m_aUserOrgs = array(); // userid -> array of orgid
  334. // Built on demand, could be optimized if necessary (doing a query for each attribute that needs to be read)
  335. protected $m_aObjectActionGrants = array();
  336. /**
  337. * Read and cache organizations allowed to the given user
  338. *
  339. * @param oUser
  340. * @param sClass -not used here but can be used in overloads
  341. */
  342. protected function GetUserOrgs($oUser, $sClass)
  343. {
  344. $iUser = $oUser->GetKey();
  345. if (!array_key_exists($iUser, $this->m_aUserOrgs))
  346. {
  347. $this->m_aUserOrgs[$iUser] = array();
  348. $sHierarchicalKeyCode = MetaModel::IsHierarchicalClass('Organization');
  349. if ($sHierarchicalKeyCode !== false)
  350. {
  351. $sUserOrgQuery = 'SELECT UserOrg, Org FROM Organization AS Org JOIN Organization AS Root ON Org.'.$sHierarchicalKeyCode.' BELOW Root.id JOIN URP_UserOrg AS UserOrg ON UserOrg.allowed_org_id = Root.id WHERE UserOrg.userid = :userid';
  352. $oUserOrgSet = new DBObjectSet(DBObjectSearch::FromOQL_AllData($sUserOrgQuery), array(), array('userid' => $iUser));
  353. while ($aRow = $oUserOrgSet->FetchAssoc())
  354. {
  355. $oUserOrg = $aRow['UserOrg'];
  356. $oOrg = $aRow['Org'];
  357. $this->m_aUserOrgs[$iUser][] = $oOrg->GetKey();
  358. }
  359. }
  360. else
  361. {
  362. $oSearch = new DBObjectSearch('URP_UserOrg');
  363. $oSearch->AllowAllData();
  364. $oCondition = new BinaryExpression(new FieldExpression('userid'), '=', new VariableExpression('userid'));
  365. $oSearch->AddConditionExpression($oCondition);
  366. $oUserOrgSet = new DBObjectSet($oSearch, array(), array('userid' => $iUser));
  367. while ($oUserOrg = $oUserOrgSet->Fetch())
  368. {
  369. $this->m_aUserOrgs[$iUser][] = $oUserOrg->Get('allowed_org_id');
  370. }
  371. }
  372. }
  373. return $this->m_aUserOrgs[$iUser];
  374. }
  375. /**
  376. * Read and cache profiles of the given user
  377. */
  378. protected function GetUserProfiles($iUser)
  379. {
  380. if (!array_key_exists($iUser, $this->m_aUserProfiles))
  381. {
  382. $oSearch = new DBObjectSearch('URP_UserProfile');
  383. $oSearch->AllowAllData();
  384. $oCondition = new BinaryExpression(new FieldExpression('userid'), '=', new VariableExpression('userid'));
  385. $oSearch->AddConditionExpression($oCondition);
  386. $this->m_aUserProfiles[$iUser] = array();
  387. $oUserProfileSet = new DBObjectSet($oSearch, array(), array('userid' => $iUser));
  388. while ($oUserProfile = $oUserProfileSet->Fetch())
  389. {
  390. $this->m_aUserProfiles[$iUser][$oUserProfile->Get('profileid')] = $oUserProfile;
  391. }
  392. }
  393. return $this->m_aUserProfiles[$iUser];
  394. }
  395. public function ResetCache()
  396. {
  397. // Loaded by Load cache
  398. $this->m_aProfiles = null;
  399. $this->m_aUserProfiles = array();
  400. $this->m_aUserOrgs = array();
  401. $this->m_aAdmins = array();
  402. $this->m_aPortalUsers = array();
  403. // Cache
  404. $this->m_aObjectActionGrants = array();
  405. }
  406. public function LoadCache()
  407. {
  408. if (!is_null($this->m_aProfiles)) return;
  409. // Could be loaded in a shared memory (?)
  410. $oKPI = new ExecutionKPI();
  411. if (self::HasSharing())
  412. {
  413. SharedObject::InitSharedClassProperties();
  414. }
  415. $oProfileSet = new DBObjectSet(DBObjectSearch::FromOQL_AllData("SELECT URP_Profiles"));
  416. $this->m_aProfiles = array();
  417. while ($oProfile = $oProfileSet->Fetch())
  418. {
  419. $this->m_aProfiles[$oProfile->GetKey()] = $oProfile;
  420. }
  421. $oKPI->ComputeAndReport('Load of user management cache (excepted Action Grants)');
  422. /*
  423. echo "<pre>\n";
  424. print_r($this->m_aProfiles);
  425. print_r($this->m_aUserProfiles);
  426. print_r($this->m_aUserOrgs);
  427. echo "</pre>\n";
  428. exit;
  429. */
  430. return true;
  431. }
  432. public function IsAdministrator($oUser)
  433. {
  434. //$this->LoadCache();
  435. $iUser = $oUser->GetKey();
  436. if (!array_key_exists($iUser, $this->m_aAdmins))
  437. {
  438. $bIsAdmin = false;
  439. foreach($this->GetUserProfiles($iUser) as $oUserProfile)
  440. {
  441. if ($oUserProfile->Get('profile') == ADMIN_PROFILE_NAME)
  442. {
  443. $bIsAdmin = true;
  444. break;
  445. }
  446. }
  447. $this->m_aAdmins[$iUser] = $bIsAdmin;
  448. }
  449. return $this->m_aAdmins[$iUser];
  450. }
  451. public function IsPortalUser($oUser)
  452. {
  453. //$this->LoadCache();
  454. $iUser = $oUser->GetKey();
  455. if (!array_key_exists($iUser, $this->m_aPortalUsers))
  456. {
  457. $bIsPortalUser = false;
  458. foreach($this->GetUserProfiles($iUser) as $oUserProfile)
  459. {
  460. if ($oUserProfile->Get('profile') == PORTAL_PROFILE_NAME)
  461. {
  462. $bIsPortalUser = true;
  463. break;
  464. }
  465. }
  466. $this->m_aPortalUsers[$iUser] = $bIsPortalUser;
  467. }
  468. return $this->m_aPortalUsers[$iUser];
  469. }
  470. public function GetSelectFilter($oUser, $sClass, $aSettings = array())
  471. {
  472. $this->LoadCache();
  473. $aObjectPermissions = $this->GetUserActionGrant($oUser, $sClass, UR_ACTION_READ);
  474. if ($aObjectPermissions['permission'] == UR_ALLOWED_NO)
  475. {
  476. return false;
  477. }
  478. // Determine how to position the objects of this class
  479. //
  480. $sAttCode = self::GetOwnerOrganizationAttCode($sClass);
  481. if (is_null($sAttCode))
  482. {
  483. // No filtering for this object
  484. return true;
  485. }
  486. // Position the user
  487. //
  488. $aUserOrgs = $this->GetUserOrgs($oUser, $sClass);
  489. if (count($aUserOrgs) == 0)
  490. {
  491. // No org means 'any org'
  492. return true;
  493. }
  494. $oExpression = new FieldExpression($sAttCode, $sClass);
  495. $oFilter = new DBObjectSearch($sClass);
  496. $oListExpr = ListExpression::FromScalars($aUserOrgs);
  497. $oCondition = new BinaryExpression($oExpression, 'IN', $oListExpr);
  498. $oFilter->AddConditionExpression($oCondition);
  499. if (self::HasSharing())
  500. {
  501. if (($sAttCode == 'id') && isset($aSettings['bSearchMode']) && $aSettings['bSearchMode'])
  502. {
  503. // Querying organizations (or derived)
  504. // and the expected list of organizations will be used as a search criteria
  505. // Therefore the query can also return organization having objects shared with the allowed organizations
  506. //
  507. // 1) build the list of organizations sharing something with the allowed organizations
  508. // Organization <== sharing_org_id == SharedObject having org_id IN {user orgs}
  509. $oShareSearch = new DBObjectSearch('SharedObject');
  510. $oOrgField = new FieldExpression('org_id', 'SharedObject');
  511. $oShareSearch->AddConditionExpression(new BinaryExpression($oOrgField, 'IN', $oListExpr));
  512. $oSearchSharers = new DBObjectSearch('Organization');
  513. $oSearchSharers->AllowAllData();
  514. $oSearchSharers->AddCondition_ReferencedBy($oShareSearch, 'sharing_org_id');
  515. $aSharers = array();
  516. foreach($oSearchSharers->ToDataArray(array('id')) as $aRow)
  517. {
  518. $aSharers[] = $aRow['id'];
  519. }
  520. // 2) Enlarge the overall results: ... OR id IN(id1, id2, id3)
  521. if (count($aSharers) > 0)
  522. {
  523. $oSharersList = ListExpression::FromScalars($aSharers);
  524. $oFilter->MergeConditionExpression(new BinaryExpression($oExpression, 'IN', $oSharersList));
  525. }
  526. }
  527. $aShareProperties = SharedObject::GetSharedClassProperties($sClass);
  528. if ($aShareProperties)
  529. {
  530. $sShareClass = $aShareProperties['share_class'];
  531. $sShareAttCode = $aShareProperties['attcode'];
  532. $oSearchShares = new DBObjectSearch($sShareClass);
  533. $oSearchShares->AllowAllData();
  534. $sHierarchicalKeyCode = MetaModel::IsHierarchicalClass('Organization');
  535. $oOrgField = new FieldExpression('org_id', $sShareClass);
  536. $oSearchShares->AddConditionExpression(new BinaryExpression($oOrgField, 'IN', $oListExpr));
  537. $aShared = array();
  538. foreach($oSearchShares->ToDataArray(array($sShareAttCode)) as $aRow)
  539. {
  540. $aShared[] = $aRow[$sShareAttCode];
  541. }
  542. if (count($aShared) > 0)
  543. {
  544. $oObjId = new FieldExpression('id', $sClass);
  545. $oSharedIdList = ListExpression::FromScalars($aShared);
  546. $oFilter->MergeConditionExpression(new BinaryExpression($oObjId, 'IN', $oSharedIdList));
  547. }
  548. }
  549. } // if HasSharing
  550. return $oFilter;
  551. }
  552. // This verb has been made public to allow the development of an accurate feedback for the current configuration
  553. public function GetProfileActionGrant($iProfile, $sClass, $sAction)
  554. {
  555. // Note: action is forced lowercase to be more flexible (historical bug)
  556. $sAction = strtolower($sAction);
  557. return ProfilesConfig::GetProfileActionGrant($iProfile, $sClass, $sAction);
  558. }
  559. protected function GetUserActionGrant($oUser, $sClass, $iActionCode)
  560. {
  561. $this->LoadCache();
  562. // load and cache permissions for the current user on the given class
  563. //
  564. $iUser = $oUser->GetKey();
  565. $aTest = @$this->m_aObjectActionGrants[$iUser][$sClass][$iActionCode];
  566. if (is_array($aTest)) return $aTest;
  567. $sAction = self::$m_aActionCodes[$iActionCode];
  568. $bStatus = null;
  569. $aAttributes = array();
  570. foreach($this->GetUserProfiles($iUser) as $iProfile => $oProfile)
  571. {
  572. $bGrant = $this->GetProfileActionGrant($iProfile, $sClass, $sAction);
  573. if (!is_null($bGrant))
  574. {
  575. if ($bGrant)
  576. {
  577. if (is_null($bStatus))
  578. {
  579. $bStatus = true;
  580. }
  581. }
  582. else
  583. {
  584. $bStatus = false;
  585. }
  586. }
  587. }
  588. $iPermission = $bStatus ? UR_ALLOWED_YES : UR_ALLOWED_NO;
  589. $aRes = array(
  590. 'permission' => $iPermission,
  591. // 'attributes' => $aAttributes,
  592. );
  593. $this->m_aObjectActionGrants[$iUser][$sClass][$iActionCode] = $aRes;
  594. return $aRes;
  595. }
  596. public function IsActionAllowed($oUser, $sClass, $iActionCode, $oInstanceSet = null)
  597. {
  598. $this->LoadCache();
  599. $aObjectPermissions = $this->GetUserActionGrant($oUser, $sClass, $iActionCode);
  600. $iPermission = $aObjectPermissions['permission'];
  601. // Note: In most cases the object set is ignored because it was interesting to optimize for huge data sets
  602. // and acceptable to consider only the root class of the object set
  603. if ($iPermission != UR_ALLOWED_YES)
  604. {
  605. // It is already NO for everyone... that's the final word!
  606. }
  607. elseif ($iActionCode == UR_ACTION_READ)
  608. {
  609. // We are protected by GetSelectFilter: the object set contains objects allowed or shared for reading
  610. }
  611. elseif ($iActionCode == UR_ACTION_BULK_READ)
  612. {
  613. // We are protected by GetSelectFilter: the object set contains objects allowed or shared for reading
  614. }
  615. elseif ($oInstanceSet)
  616. {
  617. // We are protected by GetSelectFilter: the object set contains objects allowed or shared for reading
  618. // We have to answer NO for objects shared for reading purposes
  619. if (self::HasSharing())
  620. {
  621. $aClassProps = SharedObject::GetSharedClassProperties($sClass);
  622. if ($aClassProps)
  623. {
  624. // This class is shared, GetSelectFilter may allow some objects for read only
  625. // But currently we are checking wether the objects might be written...
  626. // Let's exclude the objects based on the relevant criteria
  627. $sOrgAttCode = self::GetOwnerOrganizationAttCode($sClass);
  628. if (!is_null($sOrgAttCode))
  629. {
  630. $aUserOrgs = $this->GetUserOrgs($oUser, $sClass);
  631. if (!is_null($aUserOrgs) && count($aUserOrgs) > 0)
  632. {
  633. $iCountNO = 0;
  634. $iCountYES = 0;
  635. $oInstanceSet->Rewind();
  636. while($oObject = $oInstanceSet->Fetch())
  637. {
  638. $iOrg = $oObject->Get($sOrgAttCode);
  639. if (in_array($iOrg, $aUserOrgs))
  640. {
  641. $iCountYES++;
  642. }
  643. else
  644. {
  645. $iCountNO++;
  646. }
  647. }
  648. if ($iCountNO == 0)
  649. {
  650. $iPermission = UR_ALLOWED_YES;
  651. }
  652. elseif ($iCountYES == 0)
  653. {
  654. $iPermission = UR_ALLOWED_NO;
  655. }
  656. else
  657. {
  658. $iPermission = UR_ALLOWED_DEPENDS;
  659. }
  660. }
  661. }
  662. }
  663. }
  664. }
  665. return $iPermission;
  666. }
  667. public function IsActionAllowedOnAttribute($oUser, $sClass, $sAttCode, $iActionCode, $oInstanceSet = null)
  668. {
  669. $this->LoadCache();
  670. // Note: The object set is ignored because it was interesting to optimize for huge data sets
  671. // and acceptable to consider only the root class of the object set
  672. $aObjectPermissions = $this->GetUserActionGrant($oUser, $sClass, $iActionCode);
  673. $aAttributes = $aObjectPermissions['attributes'];
  674. if (in_array($sAttCode, $aAttributes))
  675. {
  676. return $aObjectPermissions['permission'];
  677. }
  678. else
  679. {
  680. return UR_ALLOWED_NO;
  681. }
  682. }
  683. // This verb has been made public to allow the development of an accurate feedback for the current configuration
  684. public function GetClassStimulusGrant($iProfile, $sClass, $sStimulusCode)
  685. {
  686. return ProfilesConfig::GetProfileStimulusGrant($iProfile, $sClass, $sStimulusCode);
  687. }
  688. public function IsStimulusAllowed($oUser, $sClass, $sStimulusCode, $oInstanceSet = null)
  689. {
  690. $this->LoadCache();
  691. // Note: this code is VERY close to the code of IsActionAllowed()
  692. $iUser = $oUser->GetKey();
  693. // Note: The object set is ignored because it was interesting to optimize for huge data sets
  694. // and acceptable to consider only the root class of the object set
  695. $bStatus = null;
  696. foreach($this->GetUserProfiles($iUser) as $iProfile => $oProfile)
  697. {
  698. $bGrant = $this->GetClassStimulusGrant($iProfile, $sClass, $sStimulusCode);
  699. if (!is_null($bGrant))
  700. {
  701. if ($bGrant)
  702. {
  703. if (is_null($bStatus))
  704. {
  705. $bStatus = true;
  706. }
  707. }
  708. else
  709. {
  710. $bStatus = false;
  711. }
  712. }
  713. }
  714. $iPermission = $bStatus ? UR_ALLOWED_YES : UR_ALLOWED_NO;
  715. return $iPermission;
  716. }
  717. public function FlushPrivileges()
  718. {
  719. $this->ResetCache();
  720. }
  721. /**
  722. * Find out which attribute is corresponding the the dimension 'owner org'
  723. * returns null if no such attribute has been found (no filtering should occur)
  724. */
  725. public static function GetOwnerOrganizationAttCode($sClass)
  726. {
  727. $sAttCode = null;
  728. $aCallSpec = array($sClass, 'MapContextParam');
  729. if (($sClass == 'Organization') || is_subclass_of($sClass, 'Organization'))
  730. {
  731. $sAttCode = 'id';
  732. }
  733. elseif (is_callable($aCallSpec))
  734. {
  735. $sAttCode = call_user_func($aCallSpec, 'org_id'); // Returns null when there is no mapping for this parameter
  736. if (!MetaModel::IsValidAttCode($sClass, $sAttCode))
  737. {
  738. // Skip silently. The data model checker will tell you something about this...
  739. $sAttCode = null;
  740. }
  741. }
  742. elseif(MetaModel::IsValidAttCode($sClass, 'org_id'))
  743. {
  744. $sAttCode = 'org_id';
  745. }
  746. return $sAttCode;
  747. }
  748. /**
  749. * Determine wether the objects can be shared by the mean of a class SharedObject
  750. **/
  751. protected static function HasSharing()
  752. {
  753. static $bHasSharing;
  754. if (!isset($bHasSharing))
  755. {
  756. $bHasSharing = class_exists('SharedObject');
  757. }
  758. return $bHasSharing;
  759. }
  760. }
  761. UserRights::SelectModule('UserRightsProfile');
  762. ?>