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