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