userrightsprojection.class.inc.php 55 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599
  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. * UserRightsProjection
  18. * User management Module, basing the right on profiles and a matrix (similar to UserRightsProfile, but enhanced with dimensions and projection of classes and profile over the dimensions)
  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. // Whenever something changes, reload the privileges
  30. protected function AfterInsert()
  31. {
  32. UserRights::FlushPrivileges();
  33. }
  34. protected function AfterUpdate()
  35. {
  36. UserRights::FlushPrivileges();
  37. }
  38. protected function AfterDelete()
  39. {
  40. UserRights::FlushPrivileges();
  41. }
  42. }
  43. class URP_Profiles extends UserRightsBaseClass
  44. {
  45. public static function Init()
  46. {
  47. $aParams = array
  48. (
  49. "category" => "addon/userrights",
  50. "key_type" => "autoincrement",
  51. "name_attcode" => "name",
  52. "state_attcode" => "",
  53. "reconc_keys" => array(),
  54. "db_table" => "priv_urp_profiles",
  55. "db_key_field" => "id",
  56. "db_finalclass_field" => "",
  57. "display_template" => "",
  58. );
  59. MetaModel::Init_Params($aParams);
  60. //MetaModel::Init_InheritAttributes();
  61. MetaModel::Init_AddAttribute(new AttributeString("name", array("allowed_values"=>null, "sql"=>"name", "default_value"=>null, "is_null_allowed"=>false, "depends_on"=>array())));
  62. MetaModel::Init_AddAttribute(new AttributeString("description", array("allowed_values"=>null, "sql"=>"description", "default_value"=>null, "is_null_allowed"=>false, "depends_on"=>array())));
  63. MetaModel::Init_AddAttribute(new AttributeLinkedSetIndirect("user_list", array("linked_class"=>"URP_UserProfile", "ext_key_to_me"=>"profileid", "ext_key_to_remote"=>"userid", "allowed_values"=>null, "count_min"=>1, "count_max"=>0, "depends_on"=>array())));
  64. // Display lists
  65. MetaModel::Init_SetZListItems('details', array('name', 'description', 'user_list')); // Attributes to be displayed for the complete details
  66. MetaModel::Init_SetZListItems('list', array('description')); // Attributes to be displayed for a list
  67. // Search criteria
  68. MetaModel::Init_SetZListItems('standard_search', array('name')); // Criteria of the std search form
  69. MetaModel::Init_SetZListItems('advanced_search', array('name')); // Criteria of the advanced search form
  70. }
  71. function GetGrantAsHtml($oUserRights, $sClass, $sAction)
  72. {
  73. $oGrant = $oUserRights->GetClassActionGrant($this->GetKey(), $sClass, $sAction);
  74. if (is_object($oGrant) && ($oGrant->Get('permission') == 'yes'))
  75. {
  76. return '<span style="background-color: #ddffdd;">'.Dict::S('UI:UserManagement:ActionAllowed:Yes').'</span>';
  77. }
  78. else
  79. {
  80. return '<span style="background-color: #ffdddd;">'.Dict::S('UI:UserManagement:ActionAllowed:No').'</span>';
  81. }
  82. }
  83. function DoShowGrantSumary($oPage)
  84. {
  85. if ($this->GetName() == "Administrator")
  86. {
  87. // Looks dirty, but ok that's THE ONE
  88. $oPage->p(Dict::S('UI:UserManagement:AdminProfile+'));
  89. return;
  90. }
  91. // Note: for sure, we assume that the instance is derived from UserRightsProjection
  92. $oUserRights = UserRights::GetModuleInstance();
  93. $aDisplayData = array();
  94. foreach (MetaModel::GetClasses('bizmodel') as $sClass)
  95. {
  96. // Skip non instantiable classes
  97. if (MetaModel::IsAbstract($sClass)) continue;
  98. $aStimuli = array();
  99. foreach (MetaModel::EnumStimuli($sClass) as $sStimulusCode => $oStimulus)
  100. {
  101. $oGrant = $oUserRights->GetClassStimulusGrant($this->GetKey(), $sClass, $sStimulusCode);
  102. if (is_object($oGrant) && ($oGrant->Get('permission') == 'yes'))
  103. {
  104. $aStimuli[] = '<span title="'.$sStimulusCode.': '.htmlentities($oStimulus->GetDescription()).'">'.htmlentities($oStimulus->GetLabel()).'</span>';
  105. }
  106. }
  107. $sStimuli = implode(', ', $aStimuli);
  108. $aDisplayData[] = array(
  109. 'class' => MetaModel::GetName($sClass),
  110. 'read' => $this->GetGrantAsHtml($oUserRights, $sClass, 'Read'),
  111. 'bulkread' => $this->GetGrantAsHtml($oUserRights, $sClass, 'Bulk Read'),
  112. 'write' => $this->GetGrantAsHtml($oUserRights, $sClass, 'Modify'),
  113. 'bulkwrite' => $this->GetGrantAsHtml($oUserRights, $sClass, 'Bulk Modify'),
  114. 'delete' => $this->GetGrantAsHtml($oUserRights, $sClass, 'Delete'),
  115. 'bulkdelete' => $this->GetGrantAsHtml($oUserRights, $sClass, 'Bulk Delete'),
  116. 'stimuli' => $sStimuli,
  117. );
  118. }
  119. $aDisplayConfig = array();
  120. $aDisplayConfig['class'] = array('label' => Dict::S('UI:UserManagement:Class'), 'description' => Dict::S('UI:UserManagement:Class+'));
  121. $aDisplayConfig['read'] = array('label' => Dict::S('UI:UserManagement:Action:Read'), 'description' => Dict::S('UI:UserManagement:Action:Read+'));
  122. $aDisplayConfig['bulkread'] = array('label' => Dict::S('UI:UserManagement:Action:BulkRead'), 'description' => Dict::S('UI:UserManagement:Action:BulkRead+'));
  123. $aDisplayConfig['write'] = array('label' => Dict::S('UI:UserManagement:Action:Modify'), 'description' => Dict::S('UI:UserManagement:Action:Modify+'));
  124. $aDisplayConfig['bulkwrite'] = array('label' => Dict::S('UI:UserManagement:Action:BulkModify'), 'description' => Dict::S('UI:UserManagement:Action:BulkModify+'));
  125. $aDisplayConfig['delete'] = array('label' => Dict::S('UI:UserManagement:Action:Delete'), 'description' => Dict::S('UI:UserManagement:Action:Delete+'));
  126. $aDisplayConfig['bulkdelete'] = array('label' => Dict::S('UI:UserManagement:Action:BulkDelete'), 'description' => Dict::S('UI:UserManagement:Action:BulkDelete+'));
  127. $aDisplayConfig['stimuli'] = array('label' => Dict::S('UI:UserManagement:Action:Stimuli'), 'description' => Dict::S('UI:UserManagement:Action:Stimuli+'));
  128. $oPage->table($aDisplayConfig, $aDisplayData);
  129. }
  130. function DisplayBareRelations(WebPage $oPage, $bEditMode = false)
  131. {
  132. parent::DisplayBareRelations($oPage, $bEditMode);
  133. if (!$bEditMode)
  134. {
  135. $oPage->SetCurrentTab(Dict::S('UI:UserManagement:GrantMatrix'));
  136. $this->DoShowGrantSumary($oPage);
  137. }
  138. }
  139. }
  140. class URP_Dimensions extends UserRightsBaseClass
  141. {
  142. public static function Init()
  143. {
  144. $aParams = array
  145. (
  146. "category" => "addon/userrights",
  147. "key_type" => "autoincrement",
  148. "name_attcode" => "name",
  149. "state_attcode" => "",
  150. "reconc_keys" => array(),
  151. "db_table" => "priv_urp_dimensions",
  152. "db_key_field" => "id",
  153. "db_finalclass_field" => "",
  154. "display_template" => "",
  155. );
  156. MetaModel::Init_Params($aParams);
  157. //MetaModel::Init_InheritAttributes();
  158. MetaModel::Init_AddAttribute(new AttributeString("name", array("allowed_values"=>null, "sql"=>"name", "default_value"=>null, "is_null_allowed"=>false, "depends_on"=>array())));
  159. MetaModel::Init_AddAttribute(new AttributeString("description", array("allowed_values"=>null, "sql"=>"description", "default_value"=>null, "is_null_allowed"=>false, "depends_on"=>array())));
  160. MetaModel::Init_AddAttribute(new AttributeClass("type", array("class_category"=>"bizmodel", "more_values"=>"String,Integer", "sql"=>"type", "default_value"=>'String', "is_null_allowed"=>false, "depends_on"=>array())));
  161. // Display lists
  162. MetaModel::Init_SetZListItems('details', array('name', 'description', 'type')); // Attributes to be displayed for the complete details
  163. MetaModel::Init_SetZListItems('list', array('description')); // Attributes to be displayed for a list
  164. // Search criteria
  165. MetaModel::Init_SetZListItems('standard_search', array('name')); // Criteria of the std search form
  166. MetaModel::Init_SetZListItems('advanced_search', array('name')); // Criteria of the advanced search form
  167. }
  168. public function CheckProjectionSpec($oProjectionSpec, $sProjectedClass)
  169. {
  170. $sExpression = $oProjectionSpec->Get('value');
  171. $sAttribute = $oProjectionSpec->Get('attribute');
  172. // Shortcut: "any value" or "no value" means no projection
  173. if (empty($sExpression)) return;
  174. if ($sExpression == '<any>') return;
  175. // 1st - compute the data type for the dimension
  176. //
  177. $sType = $this->Get('type');
  178. if (MetaModel::IsValidClass($sType))
  179. {
  180. $sExpectedType = $sType;
  181. }
  182. else
  183. {
  184. $sExpectedType = '_scalar_';
  185. }
  186. // 2nd - compute the data type for the projection
  187. //
  188. $sTargetClass = '';
  189. if (($sExpression == '<this>') || ($sExpression == '<user>'))
  190. {
  191. $sTargetClass = $sProjectedClass;
  192. }
  193. elseif ($sExpression == '<any>')
  194. {
  195. $sTargetClass = '';
  196. }
  197. else
  198. {
  199. // Evaluate wether it is a constant or not
  200. try
  201. {
  202. $oObjectSearch = DBObjectSearch::FromOQL_AllData($sExpression);
  203. $sTargetClass = $oObjectSearch->GetClass();
  204. }
  205. catch (OqlException $e)
  206. {
  207. }
  208. }
  209. if (empty($sTargetClass))
  210. {
  211. $sFoundType = '_void_';
  212. }
  213. else
  214. {
  215. if (empty($sAttribute))
  216. {
  217. $sFoundType = $sTargetClass;
  218. }
  219. else
  220. {
  221. if (!MetaModel::IsValidAttCode($sTargetClass, $sAttribute))
  222. {
  223. throw new CoreException('Unkown attribute code in projection specification', array('found' => $sAttribute, 'expecting' => MetaModel::GetAttributesList($sTargetClass), 'class' => $sTargetClass, 'projection' => $oProjectionSpec));
  224. }
  225. $oAttDef = MetaModel::GetAttributeDef($sTargetClass, $sAttribute);
  226. if ($oAttDef->IsExternalKey())
  227. {
  228. $sFoundType = $oAttDef->GetTargetClass();
  229. }
  230. else
  231. {
  232. $sFoundType = '_scalar_';
  233. }
  234. }
  235. }
  236. // Compare the dimension type and projection type
  237. if (($sFoundType != '_void_') && ($sFoundType != $sExpectedType))
  238. {
  239. throw new CoreException('Wrong type in projection specification', array('found' => $sFoundType, 'expecting' => $sExpectedType, 'expression' => $sExpression, 'attribute' => $sAttribute, 'projection' => $oProjectionSpec));
  240. }
  241. }
  242. }
  243. class URP_UserProfile extends UserRightsBaseClass
  244. {
  245. public static function Init()
  246. {
  247. $aParams = array
  248. (
  249. "category" => "addon/userrights",
  250. "key_type" => "autoincrement",
  251. "name_attcode" => "userid",
  252. "state_attcode" => "",
  253. "reconc_keys" => array(),
  254. "db_table" => "priv_urp_userprofile",
  255. "db_key_field" => "id",
  256. "db_finalclass_field" => "",
  257. "display_template" => "",
  258. );
  259. MetaModel::Init_Params($aParams);
  260. //MetaModel::Init_InheritAttributes();
  261. 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())));
  262. MetaModel::Init_AddAttribute(new AttributeExternalField("userlogin", array("allowed_values"=>null, "extkey_attcode"=> 'userid', "target_attcode"=>"login")));
  263. 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())));
  264. MetaModel::Init_AddAttribute(new AttributeExternalField("profile", array("allowed_values"=>null, "extkey_attcode"=> 'profileid', "target_attcode"=>"name")));
  265. MetaModel::Init_AddAttribute(new AttributeString("reason", array("allowed_values"=>null, "sql"=>"description", "default_value"=>null, "is_null_allowed"=>true, "depends_on"=>array())));
  266. // Display lists
  267. MetaModel::Init_SetZListItems('details', array('userid', 'profileid', 'reason')); // Attributes to be displayed for the complete details
  268. MetaModel::Init_SetZListItems('list', array('profileid', 'reason')); // Attributes to be displayed for a list
  269. // Search criteria
  270. MetaModel::Init_SetZListItems('standard_search', array('userid', 'profileid')); // Criteria of the std search form
  271. MetaModel::Init_SetZListItems('advanced_search', array('userid', 'profileid')); // Criteria of the advanced search form
  272. }
  273. public function GetName()
  274. {
  275. return Dict::Format('UI:UserManagement:LinkBetween_User_And_Profile', $this->Get('userlogin'), $this->Get('profile'));
  276. }
  277. }
  278. class URP_ProfileProjection extends UserRightsBaseClass
  279. {
  280. public static function Init()
  281. {
  282. $aParams = array
  283. (
  284. "category" => "addon/userrights",
  285. "key_type" => "autoincrement",
  286. "name_attcode" => "profileid",
  287. "state_attcode" => "",
  288. "reconc_keys" => array(),
  289. "db_table" => "priv_urp_profileprojection",
  290. "db_key_field" => "id",
  291. "db_finalclass_field" => "",
  292. "display_template" => "",
  293. );
  294. MetaModel::Init_Params($aParams);
  295. //MetaModel::Init_InheritAttributes();
  296. MetaModel::Init_AddAttribute(new AttributeExternalKey("dimensionid", array("targetclass"=>"URP_Dimensions", "jointype"=> "", "allowed_values"=>null, "sql"=>"dimensionid", "is_null_allowed"=>false, "on_target_delete"=>DEL_MANUAL, "depends_on"=>array())));
  297. MetaModel::Init_AddAttribute(new AttributeExternalField("dimension", array("allowed_values"=>null, "extkey_attcode"=> 'dimensionid', "target_attcode"=>"name")));
  298. 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())));
  299. MetaModel::Init_AddAttribute(new AttributeExternalField("profile", array("allowed_values"=>null, "extkey_attcode"=> 'profileid', "target_attcode"=>"name")));
  300. MetaModel::Init_AddAttribute(new AttributeString("value", array("allowed_values"=>null, "sql"=>"value", "default_value"=>"", "is_null_allowed"=>false, "depends_on"=>array())));
  301. MetaModel::Init_AddAttribute(new AttributeString("attribute", array("allowed_values"=>null, "sql"=>"attribute", "default_value"=>"", "is_null_allowed"=>false, "depends_on"=>array())));
  302. // Display lists
  303. MetaModel::Init_SetZListItems('details', array('dimensionid', 'profileid', 'value', 'attribute')); // Attributes to be displayed for the complete details
  304. MetaModel::Init_SetZListItems('list', array('profileid', 'value', 'attribute')); // Attributes to be displayed for a list
  305. // Search criteria
  306. MetaModel::Init_SetZListItems('standard_search', array('dimensionid', 'profileid')); // Criteria of the std search form
  307. MetaModel::Init_SetZListItems('advanced_search', array('dimensionid', 'profileid')); // Criteria of the advanced search form
  308. }
  309. protected $m_aUserProjections; // cache
  310. public function ProjectUser(User $oUser)
  311. {
  312. if (is_array($this->m_aUserProjections))
  313. {
  314. // Hit!
  315. return $this->m_aUserProjections;
  316. }
  317. $sExpr = $this->Get('value');
  318. if ($sExpr == '<user>')
  319. {
  320. $sColumn = $this->Get('attribute');
  321. if (empty($sColumn))
  322. {
  323. $aRes = array($oUser->GetKey());
  324. }
  325. else
  326. {
  327. $aRes = array($oUser->Get($sColumn));
  328. }
  329. }
  330. elseif (($sExpr == '<any>') || ($sExpr == ''))
  331. {
  332. $aRes = null;
  333. }
  334. elseif (strtolower(substr($sExpr, 0, 6)) == 'select')
  335. {
  336. $sColumn = $this->Get('attribute');
  337. // SELECT...
  338. $oValueSetDef = new ValueSetObjects($sExpr, $sColumn, array(), true /*allow all data*/);
  339. $aRes = $oValueSetDef->GetValues(array('user' => $oUser), '');
  340. }
  341. else
  342. {
  343. // Constant value(s)
  344. $aRes = explode(';', trim($sExpr));
  345. }
  346. $this->m_aUserProjections = $aRes;
  347. return $aRes;
  348. }
  349. }
  350. class URP_ClassProjection extends UserRightsBaseClass
  351. {
  352. public static function Init()
  353. {
  354. $aParams = array
  355. (
  356. "category" => "addon/userrights",
  357. "key_type" => "autoincrement",
  358. "name_attcode" => "dimensionid",
  359. "state_attcode" => "",
  360. "reconc_keys" => array(),
  361. "db_table" => "priv_urp_classprojection",
  362. "db_key_field" => "id",
  363. "db_finalclass_field" => "",
  364. "display_template" => "",
  365. );
  366. MetaModel::Init_Params($aParams);
  367. //MetaModel::Init_InheritAttributes();
  368. MetaModel::Init_AddAttribute(new AttributeExternalKey("dimensionid", array("targetclass"=>"URP_Dimensions", "jointype"=> "", "allowed_values"=>null, "sql"=>"dimensionid", "is_null_allowed"=>false, "on_target_delete"=>DEL_MANUAL, "depends_on"=>array())));
  369. MetaModel::Init_AddAttribute(new AttributeExternalField("dimension", array("allowed_values"=>null, "extkey_attcode"=> 'dimensionid', "target_attcode"=>"name")));
  370. MetaModel::Init_AddAttribute(new AttributeClass("class", array("class_category"=>"", "more_values"=>"", "sql"=>"class", "default_value"=>null, "is_null_allowed"=>false, "depends_on"=>array())));
  371. MetaModel::Init_AddAttribute(new AttributeString("value", array("allowed_values"=>null, "sql"=>"value", "default_value"=>"", "is_null_allowed"=>false, "depends_on"=>array())));
  372. MetaModel::Init_AddAttribute(new AttributeString("attribute", array("allowed_values"=>null, "sql"=>"attribute", "default_value"=>"", "is_null_allowed"=>false, "depends_on"=>array())));
  373. // Display lists
  374. MetaModel::Init_SetZListItems('details', array('dimensionid', 'class', 'value', 'attribute')); // Attributes to be displayed for the complete details
  375. MetaModel::Init_SetZListItems('list', array('class', 'value', 'attribute')); // Attributes to be displayed for a list
  376. // Search criteria
  377. MetaModel::Init_SetZListItems('standard_search', array('dimensionid', 'class')); // Criteria of the std search form
  378. MetaModel::Init_SetZListItems('advanced_search', array('dimensionid', 'class')); // Criteria of the advanced search form
  379. }
  380. public function ProjectObject($oObject)
  381. {
  382. $sExpr = $this->Get('value');
  383. if ($sExpr == '<this>')
  384. {
  385. $sColumn = $this->Get('attribute');
  386. if (empty($sColumn))
  387. {
  388. $aRes = array($oObject->GetKey());
  389. }
  390. else
  391. {
  392. $aRes = array($oObject->Get($sColumn));
  393. }
  394. }
  395. elseif (($sExpr == '<any>') || ($sExpr == ''))
  396. {
  397. $aRes = null;
  398. }
  399. elseif (strtolower(substr($sExpr, 0, 6)) == 'select')
  400. {
  401. $sColumn = $this->Get('attribute');
  402. // SELECT...
  403. $oValueSetDef = new ValueSetObjects($sExpr, $sColumn, array(), true /*allow all data*/);
  404. $aRes = $oValueSetDef->GetValues(array('this' => $oObject), '');
  405. }
  406. else
  407. {
  408. // Constant value(s)
  409. $aRes = explode(';', trim($sExpr));
  410. }
  411. return $aRes;
  412. }
  413. }
  414. class URP_ActionGrant extends UserRightsBaseClass
  415. {
  416. public static function Init()
  417. {
  418. $aParams = array
  419. (
  420. "category" => "addon/userrights",
  421. "key_type" => "autoincrement",
  422. "name_attcode" => "profileid",
  423. "state_attcode" => "",
  424. "reconc_keys" => array(),
  425. "db_table" => "priv_urp_grant_actions",
  426. "db_key_field" => "id",
  427. "db_finalclass_field" => "",
  428. "display_template" => "",
  429. );
  430. MetaModel::Init_Params($aParams);
  431. //MetaModel::Init_InheritAttributes();
  432. // Common to all grant classes (could be factorized by class inheritence, but this has to be benchmarked)
  433. 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())));
  434. MetaModel::Init_AddAttribute(new AttributeExternalField("profile", array("allowed_values"=>null, "extkey_attcode"=> 'profileid', "target_attcode"=>"name")));
  435. MetaModel::Init_AddAttribute(new AttributeClass("class", array("class_category"=>"", "more_values"=>"", "sql"=>"class", "default_value"=>null, "is_null_allowed"=>false, "depends_on"=>array())));
  436. 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())));
  437. MetaModel::Init_AddAttribute(new AttributeString("action", array("allowed_values"=>null, "sql"=>"action", "default_value"=>"", "is_null_allowed"=>false, "depends_on"=>array())));
  438. // Display lists
  439. MetaModel::Init_SetZListItems('details', array('profileid', 'class', 'permission', 'action')); // Attributes to be displayed for the complete details
  440. MetaModel::Init_SetZListItems('list', array('class', 'permission', 'action')); // Attributes to be displayed for a list
  441. // Search criteria
  442. MetaModel::Init_SetZListItems('standard_search', array('profileid', 'class', 'permission', 'action')); // Criteria of the std search form
  443. MetaModel::Init_SetZListItems('advanced_search', array('profileid', 'class', 'permission', 'action')); // Criteria of the advanced search form
  444. }
  445. }
  446. class URP_StimulusGrant extends UserRightsBaseClass
  447. {
  448. public static function Init()
  449. {
  450. $aParams = array
  451. (
  452. "category" => "addon/userrights",
  453. "key_type" => "autoincrement",
  454. "name_attcode" => "profileid",
  455. "state_attcode" => "",
  456. "reconc_keys" => array(),
  457. "db_table" => "priv_urp_grant_stimulus",
  458. "db_key_field" => "id",
  459. "db_finalclass_field" => "",
  460. "display_template" => "",
  461. );
  462. MetaModel::Init_Params($aParams);
  463. //MetaModel::Init_InheritAttributes();
  464. // Common to all grant classes (could be factorized by class inheritence, but this has to be benchmarked)
  465. 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())));
  466. MetaModel::Init_AddAttribute(new AttributeExternalField("profile", array("allowed_values"=>null, "extkey_attcode"=> 'profileid', "target_attcode"=>"name")));
  467. MetaModel::Init_AddAttribute(new AttributeClass("class", array("class_category"=>"", "more_values"=>"", "sql"=>"class", "default_value"=>null, "is_null_allowed"=>false, "depends_on"=>array())));
  468. 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())));
  469. MetaModel::Init_AddAttribute(new AttributeString("stimulus", array("allowed_values"=>null, "sql"=>"action", "default_value"=>"", "is_null_allowed"=>false, "depends_on"=>array())));
  470. // Display lists
  471. MetaModel::Init_SetZListItems('details', array('profileid', 'class', 'permission', 'stimulus')); // Attributes to be displayed for the complete details
  472. MetaModel::Init_SetZListItems('list', array('class', 'permission', 'stimulus')); // Attributes to be displayed for a list
  473. // Search criteria
  474. MetaModel::Init_SetZListItems('standard_search', array('profileid', 'class', 'permission', 'stimulus')); // Criteria of the std search form
  475. MetaModel::Init_SetZListItems('advanced_search', array('profileid', 'class', 'permission', 'stimulus')); // Criteria of the advanced search form
  476. }
  477. }
  478. class URP_AttributeGrant extends UserRightsBaseClass
  479. {
  480. public static function Init()
  481. {
  482. $aParams = array
  483. (
  484. "category" => "addon/userrights",
  485. "key_type" => "autoincrement",
  486. "name_attcode" => "actiongrantid",
  487. "state_attcode" => "",
  488. "reconc_keys" => array(),
  489. "db_table" => "priv_urp_grant_attributes",
  490. "db_key_field" => "id",
  491. "db_finalclass_field" => "",
  492. "display_template" => "",
  493. );
  494. MetaModel::Init_Params($aParams);
  495. //MetaModel::Init_InheritAttributes();
  496. 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())));
  497. MetaModel::Init_AddAttribute(new AttributeString("attcode", array("allowed_values"=>null, "sql"=>"attcode", "default_value"=>null, "is_null_allowed"=>false, "depends_on"=>array())));
  498. // Display lists
  499. MetaModel::Init_SetZListItems('details', array('actiongrantid', 'attcode')); // Attributes to be displayed for the complete details
  500. MetaModel::Init_SetZListItems('list', array('attcode')); // Attributes to be displayed for a list
  501. // Search criteria
  502. MetaModel::Init_SetZListItems('standard_search', array('actiongrantid', 'attcode')); // Criteria of the std search form
  503. MetaModel::Init_SetZListItems('advanced_search', array('actiongrantid', 'attcode')); // Criteria of the advanced search form
  504. }
  505. }
  506. class UserRightsProjection extends UserRightsAddOnAPI
  507. {
  508. static public $m_aActionCodes = array(
  509. UR_ACTION_READ => 'read',
  510. UR_ACTION_MODIFY => 'modify',
  511. UR_ACTION_DELETE => 'delete',
  512. UR_ACTION_BULK_READ => 'bulk read',
  513. UR_ACTION_BULK_MODIFY => 'bulk modify',
  514. UR_ACTION_BULK_DELETE => 'bulk delete',
  515. );
  516. // Installation: create the very first user
  517. public function CreateAdministrator($sAdminUser, $sAdminPwd, $sLanguage = 'EN US')
  518. {
  519. // Create a change to record the history of the User object
  520. $oChange = MetaModel::NewObject("CMDBChange");
  521. $oChange->Set("date", time());
  522. $oChange->Set("userinfo", "Initialization");
  523. $iChangeId = $oChange->DBInsert();
  524. $oOrg = new Organization();
  525. $oOrg->Set('name', 'My Company/Department');
  526. $oOrg->Set('code', 'SOMECODE');
  527. // $oOrg->Set('status', 'implementation');
  528. //$oOrg->Set('parent_id', xxx);
  529. $iOrgId = $oOrg->DBInsertTrackedNoReload($oChange, true /* skip strong security */);
  530. // Location : optional
  531. //$oLocation = new bizLocation();
  532. //$oLocation->Set('name', 'MyOffice');
  533. //$oLocation->Set('status', 'implementation');
  534. //$oLocation->Set('org_id', $iOrgId);
  535. //$oLocation->Set('severity', 'high');
  536. //$oLocation->Set('address', 'my building in my city');
  537. //$oLocation->Set('country', 'my country');
  538. //$oLocation->Set('parent_location_id', xxx);
  539. //$iLocationId = $oLocation->DBInsertNoReload();
  540. $oContact = new Person();
  541. $oContact->Set('name', 'My last name');
  542. $oContact->Set('first_name', 'My first name');
  543. //$oContact->Set('status', 'available');
  544. $oContact->Set('org_id', $iOrgId);
  545. $oContact->Set('email', 'my.email@foo.org');
  546. //$oContact->Set('phone', '');
  547. //$oContact->Set('location_id', $iLocationId);
  548. //$oContact->Set('employee_number', '');
  549. $iContactId = $oContact->DBInsertTrackedNoReload($oChange, true /* skip security */);
  550. $oUser = new UserLocal();
  551. $oUser->Set('login', $sAdminUser);
  552. $oUser->Set('password', $sAdminPwd);
  553. $oUser->Set('contactid', $iContactId);
  554. $oUser->Set('language', $sLanguage); // Language was chosen during the installation
  555. $iUserId = $oUser->DBInsertTrackedNoReload($oChange, true /* skip security */);
  556. // Add this user to the very specific 'admin' profile
  557. $oUserProfile = new URP_UserProfile();
  558. $oUserProfile->Set('userid', $iUserId);
  559. $oUserProfile->Set('profileid', ADMIN_PROFILE_ID);
  560. $oUserProfile->Set('reason', 'By definition, the administrator must have the administrator profile');
  561. $oUserProfile->DBInsertTrackedNoReload($oChange, true /* skip security */);
  562. return true;
  563. }
  564. public function IsAdministrator($oUser)
  565. {
  566. if (in_array($oUser->GetKey(), $this->m_aAdmins))
  567. {
  568. return true;
  569. }
  570. else
  571. {
  572. return false;
  573. }
  574. }
  575. public function IsPortalUser($oUser)
  576. {
  577. return true;
  578. // See implementation of userrightsprofile
  579. }
  580. public function Setup()
  581. {
  582. SetupProfiles::ComputeITILProfiles();
  583. //SetupProfiles::ComputeBasicProfiles();
  584. SetupProfiles::DoCreateDimensions();
  585. SetupProfiles::DoCreateProfiles();
  586. return true;
  587. }
  588. public function Init()
  589. {
  590. MetaModel::RegisterPlugin('userrights', 'ACbyProfile', array($this, 'CacheData'));
  591. }
  592. protected $m_aDimensions = array(); // id -> object
  593. protected $m_aClassProj = array(); // class,dimensionid -> object
  594. protected $m_aProfiles = array(); // id -> object
  595. protected $m_aUserProfiles = array(); // userid,profileid -> object
  596. protected $m_aProPro = array(); // profileid,dimensionid -> object
  597. protected $m_aAdmins = array(); // id of users being linked to the well-known admin profile
  598. protected $m_aClassActionGrants = array(); // profile, class, action -> permission
  599. protected $m_aClassStimulusGrants = array(); // profile, class, stimulus -> permission
  600. protected $m_aObjectActionGrants = array(); // userid, class, id, action -> permission, list of attributes
  601. public function CacheData()
  602. {
  603. // Could be loaded in a shared memory (?)
  604. $oDimensionSet = new DBObjectSet(DBObjectSearch::FromOQL_AllData("SELECT URP_Dimensions"));
  605. $this->m_aDimensions = array();
  606. while ($oDimension = $oDimensionSet->Fetch())
  607. {
  608. $this->m_aDimensions[$oDimension->GetKey()] = $oDimension;
  609. }
  610. $oClassProjSet = new DBObjectSet(DBObjectSearch::FromOQL_AllData("SELECT URP_ClassProjection"));
  611. $this->m_aClassProjs = array();
  612. while ($oClassProj = $oClassProjSet->Fetch())
  613. {
  614. $this->m_aClassProjs[$oClassProj->Get('class')][$oClassProj->Get('dimensionid')] = $oClassProj;
  615. }
  616. $oProfileSet = new DBObjectSet(DBObjectSearch::FromOQL_AllData("SELECT URP_Profiles"));
  617. $this->m_aProfiles = array();
  618. while ($oProfile = $oProfileSet->Fetch())
  619. {
  620. $this->m_aProfiles[$oProfile->GetKey()] = $oProfile;
  621. }
  622. $oUserProfileSet = new DBObjectSet(DBObjectSearch::FromOQL_AllData("SELECT URP_UserProfile"));
  623. $this->m_aUserProfiles = array();
  624. $this->m_aAdmins = array();
  625. while ($oUserProfile = $oUserProfileSet->Fetch())
  626. {
  627. $this->m_aUserProfiles[$oUserProfile->Get('userid')][$oUserProfile->Get('profileid')] = $oUserProfile;
  628. if ($oUserProfile->Get('profileid') == ADMIN_PROFILE_ID)
  629. {
  630. $this->m_aAdmins[] = $oUserProfile->Get('userid');
  631. }
  632. }
  633. $oProProSet = new DBObjectSet(DBObjectSearch::FromOQL_AllData("SELECT URP_ProfileProjection"));
  634. $this->m_aProPros = array();
  635. while ($oProPro = $oProProSet->Fetch())
  636. {
  637. $this->m_aProPros[$oProPro->Get('profileid')][$oProPro->Get('dimensionid')] = $oProPro;
  638. }
  639. /*
  640. echo "<pre>\n";
  641. print_r($this->m_aDimensions);
  642. print_r($this->m_aClassProjs);
  643. print_r($this->m_aProfiles);
  644. print_r($this->m_aUserProfiles);
  645. print_r($this->m_aProPros);
  646. echo "</pre>\n";
  647. exit;
  648. */
  649. return true;
  650. }
  651. public function GetSelectFilter($oUser, $sClass)
  652. {
  653. $aConditions = array();
  654. foreach ($this->m_aDimensions as $iDimension => $oDimension)
  655. {
  656. $oClassProj = @$this->m_aClassProjs[$sClass][$iDimension];
  657. if (is_null($oClassProj))
  658. {
  659. // Authorize any for this dimension, then no additional criteria is required
  660. continue;
  661. }
  662. // 1 - Get class projection info
  663. //
  664. $oExpression = null;
  665. $sExpr = $oClassProj->Get('value');
  666. if ($sExpr == '<this>')
  667. {
  668. $sColumn = $oClassProj->Get('attribute');
  669. if (empty($sColumn))
  670. {
  671. $oExpression = new FieldExpression('id', $sClass);
  672. }
  673. else
  674. {
  675. $oExpression = new FieldExpression($sColumn, $sClass);
  676. }
  677. }
  678. elseif (($sExpr == '<any>') || ($sExpr == ''))
  679. {
  680. // Authorize any for this dimension, then no additional criteria is required
  681. continue;
  682. }
  683. elseif (strtolower(substr($sExpr, 0, 6)) == 'select')
  684. {
  685. throw new CoreException('Sorry, projections by the mean of OQL are not supported currently, please specify an attribute instead', array('class' => $sClass, 'expression' => $sExpr));
  686. }
  687. else
  688. {
  689. // Constant value(s)
  690. // unsupported
  691. throw new CoreException('Sorry, constant projections are not supported currently, please specify an attribute instead', array('class' => $sClass, 'expression' => $sExpr));
  692. // $aRes = explode(';', trim($sExpr));
  693. }
  694. // 2 - Get profile projection info and use it if needed
  695. //
  696. $aProjections = self::GetReadableProjectionsByDim($oUser, $sClass, $oDimension);
  697. if (is_null($aProjections))
  698. {
  699. // Authorize any for this dimension, then no additional criteria is required
  700. continue;
  701. }
  702. elseif (count($aProjections) == 0)
  703. {
  704. // Authorize none, then exit as quickly as possible
  705. return false;
  706. }
  707. else
  708. {
  709. // Authorize the given set of values
  710. $oListExpr = ListExpression::FromScalars($aProjections);
  711. $oCondition = new BinaryExpression($oExpression, 'IN', $oListExpr);
  712. $aConditions[] = $oCondition;
  713. }
  714. }
  715. if (count($aConditions) == 0)
  716. {
  717. // allow all
  718. return true;
  719. }
  720. else
  721. {
  722. $oFilter = new DBObjectSearch($sClass);
  723. foreach($aConditions as $oCondition)
  724. {
  725. $oFilter->AddConditionExpression($oCondition);
  726. }
  727. //return true;
  728. return $oFilter;
  729. }
  730. }
  731. // This verb has been made public to allow the development of an accurate feedback for the current configuration
  732. public function GetClassActionGrant($iProfile, $sClass, $sAction)
  733. {
  734. if (isset($this->m_aClassActionGrants[$iProfile][$sClass][$sAction]))
  735. {
  736. return $this->m_aClassActionGrants[$iProfile][$sClass][$sAction];
  737. }
  738. // Get the permission for this profile/class/action
  739. $oSearch = DBObjectSearch::FromOQL_AllData("SELECT URP_ActionGrant WHERE class = :class AND action = :action AND profileid = :profile AND permission = 'yes'");
  740. $oSet = new DBObjectSet($oSearch, array(), array('class'=>$sClass, 'action'=>$sAction, 'profile'=>$iProfile));
  741. if ($oSet->Count() >= 1)
  742. {
  743. $oGrantRecord = $oSet->Fetch();
  744. }
  745. else
  746. {
  747. $sParentClass = MetaModel::GetParentPersistentClass($sClass);
  748. if (empty($sParentClass))
  749. {
  750. $oGrantRecord = null;
  751. }
  752. else
  753. {
  754. $oGrantRecord = $this->GetClassActionGrant($iProfile, $sParentClass, $sAction);
  755. }
  756. }
  757. $this->m_aClassActionGrants[$iProfile][$sClass][$sAction] = $oGrantRecord;
  758. return $oGrantRecord;
  759. }
  760. protected function GetObjectActionGrant($oUser, $sClass, $iActionCode, /*DBObject*/ $oObject = null)
  761. {
  762. if(is_null($oObject))
  763. {
  764. $iObjectRef = -999;
  765. }
  766. else
  767. {
  768. $iObjectRef = $oObject->GetKey();
  769. }
  770. // load and cache permissions for the current user on the given object
  771. //
  772. $aTest = @$this->m_aObjectActionGrants[$oUser->GetKey()][$sClass][$iObjectRef][$iActionCode];
  773. if (is_array($aTest)) return $aTest;
  774. $sAction = self::$m_aActionCodes[$iActionCode];
  775. $iInstancePermission = UR_ALLOWED_NO;
  776. $aAttributes = array();
  777. foreach($this->GetMatchingProfiles($oUser, $sClass, $oObject) as $iProfile)
  778. {
  779. $oGrantRecord = $this->GetClassActionGrant($iProfile, $sClass, $sAction);
  780. if (is_null($oGrantRecord))
  781. {
  782. continue; // loop to the next profile
  783. }
  784. else
  785. {
  786. $iInstancePermission = UR_ALLOWED_YES;
  787. // update the list of attributes with those allowed for this profile
  788. //
  789. $oSearch = DBObjectSearch::FromOQL_AllData("SELECT URP_AttributeGrant WHERE actiongrantid = :actiongrantid");
  790. $oSet = new DBObjectSet($oSearch, array(), array('actiongrantid' => $oGrantRecord->GetKey()));
  791. $aProfileAttributes = $oSet->GetColumnAsArray('attcode', false);
  792. if (count($aProfileAttributes) == 0)
  793. {
  794. $aAllAttributes = array_keys(MetaModel::ListAttributeDefs($sClass));
  795. $aAttributes = array_merge($aAttributes, $aAllAttributes);
  796. }
  797. else
  798. {
  799. $aAttributes = array_merge($aAttributes, $aProfileAttributes);
  800. }
  801. }
  802. }
  803. $aRes = array(
  804. 'permission' => $iInstancePermission,
  805. 'attributes' => $aAttributes,
  806. );
  807. $this->m_aObjectActionGrants[$oUser->GetKey()][$sClass][$iObjectRef][$iActionCode] = $aRes;
  808. return $aRes;
  809. }
  810. public function IsActionAllowed($oUser, $sClass, $iActionCode, $oInstanceSet = null)
  811. {
  812. if (is_null($oInstanceSet))
  813. {
  814. $aObjectPermissions = $this->GetObjectActionGrant($oUser, $sClass, $iActionCode);
  815. return $aObjectPermissions['permission'];
  816. }
  817. $oInstanceSet->Rewind();
  818. while($oObject = $oInstanceSet->Fetch())
  819. {
  820. $aObjectPermissions = $this->GetObjectActionGrant($oUser, $sClass, $iActionCode, $oObject);
  821. $iInstancePermission = $aObjectPermissions['permission'];
  822. if (isset($iGlobalPermission))
  823. {
  824. if ($iInstancePermission != $iGlobalPermission)
  825. {
  826. $iGlobalPermission = UR_ALLOWED_DEPENDS;
  827. break;
  828. }
  829. }
  830. else
  831. {
  832. $iGlobalPermission = $iInstancePermission;
  833. }
  834. }
  835. $oInstanceSet->Rewind();
  836. if (isset($iGlobalPermission))
  837. {
  838. return $iGlobalPermission;
  839. }
  840. else
  841. {
  842. return UR_ALLOWED_NO;
  843. }
  844. }
  845. public function IsActionAllowedOnAttribute($oUser, $sClass, $sAttCode, $iActionCode, $oInstanceSet = null)
  846. {
  847. if (is_null($oInstanceSet))
  848. {
  849. $aObjectPermissions = $this->GetObjectActionGrant($oUser, $sClass, $iActionCode);
  850. $aAttributes = $aObjectPermissions['attributes'];
  851. if (in_array($sAttCode, $aAttributes))
  852. {
  853. return $aObjectPermissions['permission'];
  854. }
  855. else
  856. {
  857. return UR_ALLOWED_NO;
  858. }
  859. }
  860. $oInstanceSet->Rewind();
  861. while($oObject = $oInstanceSet->Fetch())
  862. {
  863. $aObjectPermissions = $this->GetObjectActionGrant($oUser, $sClass, $iActionCode, $oObject);
  864. $aAttributes = $aObjectPermissions['attributes'];
  865. if (in_array($sAttCode, $aAttributes))
  866. {
  867. $iInstancePermission = $aObjectPermissions['permission'];
  868. }
  869. else
  870. {
  871. $iInstancePermission = UR_ALLOWED_NO;
  872. }
  873. if (isset($iGlobalPermission))
  874. {
  875. if ($iInstancePermission != $iGlobalPermission)
  876. {
  877. $iGlobalPermission = UR_ALLOWED_DEPENDS;
  878. }
  879. }
  880. else
  881. {
  882. $iGlobalPermission = $iInstancePermission;
  883. }
  884. }
  885. $oInstanceSet->Rewind();
  886. if (isset($iGlobalPermission))
  887. {
  888. return $iGlobalPermission;
  889. }
  890. else
  891. {
  892. return UR_ALLOWED_NO;
  893. }
  894. }
  895. // This verb has been made public to allow the development of an accurate feedback for the current configuration
  896. public function GetClassStimulusGrant($iProfile, $sClass, $sStimulusCode)
  897. {
  898. if (isset($this->m_aClassStimulusGrants[$iProfile][$sClass][$sStimulusCode]))
  899. {
  900. return $this->m_aClassStimulusGrants[$iProfile][$sClass][$sStimulusCode];
  901. }
  902. // Get the permission for this profile/class/stimulus
  903. $oSearch = DBObjectSearch::FromOQL_AllData("SELECT URP_StimulusGrant WHERE class = :class AND stimulus = :stimulus AND profileid = :profile AND permission = 'yes'");
  904. $oSet = new DBObjectSet($oSearch, array(), array('class'=>$sClass, 'stimulus'=>$sStimulusCode, 'profile'=>$iProfile));
  905. if ($oSet->Count() >= 1)
  906. {
  907. $oGrantRecord = $oSet->Fetch();
  908. }
  909. else
  910. {
  911. $oGrantRecord = null;
  912. }
  913. $this->m_aClassStimulusGrants[$iProfile][$sClass][$sStimulusCode] = $oGrantRecord;
  914. return $oGrantRecord;
  915. }
  916. public function IsStimulusAllowed($oUser, $sClass, $sStimulusCode, $oInstanceSet = null)
  917. {
  918. // Note: this code is VERY close to the code of IsActionAllowed()
  919. if (is_null($oInstanceSet))
  920. {
  921. $iInstancePermission = UR_ALLOWED_NO;
  922. foreach($this->GetMatchingProfiles($oUser, $sClass) as $iProfile)
  923. {
  924. $oGrantRecord = $this->GetClassStimulusGrant($iProfile, $sClass, $sStimulusCode);
  925. if (!is_null($oGrantRecord))
  926. {
  927. // no need to fetch the record, we've requested the records having permission = 'yes'
  928. $iInstancePermission = UR_ALLOWED_YES;
  929. }
  930. }
  931. return $iInstancePermission;
  932. }
  933. $oInstanceSet->Rewind();
  934. while($oObject = $oInstanceSet->Fetch())
  935. {
  936. $iInstancePermission = UR_ALLOWED_NO;
  937. foreach($this->GetMatchingProfiles($oUser, $sClass, $oObject) as $iProfile)
  938. {
  939. $oGrantRecord = $this->GetClassStimulusGrant($iProfile, $sClass, $sStimulusCode);
  940. if (!is_null($oGrantRecord))
  941. {
  942. // no need to fetch the record, we've requested the records having permission = 'yes'
  943. $iInstancePermission = UR_ALLOWED_YES;
  944. }
  945. }
  946. if (isset($iGlobalPermission))
  947. {
  948. if ($iInstancePermission != $iGlobalPermission)
  949. {
  950. $iGlobalPermission = UR_ALLOWED_DEPENDS;
  951. }
  952. }
  953. else
  954. {
  955. $iGlobalPermission = $iInstancePermission;
  956. }
  957. }
  958. $oInstanceSet->Rewind();
  959. if (isset($iGlobalPermission))
  960. {
  961. return $iGlobalPermission;
  962. }
  963. else
  964. {
  965. return UR_ALLOWED_NO;
  966. }
  967. }
  968. // Copied from GetMatchingProfilesByDim()
  969. // adapted to the optimized implementation of GetSelectFilter()
  970. // Note: shares the cache m_aProPros with GetMatchingProfilesByDim()
  971. // Returns null if any object is readable
  972. // an array of allowed projections otherwise (could be an empty array if none is allowed)
  973. protected function GetReadableProjectionsByDim($oUser, $sClass, $oDimension)
  974. {
  975. //
  976. // Given a dimension, lists the values for which the user will be allowed to read the objects
  977. //
  978. $iUser = $oUser->GetKey();
  979. $iDimension = $oDimension->GetKey();
  980. $aRes = array();
  981. if (array_key_exists($iUser, $this->m_aUserProfiles))
  982. {
  983. foreach ($this->m_aUserProfiles[$iUser] as $iProfile => $oProfile)
  984. {
  985. // user projection to be cached on a given page !
  986. if (!isset($this->m_aProPros[$iProfile][$iDimension]))
  987. {
  988. // No projection for a given profile: default to 'any'
  989. return null;
  990. }
  991. $aUserProjection = $this->m_aProPros[$iProfile][$iDimension]->ProjectUser($oUser);
  992. if (is_null($aUserProjection))
  993. {
  994. // No projection for a given profile: default to 'any'
  995. return null;
  996. }
  997. $aRes = array_unique(array_merge($aRes, $aUserProjection));
  998. }
  999. }
  1000. return $aRes;
  1001. }
  1002. // Note: shares the cache m_aProPros with GetReadableProjectionsByDim()
  1003. protected function GetMatchingProfilesByDim($oUser, $oObject, $oDimension)
  1004. {
  1005. //
  1006. // List profiles for which the user projection overlaps the object projection in the given dimension
  1007. //
  1008. $iUser = $oUser->GetKey();
  1009. $sClass = get_class($oObject);
  1010. $iPKey = $oObject->GetKey();
  1011. $iDimension = $oDimension->GetKey();
  1012. if (isset($this->m_aClassProjs[$sClass][$iDimension]))
  1013. {
  1014. $aObjectProjection = $this->m_aClassProjs[$sClass][$iDimension]->ProjectObject($oObject);
  1015. }
  1016. else
  1017. {
  1018. // No projection for a given class: default to 'any'
  1019. $aObjectProjection = null;
  1020. }
  1021. $aRes = array();
  1022. if (array_key_exists($iUser, $this->m_aUserProfiles))
  1023. {
  1024. foreach ($this->m_aUserProfiles[$iUser] as $iProfile => $oProfile)
  1025. {
  1026. if (is_null($aObjectProjection))
  1027. {
  1028. $aRes[] = $iProfile;
  1029. }
  1030. else
  1031. {
  1032. // user projection to be cached on a given page !
  1033. if (isset($this->m_aProPros[$iProfile][$iDimension]))
  1034. {
  1035. $aUserProjection = $this->m_aProPros[$iProfile][$iDimension]->ProjectUser($oUser);
  1036. }
  1037. else
  1038. {
  1039. // No projection for a given profile: default to 'any'
  1040. $aUserProjection = null;
  1041. }
  1042. if (is_null($aUserProjection))
  1043. {
  1044. $aRes[] = $iProfile;
  1045. }
  1046. else
  1047. {
  1048. $aMatchingValues = array_intersect($aObjectProjection, $aUserProjection);
  1049. if (count($aMatchingValues) > 0)
  1050. {
  1051. $aRes[] = $iProfile;
  1052. }
  1053. }
  1054. }
  1055. }
  1056. }
  1057. return $aRes;
  1058. }
  1059. protected $m_aMatchingProfiles = array(); // cache of the matching profiles for a given user/object
  1060. protected function GetMatchingProfiles($oUser, $sClass, /*DBObject*/ $oObject = null)
  1061. {
  1062. $iUser = $oUser->GetKey();
  1063. if(is_null($oObject))
  1064. {
  1065. $iObjectRef = -999;
  1066. }
  1067. else
  1068. {
  1069. $iObjectRef = $oObject->GetKey();
  1070. }
  1071. //
  1072. // List profiles for which the user projection overlaps the object projection in each and every dimension
  1073. // Caches the result
  1074. //
  1075. $aTest = @$this->m_aMatchingProfiles[$iUser][$sClass][$iObjectRef];
  1076. if (is_array($aTest))
  1077. {
  1078. return $aTest;
  1079. }
  1080. if (is_null($oObject))
  1081. {
  1082. if (array_key_exists($iUser, $this->m_aUserProfiles))
  1083. {
  1084. $aRes = array_keys($this->m_aUserProfiles[$iUser]);
  1085. }
  1086. else
  1087. {
  1088. // no profile has been defined for this user
  1089. $aRes = array();
  1090. }
  1091. }
  1092. else
  1093. {
  1094. $aProfileRes = array();
  1095. foreach ($this->m_aDimensions as $iDimension => $oDimension)
  1096. {
  1097. foreach ($this->GetMatchingProfilesByDim($oUser, $oObject, $oDimension) as $iProfile)
  1098. {
  1099. @$aProfileRes[$iProfile] += 1;
  1100. }
  1101. }
  1102. $aRes = array();
  1103. $iDimCount = count($this->m_aDimensions);
  1104. foreach ($aProfileRes as $iProfile => $iMatches)
  1105. {
  1106. if ($iMatches == $iDimCount)
  1107. {
  1108. $aRes[] = $iProfile;
  1109. }
  1110. }
  1111. }
  1112. // store into the cache
  1113. $this->m_aMatchingProfiles[$iUser][$sClass][$iObjectRef] = $aRes;
  1114. return $aRes;
  1115. }
  1116. public function FlushPrivileges()
  1117. {
  1118. $this->CacheData();
  1119. }
  1120. }
  1121. //
  1122. // Create simple profiles into our user management model:
  1123. // - administrator
  1124. // - readers
  1125. // - contributors
  1126. //
  1127. class SetupProfiles
  1128. {
  1129. protected static $m_aDimensions = array(
  1130. 'organization' => array(
  1131. 'description' => '',
  1132. 'type' => 'Organization',
  1133. ),
  1134. );
  1135. protected static $m_aActions = array(
  1136. UR_ACTION_READ => 'Read',
  1137. UR_ACTION_MODIFY => 'Modify',
  1138. UR_ACTION_DELETE => 'Delete',
  1139. UR_ACTION_BULK_READ => 'Bulk Read',
  1140. UR_ACTION_BULK_MODIFY => 'Bulk Modify',
  1141. UR_ACTION_BULK_DELETE => 'Bulk Delete',
  1142. );
  1143. // Note: It is possible to specify the same class in several modules
  1144. //
  1145. protected static $m_aModules = array();
  1146. protected static $m_aProfiles = array();
  1147. protected static function DoCreateClassProjection($iDimension, $sClass)
  1148. {
  1149. $oNewObj = MetaModel::NewObject("URP_ClassProjection");
  1150. $oNewObj->Set('dimensionid', $iDimension);
  1151. $oNewObj->Set('class', $sClass);
  1152. $oNewObj->Set('attribute', '');
  1153. $iId = $oNewObj->DBInsertNoReload();
  1154. return $iId;
  1155. }
  1156. protected static function DoCreateDimension($sName, $aDimensionData)
  1157. {
  1158. $oNewObj = MetaModel::NewObject("URP_Dimensions");
  1159. $oNewObj->Set('name', $sName);
  1160. $oNewObj->Set('description', $aDimensionData['description']);
  1161. $oNewObj->Set('type', $aDimensionData['type']);
  1162. $iId = $oNewObj->DBInsertNoReload();
  1163. return $iId;
  1164. }
  1165. protected static function DoCreateProfileProjection($iProfile, $iDimension)
  1166. {
  1167. $oNewObj = MetaModel::NewObject("URP_ProfileProjection");
  1168. $oNewObj->Set('profileid', $iProfile);
  1169. $oNewObj->Set('dimensionid', $iDimension);
  1170. $oNewObj->Set('value', '<any>');
  1171. $oNewObj->Set('attribute', '');
  1172. $iId = $oNewObj->DBInsertNoReload();
  1173. return $iId;
  1174. }
  1175. protected static function DoCreateActionGrant($iProfile, $iAction, $sClass, $bPermission = true)
  1176. {
  1177. $oNewObj = MetaModel::NewObject("URP_ActionGrant");
  1178. $oNewObj->Set('profileid', $iProfile);
  1179. $oNewObj->Set('permission', $bPermission ? 'yes' : 'no');
  1180. $oNewObj->Set('class', $sClass);
  1181. $oNewObj->Set('action', self::$m_aActions[$iAction]);
  1182. $iId = $oNewObj->DBInsertNoReload();
  1183. return $iId;
  1184. }
  1185. protected static function DoCreateStimulusGrant($iProfile, $sStimulusCode, $sClass)
  1186. {
  1187. $oNewObj = MetaModel::NewObject("URP_StimulusGrant");
  1188. $oNewObj->Set('profileid', $iProfile);
  1189. $oNewObj->Set('permission', 'yes');
  1190. $oNewObj->Set('class', $sClass);
  1191. $oNewObj->Set('stimulus', $sStimulusCode);
  1192. $iId = $oNewObj->DBInsertNoReload();
  1193. return $iId;
  1194. }
  1195. protected static function DoCreateAdminProfile()
  1196. {
  1197. $oNewObj = MetaModel::NewObject("URP_Profiles");
  1198. $oNewObj->Set('name', 'Administrator');
  1199. $oNewObj->Set('description', 'Has the rights on everything (bypassing any control)');
  1200. $iNewId = $oNewObj->DBInsertNoReload();
  1201. if ($iNewId != ADMIN_PROFILE_ID)
  1202. {
  1203. throw new CoreException('Admin profile could not be created with its standard id', array('requested'=>ADMIN_PROFILE_ID, 'obtained'=>$iNewId));
  1204. }
  1205. }
  1206. protected static function DoCreateOneProfile($sName, $aProfileData)
  1207. {
  1208. $sDescription = $aProfileData['description'];
  1209. if (strlen(trim($aProfileData['write_modules'])) == 0)
  1210. {
  1211. $aWriteModules = array();
  1212. }
  1213. else
  1214. {
  1215. $aWriteModules = explode(',', trim($aProfileData['write_modules']));
  1216. }
  1217. $aStimuli = $aProfileData['stimuli'];
  1218. $oNewObj = MetaModel::NewObject("URP_Profiles");
  1219. $oNewObj->Set('name', $sName);
  1220. $oNewObj->Set('description', $sDescription);
  1221. $iProfile = $oNewObj->DBInsertNoReload();
  1222. // Project in every dimension
  1223. //
  1224. $oDimensionSet = new DBObjectSet(DBObjectSearch::FromOQL_AllData("SELECT URP_Dimensions"));
  1225. while ($oDimension = $oDimensionSet->Fetch())
  1226. {
  1227. $iDimension = $oDimension->GetKey();
  1228. self::DoCreateProfileProjection($iProfile, $iDimension);
  1229. }
  1230. // Grant read rights for everything
  1231. //
  1232. foreach (MetaModel::GetClasses('bizmodel') as $sClass)
  1233. {
  1234. // Skip non instantiable classes
  1235. if (MetaModel::IsAbstract($sClass)) continue;
  1236. self::DoCreateActionGrant($iProfile, UR_ACTION_READ, $sClass);
  1237. self::DoCreateActionGrant($iProfile, UR_ACTION_BULK_READ, $sClass);
  1238. }
  1239. // Grant write for given modules
  1240. // Start by compiling the information, because some modules may overlap
  1241. $aWriteableClasses = array();
  1242. foreach ($aWriteModules as $sModule)
  1243. {
  1244. //$oPage->p('Granting write access for the module"'.$sModule.'" - '.count(self::$m_aModules[$sModule]).' classes');
  1245. foreach (self::$m_aModules[$sModule] as $sClass)
  1246. {
  1247. $aWriteableClasses[$sClass] = true;
  1248. }
  1249. }
  1250. foreach ($aWriteableClasses as $sClass => $foo)
  1251. {
  1252. // Skip non instantiable classes
  1253. if (MetaModel::IsAbstract($sClass)) continue;
  1254. if (!MetaModel::IsValidClass($sClass))
  1255. {
  1256. throw new CoreException("Invalid class name '$sClass'");
  1257. }
  1258. self::DoCreateActionGrant($iProfile, UR_ACTION_MODIFY, $sClass);
  1259. self::DoCreateActionGrant($iProfile, UR_ACTION_DELETE, $sClass);
  1260. self::DoCreateActionGrant($iProfile, UR_ACTION_BULK_MODIFY, $sClass);
  1261. // By default, do not allow bulk deletion operations for standard users
  1262. // self::DoCreateActionGrant($iProfile, UR_ACTION_BULK_DELETE, $sClass);
  1263. }
  1264. // Grant stimuli for given classes
  1265. foreach ($aStimuli as $sClass => $sAllowedStimuli)
  1266. {
  1267. if (!MetaModel::IsValidClass($sClass))
  1268. {
  1269. // Could be a class defined in a module that wasn't installed
  1270. continue;
  1271. //throw new CoreException("Invalid class name '$sClass'");
  1272. }
  1273. if ($sAllowedStimuli == 'any')
  1274. {
  1275. $aAllowedStimuli = array_keys(MetaModel::EnumStimuli($sClass));
  1276. }
  1277. elseif ($sAllowedStimuli == 'none')
  1278. {
  1279. $aAllowedStimuli = array();
  1280. }
  1281. else
  1282. {
  1283. $aAllowedStimuli = explode(',', $sAllowedStimuli);
  1284. }
  1285. foreach ($aAllowedStimuli as $sStimulusCode)
  1286. {
  1287. self::DoCreateStimulusGrant($iProfile, $sStimulusCode, $sClass);
  1288. }
  1289. }
  1290. }
  1291. public static function DoCreateDimensions()
  1292. {
  1293. $aClass = MetaModel::GetClasses();
  1294. foreach(self::$m_aDimensions as $sName => $aDimensionData)
  1295. {
  1296. $iDimension = self::DoCreateDimension($sName, $aDimensionData);
  1297. foreach($aClass as $sClass)
  1298. {
  1299. // Skip non instantiable classes
  1300. if (MetaModel::IsAbstract($sClass)) continue;
  1301. if (!MetaModel::IsValidClass($sClass))
  1302. {
  1303. throw new CoreException("Invalid class name '$sClass'");
  1304. }
  1305. self::DoCreateClassProjection($iDimension, $sClass);
  1306. }
  1307. }
  1308. }
  1309. public static function DoCreateProfiles()
  1310. {
  1311. self::DoCreateAdminProfile();
  1312. foreach(self::$m_aProfiles as $sName => $aProfileData)
  1313. {
  1314. self::DoCreateOneProfile($sName, $aProfileData);
  1315. }
  1316. }
  1317. public static function ComputeBasicProfiles()
  1318. {
  1319. // In this profiling scheme, one single module represents all the classes
  1320. //
  1321. self::$m_aModules = array(
  1322. 'UserData' => MetaModel::GetClasses('bizmodel'),
  1323. );
  1324. self::$m_aProfiles = array(
  1325. 'Reader' => array(
  1326. 'description' => 'Person having a ready-only access to the data',
  1327. 'write_modules' => '',
  1328. 'stimuli' => array(
  1329. ),
  1330. ),
  1331. 'Writer' => array(
  1332. 'description' => 'Contributor to the contents (read + write access)',
  1333. 'write_modules' => 'UserData',
  1334. 'stimuli' => array(
  1335. // any class => 'any'
  1336. ),
  1337. ),
  1338. );
  1339. }
  1340. public static function ComputeITILProfiles()
  1341. {
  1342. // In this profiling scheme, modules are based on ITIL recommendations
  1343. //
  1344. self::$m_aModules = array(
  1345. /*
  1346. 'WriteModule' => array(
  1347. 'someclass',
  1348. 'anotherclass',
  1349. ),
  1350. */
  1351. 'General' => MetaModel::GetClasses('structure'),
  1352. 'Documentation' => MetaModel::GetClasses('documentation'),
  1353. 'Configuration' => MetaModel::GetClasses('configmgmt'),
  1354. 'Incident' => MetaModel::GetClasses('incidentmgmt'),
  1355. 'Problem' => MetaModel::GetClasses('problemmgmt'),
  1356. 'Change' => MetaModel::GetClasses('changemgmt'),
  1357. 'Service' => MetaModel::GetClasses('servicemgmt'),
  1358. 'Call' => MetaModel::GetClasses('requestmgmt'),
  1359. 'KnownError' => MetaModel::GetClasses('knownerrormgmt'),
  1360. );
  1361. self::$m_aProfiles = array(
  1362. 'Configuration Manager' => array(
  1363. 'description' => 'Person in charge of the documentation of the managed CIs',
  1364. 'write_modules' => 'General,Documentation,Configuration',
  1365. 'stimuli' => array(
  1366. //'bizServer' => 'none',
  1367. //'bizContract' => 'none',
  1368. //'bizIncidentTicket' => 'none',
  1369. //'bizChangeTicket' => 'any',
  1370. ),
  1371. ),
  1372. 'Service Desk Agent' => array(
  1373. 'description' => 'Person in charge of creating incident reports',
  1374. 'write_modules' => 'Incident,Call',
  1375. 'stimuli' => array(
  1376. 'Incident' => 'ev_assign',
  1377. 'UserRequest' => 'ev_assign',
  1378. ),
  1379. ),
  1380. 'Support Agent' => array(
  1381. 'description' => 'Person analyzing and solving the current incidents or problems',
  1382. 'write_modules' => 'Incident,Problem,KnownError',
  1383. 'stimuli' => array(
  1384. 'Incident' => 'ev_assign,ev_reassign,ev_resolve,ev_close',
  1385. 'UserRequest' => 'ev_assign,ev_reassign,ev_resolve,ev_close,ev_freeze',
  1386. ),
  1387. ),
  1388. 'Change Implementor' => array(
  1389. 'description' => 'Person executing the changes',
  1390. 'write_modules' => 'Change',
  1391. 'stimuli' => array(
  1392. 'NormalChange' => 'ev_plan,ev_replan,ev_implement,ev_monitor',
  1393. 'EmergencyChange' => 'ev_plan,ev_replan,ev_implement,ev_monitor',
  1394. 'RoutineChange' => 'ev_plan,ev_replan,ev_implement,ev_monitor',
  1395. ),
  1396. ),
  1397. 'Change Supervisor' => array(
  1398. 'description' => 'Person responsible for the overall change execution',
  1399. 'write_modules' => 'Change',
  1400. 'stimuli' => array(
  1401. 'NormalChange' => 'ev_validate,ev_reject,ev_assign,ev_reopen,ev_finish',
  1402. 'EmergencyChange' => 'ev_assign,ev_reopen,ev_finish',
  1403. 'RoutineChange' => 'ev_assign,ev_reopen,ev_finish',
  1404. ),
  1405. ),
  1406. 'Change Approver' => array(
  1407. 'description' => 'Person who could be impacted by some changes',
  1408. 'write_modules' => 'Change',
  1409. 'stimuli' => array(
  1410. 'NormalChange' => 'ev_approve,ev_notapprove',
  1411. 'EmergencyChange' => 'ev_approve,ev_notapprove',
  1412. 'RoutineChange' => 'none',
  1413. ),
  1414. ),
  1415. 'Service Manager' => array(
  1416. 'description' => 'Person responsible for the service delivered to the [internal] customer',
  1417. 'write_modules' => 'Service',
  1418. 'stimuli' => array(
  1419. ),
  1420. ),
  1421. 'Document author' => array(
  1422. 'description' => 'Any person who could contribute to documentation',
  1423. 'write_modules' => 'Documentation',
  1424. 'stimuli' => array(
  1425. ),
  1426. ),
  1427. );
  1428. }
  1429. }
  1430. UserRights::SelectModule('UserRightsProjection');
  1431. ?>