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