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