MDL-56050 core: set missing context to maintenance mode
[moodle.git] / lib / moodlelib.php
CommitLineData
0d0a8bf6 1<?php
6759ad2f 2// This file is part of Moodle - http://moodle.org/
3//
0d0a8bf6 4// Moodle is free software: you can redistribute it and/or modify
5// it under the terms of the GNU General Public License as published by
6// the Free Software Foundation, either version 3 of the License, or
7// (at your option) any later version.
8//
9// Moodle is distributed in the hope that it will be useful,
10// but WITHOUT ANY WARRANTY; without even the implied warranty of
11// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12// GNU General Public License for more details.
6759ad2f 13//
0d0a8bf6 14// You should have received a copy of the GNU General Public License
15// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
65ccdd8c 16
7cf1c7bd 17/**
89dcb99d 18 * moodlelib.php - Moodle main library
7cf1c7bd 19 *
20 * Main library file of miscellaneous general-purpose Moodle functions.
21 * Other main libraries:
8c3dba73 22 * - weblib.php - functions that produce web output
23 * - datalib.php - functions that access the database
0d0a8bf6 24 *
78bfb562
PS
25 * @package core
26 * @subpackage lib
27 * @copyright 1999 onwards Martin Dougiamas http://dougiamas.com
28 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
7cf1c7bd 29 */
e1ecf0a0 30
78bfb562
PS
31defined('MOODLE_INTERNAL') || die();
32
ac7af0da 33// CONSTANTS (Encased in phpdoc proper comments).
f374fb10 34
ac7af0da 35// Date and time constants.
5602f7cf 36/**
37 * Time constant - the number of seconds in a year
38 */
5602f7cf 39define('YEARSECS', 31536000);
40
7a5672c9 41/**
2f87145b 42 * Time constant - the number of seconds in a week
7a5672c9 43 */
361855e6 44define('WEEKSECS', 604800);
2f87145b 45
46/**
47 * Time constant - the number of seconds in a day
48 */
7a5672c9 49define('DAYSECS', 86400);
2f87145b 50
51/**
52 * Time constant - the number of seconds in an hour
53 */
7a5672c9 54define('HOURSECS', 3600);
2f87145b 55
56/**
57 * Time constant - the number of seconds in a minute
58 */
7a5672c9 59define('MINSECS', 60);
2f87145b 60
61/**
62 * Time constant - the number of minutes in a day
63 */
7a5672c9 64define('DAYMINS', 1440);
2f87145b 65
66/**
67 * Time constant - the number of minutes in an hour
68 */
7a5672c9 69define('HOURMINS', 60);
f9903ed0 70
ac7af0da
SH
71// Parameter constants - every call to optional_param(), required_param()
72// or clean_param() should have a specified type of parameter.
03b31ea3 73
e0d346ff 74/**
03b31ea3 75 * PARAM_ALPHA - contains only english ascii letters a-zA-Z.
e0d346ff 76 */
03b31ea3 77define('PARAM_ALPHA', 'alpha');
bbd3f2c4 78
79/**
03b31ea3 80 * PARAM_ALPHAEXT the same contents as PARAM_ALPHA plus the chars in quotes: "_-" allowed
81 * NOTE: originally this allowed "/" too, please use PARAM_SAFEPATH if "/" needed
bbd3f2c4 82 */
03b31ea3 83define('PARAM_ALPHAEXT', 'alphaext');
bbd3f2c4 84
85/**
03b31ea3 86 * PARAM_ALPHANUM - expected numbers and letters only.
bbd3f2c4 87 */
03b31ea3 88define('PARAM_ALPHANUM', 'alphanum');
bbd3f2c4 89
90/**
03b31ea3 91 * PARAM_ALPHANUMEXT - expected numbers, letters only and _-.
bbd3f2c4 92 */
03b31ea3 93define('PARAM_ALPHANUMEXT', 'alphanumext');
bbd3f2c4 94
9dae915a 95/**
03b31ea3 96 * PARAM_AUTH - actually checks to make sure the string is a valid auth plugin
6e73ae10 97 */
03b31ea3 98define('PARAM_AUTH', 'auth');
6e73ae10 99
100/**
03b31ea3 101 * PARAM_BASE64 - Base 64 encoded format
9dae915a 102 */
03b31ea3 103define('PARAM_BASE64', 'base64');
9dae915a 104
bbd3f2c4 105/**
03b31ea3 106 * PARAM_BOOL - converts input into 0 or 1, use for switches in forms and urls.
bbd3f2c4 107 */
03b31ea3 108define('PARAM_BOOL', 'bool');
bbd3f2c4 109
110/**
03b31ea3 111 * PARAM_CAPABILITY - A capability name, like 'moodle/role:manage'. Actually
efb8c375 112 * checked against the list of capabilities in the database.
6e73ae10 113 */
03b31ea3 114define('PARAM_CAPABILITY', 'capability');
6e73ae10 115
116/**
2d2018ab
TH
117 * PARAM_CLEANHTML - cleans submitted HTML code. Note that you almost never want
118 * to use this. The normal mode of operation is to use PARAM_RAW when recieving
119 * the input (required/optional_param or formslib) and then sanitse the HTML
120 * using format_text on output. This is for the rare cases when you want to
121 * sanitise the HTML on input. This cleaning may also fix xhtml strictness.
bbd3f2c4 122 */
03b31ea3 123define('PARAM_CLEANHTML', 'cleanhtml');
bbd3f2c4 124
79f1d953 125/**
126 * PARAM_EMAIL - an email address following the RFC
127 */
128define('PARAM_EMAIL', 'email');
129
bbd3f2c4 130/**
03b31ea3 131 * PARAM_FILE - safe file name, all dangerous chars are stripped, protects against XSS, SQL injections and directory traversals
bbd3f2c4 132 */
03b31ea3 133define('PARAM_FILE', 'file');
6e73ae10 134
135/**
03b31ea3 136 * PARAM_FLOAT - a real/floating point number.
7f5f3844
TH
137 *
138 * Note that you should not use PARAM_FLOAT for numbers typed in by the user.
139 * It does not work for languages that use , as a decimal separator.
140 * Instead, do something like
141 * $rawvalue = required_param('name', PARAM_RAW);
142 * // ... other code including require_login, which sets current lang ...
143 * $realvalue = unformat_float($rawvalue);
144 * // ... then use $realvalue
6e73ae10 145 */
03b31ea3 146define('PARAM_FLOAT', 'float');
6e73ae10 147
148/**
03b31ea3 149 * PARAM_HOST - expected fully qualified domain name (FQDN) or an IPv4 dotted quad (IP address)
150 */
151define('PARAM_HOST', 'host');
152
153/**
154 * PARAM_INT - integers only, use when expecting only numbers.
6e73ae10 155 */
03b31ea3 156define('PARAM_INT', 'int');
157
158/**
159 * PARAM_LANG - checks to see if the string is a valid installed language in the current site.
160 */
161define('PARAM_LANG', 'lang');
162
163/**
ac7af0da
SH
164 * PARAM_LOCALURL - expected properly formatted URL as well as one that refers to the local server itself. (NOT orthogonal to the
165 * others! Implies PARAM_URL!)
03b31ea3 166 */
167define('PARAM_LOCALURL', 'localurl');
bbd3f2c4 168
169/**
c59733ef 170 * PARAM_NOTAGS - all html tags are stripped from the text. Do not abuse this type.
bbd3f2c4 171 */
03b31ea3 172define('PARAM_NOTAGS', 'notags');
bbd3f2c4 173
6e73ae10 174/**
ac7af0da
SH
175 * PARAM_PATH - safe relative path name, all dangerous chars are stripped, protects against XSS, SQL injections and directory
176 * traversals note: the leading slash is not removed, window drive letter is not allowed
31f26796 177 */
03b31ea3 178define('PARAM_PATH', 'path');
31f26796 179
6e73ae10 180/**
03b31ea3 181 * PARAM_PEM - Privacy Enhanced Mail format
c4ea5e78 182 */
03b31ea3 183define('PARAM_PEM', 'pem');
c4ea5e78 184
bbd3f2c4 185/**
03b31ea3 186 * PARAM_PERMISSION - A permission, one of CAP_INHERIT, CAP_ALLOW, CAP_PREVENT or CAP_PROHIBIT.
bbd3f2c4 187 */
03b31ea3 188define('PARAM_PERMISSION', 'permission');
bbd3f2c4 189
bed79931 190/**
78fcdb5f 191 * PARAM_RAW specifies a parameter that is not cleaned/processed in any way except the discarding of the invalid utf-8 characters
bed79931 192 */
03b31ea3 193define('PARAM_RAW', 'raw');
bed79931 194
652599ec
TH
195/**
196 * PARAM_RAW_TRIMMED like PARAM_RAW but leading and trailing whitespace is stripped.
197 */
198define('PARAM_RAW_TRIMMED', 'raw_trimmed');
199
bcef0319 200/**
03b31ea3 201 * PARAM_SAFEDIR - safe directory name, suitable for include() and require()
bcef0319 202 */
03b31ea3 203define('PARAM_SAFEDIR', 'safedir');
bcef0319 204
e032888c 205/**
03b31ea3 206 * PARAM_SAFEPATH - several PARAM_SAFEDIR joined by "/", suitable for include() and require(), plugin paths, etc.
38fb8190 207 */
03b31ea3 208define('PARAM_SAFEPATH', 'safepath');
e032888c 209
bbd3f2c4 210/**
03b31ea3 211 * PARAM_SEQUENCE - expects a sequence of numbers like 8 to 1,5,6,4,6,8,9. Numbers and comma only.
bbd3f2c4 212 */
03b31ea3 213define('PARAM_SEQUENCE', 'sequence');
bbd3f2c4 214
215/**
03b31ea3 216 * PARAM_TAG - one tag (interests, blogs, etc.) - mostly international characters and space, <> not supported
bbd3f2c4 217 */
03b31ea3 218define('PARAM_TAG', 'tag');
bbd3f2c4 219
220/**
03b31ea3 221 * PARAM_TAGLIST - list of tags separated by commas (interests, blogs, etc.)
bbd3f2c4 222 */
03b31ea3 223define('PARAM_TAGLIST', 'taglist');
bbd3f2c4 224
225/**
b6059edc 226 * PARAM_TEXT - general plain text compatible with multilang filter, no other html tags. Please note '<', or '>' are allowed here.
bbd3f2c4 227 */
03b31ea3 228define('PARAM_TEXT', 'text');
bbd3f2c4 229
bbd3f2c4 230/**
03b31ea3 231 * PARAM_THEME - Checks to see if the string is a valid theme name in the current site
bbd3f2c4 232 */
03b31ea3 233define('PARAM_THEME', 'theme');
bbd3f2c4 234
235/**
ac7af0da
SH
236 * PARAM_URL - expected properly formatted URL. Please note that domain part is required, http://localhost/ is not accepted but
237 * http://localhost.localdomain/ is ok.
bbd3f2c4 238 */
03b31ea3 239define('PARAM_URL', 'url');
240
07ed083e 241/**
ac7af0da
SH
242 * PARAM_USERNAME - Clean username to only contains allowed characters. This is to be used ONLY when manually creating user
243 * accounts, do NOT use when syncing with external systems!!
07ed083e
RW
244 */
245define('PARAM_USERNAME', 'username');
bbd3f2c4 246
fe6a248f
DM
247/**
248 * PARAM_STRINGID - used to check if the given string is valid string identifier for get_string()
249 */
250define('PARAM_STRINGID', 'stringid');
03b31ea3 251
ac7af0da 252// DEPRECATED PARAM TYPES OR ALIASES - DO NOT USE FOR NEW CODE.
bbd3f2c4 253/**
03b31ea3 254 * PARAM_CLEAN - obsoleted, please use a more specific type of parameter.
255 * It was one of the first types, that is why it is abused so much ;-)
44913c8d 256 * @deprecated since 2.0
bbd3f2c4 257 */
03b31ea3 258define('PARAM_CLEAN', 'clean');
bbd3f2c4 259
260/**
03b31ea3 261 * PARAM_INTEGER - deprecated alias for PARAM_INT
1e12c120 262 * @deprecated since 2.0
bbd3f2c4 263 */
03b31ea3 264define('PARAM_INTEGER', 'int');
bbd3f2c4 265
0e4af166 266/**
03b31ea3 267 * PARAM_NUMBER - deprecated alias of PARAM_FLOAT
61cca0b7 268 * @deprecated since 2.0
0e4af166 269 */
03b31ea3 270define('PARAM_NUMBER', 'float');
0e4af166 271
03d820c7 272/**
efb8c375 273 * PARAM_ACTION - deprecated alias for PARAM_ALPHANUMEXT, use for various actions in forms and urls
03b31ea3 274 * NOTE: originally alias for PARAM_APLHA
405aca35 275 * @deprecated since 2.0
03d820c7 276 */
03b31ea3 277define('PARAM_ACTION', 'alphanumext');
03d820c7 278
279/**
03b31ea3 280 * PARAM_FORMAT - deprecated alias for PARAM_ALPHANUMEXT, use for names of plugins, formats, etc.
281 * NOTE: originally alias for PARAM_APLHA
405aca35 282 * @deprecated since 2.0
03d820c7 283 */
03b31ea3 284define('PARAM_FORMAT', 'alphanumext');
03d820c7 285
ad944e78 286/**
03b31ea3 287 * PARAM_MULTILANG - deprecated alias of PARAM_TEXT.
071e68f9 288 * @deprecated since 2.0
ad944e78 289 */
03b31ea3 290define('PARAM_MULTILANG', 'text');
03d820c7 291
ccc77f91
RT
292/**
293 * PARAM_TIMEZONE - expected timezone. Timezone can be int +-(0-13) or float +-(0.5-12.5) or
ac7af0da 294 * string separated by '/' and can have '-' &/ '_' (eg. America/North_Dakota/New_Salem
ccc77f91
RT
295 * America/Port-au-Prince)
296 */
297define('PARAM_TIMEZONE', 'timezone');
298
faf75fe7 299/**
03b31ea3 300 * PARAM_CLEANFILE - deprecated alias of PARAM_FILE; originally was removing regional chars too
faf75fe7 301 */
03b31ea3 302define('PARAM_CLEANFILE', 'file');
303
aff24313
PS
304/**
305 * PARAM_COMPONENT is used for full component names (aka frankenstyle) such as 'mod_forum', 'core_rating', 'auth_ldap'.
306 * Short legacy subsystem names and module names are accepted too ex: 'forum', 'rating', 'user'.
307 * Only lowercase ascii letters, numbers and underscores are allowed, it has to start with a letter.
308 * NOTE: numbers and underscores are strongly discouraged in plugin names!
309 */
310define('PARAM_COMPONENT', 'component');
311
312/**
313 * PARAM_AREA is a name of area used when addressing files, comments, ratings, etc.
314 * It is usually used together with context id and component.
315 * Only lowercase ascii letters, numbers and underscores are allowed, it has to start with a letter.
316 */
317define('PARAM_AREA', 'area');
318
319/**
320 * PARAM_PLUGIN is used for plugin names such as 'forum', 'glossary', 'ldap', 'radius', 'paypal', 'completionstatus'.
321 * Only lowercase ascii letters, numbers and underscores are allowed, it has to start with a letter.
322 * NOTE: numbers and underscores are strongly discouraged in plugin names! Underscores are forbidden in module names.
323 */
324define('PARAM_PLUGIN', 'plugin');
325
326
ac7af0da 327// Web Services.
03b31ea3 328
382b9cea 329/**
330 * VALUE_REQUIRED - if the parameter is not supplied, there is an error
331 */
332define('VALUE_REQUIRED', 1);
333
334/**
335 * VALUE_OPTIONAL - if the parameter is not supplied, then the param has no value
336 */
337define('VALUE_OPTIONAL', 2);
338
339/**
340 * VALUE_DEFAULT - if the parameter is not supplied, then the default value is used
341 */
342define('VALUE_DEFAULT', 0);
03b31ea3 343
5a1861ee 344/**
345 * NULL_NOT_ALLOWED - the parameter can not be set to null in the database
346 */
347define('NULL_NOT_ALLOWED', false);
348
349/**
350 * NULL_ALLOWED - the parameter can be set to null in the database
351 */
352define('NULL_ALLOWED', true);
faf75fe7 353
ac7af0da
SH
354// Page types.
355
bbd3f2c4 356/**
357 * PAGE_COURSE_VIEW is a definition of a page type. For more information on the page class see moodle/lib/pagelib.php.
8bd3fad3 358 */
359define('PAGE_COURSE_VIEW', 'course-view');
8bd3fad3 360
9bda43e6 361/** Get remote addr constant */
362define('GETREMOTEADDR_SKIP_HTTP_CLIENT_IP', '1');
363/** Get remote addr constant */
364define('GETREMOTEADDR_SKIP_HTTP_X_FORWARDED_FOR', '2');
6e73ae10 365
ac7af0da 366// Blog access level constant declaration.
feaf5d06 367define ('BLOG_USER_LEVEL', 1);
368define ('BLOG_GROUP_LEVEL', 2);
369define ('BLOG_COURSE_LEVEL', 3);
370define ('BLOG_SITE_LEVEL', 4);
371define ('BLOG_GLOBAL_LEVEL', 5);
372
6e73ae10 373
ac7af0da 374// Tag constants.
4eb718d8 375/**
a905364a 376 * To prevent problems with multibytes strings,Flag updating in nav not working on the review page. this should not exceed the
6e73ae10 377 * length of "varchar(255) / 3 (bytes / utf-8 character) = 85".
378 * TODO: this is not correct, varchar(255) are 255 unicode chars ;-)
0d0a8bf6 379 *
380 * @todo define(TAG_MAX_LENGTH) this is not correct, varchar(255) are 255 unicode chars ;-)
4eb718d8 381 */
ae040d4b 382define('TAG_MAX_LENGTH', 50);
4eb718d8 383
ac7af0da 384// Password policy constants.
6499395e 385define ('PASSWORD_LOWER', 'abcdefghijklmnopqrstuvwxyz');
386define ('PASSWORD_UPPER', 'ABCDEFGHIJKLMNOPQRSTUVWXYZ');
387define ('PASSWORD_DIGITS', '0123456789');
388define ('PASSWORD_NONALPHANUM', '.,;:!?_-+/*@#&$');
389
ac7af0da 390// Feature constants.
6e73ae10 391// Used for plugin_supports() to report features that are, or are not, supported by a module.
49f6e5f4 392
393/** True if module can provide a grade */
61fceb86 394define('FEATURE_GRADE_HAS_GRADE', 'grade_has_grade');
42f103be 395/** True if module supports outcomes */
396define('FEATURE_GRADE_OUTCOMES', 'outcomes');
b11f9da6
DM
397/** True if module supports advanced grading methods */
398define('FEATURE_ADVANCED_GRADING', 'grade_advanced_grading');
455dc0de
FM
399/** True if module controls the grade visibility over the gradebook */
400define('FEATURE_CONTROLS_GRADE_VISIBILITY', 'controlsgradevisbility');
50da4ddd
KG
401/** True if module supports plagiarism plugins */
402define('FEATURE_PLAGIARISM', 'plagiarism');
42f103be 403
49f6e5f4 404/** True if module has code to track whether somebody viewed it */
61fceb86 405define('FEATURE_COMPLETION_TRACKS_VIEWS', 'completion_tracks_views');
49f6e5f4 406/** True if module has custom completion rules */
61fceb86 407define('FEATURE_COMPLETION_HAS_RULES', 'completion_has_rules');
49f6e5f4 408
0d8b6a69 409/** True if module has no 'view' page (like label) */
410define('FEATURE_NO_VIEW_LINK', 'viewlink');
de158ec5 411/** True (which is default) if the module wants support for setting the ID number for grade calculation purposes. */
42f103be 412define('FEATURE_IDNUMBER', 'idnumber');
413/** True if module supports groups */
414define('FEATURE_GROUPS', 'groups');
415/** True if module supports groupings */
416define('FEATURE_GROUPINGS', 'groupings');
061e6b28 417/**
418 * True if module supports groupmembersonly (which no longer exists)
419 * @deprecated Since Moodle 2.8
420 */
42f103be 421define('FEATURE_GROUPMEMBERSONLY', 'groupmembersonly');
422
aa54ed7b 423/** Type of module */
424define('FEATURE_MOD_ARCHETYPE', 'mod_archetype');
42f103be 425/** True if module supports intro editor */
dc5c2bd9 426define('FEATURE_MOD_INTRO', 'mod_intro');
42f103be 427/** True if module has default completion */
428define('FEATURE_MODEDIT_DEFAULT_COMPLETION', 'modedit_default_completion');
49f6e5f4 429
1bcb7eb5 430define('FEATURE_COMMENT', 'comment');
431
6c5fcef7 432define('FEATURE_RATE', 'rate');
4bfdcfcf
EL
433/** True if module supports backup/restore of moodle2 format */
434define('FEATURE_BACKUP_MOODLE2', 'backup_moodle2');
a09aeee4 435
8c40662e 436/** True if module can show description on course main page */
437define('FEATURE_SHOW_DESCRIPTION', 'showdescription');
438
b07ef13b
DP
439/** True if module uses the question bank */
440define('FEATURE_USES_QUESTIONS', 'usesquestions');
441
aa54ed7b 442/** Unspecified module archetype */
443define('MOD_ARCHETYPE_OTHER', 0);
444/** Resource-like type module */
445define('MOD_ARCHETYPE_RESOURCE', 1);
efb8c375 446/** Assignment module archetype */
aa54ed7b 447define('MOD_ARCHETYPE_ASSIGNMENT', 2);
5813c7f7 448/** System (not user-addable) module archetype */
449define('MOD_ARCHETYPE_SYSTEM', 3);
aa54ed7b 450
9ca0420e
MG
451/**
452 * Return this from modname_get_types callback to use default display in activity chooser.
453 * Deprecated, will be removed in 3.5, TODO MDL-53697.
454 * @deprecated since Moodle 3.1
455 */
50ae8814
MN
456define('MOD_SUBTYPE_NO_CHILDREN', 'modsubtypenochildren');
457
eec99048 458/**
459 * Security token used for allowing access
460 * from external application such as web services.
461 * Scripts do not use any session, performance is relatively
462 * low because we need to load access info in each request.
efb8c375 463 * Scripts are executed in parallel.
eec99048 464 */
465define('EXTERNAL_TOKEN_PERMANENT', 0);
466
467/**
468 * Security token used for allowing access
469 * of embedded applications, the code is executed in the
470 * active user session. Token is invalidated after user logs out.
471 * Scripts are executed serially - normal session locking is used.
472 */
473define('EXTERNAL_TOKEN_EMBEDDED', 1);
49f6e5f4 474
4766a50c
SH
475/**
476 * The home page should be the site home
477 */
478define('HOMEPAGE_SITE', 0);
479/**
480 * The home page should be the users my page
481 */
482define('HOMEPAGE_MY', 1);
483/**
484 * The home page can be chosen by the user
485 */
486define('HOMEPAGE_USER', 2);
fcce139a 487
94788de2 488/**
489 * Hub directory url (should be moodle.org)
490 */
491define('HUB_HUBDIRECTORYURL', "http://hubdirectory.moodle.org");
492
493
494/**
495 * Moodle.org url (should be moodle.org)
496 */
497define('HUB_MOODLEORGHUBURL', "http://hub.moodle.org");
498
c1b65883
JM
499/**
500 * Moodle mobile app service name
501 */
502define('MOODLE_OFFICIAL_MOBILE_SERVICE', 'moodle_mobile_app');
94788de2 503
bc8da017
AD
504/**
505 * Indicates the user has the capabilities required to ignore activity and course file size restrictions
506 */
507define('USER_CAN_IGNORE_FILE_SIZE_LIMITS', -1);
508
1f09018a 509/**
ac7af0da
SH
510 * Course display settings: display all sections on one page.
511 */
512define('COURSE_DISPLAY_SINGLEPAGE', 0);
513/**
514 * Course display settings: split pages into a page per section.
1f09018a 515 */
ac7af0da 516define('COURSE_DISPLAY_MULTIPAGE', 1);
1f09018a 517
ec2d8ceb 518/**
ac7af0da 519 * Authentication constant: String used in password field when password is not stored.
ec2d8ceb 520 */
ac7af0da 521define('AUTH_PASSWORD_NOT_CACHED', 'not cached');
ec2d8ceb 522
ac7af0da 523// PARAMETER HANDLING.
6b174680 524
e0d346ff 525/**
361855e6 526 * Returns a particular value for the named variable, taken from
527 * POST or GET. If the parameter doesn't exist then an error is
e0d346ff 528 * thrown because we require this variable.
529 *
361855e6 530 * This function should be used to initialise all required values
531 * in a script that are based on parameters. Usually it will be
e0d346ff 532 * used like this:
622365d2 533 * $id = required_param('id', PARAM_INT);
e0d346ff 534 *
2ca3bffa 535 * Please note the $type parameter is now required and the value can not be array.
44913c8d
PS
536 *
537 * @param string $parname the name of the page parameter we want
538 * @param string $type expected type of parameter
e0d346ff 539 * @return mixed
ac7af0da 540 * @throws coding_exception
e0d346ff 541 */
44913c8d 542function required_param($parname, $type) {
2ca3bffa
PS
543 if (func_num_args() != 2 or empty($parname) or empty($type)) {
544 throw new coding_exception('required_param() requires $parname and $type to be specified (parameter: '.$parname.')');
44913c8d 545 }
ac7af0da
SH
546 // POST has precedence.
547 if (isset($_POST[$parname])) {
a083b93c 548 $param = $_POST[$parname];
549 } else if (isset($_GET[$parname])) {
550 $param = $_GET[$parname];
e0d346ff 551 } else {
2f137aa1 552 print_error('missingparam', '', '', $parname);
e0d346ff 553 }
554
2ca3bffa
PS
555 if (is_array($param)) {
556 debugging('Invalid array parameter detected in required_param(): '.$parname);
ac7af0da 557 // TODO: switch to fatal error in Moodle 2.3.
2ca3bffa
PS
558 return required_param_array($parname, $type);
559 }
560
a083b93c 561 return clean_param($param, $type);
e0d346ff 562}
563
2ca3bffa
PS
564/**
565 * Returns a particular array value for the named variable, taken from
566 * POST or GET. If the parameter doesn't exist then an error is
567 * thrown because we require this variable.
568 *
569 * This function should be used to initialise all required values
570 * in a script that are based on parameters. Usually it will be
571 * used like this:
572 * $ids = required_param_array('ids', PARAM_INT);
573 *
574 * Note: arrays of arrays are not supported, only alphanumeric keys with _ and - are supported
575 *
576 * @param string $parname the name of the page parameter we want
577 * @param string $type expected type of parameter
578 * @return array
ac7af0da 579 * @throws coding_exception
2ca3bffa
PS
580 */
581function required_param_array($parname, $type) {
582 if (func_num_args() != 2 or empty($parname) or empty($type)) {
583 throw new coding_exception('required_param_array() requires $parname and $type to be specified (parameter: '.$parname.')');
584 }
ac7af0da
SH
585 // POST has precedence.
586 if (isset($_POST[$parname])) {
2ca3bffa
PS
587 $param = $_POST[$parname];
588 } else if (isset($_GET[$parname])) {
589 $param = $_GET[$parname];
590 } else {
591 print_error('missingparam', '', '', $parname);
592 }
593 if (!is_array($param)) {
594 print_error('missingparam', '', '', $parname);
595 }
596
597 $result = array();
ac7af0da 598 foreach ($param as $key => $value) {
2ca3bffa
PS
599 if (!preg_match('/^[a-z0-9_-]+$/i', $key)) {
600 debugging('Invalid key name in required_param_array() detected: '.$key.', parameter: '.$parname);
601 continue;
602 }
ebdeccca 603 $result[$key] = clean_param($value, $type);
2ca3bffa
PS
604 }
605
606 return $result;
e0d346ff 607}
608
609/**
361855e6 610 * Returns a particular value for the named variable, taken from
e0d346ff 611 * POST or GET, otherwise returning a given default.
612 *
361855e6 613 * This function should be used to initialise all optional values
614 * in a script that are based on parameters. Usually it will be
e0d346ff 615 * used like this:
622365d2 616 * $name = optional_param('name', 'Fred', PARAM_TEXT);
e0d346ff 617 *
2ca3bffa 618 * Please note the $type parameter is now required and the value can not be array.
44913c8d 619 *
a083b93c 620 * @param string $parname the name of the page parameter we want
e0d346ff 621 * @param mixed $default the default value to return if nothing is found
44913c8d 622 * @param string $type expected type of parameter
e0d346ff 623 * @return mixed
ac7af0da 624 * @throws coding_exception
e0d346ff 625 */
44913c8d 626function optional_param($parname, $default, $type) {
2ca3bffa 627 if (func_num_args() != 3 or empty($parname) or empty($type)) {
ac7af0da 628 throw new coding_exception('optional_param requires $parname, $default + $type to be specified (parameter: '.$parname.')');
44913c8d 629 }
44913c8d 630
ac7af0da
SH
631 // POST has precedence.
632 if (isset($_POST[$parname])) {
a083b93c 633 $param = $_POST[$parname];
634 } else if (isset($_GET[$parname])) {
635 $param = $_GET[$parname];
e0d346ff 636 } else {
637 return $default;
638 }
c7f4e3e2 639
2ca3bffa
PS
640 if (is_array($param)) {
641 debugging('Invalid array parameter detected in required_param(): '.$parname);
ac7af0da 642 // TODO: switch to $default in Moodle 2.3.
2ca3bffa
PS
643 return optional_param_array($parname, $default, $type);
644 }
645
a083b93c 646 return clean_param($param, $type);
e0d346ff 647}
648
2ca3bffa
PS
649/**
650 * Returns a particular array value for the named variable, taken from
651 * POST or GET, otherwise returning a given default.
652 *
653 * This function should be used to initialise all optional values
654 * in a script that are based on parameters. Usually it will be
655 * used like this:
656 * $ids = optional_param('id', array(), PARAM_INT);
657 *
ac7af0da 658 * Note: arrays of arrays are not supported, only alphanumeric keys with _ and - are supported
2ca3bffa
PS
659 *
660 * @param string $parname the name of the page parameter we want
ac7af0da 661 * @param mixed $default the default value to return if nothing is found
2ca3bffa
PS
662 * @param string $type expected type of parameter
663 * @return array
ac7af0da 664 * @throws coding_exception
2ca3bffa
PS
665 */
666function optional_param_array($parname, $default, $type) {
667 if (func_num_args() != 3 or empty($parname) or empty($type)) {
ac7af0da 668 throw new coding_exception('optional_param_array requires $parname, $default + $type to be specified (parameter: '.$parname.')');
2ca3bffa
PS
669 }
670
ac7af0da
SH
671 // POST has precedence.
672 if (isset($_POST[$parname])) {
2ca3bffa
PS
673 $param = $_POST[$parname];
674 } else if (isset($_GET[$parname])) {
675 $param = $_GET[$parname];
676 } else {
677 return $default;
678 }
679 if (!is_array($param)) {
680 debugging('optional_param_array() expects array parameters only: '.$parname);
681 return $default;
682 }
683
684 $result = array();
ac7af0da 685 foreach ($param as $key => $value) {
2ca3bffa
PS
686 if (!preg_match('/^[a-z0-9_-]+$/i', $key)) {
687 debugging('Invalid key name in optional_param_array() detected: '.$key.', parameter: '.$parname);
688 continue;
689 }
ebdeccca 690 $result[$key] = clean_param($value, $type);
2ca3bffa
PS
691 }
692
693 return $result;
e0d346ff 694}
695
a3f7cbf6 696/**
697 * Strict validation of parameter values, the values are only converted
698 * to requested PHP type. Internally it is using clean_param, the values
699 * before and after cleaning must be equal - otherwise
700 * an invalid_parameter_exception is thrown.
efb8c375 701 * Objects and classes are not accepted.
a3f7cbf6 702 *
703 * @param mixed $param
2ca3bffa 704 * @param string $type PARAM_ constant
a3f7cbf6 705 * @param bool $allownull are nulls valid value?
706 * @param string $debuginfo optional debug information
fea52c11
PS
707 * @return mixed the $param value converted to PHP type
708 * @throws invalid_parameter_exception if $param is not of given type
a3f7cbf6 709 */
5a1861ee 710function validate_param($param, $type, $allownull=NULL_NOT_ALLOWED, $debuginfo='') {
a3f7cbf6 711 if (is_null($param)) {
5a1861ee 712 if ($allownull == NULL_ALLOWED) {
a3f7cbf6 713 return null;
714 } else {
715 throw new invalid_parameter_exception($debuginfo);
716 }
717 }
718 if (is_array($param) or is_object($param)) {
719 throw new invalid_parameter_exception($debuginfo);
720 }
721
722 $cleaned = clean_param($param, $type);
fea52c11
PS
723
724 if ($type == PARAM_FLOAT) {
725 // Do not detect precision loss here.
726 if (is_float($param) or is_int($param)) {
727 // These always fit.
728 } else if (!is_numeric($param) or !preg_match('/^[\+-]?[0-9]*\.?[0-9]*(e[-+]?[0-9]+)?$/i', (string)$param)) {
729 throw new invalid_parameter_exception($debuginfo);
730 }
731 } else if ((string)$param !== (string)$cleaned) {
ac7af0da 732 // Conversion to string is usually lossless.
a3f7cbf6 733 throw new invalid_parameter_exception($debuginfo);
734 }
735
736 return $cleaned;
737}
738
2ca3bffa 739/**
ac7af0da
SH
740 * Makes sure array contains only the allowed types, this function does not validate array key names!
741 *
2ca3bffa
PS
742 * <code>
743 * $options = clean_param($options, PARAM_INT);
744 * </code>
745 *
746 * @param array $param the variable array we are cleaning
747 * @param string $type expected format of param after cleaning.
748 * @param bool $recursive clean recursive arrays
749 * @return array
ac7af0da 750 * @throws coding_exception
2ca3bffa
PS
751 */
752function clean_param_array(array $param = null, $type, $recursive = false) {
ac7af0da
SH
753 // Convert null to empty array.
754 $param = (array)$param;
2ca3bffa
PS
755 foreach ($param as $key => $value) {
756 if (is_array($value)) {
757 if ($recursive) {
758 $param[$key] = clean_param_array($value, $type, true);
759 } else {
ac7af0da 760 throw new coding_exception('clean_param_array can not process multidimensional arrays when $recursive is false.');
2ca3bffa
PS
761 }
762 } else {
763 $param[$key] = clean_param($value, $type);
764 }
765 }
766 return $param;
767}
768
e0d346ff 769/**
361855e6 770 * Used by {@link optional_param()} and {@link required_param()} to
771 * clean the variables and/or cast to specific types, based on
e0d346ff 772 * an options field.
bbd3f2c4 773 * <code>
774 * $course->format = clean_param($course->format, PARAM_ALPHA);
ac7af0da 775 * $selectedgradeitem = clean_param($selectedgradeitem, PARAM_INT);
bbd3f2c4 776 * </code>
e0d346ff 777 *
778 * @param mixed $param the variable we are cleaning
2ca3bffa 779 * @param string $type expected format of param after cleaning.
e0d346ff 780 * @return mixed
ac7af0da 781 * @throws coding_exception
e0d346ff 782 */
a083b93c 783function clean_param($param, $type) {
7744ea12 784 global $CFG;
c7f4e3e2 785
c16c1be7
PS
786 if (is_array($param)) {
787 throw new coding_exception('clean_param() can not process arrays, please use clean_param_array() instead.');
788 } else if (is_object($param)) {
789 if (method_exists($param, '__toString')) {
790 $param = $param->__toString();
791 } else {
792 throw new coding_exception('clean_param() can not process objects, please use clean_param_array() instead.');
793 }
80bfd470 794 }
795
a083b93c 796 switch ($type) {
ac7af0da
SH
797 case PARAM_RAW:
798 // No cleaning at all.
78fcdb5f 799 $param = fix_utf8($param);
96e98ea6 800 return $param;
801
ac7af0da
SH
802 case PARAM_RAW_TRIMMED:
803 // No cleaning, but strip leading and trailing whitespace.
78fcdb5f 804 $param = fix_utf8($param);
652599ec
TH
805 return trim($param);
806
ac7af0da
SH
807 case PARAM_CLEAN:
808 // General HTML cleaning, try to use more specific type if possible this is deprecated!
809 // Please use more specific type instead.
a083b93c 810 if (is_numeric($param)) {
811 return $param;
812 }
78fcdb5f 813 $param = fix_utf8($param);
ac7af0da
SH
814 // Sweep for scripts, etc.
815 return clean_text($param);
3af57507 816
ac7af0da
SH
817 case PARAM_CLEANHTML:
818 // Clean html fragment.
78fcdb5f 819 $param = fix_utf8($param);
ac7af0da
SH
820 // Sweep for scripts, etc.
821 $param = clean_text($param, FORMAT_HTML);
a083b93c 822 return trim($param);
e0d346ff 823
a083b93c 824 case PARAM_INT:
ac7af0da
SH
825 // Convert to integer.
826 return (int)$param;
e0d346ff 827
6e73ae10 828 case PARAM_FLOAT:
ac7af0da
SH
829 // Convert to float.
830 return (float)$param;
9dae915a 831
ac7af0da
SH
832 case PARAM_ALPHA:
833 // Remove everything not `a-z`.
6dbcacee 834 return preg_replace('/[^a-zA-Z]/i', '', $param);
e0d346ff 835
ac7af0da
SH
836 case PARAM_ALPHAEXT:
837 // Remove everything not `a-zA-Z_-` (originally allowed "/" too).
6dbcacee 838 return preg_replace('/[^a-zA-Z_-]/i', '', $param);
6e73ae10 839
ac7af0da
SH
840 case PARAM_ALPHANUM:
841 // Remove everything not `a-zA-Z0-9`.
6dbcacee 842 return preg_replace('/[^A-Za-z0-9]/i', '', $param);
f24148ef 843
ac7af0da
SH
844 case PARAM_ALPHANUMEXT:
845 // Remove everything not `a-zA-Z0-9_-`.
6dbcacee 846 return preg_replace('/[^A-Za-z0-9_-]/i', '', $param);
0ed442f8 847
ac7af0da
SH
848 case PARAM_SEQUENCE:
849 // Remove everything not `0-9,`.
6dbcacee 850 return preg_replace('/[^0-9,]/i', '', $param);
0e4af166 851
ac7af0da
SH
852 case PARAM_BOOL:
853 // Convert to 1 or 0.
a083b93c 854 $tempstr = strtolower($param);
6e73ae10 855 if ($tempstr === 'on' or $tempstr === 'yes' or $tempstr === 'true') {
a083b93c 856 $param = 1;
6e73ae10 857 } else if ($tempstr === 'off' or $tempstr === 'no' or $tempstr === 'false') {
a083b93c 858 $param = 0;
859 } else {
860 $param = empty($param) ? 0 : 1;
861 }
862 return $param;
f24148ef 863
ac7af0da
SH
864 case PARAM_NOTAGS:
865 // Strip all tags.
78fcdb5f 866 $param = fix_utf8($param);
a083b93c 867 return strip_tags($param);
3af57507 868
ac7af0da
SH
869 case PARAM_TEXT:
870 // Leave only tags needed for multilang.
78fcdb5f 871 $param = fix_utf8($param);
ac7af0da
SH
872 // If the multilang syntax is not correct we strip all tags because it would break xhtml strict which is required
873 // for accessibility standards please note this cleaning does not strip unbalanced '>' for BC compatibility reasons.
b6059edc
PS
874 do {
875 if (strpos($param, '</lang>') !== false) {
ac7af0da 876 // Old and future mutilang syntax.
b6059edc
PS
877 $param = strip_tags($param, '<lang>');
878 if (!preg_match_all('/<.*>/suU', $param, $matches)) {
879 break;
880 }
881 $open = false;
882 foreach ($matches[0] as $match) {
883 if ($match === '</lang>') {
884 if ($open) {
885 $open = false;
886 continue;
887 } else {
888 break 2;
889 }
890 }
891 if (!preg_match('/^<lang lang="[a-zA-Z0-9_-]+"\s*>$/u', $match)) {
892 break 2;
893 } else {
894 $open = true;
895 }
896 }
897 if ($open) {
898 break;
899 }
900 return $param;
901
902 } else if (strpos($param, '</span>') !== false) {
ac7af0da 903 // Current problematic multilang syntax.
b6059edc
PS
904 $param = strip_tags($param, '<span>');
905 if (!preg_match_all('/<.*>/suU', $param, $matches)) {
906 break;
907 }
908 $open = false;
909 foreach ($matches[0] as $match) {
910 if ($match === '</span>') {
911 if ($open) {
912 $open = false;
913 continue;
914 } else {
915 break 2;
916 }
917 }
918 if (!preg_match('/^<span(\s+lang="[a-zA-Z0-9_-]+"|\s+class="multilang"){2}\s*>$/u', $match)) {
919 break 2;
920 } else {
921 $open = true;
922 }
923 }
924 if ($open) {
925 break;
926 }
927 return $param;
928 }
929 } while (false);
ac7af0da 930 // Easy, just strip all tags, if we ever want to fix orphaned '&' we have to do that in format_string().
b6059edc 931 return strip_tags($param);
31f26796 932
aff24313 933 case PARAM_COMPONENT:
ac7af0da
SH
934 // We do not want any guessing here, either the name is correct or not
935 // please note only normalised component names are accepted.
a41d1ca0 936 if (!preg_match('/^[a-z]+(_[a-z][a-z0-9_]*)?[a-z0-9]+$/', $param)) {
aff24313
PS
937 return '';
938 }
939 if (strpos($param, '__') !== false) {
940 return '';
941 }
942 if (strpos($param, 'mod_') === 0) {
ac7af0da 943 // Module names must not contain underscores because we need to differentiate them from invalid plugin types.
aff24313
PS
944 if (substr_count($param, '_') != 1) {
945 return '';
946 }
947 }
948 return $param;
949
950 case PARAM_PLUGIN:
951 case PARAM_AREA:
ac7af0da 952 // We do not want any guessing here, either the name is correct or not.
5f850735 953 if (!is_valid_plugin_name($param)) {
aff24313
PS
954 return '';
955 }
956 return $param;
957
ac7af0da
SH
958 case PARAM_SAFEDIR:
959 // Remove everything not a-zA-Z0-9_- .
6dbcacee 960 return preg_replace('/[^a-zA-Z0-9_-]/i', '', $param);
95bfd207 961
ac7af0da
SH
962 case PARAM_SAFEPATH:
963 // Remove everything not a-zA-Z0-9/_- .
6759ad2f 964 return preg_replace('/[^a-zA-Z0-9\/_-]/i', '', $param);
6e73ae10 965
ac7af0da
SH
966 case PARAM_FILE:
967 // Strip all suspicious characters from filename.
78fcdb5f 968 $param = fix_utf8($param);
14f3ad15 969 $param = preg_replace('~[[:cntrl:]]|[&<>"`\|\':\\\\/]~u', '', $param);
caf16a57 970 if ($param === '.' || $param === '..') {
371a2ed0 971 $param = '';
972 }
a083b93c 973 return $param;
974
ac7af0da
SH
975 case PARAM_PATH:
976 // Strip all suspicious characters from file path.
78fcdb5f 977 $param = fix_utf8($param);
a083b93c 978 $param = str_replace('\\', '/', $param);
caf16a57
FM
979
980 // Explode the path and clean each element using the PARAM_FILE rules.
981 $breadcrumb = explode('/', $param);
982 foreach ($breadcrumb as $key => $crumb) {
983 if ($crumb === '.' && $key === 0) {
984 // Special condition to allow for relative current path such as ./currentdirfile.txt.
985 } else {
986 $crumb = clean_param($crumb, PARAM_FILE);
987 }
988 $breadcrumb[$key] = $crumb;
989 }
990 $param = implode('/', $breadcrumb);
991
992 // Remove multiple current path (./././) and multiple slashes (///).
6dbcacee 993 $param = preg_replace('~//+~', '/', $param);
caf16a57
FM
994 $param = preg_replace('~/(\./)+~', '/', $param);
995 return $param;
a083b93c 996
ac7af0da
SH
997 case PARAM_HOST:
998 // Allow FQDN or IPv4 dotted quad.
999 $param = preg_replace('/[^\.\d\w-]/', '', $param );
1000 // Match ipv4 dotted quad.
1001 if (preg_match('/(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})/', $param, $match)) {
1002 // Confirm values are ok.
a083b93c 1003 if ( $match[0] > 255
1004 || $match[1] > 255
1005 || $match[3] > 255
1006 || $match[4] > 255 ) {
ac7af0da 1007 // Hmmm, what kind of dotted quad is this?
a083b93c 1008 $param = '';
1009 }
ac7af0da
SH
1010 } else if ( preg_match('/^[\w\d\.-]+$/', $param) // Dots, hyphens, numbers.
1011 && !preg_match('/^[\.-]/', $param) // No leading dots/hyphens.
1012 && !preg_match('/[\.-]$/', $param) // No trailing dots/hyphens.
a083b93c 1013 ) {
ac7af0da 1014 // All is ok - $param is respected.
a083b93c 1015 } else {
ac7af0da 1016 // All is not ok...
a083b93c 1017 $param='';
1018 }
1019 return $param;
7744ea12 1020
ac7af0da 1021 case PARAM_URL: // Allow safe ftp, http, mailto urls.
78fcdb5f 1022 $param = fix_utf8($param);
a083b93c 1023 include_once($CFG->dirroot . '/lib/validateurlsyntax.php');
5301205a 1024 if (!empty($param) && validateUrlSyntax($param, 's?H?S?F?E?u-P-a?I?p?f?q?r?')) {
ac7af0da 1025 // All is ok, param is respected.
d2a9f7cc 1026 } else {
ac7af0da
SH
1027 // Not really ok.
1028 $param ='';
a083b93c 1029 }
1030 return $param;
1031
ac7af0da
SH
1032 case PARAM_LOCALURL:
1033 // Allow http absolute, root relative and relative URLs within wwwroot.
93684765 1034 $param = clean_param($param, PARAM_URL);
a083b93c 1035 if (!empty($param)) {
d031c2dc
FM
1036
1037 // Simulate the HTTPS version of the site.
1038 $httpswwwroot = str_replace('http://', 'https://', $CFG->wwwroot);
1039
5c1f41f0
PS
1040 if ($param === $CFG->wwwroot) {
1041 // Exact match;
1042 } else if (!empty($CFG->loginhttps) && $param === $httpswwwroot) {
1043 // Exact match;
1044 } else if (preg_match(':^/:', $param)) {
ac7af0da 1045 // Root-relative, ok!
5c1f41f0 1046 } else if (preg_match('/^' . preg_quote($CFG->wwwroot . '/', '/') . '/i', $param)) {
ac7af0da 1047 // Absolute, and matches our wwwroot.
5c1f41f0 1048 } else if (!empty($CFG->loginhttps) && preg_match('/^' . preg_quote($httpswwwroot . '/', '/') . '/i', $param)) {
d031c2dc 1049 // Absolute, and matches our httpswwwroot.
7744ea12 1050 } else {
ac7af0da 1051 // Relative - let's make sure there are no tricks.
4bea5e85 1052 if (validateUrlSyntax('/' . $param, 's-u-P-a-p-f+q?r?')) {
ac7af0da 1053 // Looks ok.
a083b93c 1054 } else {
1055 $param = '';
1056 }
d2a9f7cc 1057 }
7744ea12 1058 }
a083b93c 1059 return $param;
bcef0319 1060
03d820c7 1061 case PARAM_PEM:
1062 $param = trim($param);
ac7af0da
SH
1063 // PEM formatted strings may contain letters/numbers and the symbols:
1064 // forward slash: /
1065 // plus sign: +
1066 // equal sign: =
1067 // , surrounded by BEGIN and END CERTIFICATE prefix and suffixes.
03d820c7 1068 if (preg_match('/^-----BEGIN CERTIFICATE-----([\s\w\/\+=]+)-----END CERTIFICATE-----$/', trim($param), $matches)) {
1069 list($wholething, $body) = $matches;
1070 unset($wholething, $matches);
1071 $b64 = clean_param($body, PARAM_BASE64);
1072 if (!empty($b64)) {
1073 return "-----BEGIN CERTIFICATE-----\n$b64\n-----END CERTIFICATE-----\n";
1074 } else {
1075 return '';
1076 }
1077 }
1078 return '';
bcef0319 1079
03d820c7 1080 case PARAM_BASE64:
1081 if (!empty($param)) {
1082 // PEM formatted strings may contain letters/numbers and the symbols
ac7af0da
SH
1083 // forward slash: /
1084 // plus sign: +
1085 // equal sign: =.
03d820c7 1086 if (0 >= preg_match('/^([\s\w\/\+=]+)$/', trim($param))) {
1087 return '';
1088 }
1089 $lines = preg_split('/[\s]+/', $param, -1, PREG_SPLIT_NO_EMPTY);
ac7af0da
SH
1090 // Each line of base64 encoded data must be 64 characters in length, except for the last line which may be less
1091 // than (or equal to) 64 characters long.
03d820c7 1092 for ($i=0, $j=count($lines); $i < $j; $i++) {
1093 if ($i + 1 == $j) {
1094 if (64 < strlen($lines[$i])) {
1095 return '';
1096 }
1097 continue;
1098 }
7744ea12 1099
03d820c7 1100 if (64 != strlen($lines[$i])) {
1101 return '';
1102 }
1103 }
ac7af0da 1104 return implode("\n", $lines);
03d820c7 1105 } else {
1106 return '';
1107 }
bcef0319 1108
1109 case PARAM_TAG:
78fcdb5f 1110 $param = fix_utf8($param);
34b93e39
PS
1111 // Please note it is not safe to use the tag name directly anywhere,
1112 // it must be processed with s(), urlencode() before embedding anywhere.
ac7af0da 1113 // Remove some nasties.
6b24e35e 1114 $param = preg_replace('~[[:cntrl:]]|[<>`]~u', '', $param);
ac7af0da 1115 // Convert many whitespace chars into one.
e737c2ff 1116 $param = preg_replace('/\s+/u', ' ', $param);
2f1e464a 1117 $param = core_text::substr(trim($param), 0, TAG_MAX_LENGTH);
c93c6b3b 1118 return $param;
bcef0319 1119
ae040d4b 1120 case PARAM_TAGLIST:
78fcdb5f 1121 $param = fix_utf8($param);
ae040d4b 1122 $tags = explode(',', $param);
1123 $result = array();
1124 foreach ($tags as $tag) {
1125 $res = clean_param($tag, PARAM_TAG);
6e73ae10 1126 if ($res !== '') {
ae040d4b 1127 $result[] = $res;
1128 }
1129 }
1130 if ($result) {
1131 return implode(',', $result);
1132 } else {
1133 return '';
0d626493 1134 }
1135
ad944e78 1136 case PARAM_CAPABILITY:
4f0c2d00 1137 if (get_capability_info($param)) {
ad944e78 1138 return $param;
1139 } else {
1140 return '';
1141 }
1142
faf75fe7 1143 case PARAM_PERMISSION:
1144 $param = (int)$param;
1145 if (in_array($param, array(CAP_INHERIT, CAP_ALLOW, CAP_PREVENT, CAP_PROHIBIT))) {
1146 return $param;
1147 } else {
1148 return CAP_INHERIT;
1149 }
1150
03b31ea3 1151 case PARAM_AUTH:
aff24313
PS
1152 $param = clean_param($param, PARAM_PLUGIN);
1153 if (empty($param)) {
1154 return '';
1155 } else if (exists_auth_plugin($param)) {
03b31ea3 1156 return $param;
1157 } else {
1158 return '';
1159 }
1160
1161 case PARAM_LANG:
1162 $param = clean_param($param, PARAM_SAFEDIR);
ef686eb5 1163 if (get_string_manager()->translation_exists($param)) {
03b31ea3 1164 return $param;
1165 } else {
ac7af0da
SH
1166 // Specified language is not installed or param malformed.
1167 return '';
03b31ea3 1168 }
1169
1170 case PARAM_THEME:
aff24313
PS
1171 $param = clean_param($param, PARAM_PLUGIN);
1172 if (empty($param)) {
1173 return '';
1174 } else if (file_exists("$CFG->dirroot/theme/$param/config.php")) {
73e504bc
PS
1175 return $param;
1176 } else if (!empty($CFG->themedir) and file_exists("$CFG->themedir/$param/config.php")) {
03b31ea3 1177 return $param;
1178 } else {
ac7af0da
SH
1179 // Specified theme is not installed.
1180 return '';
03b31ea3 1181 }
1182
07ed083e 1183 case PARAM_USERNAME:
78fcdb5f 1184 $param = fix_utf8($param);
77218e4a 1185 $param = trim($param);
ac7af0da 1186 // Convert uppercase to lowercase MDL-16919.
2f1e464a 1187 $param = core_text::strtolower($param);
34d2b19a 1188 if (empty($CFG->extendedusernamechars)) {
77218e4a 1189 $param = str_replace(" " , "", $param);
ac7af0da 1190 // Regular expression, eliminate all chars EXCEPT:
07ed083e
RW
1191 // alphanum, dash (-), underscore (_), at sign (@) and period (.) characters.
1192 $param = preg_replace('/[^-\.@_a-z0-9]/', '', $param);
4f0c2d00 1193 }
07ed083e
RW
1194 return $param;
1195
79f1d953 1196 case PARAM_EMAIL:
78fcdb5f 1197 $param = fix_utf8($param);
79f1d953 1198 if (validate_email($param)) {
1199 return $param;
1200 } else {
1201 return '';
1202 }
1203
fe6a248f
DM
1204 case PARAM_STRINGID:
1205 if (preg_match('|^[a-zA-Z][a-zA-Z0-9\.:/_-]*$|', $param)) {
1206 return $param;
1207 } else {
1208 return '';
1209 }
1210
ac7af0da
SH
1211 case PARAM_TIMEZONE:
1212 // Can be int, float(with .5 or .0) or string seperated by '/' and can have '-_'.
78fcdb5f 1213 $param = fix_utf8($param);
8158ce79 1214 $timezonepattern = '/^(([+-]?(0?[0-9](\.[5|0])?|1[0-3](\.0)?|1[0-2]\.5))|(99)|[[:alnum:]]+(\/?[[:alpha:]_-])+)$/';
ccc77f91
RT
1215 if (preg_match($timezonepattern, $param)) {
1216 return $param;
1217 } else {
1218 return '';
1219 }
1220
ac7af0da
SH
1221 default:
1222 // Doh! throw error, switched parameters in optional_param or another serious problem.
03b31ea3 1223 print_error("unknownparamtype", '', '', $type);
2ae28153 1224 }
e0d346ff 1225}
1226
8a40bc36
FM
1227/**
1228 * Whether the PARAM_* type is compatible in RTL.
1229 *
1230 * Being compatible with RTL means that the data they contain can flow
1231 * from right-to-left or left-to-right without compromising the user experience.
1232 *
1233 * Take URLs for example, they are not RTL compatible as they should always
1234 * flow from the left to the right. This also applies to numbers, email addresses,
1235 * configuration snippets, base64 strings, etc...
1236 *
1237 * This function tries to best guess which parameters can contain localised strings.
1238 *
1239 * @param string $paramtype Constant PARAM_*.
1240 * @return bool
1241 */
1242function is_rtl_compatible($paramtype) {
1243 return $paramtype == PARAM_TEXT || $paramtype == PARAM_NOTAGS;
1244}
1245
78fcdb5f
PS
1246/**
1247 * Makes sure the data is using valid utf8, invalid characters are discarded.
1248 *
1249 * Note: this function is not intended for full objects with methods and private properties.
1250 *
1251 * @param mixed $value
1252 * @return mixed with proper utf-8 encoding
1253 */
1254function fix_utf8($value) {
1255 if (is_null($value) or $value === '') {
1256 return $value;
1257
1258 } else if (is_string($value)) {
1259 if ((string)(int)$value === $value) {
ac7af0da 1260 // Shortcut.
78fcdb5f
PS
1261 return $value;
1262 }
bff1d60c
PS
1263 // No null bytes expected in our data, so let's remove it.
1264 $value = str_replace("\0", '', $value);
0aff15c2 1265
0aff15c2
PS
1266 // Note: this duplicates min_fix_utf8() intentionally.
1267 static $buggyiconv = null;
1268 if ($buggyiconv === null) {
dd47f210 1269 $buggyiconv = (!function_exists('iconv') or @iconv('UTF-8', 'UTF-8//IGNORE', '100'.chr(130).'€') !== '100€');
0aff15c2
PS
1270 }
1271
1272 if ($buggyiconv) {
1273 if (function_exists('mb_convert_encoding')) {
1274 $subst = mb_substitute_character();
1275 mb_substitute_character('');
1276 $result = mb_convert_encoding($value, 'utf-8', 'utf-8');
1277 mb_substitute_character($subst);
1278
1279 } else {
1280 // Warn admins on admin/index.php page.
1281 $result = $value;
1282 }
1283
1284 } else {
dd47f210 1285 $result = @iconv('UTF-8', 'UTF-8//IGNORE', $value);
51b7297b 1286 }
0aff15c2 1287
51b7297b 1288 return $result;
78fcdb5f
PS
1289
1290 } else if (is_array($value)) {
ac7af0da 1291 foreach ($value as $k => $v) {
78fcdb5f
PS
1292 $value[$k] = fix_utf8($v);
1293 }
1294 return $value;
1295
1296 } else if (is_object($value)) {
ac7af0da
SH
1297 // Do not modify original.
1298 $value = clone($value);
1299 foreach ($value as $k => $v) {
78fcdb5f
PS
1300 $value->$k = fix_utf8($v);
1301 }
1302 return $value;
1303
1304 } else {
ac7af0da 1305 // This is some other type, no utf-8 here.
78fcdb5f
PS
1306 return $value;
1307 }
1308}
1309
6e73ae10 1310/**
1311 * Return true if given value is integer or string with integer value
0d0a8bf6 1312 *
1313 * @param mixed $value String or Int
1314 * @return bool true if number, false if not
6e73ae10 1315 */
1316function is_number($value) {
1317 if (is_int($value)) {
1318 return true;
1319 } else if (is_string($value)) {
1320 return ((string)(int)$value) === $value;
1321 } else {
1322 return false;
1323 }
1324}
7a530277 1325
aa282b10 1326/**
ac7af0da
SH
1327 * Returns host part from url.
1328 *
aa282b10 1329 * @param string $url full url
1330 * @return string host, null if not found
1331 */
1332function get_host_from_url($url) {
1333 preg_match('|^[a-z]+://([a-zA-Z0-9-.]+)|i', $url, $matches);
1334 if ($matches) {
1335 return $matches[1];
1336 }
1337 return null;
1338}
1339
94a6d656 1340/**
0d0a8bf6 1341 * Tests whether anything was returned by text editor
1342 *
94a6d656 1343 * This function is useful for testing whether something you got back from
1344 * the HTML editor actually contains anything. Sometimes the HTML editor
1345 * appear to be empty, but actually you get back a <br> tag or something.
1346 *
1347 * @param string $string a string containing HTML.
1348 * @return boolean does the string contain any actual content - that is text,
efb8c375 1349 * images, objects, etc.
94a6d656 1350 */
1351function html_is_blank($string) {
1352 return trim(strip_tags($string, '<img><object><applet><input><select><textarea><hr>')) == '';
1353}
1354
7cf1c7bd 1355/**
1356 * Set a key in global configuration
1357 *
89dcb99d 1358 * Set a key/value pair in both this session's {@link $CFG} global variable
7cf1c7bd 1359 * and in the 'config' database table for future sessions.
e1ecf0a0 1360 *
1361 * Can also be used to update keys for plugin-scoped configs in config_plugin table.
1362 * In that case it doesn't affect $CFG.
7cf1c7bd 1363 *
6fd511eb 1364 * A NULL value will delete the entry.
1365 *
08b51dd0
JO
1366 * NOTE: this function is called from lib/db/upgrade.php
1367 *
7cf1c7bd 1368 * @param string $name the key to set
9cdb766d 1369 * @param string $value the value to set (without magic quotes)
ac7af0da 1370 * @param string $plugin (optional) the plugin scope, default null
5e2f308b 1371 * @return bool true or exception
7cf1c7bd 1372 */
ac7af0da 1373function set_config($name, $value, $plugin=null) {
ae040d4b 1374 global $CFG, $DB;
42282810 1375
a4080313 1376 if (empty($plugin)) {
220a90c5 1377 if (!array_key_exists($name, $CFG->config_php_settings)) {
ac7af0da 1378 // So it's defined for this invocation at least.
220a90c5 1379 if (is_null($value)) {
1380 unset($CFG->$name);
1381 } else {
ac7af0da
SH
1382 // Settings from db are always strings.
1383 $CFG->$name = (string)$value;
220a90c5 1384 }
1385 }
e1ecf0a0 1386
ac7af0da 1387 if ($DB->get_field('config', 'name', array('name' => $name))) {
5e2f308b 1388 if ($value === null) {
ac7af0da 1389 $DB->delete_records('config', array('name' => $name));
6fd511eb 1390 } else {
ac7af0da 1391 $DB->set_field('config', 'value', $value, array('name' => $name));
6fd511eb 1392 }
a4080313 1393 } else {
5e2f308b 1394 if ($value !== null) {
365a5941 1395 $config = new stdClass();
5e2f308b 1396 $config->name = $name;
1397 $config->value = $value;
1398 $DB->insert_record('config', $config, false);
6fd511eb 1399 }
a4080313 1400 }
e0d9b7c0
SH
1401 if ($name === 'siteidentifier') {
1402 cache_helper::update_site_identifier($value);
1403 }
007bfe8b 1404 cache_helper::invalidate_by_definition('core', 'config', array(), 'core');
ac7af0da
SH
1405 } else {
1406 // Plugin scope.
1407 if ($id = $DB->get_field('config_plugins', 'id', array('name' => $name, 'plugin' => $plugin))) {
6fd511eb 1408 if ($value===null) {
ac7af0da 1409 $DB->delete_records('config_plugins', array('name' => $name, 'plugin' => $plugin));
6fd511eb 1410 } else {
ac7af0da 1411 $DB->set_field('config_plugins', 'value', $value, array('id' => $id));
6fd511eb 1412 }
a4080313 1413 } else {
5e2f308b 1414 if ($value !== null) {
365a5941 1415 $config = new stdClass();
5e2f308b 1416 $config->plugin = $plugin;
1417 $config->name = $name;
1418 $config->value = $value;
1419 $DB->insert_record('config_plugins', $config, false);
6fd511eb 1420 }
a4080313 1421 }
007bfe8b 1422 cache_helper::invalidate_by_definition('core', 'config', array(), $plugin);
a4080313 1423 }
5e2f308b 1424
1425 return true;
a4080313 1426}
1427
1428/**
e1ecf0a0 1429 * Get configuration values from the global config table
a4080313 1430 * or the config_plugins table.
1431 *
13daf6a2 1432 * If called with one parameter, it will load all the config
12bb0c3e 1433 * variables for one plugin, and return them as an object.
13daf6a2 1434 *
12bb0c3e
PS
1435 * If called with 2 parameters it will return a string single
1436 * value or false if the value is not found.
9220fba5 1437 *
08b51dd0
JO
1438 * NOTE: this function is called from lib/db/upgrade.php
1439 *
ac7af0da 1440 * @static string|false $siteidentifier The site identifier is not cached. We use this static cache so
e0d9b7c0 1441 * that we need only fetch it once per request.
12bb0c3e 1442 * @param string $plugin full component name
ac7af0da 1443 * @param string $name default null
07ab0c80 1444 * @return mixed hash-like object or single value, return false no config found
ac7af0da 1445 * @throws dml_exception
a4080313 1446 */
ac7af0da 1447function get_config($plugin, $name = null) {
ae040d4b 1448 global $CFG, $DB;
dfc9ba9b 1449
e0d9b7c0
SH
1450 static $siteidentifier = null;
1451
007bfe8b
SH
1452 if ($plugin === 'moodle' || $plugin === 'core' || empty($plugin)) {
1453 $forced =& $CFG->config_php_settings;
1454 $iscore = true;
1455 $plugin = 'core';
1456 } else {
1457 if (array_key_exists($plugin, $CFG->forced_plugin_settings)) {
1458 $forced =& $CFG->forced_plugin_settings[$plugin];
1459 } else {
1460 $forced = array();
1461 }
1462 $iscore = false;
12bb0c3e
PS
1463 }
1464
e0d9b7c0
SH
1465 if ($siteidentifier === null) {
1466 try {
1467 // This may fail during installation.
1468 // If you have a look at {@link initialise_cfg()} you will see that this is how we detect the need to
1469 // install the database.
1470 $siteidentifier = $DB->get_field('config', 'value', array('name' => 'siteidentifier'));
1471 } catch (dml_exception $ex) {
e0d9b7c0
SH
1472 // Set siteidentifier to false. We don't want to trip this continually.
1473 $siteidentifier = false;
1474 throw $ex;
1475 }
1476 }
1477
1478 if (!empty($name)) {
1479 if (array_key_exists($name, $forced)) {
1480 return (string)$forced[$name];
1481 } else if ($name === 'siteidentifier' && $plugin == 'core') {
1482 return $siteidentifier;
1483 }
007bfe8b
SH
1484 }
1485
1486 $cache = cache::make('core', 'config');
1487 $result = $cache->get($plugin);
d0749719 1488 if ($result === false) {
ac7af0da 1489 // The user is after a recordset.
007bfe8b 1490 if (!$iscore) {
ac7af0da 1491 $result = $DB->get_records_menu('config_plugins', array('plugin' => $plugin), '', 'name,value');
a4080313 1492 } else {
ac7af0da 1493 // This part is not really used any more, but anyway...
007bfe8b 1494 $result = $DB->get_records_menu('config', array(), '', 'name,value');;
a4080313 1495 }
007bfe8b 1496 $cache->set($plugin, $result);
a4080313 1497 }
1498
007bfe8b
SH
1499 if (!empty($name)) {
1500 if (array_key_exists($name, $result)) {
1501 return $result[$name];
bfb82da3 1502 }
007bfe8b
SH
1503 return false;
1504 }
e1ecf0a0 1505
e0d9b7c0
SH
1506 if ($plugin === 'core') {
1507 $result['siteidentifier'] = $siteidentifier;
1508 }
1509
007bfe8b
SH
1510 foreach ($forced as $key => $value) {
1511 if (is_null($value) or is_array($value) or is_object($value)) {
ac7af0da 1512 // We do not want any extra mess here, just real settings that could be saved in db.
007bfe8b
SH
1513 unset($result[$key]);
1514 } else {
ac7af0da 1515 // Convert to string as if it went through the DB.
007bfe8b 1516 $result[$key] = (string)$value;
12bb0c3e 1517 }
39917a09 1518 }
007bfe8b
SH
1519
1520 return (object)$result;
39917a09 1521}
1522
b0270f84 1523/**
ac7af0da 1524 * Removes a key from global configuration.
b0270f84 1525 *
08b51dd0
JO
1526 * NOTE: this function is called from lib/db/upgrade.php
1527 *
b0270f84 1528 * @param string $name the key to set
1529 * @param string $plugin (optional) the plugin scope
4b600aa0 1530 * @return boolean whether the operation succeeded.
b0270f84 1531 */
ac7af0da 1532function unset_config($name, $plugin=null) {
ae040d4b 1533 global $CFG, $DB;
b0270f84 1534
b0270f84 1535 if (empty($plugin)) {
4b600aa0 1536 unset($CFG->$name);
ac7af0da 1537 $DB->delete_records('config', array('name' => $name));
007bfe8b 1538 cache_helper::invalidate_by_definition('core', 'config', array(), 'core');
5e623a33 1539 } else {
ac7af0da 1540 $DB->delete_records('config_plugins', array('name' => $name, 'plugin' => $plugin));
007bfe8b 1541 cache_helper::invalidate_by_definition('core', 'config', array(), $plugin);
b0270f84 1542 }
013376de 1543
1544 return true;
b0270f84 1545}
1546
4b600aa0 1547/**
1548 * Remove all the config variables for a given plugin.
ac7af0da 1549 *
c2ca2d8e 1550 * NOTE: this function is called from lib/db/upgrade.php
4b600aa0 1551 *
1552 * @param string $plugin a plugin, for example 'quiz' or 'qtype_multichoice';
1553 * @return boolean whether the operation succeeded.
1554 */
1555function unset_all_config_for_plugin($plugin) {
1556 global $DB;
ac7af0da 1557 // Delete from the obvious config_plugins first.
013376de 1558 $DB->delete_records('config_plugins', array('plugin' => $plugin));
ac7af0da 1559 // Next delete any suspect settings from config.
a4193166
PS
1560 $like = $DB->sql_like('name', '?', true, true, false, '|');
1561 $params = array($DB->sql_like_escape($plugin.'_', '|') . '%');
1562 $DB->delete_records_select('config', $like, $params);
007bfe8b
SH
1563 // Finally clear both the plugin cache and the core cache (suspect settings now removed from core).
1564 cache_helper::invalidate_by_definition('core', 'config', array(), array('core', $plugin));
1565
013376de 1566 return true;
4b600aa0 1567}
1568
4413941f 1569/**
efb8c375 1570 * Use this function to get a list of users from a config setting of type admin_setting_users_with_capability.
adf176d7
PS
1571 *
1572 * All users are verified if they still have the necessary capability.
1573 *
b3d960e6 1574 * @param string $value the value of the config setting.
4413941f 1575 * @param string $capability the capability - must match the one passed to the admin_setting_users_with_capability constructor.
ac7af0da 1576 * @param bool $includeadmins include administrators.
4413941f 1577 * @return array of user objects.
1578 */
adf176d7 1579function get_users_from_config($value, $capability, $includeadmins = true) {
adf176d7
PS
1580 if (empty($value) or $value === '$@NONE@$') {
1581 return array();
4413941f 1582 }
adf176d7 1583
ac7af0da 1584 // We have to make sure that users still have the necessary capability,
adf176d7 1585 // it should be faster to fetch them all first and then test if they are present
ac7af0da 1586 // instead of validating them one-by-one.
b0c6dc1c 1587 $users = get_users_by_capability(context_system::instance(), $capability);
adf176d7
PS
1588 if ($includeadmins) {
1589 $admins = get_admins();
1590 foreach ($admins as $admin) {
1591 $users[$admin->id] = $admin;
1592 }
1593 }
1594
1595 if ($value === '$@ALL@$') {
1596 return $users;
1597 }
1598
ac7af0da 1599 $result = array(); // Result in correct order.
adf176d7
PS
1600 $allowed = explode(',', $value);
1601 foreach ($allowed as $uid) {
1602 if (isset($users[$uid])) {
1603 $user = $users[$uid];
1604 $result[$user->id] = $user;
1605 }
1606 }
1607
1608 return $result;
4413941f 1609}
1610
f87eab7e
PS
1611
1612/**
ac7af0da 1613 * Invalidates browser caches and cached data in temp.
52642d0d
SH
1614 *
1615 * IMPORTANT - If you are adding anything here to do with the cache directory you should also have a look at
ac7af0da 1616 * {@link phpunit_util::reset_dataroot()}
52642d0d 1617 *
f87eab7e
PS
1618 * @return void
1619 */
1620function purge_all_caches() {
d79d5ac2 1621 global $CFG, $DB;
f87eab7e 1622
f87eab7e
PS
1623 reset_text_filters_cache();
1624 js_reset_all_caches();
1625 theme_reset_all_caches();
1626 get_string_manager()->reset_caches();
2f1e464a 1627 core_text::reset_caches();
e87214bd
PS
1628 if (class_exists('core_plugin_manager')) {
1629 core_plugin_manager::reset_caches();
bde002b8 1630 }
f87eab7e 1631
299cfee5
MG
1632 // Bump up cacherev field for all courses.
1633 try {
1634 increment_revision_number('course', 'cacherev', '');
1635 } catch (moodle_exception $e) {
1636 // Ignore exception since this function is also called before upgrade script when field course.cacherev does not exist yet.
1637 }
1638
d79d5ac2 1639 $DB->reset_caches();
d6a1f63b
SH
1640 cache_helper::purge_all();
1641
ac7af0da 1642 // Purge all other caches: rss, simplepie, etc.
54ced30d 1643 clearstatcache();
365bec4c 1644 remove_dir($CFG->cachedir.'', true);
f87eab7e 1645
ac7af0da 1646 // Make sure cache dir is writable, throws exception if not.
5a87c912 1647 make_cache_directory('');
f87eab7e 1648
85b38061
PS
1649 // This is the only place where we purge local caches, we are only adding files there.
1650 // The $CFG->localcachedirpurged flag forces local directories to be purged on cluster nodes.
1651 remove_dir($CFG->localcachedir, true);
1652 set_config('localcachedirpurged', time());
1653 make_localcache_directory('', true);
309ae892 1654 \core\task\manager::clear_static_caches();
f87eab7e
PS
1655}
1656
bafd7e78 1657/**
1658 * Get volatile flags
1659 *
1660 * @param string $type
ac7af0da
SH
1661 * @param int $changedsince default null
1662 * @return array records array
bafd7e78 1663 */
ac7af0da 1664function get_cache_flags($type, $changedsince = null) {
ae040d4b 1665 global $DB;
bafd7e78 1666
ac7af0da 1667 $params = array('type' => $type, 'expiry' => time());
ae040d4b 1668 $sqlwhere = "flagtype = :type AND expiry >= :expiry";
ac7af0da 1669 if ($changedsince !== null) {
ae040d4b 1670 $params['changedsince'] = $changedsince;
1671 $sqlwhere .= " AND timemodified > :changedsince";
bafd7e78 1672 }
1673 $cf = array();
ae040d4b 1674 if ($flags = $DB->get_records_select('cache_flags', $sqlwhere, $params, '', 'name,value')) {
bafd7e78 1675 foreach ($flags as $flag) {
1676 $cf[$flag->name] = $flag->value;
1677 }
1678 }
1679 return $cf;
1680}
1681
a489cf72 1682/**
1683 * Get volatile flags
1684 *
1685 * @param string $type
1686 * @param string $name
ac7af0da
SH
1687 * @param int $changedsince default null
1688 * @return string|false The cache flag value or false
a489cf72 1689 */
ac7af0da 1690function get_cache_flag($type, $name, $changedsince=null) {
ae040d4b 1691 global $DB;
a489cf72 1692
ac7af0da 1693 $params = array('type' => $type, 'name' => $name, 'expiry' => time());
a489cf72 1694
ae040d4b 1695 $sqlwhere = "flagtype = :type AND name = :name AND expiry >= :expiry";
ac7af0da 1696 if ($changedsince !== null) {
ae040d4b 1697 $params['changedsince'] = $changedsince;
1698 $sqlwhere .= " AND timemodified > :changedsince";
a489cf72 1699 }
ae040d4b 1700
1701 return $DB->get_field_select('cache_flags', 'value', $sqlwhere, $params);
a489cf72 1702}
bafd7e78 1703
1704/**
1705 * Set a volatile flag
1706 *
1707 * @param string $type the "type" namespace for the key
1708 * @param string $name the key to set
ac7af0da 1709 * @param string $value the value to set (without magic quotes) - null will remove the flag
bafd7e78 1710 * @param int $expiry (optional) epoch indicating expiry - defaults to now()+ 24hs
0d0a8bf6 1711 * @return bool Always returns true
bafd7e78 1712 */
ac7af0da 1713function set_cache_flag($type, $name, $value, $expiry = null) {
ae040d4b 1714 global $DB;
bafd7e78 1715
1716 $timemodified = time();
ac7af0da 1717 if ($expiry === null || $expiry < $timemodified) {
bafd7e78 1718 $expiry = $timemodified + 24 * 60 * 60;
1719 } else {
1720 $expiry = (int)$expiry;
1721 }
1722
ac7af0da
SH
1723 if ($value === null) {
1724 unset_cache_flag($type, $name);
013376de 1725 return true;
bafd7e78 1726 }
1727
ac7af0da
SH
1728 if ($f = $DB->get_record('cache_flags', array('name' => $name, 'flagtype' => $type), '*', IGNORE_MULTIPLE)) {
1729 // This is a potential problem in DEBUG_DEVELOPER.
128f0984 1730 if ($f->value == $value and $f->expiry == $expiry and $f->timemodified == $timemodified) {
ac7af0da 1731 return true; // No need to update.
128f0984 1732 }
ae040d4b 1733 $f->value = $value;
bafd7e78 1734 $f->expiry = $expiry;
1735 $f->timemodified = $timemodified;
013376de 1736 $DB->update_record('cache_flags', $f);
bafd7e78 1737 } else {
365a5941 1738 $f = new stdClass();
bafd7e78 1739 $f->flagtype = $type;
1740 $f->name = $name;
ae040d4b 1741 $f->value = $value;
bafd7e78 1742 $f->expiry = $expiry;
1743 $f->timemodified = $timemodified;
013376de 1744 $DB->insert_record('cache_flags', $f);
bafd7e78 1745 }
013376de 1746 return true;
bafd7e78 1747}
1748
1749/**
1750 * Removes a single volatile flag
1751 *
1752 * @param string $type the "type" namespace for the key
1753 * @param string $name the key to set
bafd7e78 1754 * @return bool
1755 */
1756function unset_cache_flag($type, $name) {
ae040d4b 1757 global $DB;
ac7af0da 1758 $DB->delete_records('cache_flags', array('name' => $name, 'flagtype' => $type));
013376de 1759 return true;
bafd7e78 1760}
1761
1762/**
1763 * Garbage-collect volatile flags
1764 *
0d0a8bf6 1765 * @return bool Always returns true
bafd7e78 1766 */
1767function gc_cache_flags() {
ae040d4b 1768 global $DB;
013376de 1769 $DB->delete_records_select('cache_flags', 'expiry < ?', array(time()));
1770 return true;
bafd7e78 1771}
a4080313 1772
ac7af0da 1773// USER PREFERENCE API.
2660377f 1774
7cf1c7bd 1775/**
39461de3
PS
1776 * Refresh user preference cache. This is used most often for $USER
1777 * object that is stored in session, but it also helps with performance in cron script.
0d0a8bf6 1778 *
39461de3
PS
1779 * Preferences for each user are loaded on first use on every page, then again after the timeout expires.
1780 *
4d6b40a0
GGC
1781 * @package core
1782 * @category preference
1783 * @access public
1784 * @param stdClass $user User object. Preferences are preloaded into 'preference' property
1785 * @param int $cachelifetime Cache life time on the current page (in seconds)
1786 * @throws coding_exception
1787 * @return null
7cf1c7bd 1788 */
39461de3
PS
1789function check_user_preferences_loaded(stdClass $user, $cachelifetime = 120) {
1790 global $DB;
ac7af0da
SH
1791 // Static cache, we need to check on each page load, not only every 2 minutes.
1792 static $loadedusers = array();
2660377f 1793
39461de3
PS
1794 if (!isset($user->id)) {
1795 throw new coding_exception('Invalid $user parameter in check_user_preferences_loaded() call, missing id field');
1796 }
2660377f 1797
39461de3 1798 if (empty($user->id) or isguestuser($user->id)) {
ac7af0da 1799 // No permanent storage for not-logged-in users and guest.
39461de3
PS
1800 if (!isset($user->preference)) {
1801 $user->preference = array();
2660377f 1802 }
39461de3 1803 return;
2660377f 1804 }
70812e39 1805
39461de3 1806 $timenow = time();
070e2616 1807
39461de3
PS
1808 if (isset($loadedusers[$user->id]) and isset($user->preference) and isset($user->preference['_lastloaded'])) {
1809 // Already loaded at least once on this page. Are we up to date?
1810 if ($user->preference['_lastloaded'] + $cachelifetime > $timenow) {
ac7af0da 1811 // No need to reload - we are on the same page and we loaded prefs just a moment ago.
39461de3 1812 return;
70812e39 1813
39461de3 1814 } else if (!get_cache_flag('userpreferenceschanged', $user->id, $user->preference['_lastloaded'])) {
ac7af0da 1815 // No change since the lastcheck on this page.
39461de3
PS
1816 $user->preference['_lastloaded'] = $timenow;
1817 return;
70812e39 1818 }
c6d15803 1819 }
346c3e2f 1820
ac7af0da 1821 // OK, so we have to reload all preferences.
39461de3 1822 $loadedusers[$user->id] = true;
ac7af0da 1823 $user->preference = $DB->get_records_menu('user_preferences', array('userid' => $user->id), '', 'name,value'); // All values.
39461de3 1824 $user->preference['_lastloaded'] = $timenow;
2660377f 1825}
1826
1827/**
ac7af0da 1828 * Called from set/unset_user_preferences, so that the prefs can be correctly reloaded in different sessions.
39461de3
PS
1829 *
1830 * NOTE: internal function, do not call from other code.
0d0a8bf6 1831 *
4d6b40a0 1832 * @package core
ac7af0da
SH
1833 * @access private
1834 * @param integer $userid the user whose prefs were changed.
2660377f 1835 */
1836function mark_user_preferences_changed($userid) {
39461de3
PS
1837 global $CFG;
1838
1839 if (empty($userid) or isguestuser($userid)) {
ac7af0da 1840 // No cache flags for guest and not-logged-in users.
39461de3 1841 return;
2660377f 1842 }
39461de3 1843
2660377f 1844 set_cache_flag('userpreferenceschanged', $userid, 1, time() + $CFG->sessiontimeout);
70812e39 1845}
1846
7cf1c7bd 1847/**
39461de3 1848 * Sets a preference for the specified user.
0d0a8bf6 1849 *
4d6b40a0 1850 * If a $user object is submitted it's 'preference' property is used for the preferences cache.
0d0a8bf6 1851 *
4d6b40a0
GGC
1852 * @package core
1853 * @category preference
1854 * @access public
1855 * @param string $name The key to set as preference for the specified user
1856 * @param string $value The value to set for the $name key in the specified user's
1857 * record, null means delete current value.
1858 * @param stdClass|int|null $user A moodle user object or id, null means current user
1859 * @throws coding_exception
1860 * @return bool Always true or exception
7cf1c7bd 1861 */
39461de3 1862function set_user_preference($name, $value, $user = null) {
ae040d4b 1863 global $USER, $DB;
70812e39 1864
39461de3
PS
1865 if (empty($name) or is_numeric($name) or $name === '_lastloaded') {
1866 throw new coding_exception('Invalid preference name in set_user_preference() call');
70812e39 1867 }
1868
39461de3 1869 if (is_null($value)) {
ac7af0da 1870 // Null means delete current.
39461de3
PS
1871 return unset_user_preference($name, $user);
1872 } else if (is_object($value)) {
1873 throw new coding_exception('Invalid value in set_user_preference() call, objects are not allowed');
1874 } else if (is_array($value)) {
1875 throw new coding_exception('Invalid value in set_user_preference() call, arrays are not allowed');
1876 }
ac7af0da 1877 // Value column maximum length is 1333 characters.
39461de3 1878 $value = (string)$value;
2f1e464a 1879 if (core_text::strlen($value) > 1333) {
8e54ce97
AD
1880 throw new coding_exception('Invalid value in set_user_preference() call, value is is too long for the value column');
1881 }
39461de3
PS
1882
1883 if (is_null($user)) {
1884 $user = $USER;
1885 } else if (isset($user->id)) {
ac7af0da 1886 // It is a valid object.
39461de3 1887 } else if (is_numeric($user)) {
ac7af0da 1888 $user = (object)array('id' => (int)$user);
346c3e2f 1889 } else {
39461de3 1890 throw new coding_exception('Invalid $user parameter in set_user_preference() call');
346c3e2f 1891 }
1892
39461de3
PS
1893 check_user_preferences_loaded($user);
1894
1895 if (empty($user->id) or isguestuser($user->id)) {
ac7af0da 1896 // No permanent storage for not-logged-in users and guest.
39461de3
PS
1897 $user->preference[$name] = $value;
1898 return true;
1899 }
346c3e2f 1900
ac7af0da 1901 if ($preference = $DB->get_record('user_preferences', array('userid' => $user->id, 'name' => $name))) {
39461de3 1902 if ($preference->value === $value and isset($user->preference[$name]) and $user->preference[$name] === $value) {
ac7af0da 1903 // Preference already set to this value.
a1244706 1904 return true;
1905 }
ac7af0da 1906 $DB->set_field('user_preferences', 'value', $value, array('id' => $preference->id));
70812e39 1907
1908 } else {
365a5941 1909 $preference = new stdClass();
39461de3 1910 $preference->userid = $user->id;
ae040d4b 1911 $preference->name = $name;
39461de3 1912 $preference->value = $value;
013376de 1913 $DB->insert_record('user_preferences', $preference);
2660377f 1914 }
1915
ac7af0da 1916 // Update value in cache.
39461de3
PS
1917 $user->preference[$name] = $value;
1918
ac7af0da 1919 // Set reload flag for other sessions.
39461de3 1920 mark_user_preferences_changed($user->id);
346c3e2f 1921
013376de 1922 return true;
2660377f 1923}
1924
1925/**
1926 * Sets a whole array of preferences for the current user
0d0a8bf6 1927 *
4d6b40a0 1928 * If a $user object is submitted it's 'preference' property is used for the preferences cache.
39461de3 1929 *
4d6b40a0
GGC
1930 * @package core
1931 * @category preference
1932 * @access public
1933 * @param array $prefarray An array of key/value pairs to be set
1934 * @param stdClass|int|null $user A moodle user object or id, null means current user
1935 * @return bool Always true or exception
2660377f 1936 */
39461de3 1937function set_user_preferences(array $prefarray, $user = null) {
2660377f 1938 foreach ($prefarray as $name => $value) {
39461de3 1939 set_user_preference($name, $value, $user);
2660377f 1940 }
013376de 1941 return true;
70812e39 1942}
1943
6eb3e776 1944/**
1945 * Unsets a preference completely by deleting it from the database
0d0a8bf6 1946 *
4d6b40a0 1947 * If a $user object is submitted it's 'preference' property is used for the preferences cache.
0d0a8bf6 1948 *
4d6b40a0
GGC
1949 * @package core
1950 * @category preference
1951 * @access public
1952 * @param string $name The key to unset as preference for the specified user
1953 * @param stdClass|int|null $user A moodle user object or id, null means current user
1954 * @throws coding_exception
1955 * @return bool Always true or exception
6eb3e776 1956 */
39461de3 1957function unset_user_preference($name, $user = null) {
ae040d4b 1958 global $USER, $DB;
6eb3e776 1959
39461de3
PS
1960 if (empty($name) or is_numeric($name) or $name === '_lastloaded') {
1961 throw new coding_exception('Invalid preference name in unset_user_preference() call');
1962 }
1963
1964 if (is_null($user)) {
1965 $user = $USER;
1966 } else if (isset($user->id)) {
ac7af0da 1967 // It is a valid object.
39461de3 1968 } else if (is_numeric($user)) {
ac7af0da 1969 $user = (object)array('id' => (int)$user);
346c3e2f 1970 } else {
39461de3 1971 throw new coding_exception('Invalid $user parameter in unset_user_preference() call');
346c3e2f 1972 }
1973
39461de3 1974 check_user_preferences_loaded($user);
013376de 1975
39461de3 1976 if (empty($user->id) or isguestuser($user->id)) {
ac7af0da 1977 // No permanent storage for not-logged-in user and guest.
39461de3
PS
1978 unset($user->preference[$name]);
1979 return true;
70812e39 1980 }
1981
ac7af0da
SH
1982 // Delete from DB.
1983 $DB->delete_records('user_preferences', array('userid' => $user->id, 'name' => $name));
39461de3 1984
ac7af0da 1985 // Delete the preference from cache.
39461de3
PS
1986 unset($user->preference[$name]);
1987
ac7af0da 1988 // Set reload flag for other sessions.
39461de3
PS
1989 mark_user_preferences_changed($user->id);
1990
013376de 1991 return true;
70812e39 1992}
1993
7cf1c7bd 1994/**
0d0a8bf6 1995 * Used to fetch user preference(s)
1996 *
7cf1c7bd 1997 * If no arguments are supplied this function will return
361855e6 1998 * all of the current user preferences as an array.
0d0a8bf6 1999 *
7cf1c7bd 2000 * If a name is specified then this function
2001 * attempts to return that particular preference value. If
2002 * none is found, then the optional value $default is returned,
ac7af0da 2003 * otherwise null.
0d0a8bf6 2004 *
4d6b40a0 2005 * If a $user object is submitted it's 'preference' property is used for the preferences cache.
39461de3 2006 *
4d6b40a0
GGC
2007 * @package core
2008 * @category preference
2009 * @access public
2010 * @param string $name Name of the key to use in finding a preference value
2011 * @param mixed|null $default Value to be returned if the $name key is not set in the user preferences
2012 * @param stdClass|int|null $user A moodle user object or id, null means current user
2013 * @throws coding_exception
2014 * @return string|mixed|null A string containing the value of a single preference. An
2015 * array with all of the preferences or null
7cf1c7bd 2016 */
39461de3
PS
2017function get_user_preferences($name = null, $default = null, $user = null) {
2018 global $USER;
70812e39 2019
39461de3 2020 if (is_null($name)) {
ac7af0da 2021 // All prefs.
39461de3
PS
2022 } else if (is_numeric($name) or $name === '_lastloaded') {
2023 throw new coding_exception('Invalid preference name in get_user_preferences() call');
2024 }
346c3e2f 2025
39461de3
PS
2026 if (is_null($user)) {
2027 $user = $USER;
2028 } else if (isset($user->id)) {
ac7af0da 2029 // Is a valid object.
39461de3 2030 } else if (is_numeric($user)) {
ac7af0da 2031 $user = (object)array('id' => (int)$user);
39461de3
PS
2032 } else {
2033 throw new coding_exception('Invalid $user parameter in get_user_preferences() call');
2034 }
2035
2036 check_user_preferences_loaded($user);
346c3e2f 2037
39461de3 2038 if (empty($name)) {
ac7af0da
SH
2039 // All values.
2040 return $user->preference;
39461de3 2041 } else if (isset($user->preference[$name])) {
ac7af0da
SH
2042 // The single string value.
2043 return $user->preference[$name];
346c3e2f 2044 } else {
ac7af0da
SH
2045 // Default value (null if not specified).
2046 return $default;
70812e39 2047 }
70812e39 2048}
2049
ac7af0da 2050// FUNCTIONS FOR HANDLING TIME.
39917a09 2051
7cf1c7bd 2052/**
e83bcc10 2053 * Given Gregorian date parts in user time produce a GMT timestamp.
7cf1c7bd 2054 *
9df12115
RT
2055 * @package core
2056 * @category time
68fbd8e1 2057 * @param int $year The year part to create timestamp of
2058 * @param int $month The month part to create timestamp of
2059 * @param int $day The day part to create timestamp of
2060 * @param int $hour The hour part to create timestamp of
2061 * @param int $minute The minute part to create timestamp of
2062 * @param int $second The second part to create timestamp of
9df12115
RT
2063 * @param int|float|string $timezone Timezone modifier, used to calculate GMT time offset.
2064 * if 99 then default user's timezone is used {@link http://docs.moodle.org/dev/Time_API#Timezone}
6a0bf5c4
RT
2065 * @param bool $applydst Toggle Daylight Saving Time, default true, will be
2066 * applied only if timezone is 99 or string.
9df12115 2067 * @return int GMT timestamp
7cf1c7bd 2068 */
9f1f6daf 2069function make_timestamp($year, $month=1, $day=1, $hour=0, $minute=0, $second=0, $timezone=99, $applydst=true) {
d6e7a63d
PS
2070 $date = new DateTime('now', core_date::get_user_timezone_object($timezone));
2071 $date->setDate((int)$year, (int)$month, (int)$day);
2072 $date->setTime((int)$hour, (int)$minute, (int)$second);
39917a09 2073
d6e7a63d 2074 $time = $date->getTimestamp();
33998d30 2075
9f2b916d
RT
2076 if ($time === false) {
2077 throw new coding_exception('getTimestamp() returned false, please ensure you have passed correct values.'.
2078 ' This can fail if year is more than 2038 and OS is 32 bit windows');
2079 }
2080
d6e7a63d
PS
2081 // Moodle BC DST stuff.
2082 if (!$applydst) {
2083 $time += dst_offset_on($time, $timezone);
9f1f6daf 2084 }
2085
196f2619 2086 return $time;
85cafb3e 2087
39917a09 2088}
2089
7cf1c7bd 2090/**
0d0a8bf6 2091 * Format a date/time (seconds) as weeks, days, hours etc as needed
2092 *
7cf1c7bd 2093 * Given an amount of time in seconds, returns string
5602f7cf 2094 * formatted nicely as weeks, days, hours etc as needed
7cf1c7bd 2095 *
9df12115
RT
2096 * @package core
2097 * @category time
2f87145b 2098 * @uses MINSECS
2099 * @uses HOURSECS
2100 * @uses DAYSECS
5602f7cf 2101 * @uses YEARSECS
0d0a8bf6 2102 * @param int $totalsecs Time in seconds
ac7af0da 2103 * @param stdClass $str Should be a time object
0d0a8bf6 2104 * @return string A nicely formatted date/time string
7cf1c7bd 2105 */
ac7af0da 2106function format_time($totalsecs, $str = null) {
c7e3ac2a 2107
6b174680 2108 $totalsecs = abs($totalsecs);
c7e3ac2a 2109
ac7af0da
SH
2110 if (!$str) {
2111 // Create the str structure the slow way.
b85b25eb 2112 $str = new stdClass();
b0ccd3fb 2113 $str->day = get_string('day');
2114 $str->days = get_string('days');
2115 $str->hour = get_string('hour');
2116 $str->hours = get_string('hours');
2117 $str->min = get_string('min');
2118 $str->mins = get_string('mins');
2119 $str->sec = get_string('sec');
2120 $str->secs = get_string('secs');
5602f7cf 2121 $str->year = get_string('year');
2122 $str->years = get_string('years');
8dbed6be 2123 }
2124
5602f7cf 2125 $years = floor($totalsecs/YEARSECS);
2126 $remainder = $totalsecs - ($years*YEARSECS);
5602f7cf 2127 $days = floor($remainder/DAYSECS);
7a5672c9 2128 $remainder = $totalsecs - ($days*DAYSECS);
2129 $hours = floor($remainder/HOURSECS);
2130 $remainder = $remainder - ($hours*HOURSECS);
2131 $mins = floor($remainder/MINSECS);
2132 $secs = $remainder - ($mins*MINSECS);
8dbed6be 2133
2134 $ss = ($secs == 1) ? $str->sec : $str->secs;
2135 $sm = ($mins == 1) ? $str->min : $str->mins;
2136 $sh = ($hours == 1) ? $str->hour : $str->hours;
2137 $sd = ($days == 1) ? $str->day : $str->days;
5602f7cf 2138 $sy = ($years == 1) ? $str->year : $str->years;
8dbed6be 2139
5602f7cf 2140 $oyears = '';
b0ccd3fb 2141 $odays = '';
2142 $ohours = '';
2143 $omins = '';
2144 $osecs = '';
9c9f7d77 2145
ac7af0da
SH
2146 if ($years) {
2147 $oyears = $years .' '. $sy;
2148 }
2149 if ($days) {
2150 $odays = $days .' '. $sd;
2151 }
2152 if ($hours) {
2153 $ohours = $hours .' '. $sh;
2154 }
2155 if ($mins) {
2156 $omins = $mins .' '. $sm;
2157 }
2158 if ($secs) {
2159 $osecs = $secs .' '. $ss;
2160 }
2161
2162 if ($years) {
2163 return trim($oyears .' '. $odays);
2164 }
2165 if ($days) {
2166 return trim($odays .' '. $ohours);
2167 }
2168 if ($hours) {
2169 return trim($ohours .' '. $omins);
2170 }
2171 if ($mins) {
2172 return trim($omins .' '. $osecs);
2173 }
2174 if ($secs) {
2175 return $osecs;
2176 }
b0ccd3fb 2177 return get_string('now');
6b174680 2178}
f9903ed0 2179
7cf1c7bd 2180/**
f59ab4ad 2181 * Returns a formatted string that represents a date in user time.
7cf1c7bd 2182 *
9df12115
RT
2183 * @package core
2184 * @category time
0a0cf09a 2185 * @param int $date the timestamp in UTC, as obtained from the database.
2186 * @param string $format strftime format. You should probably get this using
9df12115 2187 * get_string('strftime...', 'langconfig');
f59ab4ad 2188 * @param int|float|string $timezone by default, uses the user's time zone. if numeric and
9df12115
RT
2189 * not 99 then daylight saving will not be added.
2190 * {@link http://docs.moodle.org/dev/Time_API#Timezone}
0a0cf09a 2191 * @param bool $fixday If true (default) then the leading zero from %d is removed.
9df12115 2192 * If false then the leading zero is maintained.
d9498b38 2193 * @param bool $fixhour If true (default) then the leading zero from %I is removed.
0a0cf09a 2194 * @return string the formatted date/time.
7cf1c7bd 2195 */
d9498b38 2196function userdate($date, $format = '', $timezone = 99, $fixday = true, $fixhour = true) {
6eafa4dd 2197 $calendartype = \core_calendar\type_factory::get_calendar_instance();
f59ab4ad 2198 return $calendartype->timestamp_to_date_string($date, $format, $timezone, $fixday, $fixhour);
873960de 2199}
2200
15396bba
FM
2201/**
2202 * Returns a formatted date ensuring it is UTF-8.
2203 *
2204 * If we are running under Windows convert to Windows encoding and then back to UTF-8
2205 * (because it's impossible to specify UTF-8 to fetch locale info in Win32).
2206 *
d6e7a63d 2207 * @param int $date the timestamp - since Moodle 2.9 this is a real UTC timestamp
15396bba 2208 * @param string $format strftime format.
d6e7a63d 2209 * @param int|float|string $tz the user timezone
15396bba 2210 * @return string the formatted date/time.
5bcfd504 2211 * @since Moodle 2.3.3
15396bba
FM
2212 */
2213function date_format_string($date, $format, $tz = 99) {
2214 global $CFG;
d61d3e82
RT
2215
2216 $localewincharset = null;
2217 // Get the calendar type user is using.
2218 if ($CFG->ostype == 'WINDOWS') {
2219 $calendartype = \core_calendar\type_factory::get_calendar_instance();
2220 $localewincharset = $calendartype->locale_win_charset();
2221 }
2222
d6e7a63d
PS
2223 if ($localewincharset) {
2224 $format = core_text::convert($format, 'utf-8', $localewincharset);
2225 }
2226
2227 date_default_timezone_set(core_date::get_user_timezone($tz));
2228 $datestring = strftime($format, $date);
2229 core_date::set_default_server_timezone();
2230
2231 if ($localewincharset) {
2232 $datestring = core_text::convert($datestring, $localewincharset, 'utf-8');
15396bba 2233 }
d6e7a63d 2234
15396bba
FM
2235 return $datestring;
2236}
2237
7cf1c7bd 2238/**
deed22ea 2239 * Given a $time timestamp in GMT (seconds since epoch),
40a6393e 2240 * returns an array that represents the Gregorian date in user time
7cf1c7bd 2241 *
9df12115
RT
2242 * @package core
2243 * @category time
deed22ea 2244 * @param int $time Timestamp in GMT
d6e7a63d 2245 * @param float|int|string $timezone user timezone
deed22ea 2246 * @return array An array that represents the date in user time
7cf1c7bd 2247 */
deed22ea 2248function usergetdate($time, $timezone=99) {
d6e7a63d
PS
2249 date_default_timezone_set(core_date::get_user_timezone($timezone));
2250 $result = getdate($time);
2251 core_date::set_default_server_timezone();
deed22ea 2252
d6e7a63d 2253 return $result;
d552ead0 2254}
2255
7cf1c7bd 2256/**
2257 * Given a GMT timestamp (seconds since epoch), offsets it by
2258 * the timezone. eg 3pm in India is 3pm GMT - 7 * 3600 seconds
2259 *
d6e7a63d
PS
2260 * NOTE: this function does not include DST properly,
2261 * you should use the PHP date stuff instead!
2262 *
9df12115
RT
2263 * @package core
2264 * @category time
9df12115 2265 * @param int $date Timestamp in GMT
d6e7a63d 2266 * @param float|int|string $timezone user timezone
c6d15803 2267 * @return int
7cf1c7bd 2268 */
d552ead0 2269function usertime($date, $timezone=99) {
d6e7a63d
PS
2270 $userdate = new DateTime('@' . $date);
2271 $userdate->setTimezone(core_date::get_user_timezone_object($timezone));
2272 $dst = dst_offset_on($date, $timezone);
a36166d3 2273
d6e7a63d 2274 return $date - $userdate->getOffset() + $dst;
d552ead0 2275}
2276
8c3dba73 2277/**
2278 * Given a time, return the GMT timestamp of the most recent midnight
2279 * for the current user.
2280 *
9df12115
RT
2281 * @package core
2282 * @category time
e34d817e 2283 * @param int $date Timestamp in GMT
d6e7a63d 2284 * @param float|int|string $timezone user timezone
0d0a8bf6 2285 * @return int Returns a GMT timestamp
8c3dba73 2286 */
edf7fe8c 2287function usergetmidnight($date, $timezone=99) {
edf7fe8c 2288
edf7fe8c 2289 $userdate = usergetdate($date, $timezone);
4606d9bb 2290
ac7af0da 2291 // Time of midnight of this user's day, in GMT.
02f0527d 2292 return make_timestamp($userdate['year'], $userdate['mon'], $userdate['mday'], 0, 0, 0, $timezone);
edf7fe8c 2293
2294}
2295
7cf1c7bd 2296/**
2297 * Returns a string that prints the user's timezone
2298 *
9df12115
RT
2299 * @package core
2300 * @category time
d6e7a63d 2301 * @param float|int|string $timezone user timezone
7cf1c7bd 2302 * @return string
2303 */
d552ead0 2304function usertimezone($timezone=99) {
d6e7a63d
PS
2305 $tz = core_date::get_user_timezone($timezone);
2306 return core_date::get_localised_timezone($tz);
61460dd6 2307}
2308
bbd3f2c4 2309/**
b2b68362 2310 * Returns a float or a string which denotes the user's timezone
2311 * 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)
2312 * means that for this timezone there are also DST rules to be taken into account
2313 * Checks various settings and picks the most dominant of those which have a value
bbd3f2c4 2314 *
9df12115
RT
2315 * @package core
2316 * @category time
2317 * @param float|int|string $tz timezone to calculate GMT time offset before
2318 * calculating user timezone, 99 is default user timezone
2319 * {@link http://docs.moodle.org/dev/Time_API#Timezone}
2320 * @return float|string
bbd3f2c4 2321 */
e8904995 2322function get_user_timezone($tz = 99) {
2323 global $USER, $CFG;
43b59916 2324
f30fe8d0 2325 $timezones = array(
e8904995 2326 $tz,
2327 isset($CFG->forcetimezone) ? $CFG->forcetimezone : 99,
43b59916 2328 isset($USER->timezone) ? $USER->timezone : 99,
2329 isset($CFG->timezone) ? $CFG->timezone : 99,
f30fe8d0 2330 );
43b59916 2331
e8904995 2332 $tz = 99;
43b59916 2333
ac7af0da
SH
2334 // Loop while $tz is, empty but not zero, or 99, and there is another timezone is the array.
2335 while (((empty($tz) && !is_numeric($tz)) || $tz == 99) && $next = each($timezones)) {
e8904995 2336 $tz = $next['value'];
43b59916 2337 }
e8904995 2338 return is_numeric($tz) ? (float) $tz : $tz;
43b59916 2339}
2340
0d0a8bf6 2341/**
efb8c375 2342 * Calculates the Daylight Saving Offset for a given date/time (timestamp)
6a0bf5c4 2343 * - Note: Daylight saving only works for string timezones and not for float.
0d0a8bf6 2344 *
9df12115
RT
2345 * @package core
2346 * @category time
0d0a8bf6 2347 * @param int $time must NOT be compensated at all, it has to be a pure timestamp
d6e7a63d 2348 * @param int|float|string $strtimezone user timezone
0d0a8bf6 2349 * @return int
2350 */
ac7af0da 2351function dst_offset_on($time, $strtimezone = null) {
d6e7a63d
PS
2352 $tz = core_date::get_user_timezone($strtimezone);
2353 $date = new DateTime('@' . $time);
2354 $date->setTimezone(new DateTimeZone($tz));
2355 if ($date->format('I') == '1') {
2356 if ($tz === 'Australia/Lord_Howe') {
2357 return 1800;
c9e72798 2358 }
d6e7a63d 2359 return 3600;
c9e72798 2360 }
d6e7a63d 2361 return 0;
85cafb3e 2362}
02f0527d 2363
0d0a8bf6 2364/**
9df12115 2365 * Calculates when the day appears in specific month
0d0a8bf6 2366 *
9df12115
RT
2367 * @package core
2368 * @category time
2369 * @param int $startday starting day of the month
2370 * @param int $weekday The day when week starts (normally taken from user preferences)
2371 * @param int $month The month whose day is sought
2372 * @param int $year The year of the month whose day is sought
0d0a8bf6 2373 * @return int
2374 */
28902d99 2375function find_day_in_month($startday, $weekday, $month, $year) {
da304137 2376 $calendartype = \core_calendar\type_factory::get_calendar_instance();
8dc3f6cf 2377
2378 $daysinmonth = days_in_month($month, $year);
da304137 2379 $daysinweek = count($calendartype->get_weekdays());
8dc3f6cf 2380
ac7af0da 2381 if ($weekday == -1) {
28902d99 2382 // Don't care about weekday, so return:
2383 // abs($startday) if $startday != -1
ac7af0da 2384 // $daysinmonth otherwise.
28902d99 2385 return ($startday == -1) ? $daysinmonth : abs($startday);
8dc3f6cf 2386 }
2387
ac7af0da 2388 // From now on we 're looking for a specific weekday.
ac7af0da
SH
2389 // Give "end of month" its actual value, since we know it.
2390 if ($startday == -1) {
28902d99 2391 $startday = -1 * $daysinmonth;
2392 }
2393
ac7af0da 2394 // Starting from day $startday, the sign is the direction.
ac7af0da 2395 if ($startday < 1) {
28902d99 2396 $startday = abs($startday);
da304137 2397 $lastmonthweekday = dayofweek($daysinmonth, $month, $year);
8dc3f6cf 2398
ac7af0da 2399 // This is the last such weekday of the month.
8dc3f6cf 2400 $lastinmonth = $daysinmonth + $weekday - $lastmonthweekday;
ac7af0da 2401 if ($lastinmonth > $daysinmonth) {
da304137 2402 $lastinmonth -= $daysinweek;
42d36497 2403 }
8dc3f6cf 2404
ac7af0da
SH
2405 // Find the first such weekday <= $startday.
2406 while ($lastinmonth > $startday) {
da304137 2407 $lastinmonth -= $daysinweek;
42d36497 2408 }
8dc3f6cf 2409
2410 return $lastinmonth;
ac7af0da 2411 } else {
da304137 2412 $indexweekday = dayofweek($startday, $month, $year);
42d36497 2413
8dc3f6cf 2414 $diff = $weekday - $indexweekday;
ac7af0da 2415 if ($diff < 0) {
da304137 2416 $diff += $daysinweek;
42d36497 2417 }
42d36497 2418
ac7af0da 2419 // This is the first such weekday of the month equal to or after $startday.
28902d99 2420 $firstfromindex = $startday + $diff;
42d36497 2421
8dc3f6cf 2422 return $firstfromindex;
8dc3f6cf 2423 }
42d36497 2424}
2425
bbd3f2c4 2426/**
2427 * Calculate the number of days in a given month
2428 *
9df12115
RT
2429 * @package core
2430 * @category time
bbd3f2c4 2431 * @param int $month The month whose day count is sought
2432 * @param int $year The year of the month whose day count is sought
2433 * @return int
2434 */
42d36497 2435function days_in_month($month, $year) {
da304137
MN
2436 $calendartype = \core_calendar\type_factory::get_calendar_instance();
2437 return $calendartype->get_num_days_in_month($year, $month);
42d36497 2438}
2439
bbd3f2c4 2440/**
2441 * Calculate the position in the week of a specific calendar day
2442 *
9df12115
RT
2443 * @package core
2444 * @category time
bbd3f2c4 2445 * @param int $day The day of the date whose position in the week is sought
2446 * @param int $month The month of the date whose position in the week is sought
2447 * @param int $year The year of the date whose position in the week is sought
2448 * @return int
2449 */
8dc3f6cf 2450function dayofweek($day, $month, $year) {
da304137
MN
2451 $calendartype = \core_calendar\type_factory::get_calendar_instance();
2452 return $calendartype->get_weekday($year, $month, $day);
8dc3f6cf 2453}
2454
ac7af0da 2455// USER AUTHENTICATION AND LOGIN.
f9903ed0 2456
93f66983 2457/**
2458 * Returns full login url.
2459 *
93f66983 2460 * @return string login url
2461 */
999b54af 2462function get_login_url() {
93f66983 2463 global $CFG;
2464
999b54af 2465 $url = "$CFG->wwwroot/login/index.php";
93f66983 2466
999b54af
PS
2467 if (!empty($CFG->loginhttps)) {
2468 $url = str_replace('http:', 'https:', $url);
93f66983 2469 }
2470
2471 return $url;
2472}
2473
7cf1c7bd 2474/**
ec81373f 2475 * This function checks that the current user is logged in and has the
2476 * required privileges
2477 *
7cf1c7bd 2478 * This function checks that the current user is logged in, and optionally
ec81373f 2479 * whether they are allowed to be in a particular course and view a particular
2480 * course module.
2481 * If they are not logged in, then it redirects them to the site login unless
d2a9f7cc 2482 * $autologinguest is set and {@link $CFG}->autologinguests is set to 1 in which
ec81373f 2483 * case they are automatically logged in as guests.
2484 * If $courseid is given and the user is not enrolled in that course then the
2485 * user is redirected to the course enrolment page.
efb8c375 2486 * If $cm is given and the course module is hidden and the user is not a teacher
ec81373f 2487 * in the course then the user is redirected to the course home page.
7cf1c7bd 2488 *
191b267b 2489 * When $cm parameter specified, this function sets page layout to 'module'.
4f0c2d00 2490 * You need to change it manually later if some other layout needed.
191b267b 2491 *
f76249cc
PS
2492 * @package core_access
2493 * @category access
2494 *
33ebaf7c 2495 * @param mixed $courseorid id of the course or course object
0d0a8bf6 2496 * @param bool $autologinguest default true
bbd3f2c4 2497 * @param object $cm course module object
f4013c10 2498 * @param bool $setwantsurltome Define if we want to set $SESSION->wantsurl, defaults to
2499 * true. Used to avoid (=false) some scripts (file.php...) to set that variable,
2500 * in order to keep redirects working properly. MDL-14495
df997f84 2501 * @param bool $preventredirect set to true in scripts that can not redirect (CLI, rss feeds, etc.), throws exceptions
0d0a8bf6 2502 * @return mixed Void, exit, and die depending on path
ac7af0da
SH
2503 * @throws coding_exception
2504 * @throws require_login_exception
7cf1c7bd 2505 */
ac7af0da 2506function require_login($courseorid = null, $autologinguest = true, $cm = null, $setwantsurltome = true, $preventredirect = false) {
f0202ae9 2507 global $CFG, $SESSION, $USER, $PAGE, $SITE, $DB, $OUTPUT;
d8ba183c 2508
f22f1caf
PS
2509 // Must not redirect when byteserving already started.
2510 if (!empty($_SERVER['HTTP_RANGE'])) {
2511 $preventredirect = true;
2512 }
2513
2ed6be87
AN
2514 if (AJAX_SCRIPT) {
2515 // We cannot redirect for AJAX scripts either.
2516 $preventredirect = true;
2517 }
2518
ac7af0da 2519 // Setup global $COURSE, themes, language and locale.
c13a5e71 2520 if (!empty($courseorid)) {
2521 if (is_object($courseorid)) {
2522 $course = $courseorid;
2523 } else if ($courseorid == SITEID) {
2524 $course = clone($SITE);
2525 } else {
74df2951 2526 $course = $DB->get_record('course', array('id' => $courseorid), '*', MUST_EXIST);
c13a5e71 2527 }
95d28870 2528 if ($cm) {
df997f84
PS
2529 if ($cm->course != $course->id) {
2530 throw new coding_exception('course and cm parameters in require_login() call do not match!!');
2531 }
ac7af0da 2532 // Make sure we have a $cm from get_fast_modinfo as this contains activity access details.
47148151 2533 if (!($cm instanceof cm_info)) {
ac7af0da 2534 // Note: nearly all pages call get_fast_modinfo anyway and it does not make any
0d8b6a69 2535 // db queries so this is not really a performance concern, however it is obviously
2536 // better if you use get_fast_modinfo to get the cm before calling this.
2537 $modinfo = get_fast_modinfo($course);
2538 $cm = $modinfo->get_cm($cm->id);
2539 }
95d28870 2540 }
e88462a0 2541 } else {
ac7af0da 2542 // Do not touch global $COURSE via $PAGE->set_course(),
df997f84
PS
2543 // the reasons is we need to be able to call require_login() at any time!!
2544 $course = $SITE;
2545 if ($cm) {
2546 throw new coding_exception('cm parameter in require_login() requires valid course parameter!');
2547 }
c13a5e71 2548 }
be933850 2549
aa4a6566
SH
2550 // If this is an AJAX request and $setwantsurltome is true then we need to override it and set it to false.
2551 // Otherwise the AJAX request URL will be set to $SESSION->wantsurl and events such as self enrolment in the future
2552 // risk leading the user back to the AJAX request URL.
2553 if ($setwantsurltome && defined('AJAX_SCRIPT') && AJAX_SCRIPT) {
2554 $setwantsurltome = false;
2555 }
2556
12fc11e7 2557 // Redirect to the login page if session has expired, only with dbsessions enabled (MDL-35029) to maintain current behaviour.
2ed6be87
AN
2558 if ((!isloggedin() or isguestuser()) && !empty($SESSION->has_timed_out) && !empty($CFG->dbsessions)) {
2559 if ($preventredirect) {
2560 throw new require_login_session_timeout_exception();
2561 } else {
2562 if ($setwantsurltome) {
2563 $SESSION->wantsurl = qualified_me();
2564 }
2565 redirect(get_login_url());
12fc11e7 2566 }
12fc11e7
DM
2567 }
2568
ac7af0da 2569 // If the user is not even logged in yet then make sure they are.
083c3743 2570 if (!isloggedin()) {
df997f84 2571 if ($autologinguest and !empty($CFG->guestloginbutton) and !empty($CFG->autologinguests)) {
999b54af 2572 if (!$guest = get_complete_user_data('id', $CFG->siteguest)) {
ac7af0da 2573 // Misconfigured site guest, just redirect to login page.
999b54af 2574 redirect(get_login_url());
ac7af0da 2575 exit; // Never reached.
df997f84 2576 }
999b54af 2577 $lang = isset($SESSION->lang) ? $SESSION->lang : $CFG->lang;
0342fc36 2578 complete_user_login($guest);
d9e07264 2579 $USER->autologinguest = true;
999b54af 2580 $SESSION->lang = $lang;
8a33e371 2581 } else {
ac7af0da 2582 // NOTE: $USER->site check was obsoleted by session test cookie, $USER->confirmed test is in login/index.php.
999b54af
PS
2583 if ($preventredirect) {
2584 throw new require_login_exception('You are not logged in');
2585 }
2586
2587 if ($setwantsurltome) {
f0202ae9 2588 $SESSION->wantsurl = qualified_me();
999b54af 2589 }
dcee0b94
SL
2590
2591 $referer = get_local_referer(false);
2592 if (!empty($referer)) {
2593 $SESSION->fromurl = $referer;
999b54af 2594 }
bf08e3f9
BH
2595
2596 // Give auth plugins an opportunity to authenticate or redirect to an external login page
2597 $authsequence = get_enabled_auth_plugins(true); // auths, in sequence
2598 foreach($authsequence as $authname) {
2599 $authplugin = get_auth_plugin($authname);
2600 $authplugin->pre_loginpage_hook();
2601 if (isloggedin()) {
2602 break;
2603 }
2604 }
2605
2606 // If we're still not logged in then go to the login page
2607 if (!isloggedin()) {
2608 redirect(get_login_url());
2609 exit; // Never reached.
2610 }
8a33e371 2611 }
f9903ed0 2612 }
808a3baa 2613
ac7af0da 2614 // Loginas as redirection if needed.
d79d5ac2 2615 if ($course->id != SITEID and \core\session\manager::is_loggedinas()) {
f6f66b03 2616 if ($USER->loginascontext->contextlevel == CONTEXT_COURSE) {
df997f84 2617 if ($USER->loginascontext->instanceid != $course->id) {
3887fe4a 2618 print_error('loginasonecourse', '', $CFG->wwwroot.'/course/view.php?id='.$USER->loginascontext->instanceid);
5e623a33 2619 }
f6f66b03 2620 }
2621 }
2622
ac7af0da 2623 // Check whether the user should be changing password (but only if it is REALLY them).
d79d5ac2 2624 if (get_user_preferences('auth_forcepasswordchange') && !\core\session\manager::is_loggedinas()) {
21e2dcd9 2625 $userauth = get_auth_plugin($USER->auth);
df997f84 2626 if ($userauth->can_change_password() and !$preventredirect) {
af572078 2627 if ($setwantsurltome) {
f0202ae9 2628 $SESSION->wantsurl = qualified_me();
af572078 2629 }
80274abf 2630 if ($changeurl = $userauth->change_password_url()) {
ac7af0da 2631 // Use plugin custom url.
80274abf 2632 redirect($changeurl);
1437f0a5 2633 } else {
ac7af0da 2634 // Use moodle internal method.
9696bd89 2635 if (empty($CFG->loginhttps)) {
2636 redirect($CFG->wwwroot .'/login/change_password.php');
2637 } else {
ac7af0da 2638 $wwwroot = str_replace('http:', 'https:', $CFG->wwwroot);
9696bd89 2639 redirect($wwwroot .'/login/change_password.php');
2640 }
1437f0a5 2641 }
d35757eb 2642 } else {
a8ee7194 2643 print_error('nopasswordchangeforced', 'auth');
d35757eb 2644 }
2645 }
083c3743 2646
8df850ad
DM
2647 // Check that the user account is properly set up. If we can't redirect to
2648 // edit their profile, perform just the lax check. It will allow them to
2649 // use filepicker on the profile edit page.
2650
2651 if ($preventredirect) {
2652 $usernotfullysetup = user_not_fully_set_up($USER, false);
2653 } else {
2654 $usernotfullysetup = user_not_fully_set_up($USER, true);
2655 }
2656
2657 if ($usernotfullysetup) {
df997f84
PS
2658 if ($preventredirect) {
2659 throw new require_login_exception('User not fully set-up');
2660 }
af572078 2661 if ($setwantsurltome) {
f0202ae9 2662 $SESSION->wantsurl = qualified_me();
af572078 2663 }
b0ccd3fb 2664 redirect($CFG->wwwroot .'/user/edit.php?id='. $USER->id .'&amp;course='. SITEID);
808a3baa 2665 }
d8ba183c 2666
df997f84 2667 // Make sure the USER has a sesskey set up. Used for CSRF protection.
04280e85 2668 sesskey();
366dfa60 2669
ac7af0da 2670 // Do not bother admins with any formalities.
df997f84 2671 if (is_siteadmin()) {
1edd3d6f
MG
2672 // Set the global $COURSE.
2673 if ($cm) {
2674 $PAGE->set_cm($cm, $course);
2675 $PAGE->set_pagelayout('incourse');
2676 } else if (!empty($courseorid)) {
2677 $PAGE->set_course($course);
2678 }
ac7af0da 2679 // Set accesstime or the user will appear offline which messes up messaging.
1560760f 2680 user_accesstime_log($course->id);
df997f84
PS
2681 return;
2682 }
2683
ac7af0da 2684 // Check that the user has agreed to a site policy if there is one - do not test in case of admins.
b593d49d
PS
2685 if (!$USER->policyagreed and !is_siteadmin()) {
2686 if (!empty($CFG->sitepolicy) and !isguestuser()) {
2687 if ($preventredirect) {
2688 throw new require_login_exception('Policy not agreed');
2689 }
af572078 2690 if ($setwantsurltome) {
f0202ae9 2691 $SESSION->wantsurl = qualified_me();
af572078 2692 }
b593d49d
PS
2693 redirect($CFG->wwwroot .'/user/policy.php');
2694 } else if (!empty($CFG->sitepolicyguest) and isguestuser()) {
2695 if ($preventredirect) {
2696 throw new require_login_exception('Policy not agreed');
2697 }
af572078 2698 if ($setwantsurltome) {
f0202ae9 2699 $SESSION->wantsurl = qualified_me();
af572078 2700 }
027a1604 2701 redirect($CFG->wwwroot .'/user/policy.php');
027a1604 2702 }
1695b680 2703 }
2704
ac7af0da 2705 // Fetch the system context, the course context, and prefetch its child contexts.
b0c6dc1c
AG
2706 $sysctx = context_system::instance();
2707 $coursecontext = context_course::instance($course->id, MUST_EXIST);
df997f84 2708 if ($cm) {
b0c6dc1c 2709 $cmcontext = context_module::instance($cm->id, MUST_EXIST);
df997f84
PS
2710 } else {
2711 $cmcontext = null;
2712 }
21e2dcd9 2713
ac7af0da 2714 // If the site is currently under maintenance, then print a message.
59c66f92 2715 if (!empty($CFG->maintenance_enabled) and !has_capability('moodle/site:maintenanceaccess', $sysctx)) {
df997f84
PS
2716 if ($preventredirect) {
2717 throw new require_login_exception('Maintenance in progress');
2718 }
a4ea86f6 2719 $PAGE->set_context(null);
4fe2250a 2720 print_maintenance_message();
027a1604 2721 }
2722
ac7af0da 2723 // Make sure the course itself is not hidden.
df997f84 2724 if ($course->id == SITEID) {
ac7af0da 2725 // Frontpage can not be hidden.
df997f84 2726 } else {
f5c1e621 2727 if (is_role_switched($course->id)) {
ac7af0da 2728 // When switching roles ignore the hidden flag - user had to be in course to do the switch.
df997f84
PS
2729 } else {
2730 if (!$course->visible and !has_capability('moodle/course:viewhiddencourses', $coursecontext)) {
ac7af0da
SH
2731 // Originally there was also test of parent category visibility, BUT is was very slow in complex queries
2732 // involving "my courses" now it is also possible to simply hide all courses user is not enrolled in :-).
df997f84
PS
2733 if ($preventredirect) {
2734 throw new require_login_exception('Course is hidden');
2735 }
1edd3d6f 2736 $PAGE->set_context(null);
ac7af0da
SH
2737 // We need to override the navigation URL as the course won't have been added to the navigation and thus
2738 // the navigation will mess up when trying to find it.
a0a39b0d 2739 navigation_node::override_active_url(new moodle_url('/'));
df997f84
PS
2740 notice(get_string('coursehidden'), $CFG->wwwroot .'/');
2741 }
2742 }
2743 }
2744
ac7af0da 2745 // Is the user enrolled?
df997f84 2746 if ($course->id == SITEID) {
ac7af0da 2747 // Everybody is enrolled on the frontpage.
df997f84 2748 } else {
d79d5ac2 2749 if (\core\session\manager::is_loggedinas()) {
ac7af0da 2750 // Make sure the REAL person can access this course first.
d79d5ac2 2751 $realuser = \core\session\manager::get_realuser();
ac7af0da
SH
2752 if (!is_enrolled($coursecontext, $realuser->id, '', true) and
2753 !is_viewing($coursecontext, $realuser->id) and !is_siteadmin($realuser->id)) {
df997f84
PS
2754 if ($preventredirect) {
2755 throw new require_login_exception('Invalid course login-as access');
2756 }
1edd3d6f 2757 $PAGE->set_context(null);
df997f84
PS
2758 echo $OUTPUT->header();
2759 notice(get_string('studentnotallowed', '', fullname($USER, true)), $CFG->wwwroot .'/');
2760 }
2761 }
2762
df997f84
PS
2763 $access = false;
2764
dbd7282c 2765 if (is_role_switched($course->id)) {
ac7af0da 2766 // Ok, user had to be inside this course before the switch.
dbd7282c
PS
2767 $access = true;
2768
2769 } else if (is_viewing($coursecontext, $USER)) {
ac7af0da 2770 // Ok, no need to mess with enrol.
df997f84
PS
2771 $access = true;
2772
2773 } else {
2774 if (isset($USER->enrol['enrolled'][$course->id])) {
bbfdff34 2775 if ($USER->enrol['enrolled'][$course->id] > time()) {
df997f84 2776 $access = true;
bbfdff34
PS
2777 if (isset($USER->enrol['tempguest'][$course->id])) {
2778 unset($USER->enrol['tempguest'][$course->id]);
2779 remove_temp_course_roles($coursecontext);
2780 }
df997f84 2781 } else {
ac7af0da 2782 // Expired.
df997f84
PS
2783 unset($USER->enrol['enrolled'][$course->id]);
2784 }
2785 }
2786 if (isset($USER->enrol['tempguest'][$course->id])) {
2787 if ($USER->enrol['tempguest'][$course->id] == 0) {
2788 $access = true;
2789 } else if ($USER->enrol['tempguest'][$course->id] > time()) {
2790 $access = true;
2791 } else {
ac7af0da 2792 // Expired.
df997f84 2793 unset($USER->enrol['tempguest'][$course->id]);
e922fe23 2794 remove_temp_course_roles($coursecontext);
df997f84
PS
2795 }
2796 }
2797
ac7af0da
SH
2798 if (!$access) {
2799 // Cache not ok.
bbfdff34
PS
2800 $until = enrol_get_enrolment_end($coursecontext->instanceid, $USER->id);
2801 if ($until !== false) {
ac7af0da 2802 // Active participants may always access, a timestamp in the future, 0 (always) or false.
bbfdff34
PS
2803 if ($until == 0) {
2804 $until = ENROL_MAX_TIMESTAMP;
df997f84 2805 }
bbfdff34
PS
2806 $USER->enrol['enrolled'][$course->id] = $until;
2807 $access = true;
2808
2809 } else {
ac7af0da
SH
2810 $params = array('courseid' => $course->id, 'status' => ENROL_INSTANCE_ENABLED);
2811 $instances = $DB->get_records('enrol', $params, 'sortorder, id ASC');
bbfdff34 2812 $enrols = enrol_get_plugins(true);
ac7af0da
SH
2813 // First ask all enabled enrol instances in course if they want to auto enrol user.
2814 foreach ($instances as $instance) {
df997f84
PS
2815 if (!isset($enrols[$instance->enrol])) {
2816 continue;
2817 }
bbfdff34
PS
2818 // Get a duration for the enrolment, a timestamp in the future, 0 (always) or false.
2819 $until = $enrols[$instance->enrol]->try_autoenrol($instance);
df997f84 2820 if ($until !== false) {
bbfdff34
PS
2821 if ($until == 0) {
2822 $until = ENROL_MAX_TIMESTAMP;
2823 }
2824 $USER->enrol['enrolled'][$course->id] = $until;
df997f84
PS
2825 $access = true;
2826 break;
2827 }
2828 }
ac7af0da 2829 // If not enrolled yet try to gain temporary guest access.
bbfdff34 2830 if (!$access) {
ac7af0da 2831 foreach ($instances as $instance) {
bbfdff34
PS
2832 if (!isset($enrols[$instance->enrol])) {
2833 continue;
2834 }
2835 // Get a duration for the guest access, a timestamp in the future or false.
2836 $until = $enrols[$instance->enrol]->try_guestaccess($instance);
2837 if ($until !== false and $until > time()) {
2838 $USER->enrol['tempguest'][$course->id] = $until;
2839 $access = true;
2840 break;
2841 }
2842 }
2843 }
df997f84
PS
2844 }
2845 }
2846 }
2847
2848 if (!$access) {
2849 if ($preventredirect) {
2850 throw new require_login_exception('Not enrolled');
2851 }
af572078 2852 if ($setwantsurltome) {
f0202ae9 2853 $SESSION->wantsurl = qualified_me();
af572078 2854 }
b3cb7264 2855 redirect($CFG->wwwroot .'/enrol/index.php?id='. $course->id);
df997f84
PS
2856 }
2857 }
2858
061e6b28 2859 // Check visibility of activity to current user; includes visible flag, conditional availability, etc.
0d8b6a69 2860 if ($cm && !$cm->uservisible) {
df997f84
PS
2861 if ($preventredirect) {
2862 throw new require_login_exception('Activity is hidden');
2863 }
ee17c773 2864 if ($course->id != SITEID) {
ac7af0da 2865 $url = new moodle_url('/course/view.php', array('id' => $course->id));
ee17c773
PS
2866 } else {
2867 $url = new moodle_url('/');
2868 }
2869 redirect($url, get_string('activityiscurrentlyhidden'));
df997f84
PS
2870 }
2871
aad5b7f1 2872 // Set the global $COURSE.
2873 if ($cm) {
2874 $PAGE->set_cm($cm, $course);
2875 $PAGE->set_pagelayout('incourse');
2876 } else if (!empty($courseorid)) {
2877 $PAGE->set_course($course);
2878 }
2879
ac7af0da 2880 // Finally access granted, update lastaccess times.
df997f84 2881 user_accesstime_log($course->id);
f9903ed0 2882}
2883
c4d0753b 2884
c4d0753b 2885/**
2886 * This function just makes sure a user is logged out.
2887 *
f76249cc 2888 * @package core_access
ac7af0da 2889 * @category access
c4d0753b 2890 */
2891function require_logout() {
d79d5ac2 2892 global $USER, $DB;
c4d0753b 2893
d79d5ac2
PS
2894 if (!isloggedin()) {
2895 // This should not happen often, no need for hooks or events here.
2896 \core\session\manager::terminate_current();
2897 return;
c4d0753b 2898 }
2899
d79d5ac2 2900 // Execute hooks before action.
f9f9d187 2901 $authplugins = array();
d79d5ac2
PS
2902 $authsequence = get_enabled_auth_plugins();
2903 foreach ($authsequence as $authname) {
f9f9d187
SL
2904 $authplugins[$authname] = get_auth_plugin($authname);
2905 $authplugins[$authname]->prelogout_hook();
d79d5ac2
PS
2906 }
2907
2908 // Store info that gets removed during logout.
2909 $sid = session_id();
bb78e249 2910 $event = \core\event\user_loggedout::create(
d79d5ac2
PS
2911 array(
2912 'userid' => $USER->id,
2913 'objectid' => $USER->id,
2914 'other' => array('sessionid' => $sid),
2915 )
2916 );
2917 if ($session = $DB->get_record('sessions', array('sid'=>$sid))) {
2918 $event->add_record_snapshot('sessions', $session);
2919 }
bb78e249 2920
f9f9d187
SL
2921 // Clone of $USER object to be used by auth plugins.
2922 $user = fullclone($USER);
2923
d79d5ac2
PS
2924 // Delete session record and drop $_SESSION content.
2925 \core\session\manager::terminate_current();
2926
2927 // Trigger event AFTER action.
2928 $event->trigger();
f9f9d187
SL
2929
2930 // Hook to execute auth plugins redirection after event trigger.
2931 foreach ($authplugins as $authplugin) {
2932 $authplugin->postlogout_hook($user);
2933 }
c4d0753b 2934}
2935
7cf1c7bd 2936/**
0d0a8bf6 2937 * Weaker version of require_login()
2938 *
7cf1c7bd 2939 * This is a weaker version of {@link require_login()} which only requires login
2940 * when called from within a course rather than the site page, unless
2941 * the forcelogin option is turned on.
0d0a8bf6 2942 * @see require_login()
7cf1c7bd 2943 *
f76249cc
PS
2944 * @package core_access
2945 * @category access
2946 *
33ebaf7c 2947 * @param mixed $courseorid The course object or id in question
bbd3f2c4 2948 * @param bool $autologinguest Allow autologin guests if that is wanted
4febb58f 2949 * @param object $cm Course activity module if known
f4013c10 2950 * @param bool $setwantsurltome Define if we want to set $SESSION->wantsurl, defaults to
2951 * true. Used to avoid (=false) some scripts (file.php...) to set that variable,
2952 * in order to keep redirects working properly. MDL-14495
df997f84
PS
2953 * @param bool $preventredirect set to true in scripts that can not redirect (CLI, rss feeds, etc.), throws exceptions
2954 * @return void
ac7af0da 2955 * @throws coding_exception
7cf1c7bd 2956 */
ac7af0da 2957function require_course_login($courseorid, $autologinguest = true, $cm = null, $setwantsurltome = true, $preventredirect = false) {
862940c0 2958 global $CFG, $PAGE, $SITE;
9d202aed
PS
2959 $issite = ((is_object($courseorid) and $courseorid->id == SITEID)
2960 or (!is_object($courseorid) and $courseorid == SITEID));
d4fb0e26 2961 if ($issite && !empty($cm) && !($cm instanceof cm_info)) {
ac7af0da 2962 // Note: nearly all pages call get_fast_modinfo anyway and it does not make any
0d8b6a69 2963 // db queries so this is not really a performance concern, however it is obviously
2964 // better if you use get_fast_modinfo to get the cm before calling this.
2965 if (is_object($courseorid)) {
2966 $course = $courseorid;
2967 } else {
2968 $course = clone($SITE);
2969 }
2970 $modinfo = get_fast_modinfo($course);
2971 $cm = $modinfo->get_cm($cm->id);
2972 }
1596edff 2973 if (!empty($CFG->forcelogin)) {
ac7af0da 2974 // Login required for both SITE and courses.
df997f84 2975 require_login($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
63c9ee99 2976
0d8b6a69 2977 } else if ($issite && !empty($cm) and !$cm->uservisible) {
ac7af0da 2978 // Always login for hidden activities.
df997f84 2979 require_login($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
63c9ee99 2980
0d8b6a69 2981 } else if ($issite) {
ac7af0da 2982 // Login for SITE not required.
48c79eb3 2983 // We still need to instatiate PAGE vars properly so that things that rely on it like navigation function correctly.
2984 if (!empty($courseorid)) {
2985 if (is_object($courseorid)) {
2986 $course = $courseorid;
2987 } else {
2988 $course = clone $SITE;
2989 }
2990 if ($cm) {
2991 if ($cm->course != $course->id) {
2992 throw new coding_exception('course and cm parameters in require_course_login() call do not match!!');
862940c0 2993 }
48c79eb3 2994 $PAGE->set_cm($cm, $course);
2995 $PAGE->set_pagelayout('incourse');
862940c0 2996 } else {
48c79eb3 2997 $PAGE->set_course($course);
862940c0 2998 }
48c79eb3 2999 } else {
3000 // If $PAGE->course, and hence $PAGE->context, have not already been set up properly, set them up now.
3001 $PAGE->set_course($PAGE->course);
9950c88f 3002 }
48c79eb3 3003 user_accesstime_log(SITEID);
3004 return;
63c9ee99 3005
33ebaf7c 3006 } else {
ac7af0da 3007 // Course login always required.
df997f84 3008 require_login($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
f950af3c 3009 }
3010}
3011
61c6071f 3012/**
3013 * Require key login. Function terminates with error if key not found or incorrect.
0d0a8bf6 3014 *
0d0a8bf6 3015 * @uses NO_MOODLE_COOKIES
3016 * @uses PARAM_ALPHANUM
61c6071f 3017 * @param string $script unique script identifier
3018 * @param int $instance optional instance id
0d0a8bf6 3019 * @return int Instance ID
61c6071f 3020 */
3021function require_user_key_login($script, $instance=null) {
ac7af0da 3022 global $DB;
61c6071f 3023
82dd4f42 3024 if (!NO_MOODLE_COOKIES) {
2f137aa1 3025 print_error('sessioncookiesdisable');
61c6071f 3026 }
3027
ac7af0da 3028 // Extra safety.
d79d5ac2 3029 \core\session\manager::write_close();
61c6071f 3030
3031 $keyvalue = required_param('key', PARAM_ALPHANUM);
3032
ac7af0da 3033 if (!$key = $DB->get_record('user_private_key', array('script' => $script, 'value' => $keyvalue, 'instance' => $instance))) {
2f137aa1 3034 print_error('invalidkey');
61c6071f 3035 }
3036
3037 if (!empty($key->validuntil) and $key->validuntil < time()) {
2f137aa1 3038 print_error('expiredkey');
61c6071f 3039 }
3040
e436033f 3041 if ($key->iprestriction) {
765a1d4b
MD
3042 $remoteaddr = getremoteaddr(null);
3043 if (empty($remoteaddr) or !address_in_subnet($remoteaddr, $key->iprestriction)) {
2f137aa1 3044 print_error('ipmismatch');
e436033f 3045 }
61c6071f 3046 }
3047
ac7af0da 3048 if (!$user = $DB->get_record('user', array('id' => $key->userid))) {
2f137aa1 3049 print_error('invaliduserid');
61c6071f 3050 }
3051
ac7af0da 3052 // Emulate normal session.
e922fe23 3053 enrol_check_plugins($user);
d79d5ac2 3054 \core\session\manager::set_user($user);
61c6071f 3055
ac7af0da 3056 // Note we are not using normal login.
e2fa911b