userrightsprofile.class.inc.php 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011
  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. $iGrant = $oUserRights->GetProfileActionGrant($this->GetKey(), $sClass, $sAction);
  73. if (!is_null($iGrant))
  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('userid', '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. if (!MetaModel::IsValidClass($sClass))
  719. {
  720. throw new CoreException("Invalid class name '$sClass'");
  721. }
  722. self::DoCreateActionGrant($iProfile, UR_ACTION_MODIFY, $sClass);
  723. self::DoCreateActionGrant($iProfile, UR_ACTION_DELETE, $sClass);
  724. self::DoCreateActionGrant($iProfile, UR_ACTION_BULK_MODIFY, $sClass);
  725. // By default, do not allow bulk deletion operations for standard users
  726. // self::DoCreateActionGrant($iProfile, UR_ACTION_BULK_DELETE, $sClass);
  727. }
  728. // Grant stimuli for given classes
  729. foreach ($aStimuli as $sClass => $sAllowedStimuli)
  730. {
  731. if (!MetaModel::IsValidClass($sClass))
  732. {
  733. // Could be a class defined in a module that wasn't installed
  734. continue;
  735. //throw new CoreException("Invalid class name '$sClass'");
  736. }
  737. if ($sAllowedStimuli == 'any')
  738. {
  739. $aAllowedStimuli = array_keys(MetaModel::EnumStimuli($sClass));
  740. }
  741. elseif ($sAllowedStimuli == 'none')
  742. {
  743. $aAllowedStimuli = array();
  744. }
  745. else
  746. {
  747. $aAllowedStimuli = explode(',', $sAllowedStimuli);
  748. }
  749. foreach ($aAllowedStimuli as $sStimulusCode)
  750. {
  751. self::DoCreateStimulusGrant($iProfile, $sStimulusCode, $sClass);
  752. }
  753. }
  754. }
  755. public static function DoCreateProfiles()
  756. {
  757. self::DoCreateAdminProfile();
  758. foreach(self::$m_aProfiles as $sName => $aProfileData)
  759. {
  760. self::DoCreateOneProfile($sName, $aProfileData);
  761. }
  762. }
  763. public static function ComputeBasicProfiles()
  764. {
  765. // In this profiling scheme, one single module represents all the classes
  766. //
  767. self::$m_aModules = array(
  768. 'UserData' => MetaModel::GetClasses('bizmodel'),
  769. );
  770. self::$m_aProfiles = array(
  771. 'Reader' => array(
  772. 'description' => 'Person having a ready-only access to the data',
  773. 'write_modules' => '',
  774. 'stimuli' => array(
  775. ),
  776. ),
  777. 'Writer' => array(
  778. 'description' => 'Contributor to the contents (read + write access)',
  779. 'write_modules' => 'UserData',
  780. 'stimuli' => array(
  781. // any class => 'any'
  782. ),
  783. ),
  784. );
  785. }
  786. public static function ComputeITILProfiles()
  787. {
  788. // In this profiling scheme, modules are based on ITIL recommendations
  789. //
  790. self::$m_aModules = array(
  791. /*
  792. 'WriteModule' => array(
  793. 'someclass',
  794. 'anotherclass',
  795. ),
  796. */
  797. 'General' => MetaModel::GetClasses('structure'),
  798. 'Documentation' => MetaModel::GetClasses('documentation'),
  799. 'Configuration' => MetaModel::GetClasses('configmgmt'),
  800. 'Incident' => MetaModel::GetClasses('incidentmgmt'),
  801. 'Problem' => MetaModel::GetClasses('problemmgmt'),
  802. 'Change' => MetaModel::GetClasses('changemgmt'),
  803. 'Service' => MetaModel::GetClasses('servicemgmt'),
  804. 'Call' => MetaModel::GetClasses('requestmgmt'),
  805. 'KnownError' => MetaModel::GetClasses('knownerrormgmt'),
  806. );
  807. self::$m_aProfiles = array(
  808. 'Configuration Manager' => array(
  809. 'description' => 'Person in charge of the documentation of the managed CIs',
  810. 'write_modules' => 'General,Documentation,Configuration',
  811. 'stimuli' => array(
  812. //'bizServer' => 'none',
  813. //'bizContract' => 'none',
  814. //'bizIncidentTicket' => 'none',
  815. //'bizChangeTicket' => 'any',
  816. ),
  817. ),
  818. 'Service Desk Agent' => array(
  819. 'description' => 'Person in charge of creating incident reports',
  820. 'write_modules' => 'Incident,Call',
  821. 'stimuli' => array(
  822. 'Incident' => 'ev_assign',
  823. 'UserRequest' => 'ev_assign',
  824. ),
  825. ),
  826. 'Support Agent' => array(
  827. 'description' => 'Person analyzing and solving the current incidents',
  828. 'write_modules' => 'Incident',
  829. 'stimuli' => array(
  830. 'Incident' => 'ev_assign,ev_reassign,ev_resolve,ev_close',
  831. 'UserRequest' => 'ev_assign,ev_reassign,ev_resolve,ev_close,ev_freeze',
  832. ),
  833. ),
  834. 'Problem Manager' => array(
  835. 'description' => 'Person analyzing and solving the current problems',
  836. 'write_modules' => 'Problem,KnownError',
  837. 'stimuli' => array(
  838. 'Problem' => 'ev_assign,ev_reassign,ev_resolve,ev_close',
  839. ),
  840. ),
  841. 'Change Implementor' => array(
  842. 'description' => 'Person executing the changes',
  843. 'write_modules' => 'Change',
  844. 'stimuli' => array(
  845. 'NormalChange' => 'ev_plan,ev_replan,ev_implement,ev_monitor',
  846. 'EmergencyChange' => 'ev_plan,ev_replan,ev_implement,ev_monitor',
  847. 'RoutineChange' => 'ev_plan,ev_replan,ev_implement,ev_monitor',
  848. ),
  849. ),
  850. 'Change Supervisor' => array(
  851. 'description' => 'Person responsible for the overall change execution',
  852. 'write_modules' => 'Change',
  853. 'stimuli' => array(
  854. 'NormalChange' => 'ev_validate,ev_reject,ev_assign,ev_reopen,ev_finish',
  855. 'EmergencyChange' => 'ev_assign,ev_reopen,ev_finish',
  856. 'RoutineChange' => 'ev_assign,ev_reopen,ev_finish',
  857. ),
  858. ),
  859. 'Change Approver' => array(
  860. 'description' => 'Person who could be impacted by some changes',
  861. 'write_modules' => 'Change',
  862. 'stimuli' => array(
  863. 'NormalChange' => 'ev_approve,ev_notapprove',
  864. 'EmergencyChange' => 'ev_approve,ev_notapprove',
  865. 'RoutineChange' => 'none',
  866. ),
  867. ),
  868. 'Service Manager' => array(
  869. 'description' => 'Person responsible for the service delivered to the [internal] customer',
  870. 'write_modules' => 'Service',
  871. 'stimuli' => array(
  872. ),
  873. ),
  874. 'Document author' => array(
  875. 'description' => 'Any person who could contribute to documentation',
  876. 'write_modules' => 'Documentation',
  877. 'stimuli' => array(
  878. ),
  879. ),
  880. );
  881. }
  882. }
  883. UserRights::SelectModule('UserRightsProfile');
  884. ?>