MDL-20365 auth_db: Warning users about case sensitive plain passwords
[moodle.git] / auth / db / auth.php
CommitLineData
b9ddb2d5 1<?php
e7aeaa65
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/>.
16
b9ddb2d5 17/**
b9ddb2d5 18 * Authentication Plugin: External Database Authentication
19 *
20 * Checks against an external database.
21 *
e7aeaa65 22 * @package auth_db
7415aed1
PS
23 * @author Martin Dougiamas
24 * @license http://www.gnu.org/copyleft/gpl.html GNU Public License
b9ddb2d5 25 */
26
7415aed1 27defined('MOODLE_INTERNAL') || die();
b9ddb2d5 28
6bc1e5d5 29require_once($CFG->libdir.'/authlib.php');
30
b9ddb2d5 31/**
32 * External database authentication plugin.
33 */
6bc1e5d5 34class auth_plugin_db extends auth_plugin_base {
b9ddb2d5 35
36 /**
37 * Constructor.
38 */
e7aeaa65
PS
39 function __construct() {
40 global $CFG;
41 require_once($CFG->libdir.'/adodb/adodb.inc.php');
42
6bc1e5d5 43 $this->authtype = 'db';
b9ddb2d5 44 $this->config = get_config('auth/db');
8ae42b8d 45 if (empty($this->config->extencoding)) {
46 $this->config->extencoding = 'utf-8';
47 }
b9ddb2d5 48 }
49
50 /**
51 * Returns true if the username and password work and false if they are
52 * wrong or don't exist.
53 *
576c063b 54 * @param string $username The username
55 * @param string $password The password
8ae42b8d 56 * @return bool Authentication success or failure.
b9ddb2d5 57 */
139ebfdb 58 function user_login($username, $password) {
576c063b 59 global $CFG, $DB;
b9ddb2d5 60
2f1e464a
PS
61 $extusername = core_text::convert($username, 'utf-8', $this->config->extencoding);
62 $extpassword = core_text::convert($password, 'utf-8', $this->config->extencoding);
8ae42b8d 63
7415aed1 64 if ($this->is_internal()) {
e7aeaa65 65 // Lookup username externally, but resolve
b9ddb2d5 66 // password locally -- to support backend that
e7aeaa65 67 // don't track passwords.
ba87b41b
PS
68
69 if (isset($this->config->removeuser) and $this->config->removeuser == AUTH_REMOVEUSER_KEEP) {
70 // No need to connect to external database in this case because users are never removed and we verify password locally.
71 if ($user = $DB->get_record('user', array('username'=>$username, 'mnethostid'=>$CFG->mnet_localhost_id, 'auth'=>$this->authtype))) {
72 return validate_internal_user_password($user, $password);
73 } else {
74 return false;
75 }
76 }
77
78 $authdb = $this->db_init();
79
e7aeaa65
PS
80 $rs = $authdb->Execute("SELECT *
81 FROM {$this->config->table}
82 WHERE {$this->config->fielduser} = '".$this->ext_addslashes($extusername)."'");
b9ddb2d5 83 if (!$rs) {
03cedd62 84 $authdb->Close();
03ea0b32 85 debugging(get_string('auth_dbcantconnect','auth_db'));
b9ddb2d5 86 return false;
87 }
8ae42b8d 88
7415aed1 89 if (!$rs->EOF) {
03cedd62 90 $rs->Close();
91 $authdb->Close();
e7aeaa65 92 // User exists externally - check username/password internally.
a0a5ca25 93 if ($user = $DB->get_record('user', array('username'=>$username, 'mnethostid'=>$CFG->mnet_localhost_id, 'auth'=>$this->authtype))) {
b9ddb2d5 94 return validate_internal_user_password($user, $password);
95 }
96 } else {
03cedd62 97 $rs->Close();
98 $authdb->Close();
e7aeaa65 99 // User does not exist externally.
b9ddb2d5 100 return false;
8ae42b8d 101 }
b9ddb2d5 102
8ae42b8d 103 } else {
e7aeaa65 104 // Normal case: use external db for both usernames and passwords.
b9ddb2d5 105
ba87b41b
PS
106 $authdb = $this->db_init();
107
e3d9fc3f 108 $rs = $authdb->Execute("SELECT {$this->config->fieldpass} AS userpass
c7c397ca 109 FROM {$this->config->table}
f97b63bf 110 WHERE {$this->config->fielduser} = '".$this->ext_addslashes($extusername)."'");
b9ddb2d5 111 if (!$rs) {
03cedd62 112 $authdb->Close();
03ea0b32 113 debugging(get_string('auth_dbcantconnect','auth_db'));
b9ddb2d5 114 return false;
115 }
8ae42b8d 116
f97b63bf 117 if ($rs->EOF) {
03cedd62 118 $authdb->Close();
f97b63bf
RM
119 return false;
120 }
121
e3d9fc3f
EL
122 $fields = array_change_key_case($rs->fields, CASE_LOWER);
123 $fromdb = $fields['userpass'];
f97b63bf
RM
124 $rs->Close();
125 $authdb->Close();
126
127 if ($this->config->passtype === 'plaintext') {
128 return ($fromdb == $extpassword);
129 } else if ($this->config->passtype === 'md5') {
c00cbdc7 130 return (strtolower($fromdb) == md5($extpassword));
f97b63bf 131 } else if ($this->config->passtype === 'sha1') {
c00cbdc7 132 return (strtolower($fromdb) == sha1($extpassword));
f97b63bf
RM
133 } else if ($this->config->passtype === 'saltedcrypt') {
134 require_once($CFG->libdir.'/password_compat/lib/password.php');
135 return password_verify($extpassword, $fromdb);
b9ddb2d5 136 } else {
137 return false;
8ae42b8d 138 }
139
b9ddb2d5 140 }
141 }
142
6cf20915
PS
143 /**
144 * Connect to external database.
145 *
146 * @return ADOConnection
147 */
139ebfdb 148 function db_init() {
e7aeaa65 149 // Connect to the external database (forcing new connection).
ab6e0848 150 $authdb = ADONewConnection($this->config->type);
8ae42b8d 151 if (!empty($this->config->debugauthdb)) {
152 $authdb->debug = true;
e7aeaa65 153 ob_start(); //Start output buffer to allow later use of the page headers.
8ae42b8d 154 }
155 $authdb->Connect($this->config->host, $this->config->user, $this->config->pass, $this->config->name, true);
b9ddb2d5 156 $authdb->SetFetchMode(ADODB_FETCH_ASSOC);
8ae42b8d 157 if (!empty($this->config->setupsql)) {
158 $authdb->Execute($this->config->setupsql);
159 }
b9ddb2d5 160
139ebfdb 161 return $authdb;
162 }
7415aed1 163
139ebfdb 164 /**
e7aeaa65 165 * Returns user attribute mappings between moodle and ldap.
139ebfdb 166 *
167 * @return array
168 */
169 function db_attributes() {
139ebfdb 170 $moodleattributes = array();
4105caff 171 foreach ($this->userfields as $field) {
139ebfdb 172 if (!empty($this->config->{"field_map_$field"})) {
173 $moodleattributes[$field] = $this->config->{"field_map_$field"};
0f02788f 174 }
175 }
5261baf1 176 $moodleattributes['username'] = $this->config->fielduser;
139ebfdb 177 return $moodleattributes;
178 }
179
180 /**
181 * Reads any other information for a user from external database,
e7aeaa65 182 * then returns it in an array.
139ebfdb 183 *
be544ec3 184 * @param string $username
e7aeaa65 185 * @return array
139ebfdb 186 */
187 function get_userinfo($username) {
139ebfdb 188 global $CFG;
189
2f1e464a 190 $extusername = core_text::convert($username, 'utf-8', $this->config->extencoding);
139ebfdb 191
192 $authdb = $this->db_init();
193
e7aeaa65 194 // Array to map local fieldnames we want, to external fieldnames.
139ebfdb 195 $selectfields = $this->db_attributes();
196
0f02788f 197 $result = array();
e7aeaa65 198 // If at least one field is mapped from external db, get that mapped data.
0f02788f 199 if ($selectfields) {
e7aeaa65 200 $select = array();
0f02788f 201 foreach ($selectfields as $localname=>$externalname) {
e7aeaa65 202 $select[] = "$externalname AS $localname";
0f02788f 203 }
e7aeaa65
PS
204 $select = implode(', ', $select);
205 $sql = "SELECT $select
206 FROM {$this->config->table}
207 WHERE {$this->config->fielduser} = '".$this->ext_addslashes($extusername)."'";
0f02788f 208 if ($rs = $authdb->Execute($sql)) {
e7aeaa65 209 if (!$rs->EOF) {
245ac557 210 $fields_obj = $rs->FetchObj();
1ed6ae07 211 $fields_obj = (object)array_change_key_case((array)$fields_obj , CASE_LOWER);
0f02788f 212 foreach ($selectfields as $localname=>$externalname) {
2f1e464a 213 $result[$localname] = core_text::convert($fields_obj->{$localname}, $this->config->extencoding, 'utf-8');
0f02788f 214 }
215 }
245ac557 216 $rs->Close();
b9ddb2d5 217 }
218 }
219 $authdb->Close();
b9ddb2d5 220 return $result;
221 }
222
fb5c7739 223 /**
e7aeaa65 224 * Change a user's password.
fb5c7739 225 *
e7aeaa65 226 * @param stdClass $user User table object
ae040d4b 227 * @param string $newpassword Plaintext password
e7aeaa65 228 * @return bool True on success
fb5c7739 229 */
da249a30 230 function user_update_password($user, $newpassword) {
5c28e3a8
PS
231 global $DB;
232
7415aed1 233 if ($this->is_internal()) {
5c28e3a8 234 $puser = $DB->get_record('user', array('id'=>$user->id), '*', MUST_EXIST);
ec2d8ceb
SC
235 // This will also update the stored hash to the latest algorithm
236 // if the existing hash is using an out-of-date algorithm (or the
237 // legacy md5 algorithm).
5c28e3a8
PS
238 if (update_internal_user_password($puser, $newpassword)) {
239 $user->password = $puser->password;
240 return true;
241 } else {
242 return false;
243 }
b9ddb2d5 244 } else {
e7aeaa65 245 // We should have never been called!
b9ddb2d5 246 return false;
247 }
248 }
249
250 /**
e7aeaa65 251 * Synchronizes user from external db to moodle user table.
b9ddb2d5 252 *
ab6e0848 253 * Sync should be done by using idnumber attribute, not username.
b9ddb2d5 254 * You need to pass firstsync parameter to function to fill in
ab6e0848 255 * idnumbers if they don't exists in moodle user table.
8ae42b8d 256 *
ab6e0848 257 * Syncing users removes (disables) users that don't exists anymore in external db.
8ae42b8d 258 * Creates new users and updates coursecreator status of users.
259 *
b9ddb2d5 260 * This implementation is simpler but less scalable than the one found in the LDAP module.
261 *
e7aeaa65 262 * @param progress_trace $trace
7415aed1 263 * @param bool $do_updates Optional: set to true to force an update of existing accounts
ab6e0848 264 * @return int 0 means success, 1 means failure
b9ddb2d5 265 */
e7aeaa65 266 function sync_users(progress_trace $trace, $do_updates=false) {
70ca450a 267 global $CFG, $DB;
b9ddb2d5 268
e0e6d931
MN
269 require_once($CFG->dirroot . '/user/lib.php');
270
e7aeaa65 271 // List external users.
b9ddb2d5 272 $userlist = $this->get_userlist();
b9ddb2d5 273
e7aeaa65 274 // Delete obsolete internal users.
139ebfdb 275 if (!empty($this->config->removeuser)) {
b9ddb2d5 276
28fd4d6c
PS
277 $suspendselect = "";
278 if ($this->config->removeuser == AUTH_REMOVEUSER_SUSPEND) {
279 $suspendselect = "AND u.suspended = 0";
280 }
281
e7aeaa65 282 // Find obsolete users.
139ebfdb 283 if (count($userlist)) {
20d8d5c7
EL
284 list($notin_sql, $params) = $DB->get_in_or_equal($userlist, SQL_PARAMS_NAMED, 'u', false);
285 $params['authtype'] = $this->authtype;
f91f3f63 286 $sql = "SELECT u.*
bc31625a 287 FROM {user} u
28fd4d6c 288 WHERE u.auth=:authtype AND u.deleted=0 AND u.mnethostid=:mnethostid $suspendselect AND u.username $notin_sql";
139ebfdb 289 } else {
f91f3f63 290 $sql = "SELECT u.*
bc31625a 291 FROM {user} u
28fd4d6c 292 WHERE u.auth=:authtype AND u.deleted=0 AND u.mnethostid=:mnethostid $suspendselect";
bc31625a 293 $params = array();
20d8d5c7 294 $params['authtype'] = $this->authtype;
139ebfdb 295 }
28fd4d6c 296 $params['mnethostid'] = $CFG->mnet_localhost_id;
bc31625a 297 $remove_users = $DB->get_records_sql($sql, $params);
139ebfdb 298
299 if (!empty($remove_users)) {
e7aeaa65 300 $trace->output(get_string('auth_dbuserstoremove','auth_db', count($remove_users)));
139ebfdb 301
139ebfdb 302 foreach ($remove_users as $user) {
6f87ef52 303 if ($this->config->removeuser == AUTH_REMOVEUSER_FULLDELETE) {
ab6e0848 304 delete_user($user);
e7aeaa65 305 $trace->output(get_string('auth_dbdeleteuser', 'auth_db', array('name'=>$user->username, 'id'=>$user->id)), 1);
6f87ef52 306 } else if ($this->config->removeuser == AUTH_REMOVEUSER_SUSPEND) {
1dffbae2 307 $updateuser = new stdClass();
139ebfdb 308 $updateuser->id = $user->id;
28fd4d6c 309 $updateuser->suspended = 1;
bb78e249 310 user_update_user($updateuser, false);
e7aeaa65 311 $trace->output(get_string('auth_dbsuspenduser', 'auth_db', array('name'=>$user->username, 'id'=>$user->id)), 1);
139ebfdb 312 }
b9ddb2d5 313 }
8ae42b8d 314 }
e7aeaa65 315 unset($remove_users);
8ae42b8d 316 }
b9ddb2d5 317
318 if (!count($userlist)) {
e7aeaa65
PS
319 // Exit right here, nothing else to do.
320 $trace->finished();
ab6e0848 321 return 0;
b9ddb2d5 322 }
323
e7aeaa65 324 // Update existing accounts.
b9ddb2d5 325 if ($do_updates) {
e7aeaa65 326 // Narrow down what fields we need to update.
b9ddb2d5 327 $all_keys = array_keys(get_object_vars($this->config));
328 $updatekeys = array();
329 foreach ($all_keys as $key) {
330 if (preg_match('/^field_updatelocal_(.+)$/',$key, $match)) {
331 if ($this->config->{$key} === 'onlogin') {
e7aeaa65 332 array_push($updatekeys, $match[1]); // The actual key name.
b9ddb2d5 333 }
334 }
335 }
b9ddb2d5 336 unset($all_keys); unset($key);
337
e7aeaa65 338 // Only go ahead if we actually have fields to update locally.
b9ddb2d5 339 if (!empty($updatekeys)) {
20d8d5c7 340 list($in_sql, $params) = $DB->get_in_or_equal($userlist, SQL_PARAMS_NAMED, 'u', true);
bc31625a
PS
341 $params['authtype'] = $this->authtype;
342 $sql = "SELECT u.id, u.username
343 FROM {user} u
344 WHERE u.auth=:authtype AND u.deleted=0 AND u.username {$in_sql}";
345 if ($update_users = $DB->get_records_sql($sql, $params)) {
e7aeaa65 346 $trace->output("User entries to update: ".count($update_users));
8ae42b8d 347
348 foreach ($update_users as $user) {
ab6e0848 349 if ($this->update_user_record($user->username, $updatekeys)) {
e7aeaa65 350 $trace->output(get_string('auth_dbupdatinguser', 'auth_db', array('name'=>$user->username, 'id'=>$user->id)), 1);
ab6e0848 351 } else {
e7aeaa65 352 $trace->output(get_string('auth_dbupdatinguser', 'auth_db', array('name'=>$user->username, 'id'=>$user->id))." - ".get_string('skipped'), 1);
139ebfdb 353 }
8ae42b8d 354 }
e7aeaa65 355 unset($update_users);
b9ddb2d5 356 }
b9ddb2d5 357 }
358 }
359
360
e7aeaa65
PS
361 // Create missing accounts.
362 // NOTE: this is very memory intensive and generally inefficient.
28fd4d6c
PS
363 $suspendselect = "";
364 if ($this->config->removeuser == AUTH_REMOVEUSER_SUSPEND) {
365 $suspendselect = "AND u.suspended = 0";
366 }
367 $sql = "SELECT u.id, u.username
368 FROM {user} u
369 WHERE u.auth=:authtype AND u.deleted='0' AND mnethostid=:mnethostid $suspendselect";
b9ddb2d5 370
28fd4d6c 371 $users = $DB->get_records_sql($sql, array('authtype'=>$this->authtype, 'mnethostid'=>$CFG->mnet_localhost_id));
8ae42b8d 372
e7aeaa65 373 // Simplify down to usernames.
b9ddb2d5 374 $usernames = array();
2b214bc1 375 if (!empty($users)) {
376 foreach ($users as $user) {
377 array_push($usernames, $user->username);
378 }
379 unset($users);
b9ddb2d5 380 }
b9ddb2d5 381
382 $add_users = array_diff($userlist, $usernames);
383 unset($usernames);
384
385 if (!empty($add_users)) {
e7aeaa65 386 $trace->output(get_string('auth_dbuserstoadd','auth_db',count($add_users)));
bee02209 387 // Do not use transactions around this foreach, we want to skip problematic users, not revert everything.
b9ddb2d5 388 foreach($add_users as $user) {
389 $username = $user;
28fd4d6c 390 if ($this->config->removeuser == AUTH_REMOVEUSER_SUSPEND) {
e0e6d931
MN
391 if ($olduser = $DB->get_record('user', array('username' => $username, 'deleted' => 0, 'suspended' => 1,
392 'mnethostid' => $CFG->mnet_localhost_id, 'auth' => $this->authtype))) {
393 $updateuser = new stdClass();
394 $updateuser->id = $olduser->id;
395 $updateuser->suspended = 0;
396 user_update_user($updateuser);
397 $trace->output(get_string('auth_dbreviveduser', 'auth_db', array('name' => $username,
398 'id' => $olduser->id)), 1);
28fd4d6c
PS
399 continue;
400 }
401 }
f0364be6
PS
402
403 // Do not try to undelete users here, instead select suspending if you ever expect users will reappear.
8ae42b8d 404
e7aeaa65 405 // Prep a few params.
f0364be6 406 $user = $this->get_userinfo_asobj($user);
b7b50143 407 $user->username = $username;
b7b50143 408 $user->confirmed = 1;
5211c7ec 409 $user->auth = $this->authtype;
b7b50143 410 $user->mnethostid = $CFG->mnet_localhost_id;
8ae42b8d 411 if (empty($user->lang)) {
412 $user->lang = $CFG->lang;
413 }
bee02209 414 if ($collision = $DB->get_record_select('user', "username = :username AND mnethostid = :mnethostid AND auth <> :auth", array('username'=>$user->username, 'mnethostid'=>$CFG->mnet_localhost_id, 'auth'=>$this->authtype), 'id,username,auth')) {
e7aeaa65 415 $trace->output(get_string('auth_dbinsertuserduplicate', 'auth_db', array('username'=>$user->username, 'auth'=>$collision->auth)), 1);
bee02209
PS
416 continue;
417 }
f0364be6 418 try {
e0e6d931 419 $id = user_create_user($user, false); // It is truly a new user.
e7aeaa65 420 $trace->output(get_string('auth_dbinsertuser', 'auth_db', array('name'=>$user->username, 'id'=>$id)), 1);
f0364be6 421 } catch (moodle_exception $e) {
e7aeaa65 422 $trace->output(get_string('auth_dbinsertusererror', 'auth_db', $user->username), 1);
bee02209 423 continue;
b9ddb2d5 424 }
e7aeaa65 425 // If relevant, tag for password generation.
f0364be6
PS
426 if ($this->is_internal()) {
427 set_user_preference('auth_forcepasswordchange', 1, $id);
428 set_user_preference('create_password', 1, $id);
429 }
bee02209
PS
430 // Make sure user context is present.
431 context_user::instance($id);
b9ddb2d5 432 }
e7aeaa65 433 unset($add_users);
b9ddb2d5 434 }
e7aeaa65 435 $trace->finished();
ab6e0848 436 return 0;
b9ddb2d5 437 }
438
139ebfdb 439 function user_exists($username) {
93901eb4 440
e7aeaa65 441 // Init result value.
a7e32367 442 $result = false;
443
2f1e464a 444 $extusername = core_text::convert($username, 'utf-8', $this->config->extencoding);
8ae42b8d 445
139ebfdb 446 $authdb = $this->db_init();
b9ddb2d5 447
e7aeaa65
PS
448 $rs = $authdb->Execute("SELECT *
449 FROM {$this->config->table}
450 WHERE {$this->config->fielduser} = '".$this->ext_addslashes($extusername)."' ");
b9ddb2d5 451
452 if (!$rs) {
2b06294b 453 print_error('auth_dbcantconnect','auth_db');
7415aed1 454 } else if (!$rs->EOF) {
e7aeaa65 455 // User exists externally.
03cedd62 456 $result = true;
8ae42b8d 457 }
a7e32367 458
459 $authdb->Close();
460 return $result;
b9ddb2d5 461 }
462
463
464 function get_userlist() {
93901eb4 465
e7aeaa65 466 // Init result value.
a7e32367 467 $result = array();
468
139ebfdb 469 $authdb = $this->db_init();
b9ddb2d5 470
e7aeaa65 471 // Fetch userlist.
b9ddb2d5 472 $rs = $authdb->Execute("SELECT {$this->config->fielduser} AS username
e7aeaa65 473 FROM {$this->config->table} ");
b9ddb2d5 474
475 if (!$rs) {
2b06294b 476 print_error('auth_dbcantconnect','auth_db');
7415aed1 477 } else if (!$rs->EOF) {
245ac557 478 while ($rec = $rs->FetchRow()) {
e9366bf8 479 $rec = (object)array_change_key_case((array)$rec , CASE_LOWER);
480 array_push($result, $rec->username);
b9ddb2d5 481 }
8ae42b8d 482 }
a7e32367 483
484 $authdb->Close();
485 return $result;
b9ddb2d5 486 }
487
488 /**
e7aeaa65 489 * Reads user information from DB and return it in an object.
b9ddb2d5 490 *
e7aeaa65 491 * @param string $username username
b9ddb2d5 492 * @return array
493 */
494 function get_userinfo_asobj($username) {
495 $user_array = truncate_userinfo($this->get_userinfo($username));
1dffbae2 496 $user = new stdClass();
b9ddb2d5 497 foreach($user_array as $key=>$value) {
498 $user->{$key} = $value;
499 }
500 return $user;
501 }
502
8ae42b8d 503 /**
504 * will update a local user record from an external source.
505 * is a lighter version of the one in moodlelib -- won't do
e7aeaa65 506 * expensive ops such as enrolment.
b9ddb2d5 507 *
8ae42b8d 508 * If you don't pass $updatekeys, there is a performance hit and
b9ddb2d5 509 * values removed from DB won't be removed from moodle.
8ae42b8d 510 *
185721a4 511 * @param string $username username
ab6e0848
PS
512 * @param bool $updatekeys
513 * @return stdClass
b9ddb2d5 514 */
139ebfdb 515 function update_user_record($username, $updatekeys=false) {
185721a4 516 global $CFG, $DB;
b9ddb2d5 517
b9ddb2d5 518 //just in case check text case
2f1e464a 519 $username = trim(core_text::strtolower($username));
8ae42b8d 520
b9ddb2d5 521 // get the current user record
185721a4 522 $user = $DB->get_record('user', array('username'=>$username, 'mnethostid'=>$CFG->mnet_localhost_id));
b9ddb2d5 523 if (empty($user)) { // trouble
524 error_log("Cannot update non-existent user: $username");
2b06294b 525 print_error('auth_dbusernotexist','auth_db',$username);
b9ddb2d5 526 die;
527 }
528
e7aeaa65 529 // Ensure userid is not overwritten.
b7b50143 530 $userid = $user->id;
e0e6d931 531 $needsupdate = false;
b7b50143 532
e0e6d931
MN
533 $updateuser = new stdClass();
534 $updateuser->id = $userid;
b9ddb2d5 535 if ($newinfo = $this->get_userinfo($username)) {
536 $newinfo = truncate_userinfo($newinfo);
8ae42b8d 537
e7aeaa65 538 if (empty($updatekeys)) { // All keys? This does not support removing values.
b9ddb2d5 539 $updatekeys = array_keys($newinfo);
540 }
8ae42b8d 541
b9ddb2d5 542 foreach ($updatekeys as $key) {
b9ddb2d5 543 if (isset($newinfo[$key])) {
544 $value = $newinfo[$key];
b9ddb2d5 545 } else {
546 $value = '';
547 }
8ae42b8d 548
549 if (!empty($this->config->{'field_updatelocal_' . $key})) {
e7aeaa65 550 if (isset($user->{$key}) and $user->{$key} != $value) { // Only update if it's changed.
e0e6d931
MN
551 $needsupdate = true;
552 $updateuser->$key = $value;
139ebfdb 553 }
b9ddb2d5 554 }
555 }
556 }
e0e6d931
MN
557 if ($needsupdate) {
558 require_once($CFG->dirroot . '/user/lib.php');
559 user_update_user($updateuser);
a4d25731 560 }
185721a4 561 return $DB->get_record('user', array('id'=>$userid, 'deleted'=>0));
139ebfdb 562 }
563
564 /**
565 * Called when the user record is updated.
566 * Modifies user in external database. It takes olduser (before changes) and newuser (after changes)
ab6e0848 567 * compares information saved modified information to external db.
139ebfdb 568 *
e7aeaa65
PS
569 * @param stdClass $olduser Userobject before modifications
570 * @param stdClass $newuser Userobject new modified userobject
139ebfdb 571 * @return boolean result
572 *
573 */
574 function user_update($olduser, $newuser) {
575 if (isset($olduser->username) and isset($newuser->username) and $olduser->username != $newuser->username) {
576 error_log("ERROR:User renaming not allowed in ext db");
577 return false;
578 }
579
5211c7ec 580 if (isset($olduser->auth) and $olduser->auth != $this->authtype) {
e7aeaa65 581 return true; // Just change auth and skip update.
139ebfdb 582 }
583
584 $curruser = $this->get_userinfo($olduser->username);
585 if (empty($curruser)) {
586 error_log("ERROR:User $olduser->username found in ext db");
587 return false;
588 }
589
2f1e464a 590 $extusername = core_text::convert($olduser->username, 'utf-8', $this->config->extencoding);
139ebfdb 591
592 $authdb = $this->db_init();
593
594 $update = array();
595 foreach($curruser as $key=>$value) {
596 if ($key == 'username') {
e7aeaa65 597 continue; // Skip this.
139ebfdb 598 }
599 if (empty($this->config->{"field_updateremote_$key"})) {
e7aeaa65 600 continue; // Remote update not requested.
139ebfdb 601 }
602 if (!isset($newuser->$key)) {
603 continue;
604 }
70ca450a 605 $nuvalue = $newuser->$key;
139ebfdb 606 if ($nuvalue != $value) {
2f1e464a 607 $update[] = $this->config->{"field_map_$key"}."='".$this->ext_addslashes(core_text::convert($nuvalue, 'utf-8', $this->config->extencoding))."'";
139ebfdb 608 }
609 }
610 if (!empty($update)) {
611 $authdb->Execute("UPDATE {$this->config->table}
7415aed1
PS
612 SET ".implode(',', $update)."
613 WHERE {$this->config->fielduser}='".$this->ext_addslashes($extusername)."'");
139ebfdb 614 }
615 $authdb->Close();
616 return true;
b9ddb2d5 617 }
618
8ae42b8d 619 /**
620 * A chance to validate form data, and last chance to
621 * do stuff before it is inserted in config_plugin
ab6e0848 622 *
e7aeaa65
PS
623 * @param stfdClass $form
624 * @param array $err errors
ab6e0848 625 * @return void
8ae42b8d 626 */
ab6e0848 627 function validate_form($form, &$err) {
150b5fb0 628 if ($form->passtype === 'internal') {
b9ddb2d5 629 $this->config->changepasswordurl = '';
630 set_config('changepasswordurl', '', 'auth/db');
631 }
b9ddb2d5 632 }
633
edb5da83 634 function prevent_local_passwords() {
7415aed1 635 return !$this->is_internal();
edb5da83
PS
636 }
637
b9ddb2d5 638 /**
7415aed1
PS
639 * Returns true if this authentication plugin is "internal".
640 *
641 * Internal plugins use password hashes from Moodle user table for authentication.
b9ddb2d5 642 *
139ebfdb 643 * @return bool
b9ddb2d5 644 */
645 function is_internal() {
e79781f7
PS
646 if (!isset($this->config->passtype)) {
647 return true;
648 }
7415aed1
PS
649 return ($this->config->passtype === 'internal');
650 }
651
652 /**
653 * Indicates if moodle should automatically update internal user
654 * records with data from external sources using the information
655 * from auth_plugin_base::get_userinfo().
656 *
657 * @return bool true means automatically copy data from ext to user table
658 */
659 function is_synchronised_with_external() {
660 return true;
b9ddb2d5 661 }
662
663 /**
664 * Returns true if this authentication plugin can change the user's
665 * password.
666 *
139ebfdb 667 * @return bool
b9ddb2d5 668 */
669 function can_change_password() {
7415aed1 670 return ($this->is_internal() or !empty($this->config->changepasswordurl));
b9ddb2d5 671 }
672
673 /**
430759a5 674 * Returns the URL for changing the user's pw, or empty if the default can
b9ddb2d5 675 * be used.
676 *
99f9f85f 677 * @return moodle_url
b9ddb2d5 678 */
679 function change_password_url() {
963cdce4 680 if ($this->is_internal() || empty($this->config->changepasswordurl)) {
e7aeaa65 681 // Standard form.
99f9f85f 682 return null;
430759a5 683 } else {
e7aeaa65 684 // Use admin defined custom url.
99f9f85f 685 return new moodle_url($this->config->changepasswordurl);
430759a5 686 }
b9ddb2d5 687 }
688
ab6ff8a4 689 /**
690 * Returns true if plugin allows resetting of internal password.
691 *
692 * @return bool
693 */
694 function can_reset_password() {
7415aed1 695 return $this->is_internal();
ab6ff8a4 696 }
697
b9ddb2d5 698 /**
699 * Prints a form for configuring this authentication plugin.
700 *
701 * This function is called from admin/auth.php, and outputs a full page with
702 * a form for configuring this plugin.
703 *
ab6e0848
PS
704 * @param stdClass $config
705 * @param array $err errors
706 * @param array $user_fields
707 * @return void
b9ddb2d5 708 */
139ebfdb 709 function config_form($config, $err, $user_fields) {
8ae42b8d 710 include 'config.html';
b9ddb2d5 711 }
712
713 /**
714 * Processes and stores configuration data for this authentication plugin.
e7aeaa65 715 *
ab6e0848
PS
716 * @param srdClass $config
717 * @return bool always true or exception
b9ddb2d5 718 */
719 function process_config($config) {
720 // set to defaults if undefined
721 if (!isset($config->host)) {
8ae42b8d 722 $config->host = 'localhost';
b9ddb2d5 723 }
724 if (!isset($config->type)) {
8ae42b8d 725 $config->type = 'mysql';
726 }
727 if (!isset($config->sybasequoting)) {
728 $config->sybasequoting = 0;
b9ddb2d5 729 }
730 if (!isset($config->name)) {
8ae42b8d 731 $config->name = '';
b9ddb2d5 732 }
733 if (!isset($config->user)) {
8ae42b8d 734 $config->user = '';
b9ddb2d5 735 }
736 if (!isset($config->pass)) {
8ae42b8d 737 $config->pass = '';
b9ddb2d5 738 }
739 if (!isset($config->table)) {
8ae42b8d 740 $config->table = '';
b9ddb2d5 741 }
742 if (!isset($config->fielduser)) {
8ae42b8d 743 $config->fielduser = '';
b9ddb2d5 744 }
745 if (!isset($config->fieldpass)) {
8ae42b8d 746 $config->fieldpass = '';
b9ddb2d5 747 }
748 if (!isset($config->passtype)) {
8ae42b8d 749 $config->passtype = 'plaintext';
750 }
751 if (!isset($config->extencoding)) {
752 $config->extencoding = 'utf-8';
753 }
754 if (!isset($config->setupsql)) {
755 $config->setupsql = '';
756 }
757 if (!isset($config->debugauthdb)) {
758 $config->debugauthdb = 0;
b9ddb2d5 759 }
139ebfdb 760 if (!isset($config->removeuser)) {
6f87ef52 761 $config->removeuser = AUTH_REMOVEUSER_KEEP;
139ebfdb 762 }
b9ddb2d5 763 if (!isset($config->changepasswordurl)) {
764 $config->changepasswordurl = '';
765 }
766
e7aeaa65 767 // Save settings.
8ae42b8d 768 set_config('host', $config->host, 'auth/db');
769 set_config('type', $config->type, 'auth/db');
770 set_config('sybasequoting', $config->sybasequoting, 'auth/db');
771 set_config('name', $config->name, 'auth/db');
772 set_config('user', $config->user, 'auth/db');
773 set_config('pass', $config->pass, 'auth/db');
774 set_config('table', $config->table, 'auth/db');
775 set_config('fielduser', $config->fielduser, 'auth/db');
776 set_config('fieldpass', $config->fieldpass, 'auth/db');
777 set_config('passtype', $config->passtype, 'auth/db');
778 set_config('extencoding', trim($config->extencoding), 'auth/db');
139ebfdb 779 set_config('setupsql', trim($config->setupsql),'auth/db');
8ae42b8d 780 set_config('debugauthdb', $config->debugauthdb, 'auth/db');
139ebfdb 781 set_config('removeuser', $config->removeuser, 'auth/db');
8ae42b8d 782 set_config('changepasswordurl', trim($config->changepasswordurl), 'auth/db');
783
b9ddb2d5 784 return true;
785 }
786
e7aeaa65
PS
787 /**
788 * Add slashes, we can not use placeholders or system functions.
789 *
790 * @param string $text
791 * @return string
792 */
8ae42b8d 793 function ext_addslashes($text) {
8ae42b8d 794 if (empty($this->config->sybasequoting)) {
795 $text = str_replace('\\', '\\\\', $text);
796 $text = str_replace(array('\'', '"', "\0"), array('\\\'', '\\"', '\\0'), $text);
797 } else {
798 $text = str_replace("'", "''", $text);
799 }
800 return $text;
801 }
6cf20915
PS
802
803 /**
804 * Test if settings are ok, print info to output.
805 * @private
806 */
807 public function test_settings() {
808 global $CFG, $OUTPUT;
809
810 // NOTE: this is not localised intentionally, admins are supposed to understand English at least a bit...
811
812 raise_memory_limit(MEMORY_HUGE);
813
814 if (empty($this->config->table)) {
815 echo $OUTPUT->notification('External table not specified.', 'notifyproblem');
816 return;
817 }
818
819 if (empty($this->config->fielduser)) {
820 echo $OUTPUT->notification('External user field not specified.', 'notifyproblem');
821 return;
822 }
823
824 $olddebug = $CFG->debug;
825 $olddisplay = ini_get('display_errors');
826 ini_set('display_errors', '1');
827 $CFG->debug = DEBUG_DEVELOPER;
828 $olddebugauthdb = $this->config->debugauthdb;
829 $this->config->debugauthdb = 1;
830 error_reporting($CFG->debug);
831
832 $adodb = $this->db_init();
833
834 if (!$adodb or !$adodb->IsConnected()) {
835 $this->config->debugauthdb = $olddebugauthdb;
836 $CFG->debug = $olddebug;
837 ini_set('display_errors', $olddisplay);
838 error_reporting($CFG->debug);
839 ob_end_flush();
840
841 echo $OUTPUT->notification('Cannot connect the database.', 'notifyproblem');
842 return;
843 }
844
845 $rs = $adodb->Execute("SELECT *
846 FROM {$this->config->table}
847 WHERE {$this->config->fielduser} <> 'random_unlikely_username'"); // Any unlikely name is ok here.
848
849 if (!$rs) {
850 echo $OUTPUT->notification('Can not read external table.', 'notifyproblem');
851
852 } else if ($rs->EOF) {
853 echo $OUTPUT->notification('External table is empty.', 'notifyproblem');
854 $rs->close();
855
856 } else {
857 $fields_obj = $rs->FetchObj();
858 $columns = array_keys((array)$fields_obj);
859
860 echo $OUTPUT->notification('External table contains following columns:<br />'.implode(', ', $columns), 'notifysuccess');
861 $rs->close();
862 }
863
864 $adodb->Close();
865
866 $this->config->debugauthdb = $olddebugauthdb;
867 $CFG->debug = $olddebug;
868 ini_set('display_errors', $olddisplay);
869 error_reporting($CFG->debug);
870 ob_end_flush();
871 }
b9ddb2d5 872}
873
5117d598 874