Merge branch 'MDL-56498-master' of git://github.com/mickhawkins/moodle
[moodle.git] / auth / db / auth.php
blob549e1032df7c9809fd6e30ccdeb2d787656c75d6
1 <?php
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.
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/>.
17 /**
18 * Authentication Plugin: External Database Authentication
20 * Checks against an external database.
22 * @package auth_db
23 * @author Martin Dougiamas
24 * @license http://www.gnu.org/copyleft/gpl.html GNU Public License
27 defined('MOODLE_INTERNAL') || die();
29 require_once($CFG->libdir.'/authlib.php');
31 /**
32 * External database authentication plugin.
34 class auth_plugin_db extends auth_plugin_base {
36 /**
37 * Constructor.
39 function __construct() {
40 global $CFG;
41 require_once($CFG->libdir.'/adodb/adodb.inc.php');
43 $this->authtype = 'db';
44 $this->config = get_config('auth_db');
45 $this->errorlogtag = '[AUTH DB] ';
46 if (empty($this->config->extencoding)) {
47 $this->config->extencoding = 'utf-8';
51 /**
52 * Returns true if the username and password work and false if they are
53 * wrong or don't exist.
55 * @param string $username The username
56 * @param string $password The password
57 * @return bool Authentication success or failure.
59 function user_login($username, $password) {
60 global $CFG, $DB;
62 if ($this->is_configured() === false) {
63 debugging(get_string('auth_notconfigured', 'auth', $this->authtype));
64 return false;
67 $extusername = core_text::convert($username, 'utf-8', $this->config->extencoding);
68 $extpassword = core_text::convert($password, 'utf-8', $this->config->extencoding);
70 if ($this->is_internal()) {
71 // Lookup username externally, but resolve
72 // password locally -- to support backend that
73 // don't track passwords.
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;
84 $authdb = $this->db_init();
86 $rs = $authdb->Execute("SELECT *
87 FROM {$this->config->table}
88 WHERE {$this->config->fielduser} = '".$this->ext_addslashes($extusername)."'");
89 if (!$rs) {
90 $authdb->Close();
91 debugging(get_string('auth_dbcantconnect','auth_db'));
92 return false;
95 if (!$rs->EOF) {
96 $rs->Close();
97 $authdb->Close();
98 // User exists externally - check username/password internally.
99 if ($user = $DB->get_record('user', array('username'=>$username, 'mnethostid'=>$CFG->mnet_localhost_id, 'auth'=>$this->authtype))) {
100 return validate_internal_user_password($user, $password);
102 } else {
103 $rs->Close();
104 $authdb->Close();
105 // User does not exist externally.
106 return false;
109 } else {
110 // Normal case: use external db for both usernames and passwords.
112 $authdb = $this->db_init();
114 $rs = $authdb->Execute("SELECT {$this->config->fieldpass}
115 FROM {$this->config->table}
116 WHERE {$this->config->fielduser} = '".$this->ext_addslashes($extusername)."'");
117 if (!$rs) {
118 $authdb->Close();
119 debugging(get_string('auth_dbcantconnect','auth_db'));
120 return false;
123 if ($rs->EOF) {
124 $authdb->Close();
125 return false;
128 $fields = array_change_key_case($rs->fields, CASE_LOWER);
129 $fromdb = $fields[strtolower($this->config->fieldpass)];
130 $rs->Close();
131 $authdb->Close();
133 if ($this->config->passtype === 'plaintext') {
134 return ($fromdb == $extpassword);
135 } else if ($this->config->passtype === 'md5') {
136 return (strtolower($fromdb) == md5($extpassword));
137 } else if ($this->config->passtype === 'sha1') {
138 return (strtolower($fromdb) == sha1($extpassword));
139 } else if ($this->config->passtype === 'saltedcrypt') {
140 return password_verify($extpassword, $fromdb);
141 } else {
142 return false;
149 * Connect to external database.
151 * @return ADOConnection
152 * @throws moodle_exception
154 function db_init() {
155 if ($this->is_configured() === false) {
156 throw new moodle_exception('auth_dbcantconnect', 'auth_db');
159 // Connect to the external database (forcing new connection).
160 $authdb = ADONewConnection($this->config->type);
161 if (!empty($this->config->debugauthdb)) {
162 $authdb->debug = true;
163 ob_start(); //Start output buffer to allow later use of the page headers.
165 $authdb->Connect($this->config->host, $this->config->user, $this->config->pass, $this->config->name, true);
166 $authdb->SetFetchMode(ADODB_FETCH_ASSOC);
167 if (!empty($this->config->setupsql)) {
168 $authdb->Execute($this->config->setupsql);
171 return $authdb;
175 * Returns user attribute mappings between moodle and the external database.
177 * @return array
179 function db_attributes() {
180 $moodleattributes = array();
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;
189 foreach ($userfields as $field) {
190 if (!empty($this->config->{"field_map_$field"})) {
191 $moodleattributes[$field] = $this->config->{"field_map_$field"};
194 $moodleattributes['username'] = $this->config->fielduser;
195 return $moodleattributes;
199 * Reads any other information for a user from external database,
200 * then returns it in an array.
202 * @param string $username
203 * @return array
205 function get_userinfo($username) {
206 global $CFG;
208 $extusername = core_text::convert($username, 'utf-8', $this->config->extencoding);
210 $authdb = $this->db_init();
212 // Array to map local fieldnames we want, to external fieldnames.
213 $selectfields = $this->db_attributes();
215 $result = array();
216 // If at least one field is mapped from external db, get that mapped data.
217 if ($selectfields) {
218 $select = array();
219 $fieldcount = 0;
220 foreach ($selectfields as $localname=>$externalname) {
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++;
226 $select = implode(', ', $select);
227 $sql = "SELECT $select
228 FROM {$this->config->table}
229 WHERE {$this->config->fielduser} = '".$this->ext_addslashes($extusername)."'";
231 if ($rs = $authdb->Execute($sql)) {
232 if (!$rs->EOF) {
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');
241 $rs->Close();
244 $authdb->Close();
245 return $result;
249 * Change a user's password.
251 * @param stdClass $user User table object
252 * @param string $newpassword Plaintext password
253 * @return bool True on success
255 function user_update_password($user, $newpassword) {
256 global $DB;
258 if ($this->is_internal()) {
259 $puser = $DB->get_record('user', array('id'=>$user->id), '*', MUST_EXIST);
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).
263 if (update_internal_user_password($puser, $newpassword)) {
264 $user->password = $puser->password;
265 return true;
266 } else {
267 return false;
269 } else {
270 // We should have never been called!
271 return false;
276 * Synchronizes user from external db to moodle user table.
278 * Sync should be done by using idnumber attribute, not username.
279 * You need to pass firstsync parameter to function to fill in
280 * idnumbers if they don't exists in moodle user table.
282 * Syncing users removes (disables) users that don't exists anymore in external db.
283 * Creates new users and updates coursecreator status of users.
285 * This implementation is simpler but less scalable than the one found in the LDAP module.
287 * @param progress_trace $trace
288 * @param bool $do_updates Optional: set to true to force an update of existing accounts
289 * @return int 0 means success, 1 means failure
291 function sync_users(progress_trace $trace, $do_updates=false) {
292 global $CFG, $DB;
294 require_once($CFG->dirroot . '/user/lib.php');
296 // List external users.
297 $userlist = $this->get_userlist();
299 // Delete obsolete internal users.
300 if (!empty($this->config->removeuser)) {
302 $suspendselect = "";
303 if ($this->config->removeuser == AUTH_REMOVEUSER_SUSPEND) {
304 $suspendselect = "AND u.suspended = 0";
307 // Find obsolete users.
308 if (count($userlist)) {
309 $removeusers = array();
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);
320 $usernamelist = array_flip($userlist);
321 foreach ($internalusersrs as $internaluser) {
322 if (!array_key_exists($internaluser->username, $usernamelist)) {
323 $removeusers[] = $internaluser;
326 $internalusersrs->close();
327 } else {
328 $sql = "SELECT u.id, u.username
329 FROM {user} u
330 WHERE u.auth=:authtype AND u.deleted=0 AND u.mnethostid=:mnethostid $suspendselect";
331 $params = array();
332 $params['authtype'] = $this->authtype;
333 $params['mnethostid'] = $CFG->mnet_localhost_id;
334 $removeusers = $DB->get_records_sql($sql, $params);
337 if (!empty($removeusers)) {
338 $trace->output(get_string('auth_dbuserstoremove', 'auth_db', count($removeusers)));
340 foreach ($removeusers as $user) {
341 if ($this->config->removeuser == AUTH_REMOVEUSER_FULLDELETE) {
342 delete_user($user);
343 $trace->output(get_string('auth_dbdeleteuser', 'auth_db', array('name'=>$user->username, 'id'=>$user->id)), 1);
344 } else if ($this->config->removeuser == AUTH_REMOVEUSER_SUSPEND) {
345 $updateuser = new stdClass();
346 $updateuser->id = $user->id;
347 $updateuser->suspended = 1;
348 user_update_user($updateuser, false);
349 $trace->output(get_string('auth_dbsuspenduser', 'auth_db', array('name'=>$user->username, 'id'=>$user->id)), 1);
353 unset($removeusers);
356 if (!count($userlist)) {
357 // Exit right here, nothing else to do.
358 $trace->finished();
359 return 0;
362 // Update existing accounts.
363 if ($do_updates) {
364 // Narrow down what fields we need to update.
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') {
370 array_push($updatekeys, $match[1]); // The actual key name.
374 unset($all_keys); unset($key);
376 // Only go ahead if we actually have fields to update locally.
377 if (!empty($updatekeys)) {
378 $update_users = array();
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);
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;
384 $params['mnethostid'] = $CFG->mnet_localhost_id;
385 $sql = "SELECT u.id, u.username, u.suspended
386 FROM {user} u
387 WHERE u.auth = :authtype AND u.deleted = 0 AND u.mnethostid = :mnethostid AND u.username {$in_sql}";
388 $update_users = $update_users + $DB->get_records_sql($sql, $params);
391 if ($update_users) {
392 $trace->output("User entries to update: ".count($update_users));
394 foreach ($update_users as $user) {
395 if ($this->update_user_record($user->username, $updatekeys, false, (bool) $user->suspended)) {
396 $trace->output(get_string('auth_dbupdatinguser', 'auth_db', array('name'=>$user->username, 'id'=>$user->id)), 1);
397 } else {
398 $trace->output(get_string('auth_dbupdatinguser', 'auth_db', array('name'=>$user->username, 'id'=>$user->id))." - ".get_string('skipped'), 1);
401 unset($update_users);
407 // Create missing accounts.
408 // NOTE: this is very memory intensive and generally inefficient.
409 $suspendselect = "";
410 if ($this->config->removeuser == AUTH_REMOVEUSER_SUSPEND) {
411 $suspendselect = "AND u.suspended = 0";
413 $sql = "SELECT u.id, u.username
414 FROM {user} u
415 WHERE u.auth=:authtype AND u.deleted='0' AND mnethostid=:mnethostid $suspendselect";
417 $users = $DB->get_records_sql($sql, array('authtype'=>$this->authtype, 'mnethostid'=>$CFG->mnet_localhost_id));
419 // Simplify down to usernames.
420 $usernames = array();
421 if (!empty($users)) {
422 foreach ($users as $user) {
423 array_push($usernames, $user->username);
425 unset($users);
428 $add_users = array_diff($userlist, $usernames);
429 unset($usernames);
431 if (!empty($add_users)) {
432 $trace->output(get_string('auth_dbuserstoadd','auth_db',count($add_users)));
433 // Do not use transactions around this foreach, we want to skip problematic users, not revert everything.
434 foreach($add_users as $user) {
435 $username = $user;
436 if ($this->config->removeuser == AUTH_REMOVEUSER_SUSPEND) {
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);
445 continue;
449 // Do not try to undelete users here, instead select suspending if you ever expect users will reappear.
451 // Prep a few params.
452 $user = $this->get_userinfo_asobj($user);
453 $user->username = $username;
454 $user->confirmed = 1;
455 $user->auth = $this->authtype;
456 $user->mnethostid = $CFG->mnet_localhost_id;
457 if (empty($user->lang)) {
458 $user->lang = $CFG->lang;
460 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')) {
461 $trace->output(get_string('auth_dbinsertuserduplicate', 'auth_db', array('username'=>$user->username, 'auth'=>$collision->auth)), 1);
462 continue;
464 try {
465 $id = user_create_user($user, false); // It is truly a new user.
466 $trace->output(get_string('auth_dbinsertuser', 'auth_db', array('name'=>$user->username, 'id'=>$id)), 1);
467 } catch (moodle_exception $e) {
468 $trace->output(get_string('auth_dbinsertusererror', 'auth_db', $user->username), 1);
469 continue;
471 // If relevant, tag for password generation.
472 if ($this->is_internal()) {
473 set_user_preference('auth_forcepasswordchange', 1, $id);
474 set_user_preference('create_password', 1, $id);
476 // Make sure user context is present.
477 context_user::instance($id);
479 unset($add_users);
481 $trace->finished();
482 return 0;
485 function user_exists($username) {
487 // Init result value.
488 $result = false;
490 $extusername = core_text::convert($username, 'utf-8', $this->config->extencoding);
492 $authdb = $this->db_init();
494 $rs = $authdb->Execute("SELECT *
495 FROM {$this->config->table}
496 WHERE {$this->config->fielduser} = '".$this->ext_addslashes($extusername)."' ");
498 if (!$rs) {
499 print_error('auth_dbcantconnect','auth_db');
500 } else if (!$rs->EOF) {
501 // User exists externally.
502 $result = true;
505 $authdb->Close();
506 return $result;
510 function get_userlist() {
512 // Init result value.
513 $result = array();
515 $authdb = $this->db_init();
517 // Fetch userlist.
518 $rs = $authdb->Execute("SELECT {$this->config->fielduser}
519 FROM {$this->config->table} ");
521 if (!$rs) {
522 print_error('auth_dbcantconnect','auth_db');
523 } else if (!$rs->EOF) {
524 while ($rec = $rs->FetchRow()) {
525 $rec = array_change_key_case((array)$rec, CASE_LOWER);
526 array_push($result, $rec[strtolower($this->config->fielduser)]);
530 $authdb->Close();
531 return $result;
535 * Reads user information from DB and return it in an object.
537 * @param string $username username
538 * @return array
540 function get_userinfo_asobj($username) {
541 $user_array = truncate_userinfo($this->get_userinfo($username));
542 $user = new stdClass();
543 foreach($user_array as $key=>$value) {
544 $user->{$key} = $value;
546 return $user;
550 * Called when the user record is updated.
551 * Modifies user in external database. It takes olduser (before changes) and newuser (after changes)
552 * compares information saved modified information to external db.
554 * @param stdClass $olduser Userobject before modifications
555 * @param stdClass $newuser Userobject new modified userobject
556 * @return boolean result
559 function user_update($olduser, $newuser) {
560 if (isset($olduser->username) and isset($newuser->username) and $olduser->username != $newuser->username) {
561 error_log("ERROR:User renaming not allowed in ext db");
562 return false;
565 if (isset($olduser->auth) and $olduser->auth != $this->authtype) {
566 return true; // Just change auth and skip update.
569 $curruser = $this->get_userinfo($olduser->username);
570 if (empty($curruser)) {
571 error_log("ERROR:User $olduser->username found in ext db");
572 return false;
575 $extusername = core_text::convert($olduser->username, 'utf-8', $this->config->extencoding);
577 $authdb = $this->db_init();
579 $update = array();
580 foreach($curruser as $key=>$value) {
581 if ($key == 'username') {
582 continue; // Skip this.
584 if (empty($this->config->{"field_updateremote_$key"})) {
585 continue; // Remote update not requested.
587 if (!isset($newuser->$key)) {
588 continue;
590 $nuvalue = $newuser->$key;
591 // Support for textarea fields.
592 if (isset($nuvalue['text'])) {
593 $nuvalue = $nuvalue['text'];
595 if ($nuvalue != $value) {
596 $update[] = $this->config->{"field_map_$key"}."='".$this->ext_addslashes(core_text::convert($nuvalue, 'utf-8', $this->config->extencoding))."'";
599 if (!empty($update)) {
600 $authdb->Execute("UPDATE {$this->config->table}
601 SET ".implode(',', $update)."
602 WHERE {$this->config->fielduser}='".$this->ext_addslashes($extusername)."'");
604 $authdb->Close();
605 return true;
608 function prevent_local_passwords() {
609 return !$this->is_internal();
613 * Returns true if this authentication plugin is "internal".
615 * Internal plugins use password hashes from Moodle user table for authentication.
617 * @return bool
619 function is_internal() {
620 if (!isset($this->config->passtype)) {
621 return true;
623 return ($this->config->passtype === 'internal');
627 * Returns false if this plugin is enabled but not configured.
629 * @return bool
631 public function is_configured() {
632 if (!empty($this->config->type)) {
633 return true;
635 return false;
639 * Indicates if moodle should automatically update internal user
640 * records with data from external sources using the information
641 * from auth_plugin_base::get_userinfo().
643 * @return bool true means automatically copy data from ext to user table
645 function is_synchronised_with_external() {
646 return true;
650 * Returns true if this authentication plugin can change the user's
651 * password.
653 * @return bool
655 function can_change_password() {
656 return ($this->is_internal() or !empty($this->config->changepasswordurl));
660 * Returns the URL for changing the user's pw, or empty if the default can
661 * be used.
663 * @return moodle_url
665 function change_password_url() {
666 if ($this->is_internal() || empty($this->config->changepasswordurl)) {
667 // Standard form.
668 return null;
669 } else {
670 // Use admin defined custom url.
671 return new moodle_url($this->config->changepasswordurl);
676 * Returns true if plugin allows resetting of internal password.
678 * @return bool
680 function can_reset_password() {
681 return $this->is_internal();
685 * Add slashes, we can not use placeholders or system functions.
687 * @param string $text
688 * @return string
690 function ext_addslashes($text) {
691 if (empty($this->config->sybasequoting)) {
692 $text = str_replace('\\', '\\\\', $text);
693 $text = str_replace(array('\'', '"', "\0"), array('\\\'', '\\"', '\\0'), $text);
694 } else {
695 $text = str_replace("'", "''", $text);
697 return $text;
701 * Test if settings are ok, print info to output.
702 * @private
704 public function test_settings() {
705 global $CFG, $OUTPUT;
707 // NOTE: this is not localised intentionally, admins are supposed to understand English at least a bit...
709 raise_memory_limit(MEMORY_HUGE);
711 if (empty($this->config->table)) {
712 echo $OUTPUT->notification('External table not specified.', 'notifyproblem');
713 return;
716 if (empty($this->config->fielduser)) {
717 echo $OUTPUT->notification('External user field not specified.', 'notifyproblem');
718 return;
721 $olddebug = $CFG->debug;
722 $olddisplay = ini_get('display_errors');
723 ini_set('display_errors', '1');
724 $CFG->debug = DEBUG_DEVELOPER;
725 $olddebugauthdb = $this->config->debugauthdb;
726 $this->config->debugauthdb = 1;
727 error_reporting($CFG->debug);
729 $adodb = $this->db_init();
731 if (!$adodb or !$adodb->IsConnected()) {
732 $this->config->debugauthdb = $olddebugauthdb;
733 $CFG->debug = $olddebug;
734 ini_set('display_errors', $olddisplay);
735 error_reporting($CFG->debug);
736 ob_end_flush();
738 echo $OUTPUT->notification('Cannot connect the database.', 'notifyproblem');
739 return;
742 $rs = $adodb->Execute("SELECT *
743 FROM {$this->config->table}
744 WHERE {$this->config->fielduser} <> 'random_unlikely_username'"); // Any unlikely name is ok here.
746 if (!$rs) {
747 echo $OUTPUT->notification('Can not read external table.', 'notifyproblem');
749 } else if ($rs->EOF) {
750 echo $OUTPUT->notification('External table is empty.', 'notifyproblem');
751 $rs->close();
753 } else {
754 $fields_obj = $rs->FetchObj();
755 $columns = array_keys((array)$fields_obj);
757 echo $OUTPUT->notification('External table contains following columns:<br />'.implode(', ', $columns), 'notifysuccess');
758 $rs->close();
761 $adodb->Close();
763 $this->config->debugauthdb = $olddebugauthdb;
764 $CFG->debug = $olddebug;
765 ini_set('display_errors', $olddisplay);
766 error_reporting($CFG->debug);
767 ob_end_flush();
771 * Clean the user data that comes from an external database.
772 * @deprecated since 3.1, please use core_user::clean_data() instead.
773 * @param array $user the user data to be validated against properties definition.
774 * @return stdClass $user the cleaned user data.
776 public function clean_data($user) {
777 debugging('The method clean_data() has been deprecated, please use core_user::clean_data() instead.',
778 DEBUG_DEVELOPER);
779 return core_user::clean_data($user);