123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775 |
- <?php
- // Copyright (C) 2010-2013 Combodo SARL
- //
- // This file is part of iTop.
- //
- // iTop is free software; you can redistribute it and/or modify
- // it under the terms of the GNU Affero General Public License as published by
- // the Free Software Foundation, either version 3 of the License, or
- // (at your option) any later version.
- //
- // iTop is distributed in the hope that it will be useful,
- // but WITHOUT ANY WARRANTY; without even the implied warranty of
- // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- // GNU Affero General Public License for more details.
- //
- // You should have received a copy of the GNU Affero General Public License
- // along with iTop. If not, see <http://www.gnu.org/licenses/>
- /**
- * UserRightsProfile
- * User management Module, basing the right on profiles and a matrix (similar to UserRightsMatrix, but profiles and other decorations have been added)
- *
- * @copyright Copyright (C) 2010-2012 Combodo SARL
- * @license http://opensource.org/licenses/AGPL-3.0
- */
- define('ADMIN_PROFILE_NAME', 'Administrator');
- define('PORTAL_PROFILE_NAME', 'Portal user');
- class UserRightsBaseClassGUI extends cmdbAbstractObject
- {
- // Whenever something changes, reload the privileges
-
- protected function AfterInsert()
- {
- UserRights::FlushPrivileges();
- }
- protected function AfterUpdate()
- {
- UserRights::FlushPrivileges();
- }
- protected function AfterDelete()
- {
- UserRights::FlushPrivileges();
- }
- }
- class URP_Profiles extends UserRightsBaseClassGUI
- {
- public static function Init()
- {
- $aParams = array
- (
- "category" => "addon/userrights",
- "key_type" => "autoincrement",
- "name_attcode" => "name",
- "state_attcode" => "",
- "reconc_keys" => array(),
- "db_table" => "priv_urp_profiles",
- "db_key_field" => "id",
- "db_finalclass_field" => "",
- "display_template" => "",
- );
- MetaModel::Init_Params($aParams);
- //MetaModel::Init_InheritAttributes();
- MetaModel::Init_AddAttribute(new AttributeString("name", array("allowed_values"=>null, "sql"=>"name", "default_value"=>null, "is_null_allowed"=>false, "depends_on"=>array())));
- MetaModel::Init_AddAttribute(new AttributeString("description", array("allowed_values"=>null, "sql"=>"description", "default_value"=>null, "is_null_allowed"=>false, "depends_on"=>array())));
- 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())));
- // Display lists
- MetaModel::Init_SetZListItems('details', array('name', 'description', 'user_list')); // Attributes to be displayed for the complete details
- MetaModel::Init_SetZListItems('list', array('description')); // Attributes to be displayed for a list
- // Search criteria
- MetaModel::Init_SetZListItems('standard_search', array('name')); // Criteria of the std search form
- MetaModel::Init_SetZListItems('advanced_search', array('name')); // Criteria of the advanced search form
- }
- protected static $m_aCacheProfiles = null;
-
- public static function DoCreateProfile($sName, $sDescription)
- {
- if (is_null(self::$m_aCacheProfiles))
- {
- self::$m_aCacheProfiles = array();
- $oFilterAll = new DBObjectSearch('URP_Profiles');
- $oSet = new DBObjectSet($oFilterAll);
- while ($oProfile = $oSet->Fetch())
- {
- self::$m_aCacheProfiles[$oProfile->Get('name')] = $oProfile->GetKey();
- }
- }
- $sCacheKey = $sName;
- if (isset(self::$m_aCacheProfiles[$sCacheKey]))
- {
- return self::$m_aCacheProfiles[$sCacheKey];
- }
- $oNewObj = MetaModel::NewObject("URP_Profiles");
- $oNewObj->Set('name', $sName);
- $oNewObj->Set('description', $sDescription);
- $iId = $oNewObj->DBInsertNoReload();
- self::$m_aCacheProfiles[$sCacheKey] = $iId;
- return $iId;
- }
-
- function GetGrantAsHtml($oUserRights, $sClass, $sAction)
- {
- $bGrant = $oUserRights->GetProfileActionGrant($this->GetKey(), $sClass, $sAction);
- if (is_null($bGrant))
- {
- return '<span style="background-color: #ffdddd;">'.Dict::S('UI:UserManagement:ActionAllowed:No').'</span>';
- }
- elseif ($bGrant)
- {
- return '<span style="background-color: #ddffdd;">'.Dict::S('UI:UserManagement:ActionAllowed:Yes').'</span>';
- }
- else
- {
- return '<span style="background-color: #ffdddd;">'.Dict::S('UI:UserManagement:ActionAllowed:No').'</span>';
- }
- }
-
- function DoShowGrantSumary($oPage)
- {
- if ($this->GetRawName() == "Administrator")
- {
- // Looks dirty, but ok that's THE ONE
- $oPage->p(Dict::S('UI:UserManagement:AdminProfile+'));
- return;
- }
- // Note: for sure, we assume that the instance is derived from UserRightsProfile
- $oUserRights = UserRights::GetModuleInstance();
-
- $aDisplayData = array();
- foreach (MetaModel::GetClasses('bizmodel') as $sClass)
- {
- // Skip non instantiable classes
- if (MetaModel::IsAbstract($sClass)) continue;
- $aStimuli = array();
- foreach (MetaModel::EnumStimuli($sClass) as $sStimulusCode => $oStimulus)
- {
- $bGrant = $oUserRights->GetClassStimulusGrant($this->GetKey(), $sClass, $sStimulusCode);
- if ($bGrant === true)
- {
- $aStimuli[] = '<span title="'.$sStimulusCode.': '.htmlentities($oStimulus->GetDescription(), ENT_QUOTES, 'UTF-8').'">'.htmlentities($oStimulus->GetLabel(), ENT_QUOTES, 'UTF-8').'</span>';
- }
- }
- $sStimuli = implode(', ', $aStimuli);
-
- $aDisplayData[] = array(
- 'class' => MetaModel::GetName($sClass),
- 'read' => $this->GetGrantAsHtml($oUserRights, $sClass, 'r'),
- 'bulkread' => $this->GetGrantAsHtml($oUserRights, $sClass, 'br'),
- 'write' => $this->GetGrantAsHtml($oUserRights, $sClass, 'w'),
- 'bulkwrite' => $this->GetGrantAsHtml($oUserRights, $sClass, 'bw'),
- 'delete' => $this->GetGrantAsHtml($oUserRights, $sClass, 'd'),
- 'bulkdelete' => $this->GetGrantAsHtml($oUserRights, $sClass, 'bd'),
- 'stimuli' => $sStimuli,
- );
- }
-
- $aDisplayConfig = array();
- $aDisplayConfig['class'] = array('label' => Dict::S('UI:UserManagement:Class'), 'description' => Dict::S('UI:UserManagement:Class+'));
- $aDisplayConfig['read'] = array('label' => Dict::S('UI:UserManagement:Action:Read'), 'description' => Dict::S('UI:UserManagement:Action:Read+'));
- $aDisplayConfig['bulkread'] = array('label' => Dict::S('UI:UserManagement:Action:BulkRead'), 'description' => Dict::S('UI:UserManagement:Action:BulkRead+'));
- $aDisplayConfig['write'] = array('label' => Dict::S('UI:UserManagement:Action:Modify'), 'description' => Dict::S('UI:UserManagement:Action:Modify+'));
- $aDisplayConfig['bulkwrite'] = array('label' => Dict::S('UI:UserManagement:Action:BulkModify'), 'description' => Dict::S('UI:UserManagement:Action:BulkModify+'));
- $aDisplayConfig['delete'] = array('label' => Dict::S('UI:UserManagement:Action:Delete'), 'description' => Dict::S('UI:UserManagement:Action:Delete+'));
- $aDisplayConfig['bulkdelete'] = array('label' => Dict::S('UI:UserManagement:Action:BulkDelete'), 'description' => Dict::S('UI:UserManagement:Action:BulkDelete+'));
- $aDisplayConfig['stimuli'] = array('label' => Dict::S('UI:UserManagement:Action:Stimuli'), 'description' => Dict::S('UI:UserManagement:Action:Stimuli+'));
- $oPage->table($aDisplayConfig, $aDisplayData);
- }
- function DisplayBareRelations(WebPage $oPage, $bEditMode = false)
- {
- parent::DisplayBareRelations($oPage, $bEditMode);
- if (!$bEditMode)
- {
- $oPage->SetCurrentTab(Dict::S('UI:UserManagement:GrantMatrix'));
- $this->DoShowGrantSumary($oPage);
- }
- }
- public static function GetReadOnlyAttributes()
- {
- return array('name', 'description');
- }
- // returns an array of id => array of column => php value(so-called "real value")
- public static function GetPredefinedObjects()
- {
- return ProfilesConfig::GetProfilesValues();
- }
- // Before deleting a profile,
- // preserve DB integrity by deleting links to users
- protected function OnDelete()
- {
- // Note: this may break the rule that says: "a user must have at least ONE profile" !
- $oLnkSet = $this->Get('user_list');
- while($oLnk = $oLnkSet->Fetch())
- {
- $oLnk->DBDelete();
- }
- }
- /**
- * Returns the set of flags (OPT_ATT_HIDDEN, OPT_ATT_READONLY, OPT_ATT_MANDATORY...)
- * for the given attribute in the current state of the object
- * @param $sAttCode string $sAttCode The code of the attribute
- * @param $aReasons array To store the reasons why the attribute is read-only (info about the synchro replicas)
- * @param $sTargetState string The target state in which to evalutate the flags, if empty the current state will be used
- * @return integer Flags: the binary combination of the flags applicable to this attribute
- */
- public function GetAttributeFlags($sAttCode, &$aReasons = array(), $sTargetState = '')
- {
- $iFlags = parent::GetAttributeFlags($sAttCode, $aReasons, $sTargetState);
- if (MetaModel::GetConfig()->Get('demo_mode'))
- {
- $aReasons[] = 'Sorry, profiles are read-only in the demonstration mode!';
- $iFlags |= OPT_ATT_READONLY;
- }
- return $iFlags;
- }
- }
- class URP_UserProfile extends UserRightsBaseClassGUI
- {
- public static function Init()
- {
- $aParams = array
- (
- "category" => "addon/userrights",
- "key_type" => "autoincrement",
- "name_attcode" => "userid",
- "state_attcode" => "",
- "reconc_keys" => array(),
- "db_table" => "priv_urp_userprofile",
- "db_key_field" => "id",
- "db_finalclass_field" => "",
- "display_template" => "",
- );
- MetaModel::Init_Params($aParams);
- //MetaModel::Init_InheritAttributes();
- 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())));
- MetaModel::Init_AddAttribute(new AttributeExternalField("userlogin", array("allowed_values"=>null, "extkey_attcode"=> 'userid', "target_attcode"=>"login")));
- 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())));
- MetaModel::Init_AddAttribute(new AttributeExternalField("profile", array("allowed_values"=>null, "extkey_attcode"=> 'profileid', "target_attcode"=>"name")));
- MetaModel::Init_AddAttribute(new AttributeString("reason", array("allowed_values"=>null, "sql"=>"description", "default_value"=>null, "is_null_allowed"=>true, "depends_on"=>array())));
- // Display lists
- MetaModel::Init_SetZListItems('details', array('userid', 'profileid', 'reason')); // Attributes to be displayed for the complete details
- MetaModel::Init_SetZListItems('list', array('userid', 'profileid', 'reason')); // Attributes to be displayed for a list
- // Search criteria
- MetaModel::Init_SetZListItems('standard_search', array('userid', 'profileid')); // Criteria of the std search form
- MetaModel::Init_SetZListItems('advanced_search', array('userid', 'profileid')); // Criteria of the advanced search form
- }
- public function GetName()
- {
- return Dict::Format('UI:UserManagement:LinkBetween_User_And_Profile', $this->Get('userlogin'), $this->Get('profile'));
- }
- public function CheckToDelete(&$oDeletionPlan)
- {
- if (MetaModel::GetConfig()->Get('demo_mode'))
- {
- // Users deletion is NOT allowed in demo mode
- $oDeletionPlan->AddToDelete($this, null);
- $oDeletionPlan->SetDeletionIssues($this, array('deletion not allowed in demo mode.'), true);
- $oDeletionPlan->ComputeResults();
- return false;
- }
- return parent::CheckToDelete($oDeletionPlan);
- }
- }
- class URP_UserOrg extends UserRightsBaseClassGUI
- {
- public static function Init()
- {
- $aParams = array
- (
- "category" => "addon/userrights",
- "key_type" => "autoincrement",
- "name_attcode" => "userid",
- "state_attcode" => "",
- "reconc_keys" => array(),
- "db_table" => "priv_urp_userorg",
- "db_key_field" => "id",
- "db_finalclass_field" => "",
- "display_template" => "",
- );
- MetaModel::Init_Params($aParams);
- //MetaModel::Init_InheritAttributes();
- 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())));
- MetaModel::Init_AddAttribute(new AttributeExternalField("userlogin", array("allowed_values"=>null, "extkey_attcode"=> 'userid', "target_attcode"=>"login")));
- 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())));
- MetaModel::Init_AddAttribute(new AttributeExternalField("allowed_org_name", array("allowed_values"=>null, "extkey_attcode"=> 'allowed_org_id', "target_attcode"=>"name")));
- MetaModel::Init_AddAttribute(new AttributeString("reason", array("allowed_values"=>null, "sql"=>"reason", "default_value"=>null, "is_null_allowed"=>true, "depends_on"=>array())));
- // Display lists
- MetaModel::Init_SetZListItems('details', array('userid', 'allowed_org_id', 'reason')); // Attributes to be displayed for the complete details
- MetaModel::Init_SetZListItems('list', array('allowed_org_id', 'reason')); // Attributes to be displayed for a list
- // Search criteria
- MetaModel::Init_SetZListItems('standard_search', array('userid', 'allowed_org_id')); // Criteria of the std search form
- MetaModel::Init_SetZListItems('advanced_search', array('userid', 'allowed_org_id')); // Criteria of the advanced search form
- }
- public function GetName()
- {
- return Dict::Format('UI:UserManagement:LinkBetween_User_And_Org', $this->Get('userlogin'), $this->Get('allowed_org_name'));
- }
- }
- class UserRightsProfile extends UserRightsAddOnAPI
- {
- static public $m_aActionCodes = array(
- UR_ACTION_READ => 'r',
- UR_ACTION_MODIFY => 'w',
- UR_ACTION_DELETE => 'd',
- UR_ACTION_BULK_READ => 'br',
- UR_ACTION_BULK_MODIFY => 'bw',
- UR_ACTION_BULK_DELETE => 'bd',
- );
- // Installation: create the very first user
- public function CreateAdministrator($sAdminUser, $sAdminPwd, $sLanguage = 'EN US')
- {
- CMDBObject::SetTrackInfo('Initialization');
- $oChange = CMDBObject::GetCurrentChange();
- $iContactId = 0;
- // Support drastic data model changes: no organization class (or not writable)!
- if (MetaModel::IsValidClass('Organization') && !MetaModel::IsAbstract('Organization'))
- {
- $oOrg = new Organization();
- $oOrg->Set('name', 'My Company/Department');
- $oOrg->Set('code', 'SOMECODE');
- $iOrgId = $oOrg->DBInsertTrackedNoReload($oChange, true /* skip security */);
- // Support drastic data model changes: no Person class (or not writable)!
- if (MetaModel::IsValidClass('Person') && !MetaModel::IsAbstract('Person'))
- {
- $oContact = new Person();
- $oContact->Set('name', 'My last name');
- $oContact->Set('first_name', 'My first name');
- if (MetaModel::IsValidAttCode('Person', 'org_id'))
- {
- $oContact->Set('org_id', $iOrgId);
- }
- if (MetaModel::IsValidAttCode('Person', 'phone'))
- {
- $oContact->Set('phone', '+00 000 000 000');
- }
- $oContact->Set('email', 'my.email@foo.org');
- $iContactId = $oContact->DBInsertTrackedNoReload($oChange, true /* skip security */);
- }
- }
- $oUser = new UserLocal();
- $oUser->Set('login', $sAdminUser);
- $oUser->Set('password', $sAdminPwd);
- if (MetaModel::IsValidAttCode('UserLocal', 'contactid') && ($iContactId != 0))
- {
- $oUser->Set('contactid', $iContactId);
- }
- $oUser->Set('language', $sLanguage); // Language was chosen during the installation
- // Add this user to the very specific 'admin' profile
- $oAdminProfile = MetaModel::GetObjectFromOQL("SELECT URP_Profiles WHERE name = :name", array('name' => ADMIN_PROFILE_NAME), true /*all data*/);
- if (is_object($oAdminProfile))
- {
- $oUserProfile = new URP_UserProfile();
- //$oUserProfile->Set('userid', $iUserId);
- $oUserProfile->Set('profileid', $oAdminProfile->GetKey());
- $oUserProfile->Set('reason', 'By definition, the administrator must have the administrator profile');
- //$oUserProfile->DBInsertTrackedNoReload($oChange, true /* skip security */);
- $oSet = DBObjectSet::FromObject($oUserProfile);
- $oUser->Set('profile_list', $oSet);
- }
- $iUserId = $oUser->DBInsertTrackedNoReload($oChange, true /* skip security */);
- return true;
- }
- public function Init()
- {
- }
- protected $m_aUserOrgs = array(); // userid -> array of orgid
- // Built on demand, could be optimized if necessary (doing a query for each attribute that needs to be read)
- protected $m_aObjectActionGrants = array();
- /**
- * Read and cache organizations allowed to the given user
- *
- * @param oUser
- * @param sClass -not used here but can be used in overloads
- */
- protected function GetUserOrgs($oUser, $sClass)
- {
- $iUser = $oUser->GetKey();
- if (!array_key_exists($iUser, $this->m_aUserOrgs))
- {
- $this->m_aUserOrgs[$iUser] = array();
- $sHierarchicalKeyCode = MetaModel::IsHierarchicalClass('Organization');
- if ($sHierarchicalKeyCode !== false)
- {
- $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';
- $oUserOrgSet = new DBObjectSet(DBObjectSearch::FromOQL_AllData($sUserOrgQuery), array(), array('userid' => $iUser));
- while ($aRow = $oUserOrgSet->FetchAssoc())
- {
- $oUserOrg = $aRow['UserOrg'];
- $oOrg = $aRow['Org'];
- $this->m_aUserOrgs[$iUser][] = $oOrg->GetKey();
- }
- }
- else
- {
- $oSearch = new DBObjectSearch('URP_UserOrg');
- $oSearch->AllowAllData();
- $oCondition = new BinaryExpression(new FieldExpression('userid'), '=', new VariableExpression('userid'));
- $oSearch->AddConditionExpression($oCondition);
-
- $oUserOrgSet = new DBObjectSet($oSearch, array(), array('userid' => $iUser));
- while ($oUserOrg = $oUserOrgSet->Fetch())
- {
- $this->m_aUserOrgs[$iUser][] = $oUserOrg->Get('allowed_org_id');
- }
- }
- }
- return $this->m_aUserOrgs[$iUser];
- }
- public function ResetCache()
- {
- // Loaded by Load cache
- $this->m_aUserOrgs = array();
- // Cache
- $this->m_aObjectActionGrants = array();
- }
- public function LoadCache()
- {
- static $bSharedObjectInitialized = false;
- if (!$bSharedObjectInitialized)
- {
- $bSharedObjectInitialized = true;
- if (self::HasSharing())
- {
- SharedObject::InitSharedClassProperties();
- }
- }
- return true;
- }
- /**
- * @param $oUser User
- * @return array
- */
- public function IsAdministrator($oUser)
- {
- // UserRights caches the list for us
- return UserRights::HasProfile(ADMIN_PROFILE_NAME, $oUser);
- }
- /**
- * @param $oUser User
- * @return array
- */
- public function IsPortalUser($oUser)
- {
- // UserRights caches the list for us
- return UserRights::HasProfile(PORTAL_PROFILE_NAME, $oUser);
- }
- /**
- * @param $oUser User
- * @return bool
- */
- public function ListProfiles($oUser)
- {
- $aRet = array();
- $oSearch = new DBObjectSearch('URP_UserProfile');
- $oSearch->AllowAllData();
- $oSearch->NoContextParameters();
- $oSearch->Addcondition('userid', $oUser->GetKey(), '=');
- $oProfiles = new DBObjectSet($oSearch);
- while ($oUserProfile = $oProfiles->Fetch())
- {
- $aRet[$oUserProfile->Get('profileid')] = $oUserProfile->Get('profileid_friendlyname');
- }
- return $aRet;
- }
- public function GetSelectFilter($oUser, $sClass, $aSettings = array())
- {
- $this->LoadCache();
- $aObjectPermissions = $this->GetUserActionGrant($oUser, $sClass, UR_ACTION_READ);
- if ($aObjectPermissions['permission'] == UR_ALLOWED_NO)
- {
- return false;
- }
- // Determine how to position the objects of this class
- //
- $sAttCode = self::GetOwnerOrganizationAttCode($sClass);
- if (is_null($sAttCode))
- {
- // No filtering for this object
- return true;
- }
- // Position the user
- //
- $aUserOrgs = $this->GetUserOrgs($oUser, $sClass);
- if (count($aUserOrgs) == 0)
- {
- // No org means 'any org'
- return true;
- }
- return $this->MakeSelectFilter($sClass, $aUserOrgs, $aSettings, $sAttCode);
- }
- // This verb has been made public to allow the development of an accurate feedback for the current configuration
- public function GetProfileActionGrant($iProfile, $sClass, $sAction)
- {
- // Note: action is forced lowercase to be more flexible (historical bug)
- $sAction = strtolower($sAction);
- return ProfilesConfig::GetProfileActionGrant($iProfile, $sClass, $sAction);
- }
- protected function GetUserActionGrant($oUser, $sClass, $iActionCode)
- {
- $this->LoadCache();
- // load and cache permissions for the current user on the given class
- //
- $iUser = $oUser->GetKey();
- $aTest = @$this->m_aObjectActionGrants[$iUser][$sClass][$iActionCode];
- if (is_array($aTest)) return $aTest;
- $sAction = self::$m_aActionCodes[$iActionCode];
- $bStatus = null;
- // Call the API of UserRights because it caches the list for us
- foreach(UserRights::ListProfiles($oUser) as $iProfile => $oProfile)
- {
- $bGrant = $this->GetProfileActionGrant($iProfile, $sClass, $sAction);
- if (!is_null($bGrant))
- {
- if ($bGrant)
- {
- if (is_null($bStatus))
- {
- $bStatus = true;
- }
- }
- else
- {
- $bStatus = false;
- }
- }
- }
- $iPermission = $bStatus ? UR_ALLOWED_YES : UR_ALLOWED_NO;
- $aRes = array(
- 'permission' => $iPermission,
- );
- $this->m_aObjectActionGrants[$iUser][$sClass][$iActionCode] = $aRes;
- return $aRes;
- }
- public function IsActionAllowed($oUser, $sClass, $iActionCode, $oInstanceSet = null)
- {
- $this->LoadCache();
- $aObjectPermissions = $this->GetUserActionGrant($oUser, $sClass, $iActionCode);
- $iPermission = $aObjectPermissions['permission'];
- // Note: In most cases the object set is ignored because it was interesting to optimize for huge data sets
- // and acceptable to consider only the root class of the object set
- if ($iPermission != UR_ALLOWED_YES)
- {
- // It is already NO for everyone... that's the final word!
- }
- elseif ($iActionCode == UR_ACTION_READ)
- {
- // We are protected by GetSelectFilter: the object set contains objects allowed or shared for reading
- }
- elseif ($iActionCode == UR_ACTION_BULK_READ)
- {
- // We are protected by GetSelectFilter: the object set contains objects allowed or shared for reading
- }
- elseif ($oInstanceSet)
- {
- // We are protected by GetSelectFilter: the object set contains objects allowed or shared for reading
- // We have to answer NO for objects shared for reading purposes
- if (self::HasSharing())
- {
- $aClassProps = SharedObject::GetSharedClassProperties($sClass);
- if ($aClassProps)
- {
- // This class is shared, GetSelectFilter may allow some objects for read only
- // But currently we are checking wether the objects might be written...
- // Let's exclude the objects based on the relevant criteria
- $sOrgAttCode = self::GetOwnerOrganizationAttCode($sClass);
- if (!is_null($sOrgAttCode))
- {
- $aUserOrgs = $this->GetUserOrgs($oUser, $sClass);
- if (!is_null($aUserOrgs) && count($aUserOrgs) > 0)
- {
- $iCountNO = 0;
- $iCountYES = 0;
- $oInstanceSet->Rewind();
- while($oObject = $oInstanceSet->Fetch())
- {
- $iOrg = $oObject->Get($sOrgAttCode);
- if (in_array($iOrg, $aUserOrgs))
- {
- $iCountYES++;
- }
- else
- {
- $iCountNO++;
- }
- }
- if ($iCountNO == 0)
- {
- $iPermission = UR_ALLOWED_YES;
- }
- elseif ($iCountYES == 0)
- {
- $iPermission = UR_ALLOWED_NO;
- }
- else
- {
- $iPermission = UR_ALLOWED_DEPENDS;
- }
- }
- }
- }
- }
- }
- return $iPermission;
- }
- public function IsActionAllowedOnAttribute($oUser, $sClass, $sAttCode, $iActionCode, $oInstanceSet = null)
- {
- $this->LoadCache();
- // Note: The object set is ignored because it was interesting to optimize for huge data sets
- // and acceptable to consider only the root class of the object set
- $aObjectPermissions = $this->GetUserActionGrant($oUser, $sClass, $iActionCode);
- return $aObjectPermissions['permission'];
- }
- // This verb has been made public to allow the development of an accurate feedback for the current configuration
- public function GetClassStimulusGrant($iProfile, $sClass, $sStimulusCode)
- {
- return ProfilesConfig::GetProfileStimulusGrant($iProfile, $sClass, $sStimulusCode);
- }
- public function IsStimulusAllowed($oUser, $sClass, $sStimulusCode, $oInstanceSet = null)
- {
- $this->LoadCache();
- // Note: this code is VERY close to the code of IsActionAllowed()
- $iUser = $oUser->GetKey();
- // Note: The object set is ignored because it was interesting to optimize for huge data sets
- // and acceptable to consider only the root class of the object set
- $bStatus = null;
- // Call the API of UserRights because it caches the list for us
- foreach(UserRights::ListProfiles($oUser) as $iProfile => $oProfile)
- {
- $bGrant = $this->GetClassStimulusGrant($iProfile, $sClass, $sStimulusCode);
- if (!is_null($bGrant))
- {
- if ($bGrant)
- {
- if (is_null($bStatus))
- {
- $bStatus = true;
- }
- }
- else
- {
- $bStatus = false;
- }
- }
- }
- $iPermission = $bStatus ? UR_ALLOWED_YES : UR_ALLOWED_NO;
- return $iPermission;
- }
- public function FlushPrivileges()
- {
- $this->ResetCache();
- }
- /**
- * Find out which attribute is corresponding the the dimension 'owner org'
- * returns null if no such attribute has been found (no filtering should occur)
- */
- public static function GetOwnerOrganizationAttCode($sClass)
- {
- $sAttCode = null;
- $aCallSpec = array($sClass, 'MapContextParam');
- if (($sClass == 'Organization') || is_subclass_of($sClass, 'Organization'))
- {
- $sAttCode = 'id';
- }
- elseif (is_callable($aCallSpec))
- {
- $sAttCode = call_user_func($aCallSpec, 'org_id'); // Returns null when there is no mapping for this parameter
- if (!MetaModel::IsValidAttCode($sClass, $sAttCode))
- {
- // Skip silently. The data model checker will tell you something about this...
- $sAttCode = null;
- }
- }
- elseif(MetaModel::IsValidAttCode($sClass, 'org_id'))
- {
- $sAttCode = 'org_id';
- }
- return $sAttCode;
- }
- /**
- * Determine wether the objects can be shared by the mean of a class SharedObject
- **/
- protected static function HasSharing()
- {
- static $bHasSharing;
- if (!isset($bHasSharing))
- {
- $bHasSharing = class_exists('SharedObject');
- }
- return $bHasSharing;
- }
- }
- UserRights::SelectModule('UserRightsProfile');
- ?>
|