fixed bug in paging bar on participants list
[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.
04280e85 798function sesskey() {
1a33f699 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.
04280e85 882 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 *
9407d456 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 */
9407d456 1089function isteacher($courseid, $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
9407d456 1096 if (empty($courseid)) {
1097 notify('isteacher() should not be used without a valid course id as argument');
1098 return isteacherinanycourse($userid, $includeadmin);
1099 }
1100
f9903ed0 1101 if (!$userid) {
71f9abf9 1102 if ($courseid) {
1103 return !empty($USER->teacher[$courseid]);
1104 }
1105 if (!isset($USER->id)) {
1106 return false;
1107 }
1108 $userid = $USER->id;
f9903ed0 1109 }
1110
9407d456 1111 return record_exists('user_teachers', 'userid', $userid, 'course', $courseid);
1112}
1113
1114/**
1115 * Determines if a user is a teacher in any course, or an admin
1116 *
1117 * @uses $USER
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.
1119 * @param boolean $includeadmin If true this function will return true when it encounters an admin user.
1120 * @return boolean
1121 * @todo Finish documenting this function
1122 */
1123function isteacherinanycourse($userid = 0, $includeadmin = true) {
1124 if(empty($userid)) {
1125 if(empty($USER) || empty($USER->id)) {
1126 return false;
1127 }
1128 $userid = $USER->id;
9d3c795c 1129 }
1130
9407d456 1131 return record_exists('user_teachers', 'userid', $userid);
f9903ed0 1132}
1133
7cf1c7bd 1134/**
1135 * Determines if a user is allowed to edit a given course
1136 *
1137 * @uses $USER
c6d15803 1138 * @param int $courseid The id of the course that is being edited
1139 * @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 1140 * @return boolean
1141 */
73047f2f 1142function isteacheredit($courseid, $userid=0) {
73047f2f 1143 global $USER;
1144
d8ba183c 1145 if (isadmin($userid)) { // admins can do anything
73047f2f 1146 return true;
1147 }
1148
1149 if (!$userid) {
1150 return !empty($USER->teacheredit[$courseid]);
1151 }
1152
b0ccd3fb 1153 return get_field('user_teachers', 'editall', 'userid', $userid, 'course', $courseid);
73047f2f 1154}
1155
7cf1c7bd 1156/**
1157 * Determines if a user can create new courses
1158 *
1159 * @uses $USER
361855e6 1160 * @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 1161 * @return boolean
1162 */
1924074c 1163function iscreator ($userid=0) {
1924074c 1164 global $USER;
8a205861 1165 if (empty($USER->id)) {
1166 return false;
1167 }
1924074c 1168 if (isadmin($userid)) { // admins can do anything
1169 return true;
1170 }
8a205861 1171 if (empty($userid)) {
b0ccd3fb 1172 return record_exists('user_coursecreators', 'userid', $USER->id);
1924074c 1173 }
1174
b0ccd3fb 1175 return record_exists('user_coursecreators', 'userid', $userid);
1924074c 1176}
1177
7cf1c7bd 1178/**
1179 * Determines if a user is a student in the specified course
361855e6 1180 *
7cf1c7bd 1181 * If the course id specifies the site then the function determines
1182 * if the user is a confirmed and valid user of this site.
1183 *
1184 * @uses $USER
1185 * @uses $CFG
c6d15803 1186 * @uses SITEID
1187 * @param int $courseid The id of the course being tested
361855e6 1188 * @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 1189 * @return boolean
1190 */
8a9e3fd7 1191function isstudent($courseid, $userid=0) {
71f9abf9 1192 global $USER, $CFG;
f9903ed0 1193
2700d113 1194 if (empty($USER->id) and !$userid) {
7064e18f 1195 return false;
1196 }
1197
222ac91b 1198 if ($courseid == SITEID) {
2cc72e84 1199 if (!$userid) {
1200 $userid = $USER->id;
1201 }
1202 if (isguest($userid)) {
1203 return false;
1204 }
71f9abf9 1205 // a site teacher can never be a site student
1206 if (isteacher($courseid, $userid)) {
1207 return false;
1208 }
2700d113 1209 if ($CFG->allusersaresitestudents) {
1210 return record_exists('user', 'id', $userid);
1211 } else {
1212 return (record_exists('user_students', 'userid', $userid)
71f9abf9 1213 or record_exists('user_teachers', 'userid', $userid));
2700d113 1214 }
8f0cd6ef 1215 }
2cc72e84 1216
f9903ed0 1217 if (!$userid) {
346b1a24 1218 return !empty($USER->student[$courseid]);
f9903ed0 1219 }
1220
ebc3bd2b 1221 // $timenow = time(); // todo: add time check below
f9903ed0 1222
b0ccd3fb 1223 return record_exists('user_students', 'userid', $userid, 'course', $courseid);
f9903ed0 1224}
1225
7cf1c7bd 1226/**
1227 * Determines if the specified user is logged in as guest.
1228 *
1229 * @uses $USER
361855e6 1230 * @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 1231 * @return boolean
1232 */
da5c172a 1233function isguest($userid=0) {
1234 global $USER;
1235
1236 if (!$userid) {
b35e8568 1237 if (empty($USER->username)) {
1238 return false;
1239 }
b0ccd3fb 1240 return ($USER->username == 'guest');
da5c172a 1241 }
1242
b0ccd3fb 1243 return record_exists('user', 'id', $userid, 'username', 'guest');
da5c172a 1244}
1245
7cf1c7bd 1246/**
1247 * Determines if the currently logged in user is in editing mode
1248 *
1249 * @uses $USER
c6d15803 1250 * @param int $courseid The id of the course being tested
89dcb99d 1251 * @param user $user A {@link $USER} object. If null then the currently logged in user is used.
7cf1c7bd 1252 * @return boolean
1253 */
2c309dc2 1254function isediting($courseid, $user=NULL) {
1255 global $USER;
1256 if (!$user){
1257 $user = $USER;
1258 }
9c9f7d77 1259 if (empty($user->editing)) {
1260 return false;
1261 }
2c309dc2 1262 return ($user->editing and isteacher($courseid, $user->id));
1263}
1264
7cf1c7bd 1265/**
1266 * Determines if the logged in user is currently moving an activity
1267 *
1268 * @uses $USER
c6d15803 1269 * @param int $courseid The id of the course being tested
7cf1c7bd 1270 * @return boolean
1271 */
7977cffd 1272function ismoving($courseid) {
7977cffd 1273 global $USER;
1274
1275 if (!empty($USER->activitycopy)) {
1276 return ($USER->activitycopycourse == $courseid);
1277 }
1278 return false;
1279}
1280
7cf1c7bd 1281/**
1282 * Given an object containing firstname and lastname
1283 * values, this function returns a string with the
1284 * full name of the person.
1285 * The result may depend on system settings
1286 * or language. 'override' will force both names
361855e6 1287 * to be used even if system settings specify one.
7cf1c7bd 1288 * @uses $CFG
1289 * @uses $SESSION
1290 * @param type description
1291 * @todo Finish documenting this function
1292 */
e2cd5065 1293function fullname($user, $override=false) {
b5cbb64d 1294
f374fb10 1295 global $CFG, $SESSION;
1296
6527c077 1297 if (!isset($user->firstname) and !isset($user->lastname)) {
1298 return '';
1299 }
1300
f374fb10 1301 if (!empty($SESSION->fullnamedisplay)) {
1302 $CFG->fullnamedisplay = $SESSION->fullnamedisplay;
1303 }
e2cd5065 1304
b5cbb64d 1305 if ($CFG->fullnamedisplay == 'firstname lastname') {
b0ccd3fb 1306 return $user->firstname .' '. $user->lastname;
b5cbb64d 1307
1308 } else if ($CFG->fullnamedisplay == 'lastname firstname') {
b0ccd3fb 1309 return $user->lastname .' '. $user->firstname;
e2cd5065 1310
b5cbb64d 1311 } else if ($CFG->fullnamedisplay == 'firstname') {
1312 if ($override) {
1313 return get_string('fullnamedisplay', '', $user);
1314 } else {
1315 return $user->firstname;
1316 }
1317 }
e2cd5065 1318
b5cbb64d 1319 return get_string('fullnamedisplay', '', $user);
e2cd5065 1320}
1321
7cf1c7bd 1322/**
1323 * Sets a moodle cookie with an encrypted string
1324 *
1325 * @uses $CFG
2f87145b 1326 * @uses DAYSECS
1327 * @uses HOURSECS
7cf1c7bd 1328 * @param string $thing The string to encrypt and place in a cookie
1329 */
f9903ed0 1330function set_moodle_cookie($thing) {
7185e073 1331 global $CFG;
482b6e6e 1332
1333 $cookiename = 'MOODLEID_'.$CFG->sessioncookie;
f9903ed0 1334
1335 $days = 60;
7a5672c9 1336 $seconds = DAYSECS*$days;
f9903ed0 1337
7a5672c9 1338 setCookie($cookiename, '', time() - HOURSECS, '/');
b0ccd3fb 1339 setCookie($cookiename, rc4encrypt($thing), time()+$seconds, '/');
f9903ed0 1340}
1341
7cf1c7bd 1342/**
1343 * Gets a moodle cookie with an encrypted string
1344 *
1345 * @uses $CFG
1346 * @return string
1347 */
f9903ed0 1348function get_moodle_cookie() {
7185e073 1349 global $CFG;
1350
482b6e6e 1351 $cookiename = 'MOODLEID_'.$CFG->sessioncookie;
7185e073 1352
1079c8a8 1353 if (empty($_COOKIE[$cookiename])) {
b0ccd3fb 1354 return '';
1079c8a8 1355 } else {
1356 return rc4decrypt($_COOKIE[$cookiename]);
1357 }
f9903ed0 1358}
1359
7cf1c7bd 1360/**
1361 * Returns true if an internal authentication method is being used.
1362 * if method not specified then, global default is assumed
1363 *
1364 * @uses $CFG
1365 * @param string $auth Form of authentication required
1366 * @return boolean
1367 * @todo Outline auth types and provide code example
1368 */
39a5a35d 1369function is_internal_auth($auth='') {
ba7166c3 1370/// Returns true if an internal authentication method is being used.
a3f1f815 1371/// If auth not specified then global default is assumed
ba7166c3 1372
1373 global $CFG;
1374
a3f1f815 1375 if (empty($auth)) {
1376 $auth = $CFG->auth;
39a5a35d 1377 }
1378
a3f1f815 1379 return ($auth == "email" || $auth == "none" || $auth == "manual");
1380}
1381
8c3dba73 1382/**
1383 * Returns an array of user fields
1384 *
c6d15803 1385 * @uses $CFG
1386 * @uses $db
1387 * @return array User field/column names
8c3dba73 1388 * @todo Finish documenting this function
1389 */
a3f1f815 1390function get_user_fieldnames() {
a3f1f815 1391
1392 global $CFG, $db;
1393
1394 $fieldarray = $db->MetaColumnNames($CFG->prefix.'user');
1395 unset($fieldarray['ID']);
1396
1397 return $fieldarray;
ba7166c3 1398}
f9903ed0 1399
7cf1c7bd 1400/**
1401 * Creates a bare-bones user record
1402 *
1403 * @uses $CFG
7cf1c7bd 1404 * @param string $username New user's username to add to record
1405 * @param string $password New user's password to add to record
1406 * @param string $auth Form of authentication required
89dcb99d 1407 * @return user A {@link $USER} object
7cf1c7bd 1408 * @todo Outline auth types and provide code example
1409 */
71f9abf9 1410function create_user_record($username, $password, $auth='') {
366dfa60 1411 global $CFG;
71f9abf9 1412
1e22bc9c 1413 //just in case check text case
1414 $username = trim(moodle_strtolower($username));
71f9abf9 1415
3271b70f 1416 if (function_exists('auth_get_userinfo')) {
e858f9da 1417 if ($newinfo = auth_get_userinfo($username)) {
b36a8fc4 1418 $newinfo = truncate_userinfo($newinfo);
34daec9b 1419 foreach ($newinfo as $key => $value){
9f44d972 1420 $newuser->$key = addslashes(stripslashes($value)); // Just in case
e858f9da 1421 }
1422 }
1423 }
f9903ed0 1424
85a1d4c9 1425 if (!empty($newuser->email)) {
1426 if (email_is_not_allowed($newuser->email)) {
1427 unset($newuser->email);
1428 }
1429 }
1430
71f9abf9 1431 $newuser->auth = (empty($auth)) ? $CFG->auth : $auth;
faebaf0f 1432 $newuser->username = $username;
1433 $newuser->password = md5($password);
a0bac19d 1434 $newuser->lang = $CFG->lang;
faebaf0f 1435 $newuser->confirmed = 1;
59619427 1436 $newuser->lastIP = getremoteaddr();
faebaf0f 1437 $newuser->timemodified = time();
f9903ed0 1438
b0ccd3fb 1439 if (insert_record('user', $newuser)) {
1440 $user = get_user_info_from_db('username', $newuser->username);
d35757eb 1441 if($CFG->{'auth_'.$newuser->auth.'_forcechangepassword'}){
1442 set_user_preference('auth_forcepasswordchange', 1, $user);
1443 }
1444 return $user;
faebaf0f 1445 }
1446 return false;
1447}
1448
7cf1c7bd 1449/**
1450 * Will update a local user record from an external source
1451 *
1452 * @uses $CFG
1453 * @param string $username New user's username to add to record
89dcb99d 1454 * @return user A {@link $USER} object
7cf1c7bd 1455 */
d35757eb 1456function update_user_record($username) {
d35757eb 1457 global $CFG;
1458
1459 if (function_exists('auth_get_userinfo')) {
1460 $username = trim(moodle_strtolower($username)); /// just in case check text case
1461
1462 if ($newinfo = auth_get_userinfo($username)) {
1463 foreach ($newinfo as $key => $value){
1464 if (!empty($CFG->{'auth_user_' . $key. '_updatelocal'})) {
1465 $value = addslashes(stripslashes($value)); // Just in case
1466 set_field('user', $key, $value, 'username', $username);
1467 }
1468 }
1469 }
1470 }
b0ccd3fb 1471 return get_user_info_from_db('username', $username);
d35757eb 1472}
0609562b 1473
b36a8fc4 1474function truncate_userinfo($info) {
1475/// will truncate userinfo as it comes from auth_get_userinfo (from external auth)
1476/// which may have large fields
1477
1478 // define the limits
1479 $limit = array(
1480 'username' => 100,
1481 'idnumber' => 12,
1482 'firstname' => 20,
1483 'lastname' => 20,
1484 'email' => 100,
1485 'icq' => 15,
1486 'phone1' => 20,
1487 'phone2' => 20,
1488 'institution' => 40,
1489 'department' => 30,
1490 'address' => 70,
1491 'city' => 20,
1492 'country' => 2,
1493 'url' => 255,
1494 );
361855e6 1495
b36a8fc4 1496 // apply where needed
1497 foreach (array_keys($info) as $key) {
1498 if (!empty($limit[$key])) {
1499 $info[$key] = substr($info[$key],0, $limit[$key]);
361855e6 1500 }
b36a8fc4 1501 }
361855e6 1502
b36a8fc4 1503 return $info;
1504}
1505
7cf1c7bd 1506/**
1507 * Retrieve the guest user object
1508 *
1509 * @uses $CFG
89dcb99d 1510 * @return user A {@link $USER} object
7cf1c7bd 1511 */
0609562b 1512function guest_user() {
1513 global $CFG;
1514
b0ccd3fb 1515 if ($newuser = get_record('user', 'username', 'guest')) {
0609562b 1516 $newuser->loggedin = true;
1517 $newuser->confirmed = 1;
1518 $newuser->site = $CFG->wwwroot;
1519 $newuser->lang = $CFG->lang;
366dfa60 1520 $newuser->lastIP = getremoteaddr();
0609562b 1521 }
1522
1523 return $newuser;
1524}
1525
7cf1c7bd 1526/**
1527 * Given a username and password, this function looks them
1528 * up using the currently selected authentication mechanism,
1529 * and if the authentication is successful, it returns a
1530 * valid $user object from the 'user' table.
361855e6 1531 *
7cf1c7bd 1532 * Uses auth_ functions from the currently active auth module
1533 *
1534 * @uses $CFG
361855e6 1535 * @param string $username User's username
1536 * @param string $password User's password
89dcb99d 1537 * @return user|flase A {@link $USER} object or false if error
7cf1c7bd 1538 */
faebaf0f 1539function authenticate_user_login($username, $password) {
faebaf0f 1540
1541 global $CFG;
1542
466558e3 1543 $md5password = md5($password);
1544
27286aeb 1545 // First try to find the user in the database
466558e3 1546
b0ccd3fb 1547 $user = get_user_info_from_db('username', $username);
39a5a35d 1548
27286aeb 1549 // Sort out the authentication method we are using.
39a5a35d 1550
27286aeb 1551 if (empty($CFG->auth)) {
b0ccd3fb 1552 $CFG->auth = 'manual'; // Default authentication module
27286aeb 1553 }
39a5a35d 1554
27286aeb 1555 if (empty($user->auth)) { // For some reason it isn't set yet
1556 if (isadmin($user->id) or isguest($user->id)) {
71f9abf9 1557 $auth = 'manual'; // Always assume these guys are internal
27286aeb 1558 } else {
71f9abf9 1559 $auth = $CFG->auth; // Normal users default to site method
27286aeb 1560 }
d35757eb 1561 // update user record from external DB
1562 if ($user->auth != 'manual' && $user->auth != 'email') {
1563 $user = update_user_record($username);
1564 }
71f9abf9 1565 } else {
1566 $auth = $user->auth;
27286aeb 1567 }
8f0cd6ef 1568
ce791f88 1569 if (detect_munged_arguments($auth, 0)) { // For safety on the next require
1570 return false;
1571 }
1572
b0ccd3fb 1573 if (!file_exists($CFG->dirroot .'/auth/'. $auth .'/lib.php')) {
1574 $auth = 'manual'; // Can't find auth module, default to internal
466558e3 1575 }
1576
b0ccd3fb 1577 require_once($CFG->dirroot .'/auth/'. $auth .'/lib.php');
faebaf0f 1578
1579 if (auth_user_login($username, $password)) { // Successful authentication
71f9abf9 1580 if ($user) { // User already exists in database
1581 if (empty($user->auth)) { // For some reason auth isn't set yet
1582 set_field('user', 'auth', $auth, 'username', $username);
1583 }
92710226 1584 if ($md5password <> $user->password) { // Update local copy of password for reference
71f9abf9 1585 set_field('user', 'password', $md5password, 'username', $username);
faebaf0f 1586 }
366dfa60 1587 if (!is_internal_auth()) { // update user record from external DB
d35757eb 1588 $user = update_user_record($username);
1589 }
faebaf0f 1590 } else {
71f9abf9 1591 $user = create_user_record($username, $password, $auth);
faebaf0f 1592 }
89b54325 1593
e582b65e 1594 if (function_exists('auth_iscreator')) { // Check if the user is a creator
f894a791 1595 $useriscreator = auth_iscreator($username);
1596 if (!is_null($useriscreator)) {
1597 if ($useriscreator) {
1598 if (! record_exists('user_coursecreators', 'userid', $user->id)) {
1599 $cdata->userid = $user->id;
1600 if (! insert_record('user_coursecreators', $cdata)) {
1601 error('Cannot add user to course creators.');
1602 }
39a5a35d 1603 }
f894a791 1604 } else {
1605 if (record_exists('user_coursecreators', 'userid', $user->id)) {
1606 if (! delete_records('user_coursecreators', 'userid', $user->id)) {
1607 error('Cannot remove user from course creators.');
1608 }
39a5a35d 1609 }
1610 }
361855e6 1611 }
39a5a35d 1612 }
366dfa60 1613 $user->sessionIP = md5(getremoteaddr()); // Store the current IP in the session
e582b65e 1614 return $user;
9d3c795c 1615
e582b65e 1616 } else {
b0ccd3fb 1617 add_to_log(0, 'login', 'error', $_SERVER['HTTP_REFERER'], $username);
3af57507 1618 error_log('[client '.$_SERVER['REMOTE_ADDR']."]\t$CFG->wwwroot\tFailed Login:\t$username\t".$_SERVER['HTTP_USER_AGENT']);
e582b65e 1619 return false;
1620 }
f9903ed0 1621}
1622
7cf1c7bd 1623/**
1624 * Enrols (or re-enrols) a student in a given course
1625 *
c6d15803 1626 * @param int $courseid The id of the course that is being viewed
1627 * @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.
1628 * @param int $timestart ?
1629 * @param int $timeend ?
7cf1c7bd 1630 * @return boolean
1631 * @todo Finish documenting this function
1632 */
6e8ca983 1633function enrol_student($userid, $courseid, $timestart=0, $timeend=0, $enrol='manual') {
b40bc478 1634
75169b06 1635 global $CFG;
1636
b0ccd3fb 1637 if (!$course = get_record('course', 'id', $courseid)) { // Check course
3041b0f8 1638 return false;
4d312bbe 1639 }
b0ccd3fb 1640 if (!$user = get_record('user', 'id', $userid)) { // Check user
631cf796 1641 return false;
1642 }
b0ccd3fb 1643 if ($student = get_record('user_students', 'userid', $userid, 'course', $courseid)) {
631cf796 1644 $student->timestart = $timestart;
1645 $student->timeend = $timeend;
1646 $student->time = time();
6e8ca983 1647 $student->enrol = $enrol;
b0ccd3fb 1648 return update_record('user_students', $student);
361855e6 1649
631cf796 1650 } else {
75169b06 1651 require_once("$CFG->dirroot/mod/forum/lib.php");
2f3b54ae 1652 forum_add_user($userid, $courseid);
1653
631cf796 1654 $student->userid = $userid;
1655 $student->course = $courseid;
1656 $student->timestart = $timestart;
1657 $student->timeend = $timeend;
1658 $student->time = time();
6e8ca983 1659 $student->enrol = $enrol;
b0ccd3fb 1660 return insert_record('user_students', $student);
631cf796 1661 }
d7facad8 1662}
1663
7cf1c7bd 1664/**
1665 * Unenrols a student from a given course
1666 *
c6d15803 1667 * @param int $courseid The id of the course that is being viewed, if any
1668 * @param int $userid The id of the user that is being tested against.
7cf1c7bd 1669 * @return boolean
1670 */
9fa62805 1671function unenrol_student($userid, $courseid=0) {
d7facad8 1672
9fa62805 1673 if ($courseid) {
9fa49e22 1674 /// First delete any crucial stuff that might still send mail
b0ccd3fb 1675 if ($forums = get_records('forum', 'course', $courseid)) {
9fa49e22 1676 foreach ($forums as $forum) {
b0ccd3fb 1677 delete_records('forum_subscriptions', 'forum', $forum->id, 'userid', $userid);
9fa62805 1678 }
1679 }
1680 if ($groups = get_groups($courseid, $userid)) {
1681 foreach ($groups as $group) {
b0ccd3fb 1682 delete_records('groups_members', 'groupid', $group->id, 'userid', $userid);
bb09fb11 1683 }
f9903ed0 1684 }
b0ccd3fb 1685 return delete_records('user_students', 'userid', $userid, 'course', $courseid);
9fa49e22 1686
f9903ed0 1687 } else {
b0ccd3fb 1688 delete_records('forum_subscriptions', 'userid', $userid);
1689 delete_records('groups_members', 'userid', $userid);
1690 return delete_records('user_students', 'userid', $userid);
f9903ed0 1691 }
1692}
1693
7cf1c7bd 1694/**
1695 * Add a teacher to a given course
1696 *
1697 * @uses $USER
c6d15803 1698 * @param int $courseid The id of the course that is being viewed, if any
1699 * @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.
1700 * @param int $editall ?
7cf1c7bd 1701 * @param string $role ?
c6d15803 1702 * @param int $timestart ?
1703 * @param int $timeend ?
7cf1c7bd 1704 * @return boolean
1705 * @todo Finish documenting this function
1706 */
6e8ca983 1707function add_teacher($userid, $courseid, $editall=1, $role='', $timestart=0, $timeend=0, $enrol='manual') {
7b5944cd 1708 global $CFG;
3041b0f8 1709
61451a36 1710 if ($teacher = get_record('user_teachers', 'userid', $userid, 'course', $courseid)) {
b40bc478 1711 $newteacher = NULL;
1712 $newteacher->id = $teacher->id;
1713 $newteacher->editall = $editall;
6e8ca983 1714 $newteacher->enrol = $enrol;
b40bc478 1715 if ($role) {
1716 $newteacher->role = $role;
1717 }
1718 if ($timestart) {
1719 $newteacher->timestart = $timestart;
3041b0f8 1720 }
b40bc478 1721 if ($timeend) {
1722 $newteacher->timeend = $timeend;
1723 }
1724 return update_record('user_teachers', $newteacher);
3041b0f8 1725 }
61451a36 1726
b0ccd3fb 1727 if (!record_exists('user', 'id', $userid)) {
61451a36 1728 return false; // no such user
1729 }
1730
b0ccd3fb 1731 if (!record_exists('course', 'id', $courseid)) {
61451a36 1732 return false; // no such course
1733 }
1734
1735 $teacher = NULL;
1736 $teacher->userid = $userid;
1737 $teacher->course = $courseid;
1738 $teacher->editall = $editall;
1739 $teacher->role = $role;
5a2dea02 1740 $teacher->timemodified = time();
1741 $newteacher->timestart = $timestart;
1742 $newteacher->timeend = $timeend;
b0ccd3fb 1743 if ($student = get_record('user_students', 'userid', $userid, 'course', $courseid)) {
5a2dea02 1744 $teacher->timestart = $student->timestart;
1745 $teacher->timeend = $student->timeend;
1746 $teacher->timeaccess = $student->timeaccess;
1747 }
61451a36 1748
b0ccd3fb 1749 if (record_exists('user_teachers', 'course', $courseid)) {
61451a36 1750 $teacher->authority = 2;
1751 } else {
1752 $teacher->authority = 1;
1753 }
b0ccd3fb 1754 delete_records('user_students', 'userid', $userid, 'course', $courseid); // Unenrol as student
8f0cd6ef 1755
709f0ec8 1756 /// Add forum subscriptions for new users
7b5944cd 1757 require_once('../mod/forum/lib.php');
1758 forum_add_user($userid, $courseid);
61451a36 1759
b0ccd3fb 1760 return insert_record('user_teachers', $teacher);
61451a36 1761
3041b0f8 1762}
1763
7cf1c7bd 1764/**
1765 * Removes a teacher from a given course (or ALL courses)
1766 * Does not delete the user account
1767 *
c6d15803 1768 * @param int $courseid The id of the course that is being viewed, if any
361855e6 1769 * @param int $userid The id of the user that is being tested against.
7cf1c7bd 1770 * @return boolean
1771 */
3041b0f8 1772function remove_teacher($userid, $courseid=0) {
3041b0f8 1773 if ($courseid) {
9fa49e22 1774 /// First delete any crucial stuff that might still send mail
b0ccd3fb 1775 if ($forums = get_records('forum', 'course', $courseid)) {
9fa49e22 1776 foreach ($forums as $forum) {
b0ccd3fb 1777 delete_records('forum_subscriptions', 'forum', $forum->id, 'userid', $userid);
9fa49e22 1778 }
1779 }
b02193e6 1780
1781 /// Next if the teacher is not registered as a student, but is
1782 /// a member of a group, remove them from the group.
1783 if (!isstudent($courseid, $userid)) {
1784 if ($groups = get_groups($courseid, $userid)) {
1785 foreach ($groups as $group) {
b0ccd3fb 1786 delete_records('groups_members', 'groupid', $group->id, 'userid', $userid);
b02193e6 1787 }
1788 }
1789 }
1790
b0ccd3fb 1791 return delete_records('user_teachers', 'userid', $userid, 'course', $courseid);
57507290 1792 } else {
b0ccd3fb 1793 delete_records('forum_subscriptions', 'userid', $userid);
1794 return delete_records('user_teachers', 'userid', $userid);
57507290 1795 }
f9903ed0 1796}
1797
7cf1c7bd 1798/**
1799 * Add a creator to the site
1800 *
361855e6 1801 * @param int $userid The id of the user that is being tested against.
7cf1c7bd 1802 * @return boolean
1803 */
3041b0f8 1804function add_creator($userid) {
3041b0f8 1805
b0ccd3fb 1806 if (!record_exists('user_admins', 'userid', $userid)) {
1807 if (record_exists('user', 'id', $userid)) {
3041b0f8 1808 $creator->userid = $userid;
b0ccd3fb 1809 return insert_record('user_coursecreators', $creator);
3041b0f8 1810 }
1811 return false;
1812 }
1813 return true;
1814}
1815
7cf1c7bd 1816/**
1817 * Remove a creator from a site
1818 *
1819 * @uses $db
c6d15803 1820 * @param int $userid The id of the user that is being tested against.
7cf1c7bd 1821 * @return boolean
1822 */
3041b0f8 1823function remove_creator($userid) {
3041b0f8 1824 global $db;
1825
b0ccd3fb 1826 return delete_records('user_coursecreators', 'userid', $userid);
3041b0f8 1827}
1828
7cf1c7bd 1829/**
1830 * Add an admin to a site
1831 *
1832 * @uses SITEID
c6d15803 1833 * @param int $userid The id of the user that is being tested against.
7cf1c7bd 1834 * @return boolean
1835 */
3041b0f8 1836function add_admin($userid) {
3041b0f8 1837
b0ccd3fb 1838 if (!record_exists('user_admins', 'userid', $userid)) {
1839 if (record_exists('user', 'id', $userid)) {
3041b0f8 1840 $admin->userid = $userid;
361855e6 1841
f950af3c 1842 // any admin is also a teacher on the site course
222ac91b 1843 if (!record_exists('user_teachers', 'course', SITEID, 'userid', $userid)) {
1844 if (!add_teacher($userid, SITEID)) {
f950af3c 1845 return false;
1846 }
1847 }
361855e6 1848
b0ccd3fb 1849 return insert_record('user_admins', $admin);
3041b0f8 1850 }
1851 return false;
1852 }
1853 return true;
1854}
1855
7cf1c7bd 1856/**
1857 * Removes an admin from a site
1858 *
1859 * @uses $db
1860 * @uses SITEID
c6d15803 1861 * @param int $userid The id of the user that is being tested against.
7cf1c7bd 1862 * @return boolean
1863 */
3041b0f8 1864function remove_admin($userid) {
9fa49e22 1865 global $db;
f9903ed0 1866
f950af3c 1867 // remove also from the list of site teachers
222ac91b 1868 remove_teacher($userid, SITEID);
f950af3c 1869
b0ccd3fb 1870 return delete_records('user_admins', 'userid', $userid);
f9903ed0 1871}
1872
7cf1c7bd 1873/**
1874 * Clear a course out completely, deleting all content
1875 * but don't delete the course itself
1876 *
1877 * @uses $USER
1878 * @uses $SESSION
1879 * @uses $CFG
c6d15803 1880 * @param int $courseid The id of the course that is being viewed
7cf1c7bd 1881 * @param boolean $showfeedback Set this to false to suppress notifications from being printed as the functions performs its steps.
1882 * @return boolean
1883 */
07aeb7b0 1884function remove_course_contents($courseid, $showfeedback=true) {
07aeb7b0 1885
ee23f384 1886 global $CFG, $THEME, $USER, $SESSION;
07aeb7b0 1887
1888 $result = true;
1889
b0ccd3fb 1890 if (! $course = get_record('course', 'id', $courseid)) {
1891 error('Course ID was incorrect (can\'t find it)');
07aeb7b0 1892 }
1893
b0ccd3fb 1894 $strdeleted = get_string('deleted');
07aeb7b0 1895
1896 // First delete every instance of every module
d8ba183c 1897
b0ccd3fb 1898 if ($allmods = get_records('modules') ) {
07aeb7b0 1899 foreach ($allmods as $mod) {
1900 $modname = $mod->name;
b0ccd3fb 1901 $modfile = $CFG->dirroot .'/mod/'. $modname .'/lib.php';
1902 $moddelete = $modname .'_delete_instance'; // Delete everything connected to an instance
1903 $moddeletecourse = $modname .'_delete_course'; // Delete other stray stuff (uncommon)
07aeb7b0 1904 $count=0;
1905 if (file_exists($modfile)) {
1906 include_once($modfile);
1907 if (function_exists($moddelete)) {
b0ccd3fb 1908 if ($instances = get_records($modname, 'course', $course->id)) {
07aeb7b0 1909 foreach ($instances as $instance) {
1910 if ($moddelete($instance->id)) {
1911 $count++;
1912 } else {
b0ccd3fb 1913 notify('Could not delete '. $modname .' instance '. $instance->id .' ('. $instance->name .')');
07aeb7b0 1914 $result = false;
1915 }
1916 }
1917 }
1918 } else {
b0ccd3fb 1919 notify('Function '. $moddelete() .'doesn\'t exist!');
07aeb7b0 1920 $result = false;
1921 }
1922
ca952b03 1923 if (function_exists($moddeletecourse)) {
1924 $moddeletecourse($course);
1925 }
07aeb7b0 1926 }
1927 if ($showfeedback) {
b0ccd3fb 1928 notify($strdeleted .' '. $count .' x '. $modname);
07aeb7b0 1929 }
1930 }
1931 } else {
b0ccd3fb 1932 error('No modules are installed!');
07aeb7b0 1933 }
1934
1935 // Delete any user stuff
1936
b0ccd3fb 1937 if (delete_records('user_students', 'course', $course->id)) {
07aeb7b0 1938 if ($showfeedback) {
b0ccd3fb 1939 notify($strdeleted .' user_students');
07aeb7b0 1940 }
1941 } else {
1942 $result = false;
1943 }
1944
b0ccd3fb 1945 if (delete_records('user_teachers', 'course', $course->id)) {
07aeb7b0 1946 if ($showfeedback) {
b0ccd3fb 1947 notify($strdeleted .' user_teachers');
07aeb7b0 1948 }
1949 } else {
1950 $result = false;
1951 }
1952
082e3ebc 1953 // Delete any groups
1954
b0ccd3fb 1955 if ($groups = get_records('groups', 'courseid', $course->id)) {
082e3ebc 1956 foreach ($groups as $group) {
b0ccd3fb 1957 if (delete_records('groups_members', 'groupid', $group->id)) {
082e3ebc 1958 if ($showfeedback) {
b0ccd3fb 1959 notify($strdeleted .' groups_members');
082e3ebc 1960 }
1961 } else {
1962 $result = false;
1963 }
b0ccd3fb 1964 if (delete_records('groups', 'id', $group->id)) {
082e3ebc 1965 if ($showfeedback) {
b0ccd3fb 1966 notify($strdeleted .' groups');
082e3ebc 1967 }
1968 } else {
1969 $result = false;
1970 }
1971 }
1972 }
1973
1974 // Delete events
1975
b0ccd3fb 1976 if (delete_records('event', 'courseid', $course->id)) {
082e3ebc 1977 if ($showfeedback) {
b0ccd3fb 1978 notify($strdeleted .' event');
082e3ebc 1979 }
1980 } else {
1981 $result = false;
1982 }
1983
07aeb7b0 1984 // Delete logs
1985
b0ccd3fb 1986 if (delete_records('log', 'course', $course->id)) {
07aeb7b0 1987 if ($showfeedback) {
b0ccd3fb 1988 notify($strdeleted .' log');
07aeb7b0 1989 }
1990 } else {
1991 $result = false;
1992 }
1993
1994 // Delete any course stuff
1995
b0ccd3fb 1996 if (delete_records('course_sections', 'course', $course->id)) {
07aeb7b0 1997 if ($showfeedback) {
b0ccd3fb 1998 notify($strdeleted .' course_sections');
07aeb7b0 1999 }
2000 } else {
2001 $result = false;
2002 }
2003
b0ccd3fb 2004 if (delete_records('course_modules', 'course', $course->id)) {
07aeb7b0 2005 if ($showfeedback) {
b0ccd3fb 2006 notify($strdeleted .' course_modules');
07aeb7b0 2007 }
2008 } else {
2009 $result = false;
2010 }
2011
2012 return $result;
2013
2014}
2015
7cf1c7bd 2016/**
2017 * This function will empty a course of USER data as much as
2018/// possible. It will retain the activities and the structure
2019/// of the course.
2020 *
2021 * @uses $USER
2022 * @uses $THEME
2023 * @uses $SESSION
2024 * @uses $CFG
c6d15803 2025 * @param int $courseid The id of the course that is being viewed
7cf1c7bd 2026 * @param boolean $showfeedback Set this to false to suppress notifications from being printed as the functions performs its steps.
2027 * @param boolean $removestudents ?
2028 * @param boolean $removeteachers ?
2029 * @param boolean $removegroups ?
2030 * @param boolean $removeevents ?
2031 * @param boolean $removelogs ?
2032 * @return boolean
2033 * @todo Finish documenting this function
2034 */
3831de52 2035function remove_course_userdata($courseid, $showfeedback=true,
2036 $removestudents=true, $removeteachers=false, $removegroups=true,
2037 $removeevents=true, $removelogs=false) {
3831de52 2038
2039 global $CFG, $THEME, $USER, $SESSION;
2040
2041 $result = true;
2042
b0ccd3fb 2043 if (! $course = get_record('course', 'id', $courseid)) {
2044 error('Course ID was incorrect (can\'t find it)');
3831de52 2045 }
2046
b0ccd3fb 2047 $strdeleted = get_string('deleted');
3831de52 2048
2049 // Look in every instance of every module for data to delete
2050
b0ccd3fb 2051 if ($allmods = get_records('modules') ) {
3831de52 2052 foreach ($allmods as $mod) {
2053 $modname = $mod->name;
b0ccd3fb 2054 $modfile = $CFG->dirroot .'/mod/'. $modname .'/lib.php';
2055 $moddeleteuserdata = $modname .'_delete_userdata'; // Function to delete user data
3831de52 2056 $count=0;
2057 if (file_exists($modfile)) {
2058 @include_once($modfile);
2059 if (function_exists($moddeleteuserdata)) {
2060 $moddeleteuserdata($course, $showfeedback);
2061 }
2062 }
2063 }
2064 } else {
b0ccd3fb 2065 error('No modules are installed!');
3831de52 2066 }
2067
2068 // Delete other stuff
2069
2070 if ($removestudents) {
2071 /// Delete student enrolments
b0ccd3fb 2072 if (delete_records('user_students', 'course', $course->id)) {
3831de52 2073 if ($showfeedback) {
b0ccd3fb 2074 notify($strdeleted .' user_students');
3831de52 2075 }
2076 } else {
2077 $result = false;
2078 }
2079 /// Delete group members (but keep the groups)
b0ccd3fb 2080 if ($groups = get_records('groups', 'courseid', $course->id)) {
3831de52 2081 foreach ($groups as $group) {
b0ccd3fb 2082 if (delete_records('groups_members', 'groupid', $group->id)) {
3831de52 2083 if ($showfeedback) {
b0ccd3fb 2084 notify($strdeleted .' groups_members');
3831de52 2085 }
2086 } else {
2087 $result = false;
2088 }
2089 }
2090 }
2091 }
2092
2093 if ($removeteachers) {
b0ccd3fb 2094 if (delete_records('user_teachers', 'course', $course->id)) {
3831de52 2095 if ($showfeedback) {
b0ccd3fb 2096 notify($strdeleted .' user_teachers');
3831de52 2097 }
2098 } else {
2099 $result = false;
2100 }
2101 }
2102
2103 if ($removegroups) {
b0ccd3fb 2104 if ($groups = get_records('groups', 'courseid', $course->id)) {
3831de52 2105 foreach ($groups as $group) {
b0ccd3fb 2106 if (delete_records('groups', 'id', $group->id)) {
3831de52 2107 if ($showfeedback) {
b0ccd3fb 2108 notify($strdeleted .' groups');
3831de52 2109 }
2110 } else {
2111 $result = false;
2112 }
2113 }
2114 }
2115 }
2116
2117 if ($removeevents) {
b0ccd3fb 2118 if (delete_records('event', 'courseid', $course->id)) {
3831de52 2119 if ($showfeedback) {
b0ccd3fb 2120 notify($strdeleted .' event');
3831de52 2121 }
2122 } else {
2123 $result = false;
2124 }
2125 }
2126
2127 if ($removelogs) {
b0ccd3fb 2128 if (delete_records('log', 'course', $course->id)) {
3831de52 2129 if ($showfeedback) {
b0ccd3fb 2130 notify($strdeleted .' log');
3831de52 2131 }
2132 } else {
2133 $result = false;
2134 }
2135 }
2136
2137 return $result;
2138
2139}
2140
2141
f9903ed0 2142
f374fb10 2143/// GROUPS /////////////////////////////////////////////////////////
d8ba183c 2144
f374fb10 2145
2146/**
2147* Returns a boolean: is the user a member of the given group?
d8ba183c 2148*
dcd338ff 2149* @param type description
7cf1c7bd 2150 * @todo Finish documenting this function
f374fb10 2151*/
2152function ismember($groupid, $userid=0) {
2153 global $USER;
2154
8a2c9076 2155 if (!$groupid) { // No point doing further checks
2156 return false;
2157 }
2158
f374fb10 2159 if (!$userid) {
0d67c514 2160 if (empty($USER->groupmember)) {
2161 return false;
2162 }
2163 foreach ($USER->groupmember as $courseid => $mgroupid) {
2164 if ($mgroupid == $groupid) {
2165 return true;
2166 }
2167 }
2168 return false;
f374fb10 2169 }
2170
b0ccd3fb 2171 return record_exists('groups_members', 'groupid', $groupid, 'userid', $userid);
f374fb10 2172}
2173
4ed533df 2174/**
2175 * Add a user to a group, return true upon success or if user already a group member
2176 *
2177 * @param groupid The group id
2178 * @param userid The user id
2179 * @todo Finish documenting this function
2180 */
2181function add_user_to_group ($groupid, $userid) {
2182 if (ismember($groupid, $userid)) return true;
2183 $record->groupid = $groupid;
2184 $record->userid = $userid;
2185 $record->timeadded = time();
2186 return (insert_record('groups_members', $record) !== false);
2187}
2188
2189
0d67c514 2190/**
c6d15803 2191 * Returns the group ID of the current user in the given course
2192 *
2193 * @uses $USER
2194 * @param int $courseid The course being examined - relates to id field in 'course' table.
7cf1c7bd 2195 * @todo Finish documenting this function
c6d15803 2196 */
0d67c514 2197function mygroupid($courseid) {
2198 global $USER;
2199
2200 if (empty($USER->groupmember[$courseid])) {
2201 return 0;
2202 } else {
2203 return $USER->groupmember[$courseid];
2204 }
2205}
2206
f374fb10 2207/**
c6d15803 2208 * For a given course, and possibly course module, determine
2209 * what the current default groupmode is:
2210 * NOGROUPS, SEPARATEGROUPS or VISIBLEGROUPS
2211 *
89dcb99d 2212 * @param course $course A {@link $COURSE} object
2213 * @param array? $cm A course module object
c6d15803 2214 * @return int A group mode (NOGROUPS, SEPARATEGROUPS or VISIBLEGROUPS)
2215 */
f374fb10 2216function groupmode($course, $cm=null) {
2217
2218 if ($cm and !$course->groupmodeforce) {
2219 return $cm->groupmode;
2220 }
2221 return $course->groupmode;
2222}
2223
2224
2225/**
c6d15803 2226 * Sets the current group in the session variable
2227 *
2228 * @uses $SESSION
2229 * @param int $courseid The course being examined - relates to id field in 'course' table.
2230 * @param int $groupid The group being examined.
2231 * @return int Current group id which was set by this function
7cf1c7bd 2232 * @todo Finish documenting this function
c6d15803 2233 */
f374fb10 2234function set_current_group($courseid, $groupid) {
2235 global $SESSION;
2236
2237 return $SESSION->currentgroup[$courseid] = $groupid;
2238}
2239
2240
2241/**
c6d15803 2242 * Gets the current group for the current user as an id or an object
2243 *
2244 * @uses $CFG
2245 * @uses $SESSION
2246 * @param int $courseid The course being examined - relates to id field in 'course' table.
9f1f6daf 2247 * @param boolean $full If true, the return value is a full record object. If false, just the id of the record.
7cf1c7bd 2248 * @todo Finish documenting this function
c6d15803 2249 */
f374fb10 2250function get_current_group($courseid, $full=false) {
2251 global $SESSION, $USER;
2252
ce04df6b 2253 if (!isset($SESSION->currentgroup[$courseid])) {
f374fb10 2254 if (empty($USER->groupmember[$courseid])) {
8a2c9076 2255 return 0;
f374fb10 2256 } else {
2257 $SESSION->currentgroup[$courseid] = $USER->groupmember[$courseid];
2258 }
2259 }
2260
2261 if ($full) {
0da33e07 2262 return get_record('groups', 'id', $SESSION->currentgroup[$courseid]);
f374fb10 2263 } else {
2264 return $SESSION->currentgroup[$courseid];
2265 }
2266}
2267
0d67c514 2268/**
c6d15803 2269 * A combination function to make it easier for modules
2270 * to set up groups.
2271 *
2272 * It will use a given "groupid" parameter and try to use
2273 * that to reset the current group for the user.
2274 *
2275 * @uses VISIBLEGROUPS
89dcb99d 2276 * @param course $course A {@link $COURSE} object
c6d15803 2277 * @param int $groupmode Either NOGROUPS, SEPARATEGROUPS or VISIBLEGROUPS
2278 * @param int $groupid Will try to use this optional parameter to
2279 * reset the current group for the user
89dcb99d 2280 * @return int|false Returns the current group id or false if error.
7cf1c7bd 2281 * @todo Finish documenting this function
c6d15803 2282 */
eb6147a8 2283function get_and_set_current_group($course, $groupmode, $groupid=-1) {
0d67c514 2284
2285 if (!$groupmode) { // Groups don't even apply
d8ba183c 2286 return false;
0d67c514 2287 }
2288
2289 $currentgroupid = get_current_group($course->id);
2290
eb6147a8 2291 if ($groupid < 0) { // No change was specified
2292 return $currentgroupid;
2293 }
2294
2295 if ($groupid) { // Try to change the current group to this groupid
0d67c514 2296 if ($group = get_record('groups', 'id', $groupid, 'courseid', $course->id)) { // Exists
2297 if (isteacheredit($course->id)) { // Sets current default group
2298 $currentgroupid = set_current_group($course->id, $group->id);
2299
2300 } else if ($groupmode == VISIBLEGROUPS) { // All groups are visible
2301 $currentgroupid = $group->id;
2302 }
2303 }
eb6147a8 2304 } else { // When groupid = 0 it means show ALL groups
2305 if (isteacheredit($course->id)) { // Sets current default group
2306 $currentgroupid = set_current_group($course->id, 0);
2307
2308 } else if ($groupmode == VISIBLEGROUPS) { // All groups are visible
2309 $currentgroupid = 0;
2310 }
0d67c514 2311 }
2312
2313 return $currentgroupid;
2314}
2315
2316
c3cbfe7f 2317/**
c6d15803 2318 * A big combination function to make it easier for modules
2319 * to set up groups.
2320 *
2321 * Terminates if the current user shouldn't be looking at this group
2322 * Otherwise returns the current group if there is one
2323 * Otherwise returns false if groups aren't relevant
2324 *
2325 * @uses SEPARATEGROUPS
2326 * @uses VISIBLEGROUPS
89dcb99d 2327 * @param course $course A {@link $COURSE} object
c6d15803 2328 * @param int $groupmode Either NOGROUPS, SEPARATEGROUPS or VISIBLEGROUPS
2329 * @param string $urlroot ?
7cf1c7bd 2330 * @todo Finish documenting this function
c6d15803 2331 */
c3cbfe7f 2332function setup_and_print_groups($course, $groupmode, $urlroot) {
2333
eb6147a8 2334 if (isset($_GET['group'])) {
2335 $changegroup = $_GET['group']; /// 0 or higher
2336 } else {
2337 $changegroup = -1; /// This means no group change was specified
2338 }
2339
2340 $currentgroup = get_and_set_current_group($course, $groupmode, $changegroup);
c3cbfe7f 2341
eb6147a8 2342 if ($currentgroup === false) {
c3cbfe7f 2343 return false;
2344 }
2345
4b6d8dd5 2346 if ($groupmode == SEPARATEGROUPS and !isteacheredit($course->id) and !$currentgroup) {
2347 print_heading(get_string('notingroup'));
c3cbfe7f 2348 print_footer($course);
2349 exit;
2350 }
2351
2352 if ($groupmode == VISIBLEGROUPS or ($groupmode and isteacheredit($course->id))) {
b0ccd3fb 2353 if ($groups = get_records_menu('groups', 'courseid', $course->id, 'name ASC', 'id,name')) {
eb6147a8 2354 echo '<div align="center">';
c3cbfe7f 2355 print_group_menu($groups, $groupmode, $currentgroup, $urlroot);
eb6147a8 2356 echo '</div>';
c3cbfe7f 2357 }
2358 }
2359
2360 return $currentgroup;
2361}
0d67c514 2362
f374fb10 2363
2364
f9903ed0 2365/// CORRESPONDENCE ////////////////////////////////////////////////
2366
7cf1c7bd 2367/**
2368 * Send an email to a specified user
2369 *
7cf1c7bd 2370 * @uses $CFG
2371 * @uses $_SERVER
c6d15803 2372 * @uses SITEID
89dcb99d 2373 * @param user $user A {@link $USER} object
2374 * @param user $from A {@link $USER} object
7cf1c7bd 2375 * @param string $subject plain text subject line of the email
2376 * @param string $messagetext plain text version of the message
2377 * @param string $messagehtml complete html version of the message (optional)
2378 * @param string $attachment a file on the filesystem, relative to $CFG->dataroot
2379 * @param string $attachname the name of the file (extension indicates MIME)
361855e6 2380 * @param boolean $usetrueaddress determines whether $from email address should
c6d15803 2381 * be sent out. Will be overruled by user profile setting for maildisplay
361855e6 2382 * @return boolean|string Returns "true" if mail was sent OK, "emailstop" if email
c6d15803 2383 * was blocked by user and "false" if there was another sort of error.
7cf1c7bd 2384 */
b0ccd3fb 2385function email_to_user($user, $from, $subject, $messagetext, $messagehtml='', $attachment='', $attachname='', $usetrueaddress=true) {
f9903ed0 2386
f9f4d999 2387 global $CFG, $FULLME;
f9903ed0 2388
0cc6fa6a 2389 global $course; // This is a bit of an ugly hack to be gotten rid of later
2390 if (!empty($course->lang)) { // Course language is defined
2391 $CFG->courselang = $course->lang;
2392 }
2393
b0ccd3fb 2394 include_once($CFG->libdir .'/phpmailer/class.phpmailer.php');
f9903ed0 2395
cadb96f2 2396 if (empty($user)) {
2397 return false;
2398 }
2399
2400 if (!empty($user->emailstop)) {
579dcca4 2401 return 'emailstop';
f9903ed0 2402 }
d8ba183c 2403
f9903ed0 2404 $mail = new phpmailer;
2405
b0ccd3fb 2406 $mail->Version = 'Moodle '. $CFG->version; // mailer version
2407 $mail->PluginDir = $CFG->libdir .'/phpmailer/'; // plugin directory (eg smtp plugin)
562bbe90 2408
98c4eae3 2409
b0ccd3fb 2410 if (current_language() != 'en') {
2411 $mail->CharSet = get_string('thischarset');
98c4eae3 2412 }
2413
b0ccd3fb 2414 if ($CFG->smtphosts == 'qmail') {
62740736 2415 $mail->IsQmail(); // use Qmail system
2416
2417 } else if (empty($CFG->smtphosts)) {
2418 $mail->IsMail(); // use PHP mail() = sendmail
2419
2420 } else {
1e411ffc 2421 $mail->IsSMTP(); // use SMTP directly
57ef3480 2422 if ($CFG->debug > 7) {
b0ccd3fb 2423 echo '<pre>' . "\n";
57ef3480 2424 $mail->SMTPDebug = true;
2425 }
b0ccd3fb 2426 $mail->Host = $CFG->smtphosts; // specify main and backup servers
9f58537a 2427
2428 if ($CFG->smtpuser) { // Use SMTP authentication
2429 $mail->SMTPAuth = true;
2430 $mail->Username = $CFG->smtpuser;
2431 $mail->Password = $CFG->smtppass;
2432 }
7f86ce17 2433 }
f9903ed0 2434
2b97bd71 2435 $adminuser = get_admin();
2436
b0ccd3fb 2437 $mail->Sender = $adminuser->email;
2b97bd71 2438
a402bdcb 2439 if (is_string($from)) { // So we can pass whatever we want if there is need
2440 $mail->From = $CFG->noreplyaddress;
0d8a590a 2441 $mail->FromName = $from;
a402bdcb 2442 } else if ($usetrueaddress and $from->maildisplay) {
b0ccd3fb 2443 $mail->From = $from->email;
6e506bf9 2444 $mail->FromName = fullname($from);
2445 } else {
b0ccd3fb 2446 $mail->From = $CFG->noreplyaddress;
0d8a590a 2447 $mail->FromName = fullname($from);
6e506bf9 2448 }
136dabd8 2449 $mail->Subject = stripslashes($subject);
f9903ed0 2450
b0ccd3fb 2451 $mail->AddAddress($user->email, fullname($user) );
f9903ed0 2452
58d24720 2453 $mail->WordWrap = 79; // set word wrap
f9903ed0 2454
857b798b 2455 if (!empty($from->customheaders)) { // Add custom headers
2456 if (is_array($from->customheaders)) {
2457 foreach ($from->customheaders as $customheader) {
2458 $mail->AddCustomHeader($customheader);
2459 }
2460 } else {
2461 $mail->AddCustomHeader($from->customheaders);
2462 }
b68dca19 2463 }
8f0cd6ef 2464
136dabd8 2465 if ($messagehtml) {
2466 $mail->IsHTML(true);
b0ccd3fb 2467 $mail->Encoding = 'quoted-printable'; // Encoding to use
136dabd8 2468 $mail->Body = $messagehtml;
78681899 2469 $mail->AltBody = "\n$messagetext\n";
136dabd8 2470 } else {
2471 $mail->IsHTML(false);
78681899 2472 $mail->Body = "\n$messagetext\n";
f9903ed0 2473 }
2474
136dabd8 2475 if ($attachment && $attachname) {
2476 if (ereg( "\\.\\." ,$attachment )) { // Security check for ".." in dir path
b0ccd3fb 2477 $mail->AddAddress($adminuser->email, fullname($adminuser) );
2478 $mail->AddStringAttachment('Error in attachment. User attempted to attach a filename with a unsafe name.', 'error.txt', '8bit', 'text/plain');
136dabd8 2479 } else {
b0ccd3fb 2480 include_once($CFG->dirroot .'/files/mimetypes.php');
2481 $mimetype = mimeinfo('type', $attachname);
2482 $mail->AddAttachment($CFG->dataroot .'/'. $attachment, $attachname, 'base64', $mimetype);
136dabd8 2483 }
f9903ed0 2484 }
2485
136dabd8 2486 if ($mail->Send()) {
2487 return true;
2488 } else {
b0ccd3fb 2489 mtrace('ERROR: '. $mail->ErrorInfo);
f9f4d999 2490 add_to_log(SITEID, 'library', 'mailer', $FULLME, 'ERROR: '. $mail->ErrorInfo);
f9903ed0 2491 return false;
2492 }
f9903ed0 2493}
2494
7cf1c7bd 2495/**
2496 * Resets specified user's password and send the new password to the user via email.
2497 *
2498 * @uses $CFG
89dcb99d 2499 * @param user $user A {@link $USER} object
361855e6 2500 * @return boolean|string Returns "true" if mail was sent OK, "emailstop" if email
c6d15803 2501 * was blocked by user and "false" if there was another sort of error.
7cf1c7bd 2502 */
1d881d92 2503function reset_password_and_mail($user) {
2504
2505 global $CFG;
2506
2507 $site = get_site();
2508 $from = get_admin();
2509
2510 $newpassword = generate_password();
2511
b0ccd3fb 2512 if (! set_field('user', 'password', md5($newpassword), 'id', $user->id) ) {
2513 error('Could not set user password!');
1d881d92 2514 }
2515
2516 $a->firstname = $user->firstname;
2517 $a->sitename = $site->fullname;
2518 $a->username = $user->username;
2519 $a->newpassword = $newpassword;
b0ccd3fb 2520 $a->link = $CFG->wwwroot .'/login/change_password.php';
2521 $a->signoff = fullname($from, true).' ('. $from->email .')';
1d881d92 2522
b0ccd3fb 2523 $message = get_string('newpasswordtext', '', $a);
1d881d92 2524
b0ccd3fb 2525 $subject = $site->fullname .': '. get_string('changedpassword');
1d881d92 2526
2527 return email_to_user($user, $from, $subject, $message);
2528
2529}
2530
7cf1c7bd 2531/**
2532 * Send email to specified user with confirmation text and activation link.
2533 *
2534 * @uses $CFG
89dcb99d 2535 * @param user $user A {@link $USER} object
361855e6 2536 * @return boolean|string Returns "true" if mail was sent OK, "emailstop" if email
c6d15803 2537 * was blocked by user and "false" if there was another sort of error.
7cf1c7bd 2538 */
2539 function send_confirmation_email($user) {
1d881d92 2540
2541 global $CFG;
2542
2543 $site = get_site();
2544 $from = get_admin();
2545
2546 $data->firstname = $user->firstname;
2547 $data->sitename = $site->fullname;
b0ccd3fb 2548 $data->link = $CFG->wwwroot .'/login/confirm.php?p='. $user->secret .'&amp;s='. $user->username;
2549 $data->admin = fullname($from) .' ('. $from->email .')';
1d881d92 2550
b0ccd3fb 2551 $message = get_string('emailconfirmation', '', $data);
2552 $subject = get_string('emailconfirmationsubject', '', $site->fullname);
1d881d92 2553
58d24720 2554 $messagehtml = text_to_html($message, false, false, true);
2555
2556 return email_to_user($user, $from, $subject, $message, $messagehtml);
1d881d92 2557
2558}
2559
7cf1c7bd 2560/**
2561 * send_password_change_confirmation_email.
2562 *
c6d15803 2563 * @uses $CFG
89dcb99d 2564 * @param user $user A {@link $USER} object
361855e6 2565 * @return boolean|string Returns "true" if mail was sent OK, "emailstop" if email
c6d15803 2566 * was blocked by user and "false" if there was another sort of error.
7cf1c7bd 2567 * @todo Finish documenting this function
2568 */
eb347b6b 2569function send_password_change_confirmation_email($user) {
2570
2571 global $CFG;
2572
2573 $site = get_site();
2574 $from = get_admin();
2575
2576 $data->firstname = $user->firstname;
2577 $data->sitename = $site->fullname;
b0ccd3fb 2578 $data->link = $CFG->wwwroot .'/login/forgot_password.php?p='. $user->secret .'&amp;s='. $user->username;
2579 $data->admin = fullname($from).' ('. $from->email .')';
eb347b6b 2580
b0ccd3fb 2581 $message = get_string('emailpasswordconfirmation', '', $data);
2582 $subject = get_string('emailpasswordconfirmationsubject', '', $site->fullname);
eb347b6b 2583
2584 return email_to_user($user, $from, $subject, $message);
2585
2586}
2587
7cf1c7bd 2588/**
2589 * Check that an email is allowed. It returns an error message if there
2590 * was a problem.
2591 *
2592 * @param type description
2593 * @todo Finish documenting this function
2594 */
85a1d4c9 2595function email_is_not_allowed($email) {
85a1d4c9 2596
2597 global $CFG;
2598
2599 if (!empty($CFG->allowemailaddresses)) {
2600 $allowed = explode(' ', $CFG->allowemailaddresses);
2601 foreach ($allowed as $allowedpattern) {
2602 $allowedpattern = trim($allowedpattern);
2603 if (!$allowedpattern) {
2604 continue;
2605 }
2606 if (strpos($email, $allowedpattern) !== false) { // Match!
2607 return false;
2608 }
2609 }
b0ccd3fb 2610 return get_string('emailonlyallowed', '', $CFG->allowemailaddresses);
85a1d4c9 2611
2612 } else if (!empty($CFG->denyemailaddresses)) {
2613 $denied = explode(' ', $CFG->denyemailaddresses);
2614 foreach ($denied as $deniedpattern) {
2615 $deniedpattern = trim($deniedpattern);
2616 if (!$deniedpattern) {
2617 continue;
2618 }
2619 if (strpos($email, $deniedpattern) !== false) { // Match!
b0ccd3fb 2620 return get_string('emailnotallowed', '', $CFG->denyemailaddresses);
85a1d4c9 2621 }
2622 }
2623 }
2624
2625 return false;
2626}
1d881d92 2627
136dabd8 2628
f9903ed0 2629/// FILE HANDLING /////////////////////////////////////////////
2630
7cf1c7bd 2631/**
c6d15803 2632 * Create a directory.
7cf1c7bd 2633 *
2634 * @uses $CFG
8c3dba73 2635 * @param string $directory a string of directory names under $CFG->dataroot eg stuff/assignment/1
c6d15803 2636 * param boolean $shownotices If true then notification messages will be printed out on error.
2637 * @return string|false Returns full path to directory if successful, false if not
7cf1c7bd 2638 */
66f9a82c 2639function make_upload_directory($directory, $shownotices=true) {
6b174680 2640
2641 global $CFG;
2642
2643 $currdir = $CFG->dataroot;
fe287429 2644
2e6d4273 2645 umask(0000);
2646
6b174680 2647 if (!file_exists($currdir)) {
2e6d4273 2648 if (! mkdir($currdir, $CFG->directorypermissions)) {
66f9a82c 2649 if ($shownotices) {
b0ccd3fb 2650 notify('ERROR: You need to create the directory '. $currdir .' with web server write access');
66f9a82c 2651 }
6b174680 2652 return false;
2653 }
2765411a 2654 if ($handle = fopen($currdir.'/.htaccess', 'w')) { // For safety
2655 @fwrite($handle, "deny from all\r\n");
2656 @fclose($handle);
2657 }
6b174680 2658 }
2659
b0ccd3fb 2660 $dirarray = explode('/', $directory);
6b174680 2661
2662 foreach ($dirarray as $dir) {
b0ccd3fb 2663 $currdir = $currdir .'/'. $dir;
6b174680 2664 if (! file_exists($currdir)) {
2e6d4273 2665 if (! mkdir($currdir, $CFG->directorypermissions)) {
66f9a82c 2666 if ($shownotices) {
b0ccd3fb 2667 notify('ERROR: Could not find or create a directory ('. $currdir .')');
66f9a82c 2668 }
6b174680 2669 return false;
2670 }
d99bab2d 2671 //@chmod($currdir, $CFG->directorypermissions); // Just in case mkdir didn't do it
6b174680 2672 }
2673 }
2674
2675 return $currdir;
2676}
1e03c552 2677
7cf1c7bd 2678/**
2679 * Makes an upload directory for a particular module.
2680 *
2681 * @uses $CFG
c6d15803 2682 * @param int $courseid The id of the course in question - maps to id field of 'course' table.
2683 * @return string|false Returns full path to directory if successful, false if not
7cf1c7bd 2684 * @todo Finish documenting this function
2685 */
ca4f8eb8 2686function make_mod_upload_directory($courseid) {
2687 global $CFG;
2688
b0ccd3fb 2689 if (! $moddata = make_upload_directory($courseid .'/'. $CFG->moddata)) {
ca4f8eb8 2690 return false;
2691 }
2692
b0ccd3fb 2693 $strreadme = get_string('readme');
ca4f8eb8 2694
b0ccd3fb 2695 if (file_exists($CFG->dirroot .'/lang/'. $CFG->lang .'/docs/module_files.txt')) {
2696 copy($CFG->dirroot .'/lang/'. $CFG->lang .'/docs/module_files.txt', $moddata .'/'. $strreadme .'.txt');
ca4f8eb8 2697 } else {
b0ccd3fb 2698 copy($CFG->dirroot .'/lang/en/docs/module_files.txt', $moddata .'/'. $strreadme .'.txt');
ca4f8eb8 2699 }
2700 return $moddata;
2701}
2702
7cf1c7bd 2703/**
c6d15803 2704 * Returns current name of file on disk if it exists.
7cf1c7bd 2705 *
c6d15803 2706 * @param string $newfile File to be verified
2707 * @return string Current name of file on disk if true
7cf1c7bd 2708 * @todo Finish documenting this function
2709 */
44e2d2bb 2710function valid_uploaded_file($newfile) {
9c9f7d77 2711 if (empty($newfile)) {
b0ccd3fb 2712 return '';
9c9f7d77 2713 }
44e2d2bb 2714 if (is_uploaded_file($newfile['tmp_name']) and $newfile['size'] > 0) {
2715 return $newfile['tmp_name'];
2716 } else {
b0ccd3fb 2717 return '';
44e2d2bb 2718 }
2719}
2720
7cf1c7bd 2721/**
2722 * Returns the maximum size for uploading files.
2723 *
2724 * There are seven possible upload limits:
2725 * 1. in Apache using LimitRequestBody (no way of checking or changing this)
2726 * 2. in php.ini for 'upload_max_filesize' (can not be changed inside PHP)
2727 * 3. in .htaccess for 'upload_max_filesize' (can not be changed inside PHP)
2728 * 4. in php.ini for 'post_max_size' (can not be changed inside PHP)
2729 * 5. by the Moodle admin in $CFG->maxbytes
2730 * 6. by the teacher in the current course $course->maxbytes
2731 * 7. by the teacher for the current module, eg $assignment->maxbytes
2732 *
2733 * These last two are passed to this function as arguments (in bytes).
2734 * Anything defined as 0 is ignored.
2735 * The smallest of all the non-zero numbers is returned.
2736 *
c6d15803 2737 * @param int $sizebytes ?
2738 * @param int $coursebytes Current course $course->maxbytes (in bytes)
2739 * @param int $modulebytes Current module ->maxbytes (in bytes)
2740 * @return int The maximum size for uploading files.
7cf1c7bd 2741 * @todo Finish documenting this function
2742 */
4909e176 2743function get_max_upload_file_size($sitebytes=0, $coursebytes=0, $modulebytes=0) {
4909e176 2744
b0ccd3fb 2745 if (! $filesize = ini_get('upload_max_filesize')) {
2746 $filesize = '5M';
44e2d2bb 2747 }
4909e176 2748 $minimumsize = get_real_size($filesize);
2749
b0ccd3fb 2750 if ($postsize = ini_get('post_max_size')) {
316ebf78 2751 $postsize = get_real_size($postsize);
2752 if ($postsize < $minimumsize) {
2753 $minimumsize = $postsize;
2754 }
2755 }
2756
4909e176 2757 if ($sitebytes and $sitebytes < $minimumsize) {
2758 $minimumsize = $sitebytes;
2759 }
2760
2761 if ($coursebytes and $coursebytes < $minimumsize) {
2762 $minimumsize = $coursebytes;
2763 }
2764
2765 if ($modulebytes and $modulebytes < $minimumsize) {
2766 $minimumsize = $modulebytes;
2767 }
2768
2769 return $minimumsize;
2770}
2771
7cf1c7bd 2772/**
2773 * Related to the above function - this function returns an
2774 * array of possible sizes in an array, translated to the
2775 * local language.
2776 *
c6d15803 2777 * @uses SORT_NUMERIC
2778 * @param int $sizebytes ?
2779 * @param int $coursebytes Current course $course->maxbytes (in bytes)
2780 * @param int $modulebytes Current module ->maxbytes (in bytes)
2781 * @return int
7cf1c7bd 2782 * @todo Finish documenting this function
2783 */
4909e176 2784function get_max_upload_sizes($sitebytes=0, $coursebytes=0, $modulebytes=0) {
4909e176 2785
2786 if (!$maxsize = get_max_upload_file_size($sitebytes, $coursebytes, $modulebytes)) {
2787 return array();
2788 }
2789
2790 $filesize[$maxsize] = display_size($maxsize);
2791
d8ba183c 2792 $sizelist = array(10240, 51200, 102400, 512000, 1048576, 2097152,
4909e176 2793 5242880, 10485760, 20971520, 52428800, 104857600);
2794
2795 foreach ($sizelist as $sizebytes) {
2796 if ($sizebytes < $maxsize) {
2797 $filesize[$sizebytes] = display_size($sizebytes);
2798 }
2799 }
2800
2801 krsort($filesize, SORT_NUMERIC);
2802
2803 return $filesize;
44e2d2bb 2804}
2805
7cf1c7bd 2806/**
2807 * If there has been an error uploading a file, print the appropriate error message
2808 * Numerical constants used as constant definitions not added until PHP version 4.2.0
2809 *
c6d15803 2810 * $filearray is a 1-dimensional sub-array of the $_FILES array
7cf1c7bd 2811 * eg $filearray = $_FILES['userfile1']
361855e6 2812 * If left empty then the first element of the $_FILES array will be used
8c3dba73 2813 *
c6d15803 2814 * @uses $_FILES
2815 * @param array $filearray A 1-dimensional sub-array of the $_FILES array
2816 * @param boolean $returnerror ?
7cf1c7bd 2817 * @return boolean
2818 * @todo Finish documenting this function
2819 */
ebd52396 2820function print_file_upload_error($filearray = '', $returnerror = false) {
ebd52396 2821
2822 if ($filearray == '' or !isset($filearray['error'])) {
2823
2824 if (empty($_FILES)) return false;
2825
2826 $files = $_FILES; /// so we don't mess up the _FILES array for subsequent code
2827 $filearray = array_shift($files); /// use first element of array
2828 }
2829
2830 switch ($filearray['error']) {
2831
2832 case 0: // UPLOAD_ERR_OK
2833 if ($filearray['size'] > 0) {
2834 $errmessage = get_string('uploadproblem', $filearray['name']);
2835 } else {
2836 $errmessage = get_string('uploadnofilefound'); /// probably a dud file name
2837 }
2838 break;
2839
2840 case 1: // UPLOAD_ERR_INI_SIZE
2841 $errmessage = get_string('uploadserverlimit');
2842 break;
2843
2844 case 2: // UPLOAD_ERR_FORM_SIZE
2845 $errmessage = get_string('uploadformlimit');
2846 break;
2847
2848 case 3: // UPLOAD_ERR_PARTIAL
2849 $errmessage = get_string('uploadpartialfile');
2850 break;
2851
2852 case 4: // UPLOAD_ERR_NO_FILE
2853 $errmessage = get_string('uploadnofilefound');
2854 break;
2855
2856 default:
2857 $errmessage = get_string('uploadproblem', $filearray['name']);
2858 }
2859
2860 if ($returnerror) {
2861 return $errmessage;
2862 } else {
2863 notify($errmessage);
2864 return true;
2865 }
2866
2867}
2868
7cf1c7bd 2869/**
2870 * Returns an array with all the filenames in
2871 * all subdirectories, relative to the given rootdir.
2872 * If excludefile is defined, then that file/directory is ignored
2873 * If getdirs is true, then (sub)directories are included in the output
2874 * If getfiles is true, then files are included in the output
2875 * (at least one of these must be true!)
2876 *
c6d15803 2877 * @param string $rootdir ?
2878 * @param string $excludefile If defined then the specified file/directory is ignored
2879 * @param boolean $descend ?
2880 * @param boolean $getdirs If true then (sub)directories are included in the output
2881 * @param boolean $getfiles If true then files are included in the output
2882 * @return array An array with all the filenames in
2883 * all subdirectories, relative to the given rootdir
2884 * @todo Finish documenting this function. Add examples of $excludefile usage.
7cf1c7bd 2885 */
b0ccd3fb 2886function get_directory_list($rootdir, $excludefile='', $descend=true, $getdirs=false, $getfiles=true) {
f9903ed0 2887
2888 $dirs = array();
f9903ed0 2889
16a5602c 2890 if (!$getdirs and !$getfiles) { // Nothing to show
12407705 2891 return $dirs;
2892 }
2893
16a5602c 2894 if (!is_dir($rootdir)) { // Must be a directory
2895 return $dirs;
2896 }
2897
2898 if (!$dir = opendir($rootdir)) { // Can't open it for some reason
d897cae4 2899 return $dirs;
2900 }
2901
81fcd0f0 2902 while (false !== ($file = readdir($dir))) {
b35e8568 2903 $firstchar = substr($file, 0, 1);
b0ccd3fb 2904 if ($firstchar == '.' or $file == 'CVS' or $file == $excludefile) {
b35e8568 2905 continue;
2906 }
b0ccd3fb 2907 $fullfile = $rootdir .'/'. $file;
2908 if (filetype($fullfile) == 'dir') {
16a5602c 2909 if ($getdirs) {
55fd8177 2910 $dirs[] = $file;
2911 }
bf5c2e84 2912 if ($descend) {
16a5602c 2913 $subdirs = get_directory_list($fullfile, $excludefile, $descend, $getdirs, $getfiles);
bf5c2e84 2914 foreach ($subdirs as $subdir) {
b0ccd3fb 2915 $dirs[] = $file .'/'. $subdir;
bf5c2e84 2916 }
f9903ed0 2917 }
16a5602c 2918 } else if ($getfiles) {
b35e8568 2919 $dirs[] = $file;
f9903ed0 2920 }
2921 }
44e2d2bb 2922 closedir($dir);
f9903ed0 2923
774ab660 2924 asort($dirs);
2925
f9903ed0 2926 return $dirs;
2927}
2928
7cf1c7bd 2929/**
2930 * Adds up all the files in a directory and works out the size.
2931 *
2932 * @param string $rootdir ?
2933 * @param string $excludefile ?
c6d15803 2934 * @return array
7cf1c7bd 2935 * @todo Finish documenting this function
2936 */
b0ccd3fb 2937function get_directory_size($rootdir, $excludefile='') {
16a5602c 2938
2939 $size = 0;
2940
2941 if (!is_dir($rootdir)) { // Must be a directory
2942 return $dirs;
2943 }
2944
b5b90f26 2945 if (!$dir = @opendir($rootdir)) { // Can't open it for some reason
16a5602c 2946 return $dirs;
2947 }
2948
2949 while (false !== ($file = readdir($dir))) {
2950 $firstchar = substr($file, 0, 1);
b0ccd3fb 2951 if ($firstchar == '.' or $file == 'CVS' or $file == $excludefile) {
16a5602c 2952 continue;
2953 }
b0ccd3fb 2954 $fullfile = $rootdir .'/'. $file;
2955 if (filetype($fullfile) == 'dir') {
16a5602c 2956 $size += get_directory_size($fullfile, $excludefile);
2957 } else {
2958 $size += filesize($fullfile);
2959 }
2960 }
2961 closedir($dir);
2962
2963 return $size;
2964}
2965
7cf1c7bd 2966/**
2967 * Converts numbers like 10M into bytes.
2968 *
7cf1c7bd 2969 * @param mixed $size The size to be converted
2970 * @return mixed
2971 */
989bfa9d 2972function get_real_size($size=0) {
989bfa9d 2973 if (!$size) {
d8ba183c 2974 return 0;
989bfa9d 2975 }
2976 $scan['MB'] = 1048576;
64efda84 2977 $scan['Mb'] = 1048576;
989bfa9d 2978 $scan['M'] = 1048576;
266a416e 2979 $scan['m'] = 1048576;
989bfa9d 2980 $scan['KB'] = 1024;
64efda84 2981 $scan['Kb'] = 1024;
989bfa9d 2982 $scan['K'] = 1024;
266a416e 2983 $scan['k'] = 1024;
989bfa9d 2984
2985 while (list($key) = each($scan)) {
2986 if ((strlen($size)>strlen($key))&&(substr($size, strlen($size) - strlen($key))==$key)) {
2987 $size = substr($size, 0, strlen($size) - strlen($key)) * $scan[$key];
2988 break;
2989 }
2990 }
2991 return $size;
2992}
2993
7cf1c7bd 2994/**
2995 * Converts bytes into display form
2996 *
c6d15803 2997 * @param string $size ?
2998 * @return string
89dcb99d 2999 * @staticvar string $gb Localized string for size in gigabytes
3000 * @staticvar string $mb Localized string for size in megabytes
3001 * @staticvar string $kb Localized string for size in kilobytes
3002 * @staticvar string $b Localized string for size in bytes
c6d15803 3003 * @todo Finish documenting this function. Verify return type.
7cf1c7bd 3004 */
44e2d2bb 3005function display_size($size) {
4909e176 3006
7cf1c7bd 3007 static $gb, $mb, $kb, $b;
4909e176 3008
3009 if (empty($gb)) {
3010 $gb = get_string('sizegb');
3011 $mb = get_string('sizemb');
3012 $kb = get_string('sizekb');
3013 $b = get_string('sizeb');
3014 }
3015
44e2d2bb 3016 if ($size >= 1073741824) {
4909e176 3017 $size = round($size / 1073741824 * 10) / 10 . $gb;
44e2d2bb 3018 } else if ($size >= 1048576) {
4909e176 3019 $size = round($size / 1048576 * 10) / 10 . $mb;
44e2d2bb 3020 } else if ($size >= 1024) {
4909e176 3021 $size = round($size / 1024 * 10) / 10 . $kb;
d8ba183c 3022 } else {
b0ccd3fb 3023 $size = $size .' '. $b;
44e2d2bb 3024 }
3025 return $size;
3026}
3027
7cf1c7bd 3028/**
8c3dba73 3029 * Cleans a given filename by removing suspicious or troublesome characters
3030 * Only these are allowed:
3031 * alphanumeric _ - .
7cf1c7bd 3032 *
c6d15803 3033 * @param string $string ?
3034 * @return string
7cf1c7bd 3035 * @todo Finish documenting this function
3036 */
6b174680 3037function clean_filename($string) {
b0ccd3fb 3038 $string = eregi_replace("\.\.+", '', $string);
8644437d 3039 $string = preg_replace('/[^\.a-zA-Z\d\_-]/','_', $string ); // only allowed chars
b0ccd3fb 3040 $string = eregi_replace("_+", '_', $string);
c6d15803 3041 return $string;
6b174680 3042}
3043
3044
1180c6dc 3045/// STRING TRANSLATION ////////////////////////////////////////
3046
8c3dba73 3047/**
3048 * Returns the code for the current language
3049 *
3050 * @uses $CFG
3051 * @param $USER
3052 * @param $SESSION
3053 * @return string
3054 */
4bfa92e7 3055function current_language() {
3db3acfb 3056 global $CFG, $USER, $SESSION;
4bfa92e7 3057
e5415d58 3058 if (!empty($CFG->courselang)) { // Course language can override all other settings for this page
b3153e4b 3059 return $CFG->courselang;
3060
e5415d58 3061 } else if (!empty($SESSION->lang)) { // Session language can override other settings
3db3acfb 3062 return $SESSION->lang;
3063
e5415d58 3064 } else if (!empty($USER->lang)) { // User language can override site language
4bfa92e7 3065 return $USER->lang;
3db3acfb 3066
4bfa92e7 3067 } else {
3068 return $CFG->lang;
3069 }
3070}
bcc83c41 3071
8c3dba73 3072/**
76115562 3073 * Prints out a translated string.
3074 *
3075 * Prints out a translated string using the return value from the {@link get_string()} function.
3076 *
3077 * Example usage of this function when the string is in the moodle.php file:<br>
3078 * <code>
3079 * echo '<strong>';
3080 * print_string('wordforstudent');
3081 * echo '</strong>';
3082 * </code>
3083 *
3084 * Example usage of this function when the string is not in the moodle.php file:<br>
3085 * <code>
3086 * echo '<h1>';
3087 * print_string('typecourse', 'calendar');
3088 * echo '</h1>';
3089 * </code>
3090 *
3091 * @param string $identifier The key identifier for the localized string
3092 * @param string $module The module where the key identifier is stored. If none is specified then moodle.php is used.
3093 * @param mixed $a An object, string or number that can be used
3094 * within translation strings
361855e6 3095 */
b0ccd3fb 3096function print_string($identifier, $module='', $a=NULL) {
9fa49e22 3097 echo get_string($identifier, $module, $a);
3098}
3099
8c3dba73 3100/**
76115562 3101 * Returns a localized string.
3102 *
3103 * Returns the translated string specified by $identifier as
8c3dba73 3104 * for $module. Uses the same format files as STphp.
3105 * $a is an object, string or number that can be used
3106 * within translation strings
3107 *
3108 * eg "hello \$a->firstname \$a->lastname"
3109 * or "hello \$a"
3110 *
76115562 3111 * If you would like to directly echo the localized string use
3112 * the function {@link print_string()}
3113 *
3114 * Example usage of this function involves finding the string you would
3115 * like a local equivalent of and using its identifier and module information
3116 * to retrive it.<br>
3117 * If you open moodle/lang/en/moodle.php and look near line 1031
3118 * you will find a string to prompt a user for their word for student
3119 * <code>
3120 * $string['wordforstudent'] = 'Your word for Student';
3121 * </code>
361855e6 3122 * So if you want to display the string 'Your word for student'
3123 * in any language that supports it on your site
76115562 3124 * you just need to use the identifier 'wordforstudent'
3125 * <code>
3126 * $mystring = '<strong>'. get_string('wordforstudent') .'</strong>';
3127or
3128 * </code>
361855e6 3129 * If the string you want is in another file you'd take a slightly
3130 * different approach. Looking in moodle/lang/en/calendar.php you find
76115562 3131 * around line 75:
3132 * <code>
3133 * $string['typecourse'] = 'Course event';
3134 * </code>
361855e6 3135 * If you want to display the string "Course event" in any language
3136 * supported you would use the identifier 'typecourse' and the module 'calendar'
76115562 3137 * (because it is in the file calendar.php):
3138 * <code>
3139 * $mystring = '<h1>'. get_string('typecourse', 'calendar') .'</h1>';
3140 * </code>
3141 *
3142 * As a last resort, should the identifier fail to map to a string
3143 * the returned string will be [[ $identifier ]]
3144 *
8c3dba73 3145 * @uses $CFG
76115562 3146 * @param string $identifier The key identifier for the localized string
3147 * @param string $module The module where the key identifier is stored. If none is specified then moodle.php is used.
3148 * @param mixed $a An object, string or number that can be used
3149 * within translation strings
3150 * @return string The localized string.
8c3dba73 3151 */
361855e6 3152function get_string($identifier, $module='', $a=NULL) {
1180c6dc 3153
4bfa92e7 3154 global $CFG;
1180c6dc 3155
e11dc9b6 3156 global $course; /// Not a nice hack, but quick
ac8abb5f 3157 if (empty($CFG->courselang)) {
3158 if (!empty($course->lang)) {
3159 $CFG->courselang = $course->lang;
3160 }
e11dc9b6 3161 }
3162
4bfa92e7 3163 $lang = current_language();
1180c6dc 3164
b0ccd3fb 3165 if ($module == '') {
3166 $module = 'moodle';
1180c6dc 3167 }
3168
d0dc2b98 3169/// Define the two or three major locations of language strings for this module
1180c6dc 3170
d0dc2b98 3171 $locations = array( $CFG->dataroot.'/lang/', $CFG->dirroot.'/lang/' );
3172 if ($module != 'moodle') {
3173 $locations[] = $CFG->dirroot .'/mod/'.$module.'/lang/';
1180c6dc 3174 }
3175
d0dc2b98 3176/// First check all the normal locations for the string in the current language
cdac797c 3177
d0dc2b98 3178 foreach ($locations as $location) {
dc0426bd 3179 $langfile = $location.$lang.'/'.$module.'.php';
cdac797c 3180 if (file_exists($langfile)) {
3181 if ($result = get_string_from_file($identifier, $langfile, "\$resultstring")) {
3182 eval($result);
3183 return $resultstring;
3184 }
3185 }
3186 }
1180c6dc 3187
d0dc2b98 3188/// If the preferred language was English we can abort now
b0ccd3fb 3189 if ($lang == 'en') {
3190 return '[['. $identifier .']]';
b947c69a 3191 }
1180c6dc 3192
d0dc2b98 3193/// Is a parent language defined? If so, try to find this string in a parent language file
d8ba183c 3194
d0dc2b98 3195 foreach ($locations as $location) {
dc0426bd 3196 $langfile = $location.$lang.'/moodle.php';
3197 if (file_exists($langfile)) {
3198 if ($result = get_string_from_file('parentlanguage', $langfile, "\$parentlang")) {
3199 eval($result);
3200 if (!empty($parentlang)) { // found it!
3201 $langfile = $location.$parentlang.'/'.$module.'.php';
3202 if (file_exists($langfile)) {
3203 if ($result = get_string_from_file($identifier, $langfile, "\$resultstring")) {
3204 eval($result);
3205 return $resultstring;
3206 }
d0dc2b98 3207 }
b947c69a 3208 }
1180c6dc 3209 }
3210 }
3211 }
b947c69a 3212
d0dc2b98 3213/// Our only remaining option is to try English
b947c69a 3214
d0dc2b98 3215 foreach ($locations as $location) {
dc0426bd 3216 $langfile = $location.'en/'.$module.'.php';
b947c69a 3217
cdac797c 3218 if (file_exists($langfile)) {
3219 if ($result = get_string_from_file($identifier, $langfile, "\$resultstring")) {
3220 eval($result);
3221 return $resultstring;
3222 }
3223 }
3224 }
3225
d0dc2b98 3226 return '[['.$identifier.']]'; // Last resort
1180c6dc 3227}
3228
8c3dba73 3229/**
c6d15803 3230 * This function is only used from {@link get_string()}.
8c3dba73 3231 *
da72d76d 3232 * @internal Only used from get_string, not meant to be public API
c6d15803 3233 * @param string $identifier ?
3234 * @param string $langfile ?
3235 * @param string $destination ?
3236 * @return string|false ?
89dcb99d 3237 * @staticvar array $strings Localized strings
da72d76d 3238 * @access private
c6d15803 3239 * @todo Finish documenting this function.
8c3dba73 3240 */
1180c6dc 3241function get_string_from_file($identifier, $langfile, $destination) {
2b32bddd 3242
3243 static $strings; // Keep the strings cached in memory.
3244
3245 if (empty($strings[$langfile])) {
a32c99e2 3246 $string = array();
2b32bddd 3247 include ($langfile);
3248 $strings[$langfile] = $string;
3249 } else {
3250 $string = &$strings[$langfile];
3251 }
1180c6dc 3252
3253 if (!isset ($string[$identifier])) {
3254 return false;
3255 }
3256
b0ccd3fb 3257 return $destination .'= sprintf("'. $string[$identifier] .'");';
1180c6dc 3258}
f9903ed0 3259
8c3dba73 3260/**
3261 * Converts an array of strings to their localized value.
3262 *
3263 * @param array $array An array of strings
3264 * @param string $module The language module that these strings can be found in.
3265 * @return string
3266 */
9d3c795c 3267function get_strings($array, $module='') {
9d3c795c 3268
3269 $string = NULL;
3270 foreach ($array as $item) {
3271 $string->$item = get_string