auth cas/db/ldap: MDL-18689 Fix typos in auth/{cas,db,ldap}/auth.php
[moodle.git] / auth / db / auth.php
1 <?php
3 /**
4  * @author Martin Dougiamas
5  * @license http://www.gnu.org/copyleft/gpl.html GNU Public License
6  * @package moodle multiauth
7  *
8  * Authentication Plugin: External Database Authentication
9  *
10  * Checks against an external database.
11  *
12  * 2006-08-28  File created.
13  */
15 if (!defined('MOODLE_INTERNAL')) {
16     die('Direct access to this script is forbidden.');    ///  It must be included from a Moodle page
17 }
19 require_once($CFG->libdir.'/authlib.php');
20 require_once($CFG->libdir.'/adodb/adodb.inc.php');
22 /**
23  * External database authentication plugin.
24  */
25 class auth_plugin_db extends auth_plugin_base {
27     /**
28      * Constructor.
29      */
30     function auth_plugin_db() {
31         $this->authtype = 'db';
32         $this->config = get_config('auth/db');
33         if (empty($this->config->extencoding)) {
34             $this->config->extencoding = 'utf-8';
35         }
36     }
38     /**
39      * Returns true if the username and password work and false if they are
40      * wrong or don't exist.
41      *
42      * @param string $username The username
43      * @param string $password The password
44      *
45      * @return bool Authentication success or failure.
46      */
47     function user_login($username, $password) {
48         global $CFG, $DB;
50         $textlib = textlib_get_instance();
51         $extusername = $textlib->convert($username, 'utf-8', $this->config->extencoding);
52         $extpassword = $textlib->convert($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_db');
65                 return false;
66             }
68             if ( !$rs->EOF ) {
69                 $rs->Close();
70                 $authdb->Close();
71                 // user exists exterally
72                 // check username/password internally
73                 if ($user = $DB->get_record('user', array('username'=>$username, 'mnethostid'=>$CFG->mnet_localhost_id))) {
74                     return validate_internal_user_password($user, $password);
75                 }
76             } else {
77                 $rs->Close();
78                 $authdb->Close();
79                 // user does not exist externally
80                 return false;
81             }
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);
90             }
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_db');
98                 return false;
99             }
101             if (!$rs->EOF) {
102                 $rs->Close();
103                 $authdb->Close();
104                 return true;
105             } else {
106                 $rs->Close();
107                 $authdb->Close();
108                 return false;
109             }
111         }
112     }
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
120         }
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);
125         }
127         return $authdb;
128     }
129     /**
130      * retuns user attribute mappings between moodle and ldap
131      *
132      * @return array
133      */
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"};
139             }
140         }
141         $moodleattributes['username'] = $this->config->fielduser;
142         return $moodleattributes;
143     }
145     /**
146      * Reads any other information for a user from external database,
147      * then returns it in an array
148      *
149      * @param string $username
150      *
151      * @return array without magic quotes
152      */
153     function get_userinfo($username) {
155         global $CFG;
157         $textlib = textlib_get_instance();
158         $extusername = $textlib->convert($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";
171             }
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->FetchObj();
179                     $fields_obj = (object)array_change_key_case((array)$fields_obj , CASE_LOWER);
180                     foreach ($selectfields as $localname=>$externalname) {
181                         $result[$localname] = $textlib->convert($fields_obj->{$localname}, $this->config->extencoding, 'utf-8');
182                      }
183                  }
184                  $rs->Close();
185             }
186         }
187         $authdb->Close();
188         return $result;
190     }
193     /**
194      * Change a user's password
195      *
196      * @param  object  $user        User table object
197      * @param  string  $newpassword Plaintext password
198      *
199      * @return bool                  True on success
200      */
201     function user_update_password($user, $newpassword) {
203         global $CFG;
204         if ($this->config->passtype === 'internal') {
205             return update_internal_user_password($user, $newpassword);
206         } else {
207             // we should have never been called!
208             return false;
209         }
210     }
212     /**
213      * syncronizes user fron external db to moodle user table
214      *
215      * Sync shouid be done by using idnumber attribute, not username.
216      * You need to pass firstsync parameter to function to fill in
217      * idnumbers if they dont exists in moodle user table.
218      *
219      * Syncing users removes (disables) users that dont exists anymore in external db.
220      * Creates new users and updates coursecreator status of users.
221      *
222      * @param bool $do_updates  Optional: set to true to force an update of existing accounts
223      *
224      * This implementation is simpler but less scalable than the one found in the LDAP module.
225      *
226      */
227     function sync_users($do_updates=false) {
229         global $CFG, $DB;
230         $pcfg = get_config('auth/db');
232 /// list external users
233         $userlist = $this->get_userlist();
234         $quoteduserlist = implode("', '", $userlist);
235         $quoteduserlist = "'$quoteduserlist'";
237 /// delete obsolete internal users
238         if (!empty($this->config->removeuser)) {
240             // find obsolete users
241             if (count($userlist)) {
242                 $sql = "SELECT u.id, u.username, u.email, u.auth
243                         FROM {user} u
244                         WHERE u.auth='db' AND u.deleted=0 AND u.username NOT IN ($quoteduserlist)";
245             } else {
246                 $sql = "SELECT u.id, u.username, u.email, u.auth
247                         FROM {user} u
248                         WHERE u.auth='db' AND u.deleted=0";
249             }
250             $remove_users = $DB->get_records_sql($sql);
252             if (!empty($remove_users)) {
253                 print_string('auth_dbuserstoremove','auth_db', count($remove_users)); echo "\n";
255                 foreach ($remove_users as $user) {
256                     if ($this->config->removeuser == AUTH_REMOVEUSER_FULLDELETE) {
257                         if (delete_user($user)) {
258                             echo "\t"; print_string('auth_dbdeleteuser', 'auth_db', array($user->username, $user->id)); echo "\n";
259                         } else {
260                             echo "\t"; print_string('auth_dbdeleteusererror', 'auth_db', $user->username); echo "\n";
261                         }
262                     } else if ($this->config->removeuser == AUTH_REMOVEUSER_SUSPEND) {
263                         $updateuser = new object();
264                         $updateuser->id   = $user->id;
265                         $updateuser->auth = 'nologin';
266                         if ($DB->update_record('user', $updateuser)) {
267                             echo "\t"; print_string('auth_dbsuspenduser', 'auth_db', array($user->username, $user->id)); echo "\n";
268                         } else {
269                             echo "\t"; print_string('auth_dbsuspendusererror', 'auth_db', $user->username); echo "\n";
270                         }
271                     }
272                 }
273             }
274             unset($remove_users); // free mem!
275         }
277         if (!count($userlist)) {
278             // exit right here
279             // nothing else to do
280             return true;
281         }
283         ///
284         /// update existing accounts
285         ///
286         if ($do_updates) {
287             // narrow down what fields we need to update
288             $all_keys = array_keys(get_object_vars($this->config));
289             $updatekeys = array();
290             foreach ($all_keys as $key) {
291                 if (preg_match('/^field_updatelocal_(.+)$/',$key, $match)) {
292                     if ($this->config->{$key} === 'onlogin') {
293                         array_push($updatekeys, $match[1]); // the actual key name
294                     }
295                 }
296             }
297             // print_r($all_keys); print_r($updatekeys);
298             unset($all_keys); unset($key);
300             // only go ahead if we actually
301             // have fields to update locally
302             if (!empty($updatekeys)) {
303                 $sql = 'SELECT u.id, u.username
304                         FROM {user} u
305                         WHERE u.auth=\'db\' AND u.deleted=\'0\' AND u.username IN (' . $quoteduserlist . ')';
306                 if ($update_users = $DB->get_records_sql($sql)) {
307                     print "User entries to update: ". count($update_users). "\n";
309                     foreach ($update_users as $user) {
310                         echo "\t"; print_string('auth_dbupdatinguser', 'auth_db', array($user->username, $user->id));
311                         if (!$this->update_user_record($user->username, $updatekeys)) {
312                             echo " - ".get_string('skipped');
313                         }
314                         echo "\n";
315                     }
316                     unset($update_users); // free memory
317                 }
318             }
319         }
322         ///
323         /// create missing accounts
324         ///
325         // NOTE: this is very memory intensive
326         // and generally inefficient
327         $sql = 'SELECT u.id, u.username
328                 FROM {user} u
329                 WHERE u.auth=\'db\' AND u.deleted=\'0\'';
331         $users = $DB->get_records_sql($sql);
333         // simplify down to usernames
334         $usernames = array();
335         if (!empty($users)) {
336             foreach ($users as $user) {
337                 array_push($usernames, $user->username);
338             }
339             unset($users);
340         }
342         $add_users = array_diff($userlist, $usernames);
343         unset($usernames);
345         if (!empty($add_users)) {
346             print_string('auth_dbuserstoadd','auth_db',count($add_users)); echo "\n";
347             $transaction = $DB->start_delegated_transaction();
348             foreach($add_users as $user) {
349                 $username = $user;
350                 $user = $this->get_userinfo_asobj($user);
352                 // prep a few params
353                 $user->username   = $username;
354                 $user->modified   = time();
355                 $user->confirmed  = 1;
356                 $user->auth       = 'db';
357                 $user->mnethostid = $CFG->mnet_localhost_id;
358                 if (empty($user->lang)) {
359                     $user->lang = $CFG->lang;
360                 }
362                 // maybe the user has been deleted before
363                 if ($old_user = $DB->get_record('user', array('username'=>$user->username, 'deleted'=>1, 'mnethostid'=>$user->mnethostid))) {
364                     $user->id = $old_user->id;
365                     $DB->set_field('user', 'deleted', 0, array('username'=>$user->username));
366                     echo "\t"; print_string('auth_dbreviveduser', 'auth_db', array($user->username, $user->id)); echo "\n";
367                     
368                 //TODO - username required to use PARAM_USERNAME before inserting into user table (MDL-16919)
369                 } elseif ($id = $DB->insert_record ('user',$user)) { // it is truly a new user
370                     echo "\t"; print_string('auth_dbinsertuser','auth_db',array($user->username, $id)); echo "\n";
371                     // if relevant, tag for password generation
372                     if ($this->config->passtype === 'internal') {
373                         set_user_preference('auth_forcepasswordchange', 1, $id);
374                         set_user_preference('create_password',          1, $id);
375                     }
376                 } else {
377                     echo "\t"; print_string('auth_dbinsertusererror', 'auth_db', $user->username); echo "\n";
378                 }
379             }
380             $transaction->allow_commit();
381             unset($add_users); // free mem
382         }
383         return true;
384     }
386     function user_exists($username) {
388     /// Init result value
389         $result = false;
391         $textlib = textlib_get_instance();
392         $extusername = $textlib->convert($username, 'utf-8', $this->config->extencoding);
394         $authdb = $this->db_init();
396         $rs = $authdb->Execute("SELECT * FROM {$this->config->table}
397                                      WHERE {$this->config->fielduser} = '".$this->ext_addslashes($extusername)."' ");
399         if (!$rs) {
400             print_error('auth_dbcantconnect','auth_db');
401         } else if ( !$rs->EOF ) {
402             // user exists exterally
403             $result = true;
404         }
406         $authdb->Close();
407         return $result;
408     }
411     function get_userlist() {
413     /// Init result value
414         $result = array();
416         $authdb = $this->db_init();
418         // fetch userlist
419         $rs = $authdb->Execute("SELECT {$this->config->fielduser} AS username
420                                 FROM   {$this->config->table} ");
422         if (!$rs) {
423             print_error('auth_dbcantconnect','auth_db');
424         } else if ( !$rs->EOF ) {
425             while ($rec = $rs->FetchRow()) {
426                 $rec = (object)array_change_key_case((array)$rec , CASE_LOWER);
427                 array_push($result, $rec->username);
428             }
429         }
431         $authdb->Close();
432         return $result;
433     }
435     /**
436      * reads userinformation from DB and return it in an object
437      *
438      * @param string $username username (with system magic quotes)
439      * @return array
440      */
441     function get_userinfo_asobj($username) {
442         $user_array = truncate_userinfo($this->get_userinfo($username));
443         $user = new object();
444         foreach($user_array as $key=>$value) {
445             $user->{$key} = $value;
446         }
447         return $user;
448     }
450     /**
451      * will update a local user record from an external source.
452      * is a lighter version of the one in moodlelib -- won't do
453      * expensive ops such as enrolment
454      *
455      * If you don't pass $updatekeys, there is a performance hit and
456      * values removed from DB won't be removed from moodle.
457      *
458      * @param string $username username
459      */
460     function update_user_record($username, $updatekeys=false) {
461         global $CFG, $DB;
463         //just in case check text case
464         $username = trim(moodle_strtolower($username));
466         // get the current user record
467         $user = $DB->get_record('user', array('username'=>$username, 'mnethostid'=>$CFG->mnet_localhost_id));
468         if (empty($user)) { // trouble
469             error_log("Cannot update non-existent user: $username");
470             print_error('auth_dbusernotexist','auth_db',$username);
471             die;
472         }
474         // Ensure userid is not overwritten
475         $userid = $user->id;
477         if ($newinfo = $this->get_userinfo($username)) {
478             $newinfo = truncate_userinfo($newinfo);
480             if (empty($updatekeys)) { // all keys? this does not support removing values
481                 $updatekeys = array_keys($newinfo);
482             }
484             foreach ($updatekeys as $key) {
485                 if (isset($newinfo[$key])) {
486                     $value = $newinfo[$key];
487                 } else {
488                     $value = '';
489                 }
491                 if (!empty($this->config->{'field_updatelocal_' . $key})) {
492                     if ($user->{$key} != $value) { // only update if it's changed
493                         $DB->set_field('user', $key, $value, array('id'=>$userid));
494                     }
495                 }
496             }
497         }
498         return $DB->get_record('user', array('id'=>$userid, 'deleted'=>0));
499     }
501     /**
502      * Called when the user record is updated.
503      * Modifies user in external database. It takes olduser (before changes) and newuser (after changes)
504      * conpares information saved modified information to external db.
505      *
506      * @param mixed $olduser     Userobject before modifications
507      * @param mixed $newuser     Userobject new modified userobject
508      * @return boolean result
509      *
510      */
511     function user_update($olduser, $newuser) {
512         if (isset($olduser->username) and isset($newuser->username) and $olduser->username != $newuser->username) {
513             error_log("ERROR:User renaming not allowed in ext db");
514             return false;
515         }
517         if (isset($olduser->auth) and $olduser->auth != 'db') {
518             return true; // just change auth and skip update
519         }
521         $curruser = $this->get_userinfo($olduser->username);
522         if (empty($curruser)) {
523             error_log("ERROR:User $olduser->username found in ext db");
524             return false;
525         }
527         $textlib = textlib_get_instance();
528         $extusername = $textlib->convert($olduser->username, 'utf-8', $this->config->extencoding);
530         $authdb = $this->db_init();
532         $update = array();
533         foreach($curruser as $key=>$value) {
534             if ($key == 'username') {
535                 continue; // skip this
536             }
537             if (empty($this->config->{"field_updateremote_$key"})) {
538                 continue; // remote update not requested
539             }
540             if (!isset($newuser->$key)) {
541                 continue;
542             }
543             $nuvalue = $newuser->$key;
544             if ($nuvalue != $value) {
545                 $update[] = $this->config->{"field_map_$key"}."='".$this->ext_addslashes($textlib->convert($nuvalue, 'utf-8', $this->config->extencoding))."'";
546             }
547         }
548         if (!empty($update)) {
549             $authdb->Execute("UPDATE {$this->config->table}
550                                 SET ".implode(',', $update)."
551                                 WHERE {$this->config->fielduser}='".$this->ext_addslashes($extusername)."'");
552         }
553         $authdb->Close();
554         return true;
555     }
557     /**
558      * A chance to validate form data, and last chance to
559      * do stuff before it is inserted in config_plugin
560      */
561      function validate_form(&$form, &$err) {
562         if ($form->passtype === 'internal') {
563             $this->config->changepasswordurl = '';
564             set_config('changepasswordurl', '', 'auth/db');
565         }
566     }
568     function prevent_local_passwords() {
569         if (!isset($this->config->passtype)) {
570             return false;
571         }
572         return ($this->config->passtype != 'internal');
573     }
575     /**
576      * Returns true if this authentication plugin is 'internal'.
577      *
578      * @return bool
579      */
580     function is_internal() {
581         if (!isset($this->config->passtype)) {
582             return true;
583         }
584         return ($this->config->passtype == 'internal');
585     }
587     /**
588      * Returns true if this authentication plugin can change the user's
589      * password.
590      *
591      * @return bool
592      */
593     function can_change_password() {
594         return ($this->config->passtype == 'internal' or !empty($this->config->changepasswordurl));
595     }
597     /**
598      * Returns the URL for changing the user's pw, or empty if the default can
599      * be used.
600      *
601      * @return string
602      */
603     function change_password_url() {
604         if ($this->config->passtype == 'internal') {
605             // standard form
606             return '';
607         } else {
608             // use custom url
609             return $this->config->changepasswordurl;
610         }
611     }
613     /**
614      * Returns true if plugin allows resetting of internal password.
615      *
616      * @return bool
617      */
618     function can_reset_password() {
619         return ($this->config->passtype == 'internal');
620     }
622     /**
623      * Prints a form for configuring this authentication plugin.
624      *
625      * This function is called from admin/auth.php, and outputs a full page with
626      * a form for configuring this plugin.
627      *
628      * @param array $page An object containing all the data for this page.
629      */
630     function config_form($config, $err, $user_fields) {
631         include 'config.html';
632     }
634     /**
635      * Processes and stores configuration data for this authentication plugin.
636      */
637     function process_config($config) {
638         // set to defaults if undefined
639         if (!isset($config->host)) {
640             $config->host = 'localhost';
641         }
642         if (!isset($config->type)) {
643             $config->type = 'mysql';
644         }
645         if (!isset($config->sybasequoting)) {
646             $config->sybasequoting = 0;
647         }
648         if (!isset($config->name)) {
649             $config->name = '';
650         }
651         if (!isset($config->user)) {
652             $config->user = '';
653         }
654         if (!isset($config->pass)) {
655             $config->pass = '';
656         }
657         if (!isset($config->table)) {
658             $config->table = '';
659         }
660         if (!isset($config->fielduser)) {
661             $config->fielduser = '';
662         }
663         if (!isset($config->fieldpass)) {
664             $config->fieldpass = '';
665         }
666         if (!isset($config->passtype)) {
667             $config->passtype = 'plaintext';
668         }
669         if (!isset($config->extencoding)) {
670             $config->extencoding = 'utf-8';
671         }
672         if (!isset($config->setupsql)) {
673             $config->setupsql = '';
674         }
675         if (!isset($config->debugauthdb)) {
676             $config->debugauthdb = 0;
677         }
678         if (!isset($config->removeuser)) {
679             $config->removeuser = AUTH_REMOVEUSER_KEEP;
680         }
681         if (!isset($config->changepasswordurl)) {
682             $config->changepasswordurl = '';
683         }
685         // save settings
686         set_config('host',          $config->host,          'auth/db');
687         set_config('type',          $config->type,          'auth/db');
688         set_config('sybasequoting', $config->sybasequoting, 'auth/db');
689         set_config('name',          $config->name,          'auth/db');
690         set_config('user',          $config->user,          'auth/db');
691         set_config('pass',          $config->pass,          'auth/db');
692         set_config('table',         $config->table,         'auth/db');
693         set_config('fielduser',     $config->fielduser,     'auth/db');
694         set_config('fieldpass',     $config->fieldpass,     'auth/db');
695         set_config('passtype',      $config->passtype,      'auth/db');
696         set_config('extencoding',   trim($config->extencoding), 'auth/db');
697         set_config('setupsql',      trim($config->setupsql),'auth/db');
698         set_config('debugauthdb',   $config->debugauthdb,   'auth/db');
699         set_config('removeuser',    $config->removeuser,    'auth/db');
700         set_config('changepasswordurl', trim($config->changepasswordurl), 'auth/db');
702         return true;
703     }
705     function ext_addslashes($text) {
706         // using custom made function for now
707         if (empty($this->config->sybasequoting)) {
708             $text = str_replace('\\', '\\\\', $text);
709             $text = str_replace(array('\'', '"', "\0"), array('\\\'', '\\"', '\\0'), $text);
710         } else {
711             $text = str_replace("'", "''", $text);
712         }
713         return $text;
714     }