weekly release 2.8.5+
[moodle.git] / auth / db / auth.php
blobfaccb6d540bd7f7917b053c62c48dcd85dbc8c29
1 <?php
2 // This file is part of Moodle - http://moodle.org/
3 //
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.
8 //
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/>.
17 /**
18 * Authentication Plugin: External Database Authentication
20 * Checks against an external database.
22 * @package auth_db
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');
31 /**
32 * External database authentication plugin.
34 class auth_plugin_db extends auth_plugin_base {
36 /**
37 * Constructor.
39 function __construct() {
40 global $CFG;
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';
50 /**
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) {
59 global $CFG, $DB;
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);
73 } else {
74 return false;
78 $authdb = $this->db_init();
80 $rs = $authdb->Execute("SELECT *
81 FROM {$this->config->table}
82 WHERE {$this->config->fielduser} = '".$this->ext_addslashes($extusername)."'");
83 if (!$rs) {
84 $authdb->Close();
85 debugging(get_string('auth_dbcantconnect','auth_db'));
86 return false;
89 if (!$rs->EOF) {
90 $rs->Close();
91 $authdb->Close();
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);
96 } else {
97 $rs->Close();
98 $authdb->Close();
99 // User does not exist externally.
100 return false;
103 } else {
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)."'");
118 if (!$rs) {
119 $authdb->Close();
120 debugging(get_string('auth_dbcantconnect','auth_db'));
121 return false;
124 if (!$rs->EOF) {
125 $rs->Close();
126 $authdb->Close();
127 return true;
128 } else {
129 $rs->Close();
130 $authdb->Close();
131 return false;
138 * Connect to external database.
140 * @return ADOConnection
142 function db_init() {
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);
155 return $authdb;
159 * Returns user attribute mappings between moodle and ldap.
161 * @return array
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
179 * @return array
181 function get_userinfo($username) {
182 global $CFG;
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();
191 $result = array();
192 // If at least one field is mapped from external db, get that mapped data.
193 if ($selectfields) {
194 $select = array();
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)) {
203 if (!$rs->EOF) {
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');
210 $rs->Close();
213 $authdb->Close();
214 return $result;
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) {
225 global $DB;
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;
234 return true;
235 } else {
236 return false;
238 } else {
239 // We should have never been called!
240 return false;
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) {
261 global $CFG, $DB;
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)) {
271 $suspendselect = "";
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;
280 $sql = "SELECT u.*
281 FROM {user} u
282 WHERE u.auth=:authtype AND u.deleted=0 AND u.mnethostid=:mnethostid $suspendselect AND u.username $notin_sql";
283 } else {
284 $sql = "SELECT u.*
285 FROM {user} u
286 WHERE u.auth=:authtype AND u.deleted=0 AND u.mnethostid=:mnethostid $suspendselect";
287 $params = array();
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) {
298 delete_user($user);
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.
314 $trace->finished();
315 return 0;
318 // Update existing accounts.
319 if ($do_updates) {
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
337 FROM {user} u
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);
345 } else {
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.
357 $suspendselect = "";
358 if ($this->config->removeuser == AUTH_REMOVEUSER_SUSPEND) {
359 $suspendselect = "AND u.suspended = 0";
361 $sql = "SELECT u.id, u.username
362 FROM {user} u
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);
373 unset($users);
376 $add_users = array_diff($userlist, $usernames);
377 unset($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) {
383 $username = $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);
393 continue;
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);
410 continue;
412 try {
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);
417 continue;
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);
427 unset($add_users);
429 $trace->finished();
430 return 0;
433 function user_exists($username) {
435 // Init result value.
436 $result = false;
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)."' ");
446 if (!$rs) {
447 print_error('auth_dbcantconnect','auth_db');
448 } else if (!$rs->EOF) {
449 // User exists externally.
450 $result = true;
453 $authdb->Close();
454 return $result;
458 function get_userlist() {
460 // Init result value.
461 $result = array();
463 $authdb = $this->db_init();
465 // Fetch userlist.
466 $rs = $authdb->Execute("SELECT {$this->config->fielduser} AS username
467 FROM {$this->config->table} ");
469 if (!$rs) {
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);
478 $authdb->Close();
479 return $result;
483 * Reads user information from DB and return it in an object.
485 * @param string $username username
486 * @return array
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;
494 return $user;
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
507 * @return stdClass
509 function update_user_record($username, $updatekeys=false) {
510 global $CFG, $DB;
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);
520 die;
523 // Ensure userid is not overwritten.
524 $userid = $user->id;
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];
539 } else {
540 $value = '';
543 if (!empty($this->config->{'field_updatelocal_' . $key})) {
544 if (isset($user->{$key}) and $user->{$key} != $value) { // Only update if it's changed.
545 $needsupdate = true;
546 $updateuser->$key = $value;
551 if ($needsupdate) {
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");
571 return false;
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");
581 return false;
584 $extusername = core_text::convert($olduser->username, 'utf-8', $this->config->extencoding);
586 $authdb = $this->db_init();
588 $update = array();
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)) {
597 continue;
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)."'");
609 $authdb->Close();
610 return true;
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
619 * @return void
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.
637 * @return bool
639 function is_internal() {
640 if (!isset($this->config->passtype)) {
641 return true;
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() {
654 return true;
658 * Returns true if this authentication plugin can change the user's
659 * password.
661 * @return bool
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
669 * be used.
671 * @return moodle_url
673 function change_password_url() {
674 if ($this->is_internal() || empty($this->config->changepasswordurl)) {
675 // Standard form.
676 return null;
677 } else {
678 // Use admin defined custom url.
679 return new moodle_url($this->config->changepasswordurl);
684 * Returns true if plugin allows resetting of internal password.
686 * @return bool
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
701 * @return void
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)) {
725 $config->name = '';
727 if (!isset($config->user)) {
728 $config->user = '';
730 if (!isset($config->pass)) {
731 $config->pass = '';
733 if (!isset($config->table)) {
734 $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 = '';
761 // Save settings.
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');
778 return true;
782 * Add slashes, we can not use placeholders or system functions.
784 * @param string $text
785 * @return string
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);
791 } else {
792 $text = str_replace("'", "''", $text);
794 return $text;
798 * Test if settings are ok, print info to output.
799 * @private
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');
810 return;
813 if (empty($this->config->fielduser)) {
814 echo $OUTPUT->notification('External user field not specified.', 'notifyproblem');
815 return;
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);
833 ob_end_flush();
835 echo $OUTPUT->notification('Cannot connect the database.', 'notifyproblem');
836 return;
839 $rs = $adodb->Execute("SELECT *
840 FROM {$this->config->table}
841 WHERE {$this->config->fielduser} <> 'random_unlikely_username'"); // Any unlikely name is ok here.
843 if (!$rs) {
844 echo $OUTPUT->notification('Can not read external table.', 'notifyproblem');
846 } else if ($rs->EOF) {
847 echo $OUTPUT->notification('External table is empty.', 'notifyproblem');
848 $rs->close();
850 } else {
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');
855 $rs->close();
858 $adodb->Close();
860 $this->config->debugauthdb = $olddebugauthdb;
861 $CFG->debug = $olddebug;
862 ini_set('display_errors', $olddisplay);
863 error_reporting($CFG->debug);
864 ob_end_flush();