"MDL-12304, fix double text"
[moodle-linuxchix.git] / auth / db / auth.php
blob8c52dbb1bf696c25b0e7954df0cdd4a37a35faf8
1 <?php
3 /**
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');
21 /**
22 * External database authentication plugin.
24 class auth_plugin_db extends auth_plugin_base {
26 /**
27 * Constructor.
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';
37 /**
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) {
48 global $CFG;
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)."' ");
62 if (!$rs) {
63 $authdb->Close();
64 print_error('auth_dbcantconnect','auth');
65 return false;
68 if ( !$rs->EOF ) {
69 $rs->Close();
70 $authdb->Close();
71 // user exists exterally
72 // check username/password internally
73 if ($user = get_record('user', 'username', $username, 'mnethostid', $CFG->mnet_localhost_id)) {
74 return validate_internal_user_password($user, $password);
76 } else {
77 $rs->Close();
78 $authdb->Close();
79 // user does not exist externally
80 return false;
83 } else {
84 // normal case: use external db for passwords
86 if ($this->config->passtype === 'md5') { // Re-format password accordingly
87 $extpassword = md5($extpassword);
88 } else if ($this->config->passtype === 'sha1') {
89 $extpassword = sha1($extpassword);
92 $rs = $authdb->Execute("SELECT * FROM {$this->config->table}
93 WHERE {$this->config->fielduser} = '".$this->ext_addslashes($extusername)."'
94 AND {$this->config->fieldpass} = '".$this->ext_addslashes($extpassword)."' ");
95 if (!$rs) {
96 $authdb->Close();
97 print_error('auth_dbcantconnect','auth');
98 return false;
101 if (!$rs->EOF) {
102 $rs->Close();
103 $authdb->Close();
104 return true;
105 } else {
106 $rs->Close();
107 $authdb->Close();
108 return false;
114 function db_init() {
115 // Connect to the external database (forcing new connection)
116 $authdb = &ADONewConnection($this->config->type);
117 if (!empty($this->config->debugauthdb)) {
118 $authdb->debug = true;
119 ob_start();//start output buffer to allow later use of the page headers
121 $authdb->Connect($this->config->host, $this->config->user, $this->config->pass, $this->config->name, true);
122 $authdb->SetFetchMode(ADODB_FETCH_ASSOC);
123 if (!empty($this->config->setupsql)) {
124 $authdb->Execute($this->config->setupsql);
127 return $authdb;
130 * retuns user attribute mappings between moodle and ldap
132 * @return array
134 function db_attributes() {
135 $moodleattributes = array();
136 foreach ($this->userfields as $field) {
137 if (!empty($this->config->{"field_map_$field"})) {
138 $moodleattributes[$field] = $this->config->{"field_map_$field"};
141 $moodleattributes['username'] = $this->config->fielduser;
142 return $moodleattributes;
146 * Reads any other information for a user from external database,
147 * then returns it in an array
149 * @param string $username (with system magic quotes)
151 * @return array without magic quotes
153 function get_userinfo($username) {
155 global $CFG;
157 $textlib = textlib_get_instance();
158 $extusername = $textlib->convert(stripslashes($username), 'utf-8', $this->config->extencoding);
160 $authdb = $this->db_init();
162 //Array to map local fieldnames we want, to external fieldnames
163 $selectfields = $this->db_attributes();
165 $result = array();
166 //If at least one field is mapped from external db, get that mapped data:
167 if ($selectfields) {
168 $select = '';
169 foreach ($selectfields as $localname=>$externalname) {
170 $select .= ", $externalname AS $localname";
172 $select = 'SELECT ' . substr($select,1);
173 $sql = $select .
174 " FROM {$this->config->table}" .
175 " WHERE {$this->config->fielduser} = '".$this->ext_addslashes($extusername)."'";
176 if ($rs = $authdb->Execute($sql)) {
177 if ( !$rs->EOF ) {
178 $fields_obj = rs_fetch_record($rs);
179 foreach ($selectfields as $localname=>$externalname) {
180 $result[$localname] = $textlib->convert($fields_obj->{$localname}, $this->config->extencoding, 'utf-8');
183 rs_close($rs);
186 $authdb->Close();
187 return $result;
193 * Change a user's password
195 * @param object $user User table object (with system magic quotes)
196 * @param string $newpassword Plaintext password (with system magic quotes)
198 * @return bool True on success
200 function user_update_password($user, $newpassword) {
202 global $CFG;
203 if ($this->config->passtype === 'internal') {
204 return update_internal_user_password($user, $newpassword);
205 } else {
206 // we should have never been called!
207 return false;
212 * syncronizes user fron external db to moodle user table
214 * Sync shouid be done by using idnumber attribute, not username.
215 * You need to pass firstsync parameter to function to fill in
216 * idnumbers if they dont exists in moodle user table.
218 * Syncing users removes (disables) users that dont exists anymore in external db.
219 * Creates new users and updates coursecreator status of users.
221 * @param bool $do_updates Optional: set to true to force an update of existing accounts
223 * This implementation is simpler but less scalable than the one found in the LDAP module.
226 function sync_users($do_updates=false) {
228 global $CFG;
229 $pcfg = get_config('auth/db');
231 /// list external users
232 $userlist = $this->get_userlist();
233 $quoteduserlist = implode("', '", addslashes_recursive($userlist));
234 $quoteduserlist = "'$quoteduserlist'";
236 /// delete obsolete internal users
237 if (!empty($this->config->removeuser)) {
239 // find obsolete users
240 if (count($userlist)) {
241 $sql = "SELECT u.id, u.username, u.email, u.auth
242 FROM {$CFG->prefix}user u
243 WHERE u.auth='db' AND u.deleted=0 AND u.username NOT IN ($quoteduserlist)";
244 } else {
245 $sql = "SELECT u.id, u.username, u.email, u.auth
246 FROM {$CFG->prefix}user u
247 WHERE u.auth='db' AND u.deleted=0";
249 $remove_users = get_records_sql($sql);
251 if (!empty($remove_users)) {
252 print_string('auth_dbuserstoremove','auth', count($remove_users)); echo "\n";
254 foreach ($remove_users as $user) {
255 if ($this->config->removeuser == 2) {
256 if (delete_user($user)) {
257 echo "\t"; print_string('auth_dbdeleteuser', 'auth', array($user->username, $user->id)); echo "\n";
258 } else {
259 echo "\t"; print_string('auth_dbdeleteusererror', 'auth', $user->username); echo "\n";
261 } else if ($this->config->removeuser == 1) {
262 $updateuser = new object();
263 $updateuser->id = $user->id;
264 $updateuser->auth = 'nologin';
265 if (update_record('user', $updateuser)) {
266 echo "\t"; print_string('auth_dbsuspenduser', 'auth', array($user->username, $user->id)); echo "\n";
267 } else {
268 echo "\t"; print_string('auth_dbsuspendusererror', 'auth', $user->username); echo "\n";
273 unset($remove_users); // free mem!
276 if (!count($userlist)) {
277 // exit right here
278 // nothing else to do
279 return true;
283 /// update existing accounts
285 if ($do_updates) {
286 // narrow down what fields we need to update
287 $all_keys = array_keys(get_object_vars($this->config));
288 $updatekeys = array();
289 foreach ($all_keys as $key) {
290 if (preg_match('/^field_updatelocal_(.+)$/',$key, $match)) {
291 if ($this->config->{$key} === 'onlogin') {
292 array_push($updatekeys, $match[1]); // the actual key name
296 // print_r($all_keys); print_r($updatekeys);
297 unset($all_keys); unset($key);
299 // only go ahead if we actually
300 // have fields to update locally
301 if (!empty($updatekeys)) {
302 $sql = 'SELECT u.id, u.username
303 FROM ' . $CFG->prefix .'user u
304 WHERE u.auth=\'db\' AND u.deleted=\'0\' AND u.username IN (' . $quoteduserlist . ')';
305 if ($update_users = get_records_sql($sql)) {
306 print "User entries to update: ". count($update_users). "\n";
308 foreach ($update_users as $user) {
309 echo "\t"; print_string('auth_dbupdatinguser', 'auth', array($user->username, $user->id));
310 if (!$this->update_user_record(addslashes($user->username), $updatekeys)) {
311 echo " - ".get_string('skipped');
313 echo "\n";
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
327 FROM ' . $CFG->prefix .'user u
328 WHERE u.auth=\'db\' AND u.deleted=\'0\'';
330 $users = 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);
338 unset($users);
341 $add_users = array_diff($userlist, $usernames);
342 unset($usernames);
344 if (!empty($add_users)) {
345 print_string('auth_dbuserstoadd','auth',count($add_users)); echo "\n";
346 begin_sql();
347 foreach($add_users as $user) {
348 $username = $user;
349 $user = $this->get_userinfo_asobj($user);
351 // prep a few params
352 $user->username = $username;
353 $user->modified = time();
354 $user->confirmed = 1;
355 $user->auth = 'db';
356 $user->mnethostid = $CFG->mnet_localhost_id;
357 if (empty($user->lang)) {
358 $user->lang = $CFG->lang;
361 $user = addslashes_object($user);
362 // maybe the user has been deleted before
363 if ($old_user = get_record('user', 'username', $user->username, 'deleted', 1, 'mnethostid', $user->mnethostid)) {
364 $user->id = $old_user->id;
365 set_field('user', 'deleted', 0, 'username', $user->username);
366 echo "\t"; print_string('auth_dbreviveuser', 'auth', array(stripslashes($user->username), $user->id)); echo "\n";
367 } elseif ($id = insert_record ('user',$user)) { // it is truly a new user
368 echo "\t"; print_string('auth_dbinsertuser','auth',array(stripslashes($user->username), $id)); echo "\n";
369 // if relevant, tag for password generation
370 if ($this->config->passtype === 'internal') {
371 set_user_preference('auth_forcepasswordchange', 1, $id);
372 set_user_preference('create_password', 1, $id);
374 } else {
375 echo "\t"; print_string('auth_dbinsertusererror', 'auth', $user->username); echo "\n";
378 commit_sql();
379 unset($add_users); // free mem
381 return true;
384 function user_exists($username) {
386 /// Init result value
387 $result = false;
389 $textlib = textlib_get_instance();
390 $extusername = $textlib->convert(stripslashes($username), 'utf-8', $this->config->extencoding);
392 $authdb = $this->db_init();
394 $rs = $authdb->Execute("SELECT * FROM {$this->config->table}
395 WHERE {$this->config->fielduser} = '".$this->ext_addslashes($extusername)."' ");
397 if (!$rs) {
398 print_error('auth_dbcantconnect','auth');
399 } else if ( !$rs->EOF ) {
400 // user exists exterally
401 $result = true;
404 $authdb->Close();
405 return $result;
409 function get_userlist() {
411 /// Init result value
412 $result = array();
414 $authdb = $this->db_init();
416 // fetch userlist
417 $rs = $authdb->Execute("SELECT {$this->config->fielduser} AS username
418 FROM {$this->config->table} ");
420 if (!$rs) {
421 print_error('auth_dbcantconnect','auth');
422 } else if ( !$rs->EOF ) {
423 while ($rec = rs_fetch_next_record($rs)) {
424 array_push($result, $rec->username);
428 $authdb->Close();
429 return $result;
433 * reads userinformation from DB and return it in an object
435 * @param string $username username (with system magic quotes)
436 * @return array
438 function get_userinfo_asobj($username) {
439 $user_array = truncate_userinfo($this->get_userinfo($username));
440 $user = new object();
441 foreach($user_array as $key=>$value) {
442 $user->{$key} = $value;
444 return $user;
448 * will update a local user record from an external source.
449 * is a lighter version of the one in moodlelib -- won't do
450 * expensive ops such as enrolment
452 * If you don't pass $updatekeys, there is a performance hit and
453 * values removed from DB won't be removed from moodle.
455 * @param string $username username (with system magic quotes)
457 function update_user_record($username, $updatekeys=false) {
458 global $CFG;
460 //just in case check text case
461 $username = trim(moodle_strtolower($username));
463 // get the current user record
464 $user = get_record('user', 'username', $username, 'mnethostid', $CFG->mnet_localhost_id);
465 if (empty($user)) { // trouble
466 error_log("Cannot update non-existent user: $username");
467 print_error('auth_dbusernotexist','auth',$username);
468 die;
471 // Ensure userid is not overwritten
472 $userid = $user->id;
474 if ($newinfo = $this->get_userinfo($username)) {
475 $newinfo = truncate_userinfo($newinfo);
477 if (empty($updatekeys)) { // all keys? this does not support removing values
478 $updatekeys = array_keys($newinfo);
481 foreach ($updatekeys as $key) {
482 if (isset($newinfo[$key])) {
483 $value = $newinfo[$key];
484 } else {
485 $value = '';
488 if (!empty($this->config->{'field_updatelocal_' . $key})) {
489 if ($user->{$key} != $value) { // only update if it's changed
490 set_field('user', $key, addslashes($value), 'id', $userid);
495 return get_record_select('user', "id = $userid AND deleted = 0");
499 * Called when the user record is updated.
500 * Modifies user in external database. It takes olduser (before changes) and newuser (after changes)
501 * conpares information saved modified information to external db.
503 * @param mixed $olduser Userobject before modifications (without system magic quotes)
504 * @param mixed $newuser Userobject new modified userobject (without system magic quotes)
505 * @return boolean result
508 function user_update($olduser, $newuser) {
509 if (isset($olduser->username) and isset($newuser->username) and $olduser->username != $newuser->username) {
510 error_log("ERROR:User renaming not allowed in ext db");
511 return false;
514 if (isset($olduser->auth) and $olduser->auth != 'db') {
515 return true; // just change auth and skip update
518 $curruser = $this->get_userinfo($olduser->username);
519 if (empty($curruser)) {
520 error_log("ERROR:User $olduser->username found in ext db");
521 return false;
524 $textlib = textlib_get_instance();
525 $extusername = $textlib->convert($olduser->username, 'utf-8', $this->config->extencoding);
527 $authdb = $this->db_init();
529 $update = array();
530 foreach($curruser as $key=>$value) {
531 if ($key == 'username') {
532 continue; // skip this
534 if (empty($this->config->{"field_updateremote_$key"})) {
535 continue; // remote update not requested
537 if (!isset($newuser->$key)) {
538 continue;
540 $nuvalue = stripslashes($newuser->$key);
541 if ($nuvalue != $value) {
542 $update[] = $this->config->{"field_map_$key"}."='".$this->ext_addslashes($textlib->convert($nuvalue, 'utf-8', $this->config->extencoding))."'";
545 if (!empty($update)) {
546 $authdb->Execute("UPDATE {$this->config->table}
547 SET ".implode(',', $update)."
548 WHERE {$this->config->fielduser}='".$this->ext_addslashes($extusername)."'");
550 $authdb->Close();
551 return true;
555 * A chance to validate form data, and last chance to
556 * do stuff before it is inserted in config_plugin
558 function validate_form(&$form, &$err) {
559 if ($form->passtype === 'internal') {
560 $this->config->changepasswordurl = '';
561 set_config('changepasswordurl', '', 'auth/db');
566 * Returns true if this authentication plugin is 'internal'.
568 * @return bool
570 function is_internal() {
571 return ($this->config->passtype == 'internal');
575 * Returns true if this authentication plugin can change the user's
576 * password.
578 * @return bool
580 function can_change_password() {
581 return ($this->config->passtype == 'internal' or !empty($this->config->changepasswordurl));
585 * Returns the URL for changing the user's pw, or empty if the default can
586 * be used.
588 * @return string
590 function change_password_url() {
591 if ($this->config->passtype == 'internal') {
592 // standard form
593 return '';
594 } else {
595 // use custom url
596 return $this->config->changepasswordurl;
601 * Returns true if plugin allows resetting of internal password.
603 * @return bool
605 function can_reset_password() {
606 return ($this->config->passtype == 'internal');
610 * Prints a form for configuring this authentication plugin.
612 * This function is called from admin/auth.php, and outputs a full page with
613 * a form for configuring this plugin.
615 * @param array $page An object containing all the data for this page.
617 function config_form($config, $err, $user_fields) {
618 include 'config.html';
622 * Processes and stores configuration data for this authentication plugin.
624 function process_config($config) {
625 // set to defaults if undefined
626 if (!isset($config->host)) {
627 $config->host = 'localhost';
629 if (!isset($config->type)) {
630 $config->type = 'mysql';
632 if (!isset($config->sybasequoting)) {
633 $config->sybasequoting = 0;
635 if (!isset($config->name)) {
636 $config->name = '';
638 if (!isset($config->user)) {
639 $config->user = '';
641 if (!isset($config->pass)) {
642 $config->pass = '';
644 if (!isset($config->table)) {
645 $config->table = '';
647 if (!isset($config->fielduser)) {
648 $config->fielduser = '';
650 if (!isset($config->fieldpass)) {
651 $config->fieldpass = '';
653 if (!isset($config->passtype)) {
654 $config->passtype = 'plaintext';
656 if (!isset($config->extencoding)) {
657 $config->extencoding = 'utf-8';
659 if (!isset($config->setupsql)) {
660 $config->setupsql = '';
662 if (!isset($config->debugauthdb)) {
663 $config->debugauthdb = 0;
665 if (!isset($config->removeuser)) {
666 $config->removeuser = 0;
668 if (!isset($config->changepasswordurl)) {
669 $config->changepasswordurl = '';
672 $config = stripslashes_recursive($config);
673 // save settings
674 set_config('host', $config->host, 'auth/db');
675 set_config('type', $config->type, 'auth/db');
676 set_config('sybasequoting', $config->sybasequoting, 'auth/db');
677 set_config('name', $config->name, 'auth/db');
678 set_config('user', $config->user, 'auth/db');
679 set_config('pass', $config->pass, 'auth/db');
680 set_config('table', $config->table, 'auth/db');
681 set_config('fielduser', $config->fielduser, 'auth/db');
682 set_config('fieldpass', $config->fieldpass, 'auth/db');
683 set_config('passtype', $config->passtype, 'auth/db');
684 set_config('extencoding', trim($config->extencoding), 'auth/db');
685 set_config('setupsql', trim($config->setupsql),'auth/db');
686 set_config('debugauthdb', $config->debugauthdb, 'auth/db');
687 set_config('removeuser', $config->removeuser, 'auth/db');
688 set_config('changepasswordurl', trim($config->changepasswordurl), 'auth/db');
690 return true;
693 function ext_addslashes($text) {
694 // using custom made function for now
695 if (empty($this->config->sybasequoting)) {
696 $text = str_replace('\\', '\\\\', $text);
697 $text = str_replace(array('\'', '"', "\0"), array('\\\'', '\\"', '\\0'), $text);
698 } else {
699 $text = str_replace("'", "''", $text);
701 return $text;