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