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