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