314e5bed9b884d0deff8dac522ab36b56744e34c
[moodle.git] / auth / ldap / auth.php
1 <?php
2 // This file is part of Moodle - http://moodle.org/
3 //
4 // Moodle is free software: you can redistribute it and/or modify
5 // it under the terms of the GNU General Public License as published by
6 // the Free Software Foundation, either version 3 of the License, or
7 // (at your option) any later version.
8 //
9 // Moodle is distributed in the hope that it will be useful,
10 // but WITHOUT ANY WARRANTY; without even the implied warranty of
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12 // GNU General Public License for more details.
13 //
14 // You should have received a copy of the GNU General Public License
15 // along with Moodle.  If not, see <http://www.gnu.org/licenses/>.
17 /**
18  * Authentication Plugin: LDAP Authentication
19  * Authentication using LDAP (Lightweight Directory Access Protocol).
20  *
21  * @package auth_ldap
22  * @author Martin Dougiamas
23  * @author IƱaki Arenaza
24  * @license http://www.gnu.org/copyleft/gpl.html GNU Public License
25  */
27 defined('MOODLE_INTERNAL') || die();
29 // See http://support.microsoft.com/kb/305144 to interprete these values.
30 if (!defined('AUTH_AD_ACCOUNTDISABLE')) {
31     define('AUTH_AD_ACCOUNTDISABLE', 0x0002);
32 }
33 if (!defined('AUTH_AD_NORMAL_ACCOUNT')) {
34     define('AUTH_AD_NORMAL_ACCOUNT', 0x0200);
35 }
36 if (!defined('AUTH_NTLMTIMEOUT')) {  // timewindow for the NTLM SSO process, in secs...
37     define('AUTH_NTLMTIMEOUT', 10);
38 }
40 // UF_DONT_EXPIRE_PASSWD value taken from MSDN directly
41 if (!defined('UF_DONT_EXPIRE_PASSWD')) {
42     define ('UF_DONT_EXPIRE_PASSWD', 0x00010000);
43 }
45 // The Posix uid and gid of the 'nobody' account and 'nogroup' group.
46 if (!defined('AUTH_UID_NOBODY')) {
47     define('AUTH_UID_NOBODY', -2);
48 }
49 if (!defined('AUTH_GID_NOGROUP')) {
50     define('AUTH_GID_NOGROUP', -2);
51 }
53 // Regular expressions for a valid NTLM username and domain name.
54 if (!defined('AUTH_NTLM_VALID_USERNAME')) {
55     define('AUTH_NTLM_VALID_USERNAME', '[^/\\\\\\\\\[\]:;|=,+*?<>@"]+');
56 }
57 if (!defined('AUTH_NTLM_VALID_DOMAINNAME')) {
58     define('AUTH_NTLM_VALID_DOMAINNAME', '[^\\\\\\\\\/:*?"<>|]+');
59 }
60 // Default format for remote users if using NTLM SSO
61 if (!defined('AUTH_NTLM_DEFAULT_FORMAT')) {
62     define('AUTH_NTLM_DEFAULT_FORMAT', '%domain%\\%username%');
63 }
65 // Allows us to retrieve a diagnostic message in case of LDAP operation error
66 if (!defined('LDAP_OPT_DIAGNOSTIC_MESSAGE')) {
67     define('LDAP_OPT_DIAGNOSTIC_MESSAGE', 0x0032);
68 }
70 require_once($CFG->libdir.'/authlib.php');
71 require_once($CFG->libdir.'/ldaplib.php');
73 /**
74  * LDAP authentication plugin.
75  */
76 class auth_plugin_ldap extends auth_plugin_base {
78     /**
79      * Init plugin config from database settings depending on the plugin auth type.
80      */
81     function init_plugin($authtype) {
82         $this->pluginconfig = 'auth/'.$authtype;
83         $this->config = get_config($this->pluginconfig);
84         if (empty($this->config->ldapencoding)) {
85             $this->config->ldapencoding = 'utf-8';
86         }
87         if (empty($this->config->user_type)) {
88             $this->config->user_type = 'default';
89         }
91         $ldap_usertypes = ldap_supported_usertypes();
92         $this->config->user_type_name = $ldap_usertypes[$this->config->user_type];
93         unset($ldap_usertypes);
95         $default = ldap_getdefaults();
97         // Use defaults if values not given
98         foreach ($default as $key => $value) {
99             // watch out - 0, false are correct values too
100             if (!isset($this->config->{$key}) or $this->config->{$key} == '') {
101                 $this->config->{$key} = $value[$this->config->user_type];
102             }
103         }
105         // Hack prefix to objectclass
106         if (empty($this->config->objectclass)) {
107             // Can't send empty filter
108             $this->config->objectclass = '(objectClass=*)';
109         } else if (stripos($this->config->objectclass, 'objectClass=') === 0) {
110             // Value is 'objectClass=some-string-here', so just add ()
111             // around the value (filter _must_ have them).
112             $this->config->objectclass = '('.$this->config->objectclass.')';
113         } else if (strpos($this->config->objectclass, '(') !== 0) {
114             // Value is 'some-string-not-starting-with-left-parentheses',
115             // which is assumed to be the objectClass matching value.
116             // So build a valid filter with it.
117             $this->config->objectclass = '(objectClass='.$this->config->objectclass.')';
118         } else {
119             // There is an additional possible value
120             // '(some-string-here)', that can be used to specify any
121             // valid filter string, to select subsets of users based
122             // on any criteria. For example, we could select the users
123             // whose objectClass is 'user' and have the
124             // 'enabledMoodleUser' attribute, with something like:
125             //
126             //   (&(objectClass=user)(enabledMoodleUser=1))
127             //
128             // In this particular case we don't need to do anything,
129             // so leave $this->config->objectclass as is.
130         }
131     }
133     /**
134      * Constructor with initialisation.
135      */
136     function auth_plugin_ldap() {
137         $this->authtype = 'ldap';
138         $this->roleauth = 'auth_ldap';
139         $this->errorlogtag = '[AUTH LDAP] ';
140         $this->init_plugin($this->authtype);
141     }
143     /**
144      * Returns true if the username and password work and false if they are
145      * wrong or don't exist.
146      *
147      * @param string $username The username (without system magic quotes)
148      * @param string $password The password (without system magic quotes)
149      *
150      * @return bool Authentication success or failure.
151      */
152     function user_login($username, $password) {
153         if (! function_exists('ldap_bind')) {
154             print_error('auth_ldapnotinstalled', 'auth_ldap');
155             return false;
156         }
158         if (!$username or !$password) {    // Don't allow blank usernames or passwords
159             return false;
160         }
162         $extusername = textlib::convert($username, 'utf-8', $this->config->ldapencoding);
163         $extpassword = textlib::convert($password, 'utf-8', $this->config->ldapencoding);
165         // Before we connect to LDAP, check if this is an AD SSO login
166         // if we succeed in this block, we'll return success early.
167         //
168         $key = sesskey();
169         if (!empty($this->config->ntlmsso_enabled) && $key === $password) {
170             $cf = get_cache_flags($this->pluginconfig.'/ntlmsess');
171             // We only get the cache flag if we retrieve it before
172             // it expires (AUTH_NTLMTIMEOUT seconds).
173             if (!isset($cf[$key]) || $cf[$key] === '') {
174                 return false;
175             }
177             $sessusername = $cf[$key];
178             if ($username === $sessusername) {
179                 unset($sessusername);
180                 unset($cf);
182                 // Check that the user is inside one of the configured LDAP contexts
183                 $validuser = false;
184                 $ldapconnection = $this->ldap_connect();
185                 // if the user is not inside the configured contexts,
186                 // ldap_find_userdn returns false.
187                 if ($this->ldap_find_userdn($ldapconnection, $extusername)) {
188                     $validuser = true;
189                 }
190                 $this->ldap_close();
192                 // Shortcut here - SSO confirmed
193                 return $validuser;
194             }
195         } // End SSO processing
196         unset($key);
198         $ldapconnection = $this->ldap_connect();
199         $ldap_user_dn = $this->ldap_find_userdn($ldapconnection, $extusername);
201         // If ldap_user_dn is empty, user does not exist
202         if (!$ldap_user_dn) {
203             $this->ldap_close();
204             return false;
205         }
207         // Try to bind with current username and password
208         $ldap_login = @ldap_bind($ldapconnection, $ldap_user_dn, $extpassword);
210         // If login fails and we are using MS Active Directory, retrieve the diagnostic
211         // message to see if this is due to an expired password, or that the user is forced to
212         // change the password on first login. If it is, only proceed if we can change
213         // password from Moodle (otherwise we'll get stuck later in the login process).
214         if (!$ldap_login && ($this->config->user_type == 'ad')
215             && $this->can_change_password()
216             && (!empty($this->config->expiration) and ($this->config->expiration == 1))) {
218             // We need to get the diagnostic message right after the call to ldap_bind(),
219             // before any other LDAP operation.
220             ldap_get_option($ldapconnection, LDAP_OPT_DIAGNOSTIC_MESSAGE, $diagmsg);
222             if ($this->ldap_ad_pwdexpired_from_diagmsg($diagmsg)) {
223                 // If login failed because user must change the password now or the
224                 // password has expired, let the user in. We'll catch this later in the
225                 // login process when we explicitly check for expired passwords.
226                 $ldap_login = true;
227             }
228         }
229         $this->ldap_close();
230         return $ldap_login;
231     }
233     /**
234      * Reads user information from ldap and returns it in array()
235      *
236      * Function should return all information available. If you are saving
237      * this information to moodle user-table you should honor syncronization flags
238      *
239      * @param string $username username
240      *
241      * @return mixed array with no magic quotes or false on error
242      */
243     function get_userinfo($username) {
244         $extusername = textlib::convert($username, 'utf-8', $this->config->ldapencoding);
246         $ldapconnection = $this->ldap_connect();
247         if(!($user_dn = $this->ldap_find_userdn($ldapconnection, $extusername))) {
248             $this->ldap_close();
249             return false;
250         }
252         $search_attribs = array();
253         $attrmap = $this->ldap_attributes();
254         foreach ($attrmap as $key => $values) {
255             if (!is_array($values)) {
256                 $values = array($values);
257             }
258             foreach ($values as $value) {
259                 if (!in_array($value, $search_attribs)) {
260                     array_push($search_attribs, $value);
261                 }
262             }
263         }
265         if (!$user_info_result = ldap_read($ldapconnection, $user_dn, '(objectClass=*)', $search_attribs)) {
266             $this->ldap_close();
267             return false; // error!
268         }
270         $user_entry = ldap_get_entries_moodle($ldapconnection, $user_info_result);
271         if (empty($user_entry)) {
272             $this->ldap_close();
273             return false; // entry not found
274         }
276         $result = array();
277         foreach ($attrmap as $key => $values) {
278             if (!is_array($values)) {
279                 $values = array($values);
280             }
281             $ldapval = NULL;
282             foreach ($values as $value) {
283                 $entry = array_change_key_case($user_entry[0], CASE_LOWER);
284                 if (($value == 'dn') || ($value == 'distinguishedname')) {
285                     $result[$key] = $user_dn;
286                     continue;
287                 }
288                 if (!array_key_exists($value, $entry)) {
289                     continue; // wrong data mapping!
290                 }
291                 if (is_array($entry[$value])) {
292                     $newval = textlib::convert($entry[$value][0], $this->config->ldapencoding, 'utf-8');
293                 } else {
294                     $newval = textlib::convert($entry[$value], $this->config->ldapencoding, 'utf-8');
295                 }
296                 if (!empty($newval)) { // favour ldap entries that are set
297                     $ldapval = $newval;
298                 }
299             }
300             if (!is_null($ldapval)) {
301                 $result[$key] = $ldapval;
302             }
303         }
305         $this->ldap_close();
306         return $result;
307     }
309     /**
310      * Reads user information from ldap and returns it in an object
311      *
312      * @param string $username username (with system magic quotes)
313      * @return mixed object or false on error
314      */
315     function get_userinfo_asobj($username) {
316         $user_array = $this->get_userinfo($username);
317         if ($user_array == false) {
318             return false; //error or not found
319         }
320         $user_array = truncate_userinfo($user_array);
321         $user = new stdClass();
322         foreach ($user_array as $key=>$value) {
323             $user->{$key} = $value;
324         }
325         return $user;
326     }
328     /**
329      * Returns all usernames from LDAP
330      *
331      * get_userlist returns all usernames from LDAP
332      *
333      * @return array
334      */
335     function get_userlist() {
336         return $this->ldap_get_userlist("({$this->config->user_attribute}=*)");
337     }
339     /**
340      * Checks if user exists on LDAP
341      *
342      * @param string $username
343      */
344     function user_exists($username) {
345         $extusername = textlib::convert($username, 'utf-8', $this->config->ldapencoding);
347         // Returns true if given username exists on ldap
348         $users = $this->ldap_get_userlist('('.$this->config->user_attribute.'='.ldap_filter_addslashes($extusername).')');
349         return count($users);
350     }
352     /**
353      * Creates a new user on LDAP.
354      * By using information in userobject
355      * Use user_exists to prevent duplicate usernames
356      *
357      * @param mixed $userobject  Moodle userobject
358      * @param mixed $plainpass   Plaintext password
359      */
360     function user_create($userobject, $plainpass) {
361         $extusername = textlib::convert($userobject->username, 'utf-8', $this->config->ldapencoding);
362         $extpassword = textlib::convert($plainpass, 'utf-8', $this->config->ldapencoding);
364         switch ($this->config->passtype) {
365             case 'md5':
366                 $extpassword = '{MD5}' . base64_encode(pack('H*', md5($extpassword)));
367                 break;
368             case 'sha1':
369                 $extpassword = '{SHA}' . base64_encode(pack('H*', sha1($extpassword)));
370                 break;
371             case 'plaintext':
372             default:
373                 break; // plaintext
374         }
376         $ldapconnection = $this->ldap_connect();
377         $attrmap = $this->ldap_attributes();
379         $newuser = array();
381         foreach ($attrmap as $key => $values) {
382             if (!is_array($values)) {
383                 $values = array($values);
384             }
385             foreach ($values as $value) {
386                 if (!empty($userobject->$key) ) {
387                     $newuser[$value] = textlib::convert($userobject->$key, 'utf-8', $this->config->ldapencoding);
388                 }
389             }
390         }
392         //Following sets all mandatory and other forced attribute values
393         //User should be creted as login disabled untill email confirmation is processed
394         //Feel free to add your user type and send patches to paca@sci.fi to add them
395         //Moodle distribution
397         switch ($this->config->user_type)  {
398             case 'edir':
399                 $newuser['objectClass']   = array('inetOrgPerson', 'organizationalPerson', 'person', 'top');
400                 $newuser['uniqueId']      = $extusername;
401                 $newuser['logindisabled'] = 'TRUE';
402                 $newuser['userpassword']  = $extpassword;
403                 $uadd = ldap_add($ldapconnection, $this->config->user_attribute.'='.ldap_addslashes($extusername).','.$this->config->create_context, $newuser);
404                 break;
405             case 'rfc2307':
406             case 'rfc2307bis':
407                 // posixAccount object class forces us to specify a uidNumber
408                 // and a gidNumber. That is quite complicated to generate from
409                 // Moodle without colliding with existing numbers and without
410                 // race conditions. As this user is supposed to be only used
411                 // with Moodle (otherwise the user would exist beforehand) and
412                 // doesn't need to login into a operating system, we assign the
413                 // user the uid of user 'nobody' and gid of group 'nogroup'. In
414                 // addition to that, we need to specify a home directory. We
415                 // use the root directory ('/') as the home directory, as this
416                 // is the only one can always be sure exists. Finally, even if
417                 // it's not mandatory, we specify '/bin/false' as the login
418                 // shell, to prevent the user from login in at the operating
419                 // system level (Moodle ignores this).
421                 $newuser['objectClass']   = array('posixAccount', 'inetOrgPerson', 'organizationalPerson', 'person', 'top');
422                 $newuser['cn']            = $extusername;
423                 $newuser['uid']           = $extusername;
424                 $newuser['uidNumber']     = AUTH_UID_NOBODY;
425                 $newuser['gidNumber']     = AUTH_GID_NOGROUP;
426                 $newuser['homeDirectory'] = '/';
427                 $newuser['loginShell']    = '/bin/false';
429                 // IMPORTANT:
430                 // We have to create the account locked, but posixAccount has
431                 // no attribute to achive this reliably. So we are going to
432                 // modify the password in a reversable way that we can later
433                 // revert in user_activate().
434                 //
435                 // Beware that this can be defeated by the user if we are not
436                 // using MD5 or SHA-1 passwords. After all, the source code of
437                 // Moodle is available, and the user can see the kind of
438                 // modification we are doing and 'undo' it by hand (but only
439                 // if we are using plain text passwords).
440                 //
441                 // Also bear in mind that you need to use a binding user that
442                 // can create accounts and has read/write privileges on the
443                 // 'userPassword' attribute for this to work.
445                 $newuser['userPassword']  = '*'.$extpassword;
446                 $uadd = ldap_add($ldapconnection, $this->config->user_attribute.'='.ldap_addslashes($extusername).','.$this->config->create_context, $newuser);
447                 break;
448             case 'ad':
449                 // User account creation is a two step process with AD. First you
450                 // create the user object, then you set the password. If you try
451                 // to set the password while creating the user, the operation
452                 // fails.
454                 // Passwords in Active Directory must be encoded as Unicode
455                 // strings (UCS-2 Little Endian format) and surrounded with
456                 // double quotes. See http://support.microsoft.com/?kbid=269190
457                 if (!function_exists('mb_convert_encoding')) {
458                     print_error('auth_ldap_no_mbstring', 'auth_ldap');
459                 }
461                 // Check for invalid sAMAccountName characters.
462                 if (preg_match('#[/\\[\]:;|=,+*?<>@"]#', $extusername)) {
463                     print_error ('auth_ldap_ad_invalidchars', 'auth_ldap');
464                 }
466                 // First create the user account, and mark it as disabled.
467                 $newuser['objectClass'] = array('top', 'person', 'user', 'organizationalPerson');
468                 $newuser['sAMAccountName'] = $extusername;
469                 $newuser['userAccountControl'] = AUTH_AD_NORMAL_ACCOUNT |
470                                                  AUTH_AD_ACCOUNTDISABLE;
471                 $userdn = 'cn='.ldap_addslashes($extusername).','.$this->config->create_context;
472                 if (!ldap_add($ldapconnection, $userdn, $newuser)) {
473                     print_error('auth_ldap_ad_create_req', 'auth_ldap');
474                 }
476                 // Now set the password
477                 unset($newuser);
478                 $newuser['unicodePwd'] = mb_convert_encoding('"' . $extpassword . '"',
479                                                              'UCS-2LE', 'UTF-8');
480                 if(!ldap_modify($ldapconnection, $userdn, $newuser)) {
481                     // Something went wrong: delete the user account and error out
482                     ldap_delete ($ldapconnection, $userdn);
483                     print_error('auth_ldap_ad_create_req', 'auth_ldap');
484                 }
485                 $uadd = true;
486                 break;
487             default:
488                print_error('auth_ldap_unsupportedusertype', 'auth_ldap', '', $this->config->user_type_name);
489         }
490         $this->ldap_close();
491         return $uadd;
492     }
494     /**
495      * Returns true if plugin allows resetting of password from moodle.
496      *
497      * @return bool
498      */
499     function can_reset_password() {
500         return !empty($this->config->stdchangepassword);
501     }
503     /**
504      * Returns true if plugin allows signup and user creation.
505      *
506      * @return bool
507      */
508     function can_signup() {
509         return (!empty($this->config->auth_user_create) and !empty($this->config->create_context));
510     }
512     /**
513      * Sign up a new user ready for confirmation.
514      * Password is passed in plaintext.
515      *
516      * @param object $user new user object
517      * @param boolean $notify print notice with link and terminate
518      */
519     function user_signup($user, $notify=true) {
520         global $CFG, $DB, $PAGE, $OUTPUT;
522         require_once($CFG->dirroot.'/user/profile/lib.php');
524         if ($this->user_exists($user->username)) {
525             print_error('auth_ldap_user_exists', 'auth_ldap');
526         }
528         $plainslashedpassword = $user->password;
529         unset($user->password);
531         if (! $this->user_create($user, $plainslashedpassword)) {
532             print_error('auth_ldap_create_error', 'auth_ldap');
533         }
535         $user->id = $DB->insert_record('user', $user);
537         // Save any custom profile field information
538         profile_save_data($user);
540         $this->update_user_record($user->username);
541         // This will also update the stored hash to the latest algorithm
542         // if the existing hash is using an out-of-date algorithm (or the
543         // legacy md5 algorithm).
544         update_internal_user_password($user, $plainslashedpassword);
546         $user = $DB->get_record('user', array('id'=>$user->id));
547         events_trigger('user_created', $user);
549         if (! send_confirmation_email($user)) {
550             print_error('noemail', 'auth_ldap');
551         }
553         if ($notify) {
554             $emailconfirm = get_string('emailconfirm');
555             $PAGE->set_url('/auth/ldap/auth.php');
556             $PAGE->navbar->add($emailconfirm);
557             $PAGE->set_title($emailconfirm);
558             $PAGE->set_heading($emailconfirm);
559             echo $OUTPUT->header();
560             notice(get_string('emailconfirmsent', '', $user->email), "{$CFG->wwwroot}/index.php");
561         } else {
562             return true;
563         }
564     }
566     /**
567      * Returns true if plugin allows confirming of new users.
568      *
569      * @return bool
570      */
571     function can_confirm() {
572         return $this->can_signup();
573     }
575     /**
576      * Confirm the new user as registered.
577      *
578      * @param string $username
579      * @param string $confirmsecret
580      */
581     function user_confirm($username, $confirmsecret) {
582         global $DB;
584         $user = get_complete_user_data('username', $username);
586         if (!empty($user)) {
587             if ($user->confirmed) {
588                 return AUTH_CONFIRM_ALREADY;
590             } else if ($user->auth != $this->authtype) {
591                 return AUTH_CONFIRM_ERROR;
593             } else if ($user->secret == $confirmsecret) {   // They have provided the secret key to get in
594                 if (!$this->user_activate($username)) {
595                     return AUTH_CONFIRM_FAIL;
596                 }
597                 $DB->set_field('user', 'confirmed', 1, array('id'=>$user->id));
598                 if ($user->firstaccess == 0) {
599                     $DB->set_field('user', 'firstaccess', time(), array('id'=>$user->id));
600                 }
601                 $euser = $DB->get_record('user', array('id' => $user->id));
602                 events_trigger('user_updated', $euser);
603                 return AUTH_CONFIRM_OK;
604             }
605         } else {
606             return AUTH_CONFIRM_ERROR;
607         }
608     }
610     /**
611      * Return number of days to user password expires
612      *
613      * If userpassword does not expire it should return 0. If password is already expired
614      * it should return negative value.
615      *
616      * @param mixed $username username
617      * @return integer
618      */
619     function password_expire($username) {
620         $result = 0;
622         $extusername = textlib::convert($username, 'utf-8', $this->config->ldapencoding);
624         $ldapconnection = $this->ldap_connect();
625         $user_dn = $this->ldap_find_userdn($ldapconnection, $extusername);
626         $search_attribs = array($this->config->expireattr);
627         $sr = ldap_read($ldapconnection, $user_dn, '(objectClass=*)', $search_attribs);
628         if ($sr)  {
629             $info = ldap_get_entries_moodle($ldapconnection, $sr);
630             if (!empty ($info)) {
631                 $info = array_change_key_case($info[0], CASE_LOWER);
632                 if (isset($info[$this->config->expireattr][0])) {
633                     $expiretime = $this->ldap_expirationtime2unix($info[$this->config->expireattr][0], $ldapconnection, $user_dn);
634                     if ($expiretime != 0) {
635                         $now = time();
636                         if ($expiretime > $now) {
637                             $result = ceil(($expiretime - $now) / DAYSECS);
638                         } else {
639                             $result = floor(($expiretime - $now) / DAYSECS);
640                         }
641                     }
642                 }
643             }
644         } else {
645             error_log($this->errorlogtag.get_string('didtfindexpiretime', 'auth_ldap'));
646         }
648         return $result;
649     }
651     /**
652      * Syncronizes user fron external LDAP server to moodle user table
653      *
654      * Sync is now using username attribute.
655      *
656      * Syncing users removes or suspends users that dont exists anymore in external LDAP.
657      * Creates new users and updates coursecreator status of users.
658      *
659      * @param bool $do_updates will do pull in data updates from LDAP if relevant
660      */
661     function sync_users($do_updates=true) {
662         global $CFG, $DB;
664         print_string('connectingldap', 'auth_ldap');
665         $ldapconnection = $this->ldap_connect();
667         $dbman = $DB->get_manager();
669     /// Define table user to be created
670         $table = new xmldb_table('tmp_extuser');
671         $table->add_field('id', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, XMLDB_SEQUENCE, null);
672         $table->add_field('username', XMLDB_TYPE_CHAR, '100', null, XMLDB_NOTNULL, null, null);
673         $table->add_field('mnethostid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null);
674         $table->add_key('primary', XMLDB_KEY_PRIMARY, array('id'));
675         $table->add_index('username', XMLDB_INDEX_UNIQUE, array('mnethostid', 'username'));
677         print_string('creatingtemptable', 'auth_ldap', 'tmp_extuser');
678         $dbman->create_temp_table($table);
680         ////
681         //// get user's list from ldap to sql in a scalable fashion
682         ////
683         // prepare some data we'll need
684         $filter = '(&('.$this->config->user_attribute.'=*)'.$this->config->objectclass.')';
686         $contexts = explode(';', $this->config->contexts);
688         if (!empty($this->config->create_context)) {
689             array_push($contexts, $this->config->create_context);
690         }
692         $ldap_pagedresults = ldap_paged_results_supported($this->config->ldap_version);
693         $ldap_cookie = '';
694         foreach ($contexts as $context) {
695             $context = trim($context);
696             if (empty($context)) {
697                 continue;
698             }
700             do {
701                 if ($ldap_pagedresults) {
702                     ldap_control_paged_result($ldapconnection, $this->config->pagesize, true, $ldap_cookie);
703                 }
704                 if ($this->config->search_sub) {
705                     // Use ldap_search to find first user from subtree.
706                     $ldap_result = ldap_search($ldapconnection, $context, $filter, array($this->config->user_attribute));
707                 } else {
708                     // Search only in this context.
709                     $ldap_result = ldap_list($ldapconnection, $context, $filter, array($this->config->user_attribute));
710                 }
711                 if(!$ldap_result) {
712                     continue;
713                 }
714                 if ($ldap_pagedresults) {
715                     ldap_control_paged_result_response($ldapconnection, $ldap_result, $ldap_cookie);
716                 }
717                 if ($entry = @ldap_first_entry($ldapconnection, $ldap_result)) {
718                     do {
719                         $value = ldap_get_values_len($ldapconnection, $entry, $this->config->user_attribute);
720                         $value = textlib::convert($value[0], $this->config->ldapencoding, 'utf-8');
721                         $this->ldap_bulk_insert($value);
722                     } while ($entry = ldap_next_entry($ldapconnection, $entry));
723                 }
724                 unset($ldap_result); // Free mem.
725             } while ($ldap_pagedresults && !empty($ldap_cookie));
726         }
728         // If LDAP paged results were used, the current connection must be completely
729         // closed and a new one created, to work without paged results from here on.
730         if ($ldap_pagedresults) {
731             $this->ldap_close(true);
732             $ldapconnection = $this->ldap_connect();
733         }
735         /// preserve our user database
736         /// if the temp table is empty, it probably means that something went wrong, exit
737         /// so as to avoid mass deletion of users; which is hard to undo
738         $count = $DB->count_records_sql('SELECT COUNT(username) AS count, 1 FROM {tmp_extuser}');
739         if ($count < 1) {
740             print_string('didntgetusersfromldap', 'auth_ldap');
741             exit;
742         } else {
743             print_string('gotcountrecordsfromldap', 'auth_ldap', $count);
744         }
747 /// User removal
748         // Find users in DB that aren't in ldap -- to be removed!
749         // this is still not as scalable (but how often do we mass delete?)
750         if ($this->config->removeuser != AUTH_REMOVEUSER_KEEP) {
751             $sql = 'SELECT u.*
752                       FROM {user} u
753                       LEFT JOIN {tmp_extuser} e ON (u.username = e.username AND u.mnethostid = e.mnethostid)
754                      WHERE u.auth = ?
755                            AND u.deleted = 0
756                            AND e.username IS NULL';
757             $remove_users = $DB->get_records_sql($sql, array($this->authtype));
759             if (!empty($remove_users)) {
760                 print_string('userentriestoremove', 'auth_ldap', count($remove_users));
762                 foreach ($remove_users as $user) {
763                     if ($this->config->removeuser == AUTH_REMOVEUSER_FULLDELETE) {
764                         if (delete_user($user)) {
765                             echo "\t"; print_string('auth_dbdeleteuser', 'auth_db', array('name'=>$user->username, 'id'=>$user->id)); echo "\n";
766                         } else {
767                             echo "\t"; print_string('auth_dbdeleteusererror', 'auth_db', $user->username); echo "\n";
768                         }
769                     } else if ($this->config->removeuser == AUTH_REMOVEUSER_SUSPEND) {
770                         $updateuser = new stdClass();
771                         $updateuser->id = $user->id;
772                         $updateuser->auth = 'nologin';
773                         $DB->update_record('user', $updateuser);
774                         echo "\t"; print_string('auth_dbsuspenduser', 'auth_db', array('name'=>$user->username, 'id'=>$user->id)); echo "\n";
775                         $euser = $DB->get_record('user', array('id' => $user->id));
776                         events_trigger('user_updated', $euser);
777                     }
778                 }
779             } else {
780                 print_string('nouserentriestoremove', 'auth_ldap');
781             }
782             unset($remove_users); // free mem!
783         }
785 /// Revive suspended users
786         if (!empty($this->config->removeuser) and $this->config->removeuser == AUTH_REMOVEUSER_SUSPEND) {
787             $sql = "SELECT u.id, u.username
788                       FROM {user} u
789                       JOIN {tmp_extuser} e ON (u.username = e.username AND u.mnethostid = e.mnethostid)
790                      WHERE u.auth = 'nologin' AND u.deleted = 0";
791             $revive_users = $DB->get_records_sql($sql);
793             if (!empty($revive_users)) {
794                 print_string('userentriestorevive', 'auth_ldap', count($revive_users));
796                 foreach ($revive_users as $user) {
797                     $updateuser = new stdClass();
798                     $updateuser->id = $user->id;
799                     $updateuser->auth = $this->authtype;
800                     $DB->update_record('user', $updateuser);
801                     echo "\t"; print_string('auth_dbreviveduser', 'auth_db', array('name'=>$user->username, 'id'=>$user->id)); echo "\n";
802                     $euser = $DB->get_record('user', array('id' => $user->id));
803                     events_trigger('user_updated', $euser);
804                 }
805             } else {
806                 print_string('nouserentriestorevive', 'auth_ldap');
807             }
809             unset($revive_users);
810         }
813 /// User Updates - time-consuming (optional)
814         if ($do_updates) {
815             // Narrow down what fields we need to update
816             $all_keys = array_keys(get_object_vars($this->config));
817             $updatekeys = array();
818             foreach ($all_keys as $key) {
819                 if (preg_match('/^field_updatelocal_(.+)$/', $key, $match)) {
820                     // If we have a field to update it from
821                     // and it must be updated 'onlogin' we
822                     // update it on cron
823                     if (!empty($this->config->{'field_map_'.$match[1]})
824                          and $this->config->{$match[0]} === 'onlogin') {
825                         array_push($updatekeys, $match[1]); // the actual key name
826                     }
827                 }
828             }
829             unset($all_keys); unset($key);
831         } else {
832             print_string('noupdatestobedone', 'auth_ldap');
833         }
834         if ($do_updates and !empty($updatekeys)) { // run updates only if relevant
835             $users = $DB->get_records_sql('SELECT u.username, u.id
836                                              FROM {user} u
837                                             WHERE u.deleted = 0 AND u.auth = ? AND u.mnethostid = ?',
838                                           array($this->authtype, $CFG->mnet_localhost_id));
839             if (!empty($users)) {
840                 print_string('userentriestoupdate', 'auth_ldap', count($users));
842                 $sitecontext = context_system::instance();
843                 if (!empty($this->config->creators) and !empty($this->config->memberattribute)
844                   and $roles = get_archetype_roles('coursecreator')) {
845                     $creatorrole = array_shift($roles);      // We can only use one, let's use the first one
846                 } else {
847                     $creatorrole = false;
848                 }
850                 $transaction = $DB->start_delegated_transaction();
851                 $xcount = 0;
852                 $maxxcount = 100;
854                 foreach ($users as $user) {
855                     echo "\t"; print_string('auth_dbupdatinguser', 'auth_db', array('name'=>$user->username, 'id'=>$user->id));
856                     if (!$this->update_user_record($user->username, $updatekeys)) {
857                         echo ' - '.get_string('skipped');
858                     }
859                     echo "\n";
860                     $xcount++;
862                     // Update course creators if needed
863                     if ($creatorrole !== false) {
864                         if ($this->iscreator($user->username)) {
865                             role_assign($creatorrole->id, $user->id, $sitecontext->id, $this->roleauth);
866                         } else {
867                             role_unassign($creatorrole->id, $user->id, $sitecontext->id, $this->roleauth);
868                         }
869                     }
870                 }
871                 $transaction->allow_commit();
872                 unset($users); // free mem
873             }
874         } else { // end do updates
875             print_string('noupdatestobedone', 'auth_ldap');
876         }
878 /// User Additions
879         // Find users missing in DB that are in LDAP
880         // and gives me a nifty object I don't want.
881         // note: we do not care about deleted accounts anymore, this feature was replaced by suspending to nologin auth plugin
882         $sql = 'SELECT e.id, e.username
883                   FROM {tmp_extuser} e
884                   LEFT JOIN {user} u ON (e.username = u.username AND e.mnethostid = u.mnethostid)
885                  WHERE u.id IS NULL';
886         $add_users = $DB->get_records_sql($sql);
888         if (!empty($add_users)) {
889             print_string('userentriestoadd', 'auth_ldap', count($add_users));
891             $sitecontext = context_system::instance();
892             if (!empty($this->config->creators) and !empty($this->config->memberattribute)
893               and $roles = get_archetype_roles('coursecreator')) {
894                 $creatorrole = array_shift($roles);      // We can only use one, let's use the first one
895             } else {
896                 $creatorrole = false;
897             }
899             $transaction = $DB->start_delegated_transaction();
900             foreach ($add_users as $user) {
901                 $user = $this->get_userinfo_asobj($user->username);
903                 // Prep a few params
904                 $user->modified   = time();
905                 $user->confirmed  = 1;
906                 $user->auth       = $this->authtype;
907                 $user->mnethostid = $CFG->mnet_localhost_id;
908                 // get_userinfo_asobj() might have replaced $user->username with the value
909                 // from the LDAP server (which can be mixed-case). Make sure it's lowercase
910                 $user->username = trim(textlib::strtolower($user->username));
911                 if (empty($user->lang)) {
912                     $user->lang = $CFG->lang;
913                 }
915                 $id = $DB->insert_record('user', $user);
916                 echo "\t"; print_string('auth_dbinsertuser', 'auth_db', array('name'=>$user->username, 'id'=>$id)); echo "\n";
917                 $euser = $DB->get_record('user', array('id' => $user->id));
918                 events_trigger('user_created', $euser);
919                 if (!empty($this->config->forcechangepassword)) {
920                     set_user_preference('auth_forcepasswordchange', 1, $id);
921                 }
923                 // Add course creators if needed
924                 if ($creatorrole !== false and $this->iscreator($user->username)) {
925                     role_assign($creatorrole->id, $id, $sitecontext->id, $this->roleauth);
926                 }
928             }
929             $transaction->allow_commit();
930             unset($add_users); // free mem
931         } else {
932             print_string('nouserstobeadded', 'auth_ldap');
933         }
935         $dbman->drop_table($table);
936         $this->ldap_close();
938         return true;
939     }
941     /**
942      * Update a local user record from an external source.
943      * This is a lighter version of the one in moodlelib -- won't do
944      * expensive ops such as enrolment.
945      *
946      * If you don't pass $updatekeys, there is a performance hit and
947      * values removed from LDAP won't be removed from moodle.
948      *
949      * @param string $username username
950      * @param boolean $updatekeys true to update the local record with the external LDAP values.
951      */
952     function update_user_record($username, $updatekeys = false) {
953         global $CFG, $DB;
955         // Just in case check text case
956         $username = trim(textlib::strtolower($username));
958         // Get the current user record
959         $user = $DB->get_record('user', array('username'=>$username, 'mnethostid'=>$CFG->mnet_localhost_id));
960         if (empty($user)) { // trouble
961             error_log($this->errorlogtag.get_string('auth_dbusernotexist', 'auth_db', '', $username));
962             print_error('auth_dbusernotexist', 'auth_db', '', $username);
963             die;
964         }
966         // Protect the userid from being overwritten
967         $userid = $user->id;
969         if ($newinfo = $this->get_userinfo($username)) {
970             $newinfo = truncate_userinfo($newinfo);
972             if (empty($updatekeys)) { // all keys? this does not support removing values
973                 $updatekeys = array_keys($newinfo);
974             }
976             foreach ($updatekeys as $key) {
977                 if (isset($newinfo[$key])) {
978                     $value = $newinfo[$key];
979                 } else {
980                     $value = '';
981                 }
983                 if (!empty($this->config->{'field_updatelocal_' . $key})) {
984                     if ($user->{$key} != $value) { // only update if it's changed
985                         $DB->set_field('user', $key, $value, array('id'=>$userid));
986                     }
987                 }
988             }
989             if (!empty($updatekeys)) {
990                 $euser = $DB->get_record('user', array('id' => $userid));
991                 events_trigger('user_updated', $euser);
992             }
993         } else {
994             return false;
995         }
996         return $DB->get_record('user', array('id'=>$userid, 'deleted'=>0));
997     }
999     /**
1000      * Bulk insert in SQL's temp table
1001      */
1002     function ldap_bulk_insert($username) {
1003         global $DB, $CFG;
1005         $username = textlib::strtolower($username); // usernames are __always__ lowercase.
1006         $DB->insert_record_raw('tmp_extuser', array('username'=>$username,
1007                                                     'mnethostid'=>$CFG->mnet_localhost_id), false, true);
1008         echo '.';
1009     }
1011     /**
1012      * Activates (enables) user in external LDAP so user can login
1013      *
1014      * @param mixed $username
1015      * @return boolean result
1016      */
1017     function user_activate($username) {
1018         $extusername = textlib::convert($username, 'utf-8', $this->config->ldapencoding);
1020         $ldapconnection = $this->ldap_connect();
1022         $userdn = $this->ldap_find_userdn($ldapconnection, $extusername);
1023         switch ($this->config->user_type)  {
1024             case 'edir':
1025                 $newinfo['loginDisabled'] = 'FALSE';
1026                 break;
1027             case 'rfc2307':
1028             case 'rfc2307bis':
1029                 // Remember that we add a '*' character in front of the
1030                 // external password string to 'disable' the account. We just
1031                 // need to remove it.
1032                 $sr = ldap_read($ldapconnection, $userdn, '(objectClass=*)',
1033                                 array('userPassword'));
1034                 $info = ldap_get_entries($ldapconnection, $sr);
1035                 $info[0] = array_change_key_case($info[0], CASE_LOWER);
1036                 $newinfo['userPassword'] = ltrim($info[0]['userpassword'][0], '*');
1037                 break;
1038             case 'ad':
1039                 // We need to unset the ACCOUNTDISABLE bit in the
1040                 // userAccountControl attribute ( see
1041                 // http://support.microsoft.com/kb/305144 )
1042                 $sr = ldap_read($ldapconnection, $userdn, '(objectClass=*)',
1043                                 array('userAccountControl'));
1044                 $info = ldap_get_entries($ldapconnection, $sr);
1045                 $info[0] = array_change_key_case($info[0], CASE_LOWER);
1046                 $newinfo['userAccountControl'] = $info[0]['useraccountcontrol'][0]
1047                                                  & (~AUTH_AD_ACCOUNTDISABLE);
1048                 break;
1049             default:
1050                 print_error('user_activatenotsupportusertype', 'auth_ldap', '', $this->config->user_type_name);
1051         }
1052         $result = ldap_modify($ldapconnection, $userdn, $newinfo);
1053         $this->ldap_close();
1054         return $result;
1055     }
1057     /**
1058      * Returns true if user should be coursecreator.
1059      *
1060      * @param mixed $username    username (without system magic quotes)
1061      * @return mixed result      null if course creators is not configured, boolean otherwise.
1062      */
1063     function iscreator($username) {
1064         if (empty($this->config->creators) or empty($this->config->memberattribute)) {
1065             return null;
1066         }
1068         $extusername = textlib::convert($username, 'utf-8', $this->config->ldapencoding);
1070         $ldapconnection = $this->ldap_connect();
1072         if ($this->config->memberattribute_isdn) {
1073             if(!($userid = $this->ldap_find_userdn($ldapconnection, $extusername))) {
1074                 return false;
1075             }
1076         } else {
1077             $userid = $extusername;
1078         }
1080         $group_dns = explode(';', $this->config->creators);
1081         $creator = ldap_isgroupmember($ldapconnection, $userid, $group_dns, $this->config->memberattribute);
1083         $this->ldap_close();
1085         return $creator;
1086     }
1088     /**
1089      * Called when the user record is updated.
1090      *
1091      * Modifies user in external LDAP server. It takes olduser (before
1092      * changes) and newuser (after changes) compares information and
1093      * saves modified information to external LDAP server.
1094      *
1095      * @param mixed $olduser     Userobject before modifications    (without system magic quotes)
1096      * @param mixed $newuser     Userobject new modified userobject (without system magic quotes)
1097      * @return boolean result
1098      *
1099      */
1100     function user_update($olduser, $newuser) {
1101         global $USER;
1103         if (isset($olduser->username) and isset($newuser->username) and $olduser->username != $newuser->username) {
1104             error_log($this->errorlogtag.get_string('renamingnotallowed', 'auth_ldap'));
1105             return false;
1106         }
1108         if (isset($olduser->auth) and $olduser->auth != $this->authtype) {
1109             return true; // just change auth and skip update
1110         }
1112         $attrmap = $this->ldap_attributes();
1113         // Before doing anything else, make sure we really need to update anything
1114         // in the external LDAP server.
1115         $update_external = false;
1116         foreach ($attrmap as $key => $ldapkeys) {
1117             if (!empty($this->config->{'field_updateremote_'.$key})) {
1118                 $update_external = true;
1119                 break;
1120             }
1121         }
1122         if (!$update_external) {
1123             return true;
1124         }
1126         $extoldusername = textlib::convert($olduser->username, 'utf-8', $this->config->ldapencoding);
1128         $ldapconnection = $this->ldap_connect();
1130         $search_attribs = array();
1131         foreach ($attrmap as $key => $values) {
1132             if (!is_array($values)) {
1133                 $values = array($values);
1134             }
1135             foreach ($values as $value) {
1136                 if (!in_array($value, $search_attribs)) {
1137                     array_push($search_attribs, $value);
1138                 }
1139             }
1140         }
1142         if(!($user_dn = $this->ldap_find_userdn($ldapconnection, $extoldusername))) {
1143             return false;
1144         }
1146         $user_info_result = ldap_read($ldapconnection, $user_dn, '(objectClass=*)', $search_attribs);
1147         if ($user_info_result) {
1148             $user_entry = ldap_get_entries_moodle($ldapconnection, $user_info_result);
1149             if (empty($user_entry)) {
1150                 $attribs = join (', ', $search_attribs);
1151                 error_log($this->errorlogtag.get_string('updateusernotfound', 'auth_ldap',
1152                                                           array('userdn'=>$user_dn,
1153                                                                 'attribs'=>$attribs)));
1154                 return false; // old user not found!
1155             } else if (count($user_entry) > 1) {
1156                 error_log($this->errorlogtag.get_string('morethanoneuser', 'auth_ldap'));
1157                 return false;
1158             }
1160             $user_entry = array_change_key_case($user_entry[0], CASE_LOWER);
1162             foreach ($attrmap as $key => $ldapkeys) {
1163                 $profilefield = '';
1164                 // Only process if the moodle field ($key) has changed and we
1165                 // are set to update LDAP with it
1166                 $customprofilefield = 'profile_field_' . $key;
1167                 if (isset($olduser->$key) and isset($newuser->$key)
1168                     and ($olduser->$key !== $newuser->$key)) {
1169                     $profilefield = $key;
1170                 } else if (isset($olduser->$customprofilefield) && isset($newuser->$customprofilefield)
1171                     && $olduser->$customprofilefield !== $newuser->$customprofilefield) {
1172                     $profilefield = $customprofilefield;
1173                 }
1175                 if (!empty($profilefield) && !empty($this->config->{'field_updateremote_' . $key})) {
1176                     // For ldap values that could be in more than one
1177                     // ldap key, we will do our best to match
1178                     // where they came from
1179                     $ambiguous = true;
1180                     $changed   = false;
1181                     if (!is_array($ldapkeys)) {
1182                         $ldapkeys = array($ldapkeys);
1183                     }
1184                     if (count($ldapkeys) < 2) {
1185                         $ambiguous = false;
1186                     }
1188                     $nuvalue = textlib::convert($newuser->$profilefield, 'utf-8', $this->config->ldapencoding);
1189                     empty($nuvalue) ? $nuvalue = array() : $nuvalue;
1190                     $ouvalue = textlib::convert($olduser->$profilefield, 'utf-8', $this->config->ldapencoding);
1192                     foreach ($ldapkeys as $ldapkey) {
1193                         $ldapkey   = $ldapkey;
1194                         $ldapvalue = $user_entry[$ldapkey][0];
1195                         if (!$ambiguous) {
1196                             // Skip update if the values already match
1197                             if ($nuvalue !== $ldapvalue) {
1198                                 // This might fail due to schema validation
1199                                 if (@ldap_modify($ldapconnection, $user_dn, array($ldapkey => $nuvalue))) {
1200                                     continue;
1201                                 } else {
1202                                     error_log($this->errorlogtag.get_string ('updateremfail', 'auth_ldap',
1203                                                                              array('errno'=>ldap_errno($ldapconnection),
1204                                                                                    'errstring'=>ldap_err2str(ldap_errno($ldapconnection)),
1205                                                                                    'key'=>$key,
1206                                                                                    'ouvalue'=>$ouvalue,
1207                                                                                    'nuvalue'=>$nuvalue)));
1208                                     continue;
1209                                 }
1210                             }
1211                         } else {
1212                             // Ambiguous. Value empty before in Moodle (and LDAP) - use
1213                             // 1st ldap candidate field, no need to guess
1214                             if ($ouvalue === '') { // value empty before - use 1st ldap candidate
1215                                 // This might fail due to schema validation
1216                                 if (@ldap_modify($ldapconnection, $user_dn, array($ldapkey => $nuvalue))) {
1217                                     $changed = true;
1218                                     continue;
1219                                 } else {
1220                                     error_log($this->errorlogtag.get_string ('updateremfail', 'auth_ldap',
1221                                                                              array('errno'=>ldap_errno($ldapconnection),
1222                                                                                    'errstring'=>ldap_err2str(ldap_errno($ldapconnection)),
1223                                                                                    'key'=>$key,
1224                                                                                    'ouvalue'=>$ouvalue,
1225                                                                                    'nuvalue'=>$nuvalue)));
1226                                     continue;
1227                                 }
1228                             }
1230                             // We found which ldap key to update!
1231                             if ($ouvalue !== '' and $ouvalue === $ldapvalue ) {
1232                                 // This might fail due to schema validation
1233                                 if (@ldap_modify($ldapconnection, $user_dn, array($ldapkey => $nuvalue))) {
1234                                     $changed = true;
1235                                     continue;
1236                                 } else {
1237                                     error_log($this->errorlogtag.get_string ('updateremfail', 'auth_ldap',
1238                                                                              array('errno'=>ldap_errno($ldapconnection),
1239                                                                                    'errstring'=>ldap_err2str(ldap_errno($ldapconnection)),
1240                                                                                    'key'=>$key,
1241                                                                                    'ouvalue'=>$ouvalue,
1242                                                                                    'nuvalue'=>$nuvalue)));
1243                                     continue;
1244                                 }
1245                             }
1246                         }
1247                     }
1249                     if ($ambiguous and !$changed) {
1250                         error_log($this->errorlogtag.get_string ('updateremfailamb', 'auth_ldap',
1251                                                                  array('key'=>$key,
1252                                                                        'ouvalue'=>$ouvalue,
1253                                                                        'nuvalue'=>$nuvalue)));
1254                     }
1255                 }
1256             }
1257         } else {
1258             error_log($this->errorlogtag.get_string ('usernotfound', 'auth_ldap'));
1259             $this->ldap_close();
1260             return false;
1261         }
1263         $this->ldap_close();
1264         return true;
1266     }
1268     /**
1269      * Changes userpassword in LDAP
1270      *
1271      * Called when the user password is updated. It assumes it is
1272      * called by an admin or that you've otherwise checked the user's
1273      * credentials
1274      *
1275      * @param  object  $user        User table object
1276      * @param  string  $newpassword Plaintext password (not crypted/md5'ed)
1277      * @return boolean result
1278      *
1279      */
1280     function user_update_password($user, $newpassword) {
1281         global $USER;
1283         $result = false;
1284         $username = $user->username;
1286         $extusername = textlib::convert($username, 'utf-8', $this->config->ldapencoding);
1287         $extpassword = textlib::convert($newpassword, 'utf-8', $this->config->ldapencoding);
1289         switch ($this->config->passtype) {
1290             case 'md5':
1291                 $extpassword = '{MD5}' . base64_encode(pack('H*', md5($extpassword)));
1292                 break;
1293             case 'sha1':
1294                 $extpassword = '{SHA}' . base64_encode(pack('H*', sha1($extpassword)));
1295                 break;
1296             case 'plaintext':
1297             default:
1298                 break; // plaintext
1299         }
1301         $ldapconnection = $this->ldap_connect();
1303         $user_dn = $this->ldap_find_userdn($ldapconnection, $extusername);
1305         if (!$user_dn) {
1306             error_log($this->errorlogtag.get_string ('nodnforusername', 'auth_ldap', $user->username));
1307             return false;
1308         }
1310         switch ($this->config->user_type) {
1311             case 'edir':
1312                 // Change password
1313                 $result = ldap_modify($ldapconnection, $user_dn, array('userPassword' => $extpassword));
1314                 if (!$result) {
1315                     error_log($this->errorlogtag.get_string ('updatepasserror', 'auth_ldap',
1316                                                                array('errno'=>ldap_errno($ldapconnection),
1317                                                                      'errstring'=>ldap_err2str(ldap_errno($ldapconnection)))));
1318                 }
1319                 // Update password expiration time, grace logins count
1320                 $search_attribs = array($this->config->expireattr, 'passwordExpirationInterval', 'loginGraceLimit');
1321                 $sr = ldap_read($ldapconnection, $user_dn, '(objectClass=*)', $search_attribs);
1322                 if ($sr) {
1323                     $entry = ldap_get_entries_moodle($ldapconnection, $sr);
1324                     $info = array_change_key_case($entry[0], CASE_LOWER);
1325                     $newattrs = array();
1326                     if (!empty($info[$this->config->expireattr][0])) {
1327                         // Set expiration time only if passwordExpirationInterval is defined
1328                         if (!empty($info['passwordexpirationinterval'][0])) {
1329                            $expirationtime = time() + $info['passwordexpirationinterval'][0];
1330                            $ldapexpirationtime = $this->ldap_unix2expirationtime($expirationtime);
1331                            $newattrs['passwordExpirationTime'] = $ldapexpirationtime;
1332                         }
1334                         // Set gracelogin count
1335                         if (!empty($info['logingracelimit'][0])) {
1336                            $newattrs['loginGraceRemaining']= $info['logingracelimit'][0];
1337                         }
1339                         // Store attribute changes in LDAP
1340                         $result = ldap_modify($ldapconnection, $user_dn, $newattrs);
1341                         if (!$result) {
1342                             error_log($this->errorlogtag.get_string ('updatepasserrorexpiregrace', 'auth_ldap',
1343                                                                        array('errno'=>ldap_errno($ldapconnection),
1344                                                                              'errstring'=>ldap_err2str(ldap_errno($ldapconnection)))));
1345                         }
1346                     }
1347                 }
1348                 else {
1349                     error_log($this->errorlogtag.get_string ('updatepasserrorexpire', 'auth_ldap',
1350                                                              array('errno'=>ldap_errno($ldapconnection),
1351                                                                    'errstring'=>ldap_err2str(ldap_errno($ldapconnection)))));
1352                 }
1353                 break;
1355             case 'ad':
1356                 // Passwords in Active Directory must be encoded as Unicode
1357                 // strings (UCS-2 Little Endian format) and surrounded with
1358                 // double quotes. See http://support.microsoft.com/?kbid=269190
1359                 if (!function_exists('mb_convert_encoding')) {
1360                     error_log($this->errorlogtag.get_string ('needmbstring', 'auth_ldap'));
1361                     return false;
1362                 }
1363                 $extpassword = mb_convert_encoding('"'.$extpassword.'"', "UCS-2LE", $this->config->ldapencoding);
1364                 $result = ldap_modify($ldapconnection, $user_dn, array('unicodePwd' => $extpassword));
1365                 if (!$result) {
1366                     error_log($this->errorlogtag.get_string ('updatepasserror', 'auth_ldap',
1367                                                              array('errno'=>ldap_errno($ldapconnection),
1368                                                                    'errstring'=>ldap_err2str(ldap_errno($ldapconnection)))));
1369                 }
1370                 break;
1372             default:
1373                 // Send LDAP the password in cleartext, it will md5 it itself
1374                 $result = ldap_modify($ldapconnection, $user_dn, array('userPassword' => $extpassword));
1375                 if (!$result) {
1376                     error_log($this->errorlogtag.get_string ('updatepasserror', 'auth_ldap',
1377                                                              array('errno'=>ldap_errno($ldapconnection),
1378                                                                    'errstring'=>ldap_err2str(ldap_errno($ldapconnection)))));
1379                 }
1381         }
1383         $this->ldap_close();
1384         return $result;
1385     }
1387     /**
1388      * Take expirationtime and return it as unix timestamp in seconds
1389      *
1390      * Takes expiration timestamp as read from LDAP and returns it as unix timestamp in seconds
1391      * Depends on $this->config->user_type variable
1392      *
1393      * @param mixed time   Time stamp read from LDAP as it is.
1394      * @param string $ldapconnection Only needed for Active Directory.
1395      * @param string $user_dn User distinguished name for the user we are checking password expiration (only needed for Active Directory).
1396      * @return timestamp
1397      */
1398     function ldap_expirationtime2unix ($time, $ldapconnection, $user_dn) {
1399         $result = false;
1400         switch ($this->config->user_type) {
1401             case 'edir':
1402                 $yr=substr($time, 0, 4);
1403                 $mo=substr($time, 4, 2);
1404                 $dt=substr($time, 6, 2);
1405                 $hr=substr($time, 8, 2);
1406                 $min=substr($time, 10, 2);
1407                 $sec=substr($time, 12, 2);
1408                 $result = mktime($hr, $min, $sec, $mo, $dt, $yr);
1409                 break;
1410             case 'rfc2307':
1411             case 'rfc2307bis':
1412                 $result = $time * DAYSECS; // The shadowExpire contains the number of DAYS between 01/01/1970 and the actual expiration date
1413                 break;
1414             case 'ad':
1415                 $result = $this->ldap_get_ad_pwdexpire($time, $ldapconnection, $user_dn);
1416                 break;
1417             default:
1418                 print_error('auth_ldap_usertypeundefined', 'auth_ldap');
1419         }
1420         return $result;
1421     }
1423     /**
1424      * Takes unix timestamp and returns it formated for storing in LDAP
1425      *
1426      * @param integer unix time stamp
1427      */
1428     function ldap_unix2expirationtime($time) {
1429         $result = false;
1430         switch ($this->config->user_type) {
1431             case 'edir':
1432                 $result=date('YmdHis', $time).'Z';
1433                 break;
1434             case 'rfc2307':
1435             case 'rfc2307bis':
1436                 $result = $time ; // Already in correct format
1437                 break;
1438             default:
1439                 print_error('auth_ldap_usertypeundefined2', 'auth_ldap');
1440         }
1441         return $result;
1443     }
1445     /**
1446      * Returns user attribute mappings between moodle and LDAP
1447      *
1448      * @return array
1449      */
1451     function ldap_attributes () {
1452         $moodleattributes = array();
1453         // If we have custom fields then merge them with user fields.
1454         $customfields = $this->get_custom_user_profile_fields();
1455         if (!empty($customfields) && !empty($this->userfields)) {
1456             $userfields = array_merge($this->userfields, $customfields);
1457         } else {
1458             $userfields = $this->userfields;
1459         }
1461         foreach ($userfields as $field) {
1462             if (!empty($this->config->{"field_map_$field"})) {
1463                 $moodleattributes[$field] = textlib::strtolower(trim($this->config->{"field_map_$field"}));
1464                 if (preg_match('/,/', $moodleattributes[$field])) {
1465                     $moodleattributes[$field] = explode(',', $moodleattributes[$field]); // split ?
1466                 }
1467             }
1468         }
1469         $moodleattributes['username'] = textlib::strtolower(trim($this->config->user_attribute));
1470         return $moodleattributes;
1471     }
1473     /**
1474      * Returns all usernames from LDAP
1475      *
1476      * @param $filter An LDAP search filter to select desired users
1477      * @return array of LDAP user names converted to UTF-8
1478      */
1479     function ldap_get_userlist($filter='*') {
1480         $fresult = array();
1482         $ldapconnection = $this->ldap_connect();
1484         if ($filter == '*') {
1485            $filter = '(&('.$this->config->user_attribute.'=*)'.$this->config->objectclass.')';
1486         }
1488         $contexts = explode(';', $this->config->contexts);
1489         if (!empty($this->config->create_context)) {
1490             array_push($contexts, $this->config->create_context);
1491         }
1493         $ldap_pagedresults = ldap_paged_results_supported($this->config->ldap_version);
1494         foreach ($contexts as $context) {
1495             $context = trim($context);
1496             if (empty($context)) {
1497                 continue;
1498             }
1500             do {
1501                 if ($ldap_pagedresults) {
1502                     ldap_control_paged_result($ldapconnection, $this->config->pagesize, true, $ldap_cookie);
1503                 }
1504                 if ($this->config->search_sub) {
1505                     // Use ldap_search to find first user from subtree.
1506                     $ldap_result = ldap_search($ldapconnection, $context, $filter, array($this->config->user_attribute));
1507                 } else {
1508                     // Search only in this context.
1509                     $ldap_result = ldap_list($ldapconnection, $context, $filter, array($this->config->user_attribute));
1510                 }
1511                 if(!$ldap_result) {
1512                     continue;
1513                 }
1514                 if ($ldap_pagedresults) {
1515                     ldap_control_paged_result_response($ldapconnection, $ldap_result, $ldap_cookie);
1516                 }
1517                 $users = ldap_get_entries_moodle($ldapconnection, $ldap_result);
1518                 // Add found users to list.
1519                 for ($i = 0; $i < count($users); $i++) {
1520                     $extuser = textlib::convert($users[$i][$this->config->user_attribute][0],
1521                                                 $this->config->ldapencoding, 'utf-8');
1522                     array_push($fresult, $extuser);
1523                 }
1524                 unset($ldap_result); // Free mem.
1525             } while ($ldap_pagedresults && !empty($ldap_cookie));
1526         }
1528         // If paged results were used, make sure the current connection is completely closed
1529         $this->ldap_close($ldap_pagedresults);
1530         return $fresult;
1531     }
1533     /**
1534      * Indicates if password hashes should be stored in local moodle database.
1535      *
1536      * @return bool true means flag 'not_cached' stored instead of password hash
1537      */
1538     function prevent_local_passwords() {
1539         return !empty($this->config->preventpassindb);
1540     }
1542     /**
1543      * Returns true if this authentication plugin is 'internal'.
1544      *
1545      * @return bool
1546      */
1547     function is_internal() {
1548         return false;
1549     }
1551     /**
1552      * Returns true if this authentication plugin can change the user's
1553      * password.
1554      *
1555      * @return bool
1556      */
1557     function can_change_password() {
1558         return !empty($this->config->stdchangepassword) or !empty($this->config->changepasswordurl);
1559     }
1561     /**
1562      * Returns the URL for changing the user's password, or empty if the default can
1563      * be used.
1564      *
1565      * @return moodle_url
1566      */
1567     function change_password_url() {
1568         if (empty($this->config->stdchangepassword)) {
1569             return new moodle_url($this->config->changepasswordurl);
1570         } else {
1571             return null;
1572         }
1573     }
1575     /**
1576      * Will get called before the login page is shownr. Ff NTLM SSO
1577      * is enabled, and the user is in the right network, we'll redirect
1578      * to the magic NTLM page for SSO...
1579      *
1580      */
1581     function loginpage_hook() {
1582         global $CFG, $SESSION;
1584         // HTTPS is potentially required
1585         //httpsrequired(); - this must be used before setting the URL, it is already done on the login/index.php
1587         if (($_SERVER['REQUEST_METHOD'] === 'GET'         // Only on initial GET of loginpage
1588              || ($_SERVER['REQUEST_METHOD'] === 'POST'
1589                  && (get_referer() != strip_querystring(qualified_me()))))
1590                                                           // Or when POSTed from another place
1591                                                           // See MDL-14071
1592             && !empty($this->config->ntlmsso_enabled)     // SSO enabled
1593             && !empty($this->config->ntlmsso_subnet)      // have a subnet to test for
1594             && empty($_GET['authldap_skipntlmsso'])       // haven't failed it yet
1595             && (isguestuser() || !isloggedin())           // guestuser or not-logged-in users
1596             && address_in_subnet(getremoteaddr(), $this->config->ntlmsso_subnet)) {
1598             // First, let's remember where we were trying to get to before we got here
1599             if (empty($SESSION->wantsurl)) {
1600                 $SESSION->wantsurl = (array_key_exists('HTTP_REFERER', $_SERVER) &&
1601                                       $_SERVER['HTTP_REFERER'] != $CFG->wwwroot &&
1602                                       $_SERVER['HTTP_REFERER'] != $CFG->wwwroot.'/' &&
1603                                       $_SERVER['HTTP_REFERER'] != $CFG->httpswwwroot.'/login/' &&
1604                                       $_SERVER['HTTP_REFERER'] != $CFG->httpswwwroot.'/login/index.php')
1605                     ? $_SERVER['HTTP_REFERER'] : NULL;
1606             }
1608             // Now start the whole NTLM machinery.
1609             if(!empty($this->config->ntlmsso_ie_fastpath)) {
1610                 // Shortcut for IE browsers: skip the attempt page
1611                 if(check_browser_version('MSIE')) {
1612                     $sesskey = sesskey();
1613                     redirect($CFG->wwwroot.'/auth/ldap/ntlmsso_magic.php?sesskey='.$sesskey);
1614                 } else {
1615                     redirect($CFG->httpswwwroot.'/login/index.php?authldap_skipntlmsso=1');
1616                 }
1617             } else {
1618                 redirect($CFG->wwwroot.'/auth/ldap/ntlmsso_attempt.php');
1619             }
1620         }
1622         // No NTLM SSO, Use the normal login page instead.
1624         // If $SESSION->wantsurl is empty and we have a 'Referer:' header, the login
1625         // page insists on redirecting us to that page after user validation. If
1626         // we clicked on the redirect link at the ntlmsso_finish.php page (instead
1627         // of waiting for the redirection to happen) then we have a 'Referer:' header
1628         // we don't want to use at all. As we can't get rid of it, just point
1629         // $SESSION->wantsurl to $CFG->wwwroot (after all, we came from there).
1630         if (empty($SESSION->wantsurl)
1631             && (get_referer() == $CFG->httpswwwroot.'/auth/ldap/ntlmsso_finish.php')) {
1633             $SESSION->wantsurl = $CFG->wwwroot;
1634         }
1635     }
1637     /**
1638      * To be called from a page running under NTLM's
1639      * "Integrated Windows Authentication".
1640      *
1641      * If successful, it will set a special "cookie" (not an HTTP cookie!)
1642      * in cache_flags under the $this->pluginconfig/ntlmsess "plugin" and return true.
1643      * The "cookie" will be picked up by ntlmsso_finish() to complete the
1644      * process.
1645      *
1646      * On failure it will return false for the caller to display an appropriate
1647      * error message (probably saying that Integrated Windows Auth isn't enabled!)
1648      *
1649      * NOTE that this code will execute under the OS user credentials,
1650      * so we MUST avoid dealing with files -- such as session files.
1651      * (The caller should define('NO_MOODLE_COOKIES', true) before including config.php)
1652      *
1653      */
1654     function ntlmsso_magic($sesskey) {
1655         if (isset($_SERVER['REMOTE_USER']) && !empty($_SERVER['REMOTE_USER'])) {
1657             // HTTP __headers__ seem to be sent in ISO-8859-1 encoding
1658             // (according to my reading of RFC-1945, RFC-2616 and RFC-2617 and
1659             // my local tests), so we need to convert the REMOTE_USER value
1660             // (i.e., what we got from the HTTP WWW-Authenticate header) into UTF-8
1661             $username = textlib::convert($_SERVER['REMOTE_USER'], 'iso-8859-1', 'utf-8');
1663             switch ($this->config->ntlmsso_type) {
1664                 case 'ntlm':
1665                     // The format is now configurable, so try to extract the username
1666                     $username = $this->get_ntlm_remote_user($username);
1667                     if (empty($username)) {
1668                         return false;
1669                     }
1670                     break;
1671                 case 'kerberos':
1672                     // Format is username@DOMAIN
1673                     $username = substr($username, 0, strpos($username, '@'));
1674                     break;
1675                 default:
1676                     error_log($this->errorlogtag.get_string ('ntlmsso_unknowntype', 'auth_ldap'));
1677                     return false; // Should never happen!
1678             }
1680             $username = textlib::strtolower($username); // Compatibility hack
1681             set_cache_flag($this->pluginconfig.'/ntlmsess', $sesskey, $username, AUTH_NTLMTIMEOUT);
1682             return true;
1683         }
1684         return false;
1685     }
1687     /**
1688      * Find the session set by ntlmsso_magic(), validate it and
1689      * call authenticate_user_login() to authenticate the user through
1690      * the auth machinery.
1691      *
1692      * It is complemented by a similar check in user_login().
1693      *
1694      * If it succeeds, it never returns.
1695      *
1696      */
1697     function ntlmsso_finish() {
1698         global $CFG, $USER, $SESSION;
1700         $key = sesskey();
1701         $cf = get_cache_flags($this->pluginconfig.'/ntlmsess');
1702         if (!isset($cf[$key]) || $cf[$key] === '') {
1703             return false;
1704         }
1705         $username   = $cf[$key];
1706         // Here we want to trigger the whole authentication machinery
1707         // to make sure no step is bypassed...
1708         $user = authenticate_user_login($username, $key);
1709         if ($user) {
1710             add_to_log(SITEID, 'user', 'login', "view.php?id=$USER->id&course=".SITEID,
1711                        $user->id, 0, $user->id);
1712             complete_user_login($user);
1714             // Cleanup the key to prevent reuse...
1715             // and to allow re-logins with normal credentials
1716             unset_cache_flag($this->pluginconfig.'/ntlmsess', $key);
1718             // Redirection
1719             if (user_not_fully_set_up($USER)) {
1720                 $urltogo = $CFG->wwwroot.'/user/edit.php';
1721                 // We don't delete $SESSION->wantsurl yet, so we get there later
1722             } else if (isset($SESSION->wantsurl) and (strpos($SESSION->wantsurl, $CFG->wwwroot) === 0)) {
1723                 $urltogo = $SESSION->wantsurl;    // Because it's an address in this site
1724                 unset($SESSION->wantsurl);
1725             } else {
1726                 // No wantsurl stored or external - go to homepage
1727                 $urltogo = $CFG->wwwroot.'/';
1728                 unset($SESSION->wantsurl);
1729             }
1730             redirect($urltogo);
1731         }
1732         // Should never reach here.
1733         return false;
1734     }
1736     /**
1737      * Sync roles for this user
1738      *
1739      * @param $user object user object (without system magic quotes)
1740      */
1741     function sync_roles($user) {
1742         $iscreator = $this->iscreator($user->username);
1743         if ($iscreator === null) {
1744             return; // Nothing to sync - creators not configured
1745         }
1747         if ($roles = get_archetype_roles('coursecreator')) {
1748             $creatorrole = array_shift($roles);      // We can only use one, let's use the first one
1749             $systemcontext = context_system::instance();
1751             if ($iscreator) { // Following calls will not create duplicates
1752                 role_assign($creatorrole->id, $user->id, $systemcontext->id, $this->roleauth);
1753             } else {
1754                 // Unassign only if previously assigned by this plugin!
1755                 role_unassign($creatorrole->id, $user->id, $systemcontext->id, $this->roleauth);
1756             }
1757         }
1758     }
1760     /**
1761      * Prints a form for configuring this authentication plugin.
1762      *
1763      * This function is called from admin/auth.php, and outputs a full page with
1764      * a form for configuring this plugin.
1765      *
1766      * @param array $page An object containing all the data for this page.
1767      */
1768     function config_form($config, $err, $user_fields) {
1769         global $CFG, $OUTPUT;
1771         if (!function_exists('ldap_connect')) { // Is php-ldap really there?
1772             echo $OUTPUT->notification(get_string('auth_ldap_noextension', 'auth_ldap'));
1773             return;
1774         }
1776         include($CFG->dirroot.'/auth/ldap/config.html');
1777     }
1779     /**
1780      * Processes and stores configuration data for this authentication plugin.
1781      */
1782     function process_config($config) {
1783         // Set to defaults if undefined
1784         if (!isset($config->host_url)) {
1785              $config->host_url = '';
1786         }
1787         if (!isset($config->start_tls)) {
1788              $config->start_tls = false;
1789         }
1790         if (empty($config->ldapencoding)) {
1791          $config->ldapencoding = 'utf-8';
1792         }
1793         if (!isset($config->pagesize)) {
1794             $config->pagesize = LDAP_DEFAULT_PAGESIZE;
1795         }
1796         if (!isset($config->contexts)) {
1797              $config->contexts = '';
1798         }
1799         if (!isset($config->user_type)) {
1800              $config->user_type = 'default';
1801         }
1802         if (!isset($config->user_attribute)) {
1803              $config->user_attribute = '';
1804         }
1805         if (!isset($config->search_sub)) {
1806              $config->search_sub = '';
1807         }
1808         if (!isset($config->opt_deref)) {
1809              $config->opt_deref = LDAP_DEREF_NEVER;
1810         }
1811         if (!isset($config->preventpassindb)) {
1812              $config->preventpassindb = 0;
1813         }
1814         if (!isset($config->bind_dn)) {
1815             $config->bind_dn = '';
1816         }
1817         if (!isset($config->bind_pw)) {
1818             $config->bind_pw = '';
1819         }
1820         if (!isset($config->ldap_version)) {
1821             $config->ldap_version = '3';
1822         }
1823         if (!isset($config->objectclass)) {
1824             $config->objectclass = '';
1825         }
1826         if (!isset($config->memberattribute)) {
1827             $config->memberattribute = '';
1828         }
1829         if (!isset($config->memberattribute_isdn)) {
1830             $config->memberattribute_isdn = '';
1831         }
1832         if (!isset($config->creators)) {
1833             $config->creators = '';
1834         }
1835         if (!isset($config->create_context)) {
1836             $config->create_context = '';
1837         }
1838         if (!isset($config->expiration)) {
1839             $config->expiration = '';
1840         }
1841         if (!isset($config->expiration_warning)) {
1842             $config->expiration_warning = '10';
1843         }
1844         if (!isset($config->expireattr)) {
1845             $config->expireattr = '';
1846         }
1847         if (!isset($config->gracelogins)) {
1848             $config->gracelogins = '';
1849         }
1850         if (!isset($config->graceattr)) {
1851             $config->graceattr = '';
1852         }
1853         if (!isset($config->auth_user_create)) {
1854             $config->auth_user_create = '';
1855         }
1856         if (!isset($config->forcechangepassword)) {
1857             $config->forcechangepassword = 0;
1858         }
1859         if (!isset($config->stdchangepassword)) {
1860             $config->stdchangepassword = 0;
1861         }
1862         if (!isset($config->passtype)) {
1863             $config->passtype = 'plaintext';
1864         }
1865         if (!isset($config->changepasswordurl)) {
1866             $config->changepasswordurl = '';
1867         }
1868         if (!isset($config->removeuser)) {
1869             $config->removeuser = AUTH_REMOVEUSER_KEEP;
1870         }
1871         if (!isset($config->ntlmsso_enabled)) {
1872             $config->ntlmsso_enabled = 0;
1873         }
1874         if (!isset($config->ntlmsso_subnet)) {
1875             $config->ntlmsso_subnet = '';
1876         }
1877         if (!isset($config->ntlmsso_ie_fastpath)) {
1878             $config->ntlmsso_ie_fastpath = 0;
1879         }
1880         if (!isset($config->ntlmsso_type)) {
1881             $config->ntlmsso_type = 'ntlm';
1882         }
1883         if (!isset($config->ntlmsso_remoteuserformat)) {
1884             $config->ntlmsso_remoteuserformat = '';
1885         }
1887         // Try to remove duplicates before storing the contexts (to avoid problems in sync_users()).
1888         $config->contexts = explode(';', $config->contexts);
1889         $config->contexts = array_map(create_function('$x', 'return textlib::strtolower(trim($x));'),
1890                                       $config->contexts);
1891         $config->contexts = implode(';', array_unique($config->contexts));
1893         // Save settings
1894         set_config('host_url', trim($config->host_url), $this->pluginconfig);
1895         set_config('start_tls', $config->start_tls, $this->pluginconfig);
1896         set_config('ldapencoding', trim($config->ldapencoding), $this->pluginconfig);
1897         set_config('pagesize', (int)trim($config->pagesize), $this->pluginconfig);
1898         set_config('contexts', $config->contexts, $this->pluginconfig);
1899         set_config('user_type', textlib::strtolower(trim($config->user_type)), $this->pluginconfig);
1900         set_config('user_attribute', textlib::strtolower(trim($config->user_attribute)), $this->pluginconfig);
1901         set_config('search_sub', $config->search_sub, $this->pluginconfig);
1902         set_config('opt_deref', $config->opt_deref, $this->pluginconfig);
1903         set_config('preventpassindb', $config->preventpassindb, $this->pluginconfig);
1904         set_config('bind_dn', trim($config->bind_dn), $this->pluginconfig);
1905         set_config('bind_pw', $config->bind_pw, $this->pluginconfig);
1906         set_config('ldap_version', $config->ldap_version, $this->pluginconfig);
1907         set_config('objectclass', trim($config->objectclass), $this->pluginconfig);
1908         set_config('memberattribute', textlib::strtolower(trim($config->memberattribute)), $this->pluginconfig);
1909         set_config('memberattribute_isdn', $config->memberattribute_isdn, $this->pluginconfig);
1910         set_config('creators', trim($config->creators), $this->pluginconfig);
1911         set_config('create_context', trim($config->create_context), $this->pluginconfig);
1912         set_config('expiration', $config->expiration, $this->pluginconfig);
1913         set_config('expiration_warning', trim($config->expiration_warning), $this->pluginconfig);
1914         set_config('expireattr', textlib::strtolower(trim($config->expireattr)), $this->pluginconfig);
1915         set_config('gracelogins', $config->gracelogins, $this->pluginconfig);
1916         set_config('graceattr', textlib::strtolower(trim($config->graceattr)), $this->pluginconfig);
1917         set_config('auth_user_create', $config->auth_user_create, $this->pluginconfig);
1918         set_config('forcechangepassword', $config->forcechangepassword, $this->pluginconfig);
1919         set_config('stdchangepassword', $config->stdchangepassword, $this->pluginconfig);
1920         set_config('passtype', $config->passtype, $this->pluginconfig);
1921         set_config('changepasswordurl', trim($config->changepasswordurl), $this->pluginconfig);
1922         set_config('removeuser', $config->removeuser, $this->pluginconfig);
1923         set_config('ntlmsso_enabled', (int)$config->ntlmsso_enabled, $this->pluginconfig);
1924         set_config('ntlmsso_subnet', trim($config->ntlmsso_subnet), $this->pluginconfig);
1925         set_config('ntlmsso_ie_fastpath', (int)$config->ntlmsso_ie_fastpath, $this->pluginconfig);
1926         set_config('ntlmsso_type', $config->ntlmsso_type, 'auth/ldap');
1927         set_config('ntlmsso_remoteuserformat', trim($config->ntlmsso_remoteuserformat), 'auth/ldap');
1929         return true;
1930     }
1932     /**
1933      * Get password expiration time for a given user from Active Directory
1934      *
1935      * @param string $pwdlastset The time last time we changed the password.
1936      * @param resource $lcapconn The open LDAP connection.
1937      * @param string $user_dn The distinguished name of the user we are checking.
1938      *
1939      * @return string $unixtime
1940      */
1941     function ldap_get_ad_pwdexpire($pwdlastset, $ldapconn, $user_dn){
1942         global $CFG;
1944         if (!function_exists('bcsub')) {
1945             error_log($this->errorlogtag.get_string ('needbcmath', 'auth_ldap'));
1946             return 0;
1947         }
1949         // If UF_DONT_EXPIRE_PASSWD flag is set in user's
1950         // userAccountControl attribute, the password doesn't expire.
1951         $sr = ldap_read($ldapconn, $user_dn, '(objectClass=*)',
1952                         array('userAccountControl'));
1953         if (!$sr) {
1954             error_log($this->errorlogtag.get_string ('useracctctrlerror', 'auth_ldap', $user_dn));
1955             // Don't expire password, as we are not sure if it has to be
1956             // expired or not.
1957             return 0;
1958         }
1960         $entry = ldap_get_entries_moodle($ldapconn, $sr);
1961         $info = array_change_key_case($entry[0], CASE_LOWER);
1962         $useraccountcontrol = $info['useraccountcontrol'][0];
1963         if ($useraccountcontrol & UF_DONT_EXPIRE_PASSWD) {
1964             // Password doesn't expire.
1965             return 0;
1966         }
1968         // If pwdLastSet is zero, the user must change his/her password now
1969         // (unless UF_DONT_EXPIRE_PASSWD flag is set, but we already
1970         // tested this above)
1971         if ($pwdlastset === '0') {
1972             // Password has expired
1973             return -1;
1974         }
1976         // ----------------------------------------------------------------
1977         // Password expiration time in Active Directory is the composition of
1978         // two values:
1979         //
1980         //   - User's pwdLastSet attribute, that stores the last time
1981         //     the password was changed.
1982         //
1983         //   - Domain's maxPwdAge attribute, that sets how long
1984         //     passwords last in this domain.
1985         //
1986         // We already have the first value (passed in as a parameter). We
1987         // need to get the second one. As we don't know the domain DN, we
1988         // have to query rootDSE's defaultNamingContext attribute to get
1989         // it. Then we have to query that DN's maxPwdAge attribute to get
1990         // the real value.
1991         //
1992         // Once we have both values, we just need to combine them. But MS
1993         // chose to use a different base and unit for time measurements.
1994         // So we need to convert the values to Unix timestamps (see
1995         // details below).
1996         // ----------------------------------------------------------------
1998         $sr = ldap_read($ldapconn, ROOTDSE, '(objectClass=*)',
1999                         array('defaultNamingContext'));
2000         if (!$sr) {
2001             error_log($this->errorlogtag.get_string ('rootdseerror', 'auth_ldap'));
2002             return 0;
2003         }
2005         $entry = ldap_get_entries_moodle($ldapconn, $sr);
2006         $info = array_change_key_case($entry[0], CASE_LOWER);
2007         $domaindn = $info['defaultnamingcontext'][0];
2009         $sr = ldap_read ($ldapconn, $domaindn, '(objectClass=*)',
2010                          array('maxPwdAge'));
2011         $entry = ldap_get_entries_moodle($ldapconn, $sr);
2012         $info = array_change_key_case($entry[0], CASE_LOWER);
2013         $maxpwdage = $info['maxpwdage'][0];
2015         // ----------------------------------------------------------------
2016         // MSDN says that "pwdLastSet contains the number of 100 nanosecond
2017         // intervals since January 1, 1601 (UTC), stored in a 64 bit integer".
2018         //
2019         // According to Perl's Date::Manip, the number of seconds between
2020         // this date and Unix epoch is 11644473600. So we have to
2021         // substract this value to calculate a Unix time, once we have
2022         // scaled pwdLastSet to seconds. This is the script used to
2023         // calculate the value shown above:
2024         //
2025         //    #!/usr/bin/perl -w
2026         //
2027         //    use Date::Manip;
2028         //
2029         //    $date1 = ParseDate ("160101010000 UTC");
2030         //    $date2 = ParseDate ("197001010000 UTC");
2031         //    $delta = DateCalc($date1, $date2, \$err);
2032         //    $secs = Delta_Format($delta, 0, "%st");
2033         //    print "$secs \n";
2034         //
2035         // MSDN also says that "maxPwdAge is stored as a large integer that
2036         // represents the number of 100 nanosecond intervals from the time
2037         // the password was set before the password expires." We also need
2038         // to scale this to seconds. Bear in mind that this value is stored
2039         // as a _negative_ quantity (at least in my AD domain).
2040         //
2041         // As a last remark, if the low 32 bits of maxPwdAge are equal to 0,
2042         // the maximum password age in the domain is set to 0, which means
2043         // passwords do not expire (see
2044         // http://msdn2.microsoft.com/en-us/library/ms974598.aspx)
2045         //
2046         // As the quantities involved are too big for PHP integers, we
2047         // need to use BCMath functions to work with arbitrary precision
2048         // numbers.
2049         // ----------------------------------------------------------------
2051         // If the low order 32 bits are 0, then passwords do not expire in
2052         // the domain. Just do '$maxpwdage mod 2^32' and check the result
2053         // (2^32 = 4294967296)
2054         if (bcmod ($maxpwdage, 4294967296) === '0') {
2055             return 0;
2056         }
2058         // Add up pwdLastSet and maxPwdAge to get password expiration
2059         // time, in MS time units. Remember maxPwdAge is stored as a
2060         // _negative_ quantity, so we need to substract it in fact.
2061         $pwdexpire = bcsub ($pwdlastset, $maxpwdage);
2063         // Scale the result to convert it to Unix time units and return
2064         // that value.
2065         return bcsub( bcdiv($pwdexpire, '10000000'), '11644473600');
2066     }
2068     /**
2069      * Connect to the LDAP server, using the plugin configured
2070      * settings. It's actually a wrapper around ldap_connect_moodle()
2071      *
2072      * @return resource A valid LDAP connection (or dies if it can't connect)
2073      */
2074     function ldap_connect() {
2075         // Cache ldap connections. They are expensive to set up
2076         // and can drain the TCP/IP ressources on the server if we
2077         // are syncing a lot of users (as we try to open a new connection
2078         // to get the user details). This is the least invasive way
2079         // to reuse existing connections without greater code surgery.
2080         if(!empty($this->ldapconnection)) {
2081             $this->ldapconns++;
2082             return $this->ldapconnection;
2083         }
2085         if($ldapconnection = ldap_connect_moodle($this->config->host_url, $this->config->ldap_version,
2086                                                  $this->config->user_type, $this->config->bind_dn,
2087                                                  $this->config->bind_pw, $this->config->opt_deref,
2088                                                  $debuginfo, $this->config->start_tls)) {
2089             $this->ldapconns = 1;
2090             $this->ldapconnection = $ldapconnection;
2091             return $ldapconnection;
2092         }
2094         print_error('auth_ldap_noconnect_all', 'auth_ldap', '', $debuginfo);
2095     }
2097     /**
2098      * Disconnects from a LDAP server
2099      *
2100      * @param force boolean Forces closing the real connection to the LDAP server, ignoring any
2101      *                      cached connections. This is needed when we've used paged results
2102      *                      and want to use normal results again.
2103      */
2104     function ldap_close($force=false) {
2105         $this->ldapconns--;
2106         if (($this->ldapconns == 0) || ($force)) {
2107             $this->ldapconns = 0;
2108             @ldap_close($this->ldapconnection);
2109             unset($this->ldapconnection);
2110         }
2111     }
2113     /**
2114      * Search specified contexts for username and return the user dn
2115      * like: cn=username,ou=suborg,o=org. It's actually a wrapper
2116      * around ldap_find_userdn().
2117      *
2118      * @param resource $ldapconnection a valid LDAP connection
2119      * @param string $extusername the username to search (in external LDAP encoding, no db slashes)
2120      * @return mixed the user dn (external LDAP encoding) or false
2121      */
2122     function ldap_find_userdn($ldapconnection, $extusername) {
2123         $ldap_contexts = explode(';', $this->config->contexts);
2124         if (!empty($this->config->create_context)) {
2125             array_push($ldap_contexts, $this->config->create_context);
2126         }
2128         return ldap_find_userdn($ldapconnection, $extusername, $ldap_contexts, $this->config->objectclass,
2129                                 $this->config->user_attribute, $this->config->search_sub);
2130     }
2133     /**
2134      * A chance to validate form data, and last chance to do stuff
2135      * before it is inserted in config_plugin
2136      *
2137      * @param object object with submitted configuration settings (without system magic quotes)
2138      * @param array $err array of error messages (passed by reference)
2139      */
2140     function validate_form($form, &$err) {
2141         if ($form->ntlmsso_type == 'ntlm') {
2142             $format = trim($form->ntlmsso_remoteuserformat);
2143             if (!empty($format) && !preg_match('/%username%/i', $format)) {
2144                 $err['ntlmsso_remoteuserformat'] = get_string('auth_ntlmsso_missing_username', 'auth_ldap');
2145             }
2146         }
2147     }
2150     /**
2151      * When using NTLM SSO, the format of the remote username we get in
2152      * $_SERVER['REMOTE_USER'] may vary, depending on where from and how the web
2153      * server gets the data. So we let the admin configure the format using two
2154      * place holders (%domain% and %username%). This function tries to extract
2155      * the username (stripping the domain part and any separators if they are
2156      * present) from the value present in $_SERVER['REMOTE_USER'], using the
2157      * configured format.
2158      *
2159      * @param string $remoteuser The value from $_SERVER['REMOTE_USER'] (converted to UTF-8)
2160      *
2161      * @return string The remote username (without domain part or
2162      *                separators). Empty string if we can't extract the username.
2163      */
2164     protected function get_ntlm_remote_user($remoteuser) {
2165         if (empty($this->config->ntlmsso_remoteuserformat)) {
2166             $format = AUTH_NTLM_DEFAULT_FORMAT;
2167         } else {
2168             $format = $this->config->ntlmsso_remoteuserformat;
2169         }
2171         $format = preg_quote($format);
2172         $formatregex = preg_replace(array('#%domain%#', '#%username%#'),
2173                                     array('('.AUTH_NTLM_VALID_DOMAINNAME.')', '('.AUTH_NTLM_VALID_USERNAME.')'),
2174                                     $format);
2175         if (preg_match('#^'.$formatregex.'$#', $remoteuser, $matches)) {
2176             $user = end($matches);
2177             return $user;
2178         }
2180         /* We are unable to extract the username with the configured format. Probably
2181          * the format specified is wrong, so log a warning for the admin and return
2182          * an empty username.
2183          */
2184         error_log($this->errorlogtag.get_string ('auth_ntlmsso_maybeinvalidformat', 'auth_ldap'));
2185         return '';
2186     }
2188     /**
2189      * Check if the diagnostic message for the LDAP login error tells us that the
2190      * login is denied because the user password has expired or the password needs
2191      * to be changed on first login (using interactive SMB/Windows logins, not
2192      * LDAP logins).
2193      *
2194      * @param string the diagnostic message for the LDAP login error
2195      * @return bool true if the password has expired or the password must be changed on first login
2196      */
2197     protected function ldap_ad_pwdexpired_from_diagmsg($diagmsg) {
2198         // The format of the diagnostic message is (actual examples from W2003 and W2008):
2199         // "80090308: LdapErr: DSID-0C090334, comment: AcceptSecurityContext error, data 52e, vece"  (W2003)
2200         // "80090308: LdapErr: DSID-0C090334, comment: AcceptSecurityContext error, data 773, vece"  (W2003)
2201         // "80090308: LdapErr: DSID-0C0903AA, comment: AcceptSecurityContext error, data 52e, v1771" (W2008)
2202         // "80090308: LdapErr: DSID-0C0903AA, comment: AcceptSecurityContext error, data 773, v1771" (W2008)
2203         // We are interested in the 'data nnn' part.
2204         //   if nnn == 773 then user must change password on first login
2205         //   if nnn == 532 then user password has expired
2206         $diagmsg = explode(',', $diagmsg);
2207         if (preg_match('/data (773|532)/i', trim($diagmsg[2]))) {
2208             return true;
2209         }
2210         return false;
2211     }
2213 } // End of the class