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%');
64 if (!defined('AUTH_NTLM_FASTPATH_ATTEMPT')) {
65 define('AUTH_NTLM_FASTPATH_ATTEMPT', 0);
67 if (!defined('AUTH_NTLM_FASTPATH_YESFORM')) {
68 define('AUTH_NTLM_FASTPATH_YESFORM', 1);
70 if (!defined('AUTH_NTLM_FASTPATH_YESATTEMPT')) {
71 define('AUTH_NTLM_FASTPATH_YESATTEMPT', 2);
74 // Allows us to retrieve a diagnostic message in case of LDAP operation error
75 if (!defined('LDAP_OPT_DIAGNOSTIC_MESSAGE')) {
76 define('LDAP_OPT_DIAGNOSTIC_MESSAGE', 0x0032);
79 require_once($CFG->libdir
.'/authlib.php');
80 require_once($CFG->libdir
.'/ldaplib.php');
81 require_once($CFG->dirroot
.'/user/lib.php');
82 require_once($CFG->dirroot
.'/auth/ldap/locallib.php');
85 * LDAP authentication plugin.
87 class auth_plugin_ldap
extends auth_plugin_base
{
90 * Init plugin config from database settings depending on the plugin auth type.
92 function init_plugin($authtype) {
93 $this->pluginconfig
= 'auth_'.$authtype;
94 $this->config
= get_config($this->pluginconfig
);
95 if (empty($this->config
->ldapencoding
)) {
96 $this->config
->ldapencoding
= 'utf-8';
98 if (empty($this->config
->user_type
)) {
99 $this->config
->user_type
= 'default';
102 $ldap_usertypes = ldap_supported_usertypes();
103 $this->config
->user_type_name
= $ldap_usertypes[$this->config
->user_type
];
104 unset($ldap_usertypes);
106 $default = ldap_getdefaults();
108 // Use defaults if values not given
109 foreach ($default as $key => $value) {
110 // watch out - 0, false are correct values too
111 if (!isset($this->config
->{$key}) or $this->config
->{$key} == '') {
112 $this->config
->{$key} = $value[$this->config
->user_type
];
116 // Hack prefix to objectclass
117 $this->config
->objectclass
= ldap_normalise_objectclass($this->config
->objectclass
);
121 * Constructor with initialisation.
123 public function __construct() {
124 $this->authtype
= 'ldap';
125 $this->roleauth
= 'auth_ldap';
126 $this->errorlogtag
= '[AUTH LDAP] ';
127 $this->init_plugin($this->authtype
);
131 * Old syntax of class constructor. Deprecated in PHP7.
133 * @deprecated since Moodle 3.1
135 public function auth_plugin_ldap() {
136 debugging('Use of class name as constructor is deprecated', DEBUG_DEVELOPER
);
141 * Returns true if the username and password work and false if they are
142 * wrong or don't exist.
144 * @param string $username The username (without system magic quotes)
145 * @param string $password The password (without system magic quotes)
147 * @return bool Authentication success or failure.
149 function user_login($username, $password) {
150 if (! function_exists('ldap_bind')) {
151 print_error('auth_ldapnotinstalled', 'auth_ldap');
155 if (!$username or !$password) { // Don't allow blank usernames or passwords
159 $extusername = core_text
::convert($username, 'utf-8', $this->config
->ldapencoding
);
160 $extpassword = core_text
::convert($password, 'utf-8', $this->config
->ldapencoding
);
162 // Before we connect to LDAP, check if this is an AD SSO login
163 // if we succeed in this block, we'll return success early.
166 if (!empty($this->config
->ntlmsso_enabled
) && $key === $password) {
167 $sessusername = get_cache_flag($this->pluginconfig
.'/ntlmsess', $key);
168 // We only get the cache flag if we retrieve it before
169 // it expires (AUTH_NTLMTIMEOUT seconds).
170 if (empty($sessusername)) {
174 if ($username === $sessusername) {
175 unset($sessusername);
177 // Check that the user is inside one of the configured LDAP contexts
179 $ldapconnection = $this->ldap_connect();
180 // if the user is not inside the configured contexts,
181 // ldap_find_userdn returns false.
182 if ($this->ldap_find_userdn($ldapconnection, $extusername)) {
187 // Shortcut here - SSO confirmed
190 } // End SSO processing
193 $ldapconnection = $this->ldap_connect();
194 $ldap_user_dn = $this->ldap_find_userdn($ldapconnection, $extusername);
196 // If ldap_user_dn is empty, user does not exist
197 if (!$ldap_user_dn) {
202 // Try to bind with current username and password
203 $ldap_login = @ldap_bind
($ldapconnection, $ldap_user_dn, $extpassword);
205 // If login fails and we are using MS Active Directory, retrieve the diagnostic
206 // message to see if this is due to an expired password, or that the user is forced to
207 // change the password on first login. If it is, only proceed if we can change
208 // password from Moodle (otherwise we'll get stuck later in the login process).
209 if (!$ldap_login && ($this->config
->user_type
== 'ad')
210 && $this->can_change_password()
211 && (!empty($this->config
->expiration
) and ($this->config
->expiration
== 1))) {
213 // We need to get the diagnostic message right after the call to ldap_bind(),
214 // before any other LDAP operation.
215 ldap_get_option($ldapconnection, LDAP_OPT_DIAGNOSTIC_MESSAGE
, $diagmsg);
217 if ($this->ldap_ad_pwdexpired_from_diagmsg($diagmsg)) {
218 // If login failed because user must change the password now or the
219 // password has expired, let the user in. We'll catch this later in the
220 // login process when we explicitly check for expired passwords.
229 * Reads user information from ldap and returns it in array()
231 * Function should return all information available. If you are saving
232 * this information to moodle user-table you should honor syncronization flags
234 * @param string $username username
236 * @return mixed array with no magic quotes or false on error
238 function get_userinfo($username) {
239 $extusername = core_text
::convert($username, 'utf-8', $this->config
->ldapencoding
);
241 $ldapconnection = $this->ldap_connect();
242 if(!($user_dn = $this->ldap_find_userdn($ldapconnection, $extusername))) {
247 $search_attribs = array();
248 $attrmap = $this->ldap_attributes();
249 foreach ($attrmap as $key => $values) {
250 if (!is_array($values)) {
251 $values = array($values);
253 foreach ($values as $value) {
254 if (!in_array($value, $search_attribs)) {
255 array_push($search_attribs, $value);
260 if (!$user_info_result = ldap_read($ldapconnection, $user_dn, '(objectClass=*)', $search_attribs)) {
262 return false; // error!
265 $user_entry = ldap_get_entries_moodle($ldapconnection, $user_info_result);
266 if (empty($user_entry)) {
268 return false; // entry not found
272 foreach ($attrmap as $key => $values) {
273 if (!is_array($values)) {
274 $values = array($values);
277 foreach ($values as $value) {
278 $entry = $user_entry[0];
279 if (($value == 'dn') ||
($value == 'distinguishedname')) {
280 $result[$key] = $user_dn;
283 if (!array_key_exists($value, $entry)) {
284 continue; // wrong data mapping!
286 if (is_array($entry[$value])) {
287 $newval = core_text
::convert($entry[$value][0], $this->config
->ldapencoding
, 'utf-8');
289 $newval = core_text
::convert($entry[$value], $this->config
->ldapencoding
, 'utf-8');
291 if (!empty($newval)) { // favour ldap entries that are set
295 if (!is_null($ldapval)) {
296 $result[$key] = $ldapval;
305 * Reads user information from ldap and returns it in an object
307 * @param string $username username (with system magic quotes)
308 * @return mixed object or false on error
310 function get_userinfo_asobj($username) {
311 $user_array = $this->get_userinfo($username);
312 if ($user_array == false) {
313 return false; //error or not found
315 $user_array = truncate_userinfo($user_array);
316 $user = new stdClass();
317 foreach ($user_array as $key=>$value) {
318 $user->{$key} = $value;
324 * Returns all usernames from LDAP
326 * get_userlist returns all usernames from LDAP
330 function get_userlist() {
331 return $this->ldap_get_userlist("({$this->config->user_attribute}=*)");
335 * Checks if user exists on LDAP
337 * @param string $username
339 function user_exists($username) {
340 $extusername = core_text
::convert($username, 'utf-8', $this->config
->ldapencoding
);
342 // Returns true if given username exists on ldap
343 $users = $this->ldap_get_userlist('('.$this->config
->user_attribute
.'='.ldap_filter_addslashes($extusername).')');
344 return count($users);
348 * Creates a new user on LDAP.
349 * By using information in userobject
350 * Use user_exists to prevent duplicate usernames
352 * @param mixed $userobject Moodle userobject
353 * @param mixed $plainpass Plaintext password
355 function user_create($userobject, $plainpass) {
356 $extusername = core_text
::convert($userobject->username
, 'utf-8', $this->config
->ldapencoding
);
357 $extpassword = core_text
::convert($plainpass, 'utf-8', $this->config
->ldapencoding
);
359 switch ($this->config
->passtype
) {
361 $extpassword = '{MD5}' . base64_encode(pack('H*', md5($extpassword)));
364 $extpassword = '{SHA}' . base64_encode(pack('H*', sha1($extpassword)));
371 $ldapconnection = $this->ldap_connect();
372 $attrmap = $this->ldap_attributes();
376 foreach ($attrmap as $key => $values) {
377 if (!is_array($values)) {
378 $values = array($values);
380 foreach ($values as $value) {
381 if (!empty($userobject->$key) ) {
382 $newuser[$value] = core_text
::convert($userobject->$key, 'utf-8', $this->config
->ldapencoding
);
387 //Following sets all mandatory and other forced attribute values
388 //User should be creted as login disabled untill email confirmation is processed
389 //Feel free to add your user type and send patches to paca@sci.fi to add them
390 //Moodle distribution
392 switch ($this->config
->user_type
) {
394 $newuser['objectClass'] = array('inetOrgPerson', 'organizationalPerson', 'person', 'top');
395 $newuser['uniqueId'] = $extusername;
396 $newuser['logindisabled'] = 'TRUE';
397 $newuser['userpassword'] = $extpassword;
398 $uadd = ldap_add($ldapconnection, $this->config
->user_attribute
.'='.ldap_addslashes($extusername).','.$this->config
->create_context
, $newuser);
402 // posixAccount object class forces us to specify a uidNumber
403 // and a gidNumber. That is quite complicated to generate from
404 // Moodle without colliding with existing numbers and without
405 // race conditions. As this user is supposed to be only used
406 // with Moodle (otherwise the user would exist beforehand) and
407 // doesn't need to login into a operating system, we assign the
408 // user the uid of user 'nobody' and gid of group 'nogroup'. In
409 // addition to that, we need to specify a home directory. We
410 // use the root directory ('/') as the home directory, as this
411 // is the only one can always be sure exists. Finally, even if
412 // it's not mandatory, we specify '/bin/false' as the login
413 // shell, to prevent the user from login in at the operating
414 // system level (Moodle ignores this).
416 $newuser['objectClass'] = array('posixAccount', 'inetOrgPerson', 'organizationalPerson', 'person', 'top');
417 $newuser['cn'] = $extusername;
418 $newuser['uid'] = $extusername;
419 $newuser['uidNumber'] = AUTH_UID_NOBODY
;
420 $newuser['gidNumber'] = AUTH_GID_NOGROUP
;
421 $newuser['homeDirectory'] = '/';
422 $newuser['loginShell'] = '/bin/false';
425 // We have to create the account locked, but posixAccount has
426 // no attribute to achive this reliably. So we are going to
427 // modify the password in a reversable way that we can later
428 // revert in user_activate().
430 // Beware that this can be defeated by the user if we are not
431 // using MD5 or SHA-1 passwords. After all, the source code of
432 // Moodle is available, and the user can see the kind of
433 // modification we are doing and 'undo' it by hand (but only
434 // if we are using plain text passwords).
436 // Also bear in mind that you need to use a binding user that
437 // can create accounts and has read/write privileges on the
438 // 'userPassword' attribute for this to work.
440 $newuser['userPassword'] = '*'.$extpassword;
441 $uadd = ldap_add($ldapconnection, $this->config
->user_attribute
.'='.ldap_addslashes($extusername).','.$this->config
->create_context
, $newuser);
444 // User account creation is a two step process with AD. First you
445 // create the user object, then you set the password. If you try
446 // to set the password while creating the user, the operation
449 // Passwords in Active Directory must be encoded as Unicode
450 // strings (UCS-2 Little Endian format) and surrounded with
451 // double quotes. See http://support.microsoft.com/?kbid=269190
452 if (!function_exists('mb_convert_encoding')) {
453 print_error('auth_ldap_no_mbstring', 'auth_ldap');
456 // Check for invalid sAMAccountName characters.
457 if (preg_match('#[/\\[\]:;|=,+*?<>@"]#', $extusername)) {
458 print_error ('auth_ldap_ad_invalidchars', 'auth_ldap');
461 // First create the user account, and mark it as disabled.
462 $newuser['objectClass'] = array('top', 'person', 'user', 'organizationalPerson');
463 $newuser['sAMAccountName'] = $extusername;
464 $newuser['userAccountControl'] = AUTH_AD_NORMAL_ACCOUNT |
465 AUTH_AD_ACCOUNTDISABLE
;
466 $userdn = 'cn='.ldap_addslashes($extusername).','.$this->config
->create_context
;
467 if (!ldap_add($ldapconnection, $userdn, $newuser)) {
468 print_error('auth_ldap_ad_create_req', 'auth_ldap');
471 // Now set the password
473 $newuser['unicodePwd'] = mb_convert_encoding('"' . $extpassword . '"',
475 if(!ldap_modify($ldapconnection, $userdn, $newuser)) {
476 // Something went wrong: delete the user account and error out
477 ldap_delete ($ldapconnection, $userdn);
478 print_error('auth_ldap_ad_create_req', 'auth_ldap');
483 print_error('auth_ldap_unsupportedusertype', 'auth_ldap', '', $this->config
->user_type_name
);
490 * Returns true if plugin allows resetting of password from moodle.
494 function can_reset_password() {
495 return !empty($this->config
->stdchangepassword
);
499 * Returns true if plugin can be manually set.
503 function can_be_manually_set() {
508 * Returns true if plugin allows signup and user creation.
512 function can_signup() {
513 return (!empty($this->config
->auth_user_create
) and !empty($this->config
->create_context
));
517 * Sign up a new user ready for confirmation.
518 * Password is passed in plaintext.
520 * @param object $user new user object
521 * @param boolean $notify print notice with link and terminate
522 * @return boolean success
524 function user_signup($user, $notify=true) {
525 global $CFG, $DB, $PAGE, $OUTPUT;
527 require_once($CFG->dirroot
.'/user/profile/lib.php');
528 require_once($CFG->dirroot
.'/user/lib.php');
530 if ($this->user_exists($user->username
)) {
531 print_error('auth_ldap_user_exists', 'auth_ldap');
534 $plainslashedpassword = $user->password
;
535 unset($user->password
);
537 if (! $this->user_create($user, $plainslashedpassword)) {
538 print_error('auth_ldap_create_error', 'auth_ldap');
541 $user->id
= user_create_user($user, false, false);
543 user_add_password_history($user->id
, $plainslashedpassword);
545 // Save any custom profile field information
546 profile_save_data($user);
548 $userinfo = $this->get_userinfo($user->username
);
549 $this->update_user_record($user->username
, false, false, $this->is_user_suspended((object) $userinfo));
551 // This will also update the stored hash to the latest algorithm
552 // if the existing hash is using an out-of-date algorithm (or the
553 // legacy md5 algorithm).
554 update_internal_user_password($user, $plainslashedpassword);
556 $user = $DB->get_record('user', array('id'=>$user->id
));
558 \core\event\user_created
::create_from_userid($user->id
)->trigger();
560 if (! send_confirmation_email($user)) {
561 print_error('noemail', 'auth_ldap');
565 $emailconfirm = get_string('emailconfirm');
566 $PAGE->set_url('/auth/ldap/auth.php');
567 $PAGE->navbar
->add($emailconfirm);
568 $PAGE->set_title($emailconfirm);
569 $PAGE->set_heading($emailconfirm);
570 echo $OUTPUT->header();
571 notice(get_string('emailconfirmsent', '', $user->email
), "{$CFG->wwwroot}/index.php");
578 * Returns true if plugin allows confirming of new users.
582 function can_confirm() {
583 return $this->can_signup();
587 * Confirm the new user as registered.
589 * @param string $username
590 * @param string $confirmsecret
592 function user_confirm($username, $confirmsecret) {
595 $user = get_complete_user_data('username', $username);
598 if ($user->auth
!= $this->authtype
) {
599 return AUTH_CONFIRM_ERROR
;
601 } else if ($user->secret
== $confirmsecret && $user->confirmed
) {
602 return AUTH_CONFIRM_ALREADY
;
604 } else if ($user->secret
== $confirmsecret) { // They have provided the secret key to get in
605 if (!$this->user_activate($username)) {
606 return AUTH_CONFIRM_FAIL
;
608 $user->confirmed
= 1;
609 user_update_user($user, false);
610 return AUTH_CONFIRM_OK
;
613 return AUTH_CONFIRM_ERROR
;
618 * Return number of days to user password expires
620 * If userpassword does not expire it should return 0. If password is already expired
621 * it should return negative value.
623 * @param mixed $username username
626 function password_expire($username) {
629 $extusername = core_text
::convert($username, 'utf-8', $this->config
->ldapencoding
);
631 $ldapconnection = $this->ldap_connect();
632 $user_dn = $this->ldap_find_userdn($ldapconnection, $extusername);
633 $search_attribs = array($this->config
->expireattr
);
634 $sr = ldap_read($ldapconnection, $user_dn, '(objectClass=*)', $search_attribs);
636 $info = ldap_get_entries_moodle($ldapconnection, $sr);
637 if (!empty ($info)) {
639 if (isset($info[$this->config
->expireattr
][0])) {
640 $expiretime = $this->ldap_expirationtime2unix($info[$this->config
->expireattr
][0], $ldapconnection, $user_dn);
641 if ($expiretime != 0) {
643 if ($expiretime > $now) {
644 $result = ceil(($expiretime - $now) / DAYSECS
);
646 $result = floor(($expiretime - $now) / DAYSECS
);
652 error_log($this->errorlogtag
.get_string('didtfindexpiretime', 'auth_ldap'));
659 * Syncronizes user fron external LDAP server to moodle user table
661 * Sync is now using username attribute.
663 * Syncing users removes or suspends users that dont exists anymore in external LDAP.
664 * Creates new users and updates coursecreator status of users.
666 * @param bool $do_updates will do pull in data updates from LDAP if relevant
668 function sync_users($do_updates=true) {
671 require_once($CFG->dirroot
. '/user/profile/lib.php');
673 print_string('connectingldap', 'auth_ldap');
674 $ldapconnection = $this->ldap_connect();
676 $dbman = $DB->get_manager();
678 /// Define table user to be created
679 $table = new xmldb_table('tmp_extuser');
680 $table->add_field('id', XMLDB_TYPE_INTEGER
, '10', XMLDB_UNSIGNED
, XMLDB_NOTNULL
, XMLDB_SEQUENCE
, null);
681 $table->add_field('username', XMLDB_TYPE_CHAR
, '100', null, XMLDB_NOTNULL
, null, null);
682 $table->add_field('mnethostid', XMLDB_TYPE_INTEGER
, '10', XMLDB_UNSIGNED
, XMLDB_NOTNULL
, null, null);
683 $table->add_key('primary', XMLDB_KEY_PRIMARY
, array('id'));
684 $table->add_index('username', XMLDB_INDEX_UNIQUE
, array('mnethostid', 'username'));
686 print_string('creatingtemptable', 'auth_ldap', 'tmp_extuser');
687 $dbman->create_temp_table($table);
690 //// get user's list from ldap to sql in a scalable fashion
692 // prepare some data we'll need
693 $filter = '(&('.$this->config
->user_attribute
.'=*)'.$this->config
->objectclass
.')';
695 $contexts = explode(';', $this->config
->contexts
);
697 if (!empty($this->config
->create_context
)) {
698 array_push($contexts, $this->config
->create_context
);
701 $ldap_pagedresults = ldap_paged_results_supported($this->config
->ldap_version
, $ldapconnection);
703 foreach ($contexts as $context) {
704 $context = trim($context);
705 if (empty($context)) {
710 if ($ldap_pagedresults) {
711 ldap_control_paged_result($ldapconnection, $this->config
->pagesize
, true, $ldap_cookie);
713 if ($this->config
->search_sub
) {
714 // Use ldap_search to find first user from subtree.
715 $ldap_result = ldap_search($ldapconnection, $context, $filter, array($this->config
->user_attribute
));
717 // Search only in this context.
718 $ldap_result = ldap_list($ldapconnection, $context, $filter, array($this->config
->user_attribute
));
723 if ($ldap_pagedresults) {
724 ldap_control_paged_result_response($ldapconnection, $ldap_result, $ldap_cookie);
726 if ($entry = @ldap_first_entry
($ldapconnection, $ldap_result)) {
728 $value = ldap_get_values_len($ldapconnection, $entry, $this->config
->user_attribute
);
729 $value = core_text
::convert($value[0], $this->config
->ldapencoding
, 'utf-8');
730 $value = trim($value);
731 $this->ldap_bulk_insert($value);
732 } while ($entry = ldap_next_entry($ldapconnection, $entry));
734 unset($ldap_result); // Free mem.
735 } while ($ldap_pagedresults && $ldap_cookie !== null && $ldap_cookie != '');
738 // If LDAP paged results were used, the current connection must be completely
739 // closed and a new one created, to work without paged results from here on.
740 if ($ldap_pagedresults) {
741 $this->ldap_close(true);
742 $ldapconnection = $this->ldap_connect();
745 /// preserve our user database
746 /// if the temp table is empty, it probably means that something went wrong, exit
747 /// so as to avoid mass deletion of users; which is hard to undo
748 $count = $DB->count_records_sql('SELECT COUNT(username) AS count, 1 FROM {tmp_extuser}');
750 print_string('didntgetusersfromldap', 'auth_ldap');
753 print_string('gotcountrecordsfromldap', 'auth_ldap', $count);
758 // Find users in DB that aren't in ldap -- to be removed!
759 // this is still not as scalable (but how often do we mass delete?)
761 if ($this->config
->removeuser
== AUTH_REMOVEUSER_FULLDELETE
) {
764 LEFT JOIN {tmp_extuser} e ON (u.username = e.username AND u.mnethostid = e.mnethostid)
767 AND e.username IS NULL";
768 $remove_users = $DB->get_records_sql($sql, array('auth'=>$this->authtype
));
770 if (!empty($remove_users)) {
771 print_string('userentriestoremove', 'auth_ldap', count($remove_users));
772 foreach ($remove_users as $user) {
773 if (delete_user($user)) {
774 echo "\t"; print_string('auth_dbdeleteuser', 'auth_db', array('name'=>$user->username
, 'id'=>$user->id
)); echo "\n";
776 echo "\t"; print_string('auth_dbdeleteusererror', 'auth_db', $user->username
); echo "\n";
780 print_string('nouserentriestoremove', 'auth_ldap');
782 unset($remove_users); // Free mem!
784 } else if ($this->config
->removeuser
== AUTH_REMOVEUSER_SUSPEND
) {
787 LEFT JOIN {tmp_extuser} e ON (u.username = e.username AND u.mnethostid = e.mnethostid)
791 AND e.username IS NULL";
792 $remove_users = $DB->get_records_sql($sql, array('auth'=>$this->authtype
));
794 if (!empty($remove_users)) {
795 print_string('userentriestoremove', 'auth_ldap', count($remove_users));
797 foreach ($remove_users as $user) {
798 $updateuser = new stdClass();
799 $updateuser->id
= $user->id
;
800 $updateuser->suspended
= 1;
801 user_update_user($updateuser, false);
802 echo "\t"; print_string('auth_dbsuspenduser', 'auth_db', array('name'=>$user->username
, 'id'=>$user->id
)); echo "\n";
803 \core\session\manager
::kill_user_sessions($user->id
);
806 print_string('nouserentriestoremove', 'auth_ldap');
808 unset($remove_users); // Free mem!
811 /// Revive suspended users
812 if (!empty($this->config
->removeuser
) and $this->config
->removeuser
== AUTH_REMOVEUSER_SUSPEND
) {
813 $sql = "SELECT u.id, u.username
815 JOIN {tmp_extuser} e ON (u.username = e.username AND u.mnethostid = e.mnethostid)
816 WHERE (u.auth = 'nologin' OR (u.auth = ? AND u.suspended = 1)) AND u.deleted = 0";
817 // Note: 'nologin' is there for backwards compatibility.
818 $revive_users = $DB->get_records_sql($sql, array($this->authtype
));
820 if (!empty($revive_users)) {
821 print_string('userentriestorevive', 'auth_ldap', count($revive_users));
823 foreach ($revive_users as $user) {
824 $updateuser = new stdClass();
825 $updateuser->id
= $user->id
;
826 $updateuser->auth
= $this->authtype
;
827 $updateuser->suspended
= 0;
828 user_update_user($updateuser, false);
829 echo "\t"; print_string('auth_dbreviveduser', 'auth_db', array('name'=>$user->username
, 'id'=>$user->id
)); echo "\n";
832 print_string('nouserentriestorevive', 'auth_ldap');
835 unset($revive_users);
839 /// User Updates - time-consuming (optional)
841 // Narrow down what fields we need to update
842 $updatekeys = $this->get_profile_keys();
845 print_string('noupdatestobedone', 'auth_ldap');
847 if ($do_updates and !empty($updatekeys)) { // run updates only if relevant
848 $users = $DB->get_records_sql('SELECT u.username, u.id
850 WHERE u.deleted = 0 AND u.auth = ? AND u.mnethostid = ?',
851 array($this->authtype
, $CFG->mnet_localhost_id
));
852 if (!empty($users)) {
853 print_string('userentriestoupdate', 'auth_ldap', count($users));
855 $transaction = $DB->start_delegated_transaction();
859 foreach ($users as $user) {
860 echo "\t"; print_string('auth_dbupdatinguser', 'auth_db', array('name'=>$user->username
, 'id'=>$user->id
));
861 $userinfo = $this->get_userinfo($user->username
);
862 if (!$this->update_user_record($user->username
, $updatekeys, true,
863 $this->is_user_suspended((object) $userinfo))) {
864 echo ' - '.get_string('skipped');
869 // Update system roles, if needed.
870 $this->sync_roles($user);
872 $transaction->allow_commit();
873 unset($users); // free mem
875 } else { // end do updates
876 print_string('noupdatestobedone', 'auth_ldap');
880 // Find users missing in DB that are in LDAP
881 // and gives me a nifty object I don't want.
882 // note: we do not care about deleted accounts anymore, this feature was replaced by suspending to nologin auth plugin
883 $sql = 'SELECT e.id, e.username
885 LEFT JOIN {user} u ON (e.username = u.username AND e.mnethostid = u.mnethostid)
887 $add_users = $DB->get_records_sql($sql);
889 if (!empty($add_users)) {
890 print_string('userentriestoadd', 'auth_ldap', count($add_users));
892 $transaction = $DB->start_delegated_transaction();
893 foreach ($add_users as $user) {
894 $user = $this->get_userinfo_asobj($user->username
);
897 $user->modified
= time();
898 $user->confirmed
= 1;
899 $user->auth
= $this->authtype
;
900 $user->mnethostid
= $CFG->mnet_localhost_id
;
901 // get_userinfo_asobj() might have replaced $user->username with the value
902 // from the LDAP server (which can be mixed-case). Make sure it's lowercase
903 $user->username
= trim(core_text
::strtolower($user->username
));
904 // It isn't possible to just rely on the configured suspension attribute since
905 // things like active directory use bit masks, other things using LDAP might
906 // do different stuff as well.
908 // The cast to int is a workaround for MDL-53959.
909 $user->suspended
= (int)$this->is_user_suspended($user);
910 if (empty($user->lang
)) {
911 $user->lang
= $CFG->lang
;
913 if (empty($user->calendartype
)) {
914 $user->calendartype
= $CFG->calendartype
;
917 $id = user_create_user($user, false);
918 echo "\t"; print_string('auth_dbinsertuser', 'auth_db', array('name'=>$user->username
, 'id'=>$id)); echo "\n";
919 $euser = $DB->get_record('user', array('id' => $id));
921 if (!empty($this->config
->forcechangepassword
)) {
922 set_user_preference('auth_forcepasswordchange', 1, $id);
925 // Save custom profile fields.
926 $this->update_user_record($user->username
, $this->get_profile_keys(true), false);
928 // Add roles if needed.
929 $this->sync_roles($euser);
932 $transaction->allow_commit();
933 unset($add_users); // free mem
935 print_string('nouserstobeadded', 'auth_ldap');
938 $dbman->drop_table($table);
945 * Bulk insert in SQL's temp table
947 function ldap_bulk_insert($username) {
950 $username = core_text
::strtolower($username); // usernames are __always__ lowercase.
951 $DB->insert_record_raw('tmp_extuser', array('username'=>$username,
952 'mnethostid'=>$CFG->mnet_localhost_id
), false, true);
957 * Activates (enables) user in external LDAP so user can login
959 * @param mixed $username
960 * @return boolean result
962 function user_activate($username) {
963 $extusername = core_text
::convert($username, 'utf-8', $this->config
->ldapencoding
);
965 $ldapconnection = $this->ldap_connect();
967 $userdn = $this->ldap_find_userdn($ldapconnection, $extusername);
968 switch ($this->config
->user_type
) {
970 $newinfo['loginDisabled'] = 'FALSE';
974 // Remember that we add a '*' character in front of the
975 // external password string to 'disable' the account. We just
976 // need to remove it.
977 $sr = ldap_read($ldapconnection, $userdn, '(objectClass=*)',
978 array('userPassword'));
979 $info = ldap_get_entries($ldapconnection, $sr);
980 $info[0] = array_change_key_case($info[0], CASE_LOWER
);
981 $newinfo['userPassword'] = ltrim($info[0]['userpassword'][0], '*');
984 // We need to unset the ACCOUNTDISABLE bit in the
985 // userAccountControl attribute ( see
986 // http://support.microsoft.com/kb/305144 )
987 $sr = ldap_read($ldapconnection, $userdn, '(objectClass=*)',
988 array('userAccountControl'));
989 $info = ldap_get_entries($ldapconnection, $sr);
990 $info[0] = array_change_key_case($info[0], CASE_LOWER
);
991 $newinfo['userAccountControl'] = $info[0]['useraccountcontrol'][0]
992 & (~AUTH_AD_ACCOUNTDISABLE
);
995 print_error('user_activatenotsupportusertype', 'auth_ldap', '', $this->config
->user_type_name
);
997 $result = ldap_modify($ldapconnection, $userdn, $newinfo);
1003 * Returns true if user should be coursecreator.
1005 * @param mixed $username username (without system magic quotes)
1006 * @return mixed result null if course creators is not configured, boolean otherwise.
1008 * @deprecated since Moodle 3.4 MDL-30634 - please do not use this function any more.
1010 function iscreator($username) {
1011 debugging('iscreator() is deprecated. Please use auth_plugin_ldap::is_role() instead.', DEBUG_DEVELOPER
);
1013 if (empty($this->config
->creators
) or empty($this->config
->memberattribute
)) {
1017 $extusername = core_text
::convert($username, 'utf-8', $this->config
->ldapencoding
);
1019 $ldapconnection = $this->ldap_connect();
1021 if ($this->config
->memberattribute_isdn
) {
1022 if(!($userid = $this->ldap_find_userdn($ldapconnection, $extusername))) {
1026 $userid = $extusername;
1029 $group_dns = explode(';', $this->config
->creators
);
1030 $creator = ldap_isgroupmember($ldapconnection, $userid, $group_dns, $this->config
->memberattribute
);
1032 $this->ldap_close();
1038 * Check if user has LDAP group membership.
1040 * Returns true if user should be assigned role.
1042 * @param mixed $username username (without system magic quotes).
1043 * @param array $role Array of role's shortname, localname, and settingname for the config value.
1044 * @return mixed result null if role/LDAP context is not configured, boolean otherwise.
1046 private function is_role($username, $role) {
1047 if (empty($this->config
->{$role['settingname']}) or empty($this->config
->memberattribute
)) {
1051 $extusername = core_text
::convert($username, 'utf-8', $this->config
->ldapencoding
);
1053 $ldapconnection = $this->ldap_connect();
1055 if ($this->config
->memberattribute_isdn
) {
1056 if (!($userid = $this->ldap_find_userdn($ldapconnection, $extusername))) {
1060 $userid = $extusername;
1063 $groupdns = explode(';', $this->config
->{$role['settingname']});
1064 $isrole = ldap_isgroupmember($ldapconnection, $userid, $groupdns, $this->config
->memberattribute
);
1066 $this->ldap_close();
1072 * Called when the user record is updated.
1074 * Modifies user in external LDAP server. It takes olduser (before
1075 * changes) and newuser (after changes) compares information and
1076 * saves modified information to external LDAP server.
1078 * @param mixed $olduser Userobject before modifications (without system magic quotes)
1079 * @param mixed $newuser Userobject new modified userobject (without system magic quotes)
1080 * @return boolean result
1083 function user_update($olduser, $newuser) {
1086 require_once($CFG->dirroot
. '/user/profile/lib.php');
1088 if (isset($olduser->username
) and isset($newuser->username
) and $olduser->username
!= $newuser->username
) {
1089 error_log($this->errorlogtag
.get_string('renamingnotallowed', 'auth_ldap'));
1093 if (isset($olduser->auth
) and $olduser->auth
!= $this->authtype
) {
1094 return true; // just change auth and skip update
1097 $attrmap = $this->ldap_attributes();
1098 // Before doing anything else, make sure we really need to update anything
1099 // in the external LDAP server.
1100 $update_external = false;
1101 foreach ($attrmap as $key => $ldapkeys) {
1102 if (!empty($this->config
->{'field_updateremote_'.$key})) {
1103 $update_external = true;
1107 if (!$update_external) {
1111 $extoldusername = core_text
::convert($olduser->username
, 'utf-8', $this->config
->ldapencoding
);
1113 $ldapconnection = $this->ldap_connect();
1115 $search_attribs = array();
1116 foreach ($attrmap as $key => $values) {
1117 if (!is_array($values)) {
1118 $values = array($values);
1120 foreach ($values as $value) {
1121 if (!in_array($value, $search_attribs)) {
1122 array_push($search_attribs, $value);
1127 if(!($user_dn = $this->ldap_find_userdn($ldapconnection, $extoldusername))) {
1131 // Load old custom fields.
1132 $olduserprofilefields = (array) profile_user_record($olduser->id
, false);
1135 foreach (profile_get_custom_fields(false) as $field) {
1136 $fields[$field->shortname
] = $field;
1140 $user_info_result = ldap_read($ldapconnection, $user_dn, '(objectClass=*)', $search_attribs);
1141 if ($user_info_result) {
1142 $user_entry = ldap_get_entries_moodle($ldapconnection, $user_info_result);
1143 if (empty($user_entry)) {
1144 $attribs = join (', ', $search_attribs);
1145 error_log($this->errorlogtag
.get_string('updateusernotfound', 'auth_ldap',
1146 array('userdn'=>$user_dn,
1147 'attribs'=>$attribs)));
1148 return false; // old user not found!
1149 } else if (count($user_entry) > 1) {
1150 error_log($this->errorlogtag
.get_string('morethanoneuser', 'auth_ldap'));
1154 $user_entry = $user_entry[0];
1156 foreach ($attrmap as $key => $ldapkeys) {
1157 if (preg_match('/^profile_field_(.*)$/', $key, $match)) {
1159 $fieldname = $match[1];
1160 if (isset($fields[$fieldname])) {
1161 $class = 'profile_field_' . $fields[$fieldname]->datatype
;
1162 $formfield = new $class($fields[$fieldname]->id
, $olduser->id
);
1163 $oldvalue = isset($olduserprofilefields[$fieldname]) ?
$olduserprofilefields[$fieldname] : null;
1167 $newvalue = $formfield->edit_save_data_preprocess($newuser->{$formfield->inputname
}, new stdClass
);
1170 $oldvalue = isset($olduser->$key) ?
$olduser->$key : null;
1171 $newvalue = isset($newuser->$key) ?
$newuser->$key : null;
1174 if ($newvalue !== null and $newvalue !== $oldvalue and !empty($this->config
->{'field_updateremote_' . $key})) {
1175 // For ldap values that could be in more than one
1176 // ldap key, we will do our best to match
1177 // where they came from
1180 if (!is_array($ldapkeys)) {
1181 $ldapkeys = array($ldapkeys);
1183 if (count($ldapkeys) < 2) {
1187 $nuvalue = core_text
::convert($newvalue, 'utf-8', $this->config
->ldapencoding
);
1188 empty($nuvalue) ?
$nuvalue = array() : $nuvalue;
1189 $ouvalue = core_text
::convert($oldvalue, 'utf-8', $this->config
->ldapencoding
);
1190 foreach ($ldapkeys as $ldapkey) {
1191 // Skip update if $ldapkey does not exist in LDAP.
1192 if (!isset($user_entry[$ldapkey][0])) {
1194 error_log($this->errorlogtag
.get_string('updateremfailfield', 'auth_ldap',
1195 array('ldapkey' => $ldapkey,
1197 'ouvalue' => $ouvalue,
1198 'nuvalue' => $nuvalue)));
1202 $ldapvalue = $user_entry[$ldapkey][0];
1204 // Skip update if the values already match
1205 if ($nuvalue !== $ldapvalue) {
1206 // This might fail due to schema validation
1207 if (@ldap_modify
($ldapconnection, $user_dn, array($ldapkey => $nuvalue))) {
1212 error_log($this->errorlogtag
.get_string ('updateremfail', 'auth_ldap',
1213 array('errno'=>ldap_errno($ldapconnection),
1214 'errstring'=>ldap_err2str(ldap_errno($ldapconnection)),
1216 'ouvalue'=>$ouvalue,
1217 'nuvalue'=>$nuvalue)));
1222 // Ambiguous. Value empty before in Moodle (and LDAP) - use
1223 // 1st ldap candidate field, no need to guess
1224 if ($ouvalue === '') { // value empty before - use 1st ldap candidate
1225 // This might fail due to schema validation
1226 if (@ldap_modify
($ldapconnection, $user_dn, array($ldapkey => $nuvalue))) {
1231 error_log($this->errorlogtag
.get_string ('updateremfail', 'auth_ldap',
1232 array('errno'=>ldap_errno($ldapconnection),
1233 'errstring'=>ldap_err2str(ldap_errno($ldapconnection)),
1235 'ouvalue'=>$ouvalue,
1236 'nuvalue'=>$nuvalue)));
1241 // We found which ldap key to update!
1242 if ($ouvalue !== '' and $ouvalue === $ldapvalue ) {
1243 // This might fail due to schema validation
1244 if (@ldap_modify
($ldapconnection, $user_dn, array($ldapkey => $nuvalue))) {
1249 error_log($this->errorlogtag
.get_string ('updateremfail', 'auth_ldap',
1250 array('errno'=>ldap_errno($ldapconnection),
1251 'errstring'=>ldap_err2str(ldap_errno($ldapconnection)),
1253 'ouvalue'=>$ouvalue,
1254 'nuvalue'=>$nuvalue)));
1261 if ($ambiguous and !$changed) {
1263 error_log($this->errorlogtag
.get_string ('updateremfailamb', 'auth_ldap',
1265 'ouvalue'=>$ouvalue,
1266 'nuvalue'=>$nuvalue)));
1271 error_log($this->errorlogtag
.get_string ('usernotfound', 'auth_ldap'));
1275 $this->ldap_close();
1281 * Changes userpassword in LDAP
1283 * Called when the user password is updated. It assumes it is
1284 * called by an admin or that you've otherwise checked the user's
1287 * @param object $user User table object
1288 * @param string $newpassword Plaintext password (not crypted/md5'ed)
1289 * @return boolean result
1292 function user_update_password($user, $newpassword) {
1296 $username = $user->username
;
1298 $extusername = core_text
::convert($username, 'utf-8', $this->config
->ldapencoding
);
1299 $extpassword = core_text
::convert($newpassword, 'utf-8', $this->config
->ldapencoding
);
1301 switch ($this->config
->passtype
) {
1303 $extpassword = '{MD5}' . base64_encode(pack('H*', md5($extpassword)));
1306 $extpassword = '{SHA}' . base64_encode(pack('H*', sha1($extpassword)));
1313 $ldapconnection = $this->ldap_connect();
1315 $user_dn = $this->ldap_find_userdn($ldapconnection, $extusername);
1318 error_log($this->errorlogtag
.get_string ('nodnforusername', 'auth_ldap', $user->username
));
1322 switch ($this->config
->user_type
) {
1325 $result = ldap_modify($ldapconnection, $user_dn, array('userPassword' => $extpassword));
1327 error_log($this->errorlogtag
.get_string ('updatepasserror', 'auth_ldap',
1328 array('errno'=>ldap_errno($ldapconnection),
1329 'errstring'=>ldap_err2str(ldap_errno($ldapconnection)))));
1331 // Update password expiration time, grace logins count
1332 $search_attribs = array($this->config
->expireattr
, 'passwordExpirationInterval', 'loginGraceLimit');
1333 $sr = ldap_read($ldapconnection, $user_dn, '(objectClass=*)', $search_attribs);
1335 $entry = ldap_get_entries_moodle($ldapconnection, $sr);
1337 $newattrs = array();
1338 if (!empty($info[$this->config
->expireattr
][0])) {
1339 // Set expiration time only if passwordExpirationInterval is defined
1340 if (!empty($info['passwordexpirationinterval'][0])) {
1341 $expirationtime = time() +
$info['passwordexpirationinterval'][0];
1342 $ldapexpirationtime = $this->ldap_unix2expirationtime($expirationtime);
1343 $newattrs['passwordExpirationTime'] = $ldapexpirationtime;
1346 // Set gracelogin count
1347 if (!empty($info['logingracelimit'][0])) {
1348 $newattrs['loginGraceRemaining']= $info['logingracelimit'][0];
1351 // Store attribute changes in LDAP
1352 $result = ldap_modify($ldapconnection, $user_dn, $newattrs);
1354 error_log($this->errorlogtag
.get_string ('updatepasserrorexpiregrace', 'auth_ldap',
1355 array('errno'=>ldap_errno($ldapconnection),
1356 'errstring'=>ldap_err2str(ldap_errno($ldapconnection)))));
1361 error_log($this->errorlogtag
.get_string ('updatepasserrorexpire', 'auth_ldap',
1362 array('errno'=>ldap_errno($ldapconnection),
1363 'errstring'=>ldap_err2str(ldap_errno($ldapconnection)))));
1368 // Passwords in Active Directory must be encoded as Unicode
1369 // strings (UCS-2 Little Endian format) and surrounded with
1370 // double quotes. See http://support.microsoft.com/?kbid=269190
1371 if (!function_exists('mb_convert_encoding')) {
1372 error_log($this->errorlogtag
.get_string ('needmbstring', 'auth_ldap'));
1375 $extpassword = mb_convert_encoding('"'.$extpassword.'"', "UCS-2LE", $this->config
->ldapencoding
);
1376 $result = ldap_modify($ldapconnection, $user_dn, array('unicodePwd' => $extpassword));
1378 error_log($this->errorlogtag
.get_string ('updatepasserror', 'auth_ldap',
1379 array('errno'=>ldap_errno($ldapconnection),
1380 'errstring'=>ldap_err2str(ldap_errno($ldapconnection)))));
1385 // Send LDAP the password in cleartext, it will md5 it itself
1386 $result = ldap_modify($ldapconnection, $user_dn, array('userPassword' => $extpassword));
1388 error_log($this->errorlogtag
.get_string ('updatepasserror', 'auth_ldap',
1389 array('errno'=>ldap_errno($ldapconnection),
1390 'errstring'=>ldap_err2str(ldap_errno($ldapconnection)))));
1395 $this->ldap_close();
1400 * Take expirationtime and return it as unix timestamp in seconds
1402 * Takes expiration timestamp as read from LDAP and returns it as unix timestamp in seconds
1403 * Depends on $this->config->user_type variable
1405 * @param mixed time Time stamp read from LDAP as it is.
1406 * @param string $ldapconnection Only needed for Active Directory.
1407 * @param string $user_dn User distinguished name for the user we are checking password expiration (only needed for Active Directory).
1410 function ldap_expirationtime2unix ($time, $ldapconnection, $user_dn) {
1412 switch ($this->config
->user_type
) {
1414 $yr=substr($time, 0, 4);
1415 $mo=substr($time, 4, 2);
1416 $dt=substr($time, 6, 2);
1417 $hr=substr($time, 8, 2);
1418 $min=substr($time, 10, 2);
1419 $sec=substr($time, 12, 2);
1420 $result = mktime($hr, $min, $sec, $mo, $dt, $yr);
1424 $result = $time * DAYSECS
; // The shadowExpire contains the number of DAYS between 01/01/1970 and the actual expiration date
1427 $result = $this->ldap_get_ad_pwdexpire($time, $ldapconnection, $user_dn);
1430 print_error('auth_ldap_usertypeundefined', 'auth_ldap');
1436 * Takes unix timestamp and returns it formated for storing in LDAP
1438 * @param integer unix time stamp
1440 function ldap_unix2expirationtime($time) {
1442 switch ($this->config
->user_type
) {
1444 $result=date('YmdHis', $time).'Z';
1448 $result = $time ; // Already in correct format
1451 print_error('auth_ldap_usertypeundefined2', 'auth_ldap');
1458 * Returns user attribute mappings between moodle and LDAP
1463 function ldap_attributes () {
1464 $moodleattributes = array();
1465 // If we have custom fields then merge them with user fields.
1466 $customfields = $this->get_custom_user_profile_fields();
1467 if (!empty($customfields) && !empty($this->userfields
)) {
1468 $userfields = array_merge($this->userfields
, $customfields);
1470 $userfields = $this->userfields
;
1473 foreach ($userfields as $field) {
1474 if (!empty($this->config
->{"field_map_$field"})) {
1475 $moodleattributes[$field] = core_text
::strtolower(trim($this->config
->{"field_map_$field"}));
1476 if (preg_match('/,/', $moodleattributes[$field])) {
1477 $moodleattributes[$field] = explode(',', $moodleattributes[$field]); // split ?
1481 $moodleattributes['username'] = core_text
::strtolower(trim($this->config
->user_attribute
));
1482 $moodleattributes['suspended'] = core_text
::strtolower(trim($this->config
->suspended_attribute
));
1483 return $moodleattributes;
1487 * Returns all usernames from LDAP
1489 * @param $filter An LDAP search filter to select desired users
1490 * @return array of LDAP user names converted to UTF-8
1492 function ldap_get_userlist($filter='*') {
1495 $ldapconnection = $this->ldap_connect();
1497 if ($filter == '*') {
1498 $filter = '(&('.$this->config
->user_attribute
.'=*)'.$this->config
->objectclass
.')';
1501 $contexts = explode(';', $this->config
->contexts
);
1502 if (!empty($this->config
->create_context
)) {
1503 array_push($contexts, $this->config
->create_context
);
1507 $ldap_pagedresults = ldap_paged_results_supported($this->config
->ldap_version
, $ldapconnection);
1508 foreach ($contexts as $context) {
1509 $context = trim($context);
1510 if (empty($context)) {
1515 if ($ldap_pagedresults) {
1516 ldap_control_paged_result($ldapconnection, $this->config
->pagesize
, true, $ldap_cookie);
1518 if ($this->config
->search_sub
) {
1519 // Use ldap_search to find first user from subtree.
1520 $ldap_result = ldap_search($ldapconnection, $context, $filter, array($this->config
->user_attribute
));
1522 // Search only in this context.
1523 $ldap_result = ldap_list($ldapconnection, $context, $filter, array($this->config
->user_attribute
));
1528 if ($ldap_pagedresults) {
1529 ldap_control_paged_result_response($ldapconnection, $ldap_result, $ldap_cookie);
1531 $users = ldap_get_entries_moodle($ldapconnection, $ldap_result);
1532 // Add found users to list.
1533 for ($i = 0; $i < count($users); $i++
) {
1534 $extuser = core_text
::convert($users[$i][$this->config
->user_attribute
][0],
1535 $this->config
->ldapencoding
, 'utf-8');
1536 array_push($fresult, $extuser);
1538 unset($ldap_result); // Free mem.
1539 } while ($ldap_pagedresults && !empty($ldap_cookie));
1542 // If paged results were used, make sure the current connection is completely closed
1543 $this->ldap_close($ldap_pagedresults);
1548 * Indicates if password hashes should be stored in local moodle database.
1550 * @return bool true means flag 'not_cached' stored instead of password hash
1552 function prevent_local_passwords() {
1553 return !empty($this->config
->preventpassindb
);
1557 * Returns true if this authentication plugin is 'internal'.
1561 function is_internal() {
1566 * Returns true if this authentication plugin can change the user's
1571 function can_change_password() {
1572 return !empty($this->config
->stdchangepassword
) or !empty($this->config
->changepasswordurl
);
1576 * Returns the URL for changing the user's password, or empty if the default can
1579 * @return moodle_url
1581 function change_password_url() {
1582 if (empty($this->config
->stdchangepassword
)) {
1583 if (!empty($this->config
->changepasswordurl
)) {
1584 return new moodle_url($this->config
->changepasswordurl
);
1594 * Will get called before the login page is shownr. Ff NTLM SSO
1595 * is enabled, and the user is in the right network, we'll redirect
1596 * to the magic NTLM page for SSO...
1599 function loginpage_hook() {
1600 global $CFG, $SESSION;
1602 // HTTPS is potentially required
1603 //httpsrequired(); - this must be used before setting the URL, it is already done on the login/index.php
1605 if (($_SERVER['REQUEST_METHOD'] === 'GET' // Only on initial GET of loginpage
1606 ||
($_SERVER['REQUEST_METHOD'] === 'POST'
1607 && (get_local_referer() != strip_querystring(qualified_me()))))
1608 // Or when POSTed from another place
1610 && !empty($this->config
->ntlmsso_enabled
) // SSO enabled
1611 && !empty($this->config
->ntlmsso_subnet
) // have a subnet to test for
1612 && empty($_GET['authldap_skipntlmsso']) // haven't failed it yet
1613 && (isguestuser() ||
!isloggedin()) // guestuser or not-logged-in users
1614 && address_in_subnet(getremoteaddr(), $this->config
->ntlmsso_subnet
)) {
1616 // First, let's remember where we were trying to get to before we got here
1617 if (empty($SESSION->wantsurl
)) {
1618 $SESSION->wantsurl
= null;
1619 $referer = get_local_referer(false);
1621 $referer != $CFG->wwwroot
&&
1622 $referer != $CFG->wwwroot
. '/' &&
1623 $referer != $CFG->wwwroot
. '/login/' &&
1624 $referer != $CFG->wwwroot
. '/login/index.php') {
1625 $SESSION->wantsurl
= $referer;
1629 // Now start the whole NTLM machinery.
1630 if($this->config
->ntlmsso_ie_fastpath
== AUTH_NTLM_FASTPATH_YESATTEMPT ||
1631 $this->config
->ntlmsso_ie_fastpath
== AUTH_NTLM_FASTPATH_YESFORM
) {
1632 if (core_useragent
::is_ie()) {
1633 $sesskey = sesskey();
1634 redirect($CFG->wwwroot
.'/auth/ldap/ntlmsso_magic.php?sesskey='.$sesskey);
1635 } else if ($this->config
->ntlmsso_ie_fastpath
== AUTH_NTLM_FASTPATH_YESFORM
) {
1636 redirect($CFG->wwwroot
.'/login/index.php?authldap_skipntlmsso=1');
1639 redirect($CFG->wwwroot
.'/auth/ldap/ntlmsso_attempt.php');
1642 // No NTLM SSO, Use the normal login page instead.
1644 // If $SESSION->wantsurl is empty and we have a 'Referer:' header, the login
1645 // page insists on redirecting us to that page after user validation. If
1646 // we clicked on the redirect link at the ntlmsso_finish.php page (instead
1647 // of waiting for the redirection to happen) then we have a 'Referer:' header
1648 // we don't want to use at all. As we can't get rid of it, just point
1649 // $SESSION->wantsurl to $CFG->wwwroot (after all, we came from there).
1650 if (empty($SESSION->wantsurl
)
1651 && (get_local_referer() == $CFG->wwwroot
.'/auth/ldap/ntlmsso_finish.php')) {
1653 $SESSION->wantsurl
= $CFG->wwwroot
;
1658 * To be called from a page running under NTLM's
1659 * "Integrated Windows Authentication".
1661 * If successful, it will set a special "cookie" (not an HTTP cookie!)
1662 * in cache_flags under the $this->pluginconfig/ntlmsess "plugin" and return true.
1663 * The "cookie" will be picked up by ntlmsso_finish() to complete the
1666 * On failure it will return false for the caller to display an appropriate
1667 * error message (probably saying that Integrated Windows Auth isn't enabled!)
1669 * NOTE that this code will execute under the OS user credentials,
1670 * so we MUST avoid dealing with files -- such as session files.
1671 * (The caller should define('NO_MOODLE_COOKIES', true) before including config.php)
1674 function ntlmsso_magic($sesskey) {
1675 if (isset($_SERVER['REMOTE_USER']) && !empty($_SERVER['REMOTE_USER'])) {
1677 // HTTP __headers__ seem to be sent in ISO-8859-1 encoding
1678 // (according to my reading of RFC-1945, RFC-2616 and RFC-2617 and
1679 // my local tests), so we need to convert the REMOTE_USER value
1680 // (i.e., what we got from the HTTP WWW-Authenticate header) into UTF-8
1681 $username = core_text
::convert($_SERVER['REMOTE_USER'], 'iso-8859-1', 'utf-8');
1683 switch ($this->config
->ntlmsso_type
) {
1685 // The format is now configurable, so try to extract the username
1686 $username = $this->get_ntlm_remote_user($username);
1687 if (empty($username)) {
1692 // Format is username@DOMAIN
1693 $username = substr($username, 0, strpos($username, '@'));
1696 error_log($this->errorlogtag
.get_string ('ntlmsso_unknowntype', 'auth_ldap'));
1697 return false; // Should never happen!
1700 $username = core_text
::strtolower($username); // Compatibility hack
1701 set_cache_flag($this->pluginconfig
.'/ntlmsess', $sesskey, $username, AUTH_NTLMTIMEOUT
);
1708 * Find the session set by ntlmsso_magic(), validate it and
1709 * call authenticate_user_login() to authenticate the user through
1710 * the auth machinery.
1712 * It is complemented by a similar check in user_login().
1714 * If it succeeds, it never returns.
1717 function ntlmsso_finish() {
1718 global $CFG, $USER, $SESSION;
1721 $username = get_cache_flag($this->pluginconfig
.'/ntlmsess', $key);
1722 if (empty($username)) {
1726 // Here we want to trigger the whole authentication machinery
1727 // to make sure no step is bypassed...
1728 $user = authenticate_user_login($username, $key);
1730 complete_user_login($user);
1732 // Cleanup the key to prevent reuse...
1733 // and to allow re-logins with normal credentials
1734 unset_cache_flag($this->pluginconfig
.'/ntlmsess', $key);
1737 if (user_not_fully_set_up($USER, true)) {
1738 $urltogo = $CFG->wwwroot
.'/user/edit.php';
1739 // We don't delete $SESSION->wantsurl yet, so we get there later
1740 } else if (isset($SESSION->wantsurl
) and (strpos($SESSION->wantsurl
, $CFG->wwwroot
) === 0)) {
1741 $urltogo = $SESSION->wantsurl
; // Because it's an address in this site
1742 unset($SESSION->wantsurl
);
1744 // No wantsurl stored or external - go to homepage
1745 $urltogo = $CFG->wwwroot
.'/';
1746 unset($SESSION->wantsurl
);
1748 // We do not want to redirect if we are in a PHPUnit test.
1749 if (!PHPUNIT_TEST
) {
1753 // Should never reach here.
1758 * Sync roles for this user.
1760 * @param object $user The user to sync (without system magic quotes).
1762 function sync_roles($user) {
1765 $roles = get_ldap_assignable_role_names(2); // Admin user.
1767 foreach ($roles as $role) {
1768 $isrole = $this->is_role($user->username
, $role);
1769 if ($isrole === null) {
1770 continue; // Nothing to sync - role/LDAP contexts not configured.
1774 $systemcontext = context_system
::instance();
1776 // Following calls will not create duplicates.
1777 role_assign($role['id'], $user->id
, $systemcontext->id
, $this->roleauth
);
1779 // Unassign only if previously assigned by this plugin.
1780 role_unassign($role['id'], $user->id
, $systemcontext->id
, $this->roleauth
);
1786 * Get password expiration time for a given user from Active Directory
1788 * @param string $pwdlastset The time last time we changed the password.
1789 * @param resource $lcapconn The open LDAP connection.
1790 * @param string $user_dn The distinguished name of the user we are checking.
1792 * @return string $unixtime
1794 function ldap_get_ad_pwdexpire($pwdlastset, $ldapconn, $user_dn){
1797 if (!function_exists('bcsub')) {
1798 error_log($this->errorlogtag
.get_string ('needbcmath', 'auth_ldap'));
1802 // If UF_DONT_EXPIRE_PASSWD flag is set in user's
1803 // userAccountControl attribute, the password doesn't expire.
1804 $sr = ldap_read($ldapconn, $user_dn, '(objectClass=*)',
1805 array('userAccountControl'));
1807 error_log($this->errorlogtag
.get_string ('useracctctrlerror', 'auth_ldap', $user_dn));
1808 // Don't expire password, as we are not sure if it has to be
1813 $entry = ldap_get_entries_moodle($ldapconn, $sr);
1815 $useraccountcontrol = $info['useraccountcontrol'][0];
1816 if ($useraccountcontrol & UF_DONT_EXPIRE_PASSWD
) {
1817 // Password doesn't expire.
1821 // If pwdLastSet is zero, the user must change his/her password now
1822 // (unless UF_DONT_EXPIRE_PASSWD flag is set, but we already
1823 // tested this above)
1824 if ($pwdlastset === '0') {
1825 // Password has expired
1829 // ----------------------------------------------------------------
1830 // Password expiration time in Active Directory is the composition of
1833 // - User's pwdLastSet attribute, that stores the last time
1834 // the password was changed.
1836 // - Domain's maxPwdAge attribute, that sets how long
1837 // passwords last in this domain.
1839 // We already have the first value (passed in as a parameter). We
1840 // need to get the second one. As we don't know the domain DN, we
1841 // have to query rootDSE's defaultNamingContext attribute to get
1842 // it. Then we have to query that DN's maxPwdAge attribute to get
1845 // Once we have both values, we just need to combine them. But MS
1846 // chose to use a different base and unit for time measurements.
1847 // So we need to convert the values to Unix timestamps (see
1849 // ----------------------------------------------------------------
1851 $sr = ldap_read($ldapconn, ROOTDSE
, '(objectClass=*)',
1852 array('defaultNamingContext'));
1854 error_log($this->errorlogtag
.get_string ('rootdseerror', 'auth_ldap'));
1858 $entry = ldap_get_entries_moodle($ldapconn, $sr);
1860 $domaindn = $info['defaultnamingcontext'][0];
1862 $sr = ldap_read ($ldapconn, $domaindn, '(objectClass=*)',
1863 array('maxPwdAge'));
1864 $entry = ldap_get_entries_moodle($ldapconn, $sr);
1866 $maxpwdage = $info['maxpwdage'][0];
1867 if ($sr = ldap_read($ldapconn, $user_dn, '(objectClass=*)', array('msDS-ResultantPSO'))) {
1868 if ($entry = ldap_get_entries_moodle($ldapconn, $sr)) {
1870 $userpso = $info['msds-resultantpso'][0];
1872 // If a PSO exists, FGPP is being utilized.
1873 // Grab the new maxpwdage from the msDS-MaximumPasswordAge attribute of the PSO.
1874 if (!empty($userpso)) {
1875 $sr = ldap_read($ldapconn, $userpso, '(objectClass=*)', array('msDS-MaximumPasswordAge'));
1876 if ($entry = ldap_get_entries_moodle($ldapconn, $sr)) {
1878 // Default value of msds-maximumpasswordage is 42 and is always set.
1879 $maxpwdage = $info['msds-maximumpasswordage'][0];
1884 // ----------------------------------------------------------------
1885 // MSDN says that "pwdLastSet contains the number of 100 nanosecond
1886 // intervals since January 1, 1601 (UTC), stored in a 64 bit integer".
1888 // According to Perl's Date::Manip, the number of seconds between
1889 // this date and Unix epoch is 11644473600. So we have to
1890 // substract this value to calculate a Unix time, once we have
1891 // scaled pwdLastSet to seconds. This is the script used to
1892 // calculate the value shown above:
1894 // #!/usr/bin/perl -w
1898 // $date1 = ParseDate ("160101010000 UTC");
1899 // $date2 = ParseDate ("197001010000 UTC");
1900 // $delta = DateCalc($date1, $date2, \$err);
1901 // $secs = Delta_Format($delta, 0, "%st");
1902 // print "$secs \n";
1904 // MSDN also says that "maxPwdAge is stored as a large integer that
1905 // represents the number of 100 nanosecond intervals from the time
1906 // the password was set before the password expires." We also need
1907 // to scale this to seconds. Bear in mind that this value is stored
1908 // as a _negative_ quantity (at least in my AD domain).
1910 // As a last remark, if the low 32 bits of maxPwdAge are equal to 0,
1911 // the maximum password age in the domain is set to 0, which means
1912 // passwords do not expire (see
1913 // http://msdn2.microsoft.com/en-us/library/ms974598.aspx)
1915 // As the quantities involved are too big for PHP integers, we
1916 // need to use BCMath functions to work with arbitrary precision
1918 // ----------------------------------------------------------------
1920 // If the low order 32 bits are 0, then passwords do not expire in
1921 // the domain. Just do '$maxpwdage mod 2^32' and check the result
1922 // (2^32 = 4294967296)
1923 if (bcmod ($maxpwdage, 4294967296) === '0') {
1927 // Add up pwdLastSet and maxPwdAge to get password expiration
1928 // time, in MS time units. Remember maxPwdAge is stored as a
1929 // _negative_ quantity, so we need to substract it in fact.
1930 $pwdexpire = bcsub ($pwdlastset, $maxpwdage);
1932 // Scale the result to convert it to Unix time units and return
1934 return bcsub( bcdiv($pwdexpire, '10000000'), '11644473600');
1938 * Connect to the LDAP server, using the plugin configured
1939 * settings. It's actually a wrapper around ldap_connect_moodle()
1941 * @return resource A valid LDAP connection (or dies if it can't connect)
1943 function ldap_connect() {
1944 // Cache ldap connections. They are expensive to set up
1945 // and can drain the TCP/IP ressources on the server if we
1946 // are syncing a lot of users (as we try to open a new connection
1947 // to get the user details). This is the least invasive way
1948 // to reuse existing connections without greater code surgery.
1949 if(!empty($this->ldapconnection
)) {
1951 return $this->ldapconnection
;
1954 if($ldapconnection = ldap_connect_moodle($this->config
->host_url
, $this->config
->ldap_version
,
1955 $this->config
->user_type
, $this->config
->bind_dn
,
1956 $this->config
->bind_pw
, $this->config
->opt_deref
,
1957 $debuginfo, $this->config
->start_tls
)) {
1958 $this->ldapconns
= 1;
1959 $this->ldapconnection
= $ldapconnection;
1960 return $ldapconnection;
1963 print_error('auth_ldap_noconnect_all', 'auth_ldap', '', $debuginfo);
1967 * Disconnects from a LDAP server
1969 * @param force boolean Forces closing the real connection to the LDAP server, ignoring any
1970 * cached connections. This is needed when we've used paged results
1971 * and want to use normal results again.
1973 function ldap_close($force=false) {
1975 if (($this->ldapconns
== 0) ||
($force)) {
1976 $this->ldapconns
= 0;
1977 @ldap_close
($this->ldapconnection
);
1978 unset($this->ldapconnection
);
1983 * Search specified contexts for username and return the user dn
1984 * like: cn=username,ou=suborg,o=org. It's actually a wrapper
1985 * around ldap_find_userdn().
1987 * @param resource $ldapconnection a valid LDAP connection
1988 * @param string $extusername the username to search (in external LDAP encoding, no db slashes)
1989 * @return mixed the user dn (external LDAP encoding) or false
1991 function ldap_find_userdn($ldapconnection, $extusername) {
1992 $ldap_contexts = explode(';', $this->config
->contexts
);
1993 if (!empty($this->config
->create_context
)) {
1994 array_push($ldap_contexts, $this->config
->create_context
);
1997 return ldap_find_userdn($ldapconnection, $extusername, $ldap_contexts, $this->config
->objectclass
,
1998 $this->config
->user_attribute
, $this->config
->search_sub
);
2002 * When using NTLM SSO, the format of the remote username we get in
2003 * $_SERVER['REMOTE_USER'] may vary, depending on where from and how the web
2004 * server gets the data. So we let the admin configure the format using two
2005 * place holders (%domain% and %username%). This function tries to extract
2006 * the username (stripping the domain part and any separators if they are
2007 * present) from the value present in $_SERVER['REMOTE_USER'], using the
2008 * configured format.
2010 * @param string $remoteuser The value from $_SERVER['REMOTE_USER'] (converted to UTF-8)
2012 * @return string The remote username (without domain part or
2013 * separators). Empty string if we can't extract the username.
2015 protected function get_ntlm_remote_user($remoteuser) {
2016 if (empty($this->config
->ntlmsso_remoteuserformat
)) {
2017 $format = AUTH_NTLM_DEFAULT_FORMAT
;
2019 $format = $this->config
->ntlmsso_remoteuserformat
;
2022 $format = preg_quote($format);
2023 $formatregex = preg_replace(array('#%domain%#', '#%username%#'),
2024 array('('.AUTH_NTLM_VALID_DOMAINNAME
.')', '('.AUTH_NTLM_VALID_USERNAME
.')'),
2026 if (preg_match('#^'.$formatregex.'$#', $remoteuser, $matches)) {
2027 $user = end($matches);
2031 /* We are unable to extract the username with the configured format. Probably
2032 * the format specified is wrong, so log a warning for the admin and return
2033 * an empty username.
2035 error_log($this->errorlogtag
.get_string ('auth_ntlmsso_maybeinvalidformat', 'auth_ldap'));
2040 * Check if the diagnostic message for the LDAP login error tells us that the
2041 * login is denied because the user password has expired or the password needs
2042 * to be changed on first login (using interactive SMB/Windows logins, not
2045 * @param string the diagnostic message for the LDAP login error
2046 * @return bool true if the password has expired or the password must be changed on first login
2048 protected function ldap_ad_pwdexpired_from_diagmsg($diagmsg) {
2049 // The format of the diagnostic message is (actual examples from W2003 and W2008):
2050 // "80090308: LdapErr: DSID-0C090334, comment: AcceptSecurityContext error, data 52e, vece" (W2003)
2051 // "80090308: LdapErr: DSID-0C090334, comment: AcceptSecurityContext error, data 773, vece" (W2003)
2052 // "80090308: LdapErr: DSID-0C0903AA, comment: AcceptSecurityContext error, data 52e, v1771" (W2008)
2053 // "80090308: LdapErr: DSID-0C0903AA, comment: AcceptSecurityContext error, data 773, v1771" (W2008)
2054 // We are interested in the 'data nnn' part.
2055 // if nnn == 773 then user must change password on first login
2056 // if nnn == 532 then user password has expired
2057 $diagmsg = explode(',', $diagmsg);
2058 if (preg_match('/data (773|532)/i', trim($diagmsg[2]))) {
2065 * Check if a user is suspended. This function is intended to be used after calling
2066 * get_userinfo_asobj. This is needed because LDAP doesn't have a notion of disabled
2067 * users, however things like MS Active Directory support it and expose information
2070 * @param object $user the user object returned by get_userinfo_asobj
2073 protected function is_user_suspended($user) {
2074 if (!$this->config
->suspended_attribute ||
!isset($user->suspended
)) {
2077 if ($this->config
->suspended_attribute
== 'useraccountcontrol' && $this->config
->user_type
== 'ad') {
2078 return (bool)($user->suspended
& AUTH_AD_ACCOUNTDISABLE
);
2081 return (bool)$user->suspended
;
2085 * Test if settings are correct, print info to output.
2087 public function test_settings() {
2090 if (!function_exists('ldap_connect')) { // Is php-ldap really there?
2091 echo $OUTPUT->notification(get_string('auth_ldap_noextension', 'auth_ldap'));
2095 // Check to see if this is actually configured.
2096 if ((isset($this->config
->host_url
)) && ($this->config
->host_url
!== '')) {
2099 $ldapconn = $this->ldap_connect();
2100 // Try to connect to the LDAP server. See if the page size setting is supported on this server.
2101 $pagedresultssupported = ldap_paged_results_supported($this->config
->ldap_version
, $ldapconn);
2102 } catch (Exception
$e) {
2104 // If we couldn't connect and get the supported options, we can only assume we don't support paged results.
2105 $pagedresultssupported = false;
2108 // Display paged file results.
2109 if ((!$pagedresultssupported)) {
2110 echo $OUTPUT->notification(get_string('pagedresultsnotsupp', 'auth_ldap'), \core\output\notification
::NOTIFY_INFO
);
2111 } else if ($ldapconn) {
2112 // We were able to connect successfuly.
2113 echo $OUTPUT->notification(get_string('connectingldapsuccess', 'auth_ldap'), \core\output\notification
::NOTIFY_SUCCESS
);
2117 // LDAP is not even configured.
2118 echo $OUTPUT->notification(get_string('ldapnotconfigured', 'auth_ldap'), \core\output\notification
::NOTIFY_INFO
);
2123 * Get the list of profile fields.
2125 * @param bool $fetchall Fetch all, not just those for update.
2128 protected function get_profile_keys($fetchall = false) {
2129 $keys = array_keys(get_object_vars($this->config
));
2131 foreach ($keys as $key) {
2132 if (preg_match('/^field_updatelocal_(.+)$/', $key, $match)) {
2133 // If we have a field to update it from and it must be updated 'onlogin' we update it on cron.
2134 if (!empty($this->config
->{'field_map_'.$match[1]})) {
2135 if ($fetchall ||
$this->config
->{$match[0]} === 'onlogin') {
2136 array_push($updatekeys, $match[1]); // the actual key name
2142 if ($this->config
->suspended_attribute
&& $this->config
->sync_suspended
) {
2143 $updatekeys[] = 'suspended';