"MDL-12304, fix double text"
[moodle-linuxchix.git] / auth / ldap / auth.php
blobf9039b3c99f85e30638a201ea9abc99b084c6482
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];
60 //hack prefix to objectclass
61 if (empty($this->config->objectclass)) { // Can't send empty filter
62 $this->config->objectclass='objectClass=*';
63 } else if (stripos($this->config->objectclass, 'objectClass=') !== 0) {
64 $this->config->objectclass = 'objectClass='.$this->config->objectclass;
69 /**
70 * Returns true if the username and password work and false if they are
71 * wrong or don't exist.
73 * @param string $username The username (with system magic quotes)
74 * @param string $password The password (with system magic quotes)
76 * @return bool Authentication success or failure.
78 function user_login($username, $password) {
79 if (! function_exists('ldap_bind')) {
80 print_error('auth_ldapnotinstalled','auth');
81 return false;
84 if (!$username or !$password) { // Don't allow blank usernames or passwords
85 return false;
88 $textlib = textlib_get_instance();
89 $extusername = $textlib->convert(stripslashes($username), 'utf-8', $this->config->ldapencoding);
90 $extpassword = $textlib->convert(stripslashes($password), 'utf-8', $this->config->ldapencoding);
93 // Before we connect to LDAP, check if this is an AD SSO login
94 // if we succeed in this block, we'll return success early.
96 $key = sesskey();
97 if (!empty($this->config->ntlmsso_enabled) && $key === $password) {
98 $cf = get_cache_flags('auth/ldap/ntlmsess');
99 // We only get the cache flag if we retrieve it before
100 // it expires (AUTH_NTLMTIMEOUT seconds).
101 if (!isset($cf[$key]) || $cf[$key] === '') {
102 return false;
105 $sessusername = $cf[$key];
106 if ($username === $sessusername) {
107 unset($sessusername);
108 unset($cf);
110 // Check that the user is inside one of the configured LDAP contexts
111 $validuser = false;
112 $ldapconnection = $this->ldap_connect();
113 if ($ldapconnection) {
114 // if the user is not inside the configured contexts,
115 // ldap_find_userdn returns false.
116 if ($this->ldap_find_userdn($ldapconnection, $extusername)) {
117 $validuser = true;
119 ldap_close($ldapconnection);
122 // Shortcut here - SSO confirmed
123 return $validuser;
125 } // End SSO processing
126 unset($key);
128 $ldapconnection = $this->ldap_connect();
129 if ($ldapconnection) {
130 $ldap_user_dn = $this->ldap_find_userdn($ldapconnection, $extusername);
132 //if ldap_user_dn is empty, user does not exist
133 if (!$ldap_user_dn) {
134 ldap_close($ldapconnection);
135 return false;
138 // Try to bind with current username and password
139 $ldap_login = @ldap_bind($ldapconnection, $ldap_user_dn, $extpassword);
140 ldap_close($ldapconnection);
141 if ($ldap_login) {
142 return true;
145 else {
146 @ldap_close($ldapconnection);
147 print_error('auth_ldap_noconnect','auth','',$this->config->host_url);
149 return false;
153 * reads userinformation from ldap and return it in array()
155 * Read user information from external database and returns it as array().
156 * Function should return all information available. If you are saving
157 * this information to moodle user-table you should honor syncronization flags
159 * @param string $username username (with system magic quotes)
161 * @return mixed array with no magic quotes or false on error
163 function get_userinfo($username) {
164 $textlib = textlib_get_instance();
165 $extusername = $textlib->convert(stripslashes($username), 'utf-8', $this->config->ldapencoding);
167 $ldapconnection = $this->ldap_connect();
168 $attrmap = $this->ldap_attributes();
170 $result = array();
171 $search_attribs = array();
173 foreach ($attrmap as $key=>$values) {
174 if (!is_array($values)) {
175 $values = array($values);
177 foreach ($values as $value) {
178 if (!in_array($value, $search_attribs)) {
179 array_push($search_attribs, $value);
184 $user_dn = $this->ldap_find_userdn($ldapconnection, $extusername);
186 if (!$user_info_result = ldap_read($ldapconnection, $user_dn, $this->config->objectclass, $search_attribs)) {
187 return false; // error!
189 $user_entry = $this->ldap_get_entries($ldapconnection, $user_info_result);
190 if (empty($user_entry)) {
191 return false; // entry not found
194 foreach ($attrmap as $key=>$values) {
195 if (!is_array($values)) {
196 $values = array($values);
198 $ldapval = NULL;
199 foreach ($values as $value) {
200 if ($value == 'dn') {
201 $result[$key] = $user_dn;
203 if (!array_key_exists($value, $user_entry[0])) {
204 continue; // wrong data mapping!
206 if (is_array($user_entry[0][$value])) {
207 $newval = $textlib->convert($user_entry[0][$value][0], $this->config->ldapencoding, 'utf-8');
208 } else {
209 $newval = $textlib->convert($user_entry[0][$value], $this->config->ldapencoding, 'utf-8');
211 if (!empty($newval)) { // favour ldap entries that are set
212 $ldapval = $newval;
215 if (!is_null($ldapval)) {
216 $result[$key] = $ldapval;
220 @ldap_close($ldapconnection);
221 return $result;
225 * reads userinformation from ldap and return it in an object
227 * @param string $username username (with system magic quotes)
228 * @return mixed object or false on error
230 function get_userinfo_asobj($username) {
231 $user_array = $this->get_userinfo($username);
232 if ($user_array == false) {
233 return false; //error or not found
235 $user_array = truncate_userinfo($user_array);
236 $user = new object();
237 foreach ($user_array as $key=>$value) {
238 $user->{$key} = $value;
240 return $user;
244 * returns all usernames from external database
246 * get_userlist returns all usernames from external database
248 * @return array
250 function get_userlist() {
251 return $this->ldap_get_userlist("({$this->config->user_attribute}=*)");
255 * checks if user exists on external db
257 * @param string $username (with system magic quotes)
259 function user_exists($username) {
261 $textlib = textlib_get_instance();
262 $extusername = $textlib->convert(stripslashes($username), 'utf-8', $this->config->ldapencoding);
264 //returns true if given username exist on ldap
265 $users = $this->ldap_get_userlist("({$this->config->user_attribute}=".$this->filter_addslashes($extusername).")");
266 return count($users);
270 * Creates a new user on external database.
271 * By using information in userobject
272 * Use user_exists to prevent dublicate usernames
274 * @param mixed $userobject Moodle userobject (with system magic quotes)
275 * @param mixed $plainpass Plaintext password (with system magic quotes)
277 function user_create($userobject, $plainpass) {
278 $textlib = textlib_get_instance();
279 $extusername = $textlib->convert(stripslashes($userobject->username), 'utf-8', $this->config->ldapencoding);
280 $extpassword = $textlib->convert(stripslashes($plainpass), 'utf-8', $this->config->ldapencoding);
282 switch ($this->config->passtype) {
283 case 'md5':
284 $extpassword = '{MD5}' . base64_encode(pack('H*', md5($extpassword)));
285 break;
286 case 'sha1':
287 $extpassword = '{SHA}' . base64_encode(pack('H*', sha1($extpassword)));
288 break;
289 case 'plaintext':
290 default:
291 break; // plaintext
294 $ldapconnection = $this->ldap_connect();
295 $attrmap = $this->ldap_attributes();
297 $newuser = array();
299 foreach ($attrmap as $key => $values) {
300 if (!is_array($values)) {
301 $values = array($values);
303 foreach ($values as $value) {
304 if (!empty($userobject->$key) ) {
305 $newuser[$value] = $textlib->convert(stripslashes($userobject->$key), 'utf-8', $this->config->ldapencoding);
310 //Following sets all mandatory and other forced attribute values
311 //User should be creted as login disabled untill email confirmation is processed
312 //Feel free to add your user type and send patches to paca@sci.fi to add them
313 //Moodle distribution
315 switch ($this->config->user_type) {
316 case 'edir':
317 $newuser['objectClass'] = array("inetOrgPerson","organizationalPerson","person","top");
318 $newuser['uniqueId'] = $extusername;
319 $newuser['logindisabled'] = "TRUE";
320 $newuser['userpassword'] = $extpassword;
321 $uadd = ldap_add($ldapconnection, $this->config->user_attribute.'="'.$this->ldap_addslashes($userobject->username).','.$this->config->create_context.'"', $newuser);
322 break;
323 case 'ad':
324 // User account creation is a two step process with AD. First you
325 // create the user object, then you set the password. If you try
326 // to set the password while creating the user, the operation
327 // fails.
329 // Passwords in Active Directory must be encoded as Unicode
330 // strings (UCS-2 Little Endian format) and surrounded with
331 // double quotes. See http://support.microsoft.com/?kbid=269190
332 if (!function_exists('mb_convert_encoding')) {
333 print_error ('auth_ldap_no_mbstring', 'auth');
336 // First create the user account, and mark it as disabled.
337 $newuser['objectClass'] = array('top','person','user','organizationalPerson');
338 $newuser['sAMAccountName'] = $extusername;
339 $newuser['userAccountControl'] = AUTH_AD_NORMAL_ACCOUNT |
340 AUTH_AD_ACCOUNTDISABLE;
341 $userdn = 'cn=' . $this->ldap_addslashes($extusername) .
342 ',' . $this->config->create_context;
343 if (!ldap_add($ldapconnection, $userdn, $newuser)) {
344 print_error ('auth_ldap_ad_create_req', 'auth');
347 // Now set the password
348 unset($newuser);
349 $newuser['unicodePwd'] = mb_convert_encoding('"' . $extpassword . '"',
350 "UCS-2LE", "UTF-8");
351 if(!ldap_modify($ldapconnection, $userdn, $newuser)) {
352 // Something went wrong: delete the user account and error out
353 ldap_delete ($ldapconnection, $userdn);
354 print_error ('auth_ldap_ad_create_req', 'auth');
356 $uadd = true;
357 break;
358 default:
359 print_error('auth_ldap_unsupportedusertype','auth','',$this->config->user_type);
361 ldap_close($ldapconnection);
362 return $uadd;
366 function can_reset_password() {
367 return !empty($this->config->stdchangepassword);
370 function can_signup() {
371 return (!empty($this->config->auth_user_create) and !empty($this->config->create_context));
375 * Sign up a new user ready for confirmation.
376 * Password is passed in plaintext.
378 * @param object $user new user object (with system magic quotes)
379 * @param boolean $notify print notice with link and terminate
381 function user_signup($user, $notify=true) {
382 global $CFG;
383 require_once($CFG->dirroot.'/user/profile/lib.php');
385 if ($this->user_exists($user->username)) {
386 print_error('auth_ldap_user_exists', 'auth');
389 $plainslashedpassword = $user->password;
390 unset($user->password);
392 if (! $this->user_create($user, $plainslashedpassword)) {
393 print_error('auth_ldap_create_error', 'auth');
396 if (! ($user->id = insert_record('user', $user)) ) {
397 print_error('auth_emailnoinsert', 'auth');
400 /// Save any custom profile field information
401 profile_save_data($user);
403 $this->update_user_record($user->username);
404 update_internal_user_password($user, $plainslashedpassword);
406 if (! send_confirmation_email($user)) {
407 print_error('auth_emailnoemail', 'auth');
410 if ($notify) {
411 global $CFG;
412 $emailconfirm = get_string('emailconfirm');
413 $navlinks = array();
414 $navlinks[] = array('name' => $emailconfirm, 'link' => null, 'type' => 'misc');
415 $navigation = build_navigation($navlinks);
417 print_header($emailconfirm, $emailconfirm, $navigation);
418 notice(get_string('emailconfirmsent', '', $user->email), "$CFG->wwwroot/index.php");
419 } else {
420 return true;
425 * Returns true if plugin allows confirming of new users.
427 * @return bool
429 function can_confirm() {
430 return $this->can_signup();
434 * Confirm the new user as registered.
436 * @param string $username (with system magic quotes)
437 * @param string $confirmsecret (with system magic quotes)
439 function user_confirm($username, $confirmsecret) {
440 $user = get_complete_user_data('username', $username);
442 if (!empty($user)) {
443 if ($user->confirmed) {
444 return AUTH_CONFIRM_ALREADY;
446 } else if ($user->auth != 'ldap') {
447 return AUTH_CONFIRM_ERROR;
449 } else if ($user->secret == stripslashes($confirmsecret)) { // They have provided the secret key to get in
450 if (!$this->user_activate($username)) {
451 return AUTH_CONFIRM_FAIL;
453 if (!set_field("user", "confirmed", 1, "id", $user->id)) {
454 return AUTH_CONFIRM_FAIL;
456 if (!set_field("user", "firstaccess", time(), "id", $user->id)) {
457 return AUTH_CONFIRM_FAIL;
459 return AUTH_CONFIRM_OK;
461 } else {
462 return AUTH_CONFIRM_ERROR;
467 * return number of days to user password expires
469 * If userpassword does not expire it should return 0. If password is already expired
470 * it should return negative value.
472 * @param mixed $username username (with system magic quotes)
473 * @return integer
475 function password_expire($username) {
476 $result = 0;
478 $textlib = textlib_get_instance();
479 $extusername = $textlib->convert(stripslashes($username), 'utf-8', $this->config->ldapencoding);
481 $ldapconnection = $this->ldap_connect();
482 $user_dn = $this->ldap_find_userdn($ldapconnection, $extusername);
483 $search_attribs = array($this->config->expireattr);
484 $sr = ldap_read($ldapconnection, $user_dn, 'objectclass=*', $search_attribs);
485 if ($sr) {
486 $info = $this->ldap_get_entries($ldapconnection, $sr);
487 if (!empty ($info) and !empty($info[0][$this->config->expireattr][0])) {
488 $expiretime = $this->ldap_expirationtime2unix($info[0][$this->config->expireattr][0], $ldapconnection, $user_dn);
489 if ($expiretime != 0) {
490 $now = time();
491 if ($expiretime > $now) {
492 $result = ceil(($expiretime - $now) / DAYSECS);
494 else {
495 $result = floor(($expiretime - $now) / DAYSECS);
499 } else {
500 error_log("ldap: password_expire did't find expiration time.");
503 //error_log("ldap: password_expire user $user_dn expires in $result days!");
504 return $result;
508 * syncronizes user fron external db to moodle user table
510 * Sync is now using username attribute.
512 * Syncing users removes or suspends users that dont exists anymore in external db.
513 * Creates new users and updates coursecreator status of users.
515 * @param int $bulk_insert_records will insert $bulkinsert_records per insert statement
516 * valid only with $unsafe. increase to a couple thousand for
517 * blinding fast inserts -- but test it: you may hit mysqld's
518 * max_allowed_packet limit.
519 * @param bool $do_updates will do pull in data updates from ldap if relevant
521 function sync_users ($bulk_insert_records = 1000, $do_updates = true) {
523 global $CFG;
525 $textlib = textlib_get_instance();
527 $droptablesql = array(); /// sql commands to drop the table (because session scope could be a problem for
528 /// some persistent drivers like ODBTP (mssql) or if this function is invoked
529 /// from within a PHP application using persistent connections
530 $temptable = $CFG->prefix . 'extuser';
531 $createtemptablesql = '';
533 // configure a temp table
534 print "Configuring temp table\n";
535 switch (strtolower($CFG->dbfamily)) {
536 case 'mysql':
537 $droptablesql[] = 'DROP TEMPORARY TABLE ' . $temptable; // sql command to drop the table (because session scope could be a problem)
538 $createtemptablesql = 'CREATE TEMPORARY TABLE ' . $temptable . ' (username VARCHAR(64), PRIMARY KEY (username)) TYPE=MyISAM';
539 break;
540 case 'postgres':
541 $droptablesql[] = 'DROP TABLE ' . $temptable; // sql command to drop the table (because session scope could be a problem)
542 $bulk_insert_records = 1; // no support for multiple sets of values
543 $createtemptablesql = 'CREATE TEMPORARY TABLE '. $temptable . ' (username VARCHAR(64), PRIMARY KEY (username))';
544 break;
545 case 'mssql':
546 $temptable = '#'. $temptable; /// MSSQL temp tables begin with #
547 $droptablesql[] = 'DROP TABLE ' . $temptable; // sql command to drop the table (because session scope could be a problem)
548 $bulk_insert_records = 1; // no support for multiple sets of values
549 $createtemptablesql = 'CREATE TABLE ' . $temptable . ' (username VARCHAR(64), PRIMARY KEY (username))';
550 break;
551 case 'oracle':
552 $droptablesql[] = 'TRUNCATE TABLE ' . $temptable; // oracle requires truncate before being able to drop a temp table
553 $droptablesql[] = 'DROP TABLE ' . $temptable; // sql command to drop the table (because session scope could be a problem)
554 $bulk_insert_records = 1; // no support for multiple sets of values
555 $createtemptablesql = 'CREATE GLOBAL TEMPORARY TABLE '.$temptable.' (username VARCHAR(64), PRIMARY KEY (username)) ON COMMIT PRESERVE ROWS';
556 break;
560 execute_sql_arr($droptablesql, true, false); /// Drop temp table to avoid persistence problems later
561 echo "Creating temp table $temptable\n";
562 if(! execute_sql($createtemptablesql, false) ){
563 print "Failed to create temporary users table - aborting\n";
564 exit;
567 print "Connecting to ldap...\n";
568 $ldapconnection = $this->ldap_connect();
570 if (!$ldapconnection) {
571 @ldap_close($ldapconnection);
572 print get_string('auth_ldap_noconnect','auth',$this->config->host_url);
573 exit;
576 ////
577 //// get user's list from ldap to sql in a scalable fashion
578 ////
579 // prepare some data we'll need
580 $filter = "(&(".$this->config->user_attribute."=*)(".$this->config->objectclass."))";
582 $contexts = explode(";",$this->config->contexts);
584 if (!empty($this->config->create_context)) {
585 array_push($contexts, $this->config->create_context);
588 $fresult = array();
589 foreach ($contexts as $context) {
590 $context = trim($context);
591 if (empty($context)) {
592 continue;
594 begin_sql();
595 if ($this->config->search_sub) {
596 //use ldap_search to find first user from subtree
597 $ldap_result = ldap_search($ldapconnection, $context,
598 $filter,
599 array($this->config->user_attribute));
600 } else {
601 //search only in this context
602 $ldap_result = ldap_list($ldapconnection, $context,
603 $filter,
604 array($this->config->user_attribute));
607 if ($entry = ldap_first_entry($ldapconnection, $ldap_result)) {
608 do {
609 $value = ldap_get_values_len($ldapconnection, $entry, $this->config->user_attribute);
610 $value = $textlib->convert($value[0], $this->config->ldapencoding, 'utf-8');
611 // usernames are __always__ lowercase.
612 array_push($fresult, moodle_strtolower($value));
613 if (count($fresult) >= $bulk_insert_records) {
614 $this->ldap_bulk_insert($fresult, $temptable);
615 $fresult = array();
617 } while ($entry = ldap_next_entry($ldapconnection, $entry));
619 unset($ldap_result); // free mem
621 // insert any remaining users and release mem
622 if (count($fresult)) {
623 $this->ldap_bulk_insert($fresult, $temptable);
624 $fresult = array();
626 commit_sql();
629 /// preserve our user database
630 /// if the temp table is empty, it probably means that something went wrong, exit
631 /// so as to avoid mass deletion of users; which is hard to undo
632 $count = get_record_sql('SELECT COUNT(username) AS count, 1 FROM ' . $temptable);
633 $count = $count->{'count'};
634 if ($count < 1) {
635 print "Did not get any users from LDAP -- error? -- exiting\n";
636 exit;
637 } else {
638 print "Got $count records from LDAP\n\n";
642 /// User removal
643 // find users in DB that aren't in ldap -- to be removed!
644 // this is still not as scalable (but how often do we mass delete?)
645 if (!empty($this->config->removeuser)) {
646 $sql = "SELECT u.id, u.username, u.email, u.auth
647 FROM {$CFG->prefix}user u
648 LEFT JOIN $temptable e ON u.username = e.username
649 WHERE u.auth='ldap'
650 AND u.deleted=0
651 AND e.username IS NULL";
652 $remove_users = get_records_sql($sql);
654 if (!empty($remove_users)) {
655 print "User entries to remove: ". count($remove_users) . "\n";
657 foreach ($remove_users as $user) {
658 if ($this->config->removeuser == 2) {
659 if (delete_user($user)) {
660 echo "\t"; print_string('auth_dbdeleteuser', 'auth', array($user->username, $user->id)); echo "\n";
661 } else {
662 echo "\t"; print_string('auth_dbdeleteusererror', 'auth', $user->username); echo "\n";
664 } else if ($this->config->removeuser == 1) {
665 $updateuser = new object();
666 $updateuser->id = $user->id;
667 $updateuser->auth = 'nologin';
668 if (update_record('user', $updateuser)) {
669 echo "\t"; print_string('auth_dbsuspenduser', 'auth', array($user->username, $user->id)); echo "\n";
670 } else {
671 echo "\t"; print_string('auth_dbsuspendusererror', 'auth', $user->username); echo "\n";
675 } else {
676 print "No user entries to be removed\n";
678 unset($remove_users); // free mem!
681 /// Revive suspended users
682 if (!empty($this->config->removeuser) and $this->config->removeuser == 1) {
683 $sql = "SELECT u.id, u.username
684 FROM $temptable e, {$CFG->prefix}user u
685 WHERE e.username=u.username
686 AND u.auth='nologin'";
687 $revive_users = get_records_sql($sql);
689 if (!empty($revive_users)) {
690 print "User entries to be revived: ". count($revive_users) . "\n";
692 begin_sql();
693 foreach ($revive_users as $user) {
694 $updateuser = new object();
695 $updateuser->id = $user->id;
696 $updateuser->auth = 'ldap';
697 if (update_record('user', $updateuser)) {
698 echo "\t"; print_string('auth_dbreviveser', 'auth', array($user->username, $user->id)); echo "\n";
699 } else {
700 echo "\t"; print_string('auth_dbreviveusererror', 'auth', $user->username); echo "\n";
703 commit_sql();
704 } else {
705 print "No user entries to be revived\n";
708 unset($revive_users);
712 /// User Updates - time-consuming (optional)
713 if ($do_updates) {
714 // narrow down what fields we need to update
715 $all_keys = array_keys(get_object_vars($this->config));
716 $updatekeys = array();
717 foreach ($all_keys as $key) {
718 if (preg_match('/^field_updatelocal_(.+)$/',$key, $match)) {
719 // if we have a field to update it from
720 // and it must be updated 'onlogin' we
721 // update it on cron
722 if ( !empty($this->config->{'field_map_'.$match[1]})
723 and $this->config->{$match[0]} === 'onlogin') {
724 array_push($updatekeys, $match[1]); // the actual key name
728 // print_r($all_keys); print_r($updatekeys);
729 unset($all_keys); unset($key);
731 } else {
732 print "No updates to be done\n";
734 if ( $do_updates and !empty($updatekeys) ) { // run updates only if relevant
735 $users = get_records_sql("SELECT u.username, u.id
736 FROM {$CFG->prefix}user u
737 WHERE u.deleted=0 AND u.auth='ldap'");
738 if (!empty($users)) {
739 print "User entries to update: ". count($users). "\n";
741 $sitecontext = get_context_instance(CONTEXT_SYSTEM);
742 if (!empty($this->config->creators) and !empty($this->config->memberattribute)
743 and $roles = get_roles_with_capability('moodle/legacy:coursecreator', CAP_ALLOW)) {
744 $creatorrole = array_shift($roles); // We can only use one, let's use the first one
745 } else {
746 $creatorrole = false;
749 begin_sql();
750 $xcount = 0;
751 $maxxcount = 100;
753 foreach ($users as $user) {
754 echo "\t"; print_string('auth_dbupdatinguser', 'auth', array($user->username, $user->id));
755 if (!$this->update_user_record(addslashes($user->username), $updatekeys)) {
756 echo " - ".get_string('skipped');
758 echo "\n";
759 $xcount++;
761 // update course creators if needed
762 if ($creatorrole !== false) {
763 if ($this->iscreator($user->username)) {
764 role_assign($creatorrole->id, $user->id, 0, $sitecontext->id, 0, 0, 0, 'ldap');
765 } else {
766 role_unassign($creatorrole->id, $user->id, 0, $sitecontext->id, 'ldap');
770 if ($xcount++ > $maxxcount) {
771 commit_sql();
772 begin_sql();
773 $xcount = 0;
776 commit_sql();
777 unset($users); // free mem
779 } else { // end do updates
780 print "No updates to be done\n";
783 /// User Additions
784 // find users missing in DB that are in LDAP
785 // note that get_records_sql wants at least 2 fields returned,
786 // and gives me a nifty object I don't want.
787 // note: we do not care about deleted accounts anymore, this feature was replaced by suspending to nologin auth plugin
788 $sql = "SELECT e.username, e.username
789 FROM $temptable e LEFT JOIN {$CFG->prefix}user u ON e.username = u.username
790 WHERE u.id IS NULL";
791 $add_users = get_records_sql($sql); // get rid of the fat
793 if (!empty($add_users)) {
794 print "User entries to add: ". count($add_users). "\n";
796 $sitecontext = get_context_instance(CONTEXT_SYSTEM);
797 if (!empty($this->config->creators) and !empty($this->config->memberattribute)
798 and $roles = get_roles_with_capability('moodle/legacy:coursecreator', CAP_ALLOW)) {
799 $creatorrole = array_shift($roles); // We can only use one, let's use the first one
800 } else {
801 $creatorrole = false;
804 begin_sql();
805 foreach ($add_users as $user) {
806 $user = $this->get_userinfo_asobj(addslashes($user->username));
808 // prep a few params
809 $user->modified = time();
810 $user->confirmed = 1;
811 $user->auth = 'ldap';
812 $user->mnethostid = $CFG->mnet_localhost_id;
813 if (empty($user->lang)) {
814 $user->lang = $CFG->lang;
817 $user = addslashes_recursive($user);
819 if ($id = insert_record('user',$user)) {
820 echo "\t"; print_string('auth_dbinsertuser', 'auth', array(stripslashes($user->username), $id)); echo "\n";
821 $userobj = $this->update_user_record($user->username);
822 if (!empty($this->config->forcechangepassword)) {
823 set_user_preference('auth_forcepasswordchange', 1, $userobj->id);
825 } else {
826 echo "\t"; print_string('auth_dbinsertusererror', 'auth', $user->username); echo "\n";
829 // add course creators if needed
830 if ($creatorrole !== false and $this->iscreator(stripslashes($user->username))) {
831 role_assign($creatorrole->id, $user->id, 0, $sitecontext->id, 0, 0, 0, 'ldap');
834 commit_sql();
835 unset($add_users); // free mem
836 } else {
837 print "No users to be added\n";
839 return true;
843 * Update a local user record from an external source.
844 * This is a lighter version of the one in moodlelib -- won't do
845 * expensive ops such as enrolment.
847 * If you don't pass $updatekeys, there is a performance hit and
848 * values removed from LDAP won't be removed from moodle.
850 * @param string $username username (with system magic quotes)
852 function update_user_record($username, $updatekeys = false) {
853 global $CFG;
855 //just in case check text case
856 $username = trim(moodle_strtolower($username));
858 // get the current user record
859 $user = get_record('user', 'username', $username, 'mnethostid', $CFG->mnet_localhost_id);
860 if (empty($user)) { // trouble
861 error_log("Cannot update non-existent user: ".stripslashes($username));
862 print_error('auth_dbusernotexist','auth','',$username);
863 die;
866 // Protect the userid from being overwritten
867 $userid = $user->id;
869 if ($newinfo = $this->get_userinfo($username)) {
870 $newinfo = truncate_userinfo($newinfo);
872 if (empty($updatekeys)) { // all keys? this does not support removing values
873 $updatekeys = array_keys($newinfo);
876 foreach ($updatekeys as $key) {
877 if (isset($newinfo[$key])) {
878 $value = $newinfo[$key];
879 } else {
880 $value = '';
883 if (!empty($this->config->{'field_updatelocal_' . $key})) {
884 if ($user->{$key} != $value) { // only update if it's changed
885 set_field('user', $key, addslashes($value), 'id', $userid);
889 } else {
890 return false;
892 return get_record_select('user', "id = $userid AND deleted = 0");
896 * Bulk insert in SQL's temp table
897 * @param array $users is an array of usernames
899 function ldap_bulk_insert($users, $temptable) {
901 // bulk insert -- superfast with $bulk_insert_records
902 $sql = 'INSERT INTO ' . $temptable . ' (username) VALUES ';
903 // make those values safe
904 $users = addslashes_recursive($users);
905 // join and quote the whole lot
906 $sql = $sql . "('" . implode("'),('", $users) . "')";
907 print "\t+ " . count($users) . " users\n";
908 execute_sql($sql, false);
913 * Activates (enables) user in external db so user can login to external db
915 * @param mixed $username username (with system magic quotes)
916 * @return boolen result
918 function user_activate($username) {
919 $textlib = textlib_get_instance();
920 $extusername = $textlib->convert(stripslashes($username), 'utf-8', $this->config->ldapencoding);
922 $ldapconnection = $this->ldap_connect();
924 $userdn = $this->ldap_find_userdn($ldapconnection, $extusername);
925 switch ($this->config->user_type) {
926 case 'edir':
927 $newinfo['loginDisabled']="FALSE";
928 break;
929 case 'ad':
930 // We need to unset the ACCOUNTDISABLE bit in the
931 // userAccountControl attribute ( see
932 // http://support.microsoft.com/kb/305144 )
933 $sr = ldap_read($ldapconnection, $userdn, '(objectClass=*)',
934 array('userAccountControl'));
935 $info = ldap_get_entries($ldapconnection, $sr);
936 $newinfo['userAccountControl'] = $info[0]['userAccountControl'][0]
937 & (~AUTH_AD_ACCOUNTDISABLE);
938 break;
939 default:
940 error ('auth: ldap user_activate() does not support selected usertype:"'.$this->config->user_type.'" (..yet)');
942 $result = ldap_modify($ldapconnection, $userdn, $newinfo);
943 ldap_close($ldapconnection);
944 return $result;
948 * Disables user in external db so user can't login to external db
950 * @param mixed $username username
951 * @return boolean result
953 /* function user_disable($username) {
954 $textlib = textlib_get_instance();
955 $extusername = $textlib->convert(stripslashes($username), 'utf-8', $this->config->ldapencoding);
957 $ldapconnection = $this->ldap_connect();
959 $userdn = $this->ldap_find_userdn($ldapconnection, $extusername);
960 switch ($this->config->user_type) {
961 case 'edir':
962 $newinfo['loginDisabled']="TRUE";
963 break;
964 case 'ad':
965 // We need to set the ACCOUNTDISABLE bit in the
966 // userAccountControl attribute ( see
967 // http://support.microsoft.com/kb/305144 )
968 $sr = ldap_read($ldapconnection, $userdn, '(objectClass=*)',
969 array('userAccountControl'));
970 $info = auth_ldap_get_entries($ldapconnection, $sr);
971 $newinfo['userAccountControl'] = $info[0]['userAccountControl'][0]
972 | AUTH_AD_ACCOUNTDISABLE;
973 break;
974 default:
975 error ('auth: ldap user_disable() does not support selected usertype (..yet)');
977 $result = ldap_modify($ldapconnection, $userdn, $newinfo);
978 ldap_close($ldapconnection);
979 return $result;
983 * Returns true if user should be coursecreator.
985 * @param mixed $username username (without system magic quotes)
986 * @return boolean result
988 function iscreator($username) {
989 if (empty($this->config->creators) or empty($this->config->memberattribute)) {
990 return null;
993 $textlib = textlib_get_instance();
994 $extusername = $textlib->convert($username, 'utf-8', $this->config->ldapencoding);
996 return (boolean)$this->ldap_isgroupmember($extusername, $this->config->creators);
1000 * Called when the user record is updated.
1001 * Modifies user in external database. It takes olduser (before changes) and newuser (after changes)
1002 * conpares information saved modified information to external db.
1004 * @param mixed $olduser Userobject before modifications (without system magic quotes)
1005 * @param mixed $newuser Userobject new modified userobject (without system magic quotes)
1006 * @return boolean result
1009 function user_update($olduser, $newuser) {
1011 global $USER;
1013 if (isset($olduser->username) and isset($newuser->username) and $olduser->username != $newuser->username) {
1014 error_log("ERROR:User renaming not allowed in LDAP");
1015 return false;
1018 if (isset($olduser->auth) and $olduser->auth != 'ldap') {
1019 return true; // just change auth and skip update
1022 $attrmap = $this->ldap_attributes();
1024 // Before doing anything else, make sure really need to update anything
1025 // in the external LDAP server.
1026 $update_external = false;
1027 foreach ($attrmap as $key => $ldapkeys) {
1028 if (!empty($this->config->{'field_updateremote_'.$key})) {
1029 $update_external = true;
1030 break;
1033 if (!$update_external) {
1034 return true;
1037 $textlib = textlib_get_instance();
1038 $extoldusername = $textlib->convert($olduser->username, 'utf-8', $this->config->ldapencoding);
1040 $ldapconnection = $this->ldap_connect();
1042 $search_attribs = array();
1044 foreach ($attrmap as $key => $values) {
1045 if (!is_array($values)) {
1046 $values = array($values);
1048 foreach ($values as $value) {
1049 if (!in_array($value, $search_attribs)) {
1050 array_push($search_attribs, $value);
1055 $user_dn = $this->ldap_find_userdn($ldapconnection, $extoldusername);
1057 $user_info_result = ldap_read($ldapconnection, $user_dn,
1058 $this->config->objectclass, $search_attribs);
1060 if ($user_info_result) {
1062 $user_entry = $this->ldap_get_entries($ldapconnection, $user_info_result);
1063 if (empty($user_entry)) {
1064 $error = 'ldap: Could not find user while updating externally. '.
1065 'Details follow: search base: \''.$user_dn.'\'; search filter: \''.
1066 $this->config->objectclass.'\'; search attributes: ';
1067 foreach ($search_attribs as $attrib) {
1068 $error .= $attrib.' ';
1070 error_log($error);
1071 return false; // old user not found!
1072 } else if (count($user_entry) > 1) {
1073 error_log('ldap: Strange! More than one user record found in ldap. Only using the first one.');
1074 return false;
1076 $user_entry = $user_entry[0];
1078 //error_log(var_export($user_entry) . 'fpp' );
1080 foreach ($attrmap as $key => $ldapkeys) {
1081 // only process if the moodle field ($key) has changed and we
1082 // are set to update LDAP with it
1083 if (isset($olduser->$key) and isset($newuser->$key)
1084 and $olduser->$key !== $newuser->$key
1085 and !empty($this->config->{'field_updateremote_'. $key})) {
1086 // for ldap values that could be in more than one
1087 // ldap key, we will do our best to match
1088 // where they came from
1089 $ambiguous = true;
1090 $changed = false;
1091 if (!is_array($ldapkeys)) {
1092 $ldapkeys = array($ldapkeys);
1094 if (count($ldapkeys) < 2) {
1095 $ambiguous = false;
1098 $nuvalue = $textlib->convert($newuser->$key, 'utf-8', $this->config->ldapencoding);
1099 empty($nuvalue) ? $nuvalue = array() : $nuvalue;
1100 $ouvalue = $textlib->convert($olduser->$key, 'utf-8', $this->config->ldapencoding);
1102 foreach ($ldapkeys as $ldapkey) {
1103 $ldapkey = $ldapkey;
1104 $ldapvalue = $user_entry[$ldapkey][0];
1105 if (!$ambiguous) {
1106 // skip update if the values already match
1107 if ($nuvalue !== $ldapvalue) {
1108 //this might fail due to schema validation
1109 if (@ldap_modify($ldapconnection, $user_dn, array($ldapkey => $nuvalue))) {
1110 continue;
1111 } else {
1112 error_log('Error updating LDAP record. Error code: '
1113 . ldap_errno($ldapconnection) . '; Error string : '
1114 . ldap_err2str(ldap_errno($ldapconnection))
1115 . "\nKey ($key) - old moodle value: '$ouvalue' new value: '$nuvalue'");
1116 continue;
1119 } else {
1120 // ambiguous
1121 // value empty before in Moodle (and LDAP) - use 1st ldap candidate field
1122 // no need to guess
1123 if ($ouvalue === '') { // value empty before - use 1st ldap candidate
1124 //this might fail due to schema validation
1125 if (@ldap_modify($ldapconnection, $user_dn, array($ldapkey => $nuvalue))) {
1126 $changed = true;
1127 continue;
1128 } else {
1129 error_log('Error updating LDAP record. Error code: '
1130 . ldap_errno($ldapconnection) . '; Error string : '
1131 . ldap_err2str(ldap_errno($ldapconnection))
1132 . "\nKey ($key) - old moodle value: '$ouvalue' new value: '$nuvalue'");
1133 continue;
1137 // we found which ldap key to update!
1138 if ($ouvalue !== '' and $ouvalue === $ldapvalue ) {
1139 //this might fail due to schema validation
1140 if (@ldap_modify($ldapconnection, $user_dn, array($ldapkey => $nuvalue))) {
1141 $changed = true;
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;
1154 if ($ambiguous and !$changed) {
1155 error_log("Failed to update LDAP with ambiguous field $key".
1156 " old moodle value: '" . $ouvalue .
1157 "' new value '" . $nuvalue );
1161 } else {
1162 error_log("ERROR:No user found in LDAP");
1163 @ldap_close($ldapconnection);
1164 return false;
1167 @ldap_close($ldapconnection);
1169 return true;
1174 * changes userpassword in external db
1176 * called when the user password is updated.
1177 * changes userpassword in external db
1179 * @param object $user User table object (with system magic quotes)
1180 * @param string $newpassword Plaintext password (with system magic quotes)
1181 * @return boolean result
1184 function user_update_password($user, $newpassword) {
1185 /// called when the user password is updated -- it assumes it is called by an admin
1186 /// or that you've otherwise checked the user's credentials
1187 /// IMPORTANT: $newpassword must be cleartext, not crypted/md5'ed
1189 global $USER;
1190 $result = false;
1191 $username = $user->username;
1193 $textlib = textlib_get_instance();
1194 $extusername = $textlib->convert(stripslashes($username), 'utf-8', $this->config->ldapencoding);
1195 $extpassword = $textlib->convert(stripslashes($newpassword), 'utf-8', $this->config->ldapencoding);
1197 switch ($this->config->passtype) {
1198 case 'md5':
1199 $extpassword = '{MD5}' . base64_encode(pack('H*', md5($extpassword)));
1200 break;
1201 case 'sha1':
1202 $extpassword = '{SHA}' . base64_encode(pack('H*', sha1($extpassword)));
1203 break;
1204 case 'plaintext':
1205 default:
1206 break; // plaintext
1209 $ldapconnection = $this->ldap_connect();
1211 $user_dn = $this->ldap_find_userdn($ldapconnection, $extusername);
1213 if (!$user_dn) {
1214 error_log('LDAP Error in user_update_password(). No DN for: ' . stripslashes($user->username));
1215 return false;
1218 switch ($this->config->user_type) {
1219 case 'edir':
1220 //Change password
1221 $result = ldap_modify($ldapconnection, $user_dn, array('userPassword' => $extpassword));
1222 if (!$result) {
1223 error_log('LDAP Error in user_update_password(). Error code: '
1224 . ldap_errno($ldapconnection) . '; Error string : '
1225 . ldap_err2str(ldap_errno($ldapconnection)));
1227 //Update password expiration time, grace logins count
1228 $search_attribs = array($this->config->expireattr, 'passwordExpirationInterval','loginGraceLimit' );
1229 $sr = ldap_read($ldapconnection, $user_dn, 'objectclass=*', $search_attribs);
1230 if ($sr) {
1231 $info=$this->ldap_get_entries($ldapconnection, $sr);
1232 $newattrs = array();
1233 if (!empty($info[0][$this->config->expireattr][0])) {
1234 //Set expiration time only if passwordExpirationInterval is defined
1235 if (!empty($info[0]['passwordExpirationInterval'][0])) {
1236 $expirationtime = time() + $info[0]['passwordExpirationInterval'][0];
1237 $ldapexpirationtime = $this->ldap_unix2expirationtime($expirationtime);
1238 $newattrs['passwordExpirationTime'] = $ldapexpirationtime;
1241 //set gracelogin count
1242 if (!empty($info[0]['loginGraceLimit'][0])) {
1243 $newattrs['loginGraceRemaining']= $info[0]['loginGraceLimit'][0];
1246 //Store attribute changes to ldap
1247 $result = ldap_modify($ldapconnection, $user_dn, $newattrs);
1248 if (!$result) {
1249 error_log('LDAP Error in user_update_password() when modifying expirationtime and/or gracelogins. Error code: '
1250 . ldap_errno($ldapconnection) . '; Error string : '
1251 . ldap_err2str(ldap_errno($ldapconnection)));
1255 else {
1256 error_log('LDAP Error in user_update_password() when reading password expiration time. Error code: '
1257 . ldap_errno($ldapconnection) . '; Error string : '
1258 . ldap_err2str(ldap_errno($ldapconnection)));
1260 break;
1262 case 'ad':
1263 // Passwords in Active Directory must be encoded as Unicode
1264 // strings (UCS-2 Little Endian format) and surrounded with
1265 // double quotes. See http://support.microsoft.com/?kbid=269190
1266 if (!function_exists('mb_convert_encoding')) {
1267 error_log ('You need the mbstring extension to change passwords in Active Directory');
1268 return false;
1270 $extpassword = mb_convert_encoding('"'.$extpassword.'"', "UCS-2LE", $this->config->ldapencoding);
1271 $result = ldap_modify($ldapconnection, $user_dn, array('unicodePwd' => $extpassword));
1272 if (!$result) {
1273 error_log('LDAP Error in user_update_password(). Error code: '
1274 . ldap_errno($ldapconnection) . '; Error string : '
1275 . ldap_err2str(ldap_errno($ldapconnection)));
1277 break;
1279 default:
1280 $usedconnection = &$ldapconnection;
1281 // send ldap the password in cleartext, it will md5 it itself
1282 $result = ldap_modify($ldapconnection, $user_dn, array('userPassword' => $extpassword));
1283 if (!$result) {
1284 error_log('LDAP Error in user_update_password(). Error code: '
1285 . ldap_errno($ldapconnection) . '; Error string : '
1286 . ldap_err2str(ldap_errno($ldapconnection)));
1291 @ldap_close($ldapconnection);
1292 return $result;
1295 //PRIVATE FUNCTIONS starts
1296 //private functions are named as ldap_*
1299 * returns predefined usertypes
1301 * @return array of predefined usertypes
1303 function ldap_suppported_usertypes() {
1304 $types = array();
1305 $types['edir']='Novell Edirectory';
1306 $types['rfc2307']='posixAccount (rfc2307)';
1307 $types['rfc2307bis']='posixAccount (rfc2307bis)';
1308 $types['samba']='sambaSamAccount (v.3.0.7)';
1309 $types['ad']='MS ActiveDirectory';
1310 $types['default']=get_string('default');
1311 return $types;
1316 * Initializes needed variables for ldap-module
1318 * Uses names defined in ldap_supported_usertypes.
1319 * $default is first defined as:
1320 * $default['pseudoname'] = array(
1321 * 'typename1' => 'value',
1322 * 'typename2' => 'value'
1323 * ....
1324 * );
1326 * @return array of default values
1328 function ldap_getdefaults() {
1329 $default['objectclass'] = array(
1330 'edir' => 'User',
1331 'rfc2307' => 'posixAccount',
1332 'rfc2307bis' => 'posixAccount',
1333 'samba' => 'sambaSamAccount',
1334 'ad' => 'user',
1335 'default' => '*'
1337 $default['user_attribute'] = array(
1338 'edir' => 'cn',
1339 'rfc2307' => 'uid',
1340 'rfc2307bis' => 'uid',
1341 'samba' => 'uid',
1342 'ad' => 'cn',
1343 'default' => 'cn'
1345 $default['memberattribute'] = array(
1346 'edir' => 'member',
1347 'rfc2307' => 'member',
1348 'rfc2307bis' => 'member',
1349 'samba' => 'member',
1350 'ad' => 'member',
1351 'default' => 'member'
1353 $default['memberattribute_isdn'] = array(
1354 'edir' => '1',
1355 'rfc2307' => '0',
1356 'rfc2307bis' => '1',
1357 'samba' => '0', //is this right?
1358 'ad' => '1',
1359 'default' => '0'
1361 $default['expireattr'] = array (
1362 'edir' => 'passwordExpirationTime',
1363 'rfc2307' => 'shadowExpire',
1364 'rfc2307bis' => 'shadowExpire',
1365 'samba' => '', //No support yet
1366 'ad' => 'pwdLastSet',
1367 'default' => ''
1369 return $default;
1373 * return binaryfields of selected usertype
1376 * @return array
1378 function ldap_getbinaryfields () {
1379 $binaryfields = array (
1380 'edir' => array('guid'),
1381 'rfc2307' => array(),
1382 'rfc2307bis' => array(),
1383 'samba' => array(),
1384 'ad' => array(),
1385 'default' => array()
1387 if (!empty($this->config->user_type)) {
1388 return $binaryfields[$this->config->user_type];
1390 else {
1391 return $binaryfields['default'];
1395 function ldap_isbinary ($field) {
1396 if (empty($field)) {
1397 return false;
1399 return array_search($field, $this->ldap_getbinaryfields());
1403 * take expirationtime and return it as unixseconds
1405 * takes expriration timestamp as readed from ldap
1406 * returns it as unix seconds
1407 * depends on $this->config->user_type variable
1409 * @param mixed time Time stamp readed from ldap as it is.
1410 * @param string $ldapconnection Just needed for Active Directory.
1411 * @param string $user_dn User distinguished name for the user we are checking password expiration (just needed for Active Directory).
1412 * @return timestamp
1414 function ldap_expirationtime2unix ($time, $ldapconnection, $user_dn) {
1415 $result = false;
1416 switch ($this->config->user_type) {
1417 case 'edir':
1418 $yr=substr($time,0,4);
1419 $mo=substr($time,4,2);
1420 $dt=substr($time,6,2);
1421 $hr=substr($time,8,2);
1422 $min=substr($time,10,2);
1423 $sec=substr($time,12,2);
1424 $result = mktime($hr,$min,$sec,$mo,$dt,$yr);
1425 break;
1426 case 'rfc2307':
1427 case 'rfc2307bis':
1428 $result = $time * DAYSECS; //The shadowExpire contains the number of DAYS between 01/01/1970 and the actual expiration date
1429 break;
1430 case 'ad':
1431 $result = $this->ldap_get_ad_pwdexpire($time, $ldapconnection, $user_dn);
1432 break;
1433 default:
1434 print_error('auth_ldap_usertypeundefined', 'auth');
1436 return $result;
1440 * takes unixtime and return it formated for storing in ldap
1442 * @param integer unix time stamp
1444 function ldap_unix2expirationtime($time) {
1445 $result = false;
1446 switch ($this->config->user_type) {
1447 case 'edir':
1448 $result=date('YmdHis', $time).'Z';
1449 break;
1450 case 'rfc2307':
1451 case 'rfc2307bis':
1452 $result = $time ; //Already in correct format
1453 break;
1454 default:
1455 print_error('auth_ldap_usertypeundefined2', 'auth');
1457 return $result;
1462 * checks if user belong to specific group(s)
1463 * or is in a subtree.
1465 * Returns true if user belongs group in grupdns string OR
1466 * if the DN of the user is in a subtree pf the DN provided
1467 * as "group"
1469 * @param mixed $username username
1470 * @param mixed $groupdns string of group dn separated by ;
1473 function ldap_isgroupmember($extusername='', $groupdns='') {
1474 // Takes username and groupdn(s) , separated by ;
1475 // Returns true if user is member of any given groups
1477 $ldapconnection = $this->ldap_connect();
1479 if (empty($extusername) or empty($groupdns)) {
1480 return false;
1483 if ($this->config->memberattribute_isdn) {
1484 $memberuser = $this->ldap_find_userdn($ldapconnection, $extusername);
1485 } else {
1486 $memberuser = $extusername;
1489 if (empty($memberuser)) {
1490 return false;
1493 $groups = explode(";",$groupdns);
1495 $result = false;
1496 foreach ($groups as $group) {
1497 $group = trim($group);
1498 if (empty($group)) {
1499 continue;
1502 // check cheaply if the user's DN sits in a subtree
1503 // of the "group" DN provided. Granted, this isn't
1504 // a proper LDAP group, but it's a popular usage.
1505 if (strpos(strrev($memberuser), strrev($group))===0) {
1506 $result = true;
1507 break;
1510 //echo "Checking group $group for member $username\n";
1511 $search = ldap_read($ldapconnection, $group, '('.$this->config->memberattribute.'='.$this->filter_addslashes($memberuser).')', array($this->config->memberattribute));
1512 if (!empty($search) and ldap_count_entries($ldapconnection, $search)) {
1513 $info = $this->ldap_get_entries($ldapconnection, $search);
1515 if (count($info) > 0 ) {
1516 // user is member of group
1517 $result = true;
1518 break;
1523 return $result;
1528 * connects to ldap server
1530 * Tries connect to specified ldap servers.
1531 * Returns connection result or error.
1533 * @return connection result
1535 function ldap_connect($binddn='',$bindpwd='') {
1536 //Select bind password, With empty values use
1537 //ldap_bind_* variables or anonymous bind if ldap_bind_* are empty
1538 if ($binddn == '' and $bindpwd == '') {
1539 if (!empty($this->config->bind_dn)) {
1540 $binddn = $this->config->bind_dn;
1542 if (!empty($this->config->bind_pw)) {
1543 $bindpwd = $this->config->bind_pw;
1547 $urls = explode(";",$this->config->host_url);
1549 foreach ($urls as $server) {
1550 $server = trim($server);
1551 if (empty($server)) {
1552 continue;
1555 $connresult = ldap_connect($server);
1556 //ldap_connect returns ALWAYS true
1558 if (!empty($this->config->version)) {
1559 ldap_set_option($connresult, LDAP_OPT_PROTOCOL_VERSION, $this->config->version);
1562 // Fix MDL-10921
1563 if ($this->config->user_type == 'ad') {
1564 ldap_set_option($connresult, LDAP_OPT_REFERRALS, 0);
1567 if (!empty($binddn)) {
1568 //bind with search-user
1569 //$debuginfo .= 'Using bind user'.$binddn.'and password:'.$bindpwd;
1570 $bindresult=ldap_bind($connresult, $binddn,$bindpwd);
1572 else {
1573 //bind anonymously
1574 $bindresult=@ldap_bind($connresult);
1577 if (!empty($this->config->opt_deref)) {
1578 ldap_set_option($connresult, LDAP_OPT_DEREF, $this->config->opt_deref);
1581 if ($bindresult) {
1582 return $connresult;
1585 $debuginfo .= "<br/>Server: '$server' <br/> Connection: '$connresult'<br/> Bind result: '$bindresult'</br>";
1588 //If any of servers are alive we have already returned connection
1589 print_error('auth_ldap_noconnect_all','auth','', $debuginfo);
1590 return false;
1594 * retuns dn of username
1596 * Search specified contexts for username and return user dn
1597 * like: cn=username,ou=suborg,o=org
1599 * @param mixed $ldapconnection $ldapconnection result
1600 * @param mixed $username username (external encoding no slashes)
1604 function ldap_find_userdn ($ldapconnection, $extusername) {
1606 //default return value
1607 $ldap_user_dn = FALSE;
1609 //get all contexts and look for first matching user
1610 $ldap_contexts = explode(";",$this->config->contexts);
1612 if (!empty($this->config->create_context)) {
1613 array_push($ldap_contexts, $this->config->create_context);
1616 foreach ($ldap_contexts as $context) {
1618 $context = trim($context);
1619 if (empty($context)) {
1620 continue;
1623 if ($this->config->search_sub) {
1624 //use ldap_search to find first user from subtree
1625 $ldap_result = ldap_search($ldapconnection, $context, "(".$this->config->user_attribute."=".$this->filter_addslashes($extusername).")",array($this->config->user_attribute));
1628 else {
1629 //search only in this context
1630 $ldap_result = ldap_list($ldapconnection, $context, "(".$this->config->user_attribute."=".$this->filter_addslashes($extusername).")",array($this->config->user_attribute));
1633 $entry = ldap_first_entry($ldapconnection,$ldap_result);
1635 if ($entry) {
1636 $ldap_user_dn = ldap_get_dn($ldapconnection, $entry);
1637 break ;
1641 return $ldap_user_dn;
1645 * retuns user attribute mappings between moodle and ldap
1647 * @return array
1650 function ldap_attributes () {
1651 $moodleattributes = array();
1652 foreach ($this->userfields as $field) {
1653 if (!empty($this->config->{"field_map_$field"})) {
1654 $moodleattributes[$field] = $this->config->{"field_map_$field"};
1655 if (preg_match('/,/',$moodleattributes[$field])) {
1656 $moodleattributes[$field] = explode(',', $moodleattributes[$field]); // split ?
1660 $moodleattributes['username'] = $this->config->user_attribute;
1661 return $moodleattributes;
1665 * return all usernames from ldap
1667 * @return array
1670 function ldap_get_userlist($filter="*") {
1671 /// returns all users from ldap servers
1672 $fresult = array();
1674 $ldapconnection = $this->ldap_connect();
1676 if ($filter=="*") {
1677 $filter = "(&(".$this->config->user_attribute."=*)(".$this->config->objectclass."))";
1680 $contexts = explode(";",$this->config->contexts);
1682 if (!empty($this->config->create_context)) {
1683 array_push($contexts, $this->config->create_context);
1686 foreach ($contexts as $context) {
1688 $context = trim($context);
1689 if (empty($context)) {
1690 continue;
1693 if ($this->config->search_sub) {
1694 //use ldap_search to find first user from subtree
1695 $ldap_result = ldap_search($ldapconnection, $context,$filter,array($this->config->user_attribute));
1697 else {
1698 //search only in this context
1699 $ldap_result = ldap_list($ldapconnection, $context,
1700 $filter,
1701 array($this->config->user_attribute));
1704 $users = $this->ldap_get_entries($ldapconnection, $ldap_result);
1706 //add found users to list
1707 for ($i=0;$i<count($users);$i++) {
1708 array_push($fresult, ($users[$i][$this->config->user_attribute][0]) );
1712 return $fresult;
1716 * return entries from ldap
1718 * Returns values like ldap_get_entries but is
1719 * binary compatible and return all attributes as array
1721 * @return array ldap-entries
1724 function ldap_get_entries($conn, $searchresult) {
1725 //Returns values like ldap_get_entries but is
1726 //binary compatible
1727 $i=0;
1728 $fresult=array();
1729 $entry = ldap_first_entry($conn, $searchresult);
1730 do {
1731 $attributes = @ldap_get_attributes($conn, $entry);
1732 for ($j=0; $j<$attributes['count']; $j++) {
1733 $values = ldap_get_values_len($conn, $entry,$attributes[$j]);
1734 if (is_array($values)) {
1735 $fresult[$i][$attributes[$j]] = $values;
1737 else {
1738 $fresult[$i][$attributes[$j]] = array($values);
1741 $i++;
1743 while ($entry = @ldap_next_entry($conn, $entry));
1744 //were done
1745 return ($fresult);
1749 * Returns true if this authentication plugin is 'internal'.
1751 * @return bool
1753 function is_internal() {
1754 return false;
1758 * Returns true if this authentication plugin can change the user's
1759 * password.
1761 * @return bool
1763 function can_change_password() {
1764 return !empty($this->config->stdchangepassword) or !empty($this->config->changepasswordurl);
1768 * Returns the URL for changing the user's pw, or empty if the default can
1769 * be used.
1771 * @return string url
1773 function change_password_url() {
1774 if (empty($this->config->stdchangepassword)) {
1775 return $this->config->changepasswordurl;
1776 } else {
1777 return '';
1782 * Will get called before the login page is shown, if NTLM SSO
1783 * is enabled, and the user is in the right network, we'll redirect
1784 * to the magic NTLM page for SSO...
1787 function loginpage_hook() {
1788 global $CFG;
1790 if ($_SERVER['REQUEST_METHOD'] === 'GET' // Only on initial GET
1791 // of loginpage
1792 &&!empty($this->config->ntlmsso_enabled)// SSO enabled
1793 && !empty($this->config->ntlmsso_subnet)// have a subnet to test for
1794 && empty($_GET['authldap_skipntlmsso']) // haven't failed it yet
1795 && (isguestuser() || !isloggedin()) // guestuser or not-logged-in users
1796 && address_in_subnet($_SERVER['REMOTE_ADDR'],$this->config->ntlmsso_subnet)) {
1797 redirect("{$CFG->wwwroot}/auth/ldap/ntlmsso_attempt.php");
1802 * To be called from a page running under NTLM's
1803 * "Integrated Windows Authentication".
1805 * If successful, it will set a special "cookie" (not an HTTP cookie!)
1806 * in cache_flags under the "auth/ldap/ntlmsess" "plugin" and return true.
1807 * The "cookie" will be picked up by ntlmsso_finish() to complete the
1808 * process.
1810 * On failure it will return false for the caller to display an appropriate
1811 * error message (probably saying that Integrated Windows Auth isn't enabled!)
1813 * NOTE that this code will execute under the OS user credentials,
1814 * so we MUST avoid dealing with files -- such as session files.
1815 * (The caller should set $nomoodlecookie before including config.php)
1818 function ntlmsso_magic($sesskey) {
1819 if (isset($_SERVER['REMOTE_USER']) && !empty($_SERVER['REMOTE_USER'])) {
1820 $username = $_SERVER['REMOTE_USER'];
1821 $username = substr(strrchr($username, '\\'), 1); //strip domain info
1822 $username = moodle_strtolower($username); //compatibility hack
1823 set_cache_flag('auth/ldap/ntlmsess', $sesskey, $username, AUTH_NTLMTIMEOUT);
1824 return true;
1826 return false;
1830 * Find the session set by ntlmsso_magic(), validate it and
1831 * call authenticate_user_login() to authenticate the user through
1832 * the auth machinery.
1834 * It is complemented by a similar check in user_login().
1836 * If it succeeds, it never returns.
1839 function ntlmsso_finish() {
1840 global $CFG, $USER, $SESSION;
1842 $key = sesskey();
1843 $cf = get_cache_flags('auth/ldap/ntlmsess');
1844 if (!isset($cf[$key]) || $cf[$key] === '') {
1845 return false;
1847 $username = $cf[$key];
1848 // Here we want to trigger the whole authentication machinery
1849 // to make sure no step is bypassed...
1850 $user = authenticate_user_login($username, $key);
1851 if ($user) {
1852 add_to_log(SITEID, 'user', 'login', "view.php?id=$USER->id&course=".SITEID,
1853 $user->id, 0, $user->id);
1854 $USER = complete_user_login($user);
1856 // Cleanup the key to prevent reuse...
1857 // and to allow re-logins with normal credentials
1858 unset_cache_flag('auth/ldap/ntlmsess', $key);
1860 /// Redirection
1861 if (user_not_fully_set_up($USER)) {
1862 $urltogo = $CFG->wwwroot.'/user/edit.php';
1863 // We don't delete $SESSION->wantsurl yet, so we get there later
1864 } else if (isset($SESSION->wantsurl) and (strpos($SESSION->wantsurl, $CFG->wwwroot) === 0)) {
1865 $urltogo = $SESSION->wantsurl; /// Because it's an address in this site
1866 unset($SESSION->wantsurl);
1867 } else {
1868 // no wantsurl stored or external - go to homepage
1869 $urltogo = $CFG->wwwroot.'/';
1870 unset($SESSION->wantsurl);
1872 redirect($urltogo);
1874 // Should never reach here.
1875 return false;
1879 * Sync roles for this user
1881 * @param $user object user object (without system magic quotes)
1883 function sync_roles($user) {
1884 $iscreator = $this->iscreator($user->username);
1885 if ($iscreator === null) {
1886 return; //nothing to sync - creators not configured
1889 if ($roles = get_roles_with_capability('moodle/legacy:coursecreator', CAP_ALLOW)) {
1890 $creatorrole = array_shift($roles); // We can only use one, let's use the first one
1891 $systemcontext = get_context_instance(CONTEXT_SYSTEM);
1893 if ($iscreator) { // Following calls will not create duplicates
1894 role_assign($creatorrole->id, $user->id, 0, $systemcontext->id, 0, 0, 0, 'ldap');
1895 } else {
1896 //unassign only if previously assigned by this plugin!
1897 role_unassign($creatorrole->id, $user->id, 0, $systemcontext->id, 'ldap');
1903 * Prints a form for configuring this authentication plugin.
1905 * This function is called from admin/auth.php, and outputs a full page with
1906 * a form for configuring this plugin.
1908 * @param array $page An object containing all the data for this page.
1910 function config_form($config, $err, $user_fields) {
1911 include 'config.html';
1915 * Processes and stores configuration data for this authentication plugin.
1917 function process_config($config) {
1918 // set to defaults if undefined
1919 if (!isset($config->host_url))
1920 { $config->host_url = ''; }
1921 if (empty($config->ldapencoding))
1922 { $config->ldapencoding = 'utf-8'; }
1923 if (!isset($config->contexts))
1924 { $config->contexts = ''; }
1925 if (!isset($config->user_type))
1926 { $config->user_type = 'default'; }
1927 if (!isset($config->user_attribute))
1928 { $config->user_attribute = ''; }
1929 if (!isset($config->search_sub))
1930 { $config->search_sub = ''; }
1931 if (!isset($config->opt_deref))
1932 { $config->opt_deref = ''; }
1933 if (!isset($config->preventpassindb))
1934 { $config->preventpassindb = 0; }
1935 if (!isset($config->bind_dn))
1936 {$config->bind_dn = ''; }
1937 if (!isset($config->bind_pw))
1938 {$config->bind_pw = ''; }
1939 if (!isset($config->version))
1940 {$config->version = '2'; }
1941 if (!isset($config->objectclass))
1942 {$config->objectclass = ''; }
1943 if (!isset($config->memberattribute))
1944 {$config->memberattribute = ''; }
1945 if (!isset($config->memberattribute_isdn))
1946 {$config->memberattribute_isdn = ''; }
1947 if (!isset($config->creators))
1948 {$config->creators = ''; }
1949 if (!isset($config->create_context))
1950 {$config->create_context = ''; }
1951 if (!isset($config->expiration))
1952 {$config->expiration = ''; }
1953 if (!isset($config->expiration_warning))
1954 {$config->expiration_warning = '10'; }
1955 if (!isset($config->expireattr))
1956 {$config->expireattr = ''; }
1957 if (!isset($config->gracelogins))
1958 {$config->gracelogins = ''; }
1959 if (!isset($config->graceattr))
1960 {$config->graceattr = ''; }
1961 if (!isset($config->auth_user_create))
1962 {$config->auth_user_create = ''; }
1963 if (!isset($config->forcechangepassword))
1964 {$config->forcechangepassword = 0; }
1965 if (!isset($config->stdchangepassword))
1966 {$config->forcechangepassword = 0; }
1967 if (!isset($config->passtype))
1968 {$config->passtype = 'plaintext'; }
1969 if (!isset($config->changepasswordurl))
1970 {$config->changepasswordurl = ''; }
1971 if (!isset($config->removeuser))
1972 {$config->removeuser = 0; }
1973 if (!isset($config->ntlmsso_enabled))
1974 {$config->ntlmsso_enabled = 0; }
1975 if (!isset($config->ntlmsso_subnet))
1976 {$config->ntlmsso_subnet = ''; }
1978 // save settings
1979 set_config('host_url', $config->host_url, 'auth/ldap');
1980 set_config('ldapencoding', $config->ldapencoding, 'auth/ldap');
1981 set_config('host_url', $config->host_url, 'auth/ldap');
1982 set_config('contexts', $config->contexts, 'auth/ldap');
1983 set_config('user_type', $config->user_type, 'auth/ldap');
1984 set_config('user_attribute', $config->user_attribute, 'auth/ldap');
1985 set_config('search_sub', $config->search_sub, 'auth/ldap');
1986 set_config('opt_deref', $config->opt_deref, 'auth/ldap');
1987 set_config('preventpassindb', $config->preventpassindb, 'auth/ldap');
1988 set_config('bind_dn', $config->bind_dn, 'auth/ldap');
1989 set_config('bind_pw', $config->bind_pw, 'auth/ldap');
1990 set_config('version', $config->version, 'auth/ldap');
1991 set_config('objectclass', $config->objectclass, 'auth/ldap');
1992 set_config('memberattribute', $config->memberattribute, 'auth/ldap');
1993 set_config('memberattribute_isdn', $config->memberattribute_isdn, 'auth/ldap');
1994 set_config('creators', $config->creators, 'auth/ldap');
1995 set_config('create_context', $config->create_context, 'auth/ldap');
1996 set_config('expiration', $config->expiration, 'auth/ldap');
1997 set_config('expiration_warning', $config->expiration_warning, 'auth/ldap');
1998 set_config('expireattr', $config->expireattr, 'auth/ldap');
1999 set_config('gracelogins', $config->gracelogins, 'auth/ldap');
2000 set_config('graceattr', $config->graceattr, 'auth/ldap');
2001 set_config('auth_user_create', $config->auth_user_create, 'auth/ldap');
2002 set_config('forcechangepassword', $config->forcechangepassword, 'auth/ldap');
2003 set_config('stdchangepassword', $config->stdchangepassword, 'auth/ldap');
2004 set_config('passtype', $config->passtype, 'auth/ldap');
2005 set_config('changepasswordurl', $config->changepasswordurl, 'auth/ldap');
2006 set_config('removeuser', $config->removeuser, 'auth/ldap');
2007 set_config('ntlmsso_enabled', (int)$config->ntlmsso_enabled, 'auth/ldap');
2008 set_config('ntlmsso_subnet', $config->ntlmsso_subnet, 'auth/ldap');
2010 return true;
2014 * Quote control characters in texts used in ldap filters - see rfc2254.txt
2016 * @param string
2018 function filter_addslashes($text) {
2019 $text = str_replace('\\', '\\5c', $text);
2020 $text = str_replace(array('*', '(', ')', "\0"),
2021 array('\\2a', '\\28', '\\29', '\\00'), $text);
2022 return $text;
2026 * Quote control characters in quoted "texts" used in ldap
2028 * @param string
2030 function ldap_addslashes($text) {
2031 $text = str_replace('\\', '\\\\', $text);
2032 $text = str_replace(array('"', "\0"),
2033 array('\\"', '\\00'), $text);
2034 return $text;
2038 * Get password expiration time for a given user from Active Directory
2040 * @param string $pwdlastset The time last time we changed the password.
2041 * @param resource $lcapconn The open LDAP connection.
2042 * @param string $user_dn The distinguished name of the user we are checking.
2044 * @return string $unixtime
2046 function ldap_get_ad_pwdexpire($pwdlastset, $ldapconn, $user_dn){
2047 define ('ROOTDSE', '');
2048 // UF_DONT_EXPIRE_PASSWD value taken from MSDN directly
2049 define ('UF_DONT_EXPIRE_PASSWD', 0x00010000);
2051 global $CFG;
2053 if (!function_exists('bcsub')) {
2054 error_log ('You need the BCMath extension to use grace logins with Active Directory');
2055 return 0;
2058 // If UF_DONT_EXPIRE_PASSWD flag is set in user's
2059 // userAccountControl attribute, the password doesn't expire.
2060 $sr = ldap_read($ldapconn, $user_dn, 'objectclass=*',
2061 array('userAccountControl'));
2062 if (!$sr) {
2063 error_log("ldap: error getting userAccountControl for $user_dn");
2064 // don't expire password, as we are not sure it has to be
2065 // expired or not.
2066 return 0;
2069 $info = $this->ldap_get_entries($ldapconn, $sr);
2070 $useraccountcontrol = $info[0]['userAccountControl'][0];
2071 if ($useraccountcontrol & UF_DONT_EXPIRE_PASSWD) {
2072 // password doesn't expire.
2073 return 0;
2076 // If pwdLastSet is zero, the user must change his/her password now
2077 // (unless UF_DONT_EXPIRE_PASSWD flag is set, but we already
2078 // tested this above)
2079 if ($pwdlastset === '0') {
2080 // password has expired
2081 return -1;
2084 // ----------------------------------------------------------------
2085 // Password expiration time in Active Directory is the composition of
2086 // two values:
2088 // - User's pwdLastSet attribute, that stores the last time
2089 // the password was changed.
2091 // - Domain's maxPwdAge attribute, that sets how long
2092 // passwords last in this domain.
2094 // We already have the first value (passed in as a parameter). We
2095 // need to get the second one. As we don't know the domain DN, we
2096 // have to query rootDSE's defaultNamingContext attribute to get
2097 // it. Then we have to query that DN's maxPwdAge attribute to get
2098 // the real value.
2100 // Once we have both values, we just need to combine them. But MS
2101 // chose to use a different base and unit for time measurements.
2102 // So we need to convert the values to Unix timestamps (see
2103 // details below).
2104 // ----------------------------------------------------------------
2106 $sr = ldap_read($ldapconn, ROOTDSE, 'objectclass=*',
2107 array('defaultNamingContext'));
2108 if (!$sr) {
2109 error_log("ldap: error querying rootDSE for Active Directory");
2110 return 0;
2113 $info = $this->ldap_get_entries($ldapconn, $sr);
2114 $domaindn = $info[0]['defaultNamingContext'][0];
2116 $sr = ldap_read ($ldapconn, $domaindn, 'objectclass=*',
2117 array('maxPwdAge'));
2118 $info = $this->ldap_get_entries($ldapconn, $sr);
2119 $maxpwdage = $info[0]['maxPwdAge'][0];
2121 // ----------------------------------------------------------------
2122 // MSDN says that "pwdLastSet contains the number of 100 nanosecond
2123 // intervals since January 1, 1601 (UTC), stored in a 64 bit integer".
2125 // According to Perl's Date::Manip, the number of seconds between
2126 // this date and Unix epoch is 11644473600. So we have to
2127 // substract this value to calculate a Unix time, once we have
2128 // scaled pwdLastSet to seconds. This is the script used to
2129 // calculate the value shown above:
2131 // #!/usr/bin/perl -w
2133 // use Date::Manip;
2135 // $date1 = ParseDate ("160101010000 UTC");
2136 // $date2 = ParseDate ("197001010000 UTC");
2137 // $delta = DateCalc($date1, $date2, \$err);
2138 // $secs = Delta_Format($delta, 0, "%st");
2139 // print "$secs \n";
2141 // MSDN also says that "maxPwdAge is stored as a large integer that
2142 // represents the number of 100 nanosecond intervals from the time
2143 // the password was set before the password expires." We also need
2144 // to scale this to seconds. Bear in mind that this value is stored
2145 // as a _negative_ quantity (at least in my AD domain).
2147 // As a last remark, if the low 32 bits of maxPwdAge are equal to 0,
2148 // the maximum password age in the domain is set to 0, which means
2149 // passwords do not expire (see
2150 // http://msdn2.microsoft.com/en-us/library/ms974598.aspx)
2152 // As the quantities involved are too big for PHP integers, we
2153 // need to use BCMath functions to work with arbitrary precision
2154 // numbers.
2155 // ----------------------------------------------------------------
2158 // If the low order 32 bits are 0, then passwords do not expire in
2159 // the domain. Just do '$maxpwdage mod 2^32' and check the result
2160 // (2^32 = 4294967296)
2161 if (bcmod ($maxpwdage, 4294967296) === '0') {
2162 return 0;
2165 // Add up pwdLastSet and maxPwdAge to get password expiration
2166 // time, in MS time units. Remember maxPwdAge is stored as a
2167 // _negative_ quantity, so we need to substract it in fact.
2168 $pwdexpire = bcsub ($pwdlastset, $maxpwdage);
2170 // Scale the result to convert it to Unix time units and return
2171 // that value.
2172 return bcsub( bcdiv($pwdexpire, '10000000'), '11644473600');