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