2 // This file is part of Moodle - http://moodle.org/
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.
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/>.
18 * Authentication Plugin: External Database Authentication
20 * Checks against an external database.
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');
32 * External database authentication plugin.
34 class auth_plugin_db extends auth_plugin_base {
39 function __construct() {
41 require_once($CFG->libdir.'/adodb/adodb.inc.php');
43 $this->authtype = 'db';
44 $this->config = get_config('auth/db');
45 if (empty($this->config->extencoding)) {
46 $this->config->extencoding = 'utf-8';
51 * Returns true if the username and password work and false if they are
52 * wrong or don't exist.
54 * @param string $username The username
55 * @param string $password The password
56 * @return bool Authentication success or failure.
58 function user_login($username, $password) {
61 $extusername = core_text::convert($username, 'utf-8', $this->config->extencoding);
62 $extpassword = core_text::convert($password, 'utf-8', $this->config->extencoding);
64 if ($this->is_internal()) {
65 // Lookup username externally, but resolve
66 // password locally -- to support backend that
67 // don't track passwords.
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);
78 $authdb = $this->db_init();
80 $rs = $authdb->Execute("SELECT *
81 FROM {$this->config->table}
82 WHERE {$this->config->fielduser} = '".$this->ext_addslashes($extusername)."'");
85 debugging(get_string('auth_dbcantconnect','auth_db'));
92 // User exists externally - check username/password internally.
93 if ($user = $DB->get_record('user', array('username'=>$username, 'mnethostid'=>$CFG->mnet_localhost_id, 'auth'=>$this->authtype))) {
94 return validate_internal_user_password($user, $password);
99 // User does not exist externally.
104 // Normal case: use external db for both usernames and passwords.
106 $authdb = $this->db_init();
108 $rs = $authdb->Execute("SELECT {$this->config->fieldpass} AS userpass
109 FROM {$this->config->table}
110 WHERE {$this->config->fielduser} = '".$this->ext_addslashes($extusername)."'");
113 debugging(get_string('auth_dbcantconnect','auth_db'));
122 $fields = array_change_key_case($rs->fields, CASE_LOWER);
123 $fromdb = $fields['userpass'];
127 if ($this->config->passtype === 'plaintext') {
128 return ($fromdb == $extpassword);
129 } else if ($this->config->passtype === 'md5') {
130 return ($fromdb == md5($extpassword));
131 } else if ($this->config->passtype === 'sha1') {
132 return ($fromdb == sha1($extpassword));
133 } else if ($this->config->passtype === 'saltedcrypt') {
134 require_once($CFG->libdir.'/password_compat/lib/password.php');
135 return password_verify($extpassword, $fromdb);
144 * Connect to external database.
146 * @return ADOConnection
149 // Connect to the external database (forcing new connection).
150 $authdb = ADONewConnection($this->config->type);
151 if (!empty($this->config->debugauthdb)) {
152 $authdb->debug = true;
153 ob_start(); //Start output buffer to allow later use of the page headers.
155 $authdb->Connect($this->config->host, $this->config->user, $this->config->pass, $this->config->name, true);
156 $authdb->SetFetchMode(ADODB_FETCH_ASSOC);
157 if (!empty($this->config->setupsql)) {
158 $authdb->Execute($this->config->setupsql);
165 * Returns user attribute mappings between moodle and ldap.
169 function db_attributes() {
170 $moodleattributes = array();
171 foreach ($this->userfields as $field) {
172 if (!empty($this->config->{"field_map_$field"})) {
173 $moodleattributes[$field] = $this->config->{"field_map_$field"};
176 $moodleattributes['username'] = $this->config->fielduser;
177 return $moodleattributes;
181 * Reads any other information for a user from external database,
182 * then returns it in an array.
184 * @param string $username
187 function get_userinfo($username) {
190 $extusername = core_text::convert($username, 'utf-8', $this->config->extencoding);
192 $authdb = $this->db_init();
194 // Array to map local fieldnames we want, to external fieldnames.
195 $selectfields = $this->db_attributes();
198 // If at least one field is mapped from external db, get that mapped data.
201 foreach ($selectfields as $localname=>$externalname) {
202 $select[] = "$externalname AS $localname";
204 $select = implode(', ', $select);
205 $sql = "SELECT $select
206 FROM {$this->config->table}
207 WHERE {$this->config->fielduser} = '".$this->ext_addslashes($extusername)."'";
208 if ($rs = $authdb->Execute($sql)) {
210 $fields_obj = $rs->FetchObj();
211 $fields_obj = (object)array_change_key_case((array)$fields_obj , CASE_LOWER);
212 foreach ($selectfields as $localname=>$externalname) {
213 $result[$localname] = core_text::convert($fields_obj->{$localname}, $this->config->extencoding, 'utf-8');
224 * Change a user's password.
226 * @param stdClass $user User table object
227 * @param string $newpassword Plaintext password
228 * @return bool True on success
230 function user_update_password($user, $newpassword) {
233 if ($this->is_internal()) {
234 $puser = $DB->get_record('user', array('id'=>$user->id), '*', MUST_EXIST);
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).
238 if (update_internal_user_password($puser, $newpassword)) {
239 $user->password = $puser->password;
245 // We should have never been called!
251 * Synchronizes user from external db to moodle user table.
253 * Sync should be done by using idnumber attribute, not username.
254 * You need to pass firstsync parameter to function to fill in
255 * idnumbers if they don't exists in moodle user table.
257 * Syncing users removes (disables) users that don't exists anymore in external db.
258 * Creates new users and updates coursecreator status of users.
260 * This implementation is simpler but less scalable than the one found in the LDAP module.
262 * @param progress_trace $trace
263 * @param bool $do_updates Optional: set to true to force an update of existing accounts
264 * @return int 0 means success, 1 means failure
266 function sync_users(progress_trace $trace, $do_updates=false) {
269 require_once($CFG->dirroot . '/user/lib.php');
271 // List external users.
272 $userlist = $this->get_userlist();
274 // Delete obsolete internal users.
275 if (!empty($this->config->removeuser)) {
278 if ($this->config->removeuser == AUTH_REMOVEUSER_SUSPEND) {
279 $suspendselect = "AND u.suspended = 0";
282 // Find obsolete users.
283 if (count($userlist)) {
284 list($notin_sql, $params) = $DB->get_in_or_equal($userlist, SQL_PARAMS_NAMED, 'u', false);
285 $params['authtype'] = $this->authtype;
288 WHERE u.auth=:authtype AND u.deleted=0 AND u.mnethostid=:mnethostid $suspendselect AND u.username $notin_sql";
292 WHERE u.auth=:authtype AND u.deleted=0 AND u.mnethostid=:mnethostid $suspendselect";
294 $params['authtype'] = $this->authtype;
296 $params['mnethostid'] = $CFG->mnet_localhost_id;
297 $remove_users = $DB->get_records_sql($sql, $params);
299 if (!empty($remove_users)) {
300 $trace->output(get_string('auth_dbuserstoremove','auth_db', count($remove_users)));
302 foreach ($remove_users as $user) {
303 if ($this->config->removeuser == AUTH_REMOVEUSER_FULLDELETE) {
305 $trace->output(get_string('auth_dbdeleteuser', 'auth_db', array('name'=>$user->username, 'id'=>$user->id)), 1);
306 } else if ($this->config->removeuser == AUTH_REMOVEUSER_SUSPEND) {
307 $updateuser = new stdClass();
308 $updateuser->id = $user->id;
309 $updateuser->suspended = 1;
310 user_update_user($updateuser, false);
311 $trace->output(get_string('auth_dbsuspenduser', 'auth_db', array('name'=>$user->username, 'id'=>$user->id)), 1);
315 unset($remove_users);
318 if (!count($userlist)) {
319 // Exit right here, nothing else to do.
324 // Update existing accounts.
326 // Narrow down what fields we need to update.
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') {
332 array_push($updatekeys, $match[1]); // The actual key name.
336 unset($all_keys); unset($key);
338 // Only go ahead if we actually have fields to update locally.
339 if (!empty($updatekeys)) {
340 list($in_sql, $params) = $DB->get_in_or_equal($userlist, SQL_PARAMS_NAMED, 'u', true);
341 $params['authtype'] = $this->authtype;
342 $sql = "SELECT u.id, u.username
344 WHERE u.auth=:authtype AND u.deleted=0 AND u.username {$in_sql}";
345 if ($update_users = $DB->get_records_sql($sql, $params)) {
346 $trace->output("User entries to update: ".count($update_users));
348 foreach ($update_users as $user) {
349 if ($this->update_user_record($user->username, $updatekeys)) {
350 $trace->output(get_string('auth_dbupdatinguser', 'auth_db', array('name'=>$user->username, 'id'=>$user->id)), 1);
352 $trace->output(get_string('auth_dbupdatinguser', 'auth_db', array('name'=>$user->username, 'id'=>$user->id))." - ".get_string('skipped'), 1);
355 unset($update_users);
361 // Create missing accounts.
362 // NOTE: this is very memory intensive and generally inefficient.
364 if ($this->config->removeuser == AUTH_REMOVEUSER_SUSPEND) {
365 $suspendselect = "AND u.suspended = 0";
367 $sql = "SELECT u.id, u.username
369 WHERE u.auth=:authtype AND u.deleted='0' AND mnethostid=:mnethostid $suspendselect";
371 $users = $DB->get_records_sql($sql, array('authtype'=>$this->authtype, 'mnethostid'=>$CFG->mnet_localhost_id));
373 // Simplify down to usernames.
374 $usernames = array();
375 if (!empty($users)) {
376 foreach ($users as $user) {
377 array_push($usernames, $user->username);
382 $add_users = array_diff($userlist, $usernames);
385 if (!empty($add_users)) {
386 $trace->output(get_string('auth_dbuserstoadd','auth_db',count($add_users)));
387 // Do not use transactions around this foreach, we want to skip problematic users, not revert everything.
388 foreach($add_users as $user) {
390 if ($this->config->removeuser == AUTH_REMOVEUSER_SUSPEND) {
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);
403 // Do not try to undelete users here, instead select suspending if you ever expect users will reappear.
405 // Prep a few params.
406 $user = $this->get_userinfo_asobj($user);
407 $user->username = $username;
408 $user->confirmed = 1;
409 $user->auth = $this->authtype;
410 $user->mnethostid = $CFG->mnet_localhost_id;
411 if (empty($user->lang)) {
412 $user->lang = $CFG->lang;
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')) {
415 $trace->output(get_string('auth_dbinsertuserduplicate', 'auth_db', array('username'=>$user->username, 'auth'=>$collision->auth)), 1);
419 $id = user_create_user($user, false); // It is truly a new user.
420 $trace->output(get_string('auth_dbinsertuser', 'auth_db', array('name'=>$user->username, 'id'=>$id)), 1);
421 } catch (moodle_exception $e) {
422 $trace->output(get_string('auth_dbinsertusererror', 'auth_db', $user->username), 1);
425 // If relevant, tag for password generation.
426 if ($this->is_internal()) {
427 set_user_preference('auth_forcepasswordchange', 1, $id);
428 set_user_preference('create_password', 1, $id);
430 // Make sure user context is present.
431 context_user::instance($id);
439 function user_exists($username) {
441 // Init result value.
444 $extusername = core_text::convert($username, 'utf-8', $this->config->extencoding);
446 $authdb = $this->db_init();
448 $rs = $authdb->Execute("SELECT *
449 FROM {$this->config->table}
450 WHERE {$this->config->fielduser} = '".$this->ext_addslashes($extusername)."' ");
453 print_error('auth_dbcantconnect','auth_db');
454 } else if (!$rs->EOF) {
455 // User exists externally.
464 function get_userlist() {
466 // Init result value.
469 $authdb = $this->db_init();
472 $rs = $authdb->Execute("SELECT {$this->config->fielduser} AS username
473 FROM {$this->config->table} ");
476 print_error('auth_dbcantconnect','auth_db');
477 } else if (!$rs->EOF) {
478 while ($rec = $rs->FetchRow()) {
479 $rec = (object)array_change_key_case((array)$rec , CASE_LOWER);
480 array_push($result, $rec->username);
489 * Reads user information from DB and return it in an object.
491 * @param string $username username
494 function get_userinfo_asobj($username) {
495 $user_array = truncate_userinfo($this->get_userinfo($username));
496 $user = new stdClass();
497 foreach($user_array as $key=>$value) {
498 $user->{$key} = $value;
504 * will update a local user record from an external source.
505 * is a lighter version of the one in moodlelib -- won't do
506 * expensive ops such as enrolment.
508 * If you don't pass $updatekeys, there is a performance hit and
509 * values removed from DB won't be removed from moodle.
511 * @param string $username username
512 * @param bool $updatekeys
515 function update_user_record($username, $updatekeys=false) {
518 //just in case check text case
519 $username = trim(core_text::strtolower($username));
521 // get the current user record
522 $user = $DB->get_record('user', array('username'=>$username, 'mnethostid'=>$CFG->mnet_localhost_id));
523 if (empty($user)) { // trouble
524 error_log("Cannot update non-existent user: $username");
525 print_error('auth_dbusernotexist','auth_db',$username);
529 // Ensure userid is not overwritten.
531 $needsupdate = false;
533 $updateuser = new stdClass();
534 $updateuser->id = $userid;
535 if ($newinfo = $this->get_userinfo($username)) {
536 $newinfo = truncate_userinfo($newinfo);
538 if (empty($updatekeys)) { // All keys? This does not support removing values.
539 $updatekeys = array_keys($newinfo);
542 foreach ($updatekeys as $key) {
543 if (isset($newinfo[$key])) {
544 $value = $newinfo[$key];
549 if (!empty($this->config->{'field_updatelocal_' . $key})) {
550 if (isset($user->{$key}) and $user->{$key} != $value) { // Only update if it's changed.
552 $updateuser->$key = $value;
558 require_once($CFG->dirroot . '/user/lib.php');
559 user_update_user($updateuser);
561 return $DB->get_record('user', array('id'=>$userid, 'deleted'=>0));
565 * Called when the user record is updated.
566 * Modifies user in external database. It takes olduser (before changes) and newuser (after changes)
567 * compares information saved modified information to external db.
569 * @param stdClass $olduser Userobject before modifications
570 * @param stdClass $newuser Userobject new modified userobject
571 * @return boolean result
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");
580 if (isset($olduser->auth) and $olduser->auth != $this->authtype) {
581 return true; // Just change auth and skip update.
584 $curruser = $this->get_userinfo($olduser->username);
585 if (empty($curruser)) {
586 error_log("ERROR:User $olduser->username found in ext db");
590 $extusername = core_text::convert($olduser->username, 'utf-8', $this->config->extencoding);
592 $authdb = $this->db_init();
595 foreach($curruser as $key=>$value) {
596 if ($key == 'username') {
597 continue; // Skip this.
599 if (empty($this->config->{"field_updateremote_$key"})) {
600 continue; // Remote update not requested.
602 if (!isset($newuser->$key)) {
605 $nuvalue = $newuser->$key;
606 if ($nuvalue != $value) {
607 $update[] = $this->config->{"field_map_$key"}."='".$this->ext_addslashes(core_text::convert($nuvalue, 'utf-8', $this->config->extencoding))."'";
610 if (!empty($update)) {
611 $authdb->Execute("UPDATE {$this->config->table}
612 SET ".implode(',', $update)."
613 WHERE {$this->config->fielduser}='".$this->ext_addslashes($extusername)."'");
620 * A chance to validate form data, and last chance to
621 * do stuff before it is inserted in config_plugin
623 * @param stfdClass $form
624 * @param array $err errors
627 function validate_form($form, &$err) {
628 if ($form->passtype === 'internal') {
629 $this->config->changepasswordurl = '';
630 set_config('changepasswordurl', '', 'auth/db');
634 function prevent_local_passwords() {
635 return !$this->is_internal();
639 * Returns true if this authentication plugin is "internal".
641 * Internal plugins use password hashes from Moodle user table for authentication.
645 function is_internal() {
646 if (!isset($this->config->passtype)) {
649 return ($this->config->passtype === 'internal');
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().
657 * @return bool true means automatically copy data from ext to user table
659 function is_synchronised_with_external() {
664 * Returns true if this authentication plugin can change the user's
669 function can_change_password() {
670 return ($this->is_internal() or !empty($this->config->changepasswordurl));
674 * Returns the URL for changing the user's pw, or empty if the default can
679 function change_password_url() {
680 if ($this->is_internal() || empty($this->config->changepasswordurl)) {
684 // Use admin defined custom url.
685 return new moodle_url($this->config->changepasswordurl);
690 * Returns true if plugin allows resetting of internal password.
694 function can_reset_password() {
695 return $this->is_internal();
699 * Prints a form for configuring this authentication plugin.
701 * This function is called from admin/auth.php, and outputs a full page with
702 * a form for configuring this plugin.
704 * @param stdClass $config
705 * @param array $err errors
706 * @param array $user_fields
709 function config_form($config, $err, $user_fields) {
710 include 'config.html';
714 * Processes and stores configuration data for this authentication plugin.
716 * @param srdClass $config
717 * @return bool always true or exception
719 function process_config($config) {
720 // set to defaults if undefined
721 if (!isset($config->host)) {
722 $config->host = 'localhost';
724 if (!isset($config->type)) {
725 $config->type = 'mysql';
727 if (!isset($config->sybasequoting)) {
728 $config->sybasequoting = 0;
730 if (!isset($config->name)) {
733 if (!isset($config->user)) {
736 if (!isset($config->pass)) {
739 if (!isset($config->table)) {
742 if (!isset($config->fielduser)) {
743 $config->fielduser = '';
745 if (!isset($config->fieldpass)) {
746 $config->fieldpass = '';
748 if (!isset($config->passtype)) {
749 $config->passtype = 'plaintext';
751 if (!isset($config->extencoding)) {
752 $config->extencoding = 'utf-8';
754 if (!isset($config->setupsql)) {
755 $config->setupsql = '';
757 if (!isset($config->debugauthdb)) {
758 $config->debugauthdb = 0;
760 if (!isset($config->removeuser)) {
761 $config->removeuser = AUTH_REMOVEUSER_KEEP;
763 if (!isset($config->changepasswordurl)) {
764 $config->changepasswordurl = '';
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');
779 set_config('setupsql', trim($config->setupsql),'auth/db');
780 set_config('debugauthdb', $config->debugauthdb, 'auth/db');
781 set_config('removeuser', $config->removeuser, 'auth/db');
782 set_config('changepasswordurl', trim($config->changepasswordurl), 'auth/db');
788 * Add slashes, we can not use placeholders or system functions.
790 * @param string $text
793 function ext_addslashes($text) {
794 if (empty($this->config->sybasequoting)) {
795 $text = str_replace('\\', '\\\\', $text);
796 $text = str_replace(array('\'', '"', "\0"), array('\\\'', '\\"', '\\0'), $text);
798 $text = str_replace("'", "''", $text);
804 * Test if settings are ok, print info to output.
807 public function test_settings() {
808 global $CFG, $OUTPUT;
810 // NOTE: this is not localised intentionally, admins are supposed to understand English at least a bit...
812 raise_memory_limit(MEMORY_HUGE);
814 if (empty($this->config->table)) {
815 echo $OUTPUT->notification('External table not specified.', 'notifyproblem');
819 if (empty($this->config->fielduser)) {
820 echo $OUTPUT->notification('External user field not specified.', 'notifyproblem');
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);
832 $adodb = $this->db_init();
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);
841 echo $OUTPUT->notification('Cannot connect the database.', 'notifyproblem');
845 $rs = $adodb->Execute("SELECT *
846 FROM {$this->config->table}
847 WHERE {$this->config->fielduser} <> 'random_unlikely_username'"); // Any unlikely name is ok here.
850 echo $OUTPUT->notification('Can not read external table.', 'notifyproblem');
852 } else if ($rs->EOF) {
853 echo $OUTPUT->notification('External table is empty.', 'notifyproblem');
857 $fields_obj = $rs->FetchObj();
858 $columns = array_keys((array)$fields_obj);
860 echo $OUTPUT->notification('External table contains following columns:<br />'.implode(', ', $columns), 'notifysuccess');
866 $this->config->debugauthdb = $olddebugauthdb;
867 $CFG->debug = $olddebug;
868 ini_set('display_errors', $olddisplay);
869 error_reporting($CFG->debug);