4 * @author Martin Dougiamas
5 * @license http://www.gnu.org/copyleft/gpl.html GNU Public License
6 * @package moodle multiauth
8 * Authentication Plugin: External Database Authentication
10 * Checks against an external database.
12 * 2006-08-28 File created.
15 if (!defined('MOODLE_INTERNAL')) {
16 die('Direct access to this script is forbidden.'); /// It must be included from a Moodle page
19 require_once($CFG->libdir
.'/authlib.php');
22 * External database authentication plugin.
24 class auth_plugin_db
extends auth_plugin_base
{
29 function auth_plugin_db() {
30 $this->authtype
= 'db';
31 $this->config
= get_config('auth/db');
32 if (empty($this->config
->extencoding
)) {
33 $this->config
->extencoding
= 'utf-8';
38 * Returns true if the username and password work and false if they are
39 * wrong or don't exist.
41 * @param string $username The username (with system magic quotes)
42 * @param string $password The password (with system magic quotes)
44 * @return bool Authentication success or failure.
46 function user_login($username, $password) {
50 $textlib = textlib_get_instance();
51 $extusername = $textlib->convert(stripslashes($username), 'utf-8', $this->config
->extencoding
);
52 $extpassword = $textlib->convert(stripslashes($password), 'utf-8', $this->config
->extencoding
);
54 $authdb = $this->db_init();
56 if ($this->config
->passtype
=== 'internal') {
57 // lookup username externally, but resolve
58 // password locally -- to support backend that
59 // don't track passwords
60 $rs = $authdb->Execute("SELECT * FROM {$this->config->table}
61 WHERE {$this->config->fielduser} = '".$this->ext_addslashes($extusername)."' ");
65 print_error('auth_dbcantconnect','auth');
69 if ( $rs->RecordCount() ) {
70 // user exists exterally
71 // check username/password internally
72 if ($user = get_record('user', 'username', $username, 'mnethostid', $CFG->mnet_localhost_id
)) {
73 return validate_internal_user_password($user, $password);
76 // user does not exist externally
81 // normal case: use external db for passwords
83 if ($this->config
->passtype
=== 'md5') { // Re-format password accordingly
84 $extpassword = md5($extpassword);
85 } else if ($this->config
->passtype
=== 'sha1') {
86 $extpassword = sha1($extpassword);
89 $rs = $authdb->Execute("SELECT * FROM {$this->config->table}
90 WHERE {$this->config->fielduser} = '".$this->ext_addslashes($extusername)."'
91 AND {$this->config->fieldpass} = '".$this->ext_addslashes($extpassword)."' ");
95 print_error('auth_dbcantconnect','auth');
99 if ($rs->RecordCount()) {
109 // Connect to the external database (forcing new connection)
110 $authdb = &ADONewConnection($this->config
->type
);
111 if (!empty($this->config
->debugauthdb
)) {
112 $authdb->debug
= true;
113 ob_start();//start output buffer to allow later use of the page headers
115 $authdb->Connect($this->config
->host
, $this->config
->user
, $this->config
->pass
, $this->config
->name
, true);
116 $authdb->SetFetchMode(ADODB_FETCH_ASSOC
);
117 if (!empty($this->config
->setupsql
)) {
118 $authdb->Execute($this->config
->setupsql
);
124 * retuns user attribute mappings between moodle and ldap
128 function db_attributes() {
129 $fields = array("firstname", "lastname", "email", "phone1", "phone2",
130 "department", "address", "city", "country", "description",
131 "idnumber", "lang" );
132 $moodleattributes = array();
133 foreach ($fields as $field) {
134 if (!empty($this->config
->{"field_map_$field"})) {
135 $moodleattributes[$field] = $this->config
->{"field_map_$field"};
138 $moodleattributes['username'] = $this->config
->fielduser
;
139 return $moodleattributes;
143 * Reads any other information for a user from external database,
144 * then returns it in an array
146 * @param string $username (with system magic quotes)
148 * @return array without magic quotes
150 function get_userinfo($username) {
154 $textlib = textlib_get_instance();
155 $extusername = $textlib->convert(stripslashes($username), 'utf-8', $this->config
->extencoding
);
157 $authdb = $this->db_init();
159 //Array to map local fieldnames we want, to external fieldnames
160 $selectfields = $this->db_attributes();
163 //If at least one field is mapped from external db, get that mapped data:
166 foreach ($selectfields as $localname=>$externalname) {
167 $select .= ", $externalname AS $localname";
169 $select = 'SELECT ' . substr($select,1);
171 " FROM {$this->config->table}" .
172 " WHERE {$this->config->fielduser} = '".$this->ext_addslashes($extusername)."'";
173 if ($rs = $authdb->Execute($sql)) {
174 if ( $rs->RecordCount() == 1 ) {
175 $fields_obj = rs_fetch_record($rs);
176 foreach ($selectfields as $localname=>$externalname) {
177 $result[$localname] = $textlib->convert($fields_obj->{$localname}, $this->config
->extencoding
, 'utf-8');
190 * Change a user's password
192 * @param object $user User table object (with system magic quotes)
193 * @param string $newpassword Plaintext password (with system magic quotes)
195 * @return bool True on success
197 function user_update_password($user, $newpassword) {
200 if ($this->config
->passtype
=== 'internal') {
201 return update_internal_user_password($user, $newpassword);
203 // we should have never been called!
209 * syncronizes user fron external db to moodle user table
211 * Sync shouid be done by using idnumber attribute, not username.
212 * You need to pass firstsync parameter to function to fill in
213 * idnumbers if they dont exists in moodle user table.
215 * Syncing users removes (disables) users that dont exists anymore in external db.
216 * Creates new users and updates coursecreator status of users.
218 * @param bool $do_updates Optional: set to true to force an update of existing accounts
220 * This implementation is simpler but less scalable than the one found in the LDAP module.
223 function sync_users($do_updates=false) {
226 $pcfg = get_config('auth/db');
228 /// list external users
229 $userlist = $this->get_userlist();
230 $quoteduserlist = implode("', '", addslashes_recursive($userlist));
231 $quoteduserlist = "'$quoteduserlist'";
233 /// delete obsolete internal users
234 if (!empty($this->config
->removeuser
)) {
236 // find obsolete users
237 if (count($userlist)) {
238 $sql = "SELECT u.id, u.username, u.email
239 FROM {$CFG->prefix}user u
240 WHERE u.auth='db' AND u.deleted=0 AND u.username NOT IN ($quoteduserlist)";
242 $sql = "SELECT u.id, u.username, u.email
243 FROM {$CFG->prefix}user u
244 WHERE u.auth='db' AND u.deleted=0";
246 $remove_users = get_records_sql($sql);
248 if (!empty($remove_users)) {
249 print_string('auth_dbuserstoremove','auth', count($remove_users)); echo "\n";
252 foreach ($remove_users as $user) {
253 if ($this->config
->removeuser
== 2) {
254 //following is copy pasted from admin/user.php
255 //maybe this should moved to function in lib/datalib.php
256 $updateuser = new object();
257 $updateuser->id
= $user->id
;
258 $updateuser->deleted
= 1;
259 $updateuser->username
= addslashes("$user->email.".time()); // Remember it just in case
260 $updateuser->email
= ''; // Clear this field to free it up
261 $updateuser->idnumber
= ''; // Clear this field to free it up
262 $updateuser->timemodified
= time();
263 if (update_record('user', $updateuser)) {
264 delete_records('role_assignments', 'userid', $user->id
); // unassign all roles
265 //copy pasted part ends
266 echo "\t"; print_string('auth_dbdeleteuser', 'auth', array($user->username
, $user->id
)); echo "\n";
268 echo "\t"; print_string('auth_dbdeleteusererror', 'auth', $user->username
); echo "\n";
270 } else if ($this->config
->removeuser
== 1) {
271 $updateuser = new object();
272 $updateuser->id
= $user->id
;
273 $updateuser->auth
= 'nologin';
274 if (update_record('user', $updateuser)) {
275 echo "\t"; print_string('auth_dbsuspenduser', 'auth', array($user->username
, $user->id
)); echo "\n";
277 echo "\t"; print_string('auth_dbsuspendusererror', 'auth', $user->username
); echo "\n";
283 unset($remove_users); // free mem!
286 if (!count($userlist)) {
288 // nothing else to do
293 /// update existing accounts
296 // narrow down what fields we need to update
297 $all_keys = array_keys(get_object_vars($this->config
));
298 $updatekeys = array();
299 foreach ($all_keys as $key) {
300 if (preg_match('/^field_updatelocal_(.+)$/',$key, $match)) {
301 if ($this->config
->{$key} === 'onlogin') {
302 array_push($updatekeys, $match[1]); // the actual key name
306 // print_r($all_keys); print_r($updatekeys);
307 unset($all_keys); unset($key);
309 // only go ahead if we actually
310 // have fields to update locally
311 if (!empty($updatekeys)) {
312 $sql = 'SELECT u.id, u.username
313 FROM ' . $CFG->prefix
.'user u
314 WHERE u.auth=\'db\' AND u.deleted=\'0\' AND u.username IN (' . $quoteduserlist . ')';
315 if ($update_users = get_records_sql($sql)) {
316 print "User entries to update: ". count($update_users). "\n";
318 foreach ($update_users as $user) {
319 echo "\t"; print_string('auth_dbupdatinguser', 'auth', array($user->username
, $user->id
));
320 if (!$this->update_user_record(addslashes($user->username
), $updatekeys)) {
321 echo " - ".get_string('skipped');
325 unset($update_users); // free memory
332 /// create missing accounts
334 // NOTE: this is very memory intensive
335 // and generally inefficient
336 $sql = 'SELECT u.id, u.username
337 FROM ' . $CFG->prefix
.'user u
338 WHERE u.auth=\'db\' AND u.deleted=\'0\'';
340 $users = get_records_sql($sql);
342 // simplify down to usernames
343 $usernames = array();
344 foreach ($users as $user) {
345 array_push($usernames, $user->username
);
349 $add_users = array_diff($userlist, $usernames);
352 if (!empty($add_users)) {
353 print_string('auth_dbuserstoadd','auth',count($add_users)); echo "\n";
355 foreach($add_users as $user) {
357 $user = $this->get_userinfo_asobj($user);
360 $user->username
= $username;
361 $user->modified
= time();
362 $user->confirmed
= 1;
364 $user->mnethostid
= $CFG->mnet_localhost_id
;
365 if (empty($user->lang
)) {
366 $user->lang
= $CFG->lang
;
369 $user = addslashes_object($user);
370 // maybe the user has been deleted before
371 if ($old_user = get_record('user', 'username', $user->username
, 'deleted', 1, 'mnethostid', $user->mnethostid
)) {
372 $user->id
= $old_user->id
;
373 set_field('user', 'deleted', 0, 'username', $user->username
);
374 echo "\t"; print_string('auth_dbreviveuser', 'auth', array(stripslashes($user->username
), $user->id
)); echo "\n";
375 } elseif ($id = insert_record ('user',$user)) { // it is truly a new user
376 echo "\t"; print_string('auth_dbinsertuser','auth',array(stripslashes($user->username
), $id)); echo "\n";
377 // if relevant, tag for password generation
378 if ($this->config
->passtype
=== 'internal') {
379 set_user_preference('auth_forcepasswordchange', 1, $id);
380 set_user_preference('create_password', 1, $id);
383 echo "\t"; print_string('auth_dbinsertusererror', 'auth', $user->username
); echo "\n";
387 unset($add_users); // free mem
392 function user_exists($username) {
394 /// Init result value
397 $textlib = textlib_get_instance();
398 $extusername = $textlib->convert(stripslashes($username), 'utf-8', $this->config
->extencoding
);
400 $authdb = $this->db_init();
402 $rs = $authdb->Execute("SELECT * FROM {$this->config->table}
403 WHERE {$this->config->fielduser} = '".$this->ext_addslashes($extusername)."' ");
406 print_error('auth_dbcantconnect','auth');
407 } else if ( $rs->RecordCount() ) {
408 // user exists exterally
409 $result = $rs->RecordCount();
417 function get_userlist() {
419 /// Init result value
422 $authdb = $this->db_init();
425 $rs = $authdb->Execute("SELECT {$this->config->fielduser} AS username
426 FROM {$this->config->table} ");
429 print_error('auth_dbcantconnect','auth');
430 } else if ( $rs->RecordCount() ) {
431 while ($rec = rs_fetch_next_record($rs)) {
432 array_push($result, $rec->username
);
441 * reads userinformation 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 object();
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 (with system magic quotes)
465 function update_user_record($username, $updatekeys=false) {
468 //just in case check text case
469 $username = trim(moodle_strtolower($username));
471 // get the current user record
472 $user = get_record('user', 'username', $username, 'mnethostid', $CFG->mnet_localhost_id
);
473 if (empty($user)) { // trouble
474 error_log("Cannot update non-existent user: $username");
475 print_error('auth_dbusernotexist','auth',$username);
479 // Ensure userid is not overwritten
482 if ($newinfo = $this->get_userinfo($username)) {
483 $newinfo = truncate_userinfo($newinfo);
485 if (empty($updatekeys)) { // all keys? this does not support removing values
486 $updatekeys = array_keys($newinfo);
489 foreach ($updatekeys as $key) {
490 if (isset($newinfo[$key])) {
491 $value = $newinfo[$key];
496 if (!empty($this->config
->{'field_updatelocal_' . $key})) {
497 if ($user->{$key} != $value) { // only update if it's changed
498 set_field('user', $key, addslashes($value), 'id', $userid);
503 return get_record_select('user', "id = $userid AND deleted = 0");
507 * Called when the user record is updated.
508 * Modifies user in external database. It takes olduser (before changes) and newuser (after changes)
509 * conpares information saved modified information to external db.
511 * @param mixed $olduser Userobject before modifications (without system magic quotes)
512 * @param mixed $newuser Userobject new modified userobject (without system magic quotes)
513 * @return boolean result
516 function user_update($olduser, $newuser) {
517 if (isset($olduser->username
) and isset($newuser->username
) and $olduser->username
!= $newuser->username
) {
518 error_log("ERROR:User renaming not allowed in ext db");
522 if (isset($olduser->auth
) and $olduser->auth
!= 'db') {
523 return true; // just change auth and skip update
526 $curruser = $this->get_userinfo($olduser->username
);
527 if (empty($curruser)) {
528 error_log("ERROR:User $olduser->username found in ext db");
532 $textlib = textlib_get_instance();
533 $extusername = $textlib->convert($olduser->username
, 'utf-8', $this->config
->extencoding
);
535 $authdb = $this->db_init();
538 foreach($curruser as $key=>$value) {
539 if ($key == 'username') {
540 continue; // skip this
542 if (empty($this->config
->{"field_updateremote_$key"})) {
543 continue; // remote update not requested
545 if (!isset($newuser->$key)) {
548 $nuvalue = stripslashes($newuser->$key);
549 if ($nuvalue != $value) {
550 $update[] = $this->config
->{"field_map_$key"}."='".$this->ext_addslashes($textlib->convert($nuvalue, 'utf-8', $this->config
->extencoding
))."'";
553 if (!empty($update)) {
554 $authdb->Execute("UPDATE {$this->config->table}
555 SET ".implode(',', $update)."
556 WHERE {$this->config->fielduser}='".$this->ext_addslashes($extusername)."'");
563 * A chance to validate form data, and last chance to
564 * do stuff before it is inserted in config_plugin
566 function validate_form(&$form, &$err) {
567 if ($form->passtype
=== 'internal') {
568 $this->config
->changepasswordurl
= '';
569 set_config('changepasswordurl', '', 'auth/db');
574 * Returns true if this authentication plugin is 'internal'.
578 function is_internal() {
579 return ($this->config
->passtype
== 'internal');
583 * Returns true if this authentication plugin can change the user's
588 function can_change_password() {
589 return ($this->config
->passtype
== 'internal' or !empty($this->config
->changepasswordurl
));
593 * Returns the URL for changing the user's pw, or empty if the default can
598 function change_password_url() {
599 if ($this->config
->passtype
== 'internal') {
604 return $this->config
->changepasswordurl
;
609 * Returns true if plugin allows resetting of internal password.
613 function can_reset_password() {
614 return ($this->config
->passtype
== 'internal');
618 * Prints a form for configuring this authentication plugin.
620 * This function is called from admin/auth.php, and outputs a full page with
621 * a form for configuring this plugin.
623 * @param array $page An object containing all the data for this page.
625 function config_form($config, $err, $user_fields) {
626 include 'config.html';
630 * Processes and stores configuration data for this authentication plugin.
632 function process_config($config) {
633 // set to defaults if undefined
634 if (!isset($config->host
)) {
635 $config->host
= 'localhost';
637 if (!isset($config->type
)) {
638 $config->type
= 'mysql';
640 if (!isset($config->sybasequoting
)) {
641 $config->sybasequoting
= 0;
643 if (!isset($config->name
)) {
646 if (!isset($config->user
)) {
649 if (!isset($config->pass
)) {
652 if (!isset($config->table
)) {
655 if (!isset($config->fielduser
)) {
656 $config->fielduser
= '';
658 if (!isset($config->fieldpass
)) {
659 $config->fieldpass
= '';
661 if (!isset($config->passtype
)) {
662 $config->passtype
= 'plaintext';
664 if (!isset($config->extencoding
)) {
665 $config->extencoding
= 'utf-8';
667 if (!isset($config->setupsql
)) {
668 $config->setupsql
= '';
670 if (!isset($config->debugauthdb
)) {
671 $config->debugauthdb
= 0;
673 if (!isset($config->removeuser
)) {
674 $config->removeuser
= 0;
676 if (!isset($config->changepasswordurl
)) {
677 $config->changepasswordurl
= '';
680 $config = stripslashes_recursive($config);
682 set_config('host', $config->host
, 'auth/db');
683 set_config('type', $config->type
, 'auth/db');
684 set_config('sybasequoting', $config->sybasequoting
, 'auth/db');
685 set_config('name', $config->name
, 'auth/db');
686 set_config('user', $config->user
, 'auth/db');
687 set_config('pass', $config->pass
, 'auth/db');
688 set_config('table', $config->table
, 'auth/db');
689 set_config('fielduser', $config->fielduser
, 'auth/db');
690 set_config('fieldpass', $config->fieldpass
, 'auth/db');
691 set_config('passtype', $config->passtype
, 'auth/db');
692 set_config('extencoding', trim($config->extencoding
), 'auth/db');
693 set_config('setupsql', trim($config->setupsql
),'auth/db');
694 set_config('debugauthdb', $config->debugauthdb
, 'auth/db');
695 set_config('removeuser', $config->removeuser
, 'auth/db');
696 set_config('changepasswordurl', trim($config->changepasswordurl
), 'auth/db');
701 function ext_addslashes($text) {
702 // using custom made function for now
703 if (empty($this->config
->sybasequoting
)) {
704 $text = str_replace('\\', '\\\\', $text);
705 $text = str_replace(array('\'', '"', "\0"), array('\\\'', '\\"', '\\0'), $text);
707 $text = str_replace("'", "''", $text);