MDL-45113 auth: add is_configured method and convert auth_db to use it
[moodle.git] / auth / db / auth.php
blobf03cbef44d64cd5ebc5cc4c7b17046c6b4ac13c6
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 if ($this->is_configured() === false) {
62 debugging(get_string('auth_notconfigured', 'auth', $this->authtype));
63 return false;
66 $extusername = core_text::convert($username, 'utf-8', $this->config->extencoding);
67 $extpassword = core_text::convert($password, 'utf-8', $this->config->extencoding);
69 if ($this->is_internal()) {
70 // Lookup username externally, but resolve
71 // password locally -- to support backend that
72 // don't track passwords.
74 if (isset($this->config->removeuser) and $this->config->removeuser == AUTH_REMOVEUSER_KEEP) {
75 // No need to connect to external database in this case because users are never removed and we verify password locally.
76 if ($user = $DB->get_record('user', array('username'=>$username, 'mnethostid'=>$CFG->mnet_localhost_id, 'auth'=>$this->authtype))) {
77 return validate_internal_user_password($user, $password);
78 } else {
79 return false;
83 $authdb = $this->db_init();
85 $rs = $authdb->Execute("SELECT *
86 FROM {$this->config->table}
87 WHERE {$this->config->fielduser} = '".$this->ext_addslashes($extusername)."'");
88 if (!$rs) {
89 $authdb->Close();
90 debugging(get_string('auth_dbcantconnect','auth_db'));
91 return false;
94 if (!$rs->EOF) {
95 $rs->Close();
96 $authdb->Close();
97 // User exists externally - check username/password internally.
98 if ($user = $DB->get_record('user', array('username'=>$username, 'mnethostid'=>$CFG->mnet_localhost_id, 'auth'=>$this->authtype))) {
99 return validate_internal_user_password($user, $password);
101 } else {
102 $rs->Close();
103 $authdb->Close();
104 // User does not exist externally.
105 return false;
108 } else {
109 // Normal case: use external db for both usernames and passwords.
111 $authdb = $this->db_init();
113 $rs = $authdb->Execute("SELECT {$this->config->fieldpass} AS userpass
114 FROM {$this->config->table}
115 WHERE {$this->config->fielduser} = '".$this->ext_addslashes($extusername)."'");
116 if (!$rs) {
117 $authdb->Close();
118 debugging(get_string('auth_dbcantconnect','auth_db'));
119 return false;
122 if ($rs->EOF) {
123 $authdb->Close();
124 return false;
127 $fields = array_change_key_case($rs->fields, CASE_LOWER);
128 $fromdb = $fields['userpass'];
129 $rs->Close();
130 $authdb->Close();
132 if ($this->config->passtype === 'plaintext') {
133 return ($fromdb == $extpassword);
134 } else if ($this->config->passtype === 'md5') {
135 return (strtolower($fromdb) == md5($extpassword));
136 } else if ($this->config->passtype === 'sha1') {
137 return (strtolower($fromdb) == sha1($extpassword));
138 } else if ($this->config->passtype === 'saltedcrypt') {
139 require_once($CFG->libdir.'/password_compat/lib/password.php');
140 return password_verify($extpassword, $fromdb);
141 } else {
142 return false;
149 * Connect to external database.
151 * @return ADOConnection
152 * @throws moodle_exception
154 function db_init() {
155 if ($this->is_configured() === false) {
156 throw new moodle_exception('auth_dbcantconnect', 'auth_db');
159 // Connect to the external database (forcing new connection).
160 $authdb = ADONewConnection($this->config->type);
161 if (!empty($this->config->debugauthdb)) {
162 $authdb->debug = true;
163 ob_start(); //Start output buffer to allow later use of the page headers.
165 $authdb->Connect($this->config->host, $this->config->user, $this->config->pass, $this->config->name, true);
166 $authdb->SetFetchMode(ADODB_FETCH_ASSOC);
167 if (!empty($this->config->setupsql)) {
168 $authdb->Execute($this->config->setupsql);
171 return $authdb;
175 * Returns user attribute mappings between moodle and ldap.
177 * @return array
179 function db_attributes() {
180 $moodleattributes = array();
181 // If we have custom fields then merge them with user fields.
182 $customfields = $this->get_custom_user_profile_fields();
183 if (!empty($customfields) && !empty($this->userfields)) {
184 $userfields = array_merge($this->userfields, $customfields);
185 } else {
186 $userfields = $this->userfields;
189 foreach ($userfields as $field) {
190 if (!empty($this->config->{"field_map_$field"})) {
191 $moodleattributes[$field] = $this->config->{"field_map_$field"};
194 $moodleattributes['username'] = $this->config->fielduser;
195 return $moodleattributes;
199 * Reads any other information for a user from external database,
200 * then returns it in an array.
202 * @param string $username
203 * @return array
205 function get_userinfo($username) {
206 global $CFG;
208 $extusername = core_text::convert($username, 'utf-8', $this->config->extencoding);
210 $authdb = $this->db_init();
212 // Array to map local fieldnames we want, to external fieldnames.
213 $selectfields = $this->db_attributes();
215 $result = array();
216 // If at least one field is mapped from external db, get that mapped data.
217 if ($selectfields) {
218 $select = array();
219 foreach ($selectfields as $localname=>$externalname) {
220 $select[] = "$externalname AS $localname";
222 $select = implode(', ', $select);
223 $sql = "SELECT $select
224 FROM {$this->config->table}
225 WHERE {$this->config->fielduser} = '".$this->ext_addslashes($extusername)."'";
226 if ($rs = $authdb->Execute($sql)) {
227 if (!$rs->EOF) {
228 $fields_obj = $rs->FetchObj();
229 $fields_obj = (object)array_change_key_case((array)$fields_obj , CASE_LOWER);
230 foreach ($selectfields as $localname=>$externalname) {
231 $result[$localname] = core_text::convert($fields_obj->{strtolower($localname)}, $this->config->extencoding, 'utf-8');
234 $rs->Close();
237 $authdb->Close();
238 return $result;
242 * Change a user's password.
244 * @param stdClass $user User table object
245 * @param string $newpassword Plaintext password
246 * @return bool True on success
248 function user_update_password($user, $newpassword) {
249 global $DB;
251 if ($this->is_internal()) {
252 $puser = $DB->get_record('user', array('id'=>$user->id), '*', MUST_EXIST);
253 // This will also update the stored hash to the latest algorithm
254 // if the existing hash is using an out-of-date algorithm (or the
255 // legacy md5 algorithm).
256 if (update_internal_user_password($puser, $newpassword)) {
257 $user->password = $puser->password;
258 return true;
259 } else {
260 return false;
262 } else {
263 // We should have never been called!
264 return false;
269 * Synchronizes user from external db to moodle user table.
271 * Sync should be done by using idnumber attribute, not username.
272 * You need to pass firstsync parameter to function to fill in
273 * idnumbers if they don't exists in moodle user table.
275 * Syncing users removes (disables) users that don't exists anymore in external db.
276 * Creates new users and updates coursecreator status of users.
278 * This implementation is simpler but less scalable than the one found in the LDAP module.
280 * @param progress_trace $trace
281 * @param bool $do_updates Optional: set to true to force an update of existing accounts
282 * @return int 0 means success, 1 means failure
284 function sync_users(progress_trace $trace, $do_updates=false) {
285 global $CFG, $DB;
287 require_once($CFG->dirroot . '/user/lib.php');
289 // List external users.
290 $userlist = $this->get_userlist();
292 // Delete obsolete internal users.
293 if (!empty($this->config->removeuser)) {
295 $suspendselect = "";
296 if ($this->config->removeuser == AUTH_REMOVEUSER_SUSPEND) {
297 $suspendselect = "AND u.suspended = 0";
300 // Find obsolete users.
301 if (count($userlist)) {
302 list($notin_sql, $params) = $DB->get_in_or_equal($userlist, SQL_PARAMS_NAMED, 'u', false);
303 $params['authtype'] = $this->authtype;
304 $sql = "SELECT u.*
305 FROM {user} u
306 WHERE u.auth=:authtype AND u.deleted=0 AND u.mnethostid=:mnethostid $suspendselect AND u.username $notin_sql";
307 } else {
308 $sql = "SELECT u.*
309 FROM {user} u
310 WHERE u.auth=:authtype AND u.deleted=0 AND u.mnethostid=:mnethostid $suspendselect";
311 $params = array();
312 $params['authtype'] = $this->authtype;
314 $params['mnethostid'] = $CFG->mnet_localhost_id;
315 $remove_users = $DB->get_records_sql($sql, $params);
317 if (!empty($remove_users)) {
318 $trace->output(get_string('auth_dbuserstoremove','auth_db', count($remove_users)));
320 foreach ($remove_users as $user) {
321 if ($this->config->removeuser == AUTH_REMOVEUSER_FULLDELETE) {
322 delete_user($user);
323 $trace->output(get_string('auth_dbdeleteuser', 'auth_db', array('name'=>$user->username, 'id'=>$user->id)), 1);
324 } else if ($this->config->removeuser == AUTH_REMOVEUSER_SUSPEND) {
325 $updateuser = new stdClass();
326 $updateuser->id = $user->id;
327 $updateuser->suspended = 1;
328 user_update_user($updateuser, false);
329 $trace->output(get_string('auth_dbsuspenduser', 'auth_db', array('name'=>$user->username, 'id'=>$user->id)), 1);
333 unset($remove_users);
336 if (!count($userlist)) {
337 // Exit right here, nothing else to do.
338 $trace->finished();
339 return 0;
342 // Update existing accounts.
343 if ($do_updates) {
344 // Narrow down what fields we need to update.
345 $all_keys = array_keys(get_object_vars($this->config));
346 $updatekeys = array();
347 foreach ($all_keys as $key) {
348 if (preg_match('/^field_updatelocal_(.+)$/',$key, $match)) {
349 if ($this->config->{$key} === 'onlogin') {
350 array_push($updatekeys, $match[1]); // The actual key name.
354 unset($all_keys); unset($key);
356 // Only go ahead if we actually have fields to update locally.
357 if (!empty($updatekeys)) {
358 list($in_sql, $params) = $DB->get_in_or_equal($userlist, SQL_PARAMS_NAMED, 'u', true);
359 $params['authtype'] = $this->authtype;
360 $sql = "SELECT u.id, u.username
361 FROM {user} u
362 WHERE u.auth=:authtype AND u.deleted=0 AND u.username {$in_sql}";
363 if ($update_users = $DB->get_records_sql($sql, $params)) {
364 $trace->output("User entries to update: ".count($update_users));
366 foreach ($update_users as $user) {
367 if ($this->update_user_record($user->username, $updatekeys)) {
368 $trace->output(get_string('auth_dbupdatinguser', 'auth_db', array('name'=>$user->username, 'id'=>$user->id)), 1);
369 } else {
370 $trace->output(get_string('auth_dbupdatinguser', 'auth_db', array('name'=>$user->username, 'id'=>$user->id))." - ".get_string('skipped'), 1);
373 unset($update_users);
379 // Create missing accounts.
380 // NOTE: this is very memory intensive and generally inefficient.
381 $suspendselect = "";
382 if ($this->config->removeuser == AUTH_REMOVEUSER_SUSPEND) {
383 $suspendselect = "AND u.suspended = 0";
385 $sql = "SELECT u.id, u.username
386 FROM {user} u
387 WHERE u.auth=:authtype AND u.deleted='0' AND mnethostid=:mnethostid $suspendselect";
389 $users = $DB->get_records_sql($sql, array('authtype'=>$this->authtype, 'mnethostid'=>$CFG->mnet_localhost_id));
391 // Simplify down to usernames.
392 $usernames = array();
393 if (!empty($users)) {
394 foreach ($users as $user) {
395 array_push($usernames, $user->username);
397 unset($users);
400 $add_users = array_diff($userlist, $usernames);
401 unset($usernames);
403 if (!empty($add_users)) {
404 $trace->output(get_string('auth_dbuserstoadd','auth_db',count($add_users)));
405 // Do not use transactions around this foreach, we want to skip problematic users, not revert everything.
406 foreach($add_users as $user) {
407 $username = $user;
408 if ($this->config->removeuser == AUTH_REMOVEUSER_SUSPEND) {
409 if ($olduser = $DB->get_record('user', array('username' => $username, 'deleted' => 0, 'suspended' => 1,
410 'mnethostid' => $CFG->mnet_localhost_id, 'auth' => $this->authtype))) {
411 $updateuser = new stdClass();
412 $updateuser->id = $olduser->id;
413 $updateuser->suspended = 0;
414 user_update_user($updateuser);
415 $trace->output(get_string('auth_dbreviveduser', 'auth_db', array('name' => $username,
416 'id' => $olduser->id)), 1);
417 continue;
421 // Do not try to undelete users here, instead select suspending if you ever expect users will reappear.
423 // Prep a few params.
424 $user = $this->get_userinfo_asobj($user);
425 $user->username = $username;
426 $user->confirmed = 1;
427 $user->auth = $this->authtype;
428 $user->mnethostid = $CFG->mnet_localhost_id;
429 if (empty($user->lang)) {
430 $user->lang = $CFG->lang;
432 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')) {
433 $trace->output(get_string('auth_dbinsertuserduplicate', 'auth_db', array('username'=>$user->username, 'auth'=>$collision->auth)), 1);
434 continue;
436 try {
437 $id = user_create_user($user, false); // It is truly a new user.
438 $trace->output(get_string('auth_dbinsertuser', 'auth_db', array('name'=>$user->username, 'id'=>$id)), 1);
439 } catch (moodle_exception $e) {
440 $trace->output(get_string('auth_dbinsertusererror', 'auth_db', $user->username), 1);
441 continue;
443 // If relevant, tag for password generation.
444 if ($this->is_internal()) {
445 set_user_preference('auth_forcepasswordchange', 1, $id);
446 set_user_preference('create_password', 1, $id);
448 // Make sure user context is present.
449 context_user::instance($id);
451 unset($add_users);
453 $trace->finished();
454 return 0;
457 function user_exists($username) {
459 // Init result value.
460 $result = false;
462 $extusername = core_text::convert($username, 'utf-8', $this->config->extencoding);
464 $authdb = $this->db_init();
466 $rs = $authdb->Execute("SELECT *
467 FROM {$this->config->table}
468 WHERE {$this->config->fielduser} = '".$this->ext_addslashes($extusername)."' ");
470 if (!$rs) {
471 print_error('auth_dbcantconnect','auth_db');
472 } else if (!$rs->EOF) {
473 // User exists externally.
474 $result = true;
477 $authdb->Close();
478 return $result;
482 function get_userlist() {
484 // Init result value.
485 $result = array();
487 $authdb = $this->db_init();
489 // Fetch userlist.
490 $rs = $authdb->Execute("SELECT {$this->config->fielduser} AS username
491 FROM {$this->config->table} ");
493 if (!$rs) {
494 print_error('auth_dbcantconnect','auth_db');
495 } else if (!$rs->EOF) {
496 while ($rec = $rs->FetchRow()) {
497 $rec = (object)array_change_key_case((array)$rec , CASE_LOWER);
498 array_push($result, $rec->username);
502 $authdb->Close();
503 return $result;
507 * Reads user information from DB and return it in an object.
509 * @param string $username username
510 * @return array
512 function get_userinfo_asobj($username) {
513 $user_array = truncate_userinfo($this->get_userinfo($username));
514 $user = new stdClass();
515 foreach($user_array as $key=>$value) {
516 $user->{$key} = $value;
518 return $user;
522 * will update a local user record from an external source.
523 * is a lighter version of the one in moodlelib -- won't do
524 * expensive ops such as enrolment.
526 * If you don't pass $updatekeys, there is a performance hit and
527 * values removed from DB won't be removed from moodle.
529 * @param string $username username
530 * @param bool $updatekeys
531 * @return stdClass
533 function update_user_record($username, $updatekeys=false) {
534 global $CFG, $DB;
536 //just in case check text case
537 $username = trim(core_text::strtolower($username));
539 // get the current user record
540 $user = $DB->get_record('user', array('username'=>$username, 'mnethostid'=>$CFG->mnet_localhost_id));
541 if (empty($user)) { // trouble
542 error_log("Cannot update non-existent user: $username");
543 print_error('auth_dbusernotexist','auth_db',$username);
544 die;
547 // Ensure userid is not overwritten.
548 $userid = $user->id;
549 $needsupdate = false;
551 $updateuser = new stdClass();
552 $updateuser->id = $userid;
553 if ($newinfo = $this->get_userinfo($username)) {
554 $newinfo = truncate_userinfo($newinfo);
556 if (empty($updatekeys)) { // All keys? This does not support removing values.
557 $updatekeys = array_keys($newinfo);
560 foreach ($updatekeys as $key) {
561 if (isset($newinfo[$key])) {
562 $value = $newinfo[$key];
563 } else {
564 $value = '';
567 if (!empty($this->config->{'field_updatelocal_' . $key})) {
568 if (isset($user->{$key}) and $user->{$key} != $value) { // Only update if it's changed.
569 $needsupdate = true;
570 $updateuser->$key = $value;
575 if ($needsupdate) {
576 require_once($CFG->dirroot . '/user/lib.php');
577 user_update_user($updateuser);
579 return $DB->get_record('user', array('id'=>$userid, 'deleted'=>0));
583 * Called when the user record is updated.
584 * Modifies user in external database. It takes olduser (before changes) and newuser (after changes)
585 * compares information saved modified information to external db.
587 * @param stdClass $olduser Userobject before modifications
588 * @param stdClass $newuser Userobject new modified userobject
589 * @return boolean result
592 function user_update($olduser, $newuser) {
593 if (isset($olduser->username) and isset($newuser->username) and $olduser->username != $newuser->username) {
594 error_log("ERROR:User renaming not allowed in ext db");
595 return false;
598 if (isset($olduser->auth) and $olduser->auth != $this->authtype) {
599 return true; // Just change auth and skip update.
602 $curruser = $this->get_userinfo($olduser->username);
603 if (empty($curruser)) {
604 error_log("ERROR:User $olduser->username found in ext db");
605 return false;
608 $extusername = core_text::convert($olduser->username, 'utf-8', $this->config->extencoding);
610 $authdb = $this->db_init();
612 $update = array();
613 foreach($curruser as $key=>$value) {
614 if ($key == 'username') {
615 continue; // Skip this.
617 if (empty($this->config->{"field_updateremote_$key"})) {
618 continue; // Remote update not requested.
620 if (!isset($newuser->$key)) {
621 continue;
623 $nuvalue = $newuser->$key;
624 // Support for textarea fields.
625 if (isset($nuvalue['text'])) {
626 $nuvalue = $nuvalue['text'];
628 if ($nuvalue != $value) {
629 $update[] = $this->config->{"field_map_$key"}."='".$this->ext_addslashes(core_text::convert($nuvalue, 'utf-8', $this->config->extencoding))."'";
632 if (!empty($update)) {
633 $authdb->Execute("UPDATE {$this->config->table}
634 SET ".implode(',', $update)."
635 WHERE {$this->config->fielduser}='".$this->ext_addslashes($extusername)."'");
637 $authdb->Close();
638 return true;
642 * A chance to validate form data, and last chance to
643 * do stuff before it is inserted in config_plugin
645 * @param stfdClass $form
646 * @param array $err errors
647 * @return void
649 function validate_form($form, &$err) {
650 if ($form->passtype === 'internal') {
651 $this->config->changepasswordurl = '';
652 set_config('changepasswordurl', '', 'auth/db');
656 function prevent_local_passwords() {
657 return !$this->is_internal();
661 * Returns true if this authentication plugin is "internal".
663 * Internal plugins use password hashes from Moodle user table for authentication.
665 * @return bool
667 function is_internal() {
668 if (!isset($this->config->passtype)) {
669 return true;
671 return ($this->config->passtype === 'internal');
675 * Returns false if this plugin is enabled but not configured.
677 * @return bool
679 public function is_configured() {
680 if (!empty($this->config->type)) {
681 return true;
683 return false;
687 * Indicates if moodle should automatically update internal user
688 * records with data from external sources using the information
689 * from auth_plugin_base::get_userinfo().
691 * @return bool true means automatically copy data from ext to user table
693 function is_synchronised_with_external() {
694 return true;
698 * Returns true if this authentication plugin can change the user's
699 * password.
701 * @return bool
703 function can_change_password() {
704 return ($this->is_internal() or !empty($this->config->changepasswordurl));
708 * Returns the URL for changing the user's pw, or empty if the default can
709 * be used.
711 * @return moodle_url
713 function change_password_url() {
714 if ($this->is_internal() || empty($this->config->changepasswordurl)) {
715 // Standard form.
716 return null;
717 } else {
718 // Use admin defined custom url.
719 return new moodle_url($this->config->changepasswordurl);
724 * Returns true if plugin allows resetting of internal password.
726 * @return bool
728 function can_reset_password() {
729 return $this->is_internal();
733 * Prints a form for configuring this authentication plugin.
735 * This function is called from admin/auth.php, and outputs a full page with
736 * a form for configuring this plugin.
738 * @param stdClass $config
739 * @param array $err errors
740 * @param array $user_fields
741 * @return void
743 function config_form($config, $err, $user_fields) {
744 include 'config.html';
748 * Processes and stores configuration data for this authentication plugin.
750 * @param srdClass $config
751 * @return bool always true or exception
753 function process_config($config) {
754 // set to defaults if undefined
755 if (!isset($config->host)) {
756 $config->host = 'localhost';
758 if (!isset($config->type)) {
759 $config->type = 'mysql';
761 if (!isset($config->sybasequoting)) {
762 $config->sybasequoting = 0;
764 if (!isset($config->name)) {
765 $config->name = '';
767 if (!isset($config->user)) {
768 $config->user = '';
770 if (!isset($config->pass)) {
771 $config->pass = '';
773 if (!isset($config->table)) {
774 $config->table = '';
776 if (!isset($config->fielduser)) {
777 $config->fielduser = '';
779 if (!isset($config->fieldpass)) {
780 $config->fieldpass = '';
782 if (!isset($config->passtype)) {
783 $config->passtype = 'plaintext';
785 if (!isset($config->extencoding)) {
786 $config->extencoding = 'utf-8';
788 if (!isset($config->setupsql)) {
789 $config->setupsql = '';
791 if (!isset($config->debugauthdb)) {
792 $config->debugauthdb = 0;
794 if (!isset($config->removeuser)) {
795 $config->removeuser = AUTH_REMOVEUSER_KEEP;
797 if (!isset($config->changepasswordurl)) {
798 $config->changepasswordurl = '';
801 // Save settings.
802 set_config('host', $config->host, 'auth/db');
803 set_config('type', $config->type, 'auth/db');
804 set_config('sybasequoting', $config->sybasequoting, 'auth/db');
805 set_config('name', $config->name, 'auth/db');
806 set_config('user', $config->user, 'auth/db');
807 set_config('pass', $config->pass, 'auth/db');
808 set_config('table', $config->table, 'auth/db');
809 set_config('fielduser', $config->fielduser, 'auth/db');
810 set_config('fieldpass', $config->fieldpass, 'auth/db');
811 set_config('passtype', $config->passtype, 'auth/db');
812 set_config('extencoding', trim($config->extencoding), 'auth/db');
813 set_config('setupsql', trim($config->setupsql),'auth/db');
814 set_config('debugauthdb', $config->debugauthdb, 'auth/db');
815 set_config('removeuser', $config->removeuser, 'auth/db');
816 set_config('changepasswordurl', trim($config->changepasswordurl), 'auth/db');
818 return true;
822 * Add slashes, we can not use placeholders or system functions.
824 * @param string $text
825 * @return string
827 function ext_addslashes($text) {
828 if (empty($this->config->sybasequoting)) {
829 $text = str_replace('\\', '\\\\', $text);
830 $text = str_replace(array('\'', '"', "\0"), array('\\\'', '\\"', '\\0'), $text);
831 } else {
832 $text = str_replace("'", "''", $text);
834 return $text;
838 * Test if settings are ok, print info to output.
839 * @private
841 public function test_settings() {
842 global $CFG, $OUTPUT;
844 // NOTE: this is not localised intentionally, admins are supposed to understand English at least a bit...
846 raise_memory_limit(MEMORY_HUGE);
848 if (empty($this->config->table)) {
849 echo $OUTPUT->notification('External table not specified.', 'notifyproblem');
850 return;
853 if (empty($this->config->fielduser)) {
854 echo $OUTPUT->notification('External user field not specified.', 'notifyproblem');
855 return;
858 $olddebug = $CFG->debug;
859 $olddisplay = ini_get('display_errors');
860 ini_set('display_errors', '1');
861 $CFG->debug = DEBUG_DEVELOPER;
862 $olddebugauthdb = $this->config->debugauthdb;
863 $this->config->debugauthdb = 1;
864 error_reporting($CFG->debug);
866 $adodb = $this->db_init();
868 if (!$adodb or !$adodb->IsConnected()) {
869 $this->config->debugauthdb = $olddebugauthdb;
870 $CFG->debug = $olddebug;
871 ini_set('display_errors', $olddisplay);
872 error_reporting($CFG->debug);
873 ob_end_flush();
875 echo $OUTPUT->notification('Cannot connect the database.', 'notifyproblem');
876 return;
879 $rs = $adodb->Execute("SELECT *
880 FROM {$this->config->table}
881 WHERE {$this->config->fielduser} <> 'random_unlikely_username'"); // Any unlikely name is ok here.
883 if (!$rs) {
884 echo $OUTPUT->notification('Can not read external table.', 'notifyproblem');
886 } else if ($rs->EOF) {
887 echo $OUTPUT->notification('External table is empty.', 'notifyproblem');
888 $rs->close();
890 } else {
891 $fields_obj = $rs->FetchObj();
892 $columns = array_keys((array)$fields_obj);
894 echo $OUTPUT->notification('External table contains following columns:<br />'.implode(', ', $columns), 'notifysuccess');
895 $rs->close();
898 $adodb->Close();
900 $this->config->debugauthdb = $olddebugauthdb;
901 $CFG->debug = $olddebug;
902 ini_set('display_errors', $olddisplay);
903 error_reporting($CFG->debug);
904 ob_end_flush();