userrights.class.inc.php 50 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674
  1. <?php
  2. // Copyright (C) 2010-2016 Combodo SARL
  3. //
  4. // This file is part of iTop.
  5. //
  6. // iTop is free software; you can redistribute it and/or modify
  7. // it under the terms of the GNU Affero General Public License as published by
  8. // the Free Software Foundation, either version 3 of the License, or
  9. // (at your option) any later version.
  10. //
  11. // iTop is distributed in the hope that it will be useful,
  12. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. // GNU Affero General Public License for more details.
  15. //
  16. // You should have received a copy of the GNU Affero General Public License
  17. // along with iTop. If not, see <http://www.gnu.org/licenses/>
  18. /**
  19. * User rights management API
  20. *
  21. * @copyright Copyright (C) 2010-2016 Combodo SARL
  22. * @license http://opensource.org/licenses/AGPL-3.0
  23. */
  24. class UserRightException extends CoreException
  25. {
  26. }
  27. define('UR_ALLOWED_NO', 0);
  28. define('UR_ALLOWED_YES', 1);
  29. define('UR_ALLOWED_DEPENDS', 2);
  30. define('UR_ACTION_READ', 1); // View an object
  31. define('UR_ACTION_MODIFY', 2); // Create/modify an object/attribute
  32. define('UR_ACTION_DELETE', 3); // Delete an object
  33. define('UR_ACTION_BULK_READ', 4); // Export multiple objects
  34. define('UR_ACTION_BULK_MODIFY', 5); // Create/modify multiple objects
  35. define('UR_ACTION_BULK_DELETE', 6); // Delete multiple objects
  36. define('UR_ACTION_CREATE', 7); // Instantiate an object
  37. define('UR_ACTION_APPLICATION_DEFINED', 10000); // Application specific actions (CSV import, View schema...)
  38. /**
  39. * User management module API
  40. *
  41. * @package iTopORM
  42. */
  43. abstract class UserRightsAddOnAPI
  44. {
  45. abstract public function CreateAdministrator($sAdminUser, $sAdminPwd, $sLanguage = 'EN US'); // could be used during initial installation
  46. abstract public function Init(); // loads data (possible optimizations)
  47. // Used to build select queries showing only objects visible for the given user
  48. abstract public function GetSelectFilter($sLogin, $sClass, $aSettings = array()); // returns a filter object
  49. abstract public function IsActionAllowed($oUser, $sClass, $iActionCode, /*dbObjectSet*/ $oInstanceSet = null);
  50. abstract public function IsStimulusAllowed($oUser, $sClass, $sStimulusCode, /*dbObjectSet*/ $oInstanceSet = null);
  51. abstract public function IsActionAllowedOnAttribute($oUser, $sClass, $sAttCode, $iActionCode, /*dbObjectSet*/ $oInstanceSet = null);
  52. abstract public function IsAdministrator($oUser);
  53. abstract public function IsPortalUser($oUser);
  54. abstract public function FlushPrivileges();
  55. /**
  56. * Default behavior for addons that do not support profiles
  57. *
  58. * @param $oUser User
  59. * @return array
  60. */
  61. public function ListProfiles($oUser)
  62. {
  63. return array();
  64. }
  65. /**
  66. * ...
  67. */
  68. public function MakeSelectFilter($sClass, $aAllowedOrgs, $aSettings = array(), $sAttCode = null)
  69. {
  70. if ($sAttCode == null)
  71. {
  72. $sAttCode = $this->GetOwnerOrganizationAttCode($sClass);
  73. }
  74. if (empty($sAttCode))
  75. {
  76. return $oFilter = new DBObjectSearch($sClass);
  77. }
  78. $oExpression = new FieldExpression($sAttCode, $sClass);
  79. $oFilter = new DBObjectSearch($sClass);
  80. $oListExpr = ListExpression::FromScalars($aAllowedOrgs);
  81. $oCondition = new BinaryExpression($oExpression, 'IN', $oListExpr);
  82. $oFilter->AddConditionExpression($oCondition);
  83. if ($this->HasSharing())
  84. {
  85. if (($sAttCode == 'id') && isset($aSettings['bSearchMode']) && $aSettings['bSearchMode'])
  86. {
  87. // Querying organizations (or derived)
  88. // and the expected list of organizations will be used as a search criteria
  89. // Therefore the query can also return organization having objects shared with the allowed organizations
  90. //
  91. // 1) build the list of organizations sharing something with the allowed organizations
  92. // Organization <== sharing_org_id == SharedObject having org_id IN {user orgs}
  93. $oShareSearch = new DBObjectSearch('SharedObject');
  94. $oOrgField = new FieldExpression('org_id', 'SharedObject');
  95. $oShareSearch->AddConditionExpression(new BinaryExpression($oOrgField, 'IN', $oListExpr));
  96. $oSearchSharers = new DBObjectSearch('Organization');
  97. $oSearchSharers->AllowAllData();
  98. $oSearchSharers->AddCondition_ReferencedBy($oShareSearch, 'sharing_org_id');
  99. $aSharers = array();
  100. foreach($oSearchSharers->ToDataArray(array('id')) as $aRow)
  101. {
  102. $aSharers[] = $aRow['id'];
  103. }
  104. // 2) Enlarge the overall results: ... OR id IN(id1, id2, id3)
  105. if (count($aSharers) > 0)
  106. {
  107. $oSharersList = ListExpression::FromScalars($aSharers);
  108. $oFilter->MergeConditionExpression(new BinaryExpression($oExpression, 'IN', $oSharersList));
  109. }
  110. }
  111. $aShareProperties = SharedObject::GetSharedClassProperties($sClass);
  112. if ($aShareProperties)
  113. {
  114. $sShareClass = $aShareProperties['share_class'];
  115. $sShareAttCode = $aShareProperties['attcode'];
  116. $oSearchShares = new DBObjectSearch($sShareClass);
  117. $oSearchShares->AllowAllData();
  118. $sHierarchicalKeyCode = MetaModel::IsHierarchicalClass('Organization');
  119. $oOrgField = new FieldExpression('org_id', $sShareClass);
  120. $oSearchShares->AddConditionExpression(new BinaryExpression($oOrgField, 'IN', $oListExpr));
  121. $aShared = array();
  122. foreach($oSearchShares->ToDataArray(array($sShareAttCode)) as $aRow)
  123. {
  124. $aShared[] = $aRow[$sShareAttCode];
  125. }
  126. if (count($aShared) > 0)
  127. {
  128. $oObjId = new FieldExpression('id', $sClass);
  129. $oSharedIdList = ListExpression::FromScalars($aShared);
  130. $oFilter->MergeConditionExpression(new BinaryExpression($oObjId, 'IN', $oSharedIdList));
  131. }
  132. }
  133. } // if HasSharing
  134. return $oFilter;
  135. }
  136. }
  137. abstract class User extends cmdbAbstractObject
  138. {
  139. public static function Init()
  140. {
  141. $aParams = array
  142. (
  143. "category" => "core",
  144. "key_type" => "autoincrement",
  145. "name_attcode" => "login",
  146. "state_attcode" => "",
  147. "reconc_keys" => array(),
  148. "db_table" => "priv_user",
  149. "db_key_field" => "id",
  150. "db_finalclass_field" => "",
  151. "display_template" => "",
  152. );
  153. MetaModel::Init_Params($aParams);
  154. //MetaModel::Init_InheritAttributes();
  155. MetaModel::Init_AddAttribute(new AttributeExternalKey("contactid", array("targetclass"=>"Person", "allowed_values"=>null, "sql"=>"contactid", "is_null_allowed"=>true, "on_target_delete"=>DEL_MANUAL, "depends_on"=>array())));
  156. MetaModel::Init_AddAttribute(new AttributeExternalField("last_name", array("allowed_values"=>null, "extkey_attcode"=> 'contactid', "target_attcode"=>"name")));
  157. MetaModel::Init_AddAttribute(new AttributeExternalField("first_name", array("allowed_values"=>null, "extkey_attcode"=> 'contactid', "target_attcode"=>"first_name")));
  158. MetaModel::Init_AddAttribute(new AttributeExternalField("email", array("allowed_values"=>null, "extkey_attcode"=> 'contactid', "target_attcode"=>"email")));
  159. MetaModel::Init_AddAttribute(new AttributeString("login", array("allowed_values"=>null, "sql"=>"login", "default_value"=>null, "is_null_allowed"=>false, "depends_on"=>array())));
  160. MetaModel::Init_AddAttribute(new AttributeApplicationLanguage("language", array("sql"=>"language", "default_value"=>"EN US", "is_null_allowed"=>false, "depends_on"=>array())));
  161. MetaModel::Init_AddAttribute(new AttributeEnum("status", array("allowed_values" => new ValueSetEnum('enabled,disabled'), "sql"=>"status", "default_value"=>"enabled", "is_null_allowed"=>false, "depends_on"=>array())));
  162. MetaModel::Init_AddAttribute(new AttributeLinkedSetIndirect("profile_list", array("linked_class"=>"URP_UserProfile", "ext_key_to_me"=>"userid", "ext_key_to_remote"=>"profileid", "allowed_values"=>null, "count_min"=>1, "count_max"=>0, "depends_on"=>array())));
  163. MetaModel::Init_AddAttribute(new AttributeLinkedSetIndirect("allowed_org_list", array("linked_class"=>"URP_UserOrg", "ext_key_to_me"=>"userid", "ext_key_to_remote"=>"allowed_org_id", "allowed_values"=>null, "count_min"=>1, "count_max"=>0, "depends_on"=>array())));
  164. // Display lists
  165. MetaModel::Init_SetZListItems('details', array('contactid', 'first_name', 'email', 'login', 'language', 'status', 'profile_list', 'allowed_org_list')); // Attributes to be displayed for the complete details
  166. MetaModel::Init_SetZListItems('list', array('finalclass', 'first_name', 'last_name', 'login', 'status')); // Attributes to be displayed for a list
  167. // Search criteria
  168. MetaModel::Init_SetZListItems('standard_search', array('login', 'contactid', 'status')); // Criteria of the std search form
  169. MetaModel::Init_SetZListItems('advanced_search', array('login', 'contactid')); // Criteria of the advanced search form
  170. }
  171. abstract public function CheckCredentials($sPassword);
  172. abstract public function TrustWebServerContext();
  173. abstract public function CanChangePassword();
  174. abstract public function ChangePassword($sOldPassword, $sNewPassword);
  175. /*
  176. * Compute a name in best effort mode
  177. */
  178. public function GetFriendlyName()
  179. {
  180. if (!MetaModel::IsValidAttCode(get_class($this), 'contactid'))
  181. {
  182. return $this->Get('login');
  183. }
  184. if ($this->Get('contactid') != 0)
  185. {
  186. $sFirstName = $this->Get('first_name');
  187. $sLastName = $this->Get('last_name');
  188. $sEmail = $this->Get('email');
  189. if (strlen($sFirstName) > 0)
  190. {
  191. return "$sFirstName $sLastName";
  192. }
  193. elseif (strlen($sEmail) > 0)
  194. {
  195. return "$sLastName <$sEmail>";
  196. }
  197. else
  198. {
  199. return $sLastName;
  200. }
  201. }
  202. return $this->Get('login');
  203. }
  204. protected $oContactObject;
  205. /**
  206. * Fetch and memoize the associated contact (if any)
  207. */
  208. public function GetContactObject()
  209. {
  210. if (is_null($this->oContactObject))
  211. {
  212. if ($this->Get('contactid') != 0)
  213. {
  214. $this->oContactObject = MetaModel::GetObject('Contact', $this->Get('contactid'));
  215. }
  216. }
  217. return $this->oContactObject;
  218. }
  219. /*
  220. * Overload the standard behavior
  221. */
  222. public function DoCheckToWrite()
  223. {
  224. parent::DoCheckToWrite();
  225. // Note: This MUST be factorized later: declare unique keys (set of columns) in the data model
  226. $aChanges = $this->ListChanges();
  227. if (array_key_exists('login', $aChanges))
  228. {
  229. if (strcasecmp($this->Get('login'), $this->GetOriginal('login')) !== 0)
  230. {
  231. $sNewLogin = $aChanges['login'];
  232. $oSearch = DBObjectSearch::FromOQL_AllData("SELECT User WHERE login = :newlogin");
  233. if (!$this->IsNew())
  234. {
  235. $oSearch->AddCondition('id', $this->GetKey(), '!=');
  236. }
  237. $oSet = new DBObjectSet($oSearch, array(), array('newlogin' => $sNewLogin));
  238. if ($oSet->Count() > 0)
  239. {
  240. $this->m_aCheckIssues[] = Dict::Format('Class:User/Error:LoginMustBeUnique', $sNewLogin);
  241. }
  242. }
  243. }
  244. // Check that this user has at least one profile assigned
  245. $oSet = $this->Get('profile_list');
  246. if ($oSet->Count() == 0)
  247. {
  248. $this->m_aCheckIssues[] = Dict::Format('Class:User/Error:AtLeastOneProfileIsNeeded');
  249. }
  250. }
  251. function GetGrantAsHtml($sClass, $iAction)
  252. {
  253. if (UserRights::IsActionAllowed($sClass, $iAction, null, $this))
  254. {
  255. return '<span style="background-color: #ddffdd;">'.Dict::S('UI:UserManagement:ActionAllowed:Yes').'</span>';
  256. }
  257. else
  258. {
  259. return '<span style="background-color: #ffdddd;">'.Dict::S('UI:UserManagement:ActionAllowed:No').'</span>';
  260. }
  261. }
  262. function DoShowGrantSumary($oPage, $sClassCategory)
  263. {
  264. if (UserRights::IsAdministrator($this))
  265. {
  266. // Looks dirty, but ok that's THE ONE
  267. $oPage->p(Dict::S('UI:UserManagement:AdminProfile+'));
  268. return;
  269. }
  270. $oKPI = new ExecutionKPI();
  271. $aDisplayData = array();
  272. foreach (MetaModel::GetClasses($sClassCategory) as $sClass)
  273. {
  274. $aClassStimuli = MetaModel::EnumStimuli($sClass);
  275. if (count($aClassStimuli) > 0)
  276. {
  277. $aStimuli = array();
  278. foreach ($aClassStimuli as $sStimulusCode => $oStimulus)
  279. {
  280. if (UserRights::IsStimulusAllowed($sClass, $sStimulusCode, null, $this))
  281. {
  282. $aStimuli[] = '<span title="'.$sStimulusCode.': '.htmlentities($oStimulus->GetDescription(), ENT_QUOTES, 'UTF-8').'">'.htmlentities($oStimulus->GetLabel(), ENT_QUOTES, 'UTF-8').'</span>';
  283. }
  284. }
  285. $sStimuli = implode(', ', $aStimuli);
  286. }
  287. else
  288. {
  289. $sStimuli = '<em title="'.Dict::S('UI:UserManagement:NoLifeCycleApplicable+').'">'.Dict::S('UI:UserManagement:NoLifeCycleApplicable').'</em>';
  290. }
  291. $aDisplayData[] = array(
  292. 'class' => MetaModel::GetName($sClass),
  293. 'read' => $this->GetGrantAsHtml($sClass, UR_ACTION_READ),
  294. 'bulkread' => $this->GetGrantAsHtml($sClass, UR_ACTION_BULK_READ),
  295. 'write' => $this->GetGrantAsHtml($sClass, UR_ACTION_MODIFY),
  296. 'bulkwrite' => $this->GetGrantAsHtml($sClass, UR_ACTION_BULK_MODIFY),
  297. 'stimuli' => $sStimuli,
  298. );
  299. }
  300. $oKPI->ComputeAndReport('Computation of user rights');
  301. $aDisplayConfig = array();
  302. $aDisplayConfig['class'] = array('label' => Dict::S('UI:UserManagement:Class'), 'description' => Dict::S('UI:UserManagement:Class+'));
  303. $aDisplayConfig['read'] = array('label' => Dict::S('UI:UserManagement:Action:Read'), 'description' => Dict::S('UI:UserManagement:Action:Read+'));
  304. $aDisplayConfig['bulkread'] = array('label' => Dict::S('UI:UserManagement:Action:BulkRead'), 'description' => Dict::S('UI:UserManagement:Action:BulkRead+'));
  305. $aDisplayConfig['write'] = array('label' => Dict::S('UI:UserManagement:Action:Modify'), 'description' => Dict::S('UI:UserManagement:Action:Modify+'));
  306. $aDisplayConfig['bulkwrite'] = array('label' => Dict::S('UI:UserManagement:Action:BulkModify'), 'description' => Dict::S('UI:UserManagement:Action:BulkModify+'));
  307. $aDisplayConfig['stimuli'] = array('label' => Dict::S('UI:UserManagement:Action:Stimuli'), 'description' => Dict::S('UI:UserManagement:Action:Stimuli+'));
  308. $oPage->table($aDisplayConfig, $aDisplayData);
  309. }
  310. function DisplayBareRelations(WebPage $oPage, $bEditMode = false)
  311. {
  312. parent::DisplayBareRelations($oPage, $bEditMode);
  313. if (!$bEditMode)
  314. {
  315. $oPage->SetCurrentTab(Dict::S('UI:UserManagement:GrantMatrix'));
  316. $this->DoShowGrantSumary($oPage, 'bizmodel');
  317. // debug
  318. if (false)
  319. {
  320. $oPage->SetCurrentTab('More on user rigths (dev only)');
  321. $oPage->add("<h3>User rights</h3>\n");
  322. $this->DoShowGrantSumary($oPage, 'addon/userrights');
  323. $oPage->add("<h3>Change log</h3>\n");
  324. $this->DoShowGrantSumary($oPage, 'core/cmdb');
  325. $oPage->add("<h3>Application</h3>\n");
  326. $this->DoShowGrantSumary($oPage, 'application');
  327. $oPage->add("<h3>GUI</h3>\n");
  328. $this->DoShowGrantSumary($oPage, 'gui');
  329. }
  330. }
  331. }
  332. public function CheckToDelete(&$oDeletionPlan)
  333. {
  334. if (MetaModel::GetConfig()->Get('demo_mode'))
  335. {
  336. // Users deletion is NOT allowed in demo mode
  337. $oDeletionPlan->AddToDelete($this, null);
  338. $oDeletionPlan->SetDeletionIssues($this, array('deletion not allowed in demo mode.'), true);
  339. $oDeletionPlan->ComputeResults();
  340. return false;
  341. }
  342. return parent::CheckToDelete($oDeletionPlan);
  343. }
  344. protected function DBDeleteSingleObject()
  345. {
  346. if (MetaModel::GetConfig()->Get('demo_mode'))
  347. {
  348. // Users deletion is NOT allowed in demo mode
  349. return;
  350. }
  351. parent::DBDeleteSingleObject();
  352. }
  353. }
  354. /**
  355. * Abstract class for all types of "internal" authentication i.e. users
  356. * for which the application is supplied a login and a password opposed
  357. * to "external" users for whom the authentication is performed outside
  358. * of the application (by the web server for example).
  359. * Note that "internal" users do not necessary correspond to a local authentication
  360. * they may be authenticated by a remote system, like in authent-ldap.
  361. */
  362. abstract class UserInternal extends User
  363. {
  364. // Nothing special, just a base class to categorize this type of authenticated users
  365. public static function Init()
  366. {
  367. $aParams = array
  368. (
  369. "category" => "core",
  370. "key_type" => "autoincrement",
  371. "name_attcode" => "login",
  372. "state_attcode" => "",
  373. "reconc_keys" => array('login'),
  374. "db_table" => "priv_internaluser",
  375. "db_key_field" => "id",
  376. "db_finalclass_field" => "",
  377. );
  378. MetaModel::Init_Params($aParams);
  379. MetaModel::Init_InheritAttributes();
  380. // When set, this token allows for password reset
  381. MetaModel::Init_AddAttribute(new AttributeOneWayPassword("reset_pwd_token", array("allowed_values"=>null, "default_value"=>null, "is_null_allowed"=>true, "depends_on"=>array())));
  382. // Display lists
  383. MetaModel::Init_SetZListItems('details', array('contactid', 'first_name', 'email', 'login', 'status', 'language', 'profile_list', 'allowed_org_list')); // Attributes to be displayed for the complete details
  384. MetaModel::Init_SetZListItems('list', array('finalclass', 'first_name', 'last_name', 'login', 'status')); // Attributes to be displayed for a list
  385. // Search criteria
  386. MetaModel::Init_SetZListItems('standard_search', array('login', 'contactid', 'status')); // Criteria of the std search form
  387. MetaModel::Init_SetZListItems('advanced_search', array('login', 'contactid')); // Criteria of the advanced search form
  388. }
  389. /**
  390. * Use with care!
  391. */
  392. public function SetPassword($sNewPassword)
  393. {
  394. }
  395. /**
  396. * The email recipient is the person who is allowed to regain control when the password gets lost
  397. * Throws an exception if the feature cannot be available
  398. */
  399. public function GetResetPasswordEmail()
  400. {
  401. if (!MetaModel::IsValidAttCode(get_class($this), 'contactid'))
  402. {
  403. throw new Exception(Dict::S('UI:ResetPwd-Error-NoContact'));
  404. }
  405. $iContactId = $this->Get('contactid');
  406. if ($iContactId == 0)
  407. {
  408. throw new Exception(Dict::S('UI:ResetPwd-Error-NoContact'));
  409. }
  410. $oContact = MetaModel::GetObject('Contact', $iContactId);
  411. // Determine the email attribute (the first one will be our choice)
  412. foreach (MetaModel::ListAttributeDefs(get_class($oContact)) as $sAttCode => $oAttDef)
  413. {
  414. if ($oAttDef instanceof AttributeEmailAddress)
  415. {
  416. $sEmailAttCode = $sAttCode;
  417. // we've got one, exit the loop
  418. break;
  419. }
  420. }
  421. if (!isset($sEmailAttCode))
  422. {
  423. throw new Exception(Dict::S('UI:ResetPwd-Error-NoEmailAtt'));
  424. }
  425. $sRes = trim($oContact->Get($sEmailAttCode));
  426. return $sRes;
  427. }
  428. }
  429. /**
  430. * Self register extension
  431. *
  432. * @package iTopORM
  433. */
  434. interface iSelfRegister
  435. {
  436. /**
  437. * Called when no user is found in iTop for the corresponding 'name'. This method
  438. * can create/synchronize the User in iTop with an external source (such as AD/LDAP) on the fly
  439. * @param string $sName The typed-in user name
  440. * @param string $sPassword The typed-in password
  441. * @param string $sLoginMode The login method used (cas|form|basic|url)
  442. * @param string $sAuthentication The authentication method used (any|internal|external)
  443. * @return bool true if the user is a valid one, false otherwise
  444. */
  445. public static function CheckCredentialsAndCreateUser($sName, $sPassword, $sLoginMode, $sAuthentication);
  446. /**
  447. * Called after the user has been authenticated and found in iTop. This method can
  448. * Update the user's definition on the fly (profiles...) to keep it in sync with an external source
  449. * @param User $oUser The user to update/synchronize
  450. * @param string $sLoginMode The login mode used (cas|form|basic|url)
  451. * @param string $sAuthentication The authentication method used
  452. * @return void
  453. */
  454. public static function UpdateUser(User $oUser, $sLoginMode, $sAuthentication);
  455. }
  456. /**
  457. * User management core API
  458. *
  459. * @package iTopORM
  460. */
  461. class UserRights
  462. {
  463. protected static $m_oAddOn;
  464. protected static $m_oUser;
  465. protected static $m_oRealUser;
  466. protected static $m_sSelfRegisterAddOn = null;
  467. public static function SelectModule($sModuleName)
  468. {
  469. if (!class_exists($sModuleName))
  470. {
  471. throw new CoreException("Could not select this module, '$sModuleName' in not a valid class name");
  472. return;
  473. }
  474. if (!is_subclass_of($sModuleName, 'UserRightsAddOnAPI'))
  475. {
  476. throw new CoreException("Could not select this module, the class '$sModuleName' is not derived from UserRightsAddOnAPI");
  477. return;
  478. }
  479. self::$m_oAddOn = new $sModuleName;
  480. self::$m_oAddOn->Init();
  481. self::$m_oUser = null;
  482. self::$m_oRealUser = null;
  483. }
  484. public static function SelectSelfRegister($sModuleName)
  485. {
  486. if (!class_exists($sModuleName))
  487. {
  488. throw new CoreException("Could not select the class, '$sModuleName' for self register, is not a valid class name");
  489. }
  490. self::$m_sSelfRegisterAddOn = $sModuleName;
  491. }
  492. public static function GetModuleInstance()
  493. {
  494. return self::$m_oAddOn;
  495. }
  496. // Installation: create the very first user
  497. public static function CreateAdministrator($sAdminUser, $sAdminPwd, $sLanguage = 'EN US')
  498. {
  499. $bRes = self::$m_oAddOn->CreateAdministrator($sAdminUser, $sAdminPwd, $sLanguage);
  500. self::FlushPrivileges(true /* reset admin cache */);
  501. return $bRes;
  502. }
  503. protected static function IsLoggedIn()
  504. {
  505. if (self::$m_oUser == null)
  506. {
  507. return false;
  508. }
  509. else
  510. {
  511. return true;
  512. }
  513. }
  514. public static function Login($sName, $sAuthentication = 'any')
  515. {
  516. $oUser = self::FindUser($sName, $sAuthentication);
  517. if (is_null($oUser))
  518. {
  519. return false;
  520. }
  521. self::$m_oUser = $oUser;
  522. Dict::SetUserLanguage(self::GetUserLanguage());
  523. return true;
  524. }
  525. public static function CheckCredentials($sName, $sPassword, $sLoginMode = 'form', $sAuthentication = 'any')
  526. {
  527. $oUser = self::FindUser($sName, $sAuthentication);
  528. if (is_null($oUser))
  529. {
  530. // Check if the user does not exist at all or if it is just disabled
  531. if (self::FindUser($sName, $sAuthentication, true) == null)
  532. {
  533. // User does not exist at all
  534. return self::CheckCredentialsAndCreateUser($sName, $sPassword, $sLoginMode, $sAuthentication);
  535. }
  536. else
  537. {
  538. // User is actually disabled
  539. return false;
  540. }
  541. }
  542. if (!$oUser->CheckCredentials($sPassword))
  543. {
  544. return false;
  545. }
  546. self::UpdateUser($oUser, $sLoginMode, $sAuthentication);
  547. return true;
  548. }
  549. public static function CheckCredentialsAndCreateUser($sName, $sPassword, $sLoginMode, $sAuthentication)
  550. {
  551. if (self::$m_sSelfRegisterAddOn != null)
  552. {
  553. return call_user_func(array(self::$m_sSelfRegisterAddOn, 'CheckCredentialsAndCreateUser'), $sName, $sPassword, $sLoginMode, $sAuthentication);
  554. }
  555. }
  556. public static function UpdateUser($oUser, $sLoginMode, $sAuthentication)
  557. {
  558. if (self::$m_sSelfRegisterAddOn != null)
  559. {
  560. call_user_func(array(self::$m_sSelfRegisterAddOn, 'UpdateUser'), $oUser, $sLoginMode, $sAuthentication);
  561. }
  562. }
  563. public static function TrustWebServerContext()
  564. {
  565. if (!is_null(self::$m_oUser))
  566. {
  567. return self::$m_oUser->TrustWebServerContext();
  568. }
  569. else
  570. {
  571. return false;
  572. }
  573. }
  574. public static function CanChangePassword()
  575. {
  576. if (MetaModel::DBIsReadOnly())
  577. {
  578. return false;
  579. }
  580. if (!is_null(self::$m_oUser))
  581. {
  582. return self::$m_oUser->CanChangePassword();
  583. }
  584. else
  585. {
  586. return false;
  587. }
  588. }
  589. public static function ChangePassword($sOldPassword, $sNewPassword, $sName = '')
  590. {
  591. if (empty($sName))
  592. {
  593. $oUser = self::$m_oUser;
  594. }
  595. else
  596. {
  597. // find the id out of the login string
  598. $oUser = self::FindUser($sName);
  599. }
  600. if (is_null($oUser))
  601. {
  602. return false;
  603. }
  604. else
  605. {
  606. return $oUser->ChangePassword($sOldPassword, $sNewPassword);
  607. }
  608. }
  609. public static function Impersonate($sName, $sPassword)
  610. {
  611. if (!self::CheckLogin()) return false;
  612. $oUser = self::FindUser($sName);
  613. if (is_null($oUser))
  614. {
  615. return false;
  616. }
  617. if (!$oUser->CheckCredentials($sPassword))
  618. {
  619. return false;
  620. }
  621. self::$m_oRealUser = self::$m_oUser;
  622. self::$m_oUser = $oUser;
  623. Dict::SetUserLanguage(self::GetUserLanguage());
  624. return true;
  625. }
  626. public static function GetUser()
  627. {
  628. if (is_null(self::$m_oUser))
  629. {
  630. return '';
  631. }
  632. else
  633. {
  634. return self::$m_oUser->Get('login');
  635. }
  636. }
  637. public static function GetUserObject()
  638. {
  639. if (is_null(self::$m_oUser))
  640. {
  641. return null;
  642. }
  643. else
  644. {
  645. return self::$m_oUser;
  646. }
  647. }
  648. public static function GetUserLanguage()
  649. {
  650. if (is_null(self::$m_oUser))
  651. {
  652. return 'EN US';
  653. }
  654. else
  655. {
  656. return self::$m_oUser->Get('language');
  657. }
  658. }
  659. public static function GetUserId($sName = '')
  660. {
  661. if (empty($sName))
  662. {
  663. // return current user id
  664. if (is_null(self::$m_oUser))
  665. {
  666. return null;
  667. }
  668. return self::$m_oUser->GetKey();
  669. }
  670. else
  671. {
  672. // find the id out of the login string
  673. $oUser = self::$m_oAddOn->FindUser($sName);
  674. if (is_null($oUser))
  675. {
  676. return null;
  677. }
  678. return $oUser->GetKey();
  679. }
  680. }
  681. public static function GetContactId($sName = '')
  682. {
  683. if (empty($sName))
  684. {
  685. $oUser = self::$m_oUser;
  686. }
  687. else
  688. {
  689. $oUser = FindUser($sName);
  690. }
  691. if (is_null($oUser))
  692. {
  693. return '';
  694. }
  695. if (!MetaModel::IsValidAttCode(get_class($oUser), 'contactid'))
  696. {
  697. return '';
  698. }
  699. return $oUser->Get('contactid');
  700. }
  701. public static function GetContactObject()
  702. {
  703. if (is_null(self::$m_oUser))
  704. {
  705. return null;
  706. }
  707. else
  708. {
  709. return self::$m_oUser->GetContactObject();
  710. }
  711. }
  712. // Render the user name in best effort mode
  713. public static function GetUserFriendlyName($sName = '')
  714. {
  715. if (empty($sName))
  716. {
  717. $oUser = self::$m_oUser;
  718. }
  719. else
  720. {
  721. $oUser = FindUser($sName);
  722. }
  723. if (is_null($oUser))
  724. {
  725. return '';
  726. }
  727. return $oUser->GetFriendlyName();
  728. }
  729. public static function IsImpersonated()
  730. {
  731. if (is_null(self::$m_oRealUser))
  732. {
  733. return false;
  734. }
  735. return true;
  736. }
  737. public static function GetRealUser()
  738. {
  739. if (is_null(self::$m_oRealUser))
  740. {
  741. return '';
  742. }
  743. return self::$m_oRealUser->Get('login');
  744. }
  745. public static function GetRealUserId()
  746. {
  747. if (is_null(self::$m_oRealUser))
  748. {
  749. return '';
  750. }
  751. return self::$m_oRealUser->GetKey();
  752. }
  753. public static function GetRealUserFriendlyName()
  754. {
  755. if (is_null(self::$m_oRealUser))
  756. {
  757. return '';
  758. }
  759. return self::$m_oRealUser->GetFriendlyName();
  760. }
  761. protected static function CheckLogin()
  762. {
  763. if (!self::IsLoggedIn())
  764. {
  765. //throw new UserRightException('No user logged in', array());
  766. return false;
  767. }
  768. return true;
  769. }
  770. public static function GetSelectFilter($sClass, $aSettings = array())
  771. {
  772. // When initializing, we need to let everything pass trough
  773. if (!self::CheckLogin()) return true;
  774. if (self::IsAdministrator()) return true;
  775. if (MetaModel::HasCategory($sClass, 'bizmodel'))
  776. {
  777. return self::$m_oAddOn->GetSelectFilter(self::$m_oUser, $sClass, $aSettings);
  778. }
  779. else
  780. {
  781. return true;
  782. }
  783. }
  784. public static function IsActionAllowed($sClass, $iActionCode, /*dbObjectSet*/ $oInstanceSet = null, $oUser = null)
  785. {
  786. // When initializing, we need to let everything pass trough
  787. if (!self::CheckLogin()) return true;
  788. if (MetaModel::DBIsReadOnly())
  789. {
  790. if ($iActionCode == UR_ACTION_CREATE) return false;
  791. if ($iActionCode == UR_ACTION_MODIFY) return false;
  792. if ($iActionCode == UR_ACTION_BULK_MODIFY) return false;
  793. if ($iActionCode == UR_ACTION_DELETE) return false;
  794. if ($iActionCode == UR_ACTION_BULK_DELETE) return false;
  795. }
  796. $aPredefinedObjects = call_user_func(array($sClass, 'GetPredefinedObjects'));
  797. if ($aPredefinedObjects != null)
  798. {
  799. // As opposed to the read-only DB, modifying an object is allowed
  800. // (the constant columns will be marked as read-only)
  801. //
  802. if ($iActionCode == UR_ACTION_CREATE) return false;
  803. if ($iActionCode == UR_ACTION_DELETE) return false;
  804. if ($iActionCode == UR_ACTION_BULK_DELETE) return false;
  805. }
  806. if (self::IsAdministrator($oUser)) return true;
  807. if (MetaModel::HasCategory($sClass, 'bizmodel'))
  808. {
  809. if (is_null($oUser))
  810. {
  811. $oUser = self::$m_oUser;
  812. }
  813. if ($iActionCode == UR_ACTION_CREATE)
  814. {
  815. // The addons currently DO NOT handle the case "CREATE"
  816. // Therefore it is considered to be equivalent to "MODIFY"
  817. $iActionCode = UR_ACTION_MODIFY;
  818. }
  819. return self::$m_oAddOn->IsActionAllowed($oUser, $sClass, $iActionCode, $oInstanceSet);
  820. }
  821. elseif(($iActionCode == UR_ACTION_READ) && MetaModel::HasCategory($sClass, 'view_in_gui'))
  822. {
  823. return true;
  824. }
  825. else
  826. {
  827. // Other classes could be edited/listed by the administrators
  828. return false;
  829. }
  830. }
  831. public static function IsStimulusAllowed($sClass, $sStimulusCode, /*dbObjectSet*/ $oInstanceSet = null, $oUser = null)
  832. {
  833. // When initializing, we need to let everything pass trough
  834. if (!self::CheckLogin()) return true;
  835. if (MetaModel::DBIsReadOnly())
  836. {
  837. return false;
  838. }
  839. if (self::IsAdministrator($oUser)) return true;
  840. if (MetaModel::HasCategory($sClass, 'bizmodel'))
  841. {
  842. if (is_null($oUser))
  843. {
  844. $oUser = self::$m_oUser;
  845. }
  846. return self::$m_oAddOn->IsStimulusAllowed($oUser, $sClass, $sStimulusCode, $oInstanceSet);
  847. }
  848. else
  849. {
  850. // Other classes could be edited/listed by the administrators
  851. return false;
  852. }
  853. }
  854. public static function IsActionAllowedOnAttribute($sClass, $sAttCode, $iActionCode, /*dbObjectSet*/ $oInstanceSet = null, $oUser = null)
  855. {
  856. // When initializing, we need to let everything pass trough
  857. if (!self::CheckLogin()) return true;
  858. if (MetaModel::DBIsReadOnly())
  859. {
  860. if ($iActionCode == UR_ACTION_MODIFY) return false;
  861. if ($iActionCode == UR_ACTION_DELETE) return false;
  862. if ($iActionCode == UR_ACTION_BULK_MODIFY) return false;
  863. if ($iActionCode == UR_ACTION_BULK_DELETE) return false;
  864. }
  865. if (self::IsAdministrator($oUser)) return true;
  866. // this module is forbidden for non admins
  867. if (MetaModel::HasCategory($sClass, 'addon/userrights')) return false;
  868. // the rest is allowed (#@# to be improved)
  869. if (!MetaModel::HasCategory($sClass, 'bizmodel')) return true;
  870. if (is_null($oUser))
  871. {
  872. $oUser = self::$m_oUser;
  873. }
  874. return self::$m_oAddOn->IsActionAllowedOnAttribute($oUser, $sClass, $sAttCode, $iActionCode, $oInstanceSet);
  875. }
  876. protected static $m_aAdmins = array();
  877. public static function IsAdministrator($oUser = null)
  878. {
  879. if (!self::CheckLogin()) return false;
  880. if (is_null($oUser))
  881. {
  882. $oUser = self::$m_oUser;
  883. }
  884. $iUser = $oUser->GetKey();
  885. if (!isset(self::$m_aAdmins[$iUser]))
  886. {
  887. self::$m_aAdmins[$iUser] = self::$m_oAddOn->IsAdministrator($oUser);
  888. }
  889. return self::$m_aAdmins[$iUser];
  890. }
  891. protected static $m_aPortalUsers = array();
  892. public static function IsPortalUser($oUser = null)
  893. {
  894. if (!self::CheckLogin()) return false;
  895. if (is_null($oUser))
  896. {
  897. $oUser = self::$m_oUser;
  898. }
  899. $iUser = $oUser->GetKey();
  900. if (!isset(self::$m_aPortalUsers[$iUser]))
  901. {
  902. self::$m_aPortalUsers[$iUser] = self::$m_oAddOn->IsPortalUser($oUser);
  903. }
  904. return self::$m_aPortalUsers[$iUser];
  905. }
  906. public static function GetAllowedPortals()
  907. {
  908. $aAllowedPortals = array();
  909. $aPortalsConf = PortalDispatcherData::GetData();
  910. $aDispatchers = array();
  911. foreach ($aPortalsConf as $sPortalId => $aConf)
  912. {
  913. $sHandlerClass = $aConf['handler'];
  914. $aDispatchers[$sPortalId] = new $sHandlerClass($sPortalId);
  915. }
  916. foreach ($aDispatchers as $sPortalId => $oDispatcher)
  917. {
  918. if ($oDispatcher->IsUserAllowed())
  919. {
  920. $aAllowedPortals[] = array(
  921. 'id' => $sPortalId,
  922. 'label' => $oDispatcher->GetLabel(),
  923. 'url' => $oDispatcher->GetUrl(),
  924. );
  925. }
  926. }
  927. return $aAllowedPortals;
  928. }
  929. public static function ListProfiles($oUser = null)
  930. {
  931. if (is_null($oUser))
  932. {
  933. $oUser = self::$m_oUser;
  934. }
  935. if ($oUser->GetKey() == self::$m_oUser->GetKey())
  936. {
  937. // Data about the current user can be found into the session data
  938. if (array_key_exists('profile_list', $_SESSION))
  939. {
  940. $aProfiles = $_SESSION['profile_list'];
  941. }
  942. }
  943. if (!isset($aProfiles))
  944. {
  945. $aProfiles = self::$m_oAddOn->ListProfiles($oUser);
  946. }
  947. return $aProfiles;
  948. }
  949. /**
  950. * @param $sProfileName Profile name to search for
  951. * @param $oUser User|null
  952. * @return bool
  953. */
  954. public static function HasProfile($sProfileName, $oUser = null)
  955. {
  956. $bRet = in_array($sProfileName, self::ListProfiles($oUser));
  957. return $bRet;
  958. }
  959. /**
  960. * Reset cached data
  961. * @param Bool Reset admin cache as well
  962. * @return void
  963. */
  964. // Reset cached data
  965. //
  966. public static function FlushPrivileges($bResetAdminCache = false)
  967. {
  968. if ($bResetAdminCache)
  969. {
  970. self::$m_aAdmins = array();
  971. self::$m_aPortalUsers = array();
  972. }
  973. self::_ResetSessionCache();
  974. return self::$m_oAddOn->FlushPrivileges();
  975. }
  976. static $m_aCacheUsers;
  977. /**
  978. * Find a user based on its login and its type of authentication
  979. * @param string $sLogin Login/identifier of the user
  980. * @param string $sAuthentication Type of authentication used: internal|external|any
  981. * @param bool $bAllowDisabledUsers Whether or not to retrieve disabled users (status != enabled)
  982. * @return User The found user or null
  983. */
  984. protected static function FindUser($sLogin, $sAuthentication = 'any', $bAllowDisabledUsers = false)
  985. {
  986. if ($sAuthentication == 'any')
  987. {
  988. $oUser = self::FindUser($sLogin, 'internal');
  989. if ($oUser == null)
  990. {
  991. $oUser = self::FindUser($sLogin, 'external');
  992. }
  993. }
  994. else
  995. {
  996. if (!isset(self::$m_aCacheUsers))
  997. {
  998. self::$m_aCacheUsers = array('internal' => array(), 'external' => array());
  999. }
  1000. if (!isset(self::$m_aCacheUsers[$sAuthentication][$sLogin]))
  1001. {
  1002. switch($sAuthentication)
  1003. {
  1004. case 'external':
  1005. $sBaseClass = 'UserExternal';
  1006. break;
  1007. case 'internal':
  1008. $sBaseClass = 'UserInternal';
  1009. break;
  1010. default:
  1011. echo "<p>sAuthentication = $sAuthentication</p>\n";
  1012. assert(false); // should never happen
  1013. }
  1014. $oSearch = DBObjectSearch::FromOQL("SELECT $sBaseClass WHERE login = :login");
  1015. if (!$bAllowDisabledUsers)
  1016. {
  1017. $oSearch->AddCondition('status', 'enabled');
  1018. }
  1019. $oSet = new DBObjectSet($oSearch, array(), array('login' => $sLogin));
  1020. $oUser = $oSet->fetch();
  1021. self::$m_aCacheUsers[$sAuthentication][$sLogin] = $oUser;
  1022. }
  1023. $oUser = self::$m_aCacheUsers[$sAuthentication][$sLogin];
  1024. }
  1025. return $oUser;
  1026. }
  1027. public static function MakeSelectFilter($sClass, $aAllowedOrgs, $aSettings = array(), $sAttCode = null)
  1028. {
  1029. return self::$m_oAddOn->MakeSelectFilter($sClass, $aAllowedOrgs, $aSettings, $sAttCode);
  1030. }
  1031. public static function _InitSessionCache()
  1032. {
  1033. // Cache data about the current user into the session
  1034. if (isset($_SESSION))
  1035. {
  1036. $_SESSION['profile_list'] = self::ListProfiles();
  1037. }
  1038. }
  1039. public static function _ResetSessionCache()
  1040. {
  1041. if (isset($_SESSION['profile_list']))
  1042. {
  1043. unset($_SESSION['profile_list']);
  1044. }
  1045. }
  1046. }
  1047. /**
  1048. * Helper class to get the number/list of items for which a given action is allowed/possible
  1049. */
  1050. class ActionChecker
  1051. {
  1052. var $oFilter;
  1053. var $iActionCode;
  1054. var $iAllowedCount = null;
  1055. var $aAllowedIDs = null;
  1056. public function __construct(DBSearch $oFilter, $iActionCode)
  1057. {
  1058. $this->oFilter = $oFilter;
  1059. $this->iActionCode = $iActionCode;
  1060. $this->iAllowedCount = null;
  1061. $this->aAllowedIDs = null;
  1062. }
  1063. /**
  1064. * returns the number of objects for which the action is allowed
  1065. * @return integer The number of "allowed" objects 0..N
  1066. */
  1067. public function GetAllowedCount()
  1068. {
  1069. if ($this->iAllowedCount == null) $this->CheckObjects();
  1070. return $this->iAllowedCount;
  1071. }
  1072. /**
  1073. * If IsAllowed returned UR_ALLOWED_DEPENDS, this methods returns
  1074. * an array of ObjKey => Status (true|false)
  1075. * @return array
  1076. */
  1077. public function GetAllowedIDs()
  1078. {
  1079. if ($this->aAllowedIDs == null) $this->IsAllowed();
  1080. return $this->aAllowedIDs;
  1081. }
  1082. /**
  1083. * Check if the speficied stimulus is allowed for the set of objects
  1084. * @return UR_ALLOWED_YES, UR_ALLOWED_NO or UR_ALLOWED_DEPENDS
  1085. */
  1086. public function IsAllowed()
  1087. {
  1088. $sClass = $this->oFilter->GetClass();
  1089. $oSet = new DBObjectSet($this->oFilter);
  1090. $iActionAllowed = UserRights::IsActionAllowed($sClass, $this->iActionCode, $oSet);
  1091. if ($iActionAllowed == UR_ALLOWED_DEPENDS)
  1092. {
  1093. // Check for each object if the action is allowed or not
  1094. $this->aAllowedIDs = array();
  1095. $oSet->Rewind();
  1096. $this->iAllowedCount = 0;
  1097. while($oObj = $oSet->Fetch())
  1098. {
  1099. $oObjSet = DBObjectSet::FromArray($sClass, array($oObj));
  1100. if (UserRights::IsActionAllowed($sClass, $this->iActionCode, $oObjSet) == UR_ALLOWED_NO)
  1101. {
  1102. $this->aAllowedIDs[$oObj->GetKey()] = false;
  1103. }
  1104. else
  1105. {
  1106. // Assume UR_ALLOWED_YES, since there is just one object !
  1107. $this->aAllowedIDs[$oObj->GetKey()] = true;
  1108. $this->iAllowedCount++;
  1109. }
  1110. }
  1111. }
  1112. else if ($iActionAllowed == UR_ALLOWED_YES)
  1113. {
  1114. $this->iAllowedCount = $oSet->Count();
  1115. $this->aAllowedIDs = array(); // Optimization: not filled when Ok for all objects
  1116. }
  1117. else // UR_ALLOWED_NO
  1118. {
  1119. $this->iAllowedCount = 0;
  1120. $this->aAllowedIDs = array();
  1121. }
  1122. return $iActionAllowed;
  1123. }
  1124. }
  1125. /**
  1126. * Helper class to get the number/list of items for which a given stimulus can be applied (allowed & possible)
  1127. */
  1128. class StimulusChecker extends ActionChecker
  1129. {
  1130. var $sState = null;
  1131. public function __construct(DBSearch $oFilter, $sState, $iStimulusCode)
  1132. {
  1133. parent::__construct($oFilter, $iStimulusCode);
  1134. $this->sState = $sState;
  1135. }
  1136. /**
  1137. * Check if the speficied stimulus is allowed for the set of objects
  1138. * @return UR_ALLOWED_YES, UR_ALLOWED_NO or UR_ALLOWED_DEPENDS
  1139. */
  1140. public function IsAllowed()
  1141. {
  1142. $sClass = $this->oFilter->GetClass();
  1143. if (MetaModel::IsAbstract($sClass)) return UR_ALLOWED_NO; // Safeguard, not implemented if the base class of the set is abstract !
  1144. $oSet = new DBObjectSet($this->oFilter);
  1145. $iActionAllowed = UserRights::IsStimulusAllowed($sClass, $this->iActionCode, $oSet);
  1146. if ($iActionAllowed == UR_ALLOWED_NO)
  1147. {
  1148. $this->iAllowedCount = 0;
  1149. $this->aAllowedIDs = array();
  1150. }
  1151. else // Even if UR_ALLOWED_YES, we need to check if each object is in the appropriate state
  1152. {
  1153. // Hmmm, may not be needed right now because we limit the "multiple" action to object in
  1154. // the same state... may be useful later on if we want to extend this behavior...
  1155. // Check for each object if the action is allowed or not
  1156. $this->aAllowedIDs = array();
  1157. $oSet->Rewind();
  1158. $iAllowedCount = 0;
  1159. $iActionAllowed = UR_ALLOWED_DEPENDS;
  1160. while($oObj = $oSet->Fetch())
  1161. {
  1162. $aTransitions = $oObj->EnumTransitions();
  1163. if (array_key_exists($this->iActionCode, $aTransitions))
  1164. {
  1165. // Temporary optimization possible: since the current implementation
  1166. // of IsActionAllowed does not perform a 'per instance' check, we could
  1167. // skip this second validation phase and assume it would return UR_ALLOWED_YES
  1168. $oObjSet = DBObjectSet::FromArray($sClass, array($oObj));
  1169. if (!UserRights::IsStimulusAllowed($sClass, $this->iActionCode, $oObjSet))
  1170. {
  1171. $this->aAllowedIDs[$oObj->GetKey()] = false;
  1172. }
  1173. else
  1174. {
  1175. // Assume UR_ALLOWED_YES, since there is just one object !
  1176. $this->aAllowedIDs[$oObj->GetKey()] = true;
  1177. $this->iState = $oObj->GetState();
  1178. $this->iAllowedCount++;
  1179. }
  1180. }
  1181. else
  1182. {
  1183. $this->aAllowedIDs[$oObj->GetKey()] = false;
  1184. }
  1185. }
  1186. }
  1187. if ($this->iAllowedCount == $oSet->Count())
  1188. {
  1189. $iActionAllowed = UR_ALLOWED_YES;
  1190. }
  1191. if ($this->iAllowedCount == 0)
  1192. {
  1193. $iActionAllowed = UR_ALLOWED_NO;
  1194. }
  1195. return $iActionAllowed;
  1196. }
  1197. public function GetState()
  1198. {
  1199. return $this->iState;
  1200. }
  1201. }
  1202. /**
  1203. * Self-register extension to allow the automatic creation & update of CAS users
  1204. *
  1205. * @package iTopORM
  1206. *
  1207. */
  1208. class CAS_SelfRegister implements iSelfRegister
  1209. {
  1210. /**
  1211. * Called when no user is found in iTop for the corresponding 'name'. This method
  1212. * can create/synchronize the User in iTop with an external source (such as AD/LDAP) on the fly
  1213. * @param string $sName The CAS authenticated user name
  1214. * @param string $sPassword Ignored
  1215. * @param string $sLoginMode The login mode used (cas|form|basic|url)
  1216. * @param string $sAuthentication The authentication method used
  1217. * @return bool true if the user is a valid one, false otherwise
  1218. */
  1219. public static function CheckCredentialsAndCreateUser($sName, $sPassword, $sLoginMode, $sAuthentication)
  1220. {
  1221. $bOk = true;
  1222. if ($sLoginMode != 'cas') return false; // Must be authenticated via CAS
  1223. $sCASMemberships = MetaModel::GetConfig()->Get('cas_memberof');
  1224. $bFound = false;
  1225. if (!empty($sCASMemberships))
  1226. {
  1227. if (phpCAS::hasAttribute('memberOf'))
  1228. {
  1229. // A list of groups is specified, the user must a be member of (at least) one of them to pass
  1230. $aCASMemberships = array();
  1231. $aTmp = explode(';', $sCASMemberships);
  1232. setlocale(LC_ALL, "en_US.utf8"); // !!! WARNING: this is needed to have the iconv //TRANSLIT working fine below !!!
  1233. foreach($aTmp as $sGroupName)
  1234. {
  1235. $aCASMemberships[] = trim(iconv('UTF-8', 'ASCII//TRANSLIT', $sGroupName)); // Just in case remove accents and spaces...
  1236. }
  1237. $aMemberOf = phpCAS::getAttribute('memberOf');
  1238. if (!is_array($aMemberOf)) $aMemberOf = array($aMemberOf); // Just one entry, turn it into an array
  1239. $aFilteredGroupNames = array();
  1240. foreach($aMemberOf as $sGroupName)
  1241. {
  1242. phpCAS::log("Info: user if a member of the group: ".$sGroupName);
  1243. $sGroupName = trim(iconv('UTF-8', 'ASCII//TRANSLIT', $sGroupName)); // Remove accents and spaces as well
  1244. $aFilteredGroupNames[] = $sGroupName;
  1245. $bIsMember = false;
  1246. foreach($aCASMemberships as $sCASPattern)
  1247. {
  1248. if (self::IsPattern($sCASPattern))
  1249. {
  1250. if (preg_match($sCASPattern, $sGroupName))
  1251. {
  1252. $bIsMember = true;
  1253. break;
  1254. }
  1255. }
  1256. else if ($sCASPattern == $sGroupName)
  1257. {
  1258. $bIsMember = true;
  1259. break;
  1260. }
  1261. }
  1262. if ($bIsMember)
  1263. {
  1264. $bCASUserSynchro = MetaModel::GetConfig()->Get('cas_user_synchro');
  1265. if ($bCASUserSynchro)
  1266. {
  1267. // If needed create a new user for this email/profile
  1268. phpCAS::log('Info: cas_user_synchro is ON');
  1269. $bOk = self::CreateCASUser(phpCAS::getUser(), $aMemberOf);
  1270. if($bOk)
  1271. {
  1272. $bFound = true;
  1273. }
  1274. else
  1275. {
  1276. phpCAS::log("User ".phpCAS::getUser()." cannot be created in iTop. Logging off...");
  1277. }
  1278. }
  1279. else
  1280. {
  1281. phpCAS::log('Info: cas_user_synchro is OFF');
  1282. $bFound = true;
  1283. }
  1284. break;
  1285. }
  1286. }
  1287. if($bOk && !$bFound)
  1288. {
  1289. phpCAS::log("User ".phpCAS::getUser().", none of his/her groups (".implode('; ', $aFilteredGroupNames).") match any of the required groups: ".implode('; ', $aCASMemberships));
  1290. }
  1291. }
  1292. else
  1293. {
  1294. // Too bad, the user is not part of any of the group => not allowed
  1295. phpCAS::log("No 'memberOf' attribute found for user ".phpCAS::getUser().". Are you using the SAML protocol (S1) ?");
  1296. }
  1297. }
  1298. else
  1299. {
  1300. // No membership: no way to create the user that should exist prior to authentication
  1301. phpCAS::log("User ".phpCAS::getUser().": missing user account in iTop (or iTop badly configured, Cf setting cas_memberof)");
  1302. $bFound = false;
  1303. }
  1304. if (!$bFound)
  1305. {
  1306. // The user is not part of the allowed groups, => log out
  1307. $sUrl = utils::GetAbsoluteUrlAppRoot().'pages/UI.php';
  1308. $sCASLogoutUrl = MetaModel::GetConfig()->Get('cas_logout_redirect_service');
  1309. if (empty($sCASLogoutUrl))
  1310. {
  1311. $sCASLogoutUrl = $sUrl;
  1312. }
  1313. phpCAS::logoutWithRedirectService($sCASLogoutUrl); // Redirects to the CAS logout page
  1314. // Will never return !
  1315. }
  1316. return $bFound;
  1317. }
  1318. /**
  1319. * Called after the user has been authenticated and found in iTop. This method can
  1320. * Update the user's definition (profiles...) on the fly to keep it in sync with an external source
  1321. * @param User $oUser The user to update/synchronize
  1322. * @param string $sLoginMode The login mode used (cas|form|basic|url)
  1323. * @param string $sAuthentication The authentication method used
  1324. * @return void
  1325. */
  1326. public static function UpdateUser(User $oUser, $sLoginMode, $sAuthentication)
  1327. {
  1328. $bCASUpdateProfiles = MetaModel::GetConfig()->Get('cas_update_profiles');
  1329. if (($sLoginMode == 'cas') && $bCASUpdateProfiles && (phpCAS::hasAttribute('memberOf')))
  1330. {
  1331. $aMemberOf = phpCAS::getAttribute('memberOf');
  1332. if (!is_array($aMemberOf)) $aMemberOf = array($aMemberOf); // Just one entry, turn it into an array
  1333. return self::SetProfilesFromCAS($oUser, $aMemberOf);
  1334. }
  1335. // No groups defined in CAS or not CAS at all: do nothing...
  1336. return true;
  1337. }
  1338. /**
  1339. * Helper method to create a CAS based user
  1340. * @param string $sEmail
  1341. * @param array $aGroups
  1342. * @return bool true on success, false otherwise
  1343. */
  1344. protected static function CreateCASUser($sEmail, $aGroups)
  1345. {
  1346. if (!MetaModel::IsValidClass('URP_Profiles'))
  1347. {
  1348. phpCAS::log("URP_Profiles is not a valid class. Automatic creation of Users is not supported in this context, sorry.");
  1349. return false;
  1350. }
  1351. $oUser = MetaModel::GetObjectByName('UserExternal', $sEmail, false);
  1352. if ($oUser == null)
  1353. {
  1354. // Create the user, link it to a contact
  1355. phpCAS::log("Info: the user '$sEmail' does not exist. A new UserExternal will be created.");
  1356. $oSearch = new DBObjectSearch('Person');
  1357. $oSearch->AddCondition('email', $sEmail);
  1358. $oSet = new DBObjectSet($oSearch);
  1359. $iContactId = 0;
  1360. switch($oSet->Count())
  1361. {
  1362. case 0:
  1363. phpCAS::log("Error: found no contact with the email: '$sEmail'. Cannot create the user in iTop.");
  1364. return false;
  1365. case 1:
  1366. $oContact = $oSet->Fetch();
  1367. $iContactId = $oContact->GetKey();
  1368. phpCAS::log("Info: Found 1 contact '".$oContact->GetName()."' (id=$iContactId) corresponding to the email '$sEmail'.");
  1369. break;
  1370. default:
  1371. phpCAS::log("Error: ".$oSet->Count()." contacts have the same email: '$sEmail'. Cannot create a user for this email.");
  1372. return false;
  1373. }
  1374. $oUser = new UserExternal();
  1375. $oUser->Set('login', $sEmail);
  1376. $oUser->Set('contactid', $iContactId);
  1377. $oUser->Set('language', MetaModel::GetConfig()->GetDefaultLanguage());
  1378. }
  1379. else
  1380. {
  1381. phpCAS::log("Info: the user '$sEmail' already exists (id=".$oUser->GetKey().").");
  1382. }
  1383. // Now synchronize the profiles
  1384. if (!self::SetProfilesFromCAS($oUser, $aGroups))
  1385. {
  1386. return false;
  1387. }
  1388. else
  1389. {
  1390. if ($oUser->IsNew() || $oUser->IsModified())
  1391. {
  1392. $oMyChange = MetaModel::NewObject("CMDBChange");
  1393. $oMyChange->Set("date", time());
  1394. $oMyChange->Set("userinfo", 'CAS/LDAP Synchro');
  1395. $oMyChange->DBInsert();
  1396. if ($oUser->IsNew())
  1397. {
  1398. $oUser->DBInsertTracked($oMyChange);
  1399. }
  1400. else
  1401. {
  1402. $oUser->DBUpdateTracked($oMyChange);
  1403. }
  1404. }
  1405. return true;
  1406. }
  1407. }
  1408. protected static function SetProfilesFromCAS($oUser, $aGroups)
  1409. {
  1410. if (!MetaModel::IsValidClass('URP_Profiles'))
  1411. {
  1412. phpCAS::log("URP_Profiles is not a valid class. Automatic creation of Users is not supported in this context, sorry.");
  1413. return false;
  1414. }
  1415. // read all the existing profiles
  1416. $oProfilesSearch = new DBObjectSearch('URP_Profiles');
  1417. $oProfilesSet = new DBObjectSet($oProfilesSearch);
  1418. $aAllProfiles = array();
  1419. while($oProfile = $oProfilesSet->Fetch())
  1420. {
  1421. $aAllProfiles[strtolower($oProfile->GetName())] = $oProfile->GetKey();
  1422. }
  1423. // Translate the CAS/LDAP group names into iTop profile names
  1424. $aProfiles = array();
  1425. $sPattern = MetaModel::GetConfig()->Get('cas_profile_pattern');
  1426. foreach($aGroups as $sGroupName)
  1427. {
  1428. if (preg_match($sPattern, $sGroupName, $aMatches))
  1429. {
  1430. if (array_key_exists(strtolower($aMatches[1]), $aAllProfiles))
  1431. {
  1432. $aProfiles[] = $aAllProfiles[strtolower($aMatches[1])];
  1433. phpCAS::log("Info: Adding the profile '{$aMatches[1]}' from CAS.");
  1434. }
  1435. else
  1436. {
  1437. phpCAS::log("Warning: {$aMatches[1]} is not a valid iTop profile (extracted from group name: '$sGroupName'). Ignored.");
  1438. }
  1439. }
  1440. else
  1441. {
  1442. phpCAS::log("Info: The CAS group '$sGroupName' does not seem to match an iTop pattern. Ignored.");
  1443. }
  1444. }
  1445. if (count($aProfiles) == 0)
  1446. {
  1447. phpCAS::log("Info: The user '".$oUser->GetName()."' has no profiles retrieved from CAS. Default profile(s) will be used.");
  1448. // Second attempt: check if there is/are valid default profile(s)
  1449. $sCASDefaultProfiles = MetaModel::GetConfig()->Get('cas_default_profiles');
  1450. $aCASDefaultProfiles = explode(';', $sCASDefaultProfiles);
  1451. foreach($aCASDefaultProfiles as $sDefaultProfileName)
  1452. {
  1453. if (array_key_exists(strtolower($sDefaultProfileName), $aAllProfiles))
  1454. {
  1455. $aProfiles[] = $aAllProfiles[strtolower($sDefaultProfileName)];
  1456. phpCAS::log("Info: Adding the default profile '".$aAllProfiles[strtolower($sDefaultProfileName)]."' from CAS.");
  1457. }
  1458. else
  1459. {
  1460. phpCAS::log("Warning: the default profile {$sDefaultProfileName} is not a valid iTop profile. Ignored.");
  1461. }
  1462. }
  1463. if (count($aProfiles) == 0)
  1464. {
  1465. phpCAS::log("Error: The user '".$oUser->GetName()."' has no profiles in iTop, and therefore cannot be created.");
  1466. return false;
  1467. }
  1468. }
  1469. // Now synchronize the profiles
  1470. $oProfilesSet = DBObjectSet::FromScratch('URP_UserProfile');
  1471. foreach($aProfiles as $iProfileId)
  1472. {
  1473. $oLink = new URP_UserProfile();
  1474. $oLink->Set('profileid', $iProfileId);
  1475. $oLink->Set('reason', 'CAS/LDAP Synchro');
  1476. $oProfilesSet->AddObject($oLink);
  1477. }
  1478. $oUser->Set('profile_list', $oProfilesSet);
  1479. phpCAS::log("Info: the user '".$oUser->GetName()."' (id=".$oUser->GetKey().") now has the following profiles: '".implode("', '", $aProfiles)."'.");
  1480. if ($oUser->IsModified())
  1481. {
  1482. $oMyChange = MetaModel::NewObject("CMDBChange");
  1483. $oMyChange->Set("date", time());
  1484. $oMyChange->Set("userinfo", 'CAS/LDAP Synchro');
  1485. $oMyChange->DBInsert();
  1486. if ($oUser->IsNew())
  1487. {
  1488. $oUser->DBInsertTracked($oMyChange);
  1489. }
  1490. else
  1491. {
  1492. $oUser->DBUpdateTracked($oMyChange);
  1493. }
  1494. }
  1495. return true;
  1496. }
  1497. /**
  1498. * Helper function to check if the supplied string is a litteral string or a regular expression pattern
  1499. * @param string $sCASPattern
  1500. * @return bool True if it's a regular expression pattern, false otherwise
  1501. */
  1502. protected static function IsPattern($sCASPattern)
  1503. {
  1504. if ((substr($sCASPattern, 0, 1) == '/') && (substr($sCASPattern, -1) == '/'))
  1505. {
  1506. // the string is enclosed by slashes, let's assume it's a pattern
  1507. return true;
  1508. }
  1509. else
  1510. {
  1511. return false;
  1512. }
  1513. }
  1514. }
  1515. // By default enable the 'CAS_SelfRegister' defined above
  1516. UserRights::SelectSelfRegister('CAS_SelfRegister');
  1517. ?>