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