2 // This file is part of Moodle - http://moodle.org/
4 // Moodle 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, either version 3 of the License, or
7 // (at your option) any later version.
9 // Moodle is distributed in the hope that it will be useful,
10 // but WITHOUT ANY WARRANTY; without even the implied warranty of
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 // GNU General Public License for more details.
14 // You should have received a copy of the GNU General Public License
15 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
18 * Authentication Plugin: LDAP Authentication
19 * Authentication using LDAP (Lightweight Directory Access Protocol).
22 * @author Martin Dougiamas
23 * @author IƱaki Arenaza
24 * @license http://www.gnu.org/copyleft/gpl.html GNU Public License
27 defined('MOODLE_INTERNAL') || die();
29 // See http://support.microsoft.com/kb/305144 to interprete these values.
30 if (!defined('AUTH_AD_ACCOUNTDISABLE')) {
31 define('AUTH_AD_ACCOUNTDISABLE', 0x0002);
33 if (!defined('AUTH_AD_NORMAL_ACCOUNT')) {
34 define('AUTH_AD_NORMAL_ACCOUNT', 0x0200);
36 if (!defined('AUTH_NTLMTIMEOUT')) { // timewindow for the NTLM SSO process, in secs...
37 define('AUTH_NTLMTIMEOUT', 10);
40 // UF_DONT_EXPIRE_PASSWD value taken from MSDN directly
41 if (!defined('UF_DONT_EXPIRE_PASSWD')) {
42 define ('UF_DONT_EXPIRE_PASSWD', 0x00010000);
45 // The Posix uid and gid of the 'nobody' account and 'nogroup' group.
46 if (!defined('AUTH_UID_NOBODY')) {
47 define('AUTH_UID_NOBODY', -2);
49 if (!defined('AUTH_GID_NOGROUP')) {
50 define('AUTH_GID_NOGROUP', -2);
53 // Regular expressions for a valid NTLM username and domain name.
54 if (!defined('AUTH_NTLM_VALID_USERNAME')) {
55 define('AUTH_NTLM_VALID_USERNAME', '[^/\\\\\\\\\[\]:;|=,+*?<>@"]+');
57 if (!defined('AUTH_NTLM_VALID_DOMAINNAME')) {
58 define('AUTH_NTLM_VALID_DOMAINNAME', '[^\\\\\\\\\/:*?"<>|]+');
60 // Default format for remote users if using NTLM SSO
61 if (!defined('AUTH_NTLM_DEFAULT_FORMAT')) {
62 define('AUTH_NTLM_DEFAULT_FORMAT', '%domain%\\%username%');
65 // Allows us to retrieve a diagnostic message in case of LDAP operation error
66 if (!defined('LDAP_OPT_DIAGNOSTIC_MESSAGE')) {
67 define('LDAP_OPT_DIAGNOSTIC_MESSAGE', 0x0032);
70 require_once($CFG->libdir.'/authlib.php');
71 require_once($CFG->libdir.'/ldaplib.php');
74 * LDAP authentication plugin.
76 class auth_plugin_ldap extends auth_plugin_base {
79 * Init plugin config from database settings depending on the plugin auth type.
81 function init_plugin($authtype) {
82 $this->pluginconfig = 'auth/'.$authtype;
83 $this->config = get_config($this->pluginconfig);
84 if (empty($this->config->ldapencoding)) {
85 $this->config->ldapencoding = 'utf-8';
87 if (empty($this->config->user_type)) {
88 $this->config->user_type = 'default';
91 $ldap_usertypes = ldap_supported_usertypes();
92 $this->config->user_type_name = $ldap_usertypes[$this->config->user_type];
93 unset($ldap_usertypes);
95 $default = ldap_getdefaults();
97 // Use defaults if values not given
98 foreach ($default as $key => $value) {
99 // watch out - 0, false are correct values too
100 if (!isset($this->config->{$key}) or $this->config->{$key} == '') {
101 $this->config->{$key} = $value[$this->config->user_type];
105 // Hack prefix to objectclass
106 if (empty($this->config->objectclass)) {
107 // Can't send empty filter
108 $this->config->objectclass = '(objectClass=*)';
109 } else if (stripos($this->config->objectclass, 'objectClass=') === 0) {
110 // Value is 'objectClass=some-string-here', so just add ()
111 // around the value (filter _must_ have them).
112 $this->config->objectclass = '('.$this->config->objectclass.')';
113 } else if (strpos($this->config->objectclass, '(') !== 0) {
114 // Value is 'some-string-not-starting-with-left-parentheses',
115 // which is assumed to be the objectClass matching value.
116 // So build a valid filter with it.
117 $this->config->objectclass = '(objectClass='.$this->config->objectclass.')';
119 // There is an additional possible value
120 // '(some-string-here)', that can be used to specify any
121 // valid filter string, to select subsets of users based
122 // on any criteria. For example, we could select the users
123 // whose objectClass is 'user' and have the
124 // 'enabledMoodleUser' attribute, with something like:
126 // (&(objectClass=user)(enabledMoodleUser=1))
128 // In this particular case we don't need to do anything,
129 // so leave $this->config->objectclass as is.
134 * Constructor with initialisation.
136 function auth_plugin_ldap() {
137 $this->authtype = 'ldap';
138 $this->roleauth = 'auth_ldap';
139 $this->errorlogtag = '[AUTH LDAP] ';
140 $this->init_plugin($this->authtype);
144 * Returns true if the username and password work and false if they are
145 * wrong or don't exist.
147 * @param string $username The username (without system magic quotes)
148 * @param string $password The password (without system magic quotes)
150 * @return bool Authentication success or failure.
152 function user_login($username, $password) {
153 if (! function_exists('ldap_bind')) {
154 print_error('auth_ldapnotinstalled', 'auth_ldap');
158 if (!$username or !$password) { // Don't allow blank usernames or passwords
162 $extusername = textlib::convert($username, 'utf-8', $this->config->ldapencoding);
163 $extpassword = textlib::convert($password, 'utf-8', $this->config->ldapencoding);
165 // Before we connect to LDAP, check if this is an AD SSO login
166 // if we succeed in this block, we'll return success early.
169 if (!empty($this->config->ntlmsso_enabled) && $key === $password) {
170 $cf = get_cache_flags($this->pluginconfig.'/ntlmsess');
171 // We only get the cache flag if we retrieve it before
172 // it expires (AUTH_NTLMTIMEOUT seconds).
173 if (!isset($cf[$key]) || $cf[$key] === '') {
177 $sessusername = $cf[$key];
178 if ($username === $sessusername) {
179 unset($sessusername);
182 // Check that the user is inside one of the configured LDAP contexts
184 $ldapconnection = $this->ldap_connect();
185 // if the user is not inside the configured contexts,
186 // ldap_find_userdn returns false.
187 if ($this->ldap_find_userdn($ldapconnection, $extusername)) {
192 // Shortcut here - SSO confirmed
195 } // End SSO processing
198 $ldapconnection = $this->ldap_connect();
199 $ldap_user_dn = $this->ldap_find_userdn($ldapconnection, $extusername);
201 // If ldap_user_dn is empty, user does not exist
202 if (!$ldap_user_dn) {
207 // Try to bind with current username and password
208 $ldap_login = @ldap_bind($ldapconnection, $ldap_user_dn, $extpassword);
210 // If login fails and we are using MS Active Directory, retrieve the diagnostic
211 // message to see if this is due to an expired password, or that the user is forced to
212 // change the password on first login. If it is, only proceed if we can change
213 // password from Moodle (otherwise we'll get stuck later in the login process).
214 if (!$ldap_login && ($this->config->user_type == 'ad')
215 && $this->can_change_password()
216 && (!empty($this->config->expiration) and ($this->config->expiration == 1))) {
218 // We need to get the diagnostic message right after the call to ldap_bind(),
219 // before any other LDAP operation.
220 ldap_get_option($ldapconnection, LDAP_OPT_DIAGNOSTIC_MESSAGE, $diagmsg);
222 if ($this->ldap_ad_pwdexpired_from_diagmsg($diagmsg)) {
223 // If login failed because user must change the password now or the
224 // password has expired, let the user in. We'll catch this later in the
225 // login process when we explicitly check for expired passwords.
234 * Reads user information from ldap and returns it in array()
236 * Function should return all information available. If you are saving
237 * this information to moodle user-table you should honor syncronization flags
239 * @param string $username username
241 * @return mixed array with no magic quotes or false on error
243 function get_userinfo($username) {
244 $extusername = textlib::convert($username, 'utf-8', $this->config->ldapencoding);
246 $ldapconnection = $this->ldap_connect();
247 if(!($user_dn = $this->ldap_find_userdn($ldapconnection, $extusername))) {
252 $search_attribs = array();
253 $attrmap = $this->ldap_attributes();
254 foreach ($attrmap as $key => $values) {
255 if (!is_array($values)) {
256 $values = array($values);
258 foreach ($values as $value) {
259 if (!in_array($value, $search_attribs)) {
260 array_push($search_attribs, $value);
265 if (!$user_info_result = ldap_read($ldapconnection, $user_dn, '(objectClass=*)', $search_attribs)) {
267 return false; // error!
270 $user_entry = ldap_get_entries_moodle($ldapconnection, $user_info_result);
271 if (empty($user_entry)) {
273 return false; // entry not found
277 foreach ($attrmap as $key => $values) {
278 if (!is_array($values)) {
279 $values = array($values);
282 foreach ($values as $value) {
283 $entry = array_change_key_case($user_entry[0], CASE_LOWER);
284 if (($value == 'dn') || ($value == 'distinguishedname')) {
285 $result[$key] = $user_dn;
288 if (!array_key_exists($value, $entry)) {
289 continue; // wrong data mapping!
291 if (is_array($entry[$value])) {
292 $newval = textlib::convert($entry[$value][0], $this->config->ldapencoding, 'utf-8');
294 $newval = textlib::convert($entry[$value], $this->config->ldapencoding, 'utf-8');
296 if (!empty($newval)) { // favour ldap entries that are set
300 if (!is_null($ldapval)) {
301 $result[$key] = $ldapval;
310 * Reads user information from ldap and returns it in an object
312 * @param string $username username (with system magic quotes)
313 * @return mixed object or false on error
315 function get_userinfo_asobj($username) {
316 $user_array = $this->get_userinfo($username);
317 if ($user_array == false) {
318 return false; //error or not found
320 $user_array = truncate_userinfo($user_array);
321 $user = new stdClass();
322 foreach ($user_array as $key=>$value) {
323 $user->{$key} = $value;
329 * Returns all usernames from LDAP
331 * get_userlist returns all usernames from LDAP
335 function get_userlist() {
336 return $this->ldap_get_userlist("({$this->config->user_attribute}=*)");
340 * Checks if user exists on LDAP
342 * @param string $username
344 function user_exists($username) {
345 $extusername = textlib::convert($username, 'utf-8', $this->config->ldapencoding);
347 // Returns true if given username exists on ldap
348 $users = $this->ldap_get_userlist('('.$this->config->user_attribute.'='.ldap_filter_addslashes($extusername).')');
349 return count($users);
353 * Creates a new user on LDAP.
354 * By using information in userobject
355 * Use user_exists to prevent duplicate usernames
357 * @param mixed $userobject Moodle userobject
358 * @param mixed $plainpass Plaintext password
360 function user_create($userobject, $plainpass) {
361 $extusername = textlib::convert($userobject->username, 'utf-8', $this->config->ldapencoding);
362 $extpassword = textlib::convert($plainpass, 'utf-8', $this->config->ldapencoding);
364 switch ($this->config->passtype) {
366 $extpassword = '{MD5}' . base64_encode(pack('H*', md5($extpassword)));
369 $extpassword = '{SHA}' . base64_encode(pack('H*', sha1($extpassword)));
376 $ldapconnection = $this->ldap_connect();
377 $attrmap = $this->ldap_attributes();
381 foreach ($attrmap as $key => $values) {
382 if (!is_array($values)) {
383 $values = array($values);
385 foreach ($values as $value) {
386 if (!empty($userobject->$key) ) {
387 $newuser[$value] = textlib::convert($userobject->$key, 'utf-8', $this->config->ldapencoding);
392 //Following sets all mandatory and other forced attribute values
393 //User should be creted as login disabled untill email confirmation is processed
394 //Feel free to add your user type and send patches to paca@sci.fi to add them
395 //Moodle distribution
397 switch ($this->config->user_type) {
399 $newuser['objectClass'] = array('inetOrgPerson', 'organizationalPerson', 'person', 'top');
400 $newuser['uniqueId'] = $extusername;
401 $newuser['logindisabled'] = 'TRUE';
402 $newuser['userpassword'] = $extpassword;
403 $uadd = ldap_add($ldapconnection, $this->config->user_attribute.'='.ldap_addslashes($extusername).','.$this->config->create_context, $newuser);
407 // posixAccount object class forces us to specify a uidNumber
408 // and a gidNumber. That is quite complicated to generate from
409 // Moodle without colliding with existing numbers and without
410 // race conditions. As this user is supposed to be only used
411 // with Moodle (otherwise the user would exist beforehand) and
412 // doesn't need to login into a operating system, we assign the
413 // user the uid of user 'nobody' and gid of group 'nogroup'. In
414 // addition to that, we need to specify a home directory. We
415 // use the root directory ('/') as the home directory, as this
416 // is the only one can always be sure exists. Finally, even if
417 // it's not mandatory, we specify '/bin/false' as the login
418 // shell, to prevent the user from login in at the operating
419 // system level (Moodle ignores this).
421 $newuser['objectClass'] = array('posixAccount', 'inetOrgPerson', 'organizationalPerson', 'person', 'top');
422 $newuser['cn'] = $extusername;
423 $newuser['uid'] = $extusername;
424 $newuser['uidNumber'] = AUTH_UID_NOBODY;
425 $newuser['gidNumber'] = AUTH_GID_NOGROUP;
426 $newuser['homeDirectory'] = '/';
427 $newuser['loginShell'] = '/bin/false';
430 // We have to create the account locked, but posixAccount has
431 // no attribute to achive this reliably. So we are going to
432 // modify the password in a reversable way that we can later
433 // revert in user_activate().
435 // Beware that this can be defeated by the user if we are not
436 // using MD5 or SHA-1 passwords. After all, the source code of
437 // Moodle is available, and the user can see the kind of
438 // modification we are doing and 'undo' it by hand (but only
439 // if we are using plain text passwords).
441 // Also bear in mind that you need to use a binding user that
442 // can create accounts and has read/write privileges on the
443 // 'userPassword' attribute for this to work.
445 $newuser['userPassword'] = '*'.$extpassword;
446 $uadd = ldap_add($ldapconnection, $this->config->user_attribute.'='.ldap_addslashes($extusername).','.$this->config->create_context, $newuser);
449 // User account creation is a two step process with AD. First you
450 // create the user object, then you set the password. If you try
451 // to set the password while creating the user, the operation
454 // Passwords in Active Directory must be encoded as Unicode
455 // strings (UCS-2 Little Endian format) and surrounded with
456 // double quotes. See http://support.microsoft.com/?kbid=269190
457 if (!function_exists('mb_convert_encoding')) {
458 print_error('auth_ldap_no_mbstring', 'auth_ldap');
461 // Check for invalid sAMAccountName characters.
462 if (preg_match('#[/\\[\]:;|=,+*?<>@"]#', $extusername)) {
463 print_error ('auth_ldap_ad_invalidchars', 'auth_ldap');
466 // First create the user account, and mark it as disabled.
467 $newuser['objectClass'] = array('top', 'person', 'user', 'organizationalPerson');
468 $newuser['sAMAccountName'] = $extusername;
469 $newuser['userAccountControl'] = AUTH_AD_NORMAL_ACCOUNT |
470 AUTH_AD_ACCOUNTDISABLE;
471 $userdn = 'cn='.ldap_addslashes($extusername).','.$this->config->create_context;
472 if (!ldap_add($ldapconnection, $userdn, $newuser)) {
473 print_error('auth_ldap_ad_create_req', 'auth_ldap');
476 // Now set the password
478 $newuser['unicodePwd'] = mb_convert_encoding('"' . $extpassword . '"',
480 if(!ldap_modify($ldapconnection, $userdn, $newuser)) {
481 // Something went wrong: delete the user account and error out
482 ldap_delete ($ldapconnection, $userdn);
483 print_error('auth_ldap_ad_create_req', 'auth_ldap');
488 print_error('auth_ldap_unsupportedusertype', 'auth_ldap', '', $this->config->user_type_name);
495 * Returns true if plugin allows resetting of password from moodle.
499 function can_reset_password() {
500 return !empty($this->config->stdchangepassword);
504 * Returns true if plugin allows signup and user creation.
508 function can_signup() {
509 return (!empty($this->config->auth_user_create) and !empty($this->config->create_context));
513 * Sign up a new user ready for confirmation.
514 * Password is passed in plaintext.
516 * @param object $user new user object
517 * @param boolean $notify print notice with link and terminate
519 function user_signup($user, $notify=true) {
520 global $CFG, $DB, $PAGE, $OUTPUT;
522 require_once($CFG->dirroot.'/user/profile/lib.php');
524 if ($this->user_exists($user->username)) {
525 print_error('auth_ldap_user_exists', 'auth_ldap');
528 $plainslashedpassword = $user->password;
529 unset($user->password);
531 if (! $this->user_create($user, $plainslashedpassword)) {
532 print_error('auth_ldap_create_error', 'auth_ldap');
535 $user->id = $DB->insert_record('user', $user);
537 // Save any custom profile field information
538 profile_save_data($user);
540 $this->update_user_record($user->username);
541 // This will also update the stored hash to the latest algorithm
542 // if the existing hash is using an out-of-date algorithm (or the
543 // legacy md5 algorithm).
544 update_internal_user_password($user, $plainslashedpassword);
546 $user = $DB->get_record('user', array('id'=>$user->id));
547 events_trigger('user_created', $user);
549 if (! send_confirmation_email($user)) {
550 print_error('noemail', 'auth_ldap');
554 $emailconfirm = get_string('emailconfirm');
555 $PAGE->set_url('/auth/ldap/auth.php');
556 $PAGE->navbar->add($emailconfirm);
557 $PAGE->set_title($emailconfirm);
558 $PAGE->set_heading($emailconfirm);
559 echo $OUTPUT->header();
560 notice(get_string('emailconfirmsent', '', $user->email), "{$CFG->wwwroot}/index.php");
567 * Returns true if plugin allows confirming of new users.
571 function can_confirm() {
572 return $this->can_signup();
576 * Confirm the new user as registered.
578 * @param string $username
579 * @param string $confirmsecret
581 function user_confirm($username, $confirmsecret) {
584 $user = get_complete_user_data('username', $username);
587 if ($user->confirmed) {
588 return AUTH_CONFIRM_ALREADY;
590 } else if ($user->auth != $this->authtype) {
591 return AUTH_CONFIRM_ERROR;
593 } else if ($user->secret == $confirmsecret) { // They have provided the secret key to get in
594 if (!$this->user_activate($username)) {
595 return AUTH_CONFIRM_FAIL;
597 $DB->set_field('user', 'confirmed', 1, array('id'=>$user->id));
598 if ($user->firstaccess == 0) {
599 $DB->set_field('user', 'firstaccess', time(), array('id'=>$user->id));
601 $euser = $DB->get_record('user', array('id' => $user->id));
602 events_trigger('user_updated', $euser);
603 return AUTH_CONFIRM_OK;
606 return AUTH_CONFIRM_ERROR;
611 * Return number of days to user password expires
613 * If userpassword does not expire it should return 0. If password is already expired
614 * it should return negative value.
616 * @param mixed $username username
619 function password_expire($username) {
622 $extusername = textlib::convert($username, 'utf-8', $this->config->ldapencoding);
624 $ldapconnection = $this->ldap_connect();
625 $user_dn = $this->ldap_find_userdn($ldapconnection, $extusername);
626 $search_attribs = array($this->config->expireattr);
627 $sr = ldap_read($ldapconnection, $user_dn, '(objectClass=*)', $search_attribs);
629 $info = ldap_get_entries_moodle($ldapconnection, $sr);
630 if (!empty ($info)) {
631 $info = array_change_key_case($info[0], CASE_LOWER);
632 if (isset($info[$this->config->expireattr][0])) {
633 $expiretime = $this->ldap_expirationtime2unix($info[$this->config->expireattr][0], $ldapconnection, $user_dn);
634 if ($expiretime != 0) {
636 if ($expiretime > $now) {
637 $result = ceil(($expiretime - $now) / DAYSECS);
639 $result = floor(($expiretime - $now) / DAYSECS);
645 error_log($this->errorlogtag.get_string('didtfindexpiretime', 'auth_ldap'));
652 * Syncronizes user fron external LDAP server to moodle user table
654 * Sync is now using username attribute.
656 * Syncing users removes or suspends users that dont exists anymore in external LDAP.
657 * Creates new users and updates coursecreator status of users.
659 * @param bool $do_updates will do pull in data updates from LDAP if relevant
661 function sync_users($do_updates=true) {
664 print_string('connectingldap', 'auth_ldap');
665 $ldapconnection = $this->ldap_connect();
667 $dbman = $DB->get_manager();
669 /// Define table user to be created
670 $table = new xmldb_table('tmp_extuser');
671 $table->add_field('id', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, XMLDB_SEQUENCE, null);
672 $table->add_field('username', XMLDB_TYPE_CHAR, '100', null, XMLDB_NOTNULL, null, null);
673 $table->add_field('mnethostid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null);
674 $table->add_key('primary', XMLDB_KEY_PRIMARY, array('id'));
675 $table->add_index('username', XMLDB_INDEX_UNIQUE, array('mnethostid', 'username'));
677 print_string('creatingtemptable', 'auth_ldap', 'tmp_extuser');
678 $dbman->create_temp_table($table);
681 //// get user's list from ldap to sql in a scalable fashion
683 // prepare some data we'll need
684 $filter = '(&('.$this->config->user_attribute.'=*)'.$this->config->objectclass.')';
686 $contexts = explode(';', $this->config->contexts);
688 if (!empty($this->config->create_context)) {
689 array_push($contexts, $this->config->create_context);
692 $ldap_pagedresults = ldap_paged_results_supported($this->config->ldap_version);
694 foreach ($contexts as $context) {
695 $context = trim($context);
696 if (empty($context)) {
701 if ($ldap_pagedresults) {
702 ldap_control_paged_result($ldapconnection, $this->config->pagesize, true, $ldap_cookie);
704 if ($this->config->search_sub) {
705 // Use ldap_search to find first user from subtree.
706 $ldap_result = ldap_search($ldapconnection, $context, $filter, array($this->config->user_attribute));
708 // Search only in this context.
709 $ldap_result = ldap_list($ldapconnection, $context, $filter, array($this->config->user_attribute));
714 if ($ldap_pagedresults) {
715 ldap_control_paged_result_response($ldapconnection, $ldap_result, $ldap_cookie);
717 if ($entry = @ldap_first_entry($ldapconnection, $ldap_result)) {
719 $value = ldap_get_values_len($ldapconnection, $entry, $this->config->user_attribute);
720 $value = textlib::convert($value[0], $this->config->ldapencoding, 'utf-8');
721 $this->ldap_bulk_insert($value);
722 } while ($entry = ldap_next_entry($ldapconnection, $entry));
724 unset($ldap_result); // Free mem.
725 } while ($ldap_pagedresults && !empty($ldap_cookie));
728 // If LDAP paged results were used, the current connection must be completely
729 // closed and a new one created, to work without paged results from here on.
730 if ($ldap_pagedresults) {
731 $this->ldap_close(true);
732 $ldapconnection = $this->ldap_connect();
735 /// preserve our user database
736 /// if the temp table is empty, it probably means that something went wrong, exit
737 /// so as to avoid mass deletion of users; which is hard to undo
738 $count = $DB->count_records_sql('SELECT COUNT(username) AS count, 1 FROM {tmp_extuser}');
740 print_string('didntgetusersfromldap', 'auth_ldap');
743 print_string('gotcountrecordsfromldap', 'auth_ldap', $count);
748 // Find users in DB that aren't in ldap -- to be removed!
749 // this is still not as scalable (but how often do we mass delete?)
750 if ($this->config->removeuser != AUTH_REMOVEUSER_KEEP) {
753 LEFT JOIN {tmp_extuser} e ON (u.username = e.username AND u.mnethostid = e.mnethostid)
756 AND e.username IS NULL';
757 $remove_users = $DB->get_records_sql($sql, array($this->authtype));
759 if (!empty($remove_users)) {
760 print_string('userentriestoremove', 'auth_ldap', count($remove_users));
762 foreach ($remove_users as $user) {
763 if ($this->config->removeuser == AUTH_REMOVEUSER_FULLDELETE) {
764 if (delete_user($user)) {
765 echo "\t"; print_string('auth_dbdeleteuser', 'auth_db', array('name'=>$user->username, 'id'=>$user->id)); echo "\n";
767 echo "\t"; print_string('auth_dbdeleteusererror', 'auth_db', $user->username); echo "\n";
769 } else if ($this->config->removeuser == AUTH_REMOVEUSER_SUSPEND) {
770 $updateuser = new stdClass();
771 $updateuser->id = $user->id;
772 $updateuser->auth = 'nologin';
773 $DB->update_record('user', $updateuser);
774 echo "\t"; print_string('auth_dbsuspenduser', 'auth_db', array('name'=>$user->username, 'id'=>$user->id)); echo "\n";
775 $euser = $DB->get_record('user', array('id' => $user->id));
776 events_trigger('user_updated', $euser);
780 print_string('nouserentriestoremove', 'auth_ldap');
782 unset($remove_users); // free mem!
785 /// Revive suspended users
786 if (!empty($this->config->removeuser) and $this->config->removeuser == AUTH_REMOVEUSER_SUSPEND) {
787 $sql = "SELECT u.id, u.username
789 JOIN {tmp_extuser} e ON (u.username = e.username AND u.mnethostid = e.mnethostid)
790 WHERE u.auth = 'nologin' AND u.deleted = 0";
791 $revive_users = $DB->get_records_sql($sql);
793 if (!empty($revive_users)) {
794 print_string('userentriestorevive', 'auth_ldap', count($revive_users));
796 foreach ($revive_users as $user) {
797 $updateuser = new stdClass();
798 $updateuser->id = $user->id;
799 $updateuser->auth = $this->authtype;
800 $DB->update_record('user', $updateuser);
801 echo "\t"; print_string('auth_dbreviveduser', 'auth_db', array('name'=>$user->username, 'id'=>$user->id)); echo "\n";
802 $euser = $DB->get_record('user', array('id' => $user->id));
803 events_trigger('user_updated', $euser);
806 print_string('nouserentriestorevive', 'auth_ldap');
809 unset($revive_users);
813 /// User Updates - time-consuming (optional)
815 // Narrow down what fields we need to update
816 $all_keys = array_keys(get_object_vars($this->config));
817 $updatekeys = array();
818 foreach ($all_keys as $key) {
819 if (preg_match('/^field_updatelocal_(.+)$/', $key, $match)) {
820 // If we have a field to update it from
821 // and it must be updated 'onlogin' we
823 if (!empty($this->config->{'field_map_'.$match[1]})
824 and $this->config->{$match[0]} === 'onlogin') {
825 array_push($updatekeys, $match[1]); // the actual key name
829 unset($all_keys); unset($key);
832 print_string('noupdatestobedone', 'auth_ldap');
834 if ($do_updates and !empty($updatekeys)) { // run updates only if relevant
835 $users = $DB->get_records_sql('SELECT u.username, u.id
837 WHERE u.deleted = 0 AND u.auth = ? AND u.mnethostid = ?',
838 array($this->authtype, $CFG->mnet_localhost_id));
839 if (!empty($users)) {
840 print_string('userentriestoupdate', 'auth_ldap', count($users));
842 $sitecontext = context_system::instance();
843 if (!empty($this->config->creators) and !empty($this->config->memberattribute)
844 and $roles = get_archetype_roles('coursecreator')) {
845 $creatorrole = array_shift($roles); // We can only use one, let's use the first one
847 $creatorrole = false;
850 $transaction = $DB->start_delegated_transaction();
854 foreach ($users as $user) {
855 echo "\t"; print_string('auth_dbupdatinguser', 'auth_db', array('name'=>$user->username, 'id'=>$user->id));
856 if (!$this->update_user_record($user->username, $updatekeys)) {
857 echo ' - '.get_string('skipped');
862 // Update course creators if needed
863 if ($creatorrole !== false) {
864 if ($this->iscreator($user->username)) {
865 role_assign($creatorrole->id, $user->id, $sitecontext->id, $this->roleauth);
867 role_unassign($creatorrole->id, $user->id, $sitecontext->id, $this->roleauth);
871 $transaction->allow_commit();
872 unset($users); // free mem
874 } else { // end do updates
875 print_string('noupdatestobedone', 'auth_ldap');
879 // Find users missing in DB that are in LDAP
880 // and gives me a nifty object I don't want.
881 // note: we do not care about deleted accounts anymore, this feature was replaced by suspending to nologin auth plugin
882 $sql = 'SELECT e.id, e.username
884 LEFT JOIN {user} u ON (e.username = u.username AND e.mnethostid = u.mnethostid)
886 $add_users = $DB->get_records_sql($sql);
888 if (!empty($add_users)) {
889 print_string('userentriestoadd', 'auth_ldap', count($add_users));
891 $sitecontext = context_system::instance();
892 if (!empty($this->config->creators) and !empty($this->config->memberattribute)
893 and $roles = get_archetype_roles('coursecreator')) {
894 $creatorrole = array_shift($roles); // We can only use one, let's use the first one
896 $creatorrole = false;
899 $transaction = $DB->start_delegated_transaction();
900 foreach ($add_users as $user) {
901 $user = $this->get_userinfo_asobj($user->username);
904 $user->modified = time();
905 $user->confirmed = 1;
906 $user->auth = $this->authtype;
907 $user->mnethostid = $CFG->mnet_localhost_id;
908 // get_userinfo_asobj() might have replaced $user->username with the value
909 // from the LDAP server (which can be mixed-case). Make sure it's lowercase
910 $user->username = trim(textlib::strtolower($user->username));
911 if (empty($user->lang)) {
912 $user->lang = $CFG->lang;
915 $id = $DB->insert_record('user', $user);
916 echo "\t"; print_string('auth_dbinsertuser', 'auth_db', array('name'=>$user->username, 'id'=>$id)); echo "\n";
917 $euser = $DB->get_record('user', array('id' => $user->id));
918 events_trigger('user_created', $euser);
919 if (!empty($this->config->forcechangepassword)) {
920 set_user_preference('auth_forcepasswordchange', 1, $id);
923 // Add course creators if needed
924 if ($creatorrole !== false and $this->iscreator($user->username)) {
925 role_assign($creatorrole->id, $id, $sitecontext->id, $this->roleauth);
929 $transaction->allow_commit();
930 unset($add_users); // free mem
932 print_string('nouserstobeadded', 'auth_ldap');
935 $dbman->drop_table($table);
942 * Update a local user record from an external source.
943 * This is a lighter version of the one in moodlelib -- won't do
944 * expensive ops such as enrolment.
946 * If you don't pass $updatekeys, there is a performance hit and
947 * values removed from LDAP won't be removed from moodle.
949 * @param string $username username
950 * @param boolean $updatekeys true to update the local record with the external LDAP values.
952 function update_user_record($username, $updatekeys = false) {
955 // Just in case check text case
956 $username = trim(textlib::strtolower($username));
958 // Get the current user record
959 $user = $DB->get_record('user', array('username'=>$username, 'mnethostid'=>$CFG->mnet_localhost_id));
960 if (empty($user)) { // trouble
961 error_log($this->errorlogtag.get_string('auth_dbusernotexist', 'auth_db', '', $username));
962 print_error('auth_dbusernotexist', 'auth_db', '', $username);
966 // Protect the userid from being overwritten
969 if ($newinfo = $this->get_userinfo($username)) {
970 $newinfo = truncate_userinfo($newinfo);
972 if (empty($updatekeys)) { // all keys? this does not support removing values
973 $updatekeys = array_keys($newinfo);
976 foreach ($updatekeys as $key) {
977 if (isset($newinfo[$key])) {
978 $value = $newinfo[$key];
983 if (!empty($this->config->{'field_updatelocal_' . $key})) {
984 if ($user->{$key} != $value) { // only update if it's changed
985 $DB->set_field('user', $key, $value, array('id'=>$userid));
989 if (!empty($updatekeys)) {
990 $euser = $DB->get_record('user', array('id' => $userid));
991 events_trigger('user_updated', $euser);
996 return $DB->get_record('user', array('id'=>$userid, 'deleted'=>0));
1000 * Bulk insert in SQL's temp table
1002 function ldap_bulk_insert($username) {
1005 $username = textlib::strtolower($username); // usernames are __always__ lowercase.
1006 $DB->insert_record_raw('tmp_extuser', array('username'=>$username,
1007 'mnethostid'=>$CFG->mnet_localhost_id), false, true);
1012 * Activates (enables) user in external LDAP so user can login
1014 * @param mixed $username
1015 * @return boolean result
1017 function user_activate($username) {
1018 $extusername = textlib::convert($username, 'utf-8', $this->config->ldapencoding);
1020 $ldapconnection = $this->ldap_connect();
1022 $userdn = $this->ldap_find_userdn($ldapconnection, $extusername);
1023 switch ($this->config->user_type) {
1025 $newinfo['loginDisabled'] = 'FALSE';
1029 // Remember that we add a '*' character in front of the
1030 // external password string to 'disable' the account. We just
1031 // need to remove it.
1032 $sr = ldap_read($ldapconnection, $userdn, '(objectClass=*)',
1033 array('userPassword'));
1034 $info = ldap_get_entries($ldapconnection, $sr);
1035 $info[0] = array_change_key_case($info[0], CASE_LOWER);
1036 $newinfo['userPassword'] = ltrim($info[0]['userpassword'][0], '*');
1039 // We need to unset the ACCOUNTDISABLE bit in the
1040 // userAccountControl attribute ( see
1041 // http://support.microsoft.com/kb/305144 )
1042 $sr = ldap_read($ldapconnection, $userdn, '(objectClass=*)',
1043 array('userAccountControl'));
1044 $info = ldap_get_entries($ldapconnection, $sr);
1045 $info[0] = array_change_key_case($info[0], CASE_LOWER);
1046 $newinfo['userAccountControl'] = $info[0]['useraccountcontrol'][0]
1047 & (~AUTH_AD_ACCOUNTDISABLE);
1050 print_error('user_activatenotsupportusertype', 'auth_ldap', '', $this->config->user_type_name);
1052 $result = ldap_modify($ldapconnection, $userdn, $newinfo);
1053 $this->ldap_close();
1058 * Returns true if user should be coursecreator.
1060 * @param mixed $username username (without system magic quotes)
1061 * @return mixed result null if course creators is not configured, boolean otherwise.
1063 function iscreator($username) {
1064 if (empty($this->config->creators) or empty($this->config->memberattribute)) {
1068 $extusername = textlib::convert($username, 'utf-8', $this->config->ldapencoding);
1070 $ldapconnection = $this->ldap_connect();
1072 if ($this->config->memberattribute_isdn) {
1073 if(!($userid = $this->ldap_find_userdn($ldapconnection, $extusername))) {
1077 $userid = $extusername;
1080 $group_dns = explode(';', $this->config->creators);
1081 $creator = ldap_isgroupmember($ldapconnection, $userid, $group_dns, $this->config->memberattribute);
1083 $this->ldap_close();
1089 * Called when the user record is updated.
1091 * Modifies user in external LDAP server. It takes olduser (before
1092 * changes) and newuser (after changes) compares information and
1093 * saves modified information to external LDAP server.
1095 * @param mixed $olduser Userobject before modifications (without system magic quotes)
1096 * @param mixed $newuser Userobject new modified userobject (without system magic quotes)
1097 * @return boolean result
1100 function user_update($olduser, $newuser) {
1103 if (isset($olduser->username) and isset($newuser->username) and $olduser->username != $newuser->username) {
1104 error_log($this->errorlogtag.get_string('renamingnotallowed', 'auth_ldap'));
1108 if (isset($olduser->auth) and $olduser->auth != $this->authtype) {
1109 return true; // just change auth and skip update
1112 $attrmap = $this->ldap_attributes();
1113 // Before doing anything else, make sure we really need to update anything
1114 // in the external LDAP server.
1115 $update_external = false;
1116 foreach ($attrmap as $key => $ldapkeys) {
1117 if (!empty($this->config->{'field_updateremote_'.$key})) {
1118 $update_external = true;
1122 if (!$update_external) {
1126 $extoldusername = textlib::convert($olduser->username, 'utf-8', $this->config->ldapencoding);
1128 $ldapconnection = $this->ldap_connect();
1130 $search_attribs = array();
1131 foreach ($attrmap as $key => $values) {
1132 if (!is_array($values)) {
1133 $values = array($values);
1135 foreach ($values as $value) {
1136 if (!in_array($value, $search_attribs)) {
1137 array_push($search_attribs, $value);
1142 if(!($user_dn = $this->ldap_find_userdn($ldapconnection, $extoldusername))) {
1146 $user_info_result = ldap_read($ldapconnection, $user_dn, '(objectClass=*)', $search_attribs);
1147 if ($user_info_result) {
1148 $user_entry = ldap_get_entries_moodle($ldapconnection, $user_info_result);
1149 if (empty($user_entry)) {
1150 $attribs = join (', ', $search_attribs);
1151 error_log($this->errorlogtag.get_string('updateusernotfound', 'auth_ldap',
1152 array('userdn'=>$user_dn,
1153 'attribs'=>$attribs)));
1154 return false; // old user not found!
1155 } else if (count($user_entry) > 1) {
1156 error_log($this->errorlogtag.get_string('morethanoneuser', 'auth_ldap'));
1160 $user_entry = array_change_key_case($user_entry[0], CASE_LOWER);
1162 foreach ($attrmap as $key => $ldapkeys) {
1164 // Only process if the moodle field ($key) has changed and we
1165 // are set to update LDAP with it
1166 $customprofilefield = 'profile_field_' . $key;
1167 if (isset($olduser->$key) and isset($newuser->$key)
1168 and ($olduser->$key !== $newuser->$key)) {
1169 $profilefield = $key;
1170 } else if (isset($olduser->$customprofilefield) && isset($newuser->$customprofilefield)
1171 && $olduser->$customprofilefield !== $newuser->$customprofilefield) {
1172 $profilefield = $customprofilefield;
1175 if (!empty($profilefield) && !empty($this->config->{'field_updateremote_' . $key})) {
1176 // For ldap values that could be in more than one
1177 // ldap key, we will do our best to match
1178 // where they came from
1181 if (!is_array($ldapkeys)) {
1182 $ldapkeys = array($ldapkeys);
1184 if (count($ldapkeys) < 2) {
1188 $nuvalue = textlib::convert($newuser->$profilefield, 'utf-8', $this->config->ldapencoding);
1189 empty($nuvalue) ? $nuvalue = array() : $nuvalue;
1190 $ouvalue = textlib::convert($olduser->$profilefield, 'utf-8', $this->config->ldapencoding);
1192 foreach ($ldapkeys as $ldapkey) {
1193 $ldapkey = $ldapkey;
1194 $ldapvalue = $user_entry[$ldapkey][0];
1196 // Skip update if the values already match
1197 if ($nuvalue !== $ldapvalue) {
1198 // This might fail due to schema validation
1199 if (@ldap_modify($ldapconnection, $user_dn, array($ldapkey => $nuvalue))) {
1202 error_log($this->errorlogtag.get_string ('updateremfail', 'auth_ldap',
1203 array('errno'=>ldap_errno($ldapconnection),
1204 'errstring'=>ldap_err2str(ldap_errno($ldapconnection)),
1206 'ouvalue'=>$ouvalue,
1207 'nuvalue'=>$nuvalue)));
1212 // Ambiguous. Value empty before in Moodle (and LDAP) - use
1213 // 1st ldap candidate field, no need to guess
1214 if ($ouvalue === '') { // value empty before - use 1st ldap candidate
1215 // This might fail due to schema validation
1216 if (@ldap_modify($ldapconnection, $user_dn, array($ldapkey => $nuvalue))) {
1220 error_log($this->errorlogtag.get_string ('updateremfail', 'auth_ldap',
1221 array('errno'=>ldap_errno($ldapconnection),
1222 'errstring'=>ldap_err2str(ldap_errno($ldapconnection)),
1224 'ouvalue'=>$ouvalue,
1225 'nuvalue'=>$nuvalue)));
1230 // We found which ldap key to update!
1231 if ($ouvalue !== '' and $ouvalue === $ldapvalue ) {
1232 // This might fail due to schema validation
1233 if (@ldap_modify($ldapconnection, $user_dn, array($ldapkey => $nuvalue))) {
1237 error_log($this->errorlogtag.get_string ('updateremfail', 'auth_ldap',
1238 array('errno'=>ldap_errno($ldapconnection),
1239 'errstring'=>ldap_err2str(ldap_errno($ldapconnection)),
1241 'ouvalue'=>$ouvalue,
1242 'nuvalue'=>$nuvalue)));
1249 if ($ambiguous and !$changed) {
1250 error_log($this->errorlogtag.get_string ('updateremfailamb', 'auth_ldap',
1252 'ouvalue'=>$ouvalue,
1253 'nuvalue'=>$nuvalue)));
1258 error_log($this->errorlogtag.get_string ('usernotfound', 'auth_ldap'));
1259 $this->ldap_close();
1263 $this->ldap_close();
1269 * Changes userpassword in LDAP
1271 * Called when the user password is updated. It assumes it is
1272 * called by an admin or that you've otherwise checked the user's
1275 * @param object $user User table object
1276 * @param string $newpassword Plaintext password (not crypted/md5'ed)
1277 * @return boolean result
1280 function user_update_password($user, $newpassword) {
1284 $username = $user->username;
1286 $extusername = textlib::convert($username, 'utf-8', $this->config->ldapencoding);
1287 $extpassword = textlib::convert($newpassword, 'utf-8', $this->config->ldapencoding);
1289 switch ($this->config->passtype) {
1291 $extpassword = '{MD5}' . base64_encode(pack('H*', md5($extpassword)));
1294 $extpassword = '{SHA}' . base64_encode(pack('H*', sha1($extpassword)));
1301 $ldapconnection = $this->ldap_connect();
1303 $user_dn = $this->ldap_find_userdn($ldapconnection, $extusername);
1306 error_log($this->errorlogtag.get_string ('nodnforusername', 'auth_ldap', $user->username));
1310 switch ($this->config->user_type) {
1313 $result = ldap_modify($ldapconnection, $user_dn, array('userPassword' => $extpassword));
1315 error_log($this->errorlogtag.get_string ('updatepasserror', 'auth_ldap',
1316 array('errno'=>ldap_errno($ldapconnection),
1317 'errstring'=>ldap_err2str(ldap_errno($ldapconnection)))));
1319 // Update password expiration time, grace logins count
1320 $search_attribs = array($this->config->expireattr, 'passwordExpirationInterval', 'loginGraceLimit');
1321 $sr = ldap_read($ldapconnection, $user_dn, '(objectClass=*)', $search_attribs);
1323 $entry = ldap_get_entries_moodle($ldapconnection, $sr);
1324 $info = array_change_key_case($entry[0], CASE_LOWER);
1325 $newattrs = array();
1326 if (!empty($info[$this->config->expireattr][0])) {
1327 // Set expiration time only if passwordExpirationInterval is defined
1328 if (!empty($info['passwordexpirationinterval'][0])) {
1329 $expirationtime = time() + $info['passwordexpirationinterval'][0];
1330 $ldapexpirationtime = $this->ldap_unix2expirationtime($expirationtime);
1331 $newattrs['passwordExpirationTime'] = $ldapexpirationtime;
1334 // Set gracelogin count
1335 if (!empty($info['logingracelimit'][0])) {
1336 $newattrs['loginGraceRemaining']= $info['logingracelimit'][0];
1339 // Store attribute changes in LDAP
1340 $result = ldap_modify($ldapconnection, $user_dn, $newattrs);
1342 error_log($this->errorlogtag.get_string ('updatepasserrorexpiregrace', 'auth_ldap',
1343 array('errno'=>ldap_errno($ldapconnection),
1344 'errstring'=>ldap_err2str(ldap_errno($ldapconnection)))));
1349 error_log($this->errorlogtag.get_string ('updatepasserrorexpire', 'auth_ldap',
1350 array('errno'=>ldap_errno($ldapconnection),
1351 'errstring'=>ldap_err2str(ldap_errno($ldapconnection)))));
1356 // Passwords in Active Directory must be encoded as Unicode
1357 // strings (UCS-2 Little Endian format) and surrounded with
1358 // double quotes. See http://support.microsoft.com/?kbid=269190
1359 if (!function_exists('mb_convert_encoding')) {
1360 error_log($this->errorlogtag.get_string ('needmbstring', 'auth_ldap'));
1363 $extpassword = mb_convert_encoding('"'.$extpassword.'"', "UCS-2LE", $this->config->ldapencoding);
1364 $result = ldap_modify($ldapconnection, $user_dn, array('unicodePwd' => $extpassword));
1366 error_log($this->errorlogtag.get_string ('updatepasserror', 'auth_ldap',
1367 array('errno'=>ldap_errno($ldapconnection),
1368 'errstring'=>ldap_err2str(ldap_errno($ldapconnection)))));
1373 // Send LDAP the password in cleartext, it will md5 it itself
1374 $result = ldap_modify($ldapconnection, $user_dn, array('userPassword' => $extpassword));
1376 error_log($this->errorlogtag.get_string ('updatepasserror', 'auth_ldap',
1377 array('errno'=>ldap_errno($ldapconnection),
1378 'errstring'=>ldap_err2str(ldap_errno($ldapconnection)))));
1383 $this->ldap_close();
1388 * Take expirationtime and return it as unix timestamp in seconds
1390 * Takes expiration timestamp as read from LDAP and returns it as unix timestamp in seconds
1391 * Depends on $this->config->user_type variable
1393 * @param mixed time Time stamp read from LDAP as it is.
1394 * @param string $ldapconnection Only needed for Active Directory.
1395 * @param string $user_dn User distinguished name for the user we are checking password expiration (only needed for Active Directory).
1398 function ldap_expirationtime2unix ($time, $ldapconnection, $user_dn) {
1400 switch ($this->config->user_type) {
1402 $yr=substr($time, 0, 4);
1403 $mo=substr($time, 4, 2);
1404 $dt=substr($time, 6, 2);
1405 $hr=substr($time, 8, 2);
1406 $min=substr($time, 10, 2);
1407 $sec=substr($time, 12, 2);
1408 $result = mktime($hr, $min, $sec, $mo, $dt, $yr);
1412 $result = $time * DAYSECS; // The shadowExpire contains the number of DAYS between 01/01/1970 and the actual expiration date
1415 $result = $this->ldap_get_ad_pwdexpire($time, $ldapconnection, $user_dn);
1418 print_error('auth_ldap_usertypeundefined', 'auth_ldap');
1424 * Takes unix timestamp and returns it formated for storing in LDAP
1426 * @param integer unix time stamp
1428 function ldap_unix2expirationtime($time) {
1430 switch ($this->config->user_type) {
1432 $result=date('YmdHis', $time).'Z';
1436 $result = $time ; // Already in correct format
1439 print_error('auth_ldap_usertypeundefined2', 'auth_ldap');
1446 * Returns user attribute mappings between moodle and LDAP
1451 function ldap_attributes () {
1452 $moodleattributes = array();
1453 // If we have custom fields then merge them with user fields.
1454 $customfields = $this->get_custom_user_profile_fields();
1455 if (!empty($customfields) && !empty($this->userfields)) {
1456 $userfields = array_merge($this->userfields, $customfields);
1458 $userfields = $this->userfields;
1461 foreach ($userfields as $field) {
1462 if (!empty($this->config->{"field_map_$field"})) {
1463 $moodleattributes[$field] = textlib::strtolower(trim($this->config->{"field_map_$field"}));
1464 if (preg_match('/,/', $moodleattributes[$field])) {
1465 $moodleattributes[$field] = explode(',', $moodleattributes[$field]); // split ?
1469 $moodleattributes['username'] = textlib::strtolower(trim($this->config->user_attribute));
1470 return $moodleattributes;
1474 * Returns all usernames from LDAP
1476 * @param $filter An LDAP search filter to select desired users
1477 * @return array of LDAP user names converted to UTF-8
1479 function ldap_get_userlist($filter='*') {
1482 $ldapconnection = $this->ldap_connect();
1484 if ($filter == '*') {
1485 $filter = '(&('.$this->config->user_attribute.'=*)'.$this->config->objectclass.')';
1488 $contexts = explode(';', $this->config->contexts);
1489 if (!empty($this->config->create_context)) {
1490 array_push($contexts, $this->config->create_context);
1493 $ldap_pagedresults = ldap_paged_results_supported($this->config->ldap_version);
1494 foreach ($contexts as $context) {
1495 $context = trim($context);
1496 if (empty($context)) {
1501 if ($ldap_pagedresults) {
1502 ldap_control_paged_result($ldapconnection, $this->config->pagesize, true, $ldap_cookie);
1504 if ($this->config->search_sub) {
1505 // Use ldap_search to find first user from subtree.
1506 $ldap_result = ldap_search($ldapconnection, $context, $filter, array($this->config->user_attribute));
1508 // Search only in this context.
1509 $ldap_result = ldap_list($ldapconnection, $context, $filter, array($this->config->user_attribute));
1514 if ($ldap_pagedresults) {
1515 ldap_control_paged_result_response($ldapconnection, $ldap_result, $ldap_cookie);
1517 $users = ldap_get_entries_moodle($ldapconnection, $ldap_result);
1518 // Add found users to list.
1519 for ($i = 0; $i < count($users); $i++) {
1520 $extuser = textlib::convert($users[$i][$this->config->user_attribute][0],
1521 $this->config->ldapencoding, 'utf-8');
1522 array_push($fresult, $extuser);
1524 unset($ldap_result); // Free mem.
1525 } while ($ldap_pagedresults && !empty($ldap_cookie));
1528 // If paged results were used, make sure the current connection is completely closed
1529 $this->ldap_close($ldap_pagedresults);
1534 * Indicates if password hashes should be stored in local moodle database.
1536 * @return bool true means flag 'not_cached' stored instead of password hash
1538 function prevent_local_passwords() {
1539 return !empty($this->config->preventpassindb);
1543 * Returns true if this authentication plugin is 'internal'.
1547 function is_internal() {
1552 * Returns true if this authentication plugin can change the user's
1557 function can_change_password() {
1558 return !empty($this->config->stdchangepassword) or !empty($this->config->changepasswordurl);
1562 * Returns the URL for changing the user's password, or empty if the default can
1565 * @return moodle_url
1567 function change_password_url() {
1568 if (empty($this->config->stdchangepassword)) {
1569 return new moodle_url($this->config->changepasswordurl);
1576 * Will get called before the login page is shownr. Ff NTLM SSO
1577 * is enabled, and the user is in the right network, we'll redirect
1578 * to the magic NTLM page for SSO...
1581 function loginpage_hook() {
1582 global $CFG, $SESSION;
1584 // HTTPS is potentially required
1585 //httpsrequired(); - this must be used before setting the URL, it is already done on the login/index.php
1587 if (($_SERVER['REQUEST_METHOD'] === 'GET' // Only on initial GET of loginpage
1588 || ($_SERVER['REQUEST_METHOD'] === 'POST'
1589 && (get_referer() != strip_querystring(qualified_me()))))
1590 // Or when POSTed from another place
1592 && !empty($this->config->ntlmsso_enabled) // SSO enabled
1593 && !empty($this->config->ntlmsso_subnet) // have a subnet to test for
1594 && empty($_GET['authldap_skipntlmsso']) // haven't failed it yet
1595 && (isguestuser() || !isloggedin()) // guestuser or not-logged-in users
1596 && address_in_subnet(getremoteaddr(), $this->config->ntlmsso_subnet)) {
1598 // First, let's remember where we were trying to get to before we got here
1599 if (empty($SESSION->wantsurl)) {
1600 $SESSION->wantsurl = (array_key_exists('HTTP_REFERER', $_SERVER) &&
1601 $_SERVER['HTTP_REFERER'] != $CFG->wwwroot &&
1602 $_SERVER['HTTP_REFERER'] != $CFG->wwwroot.'/' &&
1603 $_SERVER['HTTP_REFERER'] != $CFG->httpswwwroot.'/login/' &&
1604 $_SERVER['HTTP_REFERER'] != $CFG->httpswwwroot.'/login/index.php')
1605 ? $_SERVER['HTTP_REFERER'] : NULL;
1608 // Now start the whole NTLM machinery.
1609 if(!empty($this->config->ntlmsso_ie_fastpath)) {
1610 // Shortcut for IE browsers: skip the attempt page
1611 if(check_browser_version('MSIE')) {
1612 $sesskey = sesskey();
1613 redirect($CFG->wwwroot.'/auth/ldap/ntlmsso_magic.php?sesskey='.$sesskey);
1615 redirect($CFG->httpswwwroot.'/login/index.php?authldap_skipntlmsso=1');
1618 redirect($CFG->wwwroot.'/auth/ldap/ntlmsso_attempt.php');
1622 // No NTLM SSO, Use the normal login page instead.
1624 // If $SESSION->wantsurl is empty and we have a 'Referer:' header, the login
1625 // page insists on redirecting us to that page after user validation. If
1626 // we clicked on the redirect link at the ntlmsso_finish.php page (instead
1627 // of waiting for the redirection to happen) then we have a 'Referer:' header
1628 // we don't want to use at all. As we can't get rid of it, just point
1629 // $SESSION->wantsurl to $CFG->wwwroot (after all, we came from there).
1630 if (empty($SESSION->wantsurl)
1631 && (get_referer() == $CFG->httpswwwroot.'/auth/ldap/ntlmsso_finish.php')) {
1633 $SESSION->wantsurl = $CFG->wwwroot;
1638 * To be called from a page running under NTLM's
1639 * "Integrated Windows Authentication".
1641 * If successful, it will set a special "cookie" (not an HTTP cookie!)
1642 * in cache_flags under the $this->pluginconfig/ntlmsess "plugin" and return true.
1643 * The "cookie" will be picked up by ntlmsso_finish() to complete the
1646 * On failure it will return false for the caller to display an appropriate
1647 * error message (probably saying that Integrated Windows Auth isn't enabled!)
1649 * NOTE that this code will execute under the OS user credentials,
1650 * so we MUST avoid dealing with files -- such as session files.
1651 * (The caller should define('NO_MOODLE_COOKIES', true) before including config.php)
1654 function ntlmsso_magic($sesskey) {
1655 if (isset($_SERVER['REMOTE_USER']) && !empty($_SERVER['REMOTE_USER'])) {
1657 // HTTP __headers__ seem to be sent in ISO-8859-1 encoding
1658 // (according to my reading of RFC-1945, RFC-2616 and RFC-2617 and
1659 // my local tests), so we need to convert the REMOTE_USER value
1660 // (i.e., what we got from the HTTP WWW-Authenticate header) into UTF-8
1661 $username = textlib::convert($_SERVER['REMOTE_USER'], 'iso-8859-1', 'utf-8');
1663 switch ($this->config->ntlmsso_type) {
1665 // The format is now configurable, so try to extract the username
1666 $username = $this->get_ntlm_remote_user($username);
1667 if (empty($username)) {
1672 // Format is username@DOMAIN
1673 $username = substr($username, 0, strpos($username, '@'));
1676 error_log($this->errorlogtag.get_string ('ntlmsso_unknowntype', 'auth_ldap'));
1677 return false; // Should never happen!
1680 $username = textlib::strtolower($username); // Compatibility hack
1681 set_cache_flag($this->pluginconfig.'/ntlmsess', $sesskey, $username, AUTH_NTLMTIMEOUT);
1688 * Find the session set by ntlmsso_magic(), validate it and
1689 * call authenticate_user_login() to authenticate the user through
1690 * the auth machinery.
1692 * It is complemented by a similar check in user_login().
1694 * If it succeeds, it never returns.
1697 function ntlmsso_finish() {
1698 global $CFG, $USER, $SESSION;
1701 $cf = get_cache_flags($this->pluginconfig.'/ntlmsess');
1702 if (!isset($cf[$key]) || $cf[$key] === '') {
1705 $username = $cf[$key];
1706 // Here we want to trigger the whole authentication machinery
1707 // to make sure no step is bypassed...
1708 $user = authenticate_user_login($username, $key);
1710 add_to_log(SITEID, 'user', 'login', "view.php?id=$USER->id&course=".SITEID,
1711 $user->id, 0, $user->id);
1712 complete_user_login($user);
1714 // Cleanup the key to prevent reuse...
1715 // and to allow re-logins with normal credentials
1716 unset_cache_flag($this->pluginconfig.'/ntlmsess', $key);
1719 if (user_not_fully_set_up($USER)) {
1720 $urltogo = $CFG->wwwroot.'/user/edit.php';
1721 // We don't delete $SESSION->wantsurl yet, so we get there later
1722 } else if (isset($SESSION->wantsurl) and (strpos($SESSION->wantsurl, $CFG->wwwroot) === 0)) {
1723 $urltogo = $SESSION->wantsurl; // Because it's an address in this site
1724 unset($SESSION->wantsurl);
1726 // No wantsurl stored or external - go to homepage
1727 $urltogo = $CFG->wwwroot.'/';
1728 unset($SESSION->wantsurl);
1732 // Should never reach here.
1737 * Sync roles for this user
1739 * @param $user object user object (without system magic quotes)
1741 function sync_roles($user) {
1742 $iscreator = $this->iscreator($user->username);
1743 if ($iscreator === null) {
1744 return; // Nothing to sync - creators not configured
1747 if ($roles = get_archetype_roles('coursecreator')) {
1748 $creatorrole = array_shift($roles); // We can only use one, let's use the first one
1749 $systemcontext = context_system::instance();
1751 if ($iscreator) { // Following calls will not create duplicates
1752 role_assign($creatorrole->id, $user->id, $systemcontext->id, $this->roleauth);
1754 // Unassign only if previously assigned by this plugin!
1755 role_unassign($creatorrole->id, $user->id, $systemcontext->id, $this->roleauth);
1761 * Prints a form for configuring this authentication plugin.
1763 * This function is called from admin/auth.php, and outputs a full page with
1764 * a form for configuring this plugin.
1766 * @param array $page An object containing all the data for this page.
1768 function config_form($config, $err, $user_fields) {
1769 global $CFG, $OUTPUT;
1771 if (!function_exists('ldap_connect')) { // Is php-ldap really there?
1772 echo $OUTPUT->notification(get_string('auth_ldap_noextension', 'auth_ldap'));
1776 include($CFG->dirroot.'/auth/ldap/config.html');
1780 * Processes and stores configuration data for this authentication plugin.
1782 function process_config($config) {
1783 // Set to defaults if undefined
1784 if (!isset($config->host_url)) {
1785 $config->host_url = '';
1787 if (!isset($config->start_tls)) {
1788 $config->start_tls = false;
1790 if (empty($config->ldapencoding)) {
1791 $config->ldapencoding = 'utf-8';
1793 if (!isset($config->pagesize)) {
1794 $config->pagesize = LDAP_DEFAULT_PAGESIZE;
1796 if (!isset($config->contexts)) {
1797 $config->contexts = '';
1799 if (!isset($config->user_type)) {
1800 $config->user_type = 'default';
1802 if (!isset($config->user_attribute)) {
1803 $config->user_attribute = '';
1805 if (!isset($config->search_sub)) {
1806 $config->search_sub = '';
1808 if (!isset($config->opt_deref)) {
1809 $config->opt_deref = LDAP_DEREF_NEVER;
1811 if (!isset($config->preventpassindb)) {
1812 $config->preventpassindb = 0;
1814 if (!isset($config->bind_dn)) {
1815 $config->bind_dn = '';
1817 if (!isset($config->bind_pw)) {
1818 $config->bind_pw = '';
1820 if (!isset($config->ldap_version)) {
1821 $config->ldap_version = '3';
1823 if (!isset($config->objectclass)) {
1824 $config->objectclass = '';
1826 if (!isset($config->memberattribute)) {
1827 $config->memberattribute = '';
1829 if (!isset($config->memberattribute_isdn)) {
1830 $config->memberattribute_isdn = '';
1832 if (!isset($config->creators)) {
1833 $config->creators = '';
1835 if (!isset($config->create_context)) {
1836 $config->create_context = '';
1838 if (!isset($config->expiration)) {
1839 $config->expiration = '';
1841 if (!isset($config->expiration_warning)) {
1842 $config->expiration_warning = '10';
1844 if (!isset($config->expireattr)) {
1845 $config->expireattr = '';
1847 if (!isset($config->gracelogins)) {
1848 $config->gracelogins = '';
1850 if (!isset($config->graceattr)) {
1851 $config->graceattr = '';
1853 if (!isset($config->auth_user_create)) {
1854 $config->auth_user_create = '';
1856 if (!isset($config->forcechangepassword)) {
1857 $config->forcechangepassword = 0;
1859 if (!isset($config->stdchangepassword)) {
1860 $config->stdchangepassword = 0;
1862 if (!isset($config->passtype)) {
1863 $config->passtype = 'plaintext';
1865 if (!isset($config->changepasswordurl)) {
1866 $config->changepasswordurl = '';
1868 if (!isset($config->removeuser)) {
1869 $config->removeuser = AUTH_REMOVEUSER_KEEP;
1871 if (!isset($config->ntlmsso_enabled)) {
1872 $config->ntlmsso_enabled = 0;
1874 if (!isset($config->ntlmsso_subnet)) {
1875 $config->ntlmsso_subnet = '';
1877 if (!isset($config->ntlmsso_ie_fastpath)) {
1878 $config->ntlmsso_ie_fastpath = 0;
1880 if (!isset($config->ntlmsso_type)) {
1881 $config->ntlmsso_type = 'ntlm';
1883 if (!isset($config->ntlmsso_remoteuserformat)) {
1884 $config->ntlmsso_remoteuserformat = '';
1887 // Try to remove duplicates before storing the contexts (to avoid problems in sync_users()).
1888 $config->contexts = explode(';', $config->contexts);
1889 $config->contexts = array_map(create_function('$x', 'return textlib::strtolower(trim($x));'),
1891 $config->contexts = implode(';', array_unique($config->contexts));
1894 set_config('host_url', trim($config->host_url), $this->pluginconfig);
1895 set_config('start_tls', $config->start_tls, $this->pluginconfig);
1896 set_config('ldapencoding', trim($config->ldapencoding), $this->pluginconfig);
1897 set_config('pagesize', (int)trim($config->pagesize), $this->pluginconfig);
1898 set_config('contexts', $config->contexts, $this->pluginconfig);
1899 set_config('user_type', textlib::strtolower(trim($config->user_type)), $this->pluginconfig);
1900 set_config('user_attribute', textlib::strtolower(trim($config->user_attribute)), $this->pluginconfig);
1901 set_config('search_sub', $config->search_sub, $this->pluginconfig);
1902 set_config('opt_deref', $config->opt_deref, $this->pluginconfig);
1903 set_config('preventpassindb', $config->preventpassindb, $this->pluginconfig);
1904 set_config('bind_dn', trim($config->bind_dn), $this->pluginconfig);
1905 set_config('bind_pw', $config->bind_pw, $this->pluginconfig);
1906 set_config('ldap_version', $config->ldap_version, $this->pluginconfig);
1907 set_config('objectclass', trim($config->objectclass), $this->pluginconfig);
1908 set_config('memberattribute', textlib::strtolower(trim($config->memberattribute)), $this->pluginconfig);
1909 set_config('memberattribute_isdn', $config->memberattribute_isdn, $this->pluginconfig);
1910 set_config('creators', trim($config->creators), $this->pluginconfig);
1911 set_config('create_context', trim($config->create_context), $this->pluginconfig);
1912 set_config('expiration', $config->expiration, $this->pluginconfig);
1913 set_config('expiration_warning', trim($config->expiration_warning), $this->pluginconfig);
1914 set_config('expireattr', textlib::strtolower(trim($config->expireattr)), $this->pluginconfig);
1915 set_config('gracelogins', $config->gracelogins, $this->pluginconfig);
1916 set_config('graceattr', textlib::strtolower(trim($config->graceattr)), $this->pluginconfig);
1917 set_config('auth_user_create', $config->auth_user_create, $this->pluginconfig);
1918 set_config('forcechangepassword', $config->forcechangepassword, $this->pluginconfig);
1919 set_config('stdchangepassword', $config->stdchangepassword, $this->pluginconfig);
1920 set_config('passtype', $config->passtype, $this->pluginconfig);
1921 set_config('changepasswordurl', trim($config->changepasswordurl), $this->pluginconfig);
1922 set_config('removeuser', $config->removeuser, $this->pluginconfig);
1923 set_config('ntlmsso_enabled', (int)$config->ntlmsso_enabled, $this->pluginconfig);
1924 set_config('ntlmsso_subnet', trim($config->ntlmsso_subnet), $this->pluginconfig);
1925 set_config('ntlmsso_ie_fastpath', (int)$config->ntlmsso_ie_fastpath, $this->pluginconfig);
1926 set_config('ntlmsso_type', $config->ntlmsso_type, 'auth/ldap');
1927 set_config('ntlmsso_remoteuserformat', trim($config->ntlmsso_remoteuserformat), 'auth/ldap');
1933 * Get password expiration time for a given user from Active Directory
1935 * @param string $pwdlastset The time last time we changed the password.
1936 * @param resource $lcapconn The open LDAP connection.
1937 * @param string $user_dn The distinguished name of the user we are checking.
1939 * @return string $unixtime
1941 function ldap_get_ad_pwdexpire($pwdlastset, $ldapconn, $user_dn){
1944 if (!function_exists('bcsub')) {
1945 error_log($this->errorlogtag.get_string ('needbcmath', 'auth_ldap'));
1949 // If UF_DONT_EXPIRE_PASSWD flag is set in user's
1950 // userAccountControl attribute, the password doesn't expire.
1951 $sr = ldap_read($ldapconn, $user_dn, '(objectClass=*)',
1952 array('userAccountControl'));
1954 error_log($this->errorlogtag.get_string ('useracctctrlerror', 'auth_ldap', $user_dn));
1955 // Don't expire password, as we are not sure if it has to be
1960 $entry = ldap_get_entries_moodle($ldapconn, $sr);
1961 $info = array_change_key_case($entry[0], CASE_LOWER);
1962 $useraccountcontrol = $info['useraccountcontrol'][0];
1963 if ($useraccountcontrol & UF_DONT_EXPIRE_PASSWD) {
1964 // Password doesn't expire.
1968 // If pwdLastSet is zero, the user must change his/her password now
1969 // (unless UF_DONT_EXPIRE_PASSWD flag is set, but we already
1970 // tested this above)
1971 if ($pwdlastset === '0') {
1972 // Password has expired
1976 // ----------------------------------------------------------------
1977 // Password expiration time in Active Directory is the composition of
1980 // - User's pwdLastSet attribute, that stores the last time
1981 // the password was changed.
1983 // - Domain's maxPwdAge attribute, that sets how long
1984 // passwords last in this domain.
1986 // We already have the first value (passed in as a parameter). We
1987 // need to get the second one. As we don't know the domain DN, we
1988 // have to query rootDSE's defaultNamingContext attribute to get
1989 // it. Then we have to query that DN's maxPwdAge attribute to get
1992 // Once we have both values, we just need to combine them. But MS
1993 // chose to use a different base and unit for time measurements.
1994 // So we need to convert the values to Unix timestamps (see
1996 // ----------------------------------------------------------------
1998 $sr = ldap_read($ldapconn, ROOTDSE, '(objectClass=*)',
1999 array('defaultNamingContext'));
2001 error_log($this->errorlogtag.get_string ('rootdseerror', 'auth_ldap'));
2005 $entry = ldap_get_entries_moodle($ldapconn, $sr);
2006 $info = array_change_key_case($entry[0], CASE_LOWER);
2007 $domaindn = $info['defaultnamingcontext'][0];
2009 $sr = ldap_read ($ldapconn, $domaindn, '(objectClass=*)',
2010 array('maxPwdAge'));
2011 $entry = ldap_get_entries_moodle($ldapconn, $sr);
2012 $info = array_change_key_case($entry[0], CASE_LOWER);
2013 $maxpwdage = $info['maxpwdage'][0];
2015 // ----------------------------------------------------------------
2016 // MSDN says that "pwdLastSet contains the number of 100 nanosecond
2017 // intervals since January 1, 1601 (UTC), stored in a 64 bit integer".
2019 // According to Perl's Date::Manip, the number of seconds between
2020 // this date and Unix epoch is 11644473600. So we have to
2021 // substract this value to calculate a Unix time, once we have
2022 // scaled pwdLastSet to seconds. This is the script used to
2023 // calculate the value shown above:
2025 // #!/usr/bin/perl -w
2029 // $date1 = ParseDate ("160101010000 UTC");
2030 // $date2 = ParseDate ("197001010000 UTC");
2031 // $delta = DateCalc($date1, $date2, \$err);
2032 // $secs = Delta_Format($delta, 0, "%st");
2033 // print "$secs \n";
2035 // MSDN also says that "maxPwdAge is stored as a large integer that
2036 // represents the number of 100 nanosecond intervals from the time
2037 // the password was set before the password expires." We also need
2038 // to scale this to seconds. Bear in mind that this value is stored
2039 // as a _negative_ quantity (at least in my AD domain).
2041 // As a last remark, if the low 32 bits of maxPwdAge are equal to 0,
2042 // the maximum password age in the domain is set to 0, which means
2043 // passwords do not expire (see
2044 // http://msdn2.microsoft.com/en-us/library/ms974598.aspx)
2046 // As the quantities involved are too big for PHP integers, we
2047 // need to use BCMath functions to work with arbitrary precision
2049 // ----------------------------------------------------------------
2051 // If the low order 32 bits are 0, then passwords do not expire in
2052 // the domain. Just do '$maxpwdage mod 2^32' and check the result
2053 // (2^32 = 4294967296)
2054 if (bcmod ($maxpwdage, 4294967296) === '0') {
2058 // Add up pwdLastSet and maxPwdAge to get password expiration
2059 // time, in MS time units. Remember maxPwdAge is stored as a
2060 // _negative_ quantity, so we need to substract it in fact.
2061 $pwdexpire = bcsub ($pwdlastset, $maxpwdage);
2063 // Scale the result to convert it to Unix time units and return
2065 return bcsub( bcdiv($pwdexpire, '10000000'), '11644473600');
2069 * Connect to the LDAP server, using the plugin configured
2070 * settings. It's actually a wrapper around ldap_connect_moodle()
2072 * @return resource A valid LDAP connection (or dies if it can't connect)
2074 function ldap_connect() {
2075 // Cache ldap connections. They are expensive to set up
2076 // and can drain the TCP/IP ressources on the server if we
2077 // are syncing a lot of users (as we try to open a new connection
2078 // to get the user details). This is the least invasive way
2079 // to reuse existing connections without greater code surgery.
2080 if(!empty($this->ldapconnection)) {
2082 return $this->ldapconnection;
2085 if($ldapconnection = ldap_connect_moodle($this->config->host_url, $this->config->ldap_version,
2086 $this->config->user_type, $this->config->bind_dn,
2087 $this->config->bind_pw, $this->config->opt_deref,
2088 $debuginfo, $this->config->start_tls)) {
2089 $this->ldapconns = 1;
2090 $this->ldapconnection = $ldapconnection;
2091 return $ldapconnection;
2094 print_error('auth_ldap_noconnect_all', 'auth_ldap', '', $debuginfo);
2098 * Disconnects from a LDAP server
2100 * @param force boolean Forces closing the real connection to the LDAP server, ignoring any
2101 * cached connections. This is needed when we've used paged results
2102 * and want to use normal results again.
2104 function ldap_close($force=false) {
2106 if (($this->ldapconns == 0) || ($force)) {
2107 $this->ldapconns = 0;
2108 @ldap_close($this->ldapconnection);
2109 unset($this->ldapconnection);
2114 * Search specified contexts for username and return the user dn
2115 * like: cn=username,ou=suborg,o=org. It's actually a wrapper
2116 * around ldap_find_userdn().
2118 * @param resource $ldapconnection a valid LDAP connection
2119 * @param string $extusername the username to search (in external LDAP encoding, no db slashes)
2120 * @return mixed the user dn (external LDAP encoding) or false
2122 function ldap_find_userdn($ldapconnection, $extusername) {
2123 $ldap_contexts = explode(';', $this->config->contexts);
2124 if (!empty($this->config->create_context)) {
2125 array_push($ldap_contexts, $this->config->create_context);
2128 return ldap_find_userdn($ldapconnection, $extusername, $ldap_contexts, $this->config->objectclass,
2129 $this->config->user_attribute, $this->config->search_sub);
2134 * A chance to validate form data, and last chance to do stuff
2135 * before it is inserted in config_plugin
2137 * @param object object with submitted configuration settings (without system magic quotes)
2138 * @param array $err array of error messages (passed by reference)
2140 function validate_form($form, &$err) {
2141 if ($form->ntlmsso_type == 'ntlm') {
2142 $format = trim($form->ntlmsso_remoteuserformat);
2143 if (!empty($format) && !preg_match('/%username%/i', $format)) {
2144 $err['ntlmsso_remoteuserformat'] = get_string('auth_ntlmsso_missing_username', 'auth_ldap');
2151 * When using NTLM SSO, the format of the remote username we get in
2152 * $_SERVER['REMOTE_USER'] may vary, depending on where from and how the web
2153 * server gets the data. So we let the admin configure the format using two
2154 * place holders (%domain% and %username%). This function tries to extract
2155 * the username (stripping the domain part and any separators if they are
2156 * present) from the value present in $_SERVER['REMOTE_USER'], using the
2157 * configured format.
2159 * @param string $remoteuser The value from $_SERVER['REMOTE_USER'] (converted to UTF-8)
2161 * @return string The remote username (without domain part or
2162 * separators). Empty string if we can't extract the username.
2164 protected function get_ntlm_remote_user($remoteuser) {
2165 if (empty($this->config->ntlmsso_remoteuserformat)) {
2166 $format = AUTH_NTLM_DEFAULT_FORMAT;
2168 $format = $this->config->ntlmsso_remoteuserformat;
2171 $format = preg_quote($format);
2172 $formatregex = preg_replace(array('#%domain%#', '#%username%#'),
2173 array('('.AUTH_NTLM_VALID_DOMAINNAME.')', '('.AUTH_NTLM_VALID_USERNAME.')'),
2175 if (preg_match('#^'.$formatregex.'$#', $remoteuser, $matches)) {
2176 $user = end($matches);
2180 /* We are unable to extract the username with the configured format. Probably
2181 * the format specified is wrong, so log a warning for the admin and return
2182 * an empty username.
2184 error_log($this->errorlogtag.get_string ('auth_ntlmsso_maybeinvalidformat', 'auth_ldap'));
2189 * Check if the diagnostic message for the LDAP login error tells us that the
2190 * login is denied because the user password has expired or the password needs
2191 * to be changed on first login (using interactive SMB/Windows logins, not
2194 * @param string the diagnostic message for the LDAP login error
2195 * @return bool true if the password has expired or the password must be changed on first login
2197 protected function ldap_ad_pwdexpired_from_diagmsg($diagmsg) {
2198 // The format of the diagnostic message is (actual examples from W2003 and W2008):
2199 // "80090308: LdapErr: DSID-0C090334, comment: AcceptSecurityContext error, data 52e, vece" (W2003)
2200 // "80090308: LdapErr: DSID-0C090334, comment: AcceptSecurityContext error, data 773, vece" (W2003)
2201 // "80090308: LdapErr: DSID-0C0903AA, comment: AcceptSecurityContext error, data 52e, v1771" (W2008)
2202 // "80090308: LdapErr: DSID-0C0903AA, comment: AcceptSecurityContext error, data 773, v1771" (W2008)
2203 // We are interested in the 'data nnn' part.
2204 // if nnn == 773 then user must change password on first login
2205 // if nnn == 532 then user password has expired
2206 $diagmsg = explode(',', $diagmsg);
2207 if (preg_match('/data (773|532)/i', trim($diagmsg[2]))) {
2213 } // End of the class