loginwebpage.class.inc.php 22 KB

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