3 * Authentication Plugin: External Database Authentication
5 * Checks against an external database.
9 * @author Martin Dougiamas
10 * @license http://www.gnu.org/copyleft/gpl.html GNU Public License
13 defined('MOODLE_INTERNAL') ||
die();
15 require_once($CFG->libdir
.'/authlib.php');
16 require_once($CFG->libdir
.'/adodb/adodb.inc.php');
19 * External database authentication plugin.
21 class auth_plugin_db
extends auth_plugin_base
{
26 function auth_plugin_db() {
27 $this->authtype
= 'db';
28 $this->config
= get_config('auth/db');
29 if (empty($this->config
->extencoding
)) {
30 $this->config
->extencoding
= 'utf-8';
35 * Returns true if the username and password work and false if they are
36 * wrong or don't exist.
38 * @param string $username The username
39 * @param string $password The password
41 * @return bool Authentication success or failure.
43 function user_login($username, $password) {
46 $extusername = textlib
::convert($username, 'utf-8', $this->config
->extencoding
);
47 $extpassword = textlib
::convert($password, 'utf-8', $this->config
->extencoding
);
49 $authdb = $this->db_init();
51 if ($this->is_internal()) {
52 // lookup username externally, but resolve
53 // password locally -- to support backend that
54 // don't track passwords
55 $rs = $authdb->Execute("SELECT * FROM {$this->config->table}
56 WHERE {$this->config->fielduser} = '".$this->ext_addslashes($extusername)."' ");
59 debugging(get_string('auth_dbcantconnect','auth_db'));
66 // user exists externally
67 // check username/password internally
68 if ($user = $DB->get_record('user', array('username'=>$username, 'mnethostid'=>$CFG->mnet_localhost_id
, 'auth'=>$this->authtype
))) {
69 return validate_internal_user_password($user, $password);
74 // user does not exist externally
79 // normal case: use external db for both usernames and passwords
81 if ($this->config
->passtype
=== 'md5') { // Re-format password accordingly
82 $extpassword = md5($extpassword);
83 } else if ($this->config
->passtype
=== 'sha1') {
84 $extpassword = sha1($extpassword);
87 $rs = $authdb->Execute("SELECT * FROM {$this->config->table}
88 WHERE {$this->config->fielduser} = '".$this->ext_addslashes($extusername)."'
89 AND {$this->config->fieldpass} = '".$this->ext_addslashes($extpassword)."' ");
92 debugging(get_string('auth_dbcantconnect','auth_db'));
110 // Connect to the external database (forcing new connection)
111 $authdb = ADONewConnection($this->config
->type
);
112 if (!empty($this->config
->debugauthdb
)) {
113 $authdb->debug
= true;
114 ob_start();//start output buffer to allow later use of the page headers
116 $authdb->Connect($this->config
->host
, $this->config
->user
, $this->config
->pass
, $this->config
->name
, true);
117 $authdb->SetFetchMode(ADODB_FETCH_ASSOC
);
118 if (!empty($this->config
->setupsql
)) {
119 $authdb->Execute($this->config
->setupsql
);
126 * Returns user attribute mappings between moodle and ldap
130 function db_attributes() {
131 $moodleattributes = array();
132 foreach ($this->userfields
as $field) {
133 if (!empty($this->config
->{"field_map_$field"})) {
134 $moodleattributes[$field] = $this->config
->{"field_map_$field"};
137 $moodleattributes['username'] = $this->config
->fielduser
;
138 return $moodleattributes;
142 * Reads any other information for a user from external database,
143 * then returns it in an array
145 * @param string $username
147 * @return array without magic quotes
149 function get_userinfo($username) {
152 $extusername = textlib
::convert($username, 'utf-8', $this->config
->extencoding
);
154 $authdb = $this->db_init();
156 //Array to map local fieldnames we want, to external fieldnames
157 $selectfields = $this->db_attributes();
160 //If at least one field is mapped from external db, get that mapped data:
163 foreach ($selectfields as $localname=>$externalname) {
164 $select .= ", $externalname AS $localname";
166 $select = 'SELECT ' . substr($select,1);
168 " FROM {$this->config->table}" .
169 " WHERE {$this->config->fielduser} = '".$this->ext_addslashes($extusername)."'";
170 if ($rs = $authdb->Execute($sql)) {
172 $fields_obj = $rs->FetchObj();
173 $fields_obj = (object)array_change_key_case((array)$fields_obj , CASE_LOWER
);
174 foreach ($selectfields as $localname=>$externalname) {
175 $result[$localname] = textlib
::convert($fields_obj->{$localname}, $this->config
->extencoding
, 'utf-8');
186 * Change a user's password
188 * @param object $user User table object
189 * @param string $newpassword Plaintext password
191 * @return bool True on success
193 function user_update_password($user, $newpassword) {
194 if ($this->is_internal()) {
195 return update_internal_user_password($user, $newpassword);
197 // we should have never been called!
203 * synchronizes user from external db to moodle user table
205 * Sync should be done by using idnumber attribute, not username.
206 * You need to pass firstsync parameter to function to fill in
207 * idnumbers if they don't exists in moodle user table.
209 * Syncing users removes (disables) users that don't exists anymore in external db.
210 * Creates new users and updates coursecreator status of users.
212 * This implementation is simpler but less scalable than the one found in the LDAP module.
214 * @param bool $do_updates Optional: set to true to force an update of existing accounts
215 * @param bool $verbose
216 * @return int 0 means success, 1 means failure
218 function sync_users($do_updates=false, $verbose=false) {
221 // list external users
222 $userlist = $this->get_userlist();
224 // delete obsolete internal users
225 if (!empty($this->config
->removeuser
)) {
227 // find obsolete users
228 if (count($userlist)) {
229 list($notin_sql, $params) = $DB->get_in_or_equal($userlist, SQL_PARAMS_NAMED
, 'u', false);
230 $params['authtype'] = $this->authtype
;
233 WHERE u.auth=:authtype AND u.deleted=0 AND u.username $notin_sql";
237 WHERE u.auth=:authtype AND u.deleted=0";
239 $params['authtype'] = $this->authtype
;
241 $remove_users = $DB->get_records_sql($sql, $params);
243 if (!empty($remove_users)) {
245 mtrace(print_string('auth_dbuserstoremove','auth_db', count($remove_users)));
248 foreach ($remove_users as $user) {
249 if ($this->config
->removeuser
== AUTH_REMOVEUSER_FULLDELETE
) {
252 mtrace("\t".get_string('auth_dbdeleteuser', 'auth_db', array('name'=>$user->username
, 'id'=>$user->id
)));
254 } else if ($this->config
->removeuser
== AUTH_REMOVEUSER_SUSPEND
) {
255 $updateuser = new stdClass();
256 $updateuser->id
= $user->id
;
257 $updateuser->auth
= 'nologin';
258 $updateuser->timemodified
= time();
259 $DB->update_record('user', $updateuser);
261 mtrace("\t".get_string('auth_dbsuspenduser', 'auth_db', array('name'=>$user->username
, 'id'=>$user->id
)));
266 unset($remove_users); // free mem!
269 if (!count($userlist)) {
271 // nothing else to do
276 /// update existing accounts
279 // narrow down what fields we need to update
280 $all_keys = array_keys(get_object_vars($this->config
));
281 $updatekeys = array();
282 foreach ($all_keys as $key) {
283 if (preg_match('/^field_updatelocal_(.+)$/',$key, $match)) {
284 if ($this->config
->{$key} === 'onlogin') {
285 array_push($updatekeys, $match[1]); // the actual key name
289 // print_r($all_keys); print_r($updatekeys);
290 unset($all_keys); unset($key);
292 // only go ahead if we actually
293 // have fields to update locally
294 if (!empty($updatekeys)) {
295 list($in_sql, $params) = $DB->get_in_or_equal($userlist, SQL_PARAMS_NAMED
, 'u', true);
296 $params['authtype'] = $this->authtype
;
297 $sql = "SELECT u.id, u.username
299 WHERE u.auth=:authtype AND u.deleted=0 AND u.username {$in_sql}";
300 if ($update_users = $DB->get_records_sql($sql, $params)) {
302 mtrace("User entries to update: ".count($update_users));
305 foreach ($update_users as $user) {
306 if ($this->update_user_record($user->username
, $updatekeys)) {
308 mtrace("\t".get_string('auth_dbupdatinguser', 'auth_db', array('name'=>$user->username
, 'id'=>$user->id
)));
312 mtrace("\t".get_string('auth_dbupdatinguser', 'auth_db', array('name'=>$user->username
, 'id'=>$user->id
))." - ".get_string('skipped'));
316 unset($update_users); // free memory
323 /// create missing accounts
325 // NOTE: this is very memory intensive
326 // and generally inefficient
327 $sql = 'SELECT u.id, u.username
329 WHERE u.auth=\'' . $this->authtype
. '\' AND u.deleted=\'0\'';
331 $users = $DB->get_records_sql($sql);
333 // simplify down to usernames
334 $usernames = array();
335 if (!empty($users)) {
336 foreach ($users as $user) {
337 array_push($usernames, $user->username
);
342 $add_users = array_diff($userlist, $usernames);
345 if (!empty($add_users)) {
347 mtrace(get_string('auth_dbuserstoadd','auth_db',count($add_users)));
349 // Do not use transactions around this foreach, we want to skip problematic users, not revert everything.
350 foreach($add_users as $user) {
352 $user = $this->get_userinfo_asobj($user);
355 $user->username
= $username;
356 $user->confirmed
= 1;
357 $user->auth
= $this->authtype
;
358 $user->mnethostid
= $CFG->mnet_localhost_id
;
359 if (empty($user->lang
)) {
360 $user->lang
= $CFG->lang
;
363 // maybe the user has been deleted before
364 if ($old_user = $DB->get_record('user', array('username'=>$user->username
, 'deleted'=>1, 'mnethostid'=>$user->mnethostid
, 'auth'=>$user->auth
))) {
365 // note: this undeleting is deprecated and will be eliminated soon
366 $DB->set_field('user', 'deleted', 0, array('id'=>$old_user->id
));
367 $DB->set_field('user', 'timemodified', time(), array('id'=>$old_user->id
));
369 mtrace("\t".get_string('auth_dbreviveduser', 'auth_db', array('name'=>$old_user->username
, 'id'=>$old_user->id
)));
373 $user->timecreated
= time();
374 $user->timemodified
= $user->timecreated
;
376 $id = $DB->insert_record('user', $user); // it is truly a new user
378 mtrace("\t".get_string('auth_dbinsertuser', 'auth_db', array('name'=>$user->username
, 'id'=>$id)));
380 } catch (moodle_exception
$e) {
382 mtrace("\t".get_string('auth_dbinsertusererror', 'auth_db', $user->username
));
386 // if relevant, tag for password generation
387 if ($this->is_internal()) {
388 set_user_preference('auth_forcepasswordchange', 1, $id);
389 set_user_preference('create_password', 1, $id);
393 unset($add_users); // free mem
398 function user_exists($username) {
400 /// Init result value
403 $extusername = textlib
::convert($username, 'utf-8', $this->config
->extencoding
);
405 $authdb = $this->db_init();
407 $rs = $authdb->Execute("SELECT * FROM {$this->config->table}
408 WHERE {$this->config->fielduser} = '".$this->ext_addslashes($extusername)."' ");
411 print_error('auth_dbcantconnect','auth_db');
412 } else if (!$rs->EOF
) {
413 // user exists externally
422 function get_userlist() {
424 /// Init result value
427 $authdb = $this->db_init();
430 $rs = $authdb->Execute("SELECT {$this->config->fielduser} AS username
431 FROM {$this->config->table} ");
434 print_error('auth_dbcantconnect','auth_db');
435 } else if (!$rs->EOF
) {
436 while ($rec = $rs->FetchRow()) {
437 $rec = (object)array_change_key_case((array)$rec , CASE_LOWER
);
438 array_push($result, $rec->username
);
447 * reads user information from DB and return it in an object
449 * @param string $username username (with system magic quotes)
452 function get_userinfo_asobj($username) {
453 $user_array = truncate_userinfo($this->get_userinfo($username));
454 $user = new stdClass();
455 foreach($user_array as $key=>$value) {
456 $user->{$key} = $value;
462 * will update a local user record from an external source.
463 * is a lighter version of the one in moodlelib -- won't do
464 * expensive ops such as enrolment
466 * If you don't pass $updatekeys, there is a performance hit and
467 * values removed from DB won't be removed from moodle.
469 * @param string $username username
470 * @param bool $updatekeys
473 function update_user_record($username, $updatekeys=false) {
476 //just in case check text case
477 $username = trim(textlib
::strtolower($username));
479 // get the current user record
480 $user = $DB->get_record('user', array('username'=>$username, 'mnethostid'=>$CFG->mnet_localhost_id
));
481 if (empty($user)) { // trouble
482 error_log("Cannot update non-existent user: $username");
483 print_error('auth_dbusernotexist','auth_db',$username);
487 // Ensure userid is not overwritten
491 if ($newinfo = $this->get_userinfo($username)) {
492 $newinfo = truncate_userinfo($newinfo);
494 if (empty($updatekeys)) { // all keys? this does not support removing values
495 $updatekeys = array_keys($newinfo);
498 foreach ($updatekeys as $key) {
499 if (isset($newinfo[$key])) {
500 $value = $newinfo[$key];
505 if (!empty($this->config
->{'field_updatelocal_' . $key})) {
506 if (isset($user->{$key}) and $user->{$key} != $value) { // only update if it's changed
507 $DB->set_field('user', $key, $value, array('id'=>$userid));
514 $DB->set_field('user', 'timemodified', time(), array('id'=>$userid));
516 return $DB->get_record('user', array('id'=>$userid, 'deleted'=>0));
520 * Called when the user record is updated.
521 * Modifies user in external database. It takes olduser (before changes) and newuser (after changes)
522 * compares information saved modified information to external db.
524 * @param mixed $olduser Userobject before modifications
525 * @param mixed $newuser Userobject new modified userobject
526 * @return boolean result
529 function user_update($olduser, $newuser) {
530 if (isset($olduser->username
) and isset($newuser->username
) and $olduser->username
!= $newuser->username
) {
531 error_log("ERROR:User renaming not allowed in ext db");
535 if (isset($olduser->auth
) and $olduser->auth
!= $this->authtype
) {
536 return true; // just change auth and skip update
539 $curruser = $this->get_userinfo($olduser->username
);
540 if (empty($curruser)) {
541 error_log("ERROR:User $olduser->username found in ext db");
545 $extusername = textlib
::convert($olduser->username
, 'utf-8', $this->config
->extencoding
);
547 $authdb = $this->db_init();
550 foreach($curruser as $key=>$value) {
551 if ($key == 'username') {
552 continue; // skip this
554 if (empty($this->config
->{"field_updateremote_$key"})) {
555 continue; // remote update not requested
557 if (!isset($newuser->$key)) {
560 $nuvalue = $newuser->$key;
561 if ($nuvalue != $value) {
562 $update[] = $this->config
->{"field_map_$key"}."='".$this->ext_addslashes(textlib
::convert($nuvalue, 'utf-8', $this->config
->extencoding
))."'";
565 if (!empty($update)) {
566 $authdb->Execute("UPDATE {$this->config->table}
567 SET ".implode(',', $update)."
568 WHERE {$this->config->fielduser}='".$this->ext_addslashes($extusername)."'");
575 * A chance to validate form data, and last chance to
576 * do stuff before it is inserted in config_plugin
578 * @param stfdClass config form
579 * @param array $error errors
582 function validate_form($form, &$err) {
583 if ($form->passtype
=== 'internal') {
584 $this->config
->changepasswordurl
= '';
585 set_config('changepasswordurl', '', 'auth/db');
589 function prevent_local_passwords() {
590 return !$this->is_internal();
594 * Returns true if this authentication plugin is "internal".
596 * Internal plugins use password hashes from Moodle user table for authentication.
600 function is_internal() {
601 if (!isset($this->config
->passtype
)) {
604 return ($this->config
->passtype
=== 'internal');
608 * Indicates if moodle should automatically update internal user
609 * records with data from external sources using the information
610 * from auth_plugin_base::get_userinfo().
612 * @return bool true means automatically copy data from ext to user table
614 function is_synchronised_with_external() {
619 * Returns true if this authentication plugin can change the user's
624 function can_change_password() {
625 return ($this->is_internal() or !empty($this->config
->changepasswordurl
));
629 * Returns the URL for changing the user's pw, or empty if the default can
634 function change_password_url() {
635 if ($this->is_internal()) {
639 // use admin defined custom url
640 return new moodle_url($this->config
->changepasswordurl
);
645 * Returns true if plugin allows resetting of internal password.
649 function can_reset_password() {
650 return $this->is_internal();
654 * Prints a form for configuring this authentication plugin.
656 * This function is called from admin/auth.php, and outputs a full page with
657 * a form for configuring this plugin.
659 * @param stdClass $config
660 * @param array $err errors
661 * @param array $user_fields
664 function config_form($config, $err, $user_fields) {
665 include 'config.html';
669 * Processes and stores configuration data for this authentication plugin.
670 * @param srdClass $config
671 * @return bool always true or exception
673 function process_config($config) {
674 // set to defaults if undefined
675 if (!isset($config->host
)) {
676 $config->host
= 'localhost';
678 if (!isset($config->type
)) {
679 $config->type
= 'mysql';
681 if (!isset($config->sybasequoting
)) {
682 $config->sybasequoting
= 0;
684 if (!isset($config->name
)) {
687 if (!isset($config->user
)) {
690 if (!isset($config->pass
)) {
693 if (!isset($config->table
)) {
696 if (!isset($config->fielduser
)) {
697 $config->fielduser
= '';
699 if (!isset($config->fieldpass
)) {
700 $config->fieldpass
= '';
702 if (!isset($config->passtype
)) {
703 $config->passtype
= 'plaintext';
705 if (!isset($config->extencoding
)) {
706 $config->extencoding
= 'utf-8';
708 if (!isset($config->setupsql
)) {
709 $config->setupsql
= '';
711 if (!isset($config->debugauthdb
)) {
712 $config->debugauthdb
= 0;
714 if (!isset($config->removeuser
)) {
715 $config->removeuser
= AUTH_REMOVEUSER_KEEP
;
717 if (!isset($config->changepasswordurl
)) {
718 $config->changepasswordurl
= '';
722 set_config('host', $config->host
, 'auth/db');
723 set_config('type', $config->type
, 'auth/db');
724 set_config('sybasequoting', $config->sybasequoting
, 'auth/db');
725 set_config('name', $config->name
, 'auth/db');
726 set_config('user', $config->user
, 'auth/db');
727 set_config('pass', $config->pass
, 'auth/db');
728 set_config('table', $config->table
, 'auth/db');
729 set_config('fielduser', $config->fielduser
, 'auth/db');
730 set_config('fieldpass', $config->fieldpass
, 'auth/db');
731 set_config('passtype', $config->passtype
, 'auth/db');
732 set_config('extencoding', trim($config->extencoding
), 'auth/db');
733 set_config('setupsql', trim($config->setupsql
),'auth/db');
734 set_config('debugauthdb', $config->debugauthdb
, 'auth/db');
735 set_config('removeuser', $config->removeuser
, 'auth/db');
736 set_config('changepasswordurl', trim($config->changepasswordurl
), 'auth/db');
741 function ext_addslashes($text) {
742 // using custom made function for now
743 if (empty($this->config
->sybasequoting
)) {
744 $text = str_replace('\\', '\\\\', $text);
745 $text = str_replace(array('\'', '"', "\0"), array('\\\'', '\\"', '\\0'), $text);
747 $text = str_replace("'", "''", $text);