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