userrightsprofile.db.class.inc.php 42 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151
  1. <?php
  2. // Copyright (C) 2010-2012 Combodo SARL
  3. //
  4. // This file is part of iTop.
  5. //
  6. // iTop is free software; you can redistribute it and/or modify
  7. // it under the terms of the GNU Affero General Public License as published by
  8. // the Free Software Foundation, either version 3 of the License, or
  9. // (at your option) any later version.
  10. //
  11. // iTop is distributed in the hope that it will be useful,
  12. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. // GNU Affero General Public License for more details.
  15. //
  16. // You should have received a copy of the GNU Affero General Public License
  17. // along with iTop. If not, see <http://www.gnu.org/licenses/>
  18. /**
  19. * UserRightsProfile
  20. * User management Module, basing the right on profiles and a matrix (similar to UserRightsMatrix, but profiles and other decorations have been added)
  21. *
  22. * @copyright Copyright (C) 2010-2012 Combodo SARL
  23. * @license http://opensource.org/licenses/AGPL-3.0
  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 UserRightsBaseClass extends DBObject
  44. {
  45. // Whenever something changes, reload the privileges
  46. protected function AfterInsert()
  47. {
  48. UserRights::FlushPrivileges();
  49. }
  50. protected function AfterUpdate()
  51. {
  52. UserRights::FlushPrivileges();
  53. }
  54. protected function AfterDelete()
  55. {
  56. UserRights::FlushPrivileges();
  57. }
  58. }
  59. class URP_Profiles extends UserRightsBaseClassGUI
  60. {
  61. public static function Init()
  62. {
  63. $aParams = array
  64. (
  65. "category" => "addon/userrights",
  66. "key_type" => "autoincrement",
  67. "name_attcode" => "name",
  68. "state_attcode" => "",
  69. "reconc_keys" => array(),
  70. "db_table" => "priv_urp_profiles",
  71. "db_key_field" => "id",
  72. "db_finalclass_field" => "",
  73. "display_template" => "",
  74. );
  75. MetaModel::Init_Params($aParams);
  76. //MetaModel::Init_InheritAttributes();
  77. MetaModel::Init_AddAttribute(new AttributeString("name", array("allowed_values"=>null, "sql"=>"name", "default_value"=>null, "is_null_allowed"=>false, "depends_on"=>array())));
  78. MetaModel::Init_AddAttribute(new AttributeString("description", array("allowed_values"=>null, "sql"=>"description", "default_value"=>null, "is_null_allowed"=>false, "depends_on"=>array())));
  79. 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())));
  80. // Display lists
  81. MetaModel::Init_SetZListItems('details', array('name', 'description', 'user_list')); // Attributes to be displayed for the complete details
  82. MetaModel::Init_SetZListItems('list', array('description')); // Attributes to be displayed for a list
  83. // Search criteria
  84. MetaModel::Init_SetZListItems('standard_search', array('name')); // Criteria of the std search form
  85. MetaModel::Init_SetZListItems('advanced_search', array('name')); // Criteria of the advanced search form
  86. }
  87. protected $m_bCheckReservedNames = true;
  88. protected function DisableCheckOnReservedNames()
  89. {
  90. $this->m_bCheckReservedNames = false;
  91. }
  92. protected static $m_aActions = array(
  93. UR_ACTION_READ => 'Read',
  94. UR_ACTION_MODIFY => 'Modify',
  95. UR_ACTION_DELETE => 'Delete',
  96. UR_ACTION_BULK_READ => 'Bulk Read',
  97. UR_ACTION_BULK_MODIFY => 'Bulk Modify',
  98. UR_ACTION_BULK_DELETE => 'Bulk Delete',
  99. );
  100. protected static $m_aCacheActionGrants = null;
  101. protected static $m_aCacheStimulusGrants = null;
  102. protected static $m_aCacheProfiles = null;
  103. public static function DoCreateProfile($sName, $sDescription, $bReservedName = false)
  104. {
  105. if (is_null(self::$m_aCacheProfiles))
  106. {
  107. self::$m_aCacheProfiles = array();
  108. $oFilterAll = new DBObjectSearch('URP_Profiles');
  109. $oSet = new DBObjectSet($oFilterAll);
  110. while ($oProfile = $oSet->Fetch())
  111. {
  112. self::$m_aCacheProfiles[$oProfile->Get('name')] = $oProfile->GetKey();
  113. }
  114. }
  115. $sCacheKey = $sName;
  116. if (isset(self::$m_aCacheProfiles[$sCacheKey]))
  117. {
  118. return self::$m_aCacheProfiles[$sCacheKey];
  119. }
  120. $oNewObj = MetaModel::NewObject("URP_Profiles");
  121. $oNewObj->Set('name', $sName);
  122. $oNewObj->Set('description', $sDescription);
  123. if ($bReservedName)
  124. {
  125. $oNewObj->DisableCheckOnReservedNames();
  126. }
  127. $iId = $oNewObj->DBInsertNoReload();
  128. self::$m_aCacheProfiles[$sCacheKey] = $iId;
  129. return $iId;
  130. }
  131. public static function DoCreateActionGrant($iProfile, $iAction, $sClass, $bPermission = true)
  132. {
  133. $sAction = self::$m_aActions[$iAction];
  134. if (is_null(self::$m_aCacheActionGrants))
  135. {
  136. self::$m_aCacheActionGrants = array();
  137. $oFilterAll = new DBObjectSearch('URP_ActionGrant');
  138. $oSet = new DBObjectSet($oFilterAll);
  139. while ($oGrant = $oSet->Fetch())
  140. {
  141. self::$m_aCacheActionGrants[$oGrant->Get('profileid').'-'.$oGrant->Get('action').'-'.$oGrant->Get('class')] = $oGrant->GetKey();
  142. }
  143. }
  144. $sCacheKey = "$iProfile-$sAction-$sClass";
  145. if (isset(self::$m_aCacheActionGrants[$sCacheKey]))
  146. {
  147. return self::$m_aCacheActionGrants[$sCacheKey];
  148. }
  149. $oNewObj = MetaModel::NewObject("URP_ActionGrant");
  150. $oNewObj->Set('profileid', $iProfile);
  151. $oNewObj->Set('permission', $bPermission ? 'yes' : 'no');
  152. $oNewObj->Set('class', $sClass);
  153. $oNewObj->Set('action', $sAction);
  154. $iId = $oNewObj->DBInsertNoReload();
  155. self::$m_aCacheActionGrants[$sCacheKey] = $iId;
  156. return $iId;
  157. }
  158. public static function DoCreateStimulusGrant($iProfile, $sStimulusCode, $sClass)
  159. {
  160. if (is_null(self::$m_aCacheStimulusGrants))
  161. {
  162. self::$m_aCacheStimulusGrants = array();
  163. $oFilterAll = new DBObjectSearch('URP_StimulusGrant');
  164. $oSet = new DBObjectSet($oFilterAll);
  165. while ($oGrant = $oSet->Fetch())
  166. {
  167. self::$m_aCacheStimulusGrants[$oGrant->Get('profileid').'-'.$oGrant->Get('stimulus').'-'.$oGrant->Get('class')] = $oGrant->GetKey();
  168. }
  169. }
  170. $sCacheKey = "$iProfile-$sStimulusCode-$sClass";
  171. if (isset(self::$m_aCacheStimulusGrants[$sCacheKey]))
  172. {
  173. return self::$m_aCacheStimulusGrants[$sCacheKey];
  174. }
  175. $oNewObj = MetaModel::NewObject("URP_StimulusGrant");
  176. $oNewObj->Set('profileid', $iProfile);
  177. $oNewObj->Set('permission', 'yes');
  178. $oNewObj->Set('class', $sClass);
  179. $oNewObj->Set('stimulus', $sStimulusCode);
  180. $iId = $oNewObj->DBInsertNoReload();
  181. self::$m_aCacheStimulusGrants[$sCacheKey] = $iId;
  182. return $iId;
  183. }
  184. /*
  185. * Create the built-in Administrator profile with its reserved name
  186. */
  187. public static function DoCreateAdminProfile()
  188. {
  189. self::DoCreateProfile(ADMIN_PROFILE_NAME, 'Has the rights on everything (bypassing any control)', true /* reserved name */);
  190. }
  191. /*
  192. * Overload the standard behavior to preserve reserved names
  193. */
  194. public function DoCheckToWrite()
  195. {
  196. parent::DoCheckToWrite();
  197. if ($this->m_bCheckReservedNames)
  198. {
  199. $aChanges = $this->ListChanges();
  200. if (array_key_exists('name', $aChanges))
  201. {
  202. if ($this->GetOriginal('name') == ADMIN_PROFILE_NAME)
  203. {
  204. $this->m_aCheckIssues[] = "The name of the Administrator profile must not be changed";
  205. }
  206. elseif ($this->Get('name') == ADMIN_PROFILE_NAME)
  207. {
  208. $this->m_aCheckIssues[] = ADMIN_PROFILE_NAME." is a reserved to the built-in Administrator profile";
  209. }
  210. elseif ($this->GetOriginal('name') == PORTAL_PROFILE_NAME)
  211. {
  212. $this->m_aCheckIssues[] = "The name of the User Portal profile must not be changed";
  213. }
  214. elseif ($this->Get('name') == PORTAL_PROFILE_NAME)
  215. {
  216. $this->m_aCheckIssues[] = PORTAL_PROFILE_NAME." is a reserved to the built-in User Portal profile";
  217. }
  218. }
  219. }
  220. }
  221. function GetGrantAsHtml($oUserRights, $sClass, $sAction)
  222. {
  223. $iGrant = $oUserRights->GetProfileActionGrant($this->GetKey(), $sClass, $sAction);
  224. if (!is_null($iGrant))
  225. {
  226. return '<span style="background-color: #ddffdd;">'.Dict::S('UI:UserManagement:ActionAllowed:Yes').'</span>';
  227. }
  228. else
  229. {
  230. return '<span style="background-color: #ffdddd;">'.Dict::S('UI:UserManagement:ActionAllowed:No').'</span>';
  231. }
  232. }
  233. function DoShowGrantSumary($oPage)
  234. {
  235. if ($this->GetRawName() == "Administrator")
  236. {
  237. // Looks dirty, but ok that's THE ONE
  238. $oPage->p(Dict::S('UI:UserManagement:AdminProfile+'));
  239. return;
  240. }
  241. // Note: for sure, we assume that the instance is derived from UserRightsProfile
  242. $oUserRights = UserRights::GetModuleInstance();
  243. $aDisplayData = array();
  244. foreach (MetaModel::GetClasses('bizmodel') as $sClass)
  245. {
  246. // Skip non instantiable classes
  247. if (MetaModel::IsAbstract($sClass)) continue;
  248. $aStimuli = array();
  249. foreach (MetaModel::EnumStimuli($sClass) as $sStimulusCode => $oStimulus)
  250. {
  251. $oGrant = $oUserRights->GetClassStimulusGrant($this->GetKey(), $sClass, $sStimulusCode);
  252. if (is_object($oGrant) && ($oGrant->Get('permission') == 'yes'))
  253. {
  254. $aStimuli[] = '<span title="'.$sStimulusCode.': '.htmlentities($oStimulus->GetDescription(), ENT_QUOTES, 'UTF-8').'">'.htmlentities($oStimulus->GetLabel(), ENT_QUOTES, 'UTF-8').'</span>';
  255. }
  256. }
  257. $sStimuli = implode(', ', $aStimuli);
  258. $aDisplayData[] = array(
  259. 'class' => MetaModel::GetName($sClass),
  260. 'read' => $this->GetGrantAsHtml($oUserRights, $sClass, 'Read'),
  261. 'bulkread' => $this->GetGrantAsHtml($oUserRights, $sClass, 'Bulk Read'),
  262. 'write' => $this->GetGrantAsHtml($oUserRights, $sClass, 'Modify'),
  263. 'bulkwrite' => $this->GetGrantAsHtml($oUserRights, $sClass, 'Bulk Modify'),
  264. 'delete' => $this->GetGrantAsHtml($oUserRights, $sClass, 'Delete'),
  265. 'bulkdelete' => $this->GetGrantAsHtml($oUserRights, $sClass, 'Bulk Delete'),
  266. 'stimuli' => $sStimuli,
  267. );
  268. }
  269. $aDisplayConfig = array();
  270. $aDisplayConfig['class'] = array('label' => Dict::S('UI:UserManagement:Class'), 'description' => Dict::S('UI:UserManagement:Class+'));
  271. $aDisplayConfig['read'] = array('label' => Dict::S('UI:UserManagement:Action:Read'), 'description' => Dict::S('UI:UserManagement:Action:Read+'));
  272. $aDisplayConfig['bulkread'] = array('label' => Dict::S('UI:UserManagement:Action:BulkRead'), 'description' => Dict::S('UI:UserManagement:Action:BulkRead+'));
  273. $aDisplayConfig['write'] = array('label' => Dict::S('UI:UserManagement:Action:Modify'), 'description' => Dict::S('UI:UserManagement:Action:Modify+'));
  274. $aDisplayConfig['bulkwrite'] = array('label' => Dict::S('UI:UserManagement:Action:BulkModify'), 'description' => Dict::S('UI:UserManagement:Action:BulkModify+'));
  275. $aDisplayConfig['delete'] = array('label' => Dict::S('UI:UserManagement:Action:Delete'), 'description' => Dict::S('UI:UserManagement:Action:Delete+'));
  276. $aDisplayConfig['bulkdelete'] = array('label' => Dict::S('UI:UserManagement:Action:BulkDelete'), 'description' => Dict::S('UI:UserManagement:Action:BulkDelete+'));
  277. $aDisplayConfig['stimuli'] = array('label' => Dict::S('UI:UserManagement:Action:Stimuli'), 'description' => Dict::S('UI:UserManagement:Action:Stimuli+'));
  278. $oPage->table($aDisplayConfig, $aDisplayData);
  279. }
  280. function DisplayBareRelations(WebPage $oPage, $bEditMode = false)
  281. {
  282. parent::DisplayBareRelations($oPage, $bEditMode);
  283. if (!$bEditMode)
  284. {
  285. $oPage->SetCurrentTab(Dict::S('UI:UserManagement:GrantMatrix'));
  286. $this->DoShowGrantSumary($oPage);
  287. }
  288. }
  289. }
  290. class URP_UserProfile extends UserRightsBaseClassGUI
  291. {
  292. public static function Init()
  293. {
  294. $aParams = array
  295. (
  296. "category" => "addon/userrights",
  297. "key_type" => "autoincrement",
  298. "name_attcode" => "userid",
  299. "state_attcode" => "",
  300. "reconc_keys" => array(),
  301. "db_table" => "priv_urp_userprofile",
  302. "db_key_field" => "id",
  303. "db_finalclass_field" => "",
  304. "display_template" => "",
  305. );
  306. MetaModel::Init_Params($aParams);
  307. //MetaModel::Init_InheritAttributes();
  308. 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())));
  309. MetaModel::Init_AddAttribute(new AttributeExternalField("userlogin", array("allowed_values"=>null, "extkey_attcode"=> 'userid', "target_attcode"=>"login")));
  310. 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())));
  311. MetaModel::Init_AddAttribute(new AttributeExternalField("profile", array("allowed_values"=>null, "extkey_attcode"=> 'profileid', "target_attcode"=>"name")));
  312. MetaModel::Init_AddAttribute(new AttributeString("reason", array("allowed_values"=>null, "sql"=>"description", "default_value"=>null, "is_null_allowed"=>true, "depends_on"=>array())));
  313. // Display lists
  314. MetaModel::Init_SetZListItems('details', array('userid', 'profileid', 'reason')); // Attributes to be displayed for the complete details
  315. MetaModel::Init_SetZListItems('list', array('userid', 'profileid', 'reason')); // Attributes to be displayed for a list
  316. // Search criteria
  317. MetaModel::Init_SetZListItems('standard_search', array('userid', 'profileid')); // Criteria of the std search form
  318. MetaModel::Init_SetZListItems('advanced_search', array('userid', 'profileid')); // Criteria of the advanced search form
  319. }
  320. public function GetName()
  321. {
  322. return Dict::Format('UI:UserManagement:LinkBetween_User_And_Profile', $this->Get('userlogin'), $this->Get('profile'));
  323. }
  324. }
  325. class URP_UserOrg extends UserRightsBaseClassGUI
  326. {
  327. public static function Init()
  328. {
  329. $aParams = array
  330. (
  331. "category" => "addon/userrights",
  332. "key_type" => "autoincrement",
  333. "name_attcode" => "userid",
  334. "state_attcode" => "",
  335. "reconc_keys" => array(),
  336. "db_table" => "priv_urp_userorg",
  337. "db_key_field" => "id",
  338. "db_finalclass_field" => "",
  339. "display_template" => "",
  340. );
  341. MetaModel::Init_Params($aParams);
  342. //MetaModel::Init_InheritAttributes();
  343. 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())));
  344. MetaModel::Init_AddAttribute(new AttributeExternalField("userlogin", array("allowed_values"=>null, "extkey_attcode"=> 'userid', "target_attcode"=>"login")));
  345. 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())));
  346. MetaModel::Init_AddAttribute(new AttributeExternalField("allowed_org_name", array("allowed_values"=>null, "extkey_attcode"=> 'allowed_org_id', "target_attcode"=>"name")));
  347. MetaModel::Init_AddAttribute(new AttributeString("reason", array("allowed_values"=>null, "sql"=>"reason", "default_value"=>null, "is_null_allowed"=>true, "depends_on"=>array())));
  348. // Display lists
  349. MetaModel::Init_SetZListItems('details', array('userid', 'allowed_org_id', 'reason')); // Attributes to be displayed for the complete details
  350. MetaModel::Init_SetZListItems('list', array('allowed_org_id', 'reason')); // Attributes to be displayed for a list
  351. // Search criteria
  352. MetaModel::Init_SetZListItems('standard_search', array('userid', 'allowed_org_id')); // Criteria of the std search form
  353. MetaModel::Init_SetZListItems('advanced_search', array('userid', 'allowed_org_id')); // Criteria of the advanced search form
  354. }
  355. public function GetName()
  356. {
  357. return Dict::Format('UI:UserManagement:LinkBetween_User_And_Org', $this->Get('userlogin'), $this->Get('allowed_org_name'));
  358. }
  359. }
  360. class URP_ActionGrant extends UserRightsBaseClass
  361. {
  362. public static function Init()
  363. {
  364. $aParams = array
  365. (
  366. "category" => "addon/userrights",
  367. "key_type" => "autoincrement",
  368. "name_attcode" => "profileid",
  369. "state_attcode" => "",
  370. "reconc_keys" => array(),
  371. "db_table" => "priv_urp_grant_actions",
  372. "db_key_field" => "id",
  373. "db_finalclass_field" => "",
  374. "display_template" => "",
  375. );
  376. MetaModel::Init_Params($aParams);
  377. //MetaModel::Init_InheritAttributes();
  378. // Common to all grant classes (could be factorized by class inheritence, but this has to be benchmarked)
  379. MetaModel::Init_AddAttribute(new AttributeExternalKey("profileid", array("targetclass"=>"URP_Profiles", "jointype"=> "", "allowed_values"=>null, "sql"=>"profileid", "is_null_allowed"=>false, "on_target_delete"=>DEL_MANUAL, "depends_on"=>array())));
  380. MetaModel::Init_AddAttribute(new AttributeExternalField("profile", array("allowed_values"=>null, "extkey_attcode"=> 'profileid', "target_attcode"=>"name")));
  381. MetaModel::Init_AddAttribute(new AttributeClass("class", array("class_category"=>"", "more_values"=>"", "sql"=>"class", "default_value"=>null, "is_null_allowed"=>false, "depends_on"=>array())));
  382. MetaModel::Init_AddAttribute(new AttributeEnum("permission", array("allowed_values"=>new ValueSetEnum('yes,no'), "sql"=>"permission", "default_value"=>"yes", "is_null_allowed"=>false, "depends_on"=>array())));
  383. MetaModel::Init_AddAttribute(new AttributeString("action", array("allowed_values"=>null, "sql"=>"action", "default_value"=>"", "is_null_allowed"=>false, "depends_on"=>array())));
  384. // Display lists
  385. MetaModel::Init_SetZListItems('details', array('profileid', 'class', 'permission', 'action')); // Attributes to be displayed for the complete details
  386. MetaModel::Init_SetZListItems('list', array('class', 'permission', 'action')); // Attributes to be displayed for a list
  387. // Search criteria
  388. MetaModel::Init_SetZListItems('standard_search', array('profileid', 'class', 'permission', 'action')); // Criteria of the std search form
  389. MetaModel::Init_SetZListItems('advanced_search', array('profileid', 'class', 'permission', 'action')); // Criteria of the advanced search form
  390. }
  391. }
  392. class URP_StimulusGrant extends UserRightsBaseClass
  393. {
  394. public static function Init()
  395. {
  396. $aParams = array
  397. (
  398. "category" => "addon/userrights",
  399. "key_type" => "autoincrement",
  400. "name_attcode" => "profileid",
  401. "state_attcode" => "",
  402. "reconc_keys" => array(),
  403. "db_table" => "priv_urp_grant_stimulus",
  404. "db_key_field" => "id",
  405. "db_finalclass_field" => "",
  406. "display_template" => "",
  407. );
  408. MetaModel::Init_Params($aParams);
  409. //MetaModel::Init_InheritAttributes();
  410. // Common to all grant classes (could be factorized by class inheritence, but this has to be benchmarked)
  411. MetaModel::Init_AddAttribute(new AttributeExternalKey("profileid", array("targetclass"=>"URP_Profiles", "jointype"=> "", "allowed_values"=>null, "sql"=>"profileid", "is_null_allowed"=>false, "on_target_delete"=>DEL_MANUAL, "depends_on"=>array())));
  412. MetaModel::Init_AddAttribute(new AttributeExternalField("profile", array("allowed_values"=>null, "extkey_attcode"=> 'profileid', "target_attcode"=>"name")));
  413. MetaModel::Init_AddAttribute(new AttributeClass("class", array("class_category"=>"", "more_values"=>"", "sql"=>"class", "default_value"=>null, "is_null_allowed"=>false, "depends_on"=>array())));
  414. MetaModel::Init_AddAttribute(new AttributeEnum("permission", array("allowed_values"=>new ValueSetEnum('yes,no'), "sql"=>"permission", "default_value"=>"yes", "is_null_allowed"=>false, "depends_on"=>array())));
  415. MetaModel::Init_AddAttribute(new AttributeString("stimulus", array("allowed_values"=>null, "sql"=>"action", "default_value"=>"", "is_null_allowed"=>false, "depends_on"=>array())));
  416. // Display lists
  417. MetaModel::Init_SetZListItems('details', array('profileid', 'class', 'permission', 'stimulus')); // Attributes to be displayed for the complete details
  418. MetaModel::Init_SetZListItems('list', array('class', 'permission', 'stimulus')); // Attributes to be displayed for a list
  419. // Search criteria
  420. MetaModel::Init_SetZListItems('standard_search', array('profileid', 'class', 'permission', 'stimulus')); // Criteria of the std search form
  421. MetaModel::Init_SetZListItems('advanced_search', array('profileid', 'class', 'permission', 'stimulus')); // Criteria of the advanced search form
  422. }
  423. }
  424. class URP_AttributeGrant extends UserRightsBaseClass
  425. {
  426. public static function Init()
  427. {
  428. $aParams = array
  429. (
  430. "category" => "addon/userrights",
  431. "key_type" => "autoincrement",
  432. "name_attcode" => "actiongrantid",
  433. "state_attcode" => "",
  434. "reconc_keys" => array(),
  435. "db_table" => "priv_urp_grant_attributes",
  436. "db_key_field" => "id",
  437. "db_finalclass_field" => "",
  438. "display_template" => "",
  439. );
  440. MetaModel::Init_Params($aParams);
  441. //MetaModel::Init_InheritAttributes();
  442. MetaModel::Init_AddAttribute(new AttributeExternalKey("actiongrantid", array("targetclass"=>"URP_ActionGrant", "jointype"=> "", "allowed_values"=>null, "sql"=>"actiongrantid", "is_null_allowed"=>false, "on_target_delete"=>DEL_MANUAL, "depends_on"=>array())));
  443. MetaModel::Init_AddAttribute(new AttributeString("attcode", array("allowed_values"=>null, "sql"=>"attcode", "default_value"=>null, "is_null_allowed"=>false, "depends_on"=>array())));
  444. // Display lists
  445. MetaModel::Init_SetZListItems('details', array('actiongrantid', 'attcode')); // Attributes to be displayed for the complete details
  446. MetaModel::Init_SetZListItems('list', array('attcode')); // Attributes to be displayed for a list
  447. // Search criteria
  448. MetaModel::Init_SetZListItems('standard_search', array('actiongrantid', 'attcode')); // Criteria of the std search form
  449. MetaModel::Init_SetZListItems('advanced_search', array('actiongrantid', 'attcode')); // Criteria of the advanced search form
  450. }
  451. }
  452. class UserRightsProfile extends UserRightsAddOnAPI
  453. {
  454. static public $m_aActionCodes = array(
  455. UR_ACTION_READ => 'read',
  456. UR_ACTION_MODIFY => 'modify',
  457. UR_ACTION_DELETE => 'delete',
  458. UR_ACTION_BULK_READ => 'bulk read',
  459. UR_ACTION_BULK_MODIFY => 'bulk modify',
  460. UR_ACTION_BULK_DELETE => 'bulk delete',
  461. );
  462. // Installation: create the very first user
  463. public function CreateAdministrator($sAdminUser, $sAdminPwd, $sLanguage = 'EN US')
  464. {
  465. // Create a change to record the history of the User object
  466. $oChange = MetaModel::NewObject("CMDBChange");
  467. $oChange->Set("date", time());
  468. $oChange->Set("userinfo", "Initialization");
  469. $iChangeId = $oChange->DBInsert();
  470. $iContactId = 0;
  471. // Support drastic data model changes: no organization class (or not writable)!
  472. if (MetaModel::IsValidClass('Organization') && !MetaModel::IsAbstract('Organization'))
  473. {
  474. $oOrg = new Organization();
  475. $oOrg->Set('name', 'My Company/Department');
  476. $oOrg->Set('code', 'SOMECODE');
  477. $iOrgId = $oOrg->DBInsertTrackedNoReload($oChange, true /* skip security */);
  478. // Support drastic data model changes: no Person class (or not writable)!
  479. if (MetaModel::IsValidClass('Person') && !MetaModel::IsAbstract('Person'))
  480. {
  481. $oContact = new Person();
  482. $oContact->Set('name', 'My last name');
  483. $oContact->Set('first_name', 'My first name');
  484. if (MetaModel::IsValidAttCode('Person', 'org_id'))
  485. {
  486. $oContact->Set('org_id', $iOrgId);
  487. }
  488. if (MetaModel::IsValidAttCode('Person', 'phone'))
  489. {
  490. $oContact->Set('phone', '+00 000 000 000');
  491. }
  492. $oContact->Set('email', 'my.email@foo.org');
  493. $iContactId = $oContact->DBInsertTrackedNoReload($oChange, true /* skip security */);
  494. }
  495. }
  496. $oUser = new UserLocal();
  497. $oUser->Set('login', $sAdminUser);
  498. $oUser->Set('password', $sAdminPwd);
  499. if (MetaModel::IsValidAttCode('UserLocal', 'contactid') && ($iContactId != 0))
  500. {
  501. $oUser->Set('contactid', $iContactId);
  502. }
  503. $oUser->Set('language', $sLanguage); // Language was chosen during the installation
  504. // Add this user to the very specific 'admin' profile
  505. $oAdminProfile = MetaModel::GetObjectFromOQL("SELECT URP_Profiles WHERE name = :name", array('name' => ADMIN_PROFILE_NAME), true /*all data*/);
  506. if (is_object($oAdminProfile))
  507. {
  508. $oUserProfile = new URP_UserProfile();
  509. //$oUserProfile->Set('userid', $iUserId);
  510. $oUserProfile->Set('profileid', $oAdminProfile->GetKey());
  511. $oUserProfile->Set('reason', 'By definition, the administrator must have the administrator profile');
  512. //$oUserProfile->DBInsertTrackedNoReload($oChange, true /* skip security */);
  513. $oSet = DBObjectSet::FromObject($oUserProfile);
  514. $oUser->Set('profile_list', $oSet);
  515. }
  516. $iUserId = $oUser->DBInsertTrackedNoReload($oChange, true /* skip security */);
  517. return true;
  518. }
  519. public function Init()
  520. {
  521. }
  522. protected $m_aAdmins = array(); // id -> bool, true if the user has the well-known admin profile
  523. protected $m_aPortalUsers = array(); // id -> bool, true if the user has the well-known portal user profile
  524. protected $m_aProfiles; // id -> object
  525. protected $m_aUserProfiles = array(); // userid,profileid -> object
  526. protected $m_aUserOrgs = array(); // userid -> array of orgid
  527. // Those arrays could be completed on demand (inheriting parent permissions)
  528. protected $m_aClassActionGrants = null; // profile, class, action -> actiongrantid (or false if NO, or null/missing if undefined)
  529. protected $m_aClassStimulusGrants = array(); // profile, class, stimulus -> permission
  530. // Built on demand, could be optimized if necessary (doing a query for each attribute that needs to be read)
  531. protected $m_aObjectActionGrants = array();
  532. /**
  533. * Read and cache organizations allowed to the given user
  534. *
  535. * @param oUser
  536. * @param sClass -not used here but can be used in overloads
  537. */
  538. protected function GetUserOrgs($oUser, $sClass)
  539. {
  540. $iUser = $oUser->GetKey();
  541. if (!array_key_exists($iUser, $this->m_aUserOrgs))
  542. {
  543. $this->m_aUserOrgs[$iUser] = array();
  544. $sHierarchicalKeyCode = MetaModel::IsHierarchicalClass('Organization');
  545. if ($sHierarchicalKeyCode !== false)
  546. {
  547. $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';
  548. $oUserOrgSet = new DBObjectSet(DBObjectSearch::FromOQL_AllData($sUserOrgQuery), array(), array('userid' => $iUser));
  549. while ($aRow = $oUserOrgSet->FetchAssoc())
  550. {
  551. $oUserOrg = $aRow['UserOrg'];
  552. $oOrg = $aRow['Org'];
  553. $this->m_aUserOrgs[$iUser][] = $oOrg->GetKey();
  554. }
  555. }
  556. else
  557. {
  558. $oSearch = new DBObjectSearch('URP_UserOrg');
  559. $oSearch->AllowAllData();
  560. $oCondition = new BinaryExpression(new FieldExpression('userid'), '=', new VariableExpression('userid'));
  561. $oSearch->AddConditionExpression($oCondition);
  562. $oUserOrgSet = new DBObjectSet($oSearch, array(), array('userid' => $iUser));
  563. while ($oUserOrg = $oUserOrgSet->Fetch())
  564. {
  565. $this->m_aUserOrgs[$iUser][] = $oUserOrg->Get('allowed_org_id');
  566. }
  567. }
  568. }
  569. return $this->m_aUserOrgs[$iUser];
  570. }
  571. /**
  572. * Read and cache profiles of the given user
  573. */
  574. protected function GetUserProfiles($iUser)
  575. {
  576. if (!array_key_exists($iUser, $this->m_aUserProfiles))
  577. {
  578. $oSearch = new DBObjectSearch('URP_UserProfile');
  579. $oSearch->AllowAllData();
  580. $oCondition = new BinaryExpression(new FieldExpression('userid'), '=', new VariableExpression('userid'));
  581. $oSearch->AddConditionExpression($oCondition);
  582. $this->m_aUserProfiles[$iUser] = array();
  583. $oUserProfileSet = new DBObjectSet($oSearch, array(), array('userid' => $iUser));
  584. while ($oUserProfile = $oUserProfileSet->Fetch())
  585. {
  586. $this->m_aUserProfiles[$iUser][$oUserProfile->Get('profileid')] = $oUserProfile;
  587. }
  588. }
  589. return $this->m_aUserProfiles[$iUser];
  590. }
  591. public function ResetCache()
  592. {
  593. // Loaded by Load cache
  594. $this->m_aProfiles = null;
  595. $this->m_aUserProfiles = array();
  596. $this->m_aUserOrgs = array();
  597. $this->m_aAdmins = array();
  598. $this->m_aPortalUsers = array();
  599. // Loaded on demand (time consuming as compared to the others)
  600. $this->m_aClassActionGrants = null;
  601. $this->m_aClassStimulusGrants = null;
  602. $this->m_aObjectActionGrants = array();
  603. }
  604. // Separate load: this cache is much more time consuming while loading
  605. // Thus it is loaded iif required
  606. // Could be improved by specifying the profile id
  607. public function LoadActionGrantCache()
  608. {
  609. if (!is_null($this->m_aClassActionGrants)) return;
  610. $oKPI = new ExecutionKPI();
  611. $oFilter = DBObjectSearch::FromOQL_AllData("SELECT URP_ActionGrant AS p WHERE p.permission = 'yes'");
  612. $aGrants = $oFilter->ToDataArray();
  613. foreach($aGrants as $aGrant)
  614. {
  615. $this->m_aClassActionGrants[$aGrant['profileid']][$aGrant['class']][strtolower($aGrant['action'])] = $aGrant['id'];
  616. }
  617. $oKPI->ComputeAndReport('Load of action grants');
  618. }
  619. public function LoadCache()
  620. {
  621. if (!is_null($this->m_aProfiles)) return;
  622. // Could be loaded in a shared memory (?)
  623. $oKPI = new ExecutionKPI();
  624. if (self::HasSharing())
  625. {
  626. SharedObject::InitSharedClassProperties();
  627. }
  628. $oProfileSet = new DBObjectSet(DBObjectSearch::FromOQL_AllData("SELECT URP_Profiles"));
  629. $this->m_aProfiles = array();
  630. while ($oProfile = $oProfileSet->Fetch())
  631. {
  632. $this->m_aProfiles[$oProfile->GetKey()] = $oProfile;
  633. }
  634. $this->m_aClassStimulusGrants = array();
  635. $oStimGrantSet = new DBObjectSet(DBObjectSearch::FromOQL_AllData("SELECT URP_StimulusGrant"));
  636. $this->m_aStimGrants = array();
  637. while ($oStimGrant = $oStimGrantSet->Fetch())
  638. {
  639. $this->m_aClassStimulusGrants[$oStimGrant->Get('profileid')][$oStimGrant->Get('class')][$oStimGrant->Get('stimulus')] = $oStimGrant;
  640. }
  641. $oKPI->ComputeAndReport('Load of user management cache (excepted Action Grants)');
  642. /*
  643. echo "<pre>\n";
  644. print_r($this->m_aProfiles);
  645. print_r($this->m_aUserProfiles);
  646. print_r($this->m_aUserOrgs);
  647. print_r($this->m_aClassActionGrants);
  648. print_r($this->m_aClassStimulusGrants);
  649. echo "</pre>\n";
  650. exit;
  651. */
  652. return true;
  653. }
  654. public function IsAdministrator($oUser)
  655. {
  656. //$this->LoadCache();
  657. $iUser = $oUser->GetKey();
  658. if (!array_key_exists($iUser, $this->m_aAdmins))
  659. {
  660. $bIsAdmin = false;
  661. foreach($this->GetUserProfiles($iUser) as $oUserProfile)
  662. {
  663. if ($oUserProfile->Get('profile') == ADMIN_PROFILE_NAME)
  664. {
  665. $bIsAdmin = true;
  666. break;
  667. }
  668. }
  669. $this->m_aAdmins[$iUser] = $bIsAdmin;
  670. }
  671. return $this->m_aAdmins[$iUser];
  672. }
  673. public function IsPortalUser($oUser)
  674. {
  675. //$this->LoadCache();
  676. $iUser = $oUser->GetKey();
  677. if (!array_key_exists($iUser, $this->m_aPortalUsers))
  678. {
  679. $bIsPortalUser = false;
  680. foreach($this->GetUserProfiles($iUser) as $oUserProfile)
  681. {
  682. if ($oUserProfile->Get('profile') == PORTAL_PROFILE_NAME)
  683. {
  684. $bIsPortalUser = true;
  685. break;
  686. }
  687. }
  688. $this->m_aPortalUsers[$iUser] = $bIsPortalUser;
  689. }
  690. return $this->m_aPortalUsers[$iUser];
  691. }
  692. public function GetSelectFilter($oUser, $sClass, $aSettings = array())
  693. {
  694. $this->LoadCache();
  695. $aObjectPermissions = $this->GetUserActionGrant($oUser, $sClass, UR_ACTION_READ);
  696. if ($aObjectPermissions['permission'] == UR_ALLOWED_NO)
  697. {
  698. return false;
  699. }
  700. // Determine how to position the objects of this class
  701. //
  702. $sAttCode = self::GetOwnerOrganizationAttCode($sClass);
  703. if (is_null($sAttCode))
  704. {
  705. // No filtering for this object
  706. return true;
  707. }
  708. // Position the user
  709. //
  710. $aUserOrgs = $this->GetUserOrgs($oUser, $sClass);
  711. if (count($aUserOrgs) == 0)
  712. {
  713. // No org means 'any org'
  714. return true;
  715. }
  716. $oExpression = new FieldExpression($sAttCode, $sClass);
  717. $oFilter = new DBObjectSearch($sClass);
  718. $oListExpr = ListExpression::FromScalars($aUserOrgs);
  719. $oCondition = new BinaryExpression($oExpression, 'IN', $oListExpr);
  720. $oFilter->AddConditionExpression($oCondition);
  721. if (self::HasSharing())
  722. {
  723. if (($sAttCode == 'id') && isset($aSettings['bSearchMode']) && $aSettings['bSearchMode'])
  724. {
  725. // Querying organizations (or derived)
  726. // and the expected list of organizations will be used as a search criteria
  727. // Therefore the query can also return organization having objects shared with the allowed organizations
  728. //
  729. // 1) build the list of organizations sharing something with the allowed organizations
  730. // Organization <== sharing_org_id == SharedObject having org_id IN {user orgs}
  731. $oShareSearch = new DBObjectSearch('SharedObject');
  732. $oOrgField = new FieldExpression('org_id', 'SharedObject');
  733. $oShareSearch->AddConditionExpression(new BinaryExpression($oOrgField, 'IN', $oListExpr));
  734. $oSearchSharers = new DBObjectSearch('Organization');
  735. $oSearchSharers->AllowAllData();
  736. $oSearchSharers->AddCondition_ReferencedBy($oShareSearch, 'sharing_org_id');
  737. $aSharers = array();
  738. foreach($oSearchSharers->ToDataArray(array('id')) as $aRow)
  739. {
  740. $aSharers[] = $aRow['id'];
  741. }
  742. // 2) Enlarge the overall results: ... OR id IN(id1, id2, id3)
  743. if (count($aSharers) > 0)
  744. {
  745. $oSharersList = ListExpression::FromScalars($aSharers);
  746. $oFilter->MergeConditionExpression(new BinaryExpression($oExpression, 'IN', $oSharersList));
  747. }
  748. }
  749. $aShareProperties = SharedObject::GetSharedClassProperties($sClass);
  750. if ($aShareProperties)
  751. {
  752. $sShareClass = $aShareProperties['share_class'];
  753. $sShareAttCode = $aShareProperties['attcode'];
  754. $oSearchShares = new DBObjectSearch($sShareClass);
  755. $oSearchShares->AllowAllData();
  756. $sHierarchicalKeyCode = MetaModel::IsHierarchicalClass('Organization');
  757. $oOrgField = new FieldExpression('org_id', $sShareClass);
  758. $oSearchShares->AddConditionExpression(new BinaryExpression($oOrgField, 'IN', $oListExpr));
  759. $aShared = array();
  760. foreach($oSearchShares->ToDataArray(array($sShareAttCode)) as $aRow)
  761. {
  762. $aShared[] = $aRow[$sShareAttCode];
  763. }
  764. if (count($aShared) > 0)
  765. {
  766. $oObjId = new FieldExpression('id', $sClass);
  767. $oSharedIdList = ListExpression::FromScalars($aShared);
  768. $oFilter->MergeConditionExpression(new BinaryExpression($oObjId, 'IN', $oSharedIdList));
  769. }
  770. }
  771. } // if HasSharing
  772. return $oFilter;
  773. }
  774. // This verb has been made public to allow the development of an accurate feedback for the current configuration
  775. public function GetProfileActionGrant($iProfile, $sClass, $sAction)
  776. {
  777. $this->LoadActionGrantCache();
  778. // Note: action is forced lowercase to be more flexible (historical bug)
  779. $sAction = strtolower($sAction);
  780. if (isset($this->m_aClassActionGrants[$iProfile][$sClass][$sAction]))
  781. {
  782. return $this->m_aClassActionGrants[$iProfile][$sClass][$sAction];
  783. }
  784. // Recursively look for the grant record in the class hierarchy
  785. $sParentClass = MetaModel::GetParentPersistentClass($sClass);
  786. if (empty($sParentClass))
  787. {
  788. $iGrant = null;
  789. }
  790. else
  791. {
  792. // Recursively look for the grant record in the class hierarchy
  793. $iGrant = $this->GetProfileActionGrant($iProfile, $sParentClass, $sAction);
  794. }
  795. $this->m_aClassActionGrants[$iProfile][$sClass][$sAction] = $iGrant;
  796. return $iGrant;
  797. }
  798. protected function GetUserActionGrant($oUser, $sClass, $iActionCode)
  799. {
  800. $this->LoadCache();
  801. // load and cache permissions for the current user on the given class
  802. //
  803. $iUser = $oUser->GetKey();
  804. $aTest = @$this->m_aObjectActionGrants[$iUser][$sClass][$iActionCode];
  805. if (is_array($aTest)) return $aTest;
  806. $sAction = self::$m_aActionCodes[$iActionCode];
  807. $iPermission = UR_ALLOWED_NO;
  808. $aAttributes = array();
  809. foreach($this->GetUserProfiles($iUser) as $iProfile => $oProfile)
  810. {
  811. $iGrant = $this->GetProfileActionGrant($iProfile, $sClass, $sAction);
  812. if (is_null($iGrant) || !$iGrant)
  813. {
  814. continue; // loop to the next profile
  815. }
  816. else
  817. {
  818. $iPermission = UR_ALLOWED_YES;
  819. // update the list of attributes with those allowed for this profile
  820. //
  821. $oSearch = DBObjectSearch::FromOQL_AllData("SELECT URP_AttributeGrant WHERE actiongrantid = :actiongrantid");
  822. $oSet = new DBObjectSet($oSearch, array(), array('actiongrantid' => $iGrant));
  823. $aProfileAttributes = $oSet->GetColumnAsArray('attcode', false);
  824. if (count($aProfileAttributes) == 0)
  825. {
  826. $aAllAttributes = array_keys(MetaModel::ListAttributeDefs($sClass));
  827. $aAttributes = array_merge($aAttributes, $aAllAttributes);
  828. }
  829. else
  830. {
  831. $aAttributes = array_merge($aAttributes, $aProfileAttributes);
  832. }
  833. }
  834. }
  835. $aRes = array(
  836. 'permission' => $iPermission,
  837. 'attributes' => $aAttributes,
  838. );
  839. $this->m_aObjectActionGrants[$iUser][$sClass][$iActionCode] = $aRes;
  840. return $aRes;
  841. }
  842. public function IsActionAllowed($oUser, $sClass, $iActionCode, $oInstanceSet = null)
  843. {
  844. $this->LoadCache();
  845. $aObjectPermissions = $this->GetUserActionGrant($oUser, $sClass, $iActionCode);
  846. $iPermission = $aObjectPermissions['permission'];
  847. // Note: In most cases the object set is ignored because it was interesting to optimize for huge data sets
  848. // and acceptable to consider only the root class of the object set
  849. if ($iPermission != UR_ALLOWED_YES)
  850. {
  851. // It is already NO for everyone... that's the final word!
  852. }
  853. elseif ($iActionCode == UR_ACTION_READ)
  854. {
  855. // We are protected by GetSelectFilter: the object set contains objects allowed or shared for reading
  856. }
  857. elseif ($iActionCode == UR_ACTION_BULK_READ)
  858. {
  859. // We are protected by GetSelectFilter: the object set contains objects allowed or shared for reading
  860. }
  861. elseif ($oInstanceSet)
  862. {
  863. // We are protected by GetSelectFilter: the object set contains objects allowed or shared for reading
  864. // We have to answer NO for objects shared for reading purposes
  865. if (self::HasSharing())
  866. {
  867. $aClassProps = SharedObject::GetSharedClassProperties($sClass);
  868. if ($aClassProps)
  869. {
  870. // This class is shared, GetSelectFilter may allow some objects for read only
  871. // But currently we are checking wether the objects might be written...
  872. // Let's exclude the objects based on the relevant criteria
  873. $sOrgAttCode = self::GetOwnerOrganizationAttCode($sClass);
  874. if (!is_null($sOrgAttCode))
  875. {
  876. $aUserOrgs = $this->GetUserOrgs($oUser, $sClass);
  877. if (!is_null($aUserOrgs) && count($aUserOrgs) > 0)
  878. {
  879. $iCountNO = 0;
  880. $iCountYES = 0;
  881. $oInstanceSet->Rewind();
  882. while($oObject = $oInstanceSet->Fetch())
  883. {
  884. $iOrg = $oObject->Get($sOrgAttCode);
  885. if (in_array($iOrg, $aUserOrgs))
  886. {
  887. $iCountYES++;
  888. }
  889. else
  890. {
  891. $iCountNO++;
  892. }
  893. }
  894. if ($iCountNO == 0)
  895. {
  896. $iPermission = UR_ALLOWED_YES;
  897. }
  898. elseif ($iCountYES == 0)
  899. {
  900. $iPermission = UR_ALLOWED_NO;
  901. }
  902. else
  903. {
  904. $iPermission = UR_ALLOWED_DEPENDS;
  905. }
  906. }
  907. }
  908. }
  909. }
  910. }
  911. return $iPermission;
  912. }
  913. public function IsActionAllowedOnAttribute($oUser, $sClass, $sAttCode, $iActionCode, $oInstanceSet = null)
  914. {
  915. $this->LoadCache();
  916. // Note: The object set is ignored because it was interesting to optimize for huge data sets
  917. // and acceptable to consider only the root class of the object set
  918. $aObjectPermissions = $this->GetUserActionGrant($oUser, $sClass, $iActionCode);
  919. $aAttributes = $aObjectPermissions['attributes'];
  920. if (in_array($sAttCode, $aAttributes))
  921. {
  922. return $aObjectPermissions['permission'];
  923. }
  924. else
  925. {
  926. return UR_ALLOWED_NO;
  927. }
  928. }
  929. // This verb has been made public to allow the development of an accurate feedback for the current configuration
  930. public function GetClassStimulusGrant($iProfile, $sClass, $sStimulusCode)
  931. {
  932. $this->LoadCache();
  933. if (isset($this->m_aClassStimulusGrants[$iProfile][$sClass][$sStimulusCode]))
  934. {
  935. return $this->m_aClassStimulusGrants[$iProfile][$sClass][$sStimulusCode];
  936. }
  937. else
  938. {
  939. return null;
  940. }
  941. }
  942. public function IsStimulusAllowed($oUser, $sClass, $sStimulusCode, $oInstanceSet = null)
  943. {
  944. $this->LoadCache();
  945. // Note: this code is VERY close to the code of IsActionAllowed()
  946. $iUser = $oUser->GetKey();
  947. // Note: The object set is ignored because it was interesting to optimize for huge data sets
  948. // and acceptable to consider only the root class of the object set
  949. $iPermission = UR_ALLOWED_NO;
  950. foreach($this->GetUserProfiles($iUser) as $iProfile => $oProfile)
  951. {
  952. $oGrantRecord = $this->GetClassStimulusGrant($iProfile, $sClass, $sStimulusCode);
  953. if (!is_null($oGrantRecord))
  954. {
  955. // no need to fetch the record, we've requested the records having permission = 'yes'
  956. $iPermission = UR_ALLOWED_YES;
  957. }
  958. }
  959. return $iPermission;
  960. }
  961. public function FlushPrivileges()
  962. {
  963. $this->ResetCache();
  964. }
  965. /**
  966. * Find out which attribute is corresponding the the dimension 'owner org'
  967. * returns null if no such attribute has been found (no filtering should occur)
  968. */
  969. public static function GetOwnerOrganizationAttCode($sClass)
  970. {
  971. $sAttCode = null;
  972. $aCallSpec = array($sClass, 'MapContextParam');
  973. if (($sClass == 'Organization') || is_subclass_of($sClass, 'Organization'))
  974. {
  975. $sAttCode = 'id';
  976. }
  977. elseif (is_callable($aCallSpec))
  978. {
  979. $sAttCode = call_user_func($aCallSpec, 'org_id'); // Returns null when there is no mapping for this parameter
  980. if (!MetaModel::IsValidAttCode($sClass, $sAttCode))
  981. {
  982. // Skip silently. The data model checker will tell you something about this...
  983. $sAttCode = null;
  984. }
  985. }
  986. elseif(MetaModel::IsValidAttCode($sClass, 'org_id'))
  987. {
  988. $sAttCode = 'org_id';
  989. }
  990. return $sAttCode;
  991. }
  992. /**
  993. * Determine wether the objects can be shared by the mean of a class SharedObject
  994. **/
  995. protected static function HasSharing()
  996. {
  997. static $bHasSharing;
  998. if (!isset($bHasSharing))
  999. {
  1000. $bHasSharing = class_exists('SharedObject');
  1001. }
  1002. return $bHasSharing;
  1003. }
  1004. }
  1005. UserRights::SelectModule('UserRightsProfile');
  1006. ?>