MDL-51723 ldap: Normalise the user objectclass
[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
I
91 function init_plugin($authtype) {
92 $this->pluginconfig = 'auth/'.$authtype;
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) {
fcf46da1
I
279 $entry = array_change_key_case($user_entry[0], CASE_LOWER);
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
IA
636 if (!empty ($info)) {
637 $info = array_change_key_case($info[0], CASE_LOWER);
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
c090d7c9
IA
698 $ldap_pagedresults = ldap_paged_results_supported($this->config->ldap_version);
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 }
b9ddb2d5 852 unset($all_keys); unset($key);
139ebfdb 853
fa96bfaa 854 } else {
fcf46da1 855 print_string('noupdatestobedone', 'auth_ldap');
b9ddb2d5 856 }
fcf46da1
I
857 if ($do_updates and !empty($updatekeys)) { // run updates only if relevant
858 $users = $DB->get_records_sql('SELECT u.username, u.id
df884cd8 859 FROM {user} u
fcf46da1
I
860 WHERE u.deleted = 0 AND u.auth = ? AND u.mnethostid = ?',
861 array($this->authtype, $CFG->mnet_localhost_id));
b9ddb2d5 862 if (!empty($users)) {
fcf46da1 863 print_string('userentriestoupdate', 'auth_ldap', count($users));
139ebfdb 864
bf0f06b1 865 $sitecontext = context_system::instance();
139ebfdb 866 if (!empty($this->config->creators) and !empty($this->config->memberattribute)
4f0c2d00 867 and $roles = get_archetype_roles('coursecreator')) {
139ebfdb 868 $creatorrole = array_shift($roles); // We can only use one, let's use the first one
869 } else {
870 $creatorrole = false;
871 }
b9ddb2d5 872
d5a8d9aa 873 $transaction = $DB->start_delegated_transaction();
139ebfdb 874 $xcount = 0;
875 $maxxcount = 100;
b9ddb2d5 876
139ebfdb 877 foreach ($users as $user) {
2c10db3b 878 echo "\t"; print_string('auth_dbupdatinguser', 'auth_db', array('name'=>$user->username, 'id'=>$user->id));
7b9643b5 879 if (!$this->update_user_record($user->username, $updatekeys, true)) {
fcf46da1 880 echo ' - '.get_string('skipped');
139ebfdb 881 }
882 echo "\n";
883 $xcount++;
884
fcf46da1 885 // Update course creators if needed
139ebfdb 886 if ($creatorrole !== false) {
887 if ($this->iscreator($user->username)) {
fcf46da1 888 role_assign($creatorrole->id, $user->id, $sitecontext->id, $this->roleauth);
139ebfdb 889 } else {
fcf46da1 890 role_unassign($creatorrole->id, $user->id, $sitecontext->id, $this->roleauth);
b9ddb2d5 891 }
139ebfdb 892 }
b9ddb2d5 893 }
d5a8d9aa 894 $transaction->allow_commit();
139ebfdb 895 unset($users); // free mem
b9ddb2d5 896 }
fa96bfaa 897 } else { // end do updates
fcf46da1 898 print_string('noupdatestobedone', 'auth_ldap');
fa96bfaa 899 }
139ebfdb 900
901/// User Additions
fcf46da1 902 // Find users missing in DB that are in LDAP
b9ddb2d5 903 // and gives me a nifty object I don't want.
139ebfdb 904 // note: we do not care about deleted accounts anymore, this feature was replaced by suspending to nologin auth plugin
fcf46da1
I
905 $sql = 'SELECT e.id, e.username
906 FROM {tmp_extuser} e
907 LEFT JOIN {user} u ON (e.username = u.username AND e.mnethostid = u.mnethostid)
908 WHERE u.id IS NULL';
909 $add_users = $DB->get_records_sql($sql);
139ebfdb 910
b9ddb2d5 911 if (!empty($add_users)) {
fcf46da1 912 print_string('userentriestoadd', 'auth_ldap', count($add_users));
b9ddb2d5 913
bf0f06b1 914 $sitecontext = context_system::instance();
139ebfdb 915 if (!empty($this->config->creators) and !empty($this->config->memberattribute)
4f0c2d00 916 and $roles = get_archetype_roles('coursecreator')) {
b9ddb2d5 917 $creatorrole = array_shift($roles); // We can only use one, let's use the first one
139ebfdb 918 } else {
919 $creatorrole = false;
b9ddb2d5 920 }
921
d5a8d9aa 922 $transaction = $DB->start_delegated_transaction();
b9ddb2d5 923 foreach ($add_users as $user) {
df884cd8 924 $user = $this->get_userinfo_asobj($user->username);
139ebfdb 925
fcf46da1 926 // Prep a few params
b7b50143 927 $user->modified = time();
928 $user->confirmed = 1;
fcf46da1 929 $user->auth = $this->authtype;
b7b50143 930 $user->mnethostid = $CFG->mnet_localhost_id;
997bcd9e 931 // get_userinfo_asobj() might have replaced $user->username with the value
932 // from the LDAP server (which can be mixed-case). Make sure it's lowercase
2f1e464a 933 $user->username = trim(core_text::strtolower($user->username));
139ebfdb 934 if (empty($user->lang)) {
935 $user->lang = $CFG->lang;
b9ddb2d5 936 }
8bf0f207
MN
937 if (empty($user->calendartype)) {
938 $user->calendartype = $CFG->calendartype;
939 }
139ebfdb 940
bb78e249 941 $id = user_create_user($user, false);
a9637e7d 942 echo "\t"; print_string('auth_dbinsertuser', 'auth_db', array('name'=>$user->username, 'id'=>$id)); echo "\n";
a9166e82 943 $euser = $DB->get_record('user', array('id' => $id));
bb78e249 944
a9637e7d
PS
945 if (!empty($this->config->forcechangepassword)) {
946 set_user_preference('auth_forcepasswordchange', 1, $id);
947 }
3e5f4b87 948
a9637e7d
PS
949 // Add course creators if needed
950 if ($creatorrole !== false and $this->iscreator($user->username)) {
951 role_assign($creatorrole->id, $id, $sitecontext->id, $this->roleauth);
139ebfdb 952 }
953
b9ddb2d5 954 }
d5a8d9aa 955 $transaction->allow_commit();
b9ddb2d5 956 unset($add_users); // free mem
fa96bfaa 957 } else {
fcf46da1 958 print_string('nouserstobeadded', 'auth_ldap');
b9ddb2d5 959 }
df884cd8 960
a66b2ae4 961 $dbman->drop_table($table);
eee34307 962 $this->ldap_close();
df884cd8 963
b9ddb2d5 964 return true;
965 }
966
139ebfdb 967 /**
968 * Update a local user record from an external source.
969 * This is a lighter version of the one in moodlelib -- won't do
b9ddb2d5 970 * expensive ops such as enrolment.
971 *
139ebfdb 972 * If you don't pass $updatekeys, there is a performance hit and
973 * values removed from LDAP won't be removed from moodle.
974 *
185721a4 975 * @param string $username username
fcf46da1 976 * @param boolean $updatekeys true to update the local record with the external LDAP values.
7b9643b5
MW
977 * @param bool $triggerevent set false if user_updated event should not be triggered.
978 * This will not affect user_password_updated event triggering.
979 * @return stdClass|bool updated user record or false if there is no new info to update.
b9ddb2d5 980 */
870d1aae 981 function update_user_record($username, $updatekeys = false, $triggerevent = false) {
1aa66713 982 global $CFG, $DB;
b9ddb2d5 983
fcf46da1 984 // Just in case check text case
2f1e464a 985 $username = trim(core_text::strtolower($username));
139ebfdb 986
fcf46da1 987 // Get the current user record
185721a4 988 $user = $DB->get_record('user', array('username'=>$username, 'mnethostid'=>$CFG->mnet_localhost_id));
b9ddb2d5 989 if (empty($user)) { // trouble
fcf46da1
I
990 error_log($this->errorlogtag.get_string('auth_dbusernotexist', 'auth_db', '', $username));
991 print_error('auth_dbusernotexist', 'auth_db', '', $username);
b9ddb2d5 992 die;
993 }
994
b7b50143 995 // Protect the userid from being overwritten
996 $userid = $user->id;
997
139ebfdb 998 if ($newinfo = $this->get_userinfo($username)) {
999 $newinfo = truncate_userinfo($newinfo);
1000
1001 if (empty($updatekeys)) { // all keys? this does not support removing values
1002 $updatekeys = array_keys($newinfo);
1003 }
1004
bb78e249
RT
1005 if (!empty($updatekeys)) {
1006 $newuser = new stdClass();
1007 $newuser->id = $userid;
1008
1009 foreach ($updatekeys as $key) {
1010 if (isset($newinfo[$key])) {
1011 $value = $newinfo[$key];
1012 } else {
1013 $value = '';
1014 }
139ebfdb 1015
bb78e249
RT
1016 if (!empty($this->config->{'field_updatelocal_' . $key})) {
1017 // Only update if it's changed.
1018 if ($user->{$key} != $value) {
1019 $newuser->$key = $value;
1020 }
b9ddb2d5 1021 }
1022 }
7b9643b5 1023 user_update_user($newuser, false, $triggerevent);
9b8e4952 1024 }
139ebfdb 1025 } else {
1026 return false;
b9ddb2d5 1027 }
185721a4 1028 return $DB->get_record('user', array('id'=>$userid, 'deleted'=>0));
b9ddb2d5 1029 }
1030
139ebfdb 1031 /**
1032 * Bulk insert in SQL's temp table
139ebfdb 1033 */
df884cd8 1034 function ldap_bulk_insert($username) {
fcf46da1 1035 global $DB, $CFG;
df884cd8 1036
2f1e464a 1037 $username = core_text::strtolower($username); // usernames are __always__ lowercase.
fcf46da1
I
1038 $DB->insert_record_raw('tmp_extuser', array('username'=>$username,
1039 'mnethostid'=>$CFG->mnet_localhost_id), false, true);
1040 echo '.';
b9ddb2d5 1041 }
1042
139ebfdb 1043 /**
fcf46da1 1044 * Activates (enables) user in external LDAP so user can login
b9ddb2d5 1045 *
df884cd8 1046 * @param mixed $username
fcf46da1 1047 * @return boolean result
b9ddb2d5 1048 */
1049 function user_activate($username) {
2f1e464a 1050 $extusername = core_text::convert($username, 'utf-8', $this->config->ldapencoding);
139ebfdb 1051
b9ddb2d5 1052 $ldapconnection = $this->ldap_connect();
1053
139ebfdb 1054 $userdn = $this->ldap_find_userdn($ldapconnection, $extusername);
b9ddb2d5 1055 switch ($this->config->user_type) {
1056 case 'edir':
fcf46da1
I
1057 $newinfo['loginDisabled'] = 'FALSE';
1058 break;
1059 case 'rfc2307':
1060 case 'rfc2307bis':
1061 // Remember that we add a '*' character in front of the
1062 // external password string to 'disable' the account. We just
1063 // need to remove it.
1064 $sr = ldap_read($ldapconnection, $userdn, '(objectClass=*)',
1065 array('userPassword'));
1066 $info = ldap_get_entries($ldapconnection, $sr);
1067 $info[0] = array_change_key_case($info[0], CASE_LOWER);
1068 $newinfo['userPassword'] = ltrim($info[0]['userpassword'][0], '*');
b9ddb2d5 1069 break;
81fb221d 1070 case 'ad':
1071 // We need to unset the ACCOUNTDISABLE bit in the
1072 // userAccountControl attribute ( see
1073 // http://support.microsoft.com/kb/305144 )
1074 $sr = ldap_read($ldapconnection, $userdn, '(objectClass=*)',
1075 array('userAccountControl'));
1076 $info = ldap_get_entries($ldapconnection, $sr);
fcf46da1
I
1077 $info[0] = array_change_key_case($info[0], CASE_LOWER);
1078 $newinfo['userAccountControl'] = $info[0]['useraccountcontrol'][0]
81fb221d 1079 & (~AUTH_AD_ACCOUNTDISABLE);
1080 break;
b9ddb2d5 1081 default:
fcf46da1 1082 print_error('user_activatenotsupportusertype', 'auth_ldap', '', $this->config->user_type_name);
139ebfdb 1083 }
b9ddb2d5 1084 $result = ldap_modify($ldapconnection, $userdn, $newinfo);
eee34307 1085 $this->ldap_close();
b9ddb2d5 1086 return $result;
1087 }
1088
139ebfdb 1089 /**
b9ddb2d5 1090 * Returns true if user should be coursecreator.
1091 *
6bc1e5d5 1092 * @param mixed $username username (without system magic quotes)
fcf46da1 1093 * @return mixed result null if course creators is not configured, boolean otherwise.
b9ddb2d5 1094 */
6bc1e5d5 1095 function iscreator($username) {
139ebfdb 1096 if (empty($this->config->creators) or empty($this->config->memberattribute)) {
6bc1e5d5 1097 return null;
b9ddb2d5 1098 }
139ebfdb 1099
2f1e464a 1100 $extusername = core_text::convert($username, 'utf-8', $this->config->ldapencoding);
139ebfdb 1101
fcf46da1
I
1102 $ldapconnection = $this->ldap_connect();
1103
1104 if ($this->config->memberattribute_isdn) {
1105 if(!($userid = $this->ldap_find_userdn($ldapconnection, $extusername))) {
1106 return false;
1107 }
1108 } else {
1109 $userid = $extusername;
1110 }
1111
1112 $group_dns = explode(';', $this->config->creators);
1113 $creator = ldap_isgroupmember($ldapconnection, $userid, $group_dns, $this->config->memberattribute);
1114
1115 $this->ldap_close();
1116
1117 return $creator;
b9ddb2d5 1118 }
1119
139ebfdb 1120 /**
b9ddb2d5 1121 * Called when the user record is updated.
fcf46da1
I
1122 *
1123 * Modifies user in external LDAP server. It takes olduser (before
1124 * changes) and newuser (after changes) compares information and
1125 * saves modified information to external LDAP server.
b9ddb2d5 1126 *
139ebfdb 1127 * @param mixed $olduser Userobject before modifications (without system magic quotes)
1128 * @param mixed $newuser Userobject new modified userobject (without system magic quotes)
b9ddb2d5 1129 * @return boolean result
1130 *
1131 */
1132 function user_update($olduser, $newuser) {
139ebfdb 1133 global $USER;
1134
1135 if (isset($olduser->username) and isset($newuser->username) and $olduser->username != $newuser->username) {
fcf46da1 1136 error_log($this->errorlogtag.get_string('renamingnotallowed', 'auth_ldap'));
139ebfdb 1137 return false;
1138 }
1139
fcf46da1 1140 if (isset($olduser->auth) and $olduser->auth != $this->authtype) {
139ebfdb 1141 return true; // just change auth and skip update
1142 }
1143
1e3eee5f 1144 $attrmap = $this->ldap_attributes();
fcf46da1 1145 // Before doing anything else, make sure we really need to update anything
1e3eee5f 1146 // in the external LDAP server.
1147 $update_external = false;
1148 foreach ($attrmap as $key => $ldapkeys) {
1149 if (!empty($this->config->{'field_updateremote_'.$key})) {
1150 $update_external = true;
1151 break;
1152 }
1153 }
1154 if (!$update_external) {
1155 return true;
1156 }
1157
2f1e464a 1158 $extoldusername = core_text::convert($olduser->username, 'utf-8', $this->config->ldapencoding);
b9ddb2d5 1159
1160 $ldapconnection = $this->ldap_connect();
139ebfdb 1161
b9ddb2d5 1162 $search_attribs = array();
b9ddb2d5 1163 foreach ($attrmap as $key => $values) {
1164 if (!is_array($values)) {
1165 $values = array($values);
1166 }
1167 foreach ($values as $value) {
1168 if (!in_array($value, $search_attribs)) {
1169 array_push($search_attribs, $value);
1170 }
139ebfdb 1171 }
b9ddb2d5 1172 }
1173
fcf46da1
I
1174 if(!($user_dn = $this->ldap_find_userdn($ldapconnection, $extoldusername))) {
1175 return false;
1176 }
b9ddb2d5 1177
a8451603 1178 $success = true;
fcf46da1 1179 $user_info_result = ldap_read($ldapconnection, $user_dn, '(objectClass=*)', $search_attribs);
b9ddb2d5 1180 if ($user_info_result) {
fcf46da1 1181 $user_entry = ldap_get_entries_moodle($ldapconnection, $user_info_result);
139ebfdb 1182 if (empty($user_entry)) {
fcf46da1
I
1183 $attribs = join (', ', $search_attribs);
1184 error_log($this->errorlogtag.get_string('updateusernotfound', 'auth_ldap',
99f9f85f 1185 array('userdn'=>$user_dn,
fcf46da1 1186 'attribs'=>$attribs)));
139ebfdb 1187 return false; // old user not found!
1188 } else if (count($user_entry) > 1) {
fcf46da1 1189 error_log($this->errorlogtag.get_string('morethanoneuser', 'auth_ldap'));
139ebfdb 1190 return false;
b9ddb2d5 1191 }
b9ddb2d5 1192
fcf46da1 1193 $user_entry = array_change_key_case($user_entry[0], CASE_LOWER);
b9ddb2d5 1194
139ebfdb 1195 foreach ($attrmap as $key => $ldapkeys) {
d836e3ed 1196 $profilefield = '';
fcf46da1 1197 // Only process if the moodle field ($key) has changed and we
b9ddb2d5 1198 // are set to update LDAP with it
d8372b54 1199 $customprofilefield = 'profile_field_' . $key;
139ebfdb 1200 if (isset($olduser->$key) and isset($newuser->$key)
57d135a1 1201 and ($olduser->$key !== $newuser->$key)) {
d836e3ed 1202 $profilefield = $key;
d8372b54
RT
1203 } else if (isset($olduser->$customprofilefield) && isset($newuser->$customprofilefield)
1204 && $olduser->$customprofilefield !== $newuser->$customprofilefield) {
1205 $profilefield = $customprofilefield;
b88adb55
GPL
1206 }
1207
d836e3ed 1208 if (!empty($profilefield) && !empty($this->config->{'field_updateremote_' . $key})) {
fcf46da1 1209 // For ldap values that could be in more than one
139ebfdb 1210 // ldap key, we will do our best to match
b9ddb2d5 1211 // where they came from
1212 $ambiguous = true;
1213 $changed = false;
1214 if (!is_array($ldapkeys)) {
1215 $ldapkeys = array($ldapkeys);
1216 }
1217 if (count($ldapkeys) < 2) {
1218 $ambiguous = false;
1219 }
139ebfdb 1220
2f1e464a 1221 $nuvalue = core_text::convert($newuser->$profilefield, 'utf-8', $this->config->ldapencoding);
15f80fd8 1222 empty($nuvalue) ? $nuvalue = array() : $nuvalue;
2f1e464a 1223 $ouvalue = core_text::convert($olduser->$profilefield, 'utf-8', $this->config->ldapencoding);
139ebfdb 1224
b9ddb2d5 1225 foreach ($ldapkeys as $ldapkey) {
139ebfdb 1226 $ldapkey = $ldapkey;
d836e3ed 1227 $ldapvalue = $user_entry[$ldapkey][0];
b9ddb2d5 1228 if (!$ambiguous) {
fcf46da1 1229 // Skip update if the values already match
139ebfdb 1230 if ($nuvalue !== $ldapvalue) {
fcf46da1 1231 // This might fail due to schema validation
139ebfdb 1232 if (@ldap_modify($ldapconnection, $user_dn, array($ldapkey => $nuvalue))) {
a8451603 1233 $changed = true;
139ebfdb 1234 continue;
1235 } else {
a8451603 1236 $success = false;
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;
1244 }
b9ddb2d5 1245 }
139ebfdb 1246 } else {
fcf46da1
I
1247 // Ambiguous. Value empty before in Moodle (and LDAP) - use
1248 // 1st ldap candidate field, no need to guess
139ebfdb 1249 if ($ouvalue === '') { // value empty before - use 1st ldap candidate
fcf46da1 1250 // This might fail due to schema validation
139ebfdb 1251 if (@ldap_modify($ldapconnection, $user_dn, array($ldapkey => $nuvalue))) {
b9ddb2d5 1252 $changed = true;
139ebfdb 1253 continue;
1254 } else {
a8451603 1255 $success = false;
fcf46da1
I
1256 error_log($this->errorlogtag.get_string ('updateremfail', 'auth_ldap',
1257 array('errno'=>ldap_errno($ldapconnection),
1258 'errstring'=>ldap_err2str(ldap_errno($ldapconnection)),
1259 'key'=>$key,
1260 'ouvalue'=>$ouvalue,
1261 'nuvalue'=>$nuvalue)));
139ebfdb 1262 continue;
b9ddb2d5 1263 }
1264 }
1265
fcf46da1 1266 // We found which ldap key to update!
139ebfdb 1267 if ($ouvalue !== '' and $ouvalue === $ldapvalue ) {
fcf46da1 1268 // This might fail due to schema validation
139ebfdb 1269 if (@ldap_modify($ldapconnection, $user_dn, array($ldapkey => $nuvalue))) {
b9ddb2d5 1270 $changed = true;
139ebfdb 1271 continue;
1272 } else {
a8451603 1273 $success = false;
fcf46da1
I
1274 error_log($this->errorlogtag.get_string ('updateremfail', 'auth_ldap',
1275 array('errno'=>ldap_errno($ldapconnection),
1276 'errstring'=>ldap_err2str(ldap_errno($ldapconnection)),
1277 'key'=>$key,
1278 'ouvalue'=>$ouvalue,
1279 'nuvalue'=>$nuvalue)));
139ebfdb 1280 continue;
b9ddb2d5 1281 }
1282 }
1283 }
1284 }
139ebfdb 1285
b9ddb2d5 1286 if ($ambiguous and !$changed) {
a8451603 1287 $success = false;
fcf46da1
I
1288 error_log($this->errorlogtag.get_string ('updateremfailamb', 'auth_ldap',
1289 array('key'=>$key,
1290 'ouvalue'=>$ouvalue,
1291 'nuvalue'=>$nuvalue)));
b9ddb2d5 1292 }
1293 }
1294 }
139ebfdb 1295 } else {
fcf46da1 1296 error_log($this->errorlogtag.get_string ('usernotfound', 'auth_ldap'));
a8451603 1297 $success = false;
b9ddb2d5 1298 }
1299
eee34307 1300 $this->ldap_close();
a8451603 1301 return $success;
b9ddb2d5 1302
1303 }
1304
fb5c7739 1305 /**
fcf46da1 1306 * Changes userpassword in LDAP
b9ddb2d5 1307 *
fcf46da1
I
1308 * Called when the user password is updated. It assumes it is
1309 * called by an admin or that you've otherwise checked the user's
1310 * credentials
b9ddb2d5 1311 *
ae040d4b 1312 * @param object $user User table object
fcf46da1 1313 * @param string $newpassword Plaintext password (not crypted/md5'ed)
b9ddb2d5 1314 * @return boolean result
1315 *
1316 */
b9ddb2d5 1317 function user_update_password($user, $newpassword) {
139ebfdb 1318 global $USER;
fcf46da1 1319
b9ddb2d5 1320 $result = false;
1321 $username = $user->username;
139ebfdb 1322
2f1e464a
PS
1323 $extusername = core_text::convert($username, 'utf-8', $this->config->ldapencoding);
1324 $extpassword = core_text::convert($newpassword, 'utf-8', $this->config->ldapencoding);
139ebfdb 1325
344514fc 1326 switch ($this->config->passtype) {
1327 case 'md5':
1328 $extpassword = '{MD5}' . base64_encode(pack('H*', md5($extpassword)));
1329 break;
1330 case 'sha1':
1331 $extpassword = '{SHA}' . base64_encode(pack('H*', sha1($extpassword)));
1332 break;
1333 case 'plaintext':
1334 default:
1335 break; // plaintext
1336 }
1337
b9ddb2d5 1338 $ldapconnection = $this->ldap_connect();
1339
139ebfdb 1340 $user_dn = $this->ldap_find_userdn($ldapconnection, $extusername);
1341
b9ddb2d5 1342 if (!$user_dn) {
fcf46da1 1343 error_log($this->errorlogtag.get_string ('nodnforusername', 'auth_ldap', $user->username));
b9ddb2d5 1344 return false;
1345 }
1346
1347 switch ($this->config->user_type) {
1348 case 'edir':
fcf46da1 1349 // Change password
139ebfdb 1350 $result = ldap_modify($ldapconnection, $user_dn, array('userPassword' => $extpassword));
b9ddb2d5 1351 if (!$result) {
fcf46da1
I
1352 error_log($this->errorlogtag.get_string ('updatepasserror', 'auth_ldap',
1353 array('errno'=>ldap_errno($ldapconnection),
1354 'errstring'=>ldap_err2str(ldap_errno($ldapconnection)))));
b9ddb2d5 1355 }
fcf46da1
I
1356 // Update password expiration time, grace logins count
1357 $search_attribs = array($this->config->expireattr, 'passwordExpirationInterval', 'loginGraceLimit');
cfcb7a17 1358 $sr = ldap_read($ldapconnection, $user_dn, '(objectClass=*)', $search_attribs);
fcf46da1
I
1359 if ($sr) {
1360 $entry = ldap_get_entries_moodle($ldapconnection, $sr);
1361 $info = array_change_key_case($entry[0], CASE_LOWER);
b9ddb2d5 1362 $newattrs = array();
fcf46da1
I
1363 if (!empty($info[$this->config->expireattr][0])) {
1364 // Set expiration time only if passwordExpirationInterval is defined
1365 if (!empty($info['passwordexpirationinterval'][0])) {
1366 $expirationtime = time() + $info['passwordexpirationinterval'][0];
b9ddb2d5 1367 $ldapexpirationtime = $this->ldap_unix2expirationtime($expirationtime);
1368 $newattrs['passwordExpirationTime'] = $ldapexpirationtime;
139ebfdb 1369 }
b9ddb2d5 1370
fcf46da1
I
1371 // Set gracelogin count
1372 if (!empty($info['logingracelimit'][0])) {
1373 $newattrs['loginGraceRemaining']= $info['logingracelimit'][0];
b9ddb2d5 1374 }
139ebfdb 1375
fcf46da1 1376 // Store attribute changes in LDAP
b9ddb2d5 1377 $result = ldap_modify($ldapconnection, $user_dn, $newattrs);
1378 if (!$result) {
fcf46da1
I
1379 error_log($this->errorlogtag.get_string ('updatepasserrorexpiregrace', 'auth_ldap',
1380 array('errno'=>ldap_errno($ldapconnection),
1381 'errstring'=>ldap_err2str(ldap_errno($ldapconnection)))));
b9ddb2d5 1382 }
1383 }
1384 }
1385 else {
fcf46da1
I
1386 error_log($this->errorlogtag.get_string ('updatepasserrorexpire', 'auth_ldap',
1387 array('errno'=>ldap_errno($ldapconnection),
1388 'errstring'=>ldap_err2str(ldap_errno($ldapconnection)))));
d0e84e1b 1389 }
1390 break;
1391
1392 case 'ad':
1393 // Passwords in Active Directory must be encoded as Unicode
1394 // strings (UCS-2 Little Endian format) and surrounded with
1395 // double quotes. See http://support.microsoft.com/?kbid=269190
1396 if (!function_exists('mb_convert_encoding')) {
fcf46da1 1397 error_log($this->errorlogtag.get_string ('needmbstring', 'auth_ldap'));
d0e84e1b 1398 return false;
1399 }
1400 $extpassword = mb_convert_encoding('"'.$extpassword.'"', "UCS-2LE", $this->config->ldapencoding);
1401 $result = ldap_modify($ldapconnection, $user_dn, array('unicodePwd' => $extpassword));
1402 if (!$result) {
fcf46da1
I
1403 error_log($this->errorlogtag.get_string ('updatepasserror', 'auth_ldap',
1404 array('errno'=>ldap_errno($ldapconnection),
1405 'errstring'=>ldap_err2str(ldap_errno($ldapconnection)))));
139ebfdb 1406 }
b9ddb2d5 1407 break;
139ebfdb 1408
b9ddb2d5 1409 default:
fcf46da1 1410 // Send LDAP the password in cleartext, it will md5 it itself
139ebfdb 1411 $result = ldap_modify($ldapconnection, $user_dn, array('userPassword' => $extpassword));
b9ddb2d5 1412 if (!$result) {
fcf46da1
I
1413 error_log($this->errorlogtag.get_string ('updatepasserror', 'auth_ldap',
1414 array('errno'=>ldap_errno($ldapconnection),
1415 'errstring'=>ldap_err2str(ldap_errno($ldapconnection)))));
b9ddb2d5 1416 }
139ebfdb 1417
b9ddb2d5 1418 }
1419
eee34307 1420 $this->ldap_close();
b9ddb2d5 1421 return $result;
1422 }
1423
b9ddb2d5 1424 /**
fcf46da1 1425 * Take expirationtime and return it as unix timestamp in seconds
b9ddb2d5 1426 *
fcf46da1
I
1427 * Takes expiration timestamp as read from LDAP and returns it as unix timestamp in seconds
1428 * Depends on $this->config->user_type variable
b9ddb2d5 1429 *
fcf46da1
I
1430 * @param mixed time Time stamp read from LDAP as it is.
1431 * @param string $ldapconnection Only needed for Active Directory.
1432 * @param string $user_dn User distinguished name for the user we are checking password expiration (only needed for Active Directory).
b9ddb2d5 1433 * @return timestamp
1434 */
bffe39c6 1435 function ldap_expirationtime2unix ($time, $ldapconnection, $user_dn) {
b9ddb2d5 1436 $result = false;
1437 switch ($this->config->user_type) {
1438 case 'edir':
fcf46da1
I
1439 $yr=substr($time, 0, 4);
1440 $mo=substr($time, 4, 2);
1441 $dt=substr($time, 6, 2);
1442 $hr=substr($time, 8, 2);
1443 $min=substr($time, 10, 2);
1444 $sec=substr($time, 12, 2);
1445 $result = mktime($hr, $min, $sec, $mo, $dt, $yr);
b9ddb2d5 1446 break;
9347082d 1447 case 'rfc2307':
1448 case 'rfc2307bis':
fcf46da1 1449 $result = $time * DAYSECS; // The shadowExpire contains the number of DAYS between 01/01/1970 and the actual expiration date
b9ddb2d5 1450 break;
bffe39c6 1451 case 'ad':
1452 $result = $this->ldap_get_ad_pwdexpire($time, $ldapconnection, $user_dn);
1453 break;
139ebfdb 1454 default:
2b06294b 1455 print_error('auth_ldap_usertypeundefined', 'auth_ldap');
b9ddb2d5 1456 }
1457 return $result;
1458 }
1459
1460 /**
fcf46da1 1461 * Takes unix timestamp and returns it formated for storing in LDAP
b9ddb2d5 1462 *
1463 * @param integer unix time stamp
1464 */
1465 function ldap_unix2expirationtime($time) {
b9ddb2d5 1466 $result = false;
1467 switch ($this->config->user_type) {
1468 case 'edir':
139ebfdb 1469 $result=date('YmdHis', $time).'Z';
b9ddb2d5 1470 break;
9347082d 1471 case 'rfc2307':
1472 case 'rfc2307bis':
fcf46da1 1473 $result = $time ; // Already in correct format
b9ddb2d5 1474 break;
139ebfdb 1475 default:
2b06294b 1476 print_error('auth_ldap_usertypeundefined2', 'auth_ldap');
139ebfdb 1477 }
b9ddb2d5 1478 return $result;
1479
1480 }
1481
139ebfdb 1482 /**
fcf46da1 1483 * Returns user attribute mappings between moodle and LDAP
b9ddb2d5 1484 *
1485 * @return array
1486 */
1487
1488 function ldap_attributes () {
b9ddb2d5 1489 $moodleattributes = array();
d836e3ed
RT
1490 // If we have custom fields then merge them with user fields.
1491 $customfields = $this->get_custom_user_profile_fields();
1492 if (!empty($customfields) && !empty($this->userfields)) {
1493 $userfields = array_merge($this->userfields, $customfields);
1494 } else {
1495 $userfields = $this->userfields;
1496 }
1497
1498 foreach ($userfields as $field) {
b9ddb2d5 1499 if (!empty($this->config->{"field_map_$field"})) {
2f1e464a 1500 $moodleattributes[$field] = core_text::strtolower(trim($this->config->{"field_map_$field"}));
fcf46da1 1501 if (preg_match('/,/', $moodleattributes[$field])) {
b9ddb2d5 1502 $moodleattributes[$field] = explode(',', $moodleattributes[$field]); // split ?
1503 }
1504 }
1505 }
2f1e464a 1506 $moodleattributes['username'] = core_text::strtolower(trim($this->config->user_attribute));
b9ddb2d5 1507 return $moodleattributes;
1508 }
1509
1510 /**
fcf46da1 1511 * Returns all usernames from LDAP
b9ddb2d5 1512 *
fcf46da1
I
1513 * @param $filter An LDAP search filter to select desired users
1514 * @return array of LDAP user names converted to UTF-8
b9ddb2d5 1515 */
fcf46da1 1516 function ldap_get_userlist($filter='*') {
b9ddb2d5 1517 $fresult = array();
1518
1519 $ldapconnection = $this->ldap_connect();
1520
fcf46da1 1521 if ($filter == '*') {
cfcb7a17 1522 $filter = '(&('.$this->config->user_attribute.'=*)'.$this->config->objectclass.')';
b9ddb2d5 1523 }
1524
fcf46da1 1525 $contexts = explode(';', $this->config->contexts);
b9ddb2d5 1526 if (!empty($this->config->create_context)) {
c090d7c9 1527 array_push($contexts, $this->config->create_context);
b9ddb2d5 1528 }
1529
fcf21760 1530 $ldap_cookie = '';
c090d7c9 1531 $ldap_pagedresults = ldap_paged_results_supported($this->config->ldap_version);
b9ddb2d5 1532 foreach ($contexts as $context) {
b9ddb2d5 1533 $context = trim($context);
1534 if (empty($context)) {
1535 continue;
1536 }
1537
c090d7c9
IA
1538 do {
1539 if ($ldap_pagedresults) {
1540 ldap_control_paged_result($ldapconnection, $this->config->pagesize, true, $ldap_cookie);
1541 }
1542 if ($this->config->search_sub) {
1543 // Use ldap_search to find first user from subtree.
1544 $ldap_result = ldap_search($ldapconnection, $context, $filter, array($this->config->user_attribute));
1545 } else {
1546 // Search only in this context.
1547 $ldap_result = ldap_list($ldapconnection, $context, $filter, array($this->config->user_attribute));
1548 }
1549 if(!$ldap_result) {
1550 continue;
1551 }
1552 if ($ldap_pagedresults) {
1553 ldap_control_paged_result_response($ldapconnection, $ldap_result, $ldap_cookie);
1554 }
1555 $users = ldap_get_entries_moodle($ldapconnection, $ldap_result);
1556 // Add found users to list.
1557 for ($i = 0; $i < count($users); $i++) {
2f1e464a 1558 $extuser = core_text::convert($users[$i][$this->config->user_attribute][0],
c090d7c9
IA
1559 $this->config->ldapencoding, 'utf-8');
1560 array_push($fresult, $extuser);
1561 }
1562 unset($ldap_result); // Free mem.
1563 } while ($ldap_pagedresults && !empty($ldap_cookie));
b9ddb2d5 1564 }
139ebfdb 1565
c090d7c9
IA
1566 // If paged results were used, make sure the current connection is completely closed
1567 $this->ldap_close($ldap_pagedresults);
b9ddb2d5 1568 return $fresult;
1569 }
1570
1571 /**
fcf46da1 1572 * Indicates if password hashes should be stored in local moodle database.
b9ddb2d5 1573 *
fcf46da1 1574 * @return bool true means flag 'not_cached' stored instead of password hash
b9ddb2d5 1575 */
edb5da83
PS
1576 function prevent_local_passwords() {
1577 return !empty($this->config->preventpassindb);
1578 }
1579
b9ddb2d5 1580 /**
1581 * Returns true if this authentication plugin is 'internal'.
1582 *
139ebfdb 1583 * @return bool
b9ddb2d5 1584 */
1585 function is_internal() {
1586 return false;
1587 }
1588
1589 /**
1590 * Returns true if this authentication plugin can change the user's
1591 * password.
1592 *
139ebfdb 1593 * @return bool
b9ddb2d5 1594 */
1595 function can_change_password() {
430759a5 1596 return !empty($this->config->stdchangepassword) or !empty($this->config->changepasswordurl);
b9ddb2d5 1597 }
139ebfdb 1598
b9ddb2d5 1599 /**
fcf46da1 1600 * Returns the URL for changing the user's password, or empty if the default can
b9ddb2d5 1601 * be used.
1602 *
99f9f85f 1603 * @return moodle_url
b9ddb2d5 1604 */
1605 function change_password_url() {
139ebfdb 1606 if (empty($this->config->stdchangepassword)) {
963cdce4
AA
1607 if (!empty($this->config->changepasswordurl)) {
1608 return new moodle_url($this->config->changepasswordurl);
1609 } else {
1610 return null;
1611 }
139ebfdb 1612 } else {
99f9f85f 1613 return null;
139ebfdb 1614 }
b9ddb2d5 1615 }
139ebfdb 1616
1e8713ea 1617 /**
fcf46da1 1618 * Will get called before the login page is shownr. Ff NTLM SSO
1e8713ea 1619 * is enabled, and the user is in the right network, we'll redirect
1620 * to the magic NTLM page for SSO...
1621 *
1622 */
1623 function loginpage_hook() {
4194d321 1624 global $CFG, $SESSION;
265edb48 1625
1626 // HTTPS is potentially required
17c70aa0 1627 //httpsrequired(); - this must be used before setting the URL, it is already done on the login/index.php
5117d598 1628
4194d321 1629 if (($_SERVER['REQUEST_METHOD'] === 'GET' // Only on initial GET of loginpage
fcf46da1 1630 || ($_SERVER['REQUEST_METHOD'] === 'POST'
dcee0b94 1631 && (get_local_referer() != strip_querystring(qualified_me()))))
fcf46da1
I
1632 // Or when POSTed from another place
1633 // See MDL-14071
1634 && !empty($this->config->ntlmsso_enabled) // SSO enabled
1635 && !empty($this->config->ntlmsso_subnet) // have a subnet to test for
1636 && empty($_GET['authldap_skipntlmsso']) // haven't failed it yet
1637 && (isguestuser() || !isloggedin()) // guestuser or not-logged-in users
b8aa76c1 1638 && address_in_subnet(getremoteaddr(), $this->config->ntlmsso_subnet)) {
4194d321 1639
1640 // First, let's remember where we were trying to get to before we got here
1641 if (empty($SESSION->wantsurl)) {
dcee0b94 1642 $SESSION->wantsurl = null;
25565918 1643 $referer = get_local_referer(false);
dcee0b94
SL
1644 if ($referer &&
1645 $referer != $CFG->wwwroot &&
1646 $referer != $CFG->wwwroot . '/' &&
1647 $referer != $CFG->httpswwwroot . '/login/' &&
1648 $referer != $CFG->httpswwwroot . '/login/index.php') {
1649 $SESSION->wantsurl = $referer;
1650 }
4194d321 1651 }
02c7f3d9 1652
4194d321 1653 // Now start the whole NTLM machinery.
d962e814
DM
1654 if($this->config->ntlmsso_ie_fastpath == AUTH_NTLM_FASTPATH_YESATTEMPT ||
1655 $this->config->ntlmsso_ie_fastpath == AUTH_NTLM_FASTPATH_YESFORM) {
378b3eac 1656 if (core_useragent::is_ie()) {
16ceeb64 1657 $sesskey = sesskey();
1658 redirect($CFG->wwwroot.'/auth/ldap/ntlmsso_magic.php?sesskey='.$sesskey);
d962e814 1659 } else if ($this->config->ntlmsso_ie_fastpath == AUTH_NTLM_FASTPATH_YESFORM) {
16ceeb64 1660 redirect($CFG->httpswwwroot.'/login/index.php?authldap_skipntlmsso=1');
1661 }
16ceeb64 1662 }
d962e814 1663 redirect($CFG->wwwroot.'/auth/ldap/ntlmsso_attempt.php');
4194d321 1664 }
5117d598 1665
4194d321 1666 // No NTLM SSO, Use the normal login page instead.
1667
1668 // If $SESSION->wantsurl is empty and we have a 'Referer:' header, the login
1669 // page insists on redirecting us to that page after user validation. If
fcf46da1
I
1670 // we clicked on the redirect link at the ntlmsso_finish.php page (instead
1671 // of waiting for the redirection to happen) then we have a 'Referer:' header
4194d321 1672 // we don't want to use at all. As we can't get rid of it, just point
1673 // $SESSION->wantsurl to $CFG->wwwroot (after all, we came from there).
1674 if (empty($SESSION->wantsurl)
06ae6604 1675 && (get_local_referer() == $CFG->httpswwwroot.'/auth/ldap/ntlmsso_finish.php')) {
4194d321 1676
1677 $SESSION->wantsurl = $CFG->wwwroot;
1e8713ea 1678 }
1679 }
1680
1681 /**
1682 * To be called from a page running under NTLM's
5117d598 1683 * "Integrated Windows Authentication".
1e8713ea 1684 *
5117d598 1685 * If successful, it will set a special "cookie" (not an HTTP cookie!)
fcf46da1 1686 * in cache_flags under the $this->pluginconfig/ntlmsess "plugin" and return true.
1e8713ea 1687 * The "cookie" will be picked up by ntlmsso_finish() to complete the
1688 * process.
1689 *
1690 * On failure it will return false for the caller to display an appropriate
decd8016 1691 * error message (probably saying that Integrated Windows Auth isn't enabled!)
1e8713ea 1692 *
5117d598 1693 * NOTE that this code will execute under the OS user credentials,
1e8713ea 1694 * so we MUST avoid dealing with files -- such as session files.
6800d78e 1695 * (The caller should define('NO_MOODLE_COOKIES', true) before including config.php)
1e8713ea 1696 *
1697 */
decd8016 1698 function ntlmsso_magic($sesskey) {
1699 if (isset($_SERVER['REMOTE_USER']) && !empty($_SERVER['REMOTE_USER'])) {
4194d321 1700
1701 // HTTP __headers__ seem to be sent in ISO-8859-1 encoding
1702 // (according to my reading of RFC-1945, RFC-2616 and RFC-2617 and
1703 // my local tests), so we need to convert the REMOTE_USER value
1704 // (i.e., what we got from the HTTP WWW-Authenticate header) into UTF-8
2f1e464a 1705 $username = core_text::convert($_SERVER['REMOTE_USER'], 'iso-8859-1', 'utf-8');
4194d321 1706
fcf46da1
I
1707 switch ($this->config->ntlmsso_type) {
1708 case 'ntlm':
34b10e26
IA
1709 // The format is now configurable, so try to extract the username
1710 $username = $this->get_ntlm_remote_user($username);
1711 if (empty($username)) {
1712 return false;
1713 }
fcf46da1
I
1714 break;
1715 case 'kerberos':
1716 // Format is username@DOMAIN
1717 $username = substr($username, 0, strpos($username, '@'));
1718 break;
1719 default:
1720 error_log($this->errorlogtag.get_string ('ntlmsso_unknowntype', 'auth_ldap'));
1721 return false; // Should never happen!
1722 }
1723
2f1e464a 1724 $username = core_text::strtolower($username); // Compatibility hack
fcf46da1 1725 set_cache_flag($this->pluginconfig.'/ntlmsess', $sesskey, $username, AUTH_NTLMTIMEOUT);
065e2cc0 1726 return true;
decd8016 1727 }
1728 return false;
1e8713ea 1729 }
1730
1731 /**
5117d598 1732 * Find the session set by ntlmsso_magic(), validate it and
decd8016 1733 * call authenticate_user_login() to authenticate the user through
1734 * the auth machinery.
5117d598 1735 *
decd8016 1736 * It is complemented by a similar check in user_login().
5117d598
PS
1737 *
1738 * If it succeeds, it never returns.
decd8016 1739 *
1e8713ea 1740 */
1741 function ntlmsso_finish() {
4025cf80 1742 global $CFG, $USER, $SESSION;
02c7f3d9 1743
065e2cc0 1744 $key = sesskey();
fcf46da1 1745 $cf = get_cache_flags($this->pluginconfig.'/ntlmsess');
58eada35 1746 if (!isset($cf[$key]) || $cf[$key] === '') {
065e2cc0 1747 return false;
1748 }
1749 $username = $cf[$key];
5991cabf 1750
065e2cc0 1751 // Here we want to trigger the whole authentication machinery
1752 // to make sure no step is bypassed...
be5a3168 1753 $user = authenticate_user_login($username, $key);
065e2cc0 1754 if ($user) {
b7b64ff2 1755 complete_user_login($user);
065e2cc0 1756
1757 // Cleanup the key to prevent reuse...
1758 // and to allow re-logins with normal credentials
fcf46da1 1759 unset_cache_flag($this->pluginconfig.'/ntlmsess', $key);
065e2cc0 1760
fcf46da1 1761 // Redirection
065e2cc0 1762 if (user_not_fully_set_up($USER)) {
1763 $urltogo = $CFG->wwwroot.'/user/edit.php';
1764 // We don't delete $SESSION->wantsurl yet, so we get there later
1765 } else if (isset($SESSION->wantsurl) and (strpos($SESSION->wantsurl, $CFG->wwwroot) === 0)) {
fcf46da1 1766 $urltogo = $SESSION->wantsurl; // Because it's an address in this site
065e2cc0 1767 unset($SESSION->wantsurl);
1768 } else {
fcf46da1 1769 // No wantsurl stored or external - go to homepage
065e2cc0 1770 $urltogo = $CFG->wwwroot.'/';
1771 unset($SESSION->wantsurl);
decd8016 1772 }
5991cabf
MN
1773 // We do not want to redirect if we are in a PHPUnit test.
1774 if (!PHPUNIT_TEST) {
1775 redirect($urltogo);
1776 }
decd8016 1777 }
065e2cc0 1778 // Should never reach here.
decd8016 1779 return false;
5117d598 1780 }
1e8713ea 1781
6bc1e5d5 1782 /**
1783 * Sync roles for this user
1784 *
1785 * @param $user object user object (without system magic quotes)
1786 */
1787 function sync_roles($user) {
1788 $iscreator = $this->iscreator($user->username);
1789 if ($iscreator === null) {
fcf46da1 1790 return; // Nothing to sync - creators not configured
6bc1e5d5 1791 }
1792
4f0c2d00 1793 if ($roles = get_archetype_roles('coursecreator')) {
6bc1e5d5 1794 $creatorrole = array_shift($roles); // We can only use one, let's use the first one
bf0f06b1 1795 $systemcontext = context_system::instance();
6bc1e5d5 1796
1797 if ($iscreator) { // Following calls will not create duplicates
fcf46da1 1798 role_assign($creatorrole->id, $user->id, $systemcontext->id, $this->roleauth);
6bc1e5d5 1799 } else {
fcf46da1
I
1800 // Unassign only if previously assigned by this plugin!
1801 role_unassign($creatorrole->id, $user->id, $systemcontext->id, $this->roleauth);
6bc1e5d5 1802 }
1803 }
1804 }
1805
b9ddb2d5 1806 /**
1807 * Prints a form for configuring this authentication plugin.
1808 *
1809 * This function is called from admin/auth.php, and outputs a full page with
1810 * a form for configuring this plugin.
1811 *
1812 * @param array $page An object containing all the data for this page.
1813 */
57d135a1 1814 function config_form($config, $err, $user_fields) {
fcf46da1
I
1815 global $CFG, $OUTPUT;
1816
1817 if (!function_exists('ldap_connect')) { // Is php-ldap really there?
1818 echo $OUTPUT->notification(get_string('auth_ldap_noextension', 'auth_ldap'));
1819 return;
1820 }
95cb3955 1821
fcf46da1 1822 include($CFG->dirroot.'/auth/ldap/config.html');
b9ddb2d5 1823 }
1824
1825 /**
1826 * Processes and stores configuration data for this authentication plugin.
1827 */
1828 function process_config($config) {
fcf46da1
I
1829 // Set to defaults if undefined
1830 if (!isset($config->host_url)) {
1831 $config->host_url = '';
1832 }
326929d5
IA
1833 if (!isset($config->start_tls)) {
1834 $config->start_tls = false;
1835 }
fcf46da1
I
1836 if (empty($config->ldapencoding)) {
1837 $config->ldapencoding = 'utf-8';
1838 }
c090d7c9
IA
1839 if (!isset($config->pagesize)) {
1840 $config->pagesize = LDAP_DEFAULT_PAGESIZE;
1841 }
fcf46da1
I
1842 if (!isset($config->contexts)) {
1843 $config->contexts = '';
1844 }
1845 if (!isset($config->user_type)) {
1846 $config->user_type = 'default';
1847 }
1848 if (!isset($config->user_attribute)) {
1849 $config->user_attribute = '';
1850 }
1851 if (!isset($config->search_sub)) {
1852 $config->search_sub = '';
1853 }
1854 if (!isset($config->opt_deref)) {
1855 $config->opt_deref = LDAP_DEREF_NEVER;
1856 }
1857 if (!isset($config->preventpassindb)) {
1858 $config->preventpassindb = 0;
1859 }
1860 if (!isset($config->bind_dn)) {
1861 $config->bind_dn = '';
1862 }
1863 if (!isset($config->bind_pw)) {
1864 $config->bind_pw = '';
1865 }
1866 if (!isset($config->ldap_version)) {
1867 $config->ldap_version = '3';
1868 }
1869 if (!isset($config->objectclass)) {
1870 $config->objectclass = '';
1871 }
1872 if (!isset($config->memberattribute)) {
1873 $config->memberattribute = '';
1874 }
1875 if (!isset($config->memberattribute_isdn)) {
1876 $config->memberattribute_isdn = '';
1877 }
1878 if (!isset($config->creators)) {
1879 $config->creators = '';
1880 }
1881 if (!isset($config->create_context)) {
1882 $config->create_context = '';
1883 }
1884 if (!isset($config->expiration)) {
1885 $config->expiration = '';
1886 }
1887 if (!isset($config->expiration_warning)) {
1888 $config->expiration_warning = '10';
1889 }
1890 if (!isset($config->expireattr)) {
1891 $config->expireattr = '';
1892 }
1893 if (!isset($config->gracelogins)) {
1894 $config->gracelogins = '';
1895 }
1896 if (!isset($config->graceattr)) {
1897 $config->graceattr = '';
1898 }
1899 if (!isset($config->auth_user_create)) {
1900 $config->auth_user_create = '';
1901 }
1902 if (!isset($config->forcechangepassword)) {
1903 $config->forcechangepassword = 0;
1904 }
1905 if (!isset($config->stdchangepassword)) {
1906 $config->stdchangepassword = 0;
1907 }
1908 if (!isset($config->passtype)) {
1909 $config->passtype = 'plaintext';
1910 }
1911 if (!isset($config->changepasswordurl)) {
1912 $config->changepasswordurl = '';
1913 }
1914 if (!isset($config->removeuser)) {
1915 $config->removeuser = AUTH_REMOVEUSER_KEEP;
1916 }
1917 if (!isset($config->ntlmsso_enabled)) {
1918 $config->ntlmsso_enabled = 0;
1919 }
1920 if (!isset($config->ntlmsso_subnet)) {
1921 $config->ntlmsso_subnet = '';
1922 }
1923 if (!isset($config->ntlmsso_ie_fastpath)) {
1924 $config->ntlmsso_ie_fastpath = 0;
1925 }
1926 if (!isset($config->ntlmsso_type)) {
1927 $config->ntlmsso_type = 'ntlm';
1928 }
34b10e26
IA
1929 if (!isset($config->ntlmsso_remoteuserformat)) {
1930 $config->ntlmsso_remoteuserformat = '';
1931 }
b9ddb2d5 1932
ca769fa7
IA
1933 // Try to remove duplicates before storing the contexts (to avoid problems in sync_users()).
1934 $config->contexts = explode(';', $config->contexts);
2f1e464a 1935 $config->contexts = array_map(create_function('$x', 'return core_text::strtolower(trim($x));'),
ca769fa7
IA
1936 $config->contexts);
1937 $config->contexts = implode(';', array_unique($config->contexts));
1938
fcf46da1
I
1939 // Save settings
1940 set_config('host_url', trim($config->host_url), $this->pluginconfig);
326929d5 1941 set_config('start_tls', $config->start_tls, $this->pluginconfig);
fcf46da1 1942 set_config('ldapencoding', trim($config->ldapencoding), $this->pluginconfig);
c090d7c9 1943 set_config('pagesize', (int)trim($config->pagesize), $this->pluginconfig);
ca769fa7 1944 set_config('contexts', $config->contexts, $this->pluginconfig);
2f1e464a
PS
1945 set_config('user_type', core_text::strtolower(trim($config->user_type)), $this->pluginconfig);
1946 set_config('user_attribute', core_text::strtolower(trim($config->user_attribute)), $this->pluginconfig);
fcf46da1
I
1947 set_config('search_sub', $config->search_sub, $this->pluginconfig);
1948 set_config('opt_deref', $config->opt_deref, $this->pluginconfig);
1949 set_config('preventpassindb', $config->preventpassindb, $this->pluginconfig);
1950 set_config('bind_dn', trim($config->bind_dn), $this->pluginconfig);
1951 set_config('bind_pw', $config->bind_pw, $this->pluginconfig);
1952 set_config('ldap_version', $config->ldap_version, $this->pluginconfig);
1953 set_config('objectclass', trim($config->objectclass), $this->pluginconfig);
2f1e464a 1954 set_config('memberattribute', core_text::strtolower(trim($config->memberattribute)), $this->pluginconfig);
fcf46da1
I
1955 set_config('memberattribute_isdn', $config->memberattribute_isdn, $this->pluginconfig);
1956 set_config('creators', trim($config->creators), $this->pluginconfig);
1957 set_config('create_context', trim($config->create_context), $this->pluginconfig);
1958 set_config('expiration', $config->expiration, $this->pluginconfig);
1959 set_config('expiration_warning', trim($config->expiration_warning), $this->pluginconfig);
2f1e464a 1960 set_config('expireattr', core_text::strtolower(trim($config->expireattr)), $this->pluginconfig);
fcf46da1 1961 set_config('gracelogins', $config->gracelogins, $this->pluginconfig);
2f1e464a 1962 set_config('graceattr', core_text::strtolower(trim($config->graceattr)), $this->pluginconfig);
fcf46da1
I
1963 set_config('auth_user_create', $config->auth_user_create, $this->pluginconfig);
1964 set_config('forcechangepassword', $config->forcechangepassword, $this->pluginconfig);
1965 set_config('stdchangepassword', $config->stdchangepassword, $this->pluginconfig);
1966 set_config('passtype', $config->passtype, $this->pluginconfig);
1967 set_config('changepasswordurl', trim($config->changepasswordurl), $this->pluginconfig);
1968 set_config('removeuser', $config->removeuser, $this->pluginconfig);
1969 set_config('ntlmsso_enabled', (int)$config->ntlmsso_enabled, $this->pluginconfig);
1970 set_config('ntlmsso_subnet', trim($config->ntlmsso_subnet), $this->pluginconfig);
1971 set_config('ntlmsso_ie_fastpath', (int)$config->ntlmsso_ie_fastpath, $this->pluginconfig);
1972 set_config('ntlmsso_type', $config->ntlmsso_type, 'auth/ldap');
34b10e26 1973 set_config('ntlmsso_remoteuserformat', trim($config->ntlmsso_remoteuserformat), 'auth/ldap');
139ebfdb 1974
fcf46da1 1975 return true;
139ebfdb 1976 }
bffe39c6 1977
1978 /**
1979 * Get password expiration time for a given user from Active Directory
1980 *
1981 * @param string $pwdlastset The time last time we changed the password.
1982 * @param resource $lcapconn The open LDAP connection.
1983 * @param string $user_dn The distinguished name of the user we are checking.
1984 *
1985 * @return string $unixtime
1986 */
1987 function ldap_get_ad_pwdexpire($pwdlastset, $ldapconn, $user_dn){
bffe39c6 1988 global $CFG;
1989
1990 if (!function_exists('bcsub')) {
fcf46da1 1991 error_log($this->errorlogtag.get_string ('needbcmath', 'auth_ldap'));
bffe39c6 1992 return 0;
1993 }
1994
1995 // If UF_DONT_EXPIRE_PASSWD flag is set in user's
1996 // userAccountControl attribute, the password doesn't expire.
cfcb7a17 1997 $sr = ldap_read($ldapconn, $user_dn, '(objectClass=*)',
bffe39c6 1998 array('userAccountControl'));
1999 if (!$sr) {
fcf46da1
I
2000 error_log($this->errorlogtag.get_string ('useracctctrlerror', 'auth_ldap', $user_dn));
2001 // Don't expire password, as we are not sure if it has to be
bffe39c6 2002 // expired or not.
2003 return 0;
2004 }
e295df44 2005
fcf46da1
I
2006 $entry = ldap_get_entries_moodle($ldapconn, $sr);
2007 $info = array_change_key_case($entry[0], CASE_LOWER);
2008 $useraccountcontrol = $info['useraccountcontrol'][0];
bffe39c6 2009 if ($useraccountcontrol & UF_DONT_EXPIRE_PASSWD) {
fcf46da1 2010 // Password doesn't expire.
bffe39c6 2011 return 0;
2012 }
e295df44 2013
bffe39c6 2014 // If pwdLastSet is zero, the user must change his/her password now
2015 // (unless UF_DONT_EXPIRE_PASSWD flag is set, but we already
2016 // tested this above)
2017 if ($pwdlastset === '0') {
fcf46da1 2018 // Password has expired
bffe39c6 2019 return -1;
2020 }
e295df44 2021
bffe39c6 2022 // ----------------------------------------------------------------
2023 // Password expiration time in Active Directory is the composition of
2024 // two values:
2025 //
2026 // - User's pwdLastSet attribute, that stores the last time
2027 // the password was changed.
2028 //
2029 // - Domain's maxPwdAge attribute, that sets how long
2030 // passwords last in this domain.
2031 //
2032 // We already have the first value (passed in as a parameter). We
2033 // need to get the second one. As we don't know the domain DN, we
2034 // have to query rootDSE's defaultNamingContext attribute to get
2035 // it. Then we have to query that DN's maxPwdAge attribute to get
2036 // the real value.
2037 //
2038 // Once we have both values, we just need to combine them. But MS
2039 // chose to use a different base and unit for time measurements.
2040 // So we need to convert the values to Unix timestamps (see
2041 // details below).
2042 // ----------------------------------------------------------------
e295df44 2043
cfcb7a17 2044 $sr = ldap_read($ldapconn, ROOTDSE, '(objectClass=*)',
bffe39c6 2045 array('defaultNamingContext'));
2046 if (!$sr) {
fcf46da1 2047 error_log($this->errorlogtag.get_string ('rootdseerror', 'auth_ldap'));
bffe39c6 2048 return 0;
2049 }
e295df44 2050
fcf46da1
I
2051 $entry = ldap_get_entries_moodle($ldapconn, $sr);
2052 $info = array_change_key_case($entry[0], CASE_LOWER);
2053 $domaindn = $info['defaultnamingcontext'][0];
e295df44 2054
cfcb7a17 2055 $sr = ldap_read ($ldapconn, $domaindn, '(objectClass=*)',
bffe39c6 2056 array('maxPwdAge'));
fcf46da1
I
2057 $entry = ldap_get_entries_moodle($ldapconn, $sr);
2058 $info = array_change_key_case($entry[0], CASE_LOWER);
2059 $maxpwdage = $info['maxpwdage'][0];
bffe39c6 2060
2061 // ----------------------------------------------------------------
2062 // MSDN says that "pwdLastSet contains the number of 100 nanosecond
2063 // intervals since January 1, 1601 (UTC), stored in a 64 bit integer".
2064 //
2065 // According to Perl's Date::Manip, the number of seconds between
2066 // this date and Unix epoch is 11644473600. So we have to
2067 // substract this value to calculate a Unix time, once we have
2068 // scaled pwdLastSet to seconds. This is the script used to
2069 // calculate the value shown above:
2070 //
2071 // #!/usr/bin/perl -w
2072 //
2073 // use Date::Manip;
2074 //
2075 // $date1 = ParseDate ("160101010000 UTC");
2076 // $date2 = ParseDate ("197001010000 UTC");
2077 // $delta = DateCalc($date1, $date2, \$err);
2078 // $secs = Delta_Format($delta, 0, "%st");
2079 // print "$secs \n";
2080 //
2081 // MSDN also says that "maxPwdAge is stored as a large integer that
2082 // represents the number of 100 nanosecond intervals from the time
2083 // the password was set before the password expires." We also need
2084 // to scale this to seconds. Bear in mind that this value is stored
2085 // as a _negative_ quantity (at least in my AD domain).
2086 //
2087 // As a last remark, if the low 32 bits of maxPwdAge are equal to 0,
2088 // the maximum password age in the domain is set to 0, which means
e295df44 2089 // passwords do not expire (see
bffe39c6 2090 // http://msdn2.microsoft.com/en-us/library/ms974598.aspx)
2091 //
2092 // As the quantities involved are too big for PHP integers, we
2093 // need to use BCMath functions to work with arbitrary precision
2094 // numbers.
2095 // ----------------------------------------------------------------
e295df44 2096
bffe39c6 2097 // If the low order 32 bits are 0, then passwords do not expire in
2098 // the domain. Just do '$maxpwdage mod 2^32' and check the result
2099 // (2^32 = 4294967296)
2100 if (bcmod ($maxpwdage, 4294967296) === '0') {
2101 return 0;
2102 }
2103
2104 // Add up pwdLastSet and maxPwdAge to get password expiration
2105 // time, in MS time units. Remember maxPwdAge is stored as a
2106 // _negative_ quantity, so we need to substract it in fact.
2107 $pwdexpire = bcsub ($pwdlastset, $maxpwdage);
e295df44 2108
bffe39c6 2109 // Scale the result to convert it to Unix time units and return
2110 // that value.
2111 return bcsub( bcdiv($pwdexpire, '10000000'), '11644473600');
2112 }
2113
fcf46da1
I
2114 /**
2115 * Connect to the LDAP server, using the plugin configured
2116 * settings. It's actually a wrapper around ldap_connect_moodle()
2117 *
2118 * @return resource A valid LDAP connection (or dies if it can't connect)
2119 */
2120 function ldap_connect() {
2121 // Cache ldap connections. They are expensive to set up
2122 // and can drain the TCP/IP ressources on the server if we
2123 // are syncing a lot of users (as we try to open a new connection
2124 // to get the user details). This is the least invasive way
2125 // to reuse existing connections without greater code surgery.
2126 if(!empty($this->ldapconnection)) {
2127 $this->ldapconns++;
2128 return $this->ldapconnection;
2129 }
2130
2131 if($ldapconnection = ldap_connect_moodle($this->config->host_url, $this->config->ldap_version,
2132 $this->config->user_type, $this->config->bind_dn,
2133 $this->config->bind_pw, $this->config->opt_deref,
326929d5 2134 $debuginfo, $this->config->start_tls)) {
fcf46da1
I
2135 $this->ldapconns = 1;
2136 $this->ldapconnection = $ldapconnection;
2137 return $ldapconnection;
2138 }
b9ddb2d5 2139
fcf46da1
I
2140 print_error('auth_ldap_noconnect_all', 'auth_ldap', '', $debuginfo);
2141 }
2142
2143 /**
2144 * Disconnects from a LDAP server
2145 *
c090d7c9
IA
2146 * @param force boolean Forces closing the real connection to the LDAP server, ignoring any
2147 * cached connections. This is needed when we've used paged results
2148 * and want to use normal results again.
fcf46da1 2149 */
c090d7c9 2150 function ldap_close($force=false) {
fcf46da1 2151 $this->ldapconns--;
c090d7c9
IA
2152 if (($this->ldapconns == 0) || ($force)) {
2153 $this->ldapconns = 0;
fcf46da1
I
2154 @ldap_close($this->ldapconnection);
2155 unset($this->ldapconnection);
2156 }
2157 }
2158
2159 /**
2160 * Search specified contexts for username and return the user dn
2161 * like: cn=username,ou=suborg,o=org. It's actually a wrapper
2162 * around ldap_find_userdn().
2163 *
2164 * @param resource $ldapconnection a valid LDAP connection
2165 * @param string $extusername the username to search (in external LDAP encoding, no db slashes)
2166 * @return mixed the user dn (external LDAP encoding) or false
2167 */
2168 function ldap_find_userdn($ldapconnection, $extusername) {
2169 $ldap_contexts = explode(';', $this->config->contexts);
2170 if (!empty($this->config->create_context)) {
2171 array_push($ldap_contexts, $this->config->create_context);
2172 }
2173
2174 return ldap_find_userdn($ldapconnection, $extusername, $ldap_contexts, $this->config->objectclass,
2175 $this->config->user_attribute, $this->config->search_sub);
2176 }
5117d598 2177
34b10e26
IA
2178
2179 /**
2180 * A chance to validate form data, and last chance to do stuff
2181 * before it is inserted in config_plugin
2182 *
2183 * @param object object with submitted configuration settings (without system magic quotes)
2184 * @param array $err array of error messages (passed by reference)
2185 */
2186 function validate_form($form, &$err) {
2187 if ($form->ntlmsso_type == 'ntlm') {
2188 $format = trim($form->ntlmsso_remoteuserformat);
2189 if (!empty($format) && !preg_match('/%username%/i', $format)) {
2190 $err['ntlmsso_remoteuserformat'] = get_string('auth_ntlmsso_missing_username', 'auth_ldap');
2191 }
2192 }
2193 }
2194
2195
2196 /**
2197 * When using NTLM SSO, the format of the remote username we get in
2198 * $_SERVER['REMOTE_USER'] may vary, depending on where from and how the web
2199 * server gets the data. So we let the admin configure the format using two
2200 * place holders (%domain% and %username%). This function tries to extract
2201 * the username (stripping the domain part and any separators if they are
2202 * present) from the value present in $_SERVER['REMOTE_USER'], using the
2203 * configured format.
2204 *
2205 * @param string $remoteuser The value from $_SERVER['REMOTE_USER'] (converted to UTF-8)
2206 *
2207 * @return string The remote username (without domain part or
2208 * separators). Empty string if we can't extract the username.
2209 */
2210 protected function get_ntlm_remote_user($remoteuser) {
2211 if (empty($this->config->ntlmsso_remoteuserformat)) {
2212 $format = AUTH_NTLM_DEFAULT_FORMAT;
2213 } else {
2214 $format = $this->config->ntlmsso_remoteuserformat;
2215 }
2216
2217 $format = preg_quote($format);
2218 $formatregex = preg_replace(array('#%domain%#', '#%username%#'),
2219 array('('.AUTH_NTLM_VALID_DOMAINNAME.')', '('.AUTH_NTLM_VALID_USERNAME.')'),
2220 $format);
2221 if (preg_match('#^'.$formatregex.'$#', $remoteuser, $matches)) {
2222 $user = end($matches);
2223 return $user;
2224 }
2225
2226 /* We are unable to extract the username with the configured format. Probably
2227 * the format specified is wrong, so log a warning for the admin and return
2228 * an empty username.
2229 */
2230 error_log($this->errorlogtag.get_string ('auth_ntlmsso_maybeinvalidformat', 'auth_ldap'));
2231 return '';
2232 }
2233
cd37c1da
IA
2234 /**
2235 * Check if the diagnostic message for the LDAP login error tells us that the
2236 * login is denied because the user password has expired or the password needs
2237 * to be changed on first login (using interactive SMB/Windows logins, not
2238 * LDAP logins).
2239 *
2240 * @param string the diagnostic message for the LDAP login error
2241 * @return bool true if the password has expired or the password must be changed on first login
2242 */
2243 protected function ldap_ad_pwdexpired_from_diagmsg($diagmsg) {
2244 // The format of the diagnostic message is (actual examples from W2003 and W2008):
2245 // "80090308: LdapErr: DSID-0C090334, comment: AcceptSecurityContext error, data 52e, vece" (W2003)
2246 // "80090308: LdapErr: DSID-0C090334, comment: AcceptSecurityContext error, data 773, vece" (W2003)
2247 // "80090308: LdapErr: DSID-0C0903AA, comment: AcceptSecurityContext error, data 52e, v1771" (W2008)
2248 // "80090308: LdapErr: DSID-0C0903AA, comment: AcceptSecurityContext error, data 773, v1771" (W2008)
2249 // We are interested in the 'data nnn' part.
2250 // if nnn == 773 then user must change password on first login
2251 // if nnn == 532 then user password has expired
2252 $diagmsg = explode(',', $diagmsg);
2253 if (preg_match('/data (773|532)/i', trim($diagmsg[2]))) {
2254 return true;
2255 }
2256 return false;
2257 }
2258
fcf46da1 2259} // End of the class