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