on-demand release 4.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';
037273d8 44 $this->config = get_config('auth_db');
4afad1fa 45 $this->errorlogtag = '[AUTH DB] ';
8ae42b8d 46 if (empty($this->config->extencoding)) {
47 $this->config->extencoding = 'utf-8';
48 }
b9ddb2d5 49 }
50
51 /**
52 * Returns true if the username and password work and false if they are
53 * wrong or don't exist.
54 *
576c063b 55 * @param string $username The username
56 * @param string $password The password
8ae42b8d 57 * @return bool Authentication success or failure.
b9ddb2d5 58 */
139ebfdb 59 function user_login($username, $password) {
576c063b 60 global $CFG, $DB;
b9ddb2d5 61
b6f28375
CF
62 if ($this->is_configured() === false) {
63 debugging(get_string('auth_notconfigured', 'auth', $this->authtype));
64 return false;
65 }
66
2f1e464a
PS
67 $extusername = core_text::convert($username, 'utf-8', $this->config->extencoding);
68 $extpassword = core_text::convert($password, 'utf-8', $this->config->extencoding);
8ae42b8d 69
7415aed1 70 if ($this->is_internal()) {
e7aeaa65 71 // Lookup username externally, but resolve
b9ddb2d5 72 // password locally -- to support backend that
e7aeaa65 73 // don't track passwords.
ba87b41b
PS
74
75 if (isset($this->config->removeuser) and $this->config->removeuser == AUTH_REMOVEUSER_KEEP) {
76 // No need to connect to external database in this case because users are never removed and we verify password locally.
77 if ($user = $DB->get_record('user', array('username'=>$username, 'mnethostid'=>$CFG->mnet_localhost_id, 'auth'=>$this->authtype))) {
78 return validate_internal_user_password($user, $password);
79 } else {
80 return false;
81 }
82 }
83
84 $authdb = $this->db_init();
85
e7aeaa65
PS
86 $rs = $authdb->Execute("SELECT *
87 FROM {$this->config->table}
88 WHERE {$this->config->fielduser} = '".$this->ext_addslashes($extusername)."'");
b9ddb2d5 89 if (!$rs) {
03cedd62 90 $authdb->Close();
03ea0b32 91 debugging(get_string('auth_dbcantconnect','auth_db'));
b9ddb2d5 92 return false;
93 }
8ae42b8d 94
7415aed1 95 if (!$rs->EOF) {
03cedd62 96 $rs->Close();
97 $authdb->Close();
e7aeaa65 98 // User exists externally - check username/password internally.
a0a5ca25 99 if ($user = $DB->get_record('user', array('username'=>$username, 'mnethostid'=>$CFG->mnet_localhost_id, 'auth'=>$this->authtype))) {
b9ddb2d5 100 return validate_internal_user_password($user, $password);
101 }
102 } else {
03cedd62 103 $rs->Close();
104 $authdb->Close();
e7aeaa65 105 // User does not exist externally.
b9ddb2d5 106 return false;
8ae42b8d 107 }
b9ddb2d5 108
8ae42b8d 109 } else {
e7aeaa65 110 // Normal case: use external db for both usernames and passwords.
b9ddb2d5 111
ba87b41b
PS
112 $authdb = $this->db_init();
113
78a71368 114 $rs = $authdb->Execute("SELECT {$this->config->fieldpass}
c7c397ca 115 FROM {$this->config->table}
f97b63bf 116 WHERE {$this->config->fielduser} = '".$this->ext_addslashes($extusername)."'");
b9ddb2d5 117 if (!$rs) {
03cedd62 118 $authdb->Close();
03ea0b32 119 debugging(get_string('auth_dbcantconnect','auth_db'));
b9ddb2d5 120 return false;
121 }
8ae42b8d 122
f97b63bf 123 if ($rs->EOF) {
03cedd62 124 $authdb->Close();
f97b63bf
RM
125 return false;
126 }
127
e3d9fc3f 128 $fields = array_change_key_case($rs->fields, CASE_LOWER);
78a71368 129 $fromdb = $fields[strtolower($this->config->fieldpass)];
f97b63bf
RM
130 $rs->Close();
131 $authdb->Close();
132
133 if ($this->config->passtype === 'plaintext') {
03093b42 134 return ($fromdb === $extpassword);
f97b63bf 135 } else if ($this->config->passtype === 'md5') {
03093b42 136 return (strtolower($fromdb) === md5($extpassword));
f97b63bf 137 } else if ($this->config->passtype === 'sha1') {
03093b42 138 return (strtolower($fromdb) === sha1($extpassword));
f97b63bf 139 } else if ($this->config->passtype === 'saltedcrypt') {
f97b63bf 140 return password_verify($extpassword, $fromdb);
b9ddb2d5 141 } else {
142 return false;
8ae42b8d 143 }
144
b9ddb2d5 145 }
146 }
147
6cf20915
PS
148 /**
149 * Connect to external database.
150 *
151 * @return ADOConnection
b6f28375 152 * @throws moodle_exception
6cf20915 153 */
139ebfdb 154 function db_init() {
b6f28375
CF
155 if ($this->is_configured() === false) {
156 throw new moodle_exception('auth_dbcantconnect', 'auth_db');
157 }
158
e7aeaa65 159 // Connect to the external database (forcing new connection).
ab6e0848 160 $authdb = ADONewConnection($this->config->type);
8ae42b8d 161 if (!empty($this->config->debugauthdb)) {
162 $authdb->debug = true;
e7aeaa65 163 ob_start(); //Start output buffer to allow later use of the page headers.
8ae42b8d 164 }
165 $authdb->Connect($this->config->host, $this->config->user, $this->config->pass, $this->config->name, true);
b9ddb2d5 166 $authdb->SetFetchMode(ADODB_FETCH_ASSOC);
8ae42b8d 167 if (!empty($this->config->setupsql)) {
168 $authdb->Execute($this->config->setupsql);
169 }
b9ddb2d5 170
139ebfdb 171 return $authdb;
172 }
7415aed1 173
139ebfdb 174 /**
a86dbfbb 175 * Returns user attribute mappings between moodle and the external database.
139ebfdb 176 *
177 * @return array
178 */
179 function db_attributes() {
139ebfdb 180 $moodleattributes = array();
4ad0d0f2
VD
181 // If we have custom fields then merge them with user fields.
182 $customfields = $this->get_custom_user_profile_fields();
183 if (!empty($customfields) && !empty($this->userfields)) {
184 $userfields = array_merge($this->userfields, $customfields);
185 } else {
186 $userfields = $this->userfields;
187 }
188
189 foreach ($userfields as $field) {
139ebfdb 190 if (!empty($this->config->{"field_map_$field"})) {
191 $moodleattributes[$field] = $this->config->{"field_map_$field"};
0f02788f 192 }
193 }
5261baf1 194 $moodleattributes['username'] = $this->config->fielduser;
139ebfdb 195 return $moodleattributes;
196 }
197
198 /**
199 * Reads any other information for a user from external database,
e7aeaa65 200 * then returns it in an array.
139ebfdb 201 *
be544ec3 202 * @param string $username
e7aeaa65 203 * @return array
139ebfdb 204 */
205 function get_userinfo($username) {
139ebfdb 206 global $CFG;
207
2f1e464a 208 $extusername = core_text::convert($username, 'utf-8', $this->config->extencoding);
139ebfdb 209
210 $authdb = $this->db_init();
211
e7aeaa65 212 // Array to map local fieldnames we want, to external fieldnames.
139ebfdb 213 $selectfields = $this->db_attributes();
214
0f02788f 215 $result = array();
e7aeaa65 216 // If at least one field is mapped from external db, get that mapped data.
0f02788f 217 if ($selectfields) {
e7aeaa65 218 $select = array();
a86dbfbb 219 $fieldcount = 0;
0f02788f 220 foreach ($selectfields as $localname=>$externalname) {
a86dbfbb
MF
221 // Without aliasing, multiple occurrences of the same external
222 // name can coalesce in only occurrence in the result.
223 $select[] = "$externalname AS F".$fieldcount;
224 $fieldcount++;
0f02788f 225 }
e7aeaa65
PS
226 $select = implode(', ', $select);
227 $sql = "SELECT $select
228 FROM {$this->config->table}
229 WHERE {$this->config->fielduser} = '".$this->ext_addslashes($extusername)."'";
78a71368 230
0f02788f 231 if ($rs = $authdb->Execute($sql)) {
e7aeaa65 232 if (!$rs->EOF) {
78a71368
JO
233 $fields = $rs->FetchRow();
234 // Convert the associative array to an array of its values so we don't have to worry about the case of its keys.
235 $fields = array_values($fields);
236 foreach (array_keys($selectfields) as $index => $localname) {
237 $value = $fields[$index];
238 $result[$localname] = core_text::convert($value, $this->config->extencoding, 'utf-8');
0f02788f 239 }
240 }
245ac557 241 $rs->Close();
b9ddb2d5 242 }
243 }
244 $authdb->Close();
b9ddb2d5 245 return $result;
246 }
247
fb5c7739 248 /**
e7aeaa65 249 * Change a user's password.
fb5c7739 250 *
e7aeaa65 251 * @param stdClass $user User table object
ae040d4b 252 * @param string $newpassword Plaintext password
e7aeaa65 253 * @return bool True on success
fb5c7739 254 */
da249a30 255 function user_update_password($user, $newpassword) {
5c28e3a8
PS
256 global $DB;
257
7415aed1 258 if ($this->is_internal()) {
5c28e3a8 259 $puser = $DB->get_record('user', array('id'=>$user->id), '*', MUST_EXIST);
ec2d8ceb
SC
260 // This will also update the stored hash to the latest algorithm
261 // if the existing hash is using an out-of-date algorithm (or the
262 // legacy md5 algorithm).
5c28e3a8
PS
263 if (update_internal_user_password($puser, $newpassword)) {
264 $user->password = $puser->password;
265 return true;
266 } else {
267 return false;
268 }
b9ddb2d5 269 } else {
e7aeaa65 270 // We should have never been called!
b9ddb2d5 271 return false;
272 }
273 }
274
275 /**
e7aeaa65 276 * Synchronizes user from external db to moodle user table.
b9ddb2d5 277 *
ab6e0848 278 * Sync should be done by using idnumber attribute, not username.
b9ddb2d5 279 * You need to pass firstsync parameter to function to fill in
ab6e0848 280 * idnumbers if they don't exists in moodle user table.
8ae42b8d 281 *
ab6e0848 282 * Syncing users removes (disables) users that don't exists anymore in external db.
8ae42b8d 283 * Creates new users and updates coursecreator status of users.
284 *
b9ddb2d5 285 * This implementation is simpler but less scalable than the one found in the LDAP module.
286 *
e7aeaa65 287 * @param progress_trace $trace
7415aed1 288 * @param bool $do_updates Optional: set to true to force an update of existing accounts
ab6e0848 289 * @return int 0 means success, 1 means failure
b9ddb2d5 290 */
e7aeaa65 291 function sync_users(progress_trace $trace, $do_updates=false) {
70ca450a 292 global $CFG, $DB;
b9ddb2d5 293
e0e6d931
MN
294 require_once($CFG->dirroot . '/user/lib.php');
295
e7aeaa65 296 // List external users.
b9ddb2d5 297 $userlist = $this->get_userlist();
b9ddb2d5 298
e7aeaa65 299 // Delete obsolete internal users.
139ebfdb 300 if (!empty($this->config->removeuser)) {
b9ddb2d5 301
28fd4d6c
PS
302 $suspendselect = "";
303 if ($this->config->removeuser == AUTH_REMOVEUSER_SUSPEND) {
304 $suspendselect = "AND u.suspended = 0";
305 }
306
e7aeaa65 307 // Find obsolete users.
139ebfdb 308 if (count($userlist)) {
34949c1a 309 $removeusers = array();
7fc7486f
FM
310 $params['authtype'] = $this->authtype;
311 $sql = "SELECT u.id, u.username
312 FROM {user} u
313 WHERE u.auth=:authtype
314 AND u.deleted=0
315 AND u.mnethostid=:mnethostid
316 $suspendselect";
317 $params['mnethostid'] = $CFG->mnet_localhost_id;
318 $internalusersrs = $DB->get_recordset_sql($sql, $params);
319
320 $usernamelist = array_flip($userlist);
ec3e7913 321 foreach ($internalusersrs as $internaluser) {
ec3e7913 322 if (!array_key_exists($internaluser->username, $usernamelist)) {
34949c1a
JW
323 $removeusers[] = $internaluser;
324 }
6f08f36c 325 }
ec3e7913 326 $internalusersrs->close();
139ebfdb 327 } else {
3261b9ee 328 $sql = "SELECT u.id, u.username
bc31625a 329 FROM {user} u
28fd4d6c 330 WHERE u.auth=:authtype AND u.deleted=0 AND u.mnethostid=:mnethostid $suspendselect";
bc31625a 331 $params = array();
20d8d5c7 332 $params['authtype'] = $this->authtype;
6f08f36c 333 $params['mnethostid'] = $CFG->mnet_localhost_id;
34949c1a 334 $removeusers = $DB->get_records_sql($sql, $params);
139ebfdb 335 }
139ebfdb 336
34949c1a
JW
337 if (!empty($removeusers)) {
338 $trace->output(get_string('auth_dbuserstoremove', 'auth_db', count($removeusers)));
139ebfdb 339
34949c1a 340 foreach ($removeusers as $user) {
6f87ef52 341 if ($this->config->removeuser == AUTH_REMOVEUSER_FULLDELETE) {
ab6e0848 342 delete_user($user);
e7aeaa65 343 $trace->output(get_string('auth_dbdeleteuser', 'auth_db', array('name'=>$user->username, 'id'=>$user->id)), 1);
6f87ef52 344 } else if ($this->config->removeuser == AUTH_REMOVEUSER_SUSPEND) {
1dffbae2 345 $updateuser = new stdClass();
139ebfdb 346 $updateuser->id = $user->id;
28fd4d6c 347 $updateuser->suspended = 1;
bb78e249 348 user_update_user($updateuser, false);
e7aeaa65 349 $trace->output(get_string('auth_dbsuspenduser', 'auth_db', array('name'=>$user->username, 'id'=>$user->id)), 1);
139ebfdb 350 }
b9ddb2d5 351 }
8ae42b8d 352 }
34949c1a 353 unset($removeusers);
8ae42b8d 354 }
b9ddb2d5 355
356 if (!count($userlist)) {
e7aeaa65
PS
357 // Exit right here, nothing else to do.
358 $trace->finished();
ab6e0848 359 return 0;
b9ddb2d5 360 }
361
e7aeaa65 362 // Update existing accounts.
b9ddb2d5 363 if ($do_updates) {
e7aeaa65 364 // Narrow down what fields we need to update.
b9ddb2d5 365 $all_keys = array_keys(get_object_vars($this->config));
366 $updatekeys = array();
367 foreach ($all_keys as $key) {
368 if (preg_match('/^field_updatelocal_(.+)$/',$key, $match)) {
369 if ($this->config->{$key} === 'onlogin') {
e7aeaa65 370 array_push($updatekeys, $match[1]); // The actual key name.
b9ddb2d5 371 }
372 }
373 }
b9ddb2d5 374 unset($all_keys); unset($key);
375
e7aeaa65 376 // Only go ahead if we actually have fields to update locally.
b9ddb2d5 377 if (!empty($updatekeys)) {
6f08f36c 378 $update_users = array();
3261b9ee
AG
379 // All the drivers can cope with chunks of 10,000. See line 4491 of lib/dml/tests/dml_est.php
380 $userlistchunks = array_chunk($userlist , 10000);
6f08f36c
JM
381 foreach($userlistchunks as $userlistchunk) {
382 list($in_sql, $params) = $DB->get_in_or_equal($userlistchunk, SQL_PARAMS_NAMED, 'u', true);
383 $params['authtype'] = $this->authtype;
3261b9ee 384 $params['mnethostid'] = $CFG->mnet_localhost_id;
4e133e77 385 $sql = "SELECT u.id, u.username, u.suspended
bc31625a 386 FROM {user} u
3261b9ee 387 WHERE u.auth = :authtype AND u.deleted = 0 AND u.mnethostid = :mnethostid AND u.username {$in_sql}";
6f08f36c
JM
388 $update_users = $update_users + $DB->get_records_sql($sql, $params);
389 }
390
391 if ($update_users) {
e7aeaa65 392 $trace->output("User entries to update: ".count($update_users));
8ae42b8d 393
394 foreach ($update_users as $user) {
4e133e77 395 if ($this->update_user_record($user->username, $updatekeys, false, (bool) $user->suspended)) {
e7aeaa65 396 $trace->output(get_string('auth_dbupdatinguser', 'auth_db', array('name'=>$user->username, 'id'=>$user->id)), 1);
ab6e0848 397 } else {
e7aeaa65 398 $trace->output(get_string('auth_dbupdatinguser', 'auth_db', array('name'=>$user->username, 'id'=>$user->id))." - ".get_string('skipped'), 1);
139ebfdb 399 }
8ae42b8d 400 }
e7aeaa65 401 unset($update_users);
b9ddb2d5 402 }
b9ddb2d5 403 }
404 }
405
406
e7aeaa65
PS
407 // Create missing accounts.
408 // NOTE: this is very memory intensive and generally inefficient.
28fd4d6c
PS
409 $suspendselect = "";
410 if ($this->config->removeuser == AUTH_REMOVEUSER_SUSPEND) {
411 $suspendselect = "AND u.suspended = 0";
412 }
413 $sql = "SELECT u.id, u.username
414 FROM {user} u
415 WHERE u.auth=:authtype AND u.deleted='0' AND mnethostid=:mnethostid $suspendselect";
b9ddb2d5 416
28fd4d6c 417 $users = $DB->get_records_sql($sql, array('authtype'=>$this->authtype, 'mnethostid'=>$CFG->mnet_localhost_id));
8ae42b8d 418
e7aeaa65 419 // Simplify down to usernames.
b9ddb2d5 420 $usernames = array();
2b214bc1 421 if (!empty($users)) {
422 foreach ($users as $user) {
423 array_push($usernames, $user->username);
424 }
425 unset($users);
b9ddb2d5 426 }
b9ddb2d5 427
428 $add_users = array_diff($userlist, $usernames);
429 unset($usernames);
430
431 if (!empty($add_users)) {
e7aeaa65 432 $trace->output(get_string('auth_dbuserstoadd','auth_db',count($add_users)));
bee02209 433 // Do not use transactions around this foreach, we want to skip problematic users, not revert everything.
b9ddb2d5 434 foreach($add_users as $user) {
435 $username = $user;
28fd4d6c 436 if ($this->config->removeuser == AUTH_REMOVEUSER_SUSPEND) {
e0e6d931
MN
437 if ($olduser = $DB->get_record('user', array('username' => $username, 'deleted' => 0, 'suspended' => 1,
438 'mnethostid' => $CFG->mnet_localhost_id, 'auth' => $this->authtype))) {
439 $updateuser = new stdClass();
440 $updateuser->id = $olduser->id;
441 $updateuser->suspended = 0;
442 user_update_user($updateuser);
443 $trace->output(get_string('auth_dbreviveduser', 'auth_db', array('name' => $username,
444 'id' => $olduser->id)), 1);
28fd4d6c
PS
445 continue;
446 }
447 }
f0364be6
PS
448
449 // Do not try to undelete users here, instead select suspending if you ever expect users will reappear.
8ae42b8d 450
e7aeaa65 451 // Prep a few params.
f0364be6 452 $user = $this->get_userinfo_asobj($user);
b7b50143 453 $user->username = $username;
b7b50143 454 $user->confirmed = 1;
5211c7ec 455 $user->auth = $this->authtype;
b7b50143 456 $user->mnethostid = $CFG->mnet_localhost_id;
470f94dc 457
bee02209 458 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 459 $trace->output(get_string('auth_dbinsertuserduplicate', 'auth_db', array('username'=>$user->username, 'auth'=>$collision->auth)), 1);
bee02209
PS
460 continue;
461 }
f0364be6 462 try {
81fe9e9a 463 $id = user_create_user($user, false, false); // It is truly a new user.
e7aeaa65 464 $trace->output(get_string('auth_dbinsertuser', 'auth_db', array('name'=>$user->username, 'id'=>$id)), 1);
f0364be6 465 } catch (moodle_exception $e) {
e7aeaa65 466 $trace->output(get_string('auth_dbinsertusererror', 'auth_db', $user->username), 1);
bee02209 467 continue;
b9ddb2d5 468 }
e7aeaa65 469 // If relevant, tag for password generation.
f0364be6
PS
470 if ($this->is_internal()) {
471 set_user_preference('auth_forcepasswordchange', 1, $id);
472 set_user_preference('create_password', 1, $id);
473 }
c19ef03f 474
2f6f156a 475 // Save custom profile fields here.
c19ef03f
BW
476 require_once($CFG->dirroot . '/user/profile/lib.php');
477 $user->id = $id;
478 profile_save_data($user);
479
bee02209
PS
480 // Make sure user context is present.
481 context_user::instance($id);
81fe9e9a
MG
482
483 \core\event\user_created::create_from_userid($id)->trigger();
b9ddb2d5 484 }
e7aeaa65 485 unset($add_users);
b9ddb2d5 486 }
e7aeaa65 487 $trace->finished();
ab6e0848 488 return 0;
b9ddb2d5 489 }
490
139ebfdb 491 function user_exists($username) {
93901eb4 492
e7aeaa65 493 // Init result value.
a7e32367 494 $result = false;
495
2f1e464a 496 $extusername = core_text::convert($username, 'utf-8', $this->config->extencoding);
8ae42b8d 497
139ebfdb 498 $authdb = $this->db_init();
b9ddb2d5 499
e7aeaa65
PS
500 $rs = $authdb->Execute("SELECT *
501 FROM {$this->config->table}
502 WHERE {$this->config->fielduser} = '".$this->ext_addslashes($extusername)."' ");
b9ddb2d5 503
504 if (!$rs) {
2b06294b 505 print_error('auth_dbcantconnect','auth_db');
7415aed1 506 } else if (!$rs->EOF) {
e7aeaa65 507 // User exists externally.
03cedd62 508 $result = true;
8ae42b8d 509 }
a7e32367 510
511 $authdb->Close();
512 return $result;
b9ddb2d5 513 }
514
515
516 function get_userlist() {
93901eb4 517
e7aeaa65 518 // Init result value.
a7e32367 519 $result = array();
520
139ebfdb 521 $authdb = $this->db_init();
b9ddb2d5 522
e7aeaa65 523 // Fetch userlist.
78a71368 524 $rs = $authdb->Execute("SELECT {$this->config->fielduser}
e7aeaa65 525 FROM {$this->config->table} ");
b9ddb2d5 526
527 if (!$rs) {
2b06294b 528 print_error('auth_dbcantconnect','auth_db');
7415aed1 529 } else if (!$rs->EOF) {
245ac557 530 while ($rec = $rs->FetchRow()) {
78a71368
JO
531 $rec = array_change_key_case((array)$rec, CASE_LOWER);
532 array_push($result, $rec[strtolower($this->config->fielduser)]);
b9ddb2d5 533 }
8ae42b8d 534 }
a7e32367 535
536 $authdb->Close();
537 return $result;
b9ddb2d5 538 }
539
540 /**
e7aeaa65 541 * Reads user information from DB and return it in an object.
b9ddb2d5 542 *
e7aeaa65 543 * @param string $username username
b9ddb2d5 544 * @return array
545 */
546 function get_userinfo_asobj($username) {
547 $user_array = truncate_userinfo($this->get_userinfo($username));
1dffbae2 548 $user = new stdClass();
b9ddb2d5 549 foreach($user_array as $key=>$value) {
550 $user->{$key} = $value;
551 }
552 return $user;
553 }
554
139ebfdb 555 /**
556 * Called when the user record is updated.
557 * Modifies user in external database. It takes olduser (before changes) and newuser (after changes)
ab6e0848 558 * compares information saved modified information to external db.
139ebfdb 559 *
e7aeaa65
PS
560 * @param stdClass $olduser Userobject before modifications
561 * @param stdClass $newuser Userobject new modified userobject
139ebfdb 562 * @return boolean result
563 *
564 */
565 function user_update($olduser, $newuser) {
566 if (isset($olduser->username) and isset($newuser->username) and $olduser->username != $newuser->username) {
567 error_log("ERROR:User renaming not allowed in ext db");
568 return false;
569 }
570
5211c7ec 571 if (isset($olduser->auth) and $olduser->auth != $this->authtype) {
e7aeaa65 572 return true; // Just change auth and skip update.
139ebfdb 573 }
574
575 $curruser = $this->get_userinfo($olduser->username);
576 if (empty($curruser)) {
577 error_log("ERROR:User $olduser->username found in ext db");
578 return false;
579 }
580
2f1e464a 581 $extusername = core_text::convert($olduser->username, 'utf-8', $this->config->extencoding);
139ebfdb 582
583 $authdb = $this->db_init();
584
585 $update = array();
586 foreach($curruser as $key=>$value) {
587 if ($key == 'username') {
e7aeaa65 588 continue; // Skip this.
139ebfdb 589 }
590 if (empty($this->config->{"field_updateremote_$key"})) {
e7aeaa65 591 continue; // Remote update not requested.
139ebfdb 592 }
593 if (!isset($newuser->$key)) {
594 continue;
595 }
70ca450a 596 $nuvalue = $newuser->$key;
a6fe447a
ZD
597 // Support for textarea fields.
598 if (isset($nuvalue['text'])) {
599 $nuvalue = $nuvalue['text'];
600 }
139ebfdb 601 if ($nuvalue != $value) {
2f1e464a 602 $update[] = $this->config->{"field_map_$key"}."='".$this->ext_addslashes(core_text::convert($nuvalue, 'utf-8', $this->config->extencoding))."'";
139ebfdb 603 }
604 }
605 if (!empty($update)) {
5049102e
LS
606 $sql = "UPDATE {$this->config->table}
607 SET ".implode(',', $update)."
608 WHERE {$this->config->fielduser} = ?";
609 if (!$authdb->Execute($sql, array($this->ext_addslashes($extusername)))) {
610 print_error('auth_dbupdateerror', 'auth_db');
611 }
139ebfdb 612 }
613 $authdb->Close();
614 return true;
b9ddb2d5 615 }
616
edb5da83 617 function prevent_local_passwords() {
7415aed1 618 return !$this->is_internal();
edb5da83
PS
619 }
620
b9ddb2d5 621 /**
7415aed1
PS
622 * Returns true if this authentication plugin is "internal".
623 *
624 * Internal plugins use password hashes from Moodle user table for authentication.
b9ddb2d5 625 *
139ebfdb 626 * @return bool
b9ddb2d5 627 */
628 function is_internal() {
e79781f7
PS
629 if (!isset($this->config->passtype)) {
630 return true;
631 }
7415aed1
PS
632 return ($this->config->passtype === 'internal');
633 }
634
b6f28375
CF
635 /**
636 * Returns false if this plugin is enabled but not configured.
637 *
638 * @return bool
639 */
640 public function is_configured() {
641 if (!empty($this->config->type)) {
642 return true;
643 }
644 return false;
645 }
646
7415aed1
PS
647 /**
648 * Indicates if moodle should automatically update internal user
649 * records with data from external sources using the information
650 * from auth_plugin_base::get_userinfo().
651 *
652 * @return bool true means automatically copy data from ext to user table
653 */
654 function is_synchronised_with_external() {
655 return true;
b9ddb2d5 656 }
657
658 /**
659 * Returns true if this authentication plugin can change the user's
660 * password.
661 *
139ebfdb 662 * @return bool
b9ddb2d5 663 */
664 function can_change_password() {
7415aed1 665 return ($this->is_internal() or !empty($this->config->changepasswordurl));
b9ddb2d5 666 }
667
668 /**
430759a5 669 * Returns the URL for changing the user's pw, or empty if the default can
b9ddb2d5 670 * be used.
671 *
99f9f85f 672 * @return moodle_url
b9ddb2d5 673 */
674 function change_password_url() {
963cdce4 675 if ($this->is_internal() || empty($this->config->changepasswordurl)) {
e7aeaa65 676 // Standard form.
99f9f85f 677 return null;
430759a5 678 } else {
e7aeaa65 679 // Use admin defined custom url.
99f9f85f 680 return new moodle_url($this->config->changepasswordurl);
430759a5 681 }
b9ddb2d5 682 }
683
ab6ff8a4 684 /**
685 * Returns true if plugin allows resetting of internal password.
686 *
687 * @return bool
688 */
689 function can_reset_password() {
7415aed1 690 return $this->is_internal();
ab6ff8a4 691 }
692
e7aeaa65
PS
693 /**
694 * Add slashes, we can not use placeholders or system functions.
695 *
696 * @param string $text
697 * @return string
698 */
8ae42b8d 699 function ext_addslashes($text) {
8ae42b8d 700 if (empty($this->config->sybasequoting)) {
701 $text = str_replace('\\', '\\\\', $text);
702 $text = str_replace(array('\'', '"', "\0"), array('\\\'', '\\"', '\\0'), $text);
703 } else {
704 $text = str_replace("'", "''", $text);
705 }
706 return $text;
707 }
6cf20915
PS
708
709 /**
710 * Test if settings are ok, print info to output.
711 * @private
712 */
713 public function test_settings() {
714 global $CFG, $OUTPUT;
715
716 // NOTE: this is not localised intentionally, admins are supposed to understand English at least a bit...
717
718 raise_memory_limit(MEMORY_HUGE);
719
720 if (empty($this->config->table)) {
6bdccc74 721 echo $OUTPUT->notification(get_string('auth_dbnoexttable', 'auth_db'), 'notifyproblem');
6cf20915
PS
722 return;
723 }
724
725 if (empty($this->config->fielduser)) {
6bdccc74 726 echo $OUTPUT->notification(get_string('auth_dbnouserfield', 'auth_db'), 'notifyproblem');
6cf20915
PS
727 return;
728 }
729
730 $olddebug = $CFG->debug;
731 $olddisplay = ini_get('display_errors');
732 ini_set('display_errors', '1');
733 $CFG->debug = DEBUG_DEVELOPER;
734 $olddebugauthdb = $this->config->debugauthdb;
735 $this->config->debugauthdb = 1;
736 error_reporting($CFG->debug);
737
738 $adodb = $this->db_init();
739
740 if (!$adodb or !$adodb->IsConnected()) {
741 $this->config->debugauthdb = $olddebugauthdb;
742 $CFG->debug = $olddebug;
743 ini_set('display_errors', $olddisplay);
744 error_reporting($CFG->debug);
745 ob_end_flush();
746
6bdccc74 747 echo $OUTPUT->notification(get_string('auth_dbcannotconnect', 'auth_db'), 'notifyproblem');
6cf20915
PS
748 return;
749 }
750
751 $rs = $adodb->Execute("SELECT *
752 FROM {$this->config->table}
753 WHERE {$this->config->fielduser} <> 'random_unlikely_username'"); // Any unlikely name is ok here.
754
755 if (!$rs) {
6bdccc74 756 echo $OUTPUT->notification(get_string('auth_dbcannotreadtable', 'auth_db'), 'notifyproblem');
6cf20915
PS
757
758 } else if ($rs->EOF) {
6bdccc74 759 echo $OUTPUT->notification(get_string('auth_dbtableempty', 'auth_db'), 'notifyproblem');
6cf20915
PS
760 $rs->close();
761
762 } else {
763 $fields_obj = $rs->FetchObj();
764 $columns = array_keys((array)$fields_obj);
765
6bdccc74 766 echo $OUTPUT->notification(get_string('auth_dbcolumnlist', 'auth_db', implode(', ', $columns)), 'notifysuccess');
6cf20915
PS
767 $rs->close();
768 }
769
770 $adodb->Close();
771
772 $this->config->debugauthdb = $olddebugauthdb;
773 $CFG->debug = $olddebug;
774 ini_set('display_errors', $olddisplay);
775 error_reporting($CFG->debug);
776 ob_end_flush();
777 }
ce597604
SL
778
779 /**
780 * Clean the user data that comes from an external database.
5e60be8a 781 * @deprecated since 3.1, please use core_user::clean_data() instead.
ce597604
SL
782 * @param array $user the user data to be validated against properties definition.
783 * @return stdClass $user the cleaned user data.
784 */
785 public function clean_data($user) {
5e60be8a
SL
786 debugging('The method clean_data() has been deprecated, please use core_user::clean_data() instead.',
787 DEBUG_DEVELOPER);
788 return core_user::clean_data($user);
ce597604 789 }
b9ddb2d5 790}