User preferences were not getting set!
[moodle.git] / lib / moodlelib.php
CommitLineData
ef1e97c7 1<?php // $Id$
f9903ed0 2
9fa49e22 3///////////////////////////////////////////////////////////////////////////
4// //
5// NOTICE OF COPYRIGHT //
6// //
7// Moodle - Modular Object-Oriented Dynamic Learning Environment //
abc3b857 8// http://moodle.org //
9fa49e22 9// //
abc3b857 10// Copyright (C) 1999-2004 Martin Dougiamas http://dougiamas.com //
9fa49e22 11// //
12// This program is free software; you can redistribute it and/or modify //
13// it under the terms of the GNU General Public License as published by //
14// the Free Software Foundation; either version 2 of the License, or //
15// (at your option) any later version. //
16// //
17// This program is distributed in the hope that it will be useful, //
18// but WITHOUT ANY WARRANTY; without even the implied warranty of //
19// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the //
20// GNU General Public License for more details: //
21// //
22// http://www.gnu.org/copyleft/gpl.html //
23// //
24///////////////////////////////////////////////////////////////////////////
65ccdd8c 25
7cf1c7bd 26/**
89dcb99d 27 * moodlelib.php - Moodle main library
7cf1c7bd 28 *
29 * Main library file of miscellaneous general-purpose Moodle functions.
30 * Other main libraries:
8c3dba73 31 * - weblib.php - functions that produce web output
32 * - datalib.php - functions that access the database
7cf1c7bd 33 * @author Martin Dougiamas
34 * @version $Id$
89dcb99d 35 * @license http://www.gnu.org/copyleft/gpl.html GNU Public License
7cf1c7bd 36 * @package moodlecore
37 */
f374fb10 38/// CONSTANTS /////////////////////////////////////////////////////////////
39
6b94a807 40/**
41 * Used by some scripts to check they are being called by Moodle
42 */
43define('MOODLE_INTERNAL', true);
44
45
7cf1c7bd 46/**
47 * No groups used?
48 */
d8ba183c 49define('NOGROUPS', 0);
7cf1c7bd 50
51/**
52 * Groups used?
53 */
f374fb10 54define('SEPARATEGROUPS', 1);
7cf1c7bd 55
56/**
57 * Groups visible?
58 */
f374fb10 59define('VISIBLEGROUPS', 2);
60
7a5672c9 61/**
2f87145b 62 * Time constant - the number of seconds in a week
7a5672c9 63 */
361855e6 64define('WEEKSECS', 604800);
2f87145b 65
66/**
67 * Time constant - the number of seconds in a day
68 */
7a5672c9 69define('DAYSECS', 86400);
2f87145b 70
71/**
72 * Time constant - the number of seconds in an hour
73 */
7a5672c9 74define('HOURSECS', 3600);
2f87145b 75
76/**
77 * Time constant - the number of seconds in a minute
78 */
7a5672c9 79define('MINSECS', 60);
2f87145b 80
81/**
82 * Time constant - the number of minutes in a day
83 */
7a5672c9 84define('DAYMINS', 1440);
2f87145b 85
86/**
87 * Time constant - the number of minutes in an hour
88 */
7a5672c9 89define('HOURMINS', 60);
f9903ed0 90
e0d346ff 91/**
3af57507 92 * Parameter constants - if set then the parameter is cleaned of scripts etc
e0d346ff 93 */
3af57507 94define('PARAM_RAW', 0x00);
e0d346ff 95define('PARAM_CLEAN', 0x01);
e0d346ff 96define('PARAM_INT', 0x02);
3af57507 97define('PARAM_INTEGER', 0x02); // Alias for PARAM_INT
98define('PARAM_ALPHA', 0x04);
99define('PARAM_ACTION', 0x04); // Alias for PARAM_ALPHA
100define('PARAM_FORMAT', 0x04); // Alias for PARAM_ALPHA
101define('PARAM_NOTAGS', 0x08);
102define('PARAM_FILE', 0x10);
103define('PARAM_PATH', 0x20);
e0d346ff 104
105
9fa49e22 106/// PARAMETER HANDLING ////////////////////////////////////////////////////
6b174680 107
e0d346ff 108/**
361855e6 109 * Returns a particular value for the named variable, taken from
110 * POST or GET. If the parameter doesn't exist then an error is
e0d346ff 111 * thrown because we require this variable.
112 *
361855e6 113 * This function should be used to initialise all required values
114 * in a script that are based on parameters. Usually it will be
e0d346ff 115 * used like this:
116 * $id = required_param('id');
117 *
118 * @param string $varname the name of the parameter variable we want
119 * @param integer $options a bit field that specifies any cleaning needed
120 * @return mixed
121 */
122function required_param($varname, $options=PARAM_CLEAN) {
e0d346ff 123
124 if (isset($_POST[$varname])) { // POST has precedence
125 $param = $_POST[$varname];
126 } else if (isset($_GET[$varname])) {
127 $param = $_GET[$varname];
128 } else {
3af57507 129 error('A required parameter ('.$varname.') was missing');
e0d346ff 130 }
131
132 return clean_param($param, $options);
133}
134
135/**
361855e6 136 * Returns a particular value for the named variable, taken from
e0d346ff 137 * POST or GET, otherwise returning a given default.
138 *
361855e6 139 * This function should be used to initialise all optional values
140 * in a script that are based on parameters. Usually it will be
e0d346ff 141 * used like this:
142 * $name = optional_param('name', 'Fred');
143 *
144 * @param string $varname the name of the parameter variable we want
145 * @param mixed $default the default value to return if nothing is found
146 * @param integer $options a bit field that specifies any cleaning needed
147 * @return mixed
148 */
149function optional_param($varname, $default=NULL, $options=PARAM_CLEAN) {
e0d346ff 150
151 if (isset($_POST[$varname])) { // POST has precedence
152 $param = $_POST[$varname];
153 } else if (isset($_GET[$varname])) {
154 $param = $_GET[$varname];
155 } else {
156 return $default;
157 }
158
159 return clean_param($param, $options);
160}
161
162/**
361855e6 163 * Used by {@link optional_param()} and {@link required_param()} to
164 * clean the variables and/or cast to specific types, based on
e0d346ff 165 * an options field.
166 *
167 * @param mixed $param the variable we are cleaning
168 * @param integer $options a bit field that specifies the cleaning needed
169 * @return mixed
170 */
171function clean_param($param, $options) {
e0d346ff 172
3af57507 173 if (!$options) {
174 return $param; // Return raw value
175 }
176
7228f796 177 if ((string)$param == (string)(int)$param) { // It's just an integer
e0d346ff 178 return (int)$param;
179 }
180
181 if ($options & PARAM_CLEAN) {
182 $param = clean_text($param); // Sweep for scripts, etc
183 }
184
185 if ($options & PARAM_INT) {
186 $param = (int)$param; // Convert to integer
187 }
188
3af57507 189 if ($options & PARAM_ALPHA) { // Remove everything not a-z
190 $param = eregi_replace('[^a-z]', '', $param);
191 }
192
193 if ($options & PARAM_NOTAGS) { // Strip all tags completely
194 $param = strip_tags($param);
195 }
196
197 if ($options & PARAM_FILE) { // Strip all suspicious characters from filename
d52d5a8e 198 $param = clean_param($param, PARAM_PATH);
199 $pos = strrpos($param,'/');
200 if ($pos !== FALSE) {
201 $param = substr($param, $pos+1);
202 }
7e6b7f8d 203 if ($param === '.' or $param === ' ') {
204 $param = '';
361855e6 205 }
3af57507 206 }
207
208 if ($options & PARAM_PATH) { // Strip all suspicious characters from file path
d52d5a8e 209 $param = str_replace('\\\'', '\'', $param);
210 $param = str_replace('\\"', '"', $param);
7e6b7f8d 211 $param = str_replace('\\', '/', $param);
d52d5a8e 212 $param = ereg_replace('[[:cntrl:]]|[<>"`\|\']', '', $param);
7e6b7f8d 213 $param = ereg_replace('\.\.+', '', $param);
d52d5a8e 214 $param = ereg_replace('//+', '/', $param);
3af57507 215 }
216
e0d346ff 217 return $param;
218}
219
7cf1c7bd 220/**
7228f796 221 * For security purposes, this function will check that the currently
222 * given sesskey (passed as a parameter to the script or this function)
223 * matches that of the current user.
7cf1c7bd 224 *
7228f796 225 * @param string $sesskey optionally provided sesskey
226 * @return boolean
227 */
228function confirm_sesskey($sesskey=NULL) {
229 global $USER;
230
089e9eae 231 if (!empty($USER->ignoresesskey)) {
232 return true;
233 }
234
7228f796 235 if (empty($sesskey)) {
236 $sesskey = required_param('sesskey'); // Check script parameters
237 }
238
239 if (!isset($USER->sesskey)) {
240 return false;
241 }
242
243 return ($USER->sesskey === $sesskey);
244}
245
246
247/**
248 * Ensure that a variable is set
249 *
250 * If $var is undefined throw an error, otherwise return $var.
251 * This function will soon be made obsolete by {@link required_param()}
7cf1c7bd 252 *
7228f796 253 * @param mixed $var the variable which may be unset
254 * @param mixed $default the value to return if $var is unset
7cf1c7bd 255 */
9fa49e22 256function require_variable($var) {
9fa49e22 257 if (! isset($var)) {
b0ccd3fb 258 error('A required parameter was missing');
6b174680 259 }
260}
261
7cf1c7bd 262
263/**
264 * Ensure that a variable is set
265 *
266 * If $var is undefined set it (by reference), otherwise return $var.
7228f796 267 * This function will soon be made obsolete by {@link optional_param()}
7cf1c7bd 268 *
269 * @param mixed $var the variable which may be unset
270 * @param mixed $default the value to return if $var is unset
271 */
9fa49e22 272function optional_variable(&$var, $default=0) {
9fa49e22 273 if (! isset($var)) {
274 $var = $default;
6b174680 275 }
276}
277
7cf1c7bd 278/**
279 * Set a key in global configuration
280 *
89dcb99d 281 * Set a key/value pair in both this session's {@link $CFG} global variable
7cf1c7bd 282 * and in the 'config' database table for future sessions.
283 *
284 * @param string $name the key to set
285 * @param string $value the value to set
286 * @uses $CFG
287 * @return bool
288 */
9fa49e22 289function set_config($name, $value) {
290/// No need for get_config because they are usually always available in $CFG
70812e39 291
42282810 292 global $CFG;
293
7cf1c7bd 294
42282810 295 $CFG->$name = $value; // So it's defined for this invocation at least
dfc9ba9b 296
b0ccd3fb 297 if (get_field('config', 'name', 'name', $name)) {
298 return set_field('config', 'value', $value, 'name', $name);
d897cae4 299 } else {
9fa49e22 300 $config->name = $name;
301 $config->value = $value;
b0ccd3fb 302 return insert_record('config', $config);
39917a09 303 }
39917a09 304}
305
7cf1c7bd 306/**
307 * Refresh current $USER session global variable with all their current preferences.
308 * @uses $USER
309 */
70812e39 310function reload_user_preferences() {
70812e39 311
312 global $USER;
313
070e2616 314 if(empty($USER) || empty($USER->id)) {
315 return false;
316 }
317
d8ba183c 318 unset($USER->preference);
70812e39 319
320 if ($preferences = get_records('user_preferences', 'userid', $USER->id)) {
321 foreach ($preferences as $preference) {
322 $USER->preference[$preference->name] = $preference->value;
323 }
4586d60c 324 } else {
325 //return empty preference array to hold new values
326 $USER->preference = array();
c6d15803 327 }
70812e39 328}
329
7cf1c7bd 330/**
331 * Sets a preference for the current user
332 * Optionally, can set a preference for a different user object
333 * @uses $USER
334 * @todo Add a better description and include usage examples.
335 * @param string $name The key to set as preference for the specified user
336 * @param string $value The value to set forthe $name key in the specified user's record
c6d15803 337 * @param int $userid A moodle user ID
7cf1c7bd 338 * @todo Add inline links to $USER and user functions in above line.
339 * @return boolean
340 */
13af52a6 341function set_user_preference($name, $value, $otheruser=NULL) {
70812e39 342
343 global $USER;
344
13af52a6 345 if (empty($otheruser)){
346 if (!empty($USER) && !empty($USER->id)) {
070e2616 347 $userid = $USER->id;
13af52a6 348 } else {
070e2616 349 return false;
350 }
13af52a6 351 } else {
352 $userid = $otheruser;
d35757eb 353 }
354
70812e39 355 if (empty($name)) {
356 return false;
357 }
358
a3f1f815 359 if ($preference = get_record('user_preferences', 'userid', $userid, 'name', $name)) {
b0ccd3fb 360 if (set_field('user_preferences', 'value', $value, 'id', $preference->id)) {
13af52a6 361 if (empty($otheruser) and !empty($USER)) {
070e2616 362 $USER->preference[$name] = $value;
363 }
066af654 364 return true;
365 } else {
366 return false;
367 }
70812e39 368
369 } else {
a3f1f815 370 $preference->userid = $userid;
70812e39 371 $preference->name = $name;
372 $preference->value = (string)$value;
066af654 373 if (insert_record('user_preferences', $preference)) {
13af52a6 374 if (empty($otheruser) and !empty($USER)) {
070e2616 375 $USER->preference[$name] = $value;
376 }
70812e39 377 return true;
378 } else {
379 return false;
380 }
381 }
382}
383
6eb3e776 384/**
385 * Unsets a preference completely by deleting it from the database
386 * Optionally, can set a preference for a different user id
387 * @uses $USER
388 * @param string $name The key to unset as preference for the specified user
c6d15803 389 * @param int $userid A moodle user ID
6eb3e776 390 * @return boolean
391 */
392function unset_user_preference($name, $userid=NULL) {
393
394 global $USER;
395
361855e6 396 if (empty($userid)){
070e2616 397 if(!empty($USER) && !empty($USER->id)) {
398 $userid = $USER->id;
399 }
400 else {
401 return false;
402 }
6eb3e776 403 }
404
405 return delete_records('user_preferences', 'userid', $userid, 'name', $name);
406}
407
408
7cf1c7bd 409/**
410 * Sets a whole array of preferences for the current user
411 * @param array $prefarray An array of key/value pairs to be set
c6d15803 412 * @param int $userid A moodle user ID
7cf1c7bd 413 * @return boolean
414 */
a3f1f815 415function set_user_preferences($prefarray, $userid=NULL) {
416
417 global $USER;
70812e39 418
419 if (!is_array($prefarray) or empty($prefarray)) {
420 return false;
421 }
422
361855e6 423 if (empty($userid)){
108adee2 424 if (!empty($USER) && !empty($USER->id)) {
425 $userid = NULL; // Continue with the current user below
426 } else {
427 return false; // No-one to set!
070e2616 428 }
a3f1f815 429 }
430
70812e39 431 $return = true;
432 foreach ($prefarray as $name => $value) {
070e2616 433 // The order is important; if the test for return is done first, then
434 // if one function call fails all the remaining ones will be "optimized away"
a3f1f815 435 $return = set_user_preference($name, $value, $userid) and $return;
70812e39 436 }
437 return $return;
438}
439
7cf1c7bd 440/**
441 * If no arguments are supplied this function will return
361855e6 442 * all of the current user preferences as an array.
7cf1c7bd 443 * If a name is specified then this function
444 * attempts to return that particular preference value. If
445 * none is found, then the optional value $default is returned,
446 * otherwise NULL.
447 * @param string $name Name of the key to use in finding a preference value
448 * @param string $default Value to be returned if the $name key is not set in the user preferences
c6d15803 449 * @param int $userid A moodle user ID
7cf1c7bd 450 * @uses $USER
451 * @return string
452 */
a3f1f815 453function get_user_preferences($name=NULL, $default=NULL, $userid=NULL) {
70812e39 454
455 global $USER;
456
a3f1f815 457 if (empty($userid)) { // assume current user
458 if (empty($USER->preference)) {
459 return $default; // Default value (or NULL)
460 }
461 if (empty($name)) {
462 return $USER->preference; // Whole array
463 }
464 if (!isset($USER->preference[$name])) {
465 return $default; // Default value (or NULL)
466 }
467 return $USER->preference[$name]; // The single value
468
469 } else {
470 $preference = get_records_menu('user_preferences', 'userid', $userid, 'name', 'name,value');
471
472 if (empty($name)) {
473 return $preference;
474 }
475 if (!isset($preference[$name])) {
476 return $default; // Default value (or NULL)
477 }
478 return $preference[$name]; // The single value
70812e39 479 }
70812e39 480}
481
482
9fa49e22 483/// FUNCTIONS FOR HANDLING TIME ////////////////////////////////////////////
39917a09 484
7cf1c7bd 485/**
c6d15803 486 * Given date parts in user time produce a GMT timestamp.
7cf1c7bd 487 *
c6d15803 488 * @param int $year The year part to create timestamp of.
489 * @param int $month The month part to create timestamp of.
490 * @param int $day The day part to create timestamp of.
491 * @param int $hour The hour part to create timestamp of.
492 * @param int $minute The minute part to create timestamp of.
493 * @param int $second The second part to create timestamp of.
494 * @param int $timezone ?
495 * @return ?
7cf1c7bd 496 * @todo Finish documenting this function
497 */
9f1f6daf 498function make_timestamp($year, $month=1, $day=1, $hour=0, $minute=0, $second=0, $timezone=99, $applydst=true) {
39917a09 499
f30fe8d0 500 $timezone = get_user_timezone($timezone);
94e34118 501
502 if (abs($timezone) > 13) {
9f1f6daf 503 $time = mktime((int)$hour,(int)$minute,(int)$second,(int)$month,(int)$day,(int)$year, 0);
03c17ddf 504 } else {
86f092d2 505 $time = gmmktime((int)$hour,(int)$minute,(int)$second,(int)$month,(int)$day,(int)$year, 0);
9f1f6daf 506 $time = usertime($time, $timezone); // This is GMT
03c17ddf 507 }
9f1f6daf 508
509 if(!$applydst) {
510 return $time;
511 }
512
513 return $time;
514
515 /*
516 // WARNING: BUG: TODO: This is buggy, but it will do for testing purposes
517 if(($dstid = get_user_preferences('calendar_dstpreset')) !== NULL) {
518 $preset = get_record('dst_preset', 'id', $dstid);
519 if($time > $preset->last_change && $time < $preset->next_change) {
520 return $time;
521 }
522
523 // We need to find out what's going on...
524 $nowuserdate = usergetdate($time);
525
526 $changes = calendar_dst_changes_for_year($year, $preset);
527 if($time < $changes['activate'] || $time > $changes['deactivate']) {
528 // DST will be off at that time
529 if($preset->current_offset != 0) {
530 print_object('Uncompensated time was:');
531 print_object(usergetdate($time));
532 $time += $preset->apply_offset * 60;
533 print_object('Compensated time is:');
534 print_object(usergetdate($time));
535 }
536 }
537 else {
538 // DST will be on at that time
539 if($preset->current_offset == 0) {
540 print_object('Uncompensated time was:');
541 print_object(usergetdate($time));
542 $time -= $preset->apply_offset * 60;
543 print_object('Compensated time is:');
544 print_object(usergetdate($time));
545 }
546 }
547
548 return $time;
549 }
550 */
39917a09 551}
552
7cf1c7bd 553/**
554 * Given an amount of time in seconds, returns string
555 * formatted nicely as months, days, hours etc as needed
556 *
2f87145b 557 * @uses MINSECS
558 * @uses HOURSECS
559 * @uses DAYSECS
c6d15803 560 * @param int $totalsecs ?
561 * @param array $str ?
89dcb99d 562 * @return string
7cf1c7bd 563 * @todo Finish documenting this function
564 */
565 function format_time($totalsecs, $str=NULL) {
c7e3ac2a 566
6b174680 567 $totalsecs = abs($totalsecs);
c7e3ac2a 568
8dbed6be 569 if (!$str) { // Create the str structure the slow way
b0ccd3fb 570 $str->day = get_string('day');
571 $str->days = get_string('days');
572 $str->hour = get_string('hour');
573 $str->hours = get_string('hours');
574 $str->min = get_string('min');
575 $str->mins = get_string('mins');
576 $str->sec = get_string('sec');
577 $str->secs = get_string('secs');
8dbed6be 578 }
579
7a5672c9 580 $days = floor($totalsecs/DAYSECS);
581 $remainder = $totalsecs - ($days*DAYSECS);
582 $hours = floor($remainder/HOURSECS);
583 $remainder = $remainder - ($hours*HOURSECS);
584 $mins = floor($remainder/MINSECS);
585 $secs = $remainder - ($mins*MINSECS);
8dbed6be 586
587 $ss = ($secs == 1) ? $str->sec : $str->secs;
588 $sm = ($mins == 1) ? $str->min : $str->mins;
589 $sh = ($hours == 1) ? $str->hour : $str->hours;
590 $sd = ($days == 1) ? $str->day : $str->days;
591
b0ccd3fb 592 $odays = '';
593 $ohours = '';
594 $omins = '';
595 $osecs = '';
9c9f7d77 596
b0ccd3fb 597 if ($days) $odays = $days .' '. $sd;
598 if ($hours) $ohours = $hours .' '. $sh;
599 if ($mins) $omins = $mins .' '. $sm;
600 if ($secs) $osecs = $secs .' '. $ss;
6b174680 601
b0ccd3fb 602 if ($days) return $odays .' '. $ohours;
603 if ($hours) return $ohours .' '. $omins;
604 if ($mins) return $omins .' '. $osecs;
605 if ($secs) return $osecs;
606 return get_string('now');
6b174680 607}
f9903ed0 608
7cf1c7bd 609/**
610 * Returns a formatted string that represents a date in user time
611 * <b>WARNING: note that the format is for strftime(), not date().</b>
612 * Because of a bug in most Windows time libraries, we can't use
613 * the nicer %e, so we have to use %d which has leading zeroes.
614 * A lot of the fuss in the function is just getting rid of these leading
615 * zeroes as efficiently as possible.
361855e6 616 *
8c3dba73 617 * If parameter fixday = true (default), then take off leading
7cf1c7bd 618 * zero from %d, else mantain it.
619 *
2f87145b 620 * @uses HOURSECS
c6d15803 621 * @param int $date ?
622 * @param string $format ?
623 * @param int $timezone ?
624 * @param boolean $fixday If true (default) then the leading
625 * zero from %d is removed. If false then the leading zero is mantained.
626 * @return string
7cf1c7bd 627 * @todo Finish documenting this function
628 */
b0ccd3fb 629function userdate($date, $format='', $timezone=99, $fixday = true) {
7a302afc 630
b0ccd3fb 631 if ($format == '') {
632 $format = get_string('strftimedaydatetime');
5fa51a39 633 }
035cdbff 634
b0ccd3fb 635 $formatnoday = str_replace('%d', 'DD', $format);
61ae5d36 636 if ($fixday) {
637 $fixday = ($formatnoday != $format);
638 }
dcde9f02 639
f30fe8d0 640 $timezone = get_user_timezone($timezone);
90207a06 641
0431bd7c 642 if (abs($timezone) > 13) {
035cdbff 643 if ($fixday) {
644 $datestring = strftime($formatnoday, $date);
b0ccd3fb 645 $daystring = str_replace(' 0', '', strftime(" %d", $date));
646 $datestring = str_replace('DD', $daystring, $datestring);
035cdbff 647 } else {
648 $datestring = strftime($format, $date);
649 }
bea7a51e 650 } else {
7a5672c9 651 $date = $date + (int)($timezone * HOURSECS);
035cdbff 652 if ($fixday) {
70d4cf82 653 $datestring = gmstrftime($formatnoday, $date);
b0ccd3fb 654 $daystring = str_replace(' 0', '', gmstrftime(" %d", $date));
655 $datestring = str_replace('DD', $daystring, $datestring);
035cdbff 656 } else {
70d4cf82 657 $datestring = gmstrftime($format, $date);
035cdbff 658 }
873960de 659 }
bea7a51e 660
035cdbff 661 return $datestring;
873960de 662}
663
7cf1c7bd 664/**
361855e6 665 * Given a $date timestamp in GMT (seconds since epoch),
c6d15803 666 * returns an array that represents the date in user time
7cf1c7bd 667 *
2f87145b 668 * @uses HOURSECS
c6d15803 669 * @param int $date Timestamp in GMT
670 * @param int $timezone ?
671 * @return array An array that represents the date in user time
7cf1c7bd 672 * @todo Finish documenting this function
673 */
5fa51a39 674function usergetdate($date, $timezone=99) {
6b174680 675
f30fe8d0 676 $timezone = get_user_timezone($timezone);
a36166d3 677
0431bd7c 678 if (abs($timezone) > 13) {
873960de 679 return getdate($date);
680 }
d2d6171f 681 //There is no gmgetdate so I have to fake it...
7a5672c9 682 $date = $date + (int)($timezone * HOURSECS);
9f1f6daf 683
684 // This is independent of the server's TZ settings,
685 // unlike gmstrftime. It's also a bit faster this way.
686 list(
687 $getdate['seconds'],
688 $getdate['minutes'],
689 $getdate['hours'],
690 $getdate['mday'],
691 $getdate['mon'],
692 $getdate['year'],
693 $getdate['wday'],
694 $getdate['yday'],
695 $getdate['weekday'],
696 $getdate['month']
697 ) = explode(' ', gmdate('s i H d m Y w z l F', $date));
698
d2d6171f 699 return $getdate;
d552ead0 700}
701
7cf1c7bd 702/**
703 * Given a GMT timestamp (seconds since epoch), offsets it by
704 * the timezone. eg 3pm in India is 3pm GMT - 7 * 3600 seconds
705 *
2f87145b 706 * @uses HOURSECS
c6d15803 707 * @param int $date Timestamp in GMT
708 * @param int $timezone ?
709 * @return int
7cf1c7bd 710 * @todo Finish documenting this function
711 */
d552ead0 712function usertime($date, $timezone=99) {
a36166d3 713
f30fe8d0 714 $timezone = get_user_timezone($timezone);
0431bd7c 715 if (abs($timezone) > 13) {
d552ead0 716 return $date;
717 }
7a5672c9 718 return $date - (int)($timezone * HOURSECS);
d552ead0 719}
720
8c3dba73 721/**
722 * Given a time, return the GMT timestamp of the most recent midnight
723 * for the current user.
724 *
c6d15803 725 * @param int $date Timestamp in GMT
726 * @param int $timezone ?
727 * @return ?
728 * @todo Finish documenting this function. Is timezone an int or float?
8c3dba73 729 */
edf7fe8c 730function usergetmidnight($date, $timezone=99) {
edf7fe8c 731
f30fe8d0 732 $timezone = get_user_timezone($timezone);
edf7fe8c 733 $userdate = usergetdate($date, $timezone);
4606d9bb 734
0431bd7c 735 if (abs($timezone) > 13) {
b0ccd3fb 736 return mktime(0, 0, 0, $userdate['mon'], $userdate['mday'], $userdate['year']);
4606d9bb 737 }
738
b0ccd3fb 739 $timemidnight = gmmktime (0, 0, 0, $userdate['mon'], $userdate['mday'], $userdate['year']);
edf7fe8c 740 return usertime($timemidnight, $timezone); // Time of midnight of this user's day, in GMT
741
742}
743
7cf1c7bd 744/**
745 * Returns a string that prints the user's timezone
746 *
747 * @param float $timezone The user's timezone
748 * @return string
c6d15803 749 * @todo is $timezone an int or a float?
7cf1c7bd 750 */
d552ead0 751function usertimezone($timezone=99) {
d552ead0 752
f30fe8d0 753 $timezone = get_user_timezone($timezone);
754
0431bd7c 755 if (abs($timezone) > 13) {
b0ccd3fb 756 return 'server time';
d552ead0 757 }
758 if (abs($timezone) < 0.5) {
b0ccd3fb 759 return 'GMT';
d552ead0 760 }
761 if ($timezone > 0) {
b0ccd3fb 762 return 'GMT+'. $timezone;
d552ead0 763 } else {
b0ccd3fb 764 return 'GMT'. $timezone;
d552ead0 765 }
f9903ed0 766}
767
7cf1c7bd 768/**
769 * Returns a float which represents the user's timezone difference from GMT in hours
770 * Checks various settings and picks the most dominant of those which have a value
771 *
7cf1c7bd 772 * @uses $CFG
773 * @uses $USER
c6d15803 774 * @param int $tz The user's timezone
775 * @return int
776 * @todo is $tz an int or a float?
7cf1c7bd 777 */
f30fe8d0 778function get_user_timezone($tz = 99) {
f30fe8d0 779
780 // Variables declared explicitly global here so that if we add
781 // something later we won't forget to global it...
782 $timezones = array(
783 isset($GLOBALS['USER']->timezone) ? $GLOBALS['USER']->timezone : 99,
784 isset($GLOBALS['CFG']->timezone) ? $GLOBALS['CFG']->timezone : 99,
785 );
786 while($tz == 99 && $next = each($timezones)) {
787 $tz = (float)$next['value'];
788 }
789
790 return $tz;
791}
f9903ed0 792
9fa49e22 793/// USER AUTHENTICATION AND LOGIN ////////////////////////////////////////
f9903ed0 794
1a33f699 795// Makes sure that $USER->sesskey exists, if $USER itself exists. It sets a new sesskey
796// if one does not already exist, but does not overwrite existing sesskeys. Returns the
797// sesskey string if $USER exists, or boolean false if not.
798function set_user_sesskey() {
799 global $USER;
800
801 if(!isset($USER)) {
802 return false;
803 }
804
805 if (empty($USER->sesskey)) {
806 $USER->sesskey = random_string(10);
807 }
808
809 return $USER->sesskey;
810}
811
7cf1c7bd 812/**
813 * This function checks that the current user is logged in, and optionally
814 * whether they are "logged in" or allowed to be in a particular course.
815 * If not, then it redirects them to the site login or course enrolment.
816 * $autologinguest determines whether visitors should automatically be
89dcb99d 817 * logged in as guests provide {@link $CFG}->autologinguests is set to 1
7cf1c7bd 818 *
7cf1c7bd 819 * @uses $CFG
c6d15803 820 * @uses $SESSION
7cf1c7bd 821 * @uses $USER
822 * @uses $FULLME
c6d15803 823 * @uses SITEID
7cf1c7bd 824 * @uses $MoodleSession
c6d15803 825 * @param int $courseid The course in question
826 * @param boolean $autologinguest ?
7cf1c7bd 827 * @todo Finish documenting this function
828 */
8e8d0524 829function require_login($courseid=0, $autologinguest=true) {
f9903ed0 830
73047f2f 831 global $CFG, $SESSION, $USER, $FULLME, $MoodleSession;
d8ba183c 832
da5c172a 833 // First check that the user is logged in to the site.
c21c671d 834 if (! (isset($USER->loggedin) and $USER->confirmed and ($USER->site == $CFG->wwwroot)) ) { // They're not
f9903ed0 835 $SESSION->wantsurl = $FULLME;
b0ccd3fb 836 if (!empty($_SERVER['HTTP_REFERER'])) {
837 $SESSION->fromurl = $_SERVER['HTTP_REFERER'];
9f44d972 838 }
c21c671d 839 $USER = NULL;
8e8d0524 840 if ($autologinguest and $CFG->autologinguests and $courseid and get_field('course','guest','id',$courseid)) {
841 $loginguest = '?loginguest=true';
842 } else {
843 $loginguest = '';
a2ebe6a5 844 }
8a33e371 845 if (empty($CFG->loginhttps)) {
b0ccd3fb 846 redirect($CFG->wwwroot .'/login/index.php'. $loginguest);
8a33e371 847 } else {
b0ccd3fb 848 $wwwroot = str_replace('http','https', $CFG->wwwroot);
849 redirect($wwwroot .'/login/index.php'. $loginguest);
8a33e371 850 }
f9903ed0 851 die;
f9903ed0 852 }
808a3baa 853
d35757eb 854 // check whether the user should be changing password
027a1604 855 // reload_user_preferences(); // Why is this necessary? Seems wasteful. - MD
a3f1f815 856 if (!empty($USER->preference['auth_forcepasswordchange'])){
d35757eb 857 if (is_internal_auth() || $CFG->{'auth_'.$USER->auth.'_stdchangepassword'}){
b0ccd3fb 858 redirect($CFG->wwwroot .'/login/change_password.php');
d35757eb 859 } elseif($CFG->changepassword) {
860 redirect($CFG->changepassword);
861 } else {
361855e6 862 error('You cannot proceed without changing your password.
d35757eb 863 However there is no available page for changing it.
b0ccd3fb 864 Please contact your Moodle Administrator.');
d35757eb 865 }
866 }
867
808a3baa 868 // Check that the user account is properly set up
869 if (user_not_fully_set_up($USER)) {
b0ccd3fb 870 redirect($CFG->wwwroot .'/user/edit.php?id='. $USER->id .'&amp;course='. SITEID);
808a3baa 871 die;
872 }
d8ba183c 873
366dfa60 874 // Make sure current IP matches the one for this session (if required)
361855e6 875 if (!empty($CFG->tracksessionip)) {
366dfa60 876 if ($USER->sessionIP != md5(getremoteaddr())) {
877 error(get_string('sessionipnomatch', 'error'));
878 }
879 }
6d8f47d6 880
881 // Make sure the USER has a sesskey set up. Used for checking script parameters.
1a33f699 882 set_user_sesskey();
366dfa60 883
027a1604 884 // Check that the user has agreed to a site policy if there is one
885 if (!empty($CFG->sitepolicy)) {
886 if (!$USER->policyagreed) {
957b5198 887 $SESSION->wantsurl = $FULLME;
027a1604 888 redirect($CFG->wwwroot .'/user/policy.php');
889 die;
890 }
891 }
892
da5c172a 893 // Next, check if the user can be in a particular course
894 if ($courseid) {
361855e6 895 if ($courseid == SITEID) {
e3512050 896 return; // Anyone can be in the site course
897 }
9c9f7d77 898 if (!empty($USER->student[$courseid]) or !empty($USER->teacher[$courseid]) or !empty($USER->admin)) {
cb909d74 899 if (isset($USER->realuser)) { // Make sure the REAL person can also access this course
900 if (!isteacher($courseid, $USER->realuser)) {
901 print_header();
b0ccd3fb 902 notice(get_string('studentnotallowed', '', fullname($USER, true)), $CFG->wwwroot .'/');
cb909d74 903 }
3ce2f1e0 904 }
da5c172a 905 return; // user is a member of this course.
906 }
b0ccd3fb 907 if (! $course = get_record('course', 'id', $courseid)) {
908 error('That course doesn\'t exist');
da5c172a 909 }
1efa27fd 910 if (!$course->visible) {
911 print_header();
b0ccd3fb 912 notice(get_string('studentnotallowed', '', fullname($USER, true)), $CFG->wwwroot .'/');
1efa27fd 913 }
b0ccd3fb 914 if ($USER->username == 'guest') {
7363ff91 915 switch ($course->guest) {
916 case 0: // Guests not allowed
917 print_header();
b0ccd3fb 918 notice(get_string('guestsnotallowed', '', $course->fullname));
7363ff91 919 break;
920 case 1: // Guests allowed
7363ff91 921 return;
922 case 2: // Guests allowed with key (drop through)
923 break;
924 }
da5c172a 925 }
f9903ed0 926
7363ff91 927 // Currently not enrolled in the course, so see if they want to enrol
da5c172a 928 $SESSION->wantsurl = $FULLME;
b0ccd3fb 929 redirect($CFG->wwwroot .'/course/enrol.php?id='. $courseid);
da5c172a 930 die;
931 }
f9903ed0 932}
933
7cf1c7bd 934/**
935 * This is a weaker version of {@link require_login()} which only requires login
936 * when called from within a course rather than the site page, unless
937 * the forcelogin option is turned on.
938 *
939 * @uses $CFG
c6d15803 940 * @param int $courseid The course in question
941 * @param boolean $autologinguest ?
7cf1c7bd 942 * @todo Finish documenting this function
943 */
f950af3c 944function require_course_login($course, $autologinguest=true) {
f950af3c 945 global $CFG;
946 if ($CFG->forcelogin) {
947 require_login();
948 }
949 if ($course->category) {
950 require_login($course->id, $autologinguest);
951 }
952}
953
7cf1c7bd 954/**
955 * Modify the user table by setting the currently logged in user's
956 * last login to now.
957 *
958 * @uses $USER
959 * @return boolean
960 */
1d881d92 961function update_user_login_times() {
962 global $USER;
963
964 $USER->lastlogin = $user->lastlogin = $USER->currentlogin;
2a2f5f11 965 $USER->currentlogin = $user->lastaccess = $user->currentlogin = time();
1d881d92 966
967 $user->id = $USER->id;
968
b0ccd3fb 969 return update_record('user', $user);
1d881d92 970}
971
7cf1c7bd 972/**
973 * Determines if a user has completed setting up their account.
974 *
89dcb99d 975 * @param user $user A {@link $USER} object to test for the existance of a valid name and email
7cf1c7bd 976 * @return boolean
977 */
808a3baa 978function user_not_fully_set_up($user) {
b0ccd3fb 979 return ($user->username != 'guest' and (empty($user->firstname) or empty($user->lastname) or empty($user->email)));
808a3baa 980}
f9903ed0 981
7cf1c7bd 982/**
983 * Keeps track of login attempts
984 *
985 * @uses $SESSION
986 */
f9903ed0 987function update_login_count() {
9fa49e22 988
f9903ed0 989 global $SESSION;
990
991 $max_logins = 10;
992
993 if (empty($SESSION->logincount)) {
994 $SESSION->logincount = 1;
995 } else {
996 $SESSION->logincount++;
997 }
998
999 if ($SESSION->logincount > $max_logins) {
9fa49e22 1000 unset($SESSION->wantsurl);
b0ccd3fb 1001 error(get_string('errortoomanylogins'));
d578afc8 1002 }
1003}
1004
7cf1c7bd 1005/**
1006 * Resets login attempts
1007 *
1008 * @uses $SESSION
1009 */
9fa49e22 1010function reset_login_count() {
9fa49e22 1011 global $SESSION;
d578afc8 1012
9fa49e22 1013 $SESSION->logincount = 0;
d578afc8 1014}
1015
7cf1c7bd 1016/**
1017 * check_for_restricted_user
1018 *
89dcb99d 1019 * @uses $CFG
1020 * @uses $USER
1021 * @param string $username ?
1022 * @param string $redirect ?
7cf1c7bd 1023 * @todo Finish documenting this function
1024 */
b0ccd3fb 1025function check_for_restricted_user($username=NULL, $redirect='') {
cb98d312 1026 global $CFG, $USER;
1027
1028 if (!$username) {
1029 if (!empty($USER->username)) {
1030 $username = $USER->username;
1031 } else {
1032 return false;
1033 }
1034 }
1035
1036 if (!empty($CFG->restrictusers)) {
1037 $names = explode(',', $CFG->restrictusers);
1038 if (in_array($username, $names)) {
b0ccd3fb 1039 error(get_string('restricteduser', 'error', fullname($USER)), $redirect);
cb98d312 1040 }
1041 }
1042}
1043
7cf1c7bd 1044/**
1045 * Determines if a user an admin
1046 *
1047 * @uses $USER
c6d15803 1048 * @param int $userid The id of the user as is found in the 'user' table
89dcb99d 1049 * @staticvar array $admin ?
1050 * @staticvar array $nonadmins ?
7cf1c7bd 1051 * @return boolean
89dcb99d 1052 * @todo Complete documentation for this function
7cf1c7bd 1053 */
581d7b49 1054function isadmin($userid=0) {
f9903ed0 1055 global $USER;
aa095969 1056 static $admins = array();
1057 static $nonadmins = array();
f9903ed0 1058
581d7b49 1059 if (!$userid){
1060 if (empty($USER->id)) {
1061 return false;
1062 }
1063 $userid = $USER->id;
9bd2c874 1064 }
1065
581d7b49 1066 if (in_array($userid, $admins)) {
aa095969 1067 return true;
581d7b49 1068 } else if (in_array($userid, $nonadmins)) {
aa095969 1069 return false;
b0ccd3fb 1070 } else if (record_exists('user_admins', 'userid', $userid)){
581d7b49 1071 $admins[] = $userid;
aa095969 1072 return true;
1073 } else {
581d7b49 1074 $nonadmins[] = $userid;
aa095969 1075 return false;
f9903ed0 1076 }
f9903ed0 1077}
1078
7cf1c7bd 1079/**
1080 * Determines if a user is a teacher or an admin
1081 *
1082 * @uses $USER
c6d15803 1083 * @param int $courseid The id of the course that is being viewed, if any
1084 * @param int $userid The id of the user that is being tested against. Set this to 0 if you would just like to test against the currently logged in user.
7cf1c7bd 1085 * @param boolean $includeadmin If true this function will return true when it encounters an admin user.
1086 * @return boolean
1087 * @todo Finish documenting this function
1088 */
9d3c795c 1089function isteacher($courseid=0, $userid=0, $includeadmin=true) {
f9903ed0 1090 global $USER;
1091
9788367b 1092 if ($includeadmin and isadmin($userid)) { // admins can do anything the teacher can
d115a57f 1093 return true;
1094 }
1095
f9903ed0 1096 if (!$userid) {
71f9abf9 1097 if ($courseid) {
1098 return !empty($USER->teacher[$courseid]);
1099 }
1100 if (!isset($USER->id)) {
1101 return false;
1102 }
1103 $userid = $USER->id;
f9903ed0 1104 }
1105
9d3c795c 1106 if (!$courseid) {
b0ccd3fb 1107 return record_exists('user_teachers', 'userid', $userid);
9d3c795c 1108 }
1109
b0ccd3fb 1110 return record_exists('user_teachers', 'userid', $userid, 'course', $courseid);
f9903ed0 1111}
1112
7cf1c7bd 1113/**
1114 * Determines if a user is allowed to edit a given course
1115 *
1116 * @uses $USER
c6d15803 1117 * @param int $courseid The id of the course that is being edited
1118 * @param int $userid The id of the user that is being tested against. Set this to 0 if you would just like to test against the currently logged in user.
7cf1c7bd 1119 * @return boolean
1120 */
73047f2f 1121function isteacheredit($courseid, $userid=0) {
73047f2f 1122 global $USER;
1123
d8ba183c 1124 if (isadmin($userid)) { // admins can do anything
73047f2f 1125 return true;
1126 }
1127
1128 if (!$userid) {
1129 return !empty($USER->teacheredit[$courseid]);
1130 }
1131
b0ccd3fb 1132 return get_field('user_teachers', 'editall', 'userid', $userid, 'course', $courseid);
73047f2f 1133}
1134
7cf1c7bd 1135/**
1136 * Determines if a user can create new courses
1137 *
1138 * @uses $USER
361855e6 1139 * @param int $userid The user being tested. You can set this to 0 or leave it blank to test the currently logged in user.
7cf1c7bd 1140 * @return boolean
1141 */
1924074c 1142function iscreator ($userid=0) {
1924074c 1143 global $USER;
8a205861 1144 if (empty($USER->id)) {
1145 return false;
1146 }
1924074c 1147 if (isadmin($userid)) { // admins can do anything
1148 return true;
1149 }
8a205861 1150 if (empty($userid)) {
b0ccd3fb 1151 return record_exists('user_coursecreators', 'userid', $USER->id);
1924074c 1152 }
1153
b0ccd3fb 1154 return record_exists('user_coursecreators', 'userid', $userid);
1924074c 1155}
1156
7cf1c7bd 1157/**
1158 * Determines if a user is a student in the specified course
361855e6 1159 *
7cf1c7bd 1160 * If the course id specifies the site then the function determines
1161 * if the user is a confirmed and valid user of this site.
1162 *
1163 * @uses $USER
1164 * @uses $CFG
c6d15803 1165 * @uses SITEID
1166 * @param int $courseid The id of the course being tested
361855e6 1167 * @param int $userid The user being tested. You can set this to 0 or leave it blank to test the currently logged in user.
7cf1c7bd 1168 * @return boolean
1169 */
8a9e3fd7 1170function isstudent($courseid, $userid=0) {
71f9abf9 1171 global $USER, $CFG;
f9903ed0 1172
2700d113 1173 if (empty($USER->id) and !$userid) {
7064e18f 1174 return false;
1175 }
1176
222ac91b 1177 if ($courseid == SITEID) {
2cc72e84 1178 if (!$userid) {
1179 $userid = $USER->id;
1180 }
1181 if (isguest($userid)) {
1182 return false;
1183 }
71f9abf9 1184 // a site teacher can never be a site student
1185 if (isteacher($courseid, $userid)) {
1186 return false;
1187 }
2700d113 1188 if ($CFG->allusersaresitestudents) {
1189 return record_exists('user', 'id', $userid);
1190 } else {
1191 return (record_exists('user_students', 'userid', $userid)
71f9abf9 1192 or record_exists('user_teachers', 'userid', $userid));
2700d113 1193 }
8f0cd6ef 1194 }
2cc72e84 1195
f9903ed0 1196 if (!$userid) {
346b1a24 1197 return !empty($USER->student[$courseid]);
f9903ed0 1198 }
1199
ebc3bd2b 1200 // $timenow = time(); // todo: add time check below
f9903ed0 1201
b0ccd3fb 1202 return record_exists('user_students', 'userid', $userid, 'course', $courseid);
f9903ed0 1203}
1204
7cf1c7bd 1205/**
1206 * Determines if the specified user is logged in as guest.
1207 *
1208 * @uses $USER
361855e6 1209 * @param int $userid The user being tested. You can set this to 0 or leave it blank to test the currently logged in user.
7cf1c7bd 1210 * @return boolean
1211 */
da5c172a 1212function isguest($userid=0) {
1213 global $USER;
1214
1215 if (!$userid) {
b35e8568 1216 if (empty($USER->username)) {
1217 return false;
1218 }
b0ccd3fb 1219 return ($USER->username == 'guest');
da5c172a 1220 }
1221
b0ccd3fb 1222 return record_exists('user', 'id', $userid, 'username', 'guest');
da5c172a 1223}
1224
7cf1c7bd 1225/**
1226 * Determines if the currently logged in user is in editing mode
1227 *
1228 * @uses $USER
c6d15803 1229 * @param int $courseid The id of the course being tested
89dcb99d 1230 * @param user $user A {@link $USER} object. If null then the currently logged in user is used.
7cf1c7bd 1231 * @return boolean
1232 */
2c309dc2 1233function isediting($courseid, $user=NULL) {
1234 global $USER;
1235 if (!$user){
1236 $user = $USER;
1237 }
9c9f7d77 1238 if (empty($user->editing)) {
1239 return false;
1240 }
2c309dc2 1241 return ($user->editing and isteacher($courseid, $user->id));
1242}
1243
7cf1c7bd 1244/**
1245 * Determines if the logged in user is currently moving an activity
1246 *
1247 * @uses $USER
c6d15803 1248 * @param int $courseid The id of the course being tested
7cf1c7bd 1249 * @return boolean
1250 */
7977cffd 1251function ismoving($courseid) {
7977cffd 1252 global $USER;
1253
1254 if (!empty($USER->activitycopy)) {
1255 return ($USER->activitycopycourse == $courseid);
1256 }
1257 return false;
1258}
1259
7cf1c7bd 1260/**
1261 * Given an object containing firstname and lastname
1262 * values, this function returns a string with the
1263 * full name of the person.
1264 * The result may depend on system settings
1265 * or language. 'override' will force both names
361855e6 1266 * to be used even if system settings specify one.
7cf1c7bd 1267 * @uses $CFG
1268 * @uses $SESSION
1269 * @param type description
1270 * @todo Finish documenting this function
1271 */
e2cd5065 1272function fullname($user, $override=false) {
b5cbb64d 1273
f374fb10 1274 global $CFG, $SESSION;
1275
6527c077 1276 if (!isset($user->firstname) and !isset($user->lastname)) {
1277 return '';
1278 }
1279
f374fb10 1280 if (!empty($SESSION->fullnamedisplay)) {
1281 $CFG->fullnamedisplay = $SESSION->fullnamedisplay;
1282 }
e2cd5065 1283
b5cbb64d 1284 if ($CFG->fullnamedisplay == 'firstname lastname') {
b0ccd3fb 1285 return $user->firstname .' '. $user->lastname;
b5cbb64d 1286
1287 } else if ($CFG->fullnamedisplay == 'lastname firstname') {
b0ccd3fb 1288 return $user->lastname .' '. $user->firstname;
e2cd5065 1289
b5cbb64d 1290 } else if ($CFG->fullnamedisplay == 'firstname') {
1291 if ($override) {
1292 return get_string('fullnamedisplay', '', $user);
1293 } else {
1294 return $user->firstname;
1295 }
1296 }
e2cd5065 1297
b5cbb64d 1298 return get_string('fullnamedisplay', '', $user);
e2cd5065 1299}
1300
7cf1c7bd 1301/**
1302 * Sets a moodle cookie with an encrypted string
1303 *
1304 * @uses $CFG
2f87145b 1305 * @uses DAYSECS
1306 * @uses HOURSECS
7cf1c7bd 1307 * @param string $thing The string to encrypt and place in a cookie
1308 */
f9903ed0 1309function set_moodle_cookie($thing) {
7185e073 1310 global $CFG;
482b6e6e 1311
1312 $cookiename = 'MOODLEID_'.$CFG->sessioncookie;
f9903ed0 1313
1314 $days = 60;
7a5672c9 1315 $seconds = DAYSECS*$days;
f9903ed0 1316
7a5672c9 1317 setCookie($cookiename, '', time() - HOURSECS, '/');
b0ccd3fb 1318 setCookie($cookiename, rc4encrypt($thing), time()+$seconds, '/');
f9903ed0 1319}
1320
7cf1c7bd 1321/**
1322 * Gets a moodle cookie with an encrypted string
1323 *
1324 * @uses $CFG
1325 * @return string
1326 */
f9903ed0 1327function get_moodle_cookie() {
7185e073 1328 global $CFG;
1329
482b6e6e 1330 $cookiename = 'MOODLEID_'.$CFG->sessioncookie;
7185e073 1331
1079c8a8 1332 if (empty($_COOKIE[$cookiename])) {
b0ccd3fb 1333 return '';
1079c8a8 1334 } else {
1335 return rc4decrypt($_COOKIE[$cookiename]);
1336 }
f9903ed0 1337}
1338
7cf1c7bd 1339/**
1340 * Returns true if an internal authentication method is being used.
1341 * if method not specified then, global default is assumed
1342 *
1343 * @uses $CFG
1344 * @param string $auth Form of authentication required
1345 * @return boolean
1346 * @todo Outline auth types and provide code example
1347 */
39a5a35d 1348function is_internal_auth($auth='') {
ba7166c3 1349/// Returns true if an internal authentication method is being used.
a3f1f815 1350/// If auth not specified then global default is assumed
ba7166c3 1351
1352 global $CFG;
1353
a3f1f815 1354 if (empty($auth)) {
1355 $auth = $CFG->auth;
39a5a35d 1356 }
1357
a3f1f815 1358 return ($auth == "email" || $auth == "none" || $auth == "manual");
1359}
1360
8c3dba73 1361/**
1362 * Returns an array of user fields
1363 *
c6d15803 1364 * @uses $CFG
1365 * @uses $db
1366 * @return array User field/column names
8c3dba73 1367 * @todo Finish documenting this function
1368 */
a3f1f815 1369function get_user_fieldnames() {
a3f1f815 1370
1371 global $CFG, $db;
1372
1373 $fieldarray = $db->MetaColumnNames($CFG->prefix.'user');
1374 unset($fieldarray['ID']);
1375
1376 return $fieldarray;
ba7166c3 1377}
f9903ed0 1378
7cf1c7bd 1379/**
1380 * Creates a bare-bones user record
1381 *
1382 * @uses $CFG
7cf1c7bd 1383 * @param string $username New user's username to add to record
1384 * @param string $password New user's password to add to record
1385 * @param string $auth Form of authentication required
89dcb99d 1386 * @return user A {@link $USER} object
7cf1c7bd 1387 * @todo Outline auth types and provide code example
1388 */
71f9abf9 1389function create_user_record($username, $password, $auth='') {
366dfa60 1390 global $CFG;
71f9abf9 1391
1e22bc9c 1392 //just in case check text case
1393 $username = trim(moodle_strtolower($username));
71f9abf9 1394
3271b70f 1395 if (function_exists('auth_get_userinfo')) {
e858f9da 1396 if ($newinfo = auth_get_userinfo($username)) {
b36a8fc4 1397 $newinfo = truncate_userinfo($newinfo);
34daec9b 1398 foreach ($newinfo as $key => $value){
9f44d972 1399 $newuser->$key = addslashes(stripslashes($value)); // Just in case
e858f9da 1400 }
1401 }
1402 }
f9903ed0 1403
85a1d4c9 1404 if (!empty($newuser->email)) {
1405 if (email_is_not_allowed($newuser->email)) {
1406 unset($newuser->email);
1407 }
1408 }
1409
71f9abf9 1410 $newuser->auth = (empty($auth)) ? $CFG->auth : $auth;
faebaf0f 1411 $newuser->username = $username;
1412 $newuser->password = md5($password);
a0bac19d 1413 $newuser->lang = $CFG->lang;
faebaf0f 1414 $newuser->confirmed = 1;
59619427 1415 $newuser->lastIP = getremoteaddr();
faebaf0f 1416 $newuser->timemodified = time();
f9903ed0 1417
b0ccd3fb 1418 if (insert_record('user', $newuser)) {
1419 $user = get_user_info_from_db('username', $newuser->username);
d35757eb 1420 if($CFG->{'auth_'.$newuser->auth.'_forcechangepassword'}){
1421 set_user_preference('auth_forcepasswordchange', 1, $user);
1422 }
1423 return $user;
faebaf0f 1424 }
1425 return false;
1426}
1427
7cf1c7bd 1428/**
1429 * Will update a local user record from an external source
1430 *
1431 * @uses $CFG
1432 * @param string $username New user's username to add to record
89dcb99d 1433 * @return user A {@link $USER} object
7cf1c7bd 1434 */
d35757eb 1435function update_user_record($username) {
d35757eb 1436 global $CFG;
1437
1438 if (function_exists('auth_get_userinfo')) {
1439 $username = trim(moodle_strtolower($username)); /// just in case check text case
1440
1441 if ($newinfo = auth_get_userinfo($username)) {
1442 foreach ($newinfo as $key => $value){
1443 if (!empty($CFG->{'auth_user_' . $key. '_updatelocal'})) {
1444 $value = addslashes(stripslashes($value)); // Just in case
1445 set_field('user', $key, $value, 'username', $username);
1446 }
1447 }
1448 }
1449 }
b0ccd3fb 1450 return get_user_info_from_db('username', $username);
d35757eb 1451}
0609562b 1452
b36a8fc4 1453function truncate_userinfo($info) {
1454/// will truncate userinfo as it comes from auth_get_userinfo (from external auth)
1455/// which may have large fields
1456
1457 // define the limits
1458 $limit = array(
1459 'username' => 100,
1460 'idnumber' => 12,
1461 'firstname' => 20,
1462 'lastname' => 20,
1463 'email' => 100,
1464 'icq' => 15,
1465 'phone1' => 20,
1466 'phone2' => 20,
1467 'institution' => 40,
1468 'department' => 30,
1469 'address' => 70,
1470 'city' => 20,
1471 'country' => 2,
1472 'url' => 255,
1473 );
361855e6 1474
b36a8fc4 1475 // apply where needed
1476 foreach (array_keys($info) as $key) {
1477 if (!empty($limit[$key])) {
1478 $info[$key] = substr($info[$key],0, $limit[$key]);
361855e6 1479 }
b36a8fc4 1480 }
361855e6 1481
b36a8fc4 1482 return $info;
1483}
1484
7cf1c7bd 1485/**
1486 * Retrieve the guest user object
1487 *
1488 * @uses $CFG
89dcb99d 1489 * @return user A {@link $USER} object
7cf1c7bd 1490 */
0609562b 1491function guest_user() {
1492 global $CFG;
1493
b0ccd3fb 1494 if ($newuser = get_record('user', 'username', 'guest')) {
0609562b 1495 $newuser->loggedin = true;
1496 $newuser->confirmed = 1;
1497 $newuser->site = $CFG->wwwroot;
1498 $newuser->lang = $CFG->lang;
366dfa60 1499 $newuser->lastIP = getremoteaddr();
0609562b 1500 }
1501
1502 return $newuser;
1503}
1504
7cf1c7bd 1505/**
1506 * Given a username and password, this function looks them
1507 * up using the currently selected authentication mechanism,
1508 * and if the authentication is successful, it returns a
1509 * valid $user object from the 'user' table.
361855e6 1510 *
7cf1c7bd 1511 * Uses auth_ functions from the currently active auth module
1512 *
1513 * @uses $CFG
361855e6 1514 * @param string $username User's username
1515 * @param string $password User's password
89dcb99d 1516 * @return user|flase A {@link $USER} object or false if error
7cf1c7bd 1517 */
faebaf0f 1518function authenticate_user_login($username, $password) {
faebaf0f 1519
1520 global $CFG;
1521
466558e3 1522 $md5password = md5($password);
1523
27286aeb 1524 // First try to find the user in the database
466558e3 1525
b0ccd3fb 1526 $user = get_user_info_from_db('username', $username);
39a5a35d 1527
27286aeb 1528 // Sort out the authentication method we are using.
39a5a35d 1529
27286aeb 1530 if (empty($CFG->auth)) {
b0ccd3fb 1531 $CFG->auth = 'manual'; // Default authentication module
27286aeb 1532 }
39a5a35d 1533
27286aeb 1534 if (empty($user->auth)) { // For some reason it isn't set yet
1535 if (isadmin($user->id) or isguest($user->id)) {
71f9abf9 1536 $auth = 'manual'; // Always assume these guys are internal
27286aeb 1537 } else {
71f9abf9 1538 $auth = $CFG->auth; // Normal users default to site method
27286aeb 1539 }
d35757eb 1540 // update user record from external DB
1541 if ($user->auth != 'manual' && $user->auth != 'email') {
1542 $user = update_user_record($username);
1543 }
71f9abf9 1544 } else {
1545 $auth = $user->auth;
27286aeb 1546 }
8f0cd6ef 1547
ce791f88 1548 if (detect_munged_arguments($auth, 0)) { // For safety on the next require
1549 return false;
1550 }
1551
b0ccd3fb 1552 if (!file_exists($CFG->dirroot .'/auth/'. $auth .'/lib.php')) {
1553 $auth = 'manual'; // Can't find auth module, default to internal
466558e3 1554 }
1555
b0ccd3fb 1556 require_once($CFG->dirroot .'/auth/'. $auth .'/lib.php');
faebaf0f 1557
1558 if (auth_user_login($username, $password)) { // Successful authentication
71f9abf9 1559 if ($user) { // User already exists in database
1560 if (empty($user->auth)) { // For some reason auth isn't set yet
1561 set_field('user', 'auth', $auth, 'username', $username);
1562 }
92710226 1563 if ($md5password <> $user->password) { // Update local copy of password for reference
71f9abf9 1564 set_field('user', 'password', $md5password, 'username', $username);
faebaf0f 1565 }
366dfa60 1566 if (!is_internal_auth()) { // update user record from external DB
d35757eb 1567 $user = update_user_record($username);
1568 }
faebaf0f 1569 } else {
71f9abf9 1570 $user = create_user_record($username, $password, $auth);
faebaf0f 1571 }
89b54325 1572
e582b65e 1573 if (function_exists('auth_iscreator')) { // Check if the user is a creator
f894a791 1574 $useriscreator = auth_iscreator($username);
1575 if (!is_null($useriscreator)) {
1576 if ($useriscreator) {
1577 if (! record_exists('user_coursecreators', 'userid', $user->id)) {
1578 $cdata->userid = $user->id;
1579 if (! insert_record('user_coursecreators', $cdata)) {
1580 error('Cannot add user to course creators.');
1581 }
39a5a35d 1582 }
f894a791 1583 } else {
1584 if (record_exists('user_coursecreators', 'userid', $user->id)) {
1585 if (! delete_records('user_coursecreators', 'userid', $user->id)) {
1586 error('Cannot remove user from course creators.');
1587 }
39a5a35d 1588 }
1589 }
361855e6 1590 }
39a5a35d 1591 }
366dfa60 1592 $user->sessionIP = md5(getremoteaddr()); // Store the current IP in the session
e582b65e 1593 return $user;
9d3c795c 1594
e582b65e 1595 } else {
b0ccd3fb 1596 add_to_log(0, 'login', 'error', $_SERVER['HTTP_REFERER'], $username);
3af57507 1597 error_log('[client '.$_SERVER['REMOTE_ADDR']."]\t$CFG->wwwroot\tFailed Login:\t$username\t".$_SERVER['HTTP_USER_AGENT']);
e582b65e 1598 return false;
1599 }
f9903ed0 1600}
1601
7cf1c7bd 1602/**
1603 * Enrols (or re-enrols) a student in a given course
1604 *
c6d15803 1605 * @param int $courseid The id of the course that is being viewed
1606 * @param int $userid The id of the user that is being tested against. Set this to 0 if you would just like to test against the currently logged in user.
1607 * @param int $timestart ?
1608 * @param int $timeend ?
7cf1c7bd 1609 * @return boolean
1610 * @todo Finish documenting this function
1611 */
6e8ca983 1612function enrol_student($userid, $courseid, $timestart=0, $timeend=0, $enrol='manual') {
b40bc478 1613
75169b06 1614 global $CFG;
1615
b0ccd3fb 1616 if (!$course = get_record('course', 'id', $courseid)) { // Check course
3041b0f8 1617 return false;
4d312bbe 1618 }
b0ccd3fb 1619 if (!$user = get_record('user', 'id', $userid)) { // Check user
631cf796 1620 return false;
1621 }
b0ccd3fb 1622 if ($student = get_record('user_students', 'userid', $userid, 'course', $courseid)) {
631cf796 1623 $student->timestart = $timestart;
1624 $student->timeend = $timeend;
1625 $student->time = time();
6e8ca983 1626 $student->enrol = $enrol;
b0ccd3fb 1627 return update_record('user_students', $student);
361855e6 1628
631cf796 1629 } else {
75169b06 1630 require_once("$CFG->dirroot/mod/forum/lib.php");
2f3b54ae 1631 forum_add_user($userid, $courseid);
1632
631cf796 1633 $student->userid = $userid;
1634 $student->course = $courseid;
1635 $student->timestart = $timestart;
1636 $student->timeend = $timeend;
1637 $student->time = time();
6e8ca983 1638 $student->enrol = $enrol;
b0ccd3fb 1639 return insert_record('user_students', $student);
631cf796 1640 }
d7facad8 1641}
1642
7cf1c7bd 1643/**
1644 * Unenrols a student from a given course
1645 *
c6d15803 1646 * @param int $courseid The id of the course that is being viewed, if any
1647 * @param int $userid The id of the user that is being tested against.
7cf1c7bd 1648 * @return boolean
1649 */
9fa62805 1650function unenrol_student($userid, $courseid=0) {
d7facad8 1651
9fa62805 1652 if ($courseid) {
9fa49e22 1653 /// First delete any crucial stuff that might still send mail
b0ccd3fb 1654 if ($forums = get_records('forum', 'course', $courseid)) {
9fa49e22 1655 foreach ($forums as $forum) {
b0ccd3fb 1656 delete_records('forum_subscriptions', 'forum', $forum->id, 'userid', $userid);
9fa62805 1657 }
1658 }
1659 if ($groups = get_groups($courseid, $userid)) {
1660 foreach ($groups as $group) {
b0ccd3fb 1661 delete_records('groups_members', 'groupid', $group->id, 'userid', $userid);
bb09fb11 1662 }
f9903ed0 1663 }
b0ccd3fb 1664 return delete_records('user_students', 'userid', $userid, 'course', $courseid);
9fa49e22 1665
f9903ed0 1666 } else {
b0ccd3fb 1667 delete_records('forum_subscriptions', 'userid', $userid);
1668 delete_records('groups_members', 'userid', $userid);
1669 return delete_records('user_students', 'userid', $userid);
f9903ed0 1670 }
1671}
1672
7cf1c7bd 1673/**
1674 * Add a teacher to a given course
1675 *
1676 * @uses $USER
c6d15803 1677 * @param int $courseid The id of the course that is being viewed, if any
1678 * @param int $userid The id of the user that is being tested against. Set this to 0 if you would just like to test against the currently logged in user.
1679 * @param int $editall ?
7cf1c7bd 1680 * @param string $role ?
c6d15803 1681 * @param int $timestart ?
1682 * @param int $timeend ?
7cf1c7bd 1683 * @return boolean
1684 * @todo Finish documenting this function
1685 */
6e8ca983 1686function add_teacher($userid, $courseid, $editall=1, $role='', $timestart=0, $timeend=0, $enrol='manual') {
7b5944cd 1687 global $CFG;
3041b0f8 1688
61451a36 1689 if ($teacher = get_record('user_teachers', 'userid', $userid, 'course', $courseid)) {
b40bc478 1690 $newteacher = NULL;
1691 $newteacher->id = $teacher->id;
1692 $newteacher->editall = $editall;
6e8ca983 1693 $newteacher->enrol = $enrol;
b40bc478 1694 if ($role) {
1695 $newteacher->role = $role;
1696 }
1697 if ($timestart) {
1698 $newteacher->timestart = $timestart;
3041b0f8 1699 }
b40bc478 1700 if ($timeend) {
1701 $newteacher->timeend = $timeend;
1702 }
1703 return update_record('user_teachers', $newteacher);
3041b0f8 1704 }
61451a36 1705
b0ccd3fb 1706 if (!record_exists('user', 'id', $userid)) {
61451a36 1707 return false; // no such user
1708 }
1709
b0ccd3fb 1710 if (!record_exists('course', 'id', $courseid)) {
61451a36 1711 return false; // no such course
1712 }
1713
1714 $teacher = NULL;
1715 $teacher->userid = $userid;
1716 $teacher->course = $courseid;
1717 $teacher->editall = $editall;
1718 $teacher->role = $role;
5a2dea02 1719 $teacher->timemodified = time();
1720 $newteacher->timestart = $timestart;
1721 $newteacher->timeend = $timeend;
b0ccd3fb 1722 if ($student = get_record('user_students', 'userid', $userid, 'course', $courseid)) {
5a2dea02 1723 $teacher->timestart = $student->timestart;
1724 $teacher->timeend = $student->timeend;
1725 $teacher->timeaccess = $student->timeaccess;
1726 }
61451a36 1727
b0ccd3fb 1728 if (record_exists('user_teachers', 'course', $courseid)) {
61451a36 1729 $teacher->authority = 2;
1730 } else {
1731 $teacher->authority = 1;
1732 }
b0ccd3fb 1733 delete_records('user_students', 'userid', $userid, 'course', $courseid); // Unenrol as student
8f0cd6ef 1734
709f0ec8 1735 /// Add forum subscriptions for new users
7b5944cd 1736 require_once('../mod/forum/lib.php');
1737 forum_add_user($userid, $courseid);
61451a36 1738
b0ccd3fb 1739 return insert_record('user_teachers', $teacher);
61451a36 1740
3041b0f8 1741}
1742
7cf1c7bd 1743/**
1744 * Removes a teacher from a given course (or ALL courses)
1745 * Does not delete the user account
1746 *
c6d15803 1747 * @param int $courseid The id of the course that is being viewed, if any
361855e6 1748 * @param int $userid The id of the user that is being tested against.
7cf1c7bd 1749 * @return boolean
1750 */
3041b0f8 1751function remove_teacher($userid, $courseid=0) {
3041b0f8 1752 if ($courseid) {
9fa49e22 1753 /// First delete any crucial stuff that might still send mail
b0ccd3fb 1754 if ($forums = get_records('forum', 'course', $courseid)) {
9fa49e22 1755 foreach ($forums as $forum) {
b0ccd3fb 1756 delete_records('forum_subscriptions', 'forum', $forum->id, 'userid', $userid);
9fa49e22 1757 }
1758 }
b02193e6 1759
1760 /// Next if the teacher is not registered as a student, but is
1761 /// a member of a group, remove them from the group.
1762 if (!isstudent($courseid, $userid)) {
1763 if ($groups = get_groups($courseid, $userid)) {
1764 foreach ($groups as $group) {
b0ccd3fb 1765 delete_records('groups_members', 'groupid', $group->id, 'userid', $userid);
b02193e6 1766 }
1767 }
1768 }
1769
b0ccd3fb 1770 return delete_records('user_teachers', 'userid', $userid, 'course', $courseid);
57507290 1771 } else {
b0ccd3fb 1772 delete_records('forum_subscriptions', 'userid', $userid);
1773 return delete_records('user_teachers', 'userid', $userid);
57507290 1774 }
f9903ed0 1775}
1776
7cf1c7bd 1777/**
1778 * Add a creator to the site
1779 *
361855e6 1780 * @param int $userid The id of the user that is being tested against.
7cf1c7bd 1781 * @return boolean
1782 */
3041b0f8 1783function add_creator($userid) {
3041b0f8 1784
b0ccd3fb 1785 if (!record_exists('user_admins', 'userid', $userid)) {
1786 if (record_exists('user', 'id', $userid)) {
3041b0f8 1787 $creator->userid = $userid;
b0ccd3fb 1788 return insert_record('user_coursecreators', $creator);
3041b0f8 1789 }
1790 return false;
1791 }
1792 return true;
1793}
1794
7cf1c7bd 1795/**
1796 * Remove a creator from a site
1797 *
1798 * @uses $db
c6d15803 1799 * @param int $userid The id of the user that is being tested against.
7cf1c7bd 1800 * @return boolean
1801 */
3041b0f8 1802function remove_creator($userid) {
3041b0f8 1803 global $db;
1804
b0ccd3fb 1805 return delete_records('user_coursecreators', 'userid', $userid);
3041b0f8 1806}
1807
7cf1c7bd 1808/**
1809 * Add an admin to a site
1810 *
1811 * @uses SITEID
c6d15803 1812 * @param int $userid The id of the user that is being tested against.
7cf1c7bd 1813 * @return boolean
1814 */
3041b0f8 1815function add_admin($userid) {
3041b0f8 1816
b0ccd3fb 1817 if (!record_exists('user_admins', 'userid', $userid)) {
1818 if (record_exists('user', 'id', $userid)) {
3041b0f8 1819 $admin->userid = $userid;
361855e6 1820
f950af3c 1821 // any admin is also a teacher on the site course
222ac91b 1822 if (!record_exists('user_teachers', 'course', SITEID, 'userid', $userid)) {
1823 if (!add_teacher($userid, SITEID)) {
f950af3c 1824 return false;
1825 }
1826 }
361855e6 1827
b0ccd3fb 1828 return insert_record('user_admins', $admin);
3041b0f8 1829 }
1830 return false;
1831 }
1832 return true;
1833}
1834
7cf1c7bd 1835/**
1836 * Removes an admin from a site
1837 *
1838 * @uses $db
1839 * @uses SITEID
c6d15803 1840 * @param int $userid The id of the user that is being tested against.
7cf1c7bd 1841 * @return boolean
1842 */
3041b0f8 1843function remove_admin($userid) {
9fa49e22 1844 global $db;
f9903ed0 1845
f950af3c 1846 // remove also from the list of site teachers
222ac91b 1847 remove_teacher($userid, SITEID);
f950af3c 1848
b0ccd3fb 1849 return delete_records('user_admins', 'userid', $userid);
f9903ed0 1850}
1851
7cf1c7bd 1852/**
1853 * Clear a course out completely, deleting all content
1854 * but don't delete the course itself
1855 *
1856 * @uses $USER
1857 * @uses $SESSION
1858 * @uses $CFG
c6d15803 1859 * @param int $courseid The id of the course that is being viewed
7cf1c7bd 1860 * @param boolean $showfeedback Set this to false to suppress notifications from being printed as the functions performs its steps.
1861 * @return boolean
1862 */
07aeb7b0 1863function remove_course_contents($courseid, $showfeedback=true) {
07aeb7b0 1864
ee23f384 1865 global $CFG, $THEME, $USER, $SESSION;
07aeb7b0 1866
1867 $result = true;
1868
b0ccd3fb 1869 if (! $course = get_record('course', 'id', $courseid)) {
1870 error('Course ID was incorrect (can\'t find it)');
07aeb7b0 1871 }
1872
b0ccd3fb 1873 $strdeleted = get_string('deleted');
07aeb7b0 1874
1875 // First delete every instance of every module
d8ba183c 1876
b0ccd3fb 1877 if ($allmods = get_records('modules') ) {
07aeb7b0 1878 foreach ($allmods as $mod) {
1879 $modname = $mod->name;
b0ccd3fb 1880 $modfile = $CFG->dirroot .'/mod/'. $modname .'/lib.php';
1881 $moddelete = $modname .'_delete_instance'; // Delete everything connected to an instance
1882 $moddeletecourse = $modname .'_delete_course'; // Delete other stray stuff (uncommon)
07aeb7b0 1883 $count=0;
1884 if (file_exists($modfile)) {
1885 include_once($modfile);
1886 if (function_exists($moddelete)) {
b0ccd3fb 1887 if ($instances = get_records($modname, 'course', $course->id)) {
07aeb7b0 1888 foreach ($instances as $instance) {
1889 if ($moddelete($instance->id)) {
1890 $count++;
1891 } else {
b0ccd3fb 1892 notify('Could not delete '. $modname .' instance '. $instance->id .' ('. $instance->name .')');
07aeb7b0 1893 $result = false;
1894 }
1895 }
1896 }
1897 } else {
b0ccd3fb 1898 notify('Function '. $moddelete() .'doesn\'t exist!');
07aeb7b0 1899 $result = false;
1900 }
1901
ca952b03 1902 if (function_exists($moddeletecourse)) {
1903 $moddeletecourse($course);
1904 }
07aeb7b0 1905 }
1906 if ($showfeedback) {
b0ccd3fb 1907 notify($strdeleted .' '. $count .' x '. $modname);
07aeb7b0 1908 }
1909 }
1910 } else {
b0ccd3fb 1911 error('No modules are installed!');
07aeb7b0 1912 }
1913
1914 // Delete any user stuff
1915
b0ccd3fb 1916 if (delete_records('user_students', 'course', $course->id)) {
07aeb7b0 1917 if ($showfeedback) {
b0ccd3fb 1918 notify($strdeleted .' user_students');
07aeb7b0 1919 }
1920 } else {
1921 $result = false;
1922 }
1923
b0ccd3fb 1924 if (delete_records('user_teachers', 'course', $course->id)) {
07aeb7b0 1925 if ($showfeedback) {
b0ccd3fb 1926 notify($strdeleted .' user_teachers');
07aeb7b0 1927 }
1928 } else {
1929 $result = false;
1930 }
1931
082e3ebc 1932 // Delete any groups
1933
b0ccd3fb 1934 if ($groups = get_records('groups', 'courseid', $course->id)) {
082e3ebc 1935 foreach ($groups as $group) {
b0ccd3fb 1936 if (delete_records('groups_members', 'groupid', $group->id)) {
082e3ebc 1937 if ($showfeedback) {
b0ccd3fb 1938 notify($strdeleted .' groups_members');
082e3ebc 1939 }
1940 } else {
1941 $result = false;
1942 }
b0ccd3fb 1943 if (delete_records('groups', 'id', $group->id)) {
082e3ebc 1944 if ($showfeedback) {
b0ccd3fb 1945 notify($strdeleted .' groups');
082e3ebc 1946 }
1947 } else {
1948 $result = false;
1949 }
1950 }
1951 }
1952
1953 // Delete events
1954
b0ccd3fb 1955 if (delete_records('event', 'courseid', $course->id)) {
082e3ebc 1956 if ($showfeedback) {
b0ccd3fb 1957 notify($strdeleted .' event');
082e3ebc 1958 }
1959 } else {
1960 $result = false;
1961 }
1962
07aeb7b0 1963 // Delete logs
1964
b0ccd3fb 1965 if (delete_records('log', 'course', $course->id)) {
07aeb7b0 1966 if ($showfeedback) {
b0ccd3fb 1967 notify($strdeleted .' log');
07aeb7b0 1968 }
1969 } else {
1970 $result = false;
1971 }
1972
1973 // Delete any course stuff
1974
b0ccd3fb 1975 if (delete_records('course_sections', 'course', $course->id)) {
07aeb7b0 1976 if ($showfeedback) {
b0ccd3fb 1977 notify($strdeleted .' course_sections');
07aeb7b0 1978 }
1979 } else {
1980 $result = false;
1981 }
1982
b0ccd3fb 1983 if (delete_records('course_modules', 'course', $course->id)) {
07aeb7b0 1984 if ($showfeedback) {
b0ccd3fb 1985 notify($strdeleted .' course_modules');
07aeb7b0 1986 }
1987 } else {
1988 $result = false;
1989 }
1990
1991 return $result;
1992
1993}
1994
7cf1c7bd 1995/**
1996 * This function will empty a course of USER data as much as
1997/// possible. It will retain the activities and the structure
1998/// of the course.
1999 *
2000 * @uses $USER
2001 * @uses $THEME
2002 * @uses $SESSION
2003 * @uses $CFG
c6d15803 2004 * @param int $courseid The id of the course that is being viewed
7cf1c7bd 2005 * @param boolean $showfeedback Set this to false to suppress notifications from being printed as the functions performs its steps.
2006 * @param boolean $removestudents ?
2007 * @param boolean $removeteachers ?
2008 * @param boolean $removegroups ?
2009 * @param boolean $removeevents ?
2010 * @param boolean $removelogs ?
2011 * @return boolean
2012 * @todo Finish documenting this function
2013 */
3831de52 2014function remove_course_userdata($courseid, $showfeedback=true,
2015 $removestudents=true, $removeteachers=false, $removegroups=true,
2016 $removeevents=true, $removelogs=false) {
3831de52 2017
2018 global $CFG, $THEME, $USER, $SESSION;
2019
2020 $result = true;
2021
b0ccd3fb 2022 if (! $course = get_record('course', 'id', $courseid)) {
2023 error('Course ID was incorrect (can\'t find it)');
3831de52 2024 }
2025
b0ccd3fb 2026 $strdeleted = get_string('deleted');
3831de52 2027
2028 // Look in every instance of every module for data to delete
2029
b0ccd3fb 2030 if ($allmods = get_records('modules') ) {
3831de52 2031 foreach ($allmods as $mod) {
2032 $modname = $mod->name;
b0ccd3fb 2033 $modfile = $CFG->dirroot .'/mod/'. $modname .'/lib.php';
2034 $moddeleteuserdata = $modname .'_delete_userdata'; // Function to delete user data
3831de52 2035 $count=0;
2036 if (file_exists($modfile)) {
2037 @include_once($modfile);
2038 if (function_exists($moddeleteuserdata)) {
2039 $moddeleteuserdata($course, $showfeedback);
2040 }
2041 }
2042 }
2043 } else {
b0ccd3fb 2044 error('No modules are installed!');
3831de52 2045 }
2046
2047 // Delete other stuff
2048
2049 if ($removestudents) {
2050 /// Delete student enrolments
b0ccd3fb 2051 if (delete_records('user_students', 'course', $course->id)) {
3831de52 2052 if ($showfeedback) {
b0ccd3fb 2053 notify($strdeleted .' user_students');
3831de52 2054 }
2055 } else {
2056 $result = false;
2057 }
2058 /// Delete group members (but keep the groups)
b0ccd3fb 2059 if ($groups = get_records('groups', 'courseid', $course->id)) {
3831de52 2060 foreach ($groups as $group) {
b0ccd3fb 2061 if (delete_records('groups_members', 'groupid', $group->id)) {
3831de52 2062 if ($showfeedback) {
b0ccd3fb 2063 notify($strdeleted .' groups_members');
3831de52 2064 }
2065 } else {
2066 $result = false;
2067 }
2068 }
2069 }
2070 }
2071
2072 if ($removeteachers) {
b0ccd3fb 2073 if (delete_records('user_teachers', 'course', $course->id)) {
3831de52 2074 if ($showfeedback) {
b0ccd3fb 2075 notify($strdeleted .' user_teachers');
3831de52 2076 }
2077 } else {
2078 $result = false;
2079 }
2080 }
2081
2082 if ($removegroups) {
b0ccd3fb 2083 if ($groups = get_records('groups', 'courseid', $course->id)) {
3831de52 2084 foreach ($groups as $group) {
b0ccd3fb 2085 if (delete_records('groups', 'id', $group->id)) {
3831de52 2086 if ($showfeedback) {
b0ccd3fb 2087 notify($strdeleted .' groups');
3831de52 2088 }
2089 } else {
2090 $result = false;
2091 }
2092 }
2093 }
2094 }
2095
2096 if ($removeevents) {
b0ccd3fb 2097 if (delete_records('event', 'courseid', $course->id)) {
3831de52 2098 if ($showfeedback) {
b0ccd3fb 2099 notify($strdeleted .' event');
3831de52 2100 }
2101 } else {
2102 $result = false;
2103 }
2104 }
2105
2106 if ($removelogs) {
b0ccd3fb 2107 if (delete_records('log', 'course', $course->id)) {
3831de52 2108 if ($showfeedback) {
b0ccd3fb 2109 notify($strdeleted .' log');
3831de52 2110 }
2111 } else {
2112 $result = false;
2113 }
2114 }
2115
2116 return $result;
2117
2118}
2119
2120
f9903ed0 2121
f374fb10 2122/// GROUPS /////////////////////////////////////////////////////////
d8ba183c 2123
f374fb10 2124
2125/**
2126* Returns a boolean: is the user a member of the given group?
d8ba183c 2127*
dcd338ff 2128* @param type description
7cf1c7bd 2129 * @todo Finish documenting this function
f374fb10 2130*/
2131function ismember($groupid, $userid=0) {
2132 global $USER;
2133
8a2c9076 2134 if (!$groupid) { // No point doing further checks
2135 return false;
2136 }
2137
f374fb10 2138 if (!$userid) {
0d67c514 2139 if (empty($USER->groupmember)) {
2140 return false;
2141 }
2142 foreach ($USER->groupmember as $courseid => $mgroupid) {
2143 if ($mgroupid == $groupid) {
2144 return true;
2145 }
2146 }
2147 return false;
f374fb10 2148 }
2149
b0ccd3fb 2150 return record_exists('groups_members', 'groupid', $groupid, 'userid', $userid);
f374fb10 2151}
2152
4ed533df 2153/**
2154 * Add a user to a group, return true upon success or if user already a group member
2155 *
2156 * @param groupid The group id
2157 * @param userid The user id
2158 * @todo Finish documenting this function
2159 */
2160function add_user_to_group ($groupid, $userid) {
2161 if (ismember($groupid, $userid)) return true;
2162 $record->groupid = $groupid;
2163 $record->userid = $userid;
2164 $record->timeadded = time();
2165 return (insert_record('groups_members', $record) !== false);
2166}
2167
2168
0d67c514 2169/**
c6d15803 2170 * Returns the group ID of the current user in the given course
2171 *
2172 * @uses $USER
2173 * @param int $courseid The course being examined - relates to id field in 'course' table.
7cf1c7bd 2174 * @todo Finish documenting this function
c6d15803 2175 */
0d67c514 2176function mygroupid($courseid) {
2177 global $USER;
2178
2179 if (empty($USER->groupmember[$courseid])) {
2180 return 0;
2181 } else {
2182 return $USER->groupmember[$courseid];
2183 }
2184}
2185
f374fb10 2186/**
c6d15803 2187 * For a given course, and possibly course module, determine
2188 * what the current default groupmode is:
2189 * NOGROUPS, SEPARATEGROUPS or VISIBLEGROUPS
2190 *
89dcb99d 2191 * @param course $course A {@link $COURSE} object
2192 * @param array? $cm A course module object
c6d15803 2193 * @return int A group mode (NOGROUPS, SEPARATEGROUPS or VISIBLEGROUPS)
2194 */
f374fb10 2195function groupmode($course, $cm=null) {
2196
2197 if ($cm and !$course->groupmodeforce) {
2198 return $cm->groupmode;
2199 }
2200 return $course->groupmode;
2201}
2202
2203
2204/**
c6d15803 2205 * Sets the current group in the session variable
2206 *
2207 * @uses $SESSION
2208 * @param int $courseid The course being examined - relates to id field in 'course' table.
2209 * @param int $groupid The group being examined.
2210 * @return int Current group id which was set by this function
7cf1c7bd 2211 * @todo Finish documenting this function
c6d15803 2212 */
f374fb10 2213function set_current_group($courseid, $groupid) {
2214 global $SESSION;
2215
2216 return $SESSION->currentgroup[$courseid] = $groupid;
2217}
2218
2219
2220/**
c6d15803 2221 * Gets the current group for the current user as an id or an object
2222 *
2223 * @uses $CFG
2224 * @uses $SESSION
2225 * @param int $courseid The course being examined - relates to id field in 'course' table.
9f1f6daf 2226 * @param boolean $full If true, the return value is a full record object. If false, just the id of the record.
7cf1c7bd 2227 * @todo Finish documenting this function
c6d15803 2228 */
f374fb10 2229function get_current_group($courseid, $full=false) {
2230 global $SESSION, $USER;
2231
ce04df6b 2232 if (!isset($SESSION->currentgroup[$courseid])) {
f374fb10 2233 if (empty($USER->groupmember[$courseid])) {
8a2c9076 2234 return 0;
f374fb10 2235 } else {
2236 $SESSION->currentgroup[$courseid] = $USER->groupmember[$courseid];
2237 }
2238 }
2239
2240 if ($full) {
0da33e07 2241 return get_record('groups', 'id', $SESSION->currentgroup[$courseid]);
f374fb10 2242 } else {
2243 return $SESSION->currentgroup[$courseid];
2244 }
2245}
2246
0d67c514 2247/**
c6d15803 2248 * A combination function to make it easier for modules
2249 * to set up groups.
2250 *
2251 * It will use a given "groupid" parameter and try to use
2252 * that to reset the current group for the user.
2253 *
2254 * @uses VISIBLEGROUPS
89dcb99d 2255 * @param course $course A {@link $COURSE} object
c6d15803 2256 * @param int $groupmode Either NOGROUPS, SEPARATEGROUPS or VISIBLEGROUPS
2257 * @param int $groupid Will try to use this optional parameter to
2258 * reset the current group for the user
89dcb99d 2259 * @return int|false Returns the current group id or false if error.
7cf1c7bd 2260 * @todo Finish documenting this function
c6d15803 2261 */
eb6147a8 2262function get_and_set_current_group($course, $groupmode, $groupid=-1) {
0d67c514 2263
2264 if (!$groupmode) { // Groups don't even apply
d8ba183c 2265 return false;
0d67c514 2266 }
2267
2268 $currentgroupid = get_current_group($course->id);
2269
eb6147a8 2270 if ($groupid < 0) { // No change was specified
2271 return $currentgroupid;
2272 }
2273
2274 if ($groupid) { // Try to change the current group to this groupid
0d67c514 2275 if ($group = get_record('groups', 'id', $groupid, 'courseid', $course->id)) { // Exists
2276 if (isteacheredit($course->id)) { // Sets current default group
2277 $currentgroupid = set_current_group($course->id, $group->id);
2278
2279 } else if ($groupmode == VISIBLEGROUPS) { // All groups are visible
2280 $currentgroupid = $group->id;
2281 }
2282 }
eb6147a8 2283 } else { // When groupid = 0 it means show ALL groups
2284 if (isteacheredit($course->id)) { // Sets current default group
2285 $currentgroupid = set_current_group($course->id, 0);
2286
2287 } else if ($groupmode == VISIBLEGROUPS) { // All groups are visible
2288 $currentgroupid = 0;
2289 }
0d67c514 2290 }
2291
2292 return $currentgroupid;
2293}
2294
2295
c3cbfe7f 2296/**
c6d15803 2297 * A big combination function to make it easier for modules
2298 * to set up groups.
2299 *
2300 * Terminates if the current user shouldn't be looking at this group
2301 * Otherwise returns the current group if there is one
2302 * Otherwise returns false if groups aren't relevant
2303 *
2304 * @uses SEPARATEGROUPS
2305 * @uses VISIBLEGROUPS
89dcb99d 2306 * @param course $course A {@link $COURSE} object
c6d15803 2307 * @param int $groupmode Either NOGROUPS, SEPARATEGROUPS or VISIBLEGROUPS
2308 * @param string $urlroot ?
7cf1c7bd 2309 * @todo Finish documenting this function
c6d15803 2310 */
c3cbfe7f 2311function setup_and_print_groups($course, $groupmode, $urlroot) {
2312
eb6147a8 2313 if (isset($_GET['group'])) {
2314 $changegroup = $_GET['group']; /// 0 or higher
2315 } else {
2316 $changegroup = -1; /// This means no group change was specified
2317 }
2318
2319 $currentgroup = get_and_set_current_group($course, $groupmode, $changegroup);
c3cbfe7f 2320
eb6147a8 2321 if ($currentgroup === false) {
c3cbfe7f 2322 return false;
2323 }
2324
4b6d8dd5 2325 if ($groupmode == SEPARATEGROUPS and !isteacheredit($course->id) and !$currentgroup) {
2326 print_heading(get_string('notingroup'));
c3cbfe7f 2327 print_footer($course);
2328 exit;
2329 }
2330
2331 if ($groupmode == VISIBLEGROUPS or ($groupmode and isteacheredit($course->id))) {
b0ccd3fb 2332 if ($groups = get_records_menu('groups', 'courseid', $course->id, 'name ASC', 'id,name')) {
eb6147a8 2333 echo '<div align="center">';
c3cbfe7f 2334 print_group_menu($groups, $groupmode, $currentgroup, $urlroot);
eb6147a8 2335 echo '</div>';
c3cbfe7f 2336 }
2337 }
2338
2339 return $currentgroup;
2340}
0d67c514 2341
f374fb10 2342
2343
f9903ed0 2344/// CORRESPONDENCE ////////////////////////////////////////////////
2345
7cf1c7bd 2346/**
2347 * Send an email to a specified user
2348 *
7cf1c7bd 2349 * @uses $CFG
2350 * @uses $_SERVER
c6d15803 2351 * @uses SITEID
89dcb99d 2352 * @param user $user A {@link $USER} object
2353 * @param user $from A {@link $USER} object
7cf1c7bd 2354 * @param string $subject plain text subject line of the email
2355 * @param string $messagetext plain text version of the message
2356 * @param string $messagehtml complete html version of the message (optional)
2357 * @param string $attachment a file on the filesystem, relative to $CFG->dataroot
2358 * @param string $attachname the name of the file (extension indicates MIME)
361855e6 2359 * @param boolean $usetrueaddress determines whether $from email address should
c6d15803 2360 * be sent out. Will be overruled by user profile setting for maildisplay
361855e6 2361 * @return boolean|string Returns "true" if mail was sent OK, "emailstop" if email
c6d15803 2362 * was blocked by user and "false" if there was another sort of error.
7cf1c7bd 2363 */
b0ccd3fb 2364function email_to_user($user, $from, $subject, $messagetext, $messagehtml='', $attachment='', $attachname='', $usetrueaddress=true) {
f9903ed0 2365
f9f4d999 2366 global $CFG, $FULLME;
f9903ed0 2367
0cc6fa6a 2368 global $course; // This is a bit of an ugly hack to be gotten rid of later
2369 if (!empty($course->lang)) { // Course language is defined
2370 $CFG->courselang = $course->lang;
2371 }
2372
b0ccd3fb 2373 include_once($CFG->libdir .'/phpmailer/class.phpmailer.php');
f9903ed0 2374
cadb96f2 2375 if (empty($user)) {
2376 return false;
2377 }
2378
2379 if (!empty($user->emailstop)) {
579dcca4 2380 return 'emailstop';
f9903ed0 2381 }
d8ba183c 2382
f9903ed0 2383 $mail = new phpmailer;
2384
b0ccd3fb 2385 $mail->Version = 'Moodle '. $CFG->version; // mailer version
2386 $mail->PluginDir = $CFG->libdir .'/phpmailer/'; // plugin directory (eg smtp plugin)
562bbe90 2387
98c4eae3 2388
b0ccd3fb 2389 if (current_language() != 'en') {
2390 $mail->CharSet = get_string('thischarset');
98c4eae3 2391 }
2392
b0ccd3fb 2393 if ($CFG->smtphosts == 'qmail') {
62740736 2394 $mail->IsQmail(); // use Qmail system
2395
2396 } else if (empty($CFG->smtphosts)) {
2397 $mail->IsMail(); // use PHP mail() = sendmail
2398
2399 } else {
1e411ffc 2400 $mail->IsSMTP(); // use SMTP directly
57ef3480 2401 if ($CFG->debug > 7) {
b0ccd3fb 2402 echo '<pre>' . "\n";
57ef3480 2403 $mail->SMTPDebug = true;
2404 }
b0ccd3fb 2405 $mail->Host = $CFG->smtphosts; // specify main and backup servers
9f58537a 2406
2407 if ($CFG->smtpuser) { // Use SMTP authentication
2408 $mail->SMTPAuth = true;
2409 $mail->Username = $CFG->smtpuser;
2410 $mail->Password = $CFG->smtppass;
2411 }
7f86ce17 2412 }
f9903ed0 2413
2b97bd71 2414 $adminuser = get_admin();
2415
b0ccd3fb 2416 $mail->Sender = $adminuser->email;
2b97bd71 2417
a402bdcb 2418 if (is_string($from)) { // So we can pass whatever we want if there is need
2419 $mail->From = $CFG->noreplyaddress;
0d8a590a 2420 $mail->FromName = $from;
a402bdcb 2421 } else if ($usetrueaddress and $from->maildisplay) {
b0ccd3fb 2422 $mail->From = $from->email;
6e506bf9 2423 $mail->FromName = fullname($from);
2424 } else {
b0ccd3fb 2425 $mail->From = $CFG->noreplyaddress;
0d8a590a 2426 $mail->FromName = fullname($from);
6e506bf9 2427 }
136dabd8 2428 $mail->Subject = stripslashes($subject);
f9903ed0 2429
b0ccd3fb 2430 $mail->AddAddress($user->email, fullname($user) );
f9903ed0 2431
58d24720 2432 $mail->WordWrap = 79; // set word wrap
f9903ed0 2433
857b798b 2434 if (!empty($from->customheaders)) { // Add custom headers
2435 if (is_array($from->customheaders)) {
2436 foreach ($from->customheaders as $customheader) {
2437 $mail->AddCustomHeader($customheader);
2438 }
2439 } else {
2440 $mail->AddCustomHeader($from->customheaders);
2441 }
b68dca19 2442 }
8f0cd6ef 2443
136dabd8 2444 if ($messagehtml) {
2445 $mail->IsHTML(true);
b0ccd3fb 2446 $mail->Encoding = 'quoted-printable'; // Encoding to use
136dabd8 2447 $mail->Body = $messagehtml;
78681899 2448 $mail->AltBody = "\n$messagetext\n";
136dabd8 2449 } else {
2450 $mail->IsHTML(false);
78681899 2451 $mail->Body = "\n$messagetext\n";
f9903ed0 2452 }
2453
136dabd8 2454 if ($attachment && $attachname) {
2455 if (ereg( "\\.\\." ,$attachment )) { // Security check for ".." in dir path
b0ccd3fb 2456 $mail->AddAddress($adminuser->email, fullname($adminuser) );
2457 $mail->AddStringAttachment('Error in attachment. User attempted to attach a filename with a unsafe name.', 'error.txt', '8bit', 'text/plain');
136dabd8 2458 } else {
b0ccd3fb 2459 include_once($CFG->dirroot .'/files/mimetypes.php');
2460 $mimetype = mimeinfo('type', $attachname);
2461 $mail->AddAttachment($CFG->dataroot .'/'. $attachment, $attachname, 'base64', $mimetype);
136dabd8 2462 }
f9903ed0 2463 }
2464
136dabd8 2465 if ($mail->Send()) {
2466 return true;
2467 } else {
b0ccd3fb 2468 mtrace('ERROR: '. $mail->ErrorInfo);
f9f4d999 2469 add_to_log(SITEID, 'library', 'mailer', $FULLME, 'ERROR: '. $mail->ErrorInfo);
f9903ed0 2470 return false;
2471 }
f9903ed0 2472}
2473
7cf1c7bd 2474/**
2475 * Resets specified user's password and send the new password to the user via email.
2476 *
2477 * @uses $CFG
89dcb99d 2478 * @param user $user A {@link $USER} object
361855e6 2479 * @return boolean|string Returns "true" if mail was sent OK, "emailstop" if email
c6d15803 2480 * was blocked by user and "false" if there was another sort of error.
7cf1c7bd 2481 */
1d881d92 2482function reset_password_and_mail($user) {
2483
2484 global $CFG;
2485
2486 $site = get_site();
2487 $from = get_admin();
2488
2489 $newpassword = generate_password();
2490
b0ccd3fb 2491 if (! set_field('user', 'password', md5($newpassword), 'id', $user->id) ) {
2492 error('Could not set user password!');
1d881d92 2493 }
2494
2495 $a->firstname = $user->firstname;
2496 $a->sitename = $site->fullname;
2497 $a->username = $user->username;
2498 $a->newpassword = $newpassword;
b0ccd3fb 2499 $a->link = $CFG->wwwroot .'/login/change_password.php';
2500 $a->signoff = fullname($from, true).' ('. $from->email .')';
1d881d92 2501
b0ccd3fb 2502 $message = get_string('newpasswordtext', '', $a);
1d881d92 2503
b0ccd3fb 2504 $subject = $site->fullname .': '. get_string('changedpassword');
1d881d92 2505
2506 return email_to_user($user, $from, $subject, $message);
2507
2508}
2509
7cf1c7bd 2510/**
2511 * Send email to specified user with confirmation text and activation link.
2512 *
2513 * @uses $CFG
89dcb99d 2514 * @param user $user A {@link $USER} object
361855e6 2515 * @return boolean|string Returns "true" if mail was sent OK, "emailstop" if email
c6d15803 2516 * was blocked by user and "false" if there was another sort of error.
7cf1c7bd 2517 */
2518 function send_confirmation_email($user) {
1d881d92 2519
2520 global $CFG;
2521
2522 $site = get_site();
2523 $from = get_admin();
2524
2525 $data->firstname = $user->firstname;
2526 $data->sitename = $site->fullname;
b0ccd3fb 2527 $data->link = $CFG->wwwroot .'/login/confirm.php?p='. $user->secret .'&amp;s='. $user->username;
2528 $data->admin = fullname($from) .' ('. $from->email .')';
1d881d92 2529
b0ccd3fb 2530 $message = get_string('emailconfirmation', '', $data);
2531 $subject = get_string('emailconfirmationsubject', '', $site->fullname);
1d881d92 2532
58d24720 2533 $messagehtml = text_to_html($message, false, false, true);
2534
2535 return email_to_user($user, $from, $subject, $message, $messagehtml);
1d881d92 2536
2537}
2538
7cf1c7bd 2539/**
2540 * send_password_change_confirmation_email.
2541 *
c6d15803 2542 * @uses $CFG
89dcb99d 2543 * @param user $user A {@link $USER} object
361855e6 2544 * @return boolean|string Returns "true" if mail was sent OK, "emailstop" if email
c6d15803 2545 * was blocked by user and "false" if there was another sort of error.
7cf1c7bd 2546 * @todo Finish documenting this function
2547 */
eb347b6b 2548function send_password_change_confirmation_email($user) {
2549
2550 global $CFG;
2551
2552 $site = get_site();
2553 $from = get_admin();
2554
2555 $data->firstname = $user->firstname;
2556 $data->sitename = $site->fullname;
b0ccd3fb 2557 $data->link = $CFG->wwwroot .'/login/forgot_password.php?p='. $user->secret .'&amp;s='. $user->username;
2558 $data->admin = fullname($from).' ('. $from->email .')';
eb347b6b 2559
b0ccd3fb 2560 $message = get_string('emailpasswordconfirmation', '', $data);
2561 $subject = get_string('emailpasswordconfirmationsubject', '', $site->fullname);
eb347b6b 2562
2563 return email_to_user($user, $from, $subject, $message);
2564
2565}
2566
7cf1c7bd 2567/**
2568 * Check that an email is allowed. It returns an error message if there
2569 * was a problem.
2570 *
2571 * @param type description
2572 * @todo Finish documenting this function
2573 */
85a1d4c9 2574function email_is_not_allowed($email) {
85a1d4c9 2575
2576 global $CFG;
2577
2578 if (!empty($CFG->allowemailaddresses)) {
2579 $allowed = explode(' ', $CFG->allowemailaddresses);
2580 foreach ($allowed as $allowedpattern) {
2581 $allowedpattern = trim($allowedpattern);
2582 if (!$allowedpattern) {
2583 continue;
2584 }
2585 if (strpos($email, $allowedpattern) !== false) { // Match!
2586 return false;
2587 }
2588 }
b0ccd3fb 2589 return get_string('emailonlyallowed', '', $CFG->allowemailaddresses);
85a1d4c9 2590
2591 } else if (!empty($CFG->denyemailaddresses)) {
2592 $denied = explode(' ', $CFG->denyemailaddresses);
2593 foreach ($denied as $deniedpattern) {
2594 $deniedpattern = trim($deniedpattern);
2595 if (!$deniedpattern) {
2596 continue;
2597 }
2598 if (strpos($email, $deniedpattern) !== false) { // Match!
b0ccd3fb 2599 return get_string('emailnotallowed', '', $CFG->denyemailaddresses);
85a1d4c9 2600 }
2601 }
2602 }
2603
2604 return false;
2605}
1d881d92 2606
136dabd8 2607
f9903ed0 2608/// FILE HANDLING /////////////////////////////////////////////
2609
7cf1c7bd 2610/**
c6d15803 2611 * Create a directory.
7cf1c7bd 2612 *
2613 * @uses $CFG
8c3dba73 2614 * @param string $directory a string of directory names under $CFG->dataroot eg stuff/assignment/1
c6d15803 2615 * param boolean $shownotices If true then notification messages will be printed out on error.
2616 * @return string|false Returns full path to directory if successful, false if not
7cf1c7bd 2617 */
66f9a82c 2618function make_upload_directory($directory, $shownotices=true) {
6b174680 2619
2620 global $CFG;
2621
2622 $currdir = $CFG->dataroot;
fe287429 2623
2e6d4273 2624 umask(0000);
2625
6b174680 2626 if (!file_exists($currdir)) {
2e6d4273 2627 if (! mkdir($currdir, $CFG->directorypermissions)) {
66f9a82c 2628 if ($shownotices) {
b0ccd3fb 2629 notify('ERROR: You need to create the directory '. $currdir .' with web server write access');
66f9a82c 2630 }
6b174680 2631 return false;
2632 }
2765411a 2633 if ($handle = fopen($currdir.'/.htaccess', 'w')) { // For safety
2634 @fwrite($handle, "deny from all\r\n");
2635 @fclose($handle);
2636 }
6b174680 2637 }
2638
b0ccd3fb 2639 $dirarray = explode('/', $directory);
6b174680 2640
2641 foreach ($dirarray as $dir) {
b0ccd3fb 2642 $currdir = $currdir .'/'. $dir;
6b174680 2643 if (! file_exists($currdir)) {
2e6d4273 2644 if (! mkdir($currdir, $CFG->directorypermissions)) {
66f9a82c 2645 if ($shownotices) {
b0ccd3fb 2646 notify('ERROR: Could not find or create a directory ('. $currdir .')');
66f9a82c 2647 }
6b174680 2648 return false;
2649 }
d99bab2d 2650 //@chmod($currdir, $CFG->directorypermissions); // Just in case mkdir didn't do it
6b174680 2651 }
2652 }
2653
2654 return $currdir;
2655}
1e03c552 2656
7cf1c7bd 2657/**
2658 * Makes an upload directory for a particular module.
2659 *
2660 * @uses $CFG
c6d15803 2661 * @param int $courseid The id of the course in question - maps to id field of 'course' table.
2662 * @return string|false Returns full path to directory if successful, false if not
7cf1c7bd 2663 * @todo Finish documenting this function
2664 */
ca4f8eb8 2665function make_mod_upload_directory($courseid) {
2666 global $CFG;
2667
b0ccd3fb 2668 if (! $moddata = make_upload_directory($courseid .'/'. $CFG->moddata)) {
ca4f8eb8 2669 return false;
2670 }
2671
b0ccd3fb 2672 $strreadme = get_string('readme');
ca4f8eb8 2673
b0ccd3fb 2674 if (file_exists($CFG->dirroot .'/lang/'. $CFG->lang .'/docs/module_files.txt')) {
2675 copy($CFG->dirroot .'/lang/'. $CFG->lang .'/docs/module_files.txt', $moddata .'/'. $strreadme .'.txt');
ca4f8eb8 2676 } else {
b0ccd3fb 2677 copy($CFG->dirroot .'/lang/en/docs/module_files.txt', $moddata .'/'. $strreadme .'.txt');
ca4f8eb8 2678 }
2679 return $moddata;
2680}
2681
7cf1c7bd 2682/**
c6d15803 2683 * Returns current name of file on disk if it exists.
7cf1c7bd 2684 *
c6d15803 2685 * @param string $newfile File to be verified
2686 * @return string Current name of file on disk if true
7cf1c7bd 2687 * @todo Finish documenting this function
2688 */
44e2d2bb 2689function valid_uploaded_file($newfile) {
9c9f7d77 2690 if (empty($newfile)) {
b0ccd3fb 2691 return '';
9c9f7d77 2692 }
44e2d2bb 2693 if (is_uploaded_file($newfile['tmp_name']) and $newfile['size'] > 0) {
2694 return $newfile['tmp_name'];
2695 } else {
b0ccd3fb 2696 return '';
44e2d2bb 2697 }
2698}
2699
7cf1c7bd 2700/**
2701 * Returns the maximum size for uploading files.
2702 *
2703 * There are seven possible upload limits:
2704 * 1. in Apache using LimitRequestBody (no way of checking or changing this)
2705 * 2. in php.ini for 'upload_max_filesize' (can not be changed inside PHP)
2706 * 3. in .htaccess for 'upload_max_filesize' (can not be changed inside PHP)
2707 * 4. in php.ini for 'post_max_size' (can not be changed inside PHP)
2708 * 5. by the Moodle admin in $CFG->maxbytes
2709 * 6. by the teacher in the current course $course->maxbytes
2710 * 7. by the teacher for the current module, eg $assignment->maxbytes
2711 *
2712 * These last two are passed to this function as arguments (in bytes).
2713 * Anything defined as 0 is ignored.
2714 * The smallest of all the non-zero numbers is returned.
2715 *
c6d15803 2716 * @param int $sizebytes ?
2717 * @param int $coursebytes Current course $course->maxbytes (in bytes)
2718 * @param int $modulebytes Current module ->maxbytes (in bytes)
2719 * @return int The maximum size for uploading files.
7cf1c7bd 2720 * @todo Finish documenting this function
2721 */
4909e176 2722function get_max_upload_file_size($sitebytes=0, $coursebytes=0, $modulebytes=0) {
4909e176 2723
b0ccd3fb 2724 if (! $filesize = ini_get('upload_max_filesize')) {
2725 $filesize = '5M';
44e2d2bb 2726 }
4909e176 2727 $minimumsize = get_real_size($filesize);
2728
b0ccd3fb 2729 if ($postsize = ini_get('post_max_size')) {
316ebf78 2730 $postsize = get_real_size($postsize);
2731 if ($postsize < $minimumsize) {
2732 $minimumsize = $postsize;
2733 }
2734 }
2735
4909e176 2736 if ($sitebytes and $sitebytes < $minimumsize) {
2737 $minimumsize = $sitebytes;
2738 }
2739
2740 if ($coursebytes and $coursebytes < $minimumsize) {
2741 $minimumsize = $coursebytes;
2742 }
2743
2744 if ($modulebytes and $modulebytes < $minimumsize) {
2745 $minimumsize = $modulebytes;
2746 }
2747
2748 return $minimumsize;
2749}
2750
7cf1c7bd 2751/**
2752 * Related to the above function - this function returns an
2753 * array of possible sizes in an array, translated to the
2754 * local language.
2755 *
c6d15803 2756 * @uses SORT_NUMERIC
2757 * @param int $sizebytes ?
2758 * @param int $coursebytes Current course $course->maxbytes (in bytes)
2759 * @param int $modulebytes Current module ->maxbytes (in bytes)
2760 * @return int
7cf1c7bd 2761 * @todo Finish documenting this function
2762 */
4909e176 2763function get_max_upload_sizes($sitebytes=0, $coursebytes=0, $modulebytes=0) {
4909e176 2764
2765 if (!$maxsize = get_max_upload_file_size($sitebytes, $coursebytes, $modulebytes)) {
2766 return array();
2767 }
2768
2769 $filesize[$maxsize] = display_size($maxsize);
2770
d8ba183c 2771 $sizelist = array(10240, 51200, 102400, 512000, 1048576, 2097152,
4909e176 2772 5242880, 10485760, 20971520, 52428800, 104857600);
2773
2774 foreach ($sizelist as $sizebytes) {
2775 if ($sizebytes < $maxsize) {
2776 $filesize[$sizebytes] = display_size($sizebytes);
2777 }
2778 }
2779
2780 krsort($filesize, SORT_NUMERIC);
2781
2782 return $filesize;
44e2d2bb 2783}
2784
7cf1c7bd 2785/**
2786 * If there has been an error uploading a file, print the appropriate error message
2787 * Numerical constants used as constant definitions not added until PHP version 4.2.0
2788 *
c6d15803 2789 * $filearray is a 1-dimensional sub-array of the $_FILES array
7cf1c7bd 2790 * eg $filearray = $_FILES['userfile1']
361855e6 2791 * If left empty then the first element of the $_FILES array will be used
8c3dba73 2792 *
c6d15803 2793 * @uses $_FILES
2794 * @param array $filearray A 1-dimensional sub-array of the $_FILES array
2795 * @param boolean $returnerror ?
7cf1c7bd 2796 * @return boolean
2797 * @todo Finish documenting this function
2798 */
ebd52396 2799function print_file_upload_error($filearray = '', $returnerror = false) {
ebd52396 2800
2801 if ($filearray == '' or !isset($filearray['error'])) {
2802
2803 if (empty($_FILES)) return false;
2804
2805 $files = $_FILES; /// so we don't mess up the _FILES array for subsequent code
2806 $filearray = array_shift($files); /// use first element of array
2807 }
2808
2809 switch ($filearray['error']) {
2810
2811 case 0: // UPLOAD_ERR_OK
2812 if ($filearray['size'] > 0) {
2813 $errmessage = get_string('uploadproblem', $filearray['name']);
2814 } else {
2815 $errmessage = get_string('uploadnofilefound'); /// probably a dud file name
2816 }
2817 break;
2818
2819 case 1: // UPLOAD_ERR_INI_SIZE
2820 $errmessage = get_string('uploadserverlimit');
2821 break;
2822
2823 case 2: // UPLOAD_ERR_FORM_SIZE
2824 $errmessage = get_string('uploadformlimit');
2825 break;
2826
2827 case 3: // UPLOAD_ERR_PARTIAL
2828 $errmessage = get_string('uploadpartialfile');
2829 break;
2830
2831 case 4: // UPLOAD_ERR_NO_FILE
2832 $errmessage = get_string('uploadnofilefound');
2833 break;
2834
2835 default:
2836 $errmessage = get_string('uploadproblem', $filearray['name']);
2837 }
2838
2839 if ($returnerror) {
2840 return $errmessage;
2841 } else {
2842 notify($errmessage);
2843 return true;
2844 }
2845
2846}
2847
7cf1c7bd 2848/**
2849 * Returns an array with all the filenames in
2850 * all subdirectories, relative to the given rootdir.
2851 * If excludefile is defined, then that file/directory is ignored
2852 * If getdirs is true, then (sub)directories are included in the output
2853 * If getfiles is true, then files are included in the output
2854 * (at least one of these must be true!)
2855 *
c6d15803 2856 * @param string $rootdir ?
2857 * @param string $excludefile If defined then the specified file/directory is ignored
2858 * @param boolean $descend ?
2859 * @param boolean $getdirs If true then (sub)directories are included in the output
2860 * @param boolean $getfiles If true then files are included in the output
2861 * @return array An array with all the filenames in
2862 * all subdirectories, relative to the given rootdir
2863 * @todo Finish documenting this function. Add examples of $excludefile usage.
7cf1c7bd 2864 */
b0ccd3fb 2865function get_directory_list($rootdir, $excludefile='', $descend=true, $getdirs=false, $getfiles=true) {
f9903ed0 2866
2867 $dirs = array();
f9903ed0 2868
16a5602c 2869 if (!$getdirs and !$getfiles) { // Nothing to show
12407705 2870 return $dirs;
2871 }
2872
16a5602c 2873 if (!is_dir($rootdir)) { // Must be a directory
2874 return $dirs;
2875 }
2876
2877 if (!$dir = opendir($rootdir)) { // Can't open it for some reason
d897cae4 2878 return $dirs;
2879 }
2880
81fcd0f0 2881 while (false !== ($file = readdir($dir))) {
b35e8568 2882 $firstchar = substr($file, 0, 1);
b0ccd3fb 2883 if ($firstchar == '.' or $file == 'CVS' or $file == $excludefile) {
b35e8568 2884 continue;
2885 }
b0ccd3fb 2886 $fullfile = $rootdir .'/'. $file;
2887 if (filetype($fullfile) == 'dir') {
16a5602c 2888 if ($getdirs) {
55fd8177 2889 $dirs[] = $file;
2890 }
bf5c2e84 2891 if ($descend) {
16a5602c 2892 $subdirs = get_directory_list($fullfile, $excludefile, $descend, $getdirs, $getfiles);
bf5c2e84 2893 foreach ($subdirs as $subdir) {
b0ccd3fb 2894 $dirs[] = $file .'/'. $subdir;
bf5c2e84 2895 }
f9903ed0 2896 }
16a5602c 2897 } else if ($getfiles) {
b35e8568 2898 $dirs[] = $file;
f9903ed0 2899 }
2900 }
44e2d2bb 2901 closedir($dir);
f9903ed0 2902
774ab660 2903 asort($dirs);
2904
f9903ed0 2905 return $dirs;
2906}
2907
7cf1c7bd 2908/**
2909 * Adds up all the files in a directory and works out the size.
2910 *
2911 * @param string $rootdir ?
2912 * @param string $excludefile ?
c6d15803 2913 * @return array
7cf1c7bd 2914 * @todo Finish documenting this function
2915 */
b0ccd3fb 2916function get_directory_size($rootdir, $excludefile='') {
16a5602c 2917
2918 $size = 0;
2919
2920 if (!is_dir($rootdir)) { // Must be a directory
2921 return $dirs;
2922 }
2923
b5b90f26 2924 if (!$dir = @opendir($rootdir)) { // Can't open it for some reason
16a5602c 2925 return $dirs;
2926 }
2927
2928 while (false !== ($file = readdir($dir))) {
2929 $firstchar = substr($file, 0, 1);
b0ccd3fb 2930 if ($firstchar == '.' or $file == 'CVS' or $file == $excludefile) {
16a5602c 2931 continue;
2932 }
b0ccd3fb 2933 $fullfile = $rootdir .'/'. $file;
2934 if (filetype($fullfile) == 'dir') {
16a5602c 2935 $size += get_directory_size($fullfile, $excludefile);
2936 } else {
2937 $size += filesize($fullfile);
2938 }
2939 }
2940 closedir($dir);
2941
2942 return $size;
2943}
2944
7cf1c7bd 2945/**
2946 * Converts numbers like 10M into bytes.
2947 *
7cf1c7bd 2948 * @param mixed $size The size to be converted
2949 * @return mixed
2950 */
989bfa9d 2951function get_real_size($size=0) {
989bfa9d 2952 if (!$size) {
d8ba183c 2953 return 0;
989bfa9d 2954 }
2955 $scan['MB'] = 1048576;
64efda84 2956 $scan['Mb'] = 1048576;
989bfa9d 2957 $scan['M'] = 1048576;
266a416e 2958 $scan['m'] = 1048576;
989bfa9d 2959 $scan['KB'] = 1024;
64efda84 2960 $scan['Kb'] = 1024;
989bfa9d 2961 $scan['K'] = 1024;
266a416e 2962 $scan['k'] = 1024;
989bfa9d 2963
2964 while (list($key) = each($scan)) {
2965 if ((strlen($size)>strlen($key))&&(substr($size, strlen($size) - strlen($key))==$key)) {
2966 $size = substr($size, 0, strlen($size) - strlen($key)) * $scan[$key];
2967 break;
2968 }
2969 }
2970 return $size;
2971}
2972
7cf1c7bd 2973/**
2974 * Converts bytes into display form
2975 *
c6d15803 2976 * @param string $size ?
2977 * @return string
89dcb99d 2978 * @staticvar string $gb Localized string for size in gigabytes
2979 * @staticvar string $mb Localized string for size in megabytes
2980 * @staticvar string $kb Localized string for size in kilobytes
2981 * @staticvar string $b Localized string for size in bytes
c6d15803 2982 * @todo Finish documenting this function. Verify return type.
7cf1c7bd 2983 */
44e2d2bb 2984function display_size($size) {
4909e176 2985
7cf1c7bd 2986 static $gb, $mb, $kb, $b;
4909e176 2987
2988 if (empty($gb)) {
2989 $gb = get_string('sizegb');
2990 $mb = get_string('sizemb');
2991 $kb = get_string('sizekb');
2992 $b = get_string('sizeb');
2993 }
2994
44e2d2bb 2995 if ($size >= 1073741824) {
4909e176 2996 $size = round($size / 1073741824 * 10) / 10 . $gb;
44e2d2bb 2997 } else if ($size >= 1048576) {
4909e176 2998 $size = round($size / 1048576 * 10) / 10 . $mb;
44e2d2bb 2999 } else if ($size >= 1024) {
4909e176 3000 $size = round($size / 1024 * 10) / 10 . $kb;
d8ba183c 3001 } else {
b0ccd3fb 3002 $size = $size .' '. $b;
44e2d2bb 3003 }
3004 return $size;
3005}
3006
7cf1c7bd 3007/**
8c3dba73 3008 * Cleans a given filename by removing suspicious or troublesome characters
3009 * Only these are allowed:
3010 * alphanumeric _ - .
7cf1c7bd 3011 *
c6d15803 3012 * @param string $string ?
3013 * @return string
7cf1c7bd 3014 * @todo Finish documenting this function
3015 */
6b174680 3016function clean_filename($string) {
b0ccd3fb 3017 $string = eregi_replace("\.\.+", '', $string);
8644437d 3018 $string = preg_replace('/[^\.a-zA-Z\d\_-]/','_', $string ); // only allowed chars
b0ccd3fb 3019 $string = eregi_replace("_+", '_', $string);
c6d15803 3020 return $string;
6b174680 3021}
3022
3023
1180c6dc 3024/// STRING TRANSLATION ////////////////////////////////////////
3025
8c3dba73 3026/**
3027 * Returns the code for the current language
3028 *
3029 * @uses $CFG
3030 * @param $USER
3031 * @param $SESSION
3032 * @return string
3033 */
4bfa92e7 3034function current_language() {
3db3acfb 3035 global $CFG, $USER, $SESSION;
4bfa92e7 3036
e5415d58 3037 if (!empty($CFG->courselang)) { // Course language can override all other settings for this page
b3153e4b 3038 return $CFG->courselang;
3039
e5415d58 3040 } else if (!empty($SESSION->lang)) { // Session language can override other settings
3db3acfb 3041 return $SESSION->lang;
3042
e5415d58 3043 } else if (!empty($USER->lang)) { // User language can override site language
4bfa92e7 3044 return $USER->lang;
3db3acfb 3045
4bfa92e7 3046 } else {
3047 return $CFG->lang;
3048 }
3049}
bcc83c41 3050
8c3dba73 3051/**
76115562 3052 * Prints out a translated string.
3053 *
3054 * Prints out a translated string using the return value from the {@link get_string()} function.
3055 *
3056 * Example usage of this function when the string is in the moodle.php file:<br>
3057 * <code>
3058 * echo '<strong>';
3059 * print_string('wordforstudent');
3060 * echo '</strong>';
3061 * </code>
3062 *
3063 * Example usage of this function when the string is not in the moodle.php file:<br>
3064 * <code>
3065 * echo '<h1>';
3066 * print_string('typecourse', 'calendar');
3067 * echo '</h1>';
3068 * </code>
3069 *
3070 * @param string $identifier The key identifier for the localized string
3071 * @param string $module The module where the key identifier is stored. If none is specified then moodle.php is used.
3072 * @param mixed $a An object, string or number that can be used
3073 * within translation strings
361855e6 3074 */
b0ccd3fb 3075function print_string($identifier, $module='', $a=NULL) {
9fa49e22 3076 echo get_string($identifier, $module, $a);
3077}
3078
8c3dba73 3079/**
76115562 3080 * Returns a localized string.
3081 *
3082 * Returns the translated string specified by $identifier as
8c3dba73 3083 * for $module. Uses the same format files as STphp.
3084 * $a is an object, string or number that can be used
3085 * within translation strings
3086 *
3087 * eg "hello \$a->firstname \$a->lastname"
3088 * or "hello \$a"
3089 *
76115562 3090 * If you would like to directly echo the localized string use
3091 * the function {@link print_string()}
3092 *
3093 * Example usage of this function involves finding the string you would
3094 * like a local equivalent of and using its identifier and module information
3095 * to retrive it.<br>
3096 * If you open moodle/lang/en/moodle.php and look near line 1031
3097 * you will find a string to prompt a user for their word for student
3098 * <code>
3099 * $string['wordforstudent'] = 'Your word for Student';
3100 * </code>
361855e6 3101 * So if you want to display the string 'Your word for student'
3102 * in any language that supports it on your site
76115562 3103 * you just need to use the identifier 'wordforstudent'
3104 * <code>
3105 * $mystring = '<strong>'. get_string('wordforstudent') .'</strong>';
3106or
3107 * </code>
361855e6 3108 * If the string you want is in another file you'd take a slightly
3109 * different approach. Looking in moodle/lang/en/calendar.php you find
76115562 3110 * around line 75:
3111 * <code>
3112 * $string['typecourse'] = 'Course event';
3113 * </code>
361855e6 3114 * If you want to display the string "Course event" in any language
3115 * supported you would use the identifier 'typecourse' and the module 'calendar'
76115562 3116 * (because it is in the file calendar.php):
3117 * <code>
3118 * $mystring = '<h1>'. get_string('typecourse', 'calendar') .'</h1>';
3119 * </code>
3120 *
3121 * As a last resort, should the identifier fail to map to a string
3122 * the returned string will be [[ $identifier ]]
3123 *
8c3dba73 3124 * @uses $CFG
76115562 3125 * @param string $identifier The key identifier for the localized string
3126 * @param string $module The module where the key identifier is stored. If none is specified then moodle.php is used.
3127 * @param mixed $a An object, string or number that can be used
3128 * within translation strings
3129 * @return string The localized string.
8c3dba73 3130 */
361855e6 3131function get_string($identifier, $module='', $a=NULL) {
1180c6dc 3132
4bfa92e7 3133 global $CFG;
1180c6dc 3134
e11dc9b6 3135 global $course; /// Not a nice hack, but quick
ac8abb5f 3136 if (empty($CFG->courselang)) {
3137 if (!empty($course->lang)) {
3138 $CFG->courselang = $course->lang;
3139 }
e11dc9b6 3140 }
3141
4bfa92e7 3142 $lang = current_language();
1180c6dc 3143
b0ccd3fb 3144 if ($module == '') {
3145 $module = 'moodle';
1180c6dc 3146 }
3147
d0dc2b98 3148/// Define the two or three major locations of language strings for this module
1180c6dc 3149
d0dc2b98 3150 $locations = array( $CFG->dataroot.'/lang/', $CFG->dirroot.'/lang/' );
3151 if ($module != 'moodle') {
3152 $locations[] = $CFG->dirroot .'/mod/'.$module.'/lang/';
1180c6dc 3153 }
3154
d0dc2b98 3155/// First check all the normal locations for the string in the current language
cdac797c 3156
d0dc2b98 3157 foreach ($locations as $location) {
dc0426bd 3158 $langfile = $location.$lang.'/'.$module.'.php';
cdac797c 3159 if (file_exists($langfile)) {
3160 if ($result = get_string_from_file($identifier, $langfile, "\$resultstring")) {
3161 eval($result);
3162 return $resultstring;
3163 }
3164 }
3165 }
1180c6dc 3166
d0dc2b98 3167/// If the preferred language was English we can abort now
b0ccd3fb 3168 if ($lang == 'en') {
3169 return '[['. $identifier .']]';
b947c69a 3170 }
1180c6dc 3171
d0dc2b98 3172/// Is a parent language defined? If so, try to find this string in a parent language file
d8ba183c 3173
d0dc2b98 3174 foreach ($locations as $location) {
dc0426bd 3175 $langfile = $location.$lang.'/moodle.php';
3176 if (file_exists($langfile)) {
3177 if ($result = get_string_from_file('parentlanguage', $langfile, "\$parentlang")) {
3178 eval($result);
3179 if (!empty($parentlang)) { // found it!
3180 $langfile = $location.$parentlang.'/'.$module.'.php';
3181 if (file_exists($langfile)) {
3182 if ($result = get_string_from_file($identifier, $langfile, "\$resultstring")) {
3183 eval($result);
3184 return $resultstring;
3185 }
d0dc2b98 3186 }
b947c69a 3187 }
1180c6dc 3188 }
3189 }
3190 }
b947c69a 3191
d0dc2b98 3192/// Our only remaining option is to try English
b947c69a 3193
d0dc2b98 3194 foreach ($locations as $location) {
dc0426bd 3195 $langfile = $location.'en/'.$module.'.php';
b947c69a 3196
cdac797c 3197 if (file_exists($langfile)) {
3198 if ($result = get_string_from_file($identifier, $langfile, "\$resultstring")) {
3199 eval($result);
3200 return $resultstring;
3201 }
3202 }
3203 }
3204
d0dc2b98 3205 return '[['.$identifier.']]'; // Last resort
1180c6dc 3206}
3207
8c3dba73 3208/**
c6d15803 3209 * This function is only used from {@link get_string()}.
8c3dba73 3210 *
da72d76d 3211 * @internal Only used from get_string, not meant to be public API
c6d15803 3212 * @param string $identifier ?
3213 * @param string $langfile ?
3214 * @param string $destination ?
3215 * @return string|false ?
89dcb99d 3216 * @staticvar array $strings Localized strings
da72d76d 3217 * @access private
c6d15803 3218 * @todo Finish documenting this function.
8c3dba73 3219 */
1180c6dc 3220function get_string_from_file($identifier, $langfile, $destination) {
2b32bddd 3221
3222 static $strings; // Keep the strings cached in memory.
3223
3224 if (empty($strings[$langfile])) {
a32c99e2 3225 $string = array();
2b32bddd 3226 include ($langfile);
3227 $strings[$langfile] = $string;
3228 } else {
3229 $string = &$strings[$langfile];
3230 }
1180c6dc 3231
3232 if (!isset ($string[$identifier])) {
3233 return false;
3234 }
3235
b0ccd3fb 3236 return $destination .'= sprintf("'. $string[$identifier] .'");';
1180c6dc 3237}
f9903ed0 3238
8c3dba73 3239/**
3240 * Converts an array of strings to their localized value.
3241 *
3242 * @param array $array An array of strings
3243 * @param string $module The language module that these strings can be found in.
3244 * @return string
3245 */
9d3c795c 3246function get_strings($array, $module='') {
9d3c795c 3247
3248 $string = NULL;
3249 foreach ($array as $item) {
3250 $string->$item = get_string($item, $module);
3251 }
3252 return $string;
3253}
f9903ed0 3254
8c3dba73 3255/**
3256 * Returns a list of language codes and their full names
3257 *
c6d15803 3258 * @uses $CFG
3259 * @return array An associative array with contents in the form of LanguageCode => LanguageName
8c3dba73 3260 * @todo Finish documenting this function
3261 */
1a72314d 3262function get_list_of_languages() {
1a72314d 3263 global $CFG;
3264
984a8bf3 3265 $languages = array();
3266
3267 if (!empty($CFG->langlist)) { // use admin's list of languages
3268 $langlist = explode(',', $CFG->langlist);