Updated PaintWeb to the latest snapshot.
[moodle/mihaisucan.git] / auth / ldap / auth.php
blobdd05be6dbd7dc07bb1b00fbc902e094a0a1a659f
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)) TYPE=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_dbreviveser', 'auth', array($user->username, $user->id)); echo "\n";
727 } else {
728 echo "\t"; print_string('auth_dbreviveusererror', '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);
856 } else {
857 echo "\t"; print_string('auth_dbinsertusererror', 'auth', $user->username); echo "\n";
860 // add course creators if needed
861 if ($creatorrole !== false and $this->iscreator(stripslashes($user->username))) {
862 role_assign($creatorrole->id, $user->id, 0, $sitecontext->id, 0, 0, 0, 'ldap');
865 commit_sql();
866 unset($add_users); // free mem
867 } else {
868 print "No users to be added\n";
870 $this->ldap_close();
871 return true;
875 * Update a local user record from an external source.
876 * This is a lighter version of the one in moodlelib -- won't do
877 * expensive ops such as enrolment.
879 * If you don't pass $updatekeys, there is a performance hit and
880 * values removed from LDAP won't be removed from moodle.
882 * @param string $username username (with system magic quotes)
884 function update_user_record($username, $updatekeys = false) {
885 global $CFG;
887 //just in case check text case
888 $username = trim(moodle_strtolower($username));
890 // get the current user record
891 $user = get_record('user', 'username', $username, 'mnethostid', $CFG->mnet_localhost_id);
892 if (empty($user)) { // trouble
893 error_log("Cannot update non-existent user: ".stripslashes($username));
894 print_error('auth_dbusernotexist','auth','',$username);
895 die;
898 // Protect the userid from being overwritten
899 $userid = $user->id;
901 if ($newinfo = $this->get_userinfo($username)) {
902 $newinfo = truncate_userinfo($newinfo);
904 if (empty($updatekeys)) { // all keys? this does not support removing values
905 $updatekeys = array_keys($newinfo);
908 foreach ($updatekeys as $key) {
909 if (isset($newinfo[$key])) {
910 $value = $newinfo[$key];
911 } else {
912 $value = '';
915 if (!empty($this->config->{'field_updatelocal_' . $key})) {
916 if ($user->{$key} != $value) { // only update if it's changed
917 set_field('user', $key, addslashes($value), 'id', $userid);
921 } else {
922 return false;
924 return get_record_select('user', "id = $userid AND deleted = 0");
928 * Bulk insert in SQL's temp table
929 * @param array $users is an array of usernames
931 function ldap_bulk_insert($users, $temptable) {
933 // bulk insert -- superfast with $bulk_insert_records
934 $sql = 'INSERT INTO ' . $temptable . ' (username) VALUES ';
935 // make those values safe
936 $users = addslashes_recursive($users);
937 // join and quote the whole lot
938 $sql = $sql . "('" . implode("'),('", $users) . "')";
939 print "\t+ " . count($users) . " users\n";
940 execute_sql($sql, false);
945 * Activates (enables) user in external db so user can login to external db
947 * @param mixed $username username (with system magic quotes)
948 * @return boolen result
950 function user_activate($username) {
951 $textlib = textlib_get_instance();
952 $extusername = $textlib->convert(stripslashes($username), 'utf-8', $this->config->ldapencoding);
954 $ldapconnection = $this->ldap_connect();
956 $userdn = $this->ldap_find_userdn($ldapconnection, $extusername);
957 switch ($this->config->user_type) {
958 case 'edir':
959 $newinfo['loginDisabled']="FALSE";
960 break;
961 case 'ad':
962 // We need to unset the ACCOUNTDISABLE bit in the
963 // userAccountControl attribute ( see
964 // http://support.microsoft.com/kb/305144 )
965 $sr = ldap_read($ldapconnection, $userdn, '(objectClass=*)',
966 array('userAccountControl'));
967 $info = ldap_get_entries($ldapconnection, $sr);
968 $newinfo['userAccountControl'] = $info[0]['userAccountControl'][0]
969 & (~AUTH_AD_ACCOUNTDISABLE);
970 break;
971 default:
972 error ('auth: ldap user_activate() does not support selected usertype:"'.$this->config->user_type.'" (..yet)');
974 $result = ldap_modify($ldapconnection, $userdn, $newinfo);
975 $this->ldap_close();
976 return $result;
980 * Disables user in external db so user can't login to external db
982 * @param mixed $username username
983 * @return boolean result
985 /* function user_disable($username) {
986 $textlib = textlib_get_instance();
987 $extusername = $textlib->convert(stripslashes($username), 'utf-8', $this->config->ldapencoding);
989 $ldapconnection = $this->ldap_connect();
991 $userdn = $this->ldap_find_userdn($ldapconnection, $extusername);
992 switch ($this->config->user_type) {
993 case 'edir':
994 $newinfo['loginDisabled']="TRUE";
995 break;
996 case 'ad':
997 // We need to set the ACCOUNTDISABLE bit in the
998 // userAccountControl attribute ( see
999 // http://support.microsoft.com/kb/305144 )
1000 $sr = ldap_read($ldapconnection, $userdn, '(objectClass=*)',
1001 array('userAccountControl'));
1002 $info = auth_ldap_get_entries($ldapconnection, $sr);
1003 $newinfo['userAccountControl'] = $info[0]['userAccountControl'][0]
1004 | AUTH_AD_ACCOUNTDISABLE;
1005 break;
1006 default:
1007 error ('auth: ldap user_disable() does not support selected usertype (..yet)');
1009 $result = ldap_modify($ldapconnection, $userdn, $newinfo);
1010 $this->ldap_close();
1011 return $result;
1015 * Returns true if user should be coursecreator.
1017 * @param mixed $username username (without system magic quotes)
1018 * @return boolean result
1020 function iscreator($username) {
1021 if (empty($this->config->creators) or empty($this->config->memberattribute)) {
1022 return null;
1025 $textlib = textlib_get_instance();
1026 $extusername = $textlib->convert($username, 'utf-8', $this->config->ldapencoding);
1028 return (boolean)$this->ldap_isgroupmember($extusername, $this->config->creators);
1032 * Called when the user record is updated.
1033 * Modifies user in external database. It takes olduser (before changes) and newuser (after changes)
1034 * conpares information saved modified information to external db.
1036 * @param mixed $olduser Userobject before modifications (without system magic quotes)
1037 * @param mixed $newuser Userobject new modified userobject (without system magic quotes)
1038 * @return boolean result
1041 function user_update($olduser, $newuser) {
1043 global $USER;
1045 if (isset($olduser->username) and isset($newuser->username) and $olduser->username != $newuser->username) {
1046 error_log("ERROR:User renaming not allowed in LDAP");
1047 return false;
1050 if (isset($olduser->auth) and $olduser->auth != 'ldap') {
1051 return true; // just change auth and skip update
1054 $attrmap = $this->ldap_attributes();
1056 // Before doing anything else, make sure really need to update anything
1057 // in the external LDAP server.
1058 $update_external = false;
1059 foreach ($attrmap as $key => $ldapkeys) {
1060 if (!empty($this->config->{'field_updateremote_'.$key})) {
1061 $update_external = true;
1062 break;
1065 if (!$update_external) {
1066 return true;
1069 $textlib = textlib_get_instance();
1070 $extoldusername = $textlib->convert($olduser->username, 'utf-8', $this->config->ldapencoding);
1072 $ldapconnection = $this->ldap_connect();
1074 $search_attribs = array();
1076 foreach ($attrmap as $key => $values) {
1077 if (!is_array($values)) {
1078 $values = array($values);
1080 foreach ($values as $value) {
1081 if (!in_array($value, $search_attribs)) {
1082 array_push($search_attribs, $value);
1087 $user_dn = $this->ldap_find_userdn($ldapconnection, $extoldusername);
1089 $user_info_result = ldap_read($ldapconnection, $user_dn,
1090 $this->config->objectclass, $search_attribs);
1092 if ($user_info_result) {
1094 $user_entry = $this->ldap_get_entries($ldapconnection, $user_info_result);
1095 if (empty($user_entry)) {
1096 $error = 'ldap: Could not find user while updating externally. '.
1097 'Details follow: search base: \''.$user_dn.'\'; search filter: \''.
1098 $this->config->objectclass.'\'; search attributes: ';
1099 foreach ($search_attribs as $attrib) {
1100 $error .= $attrib.' ';
1102 error_log($error);
1103 return false; // old user not found!
1104 } else if (count($user_entry) > 1) {
1105 error_log('ldap: Strange! More than one user record found in ldap. Only using the first one.');
1106 return false;
1108 $user_entry = $user_entry[0];
1110 //error_log(var_export($user_entry) . 'fpp' );
1112 foreach ($attrmap as $key => $ldapkeys) {
1113 // only process if the moodle field ($key) has changed and we
1114 // are set to update LDAP with it
1115 if (isset($olduser->$key) and isset($newuser->$key)
1116 and $olduser->$key !== $newuser->$key
1117 and !empty($this->config->{'field_updateremote_'. $key})) {
1118 // for ldap values that could be in more than one
1119 // ldap key, we will do our best to match
1120 // where they came from
1121 $ambiguous = true;
1122 $changed = false;
1123 if (!is_array($ldapkeys)) {
1124 $ldapkeys = array($ldapkeys);
1126 if (count($ldapkeys) < 2) {
1127 $ambiguous = false;
1130 $nuvalue = $textlib->convert($newuser->$key, 'utf-8', $this->config->ldapencoding);
1131 empty($nuvalue) ? $nuvalue = array() : $nuvalue;
1132 $ouvalue = $textlib->convert($olduser->$key, 'utf-8', $this->config->ldapencoding);
1134 foreach ($ldapkeys as $ldapkey) {
1135 $ldapkey = $ldapkey;
1136 $ldapvalue = $user_entry[$ldapkey][0];
1137 if (!$ambiguous) {
1138 // skip update if the values already match
1139 if ($nuvalue !== $ldapvalue) {
1140 //this might fail due to schema validation
1141 if (@ldap_modify($ldapconnection, $user_dn, array($ldapkey => $nuvalue))) {
1142 continue;
1143 } else {
1144 error_log('Error updating LDAP record. Error code: '
1145 . ldap_errno($ldapconnection) . '; Error string : '
1146 . ldap_err2str(ldap_errno($ldapconnection))
1147 . "\nKey ($key) - old moodle value: '$ouvalue' new value: '$nuvalue'");
1148 continue;
1151 } else {
1152 // ambiguous
1153 // value empty before in Moodle (and LDAP) - use 1st ldap candidate field
1154 // no need to guess
1155 if ($ouvalue === '') { // value empty before - use 1st ldap candidate
1156 //this might fail due to schema validation
1157 if (@ldap_modify($ldapconnection, $user_dn, array($ldapkey => $nuvalue))) {
1158 $changed = true;
1159 continue;
1160 } else {
1161 error_log('Error updating LDAP record. Error code: '
1162 . ldap_errno($ldapconnection) . '; Error string : '
1163 . ldap_err2str(ldap_errno($ldapconnection))
1164 . "\nKey ($key) - old moodle value: '$ouvalue' new value: '$nuvalue'");
1165 continue;
1169 // we found which ldap key to update!
1170 if ($ouvalue !== '' and $ouvalue === $ldapvalue ) {
1171 //this might fail due to schema validation
1172 if (@ldap_modify($ldapconnection, $user_dn, array($ldapkey => $nuvalue))) {
1173 $changed = true;
1174 continue;
1175 } else {
1176 error_log('Error updating LDAP record. Error code: '
1177 . ldap_errno($ldapconnection) . '; Error string : '
1178 . ldap_err2str(ldap_errno($ldapconnection))
1179 . "\nKey ($key) - old moodle value: '$ouvalue' new value: '$nuvalue'");
1180 continue;
1186 if ($ambiguous and !$changed) {
1187 error_log("Failed to update LDAP with ambiguous field $key".
1188 " old moodle value: '" . $ouvalue .
1189 "' new value '" . $nuvalue );
1193 } else {
1194 error_log("ERROR:No user found in LDAP");
1195 $this->ldap_close();
1196 return false;
1199 $this->ldap_close();
1201 return true;
1206 * changes userpassword in external db
1208 * called when the user password is updated.
1209 * changes userpassword in external db
1211 * @param object $user User table object (with system magic quotes)
1212 * @param string $newpassword Plaintext password (with system magic quotes)
1213 * @return boolean result
1216 function user_update_password($user, $newpassword) {
1217 /// called when the user password is updated -- it assumes it is called by an admin
1218 /// or that you've otherwise checked the user's credentials
1219 /// IMPORTANT: $newpassword must be cleartext, not crypted/md5'ed
1221 global $USER;
1222 $result = false;
1223 $username = $user->username;
1225 $textlib = textlib_get_instance();
1226 $extusername = $textlib->convert(stripslashes($username), 'utf-8', $this->config->ldapencoding);
1227 $extpassword = $textlib->convert(stripslashes($newpassword), 'utf-8', $this->config->ldapencoding);
1229 switch ($this->config->passtype) {
1230 case 'md5':
1231 $extpassword = '{MD5}' . base64_encode(pack('H*', md5($extpassword)));
1232 break;
1233 case 'sha1':
1234 $extpassword = '{SHA}' . base64_encode(pack('H*', sha1($extpassword)));
1235 break;
1236 case 'plaintext':
1237 default:
1238 break; // plaintext
1241 $ldapconnection = $this->ldap_connect();
1243 $user_dn = $this->ldap_find_userdn($ldapconnection, $extusername);
1245 if (!$user_dn) {
1246 error_log('LDAP Error in user_update_password(). No DN for: ' . stripslashes($user->username));
1247 return false;
1250 switch ($this->config->user_type) {
1251 case 'edir':
1252 //Change password
1253 $result = ldap_modify($ldapconnection, $user_dn, array('userPassword' => $extpassword));
1254 if (!$result) {
1255 error_log('LDAP Error in user_update_password(). Error code: '
1256 . ldap_errno($ldapconnection) . '; Error string : '
1257 . ldap_err2str(ldap_errno($ldapconnection)));
1259 //Update password expiration time, grace logins count
1260 $search_attribs = array($this->config->expireattr, 'passwordExpirationInterval','loginGraceLimit' );
1261 $sr = ldap_read($ldapconnection, $user_dn, '(objectClass=*)', $search_attribs);
1262 if ($sr) {
1263 $info=$this->ldap_get_entries($ldapconnection, $sr);
1264 $newattrs = array();
1265 if (!empty($info[0][$this->config->expireattr][0])) {
1266 //Set expiration time only if passwordExpirationInterval is defined
1267 if (!empty($info[0]['passwordExpirationInterval'][0])) {
1268 $expirationtime = time() + $info[0]['passwordExpirationInterval'][0];
1269 $ldapexpirationtime = $this->ldap_unix2expirationtime($expirationtime);
1270 $newattrs['passwordExpirationTime'] = $ldapexpirationtime;
1273 //set gracelogin count
1274 if (!empty($info[0]['loginGraceLimit'][0])) {
1275 $newattrs['loginGraceRemaining']= $info[0]['loginGraceLimit'][0];
1278 //Store attribute changes to ldap
1279 $result = ldap_modify($ldapconnection, $user_dn, $newattrs);
1280 if (!$result) {
1281 error_log('LDAP Error in user_update_password() when modifying expirationtime and/or gracelogins. Error code: '
1282 . ldap_errno($ldapconnection) . '; Error string : '
1283 . ldap_err2str(ldap_errno($ldapconnection)));
1287 else {
1288 error_log('LDAP Error in user_update_password() when reading password expiration time. Error code: '
1289 . ldap_errno($ldapconnection) . '; Error string : '
1290 . ldap_err2str(ldap_errno($ldapconnection)));
1292 break;
1294 case 'ad':
1295 // Passwords in Active Directory must be encoded as Unicode
1296 // strings (UCS-2 Little Endian format) and surrounded with
1297 // double quotes. See http://support.microsoft.com/?kbid=269190
1298 if (!function_exists('mb_convert_encoding')) {
1299 error_log ('You need the mbstring extension to change passwords in Active Directory');
1300 return false;
1302 $extpassword = mb_convert_encoding('"'.$extpassword.'"', "UCS-2LE", $this->config->ldapencoding);
1303 $result = ldap_modify($ldapconnection, $user_dn, array('unicodePwd' => $extpassword));
1304 if (!$result) {
1305 error_log('LDAP Error in user_update_password(). Error code: '
1306 . ldap_errno($ldapconnection) . '; Error string : '
1307 . ldap_err2str(ldap_errno($ldapconnection)));
1309 break;
1311 default:
1312 $usedconnection = &$ldapconnection;
1313 // send ldap the password in cleartext, it will md5 it itself
1314 $result = ldap_modify($ldapconnection, $user_dn, array('userPassword' => $extpassword));
1315 if (!$result) {
1316 error_log('LDAP Error in user_update_password(). Error code: '
1317 . ldap_errno($ldapconnection) . '; Error string : '
1318 . ldap_err2str(ldap_errno($ldapconnection)));
1323 $this->ldap_close();
1324 return $result;
1327 //PRIVATE FUNCTIONS starts
1328 //private functions are named as ldap_*
1331 * returns predefined usertypes
1333 * @return array of predefined usertypes
1335 function ldap_suppported_usertypes() {
1336 $types = array();
1337 $types['edir']='Novell Edirectory';
1338 $types['rfc2307']='posixAccount (rfc2307)';
1339 $types['rfc2307bis']='posixAccount (rfc2307bis)';
1340 $types['samba']='sambaSamAccount (v.3.0.7)';
1341 $types['ad']='MS ActiveDirectory';
1342 $types['default']=get_string('default');
1343 return $types;
1348 * Initializes needed variables for ldap-module
1350 * Uses names defined in ldap_supported_usertypes.
1351 * $default is first defined as:
1352 * $default['pseudoname'] = array(
1353 * 'typename1' => 'value',
1354 * 'typename2' => 'value'
1355 * ....
1356 * );
1358 * @return array of default values
1360 function ldap_getdefaults() {
1361 $default['objectclass'] = array(
1362 'edir' => 'User',
1363 'rfc2307' => 'posixAccount',
1364 'rfc2307bis' => 'posixAccount',
1365 'samba' => 'sambaSamAccount',
1366 'ad' => 'user',
1367 'default' => '*'
1369 $default['user_attribute'] = array(
1370 'edir' => 'cn',
1371 'rfc2307' => 'uid',
1372 'rfc2307bis' => 'uid',
1373 'samba' => 'uid',
1374 'ad' => 'cn',
1375 'default' => 'cn'
1377 $default['memberattribute'] = array(
1378 'edir' => 'member',
1379 'rfc2307' => 'member',
1380 'rfc2307bis' => 'member',
1381 'samba' => 'member',
1382 'ad' => 'member',
1383 'default' => 'member'
1385 $default['memberattribute_isdn'] = array(
1386 'edir' => '1',
1387 'rfc2307' => '0',
1388 'rfc2307bis' => '1',
1389 'samba' => '0', //is this right?
1390 'ad' => '1',
1391 'default' => '0'
1393 $default['expireattr'] = array (
1394 'edir' => 'passwordExpirationTime',
1395 'rfc2307' => 'shadowExpire',
1396 'rfc2307bis' => 'shadowExpire',
1397 'samba' => '', //No support yet
1398 'ad' => 'pwdLastSet',
1399 'default' => ''
1401 return $default;
1405 * return binaryfields of selected usertype
1408 * @return array
1410 function ldap_getbinaryfields () {
1411 $binaryfields = array (
1412 'edir' => array('guid'),
1413 'rfc2307' => array(),
1414 'rfc2307bis' => array(),
1415 'samba' => array(),
1416 'ad' => array(),
1417 'default' => array()
1419 if (!empty($this->config->user_type)) {
1420 return $binaryfields[$this->config->user_type];
1422 else {
1423 return $binaryfields['default'];
1427 function ldap_isbinary ($field) {
1428 if (empty($field)) {
1429 return false;
1431 return array_search($field, $this->ldap_getbinaryfields());
1435 * take expirationtime and return it as unixseconds
1437 * takes expriration timestamp as readed from ldap
1438 * returns it as unix seconds
1439 * depends on $this->config->user_type variable
1441 * @param mixed time Time stamp readed from ldap as it is.
1442 * @param string $ldapconnection Just needed for Active Directory.
1443 * @param string $user_dn User distinguished name for the user we are checking password expiration (just needed for Active Directory).
1444 * @return timestamp
1446 function ldap_expirationtime2unix ($time, $ldapconnection, $user_dn) {
1447 $result = false;
1448 switch ($this->config->user_type) {
1449 case 'edir':
1450 $yr=substr($time,0,4);
1451 $mo=substr($time,4,2);
1452 $dt=substr($time,6,2);
1453 $hr=substr($time,8,2);
1454 $min=substr($time,10,2);
1455 $sec=substr($time,12,2);
1456 $result = mktime($hr,$min,$sec,$mo,$dt,$yr);
1457 break;
1458 case 'rfc2307':
1459 case 'rfc2307bis':
1460 $result = $time * DAYSECS; //The shadowExpire contains the number of DAYS between 01/01/1970 and the actual expiration date
1461 break;
1462 case 'ad':
1463 $result = $this->ldap_get_ad_pwdexpire($time, $ldapconnection, $user_dn);
1464 break;
1465 default:
1466 print_error('auth_ldap_usertypeundefined', 'auth');
1468 return $result;
1472 * takes unixtime and return it formated for storing in ldap
1474 * @param integer unix time stamp
1476 function ldap_unix2expirationtime($time) {
1477 $result = false;
1478 switch ($this->config->user_type) {
1479 case 'edir':
1480 $result=date('YmdHis', $time).'Z';
1481 break;
1482 case 'rfc2307':
1483 case 'rfc2307bis':
1484 $result = $time ; //Already in correct format
1485 break;
1486 default:
1487 print_error('auth_ldap_usertypeundefined2', 'auth');
1489 return $result;
1494 * checks if user belong to specific group(s)
1495 * or is in a subtree.
1497 * Returns true if user belongs group in grupdns string OR
1498 * if the DN of the user is in a subtree pf the DN provided
1499 * as "group"
1501 * @param mixed $username username
1502 * @param mixed $groupdns string of group dn separated by ;
1505 function ldap_isgroupmember($extusername='', $groupdns='') {
1506 // Takes username and groupdn(s) , separated by ;
1507 // Returns true if user is member of any given groups
1509 $ldapconnection = $this->ldap_connect();
1511 if (empty($extusername) or empty($groupdns)) {
1512 return false;
1515 if ($this->config->memberattribute_isdn) {
1516 $memberuser = $this->ldap_find_userdn($ldapconnection, $extusername);
1517 } else {
1518 $memberuser = $extusername;
1521 if (empty($memberuser)) {
1522 return false;
1525 $groups = explode(";",$groupdns);
1527 $result = false;
1528 foreach ($groups as $group) {
1529 $group = trim($group);
1530 if (empty($group)) {
1531 continue;
1534 // check cheaply if the user's DN sits in a subtree
1535 // of the "group" DN provided. Granted, this isn't
1536 // a proper LDAP group, but it's a popular usage.
1537 if (strpos(strrev($memberuser), strrev($group))===0) {
1538 $result = true;
1539 break;
1542 //echo "Checking group $group for member $username\n";
1543 $search = ldap_read($ldapconnection, $group, '('.$this->config->memberattribute.'='.$this->filter_addslashes($memberuser).')', array($this->config->memberattribute));
1544 if (!empty($search) and ldap_count_entries($ldapconnection, $search)) {
1545 $info = $this->ldap_get_entries($ldapconnection, $search);
1547 if (count($info) > 0 ) {
1548 // user is member of group
1549 $result = true;
1550 break;
1555 return $result;
1560 * connects to ldap server
1562 * Tries connect to specified ldap servers.
1563 * Returns connection result or error.
1565 * @return connection result
1567 function ldap_connect($binddn='',$bindpwd='') {
1568 // Cache ldap connections (they are expensive to set up
1569 // and can drain the TCP/IP ressources on the server if we
1570 // are syncing a lot of users (as we try to open a new connection
1571 // to get the user details). This is the least invasive way
1572 // to reuse existing connections without greater code surgery.
1573 if(!empty($this->ldapconnection)) {
1574 $this->ldapconns++;
1575 return $this->ldapconnection;
1578 //Select bind password, With empty values use
1579 //ldap_bind_* variables or anonymous bind if ldap_bind_* are empty
1580 if ($binddn == '' and $bindpwd == '') {
1581 if (!empty($this->config->bind_dn)) {
1582 $binddn = $this->config->bind_dn;
1584 if (!empty($this->config->bind_pw)) {
1585 $bindpwd = $this->config->bind_pw;
1589 $urls = explode(";",$this->config->host_url);
1591 foreach ($urls as $server) {
1592 $server = trim($server);
1593 if (empty($server)) {
1594 continue;
1597 $connresult = ldap_connect($server);
1598 //ldap_connect returns ALWAYS true
1600 if (!empty($this->config->version)) {
1601 ldap_set_option($connresult, LDAP_OPT_PROTOCOL_VERSION, $this->config->version);
1604 // Fix MDL-10921
1605 if ($this->config->user_type == 'ad') {
1606 ldap_set_option($connresult, LDAP_OPT_REFERRALS, 0);
1609 if (!empty($binddn)) {
1610 //bind with search-user
1611 //$debuginfo .= 'Using bind user'.$binddn.'and password:'.$bindpwd;
1612 $bindresult=ldap_bind($connresult, $binddn,$bindpwd);
1614 else {
1615 //bind anonymously
1616 $bindresult=@ldap_bind($connresult);
1619 if (!empty($this->config->opt_deref)) {
1620 ldap_set_option($connresult, LDAP_OPT_DEREF, $this->config->opt_deref);
1623 if ($bindresult) {
1624 // Set the connection counter so we can call PHP's ldap_close()
1625 // when we call $this->ldap_close() for the last 'open' connection.
1626 $this->ldapconns = 1;
1627 $this->ldapconnection = $connresult;
1628 return $connresult;
1631 $debuginfo .= "<br/>Server: '$server' <br/> Connection: '$connresult'<br/> Bind result: '$bindresult'</br>";
1634 //If any of servers are alive we have already returned connection
1635 print_error('auth_ldap_noconnect_all','auth','', $debuginfo);
1636 return false;
1640 * disconnects from a ldap server
1643 function ldap_close() {
1644 $this->ldapconns--;
1645 if($this->ldapconns == 0) {
1646 @ldap_close($this->ldapconnection);
1647 unset($this->ldapconnection);
1652 * retuns dn of username
1654 * Search specified contexts for username and return user dn
1655 * like: cn=username,ou=suborg,o=org
1657 * @param mixed $ldapconnection $ldapconnection result
1658 * @param mixed $username username (external encoding no slashes)
1662 function ldap_find_userdn ($ldapconnection, $extusername) {
1664 //default return value
1665 $ldap_user_dn = FALSE;
1667 //get all contexts and look for first matching user
1668 $ldap_contexts = explode(";",$this->config->contexts);
1670 if (!empty($this->config->create_context)) {
1671 array_push($ldap_contexts, $this->config->create_context);
1674 foreach ($ldap_contexts as $context) {
1676 $context = trim($context);
1677 if (empty($context)) {
1678 continue;
1681 if ($this->config->search_sub) {
1682 //use ldap_search to find first user from subtree
1683 $ldap_result = ldap_search($ldapconnection, $context, "(".$this->config->user_attribute."=".$this->filter_addslashes($extusername).")",array($this->config->user_attribute));
1686 else {
1687 //search only in this context
1688 $ldap_result = ldap_list($ldapconnection, $context, "(".$this->config->user_attribute."=".$this->filter_addslashes($extusername).")",array($this->config->user_attribute));
1691 $entry = ldap_first_entry($ldapconnection,$ldap_result);
1693 if ($entry) {
1694 $ldap_user_dn = ldap_get_dn($ldapconnection, $entry);
1695 break ;
1699 return $ldap_user_dn;
1703 * retuns user attribute mappings between moodle and ldap
1705 * @return array
1708 function ldap_attributes () {
1709 $moodleattributes = array();
1710 foreach ($this->userfields as $field) {
1711 if (!empty($this->config->{"field_map_$field"})) {
1712 $moodleattributes[$field] = $this->config->{"field_map_$field"};
1713 if (preg_match('/,/',$moodleattributes[$field])) {
1714 $moodleattributes[$field] = explode(',', $moodleattributes[$field]); // split ?
1718 $moodleattributes['username'] = $this->config->user_attribute;
1719 return $moodleattributes;
1723 * return all usernames from ldap
1725 * @return array
1728 function ldap_get_userlist($filter="*") {
1729 /// returns all users from ldap servers
1730 $fresult = array();
1732 $ldapconnection = $this->ldap_connect();
1734 if ($filter=="*") {
1735 $filter = '(&('.$this->config->user_attribute.'=*)'.$this->config->objectclass.')';
1738 $contexts = explode(";",$this->config->contexts);
1740 if (!empty($this->config->create_context)) {
1741 array_push($contexts, $this->config->create_context);
1744 foreach ($contexts as $context) {
1746 $context = trim($context);
1747 if (empty($context)) {
1748 continue;
1751 if ($this->config->search_sub) {
1752 //use ldap_search to find first user from subtree
1753 $ldap_result = ldap_search($ldapconnection, $context,$filter,array($this->config->user_attribute));
1755 else {
1756 //search only in this context
1757 $ldap_result = ldap_list($ldapconnection, $context,
1758 $filter,
1759 array($this->config->user_attribute));
1762 $users = $this->ldap_get_entries($ldapconnection, $ldap_result);
1764 //add found users to list
1765 for ($i=0;$i<count($users);$i++) {
1766 array_push($fresult, ($users[$i][$this->config->user_attribute][0]) );
1770 return $fresult;
1774 * return entries from ldap
1776 * Returns values like ldap_get_entries but is
1777 * binary compatible and return all attributes as array
1779 * @return array ldap-entries
1782 function ldap_get_entries($conn, $searchresult) {
1783 //Returns values like ldap_get_entries but is
1784 //binary compatible
1785 $i=0;
1786 $fresult=array();
1787 $entry = ldap_first_entry($conn, $searchresult);
1788 do {
1789 $attributes = @ldap_get_attributes($conn, $entry);
1790 for ($j=0; $j<$attributes['count']; $j++) {
1791 $values = ldap_get_values_len($conn, $entry,$attributes[$j]);
1792 if (is_array($values)) {
1793 $fresult[$i][$attributes[$j]] = $values;
1795 else {
1796 $fresult[$i][$attributes[$j]] = array($values);
1799 $i++;
1801 while ($entry = @ldap_next_entry($conn, $entry));
1802 //were done
1803 return ($fresult);
1807 * Returns true if this authentication plugin is 'internal'.
1809 * @return bool
1811 function is_internal() {
1812 return false;
1816 * Returns true if this authentication plugin can change the user's
1817 * password.
1819 * @return bool
1821 function can_change_password() {
1822 return !empty($this->config->stdchangepassword) or !empty($this->config->changepasswordurl);
1826 * Returns the URL for changing the user's pw, or empty if the default can
1827 * be used.
1829 * @return string url
1831 function change_password_url() {
1832 if (empty($this->config->stdchangepassword)) {
1833 return $this->config->changepasswordurl;
1834 } else {
1835 return '';
1840 * Will get called before the login page is shown, if NTLM SSO
1841 * is enabled, and the user is in the right network, we'll redirect
1842 * to the magic NTLM page for SSO...
1845 function loginpage_hook() {
1846 global $CFG, $SESSION;
1848 // HTTPS is potentially required
1849 httpsrequired();
1851 if (($_SERVER['REQUEST_METHOD'] === 'GET' // Only on initial GET of loginpage
1852 || ($_SERVER['REQUEST_METHOD'] === 'POST'
1853 && (get_referer() != strip_querystring(qualified_me()))))
1854 // Or when POSTed from another place
1855 // See MDL-14071
1856 && !empty($this->config->ntlmsso_enabled) // SSO enabled
1857 && !empty($this->config->ntlmsso_subnet) // have a subnet to test for
1858 && empty($_GET['authldap_skipntlmsso']) // haven't failed it yet
1859 && (isguestuser() || !isloggedin()) // guestuser or not-logged-in users
1860 && address_in_subnet(getremoteaddr(), $this->config->ntlmsso_subnet)) {
1862 // First, let's remember where we were trying to get to before we got here
1863 if (empty($SESSION->wantsurl)) {
1864 $SESSION->wantsurl = (array_key_exists('HTTP_REFERER', $_SERVER) &&
1865 $_SERVER['HTTP_REFERER'] != $CFG->wwwroot &&
1866 $_SERVER['HTTP_REFERER'] != $CFG->wwwroot.'/' &&
1867 $_SERVER['HTTP_REFERER'] != $CFG->httpswwwroot.'/login/' &&
1868 $_SERVER['HTTP_REFERER'] != $CFG->httpswwwroot.'/login/index.php')
1869 ? $_SERVER['HTTP_REFERER'] : NULL;
1872 // Now start the whole NTLM machinery.
1873 if(!empty($this->config->ntlmsso_ie_fastpath)) {
1874 // Shortcut for IE browsers: skip the attempt page at all
1875 if(check_browser_version('MSIE')) {
1876 $sesskey = sesskey();
1877 redirect($CFG->wwwroot.'/auth/ldap/ntlmsso_magic.php?sesskey='.$sesskey);
1878 } else {
1879 redirect($CFG->httpswwwroot.'/login/index.php?authldap_skipntlmsso=1');
1881 } else {
1882 redirect($CFG->wwwroot.'/auth/ldap/ntlmsso_attempt.php');
1886 // No NTLM SSO, Use the normal login page instead.
1888 // If $SESSION->wantsurl is empty and we have a 'Referer:' header, the login
1889 // page insists on redirecting us to that page after user validation. If
1890 // we clicked on the redirect link at the ntlmsso_finish.php page instead
1891 // of waiting for the redirection to happen, then we have a 'Referer:' header
1892 // we don't want to use at all. As we can't get rid of it, just point
1893 // $SESSION->wantsurl to $CFG->wwwroot (after all, we came from there).
1894 if (empty($SESSION->wantsurl)
1895 && (get_referer() == $CFG->httpswwwroot.'/auth/ldap/ntlmsso_finish.php')) {
1897 $SESSION->wantsurl = $CFG->wwwroot;
1902 * To be called from a page running under NTLM's
1903 * "Integrated Windows Authentication".
1905 * If successful, it will set a special "cookie" (not an HTTP cookie!)
1906 * in cache_flags under the "auth/ldap/ntlmsess" "plugin" and return true.
1907 * The "cookie" will be picked up by ntlmsso_finish() to complete the
1908 * process.
1910 * On failure it will return false for the caller to display an appropriate
1911 * error message (probably saying that Integrated Windows Auth isn't enabled!)
1913 * NOTE that this code will execute under the OS user credentials,
1914 * so we MUST avoid dealing with files -- such as session files.
1915 * (The caller should set $nomoodlecookie before including config.php)
1918 function ntlmsso_magic($sesskey) {
1919 if (isset($_SERVER['REMOTE_USER']) && !empty($_SERVER['REMOTE_USER'])) {
1921 // HTTP __headers__ seem to be sent in ISO-8859-1 encoding
1922 // (according to my reading of RFC-1945, RFC-2616 and RFC-2617 and
1923 // my local tests), so we need to convert the REMOTE_USER value
1924 // (i.e., what we got from the HTTP WWW-Authenticate header) into UTF-8
1925 $textlib = textlib_get_instance();
1926 $username = $textlib->convert($_SERVER['REMOTE_USER'], 'iso-8859-1', 'utf-8');
1928 $username = substr(strrchr($username, '\\'), 1); //strip domain info
1929 $username = moodle_strtolower($username); //compatibility hack
1930 set_cache_flag('auth/ldap/ntlmsess', $sesskey, $username, AUTH_NTLMTIMEOUT);
1931 return true;
1933 return false;
1937 * Find the session set by ntlmsso_magic(), validate it and
1938 * call authenticate_user_login() to authenticate the user through
1939 * the auth machinery.
1941 * It is complemented by a similar check in user_login().
1943 * If it succeeds, it never returns.
1946 function ntlmsso_finish() {
1947 global $CFG, $USER, $SESSION;
1949 $key = sesskey();
1950 $cf = get_cache_flags('auth/ldap/ntlmsess');
1951 if (!isset($cf[$key]) || $cf[$key] === '') {
1952 return false;
1954 $username = $cf[$key];
1955 // Here we want to trigger the whole authentication machinery
1956 // to make sure no step is bypassed...
1957 $user = authenticate_user_login($username, $key);
1958 if ($user) {
1959 add_to_log(SITEID, 'user', 'login', "view.php?id=$USER->id&course=".SITEID,
1960 $user->id, 0, $user->id);
1961 $USER = complete_user_login($user);
1963 // Cleanup the key to prevent reuse...
1964 // and to allow re-logins with normal credentials
1965 unset_cache_flag('auth/ldap/ntlmsess', $key);
1967 /// Redirection
1968 if (user_not_fully_set_up($USER)) {
1969 $urltogo = $CFG->wwwroot.'/user/edit.php';
1970 // We don't delete $SESSION->wantsurl yet, so we get there later
1971 } else if (isset($SESSION->wantsurl) and (strpos($SESSION->wantsurl, $CFG->wwwroot) === 0)) {
1972 $urltogo = $SESSION->wantsurl; /// Because it's an address in this site
1973 unset($SESSION->wantsurl);
1974 } else {
1975 // no wantsurl stored or external - go to homepage
1976 $urltogo = $CFG->wwwroot.'/';
1977 unset($SESSION->wantsurl);
1979 redirect($urltogo);
1981 // Should never reach here.
1982 return false;
1986 * Sync roles for this user
1988 * @param $user object user object (without system magic quotes)
1990 function sync_roles($user) {
1991 $iscreator = $this->iscreator($user->username);
1992 if ($iscreator === null) {
1993 return; //nothing to sync - creators not configured
1996 if ($roles = get_roles_with_capability('moodle/legacy:coursecreator', CAP_ALLOW)) {
1997 $creatorrole = array_shift($roles); // We can only use one, let's use the first one
1998 $systemcontext = get_context_instance(CONTEXT_SYSTEM);
2000 if ($iscreator) { // Following calls will not create duplicates
2001 role_assign($creatorrole->id, $user->id, 0, $systemcontext->id, 0, 0, 0, 'ldap');
2002 } else {
2003 //unassign only if previously assigned by this plugin!
2004 role_unassign($creatorrole->id, $user->id, 0, $systemcontext->id, 'ldap');
2010 * Prints a form for configuring this authentication plugin.
2012 * This function is called from admin/auth.php, and outputs a full page with
2013 * a form for configuring this plugin.
2015 * @param array $page An object containing all the data for this page.
2017 function config_form($config, $err, $user_fields) {
2018 include 'config.html';
2022 * Processes and stores configuration data for this authentication plugin.
2024 function process_config($config) {
2025 // set to defaults if undefined
2026 if (!isset($config->host_url))
2027 { $config->host_url = ''; }
2028 if (empty($config->ldapencoding))
2029 { $config->ldapencoding = 'utf-8'; }
2030 if (!isset($config->contexts))
2031 { $config->contexts = ''; }
2032 if (!isset($config->user_type))
2033 { $config->user_type = 'default'; }
2034 if (!isset($config->user_attribute))
2035 { $config->user_attribute = ''; }
2036 if (!isset($config->search_sub))
2037 { $config->search_sub = ''; }
2038 if (!isset($config->opt_deref))
2039 { $config->opt_deref = ''; }
2040 if (!isset($config->preventpassindb))
2041 { $config->preventpassindb = 0; }
2042 if (!isset($config->bind_dn))
2043 {$config->bind_dn = ''; }
2044 if (!isset($config->bind_pw))
2045 {$config->bind_pw = ''; }
2046 if (!isset($config->version))
2047 {$config->version = '2'; }
2048 if (!isset($config->objectclass))
2049 {$config->objectclass = ''; }
2050 if (!isset($config->memberattribute))
2051 {$config->memberattribute = ''; }
2052 if (!isset($config->memberattribute_isdn))
2053 {$config->memberattribute_isdn = ''; }
2054 if (!isset($config->creators))
2055 {$config->creators = ''; }
2056 if (!isset($config->create_context))
2057 {$config->create_context = ''; }
2058 if (!isset($config->expiration))
2059 {$config->expiration = ''; }
2060 if (!isset($config->expiration_warning))
2061 {$config->expiration_warning = '10'; }
2062 if (!isset($config->expireattr))
2063 {$config->expireattr = ''; }
2064 if (!isset($config->gracelogins))
2065 {$config->gracelogins = ''; }
2066 if (!isset($config->graceattr))
2067 {$config->graceattr = ''; }
2068 if (!isset($config->auth_user_create))
2069 {$config->auth_user_create = ''; }
2070 if (!isset($config->forcechangepassword))
2071 {$config->forcechangepassword = 0; }
2072 if (!isset($config->stdchangepassword))
2073 {$config->stdchangepassword = 0; }
2074 if (!isset($config->passtype))
2075 {$config->passtype = 'plaintext'; }
2076 if (!isset($config->changepasswordurl))
2077 {$config->changepasswordurl = ''; }
2078 if (!isset($config->removeuser))
2079 {$config->removeuser = 0; }
2080 if (!isset($config->ntlmsso_enabled))
2081 {$config->ntlmsso_enabled = 0; }
2082 if (!isset($config->ntlmsso_subnet))
2083 {$config->ntlmsso_subnet = ''; }
2084 if (!isset($config->ntlmsso_ie_fastpath))
2085 {$config->ntlmsso_ie_fastpath = 0; }
2087 // save settings
2088 set_config('host_url', $config->host_url, 'auth/ldap');
2089 set_config('ldapencoding', $config->ldapencoding, 'auth/ldap');
2090 set_config('host_url', $config->host_url, 'auth/ldap');
2091 set_config('contexts', $config->contexts, 'auth/ldap');
2092 set_config('user_type', $config->user_type, 'auth/ldap');
2093 set_config('user_attribute', $config->user_attribute, 'auth/ldap');
2094 set_config('search_sub', $config->search_sub, 'auth/ldap');
2095 set_config('opt_deref', $config->opt_deref, 'auth/ldap');
2096 set_config('preventpassindb', $config->preventpassindb, 'auth/ldap');
2097 set_config('bind_dn', $config->bind_dn, 'auth/ldap');
2098 set_config('bind_pw', $config->bind_pw, 'auth/ldap');
2099 set_config('version', $config->version, 'auth/ldap');
2100 set_config('objectclass', trim($config->objectclass), 'auth/ldap');
2101 set_config('memberattribute', $config->memberattribute, 'auth/ldap');
2102 set_config('memberattribute_isdn', $config->memberattribute_isdn, 'auth/ldap');
2103 set_config('creators', $config->creators, 'auth/ldap');
2104 set_config('create_context', $config->create_context, 'auth/ldap');
2105 set_config('expiration', $config->expiration, 'auth/ldap');
2106 set_config('expiration_warning', $config->expiration_warning, 'auth/ldap');
2107 set_config('expireattr', $config->expireattr, 'auth/ldap');
2108 set_config('gracelogins', $config->gracelogins, 'auth/ldap');
2109 set_config('graceattr', $config->graceattr, 'auth/ldap');
2110 set_config('auth_user_create', $config->auth_user_create, 'auth/ldap');
2111 set_config('forcechangepassword', $config->forcechangepassword, 'auth/ldap');
2112 set_config('stdchangepassword', $config->stdchangepassword, 'auth/ldap');
2113 set_config('passtype', $config->passtype, 'auth/ldap');
2114 set_config('changepasswordurl', $config->changepasswordurl, 'auth/ldap');
2115 set_config('removeuser', $config->removeuser, 'auth/ldap');
2116 set_config('ntlmsso_enabled', (int)$config->ntlmsso_enabled, 'auth/ldap');
2117 set_config('ntlmsso_subnet', $config->ntlmsso_subnet, 'auth/ldap');
2118 set_config('ntlmsso_ie_fastpath', (int)$config->ntlmsso_ie_fastpath, 'auth/ldap');
2120 return true;
2124 * Quote control characters in texts used in ldap filters - see RFC 4515/2254
2126 * @param string
2128 function filter_addslashes($text) {
2129 $text = str_replace('\\', '\\5c', $text);
2130 $text = str_replace(array('*', '(', ')', "\0"),
2131 array('\\2a', '\\28', '\\29', '\\00'), $text);
2132 return $text;
2136 * The order of the special characters in these arrays _IS IMPORTANT_.
2137 * Make sure '\\5C' (and '\\') are the first elements of the arrays.
2138 * Otherwise we'll double replace '\' with '\5C' which is Bad(tm)
2140 var $LDAP_DN_QUOTED_SPECIAL_CHARS = array('\\5c','\\20','\\22','\\23','\\2b','\\2c','\\3b','\\3c','\\3d','\\3e','\\00');
2141 var $LDAP_DN_SPECIAL_CHARS = array('\\', ' ', '"', '#', '+', ',', ';', '<', '=', '>', "\0");
2144 * Quote control characters in distinguished names used in ldap - See RFC 4514/2253
2146 * @param string
2147 * @return string
2149 function ldap_addslashes($text) {
2150 $text = str_replace ($this->LDAP_DN_SPECIAL_CHARS,
2151 $this->LDAP_DN_QUOTED_SPECIAL_CHARS,
2152 $text);
2153 return $text;
2157 * Get password expiration time for a given user from Active Directory
2159 * @param string $pwdlastset The time last time we changed the password.
2160 * @param resource $lcapconn The open LDAP connection.
2161 * @param string $user_dn The distinguished name of the user we are checking.
2163 * @return string $unixtime
2165 function ldap_get_ad_pwdexpire($pwdlastset, $ldapconn, $user_dn){
2166 define ('ROOTDSE', '');
2167 // UF_DONT_EXPIRE_PASSWD value taken from MSDN directly
2168 define ('UF_DONT_EXPIRE_PASSWD', 0x00010000);
2170 global $CFG;
2172 if (!function_exists('bcsub')) {
2173 error_log ('You need the BCMath extension to use grace logins with Active Directory');
2174 return 0;
2177 // If UF_DONT_EXPIRE_PASSWD flag is set in user's
2178 // userAccountControl attribute, the password doesn't expire.
2179 $sr = ldap_read($ldapconn, $user_dn, '(objectClass=*)',
2180 array('userAccountControl'));
2181 if (!$sr) {
2182 error_log("ldap: error getting userAccountControl for $user_dn");
2183 // don't expire password, as we are not sure it has to be
2184 // expired or not.
2185 return 0;
2188 $info = $this->ldap_get_entries($ldapconn, $sr);
2189 $useraccountcontrol = $info[0]['userAccountControl'][0];
2190 if ($useraccountcontrol & UF_DONT_EXPIRE_PASSWD) {
2191 // password doesn't expire.
2192 return 0;
2195 // If pwdLastSet is zero, the user must change his/her password now
2196 // (unless UF_DONT_EXPIRE_PASSWD flag is set, but we already
2197 // tested this above)
2198 if ($pwdlastset === '0') {
2199 // password has expired
2200 return -1;
2203 // ----------------------------------------------------------------
2204 // Password expiration time in Active Directory is the composition of
2205 // two values:
2207 // - User's pwdLastSet attribute, that stores the last time
2208 // the password was changed.
2210 // - Domain's maxPwdAge attribute, that sets how long
2211 // passwords last in this domain.
2213 // We already have the first value (passed in as a parameter). We
2214 // need to get the second one. As we don't know the domain DN, we
2215 // have to query rootDSE's defaultNamingContext attribute to get
2216 // it. Then we have to query that DN's maxPwdAge attribute to get
2217 // the real value.
2219 // Once we have both values, we just need to combine them. But MS
2220 // chose to use a different base and unit for time measurements.
2221 // So we need to convert the values to Unix timestamps (see
2222 // details below).
2223 // ----------------------------------------------------------------
2225 $sr = ldap_read($ldapconn, ROOTDSE, '(objectClass=*)',
2226 array('defaultNamingContext'));
2227 if (!$sr) {
2228 error_log("ldap: error querying rootDSE for Active Directory");
2229 return 0;
2232 $info = $this->ldap_get_entries($ldapconn, $sr);
2233 $domaindn = $info[0]['defaultNamingContext'][0];
2235 $sr = ldap_read ($ldapconn, $domaindn, '(objectClass=*)',
2236 array('maxPwdAge'));
2237 $info = $this->ldap_get_entries($ldapconn, $sr);
2238 $maxpwdage = $info[0]['maxPwdAge'][0];
2240 // ----------------------------------------------------------------
2241 // MSDN says that "pwdLastSet contains the number of 100 nanosecond
2242 // intervals since January 1, 1601 (UTC), stored in a 64 bit integer".
2244 // According to Perl's Date::Manip, the number of seconds between
2245 // this date and Unix epoch is 11644473600. So we have to
2246 // substract this value to calculate a Unix time, once we have
2247 // scaled pwdLastSet to seconds. This is the script used to
2248 // calculate the value shown above:
2250 // #!/usr/bin/perl -w
2252 // use Date::Manip;
2254 // $date1 = ParseDate ("160101010000 UTC");
2255 // $date2 = ParseDate ("197001010000 UTC");
2256 // $delta = DateCalc($date1, $date2, \$err);
2257 // $secs = Delta_Format($delta, 0, "%st");
2258 // print "$secs \n";
2260 // MSDN also says that "maxPwdAge is stored as a large integer that
2261 // represents the number of 100 nanosecond intervals from the time
2262 // the password was set before the password expires." We also need
2263 // to scale this to seconds. Bear in mind that this value is stored
2264 // as a _negative_ quantity (at least in my AD domain).
2266 // As a last remark, if the low 32 bits of maxPwdAge are equal to 0,
2267 // the maximum password age in the domain is set to 0, which means
2268 // passwords do not expire (see
2269 // http://msdn2.microsoft.com/en-us/library/ms974598.aspx)
2271 // As the quantities involved are too big for PHP integers, we
2272 // need to use BCMath functions to work with arbitrary precision
2273 // numbers.
2274 // ----------------------------------------------------------------
2277 // If the low order 32 bits are 0, then passwords do not expire in
2278 // the domain. Just do '$maxpwdage mod 2^32' and check the result
2279 // (2^32 = 4294967296)
2280 if (bcmod ($maxpwdage, 4294967296) === '0') {
2281 return 0;
2284 // Add up pwdLastSet and maxPwdAge to get password expiration
2285 // time, in MS time units. Remember maxPwdAge is stored as a
2286 // _negative_ quantity, so we need to substract it in fact.
2287 $pwdexpire = bcsub ($pwdlastset, $maxpwdage);
2289 // Scale the result to convert it to Unix time units and return
2290 // that value.
2291 return bcsub( bcdiv($pwdexpire, '10000000'), '11644473600');