MDL-22449 help string update
[moodle.git] / auth / ldap / auth.php
blob26de941c54a2eca1c7337e17bd756478a1b71305
1 <?php
3 /**
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');
47 /**
48 * LDAP authentication plugin.
50 class auth_plugin_ldap extends auth_plugin_base {
52 /**
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.')';
92 } else {
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');
129 return false;
132 if (!$username or !$password) { // Don't allow blank usernames or passwords
133 return false;
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.
143 $key = sesskey();
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] === '') {
149 return false;
152 $sessusername = $cf[$key];
153 if ($username === $sessusername) {
154 unset($sessusername);
155 unset($cf);
157 // Check that the user is inside one of the configured LDAP contexts
158 $validuser = false;
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)) {
163 $validuser = true;
165 $this->ldap_close();
167 // Shortcut here - SSO confirmed
168 return $validuser;
170 } // End SSO processing
171 unset($key);
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) {
178 $this->ldap_close();
179 return false;
182 // Try to bind with current username and password
183 $ldap_login = @ldap_bind($ldapconnection, $ldap_user_dn, $extpassword);
184 $this->ldap_close();
185 if ($ldap_login) {
186 return true;
188 return false;
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))) {
207 return false;
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
232 $result = array();
233 foreach ($attrmap as $key => $values) {
234 if (!is_array($values)) {
235 $values = array($values);
237 $ldapval = NULL;
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;
242 continue;
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');
249 } else {
250 $newval = $textlib->convert($entry[$value], $this->config->ldapencoding, 'utf-8');
252 if (!empty($newval)) { // favour ldap entries that are set
253 $ldapval = $newval;
256 if (!is_null($ldapval)) {
257 $result[$key] = $ldapval;
261 $this->ldap_close();
262 return $result;
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 object();
278 foreach ($user_array as $key=>$value) {
279 $user->{$key} = $value;
281 return $user;
285 * Returns all usernames from LDAP
287 * get_userlist returns all usernames from LDAP
289 * @return array
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) {
323 case 'md5':
324 $extpassword = '{MD5}' . base64_encode(pack('H*', md5($extpassword)));
325 break;
326 case 'sha1':
327 $extpassword = '{SHA}' . base64_encode(pack('H*', sha1($extpassword)));
328 break;
329 case 'plaintext':
330 default:
331 break; // plaintext
334 $ldapconnection = $this->ldap_connect();
335 $attrmap = $this->ldap_attributes();
337 $newuser = array();
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) {
356 case 'edir':
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);
362 break;
363 case 'rfc2307':
364 case 'rfc2307bis':
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';
387 // IMPORTANT:
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);
405 break;
406 case 'ad':
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
410 // fails.
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
435 unset($newuser);
436 $newuser['unicodePwd'] = mb_convert_encoding('"' . $extpassword . '"',
437 'UCS-2LE', 'UTF-8');
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');
443 $uadd = true;
444 break;
445 default:
446 print_error('auth_ldap_unsupportedusertype', 'auth_ldap', '', $this->config->user_type_name);
448 $this->ldap_close();
449 return $uadd;
453 * Returns true if plugin allows resetting of password from moodle.
455 * @return bool
457 function can_reset_password() {
458 return !empty($this->config->stdchangepassword);
462 * Returns true if plugin allows signup and user creation.
464 * @return bool
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 if (! ($user->id = $DB->insert_record('user', $user)) ) {
494 print_error('auth_emailnoinsert', 'auth_email');
497 // Save any custom profile field information
498 profile_save_data($user);
500 $this->update_user_record($user->username);
501 update_internal_user_password($user, $plainslashedpassword);
503 $user = $DB->get_record('user', array('id'=>$user->id));
504 events_trigger('user_created', $user);
506 if (! send_confirmation_email($user)) {
507 print_error('auth_emailnoemail', 'auth_email');
510 if ($notify) {
511 $emailconfirm = get_string('emailconfirm');
512 $PAGE->set_url('/auth/ldap/auth.php');
513 $PAGE->navbar->add($emailconfirm);
514 $PAGE->set_title($emailconfirm);
515 $PAGE->set_heading($emailconfirm);
516 echo $OUTPUT->header();
517 notice(get_string('emailconfirmsent', '', $user->email), "{$CFG->wwwroot}/index.php");
518 } else {
519 return true;
524 * Returns true if plugin allows confirming of new users.
526 * @return bool
528 function can_confirm() {
529 return $this->can_signup();
533 * Confirm the new user as registered.
535 * @param string $username
536 * @param string $confirmsecret
538 function user_confirm($username, $confirmsecret) {
539 global $DB;
541 $user = get_complete_user_data('username', $username);
543 if (!empty($user)) {
544 if ($user->confirmed) {
545 return AUTH_CONFIRM_ALREADY;
547 } else if ($user->auth != $this->authtype) {
548 return AUTH_CONFIRM_ERROR;
550 } else if ($user->secret == $confirmsecret) { // They have provided the secret key to get in
551 if (!$this->user_activate($username)) {
552 return AUTH_CONFIRM_FAIL;
554 if (!$DB->set_field('user', 'confirmed', 1, array('id'=>$user->id))) {
555 return AUTH_CONFIRM_FAIL;
557 if (!$DB->set_field('user', 'firstaccess', time(), array('id'=>$user->id))) {
558 return AUTH_CONFIRM_FAIL;
560 return AUTH_CONFIRM_OK;
562 } else {
563 return AUTH_CONFIRM_ERROR;
568 * Return number of days to user password expires
570 * If userpassword does not expire it should return 0. If password is already expired
571 * it should return negative value.
573 * @param mixed $username username
574 * @return integer
576 function password_expire($username) {
577 $result = 0;
579 $textlib = textlib_get_instance();
580 $extusername = $textlib->convert($username, 'utf-8', $this->config->ldapencoding);
582 $ldapconnection = $this->ldap_connect();
583 $user_dn = $this->ldap_find_userdn($ldapconnection, $extusername);
584 $search_attribs = array($this->config->expireattr);
585 $sr = ldap_read($ldapconnection, $user_dn, '(objectClass=*)', $search_attribs);
586 if ($sr) {
587 $info = ldap_get_entries_moodle($ldapconnection, $sr);
588 $info = array_change_key_case($info, CASE_LOWER);
589 if (!empty ($info) and !empty($info[0][$this->config->expireattr][0])) {
590 $expiretime = $this->ldap_expirationtime2unix($info[0][$this->config->expireattr][0], $ldapconnection, $user_dn);
591 if ($expiretime != 0) {
592 $now = time();
593 if ($expiretime > $now) {
594 $result = ceil(($expiretime - $now) / DAYSECS);
596 else {
597 $result = floor(($expiretime - $now) / DAYSECS);
601 } else {
602 error_log($this->errorlogtag.get_string('didtfindexpiretime', 'auth_ldap'));
605 return $result;
609 * Syncronizes user fron external LDAP server to moodle user table
611 * Sync is now using username attribute.
613 * Syncing users removes or suspends users that dont exists anymore in external LDAP.
614 * Creates new users and updates coursecreator status of users.
616 * @param bool $do_updates will do pull in data updates from LDAP if relevant
618 function sync_users($do_updates=true) {
619 global $CFG, $DB;
621 print_string('connectingldap', 'auth_ldap');
622 $ldapconnection = $this->ldap_connect();
624 $textlib = textlib_get_instance();
625 $dbman = $DB->get_manager();
627 /// Define table user to be created
628 $table = new xmldb_table('tmp_extuser');
629 $table->add_field('id', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, XMLDB_SEQUENCE, null);
630 $table->add_field('username', XMLDB_TYPE_CHAR, '100', null, XMLDB_NOTNULL, null, null);
631 $table->add_field('mnethostid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null);
632 $table->add_key('primary', XMLDB_KEY_PRIMARY, array('id'));
633 $table->add_index('username', XMLDB_INDEX_UNIQUE, array('mnethostid', 'username'));
635 print_string('creatingtemptable', 'auth_ldap', 'tmp_extuser');
636 $dbman->create_temp_table($table);
638 ////
639 //// get user's list from ldap to sql in a scalable fashion
640 ////
641 // prepare some data we'll need
642 $filter = '(&('.$this->config->user_attribute.'=*)'.$this->config->objectclass.')';
644 $contexts = explode(';', $this->config->contexts);
646 if (!empty($this->config->create_context)) {
647 array_push($contexts, $this->config->create_context);
650 $fresult = array();
651 foreach ($contexts as $context) {
652 $context = trim($context);
653 if (empty($context)) {
654 continue;
656 if ($this->config->search_sub) {
657 //use ldap_search to find first user from subtree
658 $ldap_result = ldap_search($ldapconnection, $context,
659 $filter,
660 array($this->config->user_attribute));
661 } else {
662 //search only in this context
663 $ldap_result = ldap_list($ldapconnection, $context,
664 $filter,
665 array($this->config->user_attribute));
668 if(!$ldap_result) {
669 continue;
672 if ($entry = @ldap_first_entry($ldapconnection, $ldap_result)) {
673 do {
674 $value = ldap_get_values_len($ldapconnection, $entry, $this->config->user_attribute);
675 $value = $textlib->convert($value[0], $this->config->ldapencoding, 'utf-8');
676 $this->ldap_bulk_insert($value);
677 } while ($entry = ldap_next_entry($ldapconnection, $entry));
679 unset($ldap_result); // free mem
682 /// preserve our user database
683 /// if the temp table is empty, it probably means that something went wrong, exit
684 /// so as to avoid mass deletion of users; which is hard to undo
685 $count = $DB->count_records_sql('SELECT COUNT(username) AS count, 1 FROM {tmp_extuser}');
686 if ($count < 1) {
687 print_string('didntgetusersfromldap', 'auth_ldap');
688 exit;
689 } else {
690 print_string('gotcountrecordsfromldap', 'auth_ldap', $count);
694 /// User removal
695 // Find users in DB that aren't in ldap -- to be removed!
696 // this is still not as scalable (but how often do we mass delete?)
697 if ($this->config->removeuser !== AUTH_REMOVEUSER_KEEP) {
698 $sql = 'SELECT u.id, u.username, u.email, u.auth
699 FROM {user} u
700 LEFT JOIN {tmp_extuser} e ON (u.username = e.username AND u.mnethostid = e.mnethostid)
701 WHERE u.auth = ?
702 AND u.deleted = 0
703 AND e.username IS NULL';
704 $remove_users = $DB->get_records_sql($sql, array($this->authtype));
706 if (!empty($remove_users)) {
707 print_string('userentriestoremove', 'auth_ldap', count($remove_users));
709 foreach ($remove_users as $user) {
710 if ($this->config->removeuser == AUTH_REMOVEUSER_FULLDELETE) {
711 if (delete_user($user)) {
712 echo "\t"; print_string('auth_dbdeleteuser', 'auth_db', array('name'=>$user->username, 'id'=>$user->id)); echo "\n";
713 } else {
714 echo "\t"; print_string('auth_dbdeleteusererror', 'auth_db', $user->username); echo "\n";
716 } else if ($this->config->removeuser == AUTH_REMOVEUSER_SUSPEND) {
717 $updateuser = new object();
718 $updateuser->id = $user->id;
719 $updateuser->auth = 'nologin';
720 if ($DB->update_record('user', $updateuser)) {
721 echo "\t"; print_string('auth_dbsuspenduser', 'auth_db', array('name'=>$user->username, 'id'=>$user->id)); echo "\n";
722 } else {
723 echo "\t"; print_string('auth_dbsuspendusererror', 'auth_db', $user->username); echo "\n";
727 } else {
728 print_string('nouserentriestoremove', 'auth_ldap');
730 unset($remove_users); // free mem!
733 /// Revive suspended users
734 if (!empty($this->config->removeuser) and $this->config->removeuser == AUTH_REMOVEUSER_SUSPEND) {
735 $sql = "SELECT u.id, u.username
736 FROM {user} u
737 JOIN {tmp_extuser} e ON (u.username = e.username AND u.mnethostid = e.mnethostid)
738 WHERE u.auth = 'nologin' AND u.deleted = 0";
739 $revive_users = $DB->get_records_sql($sql);
741 if (!empty($revive_users)) {
742 print_string('userentriestorevive', 'auth_ldap', count($revive_users));
744 foreach ($revive_users as $user) {
745 $updateuser = new object();
746 $updateuser->id = $user->id;
747 $updateuser->auth = $this->authtype;
748 if ($DB->update_record('user', $updateuser)) {
749 echo "\t"; print_string('auth_dbreviveduser', 'auth_db', array('name'=>$user->username, 'id'=>$user->id)); echo "\n";
750 } else {
751 echo "\t"; print_string('auth_dbrevivedusererror', 'auth_db', $user->username); echo "\n";
754 } else {
755 print_string('nouserentriestorevive', 'auth_ldap');
758 unset($revive_users);
762 /// User Updates - time-consuming (optional)
763 if ($do_updates) {
764 // Narrow down what fields we need to update
765 $all_keys = array_keys(get_object_vars($this->config));
766 $updatekeys = array();
767 foreach ($all_keys as $key) {
768 if (preg_match('/^field_updatelocal_(.+)$/', $key, $match)) {
769 // If we have a field to update it from
770 // and it must be updated 'onlogin' we
771 // update it on cron
772 if (!empty($this->config->{'field_map_'.$match[1]})
773 and $this->config->{$match[0]} === 'onlogin') {
774 array_push($updatekeys, $match[1]); // the actual key name
778 unset($all_keys); unset($key);
780 } else {
781 print_string('noupdatestobedone', 'auth_ldap');
783 if ($do_updates and !empty($updatekeys)) { // run updates only if relevant
784 $users = $DB->get_records_sql('SELECT u.username, u.id
785 FROM {user} u
786 WHERE u.deleted = 0 AND u.auth = ? AND u.mnethostid = ?',
787 array($this->authtype, $CFG->mnet_localhost_id));
788 if (!empty($users)) {
789 print_string('userentriestoupdate', 'auth_ldap', count($users));
791 $sitecontext = get_context_instance(CONTEXT_SYSTEM);
792 if (!empty($this->config->creators) and !empty($this->config->memberattribute)
793 and $roles = get_archetype_roles('coursecreator')) {
794 $creatorrole = array_shift($roles); // We can only use one, let's use the first one
795 } else {
796 $creatorrole = false;
799 $transaction = $DB->start_delegated_transaction();
800 $xcount = 0;
801 $maxxcount = 100;
803 foreach ($users as $user) {
804 echo "\t"; print_string('auth_dbupdatinguser', 'auth_db', array('name'=>$user->username, 'id'=>$user->id));
805 if (!$this->update_user_record($user->username, $updatekeys)) {
806 echo ' - '.get_string('skipped');
808 echo "\n";
809 $xcount++;
811 // Update course creators if needed
812 if ($creatorrole !== false) {
813 if ($this->iscreator($user->username)) {
814 role_assign($creatorrole->id, $user->id, $sitecontext->id, $this->roleauth);
815 } else {
816 role_unassign($creatorrole->id, $user->id, $sitecontext->id, $this->roleauth);
820 $transaction->allow_commit();
821 unset($users); // free mem
823 } else { // end do updates
824 print_string('noupdatestobedone', 'auth_ldap');
827 /// User Additions
828 // Find users missing in DB that are in LDAP
829 // and gives me a nifty object I don't want.
830 // note: we do not care about deleted accounts anymore, this feature was replaced by suspending to nologin auth plugin
831 $sql = 'SELECT e.id, e.username
832 FROM {tmp_extuser} e
833 LEFT JOIN {user} u ON (e.username = u.username AND e.mnethostid = u.mnethostid)
834 WHERE u.id IS NULL';
835 $add_users = $DB->get_records_sql($sql);
837 if (!empty($add_users)) {
838 print_string('userentriestoadd', 'auth_ldap', count($add_users));
840 $sitecontext = get_context_instance(CONTEXT_SYSTEM);
841 if (!empty($this->config->creators) and !empty($this->config->memberattribute)
842 and $roles = get_archetype_roles('coursecreator')) {
843 $creatorrole = array_shift($roles); // We can only use one, let's use the first one
844 } else {
845 $creatorrole = false;
848 $transaction = $DB->start_delegated_transaction();
849 foreach ($add_users as $user) {
850 $user = $this->get_userinfo_asobj($user->username);
852 // Prep a few params
853 $user->modified = time();
854 $user->confirmed = 1;
855 $user->auth = $this->authtype;
856 $user->mnethostid = $CFG->mnet_localhost_id;
857 // get_userinfo_asobj() might have replaced $user->username with the value
858 // from the LDAP server (which can be mixed-case). Make sure it's lowercase
859 $user->username = trim(moodle_strtolower($user->username));
860 if (empty($user->lang)) {
861 $user->lang = $CFG->lang;
864 if ($id = $DB->insert_record('user', $user)) {
865 echo "\t"; print_string('auth_dbinsertuser', 'auth_db', array('name'=>$user->username, 'id'=>$id)); echo "\n";
866 if (!empty($this->config->forcechangepassword)) {
867 set_user_preference('auth_forcepasswordchange', 1, $id);
869 } else {
870 echo "\t"; print_string('auth_dbinsertusererror', 'auth_db', $user->username); echo "\n";
873 // Add course creators if needed
874 if ($creatorrole !== false and $this->iscreator($user->username)) {
875 role_assign($creatorrole->id, $user->id, $sitecontext->id, $this->roleauth);
878 $transaction->allow_commit();
879 unset($add_users); // free mem
880 } else {
881 print_string('nouserstobeadded', 'auth_ldap');
884 $dbman->drop_temp_table($table);
885 $this->ldap_close();
887 return true;
891 * Update a local user record from an external source.
892 * This is a lighter version of the one in moodlelib -- won't do
893 * expensive ops such as enrolment.
895 * If you don't pass $updatekeys, there is a performance hit and
896 * values removed from LDAP won't be removed from moodle.
898 * @param string $username username
899 * @param boolean $updatekeys true to update the local record with the external LDAP values.
901 function update_user_record($username, $updatekeys = false) {
902 global $CFG, $DB;
904 // Just in case check text case
905 $username = trim(moodle_strtolower($username));
907 // Get the current user record
908 $user = $DB->get_record('user', array('username'=>$username, 'mnethostid'=>$CFG->mnet_localhost_id));
909 if (empty($user)) { // trouble
910 error_log($this->errorlogtag.get_string('auth_dbusernotexist', 'auth_db', '', $username));
911 print_error('auth_dbusernotexist', 'auth_db', '', $username);
912 die;
915 // Protect the userid from being overwritten
916 $userid = $user->id;
918 if ($newinfo = $this->get_userinfo($username)) {
919 $newinfo = truncate_userinfo($newinfo);
921 if (empty($updatekeys)) { // all keys? this does not support removing values
922 $updatekeys = array_keys($newinfo);
925 foreach ($updatekeys as $key) {
926 if (isset($newinfo[$key])) {
927 $value = $newinfo[$key];
928 } else {
929 $value = '';
932 if (!empty($this->config->{'field_updatelocal_' . $key})) {
933 if ($user->{$key} != $value) { // only update if it's changed
934 $DB->set_field('user', $key, $value, array('id'=>$userid));
938 } else {
939 return false;
941 return $DB->get_record('user', array('id'=>$userid, 'deleted'=>0));
945 * Bulk insert in SQL's temp table
947 function ldap_bulk_insert($username) {
948 global $DB, $CFG;
950 $username = moodle_strtolower($username); // usernames are __always__ lowercase.
951 $DB->insert_record_raw('tmp_extuser', array('username'=>$username,
952 'mnethostid'=>$CFG->mnet_localhost_id), false, true);
953 echo '.';
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 $textlib = textlib_get_instance();
964 $extusername = $textlib->convert($username, 'utf-8', $this->config->ldapencoding);
966 $ldapconnection = $this->ldap_connect();
968 $userdn = $this->ldap_find_userdn($ldapconnection, $extusername);
969 switch ($this->config->user_type) {
970 case 'edir':
971 $newinfo['loginDisabled'] = 'FALSE';
972 break;
973 case 'rfc2307':
974 case 'rfc2307bis':
975 // Remember that we add a '*' character in front of the
976 // external password string to 'disable' the account. We just
977 // need to remove it.
978 $sr = ldap_read($ldapconnection, $userdn, '(objectClass=*)',
979 array('userPassword'));
980 $info = ldap_get_entries($ldapconnection, $sr);
981 $info[0] = array_change_key_case($info[0], CASE_LOWER);
982 $newinfo['userPassword'] = ltrim($info[0]['userpassword'][0], '*');
983 break;
984 case 'ad':
985 // We need to unset the ACCOUNTDISABLE bit in the
986 // userAccountControl attribute ( see
987 // http://support.microsoft.com/kb/305144 )
988 $sr = ldap_read($ldapconnection, $userdn, '(objectClass=*)',
989 array('userAccountControl'));
990 $info = ldap_get_entries($ldapconnection, $sr);
991 $info[0] = array_change_key_case($info[0], CASE_LOWER);
992 $newinfo['userAccountControl'] = $info[0]['useraccountcontrol'][0]
993 & (~AUTH_AD_ACCOUNTDISABLE);
994 break;
995 default:
996 print_error('user_activatenotsupportusertype', 'auth_ldap', '', $this->config->user_type_name);
998 $result = ldap_modify($ldapconnection, $userdn, $newinfo);
999 $this->ldap_close();
1000 return $result;
1004 * Returns true if user should be coursecreator.
1006 * @param mixed $username username (without system magic quotes)
1007 * @return mixed result null if course creators is not configured, boolean otherwise.
1009 function iscreator($username) {
1010 if (empty($this->config->creators) or empty($this->config->memberattribute)) {
1011 return null;
1014 $textlib = textlib_get_instance();
1015 $extusername = $textlib->convert($username, 'utf-8', $this->config->ldapencoding);
1017 $ldapconnection = $this->ldap_connect();
1019 if ($this->config->memberattribute_isdn) {
1020 if(!($userid = $this->ldap_find_userdn($ldapconnection, $extusername))) {
1021 return false;
1023 } else {
1024 $userid = $extusername;
1027 $group_dns = explode(';', $this->config->creators);
1028 $creator = ldap_isgroupmember($ldapconnection, $userid, $group_dns, $this->config->memberattribute);
1030 $this->ldap_close();
1032 return $creator;
1036 * Called when the user record is updated.
1038 * Modifies user in external LDAP server. It takes olduser (before
1039 * changes) and newuser (after changes) compares information and
1040 * saves modified information to external LDAP server.
1042 * @param mixed $olduser Userobject before modifications (without system magic quotes)
1043 * @param mixed $newuser Userobject new modified userobject (without system magic quotes)
1044 * @return boolean result
1047 function user_update($olduser, $newuser) {
1048 global $USER;
1050 if (isset($olduser->username) and isset($newuser->username) and $olduser->username != $newuser->username) {
1051 error_log($this->errorlogtag.get_string('renamingnotallowed', 'auth_ldap'));
1052 return false;
1055 if (isset($olduser->auth) and $olduser->auth != $this->authtype) {
1056 return true; // just change auth and skip update
1059 $attrmap = $this->ldap_attributes();
1060 // Before doing anything else, make sure we really need to update anything
1061 // in the external LDAP server.
1062 $update_external = false;
1063 foreach ($attrmap as $key => $ldapkeys) {
1064 if (!empty($this->config->{'field_updateremote_'.$key})) {
1065 $update_external = true;
1066 break;
1069 if (!$update_external) {
1070 return true;
1073 $textlib = textlib_get_instance();
1074 $extoldusername = $textlib->convert($olduser->username, 'utf-8', $this->config->ldapencoding);
1076 $ldapconnection = $this->ldap_connect();
1078 $search_attribs = array();
1079 foreach ($attrmap as $key => $values) {
1080 if (!is_array($values)) {
1081 $values = array($values);
1083 foreach ($values as $value) {
1084 if (!in_array($value, $search_attribs)) {
1085 array_push($search_attribs, $value);
1090 if(!($user_dn = $this->ldap_find_userdn($ldapconnection, $extoldusername))) {
1091 return false;
1094 $user_info_result = ldap_read($ldapconnection, $user_dn, '(objectClass=*)', $search_attribs);
1095 if ($user_info_result) {
1096 $user_entry = ldap_get_entries_moodle($ldapconnection, $user_info_result);
1097 if (empty($user_entry)) {
1098 $attribs = join (', ', $search_attribs);
1099 error_log($this->errorlogtag.get_string('updateusernotfound', 'auth_ldap',
1100 array('userdn'=>$user_dn,
1101 'attribs'=>$attribs)));
1102 return false; // old user not found!
1103 } else if (count($user_entry) > 1) {
1104 error_log($this->errorlogtag.get_string('morethanoneuser', 'auth_ldap'));
1105 return false;
1108 $user_entry = array_change_key_case($user_entry[0], CASE_LOWER);
1110 foreach ($attrmap as $key => $ldapkeys) {
1111 // Only process if the moodle field ($key) has changed and we
1112 // are set to update LDAP with it
1113 if (isset($olduser->$key) and isset($newuser->$key)
1114 and $olduser->$key !== $newuser->$key
1115 and !empty($this->config->{'field_updateremote_'. $key})) {
1116 // For ldap values that could be in more than one
1117 // ldap key, we will do our best to match
1118 // where they came from
1119 $ambiguous = true;
1120 $changed = false;
1121 if (!is_array($ldapkeys)) {
1122 $ldapkeys = array($ldapkeys);
1124 if (count($ldapkeys) < 2) {
1125 $ambiguous = false;
1128 $nuvalue = $textlib->convert($newuser->$key, 'utf-8', $this->config->ldapencoding);
1129 empty($nuvalue) ? $nuvalue = array() : $nuvalue;
1130 $ouvalue = $textlib->convert($olduser->$key, 'utf-8', $this->config->ldapencoding);
1132 foreach ($ldapkeys as $ldapkey) {
1133 $ldapkey = $ldapkey;
1134 $ldapvalue = $user_entry[$ldapkey][0];
1135 if (!$ambiguous) {
1136 // Skip update if the values already match
1137 if ($nuvalue !== $ldapvalue) {
1138 // This might fail due to schema validation
1139 if (@ldap_modify($ldapconnection, $user_dn, array($ldapkey => $nuvalue))) {
1140 continue;
1141 } else {
1142 error_log($this->errorlogtag.get_string ('updateremfail', 'auth_ldap',
1143 array('errno'=>ldap_errno($ldapconnection),
1144 'errstring'=>ldap_err2str(ldap_errno($ldapconnection)),
1145 'key'=>$key,
1146 'ouvalue'=>$ouvalue,
1147 'nuvalue'=>$nuvalue)));
1148 continue;
1151 } else {
1152 // Ambiguous. Value empty before in Moodle (and LDAP) - use
1153 // 1st ldap candidate field, no need to guess
1154 if ($ouvalue === '') { // value empty before - use 1st ldap candidate
1155 // This might fail due to schema validation
1156 if (@ldap_modify($ldapconnection, $user_dn, array($ldapkey => $nuvalue))) {
1157 $changed = true;
1158 continue;
1159 } else {
1160 error_log($this->errorlogtag.get_string ('updateremfail', 'auth_ldap',
1161 array('errno'=>ldap_errno($ldapconnection),
1162 'errstring'=>ldap_err2str(ldap_errno($ldapconnection)),
1163 'key'=>$key,
1164 'ouvalue'=>$ouvalue,
1165 'nuvalue'=>$nuvalue)));
1166 continue;
1170 // We found which ldap key to update!
1171 if ($ouvalue !== '' and $ouvalue === $ldapvalue ) {
1172 // This might fail due to schema validation
1173 if (@ldap_modify($ldapconnection, $user_dn, array($ldapkey => $nuvalue))) {
1174 $changed = true;
1175 continue;
1176 } else {
1177 error_log($this->errorlogtag.get_string ('updateremfail', 'auth_ldap',
1178 array('errno'=>ldap_errno($ldapconnection),
1179 'errstring'=>ldap_err2str(ldap_errno($ldapconnection)),
1180 'key'=>$key,
1181 'ouvalue'=>$ouvalue,
1182 'nuvalue'=>$nuvalue)));
1183 continue;
1189 if ($ambiguous and !$changed) {
1190 error_log($this->errorlogtag.get_string ('updateremfailamb', 'auth_ldap',
1191 array('key'=>$key,
1192 'ouvalue'=>$ouvalue,
1193 'nuvalue'=>$nuvalue)));
1197 } else {
1198 error_log($this->errorlogtag.get_string ('usernotfound', 'auth_ldap'));
1199 $this->ldap_close();
1200 return false;
1203 $this->ldap_close();
1204 return true;
1209 * Changes userpassword in LDAP
1211 * Called when the user password is updated. It assumes it is
1212 * called by an admin or that you've otherwise checked the user's
1213 * credentials
1215 * @param object $user User table object
1216 * @param string $newpassword Plaintext password (not crypted/md5'ed)
1217 * @return boolean result
1220 function user_update_password($user, $newpassword) {
1221 global $USER;
1223 $result = false;
1224 $username = $user->username;
1226 $textlib = textlib_get_instance();
1227 $extusername = $textlib->convert($username, 'utf-8', $this->config->ldapencoding);
1228 $extpassword = $textlib->convert($newpassword, 'utf-8', $this->config->ldapencoding);
1230 switch ($this->config->passtype) {
1231 case 'md5':
1232 $extpassword = '{MD5}' . base64_encode(pack('H*', md5($extpassword)));
1233 break;
1234 case 'sha1':
1235 $extpassword = '{SHA}' . base64_encode(pack('H*', sha1($extpassword)));
1236 break;
1237 case 'plaintext':
1238 default:
1239 break; // plaintext
1242 $ldapconnection = $this->ldap_connect();
1244 $user_dn = $this->ldap_find_userdn($ldapconnection, $extusername);
1246 if (!$user_dn) {
1247 error_log($this->errorlogtag.get_string ('nodnforusername', 'auth_ldap', $user->username));
1248 return false;
1251 switch ($this->config->user_type) {
1252 case 'edir':
1253 // Change password
1254 $result = ldap_modify($ldapconnection, $user_dn, array('userPassword' => $extpassword));
1255 if (!$result) {
1256 error_log($this->errorlogtag.get_string ('updatepasserror', 'auth_ldap',
1257 array('errno'=>ldap_errno($ldapconnection),
1258 'errstring'=>ldap_err2str(ldap_errno($ldapconnection)))));
1260 // Update password expiration time, grace logins count
1261 $search_attribs = array($this->config->expireattr, 'passwordExpirationInterval', 'loginGraceLimit');
1262 $sr = ldap_read($ldapconnection, $user_dn, '(objectClass=*)', $search_attribs);
1263 if ($sr) {
1264 $entry = ldap_get_entries_moodle($ldapconnection, $sr);
1265 $info = array_change_key_case($entry[0], CASE_LOWER);
1266 $newattrs = array();
1267 if (!empty($info[$this->config->expireattr][0])) {
1268 // Set expiration time only if passwordExpirationInterval is defined
1269 if (!empty($info['passwordexpirationinterval'][0])) {
1270 $expirationtime = time() + $info['passwordexpirationinterval'][0];
1271 $ldapexpirationtime = $this->ldap_unix2expirationtime($expirationtime);
1272 $newattrs['passwordExpirationTime'] = $ldapexpirationtime;
1275 // Set gracelogin count
1276 if (!empty($info['logingracelimit'][0])) {
1277 $newattrs['loginGraceRemaining']= $info['logingracelimit'][0];
1280 // Store attribute changes in LDAP
1281 $result = ldap_modify($ldapconnection, $user_dn, $newattrs);
1282 if (!$result) {
1283 error_log($this->errorlogtag.get_string ('updatepasserrorexpiregrace', 'auth_ldap',
1284 array('errno'=>ldap_errno($ldapconnection),
1285 'errstring'=>ldap_err2str(ldap_errno($ldapconnection)))));
1289 else {
1290 error_log($this->errorlogtag.get_string ('updatepasserrorexpire', 'auth_ldap',
1291 array('errno'=>ldap_errno($ldapconnection),
1292 'errstring'=>ldap_err2str(ldap_errno($ldapconnection)))));
1294 break;
1296 case 'ad':
1297 // Passwords in Active Directory must be encoded as Unicode
1298 // strings (UCS-2 Little Endian format) and surrounded with
1299 // double quotes. See http://support.microsoft.com/?kbid=269190
1300 if (!function_exists('mb_convert_encoding')) {
1301 error_log($this->errorlogtag.get_string ('needmbstring', 'auth_ldap'));
1302 return false;
1304 $extpassword = mb_convert_encoding('"'.$extpassword.'"', "UCS-2LE", $this->config->ldapencoding);
1305 $result = ldap_modify($ldapconnection, $user_dn, array('unicodePwd' => $extpassword));
1306 if (!$result) {
1307 error_log($this->errorlogtag.get_string ('updatepasserror', 'auth_ldap',
1308 array('errno'=>ldap_errno($ldapconnection),
1309 'errstring'=>ldap_err2str(ldap_errno($ldapconnection)))));
1311 break;
1313 default:
1314 // Send LDAP the password in cleartext, it will md5 it itself
1315 $result = ldap_modify($ldapconnection, $user_dn, array('userPassword' => $extpassword));
1316 if (!$result) {
1317 error_log($this->errorlogtag.get_string ('updatepasserror', 'auth_ldap',
1318 array('errno'=>ldap_errno($ldapconnection),
1319 'errstring'=>ldap_err2str(ldap_errno($ldapconnection)))));
1324 $this->ldap_close();
1325 return $result;
1329 * Take expirationtime and return it as unix timestamp in seconds
1331 * Takes expiration timestamp as read from LDAP and returns it as unix timestamp in seconds
1332 * Depends on $this->config->user_type variable
1334 * @param mixed time Time stamp read from LDAP as it is.
1335 * @param string $ldapconnection Only needed for Active Directory.
1336 * @param string $user_dn User distinguished name for the user we are checking password expiration (only needed for Active Directory).
1337 * @return timestamp
1339 function ldap_expirationtime2unix ($time, $ldapconnection, $user_dn) {
1340 $result = false;
1341 switch ($this->config->user_type) {
1342 case 'edir':
1343 $yr=substr($time, 0, 4);
1344 $mo=substr($time, 4, 2);
1345 $dt=substr($time, 6, 2);
1346 $hr=substr($time, 8, 2);
1347 $min=substr($time, 10, 2);
1348 $sec=substr($time, 12, 2);
1349 $result = mktime($hr, $min, $sec, $mo, $dt, $yr);
1350 break;
1351 case 'rfc2307':
1352 case 'rfc2307bis':
1353 $result = $time * DAYSECS; // The shadowExpire contains the number of DAYS between 01/01/1970 and the actual expiration date
1354 break;
1355 case 'ad':
1356 $result = $this->ldap_get_ad_pwdexpire($time, $ldapconnection, $user_dn);
1357 break;
1358 default:
1359 print_error('auth_ldap_usertypeundefined', 'auth_ldap');
1361 return $result;
1365 * Takes unix timestamp and returns it formated for storing in LDAP
1367 * @param integer unix time stamp
1369 function ldap_unix2expirationtime($time) {
1370 $result = false;
1371 switch ($this->config->user_type) {
1372 case 'edir':
1373 $result=date('YmdHis', $time).'Z';
1374 break;
1375 case 'rfc2307':
1376 case 'rfc2307bis':
1377 $result = $time ; // Already in correct format
1378 break;
1379 default:
1380 print_error('auth_ldap_usertypeundefined2', 'auth_ldap');
1382 return $result;
1387 * Returns user attribute mappings between moodle and LDAP
1389 * @return array
1392 function ldap_attributes () {
1393 $moodleattributes = array();
1394 foreach ($this->userfields as $field) {
1395 if (!empty($this->config->{"field_map_$field"})) {
1396 $moodleattributes[$field] = moodle_strtolower(trim($this->config->{"field_map_$field"}));
1397 if (preg_match('/,/', $moodleattributes[$field])) {
1398 $moodleattributes[$field] = explode(',', $moodleattributes[$field]); // split ?
1402 $moodleattributes['username'] = $this->config->user_attribute;
1403 return $moodleattributes;
1407 * Returns all usernames from LDAP
1409 * @param $filter An LDAP search filter to select desired users
1410 * @return array of LDAP user names converted to UTF-8
1412 function ldap_get_userlist($filter='*') {
1413 $fresult = array();
1415 $ldapconnection = $this->ldap_connect();
1417 if ($filter == '*') {
1418 $filter = '(&('.$this->config->user_attribute.'=*)'.$this->config->objectclass.')';
1421 $contexts = explode(';', $this->config->contexts);
1422 if (!empty($this->config->create_context)) {
1423 array_push($contexts, $this->config->create_context);
1426 foreach ($contexts as $context) {
1427 $context = trim($context);
1428 if (empty($context)) {
1429 continue;
1432 if ($this->config->search_sub) {
1433 // Use ldap_search to find first user from subtree
1434 $ldap_result = ldap_search($ldapconnection, $context,
1435 $filter,
1436 array($this->config->user_attribute));
1437 } else {
1438 // Search only in this context
1439 $ldap_result = ldap_list($ldapconnection, $context,
1440 $filter,
1441 array($this->config->user_attribute));
1444 if(!$ldap_result) {
1445 continue;
1448 $users = ldap_get_entries_moodle($ldapconnection, $ldap_result);
1450 // Add found users to list
1451 $textlib = textlib_get_instance();
1452 for ($i = 0; $i < count($users); $i++) {
1453 $extuser = $textlib->convert($users[$i][$this->config->user_attribute][0],
1454 $this->config->ldapencoding, 'utf-8');
1455 array_push($fresult, $extuser);
1459 $this->ldap_close();
1460 return $fresult;
1464 * Indicates if password hashes should be stored in local moodle database.
1466 * @return bool true means flag 'not_cached' stored instead of password hash
1468 function prevent_local_passwords() {
1469 return !empty($this->config->preventpassindb);
1473 * Returns true if this authentication plugin is 'internal'.
1475 * @return bool
1477 function is_internal() {
1478 return false;
1482 * Returns true if this authentication plugin can change the user's
1483 * password.
1485 * @return bool
1487 function can_change_password() {
1488 return !empty($this->config->stdchangepassword) or !empty($this->config->changepasswordurl);
1492 * Returns the URL for changing the user's password, or empty if the default can
1493 * be used.
1495 * @return string url
1497 function change_password_url() {
1498 if (empty($this->config->stdchangepassword)) {
1499 return $this->config->changepasswordurl;
1500 } else {
1501 return '';
1506 * Will get called before the login page is shownr. Ff NTLM SSO
1507 * is enabled, and the user is in the right network, we'll redirect
1508 * to the magic NTLM page for SSO...
1511 function loginpage_hook() {
1512 global $CFG, $SESSION;
1514 // HTTPS is potentially required
1515 httpsrequired();
1517 if (($_SERVER['REQUEST_METHOD'] === 'GET' // Only on initial GET of loginpage
1518 || ($_SERVER['REQUEST_METHOD'] === 'POST'
1519 && (get_referer() != strip_querystring(qualified_me()))))
1520 // Or when POSTed from another place
1521 // See MDL-14071
1522 && !empty($this->config->ntlmsso_enabled) // SSO enabled
1523 && !empty($this->config->ntlmsso_subnet) // have a subnet to test for
1524 && empty($_GET['authldap_skipntlmsso']) // haven't failed it yet
1525 && (isguestuser() || !isloggedin()) // guestuser or not-logged-in users
1526 && address_in_subnet(getremoteaddr(), $this->config->ntlmsso_subnet)) {
1528 // First, let's remember where we were trying to get to before we got here
1529 if (empty($SESSION->wantsurl)) {
1530 $SESSION->wantsurl = (array_key_exists('HTTP_REFERER', $_SERVER) &&
1531 $_SERVER['HTTP_REFERER'] != $CFG->wwwroot &&
1532 $_SERVER['HTTP_REFERER'] != $CFG->wwwroot.'/' &&
1533 $_SERVER['HTTP_REFERER'] != $CFG->httpswwwroot.'/login/' &&
1534 $_SERVER['HTTP_REFERER'] != $CFG->httpswwwroot.'/login/index.php')
1535 ? $_SERVER['HTTP_REFERER'] : NULL;
1538 // Now start the whole NTLM machinery.
1539 if(!empty($this->config->ntlmsso_ie_fastpath)) {
1540 // Shortcut for IE browsers: skip the attempt page
1541 if(check_browser_version('MSIE')) {
1542 $sesskey = sesskey();
1543 redirect($CFG->wwwroot.'/auth/ldap/ntlmsso_magic.php?sesskey='.$sesskey);
1544 } else {
1545 redirect($CFG->httpswwwroot.'/login/index.php?authldap_skipntlmsso=1');
1547 } else {
1548 redirect($CFG->wwwroot.'/auth/ldap/ntlmsso_attempt.php');
1552 // No NTLM SSO, Use the normal login page instead.
1554 // If $SESSION->wantsurl is empty and we have a 'Referer:' header, the login
1555 // page insists on redirecting us to that page after user validation. If
1556 // we clicked on the redirect link at the ntlmsso_finish.php page (instead
1557 // of waiting for the redirection to happen) then we have a 'Referer:' header
1558 // we don't want to use at all. As we can't get rid of it, just point
1559 // $SESSION->wantsurl to $CFG->wwwroot (after all, we came from there).
1560 if (empty($SESSION->wantsurl)
1561 && (get_referer() == $CFG->httpswwwroot.'/auth/ldap/ntlmsso_finish.php')) {
1563 $SESSION->wantsurl = $CFG->wwwroot;
1568 * To be called from a page running under NTLM's
1569 * "Integrated Windows Authentication".
1571 * If successful, it will set a special "cookie" (not an HTTP cookie!)
1572 * in cache_flags under the $this->pluginconfig/ntlmsess "plugin" and return true.
1573 * The "cookie" will be picked up by ntlmsso_finish() to complete the
1574 * process.
1576 * On failure it will return false for the caller to display an appropriate
1577 * error message (probably saying that Integrated Windows Auth isn't enabled!)
1579 * NOTE that this code will execute under the OS user credentials,
1580 * so we MUST avoid dealing with files -- such as session files.
1581 * (The caller should define('NO_MOODLE_COOKIES', true) before including config.php)
1584 function ntlmsso_magic($sesskey) {
1585 if (isset($_SERVER['REMOTE_USER']) && !empty($_SERVER['REMOTE_USER'])) {
1587 // HTTP __headers__ seem to be sent in ISO-8859-1 encoding
1588 // (according to my reading of RFC-1945, RFC-2616 and RFC-2617 and
1589 // my local tests), so we need to convert the REMOTE_USER value
1590 // (i.e., what we got from the HTTP WWW-Authenticate header) into UTF-8
1591 $textlib = textlib_get_instance();
1592 $username = $textlib->convert($_SERVER['REMOTE_USER'], 'iso-8859-1', 'utf-8');
1594 switch ($this->config->ntlmsso_type) {
1595 case 'ntlm':
1596 // Format is DOMAIN\username
1597 $username = substr(strrchr($username, '\\'), 1);
1598 break;
1599 case 'kerberos':
1600 // Format is username@DOMAIN
1601 $username = substr($username, 0, strpos($username, '@'));
1602 break;
1603 default:
1604 error_log($this->errorlogtag.get_string ('ntlmsso_unknowntype', 'auth_ldap'));
1605 return false; // Should never happen!
1608 $username = moodle_strtolower($username); // Compatibility hack
1609 set_cache_flag($this->pluginconfig.'/ntlmsess', $sesskey, $username, AUTH_NTLMTIMEOUT);
1610 return true;
1612 return false;
1616 * Find the session set by ntlmsso_magic(), validate it and
1617 * call authenticate_user_login() to authenticate the user through
1618 * the auth machinery.
1620 * It is complemented by a similar check in user_login().
1622 * If it succeeds, it never returns.
1625 function ntlmsso_finish() {
1626 global $CFG, $USER, $SESSION;
1628 $key = sesskey();
1629 $cf = get_cache_flags($this->pluginconfig.'/ntlmsess');
1630 if (!isset($cf[$key]) || $cf[$key] === '') {
1631 return false;
1633 $username = $cf[$key];
1634 // Here we want to trigger the whole authentication machinery
1635 // to make sure no step is bypassed...
1636 $user = authenticate_user_login($username, $key);
1637 if ($user) {
1638 add_to_log(SITEID, 'user', 'login', "view.php?id=$USER->id&course=".SITEID,
1639 $user->id, 0, $user->id);
1640 complete_user_login($user);
1642 // Cleanup the key to prevent reuse...
1643 // and to allow re-logins with normal credentials
1644 unset_cache_flag($this->pluginconfig.'/ntlmsess', $key);
1646 // Redirection
1647 if (user_not_fully_set_up($USER)) {
1648 $urltogo = $CFG->wwwroot.'/user/edit.php';
1649 // We don't delete $SESSION->wantsurl yet, so we get there later
1650 } else if (isset($SESSION->wantsurl) and (strpos($SESSION->wantsurl, $CFG->wwwroot) === 0)) {
1651 $urltogo = $SESSION->wantsurl; // Because it's an address in this site
1652 unset($SESSION->wantsurl);
1653 } else {
1654 // No wantsurl stored or external - go to homepage
1655 $urltogo = $CFG->wwwroot.'/';
1656 unset($SESSION->wantsurl);
1658 redirect($urltogo);
1660 // Should never reach here.
1661 return false;
1665 * Sync roles for this user
1667 * @param $user object user object (without system magic quotes)
1669 function sync_roles($user) {
1670 $iscreator = $this->iscreator($user->username);
1671 if ($iscreator === null) {
1672 return; // Nothing to sync - creators not configured
1675 if ($roles = get_archetype_roles('coursecreator')) {
1676 $creatorrole = array_shift($roles); // We can only use one, let's use the first one
1677 $systemcontext = get_context_instance(CONTEXT_SYSTEM);
1679 if ($iscreator) { // Following calls will not create duplicates
1680 role_assign($creatorrole->id, $user->id, $systemcontext->id, $this->roleauth);
1681 } else {
1682 // Unassign only if previously assigned by this plugin!
1683 role_unassign($creatorrole->id, $user->id, $systemcontext->id, $this->roleauth);
1689 * Prints a form for configuring this authentication plugin.
1691 * This function is called from admin/auth.php, and outputs a full page with
1692 * a form for configuring this plugin.
1694 * @param array $page An object containing all the data for this page.
1696 function config_form($config, $err, $user_fields) {
1697 global $CFG, $OUTPUT;
1699 if (!function_exists('ldap_connect')) { // Is php-ldap really there?
1700 echo $OUTPUT->notification(get_string('auth_ldap_noextension', 'auth_ldap'));
1701 return;
1704 include($CFG->dirroot.'/auth/ldap/config.html');
1708 * Processes and stores configuration data for this authentication plugin.
1710 function process_config($config) {
1711 // Set to defaults if undefined
1712 if (!isset($config->host_url)) {
1713 $config->host_url = '';
1715 if (empty($config->ldapencoding)) {
1716 $config->ldapencoding = 'utf-8';
1718 if (!isset($config->contexts)) {
1719 $config->contexts = '';
1721 if (!isset($config->user_type)) {
1722 $config->user_type = 'default';
1724 if (!isset($config->user_attribute)) {
1725 $config->user_attribute = '';
1727 if (!isset($config->search_sub)) {
1728 $config->search_sub = '';
1730 if (!isset($config->opt_deref)) {
1731 $config->opt_deref = LDAP_DEREF_NEVER;
1733 if (!isset($config->preventpassindb)) {
1734 $config->preventpassindb = 0;
1736 if (!isset($config->bind_dn)) {
1737 $config->bind_dn = '';
1739 if (!isset($config->bind_pw)) {
1740 $config->bind_pw = '';
1742 if (!isset($config->ldap_version)) {
1743 $config->ldap_version = '3';
1745 if (!isset($config->objectclass)) {
1746 $config->objectclass = '';
1748 if (!isset($config->memberattribute)) {
1749 $config->memberattribute = '';
1751 if (!isset($config->memberattribute_isdn)) {
1752 $config->memberattribute_isdn = '';
1754 if (!isset($config->creators)) {
1755 $config->creators = '';
1757 if (!isset($config->create_context)) {
1758 $config->create_context = '';
1760 if (!isset($config->expiration)) {
1761 $config->expiration = '';
1763 if (!isset($config->expiration_warning)) {
1764 $config->expiration_warning = '10';
1766 if (!isset($config->expireattr)) {
1767 $config->expireattr = '';
1769 if (!isset($config->gracelogins)) {
1770 $config->gracelogins = '';
1772 if (!isset($config->graceattr)) {
1773 $config->graceattr = '';
1775 if (!isset($config->auth_user_create)) {
1776 $config->auth_user_create = '';
1778 if (!isset($config->forcechangepassword)) {
1779 $config->forcechangepassword = 0;
1781 if (!isset($config->stdchangepassword)) {
1782 $config->stdchangepassword = 0;
1784 if (!isset($config->passtype)) {
1785 $config->passtype = 'plaintext';
1787 if (!isset($config->changepasswordurl)) {
1788 $config->changepasswordurl = '';
1790 if (!isset($config->removeuser)) {
1791 $config->removeuser = AUTH_REMOVEUSER_KEEP;
1793 if (!isset($config->ntlmsso_enabled)) {
1794 $config->ntlmsso_enabled = 0;
1796 if (!isset($config->ntlmsso_subnet)) {
1797 $config->ntlmsso_subnet = '';
1799 if (!isset($config->ntlmsso_ie_fastpath)) {
1800 $config->ntlmsso_ie_fastpath = 0;
1802 if (!isset($config->ntlmsso_type)) {
1803 $config->ntlmsso_type = 'ntlm';
1806 // Save settings
1807 set_config('host_url', trim($config->host_url), $this->pluginconfig);
1808 set_config('ldapencoding', trim($config->ldapencoding), $this->pluginconfig);
1809 set_config('contexts', trim($config->contexts), $this->pluginconfig);
1810 set_config('user_type', moodle_strtolower(trim($config->user_type)), $this->pluginconfig);
1811 set_config('user_attribute', moodle_strtolower(trim($config->user_attribute)), $this->pluginconfig);
1812 set_config('search_sub', $config->search_sub, $this->pluginconfig);
1813 set_config('opt_deref', $config->opt_deref, $this->pluginconfig);
1814 set_config('preventpassindb', $config->preventpassindb, $this->pluginconfig);
1815 set_config('bind_dn', trim($config->bind_dn), $this->pluginconfig);
1816 set_config('bind_pw', $config->bind_pw, $this->pluginconfig);
1817 set_config('ldap_version', $config->ldap_version, $this->pluginconfig);
1818 set_config('objectclass', trim($config->objectclass), $this->pluginconfig);
1819 set_config('memberattribute', moodle_strtolower(trim($config->memberattribute)), $this->pluginconfig);
1820 set_config('memberattribute_isdn', $config->memberattribute_isdn, $this->pluginconfig);
1821 set_config('creators', trim($config->creators), $this->pluginconfig);
1822 set_config('create_context', trim($config->create_context), $this->pluginconfig);
1823 set_config('expiration', $config->expiration, $this->pluginconfig);
1824 set_config('expiration_warning', trim($config->expiration_warning), $this->pluginconfig);
1825 set_config('expireattr', moodle_strtolower(trim($config->expireattr)), $this->pluginconfig);
1826 set_config('gracelogins', $config->gracelogins, $this->pluginconfig);
1827 set_config('graceattr', moodle_strtolower(trim($config->graceattr)), $this->pluginconfig);
1828 set_config('auth_user_create', $config->auth_user_create, $this->pluginconfig);
1829 set_config('forcechangepassword', $config->forcechangepassword, $this->pluginconfig);
1830 set_config('stdchangepassword', $config->stdchangepassword, $this->pluginconfig);
1831 set_config('passtype', $config->passtype, $this->pluginconfig);
1832 set_config('changepasswordurl', trim($config->changepasswordurl), $this->pluginconfig);
1833 set_config('removeuser', $config->removeuser, $this->pluginconfig);
1834 set_config('ntlmsso_enabled', (int)$config->ntlmsso_enabled, $this->pluginconfig);
1835 set_config('ntlmsso_subnet', trim($config->ntlmsso_subnet), $this->pluginconfig);
1836 set_config('ntlmsso_ie_fastpath', (int)$config->ntlmsso_ie_fastpath, $this->pluginconfig);
1837 set_config('ntlmsso_type', $config->ntlmsso_type, 'auth/ldap');
1839 return true;
1843 * Get password expiration time for a given user from Active Directory
1845 * @param string $pwdlastset The time last time we changed the password.
1846 * @param resource $lcapconn The open LDAP connection.
1847 * @param string $user_dn The distinguished name of the user we are checking.
1849 * @return string $unixtime
1851 function ldap_get_ad_pwdexpire($pwdlastset, $ldapconn, $user_dn){
1852 global $CFG;
1854 if (!function_exists('bcsub')) {
1855 error_log($this->errorlogtag.get_string ('needbcmath', 'auth_ldap'));
1856 return 0;
1859 // If UF_DONT_EXPIRE_PASSWD flag is set in user's
1860 // userAccountControl attribute, the password doesn't expire.
1861 $sr = ldap_read($ldapconn, $user_dn, '(objectClass=*)',
1862 array('userAccountControl'));
1863 if (!$sr) {
1864 error_log($this->errorlogtag.get_string ('useracctctrlerror', 'auth_ldap', $user_dn));
1865 // Don't expire password, as we are not sure if it has to be
1866 // expired or not.
1867 return 0;
1870 $entry = ldap_get_entries_moodle($ldapconn, $sr);
1871 $info = array_change_key_case($entry[0], CASE_LOWER);
1872 $useraccountcontrol = $info['useraccountcontrol'][0];
1873 if ($useraccountcontrol & UF_DONT_EXPIRE_PASSWD) {
1874 // Password doesn't expire.
1875 return 0;
1878 // If pwdLastSet is zero, the user must change his/her password now
1879 // (unless UF_DONT_EXPIRE_PASSWD flag is set, but we already
1880 // tested this above)
1881 if ($pwdlastset === '0') {
1882 // Password has expired
1883 return -1;
1886 // ----------------------------------------------------------------
1887 // Password expiration time in Active Directory is the composition of
1888 // two values:
1890 // - User's pwdLastSet attribute, that stores the last time
1891 // the password was changed.
1893 // - Domain's maxPwdAge attribute, that sets how long
1894 // passwords last in this domain.
1896 // We already have the first value (passed in as a parameter). We
1897 // need to get the second one. As we don't know the domain DN, we
1898 // have to query rootDSE's defaultNamingContext attribute to get
1899 // it. Then we have to query that DN's maxPwdAge attribute to get
1900 // the real value.
1902 // Once we have both values, we just need to combine them. But MS
1903 // chose to use a different base and unit for time measurements.
1904 // So we need to convert the values to Unix timestamps (see
1905 // details below).
1906 // ----------------------------------------------------------------
1908 $sr = ldap_read($ldapconn, ROOTDSE, '(objectClass=*)',
1909 array('defaultNamingContext'));
1910 if (!$sr) {
1911 error_log($this->errorlogtag.get_string ('rootdseerror', 'auth_ldap'));
1912 return 0;
1915 $entry = ldap_get_entries_moodle($ldapconn, $sr);
1916 $info = array_change_key_case($entry[0], CASE_LOWER);
1917 $domaindn = $info['defaultnamingcontext'][0];
1919 $sr = ldap_read ($ldapconn, $domaindn, '(objectClass=*)',
1920 array('maxPwdAge'));
1921 $entry = ldap_get_entries_moodle($ldapconn, $sr);
1922 $info = array_change_key_case($entry[0], CASE_LOWER);
1923 $maxpwdage = $info['maxpwdage'][0];
1925 // ----------------------------------------------------------------
1926 // MSDN says that "pwdLastSet contains the number of 100 nanosecond
1927 // intervals since January 1, 1601 (UTC), stored in a 64 bit integer".
1929 // According to Perl's Date::Manip, the number of seconds between
1930 // this date and Unix epoch is 11644473600. So we have to
1931 // substract this value to calculate a Unix time, once we have
1932 // scaled pwdLastSet to seconds. This is the script used to
1933 // calculate the value shown above:
1935 // #!/usr/bin/perl -w
1937 // use Date::Manip;
1939 // $date1 = ParseDate ("160101010000 UTC");
1940 // $date2 = ParseDate ("197001010000 UTC");
1941 // $delta = DateCalc($date1, $date2, \$err);
1942 // $secs = Delta_Format($delta, 0, "%st");
1943 // print "$secs \n";
1945 // MSDN also says that "maxPwdAge is stored as a large integer that
1946 // represents the number of 100 nanosecond intervals from the time
1947 // the password was set before the password expires." We also need
1948 // to scale this to seconds. Bear in mind that this value is stored
1949 // as a _negative_ quantity (at least in my AD domain).
1951 // As a last remark, if the low 32 bits of maxPwdAge are equal to 0,
1952 // the maximum password age in the domain is set to 0, which means
1953 // passwords do not expire (see
1954 // http://msdn2.microsoft.com/en-us/library/ms974598.aspx)
1956 // As the quantities involved are too big for PHP integers, we
1957 // need to use BCMath functions to work with arbitrary precision
1958 // numbers.
1959 // ----------------------------------------------------------------
1961 // If the low order 32 bits are 0, then passwords do not expire in
1962 // the domain. Just do '$maxpwdage mod 2^32' and check the result
1963 // (2^32 = 4294967296)
1964 if (bcmod ($maxpwdage, 4294967296) === '0') {
1965 return 0;
1968 // Add up pwdLastSet and maxPwdAge to get password expiration
1969 // time, in MS time units. Remember maxPwdAge is stored as a
1970 // _negative_ quantity, so we need to substract it in fact.
1971 $pwdexpire = bcsub ($pwdlastset, $maxpwdage);
1973 // Scale the result to convert it to Unix time units and return
1974 // that value.
1975 return bcsub( bcdiv($pwdexpire, '10000000'), '11644473600');
1979 * Connect to the LDAP server, using the plugin configured
1980 * settings. It's actually a wrapper around ldap_connect_moodle()
1982 * @return resource A valid LDAP connection (or dies if it can't connect)
1984 function ldap_connect() {
1985 // Cache ldap connections. They are expensive to set up
1986 // and can drain the TCP/IP ressources on the server if we
1987 // are syncing a lot of users (as we try to open a new connection
1988 // to get the user details). This is the least invasive way
1989 // to reuse existing connections without greater code surgery.
1990 if(!empty($this->ldapconnection)) {
1991 $this->ldapconns++;
1992 return $this->ldapconnection;
1995 if($ldapconnection = ldap_connect_moodle($this->config->host_url, $this->config->ldap_version,
1996 $this->config->user_type, $this->config->bind_dn,
1997 $this->config->bind_pw, $this->config->opt_deref,
1998 $debuginfo)) {
1999 $this->ldapconns = 1;
2000 $this->ldapconnection = $ldapconnection;
2001 return $ldapconnection;
2004 print_error('auth_ldap_noconnect_all', 'auth_ldap', '', $debuginfo);
2008 * Disconnects from a LDAP server
2011 function ldap_close() {
2012 $this->ldapconns--;
2013 if($this->ldapconns == 0) {
2014 @ldap_close($this->ldapconnection);
2015 unset($this->ldapconnection);
2020 * Search specified contexts for username and return the user dn
2021 * like: cn=username,ou=suborg,o=org. It's actually a wrapper
2022 * around ldap_find_userdn().
2024 * @param resource $ldapconnection a valid LDAP connection
2025 * @param string $extusername the username to search (in external LDAP encoding, no db slashes)
2026 * @return mixed the user dn (external LDAP encoding) or false
2028 function ldap_find_userdn($ldapconnection, $extusername) {
2029 $ldap_contexts = explode(';', $this->config->contexts);
2030 if (!empty($this->config->create_context)) {
2031 array_push($ldap_contexts, $this->config->create_context);
2034 return ldap_find_userdn($ldapconnection, $extusername, $ldap_contexts, $this->config->objectclass,
2035 $this->config->user_attribute, $this->config->search_sub);
2038 } // End of the class