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