userrights.class.inc.php 43 KB

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