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