fixed text field widths in new forms
[moodle.git] / auth / db / auth.php
CommitLineData
b9ddb2d5 1<?php
2
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 */
14
15// This page cannot be called directly
16if (!isset($CFG)) exit;
17
18/**
19 * External database authentication plugin.
20 */
21class auth_plugin_db {
22
23 /**
24 * The configuration details for the plugin.
25 */
26 var $config;
27
28 /**
29 * Constructor.
30 */
31 function auth_plugin_db() {
32 $this->config = get_config('auth/db');
33 }
34
35 /**
36 * Returns true if the username and password work and false if they are
37 * wrong or don't exist.
38 *
39 * @param string $username The username
40 * @param string $password The password
41 * @returns bool Authentication success or failure.
42 */
43 function user_login ($username, $password) {
44
45 global $CFG;
46
47 // This is a hack to workaround what seems to be a bug in ADOdb with accessing
48 // two databases of the same kind ... it seems to get confused when trying to access
49 // the first database again, after having accessed the second.
50 // The following hack will make the database explicit which keeps it happy
51 // This seems to broke postgesql so ..
52
53 $prefix = $CFG->prefix.''; // Remember it. The '' is to prevent PHP5 reference.. see bug 3223
54
55 if ($CFG->dbtype != 'postgres7') {
56 $CFG->prefix = $CFG->dbname.$CFG->prefix;
57 }
58
59 // Connect to the external database
60 $authdb = &ADONewConnection($this->config->type);
61 $authdb->PConnect($this->config->host, $this->config->user, $this->config->pass, $this->config->name);
62 $authdb->SetFetchMode(ADODB_FETCH_ASSOC);
63
64 if ($this->config->passtype === 'internal') {
65 // lookup username externally, but resolve
66 // password locally -- to support backend that
67 // don't track passwords
68 $rs = $authdb->Execute("SELECT * FROM {$this->config->table}
69 WHERE {$this->config->fielduser} = '$username' ");
70 $authdb->Close();
71
72 if (!$rs) {
a9ad3633 73 print_error('auth_dbcantconnect','auth');
b9ddb2d5 74 return false;
75 }
76
77 if ( $rs->RecordCount() ) {
78 // user exists exterally
79 // check username/password internally
b7b50143 80 if ($user = get_record('user', 'username', $username, 'mnethostid', $CFG->mnet_localhost_id)) {
b9ddb2d5 81 return validate_internal_user_password($user, $password);
82 }
83 } else {
84 // user does not exist externally
85 return false;
86 }
87
88 } else {
89 // normal case: use external db for passwords
90
91 if ($this->config->passtype === 'md5') { // Re-format password accordingly
92 $password = md5($password);
93 }
94
95 $rs = $authdb->Execute("SELECT * FROM {$this->config->table}
96 WHERE {$this->config->fielduser} = '$username'
97 AND {$this->config->fieldpass} = '$password' ");
98 $authdb->Close();
99
100 $CFG->prefix = $prefix;
101
102 if (!$rs) {
a9ad3633 103 print_error('auth_dbcantconnect','auth');
b9ddb2d5 104 return false;
105 }
106
107 if ( $rs->RecordCount() ) {
108 return true;
109 } else {
110 return false;
111 }
112
113 }
114 }
115
116
117 /**
118 * Reads any other information for a user from external database,
119 * then returns it in an array
120 */
121 function get_userinfo($username) {
122
123 global $CFG;
124
125 ADOLoadCode($this->config->type);
126 $authdb = &ADONewConnection();
127 $authdb->PConnect($this->config->host, $this->config->user, $this->config->pass, $this->config->name);
128 $authdb->SetFetchMode(ADODB_FETCH_ASSOC);
129
130 $fields = array("firstname", "lastname", "email", "phone1", "phone2",
131 "department", "address", "city", "country", "description",
132 "idnumber", "lang");
133
134 $result = array();
135
136 foreach ($fields as $field) {
137 if ($this->config->{'field_map_' . $field}) {
138 if ($rs = $authdb->Execute("SELECT " . $this->config->{'field_map_' . $field} . " FROM {$this->config->table}
139 WHERE {$this->config->fielduser} = '$username'")) {
140 if ( $rs->RecordCount() == 1 ) {
141 if (!empty($CFG->unicodedb)) {
142 $result["$field"] = addslashes(stripslashes($rs->fields[0]));
143 } else {
144 $result["$field"] = addslashes(stripslashes(utf8_decode($rs->fields[0])));
145 }
146 }
147 }
148 }
149 }
150 $authdb->Close();
151
152 return $result;
153 }
154
155
156 function user_update_password($username, $newpassword) {
157
b7b50143 158 global $CFG;
b9ddb2d5 159 if ($this->config->passtype === 'internal') {
b7b50143 160 return set_field('user', 'password', md5($newpassword), 'username', $username, 'mnethostid', $CFG->mnet_localhost_id);
b9ddb2d5 161 } else {
162 // we should have never been called!
163 return false;
164 }
165 }
166
167 /**
168 * syncronizes user fron external db to moodle user table
169 *
170 * Sync shouid be done by using idnumber attribute, not username.
171 * You need to pass firstsync parameter to function to fill in
172 * idnumbers if they dont exists in moodle user table.
173 *
174 * Syncing users removes (disables) users that dont exists anymore in external db.
175 * Creates new users and updates coursecreator status of users.
176 *
177 * @param bool $do_updates Optional: set to true to force an update of existing accounts
178 *
179 * This implementation is simpler but less scalable than the one found in the LDAP module.
180 *
181 */
182 function sync_users ($do_updates=0) {
183
184 global $CFG;
185 $pcfg = get_config('auth/db');
186
187 ///
188 /// list external users
189 ///
190 $userlist = $this->get_userlist();
191 $quoteduserlist = implode("', '", $userlist);
192 $quoteduserlist = "'$quoteduserlist'";
193
194 ///
195 /// delete obsolete internal users
196 ///
197
198 // find obsolete users
199 if (count($userlist)) {
200 $sql = 'SELECT u.id, u.username
201 FROM ' . $CFG->prefix .'user u
202 WHERE u.auth=\'db\' AND u.deleted=\'0\' AND u.username NOT IN (' . $quoteduserlist . ')';
203 } else {
204 $sql = 'SELECT u.id, u.username
205 FROM ' . $CFG->prefix .'user u
206 WHERE u.auth=\'db\' AND u.deleted=\'0\' ';
207 }
208 $remove_users = get_records_sql($sql);
209
210 if (!empty($remove_users)) {
a9ad3633 211 print_string('auth_dbuserstoremove','auth', count($remove_users));
212 echo "\n";
b9ddb2d5 213
214 begin_sql();
215 foreach ($remove_users as $user) {
216 //following is copy pasted from admin/user.php
217 //maybe this should moved to function in lib/datalib.php
b7b50143 218 $updateuser = new stdClass();
b9ddb2d5 219 $updateuser->id = $user->id;
220 $updateuser->deleted = "1";
221 $updateuser->timemodified = time();
222 if (update_record("user", $updateuser)) {
223 // unenrol_student($user->id); // From all courses
224 // remove_teacher($user->id); // From all courses
225 // remove_admin($user->id);
226 delete_records('role_assignments', 'userid', $user->id); // unassign all roles
227 notify(get_string("deletedactivity", "", fullname($user, true)) );
228 } else {
229 notify(get_string("deletednot", "", fullname($user, true)));
230 }
231 //copy pasted part ends
232 }
233 commit_sql();
234 }
235 unset($remove_users); // free mem!
236
237 if (!count($userlist)) {
238 // exit right here
239 // nothing else to do
240 return true;
241 }
242
243 ///
244 /// update existing accounts
245 ///
246 if ($do_updates) {
247 // narrow down what fields we need to update
248 $all_keys = array_keys(get_object_vars($this->config));
249 $updatekeys = array();
250 foreach ($all_keys as $key) {
251 if (preg_match('/^field_updatelocal_(.+)$/',$key, $match)) {
252 if ($this->config->{$key} === 'onlogin') {
253 array_push($updatekeys, $match[1]); // the actual key name
254 }
255 }
256 }
257 // print_r($all_keys); print_r($updatekeys);
258 unset($all_keys); unset($key);
259
260 // only go ahead if we actually
261 // have fields to update locally
262 if (!empty($updatekeys)) {
263 $sql = 'SELECT u.id, u.username
264 FROM ' . $CFG->prefix .'user u
265 WHERE u.auth=\'db\' AND u.deleted=\'0\' AND u.username IN (' . $quoteduserlist . ')';
266 $update_users = get_records_sql($sql);
267
268 foreach ($update_users as $user) {
269 $this->db_update_user_record($user->username, $updatekeys);
270 }
271 unset($update_users); // free memory
272 }
273 }
274
275
276 ///
277 /// create missing accounts
278 ///
279 // NOTE: this is very memory intensive
280 // and generally inefficient
281 $sql = 'SELECT u.id, u.username
282 FROM ' . $CFG->prefix .'user u
283 WHERE u.auth=\'db\' AND u.deleted=\'0\'';
284
285 $users = get_records_sql($sql);
286
287 // simplify down to usernames
288 $usernames = array();
289 foreach ($users as $user) {
290 array_push($usernames, $user->username);
291 }
292 unset($users);
293
294 $add_users = array_diff($userlist, $usernames);
295 unset($usernames);
296
297 if (!empty($add_users)) {
a9ad3633 298 print_string('auth_dbuserstoadd','auth',count($add_users));
299 echo "\n";
b9ddb2d5 300 begin_sql();
301 foreach($add_users as $user) {
302 $username = $user;
303 $user = $this->get_userinfo_asobj($user);
304
305 // prep a few params
b7b50143 306 $user->username = $username;
307 $user->modified = time();
308 $user->confirmed = 1;
309 $user->auth = 'db';
310 $user->mnethostid = $CFG->mnet_localhost_id;
b9ddb2d5 311
312 // insert it
313 $old_debug=$CFG->debug;
314 $CFG->debug=10;
315
316 // maybe the user has been deleted before
b7b50143 317 if ($old_user = get_record('user', 'username', $user->username, 'deleted', 1, 'mnethostid', $user->mnethostid)) {
b9ddb2d5 318 $user->id = $old_user->id;
319 set_field('user', 'deleted', 0, 'username', $user->username);
a9ad3633 320 print_string('auth_dbrevive','auth',array($user->username, $user->id));
321 echo "\n";
b9ddb2d5 322 } elseif ($id=insert_record ('user',$user)) { // it is truly a new user
a9ad3633 323 print_string('auth_dbinsertuser','auth',array($user->username, $id));
324 echo "\n";
b9ddb2d5 325 $user->id = $id;
326 // if relevant, tag for password generation
327 if ($this->config->passtype === 'internal') {
328 set_user_preference('auth_forcepasswordchange', 1, $id);
329 set_user_preference('create_password', 1, $id);
330 }
331 } else {
a9ad3633 332 print_string('auth_dbinsertusererror', 'auth', $user->username);
333 echo "\n";
b9ddb2d5 334 }
335 $CFG->debug=$old_debug;
336 }
337 commit_sql();
338 unset($add_users); // free mem
339 }
340 return true;
341 }
342
343 function user_exists ($username) {
344 $authdb = &ADONewConnection($this->config->type);
345 $authdb->PConnect($this->config->host, $this->config->user, $this->config->pass, $this->config->name);
346 $authdb->SetFetchMode(ADODB_FETCH_ASSOC);
347
348 $rs = $authdb->Execute("SELECT * FROM {$this->config->table}
349 WHERE {$this->config->fielduser} = '$username' ");
350 $authdb->Close();
351
352 if (!$rs) {
a9ad3633 353 print_error('auth_dbcantconnect','auth');
b9ddb2d5 354 return false;
355 }
356
357 if ( $rs->RecordCount() ) {
358 // user exists exterally
359 // check username/password internally
360 // ?? there is no $password variable, so why??
361 /*if ($user = get_record('user', 'username', $username)) {
362 return ($user->password == md5($password));
363 }*/
364 return $rs->RecordCount();
365 } else {
366 // user does not exist externally
367 return false;
368 }
369 }
370
371
372 function get_userlist() {
373 // Connect to the external database
374 $authdb = &ADONewConnection($this->config->type);
375 $authdb->PConnect($this->config->host,$this->config->user,$this->config->pass,$this->config->name);
376 $authdb->SetFetchMode(ADODB_FETCH_ASSOC);
377
378 // fetch userlist
379 $rs = $authdb->Execute("SELECT {$this->config->fielduser} AS username
380 FROM {$this->config->table} ");
381 $authdb->Close();
382
383 if (!$rs) {
a9ad3633 384 print_error('auth_dbcantconnect','auth');
b9ddb2d5 385 return false;
386 }
387
388 if ( $rs->RecordCount() ) {
389 $userlist = array();
390 while ($rec = $rs->FetchRow()) {
391 array_push($userlist, $rec['username']);
392 }
393 return $userlist;
394 } else {
395 return array();
396 }
397 }
398
399 /**
400 * reads userinformation from DB and return it in an object
401 *
402 * @param string $username username
403 * @return array
404 */
405 function get_userinfo_asobj($username) {
406 $user_array = truncate_userinfo($this->get_userinfo($username));
407 $user = new object;
408 foreach($user_array as $key=>$value) {
409 $user->{$key} = $value;
410 }
411 return $user;
412 }
413
414 /*
415 * will update a local user record from an external source.
416 * is a lighter version of the one in moodlelib -- won't do
417 * expensive ops such as enrolment
418 *
419 * If you don't pass $updatekeys, there is a performance hit and
420 * values removed from DB won't be removed from moodle.
421 */
422 function db_update_user_record($username, $updatekeys=false) {
b7b50143 423 global $CFG;
b9ddb2d5 424
425 $pcfg = get_config('auth/db');
426
427 //just in case check text case
428 $username = trim(moodle_strtolower($username));
429
430 // get the current user record
b7b50143 431 $user = get_record('user', 'username', $username, 'mnethostid', $CFG->mnet_localhost_id);
b9ddb2d5 432 if (empty($user)) { // trouble
433 error_log("Cannot update non-existent user: $username");
a9ad3633 434 print_error('auth_dbusernotexist','auth',$username);
b9ddb2d5 435 die;
436 }
437
b7b50143 438 // Ensure userid is not overwritten
439 $userid = $user->id;
440
b9ddb2d5 441 // TODO: this had a function_exists() - now we have a $this
442 if ($newinfo = $this->get_userinfo($username)) {
443 $newinfo = truncate_userinfo($newinfo);
444
445 if (empty($updatekeys)) { // all keys? this does not support removing values
446 $updatekeys = array_keys($newinfo);
447 }
448
449 foreach ($updatekeys as $key) {
450 unset($value);
451 if (isset($newinfo[$key])) {
452 $value = $newinfo[$key];
453 $value = addslashes(stripslashes($value)); // Just in case
454 } else {
455 $value = '';
456 }
457 if (!empty($this->config->{'field_updatelocal_' . $key})) {
458 if ($user->{$key} != $value) { // only update if it's changed
b7b50143 459 set_field('user', $key, $value, 'id', $userid);
b9ddb2d5 460 }
461 }
462 }
463 }
b7b50143 464 return get_record_select("user", "id = '$userid' AND deleted <> '1'");
b9ddb2d5 465 }
466
467 // A chance to validate form data, and last chance to
468 // do stuff before it is inserted in config_plugin
469 function validate_form(&$form, &$err) {
470 if ($form['passtype'] === 'internal') {
471 $this->config->changepasswordurl = '';
472 set_config('changepasswordurl', '', 'auth/db');
473 }
474 return true;
475 }
476
477 /**
478 * Returns true if this authentication plugin is 'internal'.
479 *
480 * @returns bool
481 */
482 function is_internal() {
483 return false;
484 }
485
486 /**
487 * Returns true if this authentication plugin can change the user's
488 * password.
489 *
490 * @returns bool
491 */
492 function can_change_password() {
493 return ($this->config->passtype === 'internal');
494 }
495
496 /**
497 * Returns the URL for changing the user's pw, or false if the default can
498 * be used.
499 *
500 * @returns bool
501 */
502 function change_password_url() {
503 return $this->config->changepasswordurl;
504 }
505
506 /**
507 * Prints a form for configuring this authentication plugin.
508 *
509 * This function is called from admin/auth.php, and outputs a full page with
510 * a form for configuring this plugin.
511 *
512 * @param array $page An object containing all the data for this page.
513 */
514 function config_form($config, $err) {
515 include "config.html";
516 }
517
518 /**
519 * Processes and stores configuration data for this authentication plugin.
520 */
521 function process_config($config) {
522 // set to defaults if undefined
523 if (!isset($config->host)) {
524 $config->host = "localhost";
525 }
526 if (!isset($config->type)) {
527 $config->type = "mysql";
528 }
529 if (!isset($config->name)) {
530 $config->name = "";
531 }
532 if (!isset($config->user)) {
533 $config->user = "";
534 }
535 if (!isset($config->pass)) {
536 $config->pass = "";
537 }
538 if (!isset($config->table)) {
539 $config->table = "";
540 }
541 if (!isset($config->fielduser)) {
542 $config->fielduser = "";
543 }
544 if (!isset($config->fieldpass)) {
545 $config->fieldpass = "";
546 }
547 if (!isset($config->passtype)) {
548 $config->passtype = "plaintext";
549 }
550 if (!isset($config->changepasswordurl)) {
551 $config->changepasswordurl = '';
552 }
553
554 // save settings
555 set_config('host', $config->host, 'auth/db');
556 set_config('type', $config->type, 'auth/db');
557 set_config('name', $config->name, 'auth/db');
558 set_config('user', $config->user, 'auth/db');
559 set_config('pass', $config->pass, 'auth/db');
560 set_config('table', $config->table, 'auth/db');
561 set_config('fielduser', $config->fielduser, 'auth/db');
562 set_config('fieldpass', $config->fieldpass, 'auth/db');
563 set_config('passtype', $config->passtype, 'auth/db');
564 set_config('changepasswordurl', $config->changepasswordurl, 'auth/db');
565
566 return true;
567 }
568
569}
570
571?>