userrightsprofile.class.inc.php 37 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006
  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_ID', 1);
  26. class UserRightsBaseClass extends cmdbAbstractObject
  27. {
  28. // Whenever something changes, reload the privileges
  29. protected function AfterInsert()
  30. {
  31. UserRights::FlushPrivileges();
  32. }
  33. protected function AfterUpdate()
  34. {
  35. UserRights::FlushPrivileges();
  36. }
  37. protected function AfterDelete()
  38. {
  39. UserRights::FlushPrivileges();
  40. }
  41. }
  42. class URP_Profiles extends UserRightsBaseClass
  43. {
  44. public static function Init()
  45. {
  46. $aParams = array
  47. (
  48. "category" => "addon/userrights",
  49. "key_type" => "autoincrement",
  50. "name_attcode" => "name",
  51. "state_attcode" => "",
  52. "reconc_keys" => array(),
  53. "db_table" => "priv_urp_profiles",
  54. "db_key_field" => "id",
  55. "db_finalclass_field" => "",
  56. "display_template" => "",
  57. );
  58. MetaModel::Init_Params($aParams);
  59. //MetaModel::Init_InheritAttributes();
  60. MetaModel::Init_AddAttribute(new AttributeString("name", array("allowed_values"=>null, "sql"=>"name", "default_value"=>null, "is_null_allowed"=>false, "depends_on"=>array())));
  61. MetaModel::Init_AddAttribute(new AttributeString("description", array("allowed_values"=>null, "sql"=>"description", "default_value"=>null, "is_null_allowed"=>false, "depends_on"=>array())));
  62. 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())));
  63. // Display lists
  64. MetaModel::Init_SetZListItems('details', array('name', 'description', 'user_list')); // Attributes to be displayed for the complete details
  65. MetaModel::Init_SetZListItems('list', array('description')); // Attributes to be displayed for a list
  66. // Search criteria
  67. MetaModel::Init_SetZListItems('standard_search', array('name')); // Criteria of the std search form
  68. MetaModel::Init_SetZListItems('advanced_search', array('name')); // Criteria of the advanced search form
  69. }
  70. function GetGrantAsHtml($oUserRights, $sClass, $sAction)
  71. {
  72. $oGrant = $oUserRights->GetProfileActionGrant($this->GetKey(), $sClass, $sAction);
  73. if (is_object($oGrant) && ($oGrant->Get('permission') == 'yes'))
  74. {
  75. return '<span style="background-color: #ddffdd;">'.Dict::S('UI:UserManagement:ActionAllowed:Yes').'</span>';
  76. }
  77. else
  78. {
  79. return '<span style="background-color: #ffdddd;">'.Dict::S('UI:UserManagement:ActionAllowed:No').'</span>';
  80. }
  81. }
  82. function DoShowGrantSumary($oPage)
  83. {
  84. if ($this->GetName() == "Administrator")
  85. {
  86. // Looks dirty, but ok that's THE ONE
  87. $oPage->p(Dict::S('UI:UserManagement:AdminProfile+'));
  88. return;
  89. }
  90. // Note: for sure, we assume that the instance is derived from UserRightsProfile
  91. $oUserRights = UserRights::GetModuleInstance();
  92. $aDisplayData = array();
  93. foreach (MetaModel::GetClasses('bizmodel') as $sClass)
  94. {
  95. // Skip non instantiable classes
  96. if (MetaModel::IsAbstract($sClass)) continue;
  97. $aStimuli = array();
  98. foreach (MetaModel::EnumStimuli($sClass) as $sStimulusCode => $oStimulus)
  99. {
  100. $oGrant = $oUserRights->GetClassStimulusGrant($this->GetKey(), $sClass, $sStimulusCode);
  101. if (is_object($oGrant) && ($oGrant->Get('permission') == 'yes'))
  102. {
  103. $aStimuli[] = '<span title="'.$sStimulusCode.': '.htmlentities($oStimulus->GetDescription()).'">'.htmlentities($oStimulus->GetLabel()).'</span>';
  104. }
  105. }
  106. $sStimuli = implode(', ', $aStimuli);
  107. $aDisplayData[] = array(
  108. 'class' => MetaModel::GetName($sClass),
  109. 'read' => $this->GetGrantAsHtml($oUserRights, $sClass, 'Read'),
  110. 'bulkread' => $this->GetGrantAsHtml($oUserRights, $sClass, 'Bulk Read'),
  111. 'write' => $this->GetGrantAsHtml($oUserRights, $sClass, 'Modify'),
  112. 'bulkwrite' => $this->GetGrantAsHtml($oUserRights, $sClass, 'Bulk Modify'),
  113. 'delete' => $this->GetGrantAsHtml($oUserRights, $sClass, 'Delete'),
  114. 'bulkdelete' => $this->GetGrantAsHtml($oUserRights, $sClass, 'Bulk Delete'),
  115. 'stimuli' => $sStimuli,
  116. );
  117. }
  118. $aDisplayConfig = array();
  119. $aDisplayConfig['class'] = array('label' => Dict::S('UI:UserManagement:Class'), 'description' => Dict::S('UI:UserManagement:Class+'));
  120. $aDisplayConfig['read'] = array('label' => Dict::S('UI:UserManagement:Action:Read'), 'description' => Dict::S('UI:UserManagement:Action:Read+'));
  121. $aDisplayConfig['bulkread'] = array('label' => Dict::S('UI:UserManagement:Action:BulkRead'), 'description' => Dict::S('UI:UserManagement:Action:BulkRead+'));
  122. $aDisplayConfig['write'] = array('label' => Dict::S('UI:UserManagement:Action:Modify'), 'description' => Dict::S('UI:UserManagement:Action:Modify+'));
  123. $aDisplayConfig['bulkwrite'] = array('label' => Dict::S('UI:UserManagement:Action:BulkModify'), 'description' => Dict::S('UI:UserManagement:Action:BulkModify+'));
  124. $aDisplayConfig['delete'] = array('label' => Dict::S('UI:UserManagement:Action:Delete'), 'description' => Dict::S('UI:UserManagement:Action:Delete+'));
  125. $aDisplayConfig['bulkdelete'] = array('label' => Dict::S('UI:UserManagement:Action:BulkDelete'), 'description' => Dict::S('UI:UserManagement:Action:BulkDelete+'));
  126. $aDisplayConfig['stimuli'] = array('label' => Dict::S('UI:UserManagement:Action:Stimuli'), 'description' => Dict::S('UI:UserManagement:Action:Stimuli+'));
  127. $oPage->table($aDisplayConfig, $aDisplayData);
  128. }
  129. function DisplayBareRelations(WebPage $oPage, $bEditMode = false)
  130. {
  131. parent::DisplayBareRelations($oPage);
  132. if (!$bEditMode)
  133. {
  134. $oPage->SetCurrentTab(Dict::S('UI:UserManagement:GrantMatrix'));
  135. $this->DoShowGrantSumary($oPage);
  136. }
  137. }
  138. }
  139. class URP_UserProfile extends UserRightsBaseClass
  140. {
  141. public static function Init()
  142. {
  143. $aParams = array
  144. (
  145. "category" => "addon/userrights",
  146. "key_type" => "autoincrement",
  147. "name_attcode" => "userid",
  148. "state_attcode" => "",
  149. "reconc_keys" => array(),
  150. "db_table" => "priv_urp_userprofile",
  151. "db_key_field" => "id",
  152. "db_finalclass_field" => "",
  153. "display_template" => "",
  154. );
  155. MetaModel::Init_Params($aParams);
  156. //MetaModel::Init_InheritAttributes();
  157. 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())));
  158. MetaModel::Init_AddAttribute(new AttributeExternalField("userlogin", array("allowed_values"=>null, "extkey_attcode"=> 'userid', "target_attcode"=>"login")));
  159. 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())));
  160. MetaModel::Init_AddAttribute(new AttributeExternalField("profile", array("allowed_values"=>null, "extkey_attcode"=> 'profileid', "target_attcode"=>"name")));
  161. MetaModel::Init_AddAttribute(new AttributeString("reason", array("allowed_values"=>null, "sql"=>"description", "default_value"=>null, "is_null_allowed"=>true, "depends_on"=>array())));
  162. // Display lists
  163. MetaModel::Init_SetZListItems('details', array('userid', 'profileid', 'reason')); // Attributes to be displayed for the complete details
  164. MetaModel::Init_SetZListItems('list', array('profileid', 'reason')); // Attributes to be displayed for a list
  165. // Search criteria
  166. MetaModel::Init_SetZListItems('standard_search', array('userid', 'profileid')); // Criteria of the std search form
  167. MetaModel::Init_SetZListItems('advanced_search', array('userid', 'profileid')); // Criteria of the advanced search form
  168. }
  169. public function GetName()
  170. {
  171. return Dict::Format('UI:UserManagement:LinkBetween_User_And_Profile', $this->Get('userlogin'), $this->Get('profile'));
  172. }
  173. }
  174. class URP_UserOrg extends UserRightsBaseClass
  175. {
  176. public static function Init()
  177. {
  178. $aParams = array
  179. (
  180. "category" => "addon/userrights",
  181. "key_type" => "autoincrement",
  182. "name_attcode" => "userid",
  183. "state_attcode" => "",
  184. "reconc_keys" => array(),
  185. "db_table" => "priv_urp_userorg",
  186. "db_key_field" => "id",
  187. "db_finalclass_field" => "",
  188. "display_template" => "",
  189. );
  190. MetaModel::Init_Params($aParams);
  191. //MetaModel::Init_InheritAttributes();
  192. 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())));
  193. MetaModel::Init_AddAttribute(new AttributeExternalField("userlogin", array("allowed_values"=>null, "extkey_attcode"=> 'userid', "target_attcode"=>"login")));
  194. 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())));
  195. MetaModel::Init_AddAttribute(new AttributeExternalField("allowed_org_name", array("allowed_values"=>null, "extkey_attcode"=> 'allowed_org_id', "target_attcode"=>"name")));
  196. MetaModel::Init_AddAttribute(new AttributeString("reason", array("allowed_values"=>null, "sql"=>"reason", "default_value"=>null, "is_null_allowed"=>true, "depends_on"=>array())));
  197. // Display lists
  198. MetaModel::Init_SetZListItems('details', array('userid', 'allowed_org_id', 'reason')); // Attributes to be displayed for the complete details
  199. MetaModel::Init_SetZListItems('list', array('allowed_org_id', 'reason')); // Attributes to be displayed for a list
  200. // Search criteria
  201. MetaModel::Init_SetZListItems('standard_search', array('userid', 'allowed_org_id')); // Criteria of the std search form
  202. MetaModel::Init_SetZListItems('advanced_search', array('userid', 'allowed_org_id')); // Criteria of the advanced search form
  203. }
  204. public function GetName()
  205. {
  206. return Dict::Format('UI:UserManagement:LinkBetween_User_And_Org', $this->Get('userlogin'), $this->Get('allowed_org_name'));
  207. }
  208. }
  209. class URP_ActionGrant extends UserRightsBaseClass
  210. {
  211. public static function Init()
  212. {
  213. $aParams = array
  214. (
  215. "category" => "addon/userrights",
  216. "key_type" => "autoincrement",
  217. "name_attcode" => "profileid",
  218. "state_attcode" => "",
  219. "reconc_keys" => array(),
  220. "db_table" => "priv_urp_grant_actions",
  221. "db_key_field" => "id",
  222. "db_finalclass_field" => "",
  223. "display_template" => "",
  224. );
  225. MetaModel::Init_Params($aParams);
  226. //MetaModel::Init_InheritAttributes();
  227. // Common to all grant classes (could be factorized by class inheritence, but this has to be benchmarked)
  228. 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())));
  229. MetaModel::Init_AddAttribute(new AttributeExternalField("profile", array("allowed_values"=>null, "extkey_attcode"=> 'profileid', "target_attcode"=>"name")));
  230. MetaModel::Init_AddAttribute(new AttributeClass("class", array("class_category"=>"", "more_values"=>"", "sql"=>"class", "default_value"=>null, "is_null_allowed"=>false, "depends_on"=>array())));
  231. 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())));
  232. MetaModel::Init_AddAttribute(new AttributeString("action", array("allowed_values"=>null, "sql"=>"action", "default_value"=>"", "is_null_allowed"=>false, "depends_on"=>array())));
  233. // Display lists
  234. MetaModel::Init_SetZListItems('details', array('profileid', 'class', 'permission', 'action')); // Attributes to be displayed for the complete details
  235. MetaModel::Init_SetZListItems('list', array('class', 'permission', 'action')); // Attributes to be displayed for a list
  236. // Search criteria
  237. MetaModel::Init_SetZListItems('standard_search', array('profileid', 'class', 'permission', 'action')); // Criteria of the std search form
  238. MetaModel::Init_SetZListItems('advanced_search', array('profileid', 'class', 'permission', 'action')); // Criteria of the advanced search form
  239. }
  240. }
  241. class URP_StimulusGrant extends UserRightsBaseClass
  242. {
  243. public static function Init()
  244. {
  245. $aParams = array
  246. (
  247. "category" => "addon/userrights",
  248. "key_type" => "autoincrement",
  249. "name_attcode" => "profileid",
  250. "state_attcode" => "",
  251. "reconc_keys" => array(),
  252. "db_table" => "priv_urp_grant_stimulus",
  253. "db_key_field" => "id",
  254. "db_finalclass_field" => "",
  255. "display_template" => "",
  256. );
  257. MetaModel::Init_Params($aParams);
  258. //MetaModel::Init_InheritAttributes();
  259. // Common to all grant classes (could be factorized by class inheritence, but this has to be benchmarked)
  260. 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())));
  261. MetaModel::Init_AddAttribute(new AttributeExternalField("profile", array("allowed_values"=>null, "extkey_attcode"=> 'profileid', "target_attcode"=>"name")));
  262. MetaModel::Init_AddAttribute(new AttributeClass("class", array("class_category"=>"", "more_values"=>"", "sql"=>"class", "default_value"=>null, "is_null_allowed"=>false, "depends_on"=>array())));
  263. 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())));
  264. MetaModel::Init_AddAttribute(new AttributeString("stimulus", array("allowed_values"=>null, "sql"=>"action", "default_value"=>"", "is_null_allowed"=>false, "depends_on"=>array())));
  265. // Display lists
  266. MetaModel::Init_SetZListItems('details', array('profileid', 'class', 'permission', 'stimulus')); // Attributes to be displayed for the complete details
  267. MetaModel::Init_SetZListItems('list', array('class', 'permission', 'stimulus')); // Attributes to be displayed for a list
  268. // Search criteria
  269. MetaModel::Init_SetZListItems('standard_search', array('profileid', 'class', 'permission', 'stimulus')); // Criteria of the std search form
  270. MetaModel::Init_SetZListItems('advanced_search', array('profileid', 'class', 'permission', 'stimulus')); // Criteria of the advanced search form
  271. }
  272. }
  273. class URP_AttributeGrant extends UserRightsBaseClass
  274. {
  275. public static function Init()
  276. {
  277. $aParams = array
  278. (
  279. "category" => "addon/userrights",
  280. "key_type" => "autoincrement",
  281. "name_attcode" => "actiongrantid",
  282. "state_attcode" => "",
  283. "reconc_keys" => array(),
  284. "db_table" => "priv_urp_grant_attributes",
  285. "db_key_field" => "id",
  286. "db_finalclass_field" => "",
  287. "display_template" => "",
  288. );
  289. MetaModel::Init_Params($aParams);
  290. //MetaModel::Init_InheritAttributes();
  291. 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())));
  292. MetaModel::Init_AddAttribute(new AttributeString("attcode", array("allowed_values"=>null, "sql"=>"attcode", "default_value"=>null, "is_null_allowed"=>false, "depends_on"=>array())));
  293. // Display lists
  294. MetaModel::Init_SetZListItems('details', array('actiongrantid', 'attcode')); // Attributes to be displayed for the complete details
  295. MetaModel::Init_SetZListItems('list', array('attcode')); // Attributes to be displayed for a list
  296. // Search criteria
  297. MetaModel::Init_SetZListItems('standard_search', array('actiongrantid', 'attcode')); // Criteria of the std search form
  298. MetaModel::Init_SetZListItems('advanced_search', array('actiongrantid', 'attcode')); // Criteria of the advanced search form
  299. }
  300. }
  301. class UserRightsProfile extends UserRightsAddOnAPI
  302. {
  303. static public $m_aActionCodes = array(
  304. UR_ACTION_READ => 'read',
  305. UR_ACTION_MODIFY => 'modify',
  306. UR_ACTION_DELETE => 'delete',
  307. UR_ACTION_BULK_READ => 'bulk read',
  308. UR_ACTION_BULK_MODIFY => 'bulk modify',
  309. UR_ACTION_BULK_DELETE => 'bulk delete',
  310. );
  311. // Installation: create the very first user
  312. public function CreateAdministrator($sAdminUser, $sAdminPwd, $sLanguage = 'EN US')
  313. {
  314. // Create a change to record the history of the User object
  315. $oChange = MetaModel::NewObject("CMDBChange");
  316. $oChange->Set("date", time());
  317. $oChange->Set("userinfo", "Initialization");
  318. $iChangeId = $oChange->DBInsert();
  319. $oOrg = new Organization();
  320. $oOrg->Set('name', 'My Company/Department');
  321. $oOrg->Set('code', 'SOMECODE');
  322. // $oOrg->Set('status', 'implementation');
  323. //$oOrg->Set('parent_id', xxx);
  324. $iOrgId = $oOrg->DBInsertTrackedNoReload($oChange);
  325. $oContact = new Person();
  326. $oContact->Set('name', 'My last name');
  327. $oContact->Set('first_name', 'My first name');
  328. //$oContact->Set('status', 'available');
  329. $oContact->Set('org_id', $iOrgId);
  330. $oContact->Set('email', 'my.email@foo.org');
  331. //$oContact->Set('phone', '');
  332. //$oContact->Set('location_id', $iLocationId);
  333. //$oContact->Set('employee_number', '');
  334. $iContactId = $oContact->DBInsertTrackedNoReload($oChange);
  335. $oUser = new UserLocal();
  336. $oUser->Set('login', $sAdminUser);
  337. $oUser->Set('password', $sAdminPwd);
  338. $oUser->Set('contactid', $iContactId);
  339. $oUser->Set('language', $sLanguage); // Language was chosen during the installation
  340. $iUserId = $oUser->DBInsertTrackedNoReload($oChange);
  341. // Add this user to the very specific 'admin' profile
  342. $oUserProfile = new URP_UserProfile();
  343. $oUserProfile->Set('userid', $iUserId);
  344. $oUserProfile->Set('profileid', ADMIN_PROFILE_ID);
  345. $oUserProfile->Set('reason', 'By definition, the administrator must have the administrator profile');
  346. $oUserProfile->DBInsertTrackedNoReload($oChange);
  347. return true;
  348. }
  349. public function Setup()
  350. {
  351. SetupProfiles::ComputeITILProfiles();
  352. //SetupProfiles::ComputeBasicProfiles();
  353. SetupProfiles::DoCreateProfiles();
  354. return true;
  355. }
  356. public function Init()
  357. {
  358. MetaModel::RegisterPlugin('userrights', 'ACbyProfile');
  359. }
  360. protected $m_aAdmins; // id of users being linked to the well-known admin profile
  361. protected $m_aProfiles; // id -> object
  362. protected $m_aUserProfiles; // userid,profileid -> object
  363. protected $m_aUserOrgs; // userid,orgid -> object
  364. // Those arrays could be completed on demand (inheriting parent permissions)
  365. protected $m_aClassActionGrants = null; // profile, class, action -> actiongrantid (or false if NO, or null/missing if undefined)
  366. protected $m_aClassStimulusGrants = array(); // profile, class, stimulus -> permission
  367. // Built on demand, could be optimized if necessary (doing a query for each attribute that needs to be read)
  368. protected $m_aObjectActionGrants = array();
  369. public function ResetCache()
  370. {
  371. // Loaded by Load cache
  372. $this->m_aProfiles = null;
  373. $this->m_aUserProfiles = null;
  374. $this->m_aUserOrgs = null;
  375. $this->m_aAdmins = null;
  376. // Loaded on demand (time consuming as compared to the others)
  377. $this->m_aClassActionGrants = null;
  378. $this->m_aClassStimulusGrants = null;
  379. $this->m_aObjectActionGrants = array();
  380. }
  381. // Separate load: this cache is much more time consuming while loading
  382. // Thus it is loaded iif required
  383. // Could be improved by specifying the profile id
  384. public function LoadActionGrantCache()
  385. {
  386. if (!is_null($this->m_aClassActionGrants)) return;
  387. $oKPI = new ExecutionKPI();
  388. $oFilter = DBObjectSearch::FromOQL_AllData("SELECT URP_ActionGrant AS p WHERE p.permission = 'yes'");
  389. $aGrants = $oFilter->ToDataArray();
  390. foreach($aGrants as $aGrant)
  391. {
  392. $this->m_aClassActionGrants[$aGrant['profileid']][$aGrant['class']][strtolower($aGrant['action'])] = $aGrant['id'];
  393. }
  394. $oKPI->ComputeAndReport('Load of action grants');
  395. }
  396. public function LoadCache()
  397. {
  398. if (!is_null($this->m_aProfiles)) return;
  399. // Could be loaded in a shared memory (?)
  400. $oKPI = new ExecutionKPI();
  401. $oProfileSet = new DBObjectSet(DBObjectSearch::FromOQL_AllData("SELECT URP_Profiles"));
  402. $this->m_aProfiles = array();
  403. while ($oProfile = $oProfileSet->Fetch())
  404. {
  405. $this->m_aProfiles[$oProfile->GetKey()] = $oProfile;
  406. }
  407. $oUserProfileSet = new DBObjectSet(DBObjectSearch::FromOQL_AllData("SELECT URP_UserProfile"));
  408. $this->m_aUserProfiles = array();
  409. $this->m_aAdmins = array();
  410. while ($oUserProfile = $oUserProfileSet->Fetch())
  411. {
  412. $this->m_aUserProfiles[$oUserProfile->Get('userid')][$oUserProfile->Get('profileid')] = $oUserProfile;
  413. if ($oUserProfile->Get('profileid') == ADMIN_PROFILE_ID)
  414. {
  415. $this->m_aAdmins[] = $oUserProfile->Get('userid');
  416. }
  417. }
  418. $oUserOrgSet = new DBObjectSet(DBObjectSearch::FromOQL_AllData("SELECT URP_UserOrg"));
  419. $this->m_aUserOrgs = array();
  420. while ($oUserOrg = $oUserOrgSet->Fetch())
  421. {
  422. $this->m_aUserOrgs[$oUserOrg->Get('userid')][$oUserOrg->Get('allowed_org_id')] = $oUserOrg;
  423. }
  424. $this->m_aClassStimulusGrants = array();
  425. $oStimGrantSet = new DBObjectSet(DBObjectSearch::FromOQL_AllData("SELECT URP_StimulusGrant"));
  426. $this->m_aStimGrants = array();
  427. while ($oStimGrant = $oStimGrantSet->Fetch())
  428. {
  429. $this->m_aClassStimulusGrants[$oStimGrant->Get('profileid')][$oStimGrant->Get('class')][$oStimGrant->Get('stimulus')] = $oStimGrant;
  430. }
  431. $oKPI->ComputeAndReport('Load of user management cache (excepted Action Grants)');
  432. /*
  433. echo "<pre>\n";
  434. print_r($this->m_aProfiles);
  435. print_r($this->m_aUserProfiles);
  436. print_r($this->m_aUserOrgs);
  437. print_r($this->m_aClassActionGrants);
  438. print_r($this->m_aClassStimulusGrants);
  439. echo "</pre>\n";
  440. exit;
  441. */
  442. return true;
  443. }
  444. public function IsAdministrator($oUser)
  445. {
  446. $this->LoadCache();
  447. if (in_array($oUser->GetKey(), $this->m_aAdmins))
  448. {
  449. return true;
  450. }
  451. else
  452. {
  453. return false;
  454. }
  455. }
  456. public function GetSelectFilter($oUser, $sClass)
  457. {
  458. $this->LoadCache();
  459. $aObjectPermissions = $this->GetUserActionGrant($oUser, $sClass, UR_ACTION_READ);
  460. if ($aObjectPermissions['permission'] == UR_ALLOWED_NO)
  461. {
  462. return false;
  463. }
  464. // Determine how to position the objects of this class
  465. //
  466. if ($sClass == 'Organization')
  467. {
  468. $sAttCode = 'id';
  469. }
  470. elseif(MetaModel::IsValidAttCode($sClass, 'org_id'))
  471. {
  472. $sAttCode = 'org_id';
  473. }
  474. else
  475. {
  476. // The objects of this class are not positioned in this dimension
  477. // All of them are visible
  478. return true;
  479. }
  480. $oExpression = new FieldExpression($sAttCode, $sClass);
  481. // Position the user
  482. //
  483. @$aUserOrgs = $this->m_aUserOrgs[$oUser->GetKey()];
  484. if (!isset($aUserOrgs) || count($aUserOrgs) == 0)
  485. {
  486. // No position means 'Everywhere'
  487. return true;
  488. }
  489. $aIds = array_keys($aUserOrgs);
  490. $oListExpr = ListExpression::FromScalars($aIds);
  491. $oCondition = new BinaryExpression($oExpression, 'IN', $oListExpr);
  492. $oFilter = new DBObjectSearch($sClass);
  493. $oFilter->AddConditionExpression($oCondition);
  494. return $oFilter;
  495. }
  496. // This verb has been made public to allow the development of an accurate feedback for the current configuration
  497. public function GetProfileActionGrant($iProfile, $sClass, $sAction)
  498. {
  499. $this->LoadActionGrantCache();
  500. // Note: action is forced lowercase to be more flexible (historical bug)
  501. $sAction = strtolower($sAction);
  502. if (isset($this->m_aClassActionGrants[$iProfile][$sClass][$sAction]))
  503. {
  504. return $this->m_aClassActionGrants[$iProfile][$sClass][$sAction];
  505. }
  506. // Recursively look for the grant record in the class hierarchy
  507. $sParentClass = MetaModel::GetParentPersistentClass($sClass);
  508. if (empty($sParentClass))
  509. {
  510. $iGrant = null;
  511. }
  512. else
  513. {
  514. // Recursively look for the grant record in the class hierarchy
  515. $iGrant = $this->GetProfileActionGrant($iProfile, $sParentClass, $sAction);
  516. }
  517. $this->m_aClassActionGrants[$iProfile][$sClass][$sAction] = $iGrant;
  518. return $iGrant;
  519. }
  520. protected function GetUserActionGrant($oUser, $sClass, $iActionCode)
  521. {
  522. $this->LoadCache();
  523. // load and cache permissions for the current user on the given class
  524. //
  525. $iUser = $oUser->GetKey();
  526. $aTest = @$this->m_aObjectActionGrants[$iUser][$sClass][$iActionCode];
  527. if (is_array($aTest)) return $aTest;
  528. $sAction = self::$m_aActionCodes[$iActionCode];
  529. $iPermission = UR_ALLOWED_NO;
  530. $aAttributes = array();
  531. if (isset($this->m_aUserProfiles[$iUser]))
  532. {
  533. foreach($this->m_aUserProfiles[$iUser] as $iProfile => $oProfile)
  534. {
  535. $iGrant = $this->GetProfileActionGrant($iProfile, $sClass, $sAction);
  536. if (is_null($iGrant) || !$iGrant)
  537. {
  538. continue; // loop to the next profile
  539. }
  540. else
  541. {
  542. $iPermission = UR_ALLOWED_YES;
  543. // update the list of attributes with those allowed for this profile
  544. //
  545. $oSearch = DBObjectSearch::FromOQL_AllData("SELECT URP_AttributeGrant WHERE actiongrantid = :actiongrantid");
  546. $oSet = new DBObjectSet($oSearch, array(), array('actiongrantid' => $iGrant));
  547. $aProfileAttributes = $oSet->GetColumnAsArray('attcode', false);
  548. if (count($aProfileAttributes) == 0)
  549. {
  550. $aAllAttributes = array_keys(MetaModel::ListAttributeDefs($sClass));
  551. $aAttributes = array_merge($aAttributes, $aAllAttributes);
  552. }
  553. else
  554. {
  555. $aAttributes = array_merge($aAttributes, $aProfileAttributes);
  556. }
  557. }
  558. }
  559. }
  560. $aRes = array(
  561. 'permission' => $iPermission,
  562. 'attributes' => $aAttributes,
  563. );
  564. $this->m_aObjectActionGrants[$iUser][$sClass][$iActionCode] = $aRes;
  565. return $aRes;
  566. }
  567. public function IsActionAllowed($oUser, $sClass, $iActionCode, $oInstanceSet = null)
  568. {
  569. $this->LoadCache();
  570. // Note: The object set is ignored because it was interesting to optimize for huge data sets
  571. // and acceptable to consider only the root class of the object set
  572. $aObjectPermissions = $this->GetUserActionGrant($oUser, $sClass, $iActionCode);
  573. return $aObjectPermissions['permission'];
  574. }
  575. public function IsActionAllowedOnAttribute($oUser, $sClass, $sAttCode, $iActionCode, $oInstanceSet = null)
  576. {
  577. $this->LoadCache();
  578. // Note: The object set is ignored because it was interesting to optimize for huge data sets
  579. // and acceptable to consider only the root class of the object set
  580. $aObjectPermissions = $this->GetUserActionGrant($oUser, $sClass, $iActionCode);
  581. $aAttributes = $aObjectPermissions['attributes'];
  582. if (in_array($sAttCode, $aAttributes))
  583. {
  584. return $aObjectPermissions['permission'];
  585. }
  586. else
  587. {
  588. return UR_ALLOWED_NO;
  589. }
  590. }
  591. // This verb has been made public to allow the development of an accurate feedback for the current configuration
  592. public function GetClassStimulusGrant($iProfile, $sClass, $sStimulusCode)
  593. {
  594. $this->LoadCache();
  595. if (isset($this->m_aClassStimulusGrants[$iProfile][$sClass][$sStimulusCode]))
  596. {
  597. return $this->m_aClassStimulusGrants[$iProfile][$sClass][$sStimulusCode];
  598. }
  599. else
  600. {
  601. return null;
  602. }
  603. }
  604. public function IsStimulusAllowed($oUser, $sClass, $sStimulusCode, $oInstanceSet = null)
  605. {
  606. $this->LoadCache();
  607. // Note: this code is VERY close to the code of IsActionAllowed()
  608. $iUser = $oUser->GetKey();
  609. // Note: The object set is ignored because it was interesting to optimize for huge data sets
  610. // and acceptable to consider only the root class of the object set
  611. $iPermission = UR_ALLOWED_NO;
  612. if (isset($this->m_aUserProfiles[$iUser]))
  613. {
  614. foreach($this->m_aUserProfiles[$iUser] as $iProfile => $oProfile)
  615. {
  616. $oGrantRecord = $this->GetClassStimulusGrant($iProfile, $sClass, $sStimulusCode);
  617. if (!is_null($oGrantRecord))
  618. {
  619. // no need to fetch the record, we've requested the records having permission = 'yes'
  620. $iPermission = UR_ALLOWED_YES;
  621. }
  622. }
  623. }
  624. return $iPermission;
  625. }
  626. public function FlushPrivileges()
  627. {
  628. $this->ResetCache();
  629. }
  630. }
  631. //
  632. // Create simple profiles into our user management model:
  633. // - administrator
  634. // - readers
  635. // - contributors
  636. //
  637. class SetupProfiles
  638. {
  639. protected static $m_aActions = array(
  640. UR_ACTION_READ => 'Read',
  641. UR_ACTION_MODIFY => 'Modify',
  642. UR_ACTION_DELETE => 'Delete',
  643. UR_ACTION_BULK_READ => 'Bulk Read',
  644. UR_ACTION_BULK_MODIFY => 'Bulk Modify',
  645. UR_ACTION_BULK_DELETE => 'Bulk Delete',
  646. );
  647. // Note: It is possible to specify the same class in several modules
  648. //
  649. protected static $m_aModules = array();
  650. protected static $m_aProfiles = array();
  651. protected static function DoCreateActionGrant($iProfile, $iAction, $sClass, $bPermission = true)
  652. {
  653. $oNewObj = MetaModel::NewObject("URP_ActionGrant");
  654. $oNewObj->Set('profileid', $iProfile);
  655. $oNewObj->Set('permission', $bPermission ? 'yes' : 'no');
  656. $oNewObj->Set('class', $sClass);
  657. $oNewObj->Set('action', self::$m_aActions[$iAction]);
  658. $iId = $oNewObj->DBInsertNoReload();
  659. return $iId;
  660. }
  661. protected static function DoCreateStimulusGrant($iProfile, $sStimulusCode, $sClass)
  662. {
  663. $oNewObj = MetaModel::NewObject("URP_StimulusGrant");
  664. $oNewObj->Set('profileid', $iProfile);
  665. $oNewObj->Set('permission', 'yes');
  666. $oNewObj->Set('class', $sClass);
  667. $oNewObj->Set('stimulus', $sStimulusCode);
  668. $iId = $oNewObj->DBInsertNoReload();
  669. return $iId;
  670. }
  671. protected static function DoCreateAdminProfile()
  672. {
  673. $oNewObj = MetaModel::NewObject("URP_Profiles");
  674. $oNewObj->Set('name', 'Administrator');
  675. $oNewObj->Set('description', 'Has the rights on everything (bypassing any control)');
  676. $iNewId = $oNewObj->DBInsertNoReload();
  677. if ($iNewId != ADMIN_PROFILE_ID)
  678. {
  679. throw new CoreException('Admin profile could not be created with its standard id', array('requested'=>ADMIN_PROFILE_ID, 'obtained'=>$iNewId));
  680. }
  681. }
  682. protected static function DoCreateOneProfile($sName, $aProfileData)
  683. {
  684. $sDescription = $aProfileData['description'];
  685. if (strlen(trim($aProfileData['write_modules'])) == 0)
  686. {
  687. $aWriteModules = array();
  688. }
  689. else
  690. {
  691. $aWriteModules = explode(',', trim($aProfileData['write_modules']));
  692. }
  693. $aStimuli = $aProfileData['stimuli'];
  694. $oNewObj = MetaModel::NewObject("URP_Profiles");
  695. $oNewObj->Set('name', $sName);
  696. $oNewObj->Set('description', $sDescription);
  697. $iProfile = $oNewObj->DBInsertNoReload();
  698. // Grant read rights for everything
  699. //
  700. foreach (MetaModel::GetClasses('bizmodel') as $sClass)
  701. {
  702. self::DoCreateActionGrant($iProfile, UR_ACTION_READ, $sClass);
  703. self::DoCreateActionGrant($iProfile, UR_ACTION_BULK_READ, $sClass);
  704. }
  705. // Grant write for given modules
  706. // Start by compiling the information, because some modules may overlap
  707. $aWriteableClasses = array();
  708. foreach ($aWriteModules as $sModule)
  709. {
  710. //$oPage->p('Granting write access for the module"'.$sModule.'" - '.count(self::$m_aModules[$sModule]).' classes');
  711. foreach (self::$m_aModules[$sModule] as $sClass)
  712. {
  713. $aWriteableClasses[$sClass] = true;
  714. }
  715. }
  716. foreach ($aWriteableClasses as $sClass => $foo)
  717. {
  718. // Skip non instantiable classes
  719. if (MetaModel::IsAbstract($sClass)) continue;
  720. if (!MetaModel::IsValidClass($sClass))
  721. {
  722. throw new CoreException("Invalid class name '$sClass'");
  723. }
  724. self::DoCreateActionGrant($iProfile, UR_ACTION_MODIFY, $sClass);
  725. self::DoCreateActionGrant($iProfile, UR_ACTION_DELETE, $sClass);
  726. self::DoCreateActionGrant($iProfile, UR_ACTION_BULK_MODIFY, $sClass);
  727. // By default, do not allow bulk deletion operations for standard users
  728. // self::DoCreateActionGrant($iProfile, UR_ACTION_BULK_DELETE, $sClass);
  729. }
  730. // Grant stimuli for given classes
  731. foreach ($aStimuli as $sClass => $sAllowedStimuli)
  732. {
  733. if (!MetaModel::IsValidClass($sClass))
  734. {
  735. // Could be a class defined in a module that wasn't installed
  736. continue;
  737. //throw new CoreException("Invalid class name '$sClass'");
  738. }
  739. if ($sAllowedStimuli == 'any')
  740. {
  741. $aAllowedStimuli = array_keys(MetaModel::EnumStimuli($sClass));
  742. }
  743. elseif ($sAllowedStimuli == 'none')
  744. {
  745. $aAllowedStimuli = array();
  746. }
  747. else
  748. {
  749. $aAllowedStimuli = explode(',', $sAllowedStimuli);
  750. }
  751. foreach ($aAllowedStimuli as $sStimulusCode)
  752. {
  753. self::DoCreateStimulusGrant($iProfile, $sStimulusCode, $sClass);
  754. }
  755. }
  756. }
  757. public static function DoCreateProfiles()
  758. {
  759. self::DoCreateAdminProfile();
  760. foreach(self::$m_aProfiles as $sName => $aProfileData)
  761. {
  762. self::DoCreateOneProfile($sName, $aProfileData);
  763. }
  764. }
  765. public static function ComputeBasicProfiles()
  766. {
  767. // In this profiling scheme, one single module represents all the classes
  768. //
  769. self::$m_aModules = array(
  770. 'UserData' => MetaModel::GetClasses('bizmodel'),
  771. );
  772. self::$m_aProfiles = array(
  773. 'Reader' => array(
  774. 'description' => 'Person having a ready-only access to the data',
  775. 'write_modules' => '',
  776. 'stimuli' => array(
  777. ),
  778. ),
  779. 'Writer' => array(
  780. 'description' => 'Contributor to the contents (read + write access)',
  781. 'write_modules' => 'UserData',
  782. 'stimuli' => array(
  783. // any class => 'any'
  784. ),
  785. ),
  786. );
  787. }
  788. public static function ComputeITILProfiles()
  789. {
  790. // In this profiling scheme, modules are based on ITIL recommendations
  791. //
  792. self::$m_aModules = array(
  793. /*
  794. 'WriteModule' => array(
  795. 'someclass',
  796. 'anotherclass',
  797. ),
  798. */
  799. 'General' => MetaModel::GetClasses('structure'),
  800. 'Documentation' => MetaModel::GetClasses('documentation'),
  801. 'Configuration' => MetaModel::GetClasses('configmgmt'),
  802. 'Incident' => MetaModel::GetClasses('incidentmgmt'),
  803. 'Problem' => MetaModel::GetClasses('problemmgmt'),
  804. 'Change' => MetaModel::GetClasses('changemgmt'),
  805. 'Service' => MetaModel::GetClasses('servicemgmt'),
  806. 'Call' => MetaModel::GetClasses('requestmgmt'),
  807. 'KnownError' => MetaModel::GetClasses('knownerrormgmt'),
  808. );
  809. self::$m_aProfiles = array(
  810. 'Configuration Manager' => array(
  811. 'description' => 'Person in charge of the documentation of the managed CIs',
  812. 'write_modules' => 'General,Documentation,Configuration',
  813. 'stimuli' => array(
  814. //'bizServer' => 'none',
  815. //'bizContract' => 'none',
  816. //'bizIncidentTicket' => 'none',
  817. //'bizChangeTicket' => 'any',
  818. ),
  819. ),
  820. 'Service Desk Agent' => array(
  821. 'description' => 'Person in charge of creating incident reports',
  822. 'write_modules' => 'Incident,Call',
  823. 'stimuli' => array(
  824. 'Incident' => 'ev_assign',
  825. 'UserRequest' => 'ev_assign',
  826. ),
  827. ),
  828. 'Support Agent' => array(
  829. 'description' => 'Person analyzing and solving the current incidents or problems',
  830. 'write_modules' => 'Incident,Problem,KnownError',
  831. 'stimuli' => array(
  832. 'Incident' => 'ev_assign,ev_reassign,ev_resolve,ev_close',
  833. 'UserRequest' => 'ev_assign,ev_reassign,ev_resolve,ev_close,ev_freeze',
  834. ),
  835. ),
  836. 'Change Implementor' => array(
  837. 'description' => 'Person executing the changes',
  838. 'write_modules' => 'Change',
  839. 'stimuli' => array(
  840. 'NormalChange' => 'ev_plan,ev_replan,ev_implement,ev_monitor',
  841. 'EmergencyChange' => 'ev_plan,ev_replan,ev_implement,ev_monitor',
  842. 'RoutineChange' => 'ev_plan,ev_replan,ev_implement,ev_monitor',
  843. ),
  844. ),
  845. 'Change Supervisor' => array(
  846. 'description' => 'Person responsible for the overall change execution',
  847. 'write_modules' => 'Change',
  848. 'stimuli' => array(
  849. 'NormalChange' => 'ev_validate,ev_reject,ev_assign,ev_reopen,ev_finish',
  850. 'EmergencyChange' => 'ev_assign,ev_reopen,ev_finish',
  851. 'RoutineChange' => 'ev_assign,ev_reopen,ev_finish',
  852. ),
  853. ),
  854. 'Change Approver' => array(
  855. 'description' => 'Person who could be impacted by some changes',
  856. 'write_modules' => 'Change',
  857. 'stimuli' => array(
  858. 'NormalChange' => 'ev_approve,ev_notapprove',
  859. 'EmergencyChange' => 'ev_approve,ev_notapprove',
  860. 'RoutineChange' => 'none',
  861. ),
  862. ),
  863. 'Service Manager' => array(
  864. 'description' => 'Person responsible for the service delivered to the [internal] customer',
  865. 'write_modules' => 'Service',
  866. 'stimuli' => array(
  867. ),
  868. ),
  869. 'Document author' => array(
  870. 'description' => 'Any person who could contribute to documentation',
  871. 'write_modules' => 'Documentation',
  872. 'stimuli' => array(
  873. ),
  874. ),
  875. );
  876. }
  877. }
  878. UserRights::SelectModule('UserRightsProfile');
  879. ?>