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 if ($this->config
->passtype
=== 'md5') { // Re-format password accordingly.
109 $extpassword = md5($extpassword);
110 } else if ($this->config
->passtype
=== 'sha1') {
111 $extpassword = sha1($extpassword);
114 $rs = $authdb->Execute("SELECT *
115 FROM {$this->config->table}
116 WHERE {$this->config->fielduser} = '".$this->ext_addslashes($extusername)."'
117 AND {$this->config->fieldpass} = '".$this->ext_addslashes($extpassword)."'");
120 debugging(get_string('auth_dbcantconnect','auth_db'));
138 * Connect to external database.
140 * @return ADOConnection
143 // Connect to the external database (forcing new connection).
144 $authdb = ADONewConnection($this->config
->type
);
145 if (!empty($this->config
->debugauthdb
)) {
146 $authdb->debug
= true;
147 ob_start(); //Start output buffer to allow later use of the page headers.
149 $authdb->Connect($this->config
->host
, $this->config
->user
, $this->config
->pass
, $this->config
->name
, true);
150 $authdb->SetFetchMode(ADODB_FETCH_ASSOC
);
151 if (!empty($this->config
->setupsql
)) {
152 $authdb->Execute($this->config
->setupsql
);
159 * Returns user attribute mappings between moodle and ldap.
163 function db_attributes() {
164 $moodleattributes = array();
165 foreach ($this->userfields
as $field) {
166 if (!empty($this->config
->{"field_map_$field"})) {
167 $moodleattributes[$field] = $this->config
->{"field_map_$field"};
170 $moodleattributes['username'] = $this->config
->fielduser
;
171 return $moodleattributes;
175 * Reads any other information for a user from external database,
176 * then returns it in an array.
178 * @param string $username
181 function get_userinfo($username) {
184 $extusername = core_text
::convert($username, 'utf-8', $this->config
->extencoding
);
186 $authdb = $this->db_init();
188 // Array to map local fieldnames we want, to external fieldnames.
189 $selectfields = $this->db_attributes();
192 // If at least one field is mapped from external db, get that mapped data.
195 foreach ($selectfields as $localname=>$externalname) {
196 $select[] = "$externalname AS $localname";
198 $select = implode(', ', $select);
199 $sql = "SELECT $select
200 FROM {$this->config->table}
201 WHERE {$this->config->fielduser} = '".$this->ext_addslashes($extusername)."'";
202 if ($rs = $authdb->Execute($sql)) {
204 $fields_obj = $rs->FetchObj();
205 $fields_obj = (object)array_change_key_case((array)$fields_obj , CASE_LOWER
);
206 foreach ($selectfields as $localname=>$externalname) {
207 $result[$localname] = core_text
::convert($fields_obj->{$localname}, $this->config
->extencoding
, 'utf-8');
218 * Change a user's password.
220 * @param stdClass $user User table object
221 * @param string $newpassword Plaintext password
222 * @return bool True on success
224 function user_update_password($user, $newpassword) {
227 if ($this->is_internal()) {
228 $puser = $DB->get_record('user', array('id'=>$user->id
), '*', MUST_EXIST
);
229 // This will also update the stored hash to the latest algorithm
230 // if the existing hash is using an out-of-date algorithm (or the
231 // legacy md5 algorithm).
232 if (update_internal_user_password($puser, $newpassword)) {
233 $user->password
= $puser->password
;
239 // We should have never been called!
245 * Synchronizes user from external db to moodle user table.
247 * Sync should be done by using idnumber attribute, not username.
248 * You need to pass firstsync parameter to function to fill in
249 * idnumbers if they don't exists in moodle user table.
251 * Syncing users removes (disables) users that don't exists anymore in external db.
252 * Creates new users and updates coursecreator status of users.
254 * This implementation is simpler but less scalable than the one found in the LDAP module.
256 * @param progress_trace $trace
257 * @param bool $do_updates Optional: set to true to force an update of existing accounts
258 * @return int 0 means success, 1 means failure
260 function sync_users(progress_trace
$trace, $do_updates=false) {
263 require_once($CFG->dirroot
. '/user/lib.php');
265 // List external users.
266 $userlist = $this->get_userlist();
268 // Delete obsolete internal users.
269 if (!empty($this->config
->removeuser
)) {
272 if ($this->config
->removeuser
== AUTH_REMOVEUSER_SUSPEND
) {
273 $suspendselect = "AND u.suspended = 0";
276 // Find obsolete users.
277 if (count($userlist)) {
278 list($notin_sql, $params) = $DB->get_in_or_equal($userlist, SQL_PARAMS_NAMED
, 'u', false);
279 $params['authtype'] = $this->authtype
;
282 WHERE u.auth=:authtype AND u.deleted=0 AND u.mnethostid=:mnethostid $suspendselect AND u.username $notin_sql";
286 WHERE u.auth=:authtype AND u.deleted=0 AND u.mnethostid=:mnethostid $suspendselect";
288 $params['authtype'] = $this->authtype
;
290 $params['mnethostid'] = $CFG->mnet_localhost_id
;
291 $remove_users = $DB->get_records_sql($sql, $params);
293 if (!empty($remove_users)) {
294 $trace->output(get_string('auth_dbuserstoremove','auth_db', count($remove_users)));
296 foreach ($remove_users as $user) {
297 if ($this->config
->removeuser
== AUTH_REMOVEUSER_FULLDELETE
) {
299 $trace->output(get_string('auth_dbdeleteuser', 'auth_db', array('name'=>$user->username
, 'id'=>$user->id
)), 1);
300 } else if ($this->config
->removeuser
== AUTH_REMOVEUSER_SUSPEND
) {
301 $updateuser = new stdClass();
302 $updateuser->id
= $user->id
;
303 $updateuser->suspended
= 1;
304 user_update_user($updateuser, false);
305 $trace->output(get_string('auth_dbsuspenduser', 'auth_db', array('name'=>$user->username
, 'id'=>$user->id
)), 1);
309 unset($remove_users);
312 if (!count($userlist)) {
313 // Exit right here, nothing else to do.
318 // Update existing accounts.
320 // Narrow down what fields we need to update.
321 $all_keys = array_keys(get_object_vars($this->config
));
322 $updatekeys = array();
323 foreach ($all_keys as $key) {
324 if (preg_match('/^field_updatelocal_(.+)$/',$key, $match)) {
325 if ($this->config
->{$key} === 'onlogin') {
326 array_push($updatekeys, $match[1]); // The actual key name.
330 unset($all_keys); unset($key);
332 // Only go ahead if we actually have fields to update locally.
333 if (!empty($updatekeys)) {
334 list($in_sql, $params) = $DB->get_in_or_equal($userlist, SQL_PARAMS_NAMED
, 'u', true);
335 $params['authtype'] = $this->authtype
;
336 $sql = "SELECT u.id, u.username
338 WHERE u.auth=:authtype AND u.deleted=0 AND u.username {$in_sql}";
339 if ($update_users = $DB->get_records_sql($sql, $params)) {
340 $trace->output("User entries to update: ".count($update_users));
342 foreach ($update_users as $user) {
343 if ($this->update_user_record($user->username
, $updatekeys)) {
344 $trace->output(get_string('auth_dbupdatinguser', 'auth_db', array('name'=>$user->username
, 'id'=>$user->id
)), 1);
346 $trace->output(get_string('auth_dbupdatinguser', 'auth_db', array('name'=>$user->username
, 'id'=>$user->id
))." - ".get_string('skipped'), 1);
349 unset($update_users);
355 // Create missing accounts.
356 // NOTE: this is very memory intensive and generally inefficient.
358 if ($this->config
->removeuser
== AUTH_REMOVEUSER_SUSPEND
) {
359 $suspendselect = "AND u.suspended = 0";
361 $sql = "SELECT u.id, u.username
363 WHERE u.auth=:authtype AND u.deleted='0' AND mnethostid=:mnethostid $suspendselect";
365 $users = $DB->get_records_sql($sql, array('authtype'=>$this->authtype
, 'mnethostid'=>$CFG->mnet_localhost_id
));
367 // Simplify down to usernames.
368 $usernames = array();
369 if (!empty($users)) {
370 foreach ($users as $user) {
371 array_push($usernames, $user->username
);
376 $add_users = array_diff($userlist, $usernames);
379 if (!empty($add_users)) {
380 $trace->output(get_string('auth_dbuserstoadd','auth_db',count($add_users)));
381 // Do not use transactions around this foreach, we want to skip problematic users, not revert everything.
382 foreach($add_users as $user) {
384 if ($this->config
->removeuser
== AUTH_REMOVEUSER_SUSPEND
) {
385 if ($olduser = $DB->get_record('user', array('username' => $username, 'deleted' => 0, 'suspended' => 1,
386 'mnethostid' => $CFG->mnet_localhost_id
, 'auth' => $this->authtype
))) {
387 $updateuser = new stdClass();
388 $updateuser->id
= $olduser->id
;
389 $updateuser->suspended
= 0;
390 user_update_user($updateuser);
391 $trace->output(get_string('auth_dbreviveduser', 'auth_db', array('name' => $username,
392 'id' => $olduser->id
)), 1);
397 // Do not try to undelete users here, instead select suspending if you ever expect users will reappear.
399 // Prep a few params.
400 $user = $this->get_userinfo_asobj($user);
401 $user->username
= $username;
402 $user->confirmed
= 1;
403 $user->auth
= $this->authtype
;
404 $user->mnethostid
= $CFG->mnet_localhost_id
;
405 if (empty($user->lang
)) {
406 $user->lang
= $CFG->lang
;
408 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')) {
409 $trace->output(get_string('auth_dbinsertuserduplicate', 'auth_db', array('username'=>$user->username
, 'auth'=>$collision->auth
)), 1);
413 $id = user_create_user($user, false); // It is truly a new user.
414 $trace->output(get_string('auth_dbinsertuser', 'auth_db', array('name'=>$user->username
, 'id'=>$id)), 1);
415 } catch (moodle_exception
$e) {
416 $trace->output(get_string('auth_dbinsertusererror', 'auth_db', $user->username
), 1);
419 // If relevant, tag for password generation.
420 if ($this->is_internal()) {
421 set_user_preference('auth_forcepasswordchange', 1, $id);
422 set_user_preference('create_password', 1, $id);
424 // Make sure user context is present.
425 context_user
::instance($id);
433 function user_exists($username) {
435 // Init result value.
438 $extusername = core_text
::convert($username, 'utf-8', $this->config
->extencoding
);
440 $authdb = $this->db_init();
442 $rs = $authdb->Execute("SELECT *
443 FROM {$this->config->table}
444 WHERE {$this->config->fielduser} = '".$this->ext_addslashes($extusername)."' ");
447 print_error('auth_dbcantconnect','auth_db');
448 } else if (!$rs->EOF
) {
449 // User exists externally.
458 function get_userlist() {
460 // Init result value.
463 $authdb = $this->db_init();
466 $rs = $authdb->Execute("SELECT {$this->config->fielduser} AS username
467 FROM {$this->config->table} ");
470 print_error('auth_dbcantconnect','auth_db');
471 } else if (!$rs->EOF
) {
472 while ($rec = $rs->FetchRow()) {
473 $rec = (object)array_change_key_case((array)$rec , CASE_LOWER
);
474 array_push($result, $rec->username
);
483 * Reads user information from DB and return it in an object.
485 * @param string $username username
488 function get_userinfo_asobj($username) {
489 $user_array = truncate_userinfo($this->get_userinfo($username));
490 $user = new stdClass();
491 foreach($user_array as $key=>$value) {
492 $user->{$key} = $value;
498 * will update a local user record from an external source.
499 * is a lighter version of the one in moodlelib -- won't do
500 * expensive ops such as enrolment.
502 * If you don't pass $updatekeys, there is a performance hit and
503 * values removed from DB won't be removed from moodle.
505 * @param string $username username
506 * @param bool $updatekeys
509 function update_user_record($username, $updatekeys=false) {
512 //just in case check text case
513 $username = trim(core_text
::strtolower($username));
515 // get the current user record
516 $user = $DB->get_record('user', array('username'=>$username, 'mnethostid'=>$CFG->mnet_localhost_id
));
517 if (empty($user)) { // trouble
518 error_log("Cannot update non-existent user: $username");
519 print_error('auth_dbusernotexist','auth_db',$username);
523 // Ensure userid is not overwritten.
525 $needsupdate = false;
527 $updateuser = new stdClass();
528 $updateuser->id
= $userid;
529 if ($newinfo = $this->get_userinfo($username)) {
530 $newinfo = truncate_userinfo($newinfo);
532 if (empty($updatekeys)) { // All keys? This does not support removing values.
533 $updatekeys = array_keys($newinfo);
536 foreach ($updatekeys as $key) {
537 if (isset($newinfo[$key])) {
538 $value = $newinfo[$key];
543 if (!empty($this->config
->{'field_updatelocal_' . $key})) {
544 if (isset($user->{$key}) and $user->{$key} != $value) { // Only update if it's changed.
546 $updateuser->$key = $value;
552 require_once($CFG->dirroot
. '/user/lib.php');
553 user_update_user($updateuser);
555 return $DB->get_record('user', array('id'=>$userid, 'deleted'=>0));
559 * Called when the user record is updated.
560 * Modifies user in external database. It takes olduser (before changes) and newuser (after changes)
561 * compares information saved modified information to external db.
563 * @param stdClass $olduser Userobject before modifications
564 * @param stdClass $newuser Userobject new modified userobject
565 * @return boolean result
568 function user_update($olduser, $newuser) {
569 if (isset($olduser->username
) and isset($newuser->username
) and $olduser->username
!= $newuser->username
) {
570 error_log("ERROR:User renaming not allowed in ext db");
574 if (isset($olduser->auth
) and $olduser->auth
!= $this->authtype
) {
575 return true; // Just change auth and skip update.
578 $curruser = $this->get_userinfo($olduser->username
);
579 if (empty($curruser)) {
580 error_log("ERROR:User $olduser->username found in ext db");
584 $extusername = core_text
::convert($olduser->username
, 'utf-8', $this->config
->extencoding
);
586 $authdb = $this->db_init();
589 foreach($curruser as $key=>$value) {
590 if ($key == 'username') {
591 continue; // Skip this.
593 if (empty($this->config
->{"field_updateremote_$key"})) {
594 continue; // Remote update not requested.
596 if (!isset($newuser->$key)) {
599 $nuvalue = $newuser->$key;
600 if ($nuvalue != $value) {
601 $update[] = $this->config
->{"field_map_$key"}."='".$this->ext_addslashes(core_text
::convert($nuvalue, 'utf-8', $this->config
->extencoding
))."'";
604 if (!empty($update)) {
605 $authdb->Execute("UPDATE {$this->config->table}
606 SET ".implode(',', $update)."
607 WHERE {$this->config->fielduser}='".$this->ext_addslashes($extusername)."'");
614 * A chance to validate form data, and last chance to
615 * do stuff before it is inserted in config_plugin
617 * @param stfdClass $form
618 * @param array $err errors
621 function validate_form($form, &$err) {
622 if ($form->passtype
=== 'internal') {
623 $this->config
->changepasswordurl
= '';
624 set_config('changepasswordurl', '', 'auth/db');
628 function prevent_local_passwords() {
629 return !$this->is_internal();
633 * Returns true if this authentication plugin is "internal".
635 * Internal plugins use password hashes from Moodle user table for authentication.
639 function is_internal() {
640 if (!isset($this->config
->passtype
)) {
643 return ($this->config
->passtype
=== 'internal');
647 * Indicates if moodle should automatically update internal user
648 * records with data from external sources using the information
649 * from auth_plugin_base::get_userinfo().
651 * @return bool true means automatically copy data from ext to user table
653 function is_synchronised_with_external() {
658 * Returns true if this authentication plugin can change the user's
663 function can_change_password() {
664 return ($this->is_internal() or !empty($this->config
->changepasswordurl
));
668 * Returns the URL for changing the user's pw, or empty if the default can
673 function change_password_url() {
674 if ($this->is_internal() ||
empty($this->config
->changepasswordurl
)) {
678 // Use admin defined custom url.
679 return new moodle_url($this->config
->changepasswordurl
);
684 * Returns true if plugin allows resetting of internal password.
688 function can_reset_password() {
689 return $this->is_internal();
693 * Prints a form for configuring this authentication plugin.
695 * This function is called from admin/auth.php, and outputs a full page with
696 * a form for configuring this plugin.
698 * @param stdClass $config
699 * @param array $err errors
700 * @param array $user_fields
703 function config_form($config, $err, $user_fields) {
704 include 'config.html';
708 * Processes and stores configuration data for this authentication plugin.
710 * @param srdClass $config
711 * @return bool always true or exception
713 function process_config($config) {
714 // set to defaults if undefined
715 if (!isset($config->host
)) {
716 $config->host
= 'localhost';
718 if (!isset($config->type
)) {
719 $config->type
= 'mysql';
721 if (!isset($config->sybasequoting
)) {
722 $config->sybasequoting
= 0;
724 if (!isset($config->name
)) {
727 if (!isset($config->user
)) {
730 if (!isset($config->pass
)) {
733 if (!isset($config->table
)) {
736 if (!isset($config->fielduser
)) {
737 $config->fielduser
= '';
739 if (!isset($config->fieldpass
)) {
740 $config->fieldpass
= '';
742 if (!isset($config->passtype
)) {
743 $config->passtype
= 'plaintext';
745 if (!isset($config->extencoding
)) {
746 $config->extencoding
= 'utf-8';
748 if (!isset($config->setupsql
)) {
749 $config->setupsql
= '';
751 if (!isset($config->debugauthdb
)) {
752 $config->debugauthdb
= 0;
754 if (!isset($config->removeuser
)) {
755 $config->removeuser
= AUTH_REMOVEUSER_KEEP
;
757 if (!isset($config->changepasswordurl
)) {
758 $config->changepasswordurl
= '';
762 set_config('host', $config->host
, 'auth/db');
763 set_config('type', $config->type
, 'auth/db');
764 set_config('sybasequoting', $config->sybasequoting
, 'auth/db');
765 set_config('name', $config->name
, 'auth/db');
766 set_config('user', $config->user
, 'auth/db');
767 set_config('pass', $config->pass
, 'auth/db');
768 set_config('table', $config->table
, 'auth/db');
769 set_config('fielduser', $config->fielduser
, 'auth/db');
770 set_config('fieldpass', $config->fieldpass
, 'auth/db');
771 set_config('passtype', $config->passtype
, 'auth/db');
772 set_config('extencoding', trim($config->extencoding
), 'auth/db');
773 set_config('setupsql', trim($config->setupsql
),'auth/db');
774 set_config('debugauthdb', $config->debugauthdb
, 'auth/db');
775 set_config('removeuser', $config->removeuser
, 'auth/db');
776 set_config('changepasswordurl', trim($config->changepasswordurl
), 'auth/db');
782 * Add slashes, we can not use placeholders or system functions.
784 * @param string $text
787 function ext_addslashes($text) {
788 if (empty($this->config
->sybasequoting
)) {
789 $text = str_replace('\\', '\\\\', $text);
790 $text = str_replace(array('\'', '"', "\0"), array('\\\'', '\\"', '\\0'), $text);
792 $text = str_replace("'", "''", $text);
798 * Test if settings are ok, print info to output.
801 public function test_settings() {
802 global $CFG, $OUTPUT;
804 // NOTE: this is not localised intentionally, admins are supposed to understand English at least a bit...
806 raise_memory_limit(MEMORY_HUGE
);
808 if (empty($this->config
->table
)) {
809 echo $OUTPUT->notification('External table not specified.', 'notifyproblem');
813 if (empty($this->config
->fielduser
)) {
814 echo $OUTPUT->notification('External user field not specified.', 'notifyproblem');
818 $olddebug = $CFG->debug
;
819 $olddisplay = ini_get('display_errors');
820 ini_set('display_errors', '1');
821 $CFG->debug
= DEBUG_DEVELOPER
;
822 $olddebugauthdb = $this->config
->debugauthdb
;
823 $this->config
->debugauthdb
= 1;
824 error_reporting($CFG->debug
);
826 $adodb = $this->db_init();
828 if (!$adodb or !$adodb->IsConnected()) {
829 $this->config
->debugauthdb
= $olddebugauthdb;
830 $CFG->debug
= $olddebug;
831 ini_set('display_errors', $olddisplay);
832 error_reporting($CFG->debug
);
835 echo $OUTPUT->notification('Cannot connect the database.', 'notifyproblem');
839 $rs = $adodb->Execute("SELECT *
840 FROM {$this->config->table}
841 WHERE {$this->config->fielduser} <> 'random_unlikely_username'"); // Any unlikely name is ok here.
844 echo $OUTPUT->notification('Can not read external table.', 'notifyproblem');
846 } else if ($rs->EOF
) {
847 echo $OUTPUT->notification('External table is empty.', 'notifyproblem');
851 $fields_obj = $rs->FetchObj();
852 $columns = array_keys((array)$fields_obj);
854 echo $OUTPUT->notification('External table contains following columns:<br />'.implode(', ', $columns), 'notifysuccess');
860 $this->config
->debugauthdb
= $olddebugauthdb;
861 $CFG->debug
= $olddebug;
862 ini_set('display_errors', $olddisplay);
863 error_reporting($CFG->debug
);