userrights.class.inc.php 42 KB

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