loginwebpage.class.inc.php 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648
  1. <?php
  2. // Copyright (C) 2010 Combodo SARL
  3. //
  4. // This program is free software; you can redistribute it and/or modify
  5. // it under the terms of the GNU General Public License as published by
  6. // the Free Software Foundation; version 3 of the License.
  7. //
  8. // This program is distributed in the hope that it will be useful,
  9. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. // GNU General Public License for more details.
  12. //
  13. // You should have received a copy of the GNU General Public License
  14. // along with this program; if not, write to the Free Software
  15. // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
  16. /**
  17. * Class LoginWebPage
  18. *
  19. * @author Erwan Taloc <erwan.taloc@combodo.com>
  20. * @author Romain Quetiez <romain.quetiez@combodo.com>
  21. * @author Denis Flaven <denis.flaven@combodo.com>
  22. * @license http://www.opensource.org/licenses/gpl-3.0.html LGPL
  23. */
  24. require_once(APPROOT."/application/nicewebpage.class.inc.php");
  25. /**
  26. * Web page used for displaying the login form
  27. */
  28. class LoginWebPage extends NiceWebPage
  29. {
  30. public function __construct()
  31. {
  32. parent::__construct("iTop Login");
  33. $this->add_style(<<<EOF
  34. body {
  35. background: #eee;
  36. margin: 0;
  37. padding: 0;
  38. }
  39. #login-logo {
  40. margin-top: 150px;
  41. width: 300px;
  42. padding-left: 20px;
  43. padding-right: 20px;
  44. padding-top: 10px;
  45. padding-bottom: 10px;
  46. margin-left: auto;
  47. margin-right: auto;
  48. background: #f6f6f1;
  49. height: 54px;
  50. border-top: 1px solid #000;
  51. border-left: 1px solid #000;
  52. border-right: 1px solid #000;
  53. border-bottom: 0;
  54. text-align: center;
  55. }
  56. #login-logo img {
  57. border: 0;
  58. }
  59. #login {
  60. width: 300px;
  61. margin-left: auto;
  62. margin-right: auto;
  63. padding: 20px;
  64. background-color: #fff;
  65. border-bottom: 1px solid #000;
  66. border-left: 1px solid #000;
  67. border-right: 1px solid #000;
  68. border-top: 0;
  69. text-align: center;
  70. }
  71. #pwd, #user,#old_pwd, #new_pwd, #retype_new_pwd {
  72. width: 10em;
  73. }
  74. .center {
  75. text-align: center;
  76. }
  77. h1 {
  78. color: #1C94C4;
  79. font-size: 16pt;
  80. }
  81. .v-spacer {
  82. padding-top: 1em;
  83. }
  84. EOF
  85. );
  86. }
  87. public function DisplayLoginForm($sLoginType, $bFailedLogin = false)
  88. {
  89. switch($sLoginType)
  90. {
  91. case 'cas':
  92. utils::InitCASClient();
  93. // force CAS authentication
  94. phpCAS::forceAuthentication(); // Will redirect the user and exit since the user is not yet authenticated
  95. break;
  96. case 'basic':
  97. case 'url':
  98. $this->add_header('WWW-Authenticate: Basic realm="'.Dict::Format('UI:iTopVersion:Short', ITOP_VERSION));
  99. $this->add_header('HTTP/1.0 401 Unauthorized');
  100. // Note: displayed when the user will click on Cancel
  101. $this->add('<p><strong>'.Dict::S('UI:Login:Error:AccessRestricted').'</strong></p>');
  102. break;
  103. case 'external':
  104. case 'form':
  105. default: // In case the settings get messed up...
  106. $sAuthUser = utils::ReadParam('auth_user', '', true, 'raw_data');
  107. $sAuthPwd = utils::ReadParam('suggest_pwd', '', true, 'raw_data');
  108. $sVersionShort = Dict::Format('UI:iTopVersion:Short', ITOP_VERSION);
  109. $this->add("<div id=\"login-logo\"><a href=\"http://www.combodo.com/itop\"><img title=\"$sVersionShort\" src=\"../images/itop-logo-external.png\"></a></div>\n");
  110. $this->add("<div id=\"login\">\n");
  111. $this->add("<h1>".Dict::S('UI:Login:Welcome')."</h1>\n");
  112. if ($bFailedLogin)
  113. {
  114. $this->add("<p class=\"hilite\">".Dict::S('UI:Login:IncorrectLoginPassword')."</p>\n");
  115. }
  116. else
  117. {
  118. $this->add("<p>".Dict::S('UI:Login:IdentifyYourself')."</p>\n");
  119. }
  120. $this->add("<form method=\"post\">\n");
  121. $this->add("<table width=\"100%\">\n");
  122. $this->add("<tr><td style=\"text-align:right\"><label for=\"user\">".Dict::S('UI:Login:UserNamePrompt').":</label></td><td style=\"text-align:left\"><input id=\"user\" type=\"text\" name=\"auth_user\" value=\"".htmlentities($sAuthUser, ENT_QUOTES, 'UTF-8')."\" /></td></tr>\n");
  123. $this->add("<tr><td style=\"text-align:right\"><label for=\"pwd\">".Dict::S('UI:Login:PasswordPrompt').":</label></td><td style=\"text-align:left\"><input id=\"pwd\" type=\"password\" name=\"auth_pwd\" value=\"".htmlentities($sAuthPwd, ENT_QUOTES, 'UTF-8')."\" /></td></tr>\n");
  124. $this->add("<tr><td colspan=\"2\" class=\"center v-spacer\"> <input type=\"submit\" value=\"".Dict::S('UI:Button:Login')."\" /></td></tr>\n");
  125. $this->add("</table>\n");
  126. $this->add("<input type=\"hidden\" name=\"loginop\" value=\"login\" />\n");
  127. $this->add("</form>\n");
  128. $this->add("</div>\n");
  129. break;
  130. }
  131. }
  132. public function DisplayChangePwdForm($bFailedLogin = false)
  133. {
  134. $sAuthUser = utils::ReadParam('auth_user', '', false, 'raw_data');
  135. $sVersionShort = Dict::Format('UI:iTopVersion:Short', ITOP_VERSION);
  136. $sInconsistenPwdMsg = Dict::S('UI:Login:RetypePwdDoesNotMatch');
  137. $this->add_script(<<<EOF
  138. function GoBack()
  139. {
  140. window.history.back();
  141. }
  142. function DoCheckPwd()
  143. {
  144. if ($('#new_pwd').val() != $('#retype_new_pwd').val())
  145. {
  146. alert('$sInconsistenPwdMsg');
  147. return false;
  148. }
  149. return true;
  150. }
  151. EOF
  152. );
  153. $this->add("<div id=\"login-logo\"><a href=\"http://www.combodo.com/itop\"><img title=\"$sVersionShort\" src=\"../images/itop-logo.png\"></a></div>\n");
  154. $this->add("<div id=\"login\">\n");
  155. $this->add("<h1>".Dict::S('UI:Login:ChangeYourPassword')."</h1>\n");
  156. if ($bFailedLogin)
  157. {
  158. $this->add("<p class=\"hilite\">".Dict::S('UI:Login:IncorrectOldPassword')."</p>\n");
  159. }
  160. $this->add("<form method=\"post\">\n");
  161. $this->add("<table width=\"100%\">\n");
  162. $this->add("<tr><td style=\"text-align:right\"><label for=\"old_pwd\">".Dict::S('UI:Login:OldPasswordPrompt').":</label></td><td style=\"text-align:left\"><input type=\"password\" id=\"old_pwd\" name=\"old_pwd\" value=\"\" /></td></tr>\n");
  163. $this->add("<tr><td style=\"text-align:right\"><label for=\"new_pwd\">".Dict::S('UI:Login:NewPasswordPrompt').":</label></td><td style=\"text-align:left\"><input type=\"password\" id=\"new_pwd\" name=\"new_pwd\" value=\"\" /></td></tr>\n");
  164. $this->add("<tr><td style=\"text-align:right\"><label for=\"retype_new_pwd\">".Dict::S('UI:Login:RetypeNewPasswordPrompt').":</label></td><td style=\"text-align:left\"><input type=\"password\" id=\"retype_new_pwd\" name=\"retype_new_pwd\" value=\"\" /></td></tr>\n");
  165. $this->add("<tr><td colspan=\"2\" class=\"center v-spacer\"> <input type=\"button\" onClick=\"GoBack();\" value=\"".Dict::S('UI:Button:Cancel')."\" />&nbsp;&nbsp;<input type=\"submit\" onClick=\"return DoCheckPwd();\" value=\"".Dict::S('UI:Button:ChangePassword')."\" /></td></tr>\n");
  166. $this->add("</table>\n");
  167. $this->add("<input type=\"hidden\" name=\"loginop\" value=\"do_change_pwd\" />\n");
  168. $this->add("</form>\n");
  169. $this->add("</div>\n");
  170. }
  171. static function ResetSession()
  172. {
  173. if (isset($_SESSION['login_mode']))
  174. {
  175. $sPreviousLoginMode = $_SESSION['login_mode'];
  176. }
  177. else
  178. {
  179. $sPreviousLoginMode = '';
  180. }
  181. // Unset all of the session variables.
  182. $_SESSION = array();
  183. // If it's desired to kill the session, also delete the session cookie.
  184. // Note: This will destroy the session, and not just the session data!
  185. if (isset($_COOKIE[session_name()]))
  186. {
  187. setcookie(session_name(), '', time()-3600, '/');
  188. }
  189. // Finally, destroy the session.
  190. session_destroy();
  191. }
  192. static function SecureConnectionRequired()
  193. {
  194. return MetaModel::GetConfig()->GetSecureConnectionRequired();
  195. }
  196. static function IsConnectionSecure()
  197. {
  198. $bSecured = false;
  199. if (isset($_SERVER['HTTPS']) && ($_SERVER['HTTPS']!='off'))
  200. {
  201. $bSecured = true;
  202. }
  203. return $bSecured;
  204. }
  205. protected static function Login()
  206. {
  207. if (self::SecureConnectionRequired() && !self::IsConnectionSecure())
  208. {
  209. // Non secured URL... request for a secure connection
  210. throw new Exception('Secure connection required!');
  211. }
  212. $aAllowedLoginTypes = MetaModel::GetConfig()->GetAllowedLoginTypes();
  213. if (isset($_SESSION['auth_user']))
  214. {
  215. //echo "User: ".$_SESSION['auth_user']."\n";
  216. // Already authentified
  217. UserRights::Login($_SESSION['auth_user']); // Login & set the user's language
  218. return true;
  219. }
  220. else
  221. {
  222. $index = 0;
  223. $sLoginMode = '';
  224. $sAuthentication = 'internal';
  225. while(($sLoginMode == '') && ($index < count($aAllowedLoginTypes)))
  226. {
  227. $sLoginType = $aAllowedLoginTypes[$index];
  228. switch($sLoginType)
  229. {
  230. case 'cas':
  231. utils::InitCASClient();
  232. // check CAS authentication
  233. if (phpCAS::isAuthenticated())
  234. {
  235. // Check is a membership is required
  236. $sCASMemberships = MetaModel::GetConfig()->Get('cas_memberof');
  237. $bFound = false;
  238. if (!empty($sCASMemberships))
  239. {
  240. if (phpCAS::hasAttribute('memberOf'))
  241. {
  242. // A list of groups is specified, the user must a be member of (at least) one of them to pass
  243. $aCASMemberships = array();
  244. $aTmp = explode(';', $sCASMemberships);
  245. setlocale(LC_ALL, "en_US.utf8"); // !!! WARNING: this is needed to have the iconv //TRANSLIT working fine below !!!
  246. foreach($aTmp as $sGroupName)
  247. {
  248. $aCASMemberships[] = trim(iconv('UTF-8', 'ASCII//TRANSLIT', $sGroupName)); // Just in case remove accents and spaces...
  249. }
  250. $aMemberOf = phpCAS::getAttribute('memberOf');
  251. if (!is_array($aMemberOf)) $aMemberOf = array($aMemberOf); // Just one entry, turn it into an array
  252. $aFilteredGroupNames = array();
  253. foreach($aMemberOf as $sGroupName)
  254. {
  255. phpCAS::log("Info: user if a member of the group: ".$sGroupName);
  256. $sGroupName = trim(iconv('UTF-8', 'ASCII//TRANSLIT', $sGroupName)); // Remove accents and spaces as well
  257. $aFilteredGroupNames[] = $sGroupName;
  258. $bIsMember = false;
  259. foreach($aCASMemberships as $sCASPattern)
  260. {
  261. if (self::IsPattern($sCASPattern))
  262. {
  263. if (preg_match($sCASPattern, $sGroupName))
  264. {
  265. $bIsMember = true;
  266. break;
  267. }
  268. }
  269. else if ($sPattern == $sGroupName)
  270. {
  271. $bIsMember = true;
  272. break;
  273. }
  274. }
  275. if ($bIsMember)
  276. {
  277. $bCASUserSynchro = MetaModel::GetConfig()->Get('cas_user_synchro');
  278. if ($bCASUserSynchro)
  279. {
  280. // If needed create a new user for this email/profile
  281. phpCAS::log('Info: cas_user_synchro is ON');
  282. self::CreateCASUser(phpCAS::getUser(), $aMemberOf);
  283. }
  284. else
  285. {
  286. phpCAS::log('Info: cas_user_synchro is OFF');
  287. }
  288. $bFound = true;
  289. break;
  290. }
  291. }
  292. if(!$bFound)
  293. {
  294. phpCAS::log("User ".phpCAS::getUser().", none of his/her groups (".implode('; ', $aFilteredGroupNames).") match any of the required groups: ".implode('; ', $aCASMemberships));
  295. }
  296. }
  297. else
  298. {
  299. // Too bad, the user is not part of any of the group => not allowed
  300. phpCAS::log("No 'memberOf' attribute found for user ".phpCAS::getUser().". Are you using the SAML protocol (S1) ?");
  301. }
  302. }
  303. else
  304. {
  305. // No membership required, anybody will pass
  306. $bFound = true;
  307. }
  308. if ($bFound)
  309. {
  310. $sAuthUser = phpCAS::getUser();
  311. $sAuthPwd = '';
  312. $sLoginMode = 'cas';
  313. $sAuthentication = 'external';
  314. }
  315. else
  316. {
  317. // The user is not part of the allowed groups, => log out
  318. $sUrl = utils::GetAbsoluteUrlAppRoot().'pages/UI.php';
  319. $sCASLogoutUrl = MetaModel::GetConfig()->Get('cas_logout_redirect_service');
  320. if (empty($sCASLogoutUrl))
  321. {
  322. $sCASLogoutUrl = $sUrl;
  323. }
  324. phpCAS::logoutWithRedirectService($sCASLogoutUrl); // Redirects to the CAS logout page
  325. }
  326. }
  327. break;
  328. case 'form':
  329. // iTop standard mode: form based authentication
  330. $sAuthUser = utils::ReadPostedParam('auth_user', '', 'raw_data');
  331. $sAuthPwd = utils::ReadPostedParam('auth_pwd', '', 'raw_data');
  332. if ($sAuthUser != '')
  333. {
  334. $sLoginMode = 'form';
  335. }
  336. break;
  337. case 'basic':
  338. // Standard PHP authentication method, works with Apache...
  339. // Case 1) Apache running in CGI mode + rewrite rules in .htaccess
  340. if (isset($_SERVER['HTTP_AUTHORIZATION']) && !empty($_SERVER['HTTP_AUTHORIZATION']))
  341. {
  342. list($sAuthUser, $sAuthPwd) = explode(':' , base64_decode(substr($_SERVER['HTTP_AUTHORIZATION'], 6)));
  343. $sLoginMode = 'basic';
  344. }
  345. else if (isset($_SERVER['PHP_AUTH_USER']))
  346. {
  347. $sAuthUser = $_SERVER['PHP_AUTH_USER'];
  348. $sAuthPwd = $_SERVER['PHP_AUTH_PW'];
  349. $sLoginMode = 'basic';
  350. }
  351. break;
  352. case 'external':
  353. // Web server supplied authentication
  354. $bExternalAuth = false;
  355. $sExtAuthVar = MetaModel::GetConfig()->GetExternalAuthenticationVariable(); // In which variable is the info passed ?
  356. eval('$sAuthUser = isset('.$sExtAuthVar.') ? '.$sExtAuthVar.' : false;'); // Retrieve the value
  357. if ($sAuthUser && (strlen($sAuthUser) > 0))
  358. {
  359. $sAuthPwd = ''; // No password in this case the web server already authentified the user...
  360. $sLoginMode = 'external';
  361. $sAuthentication = 'external';
  362. }
  363. break;
  364. case 'url':
  365. // Credentials passed directly in the url
  366. $sAuthUser = utils::ReadParam('auth_user', '', false, 'raw_data');
  367. if ($sAuthUser != '')
  368. {
  369. $sAuthPwd = utils::ReadParam('auth_pwd', '', false, 'raw_data');
  370. $sLoginMode = 'url';
  371. }
  372. break;
  373. }
  374. $index++;
  375. }
  376. //echo "\nsLoginMode: $sLoginMode (user: $sAuthUser / pwd: $sAuthPwd\n)";
  377. if ($sLoginMode == '')
  378. {
  379. // First connection
  380. $sDesiredLoginMode = utils::ReadParam('login_mode');
  381. if (in_array($sDesiredLoginMode, $aAllowedLoginTypes))
  382. {
  383. $sLoginMode = $sDesiredLoginMode;
  384. }
  385. else
  386. {
  387. $sLoginMode = $aAllowedLoginTypes[0]; // First in the list...
  388. }
  389. $oPage = new LoginWebPage();
  390. $oPage->DisplayLoginForm( $sLoginMode, false /* no previous failed attempt */);
  391. $oPage->output();
  392. exit;
  393. }
  394. else
  395. {
  396. if (!UserRights::CheckCredentials($sAuthUser, $sAuthPwd, $sAuthentication))
  397. {
  398. //echo "Check Credentials returned false for user $sAuthUser!";
  399. self::ResetSession();
  400. $oPage = new LoginWebPage();
  401. $oPage->DisplayLoginForm( $sLoginMode, true /* failed attempt */);
  402. $oPage->output();
  403. exit;
  404. }
  405. else
  406. {
  407. // User is Ok, let's save it in the session and proceed with normal login
  408. UserRights::Login($sAuthUser, $sAuthentication); // Login & set the user's language
  409. if (MetaModel::GetConfig()->Get('log_usage'))
  410. {
  411. $oLog = new EventLoginUsage();
  412. $oLog->Set('userinfo', UserRights::GetUser());
  413. $oLog->Set('user_id', UserRights::GetUserObject()->GetKey());
  414. $oLog->Set('message', 'Successful login');
  415. $oLog->DBInsertNoReload();
  416. }
  417. $_SESSION['auth_user'] = $sAuthUser;
  418. $_SESSION['login_mode'] = $sLoginMode;
  419. }
  420. }
  421. }
  422. }
  423. /**
  424. * Check if the user is already authentified, if yes, then performs some additional validations:
  425. * - if $bMustBeAdmin is true, then the user must be an administrator, otherwise an error is displayed
  426. * - if $bIsAllowedToPortalUsers is false and the user has only access to the portal, then the user is redirected to the portal
  427. * @param bool $bMustBeAdmin Whether or not the user must be an admin to access the current page
  428. * @param bool $bIsAllowedToPortalUsers Whether or not the current page is considered as part of the portal
  429. */
  430. static function DoLogin($bMustBeAdmin = false, $bIsAllowedToPortalUsers = false)
  431. {
  432. $sMessage = ''; // In case we need to return a message to the calling web page
  433. $operation = utils::ReadParam('loginop', '');
  434. session_name(MetaModel::GetConfig()->Get('session_name'));
  435. session_start();
  436. if ($operation == 'logoff')
  437. {
  438. if (isset($_SESSION['login_mode']))
  439. {
  440. $sLoginMode = $_SESSION['login_mode'];
  441. }
  442. else
  443. {
  444. $aAllowedLoginTypes = MetaModel::GetConfig()->GetAllowedLoginTypes();
  445. if (count($aAllowedLoginTypes) > 0)
  446. {
  447. $sLoginMode = $aAllowedLoginTypes[0];
  448. }
  449. else
  450. {
  451. $sLoginMode = 'form';
  452. }
  453. }
  454. self::ResetSession();
  455. $oPage = new LoginWebPage();
  456. $oPage->DisplayLoginForm( $sLoginMode, false /* not a failed attempt */);
  457. $oPage->output();
  458. exit;
  459. }
  460. else if ($operation == 'change_pwd')
  461. {
  462. $sAuthUser = $_SESSION['auth_user'];
  463. UserRights::Login($sAuthUser); // Set the user's language
  464. $oPage = new LoginWebPage();
  465. $oPage->DisplayChangePwdForm();
  466. $oPage->output();
  467. exit;
  468. }
  469. if ($operation == 'do_change_pwd')
  470. {
  471. $sAuthUser = $_SESSION['auth_user'];
  472. UserRights::Login($sAuthUser); // Set the user's language
  473. $sOldPwd = utils::ReadPostedParam('old_pwd', 'raw_data');
  474. $sNewPwd = utils::ReadPostedParam('new_pwd', 'raw_data');
  475. if (UserRights::CanChangePassword() && ((!UserRights::CheckCredentials($sAuthUser, $sOldPwd)) || (!UserRights::ChangePassword($sOldPwd, $sNewPwd))))
  476. {
  477. $oPage = new LoginWebPage();
  478. $oPage->DisplayChangePwdForm(true); // old pwd was wrong
  479. $oPage->output();
  480. }
  481. $sMessage = Dict::S('UI:Login:PasswordChanged');
  482. }
  483. self::Login();
  484. if ($bMustBeAdmin && !UserRights::IsAdministrator())
  485. {
  486. require_once(APPROOT.'/setup/setuppage.class.inc.php');
  487. $oP = new SetupWebPage(Dict::S('UI:PageTitle:FatalError'));
  488. $oP->add("<h1>".Dict::S('UI:Login:Error:AccessAdmin')."</h1>\n");
  489. $oP->p("<a href=\"".utils::GetAbsoluteUrlAppRoot()."pages/logoff.php\">".Dict::S('UI:LogOffMenu')."</a>");
  490. $oP->output();
  491. exit;
  492. }
  493. elseif ( (!$bIsAllowedToPortalUsers) && (UserRights::IsPortalUser()))
  494. {
  495. // No rights to be here, redirect to the portal
  496. header('Location: '.utils::GetAbsoluteUrlAppRoot().'portal/index.php');
  497. }
  498. return $sMessage;
  499. }
  500. protected static function CreateCASUser($sEmail, $aGroups)
  501. {
  502. if (!MetaModel::IsValidClass('URP_Profiles'))
  503. {
  504. phpCAS::log("URP_Profiles is not a valid class. Automatic creation of Users is not supported in this context, sorry.");
  505. return;
  506. }
  507. // read all the existing profiles
  508. $oProfilesSearch = new DBObjectSearch('URP_Profiles');
  509. $oProfilesSet = new DBObjectSet($oProfilesSearch);
  510. $aAllProfiles = array();
  511. while($oProfile = $oProfilesSet->Fetch())
  512. {
  513. $aAllProfiles[strtolower($oProfile->GetName())] = $oProfile->GetKey();
  514. }
  515. // Translate the CAS/LDAP group names into iTop profile names
  516. $aProfiles = array();
  517. $sPattern = MetaModel::GetConfig()->Get('cas_profile_pattern');
  518. foreach($aGroups as $sGroupName)
  519. {
  520. if (preg_match($sPattern, $sGroupName, $aMatches))
  521. {
  522. if (array_key_exists(strtolower($aMatches[1]), $aAllProfiles))
  523. {
  524. $aProfiles[] = $aAllProfiles[strtolower($aMatches[1])];
  525. }
  526. else
  527. {
  528. phpCAS::log("Warning: {$aMatches[1]} is not a valid iTop profile (extracted from group name: '$sGroupName'). Ignored.");
  529. }
  530. }
  531. }
  532. if (count($aProfiles) == 0)
  533. {
  534. phpCAS::log("Error: no group name matches the pattern: '$sPattern'. The user '$sEmail' has no profiles in iTop, and therefore cannot be created.");
  535. return;
  536. }
  537. $oUser = MetaModel::GetObjectByName('UserExternal', $sEmail, false);
  538. if ($oUser == null)
  539. {
  540. // Create the user, link it to a contact
  541. phpCAS::log("Info: the user '$sEmail' does not exist. A new UserExternal will be created.");
  542. $oSearch = new DBObjectSearch('Person');
  543. $oSearch->AddCondition('email', $sEmail);
  544. $oSet = new DBObjectSet($oSearch);
  545. $iContactId = 0;
  546. switch($oSet->Count())
  547. {
  548. case 0:
  549. phpCAS::log("Error: found no contact with the email: '$sEmail'. Cannot create the user in iTop.");
  550. return;
  551. case 1:
  552. $oContact = $oSet->Fetch();
  553. $iContactId = $oContact->GetKey();
  554. phpCAS::log("Info: Found 1 contact '".$oContact->GetName()."' (id=$iContactId) corresponding to the email '$sEmail'.");
  555. break;
  556. default:
  557. phpCAS::log("Error: ".$oSet->Count()." contacts have the same email: '$sEmail'. Cannot create a user for this email.");
  558. return;
  559. }
  560. $oUser = new UserExternal();
  561. $oUser->Set('login', $sEmail);
  562. $oUser->Set('contactid', $iContactId);
  563. }
  564. else
  565. {
  566. phpCAS::log("Info: the user '$sEmail' already exists (id=".$oUser->GetKey().").");
  567. }
  568. // Now synchronize the profiles
  569. $oProfilesSet = DBObjectSet::FromScratch('URP_UserProfile');
  570. foreach($aProfiles as $iProfileId)
  571. {
  572. $oLink = new URP_UserProfile();
  573. $oLink->Set('profileid', $iProfileId);
  574. $oLink->Set('reason', 'CAS/LDAP Synchro');
  575. $oProfilesSet->AddObject($oLink);
  576. }
  577. $oUser->Set('profile_list', $oProfilesSet);
  578. phpCAS::log("Info: the user $sEmail (id=".$oUser->GetKey().") now has the following profiles: '".implode("', '", $aProfiles)."'.");
  579. if ($oUser->IsNew() || $oUser->IsModified())
  580. {
  581. $oMyChange = MetaModel::NewObject("CMDBChange");
  582. $oMyChange->Set("date", time());
  583. $oMyChange->Set("userinfo", 'CAS/LDAP Synchro');
  584. $oMyChange->DBInsert();
  585. if ($oUser->IsNew())
  586. {
  587. $oUser->DBInsertTracked($oMyChange);
  588. }
  589. else
  590. {
  591. $oUser->DBUpdateTracked($oMyChange);
  592. }
  593. }
  594. }
  595. protected static function IsPattern($sCASPattern)
  596. {
  597. if ((substr($sCASPattern, 0, 1) == '/') && (substr($sCASPattern, -1) == '/'))
  598. {
  599. // the string is enclosed by slashes, let's assume it's a pattern
  600. return true;
  601. }
  602. else
  603. {
  604. return false;
  605. }
  606. }
  607. } // End of class
  608. ?>