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