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