PHP 4 assignment is by value so course_header (containing edited names)
[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 */
e1ecf0a0 38
bbd3f2c4 39/// CONSTANTS (Encased in phpdoc proper comments)/////////////////////////
f374fb10 40
6b94a807 41/**
42 * Used by some scripts to check they are being called by Moodle
43 */
44define('MOODLE_INTERNAL', true);
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
bbd3f2c4 61/// Date and time constants ///
7a5672c9 62/**
2f87145b 63 * Time constant - the number of seconds in a week
7a5672c9 64 */
361855e6 65define('WEEKSECS', 604800);
2f87145b 66
67/**
68 * Time constant - the number of seconds in a day
69 */
7a5672c9 70define('DAYSECS', 86400);
2f87145b 71
72/**
73 * Time constant - the number of seconds in an hour
74 */
7a5672c9 75define('HOURSECS', 3600);
2f87145b 76
77/**
78 * Time constant - the number of seconds in a minute
79 */
7a5672c9 80define('MINSECS', 60);
2f87145b 81
82/**
83 * Time constant - the number of minutes in a day
84 */
7a5672c9 85define('DAYMINS', 1440);
2f87145b 86
87/**
88 * Time constant - the number of minutes in an hour
89 */
7a5672c9 90define('HOURMINS', 60);
f9903ed0 91
c59733ef 92/// Parameter constants - every call to optional_param(), required_param() ///
93/// or clean_param() should have a specified type of parameter. //////////////
94
e0d346ff 95/**
038ba6aa 96 * PARAM_RAW specifies a parameter that is not cleaned/processed in any way;
97 * originally was 0, but changed because we need to detect unknown
98 * parameter types and swiched order in clean_param().
e0d346ff 99 */
038ba6aa 100define('PARAM_RAW', 666);
bbd3f2c4 101
102/**
c59733ef 103 * PARAM_CLEAN - obsoleted, please try to use more specific type of parameter.
104 * It was one of the first types, that is why it is abused so much ;-)
bbd3f2c4 105 */
2ae28153 106define('PARAM_CLEAN', 0x0001);
bbd3f2c4 107
108/**
c59733ef 109 * PARAM_INT - integers only, use when expecting only numbers.
bbd3f2c4 110 */
2ae28153 111define('PARAM_INT', 0x0002);
bbd3f2c4 112
113/**
114 * PARAM_INTEGER - an alias for PARAM_INT
115 */
116define('PARAM_INTEGER', 0x0002);
117
9dae915a 118/**
119 * PARAM_NUMBER - a real/floating point number.
120 */
121define('PARAM_NUMBER', 0x000a);
122
bbd3f2c4 123/**
c59733ef 124 * PARAM_ALPHA - contains only english letters.
bbd3f2c4 125 */
2ae28153 126define('PARAM_ALPHA', 0x0004);
bbd3f2c4 127
128/**
c59733ef 129 * PARAM_ACTION - an alias for PARAM_ALPHA, use for various actions in formas and urls
130 * @TODO: should we alias it to PARAM_ALPHANUM ?
bbd3f2c4 131 */
132define('PARAM_ACTION', 0x0004);
133
134/**
c59733ef 135 * PARAM_FORMAT - an alias for PARAM_ALPHA, use for names of plugins, formats, etc.
136 * @TODO: should we alias it to PARAM_ALPHANUM ?
bbd3f2c4 137 */
138define('PARAM_FORMAT', 0x0004);
139
140/**
c59733ef 141 * PARAM_NOTAGS - all html tags are stripped from the text. Do not abuse this type.
bbd3f2c4 142 */
2ae28153 143define('PARAM_NOTAGS', 0x0008);
bbd3f2c4 144
31f26796 145 /**
c4ea5e78 146 * PARAM_MULTILANG - alias of PARAM_TEXT.
31f26796 147 */
148define('PARAM_MULTILANG', 0x0009);
149
c4ea5e78 150 /**
151 * PARAM_TEXT - general plain text compatible with multilang filter, no other html tags.
152 */
153define('PARAM_TEXT', 0x0009);
154
bbd3f2c4 155/**
c59733ef 156 * PARAM_FILE - safe file name, all dangerous chars are stripped, protects against XSS, SQL injections and directory traversals
bbd3f2c4 157 */
2ae28153 158define('PARAM_FILE', 0x0010);
bbd3f2c4 159
160/**
c59733ef 161 * PARAM_PATH - safe relative path name, all dangerous chars are stripped, protects against XSS, SQL injections and directory traversals
162 * note: the leading slash is not removed, window drive letter is not allowed
bbd3f2c4 163 */
2ae28153 164define('PARAM_PATH', 0x0020);
bbd3f2c4 165
166/**
c59733ef 167 * PARAM_HOST - expected fully qualified domain name (FQDN) or an IPv4 dotted quad (IP address)
bbd3f2c4 168 */
169define('PARAM_HOST', 0x0040);
170
171/**
c59733ef 172 * PARAM_URL - expected properly formatted URL.
bbd3f2c4 173 */
2ae28153 174define('PARAM_URL', 0x0080);
bbd3f2c4 175
176/**
c59733ef 177 * PARAM_LOCALURL - expected properly formatted URL as well as one that refers to the local server itself. (NOT orthogonal to the others! Implies PARAM_URL!)
bbd3f2c4 178 */
179define('PARAM_LOCALURL', 0x0180);
180
181/**
c59733ef 182 * PARAM_CLEANFILE - safe file name, all dangerous and regional chars are removed,
183 * use when you want to store a new file submitted by students
bbd3f2c4 184 */
14d6c233 185define('PARAM_CLEANFILE',0x0200);
e0d346ff 186
8bd3fad3 187/**
c59733ef 188 * PARAM_ALPHANUM - expected numbers and letters only.
bbd3f2c4 189 */
190define('PARAM_ALPHANUM', 0x0400);
191
192/**
c59733ef 193 * PARAM_BOOL - converts input into 0 or 1, use for switches in forms and urls.
bbd3f2c4 194 */
195define('PARAM_BOOL', 0x0800);
196
197/**
c59733ef 198 * PARAM_CLEANHTML - cleans submitted HTML code and removes slashes
199 * note: do not forget to addslashes() before storing into database!
bbd3f2c4 200 */
201define('PARAM_CLEANHTML',0x1000);
202
203/**
c59733ef 204 * PARAM_ALPHAEXT the same contents as PARAM_ALPHA plus the chars in quotes: "/-_" allowed,
205 * suitable for include() and require()
206 * @TODO: should we rename this function to PARAM_SAFEDIRS??
bbd3f2c4 207 */
208define('PARAM_ALPHAEXT', 0x2000);
209
210/**
c59733ef 211 * PARAM_SAFEDIR - safe directory name, suitable for include() and require()
bbd3f2c4 212 */
213define('PARAM_SAFEDIR', 0x4000);
214
0e4af166 215/**
216 * PARAM_SEQUENCE - expects a sequence of numbers like 8 to 1,5,6,4,6,8,9. Numbers and comma only.
217 */
218define('PARAM_SEQUENCE', 0x8000);
219
03d820c7 220/**
221 * PARAM_PEM - Privacy Enhanced Mail format
222 */
223define('PARAM_PEM', 0x10000);
224
225/**
226 * PARAM_BASE64 - Base 64 encoded format
227 */
228define('PARAM_BASE64', 0x20000);
229
230
bbd3f2c4 231/// Page types ///
232/**
233 * PAGE_COURSE_VIEW is a definition of a page type. For more information on the page class see moodle/lib/pagelib.php.
8bd3fad3 234 */
235define('PAGE_COURSE_VIEW', 'course-view');
8bd3fad3 236
7eb0b60a 237/// Debug levels ///
238/** no warnings at all */
239define ('DEBUG_NONE', 0);
240/** E_ERROR | E_PARSE */
241define ('DEBUG_MINIMAL', 5);
242/** E_ERROR | E_PARSE | E_WARNING | E_NOTICE */
243define ('DEBUG_NORMAL', 15);
244/** E_ALL without E_STRICT and E_RECOVERABLE_ERROR for now */
245define ('DEBUG_ALL', 2047);
246/** DEBUG_ALL with extra Moodle debug messages - (DEBUG_ALL | 32768) */
247define ('DEBUG_DEVELOPER', 34815);
bbd3f2c4 248
feaf5d06 249/**
250 * Blog access level constant declaration
251 */
252define ('BLOG_USER_LEVEL', 1);
253define ('BLOG_GROUP_LEVEL', 2);
254define ('BLOG_COURSE_LEVEL', 3);
255define ('BLOG_SITE_LEVEL', 4);
256define ('BLOG_GLOBAL_LEVEL', 5);
257
258
03d820c7 259
9fa49e22 260/// PARAMETER HANDLING ////////////////////////////////////////////////////
6b174680 261
e0d346ff 262/**
361855e6 263 * Returns a particular value for the named variable, taken from
264 * POST or GET. If the parameter doesn't exist then an error is
e0d346ff 265 * thrown because we require this variable.
266 *
361855e6 267 * This function should be used to initialise all required values
268 * in a script that are based on parameters. Usually it will be
e0d346ff 269 * used like this:
270 * $id = required_param('id');
271 *
a083b93c 272 * @param string $parname the name of the page parameter we want
273 * @param int $type expected type of parameter
e0d346ff 274 * @return mixed
275 */
a083b93c 276function required_param($parname, $type=PARAM_CLEAN) {
e0d346ff 277
5d7a9f56 278 // detect_unchecked_vars addition
279 global $CFG;
280 if (!empty($CFG->detect_unchecked_vars)) {
281 global $UNCHECKED_VARS;
a083b93c 282 unset ($UNCHECKED_VARS->vars[$parname]);
5d7a9f56 283 }
284
a083b93c 285 if (isset($_POST[$parname])) { // POST has precedence
286 $param = $_POST[$parname];
287 } else if (isset($_GET[$parname])) {
288 $param = $_GET[$parname];
e0d346ff 289 } else {
a083b93c 290 error('A required parameter ('.$parname.') was missing');
e0d346ff 291 }
292
a083b93c 293 return clean_param($param, $type);
e0d346ff 294}
295
296/**
361855e6 297 * Returns a particular value for the named variable, taken from
e0d346ff 298 * POST or GET, otherwise returning a given default.
299 *
361855e6 300 * This function should be used to initialise all optional values
301 * in a script that are based on parameters. Usually it will be
e0d346ff 302 * used like this:
303 * $name = optional_param('name', 'Fred');
304 *
a083b93c 305 * @param string $parname the name of the page parameter we want
e0d346ff 306 * @param mixed $default the default value to return if nothing is found
a083b93c 307 * @param int $type expected type of parameter
e0d346ff 308 * @return mixed
309 */
a083b93c 310function optional_param($parname, $default=NULL, $type=PARAM_CLEAN) {
e0d346ff 311
5d7a9f56 312 // detect_unchecked_vars addition
313 global $CFG;
314 if (!empty($CFG->detect_unchecked_vars)) {
315 global $UNCHECKED_VARS;
a083b93c 316 unset ($UNCHECKED_VARS->vars[$parname]);
5d7a9f56 317 }
318
a083b93c 319 if (isset($_POST[$parname])) { // POST has precedence
320 $param = $_POST[$parname];
321 } else if (isset($_GET[$parname])) {
322 $param = $_GET[$parname];
e0d346ff 323 } else {
324 return $default;
325 }
326
a083b93c 327 return clean_param($param, $type);
e0d346ff 328}
329
330/**
361855e6 331 * Used by {@link optional_param()} and {@link required_param()} to
332 * clean the variables and/or cast to specific types, based on
e0d346ff 333 * an options field.
bbd3f2c4 334 * <code>
335 * $course->format = clean_param($course->format, PARAM_ALPHA);
336 * $selectedgrade_item = clean_param($selectedgrade_item, PARAM_CLEAN);
337 * </code>
e0d346ff 338 *
bbd3f2c4 339 * @uses $CFG
340 * @uses PARAM_CLEAN
341 * @uses PARAM_INT
342 * @uses PARAM_INTEGER
343 * @uses PARAM_ALPHA
344 * @uses PARAM_ALPHANUM
345 * @uses PARAM_NOTAGS
f4f65990 346 * @uses PARAM_ALPHAEXT
bbd3f2c4 347 * @uses PARAM_BOOL
348 * @uses PARAM_SAFEDIR
349 * @uses PARAM_CLEANFILE
350 * @uses PARAM_FILE
351 * @uses PARAM_PATH
352 * @uses PARAM_HOST
353 * @uses PARAM_URL
354 * @uses PARAM_LOCALURL
355 * @uses PARAM_CLEANHTML
0e4af166 356 * @uses PARAM_SEQUENCE
e0d346ff 357 * @param mixed $param the variable we are cleaning
a083b93c 358 * @param int $type expected format of param after cleaning.
e0d346ff 359 * @return mixed
360 */
a083b93c 361function clean_param($param, $type) {
e0d346ff 362
7744ea12 363 global $CFG;
364
80bfd470 365 if (is_array($param)) { // Let's loop
366 $newparam = array();
367 foreach ($param as $key => $value) {
a083b93c 368 $newparam[$key] = clean_param($value, $type);
80bfd470 369 }
370 return $newparam;
371 }
372
a083b93c 373 switch ($type) {
96e98ea6 374 case PARAM_RAW: // no cleaning at all
375 return $param;
376
a083b93c 377 case PARAM_CLEAN: // General HTML cleaning, try to use more specific type if possible
378 if (is_numeric($param)) {
379 return $param;
380 }
381 $param = stripslashes($param); // Needed for kses to work fine
382 $param = clean_text($param); // Sweep for scripts, etc
383 return addslashes($param); // Restore original request parameter slashes
3af57507 384
a083b93c 385 case PARAM_CLEANHTML: // prepare html fragment for display, do not store it into db!!
386 $param = stripslashes($param); // Remove any slashes
387 $param = clean_text($param); // Sweep for scripts, etc
388 return trim($param);
e0d346ff 389
a083b93c 390 case PARAM_INT:
391 return (int)$param; // Convert to integer
e0d346ff 392
9dae915a 393 case PARAM_NUMBER:
394 return (float)$param; // Convert to integer
395
a083b93c 396 case PARAM_ALPHA: // Remove everything not a-z
397 return eregi_replace('[^a-zA-Z]', '', $param);
e0d346ff 398
a083b93c 399 case PARAM_ALPHANUM: // Remove everything not a-zA-Z0-9
400 return eregi_replace('[^A-Za-z0-9]', '', $param);
f24148ef 401
a083b93c 402 case PARAM_ALPHAEXT: // Remove everything not a-zA-Z/_-
403 return eregi_replace('[^a-zA-Z/_-]', '', $param);
0ed442f8 404
0e4af166 405 case PARAM_SEQUENCE: // Remove everything not 0-9,
406 return eregi_replace('[^0-9,]', '', $param);
407
a083b93c 408 case PARAM_BOOL: // Convert to 1 or 0
409 $tempstr = strtolower($param);
eb59ac27 410 if ($tempstr == 'on' or $tempstr == 'yes' ) {
a083b93c 411 $param = 1;
eb59ac27 412 } else if ($tempstr == 'off' or $tempstr == 'no') {
a083b93c 413 $param = 0;
414 } else {
415 $param = empty($param) ? 0 : 1;
416 }
417 return $param;
f24148ef 418
a083b93c 419 case PARAM_NOTAGS: // Strip all tags
420 return strip_tags($param);
3af57507 421
c4ea5e78 422 case PARAM_TEXT: // leave only tags needed for multilang
31f26796 423 return clean_param(strip_tags($param, '<lang><span>'), PARAM_CLEAN);
424
a083b93c 425 case PARAM_SAFEDIR: // Remove everything not a-zA-Z0-9_-
426 return eregi_replace('[^a-zA-Z0-9_-]', '', $param);
95bfd207 427
a083b93c 428 case PARAM_CLEANFILE: // allow only safe characters
429 return clean_filename($param);
14d6c233 430
a083b93c 431 case PARAM_FILE: // Strip all suspicious characters from filename
432 $param = ereg_replace('[[:cntrl:]]|[<>"`\|\':\\/]', '', $param);
433 $param = ereg_replace('\.\.+', '', $param);
434 if($param == '.') {
371a2ed0 435 $param = '';
436 }
a083b93c 437 return $param;
438
439 case PARAM_PATH: // Strip all suspicious characters from file path
440 $param = str_replace('\\\'', '\'', $param);
441 $param = str_replace('\\"', '"', $param);
442 $param = str_replace('\\', '/', $param);
443 $param = ereg_replace('[[:cntrl:]]|[<>"`\|\':]', '', $param);
444 $param = ereg_replace('\.\.+', '', $param);
445 $param = ereg_replace('//+', '/', $param);
446 return ereg_replace('/(\./)+', '/', $param);
447
448 case PARAM_HOST: // allow FQDN or IPv4 dotted quad
449 preg_replace('/[^\.\d\w-]/','', $param ); // only allowed chars
450 // match ipv4 dotted quad
451 if (preg_match('/(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})/',$param, $match)){
452 // confirm values are ok
453 if ( $match[0] > 255
454 || $match[1] > 255
455 || $match[3] > 255
456 || $match[4] > 255 ) {
457 // hmmm, what kind of dotted quad is this?
458 $param = '';
459 }
460 } elseif ( preg_match('/^[\w\d\.-]+$/', $param) // dots, hyphens, numbers
461 && !preg_match('/^[\.-]/', $param) // no leading dots/hyphens
462 && !preg_match('/[\.-]$/', $param) // no trailing dots/hyphens
463 ) {
464 // all is ok - $param is respected
465 } else {
466 // all is not ok...
467 $param='';
468 }
469 return $param;
7744ea12 470
a083b93c 471 case PARAM_URL: // allow safe ftp, http, mailto urls
472 include_once($CFG->dirroot . '/lib/validateurlsyntax.php');
5301205a 473 if (!empty($param) && validateUrlSyntax($param, 's?H?S?F?E?u-P-a?I?p?f?q?r?')) {
a083b93c 474 // all is ok, param is respected
d2a9f7cc 475 } else {
a083b93c 476 $param =''; // not really ok
477 }
478 return $param;
479
480 case PARAM_LOCALURL: // allow http absolute, root relative and relative URLs within wwwroot
481 clean_param($param, PARAM_URL);
482 if (!empty($param)) {
483 if (preg_match(':^/:', $param)) {
484 // root-relative, ok!
485 } elseif (preg_match('/^'.preg_quote($CFG->wwwroot, '/').'/i',$param)) {
486 // absolute, and matches our wwwroot
7744ea12 487 } else {
a083b93c 488 // relative - let's make sure there are no tricks
489 if (validateUrlSyntax($param, 's-u-P-a-p-f+q?r?')) {
490 // looks ok.
491 } else {
492 $param = '';
493 }
d2a9f7cc 494 }
7744ea12 495 }
a083b93c 496 return $param;
03d820c7 497 case PARAM_PEM:
498 $param = trim($param);
499 // PEM formatted strings may contain letters/numbers and the symbols
500 // forward slash: /
501 // plus sign: +
502 // equal sign: =
503 // , surrounded by BEGIN and END CERTIFICATE prefix and suffixes
504 if (preg_match('/^-----BEGIN CERTIFICATE-----([\s\w\/\+=]+)-----END CERTIFICATE-----$/', trim($param), $matches)) {
505 list($wholething, $body) = $matches;
506 unset($wholething, $matches);
507 $b64 = clean_param($body, PARAM_BASE64);
508 if (!empty($b64)) {
509 return "-----BEGIN CERTIFICATE-----\n$b64\n-----END CERTIFICATE-----\n";
510 } else {
511 return '';
512 }
513 }
514 return '';
515 case PARAM_BASE64:
516 if (!empty($param)) {
517 // PEM formatted strings may contain letters/numbers and the symbols
518 // forward slash: /
519 // plus sign: +
520 // equal sign: =
03d820c7 521 if (0 >= preg_match('/^([\s\w\/\+=]+)$/', trim($param))) {
522 return '';
523 }
524 $lines = preg_split('/[\s]+/', $param, -1, PREG_SPLIT_NO_EMPTY);
525 // Each line of base64 encoded data must be 64 characters in
526 // length, except for the last line which may be less than (or
527 // equal to) 64 characters long.
528 for ($i=0, $j=count($lines); $i < $j; $i++) {
529 if ($i + 1 == $j) {
530 if (64 < strlen($lines[$i])) {
531 return '';
532 }
533 continue;
534 }
7744ea12 535
03d820c7 536 if (64 != strlen($lines[$i])) {
537 return '';
538 }
539 }
540 return implode("\n",$lines);
541 } else {
542 return '';
543 }
a083b93c 544 default: // throw error, switched parameters in optional_param or another serious problem
545 error("Unknown parameter type: $type");
2ae28153 546 }
e0d346ff 547}
548
6b174680 549
7a530277 550
7cf1c7bd 551/**
552 * Set a key in global configuration
553 *
89dcb99d 554 * Set a key/value pair in both this session's {@link $CFG} global variable
7cf1c7bd 555 * and in the 'config' database table for future sessions.
e1ecf0a0 556 *
557 * Can also be used to update keys for plugin-scoped configs in config_plugin table.
558 * In that case it doesn't affect $CFG.
7cf1c7bd 559 *
560 * @param string $name the key to set
9cdb766d 561 * @param string $value the value to set (without magic quotes)
a4080313 562 * @param string $plugin (optional) the plugin scope
7cf1c7bd 563 * @uses $CFG
564 * @return bool
565 */
a4080313 566function set_config($name, $value, $plugin=NULL) {
9fa49e22 567/// No need for get_config because they are usually always available in $CFG
70812e39 568
42282810 569 global $CFG;
570
a4080313 571 if (empty($plugin)) {
572 $CFG->$name = $value; // So it's defined for this invocation at least
e1ecf0a0 573
a4080313 574 if (get_field('config', 'name', 'name', $name)) {
9cdb766d 575 return set_field('config', 'value', addslashes($value), 'name', $name);
a4080313 576 } else {
9cdb766d 577 $config = new object();
a4080313 578 $config->name = $name;
9cdb766d 579 $config->value = addslashes($value);
a4080313 580 return insert_record('config', $config);
581 }
582 } else { // plugin scope
583 if ($id = get_field('config_plugins', 'id', 'name', $name, 'plugin', $plugin)) {
9cdb766d 584 return set_field('config_plugins', 'value', addslashes($value), 'id', $id);
a4080313 585 } else {
9cdb766d 586 $config = new object();
587 $config->plugin = addslashes($plugin);
a4080313 588 $config->name = $name;
f855cdad 589 $config->value = addslashes($value);
a4080313 590 return insert_record('config_plugins', $config);
591 }
592 }
593}
594
595/**
e1ecf0a0 596 * Get configuration values from the global config table
a4080313 597 * or the config_plugins table.
598 *
599 * If called with no parameters it will do the right thing
600 * generating $CFG safely from the database without overwriting
e1ecf0a0 601 * existing values.
a4080313 602 *
9220fba5 603 * If called with 2 parameters it will return a $string single
604 * value or false of the value is not found.
605 *
e1ecf0a0 606 * @param string $plugin
607 * @param string $name
a4080313 608 * @uses $CFG
609 * @return hash-like object or single value
610 *
611 */
612function get_config($plugin=NULL, $name=NULL) {
7cf1c7bd 613
a4080313 614 global $CFG;
dfc9ba9b 615
a4080313 616 if (!empty($name)) { // the user is asking for a specific value
617 if (!empty($plugin)) {
9220fba5 618 return get_field('config_plugins', 'value', 'plugin' , $plugin, 'name', $name);
a4080313 619 } else {
9220fba5 620 return get_field('config', 'value', 'name', $name);
a4080313 621 }
622 }
623
624 // the user is after a recordset
625 if (!empty($plugin)) {
626 if ($configs=get_records('config_plugins', 'plugin', $plugin, '', 'name,value')) {
627 $configs = (array)$configs;
628 $localcfg = array();
629 foreach ($configs as $config) {
630 $localcfg[$config->name] = $config->value;
631 }
632 return (object)$localcfg;
633 } else {
634 return false;
635 }
d897cae4 636 } else {
a4080313 637 // this was originally in setup.php
638 if ($configs = get_records('config')) {
639 $localcfg = (array)$CFG;
640 foreach ($configs as $config) {
641 if (!isset($localcfg[$config->name])) {
642 $localcfg[$config->name] = $config->value;
643 } else {
e1ecf0a0 644 if ($localcfg[$config->name] != $config->value ) {
a4080313 645 // complain if the DB has a different
646 // value than config.php does
647 error_log("\$CFG->{$config->name} in config.php ({$localcfg[$config->name]}) overrides database setting ({$config->value})");
648 }
649 }
650 }
e1ecf0a0 651
a4080313 652 $localcfg = (object)$localcfg;
653 return $localcfg;
654 } else {
655 // preserve $CFG if DB returns nothing or error
656 return $CFG;
657 }
e1ecf0a0 658
39917a09 659 }
39917a09 660}
661
b0270f84 662/**
663 * Removes a key from global configuration
664 *
665 * @param string $name the key to set
666 * @param string $plugin (optional) the plugin scope
667 * @uses $CFG
668 * @return bool
669 */
670function unset_config($name, $plugin=NULL) {
671
672 global $CFG;
673
674 unset($CFG->$name);
675
676 if (empty($plugin)) {
677 return delete_records('config', 'name', $name);
678 } else {
679 return delete_records('config_plugins', 'name', $name, 'plugin', $plugin);
680 }
681}
682
a4080313 683
7cf1c7bd 684/**
685 * Refresh current $USER session global variable with all their current preferences.
686 * @uses $USER
687 */
70812e39 688function reload_user_preferences() {
70812e39 689
690 global $USER;
691
070e2616 692 if(empty($USER) || empty($USER->id)) {
693 return false;
694 }
695
d8ba183c 696 unset($USER->preference);
70812e39 697
698 if ($preferences = get_records('user_preferences', 'userid', $USER->id)) {
699 foreach ($preferences as $preference) {
700 $USER->preference[$preference->name] = $preference->value;
701 }
4586d60c 702 } else {
703 //return empty preference array to hold new values
704 $USER->preference = array();
c6d15803 705 }
70812e39 706}
707
7cf1c7bd 708/**
709 * Sets a preference for the current user
710 * Optionally, can set a preference for a different user object
711 * @uses $USER
68fbd8e1 712 * @todo Add a better description and include usage examples. Add inline links to $USER and user functions in above line.
713
7cf1c7bd 714 * @param string $name The key to set as preference for the specified user
715 * @param string $value The value to set forthe $name key in the specified user's record
c6d15803 716 * @param int $userid A moodle user ID
bbd3f2c4 717 * @return bool
7cf1c7bd 718 */
13af52a6 719function set_user_preference($name, $value, $otheruser=NULL) {
70812e39 720
721 global $USER;
722
13af52a6 723 if (empty($otheruser)){
724 if (!empty($USER) && !empty($USER->id)) {
070e2616 725 $userid = $USER->id;
13af52a6 726 } else {
070e2616 727 return false;
728 }
13af52a6 729 } else {
730 $userid = $otheruser;
d35757eb 731 }
732
70812e39 733 if (empty($name)) {
734 return false;
735 }
736
a3f1f815 737 if ($preference = get_record('user_preferences', 'userid', $userid, 'name', $name)) {
b0ccd3fb 738 if (set_field('user_preferences', 'value', $value, 'id', $preference->id)) {
29c7e083 739 if ($userid == $USER->id) {
070e2616 740 $USER->preference[$name] = $value;
741 }
066af654 742 return true;
743 } else {
744 return false;
745 }
70812e39 746
747 } else {
a3f1f815 748 $preference->userid = $userid;
70812e39 749 $preference->name = $name;
750 $preference->value = (string)$value;
066af654 751 if (insert_record('user_preferences', $preference)) {
29c7e083 752 if ($userid == $USER->id) {
070e2616 753 $USER->preference[$name] = $value;
754 }
70812e39 755 return true;
756 } else {
757 return false;
758 }
759 }
760}
761
6eb3e776 762/**
763 * Unsets a preference completely by deleting it from the database
764 * Optionally, can set a preference for a different user id
765 * @uses $USER
766 * @param string $name The key to unset as preference for the specified user
c6d15803 767 * @param int $userid A moodle user ID
bbd3f2c4 768 * @return bool
6eb3e776 769 */
770function unset_user_preference($name, $userid=NULL) {
771
772 global $USER;
773
361855e6 774 if (empty($userid)){
070e2616 775 if(!empty($USER) && !empty($USER->id)) {
776 $userid = $USER->id;
777 }
778 else {
779 return false;
780 }
6eb3e776 781 }
782
49d005ee 783 //Delete the preference from $USER
784 if (isset($USER->preference[$name])) {
785 unset($USER->preference[$name]);
786 }
e1ecf0a0 787
49d005ee 788 //Then from DB
6eb3e776 789 return delete_records('user_preferences', 'userid', $userid, 'name', $name);
790}
791
792
7cf1c7bd 793/**
794 * Sets a whole array of preferences for the current user
795 * @param array $prefarray An array of key/value pairs to be set
c6d15803 796 * @param int $userid A moodle user ID
bbd3f2c4 797 * @return bool
7cf1c7bd 798 */
a3f1f815 799function set_user_preferences($prefarray, $userid=NULL) {
800
801 global $USER;
70812e39 802
803 if (!is_array($prefarray) or empty($prefarray)) {
804 return false;
805 }
806
361855e6 807 if (empty($userid)){
108adee2 808 if (!empty($USER) && !empty($USER->id)) {
809 $userid = NULL; // Continue with the current user below
810 } else {
811 return false; // No-one to set!
070e2616 812 }
a3f1f815 813 }
814
70812e39 815 $return = true;
816 foreach ($prefarray as $name => $value) {
070e2616 817 // The order is important; if the test for return is done first, then
818 // if one function call fails all the remaining ones will be "optimized away"
a3f1f815 819 $return = set_user_preference($name, $value, $userid) and $return;
70812e39 820 }
821 return $return;
822}
823
7cf1c7bd 824/**
825 * If no arguments are supplied this function will return
361855e6 826 * all of the current user preferences as an array.
7cf1c7bd 827 * If a name is specified then this function
828 * attempts to return that particular preference value. If
829 * none is found, then the optional value $default is returned,
830 * otherwise NULL.
831 * @param string $name Name of the key to use in finding a preference value
832 * @param string $default Value to be returned if the $name key is not set in the user preferences
c6d15803 833 * @param int $userid A moodle user ID
7cf1c7bd 834 * @uses $USER
835 * @return string
836 */
a3f1f815 837function get_user_preferences($name=NULL, $default=NULL, $userid=NULL) {
70812e39 838
839 global $USER;
840
a3f1f815 841 if (empty($userid)) { // assume current user
842 if (empty($USER->preference)) {
843 return $default; // Default value (or NULL)
844 }
845 if (empty($name)) {
846 return $USER->preference; // Whole array
847 }
848 if (!isset($USER->preference[$name])) {
849 return $default; // Default value (or NULL)
850 }
851 return $USER->preference[$name]; // The single value
852
853 } else {
854 $preference = get_records_menu('user_preferences', 'userid', $userid, 'name', 'name,value');
855
856 if (empty($name)) {
857 return $preference;
858 }
859 if (!isset($preference[$name])) {
860 return $default; // Default value (or NULL)
861 }
862 return $preference[$name]; // The single value
70812e39 863 }
70812e39 864}
865
866
9fa49e22 867/// FUNCTIONS FOR HANDLING TIME ////////////////////////////////////////////
39917a09 868
7cf1c7bd 869/**
c6d15803 870 * Given date parts in user time produce a GMT timestamp.
7cf1c7bd 871 *
68fbd8e1 872 * @param int $year The year part to create timestamp of
873 * @param int $month The month part to create timestamp of
874 * @param int $day The day part to create timestamp of
875 * @param int $hour The hour part to create timestamp of
876 * @param int $minute The minute part to create timestamp of
877 * @param int $second The second part to create timestamp of
878 * @param float $timezone ?
879 * @param bool $applydst ?
e34d817e 880 * @return int timestamp
7cf1c7bd 881 * @todo Finish documenting this function
882 */
9f1f6daf 883function make_timestamp($year, $month=1, $day=1, $hour=0, $minute=0, $second=0, $timezone=99, $applydst=true) {
39917a09 884
dddb014a 885 $timezone = get_user_timezone_offset($timezone);
886
94e34118 887 if (abs($timezone) > 13) {
68fbd8e1 888 $time = mktime((int)$hour, (int)$minute, (int)$second, (int)$month, (int)$day, (int)$year);
03c17ddf 889 } else {
68fbd8e1 890 $time = gmmktime((int)$hour, (int)$minute, (int)$second, (int)$month, (int)$day, (int)$year);
196f2619 891 $time = usertime($time, $timezone);
28c66824 892 if($applydst) {
893 $time -= dst_offset_on($time);
894 }
9f1f6daf 895 }
896
196f2619 897 return $time;
85cafb3e 898
39917a09 899}
900
7cf1c7bd 901/**
902 * Given an amount of time in seconds, returns string
903 * formatted nicely as months, days, hours etc as needed
904 *
2f87145b 905 * @uses MINSECS
906 * @uses HOURSECS
907 * @uses DAYSECS
c6d15803 908 * @param int $totalsecs ?
909 * @param array $str ?
89dcb99d 910 * @return string
7cf1c7bd 911 * @todo Finish documenting this function
912 */
913 function format_time($totalsecs, $str=NULL) {
c7e3ac2a 914
6b174680 915 $totalsecs = abs($totalsecs);
c7e3ac2a 916
8dbed6be 917 if (!$str) { // Create the str structure the slow way
b0ccd3fb 918 $str->day = get_string('day');
919 $str->days = get_string('days');
920 $str->hour = get_string('hour');
921 $str->hours = get_string('hours');
922 $str->min = get_string('min');
923 $str->mins = get_string('mins');
924 $str->sec = get_string('sec');
925 $str->secs = get_string('secs');
8dbed6be 926 }
927
7a5672c9 928 $days = floor($totalsecs/DAYSECS);
929 $remainder = $totalsecs - ($days*DAYSECS);
930 $hours = floor($remainder/HOURSECS);
931 $remainder = $remainder - ($hours*HOURSECS);
932 $mins = floor($remainder/MINSECS);
933 $secs = $remainder - ($mins*MINSECS);
8dbed6be 934
935 $ss = ($secs == 1) ? $str->sec : $str->secs;
936 $sm = ($mins == 1) ? $str->min : $str->mins;
937 $sh = ($hours == 1) ? $str->hour : $str->hours;
938 $sd = ($days == 1) ? $str->day : $str->days;
939
b0ccd3fb 940 $odays = '';
941 $ohours = '';
942 $omins = '';
943 $osecs = '';
9c9f7d77 944
b0ccd3fb 945 if ($days) $odays = $days .' '. $sd;
946 if ($hours) $ohours = $hours .' '. $sh;
947 if ($mins) $omins = $mins .' '. $sm;
948 if ($secs) $osecs = $secs .' '. $ss;
6b174680 949
b0ccd3fb 950 if ($days) return $odays .' '. $ohours;
951 if ($hours) return $ohours .' '. $omins;
952 if ($mins) return $omins .' '. $osecs;
953 if ($secs) return $osecs;
954 return get_string('now');
6b174680 955}
f9903ed0 956
7cf1c7bd 957/**
958 * Returns a formatted string that represents a date in user time
959 * <b>WARNING: note that the format is for strftime(), not date().</b>
960 * Because of a bug in most Windows time libraries, we can't use
961 * the nicer %e, so we have to use %d which has leading zeroes.
962 * A lot of the fuss in the function is just getting rid of these leading
963 * zeroes as efficiently as possible.
361855e6 964 *
8c3dba73 965 * If parameter fixday = true (default), then take off leading
7cf1c7bd 966 * zero from %d, else mantain it.
967 *
2f87145b 968 * @uses HOURSECS
e34d817e 969 * @param int $date timestamp in GMT
970 * @param string $format strftime format
d2a9f7cc 971 * @param float $timezone
bbd3f2c4 972 * @param bool $fixday If true (default) then the leading
c6d15803 973 * zero from %d is removed. If false then the leading zero is mantained.
974 * @return string
7cf1c7bd 975 */
b0ccd3fb 976function userdate($date, $format='', $timezone=99, $fixday = true) {
7a302afc 977
1ac7ee24 978 global $CFG;
979
980 static $strftimedaydatetime;
102dc313 981
b0ccd3fb 982 if ($format == '') {
1ac7ee24 983 if (empty($strftimedaydatetime)) {
984 $strftimedaydatetime = get_string('strftimedaydatetime');
985 }
986 $format = $strftimedaydatetime;
5fa51a39 987 }
035cdbff 988
c3a3c5b8 989 if (!empty($CFG->nofixday)) { // Config.php can force %d not to be fixed.
990 $fixday = false;
991 } else if ($fixday) {
992 $formatnoday = str_replace('%d', 'DD', $format);
61ae5d36 993 $fixday = ($formatnoday != $format);
994 }
dcde9f02 995
88ec5b7c 996 $date += dst_offset_on($date);
85351042 997
494b9296 998 $timezone = get_user_timezone_offset($timezone);
102dc313 999
1000 if (abs($timezone) > 13) { /// Server time
d2a9f7cc 1001 if ($fixday) {
102dc313 1002 $datestring = strftime($formatnoday, $date);
1003 $daystring = str_replace(' 0', '', strftime(' %d', $date));
1004 $datestring = str_replace('DD', $daystring, $datestring);
1005 } else {
1006 $datestring = strftime($format, $date);
1007 }
88ec5b7c 1008 } else {
102dc313 1009 $date += (int)($timezone * 3600);
1010 if ($fixday) {
1011 $datestring = gmstrftime($formatnoday, $date);
1012 $daystring = str_replace(' 0', '', gmstrftime(' %d', $date));
1013 $datestring = str_replace('DD', $daystring, $datestring);
1014 } else {
1015 $datestring = gmstrftime($format, $date);
1016 }
88ec5b7c 1017 }
102dc313 1018
fb773106 1019/// If we are running under Windows convert from windows encoding to UTF-8
1020/// (because it's impossible to specify UTF-8 to fetch locale info in Win32)
11f7b25d 1021
fb773106 1022 if ($CFG->ostype == 'WINDOWS') {
11f7b25d 1023 if ($localewincharset = get_string('localewincharset')) {
1024 $textlib = textlib_get_instance();
810944af 1025 $datestring = $textlib->convert($datestring, $localewincharset, 'utf-8');
11f7b25d 1026 }
1027 }
1028
035cdbff 1029 return $datestring;
873960de 1030}
1031
7cf1c7bd 1032/**
196f2619 1033 * Given a $time timestamp in GMT (seconds since epoch),
c6d15803 1034 * returns an array that represents the date in user time
7cf1c7bd 1035 *
2f87145b 1036 * @uses HOURSECS
196f2619 1037 * @param int $time Timestamp in GMT
68fbd8e1 1038 * @param float $timezone ?
c6d15803 1039 * @return array An array that represents the date in user time
7cf1c7bd 1040 * @todo Finish documenting this function
1041 */
196f2619 1042function usergetdate($time, $timezone=99) {
6b174680 1043
494b9296 1044 $timezone = get_user_timezone_offset($timezone);
a36166d3 1045
e34d817e 1046 if (abs($timezone) > 13) { // Server time
ed1f69b0 1047 return getdate($time);
d2a9f7cc 1048 }
1049
e34d817e 1050 // There is no gmgetdate so we use gmdate instead
02f0527d 1051 $time += dst_offset_on($time);
e34d817e 1052 $time += intval((float)$timezone * HOURSECS);
3bba1e6e 1053
1054 $datestring = gmstrftime('%S_%M_%H_%d_%m_%Y_%w_%j_%A_%B', $time);
02f0527d 1055
9f1f6daf 1056 list(
1057 $getdate['seconds'],
1058 $getdate['minutes'],
1059 $getdate['hours'],
1060 $getdate['mday'],
1061 $getdate['mon'],
1062 $getdate['year'],
1063 $getdate['wday'],
1064 $getdate['yday'],
1065 $getdate['weekday'],
1066 $getdate['month']
3bba1e6e 1067 ) = explode('_', $datestring);
9f1f6daf 1068
d2d6171f 1069 return $getdate;
d552ead0 1070}
1071
7cf1c7bd 1072/**
1073 * Given a GMT timestamp (seconds since epoch), offsets it by
1074 * the timezone. eg 3pm in India is 3pm GMT - 7 * 3600 seconds
1075 *
2f87145b 1076 * @uses HOURSECS
c6d15803 1077 * @param int $date Timestamp in GMT
e34d817e 1078 * @param float $timezone
c6d15803 1079 * @return int
7cf1c7bd 1080 */
d552ead0 1081function usertime($date, $timezone=99) {
a36166d3 1082
494b9296 1083 $timezone = get_user_timezone_offset($timezone);
2665e47a 1084
0431bd7c 1085 if (abs($timezone) > 13) {
d552ead0 1086 return $date;
1087 }
7a5672c9 1088 return $date - (int)($timezone * HOURSECS);
d552ead0 1089}
1090
8c3dba73 1091/**
1092 * Given a time, return the GMT timestamp of the most recent midnight
1093 * for the current user.
1094 *
e34d817e 1095 * @param int $date Timestamp in GMT
1096 * @param float $timezone ?
c6d15803 1097 * @return ?
8c3dba73 1098 */
edf7fe8c 1099function usergetmidnight($date, $timezone=99) {
edf7fe8c 1100
494b9296 1101 $timezone = get_user_timezone_offset($timezone);
edf7fe8c 1102 $userdate = usergetdate($date, $timezone);
4606d9bb 1103
02f0527d 1104 // Time of midnight of this user's day, in GMT
1105 return make_timestamp($userdate['year'], $userdate['mon'], $userdate['mday'], 0, 0, 0, $timezone);
edf7fe8c 1106
1107}
1108
7cf1c7bd 1109/**
1110 * Returns a string that prints the user's timezone
1111 *
1112 * @param float $timezone The user's timezone
1113 * @return string
1114 */
d552ead0 1115function usertimezone($timezone=99) {
d552ead0 1116
0c244315 1117 $tz = get_user_timezone($timezone);
f30fe8d0 1118
0c244315 1119 if (!is_float($tz)) {
1120 return $tz;
d552ead0 1121 }
0c244315 1122
1123 if(abs($tz) > 13) { // Server time
1124 return get_string('serverlocaltime');
1125 }
1126
1127 if($tz == intval($tz)) {
1128 // Don't show .0 for whole hours
1129 $tz = intval($tz);
1130 }
1131
1132 if($tz == 0) {
b0ccd3fb 1133 return 'GMT';
d552ead0 1134 }
0c244315 1135 else if($tz > 0) {
1136 return 'GMT+'.$tz;
1137 }
1138 else {
1139 return 'GMT'.$tz;
d552ead0 1140 }
e1ecf0a0 1141
f9903ed0 1142}
1143
7cf1c7bd 1144/**
1145 * Returns a float which represents the user's timezone difference from GMT in hours
1146 * Checks various settings and picks the most dominant of those which have a value
1147 *
7cf1c7bd 1148 * @uses $CFG
1149 * @uses $USER
b2b68362 1150 * @param float $tz If this value is provided and not equal to 99, it will be returned as is and no other settings will be checked
c6d15803 1151 * @return int
7cf1c7bd 1152 */
494b9296 1153function get_user_timezone_offset($tz = 99) {
f30fe8d0 1154
43b59916 1155 global $USER, $CFG;
1156
e8904995 1157 $tz = get_user_timezone($tz);
c9e55a25 1158
7b9e355e 1159 if (is_float($tz)) {
1160 return $tz;
1161 } else {
e8904995 1162 $tzrecord = get_timezone_record($tz);
7b9e355e 1163 if (empty($tzrecord)) {
e8904995 1164 return 99.0;
1165 }
4f2dbde9 1166 return (float)$tzrecord->gmtoff / HOURMINS;
e8904995 1167 }
1168}
1169
bbd3f2c4 1170/**
b2b68362 1171 * Returns a float or a string which denotes the user's timezone
1172 * A float value means that a simple offset from GMT is used, while a string (it will be the name of a timezone in the database)
1173 * means that for this timezone there are also DST rules to be taken into account
1174 * Checks various settings and picks the most dominant of those which have a value
bbd3f2c4 1175 *
1176 * @uses $USER
1177 * @uses $CFG
b2b68362 1178 * @param float $tz If this value is provided and not equal to 99, it will be returned as is and no other settings will be checked
1179 * @return mixed
bbd3f2c4 1180 */
e8904995 1181function get_user_timezone($tz = 99) {
1182 global $USER, $CFG;
43b59916 1183
f30fe8d0 1184 $timezones = array(
e8904995 1185 $tz,
1186 isset($CFG->forcetimezone) ? $CFG->forcetimezone : 99,
43b59916 1187 isset($USER->timezone) ? $USER->timezone : 99,
1188 isset($CFG->timezone) ? $CFG->timezone : 99,
f30fe8d0 1189 );
43b59916 1190
e8904995 1191 $tz = 99;
43b59916 1192
e8904995 1193 while(($tz == '' || $tz == 99) && $next = each($timezones)) {
1194 $tz = $next['value'];
43b59916 1195 }
e8904995 1196
1197 return is_numeric($tz) ? (float) $tz : $tz;
43b59916 1198}
1199
bbd3f2c4 1200/**
1201 * ?
1202 *
1203 * @uses $CFG
1204 * @uses $db
1205 * @param string $timezonename ?
1206 * @return object
1207 */
43b59916 1208function get_timezone_record($timezonename) {
1209 global $CFG, $db;
1210 static $cache = NULL;
1211
8edffd15 1212 if ($cache === NULL) {
43b59916 1213 $cache = array();
1214 }
1215
8edffd15 1216 if (isset($cache[$timezonename])) {
43b59916 1217 return $cache[$timezonename];
f30fe8d0 1218 }
1219
952d8dc8 1220 return $cache[$timezonename] = get_record_sql('SELECT * FROM '.$CFG->prefix.'timezone
1221 WHERE name = '.$db->qstr($timezonename).' ORDER BY year DESC', true);
f30fe8d0 1222}
f9903ed0 1223
bbd3f2c4 1224/**
1225 * ?
1226 *
1227 * @uses $CFG
1228 * @uses $USER
1229 * @param ? $fromyear ?
1230 * @param ? $to_year ?
1231 * @return bool
1232 */
830a2bbd 1233function calculate_user_dst_table($from_year = NULL, $to_year = NULL) {
2280ecf5 1234 global $CFG, $SESSION;
85cafb3e 1235
989585e9 1236 $usertz = get_user_timezone();
7cb29a3d 1237
989585e9 1238 if (is_float($usertz)) {
1239 // Trivial timezone, no DST
1240 return false;
1241 }
1242
2280ecf5 1243 if (!empty($SESSION->dst_offsettz) && $SESSION->dst_offsettz != $usertz) {
989585e9 1244 // We have precalculated values, but the user's effective TZ has changed in the meantime, so reset
2280ecf5 1245 unset($SESSION->dst_offsets);
1246 unset($SESSION->dst_range);
830a2bbd 1247 }
1248
2280ecf5 1249 if (!empty($SESSION->dst_offsets) && empty($from_year) && empty($to_year)) {
830a2bbd 1250 // Repeat calls which do not request specific year ranges stop here, we have already calculated the table
1251 // This will be the return path most of the time, pretty light computationally
1252 return true;
85cafb3e 1253 }
1254
830a2bbd 1255 // Reaching here means we either need to extend our table or create it from scratch
989585e9 1256
1257 // Remember which TZ we calculated these changes for
2280ecf5 1258 $SESSION->dst_offsettz = $usertz;
989585e9 1259
2280ecf5 1260 if(empty($SESSION->dst_offsets)) {
830a2bbd 1261 // If we 're creating from scratch, put the two guard elements in there
2280ecf5 1262 $SESSION->dst_offsets = array(1 => NULL, 0 => NULL);
830a2bbd 1263 }
2280ecf5 1264 if(empty($SESSION->dst_range)) {
830a2bbd 1265 // If creating from scratch
1266 $from = max((empty($from_year) ? intval(date('Y')) - 3 : $from_year), 1971);
1267 $to = min((empty($to_year) ? intval(date('Y')) + 3 : $to_year), 2035);
1268
1269 // Fill in the array with the extra years we need to process
1270 $yearstoprocess = array();
1271 for($i = $from; $i <= $to; ++$i) {
1272 $yearstoprocess[] = $i;
1273 }
1274
1275 // Take note of which years we have processed for future calls
2280ecf5 1276 $SESSION->dst_range = array($from, $to);
830a2bbd 1277 }
1278 else {
1279 // If needing to extend the table, do the same
1280 $yearstoprocess = array();
1281
2280ecf5 1282 $from = max((empty($from_year) ? $SESSION->dst_range[0] : $from_year), 1971);
1283 $to = min((empty($to_year) ? $SESSION->dst_range[1] : $to_year), 2035);
830a2bbd 1284
2280ecf5 1285 if($from < $SESSION->dst_range[0]) {
830a2bbd 1286 // Take note of which years we need to process and then note that we have processed them for future calls
2280ecf5 1287 for($i = $from; $i < $SESSION->dst_range[0]; ++$i) {
830a2bbd 1288 $yearstoprocess[] = $i;
1289 }
2280ecf5 1290 $SESSION->dst_range[0] = $from;
830a2bbd 1291 }
2280ecf5 1292 if($to > $SESSION->dst_range[1]) {
830a2bbd 1293 // Take note of which years we need to process and then note that we have processed them for future calls
2280ecf5 1294 for($i = $SESSION->dst_range[1] + 1; $i <= $to; ++$i) {
830a2bbd 1295 $yearstoprocess[] = $i;
1296 }
2280ecf5 1297 $SESSION->dst_range[1] = $to;
830a2bbd 1298 }
1299 }
1300
1301 if(empty($yearstoprocess)) {
1302 // This means that there was a call requesting a SMALLER range than we have already calculated
1303 return true;
1304 }
1305
1306 // From now on, we know that the array has at least the two guard elements, and $yearstoprocess has the years we need
1307 // Also, the array is sorted in descending timestamp order!
1308
1309 // Get DB data
989585e9 1310 $presetrecords = get_records('timezone', 'name', $usertz, 'year DESC', 'year, gmtoff, dstoff, dst_month, dst_startday, dst_weekday, dst_skipweeks, dst_time, std_month, std_startday, std_weekday, std_skipweeks, std_time');
e789650d 1311 if(empty($presetrecords)) {
1312 return false;
1313 }
57f1191c 1314
830a2bbd 1315 // Remove ending guard (first element of the array)
2280ecf5 1316 reset($SESSION->dst_offsets);
1317 unset($SESSION->dst_offsets[key($SESSION->dst_offsets)]);
830a2bbd 1318
1319 // Add all required change timestamps
1320 foreach($yearstoprocess as $y) {
1321 // Find the record which is in effect for the year $y
1322 foreach($presetrecords as $year => $preset) {
1323 if($year <= $y) {
1324 break;
c9e72798 1325 }
830a2bbd 1326 }
1327
1328 $changes = dst_changes_for_year($y, $preset);
1329
1330 if($changes === NULL) {
1331 continue;
1332 }
1333 if($changes['dst'] != 0) {
2280ecf5 1334 $SESSION->dst_offsets[$changes['dst']] = $preset->dstoff * MINSECS;
830a2bbd 1335 }
1336 if($changes['std'] != 0) {
2280ecf5 1337 $SESSION->dst_offsets[$changes['std']] = 0;
c9e72798 1338 }
85cafb3e 1339 }
42d36497 1340
830a2bbd 1341 // Put in a guard element at the top
2280ecf5 1342 $maxtimestamp = max(array_keys($SESSION->dst_offsets));
1343 $SESSION->dst_offsets[($maxtimestamp + DAYSECS)] = NULL; // DAYSECS is arbitrary, any "small" number will do
830a2bbd 1344
1345 // Sort again
2280ecf5 1346 krsort($SESSION->dst_offsets);
830a2bbd 1347
e789650d 1348 return true;
1349}
42d36497 1350
e789650d 1351function dst_changes_for_year($year, $timezone) {
7cb29a3d 1352
e789650d 1353 if($timezone->dst_startday == 0 && $timezone->dst_weekday == 0 && $timezone->std_startday == 0 && $timezone->std_weekday == 0) {
1354 return NULL;
42d36497 1355 }
7cb29a3d 1356
e789650d 1357 $monthdaydst = find_day_in_month($timezone->dst_startday, $timezone->dst_weekday, $timezone->dst_month, $year);
1358 $monthdaystd = find_day_in_month($timezone->std_startday, $timezone->std_weekday, $timezone->std_month, $year);
1359
1360 list($dst_hour, $dst_min) = explode(':', $timezone->dst_time);
1361 list($std_hour, $std_min) = explode(':', $timezone->std_time);
d2a9f7cc 1362
6dc8dddc 1363 $timedst = make_timestamp($year, $timezone->dst_month, $monthdaydst, 0, 0, 0, 99, false);
1364 $timestd = make_timestamp($year, $timezone->std_month, $monthdaystd, 0, 0, 0, 99, false);
830a2bbd 1365
1366 // Instead of putting hour and minute in make_timestamp(), we add them afterwards.
1367 // This has the advantage of being able to have negative values for hour, i.e. for timezones
1368 // where GMT time would be in the PREVIOUS day than the local one on which DST changes.
1369
1370 $timedst += $dst_hour * HOURSECS + $dst_min * MINSECS;
1371 $timestd += $std_hour * HOURSECS + $std_min * MINSECS;
42d36497 1372
e789650d 1373 return array('dst' => $timedst, 0 => $timedst, 'std' => $timestd, 1 => $timestd);
42d36497 1374}
1375
02f0527d 1376// $time must NOT be compensated at all, it has to be a pure timestamp
1377function dst_offset_on($time) {
2280ecf5 1378 global $SESSION;
02f0527d 1379
2280ecf5 1380 if(!calculate_user_dst_table() || empty($SESSION->dst_offsets)) {
c9e72798 1381 return 0;
85cafb3e 1382 }
1383
2280ecf5 1384 reset($SESSION->dst_offsets);
1385 while(list($from, $offset) = each($SESSION->dst_offsets)) {
59556d48 1386 if($from <= $time) {
c9e72798 1387 break;
1388 }
1389 }
1390
830a2bbd 1391 // This is the normal return path
1392 if($offset !== NULL) {
1393 return $offset;
02f0527d 1394 }
02f0527d 1395
830a2bbd 1396 // Reaching this point means we haven't calculated far enough, do it now:
1397 // Calculate extra DST changes if needed and recurse. The recursion always
1398 // moves toward the stopping condition, so will always end.
1399
1400 if($from == 0) {
2280ecf5 1401 // We need a year smaller than $SESSION->dst_range[0]
1402 if($SESSION->dst_range[0] == 1971) {
830a2bbd 1403 return 0;
1404 }
2280ecf5 1405 calculate_user_dst_table($SESSION->dst_range[0] - 5, NULL);
830a2bbd 1406 return dst_offset_on($time);
1407 }
1408 else {
2280ecf5 1409 // We need a year larger than $SESSION->dst_range[1]
1410 if($SESSION->dst_range[1] == 2035) {
830a2bbd 1411 return 0;
1412 }
2280ecf5 1413 calculate_user_dst_table(NULL, $SESSION->dst_range[1] + 5);
830a2bbd 1414 return dst_offset_on($time);
1415 }
85cafb3e 1416}
02f0527d 1417
28902d99 1418function find_day_in_month($startday, $weekday, $month, $year) {
8dc3f6cf 1419
1420 $daysinmonth = days_in_month($month, $year);
1421
42d36497 1422 if($weekday == -1) {
28902d99 1423 // Don't care about weekday, so return:
1424 // abs($startday) if $startday != -1
1425 // $daysinmonth otherwise
1426 return ($startday == -1) ? $daysinmonth : abs($startday);
8dc3f6cf 1427 }
1428
1429 // From now on we 're looking for a specific weekday
8dc3f6cf 1430
28902d99 1431 // Give "end of month" its actual value, since we know it
1432 if($startday == -1) {
1433 $startday = -1 * $daysinmonth;
1434 }
1435
1436 // Starting from day $startday, the sign is the direction
8dc3f6cf 1437
28902d99 1438 if($startday < 1) {
8dc3f6cf 1439
28902d99 1440 $startday = abs($startday);
8dc3f6cf 1441 $lastmonthweekday = strftime('%w', mktime(12, 0, 0, $month, $daysinmonth, $year, 0));
1442
1443 // This is the last such weekday of the month
1444 $lastinmonth = $daysinmonth + $weekday - $lastmonthweekday;
1445 if($lastinmonth > $daysinmonth) {
1446 $lastinmonth -= 7;
42d36497 1447 }
8dc3f6cf 1448
28902d99 1449 // Find the first such weekday <= $startday
1450 while($lastinmonth > $startday) {
8dc3f6cf 1451 $lastinmonth -= 7;
42d36497 1452 }
8dc3f6cf 1453
1454 return $lastinmonth;
e1ecf0a0 1455
42d36497 1456 }
1457 else {
42d36497 1458
28902d99 1459 $indexweekday = strftime('%w', mktime(12, 0, 0, $month, $startday, $year, 0));
42d36497 1460
8dc3f6cf 1461 $diff = $weekday - $indexweekday;
1462 if($diff < 0) {
1463 $diff += 7;
42d36497 1464 }
42d36497 1465
28902d99 1466 // This is the first such weekday of the month equal to or after $startday
1467 $firstfromindex = $startday + $diff;
42d36497 1468
8dc3f6cf 1469 return $firstfromindex;
1470
1471 }
42d36497 1472}
1473
bbd3f2c4 1474/**
1475 * Calculate the number of days in a given month
1476 *
1477 * @param int $month The month whose day count is sought
1478 * @param int $year The year of the month whose day count is sought
1479 * @return int
1480 */
42d36497 1481function days_in_month($month, $year) {
1482 return intval(date('t', mktime(12, 0, 0, $month, 1, $year, 0)));
1483}
1484
bbd3f2c4 1485/**
1486 * Calculate the position in the week of a specific calendar day
1487 *
1488 * @param int $day The day of the date whose position in the week is sought
1489 * @param int $month The month of the date whose position in the week is sought
1490 * @param int $year The year of the date whose position in the week is sought
1491 * @return int
1492 */
8dc3f6cf 1493function dayofweek($day, $month, $year) {
1494 // I wonder if this is any different from
1495 // strftime('%w', mktime(12, 0, 0, $month, $daysinmonth, $year, 0));
1496 return intval(date('w', mktime(12, 0, 0, $month, $day, $year, 0)));
1497}
1498
9fa49e22 1499/// USER AUTHENTICATION AND LOGIN ////////////////////////////////////////
f9903ed0 1500
bbd3f2c4 1501/**
1502 * Makes sure that $USER->sesskey exists, if $USER itself exists. It sets a new sesskey
1503 * if one does not already exist, but does not overwrite existing sesskeys. Returns the
1504 * sesskey string if $USER exists, or boolean false if not.
1505 *
1506 * @uses $USER
1507 * @return string
1508 */
04280e85 1509function sesskey() {
1a33f699 1510 global $USER;
1511
1512 if(!isset($USER)) {
1513 return false;
1514 }
1515
1516 if (empty($USER->sesskey)) {
1517 $USER->sesskey = random_string(10);
1518 }
1519
1520 return $USER->sesskey;
1521}
1522
0302c52f 1523
c4d0753b 1524/**
1525 * For security purposes, this function will check that the currently
1526 * given sesskey (passed as a parameter to the script or this function)
1527 * matches that of the current user.
1528 *
1529 * @param string $sesskey optionally provided sesskey
1530 * @return bool
1531 */
1532function confirm_sesskey($sesskey=NULL) {
1533 global $USER;
0302c52f 1534
c4d0753b 1535 if (!empty($USER->ignoresesskey) || !empty($CFG->ignoresesskey)) {
1536 return true;
0302c52f 1537 }
1538
c4d0753b 1539 if (empty($sesskey)) {
1540 $sesskey = required_param('sesskey', PARAM_RAW); // Check script parameters
0302c52f 1541 }
1542
c4d0753b 1543 if (!isset($USER->sesskey)) {
1544 return false;
1545 }
0302c52f 1546
c4d0753b 1547 return ($USER->sesskey === $sesskey);
0302c52f 1548}
c4d0753b 1549
dcf6d93c 1550/**
9152fc99 1551 * Setup all global $CFG course variables, set locale and also themes
1552 * This function can be used on pages that do not require login instead of require_login()
1553 *
dcf6d93c 1554 * @param mixed $courseorid id of the course or course object
1555 */
1556function course_setup($courseorid=0) {
9152fc99 1557 global $COURSE, $CFG, $SITE, $USER;
dcf6d93c 1558
1559/// Redefine global $COURSE if needed
1560 if (empty($courseorid)) {
1561 // no change in global $COURSE - for backwards compatibiltiy
1562 // if require_rogin() used after require_login($courseid);
1563 } else if (is_object($courseorid)) {
1564 $COURSE = clone($courseorid);
1565 } else {
1566 global $course; // used here only to prevent repeated fetching from DB - may be removed later
9152fc99 1567 if (!empty($course->id) and $course->id == SITEID) {
1568 $COURSE = clone($SITE);
1569 } else if (!empty($course->id) and $course->id == $courseorid) {
dcf6d93c 1570 $COURSE = clone($course);
1571 } else {
1572 if (!$COURSE = get_record('course', 'id', $courseorid)) {
1573 error('Invalid course ID');
1574 }
1575 }
1576 }
1577
9152fc99 1578/// set locale and themes
dcf6d93c 1579 moodle_setlocale();
dcf6d93c 1580 theme_setup();
1581
dcf6d93c 1582}
c4d0753b 1583
7cf1c7bd 1584/**
ec81373f 1585 * This function checks that the current user is logged in and has the
1586 * required privileges
1587 *
7cf1c7bd 1588 * This function checks that the current user is logged in, and optionally
ec81373f 1589 * whether they are allowed to be in a particular course and view a particular
1590 * course module.
1591 * If they are not logged in, then it redirects them to the site login unless
d2a9f7cc 1592 * $autologinguest is set and {@link $CFG}->autologinguests is set to 1 in which
ec81373f 1593 * case they are automatically logged in as guests.
1594 * If $courseid is given and the user is not enrolled in that course then the
1595 * user is redirected to the course enrolment page.
1596 * If $cm is given and the coursemodule is hidden and the user is not a teacher
1597 * in the course then the user is redirected to the course home page.
7cf1c7bd 1598 *
7cf1c7bd 1599 * @uses $CFG
c6d15803 1600 * @uses $SESSION
7cf1c7bd 1601 * @uses $USER
1602 * @uses $FULLME
c6d15803 1603 * @uses SITEID
f07fa644 1604 * @uses $COURSE
33ebaf7c 1605 * @param mixed $courseorid id of the course or course object
bbd3f2c4 1606 * @param bool $autologinguest
1607 * @param object $cm course module object
7cf1c7bd 1608 */
33ebaf7c 1609function require_login($courseorid=0, $autologinguest=true, $cm=null) {
f9903ed0 1610
083c3743 1611 global $CFG, $SESSION, $USER, $COURSE, $FULLME;
d8ba183c 1612
083c3743 1613/// setup global $COURSE, themes, language and locale
dcf6d93c 1614 course_setup($courseorid);
be933850 1615
1845f8b8 1616/// If the user is not even logged in yet then make sure they are
083c3743 1617 if (!isloggedin()) {
1618 //NOTE: $USER->site check was obsoleted by session test cookie,
1619 // $USER->confirmed test is in login/index.php
f9903ed0 1620 $SESSION->wantsurl = $FULLME;
b0ccd3fb 1621 if (!empty($_SERVER['HTTP_REFERER'])) {
1622 $SESSION->fromurl = $_SERVER['HTTP_REFERER'];
9f44d972 1623 }
dcf6d93c 1624 if ($autologinguest and !empty($CFG->autologinguests) and ($COURSE->id == SITEID or $COURSE->guest) ) {
8e8d0524 1625 $loginguest = '?loginguest=true';
1626 } else {
1627 $loginguest = '';
a2ebe6a5 1628 }
083c3743 1629 if (empty($CFG->loginhttps) or $autologinguest) { //do not require https for guest logins
b0ccd3fb 1630 redirect($CFG->wwwroot .'/login/index.php'. $loginguest);
8a33e371 1631 } else {
2c3432e6 1632 $wwwroot = str_replace('http:','https:', $CFG->wwwroot);
083c3743 1633 redirect($wwwroot .'/login/index.php');
8a33e371 1634 }
20fde7b1 1635 exit;
f9903ed0 1636 }
808a3baa 1637
1845f8b8 1638/// check whether the user should be changing password
03d820c7 1639 $userauth = get_auth_plugin($USER->auth);
a3f1f815 1640 if (!empty($USER->preference['auth_forcepasswordchange'])){
03d820c7 1641 if ($userauth->can_change_password()) {
20fde7b1 1642 $SESSION->wantsurl = $FULLME;
1437f0a5 1643 if (empty($CFG->loginhttps)) {
1644 redirect($CFG->wwwroot .'/login/change_password.php');
1645 } else {
1646 $wwwroot = str_replace('http:','https:', $CFG->wwwroot);
1647 redirect($wwwroot .'/login/change_password.php');
1648 }
083c3743 1649 } else if($userauth->change_password_url()) {
63b1e351 1650 redirect($userauth->change_password_url());
d35757eb 1651 } else {
361855e6 1652 error('You cannot proceed without changing your password.
d35757eb 1653 However there is no available page for changing it.
b0ccd3fb 1654 Please contact your Moodle Administrator.');
d35757eb 1655 }
1656 }
083c3743 1657
1845f8b8 1658/// Check that the user account is properly set up
808a3baa 1659 if (user_not_fully_set_up($USER)) {
20fde7b1 1660 $SESSION->wantsurl = $FULLME;
b0ccd3fb 1661 redirect($CFG->wwwroot .'/user/edit.php?id='. $USER->id .'&amp;course='. SITEID);
808a3baa 1662 }
d8ba183c 1663
1845f8b8 1664/// Make sure current IP matches the one for this session (if required)
361855e6 1665 if (!empty($CFG->tracksessionip)) {
366dfa60 1666 if ($USER->sessionIP != md5(getremoteaddr())) {
1667 error(get_string('sessionipnomatch', 'error'));
1668 }
1669 }
6d8f47d6 1670
1845f8b8 1671/// Make sure the USER has a sesskey set up. Used for checking script parameters.
04280e85 1672 sesskey();
366dfa60 1673
027a1604 1674 // Check that the user has agreed to a site policy if there is one
1675 if (!empty($CFG->sitepolicy)) {
1676 if (!$USER->policyagreed) {
957b5198 1677 $SESSION->wantsurl = $FULLME;
027a1604 1678 redirect($CFG->wwwroot .'/user/policy.php');
027a1604 1679 }
1695b680 1680 }
1681
1845f8b8 1682/// If the site is currently under maintenance, then print a message
9c37662f 1683 if (!has_capability('moodle/site:config',get_context_instance(CONTEXT_SYSTEM, SITEID))) {
eeefd0b0 1684 if (file_exists($CFG->dataroot.'/'.SITEID.'/maintenance.html')) {
1695b680 1685 print_maintenance_message();
20fde7b1 1686 exit;
1695b680 1687 }
027a1604 1688 }
1689
1845f8b8 1690
33ebaf7c 1691 if ($COURSE->id == SITEID) {
1692/// We can eliminate hidden site activities straight away
1693 if (!empty($cm) && !$cm->visible and !has_capability('moodle/course:viewhiddenactivities',
1694 get_context_instance(CONTEXT_SYSTEM, SITEID))) {
1695 redirect($CFG->wwwroot, get_string('activityiscurrentlyhidden'));
e3512050 1696 }
33ebaf7c 1697 return;
881a77bf 1698
33ebaf7c 1699 } else {
1700/// Check if the user can be in a particular course
1701 if (!$context = get_context_instance(CONTEXT_COURSE, $COURSE->id)) {
1845f8b8 1702 print_error('nocontext');
1703 }
1704
881a77bf 1705 if (empty($USER->switchrole[$context->id]) &&
33ebaf7c 1706 !($COURSE->visible && course_parent_visible($COURSE)) &&
1707 !has_capability('moodle/course:viewhiddencourses', get_context_instance(CONTEXT_COURSE, $COURSE->id)) ){
881a77bf 1708 print_header_simple();
1709 notice(get_string('coursehidden'), $CFG->wwwroot .'/');
1710 }
1711
f71346e2 1712 /// Non-guests who don't currently have access, check if they can be allowed in as a guest
1713
1714 if ($USER->username != 'guest' and !has_capability('moodle/course:view', $context)) {
33ebaf7c 1715 if ($COURSE->guest == 1) {
f71346e2 1716 // Temporarily assign them guest role for this context,
1717 // if it fails user is asked to enrol
1718 load_guest_role($context);
1719 }
1720 }
1721
1845f8b8 1722 /// If the user is a guest then treat them according to the course policy about guests
1723
1724 if (has_capability('moodle/legacy:guest', $context, NULL, false)) {
33ebaf7c 1725 switch ($COURSE->guest) { /// Check course policy about guest access
1845f8b8 1726
1727 case 1: /// Guests always allowed
1728 if (!has_capability('moodle/course:view', $context)) { // Prohibited by capability
1729 print_header_simple();
33ebaf7c 1730 notice(get_string('guestsnotallowed', '', $COURSE->fullname), "$CFG->wwwroot/login/index.php");
1845f8b8 1731 }
1732 if (!empty($cm) and !$cm->visible) { // Not allowed to see module, send to course page
1733 redirect($CFG->wwwroot.'/course/view.php?id='.$cm->course,
1734 get_string('activityiscurrentlyhidden'));
1735 }
1736
1737 return; // User is allowed to see this course
1738
1739 break;
1740
b1f318a6 1741 case 2: /// Guests allowed with key
33ebaf7c 1742 if (!empty($USER->enrolkey[$COURSE->id])) { // Set by enrol/manual/enrol.php
b1f318a6 1743 return true;
1744 }
1745 // otherwise drop through to logic below (--> enrol.php)
1845f8b8 1746 break;
bbbf2d40 1747
1845f8b8 1748 default: /// Guests not allowed
21596567 1749 print_header_simple('', '', get_string('loggedinasguest'));
1750 if (empty($USER->switchrole[$context->id])) { // Normal guest
33ebaf7c 1751 notice(get_string('guestsnotallowed', '', $COURSE->fullname), "$CFG->wwwroot/login/index.php");
21596567 1752 } else {
33ebaf7c 1753 notify(get_string('guestsnotallowed', '', $COURSE->fullname));
1754 echo '<div class="notifyproblem">'.switchroles_form($COURSE->id).'</div>';
1755 print_footer($COURSE);
21596567 1756 exit;
1757 }
1845f8b8 1758 break;
1759 }
1760
1761 /// For non-guests, check if they have course view access
1762
1763 } else if (has_capability('moodle/course:view', $context)) {
1764 if (!empty($USER->realuser)) { // Make sure the REAL person can also access this course
d02eeded 1765 if (!has_capability('moodle/course:view', $context, $USER->realuser)) {
1845f8b8 1766 print_header_simple();
b0ccd3fb 1767 notice(get_string('studentnotallowed', '', fullname($USER, true)), $CFG->wwwroot .'/');
cb909d74 1768 }
3ce2f1e0 1769 }
1845f8b8 1770
1771 /// Make sure they can read this activity too, if specified
1772
1773 if (!empty($cm) and !$cm->visible and !has_capability('moodle/course:viewhiddenactivities', $context)) {
ec81373f 1774 redirect($CFG->wwwroot.'/course/view.php?id='.$cm->course, get_string('activityiscurrentlyhidden'));
1775 }
1845f8b8 1776 return; // User is allowed to see this course
1777
da5c172a 1778 }
f9903ed0 1779
9ca3b4f3 1780
1845f8b8 1781 /// Currently not enrolled in the course, so see if they want to enrol
da5c172a 1782 $SESSION->wantsurl = $FULLME;
33ebaf7c 1783 redirect($CFG->wwwroot .'/course/enrol.php?id='. $COURSE->id);
da5c172a 1784 die;
1785 }
f9903ed0 1786}
1787
c4d0753b 1788
1789
1790/**
1791 * This function just makes sure a user is logged out.
1792 *
1793 * @uses $CFG
1794 * @uses $USER
1795 */
1796function require_logout() {
1797
2d4beaff 1798 global $USER, $CFG, $SESSION;
c4d0753b 1799
1800 if (isset($USER) and isset($USER->id)) {
1801 add_to_log(SITEID, "user", "logout", "view.php?id=$USER->id&course=".SITEID, $USER->id, 0, $USER->id);
1802
1803 if ($USER->auth == 'cas' && !empty($CFG->cas_enabled)) {
1804 require($CFG->dirroot.'/auth/cas/logout.php');
1805 }
03d820c7 1806
81693ac7 1807 if (extension_loaded('openssl')) {
1808 require($CFG->dirroot.'/auth/mnet/auth.php');
1809 $authplugin = new auth_plugin_mnet();
1810 $authplugin->logout();
1811 }
c4d0753b 1812 }
1813
1814 if (ini_get_bool("register_globals") and check_php_version("4.3.0")) {
1815 // This method is just to try to avoid silly warnings from PHP 4.3.0
1816 session_unregister("USER");
1817 session_unregister("SESSION");
1818 }
1819
1820 setcookie('MoodleSessionTest'.$CFG->sessioncookie, '', time() - 3600, $CFG->sessioncookiepath);
1821 unset($_SESSION['USER']);
1822 unset($_SESSION['SESSION']);
1823
1824 unset($SESSION);
1825 unset($USER);
1826
1827}
1828
7cf1c7bd 1829/**
1830 * This is a weaker version of {@link require_login()} which only requires login
1831 * when called from within a course rather than the site page, unless
1832 * the forcelogin option is turned on.
1833 *
1834 * @uses $CFG
33ebaf7c 1835 * @param mixed $courseorid The course object or id in question
bbd3f2c4 1836 * @param bool $autologinguest Allow autologin guests if that is wanted
4febb58f 1837 * @param object $cm Course activity module if known
7cf1c7bd 1838 */
33ebaf7c 1839function require_course_login($courseorid, $autologinguest=true, $cm=null) {
f950af3c 1840 global $CFG;
1596edff 1841 if (!empty($CFG->forcelogin)) {
33ebaf7c 1842 // login required for both SITE and courses
1843 require_login($courseorid, $autologinguest, $cm);
39de90ac 1844 } else if ((is_object($courseorid) and $courseorid->id == SITEID)
1845 or (!is_object($courseorid) and $courseorid == SITEID)) {
33ebaf7c 1846 //login for SITE not required
1847 } else {
1848 // course login always required
1849 require_login($courseorid, $autologinguest, $cm);
f950af3c 1850 }
1851}
1852
7cf1c7bd 1853/**
1854 * Modify the user table by setting the currently logged in user's
1855 * last login to now.
1856 *
1857 * @uses $USER
bbd3f2c4 1858 * @return bool
7cf1c7bd 1859 */
1d881d92 1860function update_user_login_times() {
1861 global $USER;
1862
53467aa6 1863 $user = new object();
1d881d92 1864 $USER->lastlogin = $user->lastlogin = $USER->currentlogin;
2a2f5f11 1865 $USER->currentlogin = $user->lastaccess = $user->currentlogin = time();
1d881d92 1866
1867 $user->id = $USER->id;
1868
b0ccd3fb 1869 return update_record('user', $user);
1d881d92 1870}
1871
7cf1c7bd 1872/**
1873 * Determines if a user has completed setting up their account.
1874 *
89dcb99d 1875 * @param user $user A {@link $USER} object to test for the existance of a valid name and email
bbd3f2c4 1876 * @return bool
7cf1c7bd 1877 */
808a3baa 1878function user_not_fully_set_up($user) {
bb64b51a 1879 return ($user->username != 'guest' and (empty($user->firstname) or empty($user->lastname) or empty($user->email) or over_bounce_threshold($user)));
1880}
1881
1882function over_bounce_threshold($user) {
d2a9f7cc 1883
bb64b51a 1884 global $CFG;
d2a9f7cc 1885
bb64b51a 1886 if (empty($CFG->handlebounces)) {
1887 return false;
1888 }
1889 // set sensible defaults
1890 if (empty($CFG->minbounces)) {
1891 $CFG->minbounces = 10;
1892 }
1893 if (empty($CFG->bounceratio)) {
1894 $CFG->bounceratio = .20;
1895 }
1896 $bouncecount = 0;
1897 $sendcount = 0;
1898 if ($bounce = get_record('user_preferences','userid',$user->id,'name','email_bounce_count')) {
1899 $bouncecount = $bounce->value;
1900 }
1901 if ($send = get_record('user_preferences','userid',$user->id,'name','email_send_count')) {
1902 $sendcount = $send->value;
1903 }
1904 return ($bouncecount >= $CFG->minbounces && $bouncecount/$sendcount >= $CFG->bounceratio);
1905}
1906
d2a9f7cc 1907/**
bb64b51a 1908 * @param $user - object containing an id
1909 * @param $reset - will reset the count to 0
1910 */
1911function set_send_count($user,$reset=false) {
d2a9f7cc 1912 if ($pref = get_record('user_preferences','userid',$user->id,'name','email_send_count')) {
bb64b51a 1913 $pref->value = (!empty($reset)) ? 0 : $pref->value+1;
1914 update_record('user_preferences',$pref);
1915 }
1916 else if (!empty($reset)) { // if it's not there and we're resetting, don't bother.
1917 // make a new one
1918 $pref->name = 'email_send_count';
1919 $pref->value = 1;
1920 $pref->userid = $user->id;
06ba0b04 1921 insert_record('user_preferences',$pref, false);
bb64b51a 1922 }
1923}
1924
d2a9f7cc 1925/**
bb64b51a 1926* @param $user - object containing an id
1927 * @param $reset - will reset the count to 0
1928 */
1929function set_bounce_count($user,$reset=false) {
d2a9f7cc 1930 if ($pref = get_record('user_preferences','userid',$user->id,'name','email_bounce_count')) {
bb64b51a 1931 $pref->value = (!empty($reset)) ? 0 : $pref->value+1;
1932 update_record('user_preferences',$pref);
1933 }
1934 else if (!empty($reset)) { // if it's not there and we're resetting, don't bother.
1935 // make a new one
1936 $pref->name = 'email_bounce_count';
1937 $pref->value = 1;
1938 $pref->userid = $user->id;
06ba0b04 1939 insert_record('user_preferences',$pref, false);
bb64b51a 1940 }
808a3baa 1941}
f9903ed0 1942
7cf1c7bd 1943/**
1944 * Keeps track of login attempts
1945 *
1946 * @uses $SESSION
1947 */
f9903ed0 1948function update_login_count() {
9fa49e22 1949
f9903ed0 1950 global $SESSION;
1951
1952 $max_logins = 10;
1953
1954 if (empty($SESSION->logincount)) {
1955 $SESSION->logincount = 1;
1956 } else {
1957 $SESSION->logincount++;
1958 }
1959
1960 if ($SESSION->logincount > $max_logins) {
9fa49e22 1961 unset($SESSION->wantsurl);
b0ccd3fb 1962 error(get_string('errortoomanylogins'));
d578afc8 1963 }
1964}
1965
7cf1c7bd 1966/**
1967 * Resets login attempts
1968 *
1969 * @uses $SESSION
1970 */
9fa49e22 1971function reset_login_count() {
9fa49e22 1972 global $SESSION;
d578afc8 1973
9fa49e22 1974 $SESSION->logincount = 0;
d578afc8 1975}
1976
b61efafb 1977function sync_metacourses() {
1978
1979 global $CFG;
1980
1aad4310 1981 if (!$courses = get_records('course', 'metacourse', 1)) {
b61efafb 1982 return;
1983 }
d2a9f7cc 1984
b61efafb 1985 foreach ($courses as $course) {
1aad4310 1986 sync_metacourse($course);
b61efafb 1987 }
1988}
1989
b61efafb 1990/**
1991 * Goes through all enrolment records for the courses inside the metacourse and sync with them.
123545bc 1992 *
1993 * @param mixed $course the metacourse to synch. Either the course object itself, or the courseid.
d2a9f7cc 1994 */
1aad4310 1995function sync_metacourse($course) {
755c8d58 1996 global $CFG;
b61efafb 1997
123545bc 1998 // Check the course is valid.
1aad4310 1999 if (!is_object($course)) {
2000 if (!$course = get_record('course', 'id', $course)) {
2001 return false; // invalid course id
b61efafb 2002 }
b61efafb 2003 }
1aad4310 2004
123545bc 2005 // Check that we actually have a metacourse.
1aad4310 2006 if (empty($course->metacourse)) {
123545bc 2007 return false;
755c8d58 2008 }
87671466 2009
b3170072 2010 // Get a list of roles that should not be synced.
2011 if ($CFG->nonmetacoursesyncroleids) {
2012 $roleexclusions = 'ra.roleid NOT IN (' . $CFG->nonmetacoursesyncroleids . ') AND';
2013 } else {
2014 $roleexclusions = '';
2015 }
2016
123545bc 2017 // Get the context of the metacourse.
1aad4310 2018 $context = get_context_instance(CONTEXT_COURSE, $course->id); // SITEID can not be a metacourse
e1ecf0a0 2019
123545bc 2020 // We do not ever want to unassign the list of metacourse manager, so get a list of them.
b79da3ac 2021 if ($users = get_users_by_capability($context, 'moodle/course:managemetacourse')) {
1aad4310 2022 $managers = array_keys($users);
2023 } else {
2024 $managers = array();
b61efafb 2025 }
2026
123545bc 2027 // Get assignments of a user to a role that exist in a child course, but
2028 // not in the meta coure. That is, get a list of the assignments that need to be made.
2029 if (!$assignments = get_records_sql("
2030 SELECT
2031 ra.id, ra.roleid, ra.userid
2032 FROM
2033 {$CFG->prefix}role_assignments ra,
2034 {$CFG->prefix}context con,
2035 {$CFG->prefix}course_meta cm
2036 WHERE
2037 ra.contextid = con.id AND
2038 con.contextlevel = " . CONTEXT_COURSE . " AND
2039 con.instanceid = cm.child_course AND
2040 cm.parent_course = {$course->id} AND
b3170072 2041 $roleexclusions
123545bc 2042 NOT EXISTS (
2043 SELECT 1 FROM
2044 {$CFG->prefix}role_assignments ra2
2045 WHERE
2046 ra2.userid = ra.userid AND
2047 ra2.roleid = ra.roleid AND
2048 ra2.contextid = {$context->id}
2049 )
2050 ")) {
2051 $assignments = array();
2052 }
2053
2054 // Get assignments of a user to a role that exist in the meta course, but
2055 // not in any child courses. That is, get a list of the unassignments that need to be made.
2056 if (!$unassignments = get_records_sql("
2057 SELECT
2058 ra.id, ra.roleid, ra.userid
2059 FROM
2060 {$CFG->prefix}role_assignments ra
2061 WHERE
2062 ra.contextid = {$context->id} AND
b3170072 2063 $roleexclusions
123545bc 2064 NOT EXISTS (
2065 SELECT 1 FROM
2066 {$CFG->prefix}role_assignments ra2,
2067 {$CFG->prefix}context con2,
2068 {$CFG->prefix}course_meta cm
2069 WHERE
2070 ra2.userid = ra.userid AND
2071 ra2.roleid = ra.roleid AND
2072 ra2.contextid = con2.id AND
2073 con2.contextlevel = " . CONTEXT_COURSE . " AND
2074 con2.instanceid = cm.child_course AND
2075 cm.parent_course = {$course->id}
2076 )
2077 ")) {
2078 $unassignments = array();
2079 }
2080
2081 $success = true;
2082
2083 // Make the unassignments, if they are not managers.
2084 foreach ($unassignments as $unassignment) {
2085 if (!in_array($unassignment->userid, $managers)) {
2086 $success = role_unassign($unassignment->roleid, $unassignment->userid, 0, $context->id) && $success;
1aad4310 2087 }
755c8d58 2088 }
e1ecf0a0 2089
123545bc 2090 // Make the assignments.
2091 foreach ($assignments as $assignment) {
2092 $success = role_assign($assignment->roleid, $assignment->userid, 0, $context->id) && $success;
b61efafb 2093 }
755c8d58 2094
123545bc 2095 return $success;
2096
1aad4310 2097// TODO: finish timeend and timestart
2098// maybe we could rely on cron job to do the cleaning from time to time
b61efafb 2099}
2100
d2a9f7cc 2101/**
b61efafb 2102 * Adds a record to the metacourse table and calls sync_metacoures
2103 */
2104function add_to_metacourse ($metacourseid, $courseid) {
d2a9f7cc 2105
b61efafb 2106 if (!$metacourse = get_record("course","id",$metacourseid)) {
2107 return false;
2108 }
d2a9f7cc 2109
b61efafb 2110 if (!$course = get_record("course","id",$courseid)) {
2111 return false;
2112 }
2113
5f37b628 2114 if (!$record = get_record("course_meta","parent_course",$metacourseid,"child_course",$courseid)) {
53467aa6 2115 $rec = new object();
b61efafb 2116 $rec->parent_course = $metacourseid;
2117 $rec->child_course = $courseid;
5f37b628 2118 if (!insert_record('course_meta',$rec)) {
b61efafb 2119 return false;
2120 }
2121 return sync_metacourse($metacourseid);
2122 }
2123 return true;
d2a9f7cc 2124
b61efafb 2125}
2126
d2a9f7cc 2127/**
b61efafb 2128 * Removes the record from the metacourse table and calls sync_metacourse
2129 */
2130function remove_from_metacourse($metacourseid, $courseid) {
2131
5f37b628 2132 if (delete_records('course_meta','parent_course',$metacourseid,'child_course',$courseid)) {
b61efafb 2133 return sync_metacourse($metacourseid);
2134 }
2135 return false;
2136}
2137
2138
7c12949d 2139/**
2140 * Determines if a user is currently logged in
2141 *
2142 * @uses $USER
bbd3f2c4 2143 * @return bool
7c12949d 2144 */
2145function isloggedin() {
2146 global $USER;
2147
2148 return (!empty($USER->id));
2149}
2150
2a919fd7 2151/**
2152 * Determines if a user is logged in as real guest user with username 'guest'.
2153 * This function is similar to original isguest() in 1.6 and earlier.
2154 * Current isguest() is deprecated - do not use it anymore.
2155 *
2156 * @param $user mixed user object or id, $USER if not specified
2157 * @return bool true if user is the real guest user, false if not logged in or other user
2158 */
2159function isguestuser($user=NULL) {
2160 global $USER;
2161 if ($user === NULL) {
2162 $user = $USER;
2163 } else if (is_numeric($user)) {
2164 $user = get_record('user', 'id', $user, '', '', '', '', 'id, username');
2165 }
2166
2167 if (empty($user->id)) {
2168 return false; // not logged in, can not be guest
2169 }
2170
2171 return ($user->username == 'guest');
2172}
7c12949d 2173
7cf1c7bd 2174/**
2175 * Determines if the currently logged in user is in editing mode
2176 *
2177 * @uses $USER
c6d15803 2178 * @param int $courseid The id of the course being tested
89dcb99d 2179 * @param user $user A {@link $USER} object. If null then the currently logged in user is used.
bbd3f2c4 2180 * @return bool
7cf1c7bd 2181 */
2c309dc2 2182function isediting($courseid, $user=NULL) {
3cf4fa0c 2183 global $USER;
2184 if (!$user) {
2185 $user = $USER;
2c309dc2 2186 }
9c9f7d77 2187 if (empty($user->editing)) {
2188 return false;
2189 }
d02eeded 2190 return ($user->editing and has_capability('moodle/course:manageactivities', get_context_instance(CONTEXT_COURSE, $courseid)));
2c309dc2 2191}
2192
7cf1c7bd 2193/**
2194 * Determines if the logged in user is currently moving an activity
2195 *
2196 * @uses $USER
c6d15803 2197 * @param int $courseid The id of the course being tested
bbd3f2c4 2198 * @return bool
7cf1c7bd 2199 */
7977cffd 2200function ismoving($courseid) {
7977cffd 2201 global $USER;
2202
2203 if (!empty($USER->activitycopy)) {
2204 return ($USER->activitycopycourse == $courseid);
2205 }
2206 return false;
2207}
2208
7cf1c7bd 2209/**
2210 * Given an object containing firstname and lastname
2211 * values, this function returns a string with the
2212 * full name of the person.
2213 * The result may depend on system settings
2214 * or language. 'override' will force both names
361855e6 2215 * to be used even if system settings specify one.
68fbd8e1 2216 *
7cf1c7bd 2217 * @uses $CFG
2218 * @uses $SESSION
68fbd8e1 2219 * @param object $user A {@link $USER} object to get full name of
2220 * @param bool $override If true then the name will be first name followed by last name rather than adhering to fullnamedisplay setting.
7cf1c7bd 2221 */
e2cd5065 2222function fullname($user, $override=false) {
b5cbb64d 2223
f374fb10 2224 global $CFG, $SESSION;
2225
6527c077 2226 if (!isset($user->firstname) and !isset($user->lastname)) {
2227 return '';
2228 }
2229
4c202228 2230 if (!$override) {
2231 if (!empty($CFG->forcefirstname)) {
2232 $user->firstname = $CFG->forcefirstname;
2233 }
2234 if (!empty($CFG->forcelastname)) {
2235 $user->lastname = $CFG->forcelastname;
2236 }
2237 }
2238
f374fb10 2239 if (!empty($SESSION->fullnamedisplay)) {
2240 $CFG->fullnamedisplay = $SESSION->fullnamedisplay;
2241 }
e2cd5065 2242
b5cbb64d 2243 if ($CFG->fullnamedisplay == 'firstname lastname') {
b0ccd3fb 2244 return $user->firstname .' '. $user->lastname;
b5cbb64d 2245
2246 } else if ($CFG->fullnamedisplay == 'lastname firstname') {
b0ccd3fb 2247 return $user->lastname .' '. $user->firstname;
e2cd5065 2248
b5cbb64d 2249 } else if ($CFG->fullnamedisplay == 'firstname') {
2250 if ($override) {
2251 return get_string('fullnamedisplay', '', $user);
2252 } else {
2253 return $user->firstname;
2254 }
2255 }
e2cd5065 2256
b5cbb64d 2257 return get_string('fullnamedisplay', '', $user);
e2cd5065 2258}
2259
7cf1c7bd 2260/**
2261 * Sets a moodle cookie with an encrypted string
2262 *
2263 * @uses $CFG
2f87145b 2264 * @uses DAYSECS
2265 * @uses HOURSECS
7cf1c7bd 2266 * @param string $thing The string to encrypt and place in a cookie
2267 */
f9903ed0 2268function set_moodle_cookie($thing) {
7185e073 2269 global $CFG;
482b6e6e 2270
7cbe6afe 2271 if ($thing == 'guest') { // Ignore guest account
2272 return;
2273 }
2274
482b6e6e 2275 $cookiename = 'MOODLEID_'.$CFG->sessioncookie;
f9903ed0 2276
2277 $days = 60;
7a5672c9 2278 $seconds = DAYSECS*$days;
f9903ed0 2279
7a5672c9 2280 setCookie($cookiename, '', time() - HOURSECS, '/');
b0ccd3fb 2281 setCookie($cookiename, rc4encrypt($thing), time()+$seconds, '/');
f9903ed0 2282}
2283
7cf1c7bd 2284/**
2285 * Gets a moodle cookie with an encrypted string
2286 *
2287 * @uses $CFG
2288 * @return string
2289 */
f9903ed0 2290function get_moodle_cookie() {
7185e073 2291 global $CFG;
2292
482b6e6e 2293 $cookiename = 'MOODLEID_'.$CFG->sessioncookie;
7185e073 2294
1079c8a8 2295 if (empty($_COOKIE[$cookiename])) {
b0ccd3fb 2296 return '';
1079c8a8 2297 } else {
7cbe6afe 2298 $thing = rc4decrypt($_COOKIE[$cookiename]);
2299 return ($thing == 'guest') ? '': $thing; // Ignore guest account
1079c8a8 2300 }
f9903ed0 2301}
2302
7cf1c7bd 2303/**
03d820c7 2304 * Returns whether a given authentication plugin exists.
7cf1c7bd 2305 *
2306 * @uses $CFG
03d820c7 2307 * @param string $auth Form of authentication to check for. Defaults to the
2308 * global setting in {@link $CFG}.
2309 * @return boolean Whether the plugin is available.
7cf1c7bd 2310 */
03d820c7 2311function exists_auth_plugin($auth='') {
2312 global $CFG;
2313
2314 // use the global default if not specified
2315 if ($auth == '') {
2316 $auth = $CFG->auth;
2317 }
2318 if (file_exists("{$CFG->dirroot}/auth/$auth/auth.php")) {
2319 return is_readable("{$CFG->dirroot}/auth/$auth/auth.php");
2320 }
2321 return false;
2322}
ba7166c3 2323
03d820c7 2324/**
2325 * Checks if a given plugin is in the list of enabled authentication plugins.
2326 *
2327 * @param string $auth Authentication plugin.
2328 * @return boolean Whether the plugin is enabled.
2329 */
2330function is_enabled_auth($auth='') {
ba7166c3 2331 global $CFG;
2332
03d820c7 2333 // use the global default if not specified
2334 if ($auth == '') {
2335 $auth = $CFG->auth;
2336 }
2337 return in_array($auth, explode(',', $CFG->auth_plugins_enabled));
2338}
2339
2340/**
2341 * Returns an authentication plugin instance.
2342 *
2343 * @uses $CFG
2344 * @param string $auth Form of authentication required. Defaults to the
2345 * global setting in {@link $CFG}.
2346 * @return object An instance of the required authentication plugin.
2347 */
2348function get_auth_plugin($auth = '') {
2349 global $CFG;
2350
2351 // use the global default if not specified
2352 if ($auth == '') {
a3f1f815 2353 $auth = $CFG->auth;
39a5a35d 2354 }
2355
03d820c7 2356 // TODO: plugin enabled?
2357
2358 // check the plugin exists first
2359 if (! exists_auth_plugin($auth)) {
2360 error("Authentication plugin '$auth' not found.");
2361 }
2362
2363 // return auth plugin instance
2364 require_once "{$CFG->dirroot}/auth/$auth/auth.php";
2365 $class = "auth_plugin_$auth";
2366 return new $class;
2367}
2368
2369/**
2370 * Returns true if an internal authentication method is being used.
2371 * if method not specified then, global default is assumed
2372 *
2373 * @uses $CFG
2374 * @param string $auth Form of authentication required
2375 * @return bool
2376 * @todo Outline auth types and provide code example
2377 */
2378function is_internal_auth($auth='') {
2379 $authplugin = get_auth_plugin($auth); // throws error if bad $auth
2380 return $authplugin->is_internal();
a3f1f815 2381}
2382
8c3dba73 2383/**
2384 * Returns an array of user fields
2385 *
c6d15803 2386 * @uses $CFG
2387 * @uses $db
2388 * @return array User field/column names
8c3dba73 2389 */
a3f1f815 2390function get_user_fieldnames() {
a3f1f815 2391
2392 global $CFG, $db;
2393
2394 $fieldarray = $db->MetaColumnNames($CFG->prefix.'user');
2395 unset($fieldarray['ID']);
2396
2397 return $fieldarray;
ba7166c3 2398}
f9903ed0 2399
7cf1c7bd 2400/**
2401 * Creates a bare-bones user record
2402 *
2403 * @uses $CFG
7cf1c7bd 2404 * @param string $username New user's username to add to record
2405 * @param string $password New user's password to add to record
2406 * @param string $auth Form of authentication required
68fbd8e1 2407 * @return object A {@link $USER} object
7cf1c7bd 2408 * @todo Outline auth types and provide code example
2409 */
71f9abf9 2410function create_user_record($username, $password, $auth='') {
366dfa60 2411 global $CFG;
71f9abf9 2412
1e22bc9c 2413 //just in case check text case
2414 $username = trim(moodle_strtolower($username));
71f9abf9 2415
03d820c7 2416 $authplugin = get_auth_plugin($auth);
2417
2418 if (method_exists($authplugin, 'get_userinfo')) {
2419 if ($newinfo = $authplugin->get_userinfo($username)) {
b36a8fc4 2420 $newinfo = truncate_userinfo($newinfo);
34daec9b 2421 foreach ($newinfo as $key => $value){
9f44d972 2422 $newuser->$key = addslashes(stripslashes($value)); // Just in case
e858f9da 2423 }
2424 }
2425 }
f9903ed0 2426
85a1d4c9 2427 if (!empty($newuser->email)) {
2428 if (email_is_not_allowed($newuser->email)) {
2429 unset($newuser->email);
2430 }
2431 }
2432
71f9abf9 2433 $newuser->auth = (empty($auth)) ? $CFG->auth : $auth;
faebaf0f 2434 $newuser->username = $username;
df193157 2435 update_internal_user_password($newuser, $password, false);
e51917eb 2436
2437 // fix for MDL-8480
2438 // user CFG lang for user if $newuser->lang is empty
2439 // or $user->lang is not an installed language
2440 $sitelangs = array_keys(get_list_of_languages());
2441 if (empty($newuser->lang) || !in_array($newuser->lang, $sitelangs)) {
2442 $newuser -> lang = $CFG->lang;
2443 }
faebaf0f 2444 $newuser->confirmed = 1;
d96466d2 2445 $newuser->lastip = getremoteaddr();
faebaf0f 2446 $newuser->timemodified = time();
03d820c7 2447 $newuser->mnethostid = $CFG->mnet_localhost_id;
f9903ed0 2448
b0ccd3fb 2449 if (insert_record('user', $newuser)) {
7c12949d 2450 $user = get_complete_user_data('username', $newuser->username);
d35757eb 2451 if($CFG->{'auth_'.$newuser->auth.'_forcechangepassword'}){
4b598ff4 2452 set_user_preference('auth_forcepasswordchange', 1, $user->id);
d35757eb 2453 }
2454 return $user;
faebaf0f 2455 }
2456 return false;
2457}
2458
7cf1c7bd 2459/**
2460 * Will update a local user record from an external source
2461 *
2462 * @uses $CFG
2463 * @param string $username New user's username to add to record
89dcb99d 2464 * @return user A {@link $USER} object
7cf1c7bd 2465 */
03d820c7 2466function update_user_record($username, $authplugin) {
2467 if (method_exists($authplugin, 'get_userinfo')) {
d35757eb 2468 $username = trim(moodle_strtolower($username)); /// just in case check text case
2469
b78fbdac 2470 $oldinfo = get_record('user', 'username', $username, '','','','', 'username, auth');
03d820c7 2471 $userauth = get_auth_plugin($oldinfo->auth);
b78fbdac 2472
03d820c7 2473 if ($newinfo = $authplugin->get_userinfo($username)) {
4b598ff4 2474 $newinfo = truncate_userinfo($newinfo);
d35757eb 2475 foreach ($newinfo as $key => $value){
b78fbdac 2476 $confkey = 'field_updatelocal_' . $key;
03d820c7 2477 if (!empty($userauth->config->$confkey) and $userauth->config->$confkey === 'onlogin') {
d35757eb 2478 $value = addslashes(stripslashes($value)); // Just in case
e1ecf0a0 2479 set_field('user', $key, $value, 'username', $username)
03d820c7 2480 or error_log("Error updating $key for $username");
d35757eb 2481 }
2482 }
2483 }
2484 }
7c12949d 2485 return get_complete_user_data('username', $username);
d35757eb 2486}
0609562b 2487
b36a8fc4 2488function truncate_userinfo($info) {
2489/// will truncate userinfo as it comes from auth_get_userinfo (from external auth)
2490/// which may have large fields
2491
2492 // define the limits
2493 $limit = array(
2494 'username' => 100,
1c66bf59 2495 'idnumber' => 64,
8bcd295c 2496 'firstname' => 100,
2497 'lastname' => 100,
b36a8fc4 2498 'email' => 100,
2499 'icq' => 15,
2500 'phone1' => 20,
2501 'phone2' => 20,
2502 'institution' => 40,
2503 'department' => 30,
2504 'address' => 70,
2505 'city' => 20,
2506 'country' => 2,
2507 'url' => 255,
2508 );
361855e6 2509
b36a8fc4 2510 // apply where needed
2511 foreach (array_keys($info) as $key) {
2512 if (!empty($limit[$key])) {
adfc03f9 2513 $info[$key] = trim(substr($info[$key],0, $limit[$key]));
361855e6 2514 }
b36a8fc4 2515 }
361855e6 2516
b36a8fc4 2517 return $info;
2518}
2519
7cf1c7bd 2520/**
2521 * Retrieve the guest user object
2522 *
2523 * @uses $CFG
89dcb99d 2524 * @return user A {@link $USER} object
7cf1c7bd 2525 */
0609562b 2526function guest_user() {
2527 global $CFG;
2528
b0ccd3fb 2529 if ($newuser = get_record('user', 'username', 'guest')) {
0609562b 2530 $newuser->confirmed = 1;
0609562b 2531 $newuser->lang = $CFG->lang;
d96466d2 2532 $newuser->lastip = getremoteaddr();
0609562b 2533 }
2534
2535 return $newuser;
2536}
2537
7cf1c7bd 2538/**
2539 * Given a username and password, this function looks them
2540 * up using the currently selected authentication mechanism,
2541 * and if the authentication is successful, it returns a
2542 * valid $user object from the 'user' table.
361855e6 2543 *
7cf1c7bd 2544 * Uses auth_ functions from the currently active auth module
2545 *
2546 * @uses $CFG
361855e6 2547 * @param string $username User's username
2548 * @param string $password User's password
89dcb99d 2549 * @return user|flase A {@link $USER} object or false if error
7cf1c7bd 2550 */
faebaf0f 2551function authenticate_user_login($username, $password) {
faebaf0f 2552
2553 global $CFG;
2554
03d820c7 2555 // default to manual if global auth is undefined or broken
2556 if (empty($CFG->auth_plugins_enabled)) {
2557 $CFG->auth_plugins_enabled = empty($CFG->auth) ? 'manual' : $CFG->auth;
2558 }
2559 // if blank, set default auth to first enabled auth plugin
2560 if (empty($CFG->auth)) {
2561 $auths = explode(',', $CFG->auth_plugins_enabled);
2562 $CFG->auth = $auths[0];
2563 }
466558e3 2564
03d820c7 2565 // if user not found, use site auth
7c12949d 2566 if (!$user = get_complete_user_data('username', $username)) {
03d820c7 2567 $user = new object();
18f16d61 2568 $user->id = 0; // Not a user
03d820c7 2569 $auth = $CFG->auth_plugins_enabled;
18f16d61 2570 }
39a5a35d 2571
27286aeb 2572 // Sort out the authentication method we are using.
27286aeb 2573 if (empty($user->auth)) { // For some reason it isn't set yet
b7b97864 2574 $primadmin = get_admin();
2575 if (!empty($user->id) && (($user->id==$primadmin->id) || isguest($user->id))) {
03d820c7 2576 $auth = 'manual'; // always assume these guys are internal
27286aeb 2577 }
03d820c7 2578 else {
2579 $auth = $CFG->auth_plugins_enabled; // default to site method
d35757eb 2580 }
71f9abf9 2581 } else {
2582 $auth = $user->auth;
27286aeb 2583 }
8f0cd6ef 2584
03d820c7 2585 // walk each authentication plugin, in order
2586 $auths = explode(',', $auth);
2587 foreach ($auths as $auth) {
2588 $authplugin = get_auth_plugin($auth);
466558e3 2589
03d820c7 2590 // on auth fail, log and fall through to the next plugin
2591 if (!$authplugin->user_login($username, $password)) {
2592 add_to_log(0, 'login', 'error', 'index.php', $username);
2593 error_log("[client {$_SERVER['REMOTE_ADDR']}] $CFG->wwwroot Auth=$auth Failed Login: $username {$_SERVER['HTTP_USER_AGENT']}");
2594 continue;
2595 }
faebaf0f 2596
03d820c7 2597 // successful authentication
d613daf0 2598 if ($user->id) { // User already exists in database
71f9abf9 2599 if (empty($user->auth)) { // For some reason auth isn't set yet
2600 set_field('user', 'auth', $auth, 'username', $username);
2601 }
df193157 2602 update_internal_user_password($user, $password);
03d820c7 2603 if (!$authplugin->is_internal()) { // update user record from external DB
2604 $user = update_user_record($username, get_auth_plugin($user->auth));
d35757eb 2605 }
faebaf0f 2606 } else {
71f9abf9 2607 $user = create_user_record($username, $password, $auth);
faebaf0f 2608 }
03d820c7 2609 // fix for MDL-6928
2610 if (method_exists($authplugin, 'iscreator')) {
c768b610 2611 $sitecontext = get_context_instance(CONTEXT_SYSTEM);
2612 if ($creatorroles = get_roles_with_capability('moodle/legacy:coursecreator', CAP_ALLOW)) {
2613 $creatorrole = array_shift($creatorroles); // We can only use one, let's use the first one
2614 // Check if the user is a creator
03d820c7 2615 if ($authplugin->iscreator($username)) { // Following calls will not create duplicates
b6c59cf7 2616 role_assign($creatorrole->id, $user->id, 0, $sitecontext->id, 0, 0, 0, $auth);
4158fd81 2617 } else {
2618 role_unassign($creatorrole->id, $user->id, 0, $sitecontext->id);
c768b610 2619 }
2620 }
2621 }
01af6da6 2622
2623 /// Log in to a second system if necessary
2624 if (!empty($CFG->sso)) {
2625 include_once($CFG->dirroot .'/sso/'. $CFG->sso .'/lib.php');
2626 if (function_exists('sso_user_login')) {
2627 if (!sso_user_login($username, $password)) { // Perform the signon process
2628 notify('Second sign-on failed');
2629 }
2630 }
2631 }
2632
e582b65e 2633 return $user;
9d3c795c 2634
03d820c7 2635 }
2636
2637 // failed if all the plugins have failed
2638 add_to_log(0, 'login', 'error', 'index.php', $username);
2639 error_log('[client '.$_SERVER['REMOTE_ADDR']."] $CFG->wwwroot Failed Login: $username ".$_SERVER['HTTP_USER_AGENT']);
2640 return false;
f9903ed0 2641}
2642
df193157 2643/**
4908ad3e 2644 * Compare password against hash stored in internal user table.
df193157 2645 * If necessary it also updates the stored hash to new format.
2646 *
2647 * @param object user
2648 * @param string plain text password
2649 * @return bool is password valid?
2650 */
2651function validate_internal_user_password(&$user, $password) {
2652 global $CFG;
2653
4908ad3e 2654 if (!isset($CFG->passwordsaltmain)) {
2655 $CFG->passwordsaltmain = '';
2656 }
2657
df193157 2658 $validated = false;
2659
fb773106 2660 // get password original encoding in case it was not updated to unicode yet
2661 $textlib = textlib_get_instance();
810944af 2662 $convpassword = $textlib->convert($password, 'utf-8', get_string('oldcharset'));
df193157 2663
4908ad3e 2664 if ($user->password == md5($password.$CFG->passwordsaltmain) or $user->password == md5($password)
2665 or $user->password == md5($convpassword.$CFG->passwordsaltmain) or $user->password == md5($convpassword)) {
df193157 2666 $validated = true;
4908ad3e 2667 } else {
aaeaa4b0 2668 for ($i=1; $i<=20; $i++) { //20 alternative salts should be enough, right?
4908ad3e 2669 $alt = 'passwordsaltalt'.$i;
2670 if (!empty($CFG->$alt)) {
2671 if ($user->password == md5($password.$CFG->$alt) or $user->password == md5($convpassword.$CFG->$alt)) {
2672 $validated = true;
2673 break;
2674 }
2675 }
2676 }
df193157 2677 }
2678
2679 if ($validated) {
4908ad3e 2680 // force update of password hash using latest main password salt and encoding if needed
df193157 2681 update_internal_user_password($user, $password);
2682 }
2683
2684 return $validated;
2685}
2686
2687/**
2688 * Calculate hashed value from password using current hash mechanism.
df193157 2689 *
2690 * @param string password
2691 * @return string password hash
2692 */
2693function hash_internal_user_password($password) {
4908ad3e 2694 global $CFG;
2695
2696 if (isset($CFG->passwordsaltmain)) {
2697 return md5($password.$CFG->passwordsaltmain);
2698 } else {
2699 return md5($password);
2700 }
df193157 2701}
2702
2703/**
2704 * Update pssword hash in user object.
2705 *
2706 * @param object user
2707 * @param string plain text password
2708 * @param bool store changes also in db, default true
2709 * @return true if hash changed
2710 */
2711function update_internal_user_password(&$user, $password, $storeindb=true) {
2712 global $CFG;
2713
03d820c7 2714 $authplugin = get_auth_plugin($user->auth);
2715 if (!empty($authplugin->config->preventpassindb) /*|| $storeindb === false */) {
df193157 2716 $hashedpassword = 'not cached';
2717 } else {
2718 $hashedpassword = hash_internal_user_password($password);
2719 }
2720
b7b50143 2721 return set_field('user', 'password', $hashedpassword, 'id', $user->id);
df193157 2722}
2723
7c12949d 2724/**
2725 * Get a complete user record, which includes all the info
5c98bf9e 2726 * in the user record
7c12949d 2727 * Intended for setting as $USER session variable
2728 *
2729 * @uses $CFG
2730 * @uses SITEID
e1ecf0a0 2731 * @param string $field The user field to be checked for a given value.
7c12949d 2732 * @param string $value The value to match for $field.
2733 * @return user A {@link $USER} object.
2734 */
b7b50143 2735function get_complete_user_data($field, $value, $mnethostid=null) {
7c12949d 2736
2737 global $CFG;
2738
2739 if (!$field || !$value) {
2740 return false;
2741 }
2742
b7b50143 2743/// Build the WHERE clause for an SQL query
2744
2745 $constraints = $field .' = \''. $value .'\' AND deleted <> \'1\'';
2746
2747 if (null === $mnethostid) {
2748 $constraints .= ' AND auth != \'mnet\'';
2749 } elseif (is_numeric($mnethostid)) {
2750 $constraints .= ' AND mnethostid = \''.$mnethostid.'\'';
2751 } else {
2752 error_log('Call to get_complete_user_data for $field='.$field.', $value = '.$value.', with invalid $mnethostid: '. $mnethostid);
2753 print_error('invalidhostlogin','mnet', $CFG->wwwroot.'/login/index.php');
2754 exit;
2755 }
2756
7c12949d 2757/// Get all the basic user data
2758
b7b50143 2759 if (! $user = get_record_select('user', $constraints)) {
7c12949d 2760 return false;
2761 }
2762
7c12949d 2763/// Get various settings and preferences
2764
2765 if ($displays = get_records('course_display', 'userid', $user->id)) {
2766 foreach ($displays as $display) {
2767 $user->display[$display->course] = $display->display;
2768 }
2769 }
2770
2771 if ($preferences = get_records('user_preferences', 'userid', $user->id)) {
2772 foreach ($preferences as $preference) {
2773 $user->preference[$preference->name] = $preference->value;
2774 }
2775 }
2776
721d14cb 2777 if ($lastaccesses = get_records('user_lastaccess', 'userid', $user->id)) {
2778 foreach ($lastaccesses as $lastaccess) {
2779 $user->lastcourseaccess[$lastaccess->courseid] = $lastaccess->timeaccess;
2780 }
2781 }
2782
f4ba7e1a 2783 if ($groupids = groups_get_all_groups_for_user($user->id)) { //TODO:check.
2784 foreach ($groupids as $groupid) {
2785 $courseid = groups_get_course($groupid);
fa22fd5f 2786 //change this to 2D array so we can put multiple groups in a course
f4ba7e1a 2787 $user->groupmember[$courseid][] = $groupid;
7c12949d 2788 }
2789 }
2790
2791/// Rewrite some variables if necessary
2792 if (!empty($user->description)) {
2793 $user->description = true; // No need to cart all of it around
2794 }
2795 if ($user->username == 'guest') {
2796 $user->lang = $CFG->lang; // Guest language always same as site
2797 $user->firstname = get_string('guestuser'); // Name always in current language
2798 $user->lastname = ' ';
2799 }
2800
7c12949d 2801 $user->sesskey = random_string(10);
2802 $user->sessionIP = md5(getremoteaddr()); // Store the current IP in the session
2803
2804 return $user;
7c12949d 2805}
2806
7c12949d 2807
5c98bf9e 2808
e1ecf0a0 2809/*
7c12949d 2810 * When logging in, this function is run to set certain preferences
2811 * for the current SESSION
2812 */
2813function set_login_session_preferences() {
7c7ca1b5 2814 global $SESSION, $CFG;
7c12949d 2815
2816 $SESSION->justloggedin = true;
2817
2818 unset($SESSION->lang);
7c12949d 2819
2820 // Restore the calendar filters, if saved
2821 if (intval(get_user_preferences('calendar_persistflt', 0))) {
2822 include_once($CFG->dirroot.'/calendar/lib.php');
a266c904 2823 calendar_set_filters_status(get_user_preferences('calendav_savedflt', 0xff));
7c12949d 2824 }
2825}
2826
2827
b97c4164 2828/**
2829 * Delete a course, including all related data from the database,
2830 * and any associated files from the moodledata folder.
e1ecf0a0 2831 *
b97c4164 2832 * @param int $courseid The id of the course to delete.
2833 * @param bool $showfeedback Whether to display notifications of each action the function performs.
2834 * @return bool true if all the removals succeeded. false if there were any failures. If this
2835 * method returns false, some of the removals will probably have succeeded, and others
2836 * failed, but you have no way of knowing which.
2837 */
2838function delete_course($courseid, $showfeedback = true) {
2839 global $CFG;
2840 $result = true;
e1ecf0a0 2841
b97c4164 2842 if (!remove_course_contents($courseid, $showfeedback)) {
2843 if ($showfeedback) {
2844 notify("An error occurred while deleting some of the course contents.");
2845 }
2846 $result = false;
2847 }
2848
2849 if (!delete_records("course", "id", $courseid)) {
2850 if ($showfeedback) {
2851 notify("An error occurred while deleting the main course record.");
2852 }
2853 $result = false;
2854 }
2855
9991d157 2856 if (!delete_records('context', 'contextlevel', CONTEXT_COURSE, 'instanceid', $courseid)) {
eaa79489 2857 if ($showfeedback) {
2858 notify("An error occurred while deleting the main context record.");
2859 }
2860 $result = false;
2861 }
2862
b97c4164 2863 if (!fulldelete($CFG->dataroot.'/'.$courseid)) {
2864 if ($showfeedback) {
2865 notify("An error occurred while deleting the course files.");
2866 }
2867 $result = false;
2868 }
e1ecf0a0 2869
b97c4164 2870 return $result;
2871}
2872
7cf1c7bd 2873/**
2874 * Clear a course out completely, deleting all content
2875 * but don't delete the course itself
2876 *
7cf1c7bd 2877 * @uses $CFG
1f8ede91 2878 * @param int $courseid The id of the course that is being deleted
2879 * @param bool $showfeedback Whether to display notifications of each action the function performs.
b97c4164 2880 * @return bool true if all the removals succeeded. false if there were any failures. If this
2881 * method returns false, some of the removals will probably have succeeded, and others
2882 * failed, but you have no way of knowing which.
7cf1c7bd 2883 */
07aeb7b0 2884function remove_course_contents($courseid, $showfeedback=true) {
07aeb7b0 2885
1f8ede91 2886 global $CFG;
07aeb7b0 2887
2888 $result = true;
2889
b0ccd3fb 2890 if (! $course = get_record('course', 'id', $courseid)) {
2891 error('Course ID was incorrect (can\'t find it)');
07aeb7b0 2892 }
2893
b0ccd3fb 2894 $strdeleted = get_string('deleted');
07aeb7b0 2895
9991d157 2896/// First delete every instance of every module
d8ba183c 2897
b0ccd3fb 2898 if ($allmods = get_records('modules') ) {
07aeb7b0 2899 foreach ($allmods as $mod) {
2900 $modname = $mod->name;
b0ccd3fb 2901 $modfile = $CFG->dirroot .'/mod/'. $modname .'/lib.php';
2902 $moddelete = $modname .'_delete_instance'; // Delete everything connected to an instance
2903 $moddeletecourse = $modname .'_delete_course'; // Delete other stray stuff (uncommon)
07aeb7b0 2904 $count=0;
2905 if (file_exists($modfile)) {
2906 include_once($modfile);
2907 if (function_exists($moddelete)) {
b0ccd3fb 2908 if ($instances = get_records($modname, 'course', $course->id)) {
07aeb7b0 2909 foreach ($instances as $instance) {
eaa79489 2910 if ($cm = get_coursemodule_from_instance($modname, $instance->id, $course->id)) {
9991d157 2911 delete_context(CONTEXT_MODULE, $cm->id);
eaa79489 2912 }
07aeb7b0 2913 if ($moddelete($instance->id)) {
2914 $count++;
eaa79489 2915
07aeb7b0 2916 } else {
7eec3390 2917 notify('Could not delete '. $modname .' instance '. $instance->id .' ('. format_string($instance->name) .')');
07aeb7b0 2918 $result = false;
2919 }
2920 }
2921 }
2922 } else {
b0ccd3fb 2923 notify('Function '. $moddelete() .'doesn\'t exist!');
07aeb7b0 2924 $result = false;
2925 }
2926
ca952b03 2927 if (function_exists($moddeletecourse)) {
f67172b6 2928 $moddeletecourse($course, $showfeedback);
ca952b03 2929 }
07aeb7b0 2930 }
2931 if ($showfeedback) {
b0ccd3fb 2932 notify($strdeleted .' '. $count .' x '. $modname);
07aeb7b0 2933 }
2934 }
2935 } else {
b0ccd3fb 2936 error('No modules are installed!');
07aeb7b0 2937 }
2938
9991d157 2939/// Give local code a chance to delete its references to this course.
c0b5b31a 2940 require_once('locallib.php');
2941 notify_local_delete_course($courseid, $showfeedback);
2942
9991d157 2943/// Delete course blocks
7f869120 2944
2945 if ($blocks = get_records_sql("SELECT *
2946 FROM {$CFG->prefix}block_instance
2947 WHERE pagetype = '".PAGE_COURSE_VIEW."'
2948 AND pageid = $course->id")) {
eaa79489 2949 if (delete_records('block_instance', 'pagetype', PAGE_COURSE_VIEW, 'pageid', $course->id)) {
2950 if ($showfeedback) {
2951 notify($strdeleted .' block_instance');
2952 }
9991d157 2953 foreach ($blocks as $block) { /// Delete any associated contexts for this block
2954 delete_context(CONTEXT_BLOCK, $block->id);
2955 }
2956 } else {
2957 $result = false;
2958 }
2959 }
2960
2dee6abd 2961/// Delete any groups, removing members and grouping/course links first.
2962 //TODO: If groups or groupings are to be shared between courses, think again!
f4ba7e1a 2963 if ($groupids = groups_get_groups($course->id)) {
2964 foreach ($groupids as $groupid) {
2dee6abd 2965 if (groups_remove_all_members($groupid)) {
f4ba7e1a 2966 if ($showfeedback) {
2967 notify($strdeleted .' groups_members');
2968 }
2969 } else {
2970 $result = false;
9991d157 2971 }
f4ba7e1a 2972 /// Delete any associated context for this group ??
2dee6abd 2973 delete_context(CONTEXT_GROUP, $groupid);
f4ba7e1a 2974
2975 if (groups_delete_group($groupid)) {
2976 if ($showfeedback) {
2977 notify($strdeleted .' groups');
9991d157 2978 }
f4ba7e1a 2979 } else {
2980 $result = false;
9991d157 2981 }
251af423 2982 }
251af423 2983 }
2dee6abd 2984/// Delete any groupings.
2985 $result = groups_delete_all_groupings($course->id);
2986 if ($result && $showfeedback) {
2987 notify($strdeleted .' groupings');
2988 }
251af423 2989
9991d157 2990/// Delete all related records in other tables that may have a courseid
2991/// This array stores the tables that need to be cleared, as
2992/// table_name => column_name that contains the course id.
2993
09481160 2994 $tablestoclear = array(
09481160 2995 'event' => 'courseid', // Delete events
2996 'log' => 'course', // Delete logs
2997 'course_sections' => 'course', // Delete any course stuff
2998 'course_modules' => 'course',
2999 'grade_category' => 'courseid', // Delete gradebook stuff
3000 'grade_exceptions' => 'courseid',
3001 'grade_item' => 'courseid',
3002 'grade_letter' => 'courseid',
d148c0ed 3003 'grade_preferences' => 'courseid',
3004 'backup_courses' => 'courseid', // Delete scheduled backup stuff
3005 'backup_log' => 'courseid'
09481160 3006 );
3007 foreach ($tablestoclear as $table => $col) {
3008 if (delete_records($table, $col, $course->id)) {
3009 if ($showfeedback) {
3010 notify($strdeleted . ' ' . $table);
3011 }
3012 } else {
3013 $result = false;
07aeb7b0 3014 }
07aeb7b0 3015 }
3016
9991d157 3017
3018/// Clean up metacourse stuff
082e3ebc 3019
5f37b628 3020 if ($course->metacourse) {
3021 delete_records("course_meta","parent_course",$course->id);
b61efafb 3022 sync_metacourse($course->id); // have to do it here so the enrolments get nuked. sync_metacourses won't find it without the id.
3023 if ($showfeedback) {
5f37b628 3024 notify("$strdeleted course_meta");
b61efafb 3025 }
7ff9860d 3026 } else {
5f37b628 3027 if ($parents = get_records("course_meta","child_course",$course->id)) {
b61efafb 3028 foreach ($parents as $parent) {
3029 remove_from_metacourse($parent->parent_course,$parent->child_course); // this will do the unenrolments as well.
3030 }
3031 if ($showfeedback) {
5f37b628 3032 notify("$strdeleted course_meta");
b61efafb 3033 }
3034 }
3035 }
3036
9991d157 3037/// Delete questions and question categories
f67172b6 3038 include_once($CFG->libdir.'/questionlib.php');
3039 question_delete_course($course, $showfeedback);
3040
9991d157 3041/// Delete all roles and overiddes in the course context (but keep the course context)
39474844 3042 if ($courseid != SITEID) {
3043 delete_context(CONTEXT_COURSE, $course->id);
3044 }
3045
07aeb7b0 3046 return $result;
07aeb7b0 3047}
3048
ffd0fbb7 3049
7cf1c7bd 3050/**
ffd0fbb7 3051 * This function will empty a course of USER data as much as
3052/// possible. It will retain the activities and the structure
3053/// of the course.
7cf1c7bd 3054 *
ffd0fbb7 3055 * @uses $USER
3056 * @uses $SESSION
7cf1c7bd 3057 * @uses $CFG
ffd0fbb7 3058 * @param object $data an object containing all the boolean settings and courseid
3059 * @param bool $showfeedback if false then do it all silently
3060 * @return bool
3061 * @todo Finish documenting this function
7cf1c7bd 3062 */
ffd0fbb7 3063function reset_course_userdata($data, $showfeedback=true) {
3831de52 3064
ffd0fbb7 3065 global $CFG, $USER, $SESSION;
3831de52 3066
3067 $result = true;
3068
b0ccd3fb 3069 $strdeleted = get_string('deleted');
3831de52 3070
3071 // Look in every instance of every module for data to delete
3072
b0ccd3fb 3073 if ($allmods = get_records('modules') ) {
3831de52 3074 foreach ($allmods as $mod) {
3075 $modname = $mod->name;
b0ccd3fb 3076 $modfile = $CFG->dirroot .'/mod/'. $modname .'/lib.php';
3077 $moddeleteuserdata = $modname .'_delete_userdata'; // Function to delete user data
3831de52 3078 if (file_exists($modfile)) {
3079 @include_once($modfile);
3080 if (function_exists($moddeleteuserdata)) {
ffd0fbb7 3081 $moddeleteuserdata($data, $showfeedback);
3831de52 3082 }
3083 }
3084 }
3085 } else {
b0ccd3fb 3086 error('No modules are installed!');
3831de52 3087 }
3088
3089 // Delete other stuff
20d55a1b 3090 $coursecontext = get_context_instance(CONTEXT_COURSE, $data->courseid);
3831de52 3091
20d55a1b 3092 if (!empty($data->reset_students) or !empty($data->reset_teachers)) {
3093 $teachers = array_keys(get_users_by_capability($coursecontext, 'moodle/course:update'));
3094 $participants = array_keys(get_users_by_capability($coursecontext, 'moodle/course:view'));
3095 $students = array_diff($participants, $teachers);
3096
3097 if (!empty($data->reset_students)) {
3098 foreach ($students as $studentid) {
3099 role_unassign(0, $studentid, 0, $coursecontext->id);
3100 }
3831de52 3101 if ($showfeedback) {
20d55a1b 3102 notify($strdeleted .' '.get_string('students'), 'notifysuccess');
3831de52 3103 }
d76a5a7f 3104
f4ba7e1a 3105 /// Delete group members (but keep the groups) TODO:check.
3106 if ($groupids = groups_get_groups($data->courseid)) {
3107 foreach ($groupids as $groupid) {
3108 if (groups_remove_all_group_members($groupid)) {
20d55a1b 3109 if ($showfeedback) {
3110 notify($strdeleted .' groups_members', 'notifysuccess');
3111 }
3112 } else {
3113 $result = false;
3831de52 3114 }
3831de52 3115 }
3116 }
3117 }
3831de52 3118
20d55a1b 3119 if (!empty($data->reset_teachers)) {
3120 foreach ($teachers as $teacherid) {
3121 role_unassign(0, $teacherid, 0, $coursecontext->id);
3122 }
3831de52 3123 if ($showfeedback) {
20d55a1b 3124 notify($strdeleted .' '.get_string('teachers'), 'notifysuccess');
3831de52 3125 }
3831de52 3126 }
3127 }
3128
ffd0fbb7 3129 if (!empty($data->reset_groups)) {
f4ba7e1a 3130 if ($groupids = groups_get_groups($data->courseid)) {
3131 foreach ($groupids as $groupid) {
3132 if (groups_delete_group($groupid)) {
3831de52 3133 if ($showfeedback) {
ffd0fbb7 3134 notify($strdeleted .' groups', 'notifysuccess');
3831de52 3135 }
3136 } else {
3137 $result = false;
3138 }
3139 }
3140 }
3141 }
3142
ffd0fbb7 3143 if (!empty($data->reset_events)) {
3144 if (delete_records('event', 'courseid', $data->courseid)) {
3831de52 3145 if ($showfeedback) {
ffd0fbb7 3146 notify($strdeleted .' event', 'notifysuccess');
3831de52 3147 }
3148 } else {
3149 $result = false;
3150 }
3151 }
3152
ffd0fbb7 3153 if (!empty($data->reset_logs)) {
3154 if (delete_records('log', 'course', $data->courseid)) {
3831de52 3155 if ($showfeedback) {
ffd0fbb7 3156 notify($strdeleted .' log', 'notifysuccess');
3831de52 3157 }
3158 } else {
3159 $result = false;
3160 }
3161 }
3162
ea8158c1 3163 // deletes all role assignments, and local override, these have no courseid in table and needs separate process
9fd73f0c 3164 $context = get_context_instance(CONTEXT_COURSE, $data->courseid);
1bacd276 3165 delete_records('role_capabilities', 'contextid', $context->id);
20d55a1b 3166
3831de52 3167 return $result;
3831de52 3168}
3169
ffd0fbb7 3170
f4ba7e1a 3171require_once($CFG->dirroot.'/group/lib.php');
3172/*TODO: functions moved to /group/lib/legacylib.php
f374fb10 3173
f4ba7e1a 3174ismember
3175add_user_to_group
3176mygroupid
3177groupmode
3178set_current_group
3179... */
f374fb10 3180
0d67c514 3181
bb64b51a 3182function generate_email_processing_address($modid,$modargs) {
3183 global $CFG;
303d0af1 3184
3185 if (empty($CFG->siteidentifier)) { // Unique site identification code
3186 set_config('siteidentifier', random_string(32));
bb64b51a 3187 }
d2a9f7cc 3188
bb64b51a 3189 $header = $CFG->mailprefix . substr(base64_encode(pack('C',$modid)),0,2).$modargs;
2019116e 3190 return $header . substr(md5($header.$CFG->siteidentifier),0,16).'@'.$CFG->maildomain;
bb64b51a 3191}
3192
f374fb10 3193
bb64b51a 3194function moodle_process_email($modargs,$body) {
3195 // the first char should be an unencoded letter. We'll take this as an action
3196 switch ($modargs{0}) {
3197 case 'B': { // bounce
3198 list(,$userid) = unpack('V',base64_decode(substr($modargs,1,8)));
3199 if ($user = get_record_select("user","id=$userid","id,email")) {
3200 // check the half md5 of their email
3201 $md5check = substr(md5($user->email),0,16);
e67755a1 3202 if ($md5check == substr($modargs, -16)) {
bb64b51a 3203 set_bounce_count($user);
3204 }
3205 // else maybe they've already changed it?
3206 }
3207 }
3208 break;
3209 // maybe more later?
3210 }
3211}
f374fb10 3212
f9903ed0 3213/// CORRESPONDENCE ////////////////////////////////////////////////
3214
7cf1c7bd 3215/**
3216 * Send an email to a specified user
3217 *
7cf1c7bd 3218 * @uses $CFG
bbd3f2c4 3219 * @uses $FULLME
c6d15803 3220 * @uses SITEID
89dcb99d 3221 * @param user $user A {@link $USER} object
3222 * @param user $from A {@link $USER} object
7cf1c7bd 3223 * @param string $subject plain text subject line of the email
3224 * @param string $messagetext plain text version of the message
3225 * @param string $messagehtml complete html version of the message (optional)
3226 * @param string $attachment a file on the filesystem, relative to $CFG->dataroot
3227 * @param string $attachname the name of the file (extension indicates MIME)
bbd3f2c4 3228 * @param bool $usetrueaddress determines whether $from email address should
c6d15803 3229 * be sent out. Will be overruled by user profile setting for maildisplay
bbd3f2c4 3230 * @return bool|string Returns "true" if mail was sent OK, "emailstop" if email
c6d15803 3231 * was blocked by user and "false" if there was another sort of error.
7cf1c7bd 3232 */
043f5274 3233function email_to_user($user, $from, $subject, $messagetext, $messagehtml='', $attachment='', $attachname='', $usetrueaddress=true, $replyto='', $replytoname='') {
f9903ed0 3234
dcf6d93c 3235 global $CFG, $FULLME;
0cc6fa6a 3236
b0ccd3fb 3237 include_once($CFG->libdir .'/phpmailer/class.phpmailer.php');
f9903ed0 3238
b212c114 3239/// We are going to use textlib services here
3240 $textlib = textlib_get_instance();
3241
cadb96f2 3242 if (empty($user)) {
3243 return false;
3244 }
3245
3246 if (!empty($user->emailstop)) {
579dcca4 3247 return 'emailstop';
f9903ed0 3248 }
d2a9f7cc 3249