MDL-40436: auth_ldap: Fixed warning when adding new LDAP users
[moodle.git] / auth / ldap / auth.php
CommitLineData
b9ddb2d5 1<?php
2
3/**
4 * @author Martin Dougiamas
99f9f85f 5 * @author I�aki Arenaza
b9ddb2d5 6 * @license http://www.gnu.org/copyleft/gpl.html GNU Public License
7 * @package moodle multiauth
8 *
9 * Authentication Plugin: LDAP Authentication
10 *
11 * Authentication using LDAP (Lightweight Directory Access Protocol).
12 *
13 * 2006-08-28 File created.
14 */
15
139ebfdb 16if (!defined('MOODLE_INTERNAL')) {
17 die('Direct access to this script is forbidden.'); /// It must be included from a Moodle page
b9ddb2d5 18}
19
81fb221d 20// See http://support.microsoft.com/kb/305144 to interprete these values.
21if (!defined('AUTH_AD_ACCOUNTDISABLE')) {
22 define('AUTH_AD_ACCOUNTDISABLE', 0x0002);
23}
24if (!defined('AUTH_AD_NORMAL_ACCOUNT')) {
25 define('AUTH_AD_NORMAL_ACCOUNT', 0x0200);
26}
355bd271 27if (!defined('AUTH_NTLMTIMEOUT')) { // timewindow for the NTLM SSO process, in secs...
28 define('AUTH_NTLMTIMEOUT', 10);
29}
30
fcf46da1
I
31// UF_DONT_EXPIRE_PASSWD value taken from MSDN directly
32if (!defined('UF_DONT_EXPIRE_PASSWD')) {
33 define ('UF_DONT_EXPIRE_PASSWD', 0x00010000);
34}
35
36// The Posix uid and gid of the 'nobody' account and 'nogroup' group.
37if (!defined('AUTH_UID_NOBODY')) {
38 define('AUTH_UID_NOBODY', -2);
39}
40if (!defined('AUTH_GID_NOGROUP')) {
41 define('AUTH_GID_NOGROUP', -2);
42}
81fb221d 43
6bc1e5d5 44require_once($CFG->libdir.'/authlib.php');
fcf46da1 45require_once($CFG->libdir.'/ldaplib.php');
6bc1e5d5 46
b9ddb2d5 47/**
48 * LDAP authentication plugin.
49 */
6bc1e5d5 50class auth_plugin_ldap extends auth_plugin_base {
b9ddb2d5 51
52 /**
fcf46da1 53 * Init plugin config from database settings depending on the plugin auth type.
b9ddb2d5 54 */
fcf46da1
I
55 function init_plugin($authtype) {
56 $this->pluginconfig = 'auth/'.$authtype;
57 $this->config = get_config($this->pluginconfig);
139ebfdb 58 if (empty($this->config->ldapencoding)) {
59 $this->config->ldapencoding = 'utf-8';
60 }
61 if (empty($this->config->user_type)) {
62 $this->config->user_type = 'default';
63 }
64
fcf46da1
I
65 $ldap_usertypes = ldap_supported_usertypes();
66 $this->config->user_type_name = $ldap_usertypes[$this->config->user_type];
67 unset($ldap_usertypes);
68
69 $default = ldap_getdefaults();
139ebfdb 70
fcf46da1 71 // Use defaults if values not given
139ebfdb 72 foreach ($default as $key => $value) {
73 // watch out - 0, false are correct values too
74 if (!isset($this->config->{$key}) or $this->config->{$key} == '') {
75 $this->config->{$key} = $value[$this->config->user_type];
76 }
77 }
cfcb7a17 78
79 // Hack prefix to objectclass
80 if (empty($this->config->objectclass)) {
81 // Can't send empty filter
fcf46da1 82 $this->config->objectclass = '(objectClass=*)';
cfcb7a17 83 } else if (stripos($this->config->objectclass, 'objectClass=') === 0) {
84 // Value is 'objectClass=some-string-here', so just add ()
85 // around the value (filter _must_ have them).
86 $this->config->objectclass = '('.$this->config->objectclass.')';
fcf46da1 87 } else if (strpos($this->config->objectclass, '(') !== 0) {
cfcb7a17 88 // Value is 'some-string-not-starting-with-left-parentheses',
89 // which is assumed to be the objectClass matching value.
90 // So build a valid filter with it.
91 $this->config->objectclass = '(objectClass='.$this->config->objectclass.')';
92 } else {
93 // There is an additional possible value
94 // '(some-string-here)', that can be used to specify any
95 // valid filter string, to select subsets of users based
96 // on any criteria. For example, we could select the users
97 // whose objectClass is 'user' and have the
98 // 'enabledMoodleUser' attribute, with something like:
99 //
100 // (&(objectClass=user)(enabledMoodleUser=1))
101 //
cfcb7a17 102 // In this particular case we don't need to do anything,
103 // so leave $this->config->objectclass as is.
139ebfdb 104 }
fcf46da1 105 }
430759a5 106
fcf46da1
I
107 /**
108 * Constructor with initialisation.
109 */
110 function auth_plugin_ldap() {
111 $this->authtype = 'ldap';
112 $this->roleauth = 'auth_ldap';
113 $this->errorlogtag = '[AUTH LDAP] ';
114 $this->init_plugin($this->authtype);
b9ddb2d5 115 }
116
117 /**
118 * Returns true if the username and password work and false if they are
119 * wrong or don't exist.
120 *
fcf46da1
I
121 * @param string $username The username (without system magic quotes)
122 * @param string $password The password (without system magic quotes)
139ebfdb 123 *
124 * @return bool Authentication success or failure.
b9ddb2d5 125 */
126 function user_login($username, $password) {
b7b50143 127 if (! function_exists('ldap_bind')) {
fcf46da1 128 print_error('auth_ldapnotinstalled', 'auth_ldap');
b7b50143 129 return false;
130 }
b9ddb2d5 131
b9ddb2d5 132 if (!$username or !$password) { // Don't allow blank usernames or passwords
133 return false;
134 }
139ebfdb 135
f8311def
PS
136 $extusername = textlib::convert($username, 'utf-8', $this->config->ldapencoding);
137 $extpassword = textlib::convert($password, 'utf-8', $this->config->ldapencoding);
6221a321 138
decd8016 139 // Before we connect to LDAP, check if this is an AD SSO login
355bd271 140 // if we succeed in this block, we'll return success early.
decd8016 141 //
83cd2dce 142 $key = sesskey();
143 if (!empty($this->config->ntlmsso_enabled) && $key === $password) {
fcf46da1 144 $cf = get_cache_flags($this->pluginconfig.'/ntlmsess');
0cbcc8ef 145 // We only get the cache flag if we retrieve it before
146 // it expires (AUTH_NTLMTIMEOUT seconds).
147 if (!isset($cf[$key]) || $cf[$key] === '') {
148 return false;
149 }
150
151 $sessusername = $cf[$key];
152 if ($username === $sessusername) {
153 unset($sessusername);
154 unset($cf);
155
156 // Check that the user is inside one of the configured LDAP contexts
157 $validuser = false;
158 $ldapconnection = $this->ldap_connect();
fcf46da1
I
159 // if the user is not inside the configured contexts,
160 // ldap_find_userdn returns false.
161 if ($this->ldap_find_userdn($ldapconnection, $extusername)) {
162 $validuser = true;
decd8016 163 }
fcf46da1 164 $this->ldap_close();
0cbcc8ef 165
166 // Shortcut here - SSO confirmed
167 return $validuser;
decd8016 168 }
355bd271 169 } // End SSO processing
83cd2dce 170 unset($key);
decd8016 171
b9ddb2d5 172 $ldapconnection = $this->ldap_connect();
fcf46da1 173 $ldap_user_dn = $this->ldap_find_userdn($ldapconnection, $extusername);
139ebfdb 174
fcf46da1
I
175 // If ldap_user_dn is empty, user does not exist
176 if (!$ldap_user_dn) {
eee34307 177 $this->ldap_close();
fcf46da1 178 return false;
b9ddb2d5 179 }
fcf46da1
I
180
181 // Try to bind with current username and password
182 $ldap_login = @ldap_bind($ldapconnection, $ldap_user_dn, $extpassword);
183 $this->ldap_close();
184 if ($ldap_login) {
185 return true;
b9ddb2d5 186 }
187 return false;
188 }
189
190 /**
fcf46da1 191 * Reads user information from ldap and returns it in array()
b9ddb2d5 192 *
b9ddb2d5 193 * Function should return all information available. If you are saving
194 * this information to moodle user-table you should honor syncronization flags
195 *
be544ec3 196 * @param string $username username
139ebfdb 197 *
198 * @return mixed array with no magic quotes or false on error
b9ddb2d5 199 */
200 function get_userinfo($username) {
f8311def 201 $extusername = textlib::convert($username, 'utf-8', $this->config->ldapencoding);
139ebfdb 202
b9ddb2d5 203 $ldapconnection = $this->ldap_connect();
fcf46da1
I
204 if(!($user_dn = $this->ldap_find_userdn($ldapconnection, $extusername))) {
205 return false;
206 }
139ebfdb 207
b9ddb2d5 208 $search_attribs = array();
fcf46da1
I
209 $attrmap = $this->ldap_attributes();
210 foreach ($attrmap as $key => $values) {
b9ddb2d5 211 if (!is_array($values)) {
212 $values = array($values);
213 }
214 foreach ($values as $value) {
215 if (!in_array($value, $search_attribs)) {
216 array_push($search_attribs, $value);
139ebfdb 217 }
b9ddb2d5 218 }
219 }
220
fcf46da1 221 if (!$user_info_result = ldap_read($ldapconnection, $user_dn, '(objectClass=*)', $search_attribs)) {
139ebfdb 222 return false; // error!
223 }
fcf46da1
I
224
225 $user_entry = ldap_get_entries_moodle($ldapconnection, $user_info_result);
139ebfdb 226 if (empty($user_entry)) {
227 return false; // entry not found
228 }
229
fcf46da1
I
230 $result = array();
231 foreach ($attrmap as $key => $values) {
139ebfdb 232 if (!is_array($values)) {
233 $values = array($values);
234 }
235 $ldapval = NULL;
236 foreach ($values as $value) {
fcf46da1
I
237 $entry = array_change_key_case($user_entry[0], CASE_LOWER);
238 if (($value == 'dn') || ($value == 'distinguishedname')) {
a8d58c58 239 $result[$key] = $user_dn;
fcf46da1 240 continue;
a8d58c58 241 }
fcf46da1 242 if (!array_key_exists($value, $entry)) {
139ebfdb 243 continue; // wrong data mapping!
b9ddb2d5 244 }
fcf46da1 245 if (is_array($entry[$value])) {
f8311def 246 $newval = textlib::convert($entry[$value][0], $this->config->ldapencoding, 'utf-8');
139ebfdb 247 } else {
f8311def 248 $newval = textlib::convert($entry[$value], $this->config->ldapencoding, 'utf-8');
b9ddb2d5 249 }
139ebfdb 250 if (!empty($newval)) { // favour ldap entries that are set
251 $ldapval = $newval;
b9ddb2d5 252 }
253 }
139ebfdb 254 if (!is_null($ldapval)) {
255 $result[$key] = $ldapval;
256 }
b9ddb2d5 257 }
258
eee34307 259 $this->ldap_close();
b9ddb2d5 260 return $result;
261 }
262
263 /**
fcf46da1 264 * Reads user information from ldap and returns it in an object
b9ddb2d5 265 *
139ebfdb 266 * @param string $username username (with system magic quotes)
267 * @return mixed object or false on error
b9ddb2d5 268 */
269 function get_userinfo_asobj($username) {
139ebfdb 270 $user_array = $this->get_userinfo($username);
271 if ($user_array == false) {
272 return false; //error or not found
273 }
274 $user_array = truncate_userinfo($user_array);
1dffbae2 275 $user = new stdClass();
b9ddb2d5 276 foreach ($user_array as $key=>$value) {
277 $user->{$key} = $value;
278 }
279 return $user;
280 }
281
282 /**
fcf46da1 283 * Returns all usernames from LDAP
b9ddb2d5 284 *
fcf46da1 285 * get_userlist returns all usernames from LDAP
b9ddb2d5 286 *
139ebfdb 287 * @return array
b9ddb2d5 288 */
289 function get_userlist() {
b9ddb2d5 290 return $this->ldap_get_userlist("({$this->config->user_attribute}=*)");
291 }
292
293 /**
fcf46da1 294 * Checks if user exists on LDAP
139ebfdb 295 *
df884cd8 296 * @param string $username
b9ddb2d5 297 */
298 function user_exists($username) {
f8311def 299 $extusername = textlib::convert($username, 'utf-8', $this->config->ldapencoding);
139ebfdb 300
fcf46da1
I
301 // Returns true if given username exists on ldap
302 $users = $this->ldap_get_userlist('('.$this->config->user_attribute.'='.ldap_filter_addslashes($extusername).')');
139ebfdb 303 return count($users);
b9ddb2d5 304 }
305
306 /**
fcf46da1 307 * Creates a new user on LDAP.
b9ddb2d5 308 * By using information in userobject
fcf46da1 309 * Use user_exists to prevent duplicate usernames
b9ddb2d5 310 *
df884cd8 311 * @param mixed $userobject Moodle userobject
312 * @param mixed $plainpass Plaintext password
b9ddb2d5 313 */
314 function user_create($userobject, $plainpass) {
f8311def
PS
315 $extusername = textlib::convert($userobject->username, 'utf-8', $this->config->ldapencoding);
316 $extpassword = textlib::convert($plainpass, 'utf-8', $this->config->ldapencoding);
139ebfdb 317
344514fc 318 switch ($this->config->passtype) {
319 case 'md5':
320 $extpassword = '{MD5}' . base64_encode(pack('H*', md5($extpassword)));
321 break;
322 case 'sha1':
323 $extpassword = '{SHA}' . base64_encode(pack('H*', sha1($extpassword)));
324 break;
325 case 'plaintext':
326 default:
327 break; // plaintext
328 }
329
b9ddb2d5 330 $ldapconnection = $this->ldap_connect();
331 $attrmap = $this->ldap_attributes();
139ebfdb 332
b9ddb2d5 333 $newuser = array();
139ebfdb 334
b9ddb2d5 335 foreach ($attrmap as $key => $values) {
336 if (!is_array($values)) {
337 $values = array($values);
338 }
339 foreach ($values as $value) {
340 if (!empty($userobject->$key) ) {
f8311def 341 $newuser[$value] = textlib::convert($userobject->$key, 'utf-8', $this->config->ldapencoding);
b9ddb2d5 342 }
343 }
344 }
139ebfdb 345
b9ddb2d5 346 //Following sets all mandatory and other forced attribute values
347 //User should be creted as login disabled untill email confirmation is processed
139ebfdb 348 //Feel free to add your user type and send patches to paca@sci.fi to add them
b9ddb2d5 349 //Moodle distribution
350
351 switch ($this->config->user_type) {
352 case 'edir':
fcf46da1 353 $newuser['objectClass'] = array('inetOrgPerson', 'organizationalPerson', 'person', 'top');
139ebfdb 354 $newuser['uniqueId'] = $extusername;
fcf46da1 355 $newuser['logindisabled'] = 'TRUE';
139ebfdb 356 $newuser['userpassword'] = $extpassword;
fcf46da1
I
357 $uadd = ldap_add($ldapconnection, $this->config->user_attribute.'='.ldap_addslashes($extusername).','.$this->config->create_context, $newuser);
358 break;
359 case 'rfc2307':
360 case 'rfc2307bis':
361 // posixAccount object class forces us to specify a uidNumber
362 // and a gidNumber. That is quite complicated to generate from
363 // Moodle without colliding with existing numbers and without
364 // race conditions. As this user is supposed to be only used
365 // with Moodle (otherwise the user would exist beforehand) and
366 // doesn't need to login into a operating system, we assign the
367 // user the uid of user 'nobody' and gid of group 'nogroup'. In
368 // addition to that, we need to specify a home directory. We
369 // use the root directory ('/') as the home directory, as this
370 // is the only one can always be sure exists. Finally, even if
371 // it's not mandatory, we specify '/bin/false' as the login
372 // shell, to prevent the user from login in at the operating
373 // system level (Moodle ignores this).
374
375 $newuser['objectClass'] = array('posixAccount', 'inetOrgPerson', 'organizationalPerson', 'person', 'top');
376 $newuser['cn'] = $extusername;
377 $newuser['uid'] = $extusername;
378 $newuser['uidNumber'] = AUTH_UID_NOBODY;
379 $newuser['gidNumber'] = AUTH_GID_NOGROUP;
380 $newuser['homeDirectory'] = '/';
381 $newuser['loginShell'] = '/bin/false';
382
383 // IMPORTANT:
384 // We have to create the account locked, but posixAccount has
385 // no attribute to achive this reliably. So we are going to
386 // modify the password in a reversable way that we can later
387 // revert in user_activate().
388 //
389 // Beware that this can be defeated by the user if we are not
390 // using MD5 or SHA-1 passwords. After all, the source code of
391 // Moodle is available, and the user can see the kind of
392 // modification we are doing and 'undo' it by hand (but only
393 // if we are using plain text passwords).
394 //
395 // Also bear in mind that you need to use a binding user that
396 // can create accounts and has read/write privileges on the
397 // 'userPassword' attribute for this to work.
398
399 $newuser['userPassword'] = '*'.$extpassword;
400 $uadd = ldap_add($ldapconnection, $this->config->user_attribute.'='.ldap_addslashes($extusername).','.$this->config->create_context, $newuser);
81fb221d 401 break;
402 case 'ad':
403 // User account creation is a two step process with AD. First you
404 // create the user object, then you set the password. If you try
405 // to set the password while creating the user, the operation
406 // fails.
e295df44 407
81fb221d 408 // Passwords in Active Directory must be encoded as Unicode
409 // strings (UCS-2 Little Endian format) and surrounded with
410 // double quotes. See http://support.microsoft.com/?kbid=269190
411 if (!function_exists('mb_convert_encoding')) {
2b06294b 412 print_error('auth_ldap_no_mbstring', 'auth_ldap');
81fb221d 413 }
e295df44 414
fcf46da1
I
415 // Check for invalid sAMAccountName characters.
416 if (preg_match('#[/\\[\]:;|=,+*?<>@"]#', $extusername)) {
417 print_error ('auth_ldap_ad_invalidchars', 'auth_ldap');
418 }
419
81fb221d 420 // First create the user account, and mark it as disabled.
fcf46da1 421 $newuser['objectClass'] = array('top', 'person', 'user', 'organizationalPerson');
81fb221d 422 $newuser['sAMAccountName'] = $extusername;
e295df44 423 $newuser['userAccountControl'] = AUTH_AD_NORMAL_ACCOUNT |
81fb221d 424 AUTH_AD_ACCOUNTDISABLE;
fcf46da1 425 $userdn = 'cn='.ldap_addslashes($extusername).','.$this->config->create_context;
81fb221d 426 if (!ldap_add($ldapconnection, $userdn, $newuser)) {
2b06294b 427 print_error('auth_ldap_ad_create_req', 'auth_ldap');
81fb221d 428 }
e295df44 429
81fb221d 430 // Now set the password
431 unset($newuser);
432 $newuser['unicodePwd'] = mb_convert_encoding('"' . $extpassword . '"',
fcf46da1 433 'UCS-2LE', 'UTF-8');
81fb221d 434 if(!ldap_modify($ldapconnection, $userdn, $newuser)) {
435 // Something went wrong: delete the user account and error out
436 ldap_delete ($ldapconnection, $userdn);
2b06294b 437 print_error('auth_ldap_ad_create_req', 'auth_ldap');
81fb221d 438 }
439 $uadd = true;
b9ddb2d5 440 break;
441 default:
fcf46da1 442 print_error('auth_ldap_unsupportedusertype', 'auth_ldap', '', $this->config->user_type_name);
b9ddb2d5 443 }
eee34307 444 $this->ldap_close();
b9ddb2d5 445 return $uadd;
b9ddb2d5 446 }
447
fcf46da1
I
448 /**
449 * Returns true if plugin allows resetting of password from moodle.
450 *
451 * @return bool
452 */
4225d4ba 453 function can_reset_password() {
454 return !empty($this->config->stdchangepassword);
455 }
456
fcf46da1
I
457 /**
458 * Returns true if plugin allows signup and user creation.
459 *
460 * @return bool
461 */
4db13f94 462 function can_signup() {
463 return (!empty($this->config->auth_user_create) and !empty($this->config->create_context));
464 }
465
466 /**
467 * Sign up a new user ready for confirmation.
468 * Password is passed in plaintext.
469 *
5d910388 470 * @param object $user new user object
4db13f94 471 * @param boolean $notify print notice with link and terminate
472 */
473 function user_signup($user, $notify=true) {
fcf46da1 474 global $CFG, $DB, $PAGE, $OUTPUT;
f679d730 475
831d450e 476 require_once($CFG->dirroot.'/user/profile/lib.php');
f679d730 477
4db13f94 478 if ($this->user_exists($user->username)) {
2b06294b 479 print_error('auth_ldap_user_exists', 'auth_ldap');
4db13f94 480 }
481
482 $plainslashedpassword = $user->password;
483 unset($user->password);
484
485 if (! $this->user_create($user, $plainslashedpassword)) {
2b06294b 486 print_error('auth_ldap_create_error', 'auth_ldap');
4db13f94 487 }
488
a9637e7d 489 $user->id = $DB->insert_record('user', $user);
4db13f94 490
fcf46da1 491 // Save any custom profile field information
831d450e 492 profile_save_data($user);
493
4db13f94 494 $this->update_user_record($user->username);
495 update_internal_user_password($user, $plainslashedpassword);
496
f679d730 497 $user = $DB->get_record('user', array('id'=>$user->id));
2942a5cd 498 events_trigger('user_created', $user);
499
4db13f94 500 if (! send_confirmation_email($user)) {
c6a074f8 501 print_error('noemail', 'auth_ldap');
4db13f94 502 }
503
504 if ($notify) {
4db13f94 505 $emailconfirm = get_string('emailconfirm');
fcf46da1 506 $PAGE->set_url('/auth/ldap/auth.php');
cfc5b79b 507 $PAGE->navbar->add($emailconfirm);
508 $PAGE->set_title($emailconfirm);
509 $PAGE->set_heading($emailconfirm);
510 echo $OUTPUT->header();
fcf46da1 511 notice(get_string('emailconfirmsent', '', $user->email), "{$CFG->wwwroot}/index.php");
4db13f94 512 } else {
513 return true;
514 }
515 }
516
517 /**
518 * Returns true if plugin allows confirming of new users.
519 *
520 * @return bool
521 */
522 function can_confirm() {
523 return $this->can_signup();
524 }
525
526 /**
527 * Confirm the new user as registered.
528 *
b9a66360 529 * @param string $username
530 * @param string $confirmsecret
4db13f94 531 */
532 function user_confirm($username, $confirmsecret) {
df884cd8 533 global $DB;
534
4db13f94 535 $user = get_complete_user_data('username', $username);
536
537 if (!empty($user)) {
538 if ($user->confirmed) {
539 return AUTH_CONFIRM_ALREADY;
540
fcf46da1 541 } else if ($user->auth != $this->authtype) {
4db13f94 542 return AUTH_CONFIRM_ERROR;
543
b9a66360 544 } else if ($user->secret == $confirmsecret) { // They have provided the secret key to get in
4db13f94 545 if (!$this->user_activate($username)) {
546 return AUTH_CONFIRM_FAIL;
547 }
f685e830 548 $DB->set_field('user', 'confirmed', 1, array('id'=>$user->id));
cf1cb686
PS
549 if ($user->firstaccess == 0) {
550 $DB->set_field('user', 'firstaccess', time(), array('id'=>$user->id));
551 }
9a6230c8
JF
552 $euser = $DB->get_record('user', array('id' => $user->id));
553 events_trigger('user_updated', $euser);
4db13f94 554 return AUTH_CONFIRM_OK;
555 }
556 } else {
557 return AUTH_CONFIRM_ERROR;
558 }
559 }
560
b9ddb2d5 561 /**
fcf46da1 562 * Return number of days to user password expires
b9ddb2d5 563 *
564 * If userpassword does not expire it should return 0. If password is already expired
565 * it should return negative value.
566 *
df884cd8 567 * @param mixed $username username
b9ddb2d5 568 * @return integer
569 */
570 function password_expire($username) {
2cef74f9 571 $result = 0;
139ebfdb 572
f8311def 573 $extusername = textlib::convert($username, 'utf-8', $this->config->ldapencoding);
139ebfdb 574
b9ddb2d5 575 $ldapconnection = $this->ldap_connect();
139ebfdb 576 $user_dn = $this->ldap_find_userdn($ldapconnection, $extusername);
b9ddb2d5 577 $search_attribs = array($this->config->expireattr);
cfcb7a17 578 $sr = ldap_read($ldapconnection, $user_dn, '(objectClass=*)', $search_attribs);
b9ddb2d5 579 if ($sr) {
fcf46da1 580 $info = ldap_get_entries_moodle($ldapconnection, $sr);
fa5f5c20
IA
581 if (!empty ($info)) {
582 $info = array_change_key_case($info[0], CASE_LOWER);
583 if (!empty($info[$this->config->expireattr][0])) {
584 $expiretime = $this->ldap_expirationtime2unix($info[$this->config->expireattr][0], $ldapconnection, $user_dn);
585 if ($expiretime != 0) {
586 $now = time();
587 if ($expiretime > $now) {
588 $result = ceil(($expiretime - $now) / DAYSECS);
589 } else {
590 $result = floor(($expiretime - $now) / DAYSECS);
591 }
2cef74f9 592 }
139ebfdb 593 }
b9ddb2d5 594 }
139ebfdb 595 } else {
fcf46da1 596 error_log($this->errorlogtag.get_string('didtfindexpiretime', 'auth_ldap'));
b9ddb2d5 597 }
598
b9ddb2d5 599 return $result;
600 }
601
602 /**
fcf46da1 603 * Syncronizes user fron external LDAP server to moodle user table
b9ddb2d5 604 *
139ebfdb 605 * Sync is now using username attribute.
606 *
fcf46da1 607 * Syncing users removes or suspends users that dont exists anymore in external LDAP.
139ebfdb 608 * Creates new users and updates coursecreator status of users.
609 *
fcf46da1 610 * @param bool $do_updates will do pull in data updates from LDAP if relevant
b9ddb2d5 611 */
df884cd8 612 function sync_users($do_updates=true) {
613 global $CFG, $DB;
fa96bfaa 614
fcf46da1
I
615 print_string('connectingldap', 'auth_ldap');
616 $ldapconnection = $this->ldap_connect();
617
df884cd8 618 $dbman = $DB->get_manager();
139ebfdb 619
df884cd8 620 /// Define table user to be created
621 $table = new xmldb_table('tmp_extuser');
2a88f626 622 $table->add_field('id', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, XMLDB_SEQUENCE, null);
623 $table->add_field('username', XMLDB_TYPE_CHAR, '100', null, XMLDB_NOTNULL, null, null);
fcf46da1 624 $table->add_field('mnethostid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null);
df884cd8 625 $table->add_key('primary', XMLDB_KEY_PRIMARY, array('id'));
626 $table->add_index('username', XMLDB_INDEX_UNIQUE, array('mnethostid', 'username'));
b9ddb2d5 627
fcf46da1
I
628 print_string('creatingtemptable', 'auth_ldap', 'tmp_extuser');
629 $dbman->create_temp_table($table);
b9ddb2d5 630
631 ////
632 //// get user's list from ldap to sql in a scalable fashion
633 ////
634 // prepare some data we'll need
cfcb7a17 635 $filter = '(&('.$this->config->user_attribute.'=*)'.$this->config->objectclass.')';
b9ddb2d5 636
fcf46da1 637 $contexts = explode(';', $this->config->contexts);
139ebfdb 638
b9ddb2d5 639 if (!empty($this->config->create_context)) {
640 array_push($contexts, $this->config->create_context);
641 }
642
643 $fresult = array();
b9ddb2d5 644 foreach ($contexts as $context) {
645 $context = trim($context);
646 if (empty($context)) {
647 continue;
648 }
b9ddb2d5 649 if ($this->config->search_sub) {
650 //use ldap_search to find first user from subtree
651 $ldap_result = ldap_search($ldapconnection, $context,
652 $filter,
653 array($this->config->user_attribute));
139ebfdb 654 } else {
b9ddb2d5 655 //search only in this context
656 $ldap_result = ldap_list($ldapconnection, $context,
657 $filter,
658 array($this->config->user_attribute));
659 }
660
fcf46da1
I
661 if(!$ldap_result) {
662 continue;
663 }
664
665 if ($entry = @ldap_first_entry($ldapconnection, $ldap_result)) {
b9ddb2d5 666 do {
139ebfdb 667 $value = ldap_get_values_len($ldapconnection, $entry, $this->config->user_attribute);
f8311def 668 $value = textlib::convert($value[0], $this->config->ldapencoding, 'utf-8');
df884cd8 669 $this->ldap_bulk_insert($value);
139ebfdb 670 } while ($entry = ldap_next_entry($ldapconnection, $entry));
b9ddb2d5 671 }
139ebfdb 672 unset($ldap_result); // free mem
b9ddb2d5 673 }
b9ddb2d5 674
675 /// preserve our user database
676 /// if the temp table is empty, it probably means that something went wrong, exit
677 /// so as to avoid mass deletion of users; which is hard to undo
df884cd8 678 $count = $DB->count_records_sql('SELECT COUNT(username) AS count, 1 FROM {tmp_extuser}');
b9ddb2d5 679 if ($count < 1) {
fcf46da1 680 print_string('didntgetusersfromldap', 'auth_ldap');
b9ddb2d5 681 exit;
fa96bfaa 682 } else {
fcf46da1 683 print_string('gotcountrecordsfromldap', 'auth_ldap', $count);
b9ddb2d5 684 }
685
b9ddb2d5 686
139ebfdb 687/// User removal
fcf46da1 688 // Find users in DB that aren't in ldap -- to be removed!
139ebfdb 689 // this is still not as scalable (but how often do we mass delete?)
c31d0566 690 if ($this->config->removeuser != AUTH_REMOVEUSER_KEEP) {
f91f3f63 691 $sql = 'SELECT u.*
df884cd8 692 FROM {user} u
fcf46da1
I
693 LEFT JOIN {tmp_extuser} e ON (u.username = e.username AND u.mnethostid = e.mnethostid)
694 WHERE u.auth = ?
695 AND u.deleted = 0
696 AND e.username IS NULL';
697 $remove_users = $DB->get_records_sql($sql, array($this->authtype));
139ebfdb 698
699 if (!empty($remove_users)) {
fcf46da1 700 print_string('userentriestoremove', 'auth_ldap', count($remove_users));
139ebfdb 701
139ebfdb 702 foreach ($remove_users as $user) {
6f87ef52 703 if ($this->config->removeuser == AUTH_REMOVEUSER_FULLDELETE) {
90afcf32 704 if (delete_user($user)) {
2c10db3b 705 echo "\t"; print_string('auth_dbdeleteuser', 'auth_db', array('name'=>$user->username, 'id'=>$user->id)); echo "\n";
139ebfdb 706 } else {
2b06294b 707 echo "\t"; print_string('auth_dbdeleteusererror', 'auth_db', $user->username); echo "\n";
139ebfdb 708 }
6f87ef52 709 } else if ($this->config->removeuser == AUTH_REMOVEUSER_SUSPEND) {
1dffbae2 710 $updateuser = new stdClass();
139ebfdb 711 $updateuser->id = $user->id;
712 $updateuser->auth = 'nologin';
dd88de0e
PS
713 $DB->update_record('user', $updateuser);
714 echo "\t"; print_string('auth_dbsuspenduser', 'auth_db', array('name'=>$user->username, 'id'=>$user->id)); echo "\n";
9a6230c8
JF
715 $euser = $DB->get_record('user', array('id' => $user->id));
716 events_trigger('user_updated', $euser);
139ebfdb 717 }
b9ddb2d5 718 }
139ebfdb 719 } else {
fcf46da1 720 print_string('nouserentriestoremove', 'auth_ldap');
139ebfdb 721 }
722 unset($remove_users); // free mem!
723 }
724
725/// Revive suspended users
6f87ef52 726 if (!empty($this->config->removeuser) and $this->config->removeuser == AUTH_REMOVEUSER_SUSPEND) {
139ebfdb 727 $sql = "SELECT u.id, u.username
df884cd8 728 FROM {user} u
fcf46da1
I
729 JOIN {tmp_extuser} e ON (u.username = e.username AND u.mnethostid = e.mnethostid)
730 WHERE u.auth = 'nologin' AND u.deleted = 0";
731 $revive_users = $DB->get_records_sql($sql);
139ebfdb 732
733 if (!empty($revive_users)) {
fcf46da1 734 print_string('userentriestorevive', 'auth_ldap', count($revive_users));
139ebfdb 735
139ebfdb 736 foreach ($revive_users as $user) {
1dffbae2 737 $updateuser = new stdClass();
139ebfdb 738 $updateuser->id = $user->id;
fcf46da1 739 $updateuser->auth = $this->authtype;
dd88de0e
PS
740 $DB->update_record('user', $updateuser);
741 echo "\t"; print_string('auth_dbreviveduser', 'auth_db', array('name'=>$user->username, 'id'=>$user->id)); echo "\n";
9a6230c8
JF
742 $euser = $DB->get_record('user', array('id' => $user->id));
743 events_trigger('user_updated', $euser);
b9ddb2d5 744 }
139ebfdb 745 } else {
fcf46da1 746 print_string('nouserentriestorevive', 'auth_ldap');
139ebfdb 747 }
748
749 unset($revive_users);
fa96bfaa 750 }
b9ddb2d5 751
139ebfdb 752
753/// User Updates - time-consuming (optional)
b9ddb2d5 754 if ($do_updates) {
fcf46da1 755 // Narrow down what fields we need to update
b9ddb2d5 756 $all_keys = array_keys(get_object_vars($this->config));
757 $updatekeys = array();
758 foreach ($all_keys as $key) {
fcf46da1
I
759 if (preg_match('/^field_updatelocal_(.+)$/', $key, $match)) {
760 // If we have a field to update it from
139ebfdb 761 // and it must be updated 'onlogin' we
b9ddb2d5 762 // update it on cron
fcf46da1 763 if (!empty($this->config->{'field_map_'.$match[1]})
139ebfdb 764 and $this->config->{$match[0]} === 'onlogin') {
b9ddb2d5 765 array_push($updatekeys, $match[1]); // the actual key name
766 }
767 }
768 }
b9ddb2d5 769 unset($all_keys); unset($key);
139ebfdb 770
fa96bfaa 771 } else {
fcf46da1 772 print_string('noupdatestobedone', 'auth_ldap');
b9ddb2d5 773 }
fcf46da1
I
774 if ($do_updates and !empty($updatekeys)) { // run updates only if relevant
775 $users = $DB->get_records_sql('SELECT u.username, u.id
df884cd8 776 FROM {user} u
fcf46da1
I
777 WHERE u.deleted = 0 AND u.auth = ? AND u.mnethostid = ?',
778 array($this->authtype, $CFG->mnet_localhost_id));
b9ddb2d5 779 if (!empty($users)) {
fcf46da1 780 print_string('userentriestoupdate', 'auth_ldap', count($users));
139ebfdb 781
b9ddb2d5 782 $sitecontext = get_context_instance(CONTEXT_SYSTEM);
139ebfdb 783 if (!empty($this->config->creators) and !empty($this->config->memberattribute)
4f0c2d00 784 and $roles = get_archetype_roles('coursecreator')) {
139ebfdb 785 $creatorrole = array_shift($roles); // We can only use one, let's use the first one
786 } else {
787 $creatorrole = false;
788 }
b9ddb2d5 789
d5a8d9aa 790 $transaction = $DB->start_delegated_transaction();
139ebfdb 791 $xcount = 0;
792 $maxxcount = 100;
b9ddb2d5 793
139ebfdb 794 foreach ($users as $user) {
2c10db3b 795 echo "\t"; print_string('auth_dbupdatinguser', 'auth_db', array('name'=>$user->username, 'id'=>$user->id));
185721a4 796 if (!$this->update_user_record($user->username, $updatekeys)) {
fcf46da1 797 echo ' - '.get_string('skipped');
139ebfdb 798 }
799 echo "\n";
800 $xcount++;
801
fcf46da1 802 // Update course creators if needed
139ebfdb 803 if ($creatorrole !== false) {
804 if ($this->iscreator($user->username)) {
fcf46da1 805 role_assign($creatorrole->id, $user->id, $sitecontext->id, $this->roleauth);
139ebfdb 806 } else {
fcf46da1 807 role_unassign($creatorrole->id, $user->id, $sitecontext->id, $this->roleauth);
b9ddb2d5 808 }
139ebfdb 809 }
b9ddb2d5 810 }
d5a8d9aa 811 $transaction->allow_commit();
139ebfdb 812 unset($users); // free mem
b9ddb2d5 813 }
fa96bfaa 814 } else { // end do updates
fcf46da1 815 print_string('noupdatestobedone', 'auth_ldap');
fa96bfaa 816 }
139ebfdb 817
818/// User Additions
fcf46da1 819 // Find users missing in DB that are in LDAP
b9ddb2d5 820 // and gives me a nifty object I don't want.
139ebfdb 821 // note: we do not care about deleted accounts anymore, this feature was replaced by suspending to nologin auth plugin
fcf46da1
I
822 $sql = 'SELECT e.id, e.username
823 FROM {tmp_extuser} e
824 LEFT JOIN {user} u ON (e.username = u.username AND e.mnethostid = u.mnethostid)
825 WHERE u.id IS NULL';
826 $add_users = $DB->get_records_sql($sql);
139ebfdb 827
b9ddb2d5 828 if (!empty($add_users)) {
fcf46da1 829 print_string('userentriestoadd', 'auth_ldap', count($add_users));
b9ddb2d5 830
139ebfdb 831 $sitecontext = get_context_instance(CONTEXT_SYSTEM);
832 if (!empty($this->config->creators) and !empty($this->config->memberattribute)
4f0c2d00 833 and $roles = get_archetype_roles('coursecreator')) {
b9ddb2d5 834 $creatorrole = array_shift($roles); // We can only use one, let's use the first one
139ebfdb 835 } else {
836 $creatorrole = false;
b9ddb2d5 837 }
838
d5a8d9aa 839 $transaction = $DB->start_delegated_transaction();
b9ddb2d5 840 foreach ($add_users as $user) {
df884cd8 841 $user = $this->get_userinfo_asobj($user->username);
139ebfdb 842
fcf46da1 843 // Prep a few params
b7b50143 844 $user->modified = time();
845 $user->confirmed = 1;
fcf46da1 846 $user->auth = $this->authtype;
b7b50143 847 $user->mnethostid = $CFG->mnet_localhost_id;
997bcd9e 848 // get_userinfo_asobj() might have replaced $user->username with the value
849 // from the LDAP server (which can be mixed-case). Make sure it's lowercase
6f3451e5 850 $user->username = trim(textlib::strtolower($user->username));
139ebfdb 851 if (empty($user->lang)) {
852 $user->lang = $CFG->lang;
b9ddb2d5 853 }
139ebfdb 854
a9637e7d
PS
855 $id = $DB->insert_record('user', $user);
856 echo "\t"; print_string('auth_dbinsertuser', 'auth_db', array('name'=>$user->username, 'id'=>$id)); echo "\n";
ffbb1a21 857 $euser = $DB->get_record('user', array('id' => $id));
9a6230c8 858 events_trigger('user_created', $euser);
a9637e7d
PS
859 if (!empty($this->config->forcechangepassword)) {
860 set_user_preference('auth_forcepasswordchange', 1, $id);
861 }
3e5f4b87 862
a9637e7d
PS
863 // Add course creators if needed
864 if ($creatorrole !== false and $this->iscreator($user->username)) {
865 role_assign($creatorrole->id, $id, $sitecontext->id, $this->roleauth);
139ebfdb 866 }
867
b9ddb2d5 868 }
d5a8d9aa 869 $transaction->allow_commit();
b9ddb2d5 870 unset($add_users); // free mem
fa96bfaa 871 } else {
fcf46da1 872 print_string('nouserstobeadded', 'auth_ldap');
b9ddb2d5 873 }
df884cd8 874
a66b2ae4 875 $dbman->drop_table($table);
eee34307 876 $this->ldap_close();
df884cd8 877
b9ddb2d5 878 return true;
879 }
880
139ebfdb 881 /**
882 * Update a local user record from an external source.
883 * This is a lighter version of the one in moodlelib -- won't do
b9ddb2d5 884 * expensive ops such as enrolment.
885 *
139ebfdb 886 * If you don't pass $updatekeys, there is a performance hit and
887 * values removed from LDAP won't be removed from moodle.
888 *
185721a4 889 * @param string $username username
fcf46da1 890 * @param boolean $updatekeys true to update the local record with the external LDAP values.
b9ddb2d5 891 */
892 function update_user_record($username, $updatekeys = false) {
1aa66713 893 global $CFG, $DB;
b9ddb2d5 894
fcf46da1 895 // Just in case check text case
6f3451e5 896 $username = trim(textlib::strtolower($username));
139ebfdb 897
fcf46da1 898 // Get the current user record
185721a4 899 $user = $DB->get_record('user', array('username'=>$username, 'mnethostid'=>$CFG->mnet_localhost_id));
b9ddb2d5 900 if (empty($user)) { // trouble
fcf46da1
I
901 error_log($this->errorlogtag.get_string('auth_dbusernotexist', 'auth_db', '', $username));
902 print_error('auth_dbusernotexist', 'auth_db', '', $username);
b9ddb2d5 903 die;
904 }
905
b7b50143 906 // Protect the userid from being overwritten
907 $userid = $user->id;
908
139ebfdb 909 if ($newinfo = $this->get_userinfo($username)) {
910 $newinfo = truncate_userinfo($newinfo);
911
912 if (empty($updatekeys)) { // all keys? this does not support removing values
913 $updatekeys = array_keys($newinfo);
914 }
915
916 foreach ($updatekeys as $key) {
917 if (isset($newinfo[$key])) {
918 $value = $newinfo[$key];
919 } else {
920 $value = '';
b9ddb2d5 921 }
139ebfdb 922
923 if (!empty($this->config->{'field_updatelocal_' . $key})) {
924 if ($user->{$key} != $value) { // only update if it's changed
185721a4 925 $DB->set_field('user', $key, $value, array('id'=>$userid));
b9ddb2d5 926 }
927 }
928 }
9a6230c8
JF
929 if (!empty($updatekeys)) {
930 $euser = $DB->get_record('user', array('id' => $userid));
931 events_trigger('user_updated', $euser);
932 }
139ebfdb 933 } else {
934 return false;
b9ddb2d5 935 }
185721a4 936 return $DB->get_record('user', array('id'=>$userid, 'deleted'=>0));
b9ddb2d5 937 }
938
139ebfdb 939 /**
940 * Bulk insert in SQL's temp table
139ebfdb 941 */
df884cd8 942 function ldap_bulk_insert($username) {
fcf46da1 943 global $DB, $CFG;
df884cd8 944
6f3451e5 945 $username = textlib::strtolower($username); // usernames are __always__ lowercase.
fcf46da1
I
946 $DB->insert_record_raw('tmp_extuser', array('username'=>$username,
947 'mnethostid'=>$CFG->mnet_localhost_id), false, true);
948 echo '.';
b9ddb2d5 949 }
950
139ebfdb 951 /**
fcf46da1 952 * Activates (enables) user in external LDAP so user can login
b9ddb2d5 953 *
df884cd8 954 * @param mixed $username
fcf46da1 955 * @return boolean result
b9ddb2d5 956 */
957 function user_activate($username) {
f8311def 958 $extusername = textlib::convert($username, 'utf-8', $this->config->ldapencoding);
139ebfdb 959
b9ddb2d5 960 $ldapconnection = $this->ldap_connect();
961
139ebfdb 962 $userdn = $this->ldap_find_userdn($ldapconnection, $extusername);
b9ddb2d5 963 switch ($this->config->user_type) {
964 case 'edir':
fcf46da1
I
965 $newinfo['loginDisabled'] = 'FALSE';
966 break;
967 case 'rfc2307':
968 case 'rfc2307bis':
969 // Remember that we add a '*' character in front of the
970 // external password string to 'disable' the account. We just
971 // need to remove it.
972 $sr = ldap_read($ldapconnection, $userdn, '(objectClass=*)',
973 array('userPassword'));
974 $info = ldap_get_entries($ldapconnection, $sr);
975 $info[0] = array_change_key_case($info[0], CASE_LOWER);
976 $newinfo['userPassword'] = ltrim($info[0]['userpassword'][0], '*');
b9ddb2d5 977 break;
81fb221d 978 case 'ad':
979 // We need to unset the ACCOUNTDISABLE bit in the
980 // userAccountControl attribute ( see
981 // http://support.microsoft.com/kb/305144 )
982 $sr = ldap_read($ldapconnection, $userdn, '(objectClass=*)',
983 array('userAccountControl'));
984 $info = ldap_get_entries($ldapconnection, $sr);
fcf46da1
I
985 $info[0] = array_change_key_case($info[0], CASE_LOWER);
986 $newinfo['userAccountControl'] = $info[0]['useraccountcontrol'][0]
81fb221d 987 & (~AUTH_AD_ACCOUNTDISABLE);
988 break;
b9ddb2d5 989 default:
fcf46da1 990 print_error('user_activatenotsupportusertype', 'auth_ldap', '', $this->config->user_type_name);
139ebfdb 991 }
b9ddb2d5 992 $result = ldap_modify($ldapconnection, $userdn, $newinfo);
eee34307 993 $this->ldap_close();
b9ddb2d5 994 return $result;
995 }
996
139ebfdb 997 /**
b9ddb2d5 998 * Returns true if user should be coursecreator.
999 *
6bc1e5d5 1000 * @param mixed $username username (without system magic quotes)
fcf46da1 1001 * @return mixed result null if course creators is not configured, boolean otherwise.
b9ddb2d5 1002 */
6bc1e5d5 1003 function iscreator($username) {
139ebfdb 1004 if (empty($this->config->creators) or empty($this->config->memberattribute)) {
6bc1e5d5 1005 return null;
b9ddb2d5 1006 }
139ebfdb 1007
f8311def 1008 $extusername = textlib::convert($username, 'utf-8', $this->config->ldapencoding);
139ebfdb 1009
fcf46da1
I
1010 $ldapconnection = $this->ldap_connect();
1011
1012 if ($this->config->memberattribute_isdn) {
1013 if(!($userid = $this->ldap_find_userdn($ldapconnection, $extusername))) {
1014 return false;
1015 }
1016 } else {
1017 $userid = $extusername;
1018 }
1019
1020 $group_dns = explode(';', $this->config->creators);
1021 $creator = ldap_isgroupmember($ldapconnection, $userid, $group_dns, $this->config->memberattribute);
1022
1023 $this->ldap_close();
1024
1025 return $creator;
b9ddb2d5 1026 }
1027
139ebfdb 1028 /**
b9ddb2d5 1029 * Called when the user record is updated.
fcf46da1
I
1030 *
1031 * Modifies user in external LDAP server. It takes olduser (before
1032 * changes) and newuser (after changes) compares information and
1033 * saves modified information to external LDAP server.
b9ddb2d5 1034 *
139ebfdb 1035 * @param mixed $olduser Userobject before modifications (without system magic quotes)
1036 * @param mixed $newuser Userobject new modified userobject (without system magic quotes)
b9ddb2d5 1037 * @return boolean result
1038 *
1039 */
1040 function user_update($olduser, $newuser) {
139ebfdb 1041 global $USER;
1042
1043 if (isset($olduser->username) and isset($newuser->username) and $olduser->username != $newuser->username) {
fcf46da1 1044 error_log($this->errorlogtag.get_string('renamingnotallowed', 'auth_ldap'));
139ebfdb 1045 return false;
1046 }
1047
fcf46da1 1048 if (isset($olduser->auth) and $olduser->auth != $this->authtype) {
139ebfdb 1049 return true; // just change auth and skip update
1050 }
1051
1e3eee5f 1052 $attrmap = $this->ldap_attributes();
fcf46da1 1053 // Before doing anything else, make sure we really need to update anything
1e3eee5f 1054 // in the external LDAP server.
1055 $update_external = false;
1056 foreach ($attrmap as $key => $ldapkeys) {
1057 if (!empty($this->config->{'field_updateremote_'.$key})) {
1058 $update_external = true;
1059 break;
1060 }
1061 }
1062 if (!$update_external) {
1063 return true;
1064 }
1065
f8311def 1066 $extoldusername = textlib::convert($olduser->username, 'utf-8', $this->config->ldapencoding);
b9ddb2d5 1067
1068 $ldapconnection = $this->ldap_connect();
139ebfdb 1069
b9ddb2d5 1070 $search_attribs = array();
b9ddb2d5 1071 foreach ($attrmap as $key => $values) {
1072 if (!is_array($values)) {
1073 $values = array($values);
1074 }
1075 foreach ($values as $value) {
1076 if (!in_array($value, $search_attribs)) {
1077 array_push($search_attribs, $value);
1078 }
139ebfdb 1079 }
b9ddb2d5 1080 }
1081
fcf46da1
I
1082 if(!($user_dn = $this->ldap_find_userdn($ldapconnection, $extoldusername))) {
1083 return false;
1084 }
b9ddb2d5 1085
fcf46da1 1086 $user_info_result = ldap_read($ldapconnection, $user_dn, '(objectClass=*)', $search_attribs);
b9ddb2d5 1087 if ($user_info_result) {
fcf46da1 1088 $user_entry = ldap_get_entries_moodle($ldapconnection, $user_info_result);
139ebfdb 1089 if (empty($user_entry)) {
fcf46da1
I
1090 $attribs = join (', ', $search_attribs);
1091 error_log($this->errorlogtag.get_string('updateusernotfound', 'auth_ldap',
99f9f85f 1092 array('userdn'=>$user_dn,
fcf46da1 1093 'attribs'=>$attribs)));
139ebfdb 1094 return false; // old user not found!
1095 } else if (count($user_entry) > 1) {
fcf46da1 1096 error_log($this->errorlogtag.get_string('morethanoneuser', 'auth_ldap'));
139ebfdb 1097 return false;
b9ddb2d5 1098 }
b9ddb2d5 1099
fcf46da1 1100 $user_entry = array_change_key_case($user_entry[0], CASE_LOWER);
b9ddb2d5 1101
139ebfdb 1102 foreach ($attrmap as $key => $ldapkeys) {
fcf46da1 1103 // Only process if the moodle field ($key) has changed and we
b9ddb2d5 1104 // are set to update LDAP with it
139ebfdb 1105 if (isset($olduser->$key) and isset($newuser->$key)
1106 and $olduser->$key !== $newuser->$key
1107 and !empty($this->config->{'field_updateremote_'. $key})) {
fcf46da1 1108 // For ldap values that could be in more than one
139ebfdb 1109 // ldap key, we will do our best to match
b9ddb2d5 1110 // where they came from
1111 $ambiguous = true;
1112 $changed = false;
1113 if (!is_array($ldapkeys)) {
1114 $ldapkeys = array($ldapkeys);
1115 }
1116 if (count($ldapkeys) < 2) {
1117 $ambiguous = false;
1118 }
139ebfdb 1119
f8311def 1120 $nuvalue = textlib::convert($newuser->$key, 'utf-8', $this->config->ldapencoding);
15f80fd8 1121 empty($nuvalue) ? $nuvalue = array() : $nuvalue;
f8311def 1122 $ouvalue = textlib::convert($olduser->$key, 'utf-8', $this->config->ldapencoding);
139ebfdb 1123
b9ddb2d5 1124 foreach ($ldapkeys as $ldapkey) {
139ebfdb 1125 $ldapkey = $ldapkey;
b9ddb2d5 1126 $ldapvalue = $user_entry[$ldapkey][0];
1127 if (!$ambiguous) {
fcf46da1 1128 // Skip update if the values already match
139ebfdb 1129 if ($nuvalue !== $ldapvalue) {
fcf46da1 1130 // This might fail due to schema validation
139ebfdb 1131 if (@ldap_modify($ldapconnection, $user_dn, array($ldapkey => $nuvalue))) {
1132 continue;
1133 } else {
fcf46da1
I
1134 error_log($this->errorlogtag.get_string ('updateremfail', 'auth_ldap',
1135 array('errno'=>ldap_errno($ldapconnection),
1136 'errstring'=>ldap_err2str(ldap_errno($ldapconnection)),
1137 'key'=>$key,
1138 'ouvalue'=>$ouvalue,
1139 'nuvalue'=>$nuvalue)));
139ebfdb 1140 continue;
1141 }
b9ddb2d5 1142 }
139ebfdb 1143 } else {
fcf46da1
I
1144 // Ambiguous. Value empty before in Moodle (and LDAP) - use
1145 // 1st ldap candidate field, no need to guess
139ebfdb 1146 if ($ouvalue === '') { // value empty before - use 1st ldap candidate
fcf46da1 1147 // This might fail due to schema validation
139ebfdb 1148 if (@ldap_modify($ldapconnection, $user_dn, array($ldapkey => $nuvalue))) {
b9ddb2d5 1149 $changed = true;
139ebfdb 1150 continue;
1151 } else {
fcf46da1
I
1152 error_log($this->errorlogtag.get_string ('updateremfail', 'auth_ldap',
1153 array('errno'=>ldap_errno($ldapconnection),
1154 'errstring'=>ldap_err2str(ldap_errno($ldapconnection)),
1155 'key'=>$key,
1156 'ouvalue'=>$ouvalue,
1157 'nuvalue'=>$nuvalue)));
139ebfdb 1158 continue;
b9ddb2d5 1159 }
1160 }
1161
fcf46da1 1162 // We found which ldap key to update!
139ebfdb 1163 if ($ouvalue !== '' and $ouvalue === $ldapvalue ) {
fcf46da1 1164 // This might fail due to schema validation
139ebfdb 1165 if (@ldap_modify($ldapconnection, $user_dn, array($ldapkey => $nuvalue))) {
b9ddb2d5 1166 $changed = true;
139ebfdb 1167 continue;
1168 } else {
fcf46da1
I
1169 error_log($this->errorlogtag.get_string ('updateremfail', 'auth_ldap',
1170 array('errno'=>ldap_errno($ldapconnection),
1171 'errstring'=>ldap_err2str(ldap_errno($ldapconnection)),
1172 'key'=>$key,
1173 'ouvalue'=>$ouvalue,
1174 'nuvalue'=>$nuvalue)));
139ebfdb 1175 continue;
b9ddb2d5 1176 }
1177 }
1178 }
1179 }
139ebfdb 1180
b9ddb2d5 1181 if ($ambiguous and !$changed) {
fcf46da1
I
1182 error_log($this->errorlogtag.get_string ('updateremfailamb', 'auth_ldap',
1183 array('key'=>$key,
1184 'ouvalue'=>$ouvalue,
1185 'nuvalue'=>$nuvalue)));
b9ddb2d5 1186 }
1187 }
1188 }
139ebfdb 1189 } else {
fcf46da1 1190 error_log($this->errorlogtag.get_string ('usernotfound', 'auth_ldap'));
eee34307 1191 $this->ldap_close();
b9ddb2d5 1192 return false;
1193 }
1194
eee34307 1195 $this->ldap_close();
b9ddb2d5 1196 return true;
1197
1198 }
1199
fb5c7739 1200 /**
fcf46da1 1201 * Changes userpassword in LDAP
b9ddb2d5 1202 *
fcf46da1
I
1203 * Called when the user password is updated. It assumes it is
1204 * called by an admin or that you've otherwise checked the user's
1205 * credentials
b9ddb2d5 1206 *
ae040d4b 1207 * @param object $user User table object
fcf46da1 1208 * @param string $newpassword Plaintext password (not crypted/md5'ed)
b9ddb2d5 1209 * @return boolean result
1210 *
1211 */
b9ddb2d5 1212 function user_update_password($user, $newpassword) {
139ebfdb 1213 global $USER;
fcf46da1 1214
b9ddb2d5 1215 $result = false;
1216 $username = $user->username;
139ebfdb 1217
f8311def
PS
1218 $extusername = textlib::convert($username, 'utf-8', $this->config->ldapencoding);
1219 $extpassword = textlib::convert($newpassword, 'utf-8', $this->config->ldapencoding);
139ebfdb 1220
344514fc 1221 switch ($this->config->passtype) {
1222 case 'md5':
1223 $extpassword = '{MD5}' . base64_encode(pack('H*', md5($extpassword)));
1224 break;
1225 case 'sha1':
1226 $extpassword = '{SHA}' . base64_encode(pack('H*', sha1($extpassword)));
1227 break;
1228 case 'plaintext':
1229 default:
1230 break; // plaintext
1231 }
1232
b9ddb2d5 1233 $ldapconnection = $this->ldap_connect();
1234
139ebfdb 1235 $user_dn = $this->ldap_find_userdn($ldapconnection, $extusername);
1236
b9ddb2d5 1237 if (!$user_dn) {
fcf46da1 1238 error_log($this->errorlogtag.get_string ('nodnforusername', 'auth_ldap', $user->username));
b9ddb2d5 1239 return false;
1240 }
1241
1242 switch ($this->config->user_type) {
1243 case 'edir':
fcf46da1 1244 // Change password
139ebfdb 1245 $result = ldap_modify($ldapconnection, $user_dn, array('userPassword' => $extpassword));
b9ddb2d5 1246 if (!$result) {
fcf46da1
I
1247 error_log($this->errorlogtag.get_string ('updatepasserror', 'auth_ldap',
1248 array('errno'=>ldap_errno($ldapconnection),
1249 'errstring'=>ldap_err2str(ldap_errno($ldapconnection)))));
b9ddb2d5 1250 }
fcf46da1
I
1251 // Update password expiration time, grace logins count
1252 $search_attribs = array($this->config->expireattr, 'passwordExpirationInterval', 'loginGraceLimit');
cfcb7a17 1253 $sr = ldap_read($ldapconnection, $user_dn, '(objectClass=*)', $search_attribs);
fcf46da1
I
1254 if ($sr) {
1255 $entry = ldap_get_entries_moodle($ldapconnection, $sr);
1256 $info = array_change_key_case($entry[0], CASE_LOWER);
b9ddb2d5 1257 $newattrs = array();
fcf46da1
I
1258 if (!empty($info[$this->config->expireattr][0])) {
1259 // Set expiration time only if passwordExpirationInterval is defined
1260 if (!empty($info['passwordexpirationinterval'][0])) {
1261 $expirationtime = time() + $info['passwordexpirationinterval'][0];
b9ddb2d5 1262 $ldapexpirationtime = $this->ldap_unix2expirationtime($expirationtime);
1263 $newattrs['passwordExpirationTime'] = $ldapexpirationtime;
139ebfdb 1264 }
b9ddb2d5 1265
fcf46da1
I
1266 // Set gracelogin count
1267 if (!empty($info['logingracelimit'][0])) {
1268 $newattrs['loginGraceRemaining']= $info['logingracelimit'][0];
b9ddb2d5 1269 }
139ebfdb 1270
fcf46da1 1271 // Store attribute changes in LDAP
b9ddb2d5 1272 $result = ldap_modify($ldapconnection, $user_dn, $newattrs);
1273 if (!$result) {
fcf46da1
I
1274 error_log($this->errorlogtag.get_string ('updatepasserrorexpiregrace', 'auth_ldap',
1275 array('errno'=>ldap_errno($ldapconnection),
1276 'errstring'=>ldap_err2str(ldap_errno($ldapconnection)))));
b9ddb2d5 1277 }
1278 }
1279 }
1280 else {
fcf46da1
I
1281 error_log($this->errorlogtag.get_string ('updatepasserrorexpire', 'auth_ldap',
1282 array('errno'=>ldap_errno($ldapconnection),
1283 'errstring'=>ldap_err2str(ldap_errno($ldapconnection)))));
d0e84e1b 1284 }
1285 break;
1286
1287 case 'ad':
1288 // Passwords in Active Directory must be encoded as Unicode
1289 // strings (UCS-2 Little Endian format) and surrounded with
1290 // double quotes. See http://support.microsoft.com/?kbid=269190
1291 if (!function_exists('mb_convert_encoding')) {
fcf46da1 1292 error_log($this->errorlogtag.get_string ('needmbstring', 'auth_ldap'));
d0e84e1b 1293 return false;
1294 }
1295 $extpassword = mb_convert_encoding('"'.$extpassword.'"', "UCS-2LE", $this->config->ldapencoding);
1296 $result = ldap_modify($ldapconnection, $user_dn, array('unicodePwd' => $extpassword));
1297 if (!$result) {
fcf46da1
I
1298 error_log($this->errorlogtag.get_string ('updatepasserror', 'auth_ldap',
1299 array('errno'=>ldap_errno($ldapconnection),
1300 'errstring'=>ldap_err2str(ldap_errno($ldapconnection)))));
139ebfdb 1301 }
b9ddb2d5 1302 break;
139ebfdb 1303
b9ddb2d5 1304 default:
fcf46da1 1305 // Send LDAP the password in cleartext, it will md5 it itself
139ebfdb 1306 $result = ldap_modify($ldapconnection, $user_dn, array('userPassword' => $extpassword));
b9ddb2d5 1307 if (!$result) {
fcf46da1
I
1308 error_log($this->errorlogtag.get_string ('updatepasserror', 'auth_ldap',
1309 array('errno'=>ldap_errno($ldapconnection),
1310 'errstring'=>ldap_err2str(ldap_errno($ldapconnection)))));
b9ddb2d5 1311 }
139ebfdb 1312
b9ddb2d5 1313 }
1314
eee34307 1315 $this->ldap_close();
b9ddb2d5 1316 return $result;
1317 }
1318
b9ddb2d5 1319 /**
fcf46da1 1320 * Take expirationtime and return it as unix timestamp in seconds
b9ddb2d5 1321 *
fcf46da1
I
1322 * Takes expiration timestamp as read from LDAP and returns it as unix timestamp in seconds
1323 * Depends on $this->config->user_type variable
b9ddb2d5 1324 *
fcf46da1
I
1325 * @param mixed time Time stamp read from LDAP as it is.
1326 * @param string $ldapconnection Only needed for Active Directory.
1327 * @param string $user_dn User distinguished name for the user we are checking password expiration (only needed for Active Directory).
b9ddb2d5 1328 * @return timestamp
1329 */
bffe39c6 1330 function ldap_expirationtime2unix ($time, $ldapconnection, $user_dn) {
b9ddb2d5 1331 $result = false;
1332 switch ($this->config->user_type) {
1333 case 'edir':
fcf46da1
I
1334 $yr=substr($time, 0, 4);
1335 $mo=substr($time, 4, 2);
1336 $dt=substr($time, 6, 2);
1337 $hr=substr($time, 8, 2);
1338 $min=substr($time, 10, 2);
1339 $sec=substr($time, 12, 2);
1340 $result = mktime($hr, $min, $sec, $mo, $dt, $yr);
b9ddb2d5 1341 break;
9347082d 1342 case 'rfc2307':
1343 case 'rfc2307bis':
fcf46da1 1344 $result = $time * DAYSECS; // The shadowExpire contains the number of DAYS between 01/01/1970 and the actual expiration date
b9ddb2d5 1345 break;
bffe39c6 1346 case 'ad':
1347 $result = $this->ldap_get_ad_pwdexpire($time, $ldapconnection, $user_dn);
1348 break;
139ebfdb 1349 default:
2b06294b 1350 print_error('auth_ldap_usertypeundefined', 'auth_ldap');
b9ddb2d5 1351 }
1352 return $result;
1353 }
1354
1355 /**
fcf46da1 1356 * Takes unix timestamp and returns it formated for storing in LDAP
b9ddb2d5 1357 *
1358 * @param integer unix time stamp
1359 */
1360 function ldap_unix2expirationtime($time) {
b9ddb2d5 1361 $result = false;
1362 switch ($this->config->user_type) {
1363 case 'edir':
139ebfdb 1364 $result=date('YmdHis', $time).'Z';
b9ddb2d5 1365 break;
9347082d 1366 case 'rfc2307':
1367 case 'rfc2307bis':
fcf46da1 1368 $result = $time ; // Already in correct format
b9ddb2d5 1369 break;
139ebfdb 1370 default:
2b06294b 1371 print_error('auth_ldap_usertypeundefined2', 'auth_ldap');
139ebfdb 1372 }
b9ddb2d5 1373 return $result;
1374
1375 }
1376
139ebfdb 1377 /**
fcf46da1 1378 * Returns user attribute mappings between moodle and LDAP
b9ddb2d5 1379 *
1380 * @return array
1381 */
1382
1383 function ldap_attributes () {
b9ddb2d5 1384 $moodleattributes = array();
4105caff 1385 foreach ($this->userfields as $field) {
b9ddb2d5 1386 if (!empty($this->config->{"field_map_$field"})) {
6f3451e5 1387 $moodleattributes[$field] = textlib::strtolower(trim($this->config->{"field_map_$field"}));
fcf46da1 1388 if (preg_match('/,/', $moodleattributes[$field])) {
b9ddb2d5 1389 $moodleattributes[$field] = explode(',', $moodleattributes[$field]); // split ?
1390 }
1391 }
1392 }
6f3451e5 1393 $moodleattributes['username'] = textlib::strtolower(trim($this->config->user_attribute));
b9ddb2d5 1394 return $moodleattributes;
1395 }
1396
1397 /**
fcf46da1 1398 * Returns all usernames from LDAP
b9ddb2d5 1399 *
fcf46da1
I
1400 * @param $filter An LDAP search filter to select desired users
1401 * @return array of LDAP user names converted to UTF-8
b9ddb2d5 1402 */
fcf46da1 1403 function ldap_get_userlist($filter='*') {
b9ddb2d5 1404 $fresult = array();
1405
1406 $ldapconnection = $this->ldap_connect();
1407
fcf46da1 1408 if ($filter == '*') {
cfcb7a17 1409 $filter = '(&('.$this->config->user_attribute.'=*)'.$this->config->objectclass.')';
b9ddb2d5 1410 }
1411
fcf46da1 1412 $contexts = explode(';', $this->config->contexts);
b9ddb2d5 1413 if (!empty($this->config->create_context)) {
1414 array_push($contexts, $this->config->create_context);
1415 }
1416
1417 foreach ($contexts as $context) {
b9ddb2d5 1418 $context = trim($context);
1419 if (empty($context)) {
1420 continue;
1421 }
1422
1423 if ($this->config->search_sub) {
fcf46da1
I
1424 // Use ldap_search to find first user from subtree
1425 $ldap_result = ldap_search($ldapconnection, $context,
1426 $filter,
1427 array($this->config->user_attribute));
1428 } else {
1429 // Search only in this context
b9ddb2d5 1430 $ldap_result = ldap_list($ldapconnection, $context,
1431 $filter,
1432 array($this->config->user_attribute));
1433 }
139ebfdb 1434
fcf46da1
I
1435 if(!$ldap_result) {
1436 continue;
1437 }
1438
1439 $users = ldap_get_entries_moodle($ldapconnection, $ldap_result);
b9ddb2d5 1440
fcf46da1 1441 // Add found users to list
fcf46da1 1442 for ($i = 0; $i < count($users); $i++) {
f8311def 1443 $extuser = textlib::convert($users[$i][$this->config->user_attribute][0],
fcf46da1
I
1444 $this->config->ldapencoding, 'utf-8');
1445 array_push($fresult, $extuser);
b9ddb2d5 1446 }
1447 }
139ebfdb 1448
fcf46da1 1449 $this->ldap_close();
b9ddb2d5 1450 return $fresult;
1451 }
1452
1453 /**
fcf46da1 1454 * Indicates if password hashes should be stored in local moodle database.
b9ddb2d5 1455 *
fcf46da1 1456 * @return bool true means flag 'not_cached' stored instead of password hash
b9ddb2d5 1457 */
edb5da83
PS
1458 function prevent_local_passwords() {
1459 return !empty($this->config->preventpassindb);
1460 }
1461
b9ddb2d5 1462 /**
1463 * Returns true if this authentication plugin is 'internal'.
1464 *
139ebfdb 1465 * @return bool
b9ddb2d5 1466 */
1467 function is_internal() {
1468 return false;
1469 }
1470
1471 /**
1472 * Returns true if this authentication plugin can change the user's
1473 * password.
1474 *
139ebfdb 1475 * @return bool
b9ddb2d5 1476 */
1477 function can_change_password() {
430759a5 1478 return !empty($this->config->stdchangepassword) or !empty($this->config->changepasswordurl);
b9ddb2d5 1479 }
139ebfdb 1480
b9ddb2d5 1481 /**
fcf46da1 1482 * Returns the URL for changing the user's password, or empty if the default can
b9ddb2d5 1483 * be used.
1484 *
99f9f85f 1485 * @return moodle_url
b9ddb2d5 1486 */
1487 function change_password_url() {
139ebfdb 1488 if (empty($this->config->stdchangepassword)) {
99f9f85f 1489 return new moodle_url($this->config->changepasswordurl);
139ebfdb 1490 } else {
99f9f85f 1491 return null;
139ebfdb 1492 }
b9ddb2d5 1493 }
139ebfdb 1494
1e8713ea 1495 /**
fcf46da1 1496 * Will get called before the login page is shownr. Ff NTLM SSO
1e8713ea 1497 * is enabled, and the user is in the right network, we'll redirect
1498 * to the magic NTLM page for SSO...
1499 *
1500 */
1501 function loginpage_hook() {
4194d321 1502 global $CFG, $SESSION;
265edb48 1503
1504 // HTTPS is potentially required
17c70aa0 1505 //httpsrequired(); - this must be used before setting the URL, it is already done on the login/index.php
5117d598 1506
4194d321 1507 if (($_SERVER['REQUEST_METHOD'] === 'GET' // Only on initial GET of loginpage
fcf46da1
I
1508 || ($_SERVER['REQUEST_METHOD'] === 'POST'
1509 && (get_referer() != strip_querystring(qualified_me()))))
1510 // Or when POSTed from another place
1511 // See MDL-14071
1512 && !empty($this->config->ntlmsso_enabled) // SSO enabled
1513 && !empty($this->config->ntlmsso_subnet) // have a subnet to test for
1514 && empty($_GET['authldap_skipntlmsso']) // haven't failed it yet
1515 && (isguestuser() || !isloggedin()) // guestuser or not-logged-in users
b8aa76c1 1516 && address_in_subnet(getremoteaddr(), $this->config->ntlmsso_subnet)) {
4194d321 1517
1518 // First, let's remember where we were trying to get to before we got here
1519 if (empty($SESSION->wantsurl)) {
1520 $SESSION->wantsurl = (array_key_exists('HTTP_REFERER', $_SERVER) &&
1521 $_SERVER['HTTP_REFERER'] != $CFG->wwwroot &&
1522 $_SERVER['HTTP_REFERER'] != $CFG->wwwroot.'/' &&
1523 $_SERVER['HTTP_REFERER'] != $CFG->httpswwwroot.'/login/' &&
1524 $_SERVER['HTTP_REFERER'] != $CFG->httpswwwroot.'/login/index.php')
1525 ? $_SERVER['HTTP_REFERER'] : NULL;
1526 }
02c7f3d9 1527
4194d321 1528 // Now start the whole NTLM machinery.
16ceeb64 1529 if(!empty($this->config->ntlmsso_ie_fastpath)) {
fcf46da1 1530 // Shortcut for IE browsers: skip the attempt page
16ceeb64 1531 if(check_browser_version('MSIE')) {
1532 $sesskey = sesskey();
1533 redirect($CFG->wwwroot.'/auth/ldap/ntlmsso_magic.php?sesskey='.$sesskey);
1534 } else {
1535 redirect($CFG->httpswwwroot.'/login/index.php?authldap_skipntlmsso=1');
1536 }
1537 } else {
1538 redirect($CFG->wwwroot.'/auth/ldap/ntlmsso_attempt.php');
1539 }
4194d321 1540 }
5117d598 1541
4194d321 1542 // No NTLM SSO, Use the normal login page instead.
1543
1544 // If $SESSION->wantsurl is empty and we have a 'Referer:' header, the login
1545 // page insists on redirecting us to that page after user validation. If
fcf46da1
I
1546 // we clicked on the redirect link at the ntlmsso_finish.php page (instead
1547 // of waiting for the redirection to happen) then we have a 'Referer:' header
4194d321 1548 // we don't want to use at all. As we can't get rid of it, just point
1549 // $SESSION->wantsurl to $CFG->wwwroot (after all, we came from there).
1550 if (empty($SESSION->wantsurl)
1551 && (get_referer() == $CFG->httpswwwroot.'/auth/ldap/ntlmsso_finish.php')) {
1552
1553 $SESSION->wantsurl = $CFG->wwwroot;
1e8713ea 1554 }
1555 }
1556
1557 /**
1558 * To be called from a page running under NTLM's
5117d598 1559 * "Integrated Windows Authentication".
1e8713ea 1560 *
5117d598 1561 * If successful, it will set a special "cookie" (not an HTTP cookie!)
fcf46da1 1562 * in cache_flags under the $this->pluginconfig/ntlmsess "plugin" and return true.
1e8713ea 1563 * The "cookie" will be picked up by ntlmsso_finish() to complete the
1564 * process.
1565 *
1566 * On failure it will return false for the caller to display an appropriate
decd8016 1567 * error message (probably saying that Integrated Windows Auth isn't enabled!)
1e8713ea 1568 *
5117d598 1569 * NOTE that this code will execute under the OS user credentials,
1e8713ea 1570 * so we MUST avoid dealing with files -- such as session files.
6800d78e 1571 * (The caller should define('NO_MOODLE_COOKIES', true) before including config.php)
1e8713ea 1572 *
1573 */
decd8016 1574 function ntlmsso_magic($sesskey) {
1575 if (isset($_SERVER['REMOTE_USER']) && !empty($_SERVER['REMOTE_USER'])) {
4194d321 1576
1577 // HTTP __headers__ seem to be sent in ISO-8859-1 encoding
1578 // (according to my reading of RFC-1945, RFC-2616 and RFC-2617 and
1579 // my local tests), so we need to convert the REMOTE_USER value
1580 // (i.e., what we got from the HTTP WWW-Authenticate header) into UTF-8
f8311def 1581 $username = textlib::convert($_SERVER['REMOTE_USER'], 'iso-8859-1', 'utf-8');
4194d321 1582
fcf46da1
I
1583 switch ($this->config->ntlmsso_type) {
1584 case 'ntlm':
8d800a1b
EL
1585 // Format is DOMAIN\username
1586 $username = substr(strrchr($username, '\\'), 1);
fcf46da1
I
1587 break;
1588 case 'kerberos':
1589 // Format is username@DOMAIN
1590 $username = substr($username, 0, strpos($username, '@'));
1591 break;
1592 default:
1593 error_log($this->errorlogtag.get_string ('ntlmsso_unknowntype', 'auth_ldap'));
1594 return false; // Should never happen!
1595 }
1596
6f3451e5 1597 $username = textlib::strtolower($username); // Compatibility hack
fcf46da1 1598 set_cache_flag($this->pluginconfig.'/ntlmsess', $sesskey, $username, AUTH_NTLMTIMEOUT);
065e2cc0 1599 return true;
decd8016 1600 }
1601 return false;
1e8713ea 1602 }
1603
1604 /**
5117d598 1605 * Find the session set by ntlmsso_magic(), validate it and
decd8016 1606 * call authenticate_user_login() to authenticate the user through
1607 * the auth machinery.
5117d598 1608 *
decd8016 1609 * It is complemented by a similar check in user_login().
5117d598
PS
1610 *
1611 * If it succeeds, it never returns.
decd8016 1612 *
1e8713ea 1613 */
1614 function ntlmsso_finish() {
4025cf80 1615 global $CFG, $USER, $SESSION;
02c7f3d9 1616
065e2cc0 1617 $key = sesskey();
fcf46da1 1618 $cf = get_cache_flags($this->pluginconfig.'/ntlmsess');
58eada35 1619 if (!isset($cf[$key]) || $cf[$key] === '') {
065e2cc0 1620 return false;
1621 }
1622 $username = $cf[$key];
1623 // Here we want to trigger the whole authentication machinery
1624 // to make sure no step is bypassed...
1625 $user = authenticate_user_login($username, $key);
1626 if ($user) {
1627 add_to_log(SITEID, 'user', 'login', "view.php?id=$USER->id&course=".SITEID,
1628 $user->id, 0, $user->id);
b7b64ff2 1629 complete_user_login($user);
065e2cc0 1630
1631 // Cleanup the key to prevent reuse...
1632 // and to allow re-logins with normal credentials
fcf46da1 1633 unset_cache_flag($this->pluginconfig.'/ntlmsess', $key);
065e2cc0 1634
fcf46da1 1635 // Redirection
065e2cc0 1636 if (user_not_fully_set_up($USER)) {
1637 $urltogo = $CFG->wwwroot.'/user/edit.php';
1638 // We don't delete $SESSION->wantsurl yet, so we get there later
1639 } else if (isset($SESSION->wantsurl) and (strpos($SESSION->wantsurl, $CFG->wwwroot) === 0)) {
fcf46da1 1640 $urltogo = $SESSION->wantsurl; // Because it's an address in this site
065e2cc0 1641 unset($SESSION->wantsurl);
1642 } else {
fcf46da1 1643 // No wantsurl stored or external - go to homepage
065e2cc0 1644 $urltogo = $CFG->wwwroot.'/';
1645 unset($SESSION->wantsurl);
decd8016 1646 }
065e2cc0 1647 redirect($urltogo);
decd8016 1648 }
065e2cc0 1649 // Should never reach here.
decd8016 1650 return false;
5117d598 1651 }
1e8713ea 1652
6bc1e5d5 1653 /**
1654 * Sync roles for this user
1655 *
1656 * @param $user object user object (without system magic quotes)
1657 */
1658 function sync_roles($user) {
1659 $iscreator = $this->iscreator($user->username);
1660 if ($iscreator === null) {
fcf46da1 1661 return; // Nothing to sync - creators not configured
6bc1e5d5 1662 }
1663
4f0c2d00 1664 if ($roles = get_archetype_roles('coursecreator')) {
6bc1e5d5 1665 $creatorrole = array_shift($roles); // We can only use one, let's use the first one
1666 $systemcontext = get_context_instance(CONTEXT_SYSTEM);
1667
1668 if ($iscreator) { // Following calls will not create duplicates
fcf46da1 1669 role_assign($creatorrole->id, $user->id, $systemcontext->id, $this->roleauth);
6bc1e5d5 1670 } else {
fcf46da1
I
1671 // Unassign only if previously assigned by this plugin!
1672 role_unassign($creatorrole->id, $user->id, $systemcontext->id, $this->roleauth);
6bc1e5d5 1673 }
1674 }
1675 }
1676
b9ddb2d5 1677 /**
1678 * Prints a form for configuring this authentication plugin.
1679 *
1680 * This function is called from admin/auth.php, and outputs a full page with
1681 * a form for configuring this plugin.
1682 *
1683 * @param array $page An object containing all the data for this page.
1684 */
139ebfdb 1685 function config_form($config, $err, $user_fields) {
fcf46da1
I
1686 global $CFG, $OUTPUT;
1687
1688 if (!function_exists('ldap_connect')) { // Is php-ldap really there?
1689 echo $OUTPUT->notification(get_string('auth_ldap_noextension', 'auth_ldap'));
1690 return;
1691 }
95cb3955 1692
fcf46da1 1693 include($CFG->dirroot.'/auth/ldap/config.html');
b9ddb2d5 1694 }
1695
1696 /**
1697 * Processes and stores configuration data for this authentication plugin.
1698 */
1699 function process_config($config) {
fcf46da1
I
1700 // Set to defaults if undefined
1701 if (!isset($config->host_url)) {
1702 $config->host_url = '';
1703 }
1704 if (empty($config->ldapencoding)) {
1705 $config->ldapencoding = 'utf-8';
1706 }
1707 if (!isset($config->contexts)) {
1708 $config->contexts = '';
1709 }
1710 if (!isset($config->user_type)) {
1711 $config->user_type = 'default';
1712 }
1713 if (!isset($config->user_attribute)) {
1714 $config->user_attribute = '';
1715 }
1716 if (!isset($config->search_sub)) {
1717 $config->search_sub = '';
1718 }
1719 if (!isset($config->opt_deref)) {
1720 $config->opt_deref = LDAP_DEREF_NEVER;
1721 }
1722 if (!isset($config->preventpassindb)) {
1723 $config->preventpassindb = 0;
1724 }
1725 if (!isset($config->bind_dn)) {
1726 $config->bind_dn = '';
1727 }
1728 if (!isset($config->bind_pw)) {
1729 $config->bind_pw = '';
1730 }
1731 if (!isset($config->ldap_version)) {
1732 $config->ldap_version = '3';
1733 }
1734 if (!isset($config->objectclass)) {
1735 $config->objectclass = '';
1736 }
1737 if (!isset($config->memberattribute)) {
1738 $config->memberattribute = '';
1739 }
1740 if (!isset($config->memberattribute_isdn)) {
1741 $config->memberattribute_isdn = '';
1742 }
1743 if (!isset($config->creators)) {
1744 $config->creators = '';
1745 }
1746 if (!isset($config->create_context)) {
1747 $config->create_context = '';
1748 }
1749 if (!isset($config->expiration)) {
1750 $config->expiration = '';
1751 }
1752 if (!isset($config->expiration_warning)) {
1753 $config->expiration_warning = '10';
1754 }
1755 if (!isset($config->expireattr)) {
1756 $config->expireattr = '';
1757 }
1758 if (!isset($config->gracelogins)) {
1759 $config->gracelogins = '';
1760 }
1761 if (!isset($config->graceattr)) {
1762 $config->graceattr = '';
1763 }
1764 if (!isset($config->auth_user_create)) {
1765 $config->auth_user_create = '';
1766 }
1767 if (!isset($config->forcechangepassword)) {
1768 $config->forcechangepassword = 0;
1769 }
1770 if (!isset($config->stdchangepassword)) {
1771 $config->stdchangepassword = 0;
1772 }
1773 if (!isset($config->passtype)) {
1774 $config->passtype = 'plaintext';
1775 }
1776 if (!isset($config->changepasswordurl)) {
1777 $config->changepasswordurl = '';
1778 }
1779 if (!isset($config->removeuser)) {
1780 $config->removeuser = AUTH_REMOVEUSER_KEEP;
1781 }
1782 if (!isset($config->ntlmsso_enabled)) {
1783 $config->ntlmsso_enabled = 0;
1784 }
1785 if (!isset($config->ntlmsso_subnet)) {
1786 $config->ntlmsso_subnet = '';
1787 }
1788 if (!isset($config->ntlmsso_ie_fastpath)) {
1789 $config->ntlmsso_ie_fastpath = 0;
1790 }
1791 if (!isset($config->ntlmsso_type)) {
1792 $config->ntlmsso_type = 'ntlm';
1793 }
b9ddb2d5 1794
ca769fa7
IA
1795 // Try to remove duplicates before storing the contexts (to avoid problems in sync_users()).
1796 $config->contexts = explode(';', $config->contexts);
1797 $config->contexts = array_map(create_function('$x', 'return textlib::strtolower(trim($x));'),
1798 $config->contexts);
1799 $config->contexts = implode(';', array_unique($config->contexts));
1800
fcf46da1
I
1801 // Save settings
1802 set_config('host_url', trim($config->host_url), $this->pluginconfig);
1803 set_config('ldapencoding', trim($config->ldapencoding), $this->pluginconfig);
ca769fa7 1804 set_config('contexts', $config->contexts, $this->pluginconfig);
6f3451e5
PS
1805 set_config('user_type', textlib::strtolower(trim($config->user_type)), $this->pluginconfig);
1806 set_config('user_attribute', textlib::strtolower(trim($config->user_attribute)), $this->pluginconfig);
fcf46da1
I
1807 set_config('search_sub', $config->search_sub, $this->pluginconfig);
1808 set_config('opt_deref', $config->opt_deref, $this->pluginconfig);
1809 set_config('preventpassindb', $config->preventpassindb, $this->pluginconfig);
1810 set_config('bind_dn', trim($config->bind_dn), $this->pluginconfig);
1811 set_config('bind_pw', $config->bind_pw, $this->pluginconfig);
1812 set_config('ldap_version', $config->ldap_version, $this->pluginconfig);
1813 set_config('objectclass', trim($config->objectclass), $this->pluginconfig);
6f3451e5 1814 set_config('memberattribute', textlib::strtolower(trim($config->memberattribute)), $this->pluginconfig);
fcf46da1
I
1815 set_config('memberattribute_isdn', $config->memberattribute_isdn, $this->pluginconfig);
1816 set_config('creators', trim($config->creators), $this->pluginconfig);
1817 set_config('create_context', trim($config->create_context), $this->pluginconfig);
1818 set_config('expiration', $config->expiration, $this->pluginconfig);
1819 set_config('expiration_warning', trim($config->expiration_warning), $this->pluginconfig);
6f3451e5 1820 set_config('expireattr', textlib::strtolower(trim($config->expireattr)), $this->pluginconfig);
fcf46da1 1821 set_config('gracelogins', $config->gracelogins, $this->pluginconfig);
6f3451e5 1822 set_config('graceattr', textlib::strtolower(trim($config->graceattr)), $this->pluginconfig);
fcf46da1
I
1823 set_config('auth_user_create', $config->auth_user_create, $this->pluginconfig);
1824 set_config('forcechangepassword', $config->forcechangepassword, $this->pluginconfig);
1825 set_config('stdchangepassword', $config->stdchangepassword, $this->pluginconfig);
1826 set_config('passtype', $config->passtype, $this->pluginconfig);
1827 set_config('changepasswordurl', trim($config->changepasswordurl), $this->pluginconfig);
1828 set_config('removeuser', $config->removeuser, $this->pluginconfig);
1829 set_config('ntlmsso_enabled', (int)$config->ntlmsso_enabled, $this->pluginconfig);
1830 set_config('ntlmsso_subnet', trim($config->ntlmsso_subnet), $this->pluginconfig);
1831 set_config('ntlmsso_ie_fastpath', (int)$config->ntlmsso_ie_fastpath, $this->pluginconfig);
1832 set_config('ntlmsso_type', $config->ntlmsso_type, 'auth/ldap');
139ebfdb 1833
fcf46da1 1834 return true;
139ebfdb 1835 }
bffe39c6 1836
1837 /**
1838 * Get password expiration time for a given user from Active Directory
1839 *
1840 * @param string $pwdlastset The time last time we changed the password.
1841 * @param resource $lcapconn The open LDAP connection.
1842 * @param string $user_dn The distinguished name of the user we are checking.
1843 *
1844 * @return string $unixtime
1845 */
1846 function ldap_get_ad_pwdexpire($pwdlastset, $ldapconn, $user_dn){
bffe39c6 1847 global $CFG;
1848
1849 if (!function_exists('bcsub')) {
fcf46da1 1850 error_log($this->errorlogtag.get_string ('needbcmath', 'auth_ldap'));
bffe39c6 1851 return 0;
1852 }
1853
1854 // If UF_DONT_EXPIRE_PASSWD flag is set in user's
1855 // userAccountControl attribute, the password doesn't expire.
cfcb7a17 1856 $sr = ldap_read($ldapconn, $user_dn, '(objectClass=*)',
bffe39c6 1857 array('userAccountControl'));
1858 if (!$sr) {
fcf46da1
I
1859 error_log($this->errorlogtag.get_string ('useracctctrlerror', 'auth_ldap', $user_dn));
1860 // Don't expire password, as we are not sure if it has to be
bffe39c6 1861 // expired or not.
1862 return 0;
1863 }
e295df44 1864
fcf46da1
I
1865 $entry = ldap_get_entries_moodle($ldapconn, $sr);
1866 $info = array_change_key_case($entry[0], CASE_LOWER);
1867 $useraccountcontrol = $info['useraccountcontrol'][0];
bffe39c6 1868 if ($useraccountcontrol & UF_DONT_EXPIRE_PASSWD) {
fcf46da1 1869 // Password doesn't expire.
bffe39c6 1870 return 0;
1871 }
e295df44 1872
bffe39c6 1873 // If pwdLastSet is zero, the user must change his/her password now
1874 // (unless UF_DONT_EXPIRE_PASSWD flag is set, but we already
1875 // tested this above)
1876 if ($pwdlastset === '0') {
fcf46da1 1877 // Password has expired
bffe39c6 1878 return -1;
1879 }
e295df44 1880
bffe39c6 1881 // ----------------------------------------------------------------
1882 // Password expiration time in Active Directory is the composition of
1883 // two values:
1884 //
1885 // - User's pwdLastSet attribute, that stores the last time
1886 // the password was changed.
1887 //
1888 // - Domain's maxPwdAge attribute, that sets how long
1889 // passwords last in this domain.
1890 //
1891 // We already have the first value (passed in as a parameter). We
1892 // need to get the second one. As we don't know the domain DN, we
1893 // have to query rootDSE's defaultNamingContext attribute to get
1894 // it. Then we have to query that DN's maxPwdAge attribute to get
1895 // the real value.
1896 //
1897 // Once we have both values, we just need to combine them. But MS
1898 // chose to use a different base and unit for time measurements.
1899 // So we need to convert the values to Unix timestamps (see
1900 // details below).
1901 // ----------------------------------------------------------------
e295df44 1902
cfcb7a17 1903 $sr = ldap_read($ldapconn, ROOTDSE, '(objectClass=*)',
bffe39c6 1904 array('defaultNamingContext'));
1905 if (!$sr) {
fcf46da1 1906 error_log($this->errorlogtag.get_string ('rootdseerror', 'auth_ldap'));
bffe39c6 1907 return 0;
1908 }
e295df44 1909
fcf46da1
I
1910 $entry = ldap_get_entries_moodle($ldapconn, $sr);
1911 $info = array_change_key_case($entry[0], CASE_LOWER);
1912 $domaindn = $info['defaultnamingcontext'][0];
e295df44 1913
cfcb7a17 1914 $sr = ldap_read ($ldapconn, $domaindn, '(objectClass=*)',
bffe39c6 1915 array('maxPwdAge'));
fcf46da1
I
1916 $entry = ldap_get_entries_moodle($ldapconn, $sr);
1917 $info = array_change_key_case($entry[0], CASE_LOWER);
1918 $maxpwdage = $info['maxpwdage'][0];
bffe39c6 1919
1920 // ----------------------------------------------------------------
1921 // MSDN says that "pwdLastSet contains the number of 100 nanosecond
1922 // intervals since January 1, 1601 (UTC), stored in a 64 bit integer".
1923 //
1924 // According to Perl's Date::Manip, the number of seconds between
1925 // this date and Unix epoch is 11644473600. So we have to
1926 // substract this value to calculate a Unix time, once we have
1927 // scaled pwdLastSet to seconds. This is the script used to
1928 // calculate the value shown above:
1929 //
1930 // #!/usr/bin/perl -w
1931 //
1932 // use Date::Manip;
1933 //
1934 // $date1 = ParseDate ("160101010000 UTC");
1935 // $date2 = ParseDate ("197001010000 UTC");
1936 // $delta = DateCalc($date1, $date2, \$err);
1937 // $secs = Delta_Format($delta, 0, "%st");
1938 // print "$secs \n";
1939 //
1940 // MSDN also says that "maxPwdAge is stored as a large integer that
1941 // represents the number of 100 nanosecond intervals from the time
1942 // the password was set before the password expires." We also need
1943 // to scale this to seconds. Bear in mind that this value is stored
1944 // as a _negative_ quantity (at least in my AD domain).
1945 //
1946 // As a last remark, if the low 32 bits of maxPwdAge are equal to 0,
1947 // the maximum password age in the domain is set to 0, which means
e295df44 1948 // passwords do not expire (see
bffe39c6 1949 // http://msdn2.microsoft.com/en-us/library/ms974598.aspx)
1950 //
1951 // As the quantities involved are too big for PHP integers, we
1952 // need to use BCMath functions to work with arbitrary precision
1953 // numbers.
1954 // ----------------------------------------------------------------
e295df44 1955
bffe39c6 1956 // If the low order 32 bits are 0, then passwords do not expire in
1957 // the domain. Just do '$maxpwdage mod 2^32' and check the result
1958 // (2^32 = 4294967296)
1959 if (bcmod ($maxpwdage, 4294967296) === '0') {
1960 return 0;
1961 }
1962
1963 // Add up pwdLastSet and maxPwdAge to get password expiration
1964 // time, in MS time units. Remember maxPwdAge is stored as a
1965 // _negative_ quantity, so we need to substract it in fact.
1966 $pwdexpire = bcsub ($pwdlastset, $maxpwdage);
e295df44 1967
bffe39c6 1968 // Scale the result to convert it to Unix time units and return
1969 // that value.
1970 return bcsub( bcdiv($pwdexpire, '10000000'), '11644473600');
1971 }
1972
fcf46da1
I
1973 /**
1974 * Connect to the LDAP server, using the plugin configured
1975 * settings. It's actually a wrapper around ldap_connect_moodle()
1976 *
1977 * @return resource A valid LDAP connection (or dies if it can't connect)
1978 */
1979 function ldap_connect() {
1980 // Cache ldap connections. They are expensive to set up
1981 // and can drain the TCP/IP ressources on the server if we
1982 // are syncing a lot of users (as we try to open a new connection
1983 // to get the user details). This is the least invasive way
1984 // to reuse existing connections without greater code surgery.
1985 if(!empty($this->ldapconnection)) {
1986 $this->ldapconns++;
1987 return $this->ldapconnection;
1988 }
1989
1990 if($ldapconnection = ldap_connect_moodle($this->config->host_url, $this->config->ldap_version,
1991 $this->config->user_type, $this->config->bind_dn,
1992 $this->config->bind_pw, $this->config->opt_deref,
1993 $debuginfo)) {
1994 $this->ldapconns = 1;
1995 $this->ldapconnection = $ldapconnection;
1996 return $ldapconnection;
1997 }
b9ddb2d5 1998
fcf46da1
I
1999 print_error('auth_ldap_noconnect_all', 'auth_ldap', '', $debuginfo);
2000 }
2001
2002 /**
2003 * Disconnects from a LDAP server
2004 *
2005 */
2006 function ldap_close() {
2007 $this->ldapconns--;
2008 if($this->ldapconns == 0) {
2009 @ldap_close($this->ldapconnection);
2010 unset($this->ldapconnection);
2011 }
2012 }
2013
2014 /**
2015 * Search specified contexts for username and return the user dn
2016 * like: cn=username,ou=suborg,o=org. It's actually a wrapper
2017 * around ldap_find_userdn().
2018 *
2019 * @param resource $ldapconnection a valid LDAP connection
2020 * @param string $extusername the username to search (in external LDAP encoding, no db slashes)
2021 * @return mixed the user dn (external LDAP encoding) or false
2022 */
2023 function ldap_find_userdn($ldapconnection, $extusername) {
2024 $ldap_contexts = explode(';', $this->config->contexts);
2025 if (!empty($this->config->create_context)) {
2026 array_push($ldap_contexts, $this->config->create_context);
2027 }
2028
2029 return ldap_find_userdn($ldapconnection, $extusername, $ldap_contexts, $this->config->objectclass,
2030 $this->config->user_attribute, $this->config->search_sub);
2031 }
5117d598 2032
fcf46da1 2033} // End of the class