4 * @author Martin Dougiamas
5 * @author I�aki Arenaza
6 * @license http://www.gnu.org/copyleft/gpl.html GNU Public License
7 * @package moodle multiauth
9 * Authentication Plugin: LDAP Authentication
11 * Authentication using LDAP (Lightweight Directory Access Protocol).
13 * 2006-08-28 File created.
16 if (!defined('MOODLE_INTERNAL')) {
17 die('Direct access to this script is forbidden.'); /// It must be included from a Moodle page
20 // See http://support.microsoft.com/kb/305144 to interprete these values.
21 if (!defined('AUTH_AD_ACCOUNTDISABLE')) {
22 define('AUTH_AD_ACCOUNTDISABLE', 0x0002);
24 if (!defined('AUTH_AD_NORMAL_ACCOUNT')) {
25 define('AUTH_AD_NORMAL_ACCOUNT', 0x0200);
27 if (!defined('AUTH_NTLMTIMEOUT')) { // timewindow for the NTLM SSO process, in secs...
28 define('AUTH_NTLMTIMEOUT', 10);
31 // UF_DONT_EXPIRE_PASSWD value taken from MSDN directly
32 if (!defined('UF_DONT_EXPIRE_PASSWD')) {
33 define ('UF_DONT_EXPIRE_PASSWD', 0x00010000);
36 // The Posix uid and gid of the 'nobody' account and 'nogroup' group.
37 if (!defined('AUTH_UID_NOBODY')) {
38 define('AUTH_UID_NOBODY', -2);
40 if (!defined('AUTH_GID_NOGROUP')) {
41 define('AUTH_GID_NOGROUP', -2);
44 require_once($CFG->libdir.'/authlib.php');
45 require_once($CFG->libdir.'/ldaplib.php');
48 * LDAP authentication plugin.
50 class auth_plugin_ldap extends auth_plugin_base {
53 * Init plugin config from database settings depending on the plugin auth type.
55 function init_plugin($authtype) {
56 $this->pluginconfig = 'auth/'.$authtype;
57 $this->config = get_config($this->pluginconfig);
58 if (empty($this->config->ldapencoding)) {
59 $this->config->ldapencoding = 'utf-8';
61 if (empty($this->config->user_type)) {
62 $this->config->user_type = 'default';
65 $ldap_usertypes = ldap_supported_usertypes();
66 $this->config->user_type_name = $ldap_usertypes[$this->config->user_type];
67 unset($ldap_usertypes);
69 $default = ldap_getdefaults();
71 // Use defaults if values not given
72 foreach ($default as $key => $value) {
73 // watch out - 0, false are correct values too
74 if (!isset($this->config->{$key}) or $this->config->{$key} == '') {
75 $this->config->{$key} = $value[$this->config->user_type];
79 // Hack prefix to objectclass
80 if (empty($this->config->objectclass)) {
81 // Can't send empty filter
82 $this->config->objectclass = '(objectClass=*)';
83 } else if (stripos($this->config->objectclass, 'objectClass=') === 0) {
84 // Value is 'objectClass=some-string-here', so just add ()
85 // around the value (filter _must_ have them).
86 $this->config->objectclass = '('.$this->config->objectclass.')';
87 } else if (strpos($this->config->objectclass, '(') !== 0) {
88 // Value is 'some-string-not-starting-with-left-parentheses',
89 // which is assumed to be the objectClass matching value.
90 // So build a valid filter with it.
91 $this->config->objectclass = '(objectClass='.$this->config->objectclass.')';
93 // There is an additional possible value
94 // '(some-string-here)', that can be used to specify any
95 // valid filter string, to select subsets of users based
96 // on any criteria. For example, we could select the users
97 // whose objectClass is 'user' and have the
98 // 'enabledMoodleUser' attribute, with something like:
100 // (&(objectClass=user)(enabledMoodleUser=1))
102 // In this particular case we don't need to do anything,
103 // so leave $this->config->objectclass as is.
108 * Constructor with initialisation.
110 function auth_plugin_ldap() {
111 $this->authtype = 'ldap';
112 $this->roleauth = 'auth_ldap';
113 $this->errorlogtag = '[AUTH LDAP] ';
114 $this->init_plugin($this->authtype);
118 * Returns true if the username and password work and false if they are
119 * wrong or don't exist.
121 * @param string $username The username (without system magic quotes)
122 * @param string $password The password (without system magic quotes)
124 * @return bool Authentication success or failure.
126 function user_login($username, $password) {
127 if (! function_exists('ldap_bind')) {
128 print_error('auth_ldapnotinstalled', 'auth_ldap');
132 if (!$username or !$password) { // Don't allow blank usernames or passwords
136 $textlib = textlib_get_instance();
137 $extusername = $textlib->convert($username, 'utf-8', $this->config->ldapencoding);
138 $extpassword = $textlib->convert($password, 'utf-8', $this->config->ldapencoding);
140 // Before we connect to LDAP, check if this is an AD SSO login
141 // if we succeed in this block, we'll return success early.
144 if (!empty($this->config->ntlmsso_enabled) && $key === $password) {
145 $cf = get_cache_flags($this->pluginconfig.'/ntlmsess');
146 // We only get the cache flag if we retrieve it before
147 // it expires (AUTH_NTLMTIMEOUT seconds).
148 if (!isset($cf[$key]) || $cf[$key] === '') {
152 $sessusername = $cf[$key];
153 if ($username === $sessusername) {
154 unset($sessusername);
157 // Check that the user is inside one of the configured LDAP contexts
159 $ldapconnection = $this->ldap_connect();
160 // if the user is not inside the configured contexts,
161 // ldap_find_userdn returns false.
162 if ($this->ldap_find_userdn($ldapconnection, $extusername)) {
167 // Shortcut here - SSO confirmed
170 } // End SSO processing
173 $ldapconnection = $this->ldap_connect();
174 $ldap_user_dn = $this->ldap_find_userdn($ldapconnection, $extusername);
176 // If ldap_user_dn is empty, user does not exist
177 if (!$ldap_user_dn) {
182 // Try to bind with current username and password
183 $ldap_login = @ldap_bind($ldapconnection, $ldap_user_dn, $extpassword);
192 * Reads user information from ldap and returns it in array()
194 * Function should return all information available. If you are saving
195 * this information to moodle user-table you should honor syncronization flags
197 * @param string $username username
199 * @return mixed array with no magic quotes or false on error
201 function get_userinfo($username) {
202 $textlib = textlib_get_instance();
203 $extusername = $textlib->convert($username, 'utf-8', $this->config->ldapencoding);
205 $ldapconnection = $this->ldap_connect();
206 if(!($user_dn = $this->ldap_find_userdn($ldapconnection, $extusername))) {
210 $search_attribs = array();
211 $attrmap = $this->ldap_attributes();
212 foreach ($attrmap as $key => $values) {
213 if (!is_array($values)) {
214 $values = array($values);
216 foreach ($values as $value) {
217 if (!in_array($value, $search_attribs)) {
218 array_push($search_attribs, $value);
223 if (!$user_info_result = ldap_read($ldapconnection, $user_dn, '(objectClass=*)', $search_attribs)) {
224 return false; // error!
227 $user_entry = ldap_get_entries_moodle($ldapconnection, $user_info_result);
228 if (empty($user_entry)) {
229 return false; // entry not found
233 foreach ($attrmap as $key => $values) {
234 if (!is_array($values)) {
235 $values = array($values);
238 foreach ($values as $value) {
239 $entry = array_change_key_case($user_entry[0], CASE_LOWER);
240 if (($value == 'dn') || ($value == 'distinguishedname')) {
241 $result[$key] = $user_dn;
244 if (!array_key_exists($value, $entry)) {
245 continue; // wrong data mapping!
247 if (is_array($entry[$value])) {
248 $newval = $textlib->convert($entry[$value][0], $this->config->ldapencoding, 'utf-8');
250 $newval = $textlib->convert($entry[$value], $this->config->ldapencoding, 'utf-8');
252 if (!empty($newval)) { // favour ldap entries that are set
256 if (!is_null($ldapval)) {
257 $result[$key] = $ldapval;
266 * Reads user information from ldap and returns it in an object
268 * @param string $username username (with system magic quotes)
269 * @return mixed object or false on error
271 function get_userinfo_asobj($username) {
272 $user_array = $this->get_userinfo($username);
273 if ($user_array == false) {
274 return false; //error or not found
276 $user_array = truncate_userinfo($user_array);
277 $user = new stdClass();
278 foreach ($user_array as $key=>$value) {
279 $user->{$key} = $value;
285 * Returns all usernames from LDAP
287 * get_userlist returns all usernames from LDAP
291 function get_userlist() {
292 return $this->ldap_get_userlist("({$this->config->user_attribute}=*)");
296 * Checks if user exists on LDAP
298 * @param string $username
300 function user_exists($username) {
301 $textlib = textlib_get_instance();
302 $extusername = $textlib->convert($username, 'utf-8', $this->config->ldapencoding);
304 // Returns true if given username exists on ldap
305 $users = $this->ldap_get_userlist('('.$this->config->user_attribute.'='.ldap_filter_addslashes($extusername).')');
306 return count($users);
310 * Creates a new user on LDAP.
311 * By using information in userobject
312 * Use user_exists to prevent duplicate usernames
314 * @param mixed $userobject Moodle userobject
315 * @param mixed $plainpass Plaintext password
317 function user_create($userobject, $plainpass) {
318 $textlib = textlib_get_instance();
319 $extusername = $textlib->convert($userobject->username, 'utf-8', $this->config->ldapencoding);
320 $extpassword = $textlib->convert($plainpass, 'utf-8', $this->config->ldapencoding);
322 switch ($this->config->passtype) {
324 $extpassword = '{MD5}' . base64_encode(pack('H*', md5($extpassword)));
327 $extpassword = '{SHA}' . base64_encode(pack('H*', sha1($extpassword)));
334 $ldapconnection = $this->ldap_connect();
335 $attrmap = $this->ldap_attributes();
339 foreach ($attrmap as $key => $values) {
340 if (!is_array($values)) {
341 $values = array($values);
343 foreach ($values as $value) {
344 if (!empty($userobject->$key) ) {
345 $newuser[$value] = $textlib->convert($userobject->$key, 'utf-8', $this->config->ldapencoding);
350 //Following sets all mandatory and other forced attribute values
351 //User should be creted as login disabled untill email confirmation is processed
352 //Feel free to add your user type and send patches to paca@sci.fi to add them
353 //Moodle distribution
355 switch ($this->config->user_type) {
357 $newuser['objectClass'] = array('inetOrgPerson', 'organizationalPerson', 'person', 'top');
358 $newuser['uniqueId'] = $extusername;
359 $newuser['logindisabled'] = 'TRUE';
360 $newuser['userpassword'] = $extpassword;
361 $uadd = ldap_add($ldapconnection, $this->config->user_attribute.'='.ldap_addslashes($extusername).','.$this->config->create_context, $newuser);
365 // posixAccount object class forces us to specify a uidNumber
366 // and a gidNumber. That is quite complicated to generate from
367 // Moodle without colliding with existing numbers and without
368 // race conditions. As this user is supposed to be only used
369 // with Moodle (otherwise the user would exist beforehand) and
370 // doesn't need to login into a operating system, we assign the
371 // user the uid of user 'nobody' and gid of group 'nogroup'. In
372 // addition to that, we need to specify a home directory. We
373 // use the root directory ('/') as the home directory, as this
374 // is the only one can always be sure exists. Finally, even if
375 // it's not mandatory, we specify '/bin/false' as the login
376 // shell, to prevent the user from login in at the operating
377 // system level (Moodle ignores this).
379 $newuser['objectClass'] = array('posixAccount', 'inetOrgPerson', 'organizationalPerson', 'person', 'top');
380 $newuser['cn'] = $extusername;
381 $newuser['uid'] = $extusername;
382 $newuser['uidNumber'] = AUTH_UID_NOBODY;
383 $newuser['gidNumber'] = AUTH_GID_NOGROUP;
384 $newuser['homeDirectory'] = '/';
385 $newuser['loginShell'] = '/bin/false';
388 // We have to create the account locked, but posixAccount has
389 // no attribute to achive this reliably. So we are going to
390 // modify the password in a reversable way that we can later
391 // revert in user_activate().
393 // Beware that this can be defeated by the user if we are not
394 // using MD5 or SHA-1 passwords. After all, the source code of
395 // Moodle is available, and the user can see the kind of
396 // modification we are doing and 'undo' it by hand (but only
397 // if we are using plain text passwords).
399 // Also bear in mind that you need to use a binding user that
400 // can create accounts and has read/write privileges on the
401 // 'userPassword' attribute for this to work.
403 $newuser['userPassword'] = '*'.$extpassword;
404 $uadd = ldap_add($ldapconnection, $this->config->user_attribute.'='.ldap_addslashes($extusername).','.$this->config->create_context, $newuser);
407 // User account creation is a two step process with AD. First you
408 // create the user object, then you set the password. If you try
409 // to set the password while creating the user, the operation
412 // Passwords in Active Directory must be encoded as Unicode
413 // strings (UCS-2 Little Endian format) and surrounded with
414 // double quotes. See http://support.microsoft.com/?kbid=269190
415 if (!function_exists('mb_convert_encoding')) {
416 print_error('auth_ldap_no_mbstring', 'auth_ldap');
419 // Check for invalid sAMAccountName characters.
420 if (preg_match('#[/\\[\]:;|=,+*?<>@"]#', $extusername)) {
421 print_error ('auth_ldap_ad_invalidchars', 'auth_ldap');
424 // First create the user account, and mark it as disabled.
425 $newuser['objectClass'] = array('top', 'person', 'user', 'organizationalPerson');
426 $newuser['sAMAccountName'] = $extusername;
427 $newuser['userAccountControl'] = AUTH_AD_NORMAL_ACCOUNT |
428 AUTH_AD_ACCOUNTDISABLE;
429 $userdn = 'cn='.ldap_addslashes($extusername).','.$this->config->create_context;
430 if (!ldap_add($ldapconnection, $userdn, $newuser)) {
431 print_error('auth_ldap_ad_create_req', 'auth_ldap');
434 // Now set the password
436 $newuser['unicodePwd'] = mb_convert_encoding('"' . $extpassword . '"',
438 if(!ldap_modify($ldapconnection, $userdn, $newuser)) {
439 // Something went wrong: delete the user account and error out
440 ldap_delete ($ldapconnection, $userdn);
441 print_error('auth_ldap_ad_create_req', 'auth_ldap');
446 print_error('auth_ldap_unsupportedusertype', 'auth_ldap', '', $this->config->user_type_name);
453 * Returns true if plugin allows resetting of password from moodle.
457 function can_reset_password() {
458 return !empty($this->config->stdchangepassword);
462 * Returns true if plugin allows signup and user creation.
466 function can_signup() {
467 return (!empty($this->config->auth_user_create) and !empty($this->config->create_context));
471 * Sign up a new user ready for confirmation.
472 * Password is passed in plaintext.
474 * @param object $user new user object
475 * @param boolean $notify print notice with link and terminate
477 function user_signup($user, $notify=true) {
478 global $CFG, $DB, $PAGE, $OUTPUT;
480 require_once($CFG->dirroot.'/user/profile/lib.php');
482 if ($this->user_exists($user->username)) {
483 print_error('auth_ldap_user_exists', 'auth_ldap');
486 $plainslashedpassword = $user->password;
487 unset($user->password);
489 if (! $this->user_create($user, $plainslashedpassword)) {
490 print_error('auth_ldap_create_error', 'auth_ldap');
493 $user->id = $DB->insert_record('user', $user);
495 // Save any custom profile field information
496 profile_save_data($user);
498 $this->update_user_record($user->username);
499 update_internal_user_password($user, $plainslashedpassword);
501 $user = $DB->get_record('user', array('id'=>$user->id));
502 events_trigger('user_created', $user);
504 if (! send_confirmation_email($user)) {
505 print_error('noemail', 'auth_ldap');
509 $emailconfirm = get_string('emailconfirm');
510 $PAGE->set_url('/auth/ldap/auth.php');
511 $PAGE->navbar->add($emailconfirm);
512 $PAGE->set_title($emailconfirm);
513 $PAGE->set_heading($emailconfirm);
514 echo $OUTPUT->header();
515 notice(get_string('emailconfirmsent', '', $user->email), "{$CFG->wwwroot}/index.php");
522 * Returns true if plugin allows confirming of new users.
526 function can_confirm() {
527 return $this->can_signup();
531 * Confirm the new user as registered.
533 * @param string $username
534 * @param string $confirmsecret
536 function user_confirm($username, $confirmsecret) {
539 $user = get_complete_user_data('username', $username);
542 if ($user->confirmed) {
543 return AUTH_CONFIRM_ALREADY;
545 } else if ($user->auth != $this->authtype) {
546 return AUTH_CONFIRM_ERROR;
548 } else if ($user->secret == $confirmsecret) { // They have provided the secret key to get in
549 if (!$this->user_activate($username)) {
550 return AUTH_CONFIRM_FAIL;
552 $DB->set_field('user', 'confirmed', 1, array('id'=>$user->id));
553 $DB->set_field('user', 'firstaccess', time(), array('id'=>$user->id));
554 return AUTH_CONFIRM_OK;
557 return AUTH_CONFIRM_ERROR;
562 * Return number of days to user password expires
564 * If userpassword does not expire it should return 0. If password is already expired
565 * it should return negative value.
567 * @param mixed $username username
570 function password_expire($username) {
573 $textlib = textlib_get_instance();
574 $extusername = $textlib->convert($username, 'utf-8', $this->config->ldapencoding);
576 $ldapconnection = $this->ldap_connect();
577 $user_dn = $this->ldap_find_userdn($ldapconnection, $extusername);
578 $search_attribs = array($this->config->expireattr);
579 $sr = ldap_read($ldapconnection, $user_dn, '(objectClass=*)', $search_attribs);
581 $info = ldap_get_entries_moodle($ldapconnection, $sr);
582 $info = array_change_key_case($info, CASE_LOWER);
583 if (!empty ($info) and !empty($info[0][$this->config->expireattr][0])) {
584 $expiretime = $this->ldap_expirationtime2unix($info[0][$this->config->expireattr][0], $ldapconnection, $user_dn);
585 if ($expiretime != 0) {
587 if ($expiretime > $now) {
588 $result = ceil(($expiretime - $now) / DAYSECS);
591 $result = floor(($expiretime - $now) / DAYSECS);
596 error_log($this->errorlogtag.get_string('didtfindexpiretime', 'auth_ldap'));
603 * Syncronizes user fron external LDAP server to moodle user table
605 * Sync is now using username attribute.
607 * Syncing users removes or suspends users that dont exists anymore in external LDAP.
608 * Creates new users and updates coursecreator status of users.
610 * @param bool $do_updates will do pull in data updates from LDAP if relevant
612 function sync_users($do_updates=true) {
615 print_string('connectingldap', 'auth_ldap');
616 $ldapconnection = $this->ldap_connect();
618 $textlib = textlib_get_instance();
619 $dbman = $DB->get_manager();
621 /// Define table user to be created
622 $table = new xmldb_table('tmp_extuser');
623 $table->add_field('id', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, XMLDB_SEQUENCE, null);
624 $table->add_field('username', XMLDB_TYPE_CHAR, '100', null, XMLDB_NOTNULL, null, null);
625 $table->add_field('mnethostid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null);
626 $table->add_key('primary', XMLDB_KEY_PRIMARY, array('id'));
627 $table->add_index('username', XMLDB_INDEX_UNIQUE, array('mnethostid', 'username'));
629 print_string('creatingtemptable', 'auth_ldap', 'tmp_extuser');
630 $dbman->create_temp_table($table);
633 //// get user's list from ldap to sql in a scalable fashion
635 // prepare some data we'll need
636 $filter = '(&('.$this->config->user_attribute.'=*)'.$this->config->objectclass.')';
638 $contexts = explode(';', $this->config->contexts);
640 if (!empty($this->config->create_context)) {
641 array_push($contexts, $this->config->create_context);
645 foreach ($contexts as $context) {
646 $context = trim($context);
647 if (empty($context)) {
650 if ($this->config->search_sub) {
651 //use ldap_search to find first user from subtree
652 $ldap_result = ldap_search($ldapconnection, $context,
654 array($this->config->user_attribute));
656 //search only in this context
657 $ldap_result = ldap_list($ldapconnection, $context,
659 array($this->config->user_attribute));
666 if ($entry = @ldap_first_entry($ldapconnection, $ldap_result)) {
668 $value = ldap_get_values_len($ldapconnection, $entry, $this->config->user_attribute);
669 $value = $textlib->convert($value[0], $this->config->ldapencoding, 'utf-8');
670 $this->ldap_bulk_insert($value);
671 } while ($entry = ldap_next_entry($ldapconnection, $entry));
673 unset($ldap_result); // free mem
676 /// preserve our user database
677 /// if the temp table is empty, it probably means that something went wrong, exit
678 /// so as to avoid mass deletion of users; which is hard to undo
679 $count = $DB->count_records_sql('SELECT COUNT(username) AS count, 1 FROM {tmp_extuser}');
681 print_string('didntgetusersfromldap', 'auth_ldap');
684 print_string('gotcountrecordsfromldap', 'auth_ldap', $count);
689 // Find users in DB that aren't in ldap -- to be removed!
690 // this is still not as scalable (but how often do we mass delete?)
691 if ($this->config->removeuser !== AUTH_REMOVEUSER_KEEP) {
692 $sql = 'SELECT u.id, u.username, u.email, u.auth
694 LEFT JOIN {tmp_extuser} e ON (u.username = e.username AND u.mnethostid = e.mnethostid)
697 AND e.username IS NULL';
698 $remove_users = $DB->get_records_sql($sql, array($this->authtype));
700 if (!empty($remove_users)) {
701 print_string('userentriestoremove', 'auth_ldap', count($remove_users));
703 foreach ($remove_users as $user) {
704 if ($this->config->removeuser == AUTH_REMOVEUSER_FULLDELETE) {
705 if (delete_user($user)) {
706 echo "\t"; print_string('auth_dbdeleteuser', 'auth_db', array('name'=>$user->username, 'id'=>$user->id)); echo "\n";
708 echo "\t"; print_string('auth_dbdeleteusererror', 'auth_db', $user->username); echo "\n";
710 } else if ($this->config->removeuser == AUTH_REMOVEUSER_SUSPEND) {
711 $updateuser = new stdClass();
712 $updateuser->id = $user->id;
713 $updateuser->auth = 'nologin';
714 $DB->update_record('user', $updateuser);
715 echo "\t"; print_string('auth_dbsuspenduser', 'auth_db', array('name'=>$user->username, 'id'=>$user->id)); echo "\n";
719 print_string('nouserentriestoremove', 'auth_ldap');
721 unset($remove_users); // free mem!
724 /// Revive suspended users
725 if (!empty($this->config->removeuser) and $this->config->removeuser == AUTH_REMOVEUSER_SUSPEND) {
726 $sql = "SELECT u.id, u.username
728 JOIN {tmp_extuser} e ON (u.username = e.username AND u.mnethostid = e.mnethostid)
729 WHERE u.auth = 'nologin' AND u.deleted = 0";
730 $revive_users = $DB->get_records_sql($sql);
732 if (!empty($revive_users)) {
733 print_string('userentriestorevive', 'auth_ldap', count($revive_users));
735 foreach ($revive_users as $user) {
736 $updateuser = new stdClass();
737 $updateuser->id = $user->id;
738 $updateuser->auth = $this->authtype;
739 $DB->update_record('user', $updateuser);
740 echo "\t"; print_string('auth_dbreviveduser', 'auth_db', array('name'=>$user->username, 'id'=>$user->id)); echo "\n";
743 print_string('nouserentriestorevive', 'auth_ldap');
746 unset($revive_users);
750 /// User Updates - time-consuming (optional)
752 // Narrow down what fields we need to update
753 $all_keys = array_keys(get_object_vars($this->config));
754 $updatekeys = array();
755 foreach ($all_keys as $key) {
756 if (preg_match('/^field_updatelocal_(.+)$/', $key, $match)) {
757 // If we have a field to update it from
758 // and it must be updated 'onlogin' we
760 if (!empty($this->config->{'field_map_'.$match[1]})
761 and $this->config->{$match[0]} === 'onlogin') {
762 array_push($updatekeys, $match[1]); // the actual key name
766 unset($all_keys); unset($key);
769 print_string('noupdatestobedone', 'auth_ldap');
771 if ($do_updates and !empty($updatekeys)) { // run updates only if relevant
772 $users = $DB->get_records_sql('SELECT u.username, u.id
774 WHERE u.deleted = 0 AND u.auth = ? AND u.mnethostid = ?',
775 array($this->authtype, $CFG->mnet_localhost_id));
776 if (!empty($users)) {
777 print_string('userentriestoupdate', 'auth_ldap', count($users));
779 $sitecontext = get_context_instance(CONTEXT_SYSTEM);
780 if (!empty($this->config->creators) and !empty($this->config->memberattribute)
781 and $roles = get_archetype_roles('coursecreator')) {
782 $creatorrole = array_shift($roles); // We can only use one, let's use the first one
784 $creatorrole = false;
787 $transaction = $DB->start_delegated_transaction();
791 foreach ($users as $user) {
792 echo "\t"; print_string('auth_dbupdatinguser', 'auth_db', array('name'=>$user->username, 'id'=>$user->id));
793 if (!$this->update_user_record($user->username, $updatekeys)) {
794 echo ' - '.get_string('skipped');
799 // Update course creators if needed
800 if ($creatorrole !== false) {
801 if ($this->iscreator($user->username)) {
802 role_assign($creatorrole->id, $user->id, $sitecontext->id, $this->roleauth);
804 role_unassign($creatorrole->id, $user->id, $sitecontext->id, $this->roleauth);
808 $transaction->allow_commit();
809 unset($users); // free mem
811 } else { // end do updates
812 print_string('noupdatestobedone', 'auth_ldap');
816 // Find users missing in DB that are in LDAP
817 // and gives me a nifty object I don't want.
818 // note: we do not care about deleted accounts anymore, this feature was replaced by suspending to nologin auth plugin
819 $sql = 'SELECT e.id, e.username
821 LEFT JOIN {user} u ON (e.username = u.username AND e.mnethostid = u.mnethostid)
823 $add_users = $DB->get_records_sql($sql);
825 if (!empty($add_users)) {
826 print_string('userentriestoadd', 'auth_ldap', count($add_users));
828 $sitecontext = get_context_instance(CONTEXT_SYSTEM);
829 if (!empty($this->config->creators) and !empty($this->config->memberattribute)
830 and $roles = get_archetype_roles('coursecreator')) {
831 $creatorrole = array_shift($roles); // We can only use one, let's use the first one
833 $creatorrole = false;
836 $transaction = $DB->start_delegated_transaction();
837 foreach ($add_users as $user) {
838 $user = $this->get_userinfo_asobj($user->username);
841 $user->modified = time();
842 $user->confirmed = 1;
843 $user->auth = $this->authtype;
844 $user->mnethostid = $CFG->mnet_localhost_id;
845 // get_userinfo_asobj() might have replaced $user->username with the value
846 // from the LDAP server (which can be mixed-case). Make sure it's lowercase
847 $user->username = trim(moodle_strtolower($user->username));
848 if (empty($user->lang)) {
849 $user->lang = $CFG->lang;
852 $id = $DB->insert_record('user', $user);
853 echo "\t"; print_string('auth_dbinsertuser', 'auth_db', array('name'=>$user->username, 'id'=>$id)); echo "\n";
854 if (!empty($this->config->forcechangepassword)) {
855 set_user_preference('auth_forcepasswordchange', 1, $id);
858 // Add course creators if needed
859 if ($creatorrole !== false and $this->iscreator($user->username)) {
860 role_assign($creatorrole->id, $id, $sitecontext->id, $this->roleauth);
864 $transaction->allow_commit();
865 unset($add_users); // free mem
867 print_string('nouserstobeadded', 'auth_ldap');
870 $dbman->drop_temp_table($table);
877 * Update a local user record from an external source.
878 * This is a lighter version of the one in moodlelib -- won't do
879 * expensive ops such as enrolment.
881 * If you don't pass $updatekeys, there is a performance hit and
882 * values removed from LDAP won't be removed from moodle.
884 * @param string $username username
885 * @param boolean $updatekeys true to update the local record with the external LDAP values.
887 function update_user_record($username, $updatekeys = false) {
890 // Just in case check text case
891 $username = trim(moodle_strtolower($username));
893 // Get the current user record
894 $user = $DB->get_record('user', array('username'=>$username, 'mnethostid'=>$CFG->mnet_localhost_id));
895 if (empty($user)) { // trouble
896 error_log($this->errorlogtag.get_string('auth_dbusernotexist', 'auth_db', '', $username));
897 print_error('auth_dbusernotexist', 'auth_db', '', $username);
901 // Protect the userid from being overwritten
904 if ($newinfo = $this->get_userinfo($username)) {
905 $newinfo = truncate_userinfo($newinfo);
907 if (empty($updatekeys)) { // all keys? this does not support removing values
908 $updatekeys = array_keys($newinfo);
911 foreach ($updatekeys as $key) {
912 if (isset($newinfo[$key])) {
913 $value = $newinfo[$key];
918 if (!empty($this->config->{'field_updatelocal_' . $key})) {
919 if ($user->{$key} != $value) { // only update if it's changed
920 $DB->set_field('user', $key, $value, array('id'=>$userid));
927 return $DB->get_record('user', array('id'=>$userid, 'deleted'=>0));
931 * Bulk insert in SQL's temp table
933 function ldap_bulk_insert($username) {
936 $username = moodle_strtolower($username); // usernames are __always__ lowercase.
937 $DB->insert_record_raw('tmp_extuser', array('username'=>$username,
938 'mnethostid'=>$CFG->mnet_localhost_id), false, true);
943 * Activates (enables) user in external LDAP so user can login
945 * @param mixed $username
946 * @return boolean result
948 function user_activate($username) {
949 $textlib = textlib_get_instance();
950 $extusername = $textlib->convert($username, 'utf-8', $this->config->ldapencoding);
952 $ldapconnection = $this->ldap_connect();
954 $userdn = $this->ldap_find_userdn($ldapconnection, $extusername);
955 switch ($this->config->user_type) {
957 $newinfo['loginDisabled'] = 'FALSE';
961 // Remember that we add a '*' character in front of the
962 // external password string to 'disable' the account. We just
963 // need to remove it.
964 $sr = ldap_read($ldapconnection, $userdn, '(objectClass=*)',
965 array('userPassword'));
966 $info = ldap_get_entries($ldapconnection, $sr);
967 $info[0] = array_change_key_case($info[0], CASE_LOWER);
968 $newinfo['userPassword'] = ltrim($info[0]['userpassword'][0], '*');
971 // We need to unset the ACCOUNTDISABLE bit in the
972 // userAccountControl attribute ( see
973 // http://support.microsoft.com/kb/305144 )
974 $sr = ldap_read($ldapconnection, $userdn, '(objectClass=*)',
975 array('userAccountControl'));
976 $info = ldap_get_entries($ldapconnection, $sr);
977 $info[0] = array_change_key_case($info[0], CASE_LOWER);
978 $newinfo['userAccountControl'] = $info[0]['useraccountcontrol'][0]
979 & (~AUTH_AD_ACCOUNTDISABLE);
982 print_error('user_activatenotsupportusertype', 'auth_ldap', '', $this->config->user_type_name);
984 $result = ldap_modify($ldapconnection, $userdn, $newinfo);
990 * Returns true if user should be coursecreator.
992 * @param mixed $username username (without system magic quotes)
993 * @return mixed result null if course creators is not configured, boolean otherwise.
995 function iscreator($username) {
996 if (empty($this->config->creators) or empty($this->config->memberattribute)) {
1000 $textlib = textlib_get_instance();
1001 $extusername = $textlib->convert($username, 'utf-8', $this->config->ldapencoding);
1003 $ldapconnection = $this->ldap_connect();
1005 if ($this->config->memberattribute_isdn) {
1006 if(!($userid = $this->ldap_find_userdn($ldapconnection, $extusername))) {
1010 $userid = $extusername;
1013 $group_dns = explode(';', $this->config->creators);
1014 $creator = ldap_isgroupmember($ldapconnection, $userid, $group_dns, $this->config->memberattribute);
1016 $this->ldap_close();
1022 * Called when the user record is updated.
1024 * Modifies user in external LDAP server. It takes olduser (before
1025 * changes) and newuser (after changes) compares information and
1026 * saves modified information to external LDAP server.
1028 * @param mixed $olduser Userobject before modifications (without system magic quotes)
1029 * @param mixed $newuser Userobject new modified userobject (without system magic quotes)
1030 * @return boolean result
1033 function user_update($olduser, $newuser) {
1036 if (isset($olduser->username) and isset($newuser->username) and $olduser->username != $newuser->username) {
1037 error_log($this->errorlogtag.get_string('renamingnotallowed', 'auth_ldap'));
1041 if (isset($olduser->auth) and $olduser->auth != $this->authtype) {
1042 return true; // just change auth and skip update
1045 $attrmap = $this->ldap_attributes();
1046 // Before doing anything else, make sure we really need to update anything
1047 // in the external LDAP server.
1048 $update_external = false;
1049 foreach ($attrmap as $key => $ldapkeys) {
1050 if (!empty($this->config->{'field_updateremote_'.$key})) {
1051 $update_external = true;
1055 if (!$update_external) {
1059 $textlib = textlib_get_instance();
1060 $extoldusername = $textlib->convert($olduser->username, 'utf-8', $this->config->ldapencoding);
1062 $ldapconnection = $this->ldap_connect();
1064 $search_attribs = array();
1065 foreach ($attrmap as $key => $values) {
1066 if (!is_array($values)) {
1067 $values = array($values);
1069 foreach ($values as $value) {
1070 if (!in_array($value, $search_attribs)) {
1071 array_push($search_attribs, $value);
1076 if(!($user_dn = $this->ldap_find_userdn($ldapconnection, $extoldusername))) {
1080 $user_info_result = ldap_read($ldapconnection, $user_dn, '(objectClass=*)', $search_attribs);
1081 if ($user_info_result) {
1082 $user_entry = ldap_get_entries_moodle($ldapconnection, $user_info_result);
1083 if (empty($user_entry)) {
1084 $attribs = join (', ', $search_attribs);
1085 error_log($this->errorlogtag.get_string('updateusernotfound', 'auth_ldap',
1086 array('userdn'=>$user_dn,
1087 'attribs'=>$attribs)));
1088 return false; // old user not found!
1089 } else if (count($user_entry) > 1) {
1090 error_log($this->errorlogtag.get_string('morethanoneuser', 'auth_ldap'));
1094 $user_entry = array_change_key_case($user_entry[0], CASE_LOWER);
1096 foreach ($attrmap as $key => $ldapkeys) {
1097 // Only process if the moodle field ($key) has changed and we
1098 // are set to update LDAP with it
1099 if (isset($olduser->$key) and isset($newuser->$key)
1100 and $olduser->$key !== $newuser->$key
1101 and !empty($this->config->{'field_updateremote_'. $key})) {
1102 // For ldap values that could be in more than one
1103 // ldap key, we will do our best to match
1104 // where they came from
1107 if (!is_array($ldapkeys)) {
1108 $ldapkeys = array($ldapkeys);
1110 if (count($ldapkeys) < 2) {
1114 $nuvalue = $textlib->convert($newuser->$key, 'utf-8', $this->config->ldapencoding);
1115 empty($nuvalue) ? $nuvalue = array() : $nuvalue;
1116 $ouvalue = $textlib->convert($olduser->$key, 'utf-8', $this->config->ldapencoding);
1118 foreach ($ldapkeys as $ldapkey) {
1119 $ldapkey = $ldapkey;
1120 $ldapvalue = $user_entry[$ldapkey][0];
1122 // Skip update if the values already match
1123 if ($nuvalue !== $ldapvalue) {
1124 // This might fail due to schema validation
1125 if (@ldap_modify($ldapconnection, $user_dn, array($ldapkey => $nuvalue))) {
1128 error_log($this->errorlogtag.get_string ('updateremfail', 'auth_ldap',
1129 array('errno'=>ldap_errno($ldapconnection),
1130 'errstring'=>ldap_err2str(ldap_errno($ldapconnection)),
1132 'ouvalue'=>$ouvalue,
1133 'nuvalue'=>$nuvalue)));
1138 // Ambiguous. Value empty before in Moodle (and LDAP) - use
1139 // 1st ldap candidate field, no need to guess
1140 if ($ouvalue === '') { // value empty before - use 1st ldap candidate
1141 // This might fail due to schema validation
1142 if (@ldap_modify($ldapconnection, $user_dn, array($ldapkey => $nuvalue))) {
1146 error_log($this->errorlogtag.get_string ('updateremfail', 'auth_ldap',
1147 array('errno'=>ldap_errno($ldapconnection),
1148 'errstring'=>ldap_err2str(ldap_errno($ldapconnection)),
1150 'ouvalue'=>$ouvalue,
1151 'nuvalue'=>$nuvalue)));
1156 // We found which ldap key to update!
1157 if ($ouvalue !== '' and $ouvalue === $ldapvalue ) {
1158 // This might fail due to schema validation
1159 if (@ldap_modify($ldapconnection, $user_dn, array($ldapkey => $nuvalue))) {
1163 error_log($this->errorlogtag.get_string ('updateremfail', 'auth_ldap',
1164 array('errno'=>ldap_errno($ldapconnection),
1165 'errstring'=>ldap_err2str(ldap_errno($ldapconnection)),
1167 'ouvalue'=>$ouvalue,
1168 'nuvalue'=>$nuvalue)));
1175 if ($ambiguous and !$changed) {
1176 error_log($this->errorlogtag.get_string ('updateremfailamb', 'auth_ldap',
1178 'ouvalue'=>$ouvalue,
1179 'nuvalue'=>$nuvalue)));
1184 error_log($this->errorlogtag.get_string ('usernotfound', 'auth_ldap'));
1185 $this->ldap_close();
1189 $this->ldap_close();
1195 * Changes userpassword in LDAP
1197 * Called when the user password is updated. It assumes it is
1198 * called by an admin or that you've otherwise checked the user's
1201 * @param object $user User table object
1202 * @param string $newpassword Plaintext password (not crypted/md5'ed)
1203 * @return boolean result
1206 function user_update_password($user, $newpassword) {
1210 $username = $user->username;
1212 $textlib = textlib_get_instance();
1213 $extusername = $textlib->convert($username, 'utf-8', $this->config->ldapencoding);
1214 $extpassword = $textlib->convert($newpassword, 'utf-8', $this->config->ldapencoding);
1216 switch ($this->config->passtype) {
1218 $extpassword = '{MD5}' . base64_encode(pack('H*', md5($extpassword)));
1221 $extpassword = '{SHA}' . base64_encode(pack('H*', sha1($extpassword)));
1228 $ldapconnection = $this->ldap_connect();
1230 $user_dn = $this->ldap_find_userdn($ldapconnection, $extusername);
1233 error_log($this->errorlogtag.get_string ('nodnforusername', 'auth_ldap', $user->username));
1237 switch ($this->config->user_type) {
1240 $result = ldap_modify($ldapconnection, $user_dn, array('userPassword' => $extpassword));
1242 error_log($this->errorlogtag.get_string ('updatepasserror', 'auth_ldap',
1243 array('errno'=>ldap_errno($ldapconnection),
1244 'errstring'=>ldap_err2str(ldap_errno($ldapconnection)))));
1246 // Update password expiration time, grace logins count
1247 $search_attribs = array($this->config->expireattr, 'passwordExpirationInterval', 'loginGraceLimit');
1248 $sr = ldap_read($ldapconnection, $user_dn, '(objectClass=*)', $search_attribs);
1250 $entry = ldap_get_entries_moodle($ldapconnection, $sr);
1251 $info = array_change_key_case($entry[0], CASE_LOWER);
1252 $newattrs = array();
1253 if (!empty($info[$this->config->expireattr][0])) {
1254 // Set expiration time only if passwordExpirationInterval is defined
1255 if (!empty($info['passwordexpirationinterval'][0])) {
1256 $expirationtime = time() + $info['passwordexpirationinterval'][0];
1257 $ldapexpirationtime = $this->ldap_unix2expirationtime($expirationtime);
1258 $newattrs['passwordExpirationTime'] = $ldapexpirationtime;
1261 // Set gracelogin count
1262 if (!empty($info['logingracelimit'][0])) {
1263 $newattrs['loginGraceRemaining']= $info['logingracelimit'][0];
1266 // Store attribute changes in LDAP
1267 $result = ldap_modify($ldapconnection, $user_dn, $newattrs);
1269 error_log($this->errorlogtag.get_string ('updatepasserrorexpiregrace', 'auth_ldap',
1270 array('errno'=>ldap_errno($ldapconnection),
1271 'errstring'=>ldap_err2str(ldap_errno($ldapconnection)))));
1276 error_log($this->errorlogtag.get_string ('updatepasserrorexpire', 'auth_ldap',
1277 array('errno'=>ldap_errno($ldapconnection),
1278 'errstring'=>ldap_err2str(ldap_errno($ldapconnection)))));
1283 // Passwords in Active Directory must be encoded as Unicode
1284 // strings (UCS-2 Little Endian format) and surrounded with
1285 // double quotes. See http://support.microsoft.com/?kbid=269190
1286 if (!function_exists('mb_convert_encoding')) {
1287 error_log($this->errorlogtag.get_string ('needmbstring', 'auth_ldap'));
1290 $extpassword = mb_convert_encoding('"'.$extpassword.'"', "UCS-2LE", $this->config->ldapencoding);
1291 $result = ldap_modify($ldapconnection, $user_dn, array('unicodePwd' => $extpassword));
1293 error_log($this->errorlogtag.get_string ('updatepasserror', 'auth_ldap',
1294 array('errno'=>ldap_errno($ldapconnection),
1295 'errstring'=>ldap_err2str(ldap_errno($ldapconnection)))));
1300 // Send LDAP the password in cleartext, it will md5 it itself
1301 $result = ldap_modify($ldapconnection, $user_dn, array('userPassword' => $extpassword));
1303 error_log($this->errorlogtag.get_string ('updatepasserror', 'auth_ldap',
1304 array('errno'=>ldap_errno($ldapconnection),
1305 'errstring'=>ldap_err2str(ldap_errno($ldapconnection)))));
1310 $this->ldap_close();
1315 * Take expirationtime and return it as unix timestamp in seconds
1317 * Takes expiration timestamp as read from LDAP and returns it as unix timestamp in seconds
1318 * Depends on $this->config->user_type variable
1320 * @param mixed time Time stamp read from LDAP as it is.
1321 * @param string $ldapconnection Only needed for Active Directory.
1322 * @param string $user_dn User distinguished name for the user we are checking password expiration (only needed for Active Directory).
1325 function ldap_expirationtime2unix ($time, $ldapconnection, $user_dn) {
1327 switch ($this->config->user_type) {
1329 $yr=substr($time, 0, 4);
1330 $mo=substr($time, 4, 2);
1331 $dt=substr($time, 6, 2);
1332 $hr=substr($time, 8, 2);
1333 $min=substr($time, 10, 2);
1334 $sec=substr($time, 12, 2);
1335 $result = mktime($hr, $min, $sec, $mo, $dt, $yr);
1339 $result = $time * DAYSECS; // The shadowExpire contains the number of DAYS between 01/01/1970 and the actual expiration date
1342 $result = $this->ldap_get_ad_pwdexpire($time, $ldapconnection, $user_dn);
1345 print_error('auth_ldap_usertypeundefined', 'auth_ldap');
1351 * Takes unix timestamp and returns it formated for storing in LDAP
1353 * @param integer unix time stamp
1355 function ldap_unix2expirationtime($time) {
1357 switch ($this->config->user_type) {
1359 $result=date('YmdHis', $time).'Z';
1363 $result = $time ; // Already in correct format
1366 print_error('auth_ldap_usertypeundefined2', 'auth_ldap');
1373 * Returns user attribute mappings between moodle and LDAP
1378 function ldap_attributes () {
1379 $moodleattributes = array();
1380 foreach ($this->userfields as $field) {
1381 if (!empty($this->config->{"field_map_$field"})) {
1382 $moodleattributes[$field] = moodle_strtolower(trim($this->config->{"field_map_$field"}));
1383 if (preg_match('/,/', $moodleattributes[$field])) {
1384 $moodleattributes[$field] = explode(',', $moodleattributes[$field]); // split ?
1388 $moodleattributes['username'] = moodle_strtolower(trim($this->config->user_attribute));
1389 return $moodleattributes;
1393 * Returns all usernames from LDAP
1395 * @param $filter An LDAP search filter to select desired users
1396 * @return array of LDAP user names converted to UTF-8
1398 function ldap_get_userlist($filter='*') {
1401 $ldapconnection = $this->ldap_connect();
1403 if ($filter == '*') {
1404 $filter = '(&('.$this->config->user_attribute.'=*)'.$this->config->objectclass.')';
1407 $contexts = explode(';', $this->config->contexts);
1408 if (!empty($this->config->create_context)) {
1409 array_push($contexts, $this->config->create_context);
1412 foreach ($contexts as $context) {
1413 $context = trim($context);
1414 if (empty($context)) {
1418 if ($this->config->search_sub) {
1419 // Use ldap_search to find first user from subtree
1420 $ldap_result = ldap_search($ldapconnection, $context,
1422 array($this->config->user_attribute));
1424 // Search only in this context
1425 $ldap_result = ldap_list($ldapconnection, $context,
1427 array($this->config->user_attribute));
1434 $users = ldap_get_entries_moodle($ldapconnection, $ldap_result);
1436 // Add found users to list
1437 $textlib = textlib_get_instance();
1438 for ($i = 0; $i < count($users); $i++) {
1439 $extuser = $textlib->convert($users[$i][$this->config->user_attribute][0],
1440 $this->config->ldapencoding, 'utf-8');
1441 array_push($fresult, $extuser);
1445 $this->ldap_close();
1450 * Indicates if password hashes should be stored in local moodle database.
1452 * @return bool true means flag 'not_cached' stored instead of password hash
1454 function prevent_local_passwords() {
1455 return !empty($this->config->preventpassindb);
1459 * Returns true if this authentication plugin is 'internal'.
1463 function is_internal() {
1468 * Returns true if this authentication plugin can change the user's
1473 function can_change_password() {
1474 return !empty($this->config->stdchangepassword) or !empty($this->config->changepasswordurl);
1478 * Returns the URL for changing the user's password, or empty if the default can
1481 * @return moodle_url
1483 function change_password_url() {
1484 if (empty($this->config->stdchangepassword)) {
1485 return new moodle_url($this->config->changepasswordurl);
1492 * Will get called before the login page is shownr. Ff NTLM SSO
1493 * is enabled, and the user is in the right network, we'll redirect
1494 * to the magic NTLM page for SSO...
1497 function loginpage_hook() {
1498 global $CFG, $SESSION;
1500 // HTTPS is potentially required
1501 //httpsrequired(); - this must be used before setting the URL, it is already done on the login/index.php
1503 if (($_SERVER['REQUEST_METHOD'] === 'GET' // Only on initial GET of loginpage
1504 || ($_SERVER['REQUEST_METHOD'] === 'POST'
1505 && (get_referer() != strip_querystring(qualified_me()))))
1506 // Or when POSTed from another place
1508 && !empty($this->config->ntlmsso_enabled) // SSO enabled
1509 && !empty($this->config->ntlmsso_subnet) // have a subnet to test for
1510 && empty($_GET['authldap_skipntlmsso']) // haven't failed it yet
1511 && (isguestuser() || !isloggedin()) // guestuser or not-logged-in users
1512 && address_in_subnet(getremoteaddr(), $this->config->ntlmsso_subnet)) {
1514 // First, let's remember where we were trying to get to before we got here
1515 if (empty($SESSION->wantsurl)) {
1516 $SESSION->wantsurl = (array_key_exists('HTTP_REFERER', $_SERVER) &&
1517 $_SERVER['HTTP_REFERER'] != $CFG->wwwroot &&
1518 $_SERVER['HTTP_REFERER'] != $CFG->wwwroot.'/' &&
1519 $_SERVER['HTTP_REFERER'] != $CFG->httpswwwroot.'/login/' &&
1520 $_SERVER['HTTP_REFERER'] != $CFG->httpswwwroot.'/login/index.php')
1521 ? $_SERVER['HTTP_REFERER'] : NULL;
1524 // Now start the whole NTLM machinery.
1525 if(!empty($this->config->ntlmsso_ie_fastpath)) {
1526 // Shortcut for IE browsers: skip the attempt page
1527 if(check_browser_version('MSIE')) {
1528 $sesskey = sesskey();
1529 redirect($CFG->wwwroot.'/auth/ldap/ntlmsso_magic.php?sesskey='.$sesskey);
1531 redirect($CFG->httpswwwroot.'/login/index.php?authldap_skipntlmsso=1');
1534 redirect($CFG->wwwroot.'/auth/ldap/ntlmsso_attempt.php');
1538 // No NTLM SSO, Use the normal login page instead.
1540 // If $SESSION->wantsurl is empty and we have a 'Referer:' header, the login
1541 // page insists on redirecting us to that page after user validation. If
1542 // we clicked on the redirect link at the ntlmsso_finish.php page (instead
1543 // of waiting for the redirection to happen) then we have a 'Referer:' header
1544 // we don't want to use at all. As we can't get rid of it, just point
1545 // $SESSION->wantsurl to $CFG->wwwroot (after all, we came from there).
1546 if (empty($SESSION->wantsurl)
1547 && (get_referer() == $CFG->httpswwwroot.'/auth/ldap/ntlmsso_finish.php')) {
1549 $SESSION->wantsurl = $CFG->wwwroot;
1554 * To be called from a page running under NTLM's
1555 * "Integrated Windows Authentication".
1557 * If successful, it will set a special "cookie" (not an HTTP cookie!)
1558 * in cache_flags under the $this->pluginconfig/ntlmsess "plugin" and return true.
1559 * The "cookie" will be picked up by ntlmsso_finish() to complete the
1562 * On failure it will return false for the caller to display an appropriate
1563 * error message (probably saying that Integrated Windows Auth isn't enabled!)
1565 * NOTE that this code will execute under the OS user credentials,
1566 * so we MUST avoid dealing with files -- such as session files.
1567 * (The caller should define('NO_MOODLE_COOKIES', true) before including config.php)
1570 function ntlmsso_magic($sesskey) {
1571 if (isset($_SERVER['REMOTE_USER']) && !empty($_SERVER['REMOTE_USER'])) {
1573 // HTTP __headers__ seem to be sent in ISO-8859-1 encoding
1574 // (according to my reading of RFC-1945, RFC-2616 and RFC-2617 and
1575 // my local tests), so we need to convert the REMOTE_USER value
1576 // (i.e., what we got from the HTTP WWW-Authenticate header) into UTF-8
1577 $textlib = textlib_get_instance();
1578 $username = $textlib->convert($_SERVER['REMOTE_USER'], 'iso-8859-1', 'utf-8');
1580 switch ($this->config->ntlmsso_type) {
1582 // Format is DOMAIN\username
1583 $username = substr(strrchr($username, '\\'), 1);
1586 // Format is username@DOMAIN
1587 $username = substr($username, 0, strpos($username, '@'));
1590 error_log($this->errorlogtag.get_string ('ntlmsso_unknowntype', 'auth_ldap'));
1591 return false; // Should never happen!
1594 $username = moodle_strtolower($username); // Compatibility hack
1595 set_cache_flag($this->pluginconfig.'/ntlmsess', $sesskey, $username, AUTH_NTLMTIMEOUT);
1602 * Find the session set by ntlmsso_magic(), validate it and
1603 * call authenticate_user_login() to authenticate the user through
1604 * the auth machinery.
1606 * It is complemented by a similar check in user_login().
1608 * If it succeeds, it never returns.
1611 function ntlmsso_finish() {
1612 global $CFG, $USER, $SESSION;
1615 $cf = get_cache_flags($this->pluginconfig.'/ntlmsess');
1616 if (!isset($cf[$key]) || $cf[$key] === '') {
1619 $username = $cf[$key];
1620 // Here we want to trigger the whole authentication machinery
1621 // to make sure no step is bypassed...
1622 $user = authenticate_user_login($username, $key);
1624 add_to_log(SITEID, 'user', 'login', "view.php?id=$USER->id&course=".SITEID,
1625 $user->id, 0, $user->id);
1626 complete_user_login($user);
1628 // Cleanup the key to prevent reuse...
1629 // and to allow re-logins with normal credentials
1630 unset_cache_flag($this->pluginconfig.'/ntlmsess', $key);
1633 if (user_not_fully_set_up($USER)) {
1634 $urltogo = $CFG->wwwroot.'/user/edit.php';
1635 // We don't delete $SESSION->wantsurl yet, so we get there later
1636 } else if (isset($SESSION->wantsurl) and (strpos($SESSION->wantsurl, $CFG->wwwroot) === 0)) {
1637 $urltogo = $SESSION->wantsurl; // Because it's an address in this site
1638 unset($SESSION->wantsurl);
1640 // No wantsurl stored or external - go to homepage
1641 $urltogo = $CFG->wwwroot.'/';
1642 unset($SESSION->wantsurl);
1646 // Should never reach here.
1651 * Sync roles for this user
1653 * @param $user object user object (without system magic quotes)
1655 function sync_roles($user) {
1656 $iscreator = $this->iscreator($user->username);
1657 if ($iscreator === null) {
1658 return; // Nothing to sync - creators not configured
1661 if ($roles = get_archetype_roles('coursecreator')) {
1662 $creatorrole = array_shift($roles); // We can only use one, let's use the first one
1663 $systemcontext = get_context_instance(CONTEXT_SYSTEM);
1665 if ($iscreator) { // Following calls will not create duplicates
1666 role_assign($creatorrole->id, $user->id, $systemcontext->id, $this->roleauth);
1668 // Unassign only if previously assigned by this plugin!
1669 role_unassign($creatorrole->id, $user->id, $systemcontext->id, $this->roleauth);
1675 * Prints a form for configuring this authentication plugin.
1677 * This function is called from admin/auth.php, and outputs a full page with
1678 * a form for configuring this plugin.
1680 * @param array $page An object containing all the data for this page.
1682 function config_form($config, $err, $user_fields) {
1683 global $CFG, $OUTPUT;
1685 if (!function_exists('ldap_connect')) { // Is php-ldap really there?
1686 echo $OUTPUT->notification(get_string('auth_ldap_noextension', 'auth_ldap'));
1690 include($CFG->dirroot.'/auth/ldap/config.html');
1694 * Processes and stores configuration data for this authentication plugin.
1696 function process_config($config) {
1697 // Set to defaults if undefined
1698 if (!isset($config->host_url)) {
1699 $config->host_url = '';
1701 if (empty($config->ldapencoding)) {
1702 $config->ldapencoding = 'utf-8';
1704 if (!isset($config->contexts)) {
1705 $config->contexts = '';
1707 if (!isset($config->user_type)) {
1708 $config->user_type = 'default';
1710 if (!isset($config->user_attribute)) {
1711 $config->user_attribute = '';
1713 if (!isset($config->search_sub)) {
1714 $config->search_sub = '';
1716 if (!isset($config->opt_deref)) {
1717 $config->opt_deref = LDAP_DEREF_NEVER;
1719 if (!isset($config->preventpassindb)) {
1720 $config->preventpassindb = 0;
1722 if (!isset($config->bind_dn)) {
1723 $config->bind_dn = '';
1725 if (!isset($config->bind_pw)) {
1726 $config->bind_pw = '';
1728 if (!isset($config->ldap_version)) {
1729 $config->ldap_version = '3';
1731 if (!isset($config->objectclass)) {
1732 $config->objectclass = '';
1734 if (!isset($config->memberattribute)) {
1735 $config->memberattribute = '';
1737 if (!isset($config->memberattribute_isdn)) {
1738 $config->memberattribute_isdn = '';
1740 if (!isset($config->creators)) {
1741 $config->creators = '';
1743 if (!isset($config->create_context)) {
1744 $config->create_context = '';
1746 if (!isset($config->expiration)) {
1747 $config->expiration = '';
1749 if (!isset($config->expiration_warning)) {
1750 $config->expiration_warning = '10';
1752 if (!isset($config->expireattr)) {
1753 $config->expireattr = '';
1755 if (!isset($config->gracelogins)) {
1756 $config->gracelogins = '';
1758 if (!isset($config->graceattr)) {
1759 $config->graceattr = '';
1761 if (!isset($config->auth_user_create)) {
1762 $config->auth_user_create = '';
1764 if (!isset($config->forcechangepassword)) {
1765 $config->forcechangepassword = 0;
1767 if (!isset($config->stdchangepassword)) {
1768 $config->stdchangepassword = 0;
1770 if (!isset($config->passtype)) {
1771 $config->passtype = 'plaintext';
1773 if (!isset($config->changepasswordurl)) {
1774 $config->changepasswordurl = '';
1776 if (!isset($config->removeuser)) {
1777 $config->removeuser = AUTH_REMOVEUSER_KEEP;
1779 if (!isset($config->ntlmsso_enabled)) {
1780 $config->ntlmsso_enabled = 0;
1782 if (!isset($config->ntlmsso_subnet)) {
1783 $config->ntlmsso_subnet = '';
1785 if (!isset($config->ntlmsso_ie_fastpath)) {
1786 $config->ntlmsso_ie_fastpath = 0;
1788 if (!isset($config->ntlmsso_type)) {
1789 $config->ntlmsso_type = 'ntlm';
1793 set_config('host_url', trim($config->host_url), $this->pluginconfig);
1794 set_config('ldapencoding', trim($config->ldapencoding), $this->pluginconfig);
1795 set_config('contexts', trim($config->contexts), $this->pluginconfig);
1796 set_config('user_type', moodle_strtolower(trim($config->user_type)), $this->pluginconfig);
1797 set_config('user_attribute', moodle_strtolower(trim($config->user_attribute)), $this->pluginconfig);
1798 set_config('search_sub', $config->search_sub, $this->pluginconfig);
1799 set_config('opt_deref', $config->opt_deref, $this->pluginconfig);
1800 set_config('preventpassindb', $config->preventpassindb, $this->pluginconfig);
1801 set_config('bind_dn', trim($config->bind_dn), $this->pluginconfig);
1802 set_config('bind_pw', $config->bind_pw, $this->pluginconfig);
1803 set_config('ldap_version', $config->ldap_version, $this->pluginconfig);
1804 set_config('objectclass', trim($config->objectclass), $this->pluginconfig);
1805 set_config('memberattribute', moodle_strtolower(trim($config->memberattribute)), $this->pluginconfig);
1806 set_config('memberattribute_isdn', $config->memberattribute_isdn, $this->pluginconfig);
1807 set_config('creators', trim($config->creators), $this->pluginconfig);
1808 set_config('create_context', trim($config->create_context), $this->pluginconfig);
1809 set_config('expiration', $config->expiration, $this->pluginconfig);
1810 set_config('expiration_warning', trim($config->expiration_warning), $this->pluginconfig);
1811 set_config('expireattr', moodle_strtolower(trim($config->expireattr)), $this->pluginconfig);
1812 set_config('gracelogins', $config->gracelogins, $this->pluginconfig);
1813 set_config('graceattr', moodle_strtolower(trim($config->graceattr)), $this->pluginconfig);
1814 set_config('auth_user_create', $config->auth_user_create, $this->pluginconfig);
1815 set_config('forcechangepassword', $config->forcechangepassword, $this->pluginconfig);
1816 set_config('stdchangepassword', $config->stdchangepassword, $this->pluginconfig);
1817 set_config('passtype', $config->passtype, $this->pluginconfig);
1818 set_config('changepasswordurl', trim($config->changepasswordurl), $this->pluginconfig);
1819 set_config('removeuser', $config->removeuser, $this->pluginconfig);
1820 set_config('ntlmsso_enabled', (int)$config->ntlmsso_enabled, $this->pluginconfig);
1821 set_config('ntlmsso_subnet', trim($config->ntlmsso_subnet), $this->pluginconfig);
1822 set_config('ntlmsso_ie_fastpath', (int)$config->ntlmsso_ie_fastpath, $this->pluginconfig);
1823 set_config('ntlmsso_type', $config->ntlmsso_type, 'auth/ldap');
1829 * Get password expiration time for a given user from Active Directory
1831 * @param string $pwdlastset The time last time we changed the password.
1832 * @param resource $lcapconn The open LDAP connection.
1833 * @param string $user_dn The distinguished name of the user we are checking.
1835 * @return string $unixtime
1837 function ldap_get_ad_pwdexpire($pwdlastset, $ldapconn, $user_dn){
1840 if (!function_exists('bcsub')) {
1841 error_log($this->errorlogtag.get_string ('needbcmath', 'auth_ldap'));
1845 // If UF_DONT_EXPIRE_PASSWD flag is set in user's
1846 // userAccountControl attribute, the password doesn't expire.
1847 $sr = ldap_read($ldapconn, $user_dn, '(objectClass=*)',
1848 array('userAccountControl'));
1850 error_log($this->errorlogtag.get_string ('useracctctrlerror', 'auth_ldap', $user_dn));
1851 // Don't expire password, as we are not sure if it has to be
1856 $entry = ldap_get_entries_moodle($ldapconn, $sr);
1857 $info = array_change_key_case($entry[0], CASE_LOWER);
1858 $useraccountcontrol = $info['useraccountcontrol'][0];
1859 if ($useraccountcontrol & UF_DONT_EXPIRE_PASSWD) {
1860 // Password doesn't expire.
1864 // If pwdLastSet is zero, the user must change his/her password now
1865 // (unless UF_DONT_EXPIRE_PASSWD flag is set, but we already
1866 // tested this above)
1867 if ($pwdlastset === '0') {
1868 // Password has expired
1872 // ----------------------------------------------------------------
1873 // Password expiration time in Active Directory is the composition of
1876 // - User's pwdLastSet attribute, that stores the last time
1877 // the password was changed.
1879 // - Domain's maxPwdAge attribute, that sets how long
1880 // passwords last in this domain.
1882 // We already have the first value (passed in as a parameter). We
1883 // need to get the second one. As we don't know the domain DN, we
1884 // have to query rootDSE's defaultNamingContext attribute to get
1885 // it. Then we have to query that DN's maxPwdAge attribute to get
1888 // Once we have both values, we just need to combine them. But MS
1889 // chose to use a different base and unit for time measurements.
1890 // So we need to convert the values to Unix timestamps (see
1892 // ----------------------------------------------------------------
1894 $sr = ldap_read($ldapconn, ROOTDSE, '(objectClass=*)',
1895 array('defaultNamingContext'));
1897 error_log($this->errorlogtag.get_string ('rootdseerror', 'auth_ldap'));
1901 $entry = ldap_get_entries_moodle($ldapconn, $sr);
1902 $info = array_change_key_case($entry[0], CASE_LOWER);
1903 $domaindn = $info['defaultnamingcontext'][0];
1905 $sr = ldap_read ($ldapconn, $domaindn, '(objectClass=*)',
1906 array('maxPwdAge'));
1907 $entry = ldap_get_entries_moodle($ldapconn, $sr);
1908 $info = array_change_key_case($entry[0], CASE_LOWER);
1909 $maxpwdage = $info['maxpwdage'][0];
1911 // ----------------------------------------------------------------
1912 // MSDN says that "pwdLastSet contains the number of 100 nanosecond
1913 // intervals since January 1, 1601 (UTC), stored in a 64 bit integer".
1915 // According to Perl's Date::Manip, the number of seconds between
1916 // this date and Unix epoch is 11644473600. So we have to
1917 // substract this value to calculate a Unix time, once we have
1918 // scaled pwdLastSet to seconds. This is the script used to
1919 // calculate the value shown above:
1921 // #!/usr/bin/perl -w
1925 // $date1 = ParseDate ("160101010000 UTC");
1926 // $date2 = ParseDate ("197001010000 UTC");
1927 // $delta = DateCalc($date1, $date2, \$err);
1928 // $secs = Delta_Format($delta, 0, "%st");
1929 // print "$secs \n";
1931 // MSDN also says that "maxPwdAge is stored as a large integer that
1932 // represents the number of 100 nanosecond intervals from the time
1933 // the password was set before the password expires." We also need
1934 // to scale this to seconds. Bear in mind that this value is stored
1935 // as a _negative_ quantity (at least in my AD domain).
1937 // As a last remark, if the low 32 bits of maxPwdAge are equal to 0,
1938 // the maximum password age in the domain is set to 0, which means
1939 // passwords do not expire (see
1940 // http://msdn2.microsoft.com/en-us/library/ms974598.aspx)
1942 // As the quantities involved are too big for PHP integers, we
1943 // need to use BCMath functions to work with arbitrary precision
1945 // ----------------------------------------------------------------
1947 // If the low order 32 bits are 0, then passwords do not expire in
1948 // the domain. Just do '$maxpwdage mod 2^32' and check the result
1949 // (2^32 = 4294967296)
1950 if (bcmod ($maxpwdage, 4294967296) === '0') {
1954 // Add up pwdLastSet and maxPwdAge to get password expiration
1955 // time, in MS time units. Remember maxPwdAge is stored as a
1956 // _negative_ quantity, so we need to substract it in fact.
1957 $pwdexpire = bcsub ($pwdlastset, $maxpwdage);
1959 // Scale the result to convert it to Unix time units and return
1961 return bcsub( bcdiv($pwdexpire, '10000000'), '11644473600');
1965 * Connect to the LDAP server, using the plugin configured
1966 * settings. It's actually a wrapper around ldap_connect_moodle()
1968 * @return resource A valid LDAP connection (or dies if it can't connect)
1970 function ldap_connect() {
1971 // Cache ldap connections. They are expensive to set up
1972 // and can drain the TCP/IP ressources on the server if we
1973 // are syncing a lot of users (as we try to open a new connection
1974 // to get the user details). This is the least invasive way
1975 // to reuse existing connections without greater code surgery.
1976 if(!empty($this->ldapconnection)) {
1978 return $this->ldapconnection;
1981 if($ldapconnection = ldap_connect_moodle($this->config->host_url, $this->config->ldap_version,
1982 $this->config->user_type, $this->config->bind_dn,
1983 $this->config->bind_pw, $this->config->opt_deref,
1985 $this->ldapconns = 1;
1986 $this->ldapconnection = $ldapconnection;
1987 return $ldapconnection;
1990 print_error('auth_ldap_noconnect_all', 'auth_ldap', '', $debuginfo);
1994 * Disconnects from a LDAP server
1997 function ldap_close() {
1999 if($this->ldapconns == 0) {
2000 @ldap_close($this->ldapconnection);
2001 unset($this->ldapconnection);
2006 * Search specified contexts for username and return the user dn
2007 * like: cn=username,ou=suborg,o=org. It's actually a wrapper
2008 * around ldap_find_userdn().
2010 * @param resource $ldapconnection a valid LDAP connection
2011 * @param string $extusername the username to search (in external LDAP encoding, no db slashes)
2012 * @return mixed the user dn (external LDAP encoding) or false
2014 function ldap_find_userdn($ldapconnection, $extusername) {
2015 $ldap_contexts = explode(';', $this->config->contexts);
2016 if (!empty($this->config->create_context)) {
2017 array_push($ldap_contexts, $this->config->create_context);
2020 return ldap_find_userdn($ldapconnection, $extusername, $ldap_contexts, $this->config->objectclass,
2021 $this->config->user_attribute, $this->config->search_sub);
2024 } // End of the class