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))) {
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 $DB->update_record('user', $updateuser);
260 mtrace("\t".get_string('auth_dbsuspenduser', 'auth_db', array('name'=>$user->username, 'id'=>$user->id)));
265 unset($remove_users); // free mem!
268 if (!count($userlist)) {
270 // nothing else to do
275 /// update existing accounts
278 // narrow down what fields we need to update
279 $all_keys = array_keys(get_object_vars($this->config));
280 $updatekeys = array();
281 foreach ($all_keys as $key) {
282 if (preg_match('/^field_updatelocal_(.+)$/',$key, $match)) {
283 if ($this->config->{$key} === 'onlogin') {
284 array_push($updatekeys, $match[1]); // the actual key name
288 // print_r($all_keys); print_r($updatekeys);
289 unset($all_keys); unset($key);
291 // only go ahead if we actually
292 // have fields to update locally
293 if (!empty($updatekeys)) {
294 list($in_sql, $params) = $DB->get_in_or_equal($userlist, SQL_PARAMS_NAMED, 'u', true);
295 $params['authtype'] = $this->authtype;
296 $sql = "SELECT u.id, u.username
298 WHERE u.auth=:authtype AND u.deleted=0 AND u.username {$in_sql}";
299 if ($update_users = $DB->get_records_sql($sql, $params)) {
301 mtrace("User entries to update: ".count($update_users));
304 foreach ($update_users as $user) {
305 if ($this->update_user_record($user->username, $updatekeys)) {
307 mtrace("\t".get_string('auth_dbupdatinguser', 'auth_db', array('name'=>$user->username, 'id'=>$user->id)));
311 mtrace("\t".get_string('auth_dbupdatinguser', 'auth_db', array('name'=>$user->username, 'id'=>$user->id))." - ".get_string('skipped'));
315 unset($update_users); // free memory
322 /// create missing accounts
324 // NOTE: this is very memory intensive
325 // and generally inefficient
326 $sql = 'SELECT u.id, u.username
328 WHERE u.auth=\'' . $this->authtype . '\' AND u.deleted=\'0\'';
330 $users = $DB->get_records_sql($sql);
332 // simplify down to usernames
333 $usernames = array();
334 if (!empty($users)) {
335 foreach ($users as $user) {
336 array_push($usernames, $user->username);
341 $add_users = array_diff($userlist, $usernames);
344 if (!empty($add_users)) {
346 mtrace(get_string('auth_dbuserstoadd','auth_db',count($add_users)));
348 $transaction = $DB->start_delegated_transaction();
349 foreach($add_users as $user) {
351 $user = $this->get_userinfo_asobj($user);
354 $user->username = $username;
355 $user->modified = time();
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))) {
365 $user->id = $old_user->id;
366 $DB->set_field('user', 'deleted', 0, array('username'=>$user->username));
368 mtrace("\t".get_string('auth_dbreviveduser', 'auth_db', array('name'=>$user->username, 'id'=>$user->id)));
372 $id = $DB->insert_record ('user', $user); // it is truly a new user
374 mtrace("\t".get_string('auth_dbinsertuser', 'auth_db', array('name'=>$user->username, 'id'=>$id)));
376 // if relevant, tag for password generation
377 if ($this->is_internal()) {
378 set_user_preference('auth_forcepasswordchange', 1, $id);
379 set_user_preference('create_password', 1, $id);
383 $transaction->allow_commit();
384 unset($add_users); // free mem
389 function user_exists($username) {
391 /// Init result value
394 $extusername = textlib::convert($username, 'utf-8', $this->config->extencoding);
396 $authdb = $this->db_init();
398 $rs = $authdb->Execute("SELECT * FROM {$this->config->table}
399 WHERE {$this->config->fielduser} = '".$this->ext_addslashes($extusername)."' ");
402 print_error('auth_dbcantconnect','auth_db');
403 } else if (!$rs->EOF) {
404 // user exists externally
413 function get_userlist() {
415 /// Init result value
418 $authdb = $this->db_init();
421 $rs = $authdb->Execute("SELECT {$this->config->fielduser} AS username
422 FROM {$this->config->table} ");
425 print_error('auth_dbcantconnect','auth_db');
426 } else if (!$rs->EOF) {
427 while ($rec = $rs->FetchRow()) {
428 $rec = (object)array_change_key_case((array)$rec , CASE_LOWER);
429 array_push($result, $rec->username);
438 * reads user information from DB and return it in an object
440 * @param string $username username (with system magic quotes)
443 function get_userinfo_asobj($username) {
444 $user_array = truncate_userinfo($this->get_userinfo($username));
445 $user = new stdClass();
446 foreach($user_array as $key=>$value) {
447 $user->{$key} = $value;
453 * will update a local user record from an external source.
454 * is a lighter version of the one in moodlelib -- won't do
455 * expensive ops such as enrolment
457 * If you don't pass $updatekeys, there is a performance hit and
458 * values removed from DB won't be removed from moodle.
460 * @param string $username username
461 * @param bool $updatekeys
464 function update_user_record($username, $updatekeys=false) {
467 //just in case check text case
468 $username = trim(textlib::strtolower($username));
470 // get the current user record
471 $user = $DB->get_record('user', array('username'=>$username, 'mnethostid'=>$CFG->mnet_localhost_id));
472 if (empty($user)) { // trouble
473 error_log("Cannot update non-existent user: $username");
474 print_error('auth_dbusernotexist','auth_db',$username);
478 // Ensure userid is not overwritten
481 if ($newinfo = $this->get_userinfo($username)) {
482 $newinfo = truncate_userinfo($newinfo);
484 if (empty($updatekeys)) { // all keys? this does not support removing values
485 $updatekeys = array_keys($newinfo);
488 foreach ($updatekeys as $key) {
489 if (isset($newinfo[$key])) {
490 $value = $newinfo[$key];
495 if (!empty($this->config->{'field_updatelocal_' . $key})) {
496 if (isset($user->{$key}) and $user->{$key} != $value) { // only update if it's changed
497 $DB->set_field('user', $key, $value, array('id'=>$userid));
502 return $DB->get_record('user', array('id'=>$userid, 'deleted'=>0));
506 * Called when the user record is updated.
507 * Modifies user in external database. It takes olduser (before changes) and newuser (after changes)
508 * compares information saved modified information to external db.
510 * @param mixed $olduser Userobject before modifications
511 * @param mixed $newuser Userobject new modified userobject
512 * @return boolean result
515 function user_update($olduser, $newuser) {
516 if (isset($olduser->username) and isset($newuser->username) and $olduser->username != $newuser->username) {
517 error_log("ERROR:User renaming not allowed in ext db");
521 if (isset($olduser->auth) and $olduser->auth != $this->authtype) {
522 return true; // just change auth and skip update
525 $curruser = $this->get_userinfo($olduser->username);
526 if (empty($curruser)) {
527 error_log("ERROR:User $olduser->username found in ext db");
531 $extusername = textlib::convert($olduser->username, 'utf-8', $this->config->extencoding);
533 $authdb = $this->db_init();
536 foreach($curruser as $key=>$value) {
537 if ($key == 'username') {
538 continue; // skip this
540 if (empty($this->config->{"field_updateremote_$key"})) {
541 continue; // remote update not requested
543 if (!isset($newuser->$key)) {
546 $nuvalue = $newuser->$key;
547 if ($nuvalue != $value) {
548 $update[] = $this->config->{"field_map_$key"}."='".$this->ext_addslashes(textlib::convert($nuvalue, 'utf-8', $this->config->extencoding))."'";
551 if (!empty($update)) {
552 $authdb->Execute("UPDATE {$this->config->table}
553 SET ".implode(',', $update)."
554 WHERE {$this->config->fielduser}='".$this->ext_addslashes($extusername)."'");
561 * A chance to validate form data, and last chance to
562 * do stuff before it is inserted in config_plugin
564 * @param stfdClass config form
565 * @param array $error errors
568 function validate_form($form, &$err) {
569 if ($form->passtype === 'internal') {
570 $this->config->changepasswordurl = '';
571 set_config('changepasswordurl', '', 'auth/db');
575 function prevent_local_passwords() {
576 return !$this->is_internal();
580 * Returns true if this authentication plugin is "internal".
582 * Internal plugins use password hashes from Moodle user table for authentication.
586 function is_internal() {
587 if (!isset($this->config->passtype)) {
590 return ($this->config->passtype === 'internal');
594 * Indicates if moodle should automatically update internal user
595 * records with data from external sources using the information
596 * from auth_plugin_base::get_userinfo().
598 * @return bool true means automatically copy data from ext to user table
600 function is_synchronised_with_external() {
605 * Returns true if this authentication plugin can change the user's
610 function can_change_password() {
611 return ($this->is_internal() or !empty($this->config->changepasswordurl));
615 * Returns the URL for changing the user's pw, or empty if the default can
620 function change_password_url() {
621 if ($this->is_internal()) {
625 // use admin defined custom url
626 return new moodle_url($this->config->changepasswordurl);
631 * Returns true if plugin allows resetting of internal password.
635 function can_reset_password() {
636 return $this->is_internal();
640 * Prints a form for configuring this authentication plugin.
642 * This function is called from admin/auth.php, and outputs a full page with
643 * a form for configuring this plugin.
645 * @param stdClass $config
646 * @param array $err errors
647 * @param array $user_fields
650 function config_form($config, $err, $user_fields) {
651 include 'config.html';
655 * Processes and stores configuration data for this authentication plugin.
656 * @param srdClass $config
657 * @return bool always true or exception
659 function process_config($config) {
660 // set to defaults if undefined
661 if (!isset($config->host)) {
662 $config->host = 'localhost';
664 if (!isset($config->type)) {
665 $config->type = 'mysql';
667 if (!isset($config->sybasequoting)) {
668 $config->sybasequoting = 0;
670 if (!isset($config->name)) {
673 if (!isset($config->user)) {
676 if (!isset($config->pass)) {
679 if (!isset($config->table)) {
682 if (!isset($config->fielduser)) {
683 $config->fielduser = '';
685 if (!isset($config->fieldpass)) {
686 $config->fieldpass = '';
688 if (!isset($config->passtype)) {
689 $config->passtype = 'plaintext';
691 if (!isset($config->extencoding)) {
692 $config->extencoding = 'utf-8';
694 if (!isset($config->setupsql)) {
695 $config->setupsql = '';
697 if (!isset($config->debugauthdb)) {
698 $config->debugauthdb = 0;
700 if (!isset($config->removeuser)) {
701 $config->removeuser = AUTH_REMOVEUSER_KEEP;
703 if (!isset($config->changepasswordurl)) {
704 $config->changepasswordurl = '';
708 set_config('host', $config->host, 'auth/db');
709 set_config('type', $config->type, 'auth/db');
710 set_config('sybasequoting', $config->sybasequoting, 'auth/db');
711 set_config('name', $config->name, 'auth/db');
712 set_config('user', $config->user, 'auth/db');
713 set_config('pass', $config->pass, 'auth/db');
714 set_config('table', $config->table, 'auth/db');
715 set_config('fielduser', $config->fielduser, 'auth/db');
716 set_config('fieldpass', $config->fieldpass, 'auth/db');
717 set_config('passtype', $config->passtype, 'auth/db');
718 set_config('extencoding', trim($config->extencoding), 'auth/db');
719 set_config('setupsql', trim($config->setupsql),'auth/db');
720 set_config('debugauthdb', $config->debugauthdb, 'auth/db');
721 set_config('removeuser', $config->removeuser, 'auth/db');
722 set_config('changepasswordurl', trim($config->changepasswordurl), 'auth/db');
727 function ext_addslashes($text) {
728 // using custom made function for now
729 if (empty($this->config->sybasequoting)) {
730 $text = str_replace('\\', '\\\\', $text);
731 $text = str_replace(array('\'', '"', "\0"), array('\\\'', '\\"', '\\0'), $text);
733 $text = str_replace("'", "''", $text);