mnet: introducing print_remote_host()... and use it in print_my_courses() - add a...
[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;
589 $config->value = $value;
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)) {
13af52a6 739 if (empty($otheruser) and !empty($USER)) {
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)) {
13af52a6 752 if (empty($otheruser) and !empty($USER)) {
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
1550
7cf1c7bd 1551/**
ec81373f 1552 * This function checks that the current user is logged in and has the
1553 * required privileges
1554 *
7cf1c7bd 1555 * This function checks that the current user is logged in, and optionally
ec81373f 1556 * whether they are allowed to be in a particular course and view a particular
1557 * course module.
1558 * If they are not logged in, then it redirects them to the site login unless
d2a9f7cc 1559 * $autologinguest is set and {@link $CFG}->autologinguests is set to 1 in which
ec81373f 1560 * case they are automatically logged in as guests.
1561 * If $courseid is given and the user is not enrolled in that course then the
1562 * user is redirected to the course enrolment page.
1563 * If $cm is given and the coursemodule is hidden and the user is not a teacher
1564 * in the course then the user is redirected to the course home page.
7cf1c7bd 1565 *
7cf1c7bd 1566 * @uses $CFG
c6d15803 1567 * @uses $SESSION
7cf1c7bd 1568 * @uses $USER
1569 * @uses $FULLME
c6d15803 1570 * @uses SITEID
f07fa644 1571 * @uses $COURSE
7cf1c7bd 1572 * @uses $MoodleSession
ec81373f 1573 * @param int $courseid id of the course
bbd3f2c4 1574 * @param bool $autologinguest
1575 * @param object $cm course module object
7cf1c7bd 1576 */
ec81373f 1577function require_login($courseid=0, $autologinguest=true, $cm=null) {
f9903ed0 1578
f07fa644 1579 global $CFG, $SESSION, $USER, $COURSE, $FULLME, $MoodleSession;
d8ba183c 1580
1845f8b8 1581/// Redefine global $COURSE if we can
45fc1f75 1582 global $course; // We use the global hack once here so it doesn't need to be used again
c4d0753b 1583 if (is_object($course) and !empty($course->id) and ($courseid == 0 || $course->id == $courseid)) {
45fc1f75 1584 $COURSE = clone($course);
1585 } else if ($courseid) {
1586 $COURSE = get_record('course', 'id', $courseid);
8a58a8e1 1587 }
1588
be933850 1589 if (!empty($COURSE->lang)) {
1590 $CFG->courselang = $COURSE->lang;
1591 moodle_setlocale();
1592 }
1593
1845f8b8 1594/// If the user is not even logged in yet then make sure they are
1595 if (! (isset($USER->loggedin) and $USER->confirmed and ($USER->site == $CFG->wwwroot)) ) {
f9903ed0 1596 $SESSION->wantsurl = $FULLME;
b0ccd3fb 1597 if (!empty($_SERVER['HTTP_REFERER'])) {
1598 $SESSION->fromurl = $_SERVER['HTTP_REFERER'];
9f44d972 1599 }
c21c671d 1600 $USER = NULL;
9a76d7b9 1601 if ($autologinguest && !empty($CFG->autologinguests) and
1845f8b8 1602 $courseid and ($courseid == SITEID or get_field('course','guest','id',$courseid)) ) {
8e8d0524 1603 $loginguest = '?loginguest=true';
1604 } else {
1605 $loginguest = '';
a2ebe6a5 1606 }
8a33e371 1607 if (empty($CFG->loginhttps)) {
b0ccd3fb 1608 redirect($CFG->wwwroot .'/login/index.php'. $loginguest);
8a33e371 1609 } else {
2c3432e6 1610 $wwwroot = str_replace('http:','https:', $CFG->wwwroot);
b0ccd3fb 1611 redirect($wwwroot .'/login/index.php'. $loginguest);
8a33e371 1612 }
20fde7b1 1613 exit;
f9903ed0 1614 }
808a3baa 1615
1845f8b8 1616/// check whether the user should be changing password
03d820c7 1617 $userauth = get_auth_plugin($USER->auth);
a3f1f815 1618 if (!empty($USER->preference['auth_forcepasswordchange'])){
03d820c7 1619 if ($userauth->can_change_password()) {
20fde7b1 1620 $SESSION->wantsurl = $FULLME;
1437f0a5 1621 if (empty($CFG->loginhttps)) {
1622 redirect($CFG->wwwroot .'/login/change_password.php');
1623 } else {
1624 $wwwroot = str_replace('http:','https:', $CFG->wwwroot);
1625 redirect($wwwroot .'/login/change_password.php');
1626 }
03d820c7 1627 } elseif($userauth->change_password_url()) {
63b1e351 1628 redirect($userauth->change_password_url());
d35757eb 1629 } else {
361855e6 1630 error('You cannot proceed without changing your password.
d35757eb 1631 However there is no available page for changing it.
b0ccd3fb 1632 Please contact your Moodle Administrator.');
d35757eb 1633 }
1634 }
1845f8b8 1635/// Check that the user account is properly set up
808a3baa 1636 if (user_not_fully_set_up($USER)) {
20fde7b1 1637 $SESSION->wantsurl = $FULLME;
b0ccd3fb 1638 redirect($CFG->wwwroot .'/user/edit.php?id='. $USER->id .'&amp;course='. SITEID);
808a3baa 1639 }
d8ba183c 1640
1845f8b8 1641/// Make sure current IP matches the one for this session (if required)
361855e6 1642 if (!empty($CFG->tracksessionip)) {
366dfa60 1643 if ($USER->sessionIP != md5(getremoteaddr())) {
1644 error(get_string('sessionipnomatch', 'error'));
1645 }
1646 }
6d8f47d6 1647
1845f8b8 1648/// Make sure the USER has a sesskey set up. Used for checking script parameters.
04280e85 1649 sesskey();
366dfa60 1650
027a1604 1651 // Check that the user has agreed to a site policy if there is one
1652 if (!empty($CFG->sitepolicy)) {
1653 if (!$USER->policyagreed) {
957b5198 1654 $SESSION->wantsurl = $FULLME;
027a1604 1655 redirect($CFG->wwwroot .'/user/policy.php');
027a1604 1656 }
1695b680 1657 }
1658
1845f8b8 1659/// If the site is currently under maintenance, then print a message
9c37662f 1660 if (!has_capability('moodle/site:config',get_context_instance(CONTEXT_SYSTEM, SITEID))) {
eeefd0b0 1661 if (file_exists($CFG->dataroot.'/'.SITEID.'/maintenance.html')) {
1695b680 1662 print_maintenance_message();
20fde7b1 1663 exit;
1695b680 1664 }
027a1604 1665 }
1666
1845f8b8 1667/// Next, check if the user can be in a particular course
da5c172a 1668 if ($courseid) {
1845f8b8 1669
1670 /// Sanity check on the courseid
1671
1672 if ($courseid == $COURSE->id) { /// Pretty much always true but let's be sure
1673 $course = $COURSE;
1674 } else if (! $course = get_record('course', 'id', $courseid)) {
1675 error('That course doesn\'t exist');
1676 }
1677
1678 /// We can eliminate hidden site activities straight away
1679
1680 if ($course->id == SITEID) {
1681 if (!empty($cm) && !$cm->visible and !has_capability('moodle/course:viewhiddenactivities',
1682 get_context_instance(CONTEXT_SYSTEM, SITEID))) {
1683 redirect($CFG->wwwroot, get_string('activityiscurrentlyhidden'));
ec81373f 1684 }
d2a9f7cc 1685 return;
e3512050 1686 }
881a77bf 1687
1845f8b8 1688
1689 /// If the whole course is hidden from us then we can stop now
1690
1845f8b8 1691 if (!$context = get_context_instance(CONTEXT_COURSE, $course->id)) {
1692 print_error('nocontext');
1693 }
1694
881a77bf 1695 if (empty($USER->switchrole[$context->id]) &&
1696 !($course->visible && course_parent_visible($course)) &&
1697 !has_capability('moodle/course:viewhiddencourses', get_context_instance(CONTEXT_COURSE, $course->id)) ){
1698 print_header_simple();
1699 notice(get_string('coursehidden'), $CFG->wwwroot .'/');
1700 }
1701
f71346e2 1702 /// Non-guests who don't currently have access, check if they can be allowed in as a guest
1703
1704 if ($USER->username != 'guest' and !has_capability('moodle/course:view', $context)) {
1705 if ($course->guest == 1) {
1706 // Temporarily assign them guest role for this context,
1707 // if it fails user is asked to enrol
1708 load_guest_role($context);
1709 }
1710 }
1711
1845f8b8 1712 /// If the user is a guest then treat them according to the course policy about guests
1713
1714 if (has_capability('moodle/legacy:guest', $context, NULL, false)) {
1715 switch ($course->guest) { /// Check course policy about guest access
1716
1717 case 1: /// Guests always allowed
1718 if (!has_capability('moodle/course:view', $context)) { // Prohibited by capability
1719 print_header_simple();
1720 notice(get_string('guestsnotallowed', '', $course->fullname), "$CFG->wwwroot/login/index.php");
1721 }
1722 if (!empty($cm) and !$cm->visible) { // Not allowed to see module, send to course page
1723 redirect($CFG->wwwroot.'/course/view.php?id='.$cm->course,
1724 get_string('activityiscurrentlyhidden'));
1725 }
1726
1727 return; // User is allowed to see this course
1728
1729 break;
1730
b1f318a6 1731 case 2: /// Guests allowed with key
1732 if (!empty($USER->enrolkey[$course->id])) { // Set by enrol/manual/enrol.php
1733 return true;
1734 }
1735 // otherwise drop through to logic below (--> enrol.php)
1845f8b8 1736 break;
bbbf2d40 1737
1845f8b8 1738 default: /// Guests not allowed
21596567 1739 print_header_simple('', '', get_string('loggedinasguest'));
1740 if (empty($USER->switchrole[$context->id])) { // Normal guest
1741 notice(get_string('guestsnotallowed', '', $course->fullname), "$CFG->wwwroot/login/index.php");
1742 } else {
1743 notify(get_string('guestsnotallowed', '', $course->fullname));
1744 echo '<div class="notifyproblem">'.switchroles_form($course->id).'</div>';
1745 print_footer($course);
1746 exit;
1747 }
1845f8b8 1748 break;
1749 }
1750
1751 /// For non-guests, check if they have course view access
1752
1753 } else if (has_capability('moodle/course:view', $context)) {
1754 if (!empty($USER->realuser)) { // Make sure the REAL person can also access this course
d02eeded 1755 if (!has_capability('moodle/course:view', $context, $USER->realuser)) {
1845f8b8 1756 print_header_simple();
b0ccd3fb 1757 notice(get_string('studentnotallowed', '', fullname($USER, true)), $CFG->wwwroot .'/');
cb909d74 1758 }
3ce2f1e0 1759 }
1845f8b8 1760
1761 /// Make sure they can read this activity too, if specified
1762
1763 if (!empty($cm) and !$cm->visible and !has_capability('moodle/course:viewhiddenactivities', $context)) {
ec81373f 1764 redirect($CFG->wwwroot.'/course/view.php?id='.$cm->course, get_string('activityiscurrentlyhidden'));
1765 }
1845f8b8 1766 return; // User is allowed to see this course
1767
da5c172a 1768 }
f9903ed0 1769
9ca3b4f3 1770
1845f8b8 1771 /// Currently not enrolled in the course, so see if they want to enrol
da5c172a 1772 $SESSION->wantsurl = $FULLME;
b0ccd3fb 1773 redirect($CFG->wwwroot .'/course/enrol.php?id='. $courseid);
da5c172a 1774 die;
1775 }
f9903ed0 1776}
1777
c4d0753b 1778
1779
1780/**
1781 * This function just makes sure a user is logged out.
1782 *
1783 * @uses $CFG
1784 * @uses $USER
1785 */
1786function require_logout() {
1787
1788 global $USER, $CFG;
1789
1790 if (isset($USER) and isset($USER->id)) {
1791 add_to_log(SITEID, "user", "logout", "view.php?id=$USER->id&course=".SITEID, $USER->id, 0, $USER->id);
1792
1793 if ($USER->auth == 'cas' && !empty($CFG->cas_enabled)) {
1794 require($CFG->dirroot.'/auth/cas/logout.php');
1795 }
03d820c7 1796
81693ac7 1797 if (extension_loaded('openssl')) {
1798 require($CFG->dirroot.'/auth/mnet/auth.php');
1799 $authplugin = new auth_plugin_mnet();
1800 $authplugin->logout();
1801 }
c4d0753b 1802 }
1803
1804 if (ini_get_bool("register_globals") and check_php_version("4.3.0")) {
1805 // This method is just to try to avoid silly warnings from PHP 4.3.0
1806 session_unregister("USER");
1807 session_unregister("SESSION");
1808 }
1809
1810 setcookie('MoodleSessionTest'.$CFG->sessioncookie, '', time() - 3600, $CFG->sessioncookiepath);
1811 unset($_SESSION['USER']);
1812 unset($_SESSION['SESSION']);
1813
1814 unset($SESSION);
1815 unset($USER);
1816
1817}
1818
7cf1c7bd 1819/**
1820 * This is a weaker version of {@link require_login()} which only requires login
1821 * when called from within a course rather than the site page, unless
1822 * the forcelogin option is turned on.
1823 *
1824 * @uses $CFG
4febb58f 1825 * @param object $course The course object in question
bbd3f2c4 1826 * @param bool $autologinguest Allow autologin guests if that is wanted
4febb58f 1827 * @param object $cm Course activity module if known
7cf1c7bd 1828 */
ec81373f 1829function require_course_login($course, $autologinguest=true, $cm=null) {
f950af3c 1830 global $CFG;
1596edff 1831 if (!empty($CFG->forcelogin)) {
b56ccdd9 1832 require_login();
f950af3c 1833 }
4febb58f 1834 if ($course->id != SITEID) {
ec81373f 1835 require_login($course->id, $autologinguest, $cm);
f950af3c 1836 }
1837}
1838
7cf1c7bd 1839/**
1840 * Modify the user table by setting the currently logged in user's
1841 * last login to now.
1842 *
1843 * @uses $USER
bbd3f2c4 1844 * @return bool
7cf1c7bd 1845 */
1d881d92 1846function update_user_login_times() {
1847 global $USER;
1848
1849 $USER->lastlogin = $user->lastlogin = $USER->currentlogin;
2a2f5f11 1850 $USER->currentlogin = $user->lastaccess = $user->currentlogin = time();
1d881d92 1851
1852 $user->id = $USER->id;
1853
b0ccd3fb 1854 return update_record('user', $user);
1d881d92 1855}
1856
7cf1c7bd 1857/**
1858 * Determines if a user has completed setting up their account.
1859 *
89dcb99d 1860 * @param user $user A {@link $USER} object to test for the existance of a valid name and email
bbd3f2c4 1861 * @return bool
7cf1c7bd 1862 */
808a3baa 1863function user_not_fully_set_up($user) {
bb64b51a 1864 return ($user->username != 'guest' and (empty($user->firstname) or empty($user->lastname) or empty($user->email) or over_bounce_threshold($user)));
1865}
1866
1867function over_bounce_threshold($user) {
d2a9f7cc 1868
bb64b51a 1869 global $CFG;
d2a9f7cc 1870
bb64b51a 1871 if (empty($CFG->handlebounces)) {
1872 return false;
1873 }
1874 // set sensible defaults
1875 if (empty($CFG->minbounces)) {
1876 $CFG->minbounces = 10;
1877 }
1878 if (empty($CFG->bounceratio)) {
1879 $CFG->bounceratio = .20;
1880 }
1881 $bouncecount = 0;
1882 $sendcount = 0;
1883 if ($bounce = get_record('user_preferences','userid',$user->id,'name','email_bounce_count')) {
1884 $bouncecount = $bounce->value;
1885 }
1886 if ($send = get_record('user_preferences','userid',$user->id,'name','email_send_count')) {
1887 $sendcount = $send->value;
1888 }
1889 return ($bouncecount >= $CFG->minbounces && $bouncecount/$sendcount >= $CFG->bounceratio);
1890}
1891
d2a9f7cc 1892/**
bb64b51a 1893 * @param $user - object containing an id
1894 * @param $reset - will reset the count to 0
1895 */
1896function set_send_count($user,$reset=false) {
d2a9f7cc 1897 if ($pref = get_record('user_preferences','userid',$user->id,'name','email_send_count')) {
bb64b51a 1898 $pref->value = (!empty($reset)) ? 0 : $pref->value+1;
1899 update_record('user_preferences',$pref);
1900 }
1901 else if (!empty($reset)) { // if it's not there and we're resetting, don't bother.
1902 // make a new one
1903 $pref->name = 'email_send_count';
1904 $pref->value = 1;
1905 $pref->userid = $user->id;
06ba0b04 1906 insert_record('user_preferences',$pref, false);
bb64b51a 1907 }
1908}
1909
d2a9f7cc 1910/**
bb64b51a 1911* @param $user - object containing an id
1912 * @param $reset - will reset the count to 0
1913 */
1914function set_bounce_count($user,$reset=false) {
d2a9f7cc 1915 if ($pref = get_record('user_preferences','userid',$user->id,'name','email_bounce_count')) {
bb64b51a 1916 $pref->value = (!empty($reset)) ? 0 : $pref->value+1;
1917 update_record('user_preferences',$pref);
1918 }
1919 else if (!empty($reset)) { // if it's not there and we're resetting, don't bother.
1920 // make a new one
1921 $pref->name = 'email_bounce_count';
1922 $pref->value = 1;
1923 $pref->userid = $user->id;
06ba0b04 1924 insert_record('user_preferences',$pref, false);
bb64b51a 1925 }
808a3baa 1926}
f9903ed0 1927
7cf1c7bd 1928/**
1929 * Keeps track of login attempts
1930 *
1931 * @uses $SESSION
1932 */
f9903ed0 1933function update_login_count() {
9fa49e22 1934
f9903ed0 1935 global $SESSION;
1936
1937 $max_logins = 10;
1938
1939 if (empty($SESSION->logincount)) {
1940 $SESSION->logincount = 1;
1941 } else {
1942 $SESSION->logincount++;
1943 }
1944
1945 if ($SESSION->logincount > $max_logins) {
9fa49e22 1946 unset($SESSION->wantsurl);
b0ccd3fb 1947 error(get_string('errortoomanylogins'));
d578afc8 1948 }
1949}
1950
7cf1c7bd 1951/**
1952 * Resets login attempts
1953 *
1954 * @uses $SESSION
1955 */
9fa49e22 1956function reset_login_count() {
9fa49e22 1957 global $SESSION;
d578afc8 1958
9fa49e22 1959 $SESSION->logincount = 0;
d578afc8 1960}
1961
b61efafb 1962function sync_metacourses() {
1963
1964 global $CFG;
1965
1aad4310 1966 if (!$courses = get_records('course', 'metacourse', 1)) {
b61efafb 1967 return;
1968 }
d2a9f7cc 1969
b61efafb 1970 foreach ($courses as $course) {
1aad4310 1971 sync_metacourse($course);
b61efafb 1972 }
1973}
1974
b61efafb 1975/**
1976 * Goes through all enrolment records for the courses inside the metacourse and sync with them.
123545bc 1977 *
1978 * @param mixed $course the metacourse to synch. Either the course object itself, or the courseid.
d2a9f7cc 1979 */
1aad4310 1980function sync_metacourse($course) {
755c8d58 1981 global $CFG;
b61efafb 1982
123545bc 1983 // Check the course is valid.
1aad4310 1984 if (!is_object($course)) {
1985 if (!$course = get_record('course', 'id', $course)) {
1986 return false; // invalid course id
b61efafb 1987 }
b61efafb 1988 }
1aad4310 1989
123545bc 1990 // Check that we actually have a metacourse.
1aad4310 1991 if (empty($course->metacourse)) {
123545bc 1992 return false;
755c8d58 1993 }
87671466 1994
b3170072 1995 // Get a list of roles that should not be synced.
1996 if ($CFG->nonmetacoursesyncroleids) {
1997 $roleexclusions = 'ra.roleid NOT IN (' . $CFG->nonmetacoursesyncroleids . ') AND';
1998 } else {
1999 $roleexclusions = '';
2000 }
2001
123545bc 2002 // Get the context of the metacourse.
1aad4310 2003 $context = get_context_instance(CONTEXT_COURSE, $course->id); // SITEID can not be a metacourse
e1ecf0a0 2004
123545bc 2005 // We do not ever want to unassign the list of metacourse manager, so get a list of them.
b79da3ac 2006 if ($users = get_users_by_capability($context, 'moodle/course:managemetacourse')) {
1aad4310 2007 $managers = array_keys($users);
2008 } else {
2009 $managers = array();
b61efafb 2010 }
2011
123545bc 2012 // Get assignments of a user to a role that exist in a child course, but
2013 // not in the meta coure. That is, get a list of the assignments that need to be made.
2014 if (!$assignments = get_records_sql("
2015 SELECT
2016 ra.id, ra.roleid, ra.userid
2017 FROM
2018 {$CFG->prefix}role_assignments ra,
2019 {$CFG->prefix}context con,
2020 {$CFG->prefix}course_meta cm
2021 WHERE
2022 ra.contextid = con.id AND
2023 con.contextlevel = " . CONTEXT_COURSE . " AND
2024 con.instanceid = cm.child_course AND
2025 cm.parent_course = {$course->id} AND
b3170072 2026 $roleexclusions
123545bc 2027 NOT EXISTS (
2028 SELECT 1 FROM
2029 {$CFG->prefix}role_assignments ra2
2030 WHERE
2031 ra2.userid = ra.userid AND
2032 ra2.roleid = ra.roleid AND
2033 ra2.contextid = {$context->id}
2034 )
2035 ")) {
2036 $assignments = array();
2037 }
2038
2039 // Get assignments of a user to a role that exist in the meta course, but
2040 // not in any child courses. That is, get a list of the unassignments that need to be made.
2041 if (!$unassignments = get_records_sql("
2042 SELECT
2043 ra.id, ra.roleid, ra.userid
2044 FROM
2045 {$CFG->prefix}role_assignments ra
2046 WHERE
2047 ra.contextid = {$context->id} AND
b3170072 2048 $roleexclusions
123545bc 2049 NOT EXISTS (
2050 SELECT 1 FROM
2051 {$CFG->prefix}role_assignments ra2,
2052 {$CFG->prefix}context con2,
2053 {$CFG->prefix}course_meta cm
2054 WHERE
2055 ra2.userid = ra.userid AND
2056 ra2.roleid = ra.roleid AND
2057 ra2.contextid = con2.id AND
2058 con2.contextlevel = " . CONTEXT_COURSE . " AND
2059 con2.instanceid = cm.child_course AND
2060 cm.parent_course = {$course->id}
2061 )
2062 ")) {
2063 $unassignments = array();
2064 }
2065
2066 $success = true;
2067
2068 // Make the unassignments, if they are not managers.
2069 foreach ($unassignments as $unassignment) {
2070 if (!in_array($unassignment->userid, $managers)) {
2071 $success = role_unassign($unassignment->roleid, $unassignment->userid, 0, $context->id) && $success;
1aad4310 2072 }
755c8d58 2073 }
e1ecf0a0 2074
123545bc 2075 // Make the assignments.
2076 foreach ($assignments as $assignment) {
2077 $success = role_assign($assignment->roleid, $assignment->userid, 0, $context->id) && $success;
b61efafb 2078 }
755c8d58 2079
123545bc 2080 return $success;
2081
1aad4310 2082// TODO: finish timeend and timestart
2083// maybe we could rely on cron job to do the cleaning from time to time
b61efafb 2084}
2085
d2a9f7cc 2086/**
b61efafb 2087 * Adds a record to the metacourse table and calls sync_metacoures
2088 */
2089function add_to_metacourse ($metacourseid, $courseid) {
d2a9f7cc 2090
b61efafb 2091 if (!$metacourse = get_record("course","id",$metacourseid)) {
2092 return false;
2093 }
d2a9f7cc 2094
b61efafb 2095 if (!$course = get_record("course","id",$courseid)) {
2096 return false;
2097 }
2098
5f37b628 2099 if (!$record = get_record("course_meta","parent_course",$metacourseid,"child_course",$courseid)) {
b61efafb 2100 $rec->parent_course = $metacourseid;
2101 $rec->child_course = $courseid;
5f37b628 2102 if (!insert_record('course_meta',$rec)) {
b61efafb 2103 return false;
2104 }
2105 return sync_metacourse($metacourseid);
2106 }
2107 return true;
d2a9f7cc 2108
b61efafb 2109}
2110
d2a9f7cc 2111/**
b61efafb 2112 * Removes the record from the metacourse table and calls sync_metacourse
2113 */
2114function remove_from_metacourse($metacourseid, $courseid) {
2115
5f37b628 2116 if (delete_records('course_meta','parent_course',$metacourseid,'child_course',$courseid)) {
b61efafb 2117 return sync_metacourse($metacourseid);
2118 }
2119 return false;
2120}
2121
2122
7c12949d 2123/**
2124 * Determines if a user is currently logged in
2125 *
2126 * @uses $USER
bbd3f2c4 2127 * @return bool
7c12949d 2128 */
2129function isloggedin() {
2130 global $USER;
2131
2132 return (!empty($USER->id));
2133}
2134
2a919fd7 2135/**
2136 * Determines if a user is logged in as real guest user with username 'guest'.
2137 * This function is similar to original isguest() in 1.6 and earlier.
2138 * Current isguest() is deprecated - do not use it anymore.
2139 *
2140 * @param $user mixed user object or id, $USER if not specified
2141 * @return bool true if user is the real guest user, false if not logged in or other user
2142 */
2143function isguestuser($user=NULL) {
2144 global $USER;
2145 if ($user === NULL) {
2146 $user = $USER;
2147 } else if (is_numeric($user)) {
2148 $user = get_record('user', 'id', $user, '', '', '', '', 'id, username');
2149 }
2150
2151 if (empty($user->id)) {
2152 return false; // not logged in, can not be guest
2153 }
2154
2155 return ($user->username == 'guest');
2156}
7c12949d 2157
7cf1c7bd 2158/**
2159 * Determines if the currently logged in user is in editing mode
2160 *
2161 * @uses $USER
c6d15803 2162 * @param int $courseid The id of the course being tested
89dcb99d 2163 * @param user $user A {@link $USER} object. If null then the currently logged in user is used.
bbd3f2c4 2164 * @return bool
7cf1c7bd 2165 */
2c309dc2 2166function isediting($courseid, $user=NULL) {
3cf4fa0c 2167 global $USER;
2168 if (!$user) {
2169 $user = $USER;
2c309dc2 2170 }
9c9f7d77 2171 if (empty($user->editing)) {
2172 return false;
2173 }
d02eeded 2174 return ($user->editing and has_capability('moodle/course:manageactivities', get_context_instance(CONTEXT_COURSE, $courseid)));
2c309dc2 2175}
2176
7cf1c7bd 2177/**
2178 * Determines if the logged in user is currently moving an activity
2179 *
2180 * @uses $USER
c6d15803 2181 * @param int $courseid The id of the course being tested
bbd3f2c4 2182 * @return bool
7cf1c7bd 2183 */
7977cffd 2184function ismoving($courseid) {
7977cffd 2185 global $USER;
2186
2187 if (!empty($USER->activitycopy)) {
2188 return ($USER->activitycopycourse == $courseid);
2189 }
2190 return false;
2191}
2192
7cf1c7bd 2193/**
2194 * Given an object containing firstname and lastname
2195 * values, this function returns a string with the
2196 * full name of the person.
2197 * The result may depend on system settings
2198 * or language. 'override' will force both names
361855e6 2199 * to be used even if system settings specify one.
68fbd8e1 2200 *
7cf1c7bd 2201 * @uses $CFG
2202 * @uses $SESSION
68fbd8e1 2203 * @param object $user A {@link $USER} object to get full name of
2204 * @param bool $override If true then the name will be first name followed by last name rather than adhering to fullnamedisplay setting.
7cf1c7bd 2205 */
e2cd5065 2206function fullname($user, $override=false) {
b5cbb64d 2207
f374fb10 2208 global $CFG, $SESSION;
2209
6527c077 2210 if (!isset($user->firstname) and !isset($user->lastname)) {
2211 return '';
2212 }
2213
4c202228 2214 if (!$override) {
2215 if (!empty($CFG->forcefirstname)) {
2216 $user->firstname = $CFG->forcefirstname;
2217 }
2218 if (!empty($CFG->forcelastname)) {
2219 $user->lastname = $CFG->forcelastname;
2220 }
2221 }
2222
f374fb10 2223 if (!empty($SESSION->fullnamedisplay)) {
2224 $CFG->fullnamedisplay = $SESSION->fullnamedisplay;
2225 }
e2cd5065 2226
b5cbb64d 2227 if ($CFG->fullnamedisplay == 'firstname lastname') {
b0ccd3fb 2228 return $user->firstname .' '. $user->lastname;
b5cbb64d 2229
2230 } else if ($CFG->fullnamedisplay == 'lastname firstname') {
b0ccd3fb 2231 return $user->lastname .' '. $user->firstname;
e2cd5065 2232
b5cbb64d 2233 } else if ($CFG->fullnamedisplay == 'firstname') {
2234 if ($override) {
2235 return get_string('fullnamedisplay', '', $user);
2236 } else {
2237 return $user->firstname;
2238 }
2239 }
e2cd5065 2240
b5cbb64d 2241 return get_string('fullnamedisplay', '', $user);
e2cd5065 2242}
2243
7cf1c7bd 2244/**
2245 * Sets a moodle cookie with an encrypted string
2246 *
2247 * @uses $CFG
2f87145b 2248 * @uses DAYSECS
2249 * @uses HOURSECS
7cf1c7bd 2250 * @param string $thing The string to encrypt and place in a cookie
2251 */
f9903ed0 2252function set_moodle_cookie($thing) {
7185e073 2253 global $CFG;
482b6e6e 2254
7cbe6afe 2255 if ($thing == 'guest') { // Ignore guest account
2256 return;
2257 }
2258
482b6e6e 2259 $cookiename = 'MOODLEID_'.$CFG->sessioncookie;
f9903ed0 2260
2261 $days = 60;
7a5672c9 2262 $seconds = DAYSECS*$days;
f9903ed0 2263
7a5672c9 2264 setCookie($cookiename, '', time() - HOURSECS, '/');
b0ccd3fb 2265 setCookie($cookiename, rc4encrypt($thing), time()+$seconds, '/');
f9903ed0 2266}
2267
7cf1c7bd 2268/**
2269 * Gets a moodle cookie with an encrypted string
2270 *
2271 * @uses $CFG
2272 * @return string
2273 */
f9903ed0 2274function get_moodle_cookie() {
7185e073 2275 global $CFG;
2276
482b6e6e 2277 $cookiename = 'MOODLEID_'.$CFG->sessioncookie;
7185e073 2278
1079c8a8 2279 if (empty($_COOKIE[$cookiename])) {
b0ccd3fb 2280 return '';
1079c8a8 2281 } else {
7cbe6afe 2282 $thing = rc4decrypt($_COOKIE[$cookiename]);
2283 return ($thing == 'guest') ? '': $thing; // Ignore guest account
1079c8a8 2284 }
f9903ed0 2285}
2286
7cf1c7bd 2287/**
03d820c7 2288 * Returns whether a given authentication plugin exists.
7cf1c7bd 2289 *
2290 * @uses $CFG
03d820c7 2291 * @param string $auth Form of authentication to check for. Defaults to the
2292 * global setting in {@link $CFG}.
2293 * @return boolean Whether the plugin is available.
7cf1c7bd 2294 */
03d820c7 2295function exists_auth_plugin($auth='') {
2296 global $CFG;
2297
2298 // use the global default if not specified
2299 if ($auth == '') {
2300 $auth = $CFG->auth;
2301 }
2302 if (file_exists("{$CFG->dirroot}/auth/$auth/auth.php")) {
2303 return is_readable("{$CFG->dirroot}/auth/$auth/auth.php");
2304 }
2305 return false;
2306}
ba7166c3 2307
03d820c7 2308/**
2309 * Checks if a given plugin is in the list of enabled authentication plugins.
2310 *
2311 * @param string $auth Authentication plugin.
2312 * @return boolean Whether the plugin is enabled.
2313 */
2314function is_enabled_auth($auth='') {
ba7166c3 2315 global $CFG;
2316
03d820c7 2317 // use the global default if not specified
2318 if ($auth == '') {
2319 $auth = $CFG->auth;
2320 }
2321 return in_array($auth, explode(',', $CFG->auth_plugins_enabled));
2322}
2323
2324/**
2325 * Returns an authentication plugin instance.
2326 *
2327 * @uses $CFG
2328 * @param string $auth Form of authentication required. Defaults to the
2329 * global setting in {@link $CFG}.
2330 * @return object An instance of the required authentication plugin.
2331 */
2332function get_auth_plugin($auth = '') {
2333 global $CFG;
2334
2335 // use the global default if not specified
2336 if ($auth == '') {
a3f1f815 2337 $auth = $CFG->auth;
39a5a35d 2338 }
2339
03d820c7 2340 // TODO: plugin enabled?
2341
2342 // check the plugin exists first
2343 if (! exists_auth_plugin($auth)) {
2344 error("Authentication plugin '$auth' not found.");
2345 }
2346
2347 // return auth plugin instance
2348 require_once "{$CFG->dirroot}/auth/$auth/auth.php";
2349 $class = "auth_plugin_$auth";
2350 return new $class;
2351}
2352
2353/**
2354 * Returns true if an internal authentication method is being used.
2355 * if method not specified then, global default is assumed
2356 *
2357 * @uses $CFG
2358 * @param string $auth Form of authentication required
2359 * @return bool
2360 * @todo Outline auth types and provide code example
2361 */
2362function is_internal_auth($auth='') {
2363 $authplugin = get_auth_plugin($auth); // throws error if bad $auth
2364 return $authplugin->is_internal();
a3f1f815 2365}
2366
8c3dba73 2367/**
2368 * Returns an array of user fields
2369 *
c6d15803 2370 * @uses $CFG
2371 * @uses $db
2372 * @return array User field/column names
8c3dba73 2373 */
a3f1f815 2374function get_user_fieldnames() {
a3f1f815 2375
2376 global $CFG, $db;
2377
2378 $fieldarray = $db->MetaColumnNames($CFG->prefix.'user');
2379 unset($fieldarray['ID']);
2380
2381 return $fieldarray;
ba7166c3 2382}
f9903ed0 2383
7cf1c7bd 2384/**
2385 * Creates a bare-bones user record
2386 *
2387 * @uses $CFG
7cf1c7bd 2388 * @param string $username New user's username to add to record
2389 * @param string $password New user's password to add to record
2390 * @param string $auth Form of authentication required
68fbd8e1 2391 * @return object A {@link $USER} object
7cf1c7bd 2392 * @todo Outline auth types and provide code example
2393 */
71f9abf9 2394function create_user_record($username, $password, $auth='') {
366dfa60 2395 global $CFG;
71f9abf9 2396
1e22bc9c 2397 //just in case check text case
2398 $username = trim(moodle_strtolower($username));
71f9abf9 2399
03d820c7 2400 $authplugin = get_auth_plugin($auth);
2401
2402 if (method_exists($authplugin, 'get_userinfo')) {
2403 if ($newinfo = $authplugin->get_userinfo($username)) {
b36a8fc4 2404 $newinfo = truncate_userinfo($newinfo);
34daec9b 2405 foreach ($newinfo as $key => $value){
9f44d972 2406 $newuser->$key = addslashes(stripslashes($value)); // Just in case
e858f9da 2407 }
2408 }
2409 }
f9903ed0 2410
85a1d4c9 2411 if (!empty($newuser->email)) {
2412 if (email_is_not_allowed($newuser->email)) {
2413 unset($newuser->email);
2414 }
2415 }
2416
71f9abf9 2417 $newuser->auth = (empty($auth)) ? $CFG->auth : $auth;
faebaf0f 2418 $newuser->username = $username;
df193157 2419 update_internal_user_password($newuser, $password, false);
a0bac19d 2420 $newuser->lang = $CFG->lang;
faebaf0f 2421 $newuser->confirmed = 1;
d96466d2 2422 $newuser->lastip = getremoteaddr();
faebaf0f 2423 $newuser->timemodified = time();
03d820c7 2424 $newuser->mnethostid = $CFG->mnet_localhost_id;
f9903ed0 2425
b0ccd3fb 2426 if (insert_record('user', $newuser)) {
7c12949d 2427 $user = get_complete_user_data('username', $newuser->username);
d35757eb 2428 if($CFG->{'auth_'.$newuser->auth.'_forcechangepassword'}){
4b598ff4 2429 set_user_preference('auth_forcepasswordchange', 1, $user->id);
d35757eb 2430 }
2431 return $user;
faebaf0f 2432 }
2433 return false;
2434}
2435
7cf1c7bd 2436/**
2437 * Will update a local user record from an external source
2438 *
2439 * @uses $CFG
2440 * @param string $username New user's username to add to record
89dcb99d 2441 * @return user A {@link $USER} object
7cf1c7bd 2442 */
03d820c7 2443function update_user_record($username, $authplugin) {
2444 if (method_exists($authplugin, 'get_userinfo')) {
d35757eb 2445 $username = trim(moodle_strtolower($username)); /// just in case check text case
2446
b78fbdac 2447 $oldinfo = get_record('user', 'username', $username, '','','','', 'username, auth');
03d820c7 2448 $userauth = get_auth_plugin($oldinfo->auth);
b78fbdac 2449
03d820c7 2450 if ($newinfo = $authplugin->get_userinfo($username)) {
4b598ff4 2451 $newinfo = truncate_userinfo($newinfo);
d35757eb 2452 foreach ($newinfo as $key => $value){
b78fbdac 2453 $confkey = 'field_updatelocal_' . $key;
03d820c7 2454 if (!empty($userauth->config->$confkey) and $userauth->config->$confkey === 'onlogin') {
d35757eb 2455 $value = addslashes(stripslashes($value)); // Just in case
e1ecf0a0 2456 set_field('user', $key, $value, 'username', $username)
03d820c7 2457 or error_log("Error updating $key for $username");
d35757eb 2458 }
2459 }
2460 }
2461 }
7c12949d 2462 return get_complete_user_data('username', $username);
d35757eb 2463}
0609562b 2464
b36a8fc4 2465function truncate_userinfo($info) {
2466/// will truncate userinfo as it comes from auth_get_userinfo (from external auth)
2467/// which may have large fields
2468
2469 // define the limits
2470 $limit = array(
2471 'username' => 100,
1c66bf59 2472 'idnumber' => 64,
8bcd295c 2473 'firstname' => 100,
2474 'lastname' => 100,
b36a8fc4 2475 'email' => 100,
2476 'icq' => 15,
2477 'phone1' => 20,
2478 'phone2' => 20,
2479 'institution' => 40,
2480 'department' => 30,
2481 'address' => 70,
2482 'city' => 20,
2483 'country' => 2,
2484 'url' => 255,
2485 );
361855e6 2486
b36a8fc4 2487 // apply where needed
2488 foreach (array_keys($info) as $key) {
2489 if (!empty($limit[$key])) {
adfc03f9 2490 $info[$key] = trim(substr($info[$key],0, $limit[$key]));
361855e6 2491 }
b36a8fc4 2492 }
361855e6 2493
b36a8fc4 2494 return $info;
2495}
2496
7cf1c7bd 2497/**
2498 * Retrieve the guest user object
2499 *
2500 * @uses $CFG
89dcb99d 2501 * @return user A {@link $USER} object
7cf1c7bd 2502 */
0609562b 2503function guest_user() {
2504 global $CFG;
2505
b0ccd3fb 2506 if ($newuser = get_record('user', 'username', 'guest')) {
0609562b 2507 $newuser->loggedin = true;
2508 $newuser->confirmed = 1;
2509 $newuser->site = $CFG->wwwroot;
2510 $newuser->lang = $CFG->lang;
d96466d2 2511 $newuser->lastip = getremoteaddr();
0609562b 2512 }
2513
2514 return $newuser;
2515}
2516
7cf1c7bd 2517/**
2518 * Given a username and password, this function looks them
2519 * up using the currently selected authentication mechanism,
2520 * and if the authentication is successful, it returns a
2521 * valid $user object from the 'user' table.
361855e6 2522 *
7cf1c7bd 2523 * Uses auth_ functions from the currently active auth module
2524 *
2525 * @uses $CFG
361855e6 2526 * @param string $username User's username
2527 * @param string $password User's password
89dcb99d 2528 * @return user|flase A {@link $USER} object or false if error
7cf1c7bd 2529 */
faebaf0f 2530function authenticate_user_login($username, $password) {
faebaf0f 2531
2532 global $CFG;
2533
03d820c7 2534 // default to manual if global auth is undefined or broken
2535 if (empty($CFG->auth_plugins_enabled)) {
2536 $CFG->auth_plugins_enabled = empty($CFG->auth) ? 'manual' : $CFG->auth;
2537 }
2538 // if blank, set default auth to first enabled auth plugin
2539 if (empty($CFG->auth)) {
2540 $auths = explode(',', $CFG->auth_plugins_enabled);
2541 $CFG->auth = $auths[0];
2542 }
466558e3 2543
03d820c7 2544 // if user not found, use site auth
7c12949d 2545 if (!$user = get_complete_user_data('username', $username)) {
03d820c7 2546 $user = new object();
18f16d61 2547 $user->id = 0; // Not a user
03d820c7 2548 $auth = $CFG->auth_plugins_enabled;
18f16d61 2549 }
39a5a35d 2550
27286aeb 2551 // Sort out the authentication method we are using.
27286aeb 2552 if (empty($user->auth)) { // For some reason it isn't set yet
b7b97864 2553 $primadmin = get_admin();
2554 if (!empty($user->id) && (($user->id==$primadmin->id) || isguest($user->id))) {
03d820c7 2555 $auth = 'manual'; // always assume these guys are internal
27286aeb 2556 }
03d820c7 2557 else {
2558 $auth = $CFG->auth_plugins_enabled; // default to site method
d35757eb 2559 }
71f9abf9 2560 } else {
2561 $auth = $user->auth;
27286aeb 2562 }
8f0cd6ef 2563
03d820c7 2564 // walk each authentication plugin, in order
2565 $auths = explode(',', $auth);
2566 foreach ($auths as $auth) {
2567 $authplugin = get_auth_plugin($auth);
466558e3 2568
03d820c7 2569 // on auth fail, log and fall through to the next plugin
2570 if (!$authplugin->user_login($username, $password)) {
2571 add_to_log(0, 'login', 'error', 'index.php', $username);
2572 error_log("[client {$_SERVER['REMOTE_ADDR']}] $CFG->wwwroot Auth=$auth Failed Login: $username {$_SERVER['HTTP_USER_AGENT']}");
2573 continue;
2574 }
faebaf0f 2575
03d820c7 2576 // successful authentication
d613daf0 2577 if ($user->id) { // User already exists in database
71f9abf9 2578 if (empty($user->auth)) { // For some reason auth isn't set yet
2579 set_field('user', 'auth', $auth, 'username', $username);
2580 }
df193157 2581 update_internal_user_password($user, $password);
03d820c7 2582 if (!$authplugin->is_internal()) { // update user record from external DB
2583 $user = update_user_record($username, get_auth_plugin($user->auth));
d35757eb 2584 }
faebaf0f 2585 } else {
71f9abf9 2586 $user = create_user_record($username, $password, $auth);
faebaf0f 2587 }
03d820c7 2588 // fix for MDL-6928
2589 if (method_exists($authplugin, 'iscreator')) {
c768b610 2590 $sitecontext = get_context_instance(CONTEXT_SYSTEM);
2591 if ($creatorroles = get_roles_with_capability('moodle/legacy:coursecreator', CAP_ALLOW)) {
2592 $creatorrole = array_shift($creatorroles); // We can only use one, let's use the first one
2593 // Check if the user is a creator
03d820c7 2594 if ($authplugin->iscreator($username)) { // Following calls will not create duplicates
b6c59cf7 2595 role_assign($creatorrole->id, $user->id, 0, $sitecontext->id, 0, 0, 0, $auth);
4158fd81 2596 } else {
2597 role_unassign($creatorrole->id, $user->id, 0, $sitecontext->id);
c768b610 2598 }
2599 }
2600 }
01af6da6 2601
2602 /// Log in to a second system if necessary
2603 if (!empty($CFG->sso)) {
2604 include_once($CFG->dirroot .'/sso/'. $CFG->sso .'/lib.php');
2605 if (function_exists('sso_user_login')) {
2606 if (!sso_user_login($username, $password)) { // Perform the signon process
2607 notify('Second sign-on failed');
2608 }
2609 }
2610 }
2611
e582b65e 2612 return $user;
9d3c795c 2613
03d820c7 2614 }
2615
2616 // failed if all the plugins have failed
2617 add_to_log(0, 'login', 'error', 'index.php', $username);
2618 error_log('[client '.$_SERVER['REMOTE_ADDR']."] $CFG->wwwroot Failed Login: $username ".$_SERVER['HTTP_USER_AGENT']);
2619 return false;
f9903ed0 2620}
2621
df193157 2622/**
4908ad3e 2623 * Compare password against hash stored in internal user table.
df193157 2624 * If necessary it also updates the stored hash to new format.
2625 *
2626 * @param object user
2627 * @param string plain text password
2628 * @return bool is password valid?
2629 */
2630function validate_internal_user_password(&$user, $password) {
2631 global $CFG;
2632
4908ad3e 2633 if (!isset($CFG->passwordsaltmain)) {
2634 $CFG->passwordsaltmain = '';
2635 }
2636
df193157 2637 $validated = false;
2638
fb773106 2639 // get password original encoding in case it was not updated to unicode yet
2640 $textlib = textlib_get_instance();
810944af 2641 $convpassword = $textlib->convert($password, 'utf-8', get_string('oldcharset'));
df193157 2642
4908ad3e 2643 if ($user->password == md5($password.$CFG->passwordsaltmain) or $user->password == md5($password)
2644 or $user->password == md5($convpassword.$CFG->passwordsaltmain) or $user->password == md5($convpassword)) {
df193157 2645 $validated = true;
4908ad3e 2646 } else {
aaeaa4b0 2647 for ($i=1; $i<=20; $i++) { //20 alternative salts should be enough, right?
4908ad3e 2648 $alt = 'passwordsaltalt'.$i;
2649 if (!empty($CFG->$alt)) {
2650 if ($user->password == md5($password.$CFG->$alt) or $user->password == md5($convpassword.$CFG->$alt)) {
2651 $validated = true;
2652 break;
2653 }
2654 }
2655 }
df193157 2656 }
2657
2658 if ($validated) {
4908ad3e 2659 // force update of password hash using latest main password salt and encoding if needed
df193157 2660 update_internal_user_password($user, $password);
2661 }
2662
2663 return $validated;
2664}
2665
2666/**
2667 * Calculate hashed value from password using current hash mechanism.
df193157 2668 *
2669 * @param string password
2670 * @return string password hash
2671 */
2672function hash_internal_user_password($password) {
4908ad3e 2673 global $CFG;
2674
2675 if (isset($CFG->passwordsaltmain)) {
2676 return md5($password.$CFG->passwordsaltmain);
2677 } else {
2678 return md5($password);
2679 }
df193157 2680}
2681
2682/**
2683 * Update pssword hash in user object.
2684 *
2685 * @param object user
2686 * @param string plain text password
2687 * @param bool store changes also in db, default true
2688 * @return true if hash changed
2689 */
2690function update_internal_user_password(&$user, $password, $storeindb=true) {
2691 global $CFG;
2692
03d820c7 2693 $authplugin = get_auth_plugin($user->auth);
2694 if (!empty($authplugin->config->preventpassindb) /*|| $storeindb === false */) {
df193157 2695 $hashedpassword = 'not cached';
2696 } else {
2697 $hashedpassword = hash_internal_user_password($password);
2698 }
2699
b7b50143 2700 return set_field('user', 'password', $hashedpassword, 'id', $user->id);
df193157 2701}
2702
7c12949d 2703/**
2704 * Get a complete user record, which includes all the info
5c98bf9e 2705 * in the user record
7c12949d 2706 * Intended for setting as $USER session variable
2707 *
2708 * @uses $CFG
2709 * @uses SITEID
e1ecf0a0 2710 * @param string $field The user field to be checked for a given value.
7c12949d 2711 * @param string $value The value to match for $field.
2712 * @return user A {@link $USER} object.
2713 */
b7b50143 2714function get_complete_user_data($field, $value, $mnethostid=null) {
7c12949d 2715
2716 global $CFG;
2717
2718 if (!$field || !$value) {
2719 return false;
2720 }
2721
b7b50143 2722/// Build the WHERE clause for an SQL query
2723
2724 $constraints = $field .' = \''. $value .'\' AND deleted <> \'1\'';
2725
2726 if (null === $mnethostid) {
2727 $constraints .= ' AND auth != \'mnet\'';
2728 } elseif (is_numeric($mnethostid)) {
2729 $constraints .= ' AND mnethostid = \''.$mnethostid.'\'';
2730 } else {
2731 error_log('Call to get_complete_user_data for $field='.$field.', $value = '.$value.', with invalid $mnethostid: '. $mnethostid);
2732 print_error('invalidhostlogin','mnet', $CFG->wwwroot.'/login/index.php');
2733 exit;
2734 }
2735
7c12949d 2736/// Get all the basic user data
2737
b7b50143 2738 if (! $user = get_record_select('user', $constraints)) {
7c12949d 2739 return false;
2740 }
2741
7c12949d 2742/// Get various settings and preferences
2743
2744 if ($displays = get_records('course_display', 'userid', $user->id)) {
2745 foreach ($displays as $display) {
2746 $user->display[$display->course] = $display->display;
2747 }
2748 }
2749
2750 if ($preferences = get_records('user_preferences', 'userid', $user->id)) {
2751 foreach ($preferences as $preference) {
2752 $user->preference[$preference->name] = $preference->value;
2753 }
2754 }
2755
721d14cb 2756 if ($lastaccesses = get_records('user_lastaccess', 'userid', $user->id)) {
2757 foreach ($lastaccesses as $lastaccess) {
2758 $user->lastcourseaccess[$lastaccess->courseid] = $lastaccess->timeaccess;
2759 }
2760 }
2761
f4ba7e1a 2762 if ($groupids = groups_get_all_groups_for_user($user->id)) { //TODO:check.
2763 foreach ($groupids as $groupid) {
2764 $courseid = groups_get_course($groupid);
fa22fd5f 2765 //change this to 2D array so we can put multiple groups in a course
f4ba7e1a 2766 $user->groupmember[$courseid][] = $groupid;
7c12949d 2767 }
2768 }
2769
2770/// Rewrite some variables if necessary
2771 if (!empty($user->description)) {
2772 $user->description = true; // No need to cart all of it around
2773 }
2774 if ($user->username == 'guest') {
2775 $user->lang = $CFG->lang; // Guest language always same as site
2776 $user->firstname = get_string('guestuser'); // Name always in current language
2777 $user->lastname = ' ';
2778 }
2779
2780 $user->loggedin = true;
2781 $user->site = $CFG->wwwroot; // for added security, store the site in the session
2782 $user->sesskey = random_string(10);
2783 $user->sessionIP = md5(getremoteaddr()); // Store the current IP in the session
2784
2785 return $user;
7c12949d 2786}
2787
7c12949d 2788
5c98bf9e 2789
e1ecf0a0 2790/*
7c12949d 2791 * When logging in, this function is run to set certain preferences
2792 * for the current SESSION
2793 */
2794function set_login_session_preferences() {
7c7ca1b5 2795 global $SESSION, $CFG;
7c12949d 2796
2797 $SESSION->justloggedin = true;
2798
2799 unset($SESSION->lang);
7c12949d 2800
2801 // Restore the calendar filters, if saved
2802 if (intval(get_user_preferences('calendar_persistflt', 0))) {
2803 include_once($CFG->dirroot.'/calendar/lib.php');
a266c904 2804 calendar_set_filters_status(get_user_preferences('calendav_savedflt', 0xff));
7c12949d 2805 }
2806}
2807
2808
b97c4164 2809/**
2810 * Delete a course, including all related data from the database,
2811 * and any associated files from the moodledata folder.
e1ecf0a0 2812 *
b97c4164 2813 * @param int $courseid The id of the course to delete.
2814 * @param bool $showfeedback Whether to display notifications of each action the function performs.
2815 * @return bool true if all the removals succeeded. false if there were any failures. If this
2816 * method returns false, some of the removals will probably have succeeded, and others
2817 * failed, but you have no way of knowing which.
2818 */
2819function delete_course($courseid, $showfeedback = true) {
2820 global $CFG;
2821 $result = true;
e1ecf0a0 2822
b97c4164 2823 if (!remove_course_contents($courseid, $showfeedback)) {
2824 if ($showfeedback) {
2825 notify("An error occurred while deleting some of the course contents.");
2826 }
2827 $result = false;
2828 }
2829
2830 if (!delete_records("course", "id", $courseid)) {
2831 if ($showfeedback) {
2832 notify("An error occurred while deleting the main course record.");
2833 }
2834 $result = false;
2835 }
2836
9991d157 2837 if (!delete_records('context', 'contextlevel', CONTEXT_COURSE, 'instanceid', $courseid)) {
eaa79489 2838 if ($showfeedback) {
2839 notify("An error occurred while deleting the main context record.");
2840 }
2841 $result = false;
2842 }
2843
b97c4164 2844 if (!fulldelete($CFG->dataroot.'/'.$courseid)) {
2845 if ($showfeedback) {
2846 notify("An error occurred while deleting the course files.");
2847 }
2848 $result = false;
2849 }
e1ecf0a0 2850
b97c4164 2851 return $result;
2852}
2853
7cf1c7bd 2854/**
2855 * Clear a course out completely, deleting all content
2856 * but don't delete the course itself
2857 *
7cf1c7bd 2858 * @uses $CFG
1f8ede91 2859 * @param int $courseid The id of the course that is being deleted
2860 * @param bool $showfeedback Whether to display notifications of each action the function performs.
b97c4164 2861 * @return bool true if all the removals succeeded. false if there were any failures. If this
2862 * method returns false, some of the removals will probably have succeeded, and others
2863 * failed, but you have no way of knowing which.
7cf1c7bd 2864 */
07aeb7b0 2865function remove_course_contents($courseid, $showfeedback=true) {
07aeb7b0 2866
1f8ede91 2867 global $CFG;
07aeb7b0 2868
2869 $result = true;
2870
b0ccd3fb 2871 if (! $course = get_record('course', 'id', $courseid)) {
2872 error('Course ID was incorrect (can\'t find it)');
07aeb7b0 2873 }
2874
b0ccd3fb 2875 $strdeleted = get_string('deleted');
07aeb7b0 2876
9991d157 2877/// First delete every instance of every module
d8ba183c 2878
b0ccd3fb 2879 if ($allmods = get_records('modules') ) {
07aeb7b0 2880 foreach ($allmods as $mod) {
2881 $modname = $mod->name;
b0ccd3fb 2882 $modfile = $CFG->dirroot .'/mod/'. $modname .'/lib.php';
2883 $moddelete = $modname .'_delete_instance'; // Delete everything connected to an instance
2884 $moddeletecourse = $modname .'_delete_course'; // Delete other stray stuff (uncommon)
07aeb7b0 2885 $count=0;
2886 if (file_exists($modfile)) {
2887 include_once($modfile);
2888 if (function_exists($moddelete)) {
b0ccd3fb 2889 if ($instances = get_records($modname, 'course', $course->id)) {
07aeb7b0 2890 foreach ($instances as $instance) {
eaa79489 2891 if ($cm = get_coursemodule_from_instance($modname, $instance->id, $course->id)) {
9991d157 2892 delete_context(CONTEXT_MODULE, $cm->id);
eaa79489 2893 }
07aeb7b0 2894 if ($moddelete($instance->id)) {
2895 $count++;
eaa79489 2896
07aeb7b0 2897 } else {
7eec3390 2898 notify('Could not delete '. $modname .' instance '. $instance->id .' ('. format_string($instance->name) .')');
07aeb7b0 2899 $result = false;
2900 }
2901 }
2902 }
2903 } else {
b0ccd3fb 2904 notify('Function '. $moddelete() .'doesn\'t exist!');
07aeb7b0 2905 $result = false;
2906 }
2907
ca952b03 2908 if (function_exists($moddeletecourse)) {
f67172b6 2909 $moddeletecourse($course, $showfeedback);
ca952b03 2910 }
07aeb7b0 2911 }
2912 if ($showfeedback) {
b0ccd3fb 2913 notify($strdeleted .' '. $count .' x '. $modname);
07aeb7b0 2914 }
2915 }
2916 } else {
b0ccd3fb 2917 error('No modules are installed!');
07aeb7b0 2918 }
2919
9991d157 2920/// Give local code a chance to delete its references to this course.
c0b5b31a 2921 require_once('locallib.php');
2922 notify_local_delete_course($courseid, $showfeedback);
2923
9991d157 2924/// Delete course blocks
7f869120 2925
2926 if ($blocks = get_records_sql("SELECT *
2927 FROM {$CFG->prefix}block_instance
2928 WHERE pagetype = '".PAGE_COURSE_VIEW."'
2929 AND pageid = $course->id")) {
eaa79489 2930 if (delete_records('block_instance', 'pagetype', PAGE_COURSE_VIEW, 'pageid', $course->id)) {
2931 if ($showfeedback) {
2932 notify($strdeleted .' block_instance');
2933 }
9991d157 2934 foreach ($blocks as $block) { /// Delete any associated contexts for this block
2935 delete_context(CONTEXT_BLOCK, $block->id);
2936 }
2937 } else {
2938 $result = false;
2939 }
2940 }
2941
f4ba7e1a 2942/// Delete any groups, removing members first. TODO: check.
2943 if ($groupids = groups_get_groups($course->id)) {
2944 foreach ($groupids as $groupid) {
2945 if (groups_remove_all_group_members($groupid)) {
2946 if ($showfeedback) {
2947 notify($strdeleted .' groups_members');
2948 }
2949 } else {
2950 $result = false;
9991d157 2951 }
f4ba7e1a 2952 /// Delete any associated context for this group ??
2953 delete_context(CONTEXT_GROUP, $group->id);
2954
2955 if (groups_delete_group($groupid)) {
2956 if ($showfeedback) {
2957 notify($strdeleted .' groups');
9991d157 2958 }
f4ba7e1a 2959 } else {
2960 $result = false;
9991d157 2961 }
251af423 2962 }
251af423 2963 }
2964
9991d157 2965/// Delete all related records in other tables that may have a courseid
2966/// This array stores the tables that need to be cleared, as
2967/// table_name => column_name that contains the course id.
2968
09481160 2969 $tablestoclear = array(
09481160 2970 'event' => 'courseid', // Delete events
2971 'log' => 'course', // Delete logs
2972 'course_sections' => 'course', // Delete any course stuff
2973 'course_modules' => 'course',
2974 'grade_category' => 'courseid', // Delete gradebook stuff
2975 'grade_exceptions' => 'courseid',
2976 'grade_item' => 'courseid',
2977 'grade_letter' => 'courseid',
2978 'grade_preferences' => 'courseid'
2979 );
2980 foreach ($tablestoclear as $table => $col) {
2981 if (delete_records($table, $col, $course->id)) {
2982 if ($showfeedback) {
2983 notify($strdeleted . ' ' . $table);
2984 }
2985 } else {
2986 $result = false;
07aeb7b0 2987 }
07aeb7b0 2988 }
2989
9991d157 2990
2991/// Clean up metacourse stuff
082e3ebc 2992
5f37b628 2993 if ($course->metacourse) {
2994 delete_records("course_meta","parent_course",$course->id);
b61efafb 2995 sync_metacourse($course->id); // have to do it here so the enrolments get nuked. sync_metacourses won't find it without the id.
2996 if ($showfeedback) {
5f37b628 2997 notify("$strdeleted course_meta");
b61efafb 2998 }
7ff9860d 2999 } else {
5f37b628 3000 if ($parents = get_records("course_meta","child_course",$course->id)) {
b61efafb 3001 foreach ($parents as $parent) {
3002 remove_from_metacourse($parent->parent_course,$parent->child_course); // this will do the unenrolments as well.
3003 }
3004 if ($showfeedback) {
5f37b628 3005 notify("$strdeleted course_meta");
b61efafb 3006 }
3007 }
3008 }
3009
9991d157 3010/// Delete questions and question categories
f67172b6 3011 include_once($CFG->libdir.'/questionlib.php');
3012 question_delete_course($course, $showfeedback);
3013
9991d157 3014/// Delete all roles and overiddes in the course context (but keep the course context)
39474844 3015 if ($courseid != SITEID) {
3016 delete_context(CONTEXT_COURSE, $course->id);
3017 }
3018
07aeb7b0 3019 return $result;
07aeb7b0 3020}
3021
ffd0fbb7 3022
7cf1c7bd 3023/**
ffd0fbb7 3024 * This function will empty a course of USER data as much as
3025/// possible. It will retain the activities and the structure
3026/// of the course.
7cf1c7bd 3027 *
ffd0fbb7 3028 * @uses $USER
3029 * @uses $SESSION
7cf1c7bd 3030 * @uses $CFG
ffd0fbb7 3031 * @param object $data an object containing all the boolean settings and courseid
3032 * @param bool $showfeedback if false then do it all silently
3033 * @return bool
3034 * @todo Finish documenting this function
7cf1c7bd 3035 */
ffd0fbb7 3036function reset_course_userdata($data, $showfeedback=true) {
3831de52 3037
ffd0fbb7 3038 global $CFG, $USER, $SESSION;
3831de52 3039
3040 $result = true;
3041
b0ccd3fb 3042 $strdeleted = get_string('deleted');
3831de52 3043
3044 // Look in every instance of every module for data to delete
3045
b0ccd3fb 3046 if ($allmods = get_records('modules') ) {
3831de52 3047 foreach ($allmods as $mod) {
3048 $modname = $mod->name;
b0ccd3fb 3049 $modfile = $CFG->dirroot .'/mod/'. $modname .'/lib.php';
3050 $moddeleteuserdata = $modname .'_delete_userdata'; // Function to delete user data
3831de52 3051 if (file_exists($modfile)) {
3052 @include_once($modfile);
3053 if (function_exists($moddeleteuserdata)) {
ffd0fbb7 3054 $moddeleteuserdata($data, $showfeedback);
3831de52 3055 }
3056 }
3057 }
3058 } else {
b0ccd3fb 3059 error('No modules are installed!');
3831de52 3060 }
3061
3062 // Delete other stuff
20d55a1b 3063 $coursecontext = get_context_instance(CONTEXT_COURSE, $data->courseid);
3831de52 3064
20d55a1b 3065 if (!empty($data->reset_students) or !empty($data->reset_teachers)) {
3066 $teachers = array_keys(get_users_by_capability($coursecontext, 'moodle/course:update'));
3067 $participants = array_keys(get_users_by_capability($coursecontext, 'moodle/course:view'));
3068 $students = array_diff($participants, $teachers);
3069
3070 if (!empty($data->reset_students)) {
3071 foreach ($students as $studentid) {
3072 role_unassign(0, $studentid, 0, $coursecontext->id);
3073 }
3831de52 3074 if ($showfeedback) {
20d55a1b 3075 notify($strdeleted .' '.get_string('students'), 'notifysuccess');
3831de52 3076 }
d76a5a7f 3077
f4ba7e1a 3078 /// Delete group members (but keep the groups) TODO:check.
3079 if ($groupids = groups_get_groups($data->courseid)) {
3080 foreach ($groupids as $groupid) {
3081 if (groups_remove_all_group_members($groupid)) {
20d55a1b 3082 if ($showfeedback) {
3083 notify($strdeleted .' groups_members', 'notifysuccess');
3084 }
3085 } else {
3086 $result = false;
3831de52 3087 }
3831de52 3088 }
3089 }
3090 }
3831de52 3091
20d55a1b 3092 if (!empty($data->reset_teachers)) {
3093 foreach ($teachers as $teacherid) {
3094 role_unassign(0, $teacherid, 0, $coursecontext->id);
3095 }
3831de52 3096 if ($showfeedback) {
20d55a1b 3097 notify($strdeleted .' '.get_string('teachers'), 'notifysuccess');
3831de52 3098 }
3831de52 3099 }
3100 }
3101
ffd0fbb7 3102 if (!empty($data->reset_groups)) {
f4ba7e1a 3103 if ($groupids = groups_get_groups($data->courseid)) {
3104 foreach ($groupids as $groupid) {
3105 if (groups_delete_group($groupid)) {
3831de52 3106 if ($showfeedback) {
ffd0fbb7 3107 notify($strdeleted .' groups', 'notifysuccess');
3831de52 3108 }
3109 } else {
3110 $result = false;
3111 }
3112 }
3113 }
3114 }
3115
ffd0fbb7 3116 if (!empty($data->reset_events)) {
3117 if (delete_records('event', 'courseid', $data->courseid)) {
3831de52 3118 if ($showfeedback) {
ffd0fbb7 3119 notify($strdeleted .' event', 'notifysuccess');
3831de52 3120 }
3121 } else {
3122 $result = false;
3123 }
3124 }
3125
ffd0fbb7 3126 if (!empty($data->reset_logs)) {
3127 if (delete_records('log', 'course', $data->courseid)) {
3831de52 3128 if ($showfeedback) {
ffd0fbb7 3129 notify($strdeleted .' log', 'notifysuccess');
3831de52 3130 }
3131 } else {
3132 $result = false;
3133 }
3134 }
3135
ea8158c1 3136 // deletes all role assignments, and local override, these have no courseid in table and needs separate process
9fd73f0c 3137 $context = get_context_instance(CONTEXT_COURSE, $data->courseid);
1bacd276 3138 delete_records('role_capabilities', 'contextid', $context->id);
20d55a1b 3139
3831de52 3140 return $result;
3831de52 3141}
3142
ffd0fbb7 3143
f4ba7e1a 3144require_once($CFG->dirroot.'/group/lib.php');
3145/*TODO: functions moved to /group/lib/legacylib.php
f374fb10 3146
f4ba7e1a 3147ismember
3148add_user_to_group
3149mygroupid
3150groupmode
3151set_current_group
3152... */
f374fb10 3153
0d67c514 3154
bb64b51a 3155function generate_email_processing_address($modid,$modargs) {
3156 global $CFG;
303d0af1 3157
3158 if (empty($CFG->siteidentifier)) { // Unique site identification code
3159 set_config('siteidentifier', random_string(32));
bb64b51a 3160 }
d2a9f7cc 3161
bb64b51a 3162 $header = $CFG->mailprefix . substr(base64_encode(pack('C',$modid)),0,2).$modargs;
2019116e 3163 return $header . substr(md5($header.$CFG->siteidentifier),0,16).'@'.$CFG->maildomain;
bb64b51a 3164}
3165
f374fb10 3166
bb64b51a 3167function moodle_process_email($modargs,$body) {
3168 // the first char should be an unencoded letter. We'll take this as an action
3169 switch ($modargs{0}) {
3170 case 'B': { // bounce
3171 list(,$userid) = unpack('V',base64_decode(substr($modargs,1,8)));
3172 if ($user = get_record_select("user","id=$userid","id,email")) {
3173 // check the half md5 of their email
3174 $md5check = substr(md5($user->email),0,16);
e67755a1 3175 if ($md5check == substr($modargs, -16)) {
bb64b51a 3176 set_bounce_count($user);
3177 }
3178 // else maybe they've already changed it?
3179 }
3180 }
3181 break;
3182 // maybe more later?
3183 }
3184}
f374fb10 3185
f9903ed0 3186/// CORRESPONDENCE ////////////////////////////////////////////////
3187
7cf1c7bd 3188/**
3189 * Send an email to a specified user
3190 *
7cf1c7bd 3191 * @uses $CFG
bbd3f2c4 3192 * @uses $FULLME
c6d15803 3193 * @uses SITEID
89dcb99d 3194 * @param user $user A {@link $USER} object
3195 * @param user $from A {@link $USER} object
7cf1c7bd 3196 * @param string $subject plain text subject line of the email
3197 * @param string $messagetext plain text version of the message
3198 * @param string $messagehtml complete html version of the message (optional)
3199 * @param string $attachment a file on the filesystem, relative to $CFG->dataroot
3200 * @param string $attachname the name of the file (extension indicates MIME)
bbd3f2c4 3201 * @param bool $usetrueaddress determines whether $from email address should
c6d15803 3202 * be sent out. Will be overruled by user profile setting for maildisplay
bbd3f2c4 3203 * @return bool|string Returns "true" if mail was sent OK, "emailstop" if email
c6d15803 3204 * was blocked by user and "false" if there was another sort of error.
7cf1c7bd 3205 */
043f5274 3206function email_to_user($user, $from, $subject, $messagetext, $messagehtml='', $attachment='', $attachname='', $usetrueaddress=true, $replyto='', $replytoname='') {
f9903ed0 3207
f9f4d999 3208 global $CFG, $FULLME;
f9903ed0 3209
0cc6fa6a 3210 global $course; // This is a bit of an ugly hack to be gotten rid of later
3211 if (!empty($course->lang)) { // Course language is defined
3212 $CFG->courselang = $course->lang;
3213 }
6aaa17c7 3214 if (!empty($course->theme)) { // Course theme is defined
32e2b302 3215 $CFG->coursetheme = $course->theme;
3216 }
0cc6fa6a 3217
b0ccd3fb 3218 include_once($CFG->libdir .'/phpmailer/class.phpmailer.php');
f9903ed0 3219
b212c114 3220/// We are going to use textlib services here
3221 $textlib = textlib_get_instance();
3222
cadb96f2 3223 if (empty($user)) {
3224 return false;
3225 }
3226
3227 if (!empty($user->emailstop)) {
579dcca4 3228 return 'emailstop';
f9903ed0 3229 }
d2a9f7cc 3230
bb64b51a 3231 if (over_bounce_threshold($user)) {
3232 error_log("User $user->id (".fullname($user).") is over bounce threshold! Not sending.");
3233 return false;
3234 }
d8ba183c 3235
f9903ed0 3236 $mail = new phpmailer;
3237
b0ccd3fb 3238 $mail->Version = 'Moodle '. $CFG->version; // mailer version
3239 $mail->PluginDir = $CFG->libdir .'/phpmailer/'; // plugin directory (eg smtp plugin)
562bbe90 3240
810944af 3241 $mail->CharSet = 'utf-8';
98c4eae3 3242
b0ccd3fb 3243 if ($CFG->smtphosts == 'qmail') {
62740736 3244 $mail->IsQmail(); // use Qmail system
3245
3246 } else if (empty($CFG->smtphosts)) {
3247 $mail->IsMail(); // use PHP mail() = sendmail
3248
3249 } else {
1e411ffc 3250 $mail->IsSMTP(); // use SMTP directly
ea82d6b6 3251 if (debugging()) {
b0ccd3fb 3252 echo '<pre>' . "\n";
57ef3480 3253 $mail->SMTPDebug = true;
3254 }
b0ccd3fb 3255 $mail->Host = $CFG->smtphosts; // specify main and backup servers
9f58537a 3256
3257 if ($CFG->smtpuser) { // Use SMTP authentication
3258 $mail->SMTPAuth = true;
3259 $mail->Username = $CFG->smtpuser;
3260 $mail->Password = $CFG->smtppass;
3261 }
7f86ce17 3262