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 $transaction = $DB->start_delegated_transaction();
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
;
375 $id = $DB->insert_record ('user', $user); // it is truly a new user
377 mtrace("\t".get_string('auth_dbinsertuser', 'auth_db', array('name'=>$user->username
, 'id'=>$id)));
379 // if relevant, tag for password generation
380 if ($this->is_internal()) {
381 set_user_preference('auth_forcepasswordchange', 1, $id);
382 set_user_preference('create_password', 1, $id);
386 $transaction->allow_commit();
387 unset($add_users); // free mem
392 function user_exists($username) {
394 /// Init result value
397 $extusername = textlib
::convert($username, 'utf-8', $this->config
->extencoding
);
399 $authdb = $this->db_init();
401 $rs = $authdb->Execute("SELECT * FROM {$this->config->table}
402 WHERE {$this->config->fielduser} = '".$this->ext_addslashes($extusername)."' ");
405 print_error('auth_dbcantconnect','auth_db');
406 } else if (!$rs->EOF
) {
407 // user exists externally
416 function get_userlist() {
418 /// Init result value
421 $authdb = $this->db_init();
424 $rs = $authdb->Execute("SELECT {$this->config->fielduser} AS username
425 FROM {$this->config->table} ");
428 print_error('auth_dbcantconnect','auth_db');
429 } else if (!$rs->EOF
) {
430 while ($rec = $rs->FetchRow()) {
431 $rec = (object)array_change_key_case((array)$rec , CASE_LOWER
);
432 array_push($result, $rec->username
);
441 * reads user information from DB and return it in an object
443 * @param string $username username (with system magic quotes)
446 function get_userinfo_asobj($username) {
447 $user_array = truncate_userinfo($this->get_userinfo($username));
448 $user = new stdClass();
449 foreach($user_array as $key=>$value) {
450 $user->{$key} = $value;
456 * will update a local user record from an external source.
457 * is a lighter version of the one in moodlelib -- won't do
458 * expensive ops such as enrolment
460 * If you don't pass $updatekeys, there is a performance hit and
461 * values removed from DB won't be removed from moodle.
463 * @param string $username username
464 * @param bool $updatekeys
467 function update_user_record($username, $updatekeys=false) {
470 //just in case check text case
471 $username = trim(textlib
::strtolower($username));
473 // get the current user record
474 $user = $DB->get_record('user', array('username'=>$username, 'mnethostid'=>$CFG->mnet_localhost_id
));
475 if (empty($user)) { // trouble
476 error_log("Cannot update non-existent user: $username");
477 print_error('auth_dbusernotexist','auth_db',$username);
481 // Ensure userid is not overwritten
485 if ($newinfo = $this->get_userinfo($username)) {
486 $newinfo = truncate_userinfo($newinfo);
488 if (empty($updatekeys)) { // all keys? this does not support removing values
489 $updatekeys = array_keys($newinfo);
492 foreach ($updatekeys as $key) {
493 if (isset($newinfo[$key])) {
494 $value = $newinfo[$key];
499 if (!empty($this->config
->{'field_updatelocal_' . $key})) {
500 if (isset($user->{$key}) and $user->{$key} != $value) { // only update if it's changed
501 $DB->set_field('user', $key, $value, array('id'=>$userid));
508 $DB->set_field('user', 'timemodified', time(), array('id'=>$userid));
510 return $DB->get_record('user', array('id'=>$userid, 'deleted'=>0));
514 * Called when the user record is updated.
515 * Modifies user in external database. It takes olduser (before changes) and newuser (after changes)
516 * compares information saved modified information to external db.
518 * @param mixed $olduser Userobject before modifications
519 * @param mixed $newuser Userobject new modified userobject
520 * @return boolean result
523 function user_update($olduser, $newuser) {
524 if (isset($olduser->username
) and isset($newuser->username
) and $olduser->username
!= $newuser->username
) {
525 error_log("ERROR:User renaming not allowed in ext db");
529 if (isset($olduser->auth
) and $olduser->auth
!= $this->authtype
) {
530 return true; // just change auth and skip update
533 $curruser = $this->get_userinfo($olduser->username
);
534 if (empty($curruser)) {
535 error_log("ERROR:User $olduser->username found in ext db");
539 $extusername = textlib
::convert($olduser->username
, 'utf-8', $this->config
->extencoding
);
541 $authdb = $this->db_init();
544 foreach($curruser as $key=>$value) {
545 if ($key == 'username') {
546 continue; // skip this
548 if (empty($this->config
->{"field_updateremote_$key"})) {
549 continue; // remote update not requested
551 if (!isset($newuser->$key)) {
554 $nuvalue = $newuser->$key;
555 if ($nuvalue != $value) {
556 $update[] = $this->config
->{"field_map_$key"}."='".$this->ext_addslashes(textlib
::convert($nuvalue, 'utf-8', $this->config
->extencoding
))."'";
559 if (!empty($update)) {
560 $authdb->Execute("UPDATE {$this->config->table}
561 SET ".implode(',', $update)."
562 WHERE {$this->config->fielduser}='".$this->ext_addslashes($extusername)."'");
569 * A chance to validate form data, and last chance to
570 * do stuff before it is inserted in config_plugin
572 * @param stfdClass config form
573 * @param array $error errors
576 function validate_form($form, &$err) {
577 if ($form->passtype
=== 'internal') {
578 $this->config
->changepasswordurl
= '';
579 set_config('changepasswordurl', '', 'auth/db');
583 function prevent_local_passwords() {
584 return !$this->is_internal();
588 * Returns true if this authentication plugin is "internal".
590 * Internal plugins use password hashes from Moodle user table for authentication.
594 function is_internal() {
595 if (!isset($this->config
->passtype
)) {
598 return ($this->config
->passtype
=== 'internal');
602 * Indicates if moodle should automatically update internal user
603 * records with data from external sources using the information
604 * from auth_plugin_base::get_userinfo().
606 * @return bool true means automatically copy data from ext to user table
608 function is_synchronised_with_external() {
613 * Returns true if this authentication plugin can change the user's
618 function can_change_password() {
619 return ($this->is_internal() or !empty($this->config
->changepasswordurl
));
623 * Returns the URL for changing the user's pw, or empty if the default can
628 function change_password_url() {
629 if ($this->is_internal()) {
633 // use admin defined custom url
634 return new moodle_url($this->config
->changepasswordurl
);
639 * Returns true if plugin allows resetting of internal password.
643 function can_reset_password() {
644 return $this->is_internal();
648 * Prints a form for configuring this authentication plugin.
650 * This function is called from admin/auth.php, and outputs a full page with
651 * a form for configuring this plugin.
653 * @param stdClass $config
654 * @param array $err errors
655 * @param array $user_fields
658 function config_form($config, $err, $user_fields) {
659 include 'config.html';
663 * Processes and stores configuration data for this authentication plugin.
664 * @param srdClass $config
665 * @return bool always true or exception
667 function process_config($config) {
668 // set to defaults if undefined
669 if (!isset($config->host
)) {
670 $config->host
= 'localhost';
672 if (!isset($config->type
)) {
673 $config->type
= 'mysql';
675 if (!isset($config->sybasequoting
)) {
676 $config->sybasequoting
= 0;
678 if (!isset($config->name
)) {
681 if (!isset($config->user
)) {
684 if (!isset($config->pass
)) {
687 if (!isset($config->table
)) {
690 if (!isset($config->fielduser
)) {
691 $config->fielduser
= '';
693 if (!isset($config->fieldpass
)) {
694 $config->fieldpass
= '';
696 if (!isset($config->passtype
)) {
697 $config->passtype
= 'plaintext';
699 if (!isset($config->extencoding
)) {
700 $config->extencoding
= 'utf-8';
702 if (!isset($config->setupsql
)) {
703 $config->setupsql
= '';
705 if (!isset($config->debugauthdb
)) {
706 $config->debugauthdb
= 0;
708 if (!isset($config->removeuser
)) {
709 $config->removeuser
= AUTH_REMOVEUSER_KEEP
;
711 if (!isset($config->changepasswordurl
)) {
712 $config->changepasswordurl
= '';
716 set_config('host', $config->host
, 'auth/db');
717 set_config('type', $config->type
, 'auth/db');
718 set_config('sybasequoting', $config->sybasequoting
, 'auth/db');
719 set_config('name', $config->name
, 'auth/db');
720 set_config('user', $config->user
, 'auth/db');
721 set_config('pass', $config->pass
, 'auth/db');
722 set_config('table', $config->table
, 'auth/db');
723 set_config('fielduser', $config->fielduser
, 'auth/db');
724 set_config('fieldpass', $config->fieldpass
, 'auth/db');
725 set_config('passtype', $config->passtype
, 'auth/db');
726 set_config('extencoding', trim($config->extencoding
), 'auth/db');
727 set_config('setupsql', trim($config->setupsql
),'auth/db');
728 set_config('debugauthdb', $config->debugauthdb
, 'auth/db');
729 set_config('removeuser', $config->removeuser
, 'auth/db');
730 set_config('changepasswordurl', trim($config->changepasswordurl
), 'auth/db');
735 function ext_addslashes($text) {
736 // using custom made function for now
737 if (empty($this->config
->sybasequoting
)) {
738 $text = str_replace('\\', '\\\\', $text);
739 $text = str_replace(array('\'', '"', "\0"), array('\\\'', '\\"', '\\0'), $text);
741 $text = str_replace("'", "''", $text);