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');
30 * LDAP authentication plugin.
32 class auth_plugin_ldap
extends auth_plugin_base
{
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 (stripos($this->config
->objectclass
, 'objectClass=') !== 0) {
60 $this->config
->objectclass
= 'objectClass='.$this->config
->objectclass
;
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');
80 if (!$username or !$password) { // Don't allow blank usernames or passwords
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
95 ldap_close($ldapconnection);
99 // Try to bind with current username and password
100 $ldap_login = @ldap_bind
($ldapconnection, $ldap_user_dn, $extpassword);
101 ldap_close($ldapconnection);
107 @ldap_close
($ldapconnection);
108 print_error('auth_ldap_noconnect','auth',$this->config
->host_url
);
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();
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);
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');
170 $newval = $textlib->convert($user_entry[0][$value], $this->config
->ldapencoding
, 'utf-8');
172 if (!empty($newval)) { // favour ldap entries that are set
176 if (!is_null($ldapval)) {
177 $result[$key] = $ldapval;
181 @ldap_close
($ldapconnection);
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;
205 * returns all usernames from external database
207 * get_userlist returns all usernames from external database
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
) {
245 $extpassword = '{MD5}' . base64_encode(pack('H*', md5($extpassword)));
248 $extpassword = '{SHA}' . base64_encode(pack('H*', sha1($extpassword)));
255 $ldapconnection = $this->ldap_connect();
256 $attrmap = $this->ldap_attributes();
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
) {
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);
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
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
310 $newuser['unicodePwd'] = mb_convert_encoding('"' . $extpassword . '"',
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');
320 print_error('auth_ldap_unsupportedusertype','auth','',$this->config
->user_type
);
322 ldap_close($ldapconnection);
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) {
344 require_once($CFG->dirroot
.'/user/profile/lib.php');
346 if ($this->user_exists($user->username
)) {
347 print_error('auth_ldap_user_exists', 'auth');
350 $plainslashedpassword = $user->password
;
351 unset($user->password
);
353 if (! $this->user_create($user, $plainslashedpassword)) {
354 print_error('auth_ldap_create_error', 'auth');
357 if (! ($user->id
= insert_record('user', $user)) ) {
358 print_error('auth_emailnoinsert', 'auth');
361 /// Save any custom profile field information
362 profile_save_data($user);
364 $this->update_user_record($user->username
);
365 update_internal_user_password($user, $plainslashedpassword);
367 if (! send_confirmation_email($user)) {
368 print_error('auth_emailnoemail', 'auth');
373 $emailconfirm = get_string('emailconfirm');
375 $navlinks[] = array('name' => $emailconfirm, 'link' => null, 'type' => 'misc');
376 $navigation = build_navigation($navlinks);
378 print_header($emailconfirm, $emailconfirm, $navigation);
379 notice(get_string('emailconfirmsent', '', $user->email
), "$CFG->wwwroot/index.php");
386 * Returns true if plugin allows confirming of new users.
390 function can_confirm() {
391 return $this->can_signup();
395 * Confirm the new user as registered.
397 * @param string $username (with system magic quotes)
398 * @param string $confirmsecret (with system magic quotes)
400 function user_confirm($username, $confirmsecret) {
401 $user = get_complete_user_data('username', $username);
404 if ($user->confirmed
) {
405 return AUTH_CONFIRM_ALREADY
;
407 } else if ($user->auth
!= 'ldap') {
408 return AUTH_CONFIRM_ERROR
;
410 } else if ($user->secret
== stripslashes($confirmsecret)) { // They have provided the secret key to get in
411 if (!$this->user_activate($username)) {
412 return AUTH_CONFIRM_FAIL
;
414 if (!set_field("user", "confirmed", 1, "id", $user->id
)) {
415 return AUTH_CONFIRM_FAIL
;
417 if (!set_field("user", "firstaccess", time(), "id", $user->id
)) {
418 return AUTH_CONFIRM_FAIL
;
420 return AUTH_CONFIRM_OK
;
423 return AUTH_CONFIRM_ERROR
;
428 * return number of days to user password expires
430 * If userpassword does not expire it should return 0. If password is already expired
431 * it should return negative value.
433 * @param mixed $username username (with system magic quotes)
436 function password_expire($username) {
439 $textlib = textlib_get_instance();
440 $extusername = $textlib->convert(stripslashes($username), 'utf-8', $this->config
->ldapencoding
);
442 $ldapconnection = $this->ldap_connect();
443 $user_dn = $this->ldap_find_userdn($ldapconnection, $extusername);
444 $search_attribs = array($this->config
->expireattr
);
445 $sr = ldap_read($ldapconnection, $user_dn, 'objectclass=*', $search_attribs);
447 $info = $this->ldap_get_entries($ldapconnection, $sr);
448 if (!empty ($info) and !empty($info[0][$this->config
->expireattr
][0])) {
449 $expiretime = $this->ldap_expirationtime2unix($info[0][$this->config
->expireattr
][0], $ldapconnection, $user_dn);
450 if ($expiretime != 0) {
452 if ($expiretime > $now) {
453 $result = ceil(($expiretime - $now) / DAYSECS
);
456 $result = floor(($expiretime - $now) / DAYSECS
);
461 error_log("ldap: password_expire did't find expiration time.");
464 //error_log("ldap: password_expire user $user_dn expires in $result days!");
469 * syncronizes user fron external db to moodle user table
471 * Sync is now using username attribute.
473 * Syncing users removes or suspends users that dont exists anymore in external db.
474 * Creates new users and updates coursecreator status of users.
476 * @param int $bulk_insert_records will insert $bulkinsert_records per insert statement
477 * valid only with $unsafe. increase to a couple thousand for
478 * blinding fast inserts -- but test it: you may hit mysqld's
479 * max_allowed_packet limit.
480 * @param bool $do_updates will do pull in data updates from ldap if relevant
482 function sync_users ($bulk_insert_records = 1000, $do_updates = true) {
486 $textlib = textlib_get_instance();
488 $droptablesql = array(); /// sql commands to drop the table (because session scope could be a problem for
489 /// some persistent drivers like ODBTP (mssql) or if this function is invoked
490 /// from within a PHP application using persistent connections
491 $temptable = $CFG->prefix
. 'extuser';
492 $createtemptablesql = '';
494 // configure a temp table
495 print "Configuring temp table\n";
496 switch (strtolower($CFG->dbfamily
)) {
498 $droptablesql[] = 'DROP TEMPORARY TABLE ' . $temptable; // sql command to drop the table (because session scope could be a problem)
499 $createtemptablesql = 'CREATE TEMPORARY TABLE ' . $temptable . ' (username VARCHAR(64), PRIMARY KEY (username)) TYPE=MyISAM';
502 $droptablesql[] = 'DROP TABLE ' . $temptable; // sql command to drop the table (because session scope could be a problem)
503 $bulk_insert_records = 1; // no support for multiple sets of values
504 $createtemptablesql = 'CREATE TEMPORARY TABLE '. $temptable . ' (username VARCHAR(64), PRIMARY KEY (username))';
507 $temptable = '#'. $temptable; /// MSSQL temp tables begin with #
508 $droptablesql[] = 'DROP TABLE ' . $temptable; // sql command to drop the table (because session scope could be a problem)
509 $bulk_insert_records = 1; // no support for multiple sets of values
510 $createtemptablesql = 'CREATE TABLE ' . $temptable . ' (username VARCHAR(64), PRIMARY KEY (username))';
513 $droptablesql[] = 'TRUNCATE TABLE ' . $temptable; // oracle requires truncate before being able to drop a temp table
514 $droptablesql[] = 'DROP TABLE ' . $temptable; // sql command to drop the table (because session scope could be a problem)
515 $bulk_insert_records = 1; // no support for multiple sets of values
516 $createtemptablesql = 'CREATE GLOBAL TEMPORARY TABLE '.$temptable.' (username VARCHAR(64), PRIMARY KEY (username)) ON COMMIT PRESERVE ROWS';
521 execute_sql_arr($droptablesql, true, false); /// Drop temp table to avoid persistence problems later
522 echo "Creating temp table $temptable\n";
523 if(! execute_sql($createtemptablesql, false) ){
524 print "Failed to create temporary users table - aborting\n";
528 print "Connecting to ldap...\n";
529 $ldapconnection = $this->ldap_connect();
531 if (!$ldapconnection) {
532 @ldap_close
($ldapconnection);
533 print get_string('auth_ldap_noconnect','auth',$this->config
->host_url
);
538 //// get user's list from ldap to sql in a scalable fashion
540 // prepare some data we'll need
541 $filter = "(&(".$this->config
->user_attribute
."=*)(".$this->config
->objectclass
."))";
543 $contexts = explode(";",$this->config
->contexts
);
545 if (!empty($this->config
->create_context
)) {
546 array_push($contexts, $this->config
->create_context
);
550 foreach ($contexts as $context) {
551 $context = trim($context);
552 if (empty($context)) {
556 if ($this->config
->search_sub
) {
557 //use ldap_search to find first user from subtree
558 $ldap_result = ldap_search($ldapconnection, $context,
560 array($this->config
->user_attribute
));
562 //search only in this context
563 $ldap_result = ldap_list($ldapconnection, $context,
565 array($this->config
->user_attribute
));
568 if ($entry = ldap_first_entry($ldapconnection, $ldap_result)) {
570 $value = ldap_get_values_len($ldapconnection, $entry, $this->config
->user_attribute
);
571 $value = $textlib->convert($value[0], $this->config
->ldapencoding
, 'utf-8');
572 array_push($fresult, $value);
573 if (count($fresult) >= $bulk_insert_records) {
574 $this->ldap_bulk_insert($fresult, $temptable);
577 } while ($entry = ldap_next_entry($ldapconnection, $entry));
579 unset($ldap_result); // free mem
581 // insert any remaining users and release mem
582 if (count($fresult)) {
583 $this->ldap_bulk_insert($fresult, $temptable);
589 /// preserve our user database
590 /// if the temp table is empty, it probably means that something went wrong, exit
591 /// so as to avoid mass deletion of users; which is hard to undo
592 $count = get_record_sql('SELECT COUNT(username) AS count, 1 FROM ' . $temptable);
593 $count = $count->{'count'};
595 print "Did not get any users from LDAP -- error? -- exiting\n";
598 print "Got $count records from LDAP\n\n";
603 // find users in DB that aren't in ldap -- to be removed!
604 // this is still not as scalable (but how often do we mass delete?)
605 if (!empty($this->config
->removeuser
)) {
606 $sql = "SELECT u.id, u.username, u.email
607 FROM {$CFG->prefix}user u
608 LEFT JOIN $temptable e ON u.username = e.username
611 AND e.username IS NULL";
612 $remove_users = get_records_sql($sql);
614 if (!empty($remove_users)) {
615 print "User entries to remove: ". count($remove_users) . "\n";
617 foreach ($remove_users as $user) {
618 if ($this->config
->removeuser
== 2) {
619 if (delete_user($user)) {
620 echo "\t"; print_string('auth_dbdeleteuser', 'auth', array($user->username
, $user->id
)); echo "\n";
622 echo "\t"; print_string('auth_dbdeleteusererror', 'auth', $user->username
); echo "\n";
624 } else if ($this->config
->removeuser
== 1) {
625 $updateuser = new object();
626 $updateuser->id
= $user->id
;
627 $updateuser->auth
= 'nologin';
628 if (update_record('user', $updateuser)) {
629 echo "\t"; print_string('auth_dbsuspenduser', 'auth', array($user->username
, $user->id
)); echo "\n";
631 echo "\t"; print_string('auth_dbsuspendusererror', 'auth', $user->username
); echo "\n";
636 print "No user entries to be removed\n";
638 unset($remove_users); // free mem!
641 /// Revive suspended users
642 if (!empty($this->config
->removeuser
) and $this->config
->removeuser
== 1) {
643 $sql = "SELECT u.id, u.username
644 FROM $temptable e, {$CFG->prefix}user u
645 WHERE e.username=u.username
646 AND u.auth='nologin'";
647 $revive_users = get_records_sql($sql);
649 if (!empty($revive_users)) {
650 print "User entries to be revived: ". count($revive_users) . "\n";
653 foreach ($revive_users as $user) {
654 $updateuser = new object();
655 $updateuser->id
= $user->id
;
656 $updateuser->auth
= 'ldap';
657 if (update_record('user', $updateuser)) {
658 echo "\t"; print_string('auth_dbreviveser', 'auth', array($user->username
, $user->id
)); echo "\n";
660 echo "\t"; print_string('auth_dbreviveusererror', 'auth', $user->username
); echo "\n";
665 print "No user entries to be revived\n";
668 unset($revive_users);
672 /// User Updates - time-consuming (optional)
674 // narrow down what fields we need to update
675 $all_keys = array_keys(get_object_vars($this->config
));
676 $updatekeys = array();
677 foreach ($all_keys as $key) {
678 if (preg_match('/^field_updatelocal_(.+)$/',$key, $match)) {
679 // if we have a field to update it from
680 // and it must be updated 'onlogin' we
682 if ( !empty($this->config
->{'field_map_'.$match[1]})
683 and $this->config
->{$match[0]} === 'onlogin') {
684 array_push($updatekeys, $match[1]); // the actual key name
688 // print_r($all_keys); print_r($updatekeys);
689 unset($all_keys); unset($key);
692 print "No updates to be done\n";
694 if ( $do_updates and !empty($updatekeys) ) { // run updates only if relevant
695 $users = get_records_sql("SELECT u.username, u.id
696 FROM {$CFG->prefix}user u
697 WHERE u.deleted=0 AND u.auth='ldap'");
698 if (!empty($users)) {
699 print "User entries to update: ". count($users). "\n";
701 $sitecontext = get_context_instance(CONTEXT_SYSTEM
);
702 if (!empty($this->config
->creators
) and !empty($this->config
->memberattribute
)
703 and $roles = get_roles_with_capability('moodle/legacy:coursecreator', CAP_ALLOW
)) {
704 $creatorrole = array_shift($roles); // We can only use one, let's use the first one
706 $creatorrole = false;
713 foreach ($users as $user) {
714 echo "\t"; print_string('auth_dbupdatinguser', 'auth', array($user->username
, $user->id
));
715 if (!$this->update_user_record(addslashes($user->username
), $updatekeys)) {
716 echo " - ".get_string('skipped');
721 // update course creators if needed
722 if ($creatorrole !== false) {
723 if ($this->iscreator($user->username
)) {
724 role_assign($creatorrole->id
, $user->id
, 0, $sitecontext->id
, 0, 0, 0, 'ldap');
726 role_unassign($creatorrole->id
, $user->id
, 0, $sitecontext->id
, 'ldap');
730 if ($xcount++
> $maxxcount) {
737 unset($users); // free mem
739 } else { // end do updates
740 print "No updates to be done\n";
744 // find users missing in DB that are in LDAP
745 // note that get_records_sql wants at least 2 fields returned,
746 // and gives me a nifty object I don't want.
747 // note: we do not care about deleted accounts anymore, this feature was replaced by suspending to nologin auth plugin
748 $sql = "SELECT e.username, e.username
749 FROM $temptable e LEFT JOIN {$CFG->prefix}user u ON e.username = u.username
751 $add_users = get_records_sql($sql); // get rid of the fat
753 if (!empty($add_users)) {
754 print "User entries to add: ". count($add_users). "\n";
756 $sitecontext = get_context_instance(CONTEXT_SYSTEM
);
757 if (!empty($this->config
->creators
) and !empty($this->config
->memberattribute
)
758 and $roles = get_roles_with_capability('moodle/legacy:coursecreator', CAP_ALLOW
)) {
759 $creatorrole = array_shift($roles); // We can only use one, let's use the first one
761 $creatorrole = false;
765 foreach ($add_users as $user) {
766 $user = $this->get_userinfo_asobj(addslashes($user->username
));
769 $user->modified
= time();
770 $user->confirmed
= 1;
771 $user->auth
= 'ldap';
772 $user->mnethostid
= $CFG->mnet_localhost_id
;
773 if (empty($user->lang
)) {
774 $user->lang
= $CFG->lang
;
777 $user = addslashes_recursive($user);
779 if ($id = insert_record('user',$user)) {
780 echo "\t"; print_string('auth_dbinsertuser', 'auth', array(stripslashes($user->username
), $id)); echo "\n";
781 $userobj = $this->update_user_record($user->username
);
782 if (!empty($this->config
->forcechangepassword
)) {
783 set_user_preference('auth_forcepasswordchange', 1, $userobj->id
);
786 echo "\t"; print_string('auth_dbinsertusererror', 'auth', $user->username
); echo "\n";
789 // add course creators if needed
790 if ($creatorrole !== false and $this->iscreator(stripslashes($user->username
))) {
791 role_assign($creatorrole->id
, $user->id
, 0, $sitecontext->id
, 0, 0, 0, 'ldap');
795 unset($add_users); // free mem
797 print "No users to be added\n";
803 * Update a local user record from an external source.
804 * This is a lighter version of the one in moodlelib -- won't do
805 * expensive ops such as enrolment.
807 * If you don't pass $updatekeys, there is a performance hit and
808 * values removed from LDAP won't be removed from moodle.
810 * @param string $username username (with system magic quotes)
812 function update_user_record($username, $updatekeys = false) {
815 //just in case check text case
816 $username = trim(moodle_strtolower($username));
818 // get the current user record
819 $user = get_record('user', 'username', $username, 'mnethostid', $CFG->mnet_localhost_id
);
820 if (empty($user)) { // trouble
821 error_log("Cannot update non-existent user: ".stripslashes($username));
822 print_error('auth_dbusernotexist','auth',$username);
826 // Protect the userid from being overwritten
829 if ($newinfo = $this->get_userinfo($username)) {
830 $newinfo = truncate_userinfo($newinfo);
832 if (empty($updatekeys)) { // all keys? this does not support removing values
833 $updatekeys = array_keys($newinfo);
836 foreach ($updatekeys as $key) {
837 if (isset($newinfo[$key])) {
838 $value = $newinfo[$key];
843 if (!empty($this->config
->{'field_updatelocal_' . $key})) {
844 if ($user->{$key} != $value) { // only update if it's changed
845 set_field('user', $key, addslashes($value), 'id', $userid);
852 return get_record_select('user', "id = $userid AND deleted = 0");
856 * Bulk insert in SQL's temp table
857 * @param array $users is an array of usernames
859 function ldap_bulk_insert($users, $temptable) {
861 // bulk insert -- superfast with $bulk_insert_records
862 $sql = 'INSERT INTO ' . $temptable . ' (username) VALUES ';
863 // make those values safe
864 $users = addslashes_recursive($users);
865 // join and quote the whole lot
866 $sql = $sql . "('" . implode("'),('", $users) . "')";
867 print "\t+ " . count($users) . " users\n";
868 execute_sql($sql, false);
873 * Activates (enables) user in external db so user can login to external db
875 * @param mixed $username username (with system magic quotes)
876 * @return boolen result
878 function user_activate($username) {
879 $textlib = textlib_get_instance();
880 $extusername = $textlib->convert(stripslashes($username), 'utf-8', $this->config
->ldapencoding
);
882 $ldapconnection = $this->ldap_connect();
884 $userdn = $this->ldap_find_userdn($ldapconnection, $extusername);
885 switch ($this->config
->user_type
) {
887 $newinfo['loginDisabled']="FALSE";
890 // We need to unset the ACCOUNTDISABLE bit in the
891 // userAccountControl attribute ( see
892 // http://support.microsoft.com/kb/305144 )
893 $sr = ldap_read($ldapconnection, $userdn, '(objectClass=*)',
894 array('userAccountControl'));
895 $info = ldap_get_entries($ldapconnection, $sr);
896 $newinfo['userAccountControl'] = $info[0]['userAccountControl'][0]
897 & (~AUTH_AD_ACCOUNTDISABLE
);
900 error ('auth: ldap user_activate() does not support selected usertype:"'.$this->config
->user_type
.'" (..yet)');
902 $result = ldap_modify($ldapconnection, $userdn, $newinfo);
903 ldap_close($ldapconnection);
908 * Disables user in external db so user can't login to external db
910 * @param mixed $username username
911 * @return boolean result
913 /* function user_disable($username) {
914 $textlib = textlib_get_instance();
915 $extusername = $textlib->convert(stripslashes($username), 'utf-8', $this->config->ldapencoding);
917 $ldapconnection = $this->ldap_connect();
919 $userdn = $this->ldap_find_userdn($ldapconnection, $extusername);
920 switch ($this->config->user_type) {
922 $newinfo['loginDisabled']="TRUE";
925 // We need to set the ACCOUNTDISABLE bit in the
926 // userAccountControl attribute ( see
927 // http://support.microsoft.com/kb/305144 )
928 $sr = ldap_read($ldapconnection, $userdn, '(objectClass=*)',
929 array('userAccountControl'));
930 $info = auth_ldap_get_entries($ldapconnection, $sr);
931 $newinfo['userAccountControl'] = $info[0]['userAccountControl'][0]
932 | AUTH_AD_ACCOUNTDISABLE;
935 error ('auth: ldap user_disable() does not support selected usertype (..yet)');
937 $result = ldap_modify($ldapconnection, $userdn, $newinfo);
938 ldap_close($ldapconnection);
943 * Returns true if user should be coursecreator.
945 * @param mixed $username username (without system magic quotes)
946 * @return boolean result
948 function iscreator($username) {
949 if (empty($this->config
->creators
) or empty($this->config
->memberattribute
)) {
953 $textlib = textlib_get_instance();
954 $extusername = $textlib->convert($username, 'utf-8', $this->config
->ldapencoding
);
956 return (boolean
)$this->ldap_isgroupmember($extusername, $this->config
->creators
);
960 * Called when the user record is updated.
961 * Modifies user in external database. It takes olduser (before changes) and newuser (after changes)
962 * conpares information saved modified information to external db.
964 * @param mixed $olduser Userobject before modifications (without system magic quotes)
965 * @param mixed $newuser Userobject new modified userobject (without system magic quotes)
966 * @return boolean result
969 function user_update($olduser, $newuser) {
973 if (isset($olduser->username
) and isset($newuser->username
) and $olduser->username
!= $newuser->username
) {
974 error_log("ERROR:User renaming not allowed in LDAP");
978 if (isset($olduser->auth
) and $olduser->auth
!= 'ldap') {
979 return true; // just change auth and skip update
982 $textlib = textlib_get_instance();
983 $extoldusername = $textlib->convert($olduser->username
, 'utf-8', $this->config
->ldapencoding
);
985 $ldapconnection = $this->ldap_connect();
987 $search_attribs = array();
989 $attrmap = $this->ldap_attributes();
990 foreach ($attrmap as $key => $values) {
991 if (!is_array($values)) {
992 $values = array($values);
994 foreach ($values as $value) {
995 if (!in_array($value, $search_attribs)) {
996 array_push($search_attribs, $value);
1001 $user_dn = $this->ldap_find_userdn($ldapconnection, $extoldusername);
1003 $user_info_result = ldap_read($ldapconnection, $user_dn,
1004 $this->config
->objectclass
, $search_attribs);
1006 if ($user_info_result) {
1008 $user_entry = $this->ldap_get_entries($ldapconnection, $user_info_result);
1009 if (empty($user_entry)) {
1010 return false; // old user not found!
1011 } else if (count($user_entry) > 1) {
1012 trigger_error("ldap: Strange! More than one user record found in ldap. Only using the first one.");
1015 $user_entry = $user_entry[0];
1017 //error_log(var_export($user_entry) . 'fpp' );
1019 foreach ($attrmap as $key => $ldapkeys) {
1020 // only process if the moodle field ($key) has changed and we
1021 // are set to update LDAP with it
1022 if (isset($olduser->$key) and isset($newuser->$key)
1023 and $olduser->$key !== $newuser->$key
1024 and !empty($this->config
->{'field_updateremote_'. $key})) {
1025 // for ldap values that could be in more than one
1026 // ldap key, we will do our best to match
1027 // where they came from
1030 if (!is_array($ldapkeys)) {
1031 $ldapkeys = array($ldapkeys);
1033 if (count($ldapkeys) < 2) {
1037 $nuvalue = $textlib->convert($newuser->$key, 'utf-8', $this->config
->ldapencoding
);
1038 $ouvalue = $textlib->convert($olduser->$key, 'utf-8', $this->config
->ldapencoding
);
1040 foreach ($ldapkeys as $ldapkey) {
1041 $ldapkey = $ldapkey;
1042 $ldapvalue = $user_entry[$ldapkey][0];
1044 // skip update if the values already match
1045 if ($nuvalue !== $ldapvalue) {
1046 //this might fail due to schema validation
1047 if (@ldap_modify
($ldapconnection, $user_dn, array($ldapkey => $nuvalue))) {
1050 error_log('Error updating LDAP record. Error code: '
1051 . ldap_errno($ldapconnection) . '; Error string : '
1052 . ldap_err2str(ldap_errno($ldapconnection))
1053 . "\nKey ($key) - old moodle value: '$ouvalue' new value: '$nuvalue'");
1059 // value empty before in Moodle (and LDAP) - use 1st ldap candidate field
1061 if ($ouvalue === '') { // value empty before - use 1st ldap candidate
1062 //this might fail due to schema validation
1063 if (@ldap_modify
($ldapconnection, $user_dn, array($ldapkey => $nuvalue))) {
1067 error_log('Error updating LDAP record. Error code: '
1068 . ldap_errno($ldapconnection) . '; Error string : '
1069 . ldap_err2str(ldap_errno($ldapconnection))
1070 . "\nKey ($key) - old moodle value: '$ouvalue' new value: '$nuvalue'");
1075 // we found which ldap key to update!
1076 if ($ouvalue !== '' and $ouvalue === $ldapvalue ) {
1077 //this might fail due to schema validation
1078 if (@ldap_modify
($ldapconnection, $user_dn, array($ldapkey => $nuvalue))) {
1082 error_log('Error updating LDAP record. Error code: '
1083 . ldap_errno($ldapconnection) . '; Error string : '
1084 . ldap_err2str(ldap_errno($ldapconnection))
1085 . "\nKey ($key) - old moodle value: '$ouvalue' new value: '$nuvalue'");
1092 if ($ambiguous and !$changed) {
1093 error_log("Failed to update LDAP with ambiguous field $key".
1094 " old moodle value: '" . $ouvalue .
1095 "' new value '" . $nuvalue );
1100 error_log("ERROR:No user found in LDAP");
1101 @ldap_close
($ldapconnection);
1105 @ldap_close
($ldapconnection);
1112 * changes userpassword in external db
1114 * called when the user password is updated.
1115 * changes userpassword in external db
1117 * @param object $user User table object (with system magic quotes)
1118 * @param string $newpassword Plaintext password (with system magic quotes)
1119 * @return boolean result
1122 function user_update_password($user, $newpassword) {
1123 /// called when the user password is updated -- it assumes it is called by an admin
1124 /// or that you've otherwise checked the user's credentials
1125 /// IMPORTANT: $newpassword must be cleartext, not crypted/md5'ed
1129 $username = $user->username
;
1131 $textlib = textlib_get_instance();
1132 $extusername = $textlib->convert(stripslashes($username), 'utf-8', $this->config
->ldapencoding
);
1133 $extpassword = $textlib->convert(stripslashes($newpassword), 'utf-8', $this->config
->ldapencoding
);
1135 switch ($this->config
->passtype
) {
1137 $extpassword = '{MD5}' . base64_encode(pack('H*', md5($extpassword)));
1140 $extpassword = '{SHA}' . base64_encode(pack('H*', sha1($extpassword)));
1147 $ldapconnection = $this->ldap_connect();
1149 $user_dn = $this->ldap_find_userdn($ldapconnection, $extusername);
1152 error_log('LDAP Error in user_update_password(). No DN for: ' . stripslashes($user->username
));
1156 switch ($this->config
->user_type
) {
1159 $result = ldap_modify($ldapconnection, $user_dn, array('userPassword' => $extpassword));
1161 error_log('LDAP Error in user_update_password(). Error code: '
1162 . ldap_errno($ldapconnection) . '; Error string : '
1163 . ldap_err2str(ldap_errno($ldapconnection)));
1165 //Update password expiration time, grace logins count
1166 $search_attribs = array($this->config
->expireattr
, 'passwordExpirationInterval','loginGraceLimit' );
1167 $sr = ldap_read($ldapconnection, $user_dn, 'objectclass=*', $search_attribs);
1169 $info=$this->ldap_get_entries($ldapconnection, $sr);
1170 $newattrs = array();
1171 if (!empty($info[0][$this->config
->expireattr
][0])) {
1172 //Set expiration time only if passwordExpirationInterval is defined
1173 if (!empty($info[0]['passwordExpirationInterval'][0])) {
1174 $expirationtime = time() +
$info[0]['passwordExpirationInterval'][0];
1175 $ldapexpirationtime = $this->ldap_unix2expirationtime($expirationtime);
1176 $newattrs['passwordExpirationTime'] = $ldapexpirationtime;
1179 //set gracelogin count
1180 if (!empty($info[0]['loginGraceLimit'][0])) {
1181 $newattrs['loginGraceRemaining']= $info[0]['loginGraceLimit'][0];
1184 //Store attribute changes to ldap
1185 $result = ldap_modify($ldapconnection, $user_dn, $newattrs);
1187 error_log('LDAP Error in user_update_password() when modifying expirationtime and/or gracelogins. Error code: '
1188 . ldap_errno($ldapconnection) . '; Error string : '
1189 . ldap_err2str(ldap_errno($ldapconnection)));
1194 error_log('LDAP Error in user_update_password() when reading password expiration time. Error code: '
1195 . ldap_errno($ldapconnection) . '; Error string : '
1196 . ldap_err2str(ldap_errno($ldapconnection)));
1201 // Passwords in Active Directory must be encoded as Unicode
1202 // strings (UCS-2 Little Endian format) and surrounded with
1203 // double quotes. See http://support.microsoft.com/?kbid=269190
1204 if (!function_exists('mb_convert_encoding')) {
1205 error_log ('You need the mbstring extension to change passwords in Active Directory');
1208 $extpassword = mb_convert_encoding('"'.$extpassword.'"', "UCS-2LE", $this->config
->ldapencoding
);
1209 $result = ldap_modify($ldapconnection, $user_dn, array('unicodePwd' => $extpassword));
1211 error_log('LDAP Error in user_update_password(). Error code: '
1212 . ldap_errno($ldapconnection) . '; Error string : '
1213 . ldap_err2str(ldap_errno($ldapconnection)));
1218 $usedconnection = &$ldapconnection;
1219 // send ldap the password in cleartext, it will md5 it itself
1220 $result = ldap_modify($ldapconnection, $user_dn, array('userPassword' => $extpassword));
1222 error_log('LDAP Error in user_update_password(). Error code: '
1223 . ldap_errno($ldapconnection) . '; Error string : '
1224 . ldap_err2str(ldap_errno($ldapconnection)));
1229 @ldap_close
($ldapconnection);
1233 //PRIVATE FUNCTIONS starts
1234 //private functions are named as ldap_*
1237 * returns predefined usertypes
1239 * @return array of predefined usertypes
1241 function ldap_suppported_usertypes() {
1243 $types['edir']='Novell Edirectory';
1244 $types['rfc2307']='posixAccount (rfc2307)';
1245 $types['rfc2307bis']='posixAccount (rfc2307bis)';
1246 $types['samba']='sambaSamAccount (v.3.0.7)';
1247 $types['ad']='MS ActiveDirectory';
1248 $types['default']=get_string('default');
1254 * Initializes needed variables for ldap-module
1256 * Uses names defined in ldap_supported_usertypes.
1257 * $default is first defined as:
1258 * $default['pseudoname'] = array(
1259 * 'typename1' => 'value',
1260 * 'typename2' => 'value'
1264 * @return array of default values
1266 function ldap_getdefaults() {
1267 $default['objectclass'] = array(
1269 'rfc2307' => 'posixAccount',
1270 'rfc2307bis' => 'posixAccount',
1271 'samba' => 'sambaSamAccount',
1275 $default['user_attribute'] = array(
1278 'rfc2307bis' => 'uid',
1283 $default['memberattribute'] = array(
1285 'rfc2307' => 'member',
1286 'rfc2307bis' => 'member',
1287 'samba' => 'member',
1289 'default' => 'member'
1291 $default['memberattribute_isdn'] = array(
1294 'rfc2307bis' => '1',
1295 'samba' => '0', //is this right?
1299 $default['expireattr'] = array (
1300 'edir' => 'passwordExpirationTime',
1301 'rfc2307' => 'shadowExpire',
1302 'rfc2307bis' => 'shadowExpire',
1303 'samba' => '', //No support yet
1304 'ad' => '', //No support yet
1311 * return binaryfields of selected usertype
1316 function ldap_getbinaryfields () {
1317 $binaryfields = array (
1318 'edir' => array('guid'),
1319 'rfc2307' => array(),
1320 'rfc2307bis' => array(),
1323 'default' => array()
1325 if (!empty($this->config
->user_type
)) {
1326 return $binaryfields[$this->config
->user_type
];
1329 return $binaryfields['default'];
1333 function ldap_isbinary ($field) {
1334 if (empty($field)) {
1337 return array_search($field, $this->ldap_getbinaryfields());
1341 * take expirationtime and return it as unixseconds
1343 * takes expriration timestamp as readed from ldap
1344 * returns it as unix seconds
1345 * depends on $this->config->user_type variable
1347 * @param mixed time Time stamp readed from ldap as it is.
1348 * @param string $ldapconnection Just needed for Active Directory.
1349 * @param string $user_dn User distinguished name for the user we are checking password expiration (just needed for Active Directory).
1352 function ldap_expirationtime2unix ($time, $ldapconnection, $user_dn) {
1354 switch ($this->config
->user_type
) {
1356 $yr=substr($time,0,4);
1357 $mo=substr($time,4,2);
1358 $dt=substr($time,6,2);
1359 $hr=substr($time,8,2);
1360 $min=substr($time,10,2);
1361 $sec=substr($time,12,2);
1362 $result = mktime($hr,$min,$sec,$mo,$dt,$yr);
1366 $result = $time * DAYSECS
; //The shadowExpire contains the number of DAYS between 01/01/1970 and the actual expiration date
1369 $result = $this->ldap_get_ad_pwdexpire($time, $ldapconnection, $user_dn);
1372 print_error('auth_ldap_usertypeundefined', 'auth');
1378 * takes unixtime and return it formated for storing in ldap
1380 * @param integer unix time stamp
1382 function ldap_unix2expirationtime($time) {
1384 switch ($this->config
->user_type
) {
1386 $result=date('YmdHis', $time).'Z';
1390 $result = $time ; //Already in correct format
1393 print_error('auth_ldap_usertypeundefined2', 'auth');
1400 * checks if user belong to specific group(s)
1402 * Returns true if user belongs group in grupdns string.
1404 * @param mixed $username username
1405 * @param mixed $groupdns string of group dn separated by ;
1408 function ldap_isgroupmember($extusername='', $groupdns='') {
1409 // Takes username and groupdn(s) , separated by ;
1410 // Returns true if user is member of any given groups
1412 $ldapconnection = $this->ldap_connect();
1414 if (empty($extusername) or empty($groupdns)) {
1418 if ($this->config
->memberattribute_isdn
) {
1419 $memberuser = $this->ldap_find_userdn($ldapconnection, $extusername);
1421 $memberuser = $extusername;
1424 if (empty($memberuser)) {
1428 $groups = explode(";",$groupdns);
1431 foreach ($groups as $group) {
1432 $group = trim($group);
1433 if (empty($group)) {
1436 //echo "Checking group $group for member $username\n";
1437 $search = ldap_read($ldapconnection, $group, '('.$this->config
->memberattribute
.'='.$this->filter_addslashes($memberuser).')', array($this->config
->memberattribute
));
1438 if (!empty($search) and ldap_count_entries($ldapconnection, $search)) {
1439 $info = $this->ldap_get_entries($ldapconnection, $search);
1441 if (count($info) > 0 ) {
1442 // user is member of group
1454 * connects to ldap server
1456 * Tries connect to specified ldap servers.
1457 * Returns connection result or error.
1459 * @return connection result
1461 function ldap_connect($binddn='',$bindpwd='') {
1462 //Select bind password, With empty values use
1463 //ldap_bind_* variables or anonymous bind if ldap_bind_* are empty
1464 if ($binddn == '' and $bindpwd == '') {
1465 if (!empty($this->config
->bind_dn
)) {
1466 $binddn = $this->config
->bind_dn
;
1468 if (!empty($this->config
->bind_pw
)) {
1469 $bindpwd = $this->config
->bind_pw
;
1473 $urls = explode(";",$this->config
->host_url
);
1475 foreach ($urls as $server) {
1476 $server = trim($server);
1477 if (empty($server)) {
1481 $connresult = ldap_connect($server);
1482 //ldap_connect returns ALWAYS true
1484 if (!empty($this->config
->version
)) {
1485 ldap_set_option($connresult, LDAP_OPT_PROTOCOL_VERSION
, $this->config
->version
);
1489 if ($this->config
->user_type
== 'ad') {
1490 ldap_set_option($connresult, LDAP_OPT_REFERRALS
, 0);
1493 if (!empty($binddn)) {
1494 //bind with search-user
1495 //$debuginfo .= 'Using bind user'.$binddn.'and password:'.$bindpwd;
1496 $bindresult=ldap_bind($connresult, $binddn,$bindpwd);
1500 $bindresult=@ldap_bind
($connresult);
1503 if (!empty($this->config
->opt_deref
)) {
1504 ldap_set_option($connresult, LDAP_OPT_DEREF
, $this->config
->opt_deref
);
1511 $debuginfo .= "<br/>Server: '$server' <br/> Connection: '$connresult'<br/> Bind result: '$bindresult'</br>";
1514 //If any of servers are alive we have already returned connection
1515 print_error('auth_ldap_noconnect_all','auth',$this->config
->user_type
);
1520 * retuns dn of username
1522 * Search specified contexts for username and return user dn
1523 * like: cn=username,ou=suborg,o=org
1525 * @param mixed $ldapconnection $ldapconnection result
1526 * @param mixed $username username (external encoding no slashes)
1530 function ldap_find_userdn ($ldapconnection, $extusername) {
1532 //default return value
1533 $ldap_user_dn = FALSE;
1535 //get all contexts and look for first matching user
1536 $ldap_contexts = explode(";",$this->config
->contexts
);
1538 if (!empty($this->config
->create_context
)) {
1539 array_push($ldap_contexts, $this->config
->create_context
);
1542 foreach ($ldap_contexts as $context) {
1544 $context = trim($context);
1545 if (empty($context)) {
1549 if ($this->config
->search_sub
) {
1550 //use ldap_search to find first user from subtree
1551 $ldap_result = ldap_search($ldapconnection, $context, "(".$this->config
->user_attribute
."=".$this->filter_addslashes($extusername).")",array($this->config
->user_attribute
));
1555 //search only in this context
1556 $ldap_result = ldap_list($ldapconnection, $context, "(".$this->config
->user_attribute
."=".$this->filter_addslashes($extusername).")",array($this->config
->user_attribute
));
1559 $entry = ldap_first_entry($ldapconnection,$ldap_result);
1562 $ldap_user_dn = ldap_get_dn($ldapconnection, $entry);
1567 return $ldap_user_dn;
1571 * retuns user attribute mappings between moodle and ldap
1576 function ldap_attributes () {
1577 $fields = array("firstname", "lastname", "email", "phone1", "phone2",
1578 "department", "address", "city", "country", "description",
1579 "idnumber", "lang" );
1580 $moodleattributes = array();
1581 foreach ($fields as $field) {
1582 if (!empty($this->config
->{"field_map_$field"})) {
1583 $moodleattributes[$field] = $this->config
->{"field_map_$field"};
1584 if (preg_match('/,/',$moodleattributes[$field])) {
1585 $moodleattributes[$field] = explode(',', $moodleattributes[$field]); // split ?
1589 $moodleattributes['username'] = $this->config
->user_attribute
;
1590 return $moodleattributes;
1594 * return all usernames from ldap
1599 function ldap_get_userlist($filter="*") {
1600 /// returns all users from ldap servers
1603 $ldapconnection = $this->ldap_connect();
1606 $filter = "(&(".$this->config
->user_attribute
."=*)(".$this->config
->objectclass
."))";
1609 $contexts = explode(";",$this->config
->contexts
);
1611 if (!empty($this->config
->create_context
)) {
1612 array_push($contexts, $this->config
->create_context
);
1615 foreach ($contexts as $context) {
1617 $context = trim($context);
1618 if (empty($context)) {
1622 if ($this->config
->search_sub
) {
1623 //use ldap_search to find first user from subtree
1624 $ldap_result = ldap_search($ldapconnection, $context,$filter,array($this->config
->user_attribute
));
1627 //search only in this context
1628 $ldap_result = ldap_list($ldapconnection, $context,
1630 array($this->config
->user_attribute
));
1633 $users = $this->ldap_get_entries($ldapconnection, $ldap_result);
1635 //add found users to list
1636 for ($i=0;$i<count($users);$i++
) {
1637 array_push($fresult, ($users[$i][$this->config
->user_attribute
][0]) );
1645 * return entries from ldap
1647 * Returns values like ldap_get_entries but is
1648 * binary compatible and return all attributes as array
1650 * @return array ldap-entries
1653 function ldap_get_entries($conn, $searchresult) {
1654 //Returns values like ldap_get_entries but is
1658 $entry = ldap_first_entry($conn, $searchresult);
1660 $attributes = @ldap_get_attributes
($conn, $entry);
1661 for ($j=0; $j<$attributes['count']; $j++
) {
1662 $values = ldap_get_values_len($conn, $entry,$attributes[$j]);
1663 if (is_array($values)) {
1664 $fresult[$i][$attributes[$j]] = $values;
1667 $fresult[$i][$attributes[$j]] = array($values);
1672 while ($entry = @ldap_next_entry
($conn, $entry));
1678 * Returns true if this authentication plugin is 'internal'.
1682 function is_internal() {
1687 * Returns true if this authentication plugin can change the user's
1692 function can_change_password() {
1693 return !empty($this->config
->stdchangepassword
) or !empty($this->config
->changepasswordurl
);
1697 * Returns the URL for changing the user's pw, or empty if the default can
1700 * @return string url
1702 function change_password_url() {
1703 if (empty($this->config
->stdchangepassword
)) {
1704 return $this->config
->changepasswordurl
;
1711 * Sync roles for this user
1713 * @param $user object user object (without system magic quotes)
1715 function sync_roles($user) {
1716 $iscreator = $this->iscreator($user->username
);
1717 if ($iscreator === null) {
1718 return; //nothing to sync - creators not configured
1721 if ($roles = get_roles_with_capability('moodle/legacy:coursecreator', CAP_ALLOW
)) {
1722 $creatorrole = array_shift($roles); // We can only use one, let's use the first one
1723 $systemcontext = get_context_instance(CONTEXT_SYSTEM
);
1725 if ($iscreator) { // Following calls will not create duplicates
1726 role_assign($creatorrole->id
, $user->id
, 0, $systemcontext->id
, 0, 0, 0, 'ldap');
1728 //unassign only if previously assigned by this plugin!
1729 role_unassign($creatorrole->id
, $user->id
, 0, $systemcontext->id
, 'ldap');
1735 * Prints a form for configuring this authentication plugin.
1737 * This function is called from admin/auth.php, and outputs a full page with
1738 * a form for configuring this plugin.
1740 * @param array $page An object containing all the data for this page.
1742 function config_form($config, $err, $user_fields) {
1743 include 'config.html';
1747 * Processes and stores configuration data for this authentication plugin.
1749 function process_config($config) {
1750 // set to defaults if undefined
1751 if (!isset($config->host_url
))
1752 { $config->host_url
= ''; }
1753 if (empty($config->ldapencoding
))
1754 { $config->ldapencoding
= 'utf-8'; }
1755 if (!isset($config->contexts
))
1756 { $config->contexts
= ''; }
1757 if (!isset($config->user_type
))
1758 { $config->user_type
= 'default'; }
1759 if (!isset($config->user_attribute
))
1760 { $config->user_attribute
= ''; }
1761 if (!isset($config->search_sub
))
1762 { $config->search_sub
= ''; }
1763 if (!isset($config->opt_deref
))
1764 { $config->opt_deref
= ''; }
1765 if (!isset($config->preventpassindb
))
1766 { $config->preventpassindb
= 0; }
1767 if (!isset($config->bind_dn
))
1768 {$config->bind_dn
= ''; }
1769 if (!isset($config->bind_pw
))
1770 {$config->bind_pw
= ''; }
1771 if (!isset($config->version
))
1772 {$config->version
= '2'; }
1773 if (!isset($config->objectclass
))
1774 {$config->objectclass
= ''; }
1775 if (!isset($config->memberattribute
))
1776 {$config->memberattribute
= ''; }
1777 if (!isset($config->memberattribute_isdn
))
1778 {$config->memberattribute_isdn
= ''; }
1779 if (!isset($config->creators
))
1780 {$config->creators
= ''; }
1781 if (!isset($config->create_context
))
1782 {$config->create_context
= ''; }
1783 if (!isset($config->expiration
))
1784 {$config->expiration
= ''; }
1785 if (!isset($config->expiration_warning
))
1786 {$config->expiration_warning
= '10'; }
1787 if (!isset($config->expireattr
))
1788 {$config->expireattr
= ''; }
1789 if (!isset($config->gracelogins
))
1790 {$config->gracelogins
= ''; }
1791 if (!isset($config->graceattr
))
1792 {$config->graceattr
= ''; }
1793 if (!isset($config->auth_user_create
))
1794 {$config->auth_user_create
= ''; }
1795 if (!isset($config->forcechangepassword
))
1796 {$config->forcechangepassword
= 0; }
1797 if (!isset($config->stdchangepassword
))
1798 {$config->forcechangepassword
= 0; }
1799 if (!isset($config->passtype
))
1800 {$config->passtype
= 'plaintext'; }
1801 if (!isset($config->changepasswordurl
))
1802 {$config->changepasswordurl
= ''; }
1803 if (!isset($config->removeuser
))
1804 {$config->removeuser
= 0; }
1807 set_config('host_url', $config->host_url
, 'auth/ldap');
1808 set_config('ldapencoding', $config->ldapencoding
, 'auth/ldap');
1809 set_config('host_url', $config->host_url
, 'auth/ldap');
1810 set_config('contexts', $config->contexts
, 'auth/ldap');
1811 set_config('user_type', $config->user_type
, 'auth/ldap');
1812 set_config('user_attribute', $config->user_attribute
, 'auth/ldap');
1813 set_config('search_sub', $config->search_sub
, 'auth/ldap');
1814 set_config('opt_deref', $config->opt_deref
, 'auth/ldap');
1815 set_config('preventpassindb', $config->preventpassindb
, 'auth/ldap');
1816 set_config('bind_dn', $config->bind_dn
, 'auth/ldap');
1817 set_config('bind_pw', $config->bind_pw
, 'auth/ldap');
1818 set_config('version', $config->version
, 'auth/ldap');
1819 set_config('objectclass', $config->objectclass
, 'auth/ldap');
1820 set_config('memberattribute', $config->memberattribute
, 'auth/ldap');
1821 set_config('memberattribute_isdn', $config->memberattribute_isdn
, 'auth/ldap');
1822 set_config('creators', $config->creators
, 'auth/ldap');
1823 set_config('create_context', $config->create_context
, 'auth/ldap');
1824 set_config('expiration', $config->expiration
, 'auth/ldap');
1825 set_config('expiration_warning', $config->expiration_warning
, 'auth/ldap');
1826 set_config('expireattr', $config->expireattr
, 'auth/ldap');
1827 set_config('gracelogins', $config->gracelogins
, 'auth/ldap');
1828 set_config('graceattr', $config->graceattr
, 'auth/ldap');
1829 set_config('auth_user_create', $config->auth_user_create
, 'auth/ldap');
1830 set_config('forcechangepassword', $config->forcechangepassword
, 'auth/ldap');
1831 set_config('stdchangepassword', $config->stdchangepassword
, 'auth/ldap');
1832 set_config('passtype', $config->passtype
, 'auth/ldap');
1833 set_config('changepasswordurl', $config->changepasswordurl
, 'auth/ldap');
1834 set_config('removeuser', $config->removeuser
, 'auth/ldap');
1840 * Quote control characters in texts used in ldap filters - see rfc2254.txt
1844 function filter_addslashes($text) {
1845 $text = str_replace('\\', '\\5c', $text);
1846 $text = str_replace(array('*', '(', ')', "\0"),
1847 array('\\2a', '\\28', '\\29', '\\00'), $text);
1852 * Quote control characters in quoted "texts" used in ldap
1856 function ldap_addslashes($text) {
1857 $text = str_replace('\\', '\\\\', $text);
1858 $text = str_replace(array('"', "\0"),
1859 array('\\"', '\\00'), $text);
1864 * Get password expiration time for a given user from Active Directory
1866 * @param string $pwdlastset The time last time we changed the password.
1867 * @param resource $lcapconn The open LDAP connection.
1868 * @param string $user_dn The distinguished name of the user we are checking.
1870 * @return string $unixtime
1872 function ldap_get_ad_pwdexpire($pwdlastset, $ldapconn, $user_dn){
1873 define ('ROOTDSE', '');
1874 // UF_DONT_EXPIRE_PASSWD value taken from MSDN directly
1875 define ('UF_DONT_EXPIRE_PASSWD', 0x00010000);
1879 if (!function_exists('bcsub')) {
1880 error_log ('You need the BCMath extension to use grace logins with Active Directory');
1884 // If UF_DONT_EXPIRE_PASSWD flag is set in user's
1885 // userAccountControl attribute, the password doesn't expire.
1886 $sr = ldap_read($ldapconn, $user_dn, 'objectclass=*',
1887 array('userAccountControl'));
1889 error_log("ldap: error getting userAccountControl for $user_dn");
1890 // don't expire password, as we are not sure it has to be
1895 $info = $this->ldap_get_entries($ldapconn, $sr);
1896 $useraccountcontrol = $info[0]['userAccountControl'][0];
1897 if ($useraccountcontrol & UF_DONT_EXPIRE_PASSWD
) {
1898 // password doesn't expire.
1902 // If pwdLastSet is zero, the user must change his/her password now
1903 // (unless UF_DONT_EXPIRE_PASSWD flag is set, but we already
1904 // tested this above)
1905 if ($pwdlastset === '0') {
1906 // password has expired
1910 // ----------------------------------------------------------------
1911 // Password expiration time in Active Directory is the composition of
1914 // - User's pwdLastSet attribute, that stores the last time
1915 // the password was changed.
1917 // - Domain's maxPwdAge attribute, that sets how long
1918 // passwords last in this domain.
1920 // We already have the first value (passed in as a parameter). We
1921 // need to get the second one. As we don't know the domain DN, we
1922 // have to query rootDSE's defaultNamingContext attribute to get
1923 // it. Then we have to query that DN's maxPwdAge attribute to get
1926 // Once we have both values, we just need to combine them. But MS
1927 // chose to use a different base and unit for time measurements.
1928 // So we need to convert the values to Unix timestamps (see
1930 // ----------------------------------------------------------------
1932 $sr = ldap_read($ldapconn, ROOTDSE
, 'objectclass=*',
1933 array('defaultNamingContext'));
1935 error_log("ldap: error querying rootDSE for Active Directory");
1939 $info = $this->ldap_get_entries($ldapconn, $sr);
1940 $domaindn = $info[0]['defaultNamingContext'][0];
1942 $sr = ldap_read ($ldapconn, $domaindn, 'objectclass=*',
1943 array('maxPwdAge'));
1944 $info = $this->ldap_get_entries($ldapconn, $sr);
1945 $maxpwdage = $info[0]['maxPwdAge'][0];
1947 // ----------------------------------------------------------------
1948 // MSDN says that "pwdLastSet contains the number of 100 nanosecond
1949 // intervals since January 1, 1601 (UTC), stored in a 64 bit integer".
1951 // According to Perl's Date::Manip, the number of seconds between
1952 // this date and Unix epoch is 11644473600. So we have to
1953 // substract this value to calculate a Unix time, once we have
1954 // scaled pwdLastSet to seconds. This is the script used to
1955 // calculate the value shown above:
1957 // #!/usr/bin/perl -w
1961 // $date1 = ParseDate ("160101010000 UTC");
1962 // $date2 = ParseDate ("197001010000 UTC");
1963 // $delta = DateCalc($date1, $date2, \$err);
1964 // $secs = Delta_Format($delta, 0, "%st");
1965 // print "$secs \n";
1967 // MSDN also says that "maxPwdAge is stored as a large integer that
1968 // represents the number of 100 nanosecond intervals from the time
1969 // the password was set before the password expires." We also need
1970 // to scale this to seconds. Bear in mind that this value is stored
1971 // as a _negative_ quantity (at least in my AD domain).
1973 // As a last remark, if the low 32 bits of maxPwdAge are equal to 0,
1974 // the maximum password age in the domain is set to 0, which means
1975 // passwords do not expire (see
1976 // http://msdn2.microsoft.com/en-us/library/ms974598.aspx)
1978 // As the quantities involved are too big for PHP integers, we
1979 // need to use BCMath functions to work with arbitrary precision
1981 // ----------------------------------------------------------------
1984 // If the low order 32 bits are 0, then passwords do not expire in
1985 // the domain. Just do '$maxpwdage mod 2^32' and check the result
1986 // (2^32 = 4294967296)
1987 if (bcmod ($maxpwdage, 4294967296) === '0') {
1991 // Add up pwdLastSet and maxPwdAge to get password expiration
1992 // time, in MS time units. Remember maxPwdAge is stored as a
1993 // _negative_ quantity, so we need to substract it in fact.
1994 $pwdexpire = bcsub ($pwdlastset, $maxpwdage);
1996 // Scale the result to convert it to Unix time units and return
1998 return bcsub( bcdiv($pwdexpire, '10000000'), '11644473600');