weekly release 1.9.15+
[moodle.git] / auth / ldap / auth.php
blobd1ce83b8ba8af58861f2be83e79f81266bb7ceb7
1 <?php
3 /**
4 * @author Martin Dougiamas
5 * @license http://www.gnu.org/copyleft/gpl.html GNU Public License
6 * @package moodle multiauth
8 * Authentication Plugin: LDAP Authentication
10 * Authentication using LDAP (Lightweight Directory Access Protocol).
12 * 2006-08-28 File created.
15 if (!defined('MOODLE_INTERNAL')) {
16 die('Direct access to this script is forbidden.'); /// It must be included from a Moodle page
19 // See http://support.microsoft.com/kb/305144 to interprete these values.
20 if (!defined('AUTH_AD_ACCOUNTDISABLE')) {
21 define('AUTH_AD_ACCOUNTDISABLE', 0x0002);
23 if (!defined('AUTH_AD_NORMAL_ACCOUNT')) {
24 define('AUTH_AD_NORMAL_ACCOUNT', 0x0200);
26 if (!defined('AUTH_NTLMTIMEOUT')) { // timewindow for the NTLM SSO process, in secs...
27 define('AUTH_NTLMTIMEOUT', 10);
31 require_once($CFG->libdir.'/authlib.php');
33 /**
34 * LDAP authentication plugin.
36 class auth_plugin_ldap extends auth_plugin_base {
38 /**
39 * Constructor with initialisation.
41 function auth_plugin_ldap() {
42 $this->authtype = 'ldap';
43 $this->config = get_config('auth/ldap');
44 if (empty($this->config->ldapencoding)) {
45 $this->config->ldapencoding = 'utf-8';
47 if (empty($this->config->user_type)) {
48 $this->config->user_type = 'default';
51 $default = $this->ldap_getdefaults();
53 //use defaults if values not given
54 foreach ($default as $key => $value) {
55 // watch out - 0, false are correct values too
56 if (!isset($this->config->{$key}) or $this->config->{$key} == '') {
57 $this->config->{$key} = $value[$this->config->user_type];
61 // Hack prefix to objectclass
62 if (empty($this->config->objectclass)) {
63 // Can't send empty filter
64 $this->config->objectclass='(objectClass=*)';
65 } else if (stripos($this->config->objectclass, 'objectClass=') === 0) {
66 // Value is 'objectClass=some-string-here', so just add ()
67 // around the value (filter _must_ have them).
68 $this->config->objectclass = '('.$this->config->objectclass.')';
69 } else if (stripos($this->config->objectclass, '(') !== 0) {
70 // Value is 'some-string-not-starting-with-left-parentheses',
71 // which is assumed to be the objectClass matching value.
72 // So build a valid filter with it.
73 $this->config->objectclass = '(objectClass='.$this->config->objectclass.')';
74 } else {
75 // There is an additional possible value
76 // '(some-string-here)', that can be used to specify any
77 // valid filter string, to select subsets of users based
78 // on any criteria. For example, we could select the users
79 // whose objectClass is 'user' and have the
80 // 'enabledMoodleUser' attribute, with something like:
82 // (&(objectClass=user)(enabledMoodleUser=1))
84 // This is only used in the functions that deal with the
85 // whole potential set of users (currently sync_users()
86 // and get_user_list() only).
88 // In this particular case we don't need to do anything,
89 // so leave $this->config->objectclass as is.
94 /**
95 * Returns true if the username and password work and false if they are
96 * wrong or don't exist.
98 * @param string $username The username (with system magic quotes)
99 * @param string $password The password (with system magic quotes)
101 * @return bool Authentication success or failure.
103 function user_login($username, $password) {
104 if (! function_exists('ldap_bind')) {
105 print_error('auth_ldapnotinstalled','auth');
106 return false;
109 if (!$username or !$password) { // Don't allow blank usernames or passwords
110 return false;
113 $textlib = textlib_get_instance();
114 $extusername = $textlib->convert(stripslashes($username), 'utf-8', $this->config->ldapencoding);
115 $extpassword = $textlib->convert(stripslashes($password), 'utf-8', $this->config->ldapencoding);
118 // Before we connect to LDAP, check if this is an AD SSO login
119 // if we succeed in this block, we'll return success early.
121 $key = sesskey();
122 if (!empty($this->config->ntlmsso_enabled) && $key === $password) {
123 $cf = get_cache_flags('auth/ldap/ntlmsess');
124 // We only get the cache flag if we retrieve it before
125 // it expires (AUTH_NTLMTIMEOUT seconds).
126 if (!isset($cf[$key]) || $cf[$key] === '') {
127 return false;
130 $sessusername = $cf[$key];
131 if ($username === $sessusername) {
132 unset($sessusername);
133 unset($cf);
135 // Check that the user is inside one of the configured LDAP contexts
136 $validuser = false;
137 $ldapconnection = $this->ldap_connect();
138 if ($ldapconnection) {
139 // if the user is not inside the configured contexts,
140 // ldap_find_userdn returns false.
141 if ($this->ldap_find_userdn($ldapconnection, $extusername)) {
142 $validuser = true;
144 $this->ldap_close();
147 // Shortcut here - SSO confirmed
148 return $validuser;
150 } // End SSO processing
151 unset($key);
153 $ldapconnection = $this->ldap_connect();
154 if ($ldapconnection) {
155 $ldap_user_dn = $this->ldap_find_userdn($ldapconnection, $extusername);
157 //if ldap_user_dn is empty, user does not exist
158 if (!$ldap_user_dn) {
159 $this->ldap_close();
160 return false;
163 // Try to bind with current username and password
164 $ldap_login = @ldap_bind($ldapconnection, $ldap_user_dn, $extpassword);
165 $this->ldap_close();
166 if ($ldap_login) {
167 return true;
170 else {
171 $this->ldap_close();
172 print_error('auth_ldap_noconnect','auth','',$this->config->host_url);
174 return false;
178 * reads userinformation from ldap and return it in array()
180 * Read user information from external database and returns it as array().
181 * Function should return all information available. If you are saving
182 * this information to moodle user-table you should honor syncronization flags
184 * @param string $username username (with system magic quotes)
186 * @return mixed array with no magic quotes or false on error
188 function get_userinfo($username) {
189 $textlib = textlib_get_instance();
190 $extusername = $textlib->convert(stripslashes($username), 'utf-8', $this->config->ldapencoding);
192 $ldapconnection = $this->ldap_connect();
193 $attrmap = $this->ldap_attributes();
195 $result = array();
196 $search_attribs = array();
198 foreach ($attrmap as $key=>$values) {
199 if (!is_array($values)) {
200 $values = array($values);
202 foreach ($values as $value) {
203 if (!in_array($value, $search_attribs)) {
204 array_push($search_attribs, $value);
209 $user_dn = $this->ldap_find_userdn($ldapconnection, $extusername);
211 if (!$user_info_result = ldap_read($ldapconnection, $user_dn, $this->config->objectclass, $search_attribs)) {
212 return false; // error!
214 $user_entry = $this->ldap_get_entries($ldapconnection, $user_info_result);
215 if (empty($user_entry)) {
216 return false; // entry not found
219 foreach ($attrmap as $key=>$values) {
220 if (!is_array($values)) {
221 $values = array($values);
223 $ldapval = NULL;
224 foreach ($values as $value) {
225 if ((moodle_strtolower($value) == 'dn') || (moodle_strtolower($value) == 'distinguishedname')) {
226 $result[$key] = $user_dn;
228 if (!array_key_exists($value, $user_entry[0])) {
229 continue; // wrong data mapping!
231 if (is_array($user_entry[0][$value])) {
232 $newval = $textlib->convert($user_entry[0][$value][0], $this->config->ldapencoding, 'utf-8');
233 } else {
234 $newval = $textlib->convert($user_entry[0][$value], $this->config->ldapencoding, 'utf-8');
236 if (!empty($newval)) { // favour ldap entries that are set
237 $ldapval = $newval;
240 if (!is_null($ldapval)) {
241 $result[$key] = $ldapval;
245 $this->ldap_close();
246 return $result;
250 * reads userinformation from ldap and return it in an object
252 * @param string $username username (with system magic quotes)
253 * @return mixed object or false on error
255 function get_userinfo_asobj($username) {
256 $user_array = $this->get_userinfo($username);
257 if ($user_array == false) {
258 return false; //error or not found
260 $user_array = truncate_userinfo($user_array);
261 $user = new object();
262 foreach ($user_array as $key=>$value) {
263 $user->{$key} = $value;
265 return $user;
269 * returns all usernames from external database
271 * get_userlist returns all usernames from external database
273 * @return array
275 function get_userlist() {
276 return $this->ldap_get_userlist("({$this->config->user_attribute}=*)");
280 * checks if user exists on external db
282 * @param string $username (with system magic quotes)
284 function user_exists($username) {
286 $textlib = textlib_get_instance();
287 $extusername = $textlib->convert(stripslashes($username), 'utf-8', $this->config->ldapencoding);
289 //returns true if given username exist on ldap
290 $users = $this->ldap_get_userlist("({$this->config->user_attribute}=".$this->filter_addslashes($extusername).")");
291 return count($users);
295 * Creates a new user on external database.
296 * By using information in userobject
297 * Use user_exists to prevent dublicate usernames
299 * @param mixed $userobject Moodle userobject (with system magic quotes)
300 * @param mixed $plainpass Plaintext password (with system magic quotes)
302 function user_create($userobject, $plainpass) {
303 $textlib = textlib_get_instance();
304 $extusername = $textlib->convert(stripslashes($userobject->username), 'utf-8', $this->config->ldapencoding);
305 $extpassword = $textlib->convert(stripslashes($plainpass), 'utf-8', $this->config->ldapencoding);
307 switch ($this->config->passtype) {
308 case 'md5':
309 $extpassword = '{MD5}' . base64_encode(pack('H*', md5($extpassword)));
310 break;
311 case 'sha1':
312 $extpassword = '{SHA}' . base64_encode(pack('H*', sha1($extpassword)));
313 break;
314 case 'plaintext':
315 default:
316 break; // plaintext
319 $ldapconnection = $this->ldap_connect();
320 $attrmap = $this->ldap_attributes();
322 $newuser = array();
324 foreach ($attrmap as $key => $values) {
325 if (!is_array($values)) {
326 $values = array($values);
328 foreach ($values as $value) {
329 if (!empty($userobject->$key) ) {
330 $newuser[$value] = $textlib->convert(stripslashes($userobject->$key), 'utf-8', $this->config->ldapencoding);
335 //Following sets all mandatory and other forced attribute values
336 //User should be creted as login disabled untill email confirmation is processed
337 //Feel free to add your user type and send patches to paca@sci.fi to add them
338 //Moodle distribution
340 switch ($this->config->user_type) {
341 case 'edir':
342 $newuser['objectClass'] = array("inetOrgPerson","organizationalPerson","person","top");
343 $newuser['uniqueId'] = $extusername;
344 $newuser['logindisabled'] = "TRUE";
345 $newuser['userpassword'] = $extpassword;
346 $uadd = ldap_add($ldapconnection, $this->config->user_attribute.'="'.$this->ldap_addslashes($userobject->username).','.$this->config->create_context.'"', $newuser);
347 break;
348 case 'ad':
349 // User account creation is a two step process with AD. First you
350 // create the user object, then you set the password. If you try
351 // to set the password while creating the user, the operation
352 // fails.
354 // Passwords in Active Directory must be encoded as Unicode
355 // strings (UCS-2 Little Endian format) and surrounded with
356 // double quotes. See http://support.microsoft.com/?kbid=269190
357 if (!function_exists('mb_convert_encoding')) {
358 print_error ('auth_ldap_no_mbstring', 'auth');
361 // First create the user account, and mark it as disabled.
362 $newuser['objectClass'] = array('top','person','user','organizationalPerson');
363 $newuser['sAMAccountName'] = $extusername;
364 $newuser['userAccountControl'] = AUTH_AD_NORMAL_ACCOUNT |
365 AUTH_AD_ACCOUNTDISABLE;
366 $userdn = 'cn=' . $this->ldap_addslashes($extusername) .
367 ',' . $this->config->create_context;
368 if (!ldap_add($ldapconnection, $userdn, $newuser)) {
369 print_error ('auth_ldap_ad_create_req', 'auth');
372 // Now set the password
373 unset($newuser);
374 $newuser['unicodePwd'] = mb_convert_encoding('"' . $extpassword . '"',
375 "UCS-2LE", "UTF-8");
376 if(!ldap_modify($ldapconnection, $userdn, $newuser)) {
377 // Something went wrong: delete the user account and error out
378 ldap_delete ($ldapconnection, $userdn);
379 print_error ('auth_ldap_ad_create_req', 'auth');
381 $uadd = true;
382 break;
383 default:
384 print_error('auth_ldap_unsupportedusertype','auth','',$this->config->user_type);
386 $this->ldap_close();
387 return $uadd;
391 function can_reset_password() {
392 return !empty($this->config->stdchangepassword);
395 function can_signup() {
396 return (!empty($this->config->auth_user_create) and !empty($this->config->create_context));
400 * Sign up a new user ready for confirmation.
401 * Password is passed in plaintext.
403 * @param object $user new user object (with system magic quotes)
404 * @param boolean $notify print notice with link and terminate
406 function user_signup($user, $notify=true) {
407 global $CFG;
408 require_once($CFG->dirroot.'/user/profile/lib.php');
410 if ($this->user_exists($user->username)) {
411 print_error('auth_ldap_user_exists', 'auth');
414 $plainslashedpassword = $user->password;
415 unset($user->password);
417 if (! $this->user_create($user, $plainslashedpassword)) {
418 print_error('auth_ldap_create_error', 'auth');
421 if (! ($user->id = insert_record('user', $user)) ) {
422 print_error('auth_emailnoinsert', 'auth');
425 /// Save any custom profile field information
426 profile_save_data($user);
428 $this->update_user_record($user->username);
429 update_internal_user_password($user, $plainslashedpassword);
431 $user = get_record('user', 'id', $user->id);
432 events_trigger('user_created', $user);
434 if (! send_confirmation_email($user)) {
435 print_error('auth_emailnoemail', 'auth');
438 if ($notify) {
439 global $CFG;
440 $emailconfirm = get_string('emailconfirm');
441 $navlinks = array();
442 $navlinks[] = array('name' => $emailconfirm, 'link' => null, 'type' => 'misc');
443 $navigation = build_navigation($navlinks);
445 print_header($emailconfirm, $emailconfirm, $navigation);
446 notice(get_string('emailconfirmsent', '', $user->email), "$CFG->wwwroot/index.php");
447 } else {
448 return true;
453 * Returns true if plugin allows confirming of new users.
455 * @return bool
457 function can_confirm() {
458 return $this->can_signup();
462 * Confirm the new user as registered.
464 * @param string $username (with system magic quotes)
465 * @param string $confirmsecret (with system magic quotes)
467 function user_confirm($username, $confirmsecret) {
468 $user = get_complete_user_data('username', $username);
470 if (!empty($user)) {
471 if ($user->confirmed) {
472 return AUTH_CONFIRM_ALREADY;
474 } else if ($user->auth != 'ldap') {
475 return AUTH_CONFIRM_ERROR;
477 } else if ($user->secret == stripslashes($confirmsecret)) { // They have provided the secret key to get in
478 if (!$this->user_activate($username)) {
479 return AUTH_CONFIRM_FAIL;
481 if (!set_field("user", "confirmed", 1, "id", $user->id)) {
482 return AUTH_CONFIRM_FAIL;
484 if (!set_field("user", "firstaccess", time(), "id", $user->id)) {
485 return AUTH_CONFIRM_FAIL;
487 return AUTH_CONFIRM_OK;
489 } else {
490 return AUTH_CONFIRM_ERROR;
495 * return number of days to user password expires
497 * If userpassword does not expire it should return 0. If password is already expired
498 * it should return negative value.
500 * @param mixed $username username (with system magic quotes)
501 * @return integer
503 function password_expire($username) {
504 $result = 0;
506 $textlib = textlib_get_instance();
507 $extusername = $textlib->convert(stripslashes($username), 'utf-8', $this->config->ldapencoding);
509 $ldapconnection = $this->ldap_connect();
510 $user_dn = $this->ldap_find_userdn($ldapconnection, $extusername);
511 $search_attribs = array($this->config->expireattr);
512 $sr = ldap_read($ldapconnection, $user_dn, '(objectClass=*)', $search_attribs);
513 if ($sr) {
514 $info = $this->ldap_get_entries($ldapconnection, $sr);
515 if (!empty ($info) and !empty($info[0][$this->config->expireattr][0])) {
516 $expiretime = $this->ldap_expirationtime2unix($info[0][$this->config->expireattr][0], $ldapconnection, $user_dn);
517 if ($expiretime != 0) {
518 $now = time();
519 if ($expiretime > $now) {
520 $result = ceil(($expiretime - $now) / DAYSECS);
522 else {
523 $result = floor(($expiretime - $now) / DAYSECS);
527 } else {
528 error_log("ldap: password_expire did't find expiration time.");
531 //error_log("ldap: password_expire user $user_dn expires in $result days!");
532 return $result;
536 * syncronizes user fron external db to moodle user table
538 * Sync is now using username attribute.
540 * Syncing users removes or suspends users that dont exists anymore in external db.
541 * Creates new users and updates coursecreator status of users.
543 * @param int $bulk_insert_records will insert $bulkinsert_records per insert statement
544 * valid only with $unsafe. increase to a couple thousand for
545 * blinding fast inserts -- but test it: you may hit mysqld's
546 * max_allowed_packet limit.
547 * @param bool $do_updates will do pull in data updates from ldap if relevant
549 function sync_users ($bulk_insert_records = 1000, $do_updates = true) {
551 global $CFG;
553 $textlib = textlib_get_instance();
555 $droptablesql = array(); /// sql commands to drop the table (because session scope could be a problem for
556 /// some persistent drivers like ODBTP (mssql) or if this function is invoked
557 /// from within a PHP application using persistent connections
558 $temptable = $CFG->prefix . 'extuser';
559 $createtemptablesql = '';
561 // configure a temp table
562 print "Configuring temp table\n";
563 switch (strtolower($CFG->dbfamily)) {
564 case 'mysql':
565 $droptablesql[] = 'DROP TEMPORARY TABLE ' . $temptable; // sql command to drop the table (because session scope could be a problem)
566 $createtemptablesql = 'CREATE TEMPORARY TABLE ' . $temptable . ' (username VARCHAR(64), PRIMARY KEY (username)) ENGINE=MyISAM';
567 break;
568 case 'postgres':
569 $droptablesql[] = 'DROP TABLE ' . $temptable; // sql command to drop the table (because session scope could be a problem)
570 $bulk_insert_records = 1; // no support for multiple sets of values
571 $createtemptablesql = 'CREATE TEMPORARY TABLE '. $temptable . ' (username VARCHAR(64), PRIMARY KEY (username))';
572 break;
573 case 'mssql':
574 $temptable = '#'. $temptable; /// MSSQL temp tables begin with #
575 $droptablesql[] = 'DROP TABLE ' . $temptable; // sql command to drop the table (because session scope could be a problem)
576 $bulk_insert_records = 1; // no support for multiple sets of values
577 $createtemptablesql = 'CREATE TABLE ' . $temptable . ' (username VARCHAR(64), PRIMARY KEY (username))';
578 break;
579 case 'oracle':
580 $droptablesql[] = 'TRUNCATE TABLE ' . $temptable; // oracle requires truncate before being able to drop a temp table
581 $droptablesql[] = 'DROP TABLE ' . $temptable; // sql command to drop the table (because session scope could be a problem)
582 $bulk_insert_records = 1; // no support for multiple sets of values
583 $createtemptablesql = 'CREATE GLOBAL TEMPORARY TABLE '.$temptable.' (username VARCHAR(64), PRIMARY KEY (username)) ON COMMIT PRESERVE ROWS';
584 break;
588 execute_sql_arr($droptablesql, true, false); /// Drop temp table to avoid persistence problems later
589 echo "Creating temp table $temptable\n";
590 if(! execute_sql($createtemptablesql, false) ){
591 print "Failed to create temporary users table - aborting\n";
592 exit;
595 print "Connecting to ldap...\n";
596 $ldapconnection = $this->ldap_connect();
598 if (!$ldapconnection) {
599 $this->ldap_close();
600 print get_string('auth_ldap_noconnect','auth',$this->config->host_url);
601 exit;
604 ////
605 //// get user's list from ldap to sql in a scalable fashion
606 ////
607 // prepare some data we'll need
608 $filter = '(&('.$this->config->user_attribute.'=*)'.$this->config->objectclass.')';
610 $contexts = explode(";",$this->config->contexts);
612 if (!empty($this->config->create_context)) {
613 array_push($contexts, $this->config->create_context);
616 $fresult = array();
617 foreach ($contexts as $context) {
618 $context = trim($context);
619 if (empty($context)) {
620 continue;
622 begin_sql();
623 if ($this->config->search_sub) {
624 //use ldap_search to find first user from subtree
625 $ldap_result = ldap_search($ldapconnection, $context,
626 $filter,
627 array($this->config->user_attribute));
628 } else {
629 //search only in this context
630 $ldap_result = ldap_list($ldapconnection, $context,
631 $filter,
632 array($this->config->user_attribute));
635 if ($entry = ldap_first_entry($ldapconnection, $ldap_result)) {
636 do {
637 $value = ldap_get_values_len($ldapconnection, $entry, $this->config->user_attribute);
638 $value = $textlib->convert($value[0], $this->config->ldapencoding, 'utf-8');
639 // usernames are __always__ lowercase.
640 array_push($fresult, moodle_strtolower($value));
641 if (count($fresult) >= $bulk_insert_records) {
642 $this->ldap_bulk_insert($fresult, $temptable);
643 $fresult = array();
645 } while ($entry = ldap_next_entry($ldapconnection, $entry));
647 unset($ldap_result); // free mem
649 // insert any remaining users and release mem
650 if (count($fresult)) {
651 $this->ldap_bulk_insert($fresult, $temptable);
652 $fresult = array();
654 commit_sql();
657 /// preserve our user database
658 /// if the temp table is empty, it probably means that something went wrong, exit
659 /// so as to avoid mass deletion of users; which is hard to undo
660 $count = get_record_sql('SELECT COUNT(username) AS count, 1 FROM ' . $temptable);
661 $count = $count->{'count'};
662 if ($count < 1) {
663 print "Did not get any users from LDAP -- error? -- exiting\n";
664 exit;
665 } else {
666 print "Got $count records from LDAP\n\n";
670 /// User removal
671 // find users in DB that aren't in ldap -- to be removed!
672 // this is still not as scalable (but how often do we mass delete?)
673 if (!empty($this->config->removeuser)) {
674 $sql = "SELECT u.id, u.username, u.email, u.auth
675 FROM {$CFG->prefix}user u
676 LEFT JOIN $temptable e ON u.username = e.username
677 WHERE u.auth='ldap'
678 AND u.deleted=0
679 AND e.username IS NULL";
680 $remove_users = get_records_sql($sql);
682 if (!empty($remove_users)) {
683 print "User entries to remove: ". count($remove_users) . "\n";
685 foreach ($remove_users as $user) {
686 if ($this->config->removeuser == 2) {
687 if (delete_user($user)) {
688 echo "\t"; print_string('auth_dbdeleteuser', 'auth', array($user->username, $user->id)); echo "\n";
689 } else {
690 echo "\t"; print_string('auth_dbdeleteusererror', 'auth', $user->username); echo "\n";
692 } else if ($this->config->removeuser == 1) {
693 $updateuser = new object();
694 $updateuser->id = $user->id;
695 $updateuser->auth = 'nologin';
696 if (update_record('user', $updateuser)) {
697 echo "\t"; print_string('auth_dbsuspenduser', 'auth', array($user->username, $user->id)); echo "\n";
698 } else {
699 echo "\t"; print_string('auth_dbsuspendusererror', 'auth', $user->username); echo "\n";
703 } else {
704 print "No user entries to be removed\n";
706 unset($remove_users); // free mem!
709 /// Revive suspended users
710 if (!empty($this->config->removeuser) and $this->config->removeuser == 1) {
711 $sql = "SELECT u.id, u.username
712 FROM $temptable e, {$CFG->prefix}user u
713 WHERE e.username=u.username
714 AND u.auth='nologin'";
715 $revive_users = get_records_sql($sql);
717 if (!empty($revive_users)) {
718 print "User entries to be revived: ". count($revive_users) . "\n";
720 begin_sql();
721 foreach ($revive_users as $user) {
722 $updateuser = new object();
723 $updateuser->id = $user->id;
724 $updateuser->auth = 'ldap';
725 if (update_record('user', $updateuser)) {
726 echo "\t"; print_string('auth_dbreviveduser', 'auth', array($user->username, $user->id)); echo "\n";
727 } else {
728 echo "\t"; print_string('auth_dbrevivedusererror', 'auth', $user->username); echo "\n";
731 commit_sql();
732 } else {
733 print "No user entries to be revived\n";
736 unset($revive_users);
740 /// User Updates - time-consuming (optional)
741 if ($do_updates) {
742 // narrow down what fields we need to update
743 $all_keys = array_keys(get_object_vars($this->config));
744 $updatekeys = array();
745 foreach ($all_keys as $key) {
746 if (preg_match('/^field_updatelocal_(.+)$/',$key, $match)) {
747 // if we have a field to update it from
748 // and it must be updated 'onlogin' we
749 // update it on cron
750 if ( !empty($this->config->{'field_map_'.$match[1]})
751 and $this->config->{$match[0]} === 'onlogin') {
752 array_push($updatekeys, $match[1]); // the actual key name
756 // print_r($all_keys); print_r($updatekeys);
757 unset($all_keys); unset($key);
759 } else {
760 print "No updates to be done\n";
762 if ( $do_updates and !empty($updatekeys) ) { // run updates only if relevant
763 $users = get_records_sql("SELECT u.username, u.id
764 FROM {$CFG->prefix}user u
765 WHERE u.deleted=0 AND u.auth='ldap'");
766 if (!empty($users)) {
767 print "User entries to update: ". count($users). "\n";
769 $sitecontext = get_context_instance(CONTEXT_SYSTEM);
770 if (!empty($this->config->creators) and !empty($this->config->memberattribute)
771 and $roles = get_roles_with_capability('moodle/legacy:coursecreator', CAP_ALLOW)) {
772 $creatorrole = array_shift($roles); // We can only use one, let's use the first one
773 } else {
774 $creatorrole = false;
777 begin_sql();
778 $xcount = 0;
779 $maxxcount = 100;
781 foreach ($users as $user) {
782 echo "\t"; print_string('auth_dbupdatinguser', 'auth', array($user->username, $user->id));
783 if (!$this->update_user_record(addslashes($user->username), $updatekeys)) {
784 echo " - ".get_string('skipped');
786 echo "\n";
787 $xcount++;
789 // update course creators if needed
790 if ($creatorrole !== false) {
791 if ($this->iscreator($user->username)) {
792 role_assign($creatorrole->id, $user->id, 0, $sitecontext->id, 0, 0, 0, 'ldap');
793 } else {
794 role_unassign($creatorrole->id, $user->id, 0, $sitecontext->id, 'ldap');
798 if ($xcount++ > $maxxcount) {
799 commit_sql();
800 begin_sql();
801 $xcount = 0;
804 commit_sql();
805 unset($users); // free mem
807 } else { // end do updates
808 print "No updates to be done\n";
811 /// User Additions
812 // find users missing in DB that are in LDAP
813 // note that get_records_sql wants at least 2 fields returned,
814 // and gives me a nifty object I don't want.
815 // note: we do not care about deleted accounts anymore, this feature was replaced by suspending to nologin auth plugin
816 $sql = "SELECT e.username, e.username
817 FROM $temptable e LEFT JOIN {$CFG->prefix}user u ON e.username = u.username
818 WHERE u.id IS NULL";
819 $add_users = get_records_sql($sql); // get rid of the fat
821 if (!empty($add_users)) {
822 print "User entries to add: ". count($add_users). "\n";
824 $sitecontext = get_context_instance(CONTEXT_SYSTEM);
825 if (!empty($this->config->creators) and !empty($this->config->memberattribute)
826 and $roles = get_roles_with_capability('moodle/legacy:coursecreator', CAP_ALLOW)) {
827 $creatorrole = array_shift($roles); // We can only use one, let's use the first one
828 } else {
829 $creatorrole = false;
832 begin_sql();
833 foreach ($add_users as $user) {
834 $user = $this->get_userinfo_asobj(addslashes($user->username));
836 // prep a few params
837 $user->modified = time();
838 $user->confirmed = 1;
839 $user->auth = 'ldap';
840 $user->mnethostid = $CFG->mnet_localhost_id;
841 // get_userinfo_asobj() might have replaced $user->username with the value
842 // from the LDAP server (which can be mixed-case). Make sure it's lowercase
843 $user->username = trim(moodle_strtolower($user->username));
844 if (empty($user->lang)) {
845 $user->lang = $CFG->lang;
848 $user = addslashes_recursive($user);
850 if ($id = insert_record('user',$user)) {
851 echo "\t"; print_string('auth_dbinsertuser', 'auth', array(stripslashes($user->username), $id)); echo "\n";
852 $userobj = $this->update_user_record($user->username);
853 if (!empty($this->config->forcechangepassword)) {
854 set_user_preference('auth_forcepasswordchange', 1, $userobj->id);
857 // add course creators if needed
858 if ($creatorrole !== false and $this->iscreator(stripslashes($user->username))) {
859 role_assign($creatorrole->id, $id, 0, $sitecontext->id, 0, 0, 0, 'ldap');
861 } else {
862 echo "\t"; print_string('auth_dbinsertusererror', 'auth', $user->username); echo "\n";
866 commit_sql();
867 unset($add_users); // free mem
868 } else {
869 print "No users to be added\n";
871 $this->ldap_close();
872 return true;
876 * Update a local user record from an external source.
877 * This is a lighter version of the one in moodlelib -- won't do
878 * expensive ops such as enrolment.
880 * If you don't pass $updatekeys, there is a performance hit and
881 * values removed from LDAP won't be removed from moodle.
883 * @param string $username username (with system magic quotes)
885 function update_user_record($username, $updatekeys = false) {
886 global $CFG;
888 //just in case check text case
889 $username = trim(moodle_strtolower($username));
891 // get the current user record
892 $user = get_record('user', 'username', $username, 'mnethostid', $CFG->mnet_localhost_id);
893 if (empty($user)) { // trouble
894 error_log("Cannot update non-existent user: ".stripslashes($username));
895 print_error('auth_dbusernotexist','auth','',$username);
896 die;
899 // Protect the userid from being overwritten
900 $userid = $user->id;
902 if ($newinfo = $this->get_userinfo($username)) {
903 $newinfo = truncate_userinfo($newinfo);
905 if (empty($updatekeys)) { // all keys? this does not support removing values
906 $updatekeys = array_keys($newinfo);
909 foreach ($updatekeys as $key) {
910 if (isset($newinfo[$key])) {
911 $value = $newinfo[$key];
912 } else {
913 $value = '';
916 if (!empty($this->config->{'field_updatelocal_' . $key})) {
917 if ($user->{$key} != $value) { // only update if it's changed
918 set_field('user', $key, addslashes($value), 'id', $userid);
922 } else {
923 return false;
925 return get_record_select('user', "id = $userid AND deleted = 0");
929 * Bulk insert in SQL's temp table
930 * @param array $users is an array of usernames
932 function ldap_bulk_insert($users, $temptable) {
934 // bulk insert -- superfast with $bulk_insert_records
935 $sql = 'INSERT INTO ' . $temptable . ' (username) VALUES ';
936 // make those values safe
937 $users = addslashes_recursive($users);
938 // join and quote the whole lot
939 $sql = $sql . "('" . implode("'),('", $users) . "')";
940 print "\t+ " . count($users) . " users\n";
941 execute_sql($sql, false);
946 * Activates (enables) user in external db so user can login to external db
948 * @param mixed $username username (with system magic quotes)
949 * @return boolen result
951 function user_activate($username) {
952 $textlib = textlib_get_instance();
953 $extusername = $textlib->convert(stripslashes($username), 'utf-8', $this->config->ldapencoding);
955 $ldapconnection = $this->ldap_connect();
957 $userdn = $this->ldap_find_userdn($ldapconnection, $extusername);
958 switch ($this->config->user_type) {
959 case 'edir':
960 $newinfo['loginDisabled']="FALSE";
961 break;
962 case 'ad':
963 // We need to unset the ACCOUNTDISABLE bit in the
964 // userAccountControl attribute ( see
965 // http://support.microsoft.com/kb/305144 )
966 $sr = ldap_read($ldapconnection, $userdn, '(objectClass=*)',
967 array('userAccountControl'));
968 $info = ldap_get_entries($ldapconnection, $sr);
969 $newinfo['userAccountControl'] = $info[0]['userAccountControl'][0]
970 & (~AUTH_AD_ACCOUNTDISABLE);
971 break;
972 default:
973 error ('auth: ldap user_activate() does not support selected usertype:"'.$this->config->user_type.'" (..yet)');
975 $result = ldap_modify($ldapconnection, $userdn, $newinfo);
976 $this->ldap_close();
977 return $result;
981 * Disables user in external db so user can't login to external db
983 * @param mixed $username username
984 * @return boolean result
986 /* function user_disable($username) {
987 $textlib = textlib_get_instance();
988 $extusername = $textlib->convert(stripslashes($username), 'utf-8', $this->config->ldapencoding);
990 $ldapconnection = $this->ldap_connect();
992 $userdn = $this->ldap_find_userdn($ldapconnection, $extusername);
993 switch ($this->config->user_type) {
994 case 'edir':
995 $newinfo['loginDisabled']="TRUE";
996 break;
997 case 'ad':
998 // We need to set the ACCOUNTDISABLE bit in the
999 // userAccountControl attribute ( see
1000 // http://support.microsoft.com/kb/305144 )
1001 $sr = ldap_read($ldapconnection, $userdn, '(objectClass=*)',
1002 array('userAccountControl'));
1003 $info = auth_ldap_get_entries($ldapconnection, $sr);
1004 $newinfo['userAccountControl'] = $info[0]['userAccountControl'][0]
1005 | AUTH_AD_ACCOUNTDISABLE;
1006 break;
1007 default:
1008 error ('auth: ldap user_disable() does not support selected usertype (..yet)');
1010 $result = ldap_modify($ldapconnection, $userdn, $newinfo);
1011 $this->ldap_close();
1012 return $result;
1016 * Returns true if user should be coursecreator.
1018 * @param mixed $username username (without system magic quotes)
1019 * @return boolean result
1021 function iscreator($username) {
1022 if (empty($this->config->creators) or empty($this->config->memberattribute)) {
1023 return null;
1026 $textlib = textlib_get_instance();
1027 $extusername = $textlib->convert($username, 'utf-8', $this->config->ldapencoding);
1029 return (boolean)$this->ldap_isgroupmember($extusername, $this->config->creators);
1033 * Called when the user record is updated.
1034 * Modifies user in external database. It takes olduser (before changes) and newuser (after changes)
1035 * conpares information saved modified information to external db.
1037 * @param mixed $olduser Userobject before modifications (without system magic quotes)
1038 * @param mixed $newuser Userobject new modified userobject (without system magic quotes)
1039 * @return boolean result
1042 function user_update($olduser, $newuser) {
1044 global $USER;
1046 if (isset($olduser->username) and isset($newuser->username) and $olduser->username != $newuser->username) {
1047 error_log("ERROR:User renaming not allowed in LDAP");
1048 return false;
1051 if (isset($olduser->auth) and $olduser->auth != 'ldap') {
1052 return true; // just change auth and skip update
1055 $attrmap = $this->ldap_attributes();
1057 // Before doing anything else, make sure really need to update anything
1058 // in the external LDAP server.
1059 $update_external = false;
1060 foreach ($attrmap as $key => $ldapkeys) {
1061 if (!empty($this->config->{'field_updateremote_'.$key})) {
1062 $update_external = true;
1063 break;
1066 if (!$update_external) {
1067 return true;
1070 $textlib = textlib_get_instance();
1071 $extoldusername = $textlib->convert($olduser->username, 'utf-8', $this->config->ldapencoding);
1073 $ldapconnection = $this->ldap_connect();
1075 $search_attribs = array();
1077 foreach ($attrmap as $key => $values) {
1078 if (!is_array($values)) {
1079 $values = array($values);
1081 foreach ($values as $value) {
1082 if (!in_array($value, $search_attribs)) {
1083 array_push($search_attribs, $value);
1088 $user_dn = $this->ldap_find_userdn($ldapconnection, $extoldusername);
1090 $user_info_result = ldap_read($ldapconnection, $user_dn,
1091 $this->config->objectclass, $search_attribs);
1093 if ($user_info_result) {
1095 $user_entry = $this->ldap_get_entries($ldapconnection, $user_info_result);
1096 if (empty($user_entry)) {
1097 $error = 'ldap: Could not find user while updating externally. '.
1098 'Details follow: search base: \''.$user_dn.'\'; search filter: \''.
1099 $this->config->objectclass.'\'; search attributes: ';
1100 foreach ($search_attribs as $attrib) {
1101 $error .= $attrib.' ';
1103 error_log($error);
1104 return false; // old user not found!
1105 } else if (count($user_entry) > 1) {
1106 error_log('ldap: Strange! More than one user record found in ldap. Only using the first one.');
1107 return false;
1109 $user_entry = $user_entry[0];
1111 //error_log(var_export($user_entry) . 'fpp' );
1113 foreach ($attrmap as $key => $ldapkeys) {
1114 // only process if the moodle field ($key) has changed and we
1115 // are set to update LDAP with it
1116 if (isset($olduser->$key) and isset($newuser->$key)
1117 and $olduser->$key !== $newuser->$key
1118 and !empty($this->config->{'field_updateremote_'. $key})) {
1119 // for ldap values that could be in more than one
1120 // ldap key, we will do our best to match
1121 // where they came from
1122 $ambiguous = true;
1123 $changed = false;
1124 if (!is_array($ldapkeys)) {
1125 $ldapkeys = array($ldapkeys);
1127 if (count($ldapkeys) < 2) {
1128 $ambiguous = false;
1131 $nuvalue = $textlib->convert($newuser->$key, 'utf-8', $this->config->ldapencoding);
1132 empty($nuvalue) ? $nuvalue = array() : $nuvalue;
1133 $ouvalue = $textlib->convert($olduser->$key, 'utf-8', $this->config->ldapencoding);
1135 foreach ($ldapkeys as $ldapkey) {
1136 $ldapkey = $ldapkey;
1137 $ldapvalue = $user_entry[$ldapkey][0];
1138 if (!$ambiguous) {
1139 // skip update if the values already match
1140 if ($nuvalue !== $ldapvalue) {
1141 //this might fail due to schema validation
1142 if (@ldap_modify($ldapconnection, $user_dn, array($ldapkey => $nuvalue))) {
1143 continue;
1144 } else {
1145 error_log('Error updating LDAP record. Error code: '
1146 . ldap_errno($ldapconnection) . '; Error string : '
1147 . ldap_err2str(ldap_errno($ldapconnection))
1148 . "\nKey ($key) - old moodle value: '$ouvalue' new value: '$nuvalue'");
1149 continue;
1152 } else {
1153 // ambiguous
1154 // value empty before in Moodle (and LDAP) - use 1st ldap candidate field
1155 // no need to guess
1156 if ($ouvalue === '') { // value empty before - use 1st ldap candidate
1157 //this might fail due to schema validation
1158 if (@ldap_modify($ldapconnection, $user_dn, array($ldapkey => $nuvalue))) {
1159 $changed = true;
1160 continue;
1161 } else {
1162 error_log('Error updating LDAP record. Error code: '
1163 . ldap_errno($ldapconnection) . '; Error string : '
1164 . ldap_err2str(ldap_errno($ldapconnection))
1165 . "\nKey ($key) - old moodle value: '$ouvalue' new value: '$nuvalue'");
1166 continue;
1170 // we found which ldap key to update!
1171 if ($ouvalue !== '' and $ouvalue === $ldapvalue ) {
1172 //this might fail due to schema validation
1173 if (@ldap_modify($ldapconnection, $user_dn, array($ldapkey => $nuvalue))) {
1174 $changed = true;
1175 continue;
1176 } else {
1177 error_log('Error updating LDAP record. Error code: '
1178 . ldap_errno($ldapconnection) . '; Error string : '
1179 . ldap_err2str(ldap_errno($ldapconnection))
1180 . "\nKey ($key) - old moodle value: '$ouvalue' new value: '$nuvalue'");
1181 continue;
1187 if ($ambiguous and !$changed) {
1188 error_log("Failed to update LDAP with ambiguous field $key".
1189 " old moodle value: '" . $ouvalue .
1190 "' new value '" . $nuvalue );
1194 } else {
1195 error_log("ERROR:No user found in LDAP");
1196 $this->ldap_close();
1197 return false;
1200 $this->ldap_close();
1202 return true;
1207 * changes userpassword in external db
1209 * called when the user password is updated.
1210 * changes userpassword in external db
1212 * @param object $user User table object (with system magic quotes)
1213 * @param string $newpassword Plaintext password (with system magic quotes)
1214 * @return boolean result
1217 function user_update_password($user, $newpassword) {
1218 /// called when the user password is updated -- it assumes it is called by an admin
1219 /// or that you've otherwise checked the user's credentials
1220 /// IMPORTANT: $newpassword must be cleartext, not crypted/md5'ed
1222 global $USER;
1223 $result = false;
1224 $username = $user->username;
1226 $textlib = textlib_get_instance();
1227 $extusername = $textlib->convert(stripslashes($username), 'utf-8', $this->config->ldapencoding);
1228 $extpassword = $textlib->convert(stripslashes($newpassword), 'utf-8', $this->config->ldapencoding);
1230 switch ($this->config->passtype) {
1231 case 'md5':
1232 $extpassword = '{MD5}' . base64_encode(pack('H*', md5($extpassword)));
1233 break;
1234 case 'sha1':
1235 $extpassword = '{SHA}' . base64_encode(pack('H*', sha1($extpassword)));
1236 break;
1237 case 'plaintext':
1238 default:
1239 break; // plaintext
1242 $ldapconnection = $this->ldap_connect();
1244 $user_dn = $this->ldap_find_userdn($ldapconnection, $extusername);
1246 if (!$user_dn) {
1247 error_log('LDAP Error in user_update_password(). No DN for: ' . stripslashes($user->username));
1248 return false;
1251 switch ($this->config->user_type) {
1252 case 'edir':
1253 //Change password
1254 $result = ldap_modify($ldapconnection, $user_dn, array('userPassword' => $extpassword));
1255 if (!$result) {
1256 error_log('LDAP Error in user_update_password(). Error code: '
1257 . ldap_errno($ldapconnection) . '; Error string : '
1258 . ldap_err2str(ldap_errno($ldapconnection)));
1260 //Update password expiration time, grace logins count
1261 $search_attribs = array($this->config->expireattr, 'passwordExpirationInterval','loginGraceLimit' );
1262 $sr = ldap_read($ldapconnection, $user_dn, '(objectClass=*)', $search_attribs);
1263 if ($sr) {
1264 $info=$this->ldap_get_entries($ldapconnection, $sr);
1265 $newattrs = array();
1266 if (!empty($info[0][$this->config->expireattr][0])) {
1267 //Set expiration time only if passwordExpirationInterval is defined
1268 if (!empty($info[0]['passwordExpirationInterval'][0])) {
1269 $expirationtime = time() + $info[0]['passwordExpirationInterval'][0];
1270 $ldapexpirationtime = $this->ldap_unix2expirationtime($expirationtime);
1271 $newattrs['passwordExpirationTime'] = $ldapexpirationtime;
1274 //set gracelogin count
1275 if (!empty($info[0]['loginGraceLimit'][0])) {
1276 $newattrs['loginGraceRemaining']= $info[0]['loginGraceLimit'][0];
1279 //Store attribute changes to ldap
1280 $result = ldap_modify($ldapconnection, $user_dn, $newattrs);
1281 if (!$result) {
1282 error_log('LDAP Error in user_update_password() when modifying expirationtime and/or gracelogins. Error code: '
1283 . ldap_errno($ldapconnection) . '; Error string : '
1284 . ldap_err2str(ldap_errno($ldapconnection)));
1288 else {
1289 error_log('LDAP Error in user_update_password() when reading password expiration time. Error code: '
1290 . ldap_errno($ldapconnection) . '; Error string : '
1291 . ldap_err2str(ldap_errno($ldapconnection)));
1293 break;
1295 case 'ad':
1296 // Passwords in Active Directory must be encoded as Unicode
1297 // strings (UCS-2 Little Endian format) and surrounded with
1298 // double quotes. See http://support.microsoft.com/?kbid=269190
1299 if (!function_exists('mb_convert_encoding')) {
1300 error_log ('You need the mbstring extension to change passwords in Active Directory');
1301 return false;
1303 $extpassword = mb_convert_encoding('"'.$extpassword.'"', "UCS-2LE", $this->config->ldapencoding);
1304 $result = ldap_modify($ldapconnection, $user_dn, array('unicodePwd' => $extpassword));
1305 if (!$result) {
1306 error_log('LDAP Error in user_update_password(). Error code: '
1307 . ldap_errno($ldapconnection) . '; Error string : '
1308 . ldap_err2str(ldap_errno($ldapconnection)));
1310 break;
1312 default:
1313 $usedconnection = &$ldapconnection;
1314 // send ldap the password in cleartext, it will md5 it itself
1315 $result = ldap_modify($ldapconnection, $user_dn, array('userPassword' => $extpassword));
1316 if (!$result) {
1317 error_log('LDAP Error in user_update_password(). Error code: '
1318 . ldap_errno($ldapconnection) . '; Error string : '
1319 . ldap_err2str(ldap_errno($ldapconnection)));
1324 $this->ldap_close();
1325 return $result;
1328 //PRIVATE FUNCTIONS starts
1329 //private functions are named as ldap_*
1332 * returns predefined usertypes
1334 * @return array of predefined usertypes
1336 function ldap_suppported_usertypes() {
1337 $types = array();
1338 $types['edir']='Novell Edirectory';
1339 $types['rfc2307']='posixAccount (rfc2307)';
1340 $types['rfc2307bis']='posixAccount (rfc2307bis)';
1341 $types['samba']='sambaSamAccount (v.3.0.7)';
1342 $types['ad']='MS ActiveDirectory';
1343 $types['default']=get_string('default');
1344 return $types;
1349 * Initializes needed variables for ldap-module
1351 * Uses names defined in ldap_supported_usertypes.
1352 * $default is first defined as:
1353 * $default['pseudoname'] = array(
1354 * 'typename1' => 'value',
1355 * 'typename2' => 'value'
1356 * ....
1357 * );
1359 * @return array of default values
1361 function ldap_getdefaults() {
1362 $default['objectclass'] = array(
1363 'edir' => 'User',
1364 'rfc2307' => 'posixAccount',
1365 'rfc2307bis' => 'posixAccount',
1366 'samba' => 'sambaSamAccount',
1367 'ad' => 'user',
1368 'default' => '*'
1370 $default['user_attribute'] = array(
1371 'edir' => 'cn',
1372 'rfc2307' => 'uid',
1373 'rfc2307bis' => 'uid',
1374 'samba' => 'uid',
1375 'ad' => 'cn',
1376 'default' => 'cn'
1378 $default['memberattribute'] = array(
1379 'edir' => 'member',
1380 'rfc2307' => 'member',
1381 'rfc2307bis' => 'member',
1382 'samba' => 'member',
1383 'ad' => 'member',
1384 'default' => 'member'
1386 $default['memberattribute_isdn'] = array(
1387 'edir' => '1',
1388 'rfc2307' => '0',
1389 'rfc2307bis' => '1',
1390 'samba' => '0', //is this right?
1391 'ad' => '1',
1392 'default' => '0'
1394 $default['expireattr'] = array (
1395 'edir' => 'passwordExpirationTime',
1396 'rfc2307' => 'shadowExpire',
1397 'rfc2307bis' => 'shadowExpire',
1398 'samba' => '', //No support yet
1399 'ad' => 'pwdLastSet',
1400 'default' => ''
1402 return $default;
1406 * return binaryfields of selected usertype
1409 * @return array
1411 function ldap_getbinaryfields () {
1412 $binaryfields = array (
1413 'edir' => array('guid'),
1414 'rfc2307' => array(),
1415 'rfc2307bis' => array(),
1416 'samba' => array(),
1417 'ad' => array(),
1418 'default' => array()
1420 if (!empty($this->config->user_type)) {
1421 return $binaryfields[$this->config->user_type];
1423 else {
1424 return $binaryfields['default'];
1428 function ldap_isbinary ($field) {
1429 if (empty($field)) {
1430 return false;
1432 return array_search($field, $this->ldap_getbinaryfields());
1436 * take expirationtime and return it as unixseconds
1438 * takes expriration timestamp as readed from ldap
1439 * returns it as unix seconds
1440 * depends on $this->config->user_type variable
1442 * @param mixed time Time stamp readed from ldap as it is.
1443 * @param string $ldapconnection Just needed for Active Directory.
1444 * @param string $user_dn User distinguished name for the user we are checking password expiration (just needed for Active Directory).
1445 * @return timestamp
1447 function ldap_expirationtime2unix ($time, $ldapconnection, $user_dn) {
1448 $result = false;
1449 switch ($this->config->user_type) {
1450 case 'edir':
1451 $yr=substr($time,0,4);
1452 $mo=substr($time,4,2);
1453 $dt=substr($time,6,2);
1454 $hr=substr($time,8,2);
1455 $min=substr($time,10,2);
1456 $sec=substr($time,12,2);
1457 $result = mktime($hr,$min,$sec,$mo,$dt,$yr);
1458 break;
1459 case 'rfc2307':
1460 case 'rfc2307bis':
1461 $result = $time * DAYSECS; //The shadowExpire contains the number of DAYS between 01/01/1970 and the actual expiration date
1462 break;
1463 case 'ad':
1464 $result = $this->ldap_get_ad_pwdexpire($time, $ldapconnection, $user_dn);
1465 break;
1466 default:
1467 print_error('auth_ldap_usertypeundefined', 'auth');
1469 return $result;
1473 * takes unixtime and return it formated for storing in ldap
1475 * @param integer unix time stamp
1477 function ldap_unix2expirationtime($time) {
1478 $result = false;
1479 switch ($this->config->user_type) {
1480 case 'edir':
1481 $result=date('YmdHis', $time).'Z';
1482 break;
1483 case 'rfc2307':
1484 case 'rfc2307bis':
1485 $result = $time ; //Already in correct format
1486 break;
1487 default:
1488 print_error('auth_ldap_usertypeundefined2', 'auth');
1490 return $result;
1495 * checks if user belong to specific group(s)
1496 * or is in a subtree.
1498 * Returns true if user belongs group in grupdns string OR
1499 * if the DN of the user is in a subtree pf the DN provided
1500 * as "group"
1502 * @param mixed $username username
1503 * @param mixed $groupdns string of group dn separated by ;
1506 function ldap_isgroupmember($extusername='', $groupdns='') {
1507 // Takes username and groupdn(s) , separated by ;
1508 // Returns true if user is member of any given groups
1510 $ldapconnection = $this->ldap_connect();
1512 if (empty($extusername) or empty($groupdns)) {
1513 return false;
1516 if ($this->config->memberattribute_isdn) {
1517 $memberuser = $this->ldap_find_userdn($ldapconnection, $extusername);
1518 } else {
1519 $memberuser = $extusername;
1522 if (empty($memberuser)) {
1523 return false;
1526 $groups = explode(";",$groupdns);
1528 $result = false;
1529 foreach ($groups as $group) {
1530 $group = trim($group);
1531 if (empty($group)) {
1532 continue;
1535 // check cheaply if the user's DN sits in a subtree
1536 // of the "group" DN provided. Granted, this isn't
1537 // a proper LDAP group, but it's a popular usage.
1538 if (strpos(strrev(strtolower($memberuser)), strrev(strtolower($group)))===0) {
1539 $result = true;
1540 break;
1543 //echo "Checking group $group for member $username\n";
1544 $search = ldap_read($ldapconnection, $group, '('.$this->config->memberattribute.'='.$this->filter_addslashes($memberuser).')', array($this->config->memberattribute));
1545 if (!empty($search) and ldap_count_entries($ldapconnection, $search)) {
1546 $info = $this->ldap_get_entries($ldapconnection, $search);
1548 if (count($info) > 0 ) {
1549 // user is member of group
1550 $result = true;
1551 break;
1556 return $result;
1561 * connects to ldap server
1563 * Tries connect to specified ldap servers.
1564 * Returns connection result or error.
1566 * @return connection result
1568 function ldap_connect($binddn='',$bindpwd='') {
1569 // Cache ldap connections (they are expensive to set up
1570 // and can drain the TCP/IP ressources on the server if we
1571 // are syncing a lot of users (as we try to open a new connection
1572 // to get the user details). This is the least invasive way
1573 // to reuse existing connections without greater code surgery.
1574 if(!empty($this->ldapconnection)) {
1575 $this->ldapconns++;
1576 return $this->ldapconnection;
1579 //Select bind password, With empty values use
1580 //ldap_bind_* variables or anonymous bind if ldap_bind_* are empty
1581 if ($binddn == '' and $bindpwd == '') {
1582 if (!empty($this->config->bind_dn)) {
1583 $binddn = $this->config->bind_dn;
1585 if (!empty($this->config->bind_pw)) {
1586 $bindpwd = $this->config->bind_pw;
1590 $urls = explode(";",$this->config->host_url);
1592 foreach ($urls as $server) {
1593 $server = trim($server);
1594 if (empty($server)) {
1595 continue;
1598 $connresult = ldap_connect($server);
1599 //ldap_connect returns ALWAYS true
1601 if (!empty($this->config->version)) {
1602 ldap_set_option($connresult, LDAP_OPT_PROTOCOL_VERSION, $this->config->version);
1605 // Fix MDL-10921
1606 if ($this->config->user_type == 'ad') {
1607 ldap_set_option($connresult, LDAP_OPT_REFERRALS, 0);
1610 if (!empty($binddn)) {
1611 //bind with search-user
1612 //$debuginfo .= 'Using bind user'.$binddn.'and password:'.$bindpwd;
1613 $bindresult=ldap_bind($connresult, $binddn,$bindpwd);
1615 else {
1616 //bind anonymously
1617 $bindresult=@ldap_bind($connresult);
1620 if (!empty($this->config->opt_deref)) {
1621 ldap_set_option($connresult, LDAP_OPT_DEREF, $this->config->opt_deref);
1624 if ($bindresult) {
1625 // Set the connection counter so we can call PHP's ldap_close()
1626 // when we call $this->ldap_close() for the last 'open' connection.
1627 $this->ldapconns = 1;
1628 $this->ldapconnection = $connresult;
1629 return $connresult;
1632 $debuginfo .= "<br/>Server: '$server' <br/> Connection: '$connresult'<br/> Bind result: '$bindresult'</br>";
1635 //If any of servers are alive we have already returned connection
1636 print_error('auth_ldap_noconnect_all','auth','', $debuginfo);
1637 return false;
1641 * disconnects from a ldap server
1644 function ldap_close() {
1645 $this->ldapconns--;
1646 if($this->ldapconns == 0) {
1647 @ldap_close($this->ldapconnection);
1648 unset($this->ldapconnection);
1653 * retuns dn of username
1655 * Search specified contexts for username and return user dn
1656 * like: cn=username,ou=suborg,o=org
1658 * @param mixed $ldapconnection $ldapconnection result
1659 * @param mixed $username username (external encoding no slashes)
1663 function ldap_find_userdn ($ldapconnection, $extusername) {
1665 //default return value
1666 $ldap_user_dn = FALSE;
1668 //get all contexts and look for first matching user
1669 $ldap_contexts = explode(";",$this->config->contexts);
1671 if (!empty($this->config->create_context)) {
1672 array_push($ldap_contexts, $this->config->create_context);
1675 foreach ($ldap_contexts as $context) {
1677 $context = trim($context);
1678 if (empty($context)) {
1679 continue;
1682 if ($this->config->search_sub) {
1683 //use ldap_search to find first user from subtree
1684 $ldap_result = ldap_search($ldapconnection, $context, "(".$this->config->user_attribute."=".$this->filter_addslashes($extusername).")",array($this->config->user_attribute));
1687 else {
1688 //search only in this context
1689 $ldap_result = ldap_list($ldapconnection, $context, "(".$this->config->user_attribute."=".$this->filter_addslashes($extusername).")",array($this->config->user_attribute));
1692 $entry = ldap_first_entry($ldapconnection,$ldap_result);
1694 if ($entry) {
1695 $ldap_user_dn = ldap_get_dn($ldapconnection, $entry);
1696 break ;
1700 return $ldap_user_dn;
1704 * retuns user attribute mappings between moodle and ldap
1706 * @return array
1709 function ldap_attributes () {
1710 $moodleattributes = array();
1711 foreach ($this->userfields as $field) {
1712 if (!empty($this->config->{"field_map_$field"})) {
1713 $moodleattributes[$field] = $this->config->{"field_map_$field"};
1714 if (preg_match('/,/',$moodleattributes[$field])) {
1715 $moodleattributes[$field] = explode(',', $moodleattributes[$field]); // split ?
1719 $moodleattributes['username'] = $this->config->user_attribute;
1720 return $moodleattributes;
1724 * return all usernames from ldap
1726 * @return array
1729 function ldap_get_userlist($filter="*") {
1730 /// returns all users from ldap servers
1731 $fresult = array();
1733 $ldapconnection = $this->ldap_connect();
1735 if ($filter=="*") {
1736 $filter = '(&('.$this->config->user_attribute.'=*)'.$this->config->objectclass.')';
1739 $contexts = explode(";",$this->config->contexts);
1741 if (!empty($this->config->create_context)) {
1742 array_push($contexts, $this->config->create_context);
1745 foreach ($contexts as $context) {
1747 $context = trim($context);
1748 if (empty($context)) {
1749 continue;
1752 if ($this->config->search_sub) {
1753 //use ldap_search to find first user from subtree
1754 $ldap_result = ldap_search($ldapconnection, $context,$filter,array($this->config->user_attribute));
1756 else {
1757 //search only in this context
1758 $ldap_result = ldap_list($ldapconnection, $context,
1759 $filter,
1760 array($this->config->user_attribute));
1763 $users = $this->ldap_get_entries($ldapconnection, $ldap_result);
1765 //add found users to list
1766 for ($i=0;$i<count($users);$i++) {
1767 array_push($fresult, ($users[$i][$this->config->user_attribute][0]) );
1771 return $fresult;
1775 * return entries from ldap
1777 * Returns values like ldap_get_entries but is
1778 * binary compatible and return all attributes as array
1780 * @return array ldap-entries
1783 function ldap_get_entries($conn, $searchresult) {
1784 //Returns values like ldap_get_entries but is
1785 //binary compatible
1786 $i=0;
1787 $fresult=array();
1788 $entry = ldap_first_entry($conn, $searchresult);
1789 do {
1790 $attributes = @ldap_get_attributes($conn, $entry);
1791 for ($j=0; $j<$attributes['count']; $j++) {
1792 $values = ldap_get_values_len($conn, $entry,$attributes[$j]);
1793 if (is_array($values)) {
1794 $fresult[$i][$attributes[$j]] = $values;
1796 else {
1797 $fresult[$i][$attributes[$j]] = array($values);
1800 $i++;
1802 while ($entry = @ldap_next_entry($conn, $entry));
1803 //were done
1804 return ($fresult);
1807 function prevent_local_passwords() {
1808 return !empty($this->config->preventpassindb);
1812 * Returns true if this authentication plugin is 'internal'.
1814 * @return bool
1816 function is_internal() {
1817 return false;
1821 * Returns true if this authentication plugin can change the user's
1822 * password.
1824 * @return bool
1826 function can_change_password() {
1827 return !empty($this->config->stdchangepassword) or !empty($this->config->changepasswordurl);
1831 * Returns the URL for changing the user's pw, or empty if the default can
1832 * be used.
1834 * @return string url
1836 function change_password_url() {
1837 if (empty($this->config->stdchangepassword)) {
1838 return $this->config->changepasswordurl;
1839 } else {
1840 return '';
1845 * Will get called before the login page is shown, if NTLM SSO
1846 * is enabled, and the user is in the right network, we'll redirect
1847 * to the magic NTLM page for SSO...
1850 function loginpage_hook() {
1851 global $CFG, $SESSION;
1853 // HTTPS is potentially required
1854 httpsrequired();
1856 if (($_SERVER['REQUEST_METHOD'] === 'GET' // Only on initial GET of loginpage
1857 || ($_SERVER['REQUEST_METHOD'] === 'POST'
1858 && (get_referer() != strip_querystring(qualified_me()))))
1859 // Or when POSTed from another place
1860 // See MDL-14071
1861 && !empty($this->config->ntlmsso_enabled) // SSO enabled
1862 && !empty($this->config->ntlmsso_subnet) // have a subnet to test for
1863 && empty($_GET['authldap_skipntlmsso']) // haven't failed it yet
1864 && (isguestuser() || !isloggedin()) // guestuser or not-logged-in users
1865 && address_in_subnet(getremoteaddr(), $this->config->ntlmsso_subnet)) {
1867 // First, let's remember where we were trying to get to before we got here
1868 if (empty($SESSION->wantsurl)) {
1869 $SESSION->wantsurl = (array_key_exists('HTTP_REFERER', $_SERVER) &&
1870 $_SERVER['HTTP_REFERER'] != $CFG->wwwroot &&
1871 $_SERVER['HTTP_REFERER'] != $CFG->wwwroot.'/' &&
1872 $_SERVER['HTTP_REFERER'] != $CFG->httpswwwroot.'/login/' &&
1873 $_SERVER['HTTP_REFERER'] != $CFG->httpswwwroot.'/login/index.php')
1874 ? $_SERVER['HTTP_REFERER'] : NULL;
1877 // Now start the whole NTLM machinery.
1878 if(!empty($this->config->ntlmsso_ie_fastpath)) {
1879 // Shortcut for IE browsers: skip the attempt page at all
1880 if(check_browser_version('MSIE')) {
1881 $sesskey = sesskey();
1882 redirect($CFG->wwwroot.'/auth/ldap/ntlmsso_magic.php?sesskey='.$sesskey);
1883 } else {
1884 redirect($CFG->httpswwwroot.'/login/index.php?authldap_skipntlmsso=1');
1886 } else {
1887 redirect($CFG->wwwroot.'/auth/ldap/ntlmsso_attempt.php');
1891 // No NTLM SSO, Use the normal login page instead.
1893 // If $SESSION->wantsurl is empty and we have a 'Referer:' header, the login
1894 // page insists on redirecting us to that page after user validation. If
1895 // we clicked on the redirect link at the ntlmsso_finish.php page instead
1896 // of waiting for the redirection to happen, then we have a 'Referer:' header
1897 // we don't want to use at all. As we can't get rid of it, just point
1898 // $SESSION->wantsurl to $CFG->wwwroot (after all, we came from there).
1899 if (empty($SESSION->wantsurl)
1900 && (get_referer() == $CFG->httpswwwroot.'/auth/ldap/ntlmsso_finish.php')) {
1902 $SESSION->wantsurl = $CFG->wwwroot;
1907 * To be called from a page running under NTLM's
1908 * "Integrated Windows Authentication".
1910 * If successful, it will set a special "cookie" (not an HTTP cookie!)
1911 * in cache_flags under the "auth/ldap/ntlmsess" "plugin" and return true.
1912 * The "cookie" will be picked up by ntlmsso_finish() to complete the
1913 * process.
1915 * On failure it will return false for the caller to display an appropriate
1916 * error message (probably saying that Integrated Windows Auth isn't enabled!)
1918 * NOTE that this code will execute under the OS user credentials,
1919 * so we MUST avoid dealing with files -- such as session files.
1920 * (The caller should set $nomoodlecookie before including config.php)
1923 function ntlmsso_magic($sesskey) {
1924 if (isset($_SERVER['REMOTE_USER']) && !empty($_SERVER['REMOTE_USER'])) {
1926 // HTTP __headers__ seem to be sent in ISO-8859-1 encoding
1927 // (according to my reading of RFC-1945, RFC-2616 and RFC-2617 and
1928 // my local tests), so we need to convert the REMOTE_USER value
1929 // (i.e., what we got from the HTTP WWW-Authenticate header) into UTF-8
1930 $textlib = textlib_get_instance();
1931 $username = $textlib->convert($_SERVER['REMOTE_USER'], 'iso-8859-1', 'utf-8');
1933 $username = substr(strrchr($username, '\\'), 1); //strip domain info
1934 $username = moodle_strtolower($username); //compatibility hack
1935 set_cache_flag('auth/ldap/ntlmsess', $sesskey, $username, AUTH_NTLMTIMEOUT);
1936 return true;
1938 return false;
1942 * Find the session set by ntlmsso_magic(), validate it and
1943 * call authenticate_user_login() to authenticate the user through
1944 * the auth machinery.
1946 * It is complemented by a similar check in user_login().
1948 * If it succeeds, it never returns.
1951 function ntlmsso_finish() {
1952 global $CFG, $USER, $SESSION;
1954 $key = sesskey();
1955 $cf = get_cache_flags('auth/ldap/ntlmsess');
1956 if (!isset($cf[$key]) || $cf[$key] === '') {
1957 return false;
1959 $username = $cf[$key];
1960 // Here we want to trigger the whole authentication machinery
1961 // to make sure no step is bypassed...
1962 $user = authenticate_user_login($username, $key);
1963 if ($user) {
1964 add_to_log(SITEID, 'user', 'login', "view.php?id=$USER->id&course=".SITEID,
1965 $user->id, 0, $user->id);
1966 $USER = complete_user_login($user);
1968 // Cleanup the key to prevent reuse...
1969 // and to allow re-logins with normal credentials
1970 unset_cache_flag('auth/ldap/ntlmsess', $key);
1972 /// Redirection
1973 if (user_not_fully_set_up($USER)) {
1974 $urltogo = $CFG->wwwroot.'/user/edit.php';
1975 // We don't delete $SESSION->wantsurl yet, so we get there later
1976 } else if (isset($SESSION->wantsurl) and (strpos($SESSION->wantsurl, $CFG->wwwroot) === 0)) {
1977 $urltogo = $SESSION->wantsurl; /// Because it's an address in this site
1978 unset($SESSION->wantsurl);
1979 } else {
1980 // no wantsurl stored or external - go to homepage
1981 $urltogo = $CFG->wwwroot.'/';
1982 unset($SESSION->wantsurl);
1984 redirect($urltogo);
1986 // Should never reach here.
1987 return false;
1991 * Sync roles for this user
1993 * @param $user object user object (without system magic quotes)
1995 function sync_roles($user) {
1996 $iscreator = $this->iscreator($user->username);
1997 if ($iscreator === null) {
1998 return; //nothing to sync - creators not configured
2001 if ($roles = get_roles_with_capability('moodle/legacy:coursecreator', CAP_ALLOW)) {
2002 $creatorrole = array_shift($roles); // We can only use one, let's use the first one
2003 $systemcontext = get_context_instance(CONTEXT_SYSTEM);
2005 if ($iscreator) { // Following calls will not create duplicates
2006 role_assign($creatorrole->id, $user->id, 0, $systemcontext->id, 0, 0, 0, 'ldap');
2007 } else {
2008 //unassign only if previously assigned by this plugin!
2009 role_unassign($creatorrole->id, $user->id, 0, $systemcontext->id, 'ldap');
2015 * Prints a form for configuring this authentication plugin.
2017 * This function is called from admin/auth.php, and outputs a full page with
2018 * a form for configuring this plugin.
2020 * @param array $page An object containing all the data for this page.
2022 function config_form($config, $err, $user_fields) {
2023 include 'config.html';
2027 * Processes and stores configuration data for this authentication plugin.
2029 function process_config($config) {
2030 // set to defaults if undefined
2031 if (!isset($config->host_url))
2032 { $config->host_url = ''; }
2033 if (empty($config->ldapencoding))
2034 { $config->ldapencoding = 'utf-8'; }
2035 if (!isset($config->contexts))
2036 { $config->contexts = ''; }
2037 if (!isset($config->user_type))
2038 { $config->user_type = 'default'; }
2039 if (!isset($config->user_attribute))
2040 { $config->user_attribute = ''; }
2041 if (!isset($config->search_sub))
2042 { $config->search_sub = ''; }
2043 if (!isset($config->opt_deref))
2044 { $config->opt_deref = ''; }
2045 if (!isset($config->preventpassindb))
2046 { $config->preventpassindb = 0; }
2047 if (!isset($config->bind_dn))
2048 {$config->bind_dn = ''; }
2049 if (!isset($config->bind_pw))
2050 {$config->bind_pw = ''; }
2051 if (!isset($config->version))
2052 {$config->version = '2'; }
2053 if (!isset($config->objectclass))
2054 {$config->objectclass = ''; }
2055 if (!isset($config->memberattribute))
2056 {$config->memberattribute = ''; }
2057 if (!isset($config->memberattribute_isdn))
2058 {$config->memberattribute_isdn = ''; }
2059 if (!isset($config->creators))
2060 {$config->creators = ''; }
2061 if (!isset($config->create_context))
2062 {$config->create_context = ''; }
2063 if (!isset($config->expiration))
2064 {$config->expiration = ''; }
2065 if (!isset($config->expiration_warning))
2066 {$config->expiration_warning = '10'; }
2067 if (!isset($config->expireattr))
2068 {$config->expireattr = ''; }
2069 if (!isset($config->gracelogins))
2070 {$config->gracelogins = ''; }
2071 if (!isset($config->graceattr))
2072 {$config->graceattr = ''; }
2073 if (!isset($config->auth_user_create))
2074 {$config->auth_user_create = ''; }
2075 if (!isset($config->forcechangepassword))
2076 {$config->forcechangepassword = 0; }
2077 if (!isset($config->stdchangepassword))
2078 {$config->stdchangepassword = 0; }
2079 if (!isset($config->passtype))
2080 {$config->passtype = 'plaintext'; }
2081 if (!isset($config->changepasswordurl))
2082 {$config->changepasswordurl = ''; }
2083 if (!isset($config->removeuser))
2084 {$config->removeuser = 0; }
2085 if (!isset($config->ntlmsso_enabled))
2086 {$config->ntlmsso_enabled = 0; }
2087 if (!isset($config->ntlmsso_subnet))
2088 {$config->ntlmsso_subnet = ''; }
2089 if (!isset($config->ntlmsso_ie_fastpath))
2090 {$config->ntlmsso_ie_fastpath = 0; }
2092 // save settings
2093 set_config('host_url', $config->host_url, 'auth/ldap');
2094 set_config('ldapencoding', $config->ldapencoding, 'auth/ldap');
2095 set_config('host_url', $config->host_url, 'auth/ldap');
2096 set_config('contexts', $config->contexts, 'auth/ldap');
2097 set_config('user_type', $config->user_type, 'auth/ldap');
2098 set_config('user_attribute', $config->user_attribute, 'auth/ldap');
2099 set_config('search_sub', $config->search_sub, 'auth/ldap');
2100 set_config('opt_deref', $config->opt_deref, 'auth/ldap');
2101 set_config('preventpassindb', $config->preventpassindb, 'auth/ldap');
2102 set_config('bind_dn', $config->bind_dn, 'auth/ldap');
2103 set_config('bind_pw', $config->bind_pw, 'auth/ldap');
2104 set_config('version', $config->version, 'auth/ldap');
2105 set_config('objectclass', trim($config->objectclass), 'auth/ldap');
2106 set_config('memberattribute', $config->memberattribute, 'auth/ldap');
2107 set_config('memberattribute_isdn', $config->memberattribute_isdn, 'auth/ldap');
2108 set_config('creators', $config->creators, 'auth/ldap');
2109 set_config('create_context', $config->create_context, 'auth/ldap');
2110 set_config('expiration', $config->expiration, 'auth/ldap');
2111 set_config('expiration_warning', $config->expiration_warning, 'auth/ldap');
2112 set_config('expireattr', $config->expireattr, 'auth/ldap');
2113 set_config('gracelogins', $config->gracelogins, 'auth/ldap');
2114 set_config('graceattr', $config->graceattr, 'auth/ldap');
2115 set_config('auth_user_create', $config->auth_user_create, 'auth/ldap');
2116 set_config('forcechangepassword', $config->forcechangepassword, 'auth/ldap');
2117 set_config('stdchangepassword', $config->stdchangepassword, 'auth/ldap');
2118 set_config('passtype', $config->passtype, 'auth/ldap');
2119 set_config('changepasswordurl', $config->changepasswordurl, 'auth/ldap');
2120 set_config('removeuser', $config->removeuser, 'auth/ldap');
2121 set_config('ntlmsso_enabled', (int)$config->ntlmsso_enabled, 'auth/ldap');
2122 set_config('ntlmsso_subnet', $config->ntlmsso_subnet, 'auth/ldap');
2123 set_config('ntlmsso_ie_fastpath', (int)$config->ntlmsso_ie_fastpath, 'auth/ldap');
2125 return true;
2129 * Quote control characters in texts used in ldap filters - see RFC 4515/2254
2131 * @param string
2133 function filter_addslashes($text) {
2134 $text = str_replace('\\', '\\5c', $text);
2135 $text = str_replace(array('*', '(', ')', "\0"),
2136 array('\\2a', '\\28', '\\29', '\\00'), $text);
2137 return $text;
2141 * The order of the special characters in these arrays _IS IMPORTANT_.
2142 * Make sure '\\5C' (and '\\') are the first elements of the arrays.
2143 * Otherwise we'll double replace '\' with '\5C' which is Bad(tm)
2145 var $LDAP_DN_QUOTED_SPECIAL_CHARS = array('\\5c','\\20','\\22','\\23','\\2b','\\2c','\\3b','\\3c','\\3d','\\3e','\\00');
2146 var $LDAP_DN_SPECIAL_CHARS = array('\\', ' ', '"', '#', '+', ',', ';', '<', '=', '>', "\0");
2149 * Quote control characters in distinguished names used in ldap - See RFC 4514/2253
2151 * @param string
2152 * @return string
2154 function ldap_addslashes($text) {
2155 $text = str_replace ($this->LDAP_DN_SPECIAL_CHARS,
2156 $this->LDAP_DN_QUOTED_SPECIAL_CHARS,
2157 $text);
2158 return $text;
2162 * Get password expiration time for a given user from Active Directory
2164 * @param string $pwdlastset The time last time we changed the password.
2165 * @param resource $lcapconn The open LDAP connection.
2166 * @param string $user_dn The distinguished name of the user we are checking.
2168 * @return string $unixtime
2170 function ldap_get_ad_pwdexpire($pwdlastset, $ldapconn, $user_dn){
2171 define ('ROOTDSE', '');
2172 // UF_DONT_EXPIRE_PASSWD value taken from MSDN directly
2173 define ('UF_DONT_EXPIRE_PASSWD', 0x00010000);
2175 global $CFG;
2177 if (!function_exists('bcsub')) {
2178 error_log ('You need the BCMath extension to use grace logins with Active Directory');
2179 return 0;
2182 // If UF_DONT_EXPIRE_PASSWD flag is set in user's
2183 // userAccountControl attribute, the password doesn't expire.
2184 $sr = ldap_read($ldapconn, $user_dn, '(objectClass=*)',
2185 array('userAccountControl'));
2186 if (!$sr) {
2187 error_log("ldap: error getting userAccountControl for $user_dn");
2188 // don't expire password, as we are not sure it has to be
2189 // expired or not.
2190 return 0;
2193 $info = $this->ldap_get_entries($ldapconn, $sr);
2194 $useraccountcontrol = $info[0]['userAccountControl'][0];
2195 if ($useraccountcontrol & UF_DONT_EXPIRE_PASSWD) {
2196 // password doesn't expire.
2197 return 0;
2200 // If pwdLastSet is zero, the user must change his/her password now
2201 // (unless UF_DONT_EXPIRE_PASSWD flag is set, but we already
2202 // tested this above)
2203 if ($pwdlastset === '0') {
2204 // password has expired
2205 return -1;
2208 // ----------------------------------------------------------------
2209 // Password expiration time in Active Directory is the composition of
2210 // two values:
2212 // - User's pwdLastSet attribute, that stores the last time
2213 // the password was changed.
2215 // - Domain's maxPwdAge attribute, that sets how long
2216 // passwords last in this domain.
2218 // We already have the first value (passed in as a parameter). We
2219 // need to get the second one. As we don't know the domain DN, we
2220 // have to query rootDSE's defaultNamingContext attribute to get
2221 // it. Then we have to query that DN's maxPwdAge attribute to get
2222 // the real value.
2224 // Once we have both values, we just need to combine them. But MS
2225 // chose to use a different base and unit for time measurements.
2226 // So we need to convert the values to Unix timestamps (see
2227 // details below).
2228 // ----------------------------------------------------------------
2230 $sr = ldap_read($ldapconn, ROOTDSE, '(objectClass=*)',
2231 array('defaultNamingContext'));
2232 if (!$sr) {
2233 error_log("ldap: error querying rootDSE for Active Directory");
2234 return 0;
2237 $info = $this->ldap_get_entries($ldapconn, $sr);
2238 $domaindn = $info[0]['defaultNamingContext'][0];
2240 $sr = ldap_read ($ldapconn, $domaindn, '(objectClass=*)',
2241 array('maxPwdAge'));
2242 $info = $this->ldap_get_entries($ldapconn, $sr);
2243 $maxpwdage = $info[0]['maxPwdAge'][0];
2245 // ----------------------------------------------------------------
2246 // MSDN says that "pwdLastSet contains the number of 100 nanosecond
2247 // intervals since January 1, 1601 (UTC), stored in a 64 bit integer".
2249 // According to Perl's Date::Manip, the number of seconds between
2250 // this date and Unix epoch is 11644473600. So we have to
2251 // substract this value to calculate a Unix time, once we have
2252 // scaled pwdLastSet to seconds. This is the script used to
2253 // calculate the value shown above:
2255 // #!/usr/bin/perl -w
2257 // use Date::Manip;
2259 // $date1 = ParseDate ("160101010000 UTC");
2260 // $date2 = ParseDate ("197001010000 UTC");
2261 // $delta = DateCalc($date1, $date2, \$err);
2262 // $secs = Delta_Format($delta, 0, "%st");
2263 // print "$secs \n";
2265 // MSDN also says that "maxPwdAge is stored as a large integer that
2266 // represents the number of 100 nanosecond intervals from the time
2267 // the password was set before the password expires." We also need
2268 // to scale this to seconds. Bear in mind that this value is stored
2269 // as a _negative_ quantity (at least in my AD domain).
2271 // As a last remark, if the low 32 bits of maxPwdAge are equal to 0,
2272 // the maximum password age in the domain is set to 0, which means
2273 // passwords do not expire (see
2274 // http://msdn2.microsoft.com/en-us/library/ms974598.aspx)
2276 // As the quantities involved are too big for PHP integers, we
2277 // need to use BCMath functions to work with arbitrary precision
2278 // numbers.
2279 // ----------------------------------------------------------------
2282 // If the low order 32 bits are 0, then passwords do not expire in
2283 // the domain. Just do '$maxpwdage mod 2^32' and check the result
2284 // (2^32 = 4294967296)
2285 if (bcmod ($maxpwdage, 4294967296) === '0') {
2286 return 0;
2289 // Add up pwdLastSet and maxPwdAge to get password expiration
2290 // time, in MS time units. Remember maxPwdAge is stored as a
2291 // _negative_ quantity, so we need to substract it in fact.
2292 $pwdexpire = bcsub ($pwdlastset, $maxpwdage);
2294 // Scale the result to convert it to Unix time units and return
2295 // that value.
2296 return bcsub( bcdiv($pwdexpire, '10000000'), '11644473600');