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";
251 foreach ($remove_users as $user) {
252 if ($this->config
->removeuser
== 2) {
253 if (delete_user($user)) {
254 echo "\t"; print_string('auth_dbdeleteuser', 'auth', array($user->username
, $user->id
)); echo "\n";
256 echo "\t"; print_string('auth_dbdeleteusererror', 'auth', $user->username
); echo "\n";
258 } else if ($this->config
->removeuser
== 1) {
259 $updateuser = new object();
260 $updateuser->id
= $user->id
;
261 $updateuser->auth
= 'nologin';
262 if (update_record('user', $updateuser)) {
263 echo "\t"; print_string('auth_dbsuspenduser', 'auth', array($user->username
, $user->id
)); echo "\n";
265 echo "\t"; print_string('auth_dbsuspendusererror', 'auth', $user->username
); echo "\n";
270 unset($remove_users); // free mem!
273 if (!count($userlist)) {
275 // nothing else to do
280 /// update existing accounts
283 // narrow down what fields we need to update
284 $all_keys = array_keys(get_object_vars($this->config
));
285 $updatekeys = array();
286 foreach ($all_keys as $key) {
287 if (preg_match('/^field_updatelocal_(.+)$/',$key, $match)) {
288 if ($this->config
->{$key} === 'onlogin') {
289 array_push($updatekeys, $match[1]); // the actual key name
293 // print_r($all_keys); print_r($updatekeys);
294 unset($all_keys); unset($key);
296 // only go ahead if we actually
297 // have fields to update locally
298 if (!empty($updatekeys)) {
299 $sql = 'SELECT u.id, u.username
300 FROM ' . $CFG->prefix
.'user u
301 WHERE u.auth=\'db\' AND u.deleted=\'0\' AND u.username IN (' . $quoteduserlist . ')';
302 if ($update_users = get_records_sql($sql)) {
303 print "User entries to update: ". count($update_users). "\n";
305 foreach ($update_users as $user) {
306 echo "\t"; print_string('auth_dbupdatinguser', 'auth', array($user->username
, $user->id
));
307 if (!$this->update_user_record(addslashes($user->username
), $updatekeys)) {
308 echo " - ".get_string('skipped');
312 unset($update_users); // free memory
319 /// create missing accounts
321 // NOTE: this is very memory intensive
322 // and generally inefficient
323 $sql = 'SELECT u.id, u.username
324 FROM ' . $CFG->prefix
.'user u
325 WHERE u.auth=\'db\' AND u.deleted=\'0\'';
327 $users = get_records_sql($sql);
329 // simplify down to usernames
330 $usernames = array();
331 foreach ($users as $user) {
332 array_push($usernames, $user->username
);
336 $add_users = array_diff($userlist, $usernames);
339 if (!empty($add_users)) {
340 print_string('auth_dbuserstoadd','auth',count($add_users)); echo "\n";
342 foreach($add_users as $user) {
344 $user = $this->get_userinfo_asobj($user);
347 $user->username
= $username;
348 $user->modified
= time();
349 $user->confirmed
= 1;
351 $user->mnethostid
= $CFG->mnet_localhost_id
;
352 if (empty($user->lang
)) {
353 $user->lang
= $CFG->lang
;
356 $user = addslashes_object($user);
357 // maybe the user has been deleted before
358 if ($old_user = get_record('user', 'username', $user->username
, 'deleted', 1, 'mnethostid', $user->mnethostid
)) {
359 $user->id
= $old_user->id
;
360 set_field('user', 'deleted', 0, 'username', $user->username
);
361 echo "\t"; print_string('auth_dbreviveuser', 'auth', array(stripslashes($user->username
), $user->id
)); echo "\n";
362 } elseif ($id = insert_record ('user',$user)) { // it is truly a new user
363 echo "\t"; print_string('auth_dbinsertuser','auth',array(stripslashes($user->username
), $id)); echo "\n";
364 // if relevant, tag for password generation
365 if ($this->config
->passtype
=== 'internal') {
366 set_user_preference('auth_forcepasswordchange', 1, $id);
367 set_user_preference('create_password', 1, $id);
370 echo "\t"; print_string('auth_dbinsertusererror', 'auth', $user->username
); echo "\n";
374 unset($add_users); // free mem
379 function user_exists($username) {
381 /// Init result value
384 $textlib = textlib_get_instance();
385 $extusername = $textlib->convert(stripslashes($username), 'utf-8', $this->config
->extencoding
);
387 $authdb = $this->db_init();
389 $rs = $authdb->Execute("SELECT * FROM {$this->config->table}
390 WHERE {$this->config->fielduser} = '".$this->ext_addslashes($extusername)."' ");
393 print_error('auth_dbcantconnect','auth');
394 } else if ( $rs->RecordCount() ) {
395 // user exists exterally
396 $result = $rs->RecordCount();
404 function get_userlist() {
406 /// Init result value
409 $authdb = $this->db_init();
412 $rs = $authdb->Execute("SELECT {$this->config->fielduser} AS username
413 FROM {$this->config->table} ");
416 print_error('auth_dbcantconnect','auth');
417 } else if ( $rs->RecordCount() ) {
418 while ($rec = rs_fetch_next_record($rs)) {
419 array_push($result, $rec->username
);
428 * reads userinformation from DB and return it in an object
430 * @param string $username username (with system magic quotes)
433 function get_userinfo_asobj($username) {
434 $user_array = truncate_userinfo($this->get_userinfo($username));
435 $user = new object();
436 foreach($user_array as $key=>$value) {
437 $user->{$key} = $value;
443 * will update a local user record from an external source.
444 * is a lighter version of the one in moodlelib -- won't do
445 * expensive ops such as enrolment
447 * If you don't pass $updatekeys, there is a performance hit and
448 * values removed from DB won't be removed from moodle.
450 * @param string $username username (with system magic quotes)
452 function update_user_record($username, $updatekeys=false) {
455 //just in case check text case
456 $username = trim(moodle_strtolower($username));
458 // get the current user record
459 $user = get_record('user', 'username', $username, 'mnethostid', $CFG->mnet_localhost_id
);
460 if (empty($user)) { // trouble
461 error_log("Cannot update non-existent user: $username");
462 print_error('auth_dbusernotexist','auth',$username);
466 // Ensure userid is not overwritten
469 if ($newinfo = $this->get_userinfo($username)) {
470 $newinfo = truncate_userinfo($newinfo);
472 if (empty($updatekeys)) { // all keys? this does not support removing values
473 $updatekeys = array_keys($newinfo);
476 foreach ($updatekeys as $key) {
477 if (isset($newinfo[$key])) {
478 $value = $newinfo[$key];
483 if (!empty($this->config
->{'field_updatelocal_' . $key})) {
484 if ($user->{$key} != $value) { // only update if it's changed
485 set_field('user', $key, addslashes($value), 'id', $userid);
490 return get_record_select('user', "id = $userid AND deleted = 0");
494 * Called when the user record is updated.
495 * Modifies user in external database. It takes olduser (before changes) and newuser (after changes)
496 * conpares information saved modified information to external db.
498 * @param mixed $olduser Userobject before modifications (without system magic quotes)
499 * @param mixed $newuser Userobject new modified userobject (without system magic quotes)
500 * @return boolean result
503 function user_update($olduser, $newuser) {
504 if (isset($olduser->username
) and isset($newuser->username
) and $olduser->username
!= $newuser->username
) {
505 error_log("ERROR:User renaming not allowed in ext db");
509 if (isset($olduser->auth
) and $olduser->auth
!= 'db') {
510 return true; // just change auth and skip update
513 $curruser = $this->get_userinfo($olduser->username
);
514 if (empty($curruser)) {
515 error_log("ERROR:User $olduser->username found in ext db");
519 $textlib = textlib_get_instance();
520 $extusername = $textlib->convert($olduser->username
, 'utf-8', $this->config
->extencoding
);
522 $authdb = $this->db_init();
525 foreach($curruser as $key=>$value) {
526 if ($key == 'username') {
527 continue; // skip this
529 if (empty($this->config
->{"field_updateremote_$key"})) {
530 continue; // remote update not requested
532 if (!isset($newuser->$key)) {
535 $nuvalue = stripslashes($newuser->$key);
536 if ($nuvalue != $value) {
537 $update[] = $this->config
->{"field_map_$key"}."='".$this->ext_addslashes($textlib->convert($nuvalue, 'utf-8', $this->config
->extencoding
))."'";
540 if (!empty($update)) {
541 $authdb->Execute("UPDATE {$this->config->table}
542 SET ".implode(',', $update)."
543 WHERE {$this->config->fielduser}='".$this->ext_addslashes($extusername)."'");
550 * A chance to validate form data, and last chance to
551 * do stuff before it is inserted in config_plugin
553 function validate_form(&$form, &$err) {
554 if ($form->passtype
=== 'internal') {
555 $this->config
->changepasswordurl
= '';
556 set_config('changepasswordurl', '', 'auth/db');
561 * Returns true if this authentication plugin is 'internal'.
565 function is_internal() {
566 return ($this->config
->passtype
== 'internal');
570 * Returns true if this authentication plugin can change the user's
575 function can_change_password() {
576 return ($this->config
->passtype
== 'internal' or !empty($this->config
->changepasswordurl
));
580 * Returns the URL for changing the user's pw, or empty if the default can
585 function change_password_url() {
586 if ($this->config
->passtype
== 'internal') {
591 return $this->config
->changepasswordurl
;
596 * Returns true if plugin allows resetting of internal password.
600 function can_reset_password() {
601 return ($this->config
->passtype
== 'internal');
605 * Prints a form for configuring this authentication plugin.
607 * This function is called from admin/auth.php, and outputs a full page with
608 * a form for configuring this plugin.
610 * @param array $page An object containing all the data for this page.
612 function config_form($config, $err, $user_fields) {
613 include 'config.html';
617 * Processes and stores configuration data for this authentication plugin.
619 function process_config($config) {
620 // set to defaults if undefined
621 if (!isset($config->host
)) {
622 $config->host
= 'localhost';
624 if (!isset($config->type
)) {
625 $config->type
= 'mysql';
627 if (!isset($config->sybasequoting
)) {
628 $config->sybasequoting
= 0;
630 if (!isset($config->name
)) {
633 if (!isset($config->user
)) {
636 if (!isset($config->pass
)) {
639 if (!isset($config->table
)) {
642 if (!isset($config->fielduser
)) {
643 $config->fielduser
= '';
645 if (!isset($config->fieldpass
)) {
646 $config->fieldpass
= '';
648 if (!isset($config->passtype
)) {
649 $config->passtype
= 'plaintext';
651 if (!isset($config->extencoding
)) {
652 $config->extencoding
= 'utf-8';
654 if (!isset($config->setupsql
)) {
655 $config->setupsql
= '';
657 if (!isset($config->debugauthdb
)) {
658 $config->debugauthdb
= 0;
660 if (!isset($config->removeuser
)) {
661 $config->removeuser
= 0;
663 if (!isset($config->changepasswordurl
)) {
664 $config->changepasswordurl
= '';
667 $config = stripslashes_recursive($config);
669 set_config('host', $config->host
, 'auth/db');
670 set_config('type', $config->type
, 'auth/db');
671 set_config('sybasequoting', $config->sybasequoting
, 'auth/db');
672 set_config('name', $config->name
, 'auth/db');
673 set_config('user', $config->user
, 'auth/db');
674 set_config('pass', $config->pass
, 'auth/db');
675 set_config('table', $config->table
, 'auth/db');
676 set_config('fielduser', $config->fielduser
, 'auth/db');
677 set_config('fieldpass', $config->fieldpass
, 'auth/db');
678 set_config('passtype', $config->passtype
, 'auth/db');
679 set_config('extencoding', trim($config->extencoding
), 'auth/db');
680 set_config('setupsql', trim($config->setupsql
),'auth/db');
681 set_config('debugauthdb', $config->debugauthdb
, 'auth/db');
682 set_config('removeuser', $config->removeuser
, 'auth/db');
683 set_config('changepasswordurl', trim($config->changepasswordurl
), 'auth/db');
688 function ext_addslashes($text) {
689 // using custom made function for now
690 if (empty($this->config
->sybasequoting
)) {
691 $text = str_replace('\\', '\\\\', $text);
692 $text = str_replace(array('\'', '"', "\0"), array('\\\'', '\\"', '\\0'), $text);
694 $text = str_replace("'", "''", $text);