Merged MDL-11332 from stable.
[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// //
56a1a882 10// Copyright (C) 1999 onwards 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/**
41b7618b 173 * PARAM_URL - expected properly formatted URL. Please note that domain part is required, http://localhost/ is not acceppted but http://localhost.localdomain/ is ok.
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
bafd7e78 723/**
724 * Get volatile flags
725 *
726 * @param string $type
727 * @param int $changedsince
728 * @return records array
729 *
730 */
731function get_cache_flags($type, $changedsince=NULL) {
732
733 $type = addslashes($type);
734
735 $sqlwhere = 'flagtype=\'' . $type . '\' AND expiry >= ' . time();
736 if ($changedsince !== NULL) {
737 $changedsince = (int)$changedsince;
738 $sqlwhere .= ' AND timemodified > ' . $changedsince;
739 }
740 $cf = array();
741 if ($flags=get_records_select('cache_flags', $sqlwhere, '', 'name,value')) {
742 foreach ($flags as $flag) {
743 $cf[$flag->name] = $flag->value;
744 }
745 }
746 return $cf;
747}
748
749
750/**
751 * Set a volatile flag
752 *
753 * @param string $type the "type" namespace for the key
754 * @param string $name the key to set
755 * @param string $value the value to set (without magic quotes) - NULL will remove the flag
756 * @param int $expiry (optional) epoch indicating expiry - defaults to now()+ 24hs
757 * @return bool
758 */
759function set_cache_flag($type, $name, $value, $expiry=NULL) {
760
761
762 $timemodified = time();
763 if ($expiry===NULL || $expiry < $timemodified) {
764 $expiry = $timemodified + 24 * 60 * 60;
765 } else {
766 $expiry = (int)$expiry;
767 }
768
769 if ($value === NULL) {
770 return unset_cache_flag($type,$name);
771 }
772
773 $type = addslashes($type);
774 $name = addslashes($name);
128f0984 775 if ($f = get_record('cache_flags', 'name', $name, 'flagtype', $type)) { // this is a potentail problem in DEBUG_DEVELOPER
776 if ($f->value == $value and $f->expiry == $expiry and $f->timemodified == $timemodified) {
777 return true; //no need to update; helps rcache too
778 }
779 $f->value = addslashes($value);
bafd7e78 780 $f->expiry = $expiry;
781 $f->timemodified = $timemodified;
782 return update_record('cache_flags', $f);
783 } else {
128f0984 784 $f = new object();
bafd7e78 785 $f->flagtype = $type;
786 $f->name = $name;
128f0984 787 $f->value = addslashes($value);
bafd7e78 788 $f->expiry = $expiry;
789 $f->timemodified = $timemodified;
128f0984 790 return (bool)insert_record('cache_flags', $f);
bafd7e78 791 }
792}
793
794/**
795 * Removes a single volatile flag
796 *
797 * @param string $type the "type" namespace for the key
798 * @param string $name the key to set
799 * @uses $CFG
800 * @return bool
801 */
802function unset_cache_flag($type, $name) {
803
804 return delete_records('cache_flags',
805 'name', addslashes($name),
806 'flagtype', addslashes($type));
807}
808
809/**
810 * Garbage-collect volatile flags
811 *
812 */
813function gc_cache_flags() {
814 return delete_records_select('cache_flags', 'expiry < ' . time());
815}
a4080313 816
7cf1c7bd 817/**
818 * Refresh current $USER session global variable with all their current preferences.
819 * @uses $USER
820 */
70812e39 821function reload_user_preferences() {
70812e39 822
823 global $USER;
824
346c3e2f 825 //reset preference
826 $USER->preference = array();
070e2616 827
346c3e2f 828 if (!isloggedin() or isguestuser()) {
829 // no pernament storage for not-logged-in user and guest
70812e39 830
346c3e2f 831 } else if ($preferences = get_records('user_preferences', 'userid', $USER->id)) {
70812e39 832 foreach ($preferences as $preference) {
833 $USER->preference[$preference->name] = $preference->value;
834 }
c6d15803 835 }
346c3e2f 836
837 return true;
70812e39 838}
839
7cf1c7bd 840/**
841 * Sets a preference for the current user
842 * Optionally, can set a preference for a different user object
843 * @uses $USER
68fbd8e1 844 * @todo Add a better description and include usage examples. Add inline links to $USER and user functions in above line.
845
7cf1c7bd 846 * @param string $name The key to set as preference for the specified user
847 * @param string $value The value to set forthe $name key in the specified user's record
346c3e2f 848 * @param int $otheruserid A moodle user ID
bbd3f2c4 849 * @return bool
7cf1c7bd 850 */
346c3e2f 851function set_user_preference($name, $value, $otheruserid=NULL) {
70812e39 852
853 global $USER;
854
346c3e2f 855 if (!isset($USER->preference)) {
856 reload_user_preferences();
d35757eb 857 }
858
70812e39 859 if (empty($name)) {
860 return false;
861 }
862
346c3e2f 863 $nostore = false;
864
865 if (empty($otheruserid)){
866 if (!isloggedin() or isguestuser()) {
867 $nostore = true;
868 }
869 $userid = $USER->id;
870 } else {
871 if (isguestuser($otheruserid)) {
872 $nostore = true;
873 }
874 $userid = $otheruserid;
875 }
876
877 $return = true;
878 if ($nostore) {
879 // no pernament storage for not-logged-in user and guest
880
881 } else if ($preference = get_record('user_preferences', 'userid', $userid, 'name', addslashes($name))) {
a1244706 882 if ($preference->value === $value) {
883 return true;
884 }
346c3e2f 885 if (!set_field('user_preferences', 'value', addslashes((string)$value), 'id', $preference->id)) {
886 $return = false;
066af654 887 }
70812e39 888
889 } else {
346c3e2f 890 $preference = new object();
a3f1f815 891 $preference->userid = $userid;
346c3e2f 892 $preference->name = addslashes($name);
893 $preference->value = addslashes((string)$value);
894 if (!insert_record('user_preferences', $preference)) {
895 $return = false;
70812e39 896 }
897 }
346c3e2f 898
899 // update value in USER session if needed
900 if ($userid == $USER->id) {
901 $USER->preference[$name] = (string)$value;
902 }
903
904 return $return;
70812e39 905}
906
6eb3e776 907/**
908 * Unsets a preference completely by deleting it from the database
909 * Optionally, can set a preference for a different user id
910 * @uses $USER
911 * @param string $name The key to unset as preference for the specified user
346c3e2f 912 * @param int $otheruserid A moodle user ID
6eb3e776 913 */
346c3e2f 914function unset_user_preference($name, $otheruserid=NULL) {
6eb3e776 915
916 global $USER;
917
346c3e2f 918 if (!isset($USER->preference)) {
919 reload_user_preferences();
6eb3e776 920 }
921
346c3e2f 922 if (empty($otheruserid)){
923 $userid = $USER->id;
924 } else {
925 $userid = $otheruserid;
926 }
927
928 //Delete the preference from $USER if needed
929 if ($userid == $USER->id) {
49d005ee 930 unset($USER->preference[$name]);
931 }
e1ecf0a0 932
49d005ee 933 //Then from DB
346c3e2f 934 return delete_records('user_preferences', 'userid', $userid, 'name', addslashes($name));
6eb3e776 935}
936
937
7cf1c7bd 938/**
939 * Sets a whole array of preferences for the current user
940 * @param array $prefarray An array of key/value pairs to be set
346c3e2f 941 * @param int $otheruserid A moodle user ID
bbd3f2c4 942 * @return bool
7cf1c7bd 943 */
346c3e2f 944function set_user_preferences($prefarray, $otheruserid=NULL) {
70812e39 945
946 if (!is_array($prefarray) or empty($prefarray)) {
947 return false;
948 }
949
950 $return = true;
951 foreach ($prefarray as $name => $value) {
346c3e2f 952 // The order is important; test for return is done first
953 $return = (set_user_preference($name, $value, $otheruserid) && $return);
70812e39 954 }
955 return $return;
956}
957
7cf1c7bd 958/**
959 * If no arguments are supplied this function will return
361855e6 960 * all of the current user preferences as an array.
7cf1c7bd 961 * If a name is specified then this function
962 * attempts to return that particular preference value. If
963 * none is found, then the optional value $default is returned,
964 * otherwise NULL.
965 * @param string $name Name of the key to use in finding a preference value
966 * @param string $default Value to be returned if the $name key is not set in the user preferences
346c3e2f 967 * @param int $otheruserid A moodle user ID
7cf1c7bd 968 * @uses $USER
969 * @return string
970 */
346c3e2f 971function get_user_preferences($name=NULL, $default=NULL, $otheruserid=NULL) {
70812e39 972 global $USER;
973
346c3e2f 974 if (!isset($USER->preference)) {
975 reload_user_preferences();
976 }
a3f1f815 977
346c3e2f 978 if (empty($otheruserid)){
979 $userid = $USER->id;
a3f1f815 980 } else {
346c3e2f 981 $userid = $otheruserid;
982 }
a3f1f815 983
346c3e2f 984 if ($userid == $USER->id) {
985 $preference = $USER->preference;
986
987 } else {
988 $preference = array();
989 if ($prefdata = get_records('user_preferences', 'userid', $userid)) {
990 foreach ($prefdata as $pref) {
991 $preference[$pref->name] = $pref->value;
992 }
a3f1f815 993 }
346c3e2f 994 }
995
996 if (empty($name)) {
997 return $preference; // All values
998
999 } else if (array_key_exists($name, $preference)) {
1000 return $preference[$name]; // The single value
1001
1002 } else {
1003 return $default; // Default value (or NULL)
70812e39 1004 }
70812e39 1005}
1006
1007
9fa49e22 1008/// FUNCTIONS FOR HANDLING TIME ////////////////////////////////////////////
39917a09 1009
7cf1c7bd 1010/**
c6d15803 1011 * Given date parts in user time produce a GMT timestamp.
7cf1c7bd 1012 *
68fbd8e1 1013 * @param int $year The year part to create timestamp of
1014 * @param int $month The month part to create timestamp of
1015 * @param int $day The day part to create timestamp of
1016 * @param int $hour The hour part to create timestamp of
1017 * @param int $minute The minute part to create timestamp of
1018 * @param int $second The second part to create timestamp of
1019 * @param float $timezone ?
1020 * @param bool $applydst ?
e34d817e 1021 * @return int timestamp
7cf1c7bd 1022 * @todo Finish documenting this function
1023 */
9f1f6daf 1024function make_timestamp($year, $month=1, $day=1, $hour=0, $minute=0, $second=0, $timezone=99, $applydst=true) {
39917a09 1025
dddb014a 1026 $timezone = get_user_timezone_offset($timezone);
1027
94e34118 1028 if (abs($timezone) > 13) {
68fbd8e1 1029 $time = mktime((int)$hour, (int)$minute, (int)$second, (int)$month, (int)$day, (int)$year);
03c17ddf 1030 } else {
68fbd8e1 1031 $time = gmmktime((int)$hour, (int)$minute, (int)$second, (int)$month, (int)$day, (int)$year);
196f2619 1032 $time = usertime($time, $timezone);
28c66824 1033 if($applydst) {
1034 $time -= dst_offset_on($time);
1035 }
9f1f6daf 1036 }
1037
196f2619 1038 return $time;
85cafb3e 1039
39917a09 1040}
1041
7cf1c7bd 1042/**
1043 * Given an amount of time in seconds, returns string
5602f7cf 1044 * formatted nicely as weeks, days, hours etc as needed
7cf1c7bd 1045 *
2f87145b 1046 * @uses MINSECS
1047 * @uses HOURSECS
1048 * @uses DAYSECS
5602f7cf 1049 * @uses YEARSECS
c6d15803 1050 * @param int $totalsecs ?
1051 * @param array $str ?
89dcb99d 1052 * @return string
7cf1c7bd 1053 */
1054 function format_time($totalsecs, $str=NULL) {
c7e3ac2a 1055
6b174680 1056 $totalsecs = abs($totalsecs);
c7e3ac2a 1057
8dbed6be 1058 if (!$str) { // Create the str structure the slow way
b0ccd3fb 1059 $str->day = get_string('day');
1060 $str->days = get_string('days');
1061 $str->hour = get_string('hour');
1062 $str->hours = get_string('hours');
1063 $str->min = get_string('min');
1064 $str->mins = get_string('mins');
1065 $str->sec = get_string('sec');
1066 $str->secs = get_string('secs');
5602f7cf 1067 $str->year = get_string('year');
1068 $str->years = get_string('years');
8dbed6be 1069 }
1070
5602f7cf 1071
1072 $years = floor($totalsecs/YEARSECS);
1073 $remainder = $totalsecs - ($years*YEARSECS);
5602f7cf 1074 $days = floor($remainder/DAYSECS);
7a5672c9 1075 $remainder = $totalsecs - ($days*DAYSECS);
1076 $hours = floor($remainder/HOURSECS);
1077 $remainder = $remainder - ($hours*HOURSECS);
1078 $mins = floor($remainder/MINSECS);
1079 $secs = $remainder - ($mins*MINSECS);
8dbed6be 1080
1081 $ss = ($secs == 1) ? $str->sec : $str->secs;
1082 $sm = ($mins == 1) ? $str->min : $str->mins;
1083 $sh = ($hours == 1) ? $str->hour : $str->hours;
1084 $sd = ($days == 1) ? $str->day : $str->days;
5602f7cf 1085 $sy = ($years == 1) ? $str->year : $str->years;
8dbed6be 1086
5602f7cf 1087 $oyears = '';
b0ccd3fb 1088 $odays = '';
1089 $ohours = '';
1090 $omins = '';
1091 $osecs = '';
9c9f7d77 1092
5602f7cf 1093 if ($years) $oyears = $years .' '. $sy;
b0ccd3fb 1094 if ($days) $odays = $days .' '. $sd;
1095 if ($hours) $ohours = $hours .' '. $sh;
1096 if ($mins) $omins = $mins .' '. $sm;
1097 if ($secs) $osecs = $secs .' '. $ss;
6b174680 1098
77ac808e 1099 if ($years) return trim($oyears .' '. $odays);
1100 if ($days) return trim($odays .' '. $ohours);
1101 if ($hours) return trim($ohours .' '. $omins);
1102 if ($mins) return trim($omins .' '. $osecs);
b0ccd3fb 1103 if ($secs) return $osecs;
1104 return get_string('now');
6b174680 1105}
f9903ed0 1106
7cf1c7bd 1107/**
1108 * Returns a formatted string that represents a date in user time
1109 * <b>WARNING: note that the format is for strftime(), not date().</b>
1110 * Because of a bug in most Windows time libraries, we can't use
1111 * the nicer %e, so we have to use %d which has leading zeroes.
1112 * A lot of the fuss in the function is just getting rid of these leading
1113 * zeroes as efficiently as possible.
361855e6 1114 *
8c3dba73 1115 * If parameter fixday = true (default), then take off leading
7cf1c7bd 1116 * zero from %d, else mantain it.
1117 *
2f87145b 1118 * @uses HOURSECS
e34d817e 1119 * @param int $date timestamp in GMT
1120 * @param string $format strftime format
d2a9f7cc 1121 * @param float $timezone
bbd3f2c4 1122 * @param bool $fixday If true (default) then the leading
c6d15803 1123 * zero from %d is removed. If false then the leading zero is mantained.
1124 * @return string
7cf1c7bd 1125 */
b0ccd3fb 1126function userdate($date, $format='', $timezone=99, $fixday = true) {
7a302afc 1127
1ac7ee24 1128 global $CFG;
1129
1306c5ea 1130 if (empty($format)) {
1131 $format = get_string('strftimedaydatetime');
5fa51a39 1132 }
035cdbff 1133
c3a3c5b8 1134 if (!empty($CFG->nofixday)) { // Config.php can force %d not to be fixed.
1135 $fixday = false;
1136 } else if ($fixday) {
1137 $formatnoday = str_replace('%d', 'DD', $format);
61ae5d36 1138 $fixday = ($formatnoday != $format);
1139 }
dcde9f02 1140
88ec5b7c 1141 $date += dst_offset_on($date);
85351042 1142
494b9296 1143 $timezone = get_user_timezone_offset($timezone);
102dc313 1144
1145 if (abs($timezone) > 13) { /// Server time
d2a9f7cc 1146 if ($fixday) {
102dc313 1147 $datestring = strftime($formatnoday, $date);
1148 $daystring = str_replace(' 0', '', strftime(' %d', $date));
1149 $datestring = str_replace('DD', $daystring, $datestring);
1150 } else {
1151 $datestring = strftime($format, $date);
1152 }
88ec5b7c 1153 } else {
102dc313 1154 $date += (int)($timezone * 3600);
1155 if ($fixday) {
1156 $datestring = gmstrftime($formatnoday, $date);
1157 $daystring = str_replace(' 0', '', gmstrftime(' %d', $date));
1158 $datestring = str_replace('DD', $daystring, $datestring);
1159 } else {
1160 $datestring = gmstrftime($format, $date);
1161 }
88ec5b7c 1162 }
102dc313 1163
fb773106 1164/// If we are running under Windows convert from windows encoding to UTF-8
1165/// (because it's impossible to specify UTF-8 to fetch locale info in Win32)
11f7b25d 1166
fb773106 1167 if ($CFG->ostype == 'WINDOWS') {
11f7b25d 1168 if ($localewincharset = get_string('localewincharset')) {
1169 $textlib = textlib_get_instance();
810944af 1170 $datestring = $textlib->convert($datestring, $localewincharset, 'utf-8');
11f7b25d 1171 }
1172 }
1173
035cdbff 1174 return $datestring;
873960de 1175}
1176
7cf1c7bd 1177/**
196f2619 1178 * Given a $time timestamp in GMT (seconds since epoch),
c6d15803 1179 * returns an array that represents the date in user time
7cf1c7bd 1180 *
2f87145b 1181 * @uses HOURSECS
196f2619 1182 * @param int $time Timestamp in GMT
68fbd8e1 1183 * @param float $timezone ?
c6d15803 1184 * @return array An array that represents the date in user time
7cf1c7bd 1185 * @todo Finish documenting this function
1186 */
196f2619 1187function usergetdate($time, $timezone=99) {
6b174680 1188
494b9296 1189 $timezone = get_user_timezone_offset($timezone);
a36166d3 1190
e34d817e 1191 if (abs($timezone) > 13) { // Server time
ed1f69b0 1192 return getdate($time);
d2a9f7cc 1193 }
1194
e34d817e 1195 // There is no gmgetdate so we use gmdate instead
02f0527d 1196 $time += dst_offset_on($time);
e34d817e 1197 $time += intval((float)$timezone * HOURSECS);
3bba1e6e 1198
1199 $datestring = gmstrftime('%S_%M_%H_%d_%m_%Y_%w_%j_%A_%B', $time);
02f0527d 1200
9f1f6daf 1201 list(
1202 $getdate['seconds'],
1203 $getdate['minutes'],
1204 $getdate['hours'],
1205 $getdate['mday'],
1206 $getdate['mon'],
1207 $getdate['year'],
1208 $getdate['wday'],
1209 $getdate['yday'],
1210 $getdate['weekday'],
1211 $getdate['month']
3bba1e6e 1212 ) = explode('_', $datestring);
9f1f6daf 1213
d2d6171f 1214 return $getdate;
d552ead0 1215}
1216
7cf1c7bd 1217/**
1218 * Given a GMT timestamp (seconds since epoch), offsets it by
1219 * the timezone. eg 3pm in India is 3pm GMT - 7 * 3600 seconds
1220 *
2f87145b 1221 * @uses HOURSECS
c6d15803 1222 * @param int $date Timestamp in GMT
e34d817e 1223 * @param float $timezone
c6d15803 1224 * @return int
7cf1c7bd 1225 */
d552ead0 1226function usertime($date, $timezone=99) {
a36166d3 1227
494b9296 1228 $timezone = get_user_timezone_offset($timezone);
2665e47a 1229
0431bd7c 1230 if (abs($timezone) > 13) {
d552ead0 1231 return $date;
1232 }
7a5672c9 1233 return $date - (int)($timezone * HOURSECS);
d552ead0 1234}
1235
8c3dba73 1236/**
1237 * Given a time, return the GMT timestamp of the most recent midnight
1238 * for the current user.
1239 *
e34d817e 1240 * @param int $date Timestamp in GMT
1241 * @param float $timezone ?
c6d15803 1242 * @return ?
8c3dba73 1243 */
edf7fe8c 1244function usergetmidnight($date, $timezone=99) {
edf7fe8c 1245
494b9296 1246 $timezone = get_user_timezone_offset($timezone);
edf7fe8c 1247 $userdate = usergetdate($date, $timezone);
4606d9bb 1248
02f0527d 1249 // Time of midnight of this user's day, in GMT
1250 return make_timestamp($userdate['year'], $userdate['mon'], $userdate['mday'], 0, 0, 0, $timezone);
edf7fe8c 1251
1252}
1253
7cf1c7bd 1254/**
1255 * Returns a string that prints the user's timezone
1256 *
1257 * @param float $timezone The user's timezone
1258 * @return string
1259 */
d552ead0 1260function usertimezone($timezone=99) {
d552ead0 1261
0c244315 1262 $tz = get_user_timezone($timezone);
f30fe8d0 1263
0c244315 1264 if (!is_float($tz)) {
1265 return $tz;
d552ead0 1266 }
0c244315 1267
1268 if(abs($tz) > 13) { // Server time
1269 return get_string('serverlocaltime');
1270 }
1271
1272 if($tz == intval($tz)) {
1273 // Don't show .0 for whole hours
1274 $tz = intval($tz);
1275 }
1276
1277 if($tz == 0) {
b0ccd3fb 1278 return 'GMT';
d552ead0 1279 }
0c244315 1280 else if($tz > 0) {
1281 return 'GMT+'.$tz;
1282 }
1283 else {
1284 return 'GMT'.$tz;
d552ead0 1285 }
e1ecf0a0 1286
f9903ed0 1287}
1288
7cf1c7bd 1289/**
1290 * Returns a float which represents the user's timezone difference from GMT in hours
1291 * Checks various settings and picks the most dominant of those which have a value
1292 *
7cf1c7bd 1293 * @uses $CFG
1294 * @uses $USER
b2b68362 1295 * @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 1296 * @return int
7cf1c7bd 1297 */
494b9296 1298function get_user_timezone_offset($tz = 99) {
f30fe8d0 1299
43b59916 1300 global $USER, $CFG;
1301
e8904995 1302 $tz = get_user_timezone($tz);
c9e55a25 1303
7b9e355e 1304 if (is_float($tz)) {
1305 return $tz;
1306 } else {
e8904995 1307 $tzrecord = get_timezone_record($tz);
7b9e355e 1308 if (empty($tzrecord)) {
e8904995 1309 return 99.0;
1310 }
4f2dbde9 1311 return (float)$tzrecord->gmtoff / HOURMINS;
e8904995 1312 }
1313}
1314
bbd3f2c4 1315/**
b2b68362 1316 * Returns a float or a string which denotes the user's timezone
1317 * 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)
1318 * means that for this timezone there are also DST rules to be taken into account
1319 * Checks various settings and picks the most dominant of those which have a value
bbd3f2c4 1320 *
1321 * @uses $USER
1322 * @uses $CFG
b2b68362 1323 * @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
1324 * @return mixed
bbd3f2c4 1325 */
e8904995 1326function get_user_timezone($tz = 99) {
1327 global $USER, $CFG;
43b59916 1328
f30fe8d0 1329 $timezones = array(
e8904995 1330 $tz,
1331 isset($CFG->forcetimezone) ? $CFG->forcetimezone : 99,
43b59916 1332 isset($USER->timezone) ? $USER->timezone : 99,
1333 isset($CFG->timezone) ? $CFG->timezone : 99,
f30fe8d0 1334 );
43b59916 1335
e8904995 1336 $tz = 99;
43b59916 1337
e8904995 1338 while(($tz == '' || $tz == 99) && $next = each($timezones)) {
1339 $tz = $next['value'];
43b59916 1340 }
e8904995 1341
1342 return is_numeric($tz) ? (float) $tz : $tz;
43b59916 1343}
1344
bbd3f2c4 1345/**
1346 * ?
1347 *
1348 * @uses $CFG
1349 * @uses $db
1350 * @param string $timezonename ?
1351 * @return object
1352 */
43b59916 1353function get_timezone_record($timezonename) {
1354 global $CFG, $db;
1355 static $cache = NULL;
1356
8edffd15 1357 if ($cache === NULL) {
43b59916 1358 $cache = array();
1359 }
1360
8edffd15 1361 if (isset($cache[$timezonename])) {
43b59916 1362 return $cache[$timezonename];
f30fe8d0 1363 }
1364
952d8dc8 1365 return $cache[$timezonename] = get_record_sql('SELECT * FROM '.$CFG->prefix.'timezone
1366 WHERE name = '.$db->qstr($timezonename).' ORDER BY year DESC', true);
f30fe8d0 1367}
f9903ed0 1368
bbd3f2c4 1369/**
1370 * ?
1371 *
1372 * @uses $CFG
1373 * @uses $USER
1374 * @param ? $fromyear ?
1375 * @param ? $to_year ?
1376 * @return bool
1377 */
830a2bbd 1378function calculate_user_dst_table($from_year = NULL, $to_year = NULL) {
2280ecf5 1379 global $CFG, $SESSION;
85cafb3e 1380
989585e9 1381 $usertz = get_user_timezone();
7cb29a3d 1382
989585e9 1383 if (is_float($usertz)) {
1384 // Trivial timezone, no DST
1385 return false;
1386 }
1387
2280ecf5 1388 if (!empty($SESSION->dst_offsettz) && $SESSION->dst_offsettz != $usertz) {
989585e9 1389 // We have precalculated values, but the user's effective TZ has changed in the meantime, so reset
2280ecf5 1390 unset($SESSION->dst_offsets);
1391 unset($SESSION->dst_range);
830a2bbd 1392 }
1393
2280ecf5 1394 if (!empty($SESSION->dst_offsets) && empty($from_year) && empty($to_year)) {
830a2bbd 1395 // Repeat calls which do not request specific year ranges stop here, we have already calculated the table
1396 // This will be the return path most of the time, pretty light computationally
1397 return true;
85cafb3e 1398 }
1399
830a2bbd 1400 // Reaching here means we either need to extend our table or create it from scratch
989585e9 1401
1402 // Remember which TZ we calculated these changes for
2280ecf5 1403 $SESSION->dst_offsettz = $usertz;
989585e9 1404
2280ecf5 1405 if(empty($SESSION->dst_offsets)) {
830a2bbd 1406 // If we 're creating from scratch, put the two guard elements in there
2280ecf5 1407 $SESSION->dst_offsets = array(1 => NULL, 0 => NULL);
830a2bbd 1408 }
2280ecf5 1409 if(empty($SESSION->dst_range)) {
830a2bbd 1410 // If creating from scratch
1411 $from = max((empty($from_year) ? intval(date('Y')) - 3 : $from_year), 1971);
1412 $to = min((empty($to_year) ? intval(date('Y')) + 3 : $to_year), 2035);
1413
1414 // Fill in the array with the extra years we need to process
1415 $yearstoprocess = array();
1416 for($i = $from; $i <= $to; ++$i) {
1417 $yearstoprocess[] = $i;
1418 }
1419
1420 // Take note of which years we have processed for future calls
2280ecf5 1421 $SESSION->dst_range = array($from, $to);
830a2bbd 1422 }
1423 else {
1424 // If needing to extend the table, do the same
1425 $yearstoprocess = array();
1426
2280ecf5 1427 $from = max((empty($from_year) ? $SESSION->dst_range[0] : $from_year), 1971);
1428 $to = min((empty($to_year) ? $SESSION->dst_range[1] : $to_year), 2035);
830a2bbd 1429
2280ecf5 1430 if($from < $SESSION->dst_range[0]) {
830a2bbd 1431 // Take note of which years we need to process and then note that we have processed them for future calls
2280ecf5 1432 for($i = $from; $i < $SESSION->dst_range[0]; ++$i) {
830a2bbd 1433 $yearstoprocess[] = $i;
1434 }
2280ecf5 1435 $SESSION->dst_range[0] = $from;
830a2bbd 1436 }
2280ecf5 1437 if($to > $SESSION->dst_range[1]) {
830a2bbd 1438 // Take note of which years we need to process and then note that we have processed them for future calls
2280ecf5 1439 for($i = $SESSION->dst_range[1] + 1; $i <= $to; ++$i) {
830a2bbd 1440 $yearstoprocess[] = $i;
1441 }
2280ecf5 1442 $SESSION->dst_range[1] = $to;
830a2bbd 1443 }
1444 }
1445
1446 if(empty($yearstoprocess)) {
1447 // This means that there was a call requesting a SMALLER range than we have already calculated
1448 return true;
1449 }
1450
1451 // From now on, we know that the array has at least the two guard elements, and $yearstoprocess has the years we need
1452 // Also, the array is sorted in descending timestamp order!
1453
1454 // Get DB data
989585e9 1455 $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 1456 if(empty($presetrecords)) {
1457 return false;
1458 }
57f1191c 1459
830a2bbd 1460 // Remove ending guard (first element of the array)
2280ecf5 1461 reset($SESSION->dst_offsets);
1462 unset($SESSION->dst_offsets[key($SESSION->dst_offsets)]);
830a2bbd 1463
1464 // Add all required change timestamps
1465 foreach($yearstoprocess as $y) {
1466 // Find the record which is in effect for the year $y
1467 foreach($presetrecords as $year => $preset) {
1468 if($year <= $y) {
1469 break;
c9e72798 1470 }
830a2bbd 1471 }
1472
1473 $changes = dst_changes_for_year($y, $preset);
1474
1475 if($changes === NULL) {
1476 continue;
1477 }
1478 if($changes['dst'] != 0) {
2280ecf5 1479 $SESSION->dst_offsets[$changes['dst']] = $preset->dstoff * MINSECS;
830a2bbd 1480 }
1481 if($changes['std'] != 0) {
2280ecf5 1482 $SESSION->dst_offsets[$changes['std']] = 0;
c9e72798 1483 }
85cafb3e 1484 }
42d36497 1485
830a2bbd 1486 // Put in a guard element at the top
2280ecf5 1487 $maxtimestamp = max(array_keys($SESSION->dst_offsets));
1488 $SESSION->dst_offsets[($maxtimestamp + DAYSECS)] = NULL; // DAYSECS is arbitrary, any "small" number will do
830a2bbd 1489
1490 // Sort again
2280ecf5 1491 krsort($SESSION->dst_offsets);
830a2bbd 1492
e789650d 1493 return true;
1494}
42d36497 1495
e789650d 1496function dst_changes_for_year($year, $timezone) {
7cb29a3d 1497
e789650d 1498 if($timezone->dst_startday == 0 && $timezone->dst_weekday == 0 && $timezone->std_startday == 0 && $timezone->std_weekday == 0) {
1499 return NULL;
42d36497 1500 }
7cb29a3d 1501
e789650d 1502 $monthdaydst = find_day_in_month($timezone->dst_startday, $timezone->dst_weekday, $timezone->dst_month, $year);
1503 $monthdaystd = find_day_in_month($timezone->std_startday, $timezone->std_weekday, $timezone->std_month, $year);
1504
1505 list($dst_hour, $dst_min) = explode(':', $timezone->dst_time);
1506 list($std_hour, $std_min) = explode(':', $timezone->std_time);
d2a9f7cc 1507
6dc8dddc 1508 $timedst = make_timestamp($year, $timezone->dst_month, $monthdaydst, 0, 0, 0, 99, false);
1509 $timestd = make_timestamp($year, $timezone->std_month, $monthdaystd, 0, 0, 0, 99, false);
830a2bbd 1510
1511 // Instead of putting hour and minute in make_timestamp(), we add them afterwards.
1512 // This has the advantage of being able to have negative values for hour, i.e. for timezones
1513 // where GMT time would be in the PREVIOUS day than the local one on which DST changes.
1514
1515 $timedst += $dst_hour * HOURSECS + $dst_min * MINSECS;
1516 $timestd += $std_hour * HOURSECS + $std_min * MINSECS;
42d36497 1517
e789650d 1518 return array('dst' => $timedst, 0 => $timedst, 'std' => $timestd, 1 => $timestd);
42d36497 1519}
1520
02f0527d 1521// $time must NOT be compensated at all, it has to be a pure timestamp
1522function dst_offset_on($time) {
2280ecf5 1523 global $SESSION;
02f0527d 1524
2280ecf5 1525 if(!calculate_user_dst_table() || empty($SESSION->dst_offsets)) {
c9e72798 1526 return 0;
85cafb3e 1527 }
1528
2280ecf5 1529 reset($SESSION->dst_offsets);
1530 while(list($from, $offset) = each($SESSION->dst_offsets)) {
59556d48 1531 if($from <= $time) {
c9e72798 1532 break;
1533 }
1534 }
1535
830a2bbd 1536 // This is the normal return path
1537 if($offset !== NULL) {
1538 return $offset;
02f0527d 1539 }
02f0527d 1540
830a2bbd 1541 // Reaching this point means we haven't calculated far enough, do it now:
1542 // Calculate extra DST changes if needed and recurse. The recursion always
1543 // moves toward the stopping condition, so will always end.
1544
1545 if($from == 0) {
2280ecf5 1546 // We need a year smaller than $SESSION->dst_range[0]
1547 if($SESSION->dst_range[0] == 1971) {
830a2bbd 1548 return 0;
1549 }
2280ecf5 1550 calculate_user_dst_table($SESSION->dst_range[0] - 5, NULL);
830a2bbd 1551 return dst_offset_on($time);
1552 }
1553 else {
2280ecf5 1554 // We need a year larger than $SESSION->dst_range[1]
1555 if($SESSION->dst_range[1] == 2035) {
830a2bbd 1556 return 0;
1557 }
2280ecf5 1558 calculate_user_dst_table(NULL, $SESSION->dst_range[1] + 5);
830a2bbd 1559 return dst_offset_on($time);
1560 }
85cafb3e 1561}
02f0527d 1562
28902d99 1563function find_day_in_month($startday, $weekday, $month, $year) {
8dc3f6cf 1564
1565 $daysinmonth = days_in_month($month, $year);
1566
42d36497 1567 if($weekday == -1) {
28902d99 1568 // Don't care about weekday, so return:
1569 // abs($startday) if $startday != -1
1570 // $daysinmonth otherwise
1571 return ($startday == -1) ? $daysinmonth : abs($startday);
8dc3f6cf 1572 }
1573
1574 // From now on we 're looking for a specific weekday
8dc3f6cf 1575
28902d99 1576 // Give "end of month" its actual value, since we know it
1577 if($startday == -1) {
1578 $startday = -1 * $daysinmonth;
1579 }
1580
1581 // Starting from day $startday, the sign is the direction
8dc3f6cf 1582
28902d99 1583 if($startday < 1) {
8dc3f6cf 1584
28902d99 1585 $startday = abs($startday);
8dc3f6cf 1586 $lastmonthweekday = strftime('%w', mktime(12, 0, 0, $month, $daysinmonth, $year, 0));
1587
1588 // This is the last such weekday of the month
1589 $lastinmonth = $daysinmonth + $weekday - $lastmonthweekday;
1590 if($lastinmonth > $daysinmonth) {
1591 $lastinmonth -= 7;
42d36497 1592 }
8dc3f6cf 1593
28902d99 1594 // Find the first such weekday <= $startday
1595 while($lastinmonth > $startday) {
8dc3f6cf 1596 $lastinmonth -= 7;
42d36497 1597 }
8dc3f6cf 1598
1599 return $lastinmonth;
e1ecf0a0 1600
42d36497 1601 }
1602 else {
42d36497 1603
28902d99 1604 $indexweekday = strftime('%w', mktime(12, 0, 0, $month, $startday, $year, 0));
42d36497 1605
8dc3f6cf 1606 $diff = $weekday - $indexweekday;
1607 if($diff < 0) {
1608 $diff += 7;
42d36497 1609 }
42d36497 1610
28902d99 1611 // This is the first such weekday of the month equal to or after $startday
1612 $firstfromindex = $startday + $diff;
42d36497 1613
8dc3f6cf 1614 return $firstfromindex;
1615
1616 }
42d36497 1617}
1618
bbd3f2c4 1619/**
1620 * Calculate the number of days in a given month
1621 *
1622 * @param int $month The month whose day count is sought
1623 * @param int $year The year of the month whose day count is sought
1624 * @return int
1625 */
42d36497 1626function days_in_month($month, $year) {
1627 return intval(date('t', mktime(12, 0, 0, $month, 1, $year, 0)));
1628}
1629
bbd3f2c4 1630/**
1631 * Calculate the position in the week of a specific calendar day
1632 *
1633 * @param int $day The day of the date whose position in the week is sought
1634 * @param int $month The month of the date whose position in the week is sought
1635 * @param int $year The year of the date whose position in the week is sought
1636 * @return int
1637 */
8dc3f6cf 1638function dayofweek($day, $month, $year) {
1639 // I wonder if this is any different from
1640 // strftime('%w', mktime(12, 0, 0, $month, $daysinmonth, $year, 0));
1641 return intval(date('w', mktime(12, 0, 0, $month, $day, $year, 0)));
1642}
1643
9fa49e22 1644/// USER AUTHENTICATION AND LOGIN ////////////////////////////////////////
f9903ed0 1645
bbd3f2c4 1646/**
1647 * Makes sure that $USER->sesskey exists, if $USER itself exists. It sets a new sesskey
1648 * if one does not already exist, but does not overwrite existing sesskeys. Returns the
1649 * sesskey string if $USER exists, or boolean false if not.
1650 *
1651 * @uses $USER
1652 * @return string
1653 */
04280e85 1654function sesskey() {
1a33f699 1655 global $USER;
1656
1657 if(!isset($USER)) {
1658 return false;
1659 }
1660
1661 if (empty($USER->sesskey)) {
1662 $USER->sesskey = random_string(10);
1663 }
1664
1665 return $USER->sesskey;
1666}
1667
0302c52f 1668
c4d0753b 1669/**
1670 * For security purposes, this function will check that the currently
1671 * given sesskey (passed as a parameter to the script or this function)
1672 * matches that of the current user.
1673 *
1674 * @param string $sesskey optionally provided sesskey
1675 * @return bool
1676 */
1677function confirm_sesskey($sesskey=NULL) {
1678 global $USER;
0302c52f 1679
c4d0753b 1680 if (!empty($USER->ignoresesskey) || !empty($CFG->ignoresesskey)) {
1681 return true;
0302c52f 1682 }
1683
c4d0753b 1684 if (empty($sesskey)) {
1685 $sesskey = required_param('sesskey', PARAM_RAW); // Check script parameters
0302c52f 1686 }
1687
c4d0753b 1688 if (!isset($USER->sesskey)) {
1689 return false;
1690 }
0302c52f 1691
c4d0753b 1692 return ($USER->sesskey === $sesskey);
0302c52f 1693}
c4d0753b 1694
dcf6d93c 1695/**
9152fc99 1696 * Setup all global $CFG course variables, set locale and also themes
1697 * This function can be used on pages that do not require login instead of require_login()
1698 *
dcf6d93c 1699 * @param mixed $courseorid id of the course or course object
1700 */
1701function course_setup($courseorid=0) {
1306c5ea 1702 global $COURSE, $CFG, $SITE;
dcf6d93c 1703
1704/// Redefine global $COURSE if needed
1705 if (empty($courseorid)) {
1706 // no change in global $COURSE - for backwards compatibiltiy
5e623a33 1707 // if require_rogin() used after require_login($courseid);
dcf6d93c 1708 } else if (is_object($courseorid)) {
1709 $COURSE = clone($courseorid);
1710 } else {
1711 global $course; // used here only to prevent repeated fetching from DB - may be removed later
9152fc99 1712 if (!empty($course->id) and $course->id == SITEID) {
1713 $COURSE = clone($SITE);
1714 } else if (!empty($course->id) and $course->id == $courseorid) {
dcf6d93c 1715 $COURSE = clone($course);
1716 } else {
1717 if (!$COURSE = get_record('course', 'id', $courseorid)) {
1718 error('Invalid course ID');
1719 }
1720 }
1721 }
1722
9152fc99 1723/// set locale and themes
dcf6d93c 1724 moodle_setlocale();
dcf6d93c 1725 theme_setup();
1726
dcf6d93c 1727}
c4d0753b 1728
7cf1c7bd 1729/**
ec81373f 1730 * This function checks that the current user is logged in and has the
1731 * required privileges
1732 *
7cf1c7bd 1733 * This function checks that the current user is logged in, and optionally
ec81373f 1734 * whether they are allowed to be in a particular course and view a particular
1735 * course module.
1736 * If they are not logged in, then it redirects them to the site login unless
d2a9f7cc 1737 * $autologinguest is set and {@link $CFG}->autologinguests is set to 1 in which
ec81373f 1738 * case they are automatically logged in as guests.
1739 * If $courseid is given and the user is not enrolled in that course then the
1740 * user is redirected to the course enrolment page.
1741 * If $cm is given and the coursemodule is hidden and the user is not a teacher
1742 * in the course then the user is redirected to the course home page.
7cf1c7bd 1743 *
7cf1c7bd 1744 * @uses $CFG
c6d15803 1745 * @uses $SESSION
7cf1c7bd 1746 * @uses $USER
1747 * @uses $FULLME
c6d15803 1748 * @uses SITEID
f07fa644 1749 * @uses $COURSE
33ebaf7c 1750 * @param mixed $courseorid id of the course or course object
bbd3f2c4 1751 * @param bool $autologinguest
1752 * @param object $cm course module object
7cf1c7bd 1753 */
33ebaf7c 1754function require_login($courseorid=0, $autologinguest=true, $cm=null) {
f9903ed0 1755
083c3743 1756 global $CFG, $SESSION, $USER, $COURSE, $FULLME;
d8ba183c 1757
083c3743 1758/// setup global $COURSE, themes, language and locale
dcf6d93c 1759 course_setup($courseorid);
be933850 1760
1845f8b8 1761/// If the user is not even logged in yet then make sure they are
083c3743 1762 if (!isloggedin()) {
1763 //NOTE: $USER->site check was obsoleted by session test cookie,
1764 // $USER->confirmed test is in login/index.php
f9903ed0 1765 $SESSION->wantsurl = $FULLME;
b0ccd3fb 1766 if (!empty($_SERVER['HTTP_REFERER'])) {
1767 $SESSION->fromurl = $_SERVER['HTTP_REFERER'];
9f44d972 1768 }
ad56b737 1769 if ($autologinguest and !empty($CFG->guestloginbutton) and !empty($CFG->autologinguests) and ($COURSE->id == SITEID or $COURSE->guest) ) {
8e8d0524 1770 $loginguest = '?loginguest=true';
1771 } else {
1772 $loginguest = '';
a2ebe6a5 1773 }
2c040c29 1774 if (empty($CFG->loginhttps) or $loginguest) { //do not require https for guest logins
b0ccd3fb 1775 redirect($CFG->wwwroot .'/login/index.php'. $loginguest);
8a33e371 1776 } else {
2c3432e6 1777 $wwwroot = str_replace('http:','https:', $CFG->wwwroot);
083c3743 1778 redirect($wwwroot .'/login/index.php');
8a33e371 1779 }
20fde7b1 1780 exit;
f9903ed0 1781 }
808a3baa 1782
f6f66b03 1783/// loginas as redirection if needed
1784 if ($COURSE->id != SITEID and !empty($USER->realuser)) {
1785 if ($USER->loginascontext->contextlevel == CONTEXT_COURSE) {
1786 if ($USER->loginascontext->instanceid != $COURSE->id) {
3887fe4a 1787 print_error('loginasonecourse', '', $CFG->wwwroot.'/course/view.php?id='.$USER->loginascontext->instanceid);
5e623a33 1788 }
f6f66b03 1789 }
1790 }
1791
1792
5602f7cf 1793/// check whether the user should be changing password (but only if it is REALLY them)
346c3e2f 1794 if (get_user_preferences('auth_forcepasswordchange') && empty($USER->realuser)) {
21e2dcd9 1795 $userauth = get_auth_plugin($USER->auth);
03d820c7 1796 if ($userauth->can_change_password()) {
20fde7b1 1797 $SESSION->wantsurl = $FULLME;
80274abf 1798 if ($changeurl = $userauth->change_password_url()) {
9696bd89 1799 //use plugin custom url
80274abf 1800 redirect($changeurl);
1437f0a5 1801 } else {
9696bd89 1802 //use moodle internal method
1803 if (empty($CFG->loginhttps)) {
1804 redirect($CFG->wwwroot .'/login/change_password.php');
1805 } else {
1806 $wwwroot = str_replace('http:','https:', $CFG->wwwroot);
1807 redirect($wwwroot .'/login/change_password.php');
1808 }
1437f0a5 1809 }
d35757eb 1810 } else {
4fa94a56 1811 error(get_string('nopasswordchangeforced', 'auth'));
d35757eb 1812 }
1813 }
083c3743 1814
1845f8b8 1815/// Check that the user account is properly set up
808a3baa 1816 if (user_not_fully_set_up($USER)) {
20fde7b1 1817 $SESSION->wantsurl = $FULLME;
b0ccd3fb 1818 redirect($CFG->wwwroot .'/user/edit.php?id='. $USER->id .'&amp;course='. SITEID);
808a3baa 1819 }
d8ba183c 1820
1845f8b8 1821/// Make sure current IP matches the one for this session (if required)
361855e6 1822 if (!empty($CFG->tracksessionip)) {
366dfa60 1823 if ($USER->sessionIP != md5(getremoteaddr())) {
1824 error(get_string('sessionipnomatch', 'error'));
1825 }
1826 }
6d8f47d6 1827
1845f8b8 1828/// Make sure the USER has a sesskey set up. Used for checking script parameters.
04280e85 1829 sesskey();
366dfa60 1830
027a1604 1831 // Check that the user has agreed to a site policy if there is one
1832 if (!empty($CFG->sitepolicy)) {
1833 if (!$USER->policyagreed) {
957b5198 1834 $SESSION->wantsurl = $FULLME;
027a1604 1835 redirect($CFG->wwwroot .'/user/policy.php');
027a1604 1836 }
1695b680 1837 }
1838
21e2dcd9 1839 // Fetch the system context, we are going to use it a lot.
1840 $sysctx = get_context_instance(CONTEXT_SYSTEM);
1841
1845f8b8 1842/// If the site is currently under maintenance, then print a message
21e2dcd9 1843 if (!has_capability('moodle/site:config', $sysctx)) {
eeefd0b0 1844 if (file_exists($CFG->dataroot.'/'.SITEID.'/maintenance.html')) {
1695b680 1845 print_maintenance_message();
20fde7b1 1846 exit;
1695b680 1847 }
027a1604 1848 }
1849
f8e3d5f0 1850/// groupmembersonly access control
1851 if (!empty($CFG->enablegroupings) and $cm and $cm->groupmembersonly and !has_capability('moodle/site:accessallgroups', get_context_instance(CONTEXT_MODULE, $cm->id))) {
1852 if (isguestuser() or !groups_has_membership($cm)) {
1853 error(get_string('groupmembersonlyerror', 'group'), $CFG->wwwroot.'/course/view.php?id='.$cm->course);
1854 }
1855 }
1845f8b8 1856
21e2dcd9 1857 // Fetch the course context, and prefetch its child contexts
1858 if (!isset($COURSE->context)) {
1859 if ( ! $COURSE->context = get_context_instance(CONTEXT_COURSE, $COURSE->id) ) {
1860 print_error('nocontext');
1861 }
1862 }
33ebaf7c 1863 if ($COURSE->id == SITEID) {
21e2dcd9 1864 /// Eliminate hidden site activities straight away
1865 if (!empty($cm) && !$cm->visible
1866 && !has_capability('moodle/course:viewhiddenactivities', $COURSE->context)) {
33ebaf7c 1867 redirect($CFG->wwwroot, get_string('activityiscurrentlyhidden'));
e3512050 1868 }
33ebaf7c 1869 return;
881a77bf 1870
5e623a33 1871 } else {
1845f8b8 1872
21e2dcd9 1873 /// Check if the user can be in a particular course
1874 if (empty($USER->access['rsw'][$COURSE->context->path])) {
1cf2e21b 1875 //
1876 // Spaghetti logic construct
1877 //
1878 // - able to view course?
1879 // - able to view category?
1880 // => if either is missing, course is hidden from this user
1881 //
1882 // It's carefully ordered so we run the cheap checks first, and the
1883 // more costly checks last...
1884 //
21e2dcd9 1885 if (! (($COURSE->visible || has_capability('moodle/course:viewhiddencourses', $COURSE->context))
1cf2e21b 1886 && (course_parent_visible($COURSE)) || has_capability('moodle/course:viewhiddencourses',
1887 get_context_instance(CONTEXT_COURSECAT,
1888 $COURSE->category)))) {
1889 print_header_simple();
1890 notice(get_string('coursehidden'), $CFG->wwwroot .'/');
1891 }
1892 }
1893
f71346e2 1894 /// Non-guests who don't currently have access, check if they can be allowed in as a guest
1895
21e2dcd9 1896 if ($USER->username != 'guest' and !has_capability('moodle/course:view', $COURSE->context)) {
33ebaf7c 1897 if ($COURSE->guest == 1) {
eef879ec 1898 // Temporarily assign them guest role for this context, if it fails later user is asked to enrol
21e2dcd9 1899 $USER->access = load_temp_role($COURSE->context, $CFG->guestroleid, $USER->access);
f71346e2 1900 }
1901 }
1902
1845f8b8 1903 /// If the user is a guest then treat them according to the course policy about guests
1904
21e2dcd9 1905 if (has_capability('moodle/legacy:guest', $COURSE->context, NULL, false)) {
33ebaf7c 1906 switch ($COURSE->guest) { /// Check course policy about guest access
1845f8b8 1907
21e2dcd9 1908 case 1: /// Guests always allowed
1909 if (!has_capability('moodle/course:view', $COURSE->context)) { // Prohibited by capability
1845f8b8 1910 print_header_simple();
6ba65fa0 1911 notice(get_string('guestsnotallowed', '', format_string($COURSE->fullname)), "$CFG->wwwroot/login/index.php");
1845f8b8 1912 }
1913 if (!empty($cm) and !$cm->visible) { // Not allowed to see module, send to course page
5e623a33 1914 redirect($CFG->wwwroot.'/course/view.php?id='.$cm->course,
1845f8b8 1915 get_string('activityiscurrentlyhidden'));
1916 }
1917
1918 return; // User is allowed to see this course
1919
1920 break;
1921
5e623a33 1922 case 2: /// Guests allowed with key
33ebaf7c 1923 if (!empty($USER->enrolkey[$COURSE->id])) { // Set by enrol/manual/enrol.php
b1f318a6 1924 return true;
1925 }
1926 // otherwise drop through to logic below (--> enrol.php)
1845f8b8 1927 break;
bbbf2d40 1928
1845f8b8 1929 default: /// Guests not allowed
0be6f678 1930 $strloggedinasguest = get_string('loggedinasguest');
1931 print_header_simple('', '',
1932 build_navigation(array(array('name' => $strloggedinasguest, 'link' => null, 'type' => 'misc'))));
21e2dcd9 1933 if (empty($USER->access['rsw'][$COURSE->context->path])) { // Normal guest
6ba65fa0 1934 notice(get_string('guestsnotallowed', '', format_string($COURSE->fullname)), "$CFG->wwwroot/login/index.php");
21596567 1935 } else {
6ba65fa0 1936 notify(get_string('guestsnotallowed', '', format_string($COURSE->fullname)));
33ebaf7c 1937 echo '<div class="notifyproblem">'.switchroles_form($COURSE->id).'</div>';
1938 print_footer($COURSE);
21596567 1939 exit;
1940 }
1845f8b8 1941 break;
1942 }
1943
1944 /// For non-guests, check if they have course view access
1945
21e2dcd9 1946 } else if (has_capability('moodle/course:view', $COURSE->context)) {
1845f8b8 1947 if (!empty($USER->realuser)) { // Make sure the REAL person can also access this course
21e2dcd9 1948 if (!has_capability('moodle/course:view', $COURSE->context, $USER->realuser)) {
1845f8b8 1949 print_header_simple();
b0ccd3fb 1950 notice(get_string('studentnotallowed', '', fullname($USER, true)), $CFG->wwwroot .'/');
cb909d74 1951 }
3ce2f1e0 1952 }
1845f8b8 1953
1954 /// Make sure they can read this activity too, if specified
1955
21e2dcd9 1956 if (!empty($cm) and !$cm->visible and !has_capability('moodle/course:viewhiddenactivities', $COURSE->context)) {
ec81373f 1957 redirect($CFG->wwwroot.'/course/view.php?id='.$cm->course, get_string('activityiscurrentlyhidden'));
1958 }
1845f8b8 1959 return; // User is allowed to see this course
1960
da5c172a 1961 }
f9903ed0 1962
9ca3b4f3 1963
1845f8b8 1964 /// Currently not enrolled in the course, so see if they want to enrol
da5c172a 1965 $SESSION->wantsurl = $FULLME;
33ebaf7c 1966 redirect($CFG->wwwroot .'/course/enrol.php?id='. $COURSE->id);
da5c172a 1967 die;
1968 }
f9903ed0 1969}
1970
c4d0753b 1971
1972
1973/**
1974 * This function just makes sure a user is logged out.
1975 *
1976 * @uses $CFG
1977 * @uses $USER
1978 */
1979function require_logout() {
1980
2d4beaff 1981 global $USER, $CFG, $SESSION;
c4d0753b 1982
111e2360 1983 if (isloggedin()) {
c4d0753b 1984 add_to_log(SITEID, "user", "logout", "view.php?id=$USER->id&course=".SITEID, $USER->id, 0, $USER->id);
1985
533f7910 1986 $authsequence = get_enabled_auth_plugins(); // auths, in sequence
1987 foreach($authsequence as $authname) {
1988 $authplugin = get_auth_plugin($authname);
1989 $authplugin->prelogout_hook();
81693ac7 1990 }
c4d0753b 1991 }
1992
1993 if (ini_get_bool("register_globals") and check_php_version("4.3.0")) {
1994 // This method is just to try to avoid silly warnings from PHP 4.3.0
1995 session_unregister("USER");
1996 session_unregister("SESSION");
1997 }
1998
f8bd7030 1999 // Initialize variable to pass-by-reference to headers_sent(&$file, &$line)
2000 $file = $line = null;
2001 if (headers_sent($file, $line)) {
2002 error_log('MoodleSessionTest cookie could not be set in moodlelib.php:'.__LINE__);
2003 error_log('Headers were already sent in file: '.$file.' on line '.$line);
2004 } else {
2005 setcookie('MoodleSessionTest'.$CFG->sessioncookie, '', time() - 3600, $CFG->sessioncookiepath);
2006 }
2007
c4d0753b 2008 unset($_SESSION['USER']);
2009 unset($_SESSION['SESSION']);
2010
2011 unset($SESSION);
2012 unset($USER);
2013
2014}
2015
7cf1c7bd 2016/**
2017 * This is a weaker version of {@link require_login()} which only requires login
2018 * when called from within a course rather than the site page, unless
2019 * the forcelogin option is turned on.
2020 *
2021 * @uses $CFG
33ebaf7c 2022 * @param mixed $courseorid The course object or id in question
bbd3f2c4 2023 * @param bool $autologinguest Allow autologin guests if that is wanted
4febb58f 2024 * @param object $cm Course activity module if known
7cf1c7bd 2025 */
33ebaf7c 2026function require_course_login($courseorid, $autologinguest=true, $cm=null) {
f950af3c 2027 global $CFG;
1596edff 2028 if (!empty($CFG->forcelogin)) {
33ebaf7c 2029 // login required for both SITE and courses
2030 require_login($courseorid, $autologinguest, $cm);
63c9ee99 2031
2032 } else if (!empty($cm) and !$cm->visible) {
2033 // always login for hidden activities
2034 require_login($courseorid, $autologinguest, $cm);
2035
39de90ac 2036 } else if ((is_object($courseorid) and $courseorid->id == SITEID)
2037 or (!is_object($courseorid) and $courseorid == SITEID)) {
33ebaf7c 2038 //login for SITE not required
63c9ee99 2039 return;
2040
33ebaf7c 2041 } else {
2042 // course login always required
2043 require_login($courseorid, $autologinguest, $cm);
f950af3c 2044 }
2045}
2046
61c6071f 2047/**
2048 * Require key login. Function terminates with error if key not found or incorrect.
2049 * @param string $script unique script identifier
2050 * @param int $instance optional instance id
2051 */
2052function require_user_key_login($script, $instance=null) {
e2fa911b 2053 global $nomoodlecookie, $USER, $SESSION, $CFG;
61c6071f 2054
2055 if (empty($nomoodlecookie)) {
2056 error('Incorrect use of require_key_login() - session cookies must be disabled!');
2057 }
2058
2059/// extra safety
2060 @session_write_close();
2061
2062 $keyvalue = required_param('key', PARAM_ALPHANUM);
2063
2064 if (!$key = get_record('user_private_key', 'script', $script, 'value', $keyvalue, 'instance', $instance)) {
2065 error('Incorrect key');
2066 }
2067
2068 if (!empty($key->validuntil) and $key->validuntil < time()) {
2069 error('Expired key');
2070 }
2071
e436033f 2072 if ($key->iprestriction) {
2073 $remoteaddr = getremoteaddr();
2074 if ($remoteaddr == '' or !address_in_subnet($remoteaddr, $key->iprestriction)) {
2075 error('Client IP address mismatch');
2076 }
61c6071f 2077 }
2078
2079 if (!$user = get_record('user', 'id', $key->userid)) {
2080 error('Incorrect user record');
2081 }
2082
2083/// emulate normal session
2084 $SESSION = new object();
2085 $USER = $user;
2086
e2fa911b 2087/// note we are not using normal login
2088 if (!defined('USER_KEY_LOGIN')) {
2089 define('USER_KEY_LOGIN', true);
2090 }
2091
2092 load_all_capabilities();
2093
61c6071f 2094/// return isntance id - it might be empty
2095 return $key->instance;
2096}
2097
2098/**
2099 * Creates a new private user access key.
2100 * @param string $script unique target identifier
2101 * @param int $userid
2102 * @param instance $int optional instance id
2103 * @param string $iprestriction optional ip restricted access
2104 * @param timestamp $validuntil key valid only until given data
2105 * @return string access key value
2106 */
2107function create_user_key($script, $userid, $instance=null, $iprestriction=null, $validuntil=null) {
2108 $key = new object();
2109 $key->script = $script;
2110 $key->userid = $userid;
2111 $key->instance = $instance;
2112 $key->iprestriction = $iprestriction;
2113 $key->validuntil = $validuntil;
2114 $key->timecreated = time();
2115
2116 $key->value = md5($userid.'_'.time().random_string(40)); // something long and unique
2117 while (record_exists('user_private_key', 'value', $key->value)) {
2118 // must be unique
2119 $key->value = md5($userid.'_'.time().random_string(40));
2120 }
2121
2122 if (!insert_record('user_private_key', $key)) {
2123 error('Can not insert new key');
2124 }
2125
2126 return $key->value;
2127}
2128
7cf1c7bd 2129/**
2130 * Modify the user table by setting the currently logged in user's
2131 * last login to now.
2132 *
2133 * @uses $USER
bbd3f2c4 2134 * @return bool
7cf1c7bd 2135 */
1d881d92 2136function update_user_login_times() {
2137 global $USER;
2138
53467aa6 2139 $user = new object();
1d881d92 2140 $USER->lastlogin = $user->lastlogin = $USER->currentlogin;
2a2f5f11 2141 $USER->currentlogin = $user->lastaccess = $user->currentlogin = time();
1d881d92 2142
2143 $user->id = $USER->id;
2144
b0ccd3fb 2145 return update_record('user', $user);
1d881d92 2146}
2147
7cf1c7bd 2148/**
2149 * Determines if a user has completed setting up their account.
2150 *
89dcb99d 2151 * @param user $user A {@link $USER} object to test for the existance of a valid name and email
bbd3f2c4 2152 * @return bool
7cf1c7bd 2153 */
808a3baa 2154function user_not_fully_set_up($user) {
bb64b51a 2155 return ($user->username != 'guest' and (empty($user->firstname) or empty($user->lastname) or empty($user->email) or over_bounce_threshold($user)));
2156}
2157
2158function over_bounce_threshold($user) {
d2a9f7cc 2159
bb64b51a 2160 global $CFG;
d2a9f7cc 2161
bb64b51a 2162 if (empty($CFG->handlebounces)) {
2163 return false;
2164 }
2165 // set sensible defaults
2166 if (empty($CFG->minbounces)) {
2167 $CFG->minbounces = 10;
2168 }
2169 if (empty($CFG->bounceratio)) {
2170 $CFG->bounceratio = .20;
2171 }
2172 $bouncecount = 0;
2173 $sendcount = 0;
2174 if ($bounce = get_record('user_preferences','userid',$user->id,'name','email_bounce_count')) {
2175 $bouncecount = $bounce->value;
2176 }
2177 if ($send = get_record('user_preferences','userid',$user->id,'name','email_send_count')) {
2178 $sendcount = $send->value;
2179 }
2180 return ($bouncecount >= $CFG->minbounces && $bouncecount/$sendcount >= $CFG->bounceratio);
2181}
2182
d2a9f7cc 2183/**
bb64b51a 2184 * @param $user - object containing an id
2185 * @param $reset - will reset the count to 0
2186 */
2187function set_send_count($user,$reset=false) {
d2a9f7cc 2188 if ($pref = get_record('user_preferences','userid',$user->id,'name','email_send_count')) {
bb64b51a 2189 $pref->value = (!empty($reset)) ? 0 : $pref->value+1;
2190 update_record('user_preferences',$pref);
2191 }
2192 else if (!empty($reset)) { // if it's not there and we're resetting, don't bother.
2193 // make a new one
2194 $pref->name = 'email_send_count';
2195 $pref->value = 1;
2196 $pref->userid = $user->id;
06ba0b04 2197 insert_record('user_preferences',$pref, false);
bb64b51a 2198 }
2199}
2200
d2a9f7cc 2201/**
bb64b51a 2202* @param $user - object containing an id
2203 * @param $reset - will reset the count to 0
2204 */
2205function set_bounce_count($user,$reset=false) {
d2a9f7cc 2206 if ($pref = get_record('user_preferences','userid',$user->id,'name','email_bounce_count')) {
bb64b51a 2207 $pref->value = (!empty($reset)) ? 0 : $pref->value+1;
2208 update_record('user_preferences',$pref);
2209 }
2210 else if (!empty($reset)) { // if it's not there and we're resetting, don't bother.
2211 // make a new one
2212 $pref->name = 'email_bounce_count';
2213 $pref->value = 1;
2214 $pref->userid = $user->id;
06ba0b04 2215 insert_record('user_preferences',$pref, false);
bb64b51a 2216 }
808a3baa 2217}
f9903ed0 2218
7cf1c7bd 2219/**
2220 * Keeps track of login attempts
2221 *
2222 * @uses $SESSION
2223 */
f9903ed0 2224function update_login_count() {
9fa49e22 2225
f9903ed0 2226 global $SESSION;
2227
2228 $max_logins = 10;
2229
2230 if (empty($SESSION->logincount)) {
2231 $SESSION->logincount = 1;
2232 } else {
2233 $SESSION->logincount++;
2234 }
2235
2236 if ($SESSION->logincount > $max_logins) {
9fa49e22 2237 unset($SESSION->wantsurl);
b0ccd3fb 2238 error(get_string('errortoomanylogins'));
d578afc8 2239 }
2240}
2241
7cf1c7bd 2242/**
2243 * Resets login attempts
2244 *
2245 * @uses $SESSION
2246 */
9fa49e22 2247function reset_login_count() {
9fa49e22 2248 global $SESSION;
d578afc8 2249
9fa49e22 2250 $SESSION->logincount = 0;
d578afc8 2251}
2252
b61efafb 2253function sync_metacourses() {
2254
2255 global $CFG;
2256
1aad4310 2257 if (!$courses = get_records('course', 'metacourse', 1)) {
b61efafb 2258 return;
2259 }
d2a9f7cc 2260
b61efafb 2261 foreach ($courses as $course) {
1aad4310 2262 sync_metacourse($course);
b61efafb 2263 }
2264}
2265
b61efafb 2266/**
2267 * Goes through all enrolment records for the courses inside the metacourse and sync with them.
5e623a33 2268 *
123545bc 2269 * @param mixed $course the metacourse to synch. Either the course object itself, or the courseid.
d2a9f7cc 2270 */
1aad4310 2271function sync_metacourse($course) {
755c8d58 2272 global $CFG;
b61efafb 2273
123545bc 2274 // Check the course is valid.
1aad4310 2275 if (!is_object($course)) {
2276 if (!$course = get_record('course', 'id', $course)) {
2277 return false; // invalid course id
b61efafb 2278 }
b61efafb 2279 }
5e623a33 2280
123545bc 2281 // Check that we actually have a metacourse.
1aad4310 2282 if (empty($course->metacourse)) {
123545bc 2283 return false;
755c8d58 2284 }
87671466 2285
b3170072 2286 // Get a list of roles that should not be synced.
4db9bff7 2287 if (!empty($CFG->nonmetacoursesyncroleids)) {
b3170072 2288 $roleexclusions = 'ra.roleid NOT IN (' . $CFG->nonmetacoursesyncroleids . ') AND';
5e623a33 2289 } else {
b3170072 2290 $roleexclusions = '';
2291 }
2292
123545bc 2293 // Get the context of the metacourse.
1aad4310 2294 $context = get_context_instance(CONTEXT_COURSE, $course->id); // SITEID can not be a metacourse
e1ecf0a0 2295
123545bc 2296 // We do not ever want to unassign the list of metacourse manager, so get a list of them.
b79da3ac 2297 if ($users = get_users_by_capability($context, 'moodle/course:managemetacourse')) {
1aad4310 2298 $managers = array_keys($users);
2299 } else {
2300 $managers = array();
b61efafb 2301 }
2302
123545bc 2303 // Get assignments of a user to a role that exist in a child course, but
2304 // not in the meta coure. That is, get a list of the assignments that need to be made.
2305 if (!$assignments = get_records_sql("
2306 SELECT
2307 ra.id, ra.roleid, ra.userid
2308 FROM
2309 {$CFG->prefix}role_assignments ra,
2310 {$CFG->prefix}context con,
2311 {$CFG->prefix}course_meta cm
2312 WHERE
2313 ra.contextid = con.id AND
2314 con.contextlevel = " . CONTEXT_COURSE . " AND
2315 con.instanceid = cm.child_course AND
2316 cm.parent_course = {$course->id} AND
b3170072 2317 $roleexclusions
123545bc 2318 NOT EXISTS (
2319 SELECT 1 FROM
2320 {$CFG->prefix}role_assignments ra2
2321 WHERE
2322 ra2.userid = ra.userid AND
2323 ra2.roleid = ra.roleid AND
2324 ra2.contextid = {$context->id}
2325 )
2326 ")) {
2327 $assignments = array();
2328 }
2329
2330 // Get assignments of a user to a role that exist in the meta course, but
2331 // not in any child courses. That is, get a list of the unassignments that need to be made.
2332 if (!$unassignments = get_records_sql("
2333 SELECT
2334 ra.id, ra.roleid, ra.userid
2335 FROM
2336 {$CFG->prefix}role_assignments ra
2337 WHERE
2338 ra.contextid = {$context->id} AND
b3170072 2339 $roleexclusions
123545bc 2340 NOT EXISTS (
2341 SELECT 1 FROM
2342 {$CFG->prefix}role_assignments ra2,
2343 {$CFG->prefix}context con2,
2344 {$CFG->prefix}course_meta cm
2345 WHERE
2346 ra2.userid = ra.userid AND
2347 ra2.roleid = ra.roleid AND
2348 ra2.contextid = con2.id AND
2349 con2.contextlevel = " . CONTEXT_COURSE . " AND
2350 con2.instanceid = cm.child_course AND
2351 cm.parent_course = {$course->id}
2352 )
2353 ")) {
2354 $unassignments = array();
2355 }
2356
2357 $success = true;
2358
2359 // Make the unassignments, if they are not managers.
2360 foreach ($unassignments as $unassignment) {
2361 if (!in_array($unassignment->userid, $managers)) {
2362 $success = role_unassign($unassignment->roleid, $unassignment->userid, 0, $context->id) && $success;
1aad4310 2363 }
755c8d58 2364 }
e1ecf0a0 2365
123545bc 2366 // Make the assignments.
2367 foreach ($assignments as $assignment) {
2368 $success = role_assign($assignment->roleid, $assignment->userid, 0, $context->id) && $success;
b61efafb 2369 }
755c8d58 2370
123545bc 2371 return $success;
5e623a33 2372
1aad4310 2373// TODO: finish timeend and timestart
2374// maybe we could rely on cron job to do the cleaning from time to time
b61efafb 2375}
2376
d2a9f7cc 2377/**
b61efafb 2378 * Adds a record to the metacourse table and calls sync_metacoures
2379 */
2380function add_to_metacourse ($metacourseid, $courseid) {
d2a9f7cc 2381
b61efafb 2382 if (!$metacourse = get_record("course","id",$metacourseid)) {
2383 return false;
2384 }
d2a9f7cc 2385
b61efafb 2386 if (!$course = get_record("course","id",$courseid)) {
2387 return false;
2388 }
2389
5f37b628 2390 if (!$record = get_record("course_meta","parent_course",$metacourseid,"child_course",$courseid)) {
53467aa6 2391 $rec = new object();
b61efafb 2392 $rec->parent_course = $metacourseid;
2393 $rec->child_course = $courseid;
5f37b628 2394 if (!insert_record('course_meta',$rec)) {
b61efafb 2395 return false;
2396 }
2397 return sync_metacourse($metacourseid);
2398 }
2399 return true;
d2a9f7cc 2400
b61efafb 2401}
2402
d2a9f7cc 2403/**
b61efafb 2404 * Removes the record from the metacourse table and calls sync_metacourse
2405 */
2406function remove_from_metacourse($metacourseid, $courseid) {
2407
5f37b628 2408 if (delete_records('course_meta','parent_course',$metacourseid,'child_course',$courseid)) {
b61efafb 2409 return sync_metacourse($metacourseid);
2410 }
2411 return false;
2412}
2413
2414
7c12949d 2415/**
2416 * Determines if a user is currently logged in
2417 *
2418 * @uses $USER
bbd3f2c4 2419 * @return bool
7c12949d 2420 */
2421function isloggedin() {
2422 global $USER;
2423
2424 return (!empty($USER->id));
2425}
2426
2a919fd7 2427/**
2428 * Determines if a user is logged in as real guest user with username 'guest'.
2429 * This function is similar to original isguest() in 1.6 and earlier.
2430 * Current isguest() is deprecated - do not use it anymore.
2431 *
2432 * @param $user mixed user object or id, $USER if not specified
2433 * @return bool true if user is the real guest user, false if not logged in or other user
2434 */
2435function isguestuser($user=NULL) {
2436 global $USER;
2437 if ($user === NULL) {
2438 $user = $USER;
2439 } else if (is_numeric($user)) {
2440 $user = get_record('user', 'id', $user, '', '', '', '', 'id, username');
2441 }
2442
2443 if (empty($user->id)) {
2444 return false; // not logged in, can not be guest
2445 }
2446
2447 return ($user->username == 'guest');
2448}
7c12949d 2449
7cf1c7bd 2450/**
e6260a45 2451 * Determines if the currently logged in user is in editing mode.
2452 * Note: originally this function had $userid parameter - it was not usable anyway
7cf1c7bd 2453 *
0df35335 2454 * @uses $USER, $PAGE
bbd3f2c4 2455 * @return bool
7cf1c7bd 2456 */
0df35335 2457function isediting() {
2458 global $USER, $PAGE;
e6260a45 2459
2460 if (empty($USER->editing)) {
9c9f7d77 2461 return false;
0df35335 2462 } elseif (is_object($PAGE) && method_exists($PAGE,'user_allowed_editing')) {
2463 return $PAGE->user_allowed_editing();
9c9f7d77 2464 }
0df35335 2465 return true;//false;
2c309dc2 2466}
2467
7cf1c7bd 2468/**
2469 * Determines if the logged in user is currently moving an activity
2470 *
2471 * @uses $USER
c6d15803 2472 * @param int $courseid The id of the course being tested
bbd3f2c4 2473 * @return bool
7cf1c7bd 2474 */
7977cffd 2475function ismoving($courseid) {
7977cffd 2476 global $USER;
2477
2478 if (!empty($USER->activitycopy)) {
2479 return ($USER->activitycopycourse == $courseid);
2480 }
2481 return false;
2482}
2483
7cf1c7bd 2484/**
2485 * Given an object containing firstname and lastname
2486 * values, this function returns a string with the
2487 * full name of the person.
2488 * The result may depend on system settings
2489 * or language. 'override' will force both names
361855e6 2490 * to be used even if system settings specify one.
68fbd8e1 2491 *
7cf1c7bd 2492 * @uses $CFG
2493 * @uses $SESSION
68fbd8e1 2494 * @param object $user A {@link $USER} object to get full name of
2495 * @param bool $override If true then the name will be first name followed by last name rather than adhering to fullnamedisplay setting.
7cf1c7bd 2496 */
e2cd5065 2497function fullname($user, $override=false) {
b5cbb64d 2498
f374fb10 2499 global $CFG, $SESSION;
2500
6527c077 2501 if (!isset($user->firstname) and !isset($user->lastname)) {
2502 return '';
2503 }
2504
4c202228 2505 if (!$override) {
2506 if (!empty($CFG->forcefirstname)) {
2507 $user->firstname = $CFG->forcefirstname;
2508 }
2509 if (!empty($CFG->forcelastname)) {
2510 $user->lastname = $CFG->forcelastname;
2511 }
2512 }
2513
f374fb10 2514 if (!empty($SESSION->fullnamedisplay)) {
2515 $CFG->fullnamedisplay = $SESSION->fullnamedisplay;
2516 }
e2cd5065 2517
b5cbb64d 2518 if ($CFG->fullnamedisplay == 'firstname lastname') {
b0ccd3fb 2519 return $user->firstname .' '. $user->lastname;
b5cbb64d 2520
2521 } else if ($CFG->fullnamedisplay == 'lastname firstname') {
b0ccd3fb 2522 return $user->lastname .' '. $user->firstname;
e2cd5065 2523
b5cbb64d 2524 } else if ($CFG->fullnamedisplay == 'firstname') {
2525 if ($override) {
2526 return get_string('fullnamedisplay', '', $user);
2527 } else {
2528 return $user->firstname;
2529 }
2530 }
e2cd5065 2531
b5cbb64d 2532 return get_string('fullnamedisplay', '', $user);
e2cd5065 2533}
2534
7cf1c7bd 2535/**
2536 * Sets a moodle cookie with an encrypted string
2537 *
2538 * @uses $CFG
2f87145b 2539 * @uses DAYSECS
2540 * @uses HOURSECS
7cf1c7bd 2541 * @param string $thing The string to encrypt and place in a cookie
2542 */
f9903ed0 2543function set_moodle_cookie($thing) {
7185e073 2544 global $CFG;
482b6e6e 2545
7cbe6afe 2546 if ($thing == 'guest') { // Ignore guest account
2547 return;
2548 }
2549
482b6e6e 2550 $cookiename = 'MOODLEID_'.$CFG->sessioncookie;
f9903ed0 2551
2552 $days = 60;
7a5672c9 2553 $seconds = DAYSECS*$days;
f9903ed0 2554
1504e261 2555 setCookie($cookiename, '', time() - HOURSECS, $CFG->sessioncookiepath);
2556 setCookie($cookiename, rc4encrypt($thing), time()+$seconds, $CFG->sessioncookiepath);
f9903ed0 2557}
2558
7cf1c7bd 2559/**
2560 * Gets a moodle cookie with an encrypted string
2561 *
2562 * @uses $CFG
2563 * @return string
2564 */
f9903ed0 2565function get_moodle_cookie() {
7185e073 2566 global $CFG;
2567
482b6e6e 2568 $cookiename = 'MOODLEID_'.$CFG->sessioncookie;
7185e073 2569
1079c8a8 2570 if (empty($_COOKIE[$cookiename])) {
b0ccd3fb 2571 return '';
1079c8a8 2572 } else {
7cbe6afe 2573 $thing = rc4decrypt($_COOKIE[$cookiename]);
2574 return ($thing == 'guest') ? '': $thing; // Ignore guest account
1079c8a8 2575 }
f9903ed0 2576}
2577
7cf1c7bd 2578/**
03d820c7 2579 * Returns whether a given authentication plugin exists.
7cf1c7bd 2580 *
2581 * @uses $CFG
03d820c7 2582 * @param string $auth Form of authentication to check for. Defaults to the
2583 * global setting in {@link $CFG}.
2584 * @return boolean Whether the plugin is available.
7cf1c7bd 2585 */
16793340 2586function exists_auth_plugin($auth) {
03d820c7 2587 global $CFG;
5e623a33 2588
03d820c7 2589 if (file_exists("{$CFG->dirroot}/auth/$auth/auth.php")) {
2590 return is_readable("{$CFG->dirroot}/auth/$auth/auth.php");
2591 }
2592 return false;
2593}
ba7166c3 2594
03d820c7 2595/**
2596 * Checks if a given plugin is in the list of enabled authentication plugins.
5e623a33 2597 *
03d820c7 2598 * @param string $auth Authentication plugin.
2599 * @return boolean Whether the plugin is enabled.
2600 */
16793340 2601function is_enabled_auth($auth) {
16793340 2602 if (empty($auth)) {
2603 return false;
03d820c7 2604 }
16793340 2605
c7b10b5f 2606 $enabled = get_enabled_auth_plugins();
2607
2608 return in_array($auth, $enabled);
03d820c7 2609}
2610
2611/**
2612 * Returns an authentication plugin instance.
2613 *
2614 * @uses $CFG
9696bd89 2615 * @param string $auth name of authentication plugin
03d820c7 2616 * @return object An instance of the required authentication plugin.
2617 */
9696bd89 2618function get_auth_plugin($auth) {
03d820c7 2619 global $CFG;
5e623a33 2620
03d820c7 2621 // check the plugin exists first
2622 if (! exists_auth_plugin($auth)) {
2623 error("Authentication plugin '$auth' not found.");
2624 }
5e623a33 2625
03d820c7 2626 // return auth plugin instance
2627 require_once "{$CFG->dirroot}/auth/$auth/auth.php";
2628 $class = "auth_plugin_$auth";
2629 return new $class;
2630}
2631
c7b10b5f 2632/**
2633 * Returns array of active auth plugins.
2634 *
2635 * @param bool $fix fix $CFG->auth if needed
2636 * @return array
2637 */
2638function get_enabled_auth_plugins($fix=false) {
2639 global $CFG;
2640
2641 $default = array('manual', 'nologin');
2642
2643 if (empty($CFG->auth)) {
2644 $auths = array();
2645 } else {
2646 $auths = explode(',', $CFG->auth);
2647 }
2648
2649 if ($fix) {
2650 $auths = array_unique($auths);
2651 foreach($auths as $k=>$authname) {
2652 if (!exists_auth_plugin($authname) or in_array($authname, $default)) {
2653 unset($auths[$k]);
2654 }
2655 }
2656 $newconfig = implode(',', $auths);
2657 if (!isset($CFG->auth) or $newconfig != $CFG->auth) {
2658 set_config('auth', $newconfig);
2659 }
2660 }
2661
2662 return (array_merge($default, $auths));
2663}
2664
03d820c7 2665/**
2666 * Returns true if an internal authentication method is being used.
2667 * if method not specified then, global default is assumed
2668 *
2669 * @uses $CFG
2670 * @param string $auth Form of authentication required
2671 * @return bool
03d820c7 2672 */
16793340 2673function is_internal_auth($auth) {
03d820c7 2674 $authplugin = get_auth_plugin($auth); // throws error if bad $auth
2675 return $authplugin->is_internal();
a3f1f815 2676}
2677
8c3dba73 2678/**
2679 * Returns an array of user fields
2680 *
c6d15803 2681 * @uses $CFG
2682 * @uses $db
2683 * @return array User field/column names
8c3dba73 2684 */
a3f1f815 2685function get_user_fieldnames() {
a3f1f815 2686
2687 global $CFG, $db;
2688
2689 $fieldarray = $db->MetaColumnNames($CFG->prefix.'user');
2690 unset($fieldarray['ID']);
2691
2692 return $fieldarray;
ba7166c3 2693}
f9903ed0 2694
08103c93
ML
2695/**
2696 * Creates the default "guest" user. Used both from
2697 * admin/index.php and login/index.php
2698 * @return mixed user object created or boolean false if the creation has failed
2699 */
2700function create_guest_record() {
2701
2702 global $CFG;
2703
c824d478 2704 $guest = new stdClass();
08103c93
ML
2705 $guest->auth = 'manual';
2706 $guest->username = 'guest';
2707 $guest->password = hash_internal_user_password('guest');
2708 $guest->firstname = addslashes(get_string('guestuser'));
2709 $guest->lastname = ' ';
2710 $guest->email = 'root@localhost';
2711 $guest->description = addslashes(get_string('guestuserinfo'));
2712 $guest->mnethostid = $CFG->mnet_localhost_id;
2713 $guest->confirmed = 1;
2714 $guest->lang = $CFG->lang;
2715 $guest->timemodified= time();
2716
2717 if (! $guest->id = insert_record("user", $guest)) {
2718 return false;
2719 }
2720
2721 return $guest;
2722}
2723
7cf1c7bd 2724/**
2725 * Creates a bare-bones user record
2726 *
2727 * @uses $CFG
7cf1c7bd 2728 * @param string $username New user's username to add to record
2729 * @param string $password New user's password to add to record
2730 * @param string $auth Form of authentication required
68fbd8e1 2731 * @return object A {@link $USER} object
7cf1c7bd 2732 * @todo Outline auth types and provide code example
2733 */
f76cfc7a 2734function create_user_record($username, $password, $auth='manual') {
366dfa60 2735 global $CFG;
71f9abf9 2736
1e22bc9c 2737 //just in case check text case
2738 $username = trim(moodle_strtolower($username));
71f9abf9 2739
03d820c7 2740 $authplugin = get_auth_plugin($auth);
2741
6bc1e5d5 2742 if ($newinfo = $authplugin->get_userinfo($username)) {
2743 $newinfo = truncate_userinfo($newinfo);
2744 foreach ($newinfo as $key => $value){
2745 $newuser->$key = addslashes($value);
e858f9da 2746 }
2747 }
f9903ed0 2748
85a1d4c9 2749 if (!empty($newuser->email)) {
2750 if (email_is_not_allowed($newuser->email)) {
2751 unset($newuser->email);
2752 }
2753 }
2754
f76cfc7a 2755 $newuser->auth = $auth;
faebaf0f 2756 $newuser->username = $username;
5e623a33 2757
e51917eb 2758 // fix for MDL-8480
2759 // user CFG lang for user if $newuser->lang is empty
2760 // or $user->lang is not an installed language
2761 $sitelangs = array_keys(get_list_of_languages());
2762 if (empty($newuser->lang) || !in_array($newuser->lang, $sitelangs)) {
2763 $newuser -> lang = $CFG->lang;
5e623a33 2764 }
faebaf0f 2765 $newuser->confirmed = 1;
d96466d2 2766 $newuser->lastip = getremoteaddr();
faebaf0f 2767 $newuser->timemodified = time();
03d820c7 2768 $newuser->mnethostid = $CFG->mnet_localhost_id;
f9903ed0 2769
b0ccd3fb 2770 if (insert_record('user', $newuser)) {
16793340 2771 $user = get_complete_user_data('username', $newuser->username);
da5bcc9f 2772 if(!empty($CFG->{'auth_'.$newuser->auth.'_forcechangepassword'})){
16793340 2773 set_user_preference('auth_forcepasswordchange', 1, $user->id);
2774 }
2775 update_internal_user_password($user, $password);
2776 return $user;
faebaf0f 2777 }
2778 return false;
2779}
2780
7cf1c7bd 2781/**
2782 * Will update a local user record from an external source
2783 *
2784 * @uses $CFG
2785 * @param string $username New user's username to add to record
89dcb99d 2786 * @return user A {@link $USER} object
7cf1c7bd 2787 */
03d820c7 2788function update_user_record($username, $authplugin) {
6bc1e5d5 2789 $username = trim(moodle_strtolower($username)); /// just in case check text case
2790
2791 $oldinfo = get_record('user', 'username', $username, '','','','', 'username, auth');
2792 $userauth = get_auth_plugin($oldinfo->auth);
2793
2794 if ($newinfo = $userauth->get_userinfo($username)) {
2795 $newinfo = truncate_userinfo($newinfo);
2796 foreach ($newinfo as $key => $value){
2797 $confkey = 'field_updatelocal_' . $key;
2798 if (!empty($userauth->config->$confkey) and $userauth->config->$confkey === 'onlogin') {
2799 $value = addslashes(stripslashes($value)); // Just in case
2800 set_field('user', $key, $value, 'username', $username)
2801 or error_log("Error updating $key for $username");
d35757eb 2802 }
2803 }
2804 }
6bc1e5d5 2805
7c12949d 2806 return get_complete_user_data('username', $username);
d35757eb 2807}
0609562b 2808
b36a8fc4 2809function truncate_userinfo($info) {
2810/// will truncate userinfo as it comes from auth_get_userinfo (from external auth)
2811/// which may have large fields
2812
2813 // define the limits
2814 $limit = array(
2815 'username' => 100,
1c66bf59 2816 'idnumber' => 64,
8bcd295c 2817 'firstname' => 100,
2818 'lastname' => 100,
b36a8fc4 2819 'email' => 100,
2820 'icq' => 15,
2821 'phone1' => 20,
2822 'phone2' => 20,
2823 'institution' => 40,
2824 'department' => 30,
2825 'address' => 70,
2826 'city' => 20,
2827 'country' => 2,
2828 'url' => 255,
2829 );
361855e6 2830
b36a8fc4 2831 // apply where needed
2832 foreach (array_keys($info) as $key) {
2833 if (!empty($limit[$key])) {
adfc03f9 2834 $info[$key] = trim(substr($info[$key],0, $limit[$key]));
361855e6 2835 }
b36a8fc4 2836 }
361855e6 2837
b36a8fc4 2838 return $info;
90afcf32 2839}
2840
2841/**
2842 * Marks user deleted in internal user database and notifies the auth plugin.
2843 * Also unenrols user from all roles and does other cleanup.
2844 * @param object $user Userobject before delete (without system magic quotes)
2845 * @return boolean success
2846 */
2847function delete_user($user) {
2848 global $CFG;
2849 require_once($CFG->libdir.'/grouplib.php');
ece966f0 2850 require_once($CFG->libdir.'/gradelib.php');
90afcf32 2851
2852 begin_sql();
2853
2854 // delete all grades - backup is kept in grade_grades_history table
2855 if ($grades = grade_grade::fetch_all(array('userid'=>$user->id))) {
2856 foreach ($grades as $grade) {
2857 $grade->delete('userdelete');
2858 }
2859 }
2860
2861 // remove from all groups
2862 delete_records('groups_members', 'userid', $user->id);
2863
2864 // unenrol from all roles in all contexts
2865 role_unassign(0, $user->id); // this might be slow but it is really needed - modules might do some extra cleanup!
2866
2867 // now do a final accesslib cleanup - removes all role assingments in user context and context itself
2868 delete_context(CONTEXT_USER, $user->id);
2869
6d11d0ee 2870 // workaround for bulk deletes of users with the same email address
2871 $delname = addslashes("$user->email.".time());
2872 while (record_exists('user', 'username', $delname)) { // no need to use mnethostid here
2873 $delname++;
2874 }
2875
90afcf32 2876 // mark internal user record as "deleted"
2877 $updateuser = new object();
2878 $updateuser->id = $user->id;
2879 $updateuser->deleted = 1;
6d11d0ee 2880 $updateuser->username = $delname; // Remember it just in case
90afcf32 2881 $updateuser->email = ''; // Clear this field to free it up
2882 $updateuser->idnumber = ''; // Clear this field to free it up
2883 $updateuser->timemodified = time();
2884
2885 if (update_record('user', $updateuser)) {
2886 commit_sql();
2887 // notify auth plugin - do not block the delete even when plugin fails
2888 $authplugin = get_auth_plugin($user->auth);
2889 $authplugin->user_delete($user);
2890 return true;
2891
2892 } else {
2893 rollback_sql();
2894 return false;
2895 }
b36a8fc4 2896}
2897
7cf1c7bd 2898/**
2899 * Retrieve the guest user object
2900 *
2901 * @uses $CFG
89dcb99d 2902 * @return user A {@link $USER} object
7cf1c7bd 2903 */
0609562b 2904function guest_user() {
2905 global $CFG;
2906
b59c7ec0 2907 if ($newuser = get_record('user', 'username', 'guest', 'mnethostid', $CFG->mnet_localhost_id)) {
0609562b 2908 $newuser->confirmed = 1;
0609562b 2909 $newuser->lang = $CFG->lang;
d96466d2 2910 $newuser->lastip = getremoteaddr();
0609562b 2911 }
2912
2913 return $newuser;
2914}
2915
7cf1c7bd 2916/**
2917 * Given a username and password, this function looks them
2918 * up using the currently selected authentication mechanism,
2919 * and if the authentication is successful, it returns a
2920 * valid $user object from the 'user' table.
361855e6 2921 *
7cf1c7bd 2922 * Uses auth_ functions from the currently active auth module
2923 *
2924 * @uses $CFG
f5fd4347 2925 * @param string $username User's username (with system magic quotes)
2926 * @param string $password User's password (with system magic quotes)
89dcb99d 2927 * @return user|flase A {@link $USER} object or false if error
7cf1c7bd 2928 */
faebaf0f 2929function authenticate_user_login($username, $password) {
faebaf0f 2930
2931 global $CFG;
2932
c7b10b5f 2933 $authsenabled = get_enabled_auth_plugins();
39a5a35d 2934
16793340 2935 if ($user = get_complete_user_data('username', $username)) {
2936 $auth = empty($user->auth) ? 'manual' : $user->auth; // use manual if auth not set
2937 if ($auth=='nologin' or !is_enabled_auth($auth)) {
2938 add_to_log(0, 'login', 'error', 'index.php', $username);
2939 error_log('[client '.$_SERVER['REMOTE_ADDR']."] $CFG->wwwroot Disabled Login: $username ".$_SERVER['HTTP_USER_AGENT']);
2940 return false;
27286aeb 2941 }
16793340 2942 if (!empty($user->deleted)) {
2943 add_to_log(0, 'login', 'error', 'index.php', $username);
2944 error_log('[client '.$_SERVER['REMOTE_ADDR']."] $CFG->wwwroot Deleted Login: $username ".$_SERVER['HTTP_USER_AGENT']);
2945 return false;
d35757eb 2946 }
16793340 2947 $auths = array($auth);
2948
71f9abf9 2949 } else {
16793340 2950 $auths = $authsenabled;
2951 $user = new object();
2952 $user->id = 0; // User does not exist
27286aeb 2953 }
8f0cd6ef 2954
03d820c7 2955 foreach ($auths as $auth) {
2956 $authplugin = get_auth_plugin($auth);
466558e3 2957
16793340 2958 // on auth fail fall through to the next plugin
03d820c7 2959 if (!$authplugin->user_login($username, $password)) {
03d820c7 2960 continue;
2961 }
faebaf0f 2962
03d820c7 2963 // successful authentication
d613daf0 2964 if ($user->id) { // User already exists in database
71f9abf9 2965 if (empty($user->auth)) { // For some reason auth isn't set yet
2966 set_field('user', 'auth', $auth, 'username', $username);
16793340 2967 $user->auth = $auth;
71f9abf9 2968 }
16793340 2969
2970 update_internal_user_password($user, $password); // just in case salt or encoding were changed (magic quotes too one day)
2971
03d820c7 2972 if (!$authplugin->is_internal()) { // update user record from external DB
2973 $user = update_user_record($username, get_auth_plugin($user->auth));
d35757eb 2974 }
faebaf0f 2975 } else {
16793340 2976 // if user not found, create him
71f9abf9 2977 $user = create_user_record($username, $password, $auth);
faebaf0f 2978 }
01af6da6 2979
6bc1e5d5 2980 $authplugin->sync_roles($user);
2981
f5fd4347 2982 foreach ($authsenabled as $hau) {
2983 $hauth = get_auth_plugin($hau);
2984 $hauth->user_authenticated_hook($user, $username, $password);
2985 }
2986
2987 /// Log in to a second system if necessary
2988 /// NOTICE: /sso/ will be moved to auth and deprecated soon; use user_authenticated_hook() instead
2989 if (!empty($CFG->sso)) {
2990 include_once($CFG->dirroot .'/sso/'. $CFG->sso .'/lib.php');
2991 if (function_exists('sso_user_login')) {
2992 if (!sso_user_login($username, $password)) { // Perform the signon process
2993 notify('Second sign-on failed');
2994 }
2995 }
2996 }
01af6da6 2997
e582b65e 2998 return $user;
9d3c795c 2999
5e623a33 3000 }
3001
03d820c7 3002 // failed if all the plugins have failed
3003 add_to_log(0, 'login', 'error', 'index.php', $username);
3004 error_log('[client '.$_SERVER['REMOTE_ADDR']."] $CFG->wwwroot Failed Login: $username ".$_SERVER['HTTP_USER_AGENT']);
3005 return false;
f9903ed0 3006}
3007
df193157 3008/**
4908ad3e 3009 * Compare password against hash stored in internal user table.
df193157 3010 * If necessary it also updates the stored hash to new format.
5e623a33 3011 *
df193157 3012 * @param object user
3013 * @param string plain text password
3014 * @return bool is password valid?
3015 */
3016function validate_internal_user_password(&$user, $password) {
3017 global $CFG;
3018
4908ad3e 3019 if (!isset($CFG->passwordsaltmain)) {
3020 $CFG->passwordsaltmain = '';
3021 }
3022
df193157 3023 $validated = false;
3024
a044c05d 3025 // get password original encoding in case it was not updated to unicode yet
fb773106 3026 $textlib = textlib_get_instance();
810944af 3027 $convpassword = $textlib->convert($password, 'utf-8', get_string('oldcharset'));
df193157 3028
4908ad3e 3029 if ($user->password == md5($password.$CFG->passwordsaltmain) or $user->password == md5($password)
3030 or $user->password == md5($convpassword.$CFG->passwordsaltmain) or $user->password == md5($convpassword)) {
df193157 3031 $validated = true;
4908ad3e 3032 } else {
aaeaa4b0 3033 for ($i=1; $i<=20; $i++) { //20 alternative salts should be enough, right?
4908ad3e 3034 $alt = 'passwordsaltalt'.$i;
3035 if (!empty($CFG->$alt)) {
3036 if ($user->password == md5($password.$CFG->$alt) or $user->password == md5($convpassword.$CFG->$alt)) {
3037 $validated = true;
3038 break;
3039 }
3040 }
3041 }
df193157 3042 }
3043
3044 if ($validated) {
4908ad3e 3045 // force update of password hash using latest main password salt and encoding if needed
df193157 3046 update_internal_user_password($user, $password);
3047 }
3048
3049 return $validated;
3050}
3051
3052/**
3053 * Calculate hashed value from password using current hash mechanism.
5e623a33 3054 *
df193157 3055 * @param string password
3056 * @return string password hash
3057 */
3058function hash_internal_user_password($password) {
4908ad3e 3059 global $CFG;
3060
3061 if (isset($CFG->passwordsaltmain)) {
3062 return md5($password.$CFG->passwordsaltmain);
3063 } else {
3064 return md5($password);
3065 }
df193157 3066}
3067
3068/**
3069 * Update pssword hash in user object.
5e623a33 3070 *
df193157 3071 * @param object user
3072 * @param string plain text password
3073 * @param bool store changes also in db, default true
3074 * @return true if hash changed
3075 */
16793340 3076function update_internal_user_password(&$user, $password) {
df193157 3077 global $CFG;
3078
03d820c7 3079 $authplugin = get_auth_plugin($user->auth);
16793340 3080 if (!empty($authplugin->config->preventpassindb)) {
df193157 3081 $hashedpassword = 'not cached';
3082 } else {
3083 $hashedpassword = hash_internal_user_password($password);
3084 }
3085
b7b50143 3086 return set_field('user', 'password', $hashedpassword, 'id', $user->id);
df193157 3087}
3088
7c12949d 3089/**
3090 * Get a complete user record, which includes all the info
5c98bf9e 3091 * in the user record
7c12949d 3092 * Intended for setting as $USER session variable
3093 *
3094 * @uses $CFG
3095 * @uses SITEID
e1ecf0a0 3096 * @param string $field The user field to be checked for a given value.
7c12949d 3097 * @param string $value The value to match for $field.
3098 * @return user A {@link $USER} object.
3099 */
b7b50143 3100function get_complete_user_data($field, $value, $mnethostid=null) {
7c12949d 3101
3102 global $CFG;
3103
3104 if (!$field || !$value) {
3105 return false;
3106 }
3107
b7b50143 3108/// Build the WHERE clause for an SQL query
3109
3110 $constraints = $field .' = \''. $value .'\' AND deleted <> \'1\'';
3111
e5edab1b 3112 if (is_null($mnethostid)) {
3113 // if null, we restrict to local users
3114 // ** testing for local user can be done with
5e623a33 3115 // mnethostid = $CFG->mnet_localhost_id
e5edab1b 3116 // or with
5e623a33 3117 // auth != 'mnet'
e5edab1b 3118 // but the first one is FAST with our indexes
3119 $mnethostid = $CFG->mnet_localhost_id;
3120 }
3121 $mnethostid = (int)$mnethostid;
3122 $constraints .= ' AND mnethostid = \''.$mnethostid.'\'';
b7b50143 3123
7c12949d 3124/// Get all the basic user data
3125
b7b50143 3126 if (! $user = get_record_select('user', $constraints)) {
7c12949d 3127 return false;
3128 }
3129
7c12949d 3130/// Get various settings and preferences
3131
3132 if ($displays = get_records('course_display', 'userid', $user->id)) {
3133 foreach ($displays as $display) {
3134 $user->display[$display->course] = $display->display;
3135 }
3136 }
3137
346c3e2f 3138 $user->preference = get_user_preferences(null, null, $user->id);
7c12949d 3139
721d14cb 3140 if ($lastaccesses = get_records('user_lastaccess', 'userid', $user->id)) {
3141 foreach ($lastaccesses as $lastaccess) {
3142 $user->lastcourseaccess[$lastaccess->courseid] = $lastaccess->timeaccess;
3143 }
3144 }
3145
5bf243d1 3146 $sql = "SELECT g.id, g.courseid
3147 FROM {$CFG->prefix}groups g, {$CFG->prefix}groups_members gm
3148 WHERE gm.groupid=g.id AND gm.userid={$user->id}";
3149
3150 // this is a special hack to speedup calendar display
3151 $user->groupmember = array();
3152 if ($groups = get_records_sql($sql)) {
3153 foreach ($groups as $group) {
3154 if (!array_key_exists($group->courseid, $user->groupmember)) {
3155 $user->groupmember[$group->courseid] = array();
3156 }
3157 $user->groupmember[$group->courseid][$group->id] = $group->id;
7c12949d 3158 }
3159 }
3160
323ccc26 3161/// Add the custom profile fields to the user record
3162 include_once($CFG->dirroot.'/user/profile/lib.php');
3163 $customfields = (array)profile_user_record($user->id);
3164 foreach ($customfields as $cname=>$cvalue) {
3165 if (!isset($user->$cname)) { // Don't overwrite any standard fields
3166 $user->$cname = $cvalue;
3167 }
3168 }
3169
7c12949d 3170/// Rewrite some variables if necessary
3171 if (!empty($user->description)) {
3172 $user->description = true; // No need to cart all of it around
3173 }
3174 if ($user->username == 'guest') {
3175 $user->lang = $CFG->lang; // Guest language always same as site
3176 $user->firstname = get_string('guestuser'); // Name always in current language
3177 $user->lastname = ' ';
3178 }
3179
7c12949d 3180 $user->sesskey = random_string(10);
3181 $user->sessionIP = md5(getremoteaddr()); // Store the current IP in the session
3182
3183 return $user;
7c12949d 3184}
3185
83022298 3186/**
3187 * @uses $CFG
3188 * @param string $password the password to be checked agains the password policy
3189 * @param string $errmsg the error message to display when the password doesn't comply with the policy.
3190 * @return bool true if the password is valid according to the policy. false otherwise.
3191 */
3192function check_password_policy($password, &$errmsg) {
3193 global $CFG;
3194
3195 if (empty($CFG->passwordpolicy)) {
3196 return true;
3197 }
3198
8e1ec6be 3199 $textlib = textlib_get_instance();
83022298 3200 $errmsg = '';
3201 if ($textlib->strlen($password) < $CFG->minpasswordlength) {
3202 $errmsg = get_string('errorminpasswordlength', 'auth', $CFG->minpasswordlength);
3203
3204 } else if (preg_match_all('/[[:digit:]]/u', $password, $matches) < $CFG->minpassworddigits) {
3205 $errmsg = get_string('errorminpassworddigits', 'auth', $CFG->minpassworddigits);
3206
3207 } else if (preg_match_all('/[[:lower:]]/u', $password, $matches) < $CFG->minpasswordlower) {
3208 $errmsg = get_string('errorminpasswordlower', 'auth', $CFG->minpasswordlower);
3209
3210 } else if (preg_match_all('/[[:upper:]]/u', $password, $matches) < $CFG->minpasswordupper) {
3211 $errmsg = get_string('errorminpasswordupper', 'auth', $CFG->minpasswordupper);
7c12949d 3212
83022298 3213 } else if (preg_match_all('/[^[:upper:][:lower:][:digit:]]/u', $password, $matches) < $CFG->minpasswordnonalphanum) {
3214 $errmsg = get_string('errorminpasswordnonalphanum', 'auth', $CFG->minpasswordnonalphanum);
5c98bf9e 3215
83022298 3216 } else if ($password == 'admin' or $password == 'password') {
3217 $errmsg = get_string('unsafepassword');
3218 }
3219
3220 if ($errmsg == '') {
3221 return true;
3222 } else {
3223 return false;
3224 }
3225}
3226
3227
3228/**
7c12949d 3229 * When logging in, this function is run to set certain preferences
3230 * for the current SESSION
3231 */
3232function set_login_session_preferences() {
7c7ca1b5 3233 global $SESSION, $CFG;
7c12949d 3234
3235 $SESSION->justloggedin = true;
3236
3237 unset($SESSION->lang);
7c12949d 3238
3239 // Restore the calendar filters, if saved
3240 if (intval(get_user_preferences('calendar_persistflt', 0))) {
3241 include_once($CFG->dirroot.'/calendar/lib.php');
a266c904 3242 calendar_set_filters_status(get_user_preferences('calendav_savedflt', 0xff));
7c12949d 3243 }
3244}
3245
3246
b97c4164 3247/**
3248 * Delete a course, including all related data from the database,
3249 * and any associated files from the moodledata folder.
e1ecf0a0 3250 *
b97c4164 3251 * @param int $courseid The id of the course to delete.
3252 * @param bool $showfeedback Whether to display notifications of each action the function performs.
3253 * @return bool true if all the removals succeeded. false if there were any failures. If this
3254 * method returns false, some of the removals will probably have succeeded, and others
3255 * failed, but you have no way of knowing which.
3256 */
3257function delete_course($courseid, $showfeedback = true) {
3258 global $CFG;
f615fbab 3259 require_once($CFG->libdir.'/gradelib.php');
b97c4164 3260 $result = true;
e1ecf0a0 3261
b51ece5b 3262 // frontpage course can not be deleted!!
3263 if ($courseid == SITEID) {
3264 return false;
3265 }
3266
3267 $context = get_context_instance(CONTEXT_COURSE, $courseid);
3268
b97c4164 3269 if (!remove_course_contents($courseid, $showfeedback)) {
3270 if ($showfeedback) {
3271 notify("An error occurred while deleting some of the course contents.");
3272 }
3273 $result = false;
3274 }
3275
f615fbab 3276 remove_course_grades($courseid, $showfeedback);
b51ece5b 3277 remove_grade_letters($context, $showfeedback);
f615fbab 3278
b97c4164 3279 if (!delete_records("course", "id", $courseid)) {
3280 if ($showfeedback) {
3281 notify("An error occurred while deleting the main course record.");
3282 }
3283 $result = false;
3284 }
3285
b51ece5b 3286/// Delete all roles and overiddes in the course context
3287 if (!delete_context(CONTEXT_COURSE, $courseid)) {
eaa79489 3288 if ($showfeedback) {
b51ece5b 3289 notify("An error occurred while deleting the main course context.");
eaa79489 3290 }
3291 $result = false;
3292 }
3293
b97c4164 3294 if (!fulldelete($CFG->dataroot.'/'.$courseid)) {
3295 if ($showfeedback) {
3296 notify("An error occurred while deleting the course files.");
3297 }
3298 $result = false;
3299 }