Automatic installer.php lang files by installer_builder (20070726)
[moodle-linuxchix.git] / auth / ldap / auth.php
blob6170eabcf1e141e20aa282143d50bb53bb2b770a
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);
27 require_once($CFG->libdir.'/authlib.php');
29 /**
30 * LDAP authentication plugin.
32 class auth_plugin_ldap extends auth_plugin_base {
34 /**
35 * Constructor with initialisation.
37 function auth_plugin_ldap() {
38 $this->authtype = 'ldap';
39 $this->config = get_config('auth/ldap');
40 if (empty($this->config->ldapencoding)) {
41 $this->config->ldapencoding = 'utf-8';
43 if (empty($this->config->user_type)) {
44 $this->config->user_type = 'default';
47 $default = $this->ldap_getdefaults();
49 //use defaults if values not given
50 foreach ($default as $key => $value) {
51 // watch out - 0, false are correct values too
52 if (!isset($this->config->{$key}) or $this->config->{$key} == '') {
53 $this->config->{$key} = $value[$this->config->user_type];
56 //hack prefix to objectclass
57 if (empty($this->config->objectclass)) { // Can't send empty filter
58 $this->config->objectclass='objectClass=*';
59 } else if (strpos($this->config->objectclass, 'objectClass=') !== 0) {
60 $this->config->objectclass = 'objectClass='.$this->config->objectclass;
65 /**
66 * Returns true if the username and password work and false if they are
67 * wrong or don't exist.
69 * @param string $username The username (with system magic quotes)
70 * @param string $password The password (with system magic quotes)
72 * @return bool Authentication success or failure.
74 function user_login($username, $password) {
75 if (! function_exists('ldap_bind')) {
76 print_error('auth_ldapnotinstalled','auth');
77 return false;
80 if (!$username or !$password) { // Don't allow blank usernames or passwords
81 return false;
84 $textlib = textlib_get_instance();
85 $extusername = $textlib->convert(stripslashes($username), 'utf-8', $this->config->ldapencoding);
86 $extpassword = $textlib->convert(stripslashes($password), 'utf-8', $this->config->ldapencoding);
88 $ldapconnection = $this->ldap_connect();
90 if ($ldapconnection) {
91 $ldap_user_dn = $this->ldap_find_userdn($ldapconnection, $extusername);
93 //if ldap_user_dn is empty, user does not exist
94 if (!$ldap_user_dn) {
95 ldap_close($ldapconnection);
96 return false;
99 // Try to bind with current username and password
100 $ldap_login = @ldap_bind($ldapconnection, $ldap_user_dn, $extpassword);
101 ldap_close($ldapconnection);
102 if ($ldap_login) {
103 return true;
106 else {
107 @ldap_close($ldapconnection);
108 print_error('auth_ldap_noconnect','auth',$this->config->host_url);
110 return false;
114 * reads userinformation from ldap and return it in array()
116 * Read user information from external database and returns it as array().
117 * Function should return all information available. If you are saving
118 * this information to moodle user-table you should honor syncronization flags
120 * @param string $username username (with system magic quotes)
122 * @return mixed array with no magic quotes or false on error
124 function get_userinfo($username) {
125 $textlib = textlib_get_instance();
126 $extusername = $textlib->convert(stripslashes($username), 'utf-8', $this->config->ldapencoding);
128 $ldapconnection = $this->ldap_connect();
129 $attrmap = $this->ldap_attributes();
131 $result = array();
132 $search_attribs = array();
134 foreach ($attrmap as $key=>$values) {
135 if (!is_array($values)) {
136 $values = array($values);
138 foreach ($values as $value) {
139 if (!in_array($value, $search_attribs)) {
140 array_push($search_attribs, $value);
145 $user_dn = $this->ldap_find_userdn($ldapconnection, $extusername);
147 if (!$user_info_result = ldap_read($ldapconnection, $user_dn, $this->config->objectclass, $search_attribs)) {
148 return false; // error!
150 $user_entry = $this->ldap_get_entries($ldapconnection, $user_info_result);
151 if (empty($user_entry)) {
152 return false; // entry not found
155 foreach ($attrmap as $key=>$values) {
156 if (!is_array($values)) {
157 $values = array($values);
159 $ldapval = NULL;
160 foreach ($values as $value) {
161 if ($value == 'dn') {
162 $result[$key] = $user_dn;
164 if (!array_key_exists($value, $user_entry[0])) {
165 continue; // wrong data mapping!
167 if (is_array($user_entry[0][$value])) {
168 $newval = $textlib->convert($user_entry[0][$value][0], $this->config->ldapencoding, 'utf-8');
169 } else {
170 $newval = $textlib->convert($user_entry[0][$value], $this->config->ldapencoding, 'utf-8');
172 if (!empty($newval)) { // favour ldap entries that are set
173 $ldapval = $newval;
176 if (!is_null($ldapval)) {
177 $result[$key] = $ldapval;
181 @ldap_close($ldapconnection);
182 return $result;
186 * reads userinformation from ldap and return it in an object
188 * @param string $username username (with system magic quotes)
189 * @return mixed object or false on error
191 function get_userinfo_asobj($username) {
192 $user_array = $this->get_userinfo($username);
193 if ($user_array == false) {
194 return false; //error or not found
196 $user_array = truncate_userinfo($user_array);
197 $user = new object();
198 foreach ($user_array as $key=>$value) {
199 $user->{$key} = $value;
201 return $user;
205 * returns all usernames from external database
207 * get_userlist returns all usernames from external database
209 * @return array
211 function get_userlist() {
212 return $this->ldap_get_userlist("({$this->config->user_attribute}=*)");
216 * checks if user exists on external db
218 * @param string $username (with system magic quotes)
220 function user_exists($username) {
222 $textlib = textlib_get_instance();
223 $extusername = $textlib->convert(stripslashes($username), 'utf-8', $this->config->ldapencoding);
225 //returns true if given username exist on ldap
226 $users = $this->ldap_get_userlist("({$this->config->user_attribute}=".$this->filter_addslashes($extusername).")");
227 return count($users);
231 * Creates a new user on external database.
232 * By using information in userobject
233 * Use user_exists to prevent dublicate usernames
235 * @param mixed $userobject Moodle userobject (with system magic quotes)
236 * @param mixed $plainpass Plaintext password (with system magic quotes)
238 function user_create($userobject, $plainpass) {
239 $textlib = textlib_get_instance();
240 $extusername = $textlib->convert(stripslashes($userobject->username), 'utf-8', $this->config->ldapencoding);
241 $extpassword = $textlib->convert(stripslashes($plainpass), 'utf-8', $this->config->ldapencoding);
243 switch ($this->config->passtype) {
244 case 'md5':
245 $extpassword = '{MD5}' . base64_encode(pack('H*', md5($extpassword)));
246 break;
247 case 'sha1':
248 $extpassword = '{SHA}' . base64_encode(pack('H*', sha1($extpassword)));
249 break;
250 case 'plaintext':
251 default:
252 break; // plaintext
255 $ldapconnection = $this->ldap_connect();
256 $attrmap = $this->ldap_attributes();
258 $newuser = array();
260 foreach ($attrmap as $key => $values) {
261 if (!is_array($values)) {
262 $values = array($values);
264 foreach ($values as $value) {
265 if (!empty($userobject->$key) ) {
266 $newuser[$value] = $textlib->convert(stripslashes($userobject->$key), 'utf-8', $this->config->ldapencoding);
271 //Following sets all mandatory and other forced attribute values
272 //User should be creted as login disabled untill email confirmation is processed
273 //Feel free to add your user type and send patches to paca@sci.fi to add them
274 //Moodle distribution
276 switch ($this->config->user_type) {
277 case 'edir':
278 $newuser['objectClass'] = array("inetOrgPerson","organizationalPerson","person","top");
279 $newuser['uniqueId'] = $extusername;
280 $newuser['logindisabled'] = "TRUE";
281 $newuser['userpassword'] = $extpassword;
282 $uadd = ldap_add($ldapconnection, $this->config->user_attribute.'="'.$this->ldap_addslashes($userobject->username).','.$this->config->create_context.'"', $newuser);
283 break;
284 case 'ad':
285 // User account creation is a two step process with AD. First you
286 // create the user object, then you set the password. If you try
287 // to set the password while creating the user, the operation
288 // fails.
290 // Passwords in Active Directory must be encoded as Unicode
291 // strings (UCS-2 Little Endian format) and surrounded with
292 // double quotes. See http://support.microsoft.com/?kbid=269190
293 if (!function_exists('mb_convert_encoding')) {
294 print_error ('auth_ldap_no_mbstring', 'auth');
297 // First create the user account, and mark it as disabled.
298 $newuser['objectClass'] = array('top','person','user','organizationalPerson');
299 $newuser['sAMAccountName'] = $extusername;
300 $newuser['userAccountControl'] = AUTH_AD_NORMAL_ACCOUNT |
301 AUTH_AD_ACCOUNTDISABLE;
302 $userdn = 'cn=' . $this->ldap_addslashes($extusername) .
303 ',' . $this->config->create_context;
304 if (!ldap_add($ldapconnection, $userdn, $newuser)) {
305 print_error ('auth_ldap_ad_create_req', 'auth');
308 // Now set the password
309 unset($newuser);
310 $newuser['unicodePwd'] = mb_convert_encoding('"' . $extpassword . '"',
311 "UCS-2LE", "UTF-8");
312 if(!ldap_modify($ldapconnection, $userdn, $newuser)) {
313 // Something went wrong: delete the user account and error out
314 ldap_delete ($ldapconnection, $userdn);
315 print_error ('auth_ldap_ad_create_req', 'auth');
317 $uadd = true;
318 break;
319 default:
320 print_error('auth_ldap_unsupportedusertype','auth','',$this->config->user_type);
322 ldap_close($ldapconnection);
323 return $uadd;
327 function can_reset_password() {
328 return !empty($this->config->stdchangepassword);
331 function can_signup() {
332 return (!empty($this->config->auth_user_create) and !empty($this->config->create_context));
336 * Sign up a new user ready for confirmation.
337 * Password is passed in plaintext.
339 * @param object $user new user object (with system magic quotes)
340 * @param boolean $notify print notice with link and terminate
342 function user_signup($user, $notify=true) {
343 if ($this->user_exists($user->username)) {
344 print_error('auth_ldap_user_exists', 'auth');
347 $plainslashedpassword = $user->password;
348 unset($user->password);
350 if (! $this->user_create($user, $plainslashedpassword)) {
351 print_error('auth_ldap_create_error', 'auth');
354 if (! ($user->id = insert_record('user', $user)) ) {
355 print_error('auth_emailnoinsert', 'auth');
358 $this->update_user_record($user->username);
359 update_internal_user_password($user, $plainslashedpassword);
361 if (! send_confirmation_email($user)) {
362 print_error('auth_emailnoemail', 'auth');
365 if ($notify) {
366 global $CFG;
367 $emailconfirm = get_string('emailconfirm');
368 print_header($emailconfirm, $emailconfirm, $emailconfirm);
369 notice(get_string('emailconfirmsent', '', $user->email), "$CFG->wwwroot/index.php");
370 } else {
371 return true;
376 * Returns true if plugin allows confirming of new users.
378 * @return bool
380 function can_confirm() {
381 return $this->can_signup();
385 * Confirm the new user as registered.
387 * @param string $username (with system magic quotes)
388 * @param string $confirmsecret (with system magic quotes)
390 function user_confirm($username, $confirmsecret) {
391 $user = get_complete_user_data('username', $username);
393 if (!empty($user)) {
394 if ($user->confirmed) {
395 return AUTH_CONFIRM_ALREADY;
397 } else if ($user->auth != 'ldap') {
398 return AUTH_CONFIRM_ERROR;
400 } else if ($user->secret == stripslashes($confirmsecret)) { // They have provided the secret key to get in
401 if (!$this->user_activate($username)) {
402 return AUTH_CONFIRM_FAIL;
404 if (!set_field("user", "confirmed", 1, "id", $user->id)) {
405 return AUTH_CONFIRM_FAIL;
407 if (!set_field("user", "firstaccess", time(), "id", $user->id)) {
408 return AUTH_CONFIRM_FAIL;
410 return AUTH_CONFIRM_OK;
412 } else {
413 return AUTH_CONFIRM_ERROR;
418 * return number of days to user password expires
420 * If userpassword does not expire it should return 0. If password is already expired
421 * it should return negative value.
423 * @param mixed $username username (with system magic quotes)
424 * @return integer
426 function password_expire($username) {
427 $result = 0;
429 $textlib = textlib_get_instance();
430 $extusername = $textlib->convert(stripslashes($username), 'utf-8', $this->config->ldapencoding);
432 $ldapconnection = $this->ldap_connect();
433 $user_dn = $this->ldap_find_userdn($ldapconnection, $extusername);
434 $search_attribs = array($this->config->expireattr);
435 $sr = ldap_read($ldapconnection, $user_dn, 'objectclass=*', $search_attribs);
436 if ($sr) {
437 $info = $this->ldap_get_entries($ldapconnection, $sr);
438 if (!empty ($info) and !empty($info[0][$this->config->expireattr][0])) {
439 $expiretime = $this->ldap_expirationtime2unix($info[0][$this->config->expireattr][0], $ldapconnection, $user_dn);
440 if ($expiretime != 0) {
441 $now = time();
442 if ($expiretime > $now) {
443 $result = ceil(($expiretime - $now) / DAYSECS);
445 else {
446 $result = floor(($expiretime - $now) / DAYSECS);
450 } else {
451 error_log("ldap: password_expire did't find expiration time.");
454 //error_log("ldap: password_expire user $user_dn expires in $result days!");
455 return $result;
459 * syncronizes user fron external db to moodle user table
461 * Sync is now using username attribute.
463 * Syncing users removes or suspends users that dont exists anymore in external db.
464 * Creates new users and updates coursecreator status of users.
466 * @param int $bulk_insert_records will insert $bulkinsert_records per insert statement
467 * valid only with $unsafe. increase to a couple thousand for
468 * blinding fast inserts -- but test it: you may hit mysqld's
469 * max_allowed_packet limit.
470 * @param bool $do_updates will do pull in data updates from ldap if relevant
472 function sync_users ($bulk_insert_records = 1000, $do_updates = true) {
474 global $CFG;
476 $textlib = textlib_get_instance();
478 $droptablesql = array(); /// sql commands to drop the table (because session scope could be a problem for
479 /// some persistent drivers like ODBTP (mssql) or if this function is invoked
480 /// from within a PHP application using persistent connections
481 $temptable = $CFG->prefix . 'extuser';
482 $createtemptablesql = '';
484 // configure a temp table
485 print "Configuring temp table\n";
486 switch (strtolower($CFG->dbfamily)) {
487 case 'mysql':
488 $droptablesql[] = 'DROP TEMPORARY TABLE ' . $temptable; // sql command to drop the table (because session scope could be a problem)
489 $createtemptablesql = 'CREATE TEMPORARY TABLE ' . $temptable . ' (username VARCHAR(64), PRIMARY KEY (username)) TYPE=MyISAM';
490 break;
491 case 'postgres':
492 $droptablesql[] = 'DROP TABLE ' . $temptable; // sql command to drop the table (because session scope could be a problem)
493 $bulk_insert_records = 1; // no support for multiple sets of values
494 $createtemptablesql = 'CREATE TEMPORARY TABLE '. $temptable . ' (username VARCHAR(64), PRIMARY KEY (username))';
495 break;
496 case 'mssql':
497 $temptable = '#'. $temptable; /// MSSQL temp tables begin with #
498 $droptablesql[] = 'DROP TABLE ' . $temptable; // sql command to drop the table (because session scope could be a problem)
499 $bulk_insert_records = 1; // no support for multiple sets of values
500 $createtemptablesql = 'CREATE TABLE ' . $temptable . ' (username VARCHAR(64), PRIMARY KEY (username))';
501 break;
502 case 'oracle':
503 $droptablesql[] = 'TRUNCATE TABLE ' . $temptable; // oracle requires truncate before being able to drop a temp table
504 $droptablesql[] = 'DROP TABLE ' . $temptable; // sql command to drop the table (because session scope could be a problem)
505 $bulk_insert_records = 1; // no support for multiple sets of values
506 $createtemptablesql = 'CREATE GLOBAL TEMPORARY TABLE '.$temptable.' (username VARCHAR(64), PRIMARY KEY (username)) ON COMMIT PRESERVE ROWS';
507 break;
511 execute_sql_arr($droptablesql, true, false); /// Drop temp table to avoid persistence problems later
512 echo "Creating temp table $temptable\n";
513 if(! execute_sql($createtemptablesql, false) ){
514 print "Failed to create temporary users table - aborting\n";
515 exit;
518 print "Connecting to ldap...\n";
519 $ldapconnection = $this->ldap_connect();
521 if (!$ldapconnection) {
522 @ldap_close($ldapconnection);
523 print get_string('auth_ldap_noconnect','auth',$this->config->host_url);
524 exit;
527 ////
528 //// get user's list from ldap to sql in a scalable fashion
529 ////
530 // prepare some data we'll need
531 $filter = "(&(".$this->config->user_attribute."=*)(".$this->config->objectclass."))";
533 $contexts = explode(";",$this->config->contexts);
535 if (!empty($this->config->create_context)) {
536 array_push($contexts, $this->config->create_context);
539 $fresult = array();
540 foreach ($contexts as $context) {
541 $context = trim($context);
542 if (empty($context)) {
543 continue;
545 begin_sql();
546 if ($this->config->search_sub) {
547 //use ldap_search to find first user from subtree
548 $ldap_result = ldap_search($ldapconnection, $context,
549 $filter,
550 array($this->config->user_attribute));
551 } else {
552 //search only in this context
553 $ldap_result = ldap_list($ldapconnection, $context,
554 $filter,
555 array($this->config->user_attribute));
558 if ($entry = ldap_first_entry($ldapconnection, $ldap_result)) {
559 do {
560 $value = ldap_get_values_len($ldapconnection, $entry, $this->config->user_attribute);
561 $value = $textlib->convert($value[0], $this->config->ldapencoding, 'utf-8');
562 array_push($fresult, $value);
563 if (count($fresult) >= $bulk_insert_records) {
564 $this->ldap_bulk_insert($fresult, $temptable);
565 $fresult = array();
567 } while ($entry = ldap_next_entry($ldapconnection, $entry));
569 unset($ldap_result); // free mem
571 // insert any remaining users and release mem
572 if (count($fresult)) {
573 $this->ldap_bulk_insert($fresult, $temptable);
574 $fresult = array();
576 commit_sql();
579 /// preserve our user database
580 /// if the temp table is empty, it probably means that something went wrong, exit
581 /// so as to avoid mass deletion of users; which is hard to undo
582 $count = get_record_sql('SELECT COUNT(username) AS count, 1 FROM ' . $temptable);
583 $count = $count->{'count'};
584 if ($count < 1) {
585 print "Did not get any users from LDAP -- error? -- exiting\n";
586 exit;
587 } else {
588 print "Got $count records from LDAP\n\n";
592 /// User removal
593 // find users in DB that aren't in ldap -- to be removed!
594 // this is still not as scalable (but how often do we mass delete?)
595 if (!empty($this->config->removeuser)) {
596 $sql = "SELECT u.id, u.username, u.email
597 FROM {$CFG->prefix}user u
598 LEFT JOIN $temptable e ON u.username = e.username
599 WHERE u.auth='ldap'
600 AND u.deleted=0
601 AND e.username IS NULL";
602 $remove_users = get_records_sql($sql);
604 if (!empty($remove_users)) {
605 print "User entries to remove: ". count($remove_users) . "\n";
607 begin_sql();
608 foreach ($remove_users as $user) {
609 if ($this->config->removeuser == 2) {
610 //following is copy pasted from admin/user.php
611 //maybe this should moved to function in lib/datalib.php
612 $updateuser = new object();
613 $updateuser->id = $user->id;
614 $updateuser->deleted = 1;
615 $updateuser->username = addslashes("$user->email.".time()); // Remember it just in case
616 $updateuser->email = ''; // Clear this field to free it up
617 $updateuser->idnumber = ''; // Clear this field to free it up
618 $updateuser->timemodified = time();
619 if (update_record('user', $updateuser)) {
620 delete_records('role_assignments', 'userid', $user->id); // unassign all roles
621 //copy pasted part ends
622 echo "\t"; print_string('auth_dbdeleteuser', 'auth', array($user->username, $user->id)); echo "\n";
623 } else {
624 echo "\t"; print_string('auth_dbdeleteusererror', 'auth', $user->username); echo "\n";
626 } else if ($this->config->removeuser == 1) {
627 $updateuser = new object();
628 $updateuser->id = $user->id;
629 $updateuser->auth = 'nologin';
630 if (update_record('user', $updateuser)) {
631 echo "\t"; print_string('auth_dbsuspenduser', 'auth', array($user->username, $user->id)); echo "\n";
632 } else {
633 echo "\t"; print_string('auth_dbsuspendusererror', 'auth', $user->username); echo "\n";
637 commit_sql();
638 } else {
639 print "No user entries to be removed\n";
641 unset($remove_users); // free mem!
644 /// Revive suspended users
645 if (!empty($this->config->removeuser) and $this->config->removeuser == 1) {
646 $sql = "SELECT u.id, u.username
647 FROM $temptable e, {$CFG->prefix}user u
648 WHERE e.username=u.username
649 AND u.auth='nologin'";
650 $revive_users = get_records_sql($sql);
652 if (!empty($revive_users)) {
653 print "User entries to be revived: ". count($revive_users) . "\n";
655 begin_sql();
656 foreach ($revive_users as $user) {
657 $updateuser = new object();
658 $updateuser->id = $user->id;
659 $updateuser->auth = 'ldap';
660 if (update_record('user', $updateuser)) {
661 echo "\t"; print_string('auth_dbreviveser', 'auth', array($user->username, $user->id)); echo "\n";
662 } else {
663 echo "\t"; print_string('auth_dbreviveusererror', 'auth', $user->username); echo "\n";
666 commit_sql();
667 } else {
668 print "No user entries to be revived\n";
671 unset($revive_users);
675 /// User Updates - time-consuming (optional)
676 if ($do_updates) {
677 // narrow down what fields we need to update
678 $all_keys = array_keys(get_object_vars($this->config));
679 $updatekeys = array();
680 foreach ($all_keys as $key) {
681 if (preg_match('/^field_updatelocal_(.+)$/',$key, $match)) {
682 // if we have a field to update it from
683 // and it must be updated 'onlogin' we
684 // update it on cron
685 if ( !empty($this->config->{'field_map_'.$match[1]})
686 and $this->config->{$match[0]} === 'onlogin') {
687 array_push($updatekeys, $match[1]); // the actual key name
691 // print_r($all_keys); print_r($updatekeys);
692 unset($all_keys); unset($key);
694 } else {
695 print "No updates to be done\n";
697 if ( $do_updates and !empty($updatekeys) ) { // run updates only if relevant
698 $users = get_records_sql("SELECT u.username, u.id
699 FROM {$CFG->prefix}user u
700 WHERE u.deleted=0 AND u.auth='ldap'");
701 if (!empty($users)) {
702 print "User entries to update: ". count($users). "\n";
704 $sitecontext = get_context_instance(CONTEXT_SYSTEM);
705 if (!empty($this->config->creators) and !empty($this->config->memberattribute)
706 and $roles = get_roles_with_capability('moodle/legacy:coursecreator', CAP_ALLOW)) {
707 $creatorrole = array_shift($roles); // We can only use one, let's use the first one
708 } else {
709 $creatorrole = false;
712 begin_sql();
713 $xcount = 0;
714 $maxxcount = 100;
716 foreach ($users as $user) {
717 echo "\t"; print_string('auth_dbupdatinguser', 'auth', array($user->username, $user->id));
718 if (!$this->update_user_record(addslashes($user->username), $updatekeys)) {
719 echo " - ".get_string('skipped');
721 echo "\n";
722 $xcount++;
724 // update course creators if needed
725 if ($creatorrole !== false) {
726 if ($this->iscreator($user->username)) {
727 role_assign($creatorrole->id, $user->id, 0, $sitecontext->id, 0, 0, 0, 'ldap');
728 } else {
729 role_unassign($creatorrole->id, $user->id, 0, $sitecontext->id, 'ldap');
733 if ($xcount++ > $maxxcount) {
734 commit_sql();
735 begin_sql();
736 $xcount = 0;
739 commit_sql();
740 unset($users); // free mem
742 } else { // end do updates
743 print "No updates to be done\n";
746 /// User Additions
747 // find users missing in DB that are in LDAP
748 // note that get_records_sql wants at least 2 fields returned,
749 // and gives me a nifty object I don't want.
750 // note: we do not care about deleted accounts anymore, this feature was replaced by suspending to nologin auth plugin
751 $sql = "SELECT e.username, e.username
752 FROM $temptable e LEFT JOIN {$CFG->prefix}user u ON e.username = u.username
753 WHERE u.id IS NULL";
754 $add_users = get_records_sql($sql); // get rid of the fat
756 if (!empty($add_users)) {
757 print "User entries to add: ". count($add_users). "\n";
759 $sitecontext = get_context_instance(CONTEXT_SYSTEM);
760 if (!empty($this->config->creators) and !empty($this->config->memberattribute)
761 and $roles = get_roles_with_capability('moodle/legacy:coursecreator', CAP_ALLOW)) {
762 $creatorrole = array_shift($roles); // We can only use one, let's use the first one
763 } else {
764 $creatorrole = false;
767 begin_sql();
768 foreach ($add_users as $user) {
769 $user = $this->get_userinfo_asobj(addslashes($user->username));
771 // prep a few params
772 $user->modified = time();
773 $user->confirmed = 1;
774 $user->auth = 'ldap';
775 $user->mnethostid = $CFG->mnet_localhost_id;
776 if (empty($user->lang)) {
777 $user->lang = $CFG->lang;
780 $user = addslashes_recursive($user);
782 if ($id = insert_record('user',$user)) {
783 echo "\t"; print_string('auth_dbinsertuser', 'auth', array(stripslashes($user->username), $id)); echo "\n";
784 $userobj = $this->update_user_record($user->username);
785 if (!empty($this->config->forcechangepassword)) {
786 set_user_preference('auth_forcepasswordchange', 1, $userobj->id);
788 } else {
789 echo "\t"; print_string('auth_dbinsertusererror', 'auth', $user->username); echo "\n";
792 // add course creators if needed
793 if ($creatorrole !== false and $this->iscreator(stripslashes($user->username))) {
794 role_assign($creatorrole->id, $user->id, 0, $sitecontext->id, 0, 0, 0, 'ldap');
797 commit_sql();
798 unset($add_users); // free mem
799 } else {
800 print "No users to be added\n";
802 return true;
806 * Update a local user record from an external source.
807 * This is a lighter version of the one in moodlelib -- won't do
808 * expensive ops such as enrolment.
810 * If you don't pass $updatekeys, there is a performance hit and
811 * values removed from LDAP won't be removed from moodle.
813 * @param string $username username (with system magic quotes)
815 function update_user_record($username, $updatekeys = false) {
816 global $CFG;
818 //just in case check text case
819 $username = trim(moodle_strtolower($username));
821 // get the current user record
822 $user = get_record('user', 'username', $username, 'mnethostid', $CFG->mnet_localhost_id);
823 if (empty($user)) { // trouble
824 error_log("Cannot update non-existent user: ".stripslashes($username));
825 print_error('auth_dbusernotexist','auth',$username);
826 die;
829 // Protect the userid from being overwritten
830 $userid = $user->id;
832 if ($newinfo = $this->get_userinfo($username)) {
833 $newinfo = truncate_userinfo($newinfo);
835 if (empty($updatekeys)) { // all keys? this does not support removing values
836 $updatekeys = array_keys($newinfo);
839 foreach ($updatekeys as $key) {
840 if (isset($newinfo[$key])) {
841 $value = $newinfo[$key];
842 } else {
843 $value = '';
846 if (!empty($this->config->{'field_updatelocal_' . $key})) {
847 if ($user->{$key} != $value) { // only update if it's changed
848 set_field('user', $key, addslashes($value), 'id', $userid);
852 } else {
853 return false;
855 return get_record_select('user', "id = $userid AND deleted = 0");
859 * Bulk insert in SQL's temp table
860 * @param array $users is an array of usernames
862 function ldap_bulk_insert($users, $temptable) {
864 // bulk insert -- superfast with $bulk_insert_records
865 $sql = 'INSERT INTO ' . $temptable . ' (username) VALUES ';
866 // make those values safe
867 $users = addslashes_recursive($users);
868 // join and quote the whole lot
869 $sql = $sql . "('" . implode("'),('", $users) . "')";
870 print "\t+ " . count($users) . " users\n";
871 execute_sql($sql, false);
876 * Activates (enables) user in external db so user can login to external db
878 * @param mixed $username username (with system magic quotes)
879 * @return boolen result
881 function user_activate($username) {
882 $textlib = textlib_get_instance();
883 $extusername = $textlib->convert(stripslashes($username), 'utf-8', $this->config->ldapencoding);
885 $ldapconnection = $this->ldap_connect();
887 $userdn = $this->ldap_find_userdn($ldapconnection, $extusername);
888 switch ($this->config->user_type) {
889 case 'edir':
890 $newinfo['loginDisabled']="FALSE";
891 break;
892 case 'ad':
893 // We need to unset the ACCOUNTDISABLE bit in the
894 // userAccountControl attribute ( see
895 // http://support.microsoft.com/kb/305144 )
896 $sr = ldap_read($ldapconnection, $userdn, '(objectClass=*)',
897 array('userAccountControl'));
898 $info = ldap_get_entries($ldapconnection, $sr);
899 $newinfo['userAccountControl'] = $info[0]['userAccountControl'][0]
900 & (~AUTH_AD_ACCOUNTDISABLE);
901 break;
902 default:
903 error ('auth: ldap user_activate() does not support selected usertype:"'.$this->config->user_type.'" (..yet)');
905 $result = ldap_modify($ldapconnection, $userdn, $newinfo);
906 ldap_close($ldapconnection);
907 return $result;
911 * Disables user in external db so user can't login to external db
913 * @param mixed $username username
914 * @return boolean result
916 /* function user_disable($username) {
917 $textlib = textlib_get_instance();
918 $extusername = $textlib->convert(stripslashes($username), 'utf-8', $this->config->ldapencoding);
920 $ldapconnection = $this->ldap_connect();
922 $userdn = $this->ldap_find_userdn($ldapconnection, $extusername);
923 switch ($this->config->user_type) {
924 case 'edir':
925 $newinfo['loginDisabled']="TRUE";
926 break;
927 case 'ad':
928 // We need to set the ACCOUNTDISABLE bit in the
929 // userAccountControl attribute ( see
930 // http://support.microsoft.com/kb/305144 )
931 $sr = ldap_read($ldapconnection, $userdn, '(objectClass=*)',
932 array('userAccountControl'));
933 $info = auth_ldap_get_entries($ldapconnection, $sr);
934 $newinfo['userAccountControl'] = $info[0]['userAccountControl'][0]
935 | AUTH_AD_ACCOUNTDISABLE;
936 break;
937 default:
938 error ('auth: ldap user_disable() does not support selected usertype (..yet)');
940 $result = ldap_modify($ldapconnection, $userdn, $newinfo);
941 ldap_close($ldapconnection);
942 return $result;
946 * Returns true if user should be coursecreator.
948 * @param mixed $username username (without system magic quotes)
949 * @return boolean result
951 function iscreator($username) {
952 if (empty($this->config->creators) or empty($this->config->memberattribute)) {
953 return null;
956 $textlib = textlib_get_instance();
957 $extusername = $textlib->convert($username, 'utf-8', $this->config->ldapencoding);
959 return (boolean)$this->ldap_isgroupmember($extusername, $this->config->creators);
963 * Called when the user record is updated.
964 * Modifies user in external database. It takes olduser (before changes) and newuser (after changes)
965 * conpares information saved modified information to external db.
967 * @param mixed $olduser Userobject before modifications (without system magic quotes)
968 * @param mixed $newuser Userobject new modified userobject (without system magic quotes)
969 * @return boolean result
972 function user_update($olduser, $newuser) {
974 global $USER;
976 if (isset($olduser->username) and isset($newuser->username) and $olduser->username != $newuser->username) {
977 error_log("ERROR:User renaming not allowed in LDAP");
978 return false;
981 if (isset($olduser->auth) and $olduser->auth != 'ldap') {
982 return true; // just change auth and skip update
985 $textlib = textlib_get_instance();
986 $extoldusername = $textlib->convert($olduser->username, 'utf-8', $this->config->ldapencoding);
988 $ldapconnection = $this->ldap_connect();
990 $search_attribs = array();
992 $attrmap = $this->ldap_attributes();
993 foreach ($attrmap as $key => $values) {
994 if (!is_array($values)) {
995 $values = array($values);
997 foreach ($values as $value) {
998 if (!in_array($value, $search_attribs)) {
999 array_push($search_attribs, $value);
1004 $user_dn = $this->ldap_find_userdn($ldapconnection, $extoldusername);
1006 $user_info_result = ldap_read($ldapconnection, $user_dn,
1007 $this->config->objectclass, $search_attribs);
1009 if ($user_info_result) {
1011 $user_entry = $this->ldap_get_entries($ldapconnection, $user_info_result);
1012 if (empty($user_entry)) {
1013 return false; // old user not found!
1014 } else if (count($user_entry) > 1) {
1015 trigger_error("ldap: Strange! More than one user record found in ldap. Only using the first one.");
1016 return false;
1018 $user_entry = $user_entry[0];
1020 //error_log(var_export($user_entry) . 'fpp' );
1022 foreach ($attrmap as $key => $ldapkeys) {
1023 // only process if the moodle field ($key) has changed and we
1024 // are set to update LDAP with it
1025 if (isset($olduser->$key) and isset($newuser->$key)
1026 and $olduser->$key !== $newuser->$key
1027 and !empty($this->config->{'field_updateremote_'. $key})) {
1028 // for ldap values that could be in more than one
1029 // ldap key, we will do our best to match
1030 // where they came from
1031 $ambiguous = true;
1032 $changed = false;
1033 if (!is_array($ldapkeys)) {
1034 $ldapkeys = array($ldapkeys);
1036 if (count($ldapkeys) < 2) {
1037 $ambiguous = false;
1040 $nuvalue = $textlib->convert($newuser->$key, 'utf-8', $this->config->ldapencoding);
1041 $ouvalue = $textlib->convert($olduser->$key, 'utf-8', $this->config->ldapencoding);
1043 foreach ($ldapkeys as $ldapkey) {
1044 $ldapkey = $ldapkey;
1045 $ldapvalue = $user_entry[$ldapkey][0];
1046 if (!$ambiguous) {
1047 // skip update if the values already match
1048 if ($nuvalue !== $ldapvalue) {
1049 //this might fail due to schema validation
1050 if (@ldap_modify($ldapconnection, $user_dn, array($ldapkey => $nuvalue))) {
1051 continue;
1052 } else {
1053 error_log('Error updating LDAP record. Error code: '
1054 . ldap_errno($ldapconnection) . '; Error string : '
1055 . ldap_err2str(ldap_errno($ldapconnection))
1056 . "\nKey ($key) - old moodle value: '$ouvalue' new value: '$nuvalue'");
1057 continue;
1060 } else {
1061 // ambiguous
1062 // value empty before in Moodle (and LDAP) - use 1st ldap candidate field
1063 // no need to guess
1064 if ($ouvalue === '') { // value empty before - use 1st ldap candidate
1065 //this might fail due to schema validation
1066 if (@ldap_modify($ldapconnection, $user_dn, array($ldapkey => $nuvalue))) {
1067 $changed = true;
1068 continue;
1069 } else {
1070 error_log('Error updating LDAP record. Error code: '
1071 . ldap_errno($ldapconnection) . '; Error string : '
1072 . ldap_err2str(ldap_errno($ldapconnection))
1073 . "\nKey ($key) - old moodle value: '$ouvalue' new value: '$nuvalue'");
1074 continue;
1078 // we found which ldap key to update!
1079 if ($ouvalue !== '' and $ouvalue === $ldapvalue ) {
1080 //this might fail due to schema validation
1081 if (@ldap_modify($ldapconnection, $user_dn, array($ldapkey => $nuvalue))) {
1082 $changed = true;
1083 continue;
1084 } else {
1085 error_log('Error updating LDAP record. Error code: '
1086 . ldap_errno($ldapconnection) . '; Error string : '
1087 . ldap_err2str(ldap_errno($ldapconnection))
1088 . "\nKey ($key) - old moodle value: '$ouvalue' new value: '$nuvalue'");
1089 continue;
1095 if ($ambiguous and !$changed) {
1096 error_log("Failed to update LDAP with ambiguous field $key".
1097 " old moodle value: '" . $ouvalue .
1098 "' new value '" . $nuvalue );
1102 } else {
1103 error_log("ERROR:No user found in LDAP");
1104 @ldap_close($ldapconnection);
1105 return false;
1108 @ldap_close($ldapconnection);
1110 return true;
1115 * changes userpassword in external db
1117 * called when the user password is updated.
1118 * changes userpassword in external db
1120 * @param object $user User table object (with system magic quotes)
1121 * @param string $newpassword Plaintext password (with system magic quotes)
1122 * @return boolean result
1125 function user_update_password($user, $newpassword) {
1126 /// called when the user password is updated -- it assumes it is called by an admin
1127 /// or that you've otherwise checked the user's credentials
1128 /// IMPORTANT: $newpassword must be cleartext, not crypted/md5'ed
1130 global $USER;
1131 $result = false;
1132 $username = $user->username;
1134 $textlib = textlib_get_instance();
1135 $extusername = $textlib->convert(stripslashes($username), 'utf-8', $this->config->ldapencoding);
1136 $extpassword = $textlib->convert(stripslashes($newpassword), 'utf-8', $this->config->ldapencoding);
1138 switch ($this->config->passtype) {
1139 case 'md5':
1140 $extpassword = '{MD5}' . base64_encode(pack('H*', md5($extpassword)));
1141 break;
1142 case 'sha1':
1143 $extpassword = '{SHA}' . base64_encode(pack('H*', sha1($extpassword)));
1144 break;
1145 case 'plaintext':
1146 default:
1147 break; // plaintext
1150 $ldapconnection = $this->ldap_connect();
1152 $user_dn = $this->ldap_find_userdn($ldapconnection, $extusername);
1154 if (!$user_dn) {
1155 error_log('LDAP Error in user_update_password(). No DN for: ' . stripslashes($user->username));
1156 return false;
1159 switch ($this->config->user_type) {
1160 case 'edir':
1161 //Change password
1162 $result = ldap_modify($ldapconnection, $user_dn, array('userPassword' => $extpassword));
1163 if (!$result) {
1164 error_log('LDAP Error in user_update_password(). Error code: '
1165 . ldap_errno($ldapconnection) . '; Error string : '
1166 . ldap_err2str(ldap_errno($ldapconnection)));
1168 //Update password expiration time, grace logins count
1169 $search_attribs = array($this->config->expireattr, 'passwordExpirationInterval','loginGraceLimit' );
1170 $sr = ldap_read($ldapconnection, $user_dn, 'objectclass=*', $search_attribs);
1171 if ($sr) {
1172 $info=$this->ldap_get_entries($ldapconnection, $sr);
1173 $newattrs = array();
1174 if (!empty($info[0][$this->config->expireattr][0])) {
1175 //Set expiration time only if passwordExpirationInterval is defined
1176 if (!empty($info[0]['passwordExpirationInterval'][0])) {
1177 $expirationtime = time() + $info[0]['passwordExpirationInterval'][0];
1178 $ldapexpirationtime = $this->ldap_unix2expirationtime($expirationtime);
1179 $newattrs['passwordExpirationTime'] = $ldapexpirationtime;
1182 //set gracelogin count
1183 if (!empty($info[0]['loginGraceLimit'][0])) {
1184 $newattrs['loginGraceRemaining']= $info[0]['loginGraceLimit'][0];
1187 //Store attribute changes to ldap
1188 $result = ldap_modify($ldapconnection, $user_dn, $newattrs);
1189 if (!$result) {
1190 error_log('LDAP Error in user_update_password() when modifying expirationtime and/or gracelogins. Error code: '
1191 . ldap_errno($ldapconnection) . '; Error string : '
1192 . ldap_err2str(ldap_errno($ldapconnection)));
1196 else {
1197 error_log('LDAP Error in user_update_password() when reading password expiration time. Error code: '
1198 . ldap_errno($ldapconnection) . '; Error string : '
1199 . ldap_err2str(ldap_errno($ldapconnection)));
1201 break;
1203 case 'ad':
1204 // Passwords in Active Directory must be encoded as Unicode
1205 // strings (UCS-2 Little Endian format) and surrounded with
1206 // double quotes. See http://support.microsoft.com/?kbid=269190
1207 if (!function_exists('mb_convert_encoding')) {
1208 error_log ('You need the mbstring extension to change passwords in Active Directory');
1209 return false;
1211 $extpassword = mb_convert_encoding('"'.$extpassword.'"', "UCS-2LE", $this->config->ldapencoding);
1212 $result = ldap_modify($ldapconnection, $user_dn, array('unicodePwd' => $extpassword));
1213 if (!$result) {
1214 error_log('LDAP Error in user_update_password(). Error code: '
1215 . ldap_errno($ldapconnection) . '; Error string : '
1216 . ldap_err2str(ldap_errno($ldapconnection)));
1218 break;
1220 default:
1221 $usedconnection = &$ldapconnection;
1222 // send ldap the password in cleartext, it will md5 it itself
1223 $result = ldap_modify($ldapconnection, $user_dn, array('userPassword' => $extpassword));
1224 if (!$result) {
1225 error_log('LDAP Error in user_update_password(). Error code: '
1226 . ldap_errno($ldapconnection) . '; Error string : '
1227 . ldap_err2str(ldap_errno($ldapconnection)));
1232 @ldap_close($ldapconnection);
1233 return $result;
1236 //PRIVATE FUNCTIONS starts
1237 //private functions are named as ldap_*
1240 * returns predefined usertypes
1242 * @return array of predefined usertypes
1244 function ldap_suppported_usertypes() {
1245 $types = array();
1246 $types['edir']='Novell Edirectory';
1247 $types['rfc2307']='posixAccount (rfc2307)';
1248 $types['rfc2307bis']='posixAccount (rfc2307bis)';
1249 $types['samba']='sambaSamAccount (v.3.0.7)';
1250 $types['ad']='MS ActiveDirectory';
1251 $types['default']=get_string('default');
1252 return $types;
1257 * Initializes needed variables for ldap-module
1259 * Uses names defined in ldap_supported_usertypes.
1260 * $default is first defined as:
1261 * $default['pseudoname'] = array(
1262 * 'typename1' => 'value',
1263 * 'typename2' => 'value'
1264 * ....
1265 * );
1267 * @return array of default values
1269 function ldap_getdefaults() {
1270 $default['objectclass'] = array(
1271 'edir' => 'User',
1272 'rfc2307' => 'posixAccount',
1273 'rfc2307bis' => 'posixAccount',
1274 'samba' => 'sambaSamAccount',
1275 'ad' => 'user',
1276 'default' => '*'
1278 $default['user_attribute'] = array(
1279 'edir' => 'cn',
1280 'rfc2307' => 'uid',
1281 'rfc2307bis' => 'uid',
1282 'samba' => 'uid',
1283 'ad' => 'cn',
1284 'default' => 'cn'
1286 $default['memberattribute'] = array(
1287 'edir' => 'member',
1288 'rfc2307' => 'member',
1289 'rfc2307bis' => 'member',
1290 'samba' => 'member',
1291 'ad' => 'member',
1292 'default' => 'member'
1294 $default['memberattribute_isdn'] = array(
1295 'edir' => '1',
1296 'rfc2307' => '0',
1297 'rfc2307bis' => '1',
1298 'samba' => '0', //is this right?
1299 'ad' => '1',
1300 'default' => '0'
1302 $default['expireattr'] = array (
1303 'edir' => 'passwordExpirationTime',
1304 'rfc2307' => 'shadowExpire',
1305 'rfc2307bis' => 'shadowExpire',
1306 'samba' => '', //No support yet
1307 'ad' => '', //No support yet
1308 'default' => ''
1310 return $default;
1314 * return binaryfields of selected usertype
1317 * @return array
1319 function ldap_getbinaryfields () {
1320 $binaryfields = array (
1321 'edir' => array('guid'),
1322 'rfc2307' => array(),
1323 'rfc2307bis' => array(),
1324 'samba' => array(),
1325 'ad' => array(),
1326 'default' => array()
1328 if (!empty($this->config->user_type)) {
1329 return $binaryfields[$this->config->user_type];
1331 else {
1332 return $binaryfields['default'];
1336 function ldap_isbinary ($field) {
1337 if (empty($field)) {
1338 return false;
1340 return array_search($field, $this->ldap_getbinaryfields());
1344 * take expirationtime and return it as unixseconds
1346 * takes expriration timestamp as readed from ldap
1347 * returns it as unix seconds
1348 * depends on $this->config->user_type variable
1350 * @param mixed time Time stamp readed from ldap as it is.
1351 * @param string $ldapconnection Just needed for Active Directory.
1352 * @param string $user_dn User distinguished name for the user we are checking password expiration (just needed for Active Directory).
1353 * @return timestamp
1355 function ldap_expirationtime2unix ($time, $ldapconnection, $user_dn) {
1356 $result = false;
1357 switch ($this->config->user_type) {
1358 case 'edir':
1359 $yr=substr($time,0,4);
1360 $mo=substr($time,4,2);
1361 $dt=substr($time,6,2);
1362 $hr=substr($time,8,2);
1363 $min=substr($time,10,2);
1364 $sec=substr($time,12,2);
1365 $result = mktime($hr,$min,$sec,$mo,$dt,$yr);
1366 break;
1367 case 'rfc2307':
1368 case 'rfc2307bis':
1369 $result = $time * DAYSECS; //The shadowExpire contains the number of DAYS between 01/01/1970 and the actual expiration date
1370 break;
1371 case 'ad':
1372 $result = $this->ldap_get_ad_pwdexpire($time, $ldapconnection, $user_dn);
1373 break;
1374 default:
1375 print_error('auth_ldap_usertypeundefined', 'auth');
1377 return $result;
1381 * takes unixtime and return it formated for storing in ldap
1383 * @param integer unix time stamp
1385 function ldap_unix2expirationtime($time) {
1386 $result = false;
1387 switch ($this->config->user_type) {
1388 case 'edir':
1389 $result=date('YmdHis', $time).'Z';
1390 break;
1391 case 'rfc2307':
1392 case 'rfc2307bis':
1393 $result = $time ; //Already in correct format
1394 break;
1395 default:
1396 print_error('auth_ldap_usertypeundefined2', 'auth');
1398 return $result;
1403 * checks if user belong to specific group(s)
1405 * Returns true if user belongs group in grupdns string.
1407 * @param mixed $username username
1408 * @param mixed $groupdns string of group dn separated by ;
1411 function ldap_isgroupmember($extusername='', $groupdns='') {
1412 // Takes username and groupdn(s) , separated by ;
1413 // Returns true if user is member of any given groups
1415 $ldapconnection = $this->ldap_connect();
1417 if (empty($extusername) or empty($groupdns)) {
1418 return false;
1421 if ($this->config->memberattribute_isdn) {
1422 $memberuser = $this->ldap_find_userdn($ldapconnection, $extusername);
1423 } else {
1424 $memberuser = $extusername;
1427 if (empty($memberuser)) {
1428 return false;
1431 $groups = explode(";",$groupdns);
1433 $result = false;
1434 foreach ($groups as $group) {
1435 $group = trim($group);
1436 if (empty($group)) {
1437 continue;
1439 //echo "Checking group $group for member $username\n";
1440 $search = ldap_read($ldapconnection, $group, '('.$this->config->memberattribute.'='.$this->filter_addslashes($memberuser).')', array($this->config->memberattribute));
1441 if (!empty($search) and ldap_count_entries($ldapconnection, $search)) {
1442 $info = $this->ldap_get_entries($ldapconnection, $search);
1444 if (count($info) > 0 ) {
1445 // user is member of group
1446 $result = true;
1447 break;
1452 return $result;
1457 * connects to ldap server
1459 * Tries connect to specified ldap servers.
1460 * Returns connection result or error.
1462 * @return connection result
1464 function ldap_connect($binddn='',$bindpwd='') {
1465 //Select bind password, With empty values use
1466 //ldap_bind_* variables or anonymous bind if ldap_bind_* are empty
1467 if ($binddn == '' and $bindpwd == '') {
1468 if (!empty($this->config->bind_dn)) {
1469 $binddn = $this->config->bind_dn;
1471 if (!empty($this->config->bind_pw)) {
1472 $bindpwd = $this->config->bind_pw;
1476 $urls = explode(";",$this->config->host_url);
1478 foreach ($urls as $server) {
1479 $server = trim($server);
1480 if (empty($server)) {
1481 continue;
1484 $connresult = ldap_connect($server);
1485 //ldap_connect returns ALWAYS true
1487 if (!empty($this->config->version)) {
1488 ldap_set_option($connresult, LDAP_OPT_PROTOCOL_VERSION, $this->config->version);
1491 if (!empty($binddn)) {
1492 //bind with search-user
1493 //$debuginfo .= 'Using bind user'.$binddn.'and password:'.$bindpwd;
1494 $bindresult=ldap_bind($connresult, $binddn,$bindpwd);
1496 else {
1497 //bind anonymously
1498 $bindresult=@ldap_bind($connresult);
1501 if (!empty($this->config->opt_deref)) {
1502 ldap_set_option($connresult, LDAP_OPT_DEREF, $this->config->opt_deref);
1505 if ($bindresult) {
1506 return $connresult;
1509 $debuginfo .= "<br/>Server: '$server' <br/> Connection: '$connresult'<br/> Bind result: '$bindresult'</br>";
1512 //If any of servers are alive we have already returned connection
1513 print_error('auth_ldap_noconnect_all','auth',$this->config->user_type);
1514 return false;
1518 * retuns dn of username
1520 * Search specified contexts for username and return user dn
1521 * like: cn=username,ou=suborg,o=org
1523 * @param mixed $ldapconnection $ldapconnection result
1524 * @param mixed $username username (external encoding no slashes)
1528 function ldap_find_userdn ($ldapconnection, $extusername) {
1530 //default return value
1531 $ldap_user_dn = FALSE;
1533 //get all contexts and look for first matching user
1534 $ldap_contexts = explode(";",$this->config->contexts);
1536 if (!empty($this->config->create_context)) {
1537 array_push($ldap_contexts, $this->config->create_context);
1540 foreach ($ldap_contexts as $context) {
1542 $context = trim($context);
1543 if (empty($context)) {
1544 continue;
1547 if ($this->config->search_sub) {
1548 //use ldap_search to find first user from subtree
1549 $ldap_result = ldap_search($ldapconnection, $context, "(".$this->config->user_attribute."=".$this->filter_addslashes($extusername).")",array($this->config->user_attribute));
1552 else {
1553 //search only in this context
1554 $ldap_result = ldap_list($ldapconnection, $context, "(".$this->config->user_attribute."=".$this->filter_addslashes($extusername).")",array($this->config->user_attribute));
1557 $entry = ldap_first_entry($ldapconnection,$ldap_result);
1559 if ($entry) {
1560 $ldap_user_dn = ldap_get_dn($ldapconnection, $entry);
1561 break ;
1565 return $ldap_user_dn;
1569 * retuns user attribute mappings between moodle and ldap
1571 * @return array
1574 function ldap_attributes () {
1575 $fields = array("firstname", "lastname", "email", "phone1", "phone2",
1576 "department", "address", "city", "country", "description",
1577 "idnumber", "lang" );
1578 $moodleattributes = array();
1579 foreach ($fields as $field) {
1580 if (!empty($this->config->{"field_map_$field"})) {
1581 $moodleattributes[$field] = $this->config->{"field_map_$field"};
1582 if (preg_match('/,/',$moodleattributes[$field])) {
1583 $moodleattributes[$field] = explode(',', $moodleattributes[$field]); // split ?
1587 $moodleattributes['username'] = $this->config->user_attribute;
1588 return $moodleattributes;
1592 * return all usernames from ldap
1594 * @return array
1597 function ldap_get_userlist($filter="*") {
1598 /// returns all users from ldap servers
1599 $fresult = array();
1601 $ldapconnection = $this->ldap_connect();
1603 if ($filter=="*") {
1604 $filter = "(&(".$this->config->user_attribute."=*)(".$this->config->objectclass."))";
1607 $contexts = explode(";",$this->config->contexts);
1609 if (!empty($this->config->create_context)) {
1610 array_push($contexts, $this->config->create_context);
1613 foreach ($contexts as $context) {
1615 $context = trim($context);
1616 if (empty($context)) {
1617 continue;
1620 if ($this->config->search_sub) {
1621 //use ldap_search to find first user from subtree
1622 $ldap_result = ldap_search($ldapconnection, $context,$filter,array($this->config->user_attribute));
1624 else {
1625 //search only in this context
1626 $ldap_result = ldap_list($ldapconnection, $context,
1627 $filter,
1628 array($this->config->user_attribute));
1631 $users = $this->ldap_get_entries($ldapconnection, $ldap_result);
1633 //add found users to list
1634 for ($i=0;$i<count($users);$i++) {
1635 array_push($fresult, ($users[$i][$this->config->user_attribute][0]) );
1639 return $fresult;
1643 * return entries from ldap
1645 * Returns values like ldap_get_entries but is
1646 * binary compatible and return all attributes as array
1648 * @return array ldap-entries
1651 function ldap_get_entries($conn, $searchresult) {
1652 //Returns values like ldap_get_entries but is
1653 //binary compatible
1654 $i=0;
1655 $fresult=array();
1656 $entry = ldap_first_entry($conn, $searchresult);
1657 do {
1658 $attributes = @ldap_get_attributes($conn, $entry);
1659 for ($j=0; $j<$attributes['count']; $j++) {
1660 $values = ldap_get_values_len($conn, $entry,$attributes[$j]);
1661 if (is_array($values)) {
1662 $fresult[$i][$attributes[$j]] = $values;
1664 else {
1665 $fresult[$i][$attributes[$j]] = array($values);
1668 $i++;
1670 while ($entry = @ldap_next_entry($conn, $entry));
1671 //were done
1672 return ($fresult);
1676 * Returns true if this authentication plugin is 'internal'.
1678 * @return bool
1680 function is_internal() {
1681 return false;
1685 * Returns true if this authentication plugin can change the user's
1686 * password.
1688 * @return bool
1690 function can_change_password() {
1691 return !empty($this->config->stdchangepassword) or !empty($this->config->changepasswordurl);
1695 * Returns the URL for changing the user's pw, or empty if the default can
1696 * be used.
1698 * @return string url
1700 function change_password_url() {
1701 if (empty($this->config->stdchangepassword)) {
1702 return $this->config->changepasswordurl;
1703 } else {
1704 return '';
1709 * Sync roles for this user
1711 * @param $user object user object (without system magic quotes)
1713 function sync_roles($user) {
1714 $iscreator = $this->iscreator($user->username);
1715 if ($iscreator === null) {
1716 return; //nothing to sync - creators not configured
1719 if ($roles = get_roles_with_capability('moodle/legacy:coursecreator', CAP_ALLOW)) {
1720 $creatorrole = array_shift($roles); // We can only use one, let's use the first one
1721 $systemcontext = get_context_instance(CONTEXT_SYSTEM);
1723 if ($iscreator) { // Following calls will not create duplicates
1724 role_assign($creatorrole->id, $user->id, 0, $systemcontext->id, 0, 0, 0, 'ldap');
1725 } else {
1726 //unassign only if previously assigned by this plugin!
1727 role_unassign($creatorrole->id, $user->id, 0, $systemcontext->id, 'ldap');
1733 * Prints a form for configuring this authentication plugin.
1735 * This function is called from admin/auth.php, and outputs a full page with
1736 * a form for configuring this plugin.
1738 * @param array $page An object containing all the data for this page.
1740 function config_form($config, $err, $user_fields) {
1741 include 'config.html';
1745 * Processes and stores configuration data for this authentication plugin.
1747 function process_config($config) {
1748 // set to defaults if undefined
1749 if (!isset($config->host_url))
1750 { $config->host_url = ''; }
1751 if (empty($config->ldapencoding))
1752 { $config->ldapencoding = 'utf-8'; }
1753 if (!isset($config->contexts))
1754 { $config->contexts = ''; }
1755 if (!isset($config->user_type))
1756 { $config->user_type = 'default'; }
1757 if (!isset($config->user_attribute))
1758 { $config->user_attribute = ''; }
1759 if (!isset($config->search_sub))
1760 { $config->search_sub = ''; }
1761 if (!isset($config->opt_deref))
1762 { $config->opt_deref = ''; }
1763 if (!isset($config->preventpassindb))
1764 { $config->preventpassindb = 0; }
1765 if (!isset($config->bind_dn))
1766 {$config->bind_dn = ''; }
1767 if (!isset($config->bind_pw))
1768 {$config->bind_pw = ''; }
1769 if (!isset($config->version))
1770 {$config->version = '2'; }
1771 if (!isset($config->objectclass))
1772 {$config->objectclass = ''; }
1773 if (!isset($config->memberattribute))
1774 {$config->memberattribute = ''; }
1775 if (!isset($config->memberattribute_isdn))
1776 {$config->memberattribute_isdn = ''; }
1777 if (!isset($config->creators))
1778 {$config->creators = ''; }
1779 if (!isset($config->create_context))
1780 {$config->create_context = ''; }
1781 if (!isset($config->expiration))
1782 {$config->expiration = ''; }
1783 if (!isset($config->expiration_warning))
1784 {$config->expiration_warning = '10'; }
1785 if (!isset($config->expireattr))
1786 {$config->expireattr = ''; }
1787 if (!isset($config->gracelogins))
1788 {$config->gracelogins = ''; }
1789 if (!isset($config->graceattr))
1790 {$config->graceattr = ''; }
1791 if (!isset($config->auth_user_create))
1792 {$config->auth_user_create = ''; }
1793 if (!isset($config->forcechangepassword))
1794 {$config->forcechangepassword = 0; }
1795 if (!isset($config->stdchangepassword))
1796 {$config->forcechangepassword = 0; }
1797 if (!isset($config->passtype))
1798 {$config->passtype = 'plaintext'; }
1799 if (!isset($config->changepasswordurl))
1800 {$config->changepasswordurl = ''; }
1801 if (!isset($config->removeuser))
1802 {$config->removeuser = 0; }
1804 // save settings
1805 set_config('host_url', $config->host_url, 'auth/ldap');
1806 set_config('ldapencoding', $config->ldapencoding, 'auth/ldap');
1807 set_config('host_url', $config->host_url, 'auth/ldap');
1808 set_config('contexts', $config->contexts, 'auth/ldap');
1809 set_config('user_type', $config->user_type, 'auth/ldap');
1810 set_config('user_attribute', $config->user_attribute, 'auth/ldap');
1811 set_config('search_sub', $config->search_sub, 'auth/ldap');
1812 set_config('opt_deref', $config->opt_deref, 'auth/ldap');
1813 set_config('preventpassindb', $config->preventpassindb, 'auth/ldap');
1814 set_config('bind_dn', $config->bind_dn, 'auth/ldap');
1815 set_config('bind_pw', $config->bind_pw, 'auth/ldap');
1816 set_config('version', $config->version, 'auth/ldap');
1817 set_config('objectclass', $config->objectclass, 'auth/ldap');
1818 set_config('memberattribute', $config->memberattribute, 'auth/ldap');
1819 set_config('memberattribute_isdn', $config->memberattribute_isdn, 'auth/ldap');
1820 set_config('creators', $config->creators, 'auth/ldap');
1821 set_config('create_context', $config->create_context, 'auth/ldap');
1822 set_config('expiration', $config->expiration, 'auth/ldap');
1823 set_config('expiration_warning', $config->expiration_warning, 'auth/ldap');
1824 set_config('expireattr', $config->expireattr, 'auth/ldap');
1825 set_config('gracelogins', $config->gracelogins, 'auth/ldap');
1826 set_config('graceattr', $config->graceattr, 'auth/ldap');
1827 set_config('auth_user_create', $config->auth_user_create, 'auth/ldap');
1828 set_config('forcechangepassword', $config->forcechangepassword, 'auth/ldap');
1829 set_config('stdchangepassword', $config->stdchangepassword, 'auth/ldap');
1830 set_config('passtype', $config->passtype, 'auth/ldap');
1831 set_config('changepasswordurl', $config->changepasswordurl, 'auth/ldap');
1832 set_config('removeuser', $config->removeuser, 'auth/ldap');
1834 return true;
1838 * Quote control characters in texts used in ldap filters - see rfc2254.txt
1840 * @param string
1842 function filter_addslashes($text) {
1843 $text = str_replace('\\', '\\5c', $text);
1844 $text = str_replace(array('*', '(', ')', "\0"),
1845 array('\\2a', '\\28', '\\29', '\\00'), $text);
1846 return $text;
1850 * Quote control characters in quoted "texts" used in ldap
1852 * @param string
1854 function ldap_addslashes($text) {
1855 $text = str_replace('\\', '\\\\', $text);
1856 $text = str_replace(array('"', "\0"),
1857 array('\\"', '\\00'), $text);
1858 return $text;
1862 * Get password expiration time for a given user from Active Directory
1864 * @param string $pwdlastset The time last time we changed the password.
1865 * @param resource $lcapconn The open LDAP connection.
1866 * @param string $user_dn The distinguished name of the user we are checking.
1868 * @return string $unixtime
1870 function ldap_get_ad_pwdexpire($pwdlastset, $ldapconn, $user_dn){
1871 define ('ROOTDSE', '');
1872 // UF_DONT_EXPIRE_PASSWD value taken from MSDN directly
1873 define ('UF_DONT_EXPIRE_PASSWD', 0x00010000);
1875 global $CFG;
1877 if (!function_exists('bcsub')) {
1878 error_log ('You need the BCMath extension to use grace logins with Active Directory');
1879 return 0;
1882 // If UF_DONT_EXPIRE_PASSWD flag is set in user's
1883 // userAccountControl attribute, the password doesn't expire.
1884 $sr = ldap_read($ldapconn, $user_dn, 'objectclass=*',
1885 array('userAccountControl'));
1886 if (!$sr) {
1887 error_log("ldap: error getting userAccountControl for $user_dn");
1888 // don't expire password, as we are not sure it has to be
1889 // expired or not.
1890 return 0;
1893 $info = $this->ldap_get_entries($ldapconn, $sr);
1894 $useraccountcontrol = $info[0]['userAccountControl'][0];
1895 if ($useraccountcontrol & UF_DONT_EXPIRE_PASSWD) {
1896 // password doesn't expire.
1897 return 0;
1900 // If pwdLastSet is zero, the user must change his/her password now
1901 // (unless UF_DONT_EXPIRE_PASSWD flag is set, but we already
1902 // tested this above)
1903 if ($pwdlastset === '0') {
1904 // password has expired
1905 return -1;
1908 // ----------------------------------------------------------------
1909 // Password expiration time in Active Directory is the composition of
1910 // two values:
1912 // - User's pwdLastSet attribute, that stores the last time
1913 // the password was changed.
1915 // - Domain's maxPwdAge attribute, that sets how long
1916 // passwords last in this domain.
1918 // We already have the first value (passed in as a parameter). We
1919 // need to get the second one. As we don't know the domain DN, we
1920 // have to query rootDSE's defaultNamingContext attribute to get
1921 // it. Then we have to query that DN's maxPwdAge attribute to get
1922 // the real value.
1924 // Once we have both values, we just need to combine them. But MS
1925 // chose to use a different base and unit for time measurements.
1926 // So we need to convert the values to Unix timestamps (see
1927 // details below).
1928 // ----------------------------------------------------------------
1930 $sr = ldap_read($ldapconn, ROOTDSE, 'objectclass=*',
1931 array('defaultNamingContext'));
1932 if (!$sr) {
1933 error_log("ldap: error querying rootDSE for Active Directory");
1934 return 0;
1937 $info = $this->ldap_get_entries($ldapconn, $sr);
1938 $domaindn = $info[0]['defaultNamingContext'][0];
1940 $sr = ldap_read ($ldapconn, $domaindn, 'objectclass=*',
1941 array('maxPwdAge'));
1942 $info = $this->ldap_get_entries($ldapconn, $sr);
1943 $maxpwdage = $info[0]['maxPwdAge'][0];
1945 // ----------------------------------------------------------------
1946 // MSDN says that "pwdLastSet contains the number of 100 nanosecond
1947 // intervals since January 1, 1601 (UTC), stored in a 64 bit integer".
1949 // According to Perl's Date::Manip, the number of seconds between
1950 // this date and Unix epoch is 11644473600. So we have to
1951 // substract this value to calculate a Unix time, once we have
1952 // scaled pwdLastSet to seconds. This is the script used to
1953 // calculate the value shown above:
1955 // #!/usr/bin/perl -w
1957 // use Date::Manip;
1959 // $date1 = ParseDate ("160101010000 UTC");
1960 // $date2 = ParseDate ("197001010000 UTC");
1961 // $delta = DateCalc($date1, $date2, \$err);
1962 // $secs = Delta_Format($delta, 0, "%st");
1963 // print "$secs \n";
1965 // MSDN also says that "maxPwdAge is stored as a large integer that
1966 // represents the number of 100 nanosecond intervals from the time
1967 // the password was set before the password expires." We also need
1968 // to scale this to seconds. Bear in mind that this value is stored
1969 // as a _negative_ quantity (at least in my AD domain).
1971 // As a last remark, if the low 32 bits of maxPwdAge are equal to 0,
1972 // the maximum password age in the domain is set to 0, which means
1973 // passwords do not expire (see
1974 // http://msdn2.microsoft.com/en-us/library/ms974598.aspx)
1976 // As the quantities involved are too big for PHP integers, we
1977 // need to use BCMath functions to work with arbitrary precision
1978 // numbers.
1979 // ----------------------------------------------------------------
1982 // If the low order 32 bits are 0, then passwords do not expire in
1983 // the domain. Just do '$maxpwdage mod 2^32' and check the result
1984 // (2^32 = 4294967296)
1985 if (bcmod ($maxpwdage, 4294967296) === '0') {
1986 return 0;
1989 // Add up pwdLastSet and maxPwdAge to get password expiration
1990 // time, in MS time units. Remember maxPwdAge is stored as a
1991 // _negative_ quantity, so we need to substract it in fact.
1992 $pwdexpire = bcsub ($pwdlastset, $maxpwdage);
1994 // Scale the result to convert it to Unix time units and return
1995 // that value.
1996 return bcsub( bcdiv($pwdexpire, '10000000'), '11644473600');