userrights.class.inc.php 52 KB

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