MDL-41847 core_user: Add lang to login URL email for new user accounts
[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.
140 * Instead, do something like
141 * $rawvalue = required_param('name', PARAM_RAW);
142 * // ... other code including require_login, which sets current lang ...
143 * $realvalue = unformat_float($rawvalue);
144 * // ... then use $realvalue
6e73ae10 145 */
03b31ea3 146define('PARAM_FLOAT', 'float');
6e73ae10 147
148/**
03b31ea3 149 * PARAM_HOST - expected fully qualified domain name (FQDN) or an IPv4 dotted quad (IP address)
150 */
151define('PARAM_HOST', 'host');
152
153/**
154 * PARAM_INT - integers only, use when expecting only numbers.
6e73ae10 155 */
03b31ea3 156define('PARAM_INT', 'int');
157
158/**
159 * PARAM_LANG - checks to see if the string is a valid installed language in the current site.
160 */
161define('PARAM_LANG', 'lang');
162
163/**
ac7af0da
SH
164 * PARAM_LOCALURL - expected properly formatted URL as well as one that refers to the local server itself. (NOT orthogonal to the
165 * others! Implies PARAM_URL!)
03b31ea3 166 */
167define('PARAM_LOCALURL', 'localurl');
bbd3f2c4 168
169/**
c59733ef 170 * PARAM_NOTAGS - all html tags are stripped from the text. Do not abuse this type.
bbd3f2c4 171 */
03b31ea3 172define('PARAM_NOTAGS', 'notags');
bbd3f2c4 173
6e73ae10 174/**
ac7af0da
SH
175 * PARAM_PATH - safe relative path name, all dangerous chars are stripped, protects against XSS, SQL injections and directory
176 * traversals note: the leading slash is not removed, window drive letter is not allowed
31f26796 177 */
03b31ea3 178define('PARAM_PATH', 'path');
31f26796 179
6e73ae10 180/**
03b31ea3 181 * PARAM_PEM - Privacy Enhanced Mail format
c4ea5e78 182 */
03b31ea3 183define('PARAM_PEM', 'pem');
c4ea5e78 184
bbd3f2c4 185/**
03b31ea3 186 * PARAM_PERMISSION - A permission, one of CAP_INHERIT, CAP_ALLOW, CAP_PREVENT or CAP_PROHIBIT.
bbd3f2c4 187 */
03b31ea3 188define('PARAM_PERMISSION', 'permission');
bbd3f2c4 189
bed79931 190/**
78fcdb5f 191 * PARAM_RAW specifies a parameter that is not cleaned/processed in any way except the discarding of the invalid utf-8 characters
bed79931 192 */
03b31ea3 193define('PARAM_RAW', 'raw');
bed79931 194
652599ec
TH
195/**
196 * PARAM_RAW_TRIMMED like PARAM_RAW but leading and trailing whitespace is stripped.
197 */
198define('PARAM_RAW_TRIMMED', 'raw_trimmed');
199
bcef0319 200/**
03b31ea3 201 * PARAM_SAFEDIR - safe directory name, suitable for include() and require()
bcef0319 202 */
03b31ea3 203define('PARAM_SAFEDIR', 'safedir');
bcef0319 204
e032888c 205/**
03b31ea3 206 * PARAM_SAFEPATH - several PARAM_SAFEDIR joined by "/", suitable for include() and require(), plugin paths, etc.
38fb8190 207 */
03b31ea3 208define('PARAM_SAFEPATH', 'safepath');
e032888c 209
bbd3f2c4 210/**
03b31ea3 211 * PARAM_SEQUENCE - expects a sequence of numbers like 8 to 1,5,6,4,6,8,9. Numbers and comma only.
bbd3f2c4 212 */
03b31ea3 213define('PARAM_SEQUENCE', 'sequence');
bbd3f2c4 214
215/**
03b31ea3 216 * PARAM_TAG - one tag (interests, blogs, etc.) - mostly international characters and space, <> not supported
bbd3f2c4 217 */
03b31ea3 218define('PARAM_TAG', 'tag');
bbd3f2c4 219
220/**
03b31ea3 221 * PARAM_TAGLIST - list of tags separated by commas (interests, blogs, etc.)
bbd3f2c4 222 */
03b31ea3 223define('PARAM_TAGLIST', 'taglist');
bbd3f2c4 224
225/**
b6059edc 226 * PARAM_TEXT - general plain text compatible with multilang filter, no other html tags. Please note '<', or '>' are allowed here.
bbd3f2c4 227 */
03b31ea3 228define('PARAM_TEXT', 'text');
bbd3f2c4 229
bbd3f2c4 230/**
03b31ea3 231 * PARAM_THEME - Checks to see if the string is a valid theme name in the current site
bbd3f2c4 232 */
03b31ea3 233define('PARAM_THEME', 'theme');
bbd3f2c4 234
235/**
ac7af0da
SH
236 * PARAM_URL - expected properly formatted URL. Please note that domain part is required, http://localhost/ is not accepted but
237 * http://localhost.localdomain/ is ok.
bbd3f2c4 238 */
03b31ea3 239define('PARAM_URL', 'url');
240
07ed083e 241/**
ac7af0da
SH
242 * PARAM_USERNAME - Clean username to only contains allowed characters. This is to be used ONLY when manually creating user
243 * accounts, do NOT use when syncing with external systems!!
07ed083e
RW
244 */
245define('PARAM_USERNAME', 'username');
bbd3f2c4 246
fe6a248f
DM
247/**
248 * PARAM_STRINGID - used to check if the given string is valid string identifier for get_string()
249 */
250define('PARAM_STRINGID', 'stringid');
03b31ea3 251
ac7af0da 252// DEPRECATED PARAM TYPES OR ALIASES - DO NOT USE FOR NEW CODE.
bbd3f2c4 253/**
03b31ea3 254 * PARAM_CLEAN - obsoleted, please use a more specific type of parameter.
255 * It was one of the first types, that is why it is abused so much ;-)
44913c8d 256 * @deprecated since 2.0
bbd3f2c4 257 */
03b31ea3 258define('PARAM_CLEAN', 'clean');
bbd3f2c4 259
260/**
03b31ea3 261 * PARAM_INTEGER - deprecated alias for PARAM_INT
1e12c120 262 * @deprecated since 2.0
bbd3f2c4 263 */
03b31ea3 264define('PARAM_INTEGER', 'int');
bbd3f2c4 265
0e4af166 266/**
03b31ea3 267 * PARAM_NUMBER - deprecated alias of PARAM_FLOAT
61cca0b7 268 * @deprecated since 2.0
0e4af166 269 */
03b31ea3 270define('PARAM_NUMBER', 'float');
0e4af166 271
03d820c7 272/**
efb8c375 273 * PARAM_ACTION - deprecated alias for PARAM_ALPHANUMEXT, use for various actions in forms and urls
03b31ea3 274 * NOTE: originally alias for PARAM_APLHA
405aca35 275 * @deprecated since 2.0
03d820c7 276 */
03b31ea3 277define('PARAM_ACTION', 'alphanumext');
03d820c7 278
279/**
03b31ea3 280 * PARAM_FORMAT - deprecated alias for PARAM_ALPHANUMEXT, use for names of plugins, formats, etc.
281 * NOTE: originally alias for PARAM_APLHA
405aca35 282 * @deprecated since 2.0
03d820c7 283 */
03b31ea3 284define('PARAM_FORMAT', 'alphanumext');
03d820c7 285
ad944e78 286/**
03b31ea3 287 * PARAM_MULTILANG - deprecated alias of PARAM_TEXT.
071e68f9 288 * @deprecated since 2.0
ad944e78 289 */
03b31ea3 290define('PARAM_MULTILANG', 'text');
03d820c7 291
ccc77f91
RT
292/**
293 * PARAM_TIMEZONE - expected timezone. Timezone can be int +-(0-13) or float +-(0.5-12.5) or
ac7af0da 294 * string separated by '/' and can have '-' &/ '_' (eg. America/North_Dakota/New_Salem
ccc77f91
RT
295 * America/Port-au-Prince)
296 */
297define('PARAM_TIMEZONE', 'timezone');
298
faf75fe7 299/**
03b31ea3 300 * PARAM_CLEANFILE - deprecated alias of PARAM_FILE; originally was removing regional chars too
faf75fe7 301 */
03b31ea3 302define('PARAM_CLEANFILE', 'file');
303
aff24313
PS
304/**
305 * PARAM_COMPONENT is used for full component names (aka frankenstyle) such as 'mod_forum', 'core_rating', 'auth_ldap'.
306 * Short legacy subsystem names and module names are accepted too ex: 'forum', 'rating', 'user'.
307 * Only lowercase ascii letters, numbers and underscores are allowed, it has to start with a letter.
308 * NOTE: numbers and underscores are strongly discouraged in plugin names!
309 */
310define('PARAM_COMPONENT', 'component');
311
312/**
313 * PARAM_AREA is a name of area used when addressing files, comments, ratings, etc.
314 * It is usually used together with context id and component.
315 * Only lowercase ascii letters, numbers and underscores are allowed, it has to start with a letter.
316 */
317define('PARAM_AREA', 'area');
318
319/**
159c2c91 320 * PARAM_PLUGIN is used for plugin names such as 'forum', 'glossary', 'ldap', 'paypal', 'completionstatus'.
aff24313
PS
321 * Only lowercase ascii letters, numbers and underscores are allowed, it has to start with a letter.
322 * NOTE: numbers and underscores are strongly discouraged in plugin names! Underscores are forbidden in module names.
323 */
324define('PARAM_PLUGIN', 'plugin');
325
326
ac7af0da 327// Web Services.
03b31ea3 328
382b9cea 329/**
330 * VALUE_REQUIRED - if the parameter is not supplied, there is an error
331 */
332define('VALUE_REQUIRED', 1);
333
334/**
335 * VALUE_OPTIONAL - if the parameter is not supplied, then the param has no value
336 */
337define('VALUE_OPTIONAL', 2);
338
339/**
340 * VALUE_DEFAULT - if the parameter is not supplied, then the default value is used
341 */
342define('VALUE_DEFAULT', 0);
03b31ea3 343
5a1861ee 344/**
345 * NULL_NOT_ALLOWED - the parameter can not be set to null in the database
346 */
347define('NULL_NOT_ALLOWED', false);
348
349/**
350 * NULL_ALLOWED - the parameter can be set to null in the database
351 */
352define('NULL_ALLOWED', true);
faf75fe7 353
ac7af0da
SH
354// Page types.
355
bbd3f2c4 356/**
357 * PAGE_COURSE_VIEW is a definition of a page type. For more information on the page class see moodle/lib/pagelib.php.
8bd3fad3 358 */
359define('PAGE_COURSE_VIEW', 'course-view');
8bd3fad3 360
9bda43e6 361/** Get remote addr constant */
362define('GETREMOTEADDR_SKIP_HTTP_CLIENT_IP', '1');
363/** Get remote addr constant */
364define('GETREMOTEADDR_SKIP_HTTP_X_FORWARDED_FOR', '2');
6e73ae10 365
ac7af0da 366// Blog access level constant declaration.
feaf5d06 367define ('BLOG_USER_LEVEL', 1);
368define ('BLOG_GROUP_LEVEL', 2);
369define ('BLOG_COURSE_LEVEL', 3);
370define ('BLOG_SITE_LEVEL', 4);
371define ('BLOG_GLOBAL_LEVEL', 5);
372
6e73ae10 373
ac7af0da 374// Tag constants.
4eb718d8 375/**
a905364a 376 * To prevent problems with multibytes strings,Flag updating in nav not working on the review page. this should not exceed the
6e73ae10 377 * length of "varchar(255) / 3 (bytes / utf-8 character) = 85".
378 * TODO: this is not correct, varchar(255) are 255 unicode chars ;-)
0d0a8bf6 379 *
380 * @todo define(TAG_MAX_LENGTH) this is not correct, varchar(255) are 255 unicode chars ;-)
4eb718d8 381 */
ae040d4b 382define('TAG_MAX_LENGTH', 50);
4eb718d8 383
ac7af0da 384// Password policy constants.
6499395e 385define ('PASSWORD_LOWER', 'abcdefghijklmnopqrstuvwxyz');
386define ('PASSWORD_UPPER', 'ABCDEFGHIJKLMNOPQRSTUVWXYZ');
387define ('PASSWORD_DIGITS', '0123456789');
388define ('PASSWORD_NONALPHANUM', '.,;:!?_-+/*@#&$');
389
ac7af0da 390// Feature constants.
6e73ae10 391// Used for plugin_supports() to report features that are, or are not, supported by a module.
49f6e5f4 392
393/** True if module can provide a grade */
61fceb86 394define('FEATURE_GRADE_HAS_GRADE', 'grade_has_grade');
42f103be 395/** True if module supports outcomes */
396define('FEATURE_GRADE_OUTCOMES', 'outcomes');
b11f9da6
DM
397/** True if module supports advanced grading methods */
398define('FEATURE_ADVANCED_GRADING', 'grade_advanced_grading');
455dc0de
FM
399/** True if module controls the grade visibility over the gradebook */
400define('FEATURE_CONTROLS_GRADE_VISIBILITY', 'controlsgradevisbility');
50da4ddd
KG
401/** True if module supports plagiarism plugins */
402define('FEATURE_PLAGIARISM', 'plagiarism');
42f103be 403
49f6e5f4 404/** True if module has code to track whether somebody viewed it */
61fceb86 405define('FEATURE_COMPLETION_TRACKS_VIEWS', 'completion_tracks_views');
49f6e5f4 406/** True if module has custom completion rules */
61fceb86 407define('FEATURE_COMPLETION_HAS_RULES', 'completion_has_rules');
49f6e5f4 408
0d8b6a69 409/** True if module has no 'view' page (like label) */
410define('FEATURE_NO_VIEW_LINK', 'viewlink');
de158ec5 411/** True (which is default) if the module wants support for setting the ID number for grade calculation purposes. */
42f103be 412define('FEATURE_IDNUMBER', 'idnumber');
413/** True if module supports groups */
414define('FEATURE_GROUPS', 'groups');
415/** True if module supports groupings */
416define('FEATURE_GROUPINGS', 'groupings');
061e6b28 417/**
418 * True if module supports groupmembersonly (which no longer exists)
419 * @deprecated Since Moodle 2.8
420 */
42f103be 421define('FEATURE_GROUPMEMBERSONLY', 'groupmembersonly');
422
aa54ed7b 423/** Type of module */
424define('FEATURE_MOD_ARCHETYPE', 'mod_archetype');
42f103be 425/** True if module supports intro editor */
dc5c2bd9 426define('FEATURE_MOD_INTRO', 'mod_intro');
42f103be 427/** True if module has default completion */
428define('FEATURE_MODEDIT_DEFAULT_COMPLETION', 'modedit_default_completion');
49f6e5f4 429
1bcb7eb5 430define('FEATURE_COMMENT', 'comment');
431
6c5fcef7 432define('FEATURE_RATE', 'rate');
4bfdcfcf
EL
433/** True if module supports backup/restore of moodle2 format */
434define('FEATURE_BACKUP_MOODLE2', 'backup_moodle2');
a09aeee4 435
8c40662e 436/** True if module can show description on course main page */
437define('FEATURE_SHOW_DESCRIPTION', 'showdescription');
438
b07ef13b
DP
439/** True if module uses the question bank */
440define('FEATURE_USES_QUESTIONS', 'usesquestions');
441
757a889b
MG
442/**
443 * Maximum filename char size
444 */
d609207c 445define('MAX_FILENAME_SIZE', 100);
757a889b 446
aa54ed7b 447/** Unspecified module archetype */
448define('MOD_ARCHETYPE_OTHER', 0);
449/** Resource-like type module */
450define('MOD_ARCHETYPE_RESOURCE', 1);
efb8c375 451/** Assignment module archetype */
aa54ed7b 452define('MOD_ARCHETYPE_ASSIGNMENT', 2);
5813c7f7 453/** System (not user-addable) module archetype */
454define('MOD_ARCHETYPE_SYSTEM', 3);
aa54ed7b 455
eec99048 456/**
457 * Security token used for allowing access
458 * from external application such as web services.
459 * Scripts do not use any session, performance is relatively
460 * low because we need to load access info in each request.
efb8c375 461 * Scripts are executed in parallel.
eec99048 462 */
463define('EXTERNAL_TOKEN_PERMANENT', 0);
464
465/**
466 * Security token used for allowing access
467 * of embedded applications, the code is executed in the
468 * active user session. Token is invalidated after user logs out.
469 * Scripts are executed serially - normal session locking is used.
470 */
471define('EXTERNAL_TOKEN_EMBEDDED', 1);
49f6e5f4 472
4766a50c
SH
473/**
474 * The home page should be the site home
475 */
476define('HOMEPAGE_SITE', 0);
477/**
478 * The home page should be the users my page
479 */
480define('HOMEPAGE_MY', 1);
481/**
482 * The home page can be chosen by the user
483 */
484define('HOMEPAGE_USER', 2);
fcce139a 485
94788de2 486/**
487 * Hub directory url (should be moodle.org)
488 */
7d792aee 489define('HUB_HUBDIRECTORYURL', "https://hubdirectory.moodle.org");
94788de2 490
491
492/**
7d792aee 493 * Moodle.net url (should be moodle.net)
94788de2 494 */
7d792aee
MG
495define('HUB_MOODLEORGHUBURL', "https://moodle.net");
496define('HUB_OLDMOODLEORGHUBURL', "http://hub.moodle.org");
94788de2 497
c1b65883
JM
498/**
499 * Moodle mobile app service name
500 */
501define('MOODLE_OFFICIAL_MOBILE_SERVICE', 'moodle_mobile_app');
94788de2 502
bc8da017
AD
503/**
504 * Indicates the user has the capabilities required to ignore activity and course file size restrictions
505 */
506define('USER_CAN_IGNORE_FILE_SIZE_LIMITS', -1);
507
1f09018a 508/**
ac7af0da
SH
509 * Course display settings: display all sections on one page.
510 */
511define('COURSE_DISPLAY_SINGLEPAGE', 0);
512/**
513 * Course display settings: split pages into a page per section.
1f09018a 514 */
ac7af0da 515define('COURSE_DISPLAY_MULTIPAGE', 1);
1f09018a 516
ec2d8ceb 517/**
ac7af0da 518 * Authentication constant: String used in password field when password is not stored.
ec2d8ceb 519 */
ac7af0da 520define('AUTH_PASSWORD_NOT_CACHED', 'not cached');
ec2d8ceb 521
9715f61a
AG
522/**
523 * Email from header to never include via information.
524 */
525define('EMAIL_VIA_NEVER', 0);
526
527/**
528 * Email from header to always include via information.
529 */
530define('EMAIL_VIA_ALWAYS', 1);
531
532/**
533 * Email from header to only include via information if the address is no-reply.
534 */
535define('EMAIL_VIA_NO_REPLY_ONLY', 2);
536
ac7af0da 537// PARAMETER HANDLING.
6b174680 538
e0d346ff 539/**
361855e6 540 * Returns a particular value for the named variable, taken from
541 * POST or GET. If the parameter doesn't exist then an error is
e0d346ff 542 * thrown because we require this variable.
543 *
361855e6 544 * This function should be used to initialise all required values
545 * in a script that are based on parameters. Usually it will be
e0d346ff 546 * used like this:
622365d2 547 * $id = required_param('id', PARAM_INT);
e0d346ff 548 *
2ca3bffa 549 * Please note the $type parameter is now required and the value can not be array.
44913c8d
PS
550 *
551 * @param string $parname the name of the page parameter we want
552 * @param string $type expected type of parameter
e0d346ff 553 * @return mixed
ac7af0da 554 * @throws coding_exception
e0d346ff 555 */
44913c8d 556function required_param($parname, $type) {
2ca3bffa
PS
557 if (func_num_args() != 2 or empty($parname) or empty($type)) {
558 throw new coding_exception('required_param() requires $parname and $type to be specified (parameter: '.$parname.')');
44913c8d 559 }
ac7af0da
SH
560 // POST has precedence.
561 if (isset($_POST[$parname])) {
a083b93c 562 $param = $_POST[$parname];
563 } else if (isset($_GET[$parname])) {
564 $param = $_GET[$parname];
e0d346ff 565 } else {
2f137aa1 566 print_error('missingparam', '', '', $parname);
e0d346ff 567 }
568
2ca3bffa
PS
569 if (is_array($param)) {
570 debugging('Invalid array parameter detected in required_param(): '.$parname);
ac7af0da 571 // TODO: switch to fatal error in Moodle 2.3.
2ca3bffa
PS
572 return required_param_array($parname, $type);
573 }
574
a083b93c 575 return clean_param($param, $type);
e0d346ff 576}
577
2ca3bffa
PS
578/**
579 * Returns a particular array value for the named variable, taken from
580 * POST or GET. If the parameter doesn't exist then an error is
581 * thrown because we require this variable.
582 *
583 * This function should be used to initialise all required values
584 * in a script that are based on parameters. Usually it will be
585 * used like this:
586 * $ids = required_param_array('ids', PARAM_INT);
587 *
588 * Note: arrays of arrays are not supported, only alphanumeric keys with _ and - are supported
589 *
590 * @param string $parname the name of the page parameter we want
591 * @param string $type expected type of parameter
592 * @return array
ac7af0da 593 * @throws coding_exception
2ca3bffa
PS
594 */
595function required_param_array($parname, $type) {
596 if (func_num_args() != 2 or empty($parname) or empty($type)) {
597 throw new coding_exception('required_param_array() requires $parname and $type to be specified (parameter: '.$parname.')');
598 }
ac7af0da
SH
599 // POST has precedence.
600 if (isset($_POST[$parname])) {
2ca3bffa
PS
601 $param = $_POST[$parname];
602 } else if (isset($_GET[$parname])) {
603 $param = $_GET[$parname];
604 } else {
605 print_error('missingparam', '', '', $parname);
606 }
607 if (!is_array($param)) {
608 print_error('missingparam', '', '', $parname);
609 }
610
611 $result = array();
ac7af0da 612 foreach ($param as $key => $value) {
2ca3bffa
PS
613 if (!preg_match('/^[a-z0-9_-]+$/i', $key)) {
614 debugging('Invalid key name in required_param_array() detected: '.$key.', parameter: '.$parname);
615 continue;
616 }
ebdeccca 617 $result[$key] = clean_param($value, $type);
2ca3bffa
PS
618 }
619
620 return $result;
e0d346ff 621}
622
623/**
361855e6 624 * Returns a particular value for the named variable, taken from
e0d346ff 625 * POST or GET, otherwise returning a given default.
626 *
361855e6 627 * This function should be used to initialise all optional values
628 * in a script that are based on parameters. Usually it will be
e0d346ff 629 * used like this:
622365d2 630 * $name = optional_param('name', 'Fred', PARAM_TEXT);
e0d346ff 631 *
2ca3bffa 632 * Please note the $type parameter is now required and the value can not be array.
44913c8d 633 *
a083b93c 634 * @param string $parname the name of the page parameter we want
e0d346ff 635 * @param mixed $default the default value to return if nothing is found
44913c8d 636 * @param string $type expected type of parameter
e0d346ff 637 * @return mixed
ac7af0da 638 * @throws coding_exception
e0d346ff 639 */
44913c8d 640function optional_param($parname, $default, $type) {
2ca3bffa 641 if (func_num_args() != 3 or empty($parname) or empty($type)) {
ac7af0da 642 throw new coding_exception('optional_param requires $parname, $default + $type to be specified (parameter: '.$parname.')');
44913c8d 643 }
44913c8d 644
ac7af0da
SH
645 // POST has precedence.
646 if (isset($_POST[$parname])) {
a083b93c 647 $param = $_POST[$parname];
648 } else if (isset($_GET[$parname])) {
649 $param = $_GET[$parname];
e0d346ff 650 } else {
651 return $default;
652 }
c7f4e3e2 653
2ca3bffa
PS
654 if (is_array($param)) {
655 debugging('Invalid array parameter detected in required_param(): '.$parname);
ac7af0da 656 // TODO: switch to $default in Moodle 2.3.
2ca3bffa
PS
657 return optional_param_array($parname, $default, $type);
658 }
659
a083b93c 660 return clean_param($param, $type);
e0d346ff 661}
662
2ca3bffa
PS
663/**
664 * Returns a particular array value for the named variable, taken from
665 * POST or GET, otherwise returning a given default.
666 *
667 * This function should be used to initialise all optional values
668 * in a script that are based on parameters. Usually it will be
669 * used like this:
670 * $ids = optional_param('id', array(), PARAM_INT);
671 *
ac7af0da 672 * Note: arrays of arrays are not supported, only alphanumeric keys with _ and - are supported
2ca3bffa
PS
673 *
674 * @param string $parname the name of the page parameter we want
ac7af0da 675 * @param mixed $default the default value to return if nothing is found
2ca3bffa
PS
676 * @param string $type expected type of parameter
677 * @return array
ac7af0da 678 * @throws coding_exception
2ca3bffa
PS
679 */
680function optional_param_array($parname, $default, $type) {
681 if (func_num_args() != 3 or empty($parname) or empty($type)) {
ac7af0da 682 throw new coding_exception('optional_param_array requires $parname, $default + $type to be specified (parameter: '.$parname.')');
2ca3bffa
PS
683 }
684
ac7af0da
SH
685 // POST has precedence.
686 if (isset($_POST[$parname])) {
2ca3bffa
PS
687 $param = $_POST[$parname];
688 } else if (isset($_GET[$parname])) {
689 $param = $_GET[$parname];
690 } else {
691 return $default;
692 }
693 if (!is_array($param)) {
694 debugging('optional_param_array() expects array parameters only: '.$parname);
695 return $default;
696 }
697
698 $result = array();
ac7af0da 699 foreach ($param as $key => $value) {
2ca3bffa
PS
700 if (!preg_match('/^[a-z0-9_-]+$/i', $key)) {
701 debugging('Invalid key name in optional_param_array() detected: '.$key.', parameter: '.$parname);
702 continue;
703 }
ebdeccca 704 $result[$key] = clean_param($value, $type);
2ca3bffa
PS
705 }
706
707 return $result;
e0d346ff 708}
709
a3f7cbf6 710/**
711 * Strict validation of parameter values, the values are only converted
712 * to requested PHP type. Internally it is using clean_param, the values
713 * before and after cleaning must be equal - otherwise
714 * an invalid_parameter_exception is thrown.
efb8c375 715 * Objects and classes are not accepted.
a3f7cbf6 716 *
717 * @param mixed $param
2ca3bffa 718 * @param string $type PARAM_ constant
a3f7cbf6 719 * @param bool $allownull are nulls valid value?
720 * @param string $debuginfo optional debug information
fea52c11
PS
721 * @return mixed the $param value converted to PHP type
722 * @throws invalid_parameter_exception if $param is not of given type
a3f7cbf6 723 */
5a1861ee 724function validate_param($param, $type, $allownull=NULL_NOT_ALLOWED, $debuginfo='') {
a3f7cbf6 725 if (is_null($param)) {
5a1861ee 726 if ($allownull == NULL_ALLOWED) {
a3f7cbf6 727 return null;
728 } else {
729 throw new invalid_parameter_exception($debuginfo);
730 }
731 }
732 if (is_array($param) or is_object($param)) {
733 throw new invalid_parameter_exception($debuginfo);
734 }
735
736 $cleaned = clean_param($param, $type);
fea52c11
PS
737
738 if ($type == PARAM_FLOAT) {
739 // Do not detect precision loss here.
740 if (is_float($param) or is_int($param)) {
741 // These always fit.
742 } else if (!is_numeric($param) or !preg_match('/^[\+-]?[0-9]*\.?[0-9]*(e[-+]?[0-9]+)?$/i', (string)$param)) {
743 throw new invalid_parameter_exception($debuginfo);
744 }
745 } else if ((string)$param !== (string)$cleaned) {
ac7af0da 746 // Conversion to string is usually lossless.
a3f7cbf6 747 throw new invalid_parameter_exception($debuginfo);
748 }
749
750 return $cleaned;
751}
752
2ca3bffa 753/**
ac7af0da
SH
754 * Makes sure array contains only the allowed types, this function does not validate array key names!
755 *
2ca3bffa
PS
756 * <code>
757 * $options = clean_param($options, PARAM_INT);
758 * </code>
759 *
760 * @param array $param the variable array we are cleaning
761 * @param string $type expected format of param after cleaning.
762 * @param bool $recursive clean recursive arrays
763 * @return array
ac7af0da 764 * @throws coding_exception
2ca3bffa
PS
765 */
766function clean_param_array(array $param = null, $type, $recursive = false) {
ac7af0da
SH
767 // Convert null to empty array.
768 $param = (array)$param;
2ca3bffa
PS
769 foreach ($param as $key => $value) {
770 if (is_array($value)) {
771 if ($recursive) {
772 $param[$key] = clean_param_array($value, $type, true);
773 } else {
ac7af0da 774 throw new coding_exception('clean_param_array can not process multidimensional arrays when $recursive is false.');
2ca3bffa
PS
775 }
776 } else {
777 $param[$key] = clean_param($value, $type);
778 }
779 }
780 return $param;
781}
782
e0d346ff 783/**
361855e6 784 * Used by {@link optional_param()} and {@link required_param()} to
785 * clean the variables and/or cast to specific types, based on
e0d346ff 786 * an options field.
bbd3f2c4 787 * <code>
788 * $course->format = clean_param($course->format, PARAM_ALPHA);
ac7af0da 789 * $selectedgradeitem = clean_param($selectedgradeitem, PARAM_INT);
bbd3f2c4 790 * </code>
e0d346ff 791 *
792 * @param mixed $param the variable we are cleaning
2ca3bffa 793 * @param string $type expected format of param after cleaning.
e0d346ff 794 * @return mixed
ac7af0da 795 * @throws coding_exception
e0d346ff 796 */
a083b93c 797function clean_param($param, $type) {
7744ea12 798 global $CFG;
c7f4e3e2 799
c16c1be7
PS
800 if (is_array($param)) {
801 throw new coding_exception('clean_param() can not process arrays, please use clean_param_array() instead.');
802 } else if (is_object($param)) {
803 if (method_exists($param, '__toString')) {
804 $param = $param->__toString();
805 } else {
806 throw new coding_exception('clean_param() can not process objects, please use clean_param_array() instead.');
807 }
80bfd470 808 }
809
a083b93c 810 switch ($type) {
ac7af0da
SH
811 case PARAM_RAW:
812 // No cleaning at all.
78fcdb5f 813 $param = fix_utf8($param);
96e98ea6 814 return $param;
815
ac7af0da
SH
816 case PARAM_RAW_TRIMMED:
817 // No cleaning, but strip leading and trailing whitespace.
78fcdb5f 818 $param = fix_utf8($param);
652599ec
TH
819 return trim($param);
820
ac7af0da
SH
821 case PARAM_CLEAN:
822 // General HTML cleaning, try to use more specific type if possible this is deprecated!
823 // Please use more specific type instead.
a083b93c 824 if (is_numeric($param)) {
825 return $param;
826 }
78fcdb5f 827 $param = fix_utf8($param);
ac7af0da
SH
828 // Sweep for scripts, etc.
829 return clean_text($param);
3af57507 830
ac7af0da
SH
831 case PARAM_CLEANHTML:
832 // Clean html fragment.
78fcdb5f 833 $param = fix_utf8($param);
ac7af0da
SH
834 // Sweep for scripts, etc.
835 $param = clean_text($param, FORMAT_HTML);
a083b93c 836 return trim($param);
e0d346ff 837
a083b93c 838 case PARAM_INT:
ac7af0da
SH
839 // Convert to integer.
840 return (int)$param;
e0d346ff 841
6e73ae10 842 case PARAM_FLOAT:
ac7af0da
SH
843 // Convert to float.
844 return (float)$param;
9dae915a 845
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 }
a4080313 1408 }
e0d9b7c0
SH
1409 if ($name === 'siteidentifier') {
1410 cache_helper::update_site_identifier($value);
1411 }
007bfe8b 1412 cache_helper::invalidate_by_definition('core', 'config', array(), 'core');
ac7af0da
SH
1413 } else {
1414 // Plugin scope.
1415 if ($id = $DB->get_field('config_plugins', 'id', array('name' => $name, 'plugin' => $plugin))) {
6fd511eb 1416 if ($value===null) {
ac7af0da 1417 $DB->delete_records('config_plugins', array('name' => $name, 'plugin' => $plugin));
6fd511eb 1418 } else {
ac7af0da 1419 $DB->set_field('config_plugins', 'value', $value, array('id' => $id));
6fd511eb 1420 }
a4080313 1421 } else {
5e2f308b 1422 if ($value !== null) {
365a5941 1423 $config = new stdClass();
5e2f308b 1424 $config->plugin = $plugin;
1425 $config->name = $name;
1426 $config->value = $value;
1427 $DB->insert_record('config_plugins', $config, false);
6fd511eb 1428 }
a4080313 1429 }
007bfe8b 1430 cache_helper::invalidate_by_definition('core', 'config', array(), $plugin);
a4080313 1431 }
5e2f308b 1432
1433 return true;
a4080313 1434}
1435
1436/**
e1ecf0a0 1437 * Get configuration values from the global config table
a4080313 1438 * or the config_plugins table.
1439 *
13daf6a2 1440 * If called with one parameter, it will load all the config
12bb0c3e 1441 * variables for one plugin, and return them as an object.
13daf6a2 1442 *
12bb0c3e
PS
1443 * If called with 2 parameters it will return a string single
1444 * value or false if the value is not found.
9220fba5 1445 *
08b51dd0
JO
1446 * NOTE: this function is called from lib/db/upgrade.php
1447 *
ac7af0da 1448 * @static string|false $siteidentifier The site identifier is not cached. We use this static cache so
e0d9b7c0 1449 * that we need only fetch it once per request.
12bb0c3e 1450 * @param string $plugin full component name
ac7af0da 1451 * @param string $name default null
07ab0c80 1452 * @return mixed hash-like object or single value, return false no config found
ac7af0da 1453 * @throws dml_exception
a4080313 1454 */
ac7af0da 1455function get_config($plugin, $name = null) {
ae040d4b 1456 global $CFG, $DB;
dfc9ba9b 1457
e0d9b7c0
SH
1458 static $siteidentifier = null;
1459
007bfe8b
SH
1460 if ($plugin === 'moodle' || $plugin === 'core' || empty($plugin)) {
1461 $forced =& $CFG->config_php_settings;
1462 $iscore = true;
1463 $plugin = 'core';
1464 } else {
1465 if (array_key_exists($plugin, $CFG->forced_plugin_settings)) {
1466 $forced =& $CFG->forced_plugin_settings[$plugin];
1467 } else {
1468 $forced = array();
1469 }
1470 $iscore = false;
12bb0c3e
PS
1471 }
1472
e0d9b7c0
SH
1473 if ($siteidentifier === null) {
1474 try {
1475 // This may fail during installation.
1476 // If you have a look at {@link initialise_cfg()} you will see that this is how we detect the need to
1477 // install the database.
1478 $siteidentifier = $DB->get_field('config', 'value', array('name' => 'siteidentifier'));
1479 } catch (dml_exception $ex) {
e0d9b7c0
SH
1480 // Set siteidentifier to false. We don't want to trip this continually.
1481 $siteidentifier = false;
1482 throw $ex;
1483 }
1484 }
1485
1486 if (!empty($name)) {
1487 if (array_key_exists($name, $forced)) {
1488 return (string)$forced[$name];
1489 } else if ($name === 'siteidentifier' && $plugin == 'core') {
1490 return $siteidentifier;
1491 }
007bfe8b
SH
1492 }
1493
1494 $cache = cache::make('core', 'config');
1495 $result = $cache->get($plugin);
d0749719 1496 if ($result === false) {
ac7af0da 1497 // The user is after a recordset.
007bfe8b 1498 if (!$iscore) {
ac7af0da 1499 $result = $DB->get_records_menu('config_plugins', array('plugin' => $plugin), '', 'name,value');
a4080313 1500 } else {
ac7af0da 1501 // This part is not really used any more, but anyway...
007bfe8b 1502 $result = $DB->get_records_menu('config', array(), '', 'name,value');;
a4080313 1503 }
007bfe8b 1504 $cache->set($plugin, $result);
a4080313 1505 }
1506
007bfe8b
SH
1507 if (!empty($name)) {
1508 if (array_key_exists($name, $result)) {
1509 return $result[$name];
bfb82da3 1510 }
007bfe8b
SH
1511 return false;
1512 }
e1ecf0a0 1513
e0d9b7c0
SH
1514 if ($plugin === 'core') {
1515 $result['siteidentifier'] = $siteidentifier;
1516 }
1517
007bfe8b
SH
1518 foreach ($forced as $key => $value) {
1519 if (is_null($value) or is_array($value) or is_object($value)) {
ac7af0da 1520 // We do not want any extra mess here, just real settings that could be saved in db.
007bfe8b
SH
1521 unset($result[$key]);
1522 } else {
ac7af0da 1523 // Convert to string as if it went through the DB.
007bfe8b 1524 $result[$key] = (string)$value;
12bb0c3e 1525 }
39917a09 1526 }
007bfe8b
SH
1527
1528 return (object)$result;
39917a09 1529}
1530
b0270f84 1531/**
ac7af0da 1532 * Removes a key from global configuration.
b0270f84 1533 *
08b51dd0
JO
1534 * NOTE: this function is called from lib/db/upgrade.php
1535 *
b0270f84 1536 * @param string $name the key to set
1537 * @param string $plugin (optional) the plugin scope
4b600aa0 1538 * @return boolean whether the operation succeeded.
b0270f84 1539 */
ac7af0da 1540function unset_config($name, $plugin=null) {
ae040d4b 1541 global $CFG, $DB;
b0270f84 1542
b0270f84 1543 if (empty($plugin)) {
4b600aa0 1544 unset($CFG->$name);
ac7af0da 1545 $DB->delete_records('config', array('name' => $name));
007bfe8b 1546 cache_helper::invalidate_by_definition('core', 'config', array(), 'core');
5e623a33 1547 } else {
ac7af0da 1548 $DB->delete_records('config_plugins', array('name' => $name, 'plugin' => $plugin));
007bfe8b 1549 cache_helper::invalidate_by_definition('core', 'config', array(), $plugin);
b0270f84 1550 }
013376de 1551
1552 return true;
b0270f84 1553}
1554
4b600aa0 1555/**
1556 * Remove all the config variables for a given plugin.
ac7af0da 1557 *
c2ca2d8e 1558 * NOTE: this function is called from lib/db/upgrade.php
4b600aa0 1559 *
1560 * @param string $plugin a plugin, for example 'quiz' or 'qtype_multichoice';
1561 * @return boolean whether the operation succeeded.
1562 */
1563function unset_all_config_for_plugin($plugin) {
1564 global $DB;
ac7af0da 1565 // Delete from the obvious config_plugins first.
013376de 1566 $DB->delete_records('config_plugins', array('plugin' => $plugin));
ac7af0da 1567 // Next delete any suspect settings from config.
a4193166
PS
1568 $like = $DB->sql_like('name', '?', true, true, false, '|');
1569 $params = array($DB->sql_like_escape($plugin.'_', '|') . '%');
1570 $DB->delete_records_select('config', $like, $params);
007bfe8b
SH
1571 // Finally clear both the plugin cache and the core cache (suspect settings now removed from core).
1572 cache_helper::invalidate_by_definition('core', 'config', array(), array('core', $plugin));
1573
013376de 1574 return true;
4b600aa0 1575}
1576
4413941f 1577/**
efb8c375 1578 * Use this function to get a list of users from a config setting of type admin_setting_users_with_capability.
adf176d7
PS
1579 *
1580 * All users are verified if they still have the necessary capability.
1581 *
b3d960e6 1582 * @param string $value the value of the config setting.
4413941f 1583 * @param string $capability the capability - must match the one passed to the admin_setting_users_with_capability constructor.
ac7af0da 1584 * @param bool $includeadmins include administrators.
4413941f 1585 * @return array of user objects.
1586 */
adf176d7 1587function get_users_from_config($value, $capability, $includeadmins = true) {
adf176d7
PS
1588 if (empty($value) or $value === '$@NONE@$') {
1589 return array();
4413941f 1590 }
adf176d7 1591
ac7af0da 1592 // We have to make sure that users still have the necessary capability,
adf176d7 1593 // it should be faster to fetch them all first and then test if they are present
ac7af0da 1594 // instead of validating them one-by-one.
b0c6dc1c 1595 $users = get_users_by_capability(context_system::instance(), $capability);
adf176d7
PS
1596 if ($includeadmins) {
1597 $admins = get_admins();
1598 foreach ($admins as $admin) {
1599 $users[$admin->id] = $admin;
1600 }
1601 }
1602
1603 if ($value === '$@ALL@$') {
1604 return $users;
1605 }
1606
ac7af0da 1607 $result = array(); // Result in correct order.
adf176d7
PS
1608 $allowed = explode(',', $value);
1609 foreach ($allowed as $uid) {
1610 if (isset($users[$uid])) {
1611 $user = $users[$uid];
1612 $result[$user->id] = $user;
1613 }
1614 }
1615
1616 return $result;
4413941f 1617}
1618
f87eab7e
PS
1619
1620/**
ac7af0da 1621 * Invalidates browser caches and cached data in temp.
52642d0d 1622 *
f87eab7e
PS
1623 * @return void
1624 */
1625function purge_all_caches() {
e3389c83
MJ
1626 purge_caches();
1627}
f87eab7e 1628
e3389c83
MJ
1629/**
1630 * Selectively invalidate different types of cache.
1631 *
1632 * Purges the cache areas specified. By default, this will purge all caches but can selectively purge specific
1633 * areas alone or in combination.
1634 *
1635 * @param bool[] $options Specific parts of the cache to purge. Valid options are:
1636 * 'muc' Purge MUC caches?
1637 * 'theme' Purge theme cache?
1638 * 'lang' Purge language string cache?
1639 * 'js' Purge javascript cache?
1640 * 'filter' Purge text filter cache?
1641 * 'other' Purge all other caches?
1642 */
1643function purge_caches($options = []) {
1644 $defaults = array_fill_keys(['muc', 'theme', 'lang', 'js', 'filter', 'other'], false);
1645 if (empty(array_filter($options))) {
1646 $options = array_fill_keys(array_keys($defaults), true); // Set all options to true.
1647 } else {
1648 $options = array_merge($defaults, array_intersect_key($options, $defaults)); // Override defaults with specified options.
1649 }
1650 if ($options['muc']) {
1651 cache_helper::purge_all();
1652 }
1653 if ($options['theme']) {
1654 theme_reset_all_caches();
1655 }
1656 if ($options['lang']) {
1657 get_string_manager()->reset_caches();
1658 }
1659 if ($options['js']) {
1660 js_reset_all_caches();
1661 }
1662 if ($options['filter']) {
1663 reset_text_filters_cache();
1664 }
1665 if ($options['other']) {
1666 purge_other_caches();
1667 }
1668}
1669
1670/**
1671 * Purge all non-MUC caches not otherwise purged in purge_caches.
1672 *
1673 * IMPORTANT - If you are adding anything here to do with the cache directory you should also have a look at
1674 * {@link phpunit_util::reset_dataroot()}
1675 */
1676function purge_other_caches() {
1677 global $DB, $CFG;
2f1e464a 1678 core_text::reset_caches();
e87214bd
PS
1679 if (class_exists('core_plugin_manager')) {
1680 core_plugin_manager::reset_caches();
bde002b8 1681 }
f87eab7e 1682
299cfee5
MG
1683 // Bump up cacherev field for all courses.
1684 try {
1685 increment_revision_number('course', 'cacherev', '');
1686 } catch (moodle_exception $e) {
1687 // Ignore exception since this function is also called before upgrade script when field course.cacherev does not exist yet.
1688 }
1689
d79d5ac2 1690 $DB->reset_caches();
d6a1f63b 1691
ac7af0da 1692 // Purge all other caches: rss, simplepie, etc.
54ced30d 1693 clearstatcache();
365bec4c 1694 remove_dir($CFG->cachedir.'', true);
f87eab7e 1695
ac7af0da 1696 // Make sure cache dir is writable, throws exception if not.
5a87c912 1697 make_cache_directory('');
f87eab7e 1698
85b38061
PS
1699 // This is the only place where we purge local caches, we are only adding files there.
1700 // The $CFG->localcachedirpurged flag forces local directories to be purged on cluster nodes.
1701 remove_dir($CFG->localcachedir, true);
1702 set_config('localcachedirpurged', time());
1703 make_localcache_directory('', true);
309ae892 1704 \core\task\manager::clear_static_caches();
f87eab7e
PS
1705}
1706
bafd7e78 1707/**
1708 * Get volatile flags
1709 *
1710 * @param string $type
ac7af0da
SH
1711 * @param int $changedsince default null
1712 * @return array records array
bafd7e78 1713 */
ac7af0da 1714function get_cache_flags($type, $changedsince = null) {
ae040d4b 1715 global $DB;
bafd7e78 1716
ac7af0da 1717 $params = array('type' => $type, 'expiry' => time());
ae040d4b 1718 $sqlwhere = "flagtype = :type AND expiry >= :expiry";
ac7af0da 1719 if ($changedsince !== null) {
ae040d4b 1720 $params['changedsince'] = $changedsince;
1721 $sqlwhere .= " AND timemodified > :changedsince";
bafd7e78 1722 }
1723 $cf = array();
ae040d4b 1724 if ($flags = $DB->get_records_select('cache_flags', $sqlwhere, $params, '', 'name,value')) {
bafd7e78 1725 foreach ($flags as $flag) {
1726 $cf[$flag->name] = $flag->value;
1727 }
1728 }
1729 return $cf;
1730}
1731
a489cf72 1732/**
1733 * Get volatile flags
1734 *
1735 * @param string $type
1736 * @param string $name
ac7af0da
SH
1737 * @param int $changedsince default null
1738 * @return string|false The cache flag value or false
a489cf72 1739 */
ac7af0da 1740function get_cache_flag($type, $name, $changedsince=null) {
ae040d4b 1741 global $DB;
a489cf72 1742
ac7af0da 1743 $params = array('type' => $type, 'name' => $name, 'expiry' => time());
a489cf72 1744
ae040d4b 1745 $sqlwhere = "flagtype = :type AND name = :name AND expiry >= :expiry";
ac7af0da 1746 if ($changedsince !== null) {
ae040d4b 1747 $params['changedsince'] = $changedsince;
1748 $sqlwhere .= " AND timemodified > :changedsince";
a489cf72 1749 }
ae040d4b 1750
1751 return $DB->get_field_select('cache_flags', 'value', $sqlwhere, $params);
a489cf72 1752}
bafd7e78 1753
1754/**
1755 * Set a volatile flag
1756 *
1757 * @param string $type the "type" namespace for the key
1758 * @param string $name the key to set
ac7af0da 1759 * @param string $value the value to set (without magic quotes) - null will remove the flag
bafd7e78 1760 * @param int $expiry (optional) epoch indicating expiry - defaults to now()+ 24hs
0d0a8bf6 1761 * @return bool Always returns true
bafd7e78 1762 */
ac7af0da 1763function set_cache_flag($type, $name, $value, $expiry = null) {
ae040d4b 1764 global $DB;
bafd7e78 1765
1766 $timemodified = time();
ac7af0da 1767 if ($expiry === null || $expiry < $timemodified) {
bafd7e78 1768 $expiry = $timemodified + 24 * 60 * 60;
1769 } else {
1770 $expiry = (int)$expiry;
1771 }
1772
ac7af0da
SH
1773 if ($value === null) {
1774 unset_cache_flag($type, $name);
013376de 1775 return true;
bafd7e78 1776 }
1777
ac7af0da
SH
1778 if ($f = $DB->get_record('cache_flags', array('name' => $name, 'flagtype' => $type), '*', IGNORE_MULTIPLE)) {
1779 // This is a potential problem in DEBUG_DEVELOPER.
128f0984 1780 if ($f->value == $value and $f->expiry == $expiry and $f->timemodified == $timemodified) {
ac7af0da 1781 return true; // No need to update.
128f0984 1782 }
ae040d4b 1783 $f->value = $value;
bafd7e78 1784 $f->expiry = $expiry;
1785 $f->timemodified = $timemodified;
013376de 1786 $DB->update_record('cache_flags', $f);
bafd7e78 1787 } else {
365a5941 1788 $f = new stdClass();
bafd7e78 1789 $f->flagtype = $type;
1790 $f->name = $name;
ae040d4b 1791 $f->value = $value;
bafd7e78 1792 $f->expiry = $expiry;
1793 $f->timemodified = $timemodified;
013376de 1794 $DB->insert_record('cache_flags', $f);
bafd7e78 1795 }
013376de 1796 return true;
bafd7e78 1797}
1798
1799/**
1800 * Removes a single volatile flag
1801 *
1802 * @param string $type the "type" namespace for the key
1803 * @param string $name the key to set
bafd7e78 1804 * @return bool
1805 */
1806function unset_cache_flag($type, $name) {
ae040d4b 1807 global $DB;
ac7af0da 1808 $DB->delete_records('cache_flags', array('name' => $name, 'flagtype' => $type));
013376de 1809 return true;
bafd7e78 1810}
1811
1812/**
1813 * Garbage-collect volatile flags
1814 *
0d0a8bf6 1815 * @return bool Always returns true
bafd7e78 1816 */
1817function gc_cache_flags() {
ae040d4b 1818 global $DB;
013376de 1819 $DB->delete_records_select('cache_flags', 'expiry < ?', array(time()));
1820 return true;
bafd7e78 1821}
a4080313 1822
ac7af0da 1823// USER PREFERENCE API.
2660377f 1824
7cf1c7bd 1825/**
39461de3
PS
1826 * Refresh user preference cache. This is used most often for $USER
1827 * object that is stored in session, but it also helps with performance in cron script.
0d0a8bf6 1828 *
39461de3
PS
1829 * Preferences for each user are loaded on first use on every page, then again after the timeout expires.
1830 *
4d6b40a0
GGC
1831 * @package core
1832 * @category preference
1833 * @access public
1834 * @param stdClass $user User object. Preferences are preloaded into 'preference' property
1835 * @param int $cachelifetime Cache life time on the current page (in seconds)
1836 * @throws coding_exception
1837 * @return null
7cf1c7bd 1838 */
39461de3
PS
1839function check_user_preferences_loaded(stdClass $user, $cachelifetime = 120) {
1840 global $DB;
ac7af0da
SH
1841 // Static cache, we need to check on each page load, not only every 2 minutes.
1842 static $loadedusers = array();
2660377f 1843
39461de3
PS
1844 if (!isset($user->id)) {
1845 throw new coding_exception('Invalid $user parameter in check_user_preferences_loaded() call, missing id field');
1846 }
2660377f 1847
39461de3 1848 if (empty($user->id) or isguestuser($user->id)) {
ac7af0da 1849 // No permanent storage for not-logged-in users and guest.
39461de3
PS
1850 if (!isset($user->preference)) {
1851 $user->preference = array();
2660377f 1852 }
39461de3 1853 return;
2660377f 1854 }
70812e39 1855
39461de3 1856 $timenow = time();
070e2616 1857
39461de3
PS
1858 if (isset($loadedusers[$user->id]) and isset($user->preference) and isset($user->preference['_lastloaded'])) {
1859 // Already loaded at least once on this page. Are we up to date?
1860 if ($user->preference['_lastloaded'] + $cachelifetime > $timenow) {
ac7af0da 1861 // No need to reload - we are on the same page and we loaded prefs just a moment ago.
39461de3 1862 return;
70812e39 1863
39461de3 1864 } else if (!get_cache_flag('userpreferenceschanged', $user->id, $user->preference['_lastloaded'])) {
ac7af0da 1865 // No change since the lastcheck on this page.
39461de3
PS
1866 $user->preference['_lastloaded'] = $timenow;
1867 return;
70812e39 1868 }
c6d15803 1869 }
346c3e2f 1870
ac7af0da 1871 // OK, so we have to reload all preferences.
39461de3 1872 $loadedusers[$user->id] = true;
ac7af0da 1873 $user->preference = $DB->get_records_menu('user_preferences', array('userid' => $user->id), '', 'name,value'); // All values.
39461de3 1874 $user->preference['_lastloaded'] = $timenow;
2660377f 1875}
1876
1877/**
ac7af0da 1878 * Called from set/unset_user_preferences, so that the prefs can be correctly reloaded in different sessions.
39461de3
PS
1879 *
1880 * NOTE: internal function, do not call from other code.
0d0a8bf6 1881 *
4d6b40a0 1882 * @package core
ac7af0da
SH
1883 * @access private
1884 * @param integer $userid the user whose prefs were changed.
2660377f 1885 */
1886function mark_user_preferences_changed($userid) {
39461de3
PS
1887 global $CFG;
1888
1889 if (empty($userid) or isguestuser($userid)) {
ac7af0da 1890 // No cache flags for guest and not-logged-in users.
39461de3 1891 return;
2660377f 1892 }
39461de3 1893
2660377f 1894 set_cache_flag('userpreferenceschanged', $userid, 1, time() + $CFG->sessiontimeout);
70812e39 1895}
1896
7cf1c7bd 1897/**
39461de3 1898 * Sets a preference for the specified user.
0d0a8bf6 1899 *
4d6b40a0 1900 * If a $user object is submitted it's 'preference' property is used for the preferences cache.
0d0a8bf6 1901 *
6e65554e
MG
1902 * When additional validation/permission check is needed it is better to use {@see useredit_update_user_preference()}
1903 *
4d6b40a0
GGC
1904 * @package core
1905 * @category preference
1906 * @access public
1907 * @param string $name The key to set as preference for the specified user
1908 * @param string $value The value to set for the $name key in the specified user's
1909 * record, null means delete current value.
1910 * @param stdClass|int|null $user A moodle user object or id, null means current user
1911 * @throws coding_exception
1912 * @return bool Always true or exception
7cf1c7bd 1913 */
39461de3 1914function set_user_preference($name, $value, $user = null) {
ae040d4b 1915 global $USER, $DB;
70812e39 1916
39461de3
PS
1917 if (empty($name) or is_numeric($name) or $name === '_lastloaded') {
1918 throw new coding_exception('Invalid preference name in set_user_preference() call');
70812e39 1919 }
1920
39461de3 1921 if (is_null($value)) {
ac7af0da 1922 // Null means delete current.
39461de3
PS
1923 return unset_user_preference($name, $user);
1924 } else if (is_object($value)) {
1925 throw new coding_exception('Invalid value in set_user_preference() call, objects are not allowed');
1926 } else if (is_array($value)) {
1927 throw new coding_exception('Invalid value in set_user_preference() call, arrays are not allowed');
1928 }
ac7af0da 1929 // Value column maximum length is 1333 characters.
39461de3 1930 $value = (string)$value;
2f1e464a 1931 if (core_text::strlen($value) > 1333) {
8e54ce97
AD
1932 throw new coding_exception('Invalid value in set_user_preference() call, value is is too long for the value column');
1933 }
39461de3
PS
1934
1935 if (is_null($user)) {
1936 $user = $USER;
1937 } else if (isset($user->id)) {
ac7af0da 1938 // It is a valid object.
39461de3 1939 } else if (is_numeric($user)) {
ac7af0da 1940 $user = (object)array('id' => (int)$user);
346c3e2f 1941 } else {
39461de3 1942 throw new coding_exception('Invalid $user parameter in set_user_preference() call');
346c3e2f 1943 }
1944
39461de3
PS
1945 check_user_preferences_loaded($user);
1946
1947 if (empty($user->id) or isguestuser($user->id)) {
ac7af0da 1948 // No permanent storage for not-logged-in users and guest.
39461de3
PS
1949 $user->preference[$name] = $value;
1950 return true;
1951 }
346c3e2f 1952
ac7af0da 1953 if ($preference = $DB->get_record('user_preferences', array('userid' => $user->id, 'name' => $name))) {
39461de3 1954 if ($preference->value === $value and isset($user->preference[$name]) and $user->preference[$name] === $value) {
ac7af0da 1955 // Preference already set to this value.
a1244706 1956 return true;
1957 }
ac7af0da 1958 $DB->set_field('user_preferences', 'value', $value, array('id' => $preference->id));
70812e39 1959
1960 } else {
365a5941 1961 $preference = new stdClass();
39461de3 1962 $preference->userid = $user->id;
ae040d4b 1963 $preference->name = $name;
39461de3 1964 $preference->value = $value;
013376de 1965 $DB->insert_record('user_preferences', $preference);
2660377f 1966 }
1967
ac7af0da 1968 // Update value in cache.
39461de3 1969 $user->preference[$name] = $value;
4ba4ecfa 1970 // Update the $USER in case where we've not a direct reference to $USER.
2524990d
TH
1971 if ($user !== $USER && $user->id == $USER->id) {
1972 $USER->preference[$name] = $value;
1973 }
39461de3 1974
ac7af0da 1975 // Set reload flag for other sessions.
39461de3 1976 mark_user_preferences_changed($user->id);
346c3e2f 1977
013376de 1978 return true;
2660377f 1979}
1980
1981/**
1982 * Sets a whole array of preferences for the current user
0d0a8bf6 1983 *
4d6b40a0 1984 * If a $user object is submitted it's 'preference' property is used for the preferences cache.
39461de3 1985 *
4d6b40a0
GGC
1986 * @package core
1987 * @category preference
1988 * @access public
1989 * @param array $prefarray An array of key/value pairs to be set
1990 * @param stdClass|int|null $user A moodle user object or id, null means current user
1991 * @return bool Always true or exception
2660377f 1992 */
39461de3 1993function set_user_preferences(array $prefarray, $user = null) {
2660377f 1994 foreach ($prefarray as $name => $value) {
39461de3 1995 set_user_preference($name, $value, $user);
2660377f 1996 }
013376de 1997 return true;
70812e39 1998}
1999
6eb3e776 2000/**
2001 * Unsets a preference completely by deleting it from the database
0d0a8bf6 2002 *
4d6b40a0 2003 * If a $user object is submitted it's 'preference' property is used for the preferences cache.
0d0a8bf6 2004 *
4d6b40a0
GGC
2005 * @package core
2006 * @category preference
2007 * @access public
2008 * @param string $name The key to unset as preference for the specified user
2009 * @param stdClass|int|null $user A moodle user object or id, null means current user
2010 * @throws coding_exception
2011 * @return bool Always true or exception
6eb3e776 2012 */
39461de3 2013function unset_user_preference($name, $user = null) {
ae040d4b 2014 global $USER, $DB;
6eb3e776 2015
39461de3
PS
2016 if (empty($name) or is_numeric($name) or $name === '_lastloaded') {
2017 throw new coding_exception('Invalid preference name in unset_user_preference() call');
2018 }
2019
2020 if (is_null($user)) {
2021 $user = $USER;
2022 } else if (isset($user->id)) {
ac7af0da 2023 // It is a valid object.
39461de3 2024 } else if (is_numeric($user)) {
ac7af0da 2025 $user = (object)array('id' => (int)$user);
346c3e2f 2026 } else {
39461de3 2027 throw new coding_exception('Invalid $user parameter in unset_user_preference() call');
346c3e2f 2028 }
2029
39461de3 2030 check_user_preferences_loaded($user);
013376de 2031
39461de3 2032 if (empty($user->id) or isguestuser($user->id)) {
ac7af0da 2033 // No permanent storage for not-logged-in user and guest.
39461de3
PS
2034 unset($user->preference[$name]);
2035 return true;
70812e39 2036 }
2037
ac7af0da
SH
2038 // Delete from DB.
2039 $DB->delete_records('user_preferences', array('userid' => $user->id, 'name' => $name));
39461de3 2040
ac7af0da 2041 // Delete the preference from cache.
39461de3 2042 unset($user->preference[$name]);
4ba4ecfa 2043 // Update the $USER in case where we've not a direct reference to $USER.
2524990d
TH
2044 if ($user !== $USER && $user->id == $USER->id) {
2045 unset($USER->preference[$name]);
2046 }
39461de3 2047
ac7af0da 2048 // Set reload flag for other sessions.
39461de3
PS
2049 mark_user_preferences_changed($user->id);
2050
013376de 2051 return true;
70812e39 2052}
2053
7cf1c7bd 2054/**
0d0a8bf6 2055 * Used to fetch user preference(s)
2056 *
7cf1c7bd 2057 * If no arguments are supplied this function will return
361855e6 2058 * all of the current user preferences as an array.
0d0a8bf6 2059 *
7cf1c7bd 2060 * If a name is specified then this function
2061 * attempts to return that particular preference value. If
2062 * none is found, then the optional value $default is returned,
ac7af0da 2063 * otherwise null.
0d0a8bf6 2064 *
4d6b40a0 2065 * If a $user object is submitted it's 'preference' property is used for the preferences cache.
39461de3 2066 *
4d6b40a0
GGC
2067 * @package core
2068 * @category preference
2069 * @access public
2070 * @param string $name Name of the key to use in finding a preference value
2071 * @param mixed|null $default Value to be returned if the $name key is not set in the user preferences
2072 * @param stdClass|int|null $user A moodle user object or id, null means current user
2073 * @throws coding_exception
2074 * @return string|mixed|null A string containing the value of a single preference. An
2075 * array with all of the preferences or null
7cf1c7bd 2076 */
39461de3
PS
2077function get_user_preferences($name = null, $default = null, $user = null) {
2078 global $USER;
70812e39 2079
39461de3 2080 if (is_null($name)) {
ac7af0da 2081 // All prefs.
39461de3
PS
2082 } else if (is_numeric($name) or $name === '_lastloaded') {
2083 throw new coding_exception('Invalid preference name in get_user_preferences() call');
2084 }
346c3e2f 2085
39461de3
PS
2086 if (is_null($user)) {
2087 $user = $USER;
2088 } else if (isset($user->id)) {
ac7af0da 2089 // Is a valid object.
39461de3 2090 } else if (is_numeric($user)) {
ac7af0da 2091 $user = (object)array('id' => (int)$user);
39461de3
PS
2092 } else {
2093 throw new coding_exception('Invalid $user parameter in get_user_preferences() call');
2094 }
2095
2096 check_user_preferences_loaded($user);
346c3e2f 2097
39461de3 2098 if (empty($name)) {
ac7af0da
SH
2099 // All values.
2100 return $user->preference;
39461de3 2101 } else if (isset($user->preference[$name])) {
ac7af0da
SH
2102 // The single string value.
2103 return $user->preference[$name];
346c3e2f 2104 } else {
ac7af0da
SH
2105 // Default value (null if not specified).
2106 return $default;
70812e39 2107 }
70812e39 2108}
2109
ac7af0da 2110// FUNCTIONS FOR HANDLING TIME.
39917a09 2111
7cf1c7bd 2112/**
e83bcc10 2113 * Given Gregorian date parts in user time produce a GMT timestamp.
7cf1c7bd 2114 *
9df12115
RT
2115 * @package core
2116 * @category time
68fbd8e1 2117 * @param int $year The year part to create timestamp of
2118 * @param int $month The month part to create timestamp of
2119 * @param int $day The day part to create timestamp of
2120 * @param int $hour The hour part to create timestamp of
2121 * @param int $minute The minute part to create timestamp of
2122 * @param int $second The second part to create timestamp of
9df12115
RT
2123 * @param int|float|string $timezone Timezone modifier, used to calculate GMT time offset.
2124 * if 99 then default user's timezone is used {@link http://docs.moodle.org/dev/Time_API#Timezone}
6a0bf5c4
RT
2125 * @param bool $applydst Toggle Daylight Saving Time, default true, will be
2126 * applied only if timezone is 99 or string.
9df12115 2127 * @return int GMT timestamp
7cf1c7bd 2128 */
9f1f6daf 2129function make_timestamp($year, $month=1, $day=1, $hour=0, $minute=0, $second=0, $timezone=99, $applydst=true) {
d6e7a63d
PS
2130 $date = new DateTime('now', core_date::get_user_timezone_object($timezone));
2131 $date->setDate((int)$year, (int)$month, (int)$day);
2132 $date->setTime((int)$hour, (int)$minute, (int)$second);
39917a09 2133
d6e7a63d 2134 $time = $date->getTimestamp();
33998d30 2135
9f2b916d
RT
2136 if ($time === false) {
2137 throw new coding_exception('getTimestamp() returned false, please ensure you have passed correct values.'.
2138 ' This can fail if year is more than 2038 and OS is 32 bit windows');
2139 }
2140
d6e7a63d
PS
2141 // Moodle BC DST stuff.
2142 if (!$applydst) {
2143 $time += dst_offset_on($time, $timezone);
9f1f6daf 2144 }
2145
196f2619 2146 return $time;
85cafb3e 2147
39917a09 2148}
2149
7cf1c7bd 2150/**
0d0a8bf6 2151 * Format a date/time (seconds) as weeks, days, hours etc as needed
2152 *
7cf1c7bd 2153 * Given an amount of time in seconds, returns string
8c42eef3 2154 * formatted nicely as years, days, hours etc as needed
7cf1c7bd 2155 *
9df12115
RT
2156 * @package core
2157 * @category time
2f87145b 2158 * @uses MINSECS
2159 * @uses HOURSECS
2160 * @uses DAYSECS
5602f7cf 2161 * @uses YEARSECS
0d0a8bf6 2162 * @param int $totalsecs Time in seconds
ac7af0da 2163 * @param stdClass $str Should be a time object
0d0a8bf6 2164 * @return string A nicely formatted date/time string
7cf1c7bd 2165 */
ac7af0da 2166function format_time($totalsecs, $str = null) {
c7e3ac2a 2167
6b174680 2168 $totalsecs = abs($totalsecs);
c7e3ac2a 2169
ac7af0da
SH
2170 if (!$str) {
2171 // Create the str structure the slow way.
b85b25eb 2172 $str = new stdClass();
b0ccd3fb 2173 $str->day = get_string('day');
2174 $str->days = get_string('days');
2175 $str->hour = get_string('hour');
2176 $str->hours = get_string('hours');
2177 $str->min = get_string('min');
2178 $str->mins = get_string('mins');
2179 $str->sec = get_string('sec');
2180 $str->secs = get_string('secs');
5602f7cf 2181 $str->year = get_string('year');
2182 $str->years = get_string('years');
8dbed6be 2183 }
2184
5602f7cf 2185 $years = floor($totalsecs/YEARSECS);
2186 $remainder = $totalsecs - ($years*YEARSECS);
5602f7cf 2187 $days = floor($remainder/DAYSECS);
7a5672c9 2188 $remainder = $totalsecs - ($days*DAYSECS);
2189 $hours = floor($remainder/HOURSECS);
2190 $remainder = $remainder - ($hours*HOURSECS);
2191 $mins = floor($remainder/MINSECS);
2192 $secs = $remainder - ($mins*MINSECS);
8dbed6be 2193
2194 $ss = ($secs == 1) ? $str->sec : $str->secs;
2195 $sm = ($mins == 1) ? $str->min : $str->mins;
2196 $sh = ($hours == 1) ? $str->hour : $str->hours;
2197 $sd = ($days == 1) ? $str->day : $str->days;
5602f7cf 2198 $sy = ($years == 1) ? $str->year : $str->years;
8dbed6be 2199
5602f7cf 2200 $oyears = '';
b0ccd3fb 2201 $odays = '';
2202 $ohours = '';
2203 $omins = '';
2204 $osecs = '';
9c9f7d77 2205
ac7af0da
SH
2206 if ($years) {
2207 $oyears = $years .' '. $sy;
2208 }
2209 if ($days) {
2210 $odays = $days .' '. $sd;
2211 }
2212 if ($hours) {
2213 $ohours = $hours .' '. $sh;
2214 }
2215 if ($mins) {
2216 $omins = $mins .' '. $sm;
2217 }
2218 if ($secs) {
2219 $osecs = $secs .' '. $ss;
2220 }
2221
2222 if ($years) {
2223 return trim($oyears .' '. $odays);
2224 }
2225 if ($days) {
2226 return trim($odays .' '. $ohours);
2227 }
2228 if ($hours) {
2229 return trim($ohours .' '. $omins);
2230 }
2231 if ($mins) {
2232 return trim($omins .' '. $osecs);
2233 }
2234 if ($secs) {
2235 return $osecs;
2236 }
b0ccd3fb 2237 return get_string('now');
6b174680 2238}
f9903ed0 2239
7cf1c7bd 2240/**
f59ab4ad 2241 * Returns a formatted string that represents a date in user time.
7cf1c7bd 2242 *
9df12115
RT
2243 * @package core
2244 * @category time
0a0cf09a 2245 * @param int $date the timestamp in UTC, as obtained from the database.
2246 * @param string $format strftime format. You should probably get this using
9df12115 2247 * get_string('strftime...', 'langconfig');
f59ab4ad 2248 * @param int|float|string $timezone by default, uses the user's time zone. if numeric and
9df12115
RT
2249 * not 99 then daylight saving will not be added.
2250 * {@link http://docs.moodle.org/dev/Time_API#Timezone}
0a0cf09a 2251 * @param bool $fixday If true (default) then the leading zero from %d is removed.
9df12115 2252 * If false then the leading zero is maintained.
d9498b38 2253 * @param bool $fixhour If true (default) then the leading zero from %I is removed.
0a0cf09a 2254 * @return string the formatted date/time.
7cf1c7bd 2255 */
d9498b38 2256function userdate($date, $format = '', $timezone = 99, $fixday = true, $fixhour = true) {
6eafa4dd 2257 $calendartype = \core_calendar\type_factory::get_calendar_instance();
f59ab4ad 2258 return $calendartype->timestamp_to_date_string($date, $format, $timezone, $fixday, $fixhour);
873960de 2259}
2260
15396bba
FM
2261/**
2262 * Returns a formatted date ensuring it is UTF-8.
2263 *
2264 * If we are running under Windows convert to Windows encoding and then back to UTF-8
2265 * (because it's impossible to specify UTF-8 to fetch locale info in Win32).
2266 *
d6e7a63d 2267 * @param int $date the timestamp - since Moodle 2.9 this is a real UTC timestamp
15396bba 2268 * @param string $format strftime format.
d6e7a63d 2269 * @param int|float|string $tz the user timezone
15396bba 2270 * @return string the formatted date/time.
5bcfd504 2271 * @since Moodle 2.3.3
15396bba
FM
2272 */
2273function date_format_string($date, $format, $tz = 99) {
2274 global $CFG;
d61d3e82
RT
2275
2276 $localewincharset = null;
2277 // Get the calendar type user is using.
2278 if ($CFG->ostype == 'WINDOWS') {
2279 $calendartype = \core_calendar\type_factory::get_calendar_instance();
2280 $localewincharset = $calendartype->locale_win_charset();
2281 }
2282
d6e7a63d
PS
2283 if ($localewincharset) {
2284 $format = core_text::convert($format, 'utf-8', $localewincharset);
2285 }
2286
2287 date_default_timezone_set(core_date::get_user_timezone($tz));
2288 $datestring = strftime($format, $date);
2289 core_date::set_default_server_timezone();
2290
2291 if ($localewincharset) {
2292 $datestring = core_text::convert($datestring, $localewincharset, 'utf-8');
15396bba 2293 }
d6e7a63d 2294
15396bba
FM
2295 return $datestring;
2296}
2297
7cf1c7bd 2298/**
deed22ea 2299 * Given a $time timestamp in GMT (seconds since epoch),
40a6393e 2300 * returns an array that represents the Gregorian date in user time
7cf1c7bd 2301 *
9df12115
RT
2302 * @package core
2303 * @category time
deed22ea 2304 * @param int $time Timestamp in GMT
d6e7a63d 2305 * @param float|int|string $timezone user timezone
deed22ea 2306 * @return array An array that represents the date in user time
7cf1c7bd 2307 */
deed22ea 2308function usergetdate($time, $timezone=99) {
d6e7a63d
PS
2309 date_default_timezone_set(core_date::get_user_timezone($timezone));
2310 $result = getdate($time);
2311 core_date::set_default_server_timezone();
deed22ea 2312
d6e7a63d 2313 return $result;
d552ead0 2314}
2315
7cf1c7bd 2316/**
2317 * Given a GMT timestamp (seconds since epoch), offsets it by
2318 * the timezone. eg 3pm in India is 3pm GMT - 7 * 3600 seconds
2319 *
d6e7a63d
PS
2320 * NOTE: this function does not include DST properly,
2321 * you should use the PHP date stuff instead!
2322 *
9df12115
RT
2323 * @package core
2324 * @category time
9df12115 2325 * @param int $date Timestamp in GMT
d6e7a63d 2326 * @param float|int|string $timezone user timezone
c6d15803 2327 * @return int
7cf1c7bd 2328 */
d552ead0 2329function usertime($date, $timezone=99) {
d6e7a63d
PS
2330 $userdate = new DateTime('@' . $date);
2331 $userdate->setTimezone(core_date::get_user_timezone_object($timezone));
2332 $dst = dst_offset_on($date, $timezone);
a36166d3 2333
d6e7a63d 2334 return $date - $userdate->getOffset() + $dst;
d552ead0 2335}
2336
8c3dba73 2337/**
2338 * Given a time, return the GMT timestamp of the most recent midnight
2339 * for the current user.
2340 *
9df12115
RT
2341 * @package core
2342 * @category time
e34d817e 2343 * @param int $date Timestamp in GMT
d6e7a63d 2344 * @param float|int|string $timezone user timezone
0d0a8bf6 2345 * @return int Returns a GMT timestamp
8c3dba73 2346 */
edf7fe8c 2347function usergetmidnight($date, $timezone=99) {
edf7fe8c 2348
edf7fe8c 2349 $userdate = usergetdate($date, $timezone);
4606d9bb 2350
ac7af0da 2351 // Time of midnight of this user's day, in GMT.
02f0527d 2352 return make_timestamp($userdate['year'], $userdate['mon'], $userdate['mday'], 0, 0, 0, $timezone);
edf7fe8c 2353
2354}
2355
7cf1c7bd 2356/**
2357 * Returns a string that prints the user's timezone
2358 *
9df12115
RT
2359 * @package core
2360 * @category time
d6e7a63d 2361 * @param float|int|string $timezone user timezone
7cf1c7bd 2362 * @return string
2363 */
d552ead0 2364function usertimezone($timezone=99) {
d6e7a63d
PS
2365 $tz = core_date::get_user_timezone($timezone);
2366 return core_date::get_localised_timezone($tz);
61460dd6 2367}
2368
bbd3f2c4 2369/**
b2b68362 2370 * Returns a float or a string which denotes the user's timezone
2371 * 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)
2372 * means that for this timezone there are also DST rules to be taken into account
2373 * Checks various settings and picks the most dominant of those which have a value
bbd3f2c4 2374 *
9df12115
RT
2375 * @package core
2376 * @category time
2377 * @param float|int|string $tz timezone to calculate GMT time offset before
2378 * calculating user timezone, 99 is default user timezone
2379 * {@link http://docs.moodle.org/dev/Time_API#Timezone}
2380 * @return float|string
bbd3f2c4 2381 */
e8904995 2382function get_user_timezone($tz = 99) {
2383 global $USER, $CFG;
43b59916 2384
f30fe8d0 2385 $timezones = array(
e8904995 2386 $tz,
2387 isset($CFG->forcetimezone) ? $CFG->forcetimezone : 99,
43b59916 2388 isset($USER->timezone) ? $USER->timezone : 99,
2389 isset($CFG->timezone) ? $CFG->timezone : 99,
f30fe8d0 2390 );
43b59916 2391
e8904995 2392 $tz = 99;
43b59916 2393
ac7af0da 2394 // Loop while $tz is, empty but not zero, or 99, and there is another timezone is the array.
33683bc8
MG
2395 foreach ($timezones as $nextvalue) {
2396 if ((empty($tz) && !is_numeric($tz)) || $tz == 99) {
2397 $tz = $nextvalue;
2398 }
43b59916 2399 }
e8904995 2400 return is_numeric($tz) ? (float) $tz : $tz;
43b59916 2401}
2402
0d0a8bf6 2403/**
efb8c375 2404 * Calculates the Daylight Saving Offset for a given date/time (timestamp)
6a0bf5c4 2405 * - Note: Daylight saving only works for string timezones and not for float.
0d0a8bf6 2406 *
9df12115
RT
2407 * @package core
2408 * @category time
0d0a8bf6 2409 * @param int $time must NOT be compensated at all, it has to be a pure timestamp
d6e7a63d 2410 * @param int|float|string $strtimezone user timezone
0d0a8bf6 2411 * @return int
2412 */
ac7af0da 2413function dst_offset_on($time, $strtimezone = null) {
d6e7a63d
PS
2414 $tz = core_date::get_user_timezone($strtimezone);
2415 $date = new DateTime('@' . $time);
2416 $date->setTimezone(new DateTimeZone($tz));
2417 if ($date->format('I') == '1') {
2418 if ($tz === 'Australia/Lord_Howe') {
2419 return 1800;
c9e72798 2420 }
d6e7a63d 2421 return 3600;
c9e72798 2422 }
d6e7a63d 2423 return 0;
85cafb3e 2424}
02f0527d 2425
0d0a8bf6 2426/**
9df12115 2427 * Calculates when the day appears in specific month
0d0a8bf6 2428 *
9df12115
RT
2429 * @package core
2430 * @category time
2431 * @param int $startday starting day of the month
2432 * @param int $weekday The day when week starts (normally taken from user preferences)
2433 * @param int $month The month whose day is sought
2434 * @param int $year The year of the month whose day is sought
0d0a8bf6 2435 * @return int
2436 */
28902d99 2437function find_day_in_month($startday, $weekday, $month, $year) {
da304137 2438 $calendartype = \core_calendar\type_factory::get_calendar_instance();
8dc3f6cf 2439
2440 $daysinmonth = days_in_month($month, $year);
da304137 2441 $daysinweek = count($calendartype->get_weekdays());
8dc3f6cf 2442
ac7af0da 2443 if ($weekday == -1) {
28902d99 2444 // Don't care about weekday, so return:
2445 // abs($startday) if $startday != -1
ac7af0da 2446 // $daysinmonth otherwise.
28902d99 2447 return ($startday == -1) ? $daysinmonth : abs($startday);
8dc3f6cf 2448 }
2449
ac7af0da 2450 // From now on we 're looking for a specific weekday.
ac7af0da
SH
2451 // Give "end of month" its actual value, since we know it.
2452 if ($startday == -1) {
28902d99 2453 $startday = -1 * $daysinmonth;
2454 }
2455
ac7af0da 2456 // Starting from day $startday, the sign is the direction.
ac7af0da 2457 if ($startday < 1) {
28902d99 2458 $startday = abs($startday);
da304137 2459 $lastmonthweekday = dayofweek($daysinmonth, $month, $year);
8dc3f6cf 2460
ac7af0da 2461 // This is the last such weekday of the month.
8dc3f6cf 2462 $lastinmonth = $daysinmonth + $weekday - $lastmonthweekday;
ac7af0da 2463 if ($lastinmonth > $daysinmonth) {
da304137 2464 $lastinmonth -= $daysinweek;
42d36497 2465 }
8dc3f6cf 2466
ac7af0da
SH
2467 // Find the first such weekday <= $startday.
2468 while ($lastinmonth > $startday) {
da304137 2469 $lastinmonth -= $daysinweek;
42d36497 2470 }
8dc3f6cf 2471
2472 return $lastinmonth;
ac7af0da 2473 } else {
da304137 2474 $indexweekday = dayofweek($startday, $month, $year);
42d36497 2475
8dc3f6cf 2476 $diff = $weekday - $indexweekday;
ac7af0da 2477 if ($diff < 0) {
da304137 2478 $diff += $daysinweek;
42d36497 2479 }
42d36497 2480
ac7af0da 2481 // This is the first such weekday of the month equal to or after $startday.
28902d99 2482 $firstfromindex = $startday + $diff;
42d36497 2483
8dc3f6cf 2484 return $firstfromindex;
8dc3f6cf 2485 }
42d36497 2486}
2487
bbd3f2c4 2488/**
2489 * Calculate the number of days in a given month
2490 *
9df12115
RT
2491 * @package core
2492 * @category time
bbd3f2c4 2493 * @param int $month The month whose day count is sought
2494 * @param int $year The year of the month whose day count is sought
2495 * @return int
2496 */
42d36497 2497function days_in_month($month, $year) {
da304137
MN
2498 $calendartype = \core_calendar\type_factory::get_calendar_instance();
2499 return $calendartype->get_num_days_in_month($year, $month);
42d36497 2500}
2501
bbd3f2c4 2502/**
2503 * Calculate the position in the week of a specific calendar day
2504 *
9df12115
RT
2505 * @package core
2506 * @category time
bbd3f2c4 2507 * @param int $day The day of the date whose position in the week is sought
2508 * @param int $month The month of the date whose position in the week is sought
2509 * @param int $year The year of the date whose position in the week is sought
2510 * @return int
2511 */
8dc3f6cf 2512function dayofweek($day, $month, $year) {
da304137
MN
2513 $calendartype = \core_calendar\type_factory::get_calendar_instance();
2514 return $calendartype->get_weekday($year, $month, $day);
8dc3f6cf 2515}
2516
ac7af0da 2517// USER AUTHENTICATION AND LOGIN.
f9903ed0 2518
93f66983 2519/**
2520 * Returns full login url.
2521 *
93f66983 2522 * @return string login url
2523 */
999b54af 2524function get_login_url() {
93f66983 2525 global $CFG;
2526
b58764ff 2527 return "$CFG->wwwroot/login/index.php";
93f66983 2528}
2529
7cf1c7bd 2530/**
ec81373f 2531 * This function checks that the current user is logged in and has the
2532 * required privileges
2533 *
7cf1c7bd 2534 * This function checks that the current user is logged in, and optionally
ec81373f 2535 * whether they are allowed to be in a particular course and view a particular
2536 * course module.
2537 * If they are not logged in, then it redirects them to the site login unless
d2a9f7cc 2538 * $autologinguest is set and {@link $CFG}->autologinguests is set to 1 in which
ec81373f 2539 * case they are automatically logged in as guests.
2540 * If $courseid is given and the user is not enrolled in that course then the
2541 * user is redirected to the course enrolment page.
efb8c375 2542 * If $cm is given and the course module is hidden and the user is not a teacher
ec81373f 2543 * in the course then the user is redirected to the course home page.
7cf1c7bd 2544 *
191b267b 2545 * When $cm parameter specified, this function sets page layout to 'module'.
4f0c2d00 2546 * You need to change it manually later if some other layout needed.
191b267b 2547 *
f76249cc
PS
2548 * @package core_access
2549 * @category access
2550 *
33ebaf7c 2551 * @param mixed $courseorid id of the course or course object
0d0a8bf6 2552 * @param bool $autologinguest default true
bbd3f2c4 2553 * @param object $cm course module object
f4013c10 2554 * @param bool $setwantsurltome Define if we want to set $SESSION->wantsurl, defaults to
2555 * true. Used to avoid (=false) some scripts (file.php...) to set that variable,
2556 * in order to keep redirects working properly. MDL-14495
df997f84 2557 * @param bool $preventredirect set to true in scripts that can not redirect (CLI, rss feeds, etc.), throws exceptions
0d0a8bf6 2558 * @return mixed Void, exit, and die depending on path
ac7af0da
SH
2559 * @throws coding_exception
2560 * @throws require_login_exception
a428cf4a 2561 * @throws moodle_exception
7cf1c7bd 2562 */
ac7af0da 2563function require_login($courseorid = null, $autologinguest = true, $cm = null, $setwantsurltome = true, $preventredirect = false) {
f0202ae9 2564 global $CFG, $SESSION, $USER, $PAGE, $SITE, $DB, $OUTPUT;
d8ba183c 2565
f22f1caf
PS
2566 // Must not redirect when byteserving already started.
2567 if (!empty($_SERVER['HTTP_RANGE'])) {
2568 $preventredirect = true;
2569 }
2570
2ed6be87
AN
2571 if (AJAX_SCRIPT) {
2572 // We cannot redirect for AJAX scripts either.
2573 $preventredirect = true;
2574 }
2575
ac7af0da 2576 // Setup global $COURSE, themes, language and locale.
c13a5e71 2577 if (!empty($courseorid)) {
2578 if (is_object($courseorid)) {
2579 $course = $courseorid;
2580 } else if ($courseorid == SITEID) {
2581 $course = clone($SITE);
2582 } else {
74df2951 2583 $course = $DB->get_record('course', array('id' => $courseorid), '*', MUST_EXIST);
c13a5e71 2584 }
95d28870 2585 if ($cm) {
df997f84
PS
2586 if ($cm->course != $course->id) {
2587 throw new coding_exception('course and cm parameters in require_login() call do not match!!');
2588 }
ac7af0da 2589 // Make sure we have a $cm from get_fast_modinfo as this contains activity access details.
47148151 2590 if (!($cm instanceof cm_info)) {
ac7af0da 2591 // Note: nearly all pages call get_fast_modinfo anyway and it does not make any
0d8b6a69 2592 // db queries so this is not really a performance concern, however it is obviously
2593 // better if you use get_fast_modinfo to get the cm before calling this.
2594 $modinfo = get_fast_modinfo($course);
2595 $cm = $modinfo->get_cm($cm->id);
2596 }
95d28870 2597 }
e88462a0 2598 } else {
ac7af0da 2599 // Do not touch global $COURSE via $PAGE->set_course(),
df997f84
PS
2600 // the reasons is we need to be able to call require_login() at any time!!
2601 $course = $SITE;
2602 if ($cm) {
2603 throw new coding_exception('cm parameter in require_login() requires valid course parameter!');
2604 }
c13a5e71 2605 }
be933850 2606
aa4a6566
SH
2607 // If this is an AJAX request and $setwantsurltome is true then we need to override it and set it to false.
2608 // Otherwise the AJAX request URL will be set to $SESSION->wantsurl and events such as self enrolment in the future
2609 // risk leading the user back to the AJAX request URL.
2610 if ($setwantsurltome && defined('AJAX_SCRIPT') && AJAX_SCRIPT) {
2611 $setwantsurltome = false;
2612 }
2613
12fc11e7 2614 // Redirect to the login page if session has expired, only with dbsessions enabled (MDL-35029) to maintain current behaviour.
2ed6be87
AN
2615 if ((!isloggedin() or isguestuser()) && !empty($SESSION->has_timed_out) && !empty($CFG->dbsessions)) {
2616 if ($preventredirect) {
2617 throw new require_login_session_timeout_exception();
2618 } else {
2619 if ($setwantsurltome) {
2620 $SESSION->wantsurl = qualified_me();
2621 }
2622 redirect(get_login_url());
12fc11e7 2623 }
12fc11e7
DM
2624 }
2625
ac7af0da 2626 // If the user is not even logged in yet then make sure they are.
083c3743 2627 if (!isloggedin()) {
df997f84 2628 if ($autologinguest and !empty($CFG->guestloginbutton) and !empty($CFG->autologinguests)) {
999b54af 2629 if (!$guest = get_complete_user_data('id', $CFG->siteguest)) {
ac7af0da 2630 // Misconfigured site guest, just redirect to login page.
999b54af 2631 redirect(get_login_url());
ac7af0da 2632 exit; // Never reached.
df997f84 2633 }
999b54af 2634 $lang = isset($SESSION->lang) ? $SESSION->lang : $CFG->lang;
0342fc36 2635 complete_user_login($guest);
d9e07264 2636 $USER->autologinguest = true;
999b54af 2637 $SESSION->lang = $lang;
8a33e371 2638 } else {
ac7af0da 2639 // NOTE: $USER->site check was obsoleted by session test cookie, $USER->confirmed test is in login/index.php.
999b54af
PS
2640 if ($preventredirect) {
2641 throw new require_login_exception('You are not logged in');
2642 }
2643
2644 if ($setwantsurltome) {
f0202ae9 2645 $SESSION->wantsurl = qualified_me();
999b54af 2646 }
dcee0b94
SL
2647
2648 $referer = get_local_referer(false);
2649 if (!empty($referer)) {
2650 $SESSION->fromurl = $referer;
999b54af 2651 }
bf08e3f9
BH
2652
2653 // Give auth plugins an opportunity to authenticate or redirect to an external login page
2654 $authsequence = get_enabled_auth_plugins(true); // auths, in sequence
2655 foreach($authsequence as $authname) {
2656 $authplugin = get_auth_plugin($authname);
2657 $authplugin->pre_loginpage_hook();
2658 if (isloggedin()) {
2659 break;
2660 }
2661 }
2662
2663 // If we're still not logged in then go to the login page
2664 if (!isloggedin()) {
2665 redirect(get_login_url());
2666 exit; // Never reached.
2667 }
8a33e371 2668 }
f9903ed0 2669 }
808a3baa 2670
ac7af0da 2671 // Loginas as redirection if needed.
d79d5ac2 2672 if ($course->id != SITEID and \core\session\manager::is_loggedinas()) {
f6f66b03 2673 if ($USER->loginascontext->contextlevel == CONTEXT_COURSE) {
df997f84 2674 if ($USER->loginascontext->instanceid != $course->id) {
3887fe4a 2675 print_error('loginasonecourse', '', $CFG->wwwroot.'/course/view.php?id='.$USER->loginascontext->instanceid);
5e623a33 2676 }
f6f66b03 2677 }
2678 }
2679
ac7af0da 2680 // Check whether the user should be changing password (but only if it is REALLY them).
d79d5ac2 2681 if (get_user_preferences('auth_forcepasswordchange') && !\core\session\manager::is_loggedinas()) {
21e2dcd9 2682 $userauth = get_auth_plugin($USER->auth);
df997f84 2683 if ($userauth->can_change_password() and !$preventredirect) {
af572078 2684 if ($setwantsurltome) {
f0202ae9 2685 $SESSION->wantsurl = qualified_me();
af572078 2686 }
80274abf 2687 if ($changeurl = $userauth->change_password_url()) {
ac7af0da 2688 // Use plugin custom url.
80274abf 2689 redirect($changeurl);
1437f0a5 2690 } else {
ac7af0da 2691 // Use moodle internal method.
b58764ff 2692 redirect($CFG->wwwroot .'/login/change_password.php');
1437f0a5 2693 }
80e0f0b8
JL
2694 } else if ($userauth->can_change_password()) {
2695 throw new moodle_exception('forcepasswordchangenotice');
d35757eb 2696 } else {
80e0f0b8 2697 throw new moodle_exception('nopasswordchangeforced', 'auth');
d35757eb 2698 }
2699 }
083c3743 2700
8df850ad 2701 // Check that the user account is properly set up. If we can't redirect to
eeae783c
JL
2702 // edit their profile and this is not a WS request, perform just the lax check.
2703 // It will allow them to use filepicker on the profile edit page.
8df850ad 2704
eeae783c 2705 if ($preventredirect && !WS_SERVER) {
8df850ad
DM
2706 $usernotfullysetup = user_not_fully_set_up($USER, false);
2707 } else {
2708 $usernotfullysetup = user_not_fully_set_up($USER, true);
2709 }
2710
2711 if ($usernotfullysetup) {
df997f84 2712 if ($preventredirect) {
80e0f0b8 2713 throw new moodle_exception('usernotfullysetup');
df997f84 2714 }
af572078 2715 if ($setwantsurltome) {
f0202ae9 2716 $SESSION->wantsurl = qualified_me();
af572078 2717 }
b0ccd3fb 2718 redirect($CFG->wwwroot .'/user/edit.php?id='. $USER->id .'&amp;course='. SITEID);
808a3baa 2719 }
d8ba183c 2720
df997f84 2721 // Make sure the USER has a sesskey set up. Used for CSRF protection.
04280e85 2722 sesskey();
366dfa60 2723
a428cf4a
JD
2724 // Do not bother admins with any formalities, except for activities pending deletion.
2725 if (is_siteadmin() && !($cm && $cm->deletioninprogress)) {
1edd3d6f
MG
2726 // Set the global $COURSE.
2727 if ($cm) {
2728 $PAGE->set_cm($cm, $course);
2729 $PAGE->set_pagelayout('incourse');
2730 } else if (!empty($courseorid)) {
2731 $PAGE->set_course($course);
2732 }
ac7af0da 2733 // Set accesstime or the user will appear offline which messes up messaging.
1560760f 2734 user_accesstime_log($course->id);
df997f84
PS
2735 return;
2736 }
2737
0bdc5785
DM
2738 // Scripts have a chance to declare that $USER->policyagreed should not be checked.
2739 // This is mostly for places where users are actually accepting the policies, to avoid the redirect loop.
2740 if (!defined('NO_SITEPOLICY_CHECK')) {
2741 define('NO_SITEPOLICY_CHECK', false);
2742 }
2743
ac7af0da 2744 // Check that the user has agreed to a site policy if there is one - do not test in case of admins.
0bdc5785 2745 // Do not test if the script explicitly asked for skipping the site policies check.
1727c939
MG
2746 if (!$USER->policyagreed && !is_siteadmin() && !NO_SITEPOLICY_CHECK) {
2747 $manager = new \core_privacy\local\sitepolicy\manager();
2748 if ($policyurl = $manager->get_redirect_url(isguestuser())) {
b593d49d 2749 if ($preventredirect) {
1727c939 2750 throw new moodle_exception('sitepolicynotagreed', 'error', '', $policyurl->out());
b593d49d 2751 }
af572078 2752 if ($setwantsurltome) {
f0202ae9 2753 $SESSION->wantsurl = qualified_me();
af572078 2754 }
1727c939 2755 redirect($policyurl);
027a1604 2756 }
1695b680 2757 }
2758
ac7af0da 2759 // Fetch the system context, the course context, and prefetch its child contexts.
b0c6dc1c
AG
2760 $sysctx = context_system::instance();
2761 $coursecontext = context_course::instance($course->id, MUST_EXIST);
df997f84 2762 if ($cm) {
b0c6dc1c 2763 $cmcontext = context_module::instance($cm->id, MUST_EXIST);
df997f84
PS
2764 } else {
2765 $cmcontext = null;
2766 }
21e2dcd9 2767
ac7af0da 2768 // If the site is currently under maintenance, then print a message.
59c66f92 2769 if (!empty($CFG->maintenance_enabled) and !has_capability('moodle/site:maintenanceaccess', $sysctx)) {
df997f84
PS
2770 if ($preventredirect) {
2771 throw new require_login_exception('Maintenance in progress');
2772 }
a4ea86f6 2773 $PAGE->set_context(null);
4fe2250a 2774 print_maintenance_message();
027a1604 2775 }
2776
ac7af0da 2777 // Make sure the course itself is not hidden.
df997f84 2778 if ($course->id == SITEID) {
ac7af0da 2779 // Frontpage can not be hidden.
df997f84 2780 } else {
f5c1e621 2781 if (is_role_switched($course->id)) {
ac7af0da 2782 // When switching roles ignore the hidden flag - user had to be in course to do the switch.
df997f84
PS
2783 } else {
2784 if (!$course->visible and !has_capability('moodle/course:viewhiddencourses', $coursecontext)) {
ac7af0da
SH
2785 // Originally there was also test of parent category visibility, BUT is was very slow in complex queries
2786 // involving "my courses" now it is also possible to simply hide all courses user is not enrolled in :-).
df997f84
PS
2787 if ($preventredirect) {
2788 throw new require_login_exception('Course is hidden');
2789 }
1edd3d6f 2790 $PAGE->set_context(null);
ac7af0da
SH
2791 // We need to override the navigation URL as the course won't have been added to the navigation and thus
2792 // the navigation will mess up when trying to find it.
a0a39b0d 2793 navigation_node::override_active_url(new moodle_url('/'));
df997f84
PS
2794 notice(get_string('coursehidden'), $CFG->wwwroot .'/');
2795 }
2796 }
2797 }
2798
ac7af0da 2799 // Is the user enrolled?
df997f84 2800 if ($course->id == SITEID) {
ac7af0da 2801 // Everybody is enrolled on the frontpage.
df997f84 2802 } else {
d79d5ac2 2803 if (\core\session\manager::is_loggedinas()) {
ac7af0da 2804 // Make sure the REAL person can access this course first.
d79d5ac2 2805 $realuser = \core\session\manager::get_realuser();
ac7af0da
SH
2806 if (!is_enrolled($coursecontext, $realuser->id, '', true) and
2807 !is_viewing($coursecontext, $realuser->id) and !is_siteadmin($realuser->id)) {
df997f84
PS
2808 if ($preventredirect) {
2809 throw new require_login_exception('Invalid course login-as access');
2810 }
1edd3d6f 2811 $PAGE->set_context(null);
df997f84
PS
2812 echo $OUTPUT->header();
2813 notice(get_string('studentnotallowed', '', fullname($USER, true)), $CFG->wwwroot .'/');
2814 }
2815 }
2816
df997f84
PS
2817 $access = false;
2818
dbd7282c 2819 if (is_role_switched($course->id)) {
ac7af0da 2820 // Ok, user had to be inside this course before the switch.
dbd7282c
PS
2821 $access = true;
2822
2823 } else if (is_viewing($coursecontext, $USER)) {
ac7af0da 2824 // Ok, no need to mess with enrol.
df997f84
PS
2825 $access = true;
2826
2827 } else {
2828 if (isset($USER->enrol['enrolled'][$course->id])) {
bbfdff34 2829 if ($USER->enrol['enrolled'][$course->id] > time()) {
df997f84 2830 $access = true;
bbfdff34
PS
2831 if (isset($USER->enrol['tempguest'][$course->id])) {
2832 unset($USER->enrol['tempguest'][$course->id]);
2833 remove_temp_course_roles($coursecontext);
2834 }
df997f84 2835 } else {
ac7af0da 2836 // Expired.
df997f84
PS
2837 unset($USER->enrol['enrolled'][$course->id]);
2838 }
2839 }
2840 if (isset($USER->enrol['tempguest'][$course->id])) {
2841 if ($USER->enrol['tempguest'][$course->id] == 0) {
2842 $access = true;
2843 } else if ($USER->enrol['tempguest'][$course->id] > time()) {
2844 $access = true;
2845 } else {
ac7af0da 2846 // Expired.
df997f84 2847 unset($USER->enrol['tempguest'][$course->id]);
e922fe23 2848 remove_temp_course_roles($coursecontext);
df997f84
PS
2849 }
2850 }
2851
ac7af0da
SH
2852 if (!$access) {
2853 // Cache not ok.
bbfdff34
PS
2854 $until = enrol_get_enrolment_end($coursecontext->instanceid, $USER->id);
2855 if ($until !== false) {
ac7af0da 2856 // Active participants may always access, a timestamp in the future, 0 (always) or false.
bbfdff34
PS
2857 if ($until == 0) {
2858 $until = ENROL_MAX_TIMESTAMP;
df997f84 2859 }
bbfdff34
PS
2860 $USER->enrol['enrolled'][$course->id] = $until;
2861 $access = true;
2862
2863 } else {
ac7af0da
SH
2864 $params = array('courseid' => $course->id, 'status' => ENROL_INSTANCE_ENABLED);
2865 $instances = $DB->get_records('enrol', $params, 'sortorder, id ASC');
bbfdff34 2866 $enrols = enrol_get_plugins(true);
ac7af0da
SH
2867 // First ask all enabled enrol instances in course if they want to auto enrol user.
2868 foreach ($instances as $instance) {
df997f84
PS
2869 if (!isset($enrols[$instance->enrol])) {
2870 continue;
2871 }
bbfdff34
PS
2872 // Get a duration for the enrolment, a timestamp in the future, 0 (always) or false.
2873 $until = $enrols[$instance->enrol]->try_autoenrol($instance);
df997f84 2874 if ($until !== false) {
bbfdff34
PS
2875 if ($until == 0) {
2876 $until = ENROL_MAX_TIMESTAMP;
2877 }
2878 $USER->enrol['enrolled'][$course->id] = $until;
df997f84
PS
2879 $access = true;
2880 break;
2881 }
2882 }
ac7af0da 2883 // If not enrolled yet try to gain temporary guest access.
bbfdff34 2884 if (!$access) {
ac7af0da 2885 foreach ($instances as $instance) {
bbfdff34
PS
2886 if (!isset($enrols[$instance->enrol])) {
2887 continue;
2888 }
2889 // Get a duration for the guest access, a timestamp in the future or false.
2890 $until = $enrols[$instance->enrol]->try_guestaccess($instance);
2891 if ($until !== false and $until > time()) {
2892 $USER->enrol['tempguest'][$course->id] = $until;
2893 $access = true;
2894 break;
2895 }
2896 }
2897 }
df997f84
PS
2898 }
2899 }
2900 }
2901
2902 if (!$access) {
2903 if ($preventredirect) {
2904 throw new require_login_exception('Not enrolled');
2905 }
af572078 2906 if ($setwantsurltome) {
f0202ae9 2907 $SESSION->wantsurl = qualified_me();
af572078 2908 }
b3cb7264 2909 redirect($CFG->wwwroot .'/enrol/index.php?id='. $course->id);
df997f84
PS
2910 }
2911 }
2912
a428cf4a
JD
2913 // Check whether the activity has been scheduled for deletion. If so, then deny access, even for admins.
2914 if ($cm && $cm->deletioninprogress) {
2915 if ($preventredirect) {
2916 throw new moodle_exception('activityisscheduledfordeletion');
2917 }
2918 require_once($CFG->dirroot . '/course/lib.php');
2919 redirect(course_get_url($course), get_string('activityisscheduledfordeletion', 'error'));
2920 }
2921
061e6b28 2922 // Check visibility of activity to current user; includes visible flag, conditional availability, etc.
0d8b6a69 2923 if ($cm && !$cm->uservisible) {
df997f84
PS
2924 if ($preventredirect) {
2925 throw new require_login_exception('Activity is hidden');
2926 }
592f3ae2
MG
2927 // Get the error message that activity is not available and why (if explanation can be shown to the user).
2928 $PAGE->set_course($course);
2929 $renderer = $PAGE->get_renderer('course');
2c3a34f0 2930 $message = $renderer->course_section_cm_unavailable_error_message($cm);
592f3ae2 2931 redirect(course_get_url($course), $message, null, \core\output\notification::NOTIFY_ERROR);
df997f84
PS
2932 }
2933
aad5b7f1 2934 // Set the global $COURSE.
2935 if ($cm) {
2936 $PAGE->set_cm($cm, $course);
2937 $PAGE->set_pagelayout('incourse');
2938 } else if (!empty($courseorid)) {
2939 $PAGE->set_course($course);
2940 }
2941
ac7af0da 2942 // Finally access granted, update lastaccess times.
df997f84 2943 user_accesstime_log($course->id);
f9903ed0 2944}
2945
c4d0753b 2946
c4d0753b 2947/**
2948 * This function just makes sure a user is logged out.
2949 *
f76249cc 2950 * @package core_access
ac7af0da 2951 * @category access
c4d0753b 2952 */
2953function require_logout() {
d79d5ac2 2954 global $USER, $DB;
c4d0753b 2955
d79d5ac2
PS
2956 if (!isloggedin()) {
2957 // This should not happen often, no need for hooks or events here.
2958 \core\session\manager::terminate_current();
2959 return;
c4d0753b 2960 }
2961
d79d5ac2 2962 // Execute hooks before action.
f9f9d187 2963 $authplugins = array();
d79d5ac2
PS
2964 $authsequence = get_enabled_auth_plugins();
2965 foreach ($authsequence as $authname) {
f9f9d187
SL
2966 $authplugins[$authname] = get_auth_plugin($authname);
2967 $authplugins[$authname]->prelogout_hook();
d79d5ac2
PS
2968 }
2969
2970 // Store info that gets removed during logout.
2971 $sid = session_id();
bb78e249 2972 $event = \core\event\user_loggedout::create(
d79d5ac2
PS
2973 array(
2974 'userid' => $USER->id,
2975 'objectid' => $USER->id,
2976 'other' => array('sessionid' => $sid),
2977 )
2978 );
2979 if ($session = $DB->get_record('sessions', array('sid'=>$sid))) {
2980 $event->add_record_snapshot('sessions', $session);
2981 }
bb78e249 2982
f9f9d187
SL
2983 // Clone of $USER object to be used by auth plugins.
2984 $user = fullclone($USER);
2985
d79d5ac2
PS
2986 // Delete session record and drop $_SESSION content.
2987 \core\session\manager::terminate_current();
2988
2989 // Trigger event AFTER action.
2990 $event->trigger();
f9f9d187
SL
2991
2992 // Hook to execute auth plugins redirection after event trigger.
2993 foreach ($authplugins as $authplugin) {
2994 $authplugin->postlogout_hook($user);
2995 }
c4d0753b 2996}
2997
7cf1c7bd 2998/**
0d0a8bf6 2999 * Weaker version of require_login()
3000 *
7cf1c7bd 3001 * This is a weaker version of {@link require_login()} which only requires login
3002 * when called from within a course rather than the site page, unless
3003 * the forcelogin option is turned on.
0d0a8bf6 3004 * @see require_login()
7cf1c7bd 3005 *
f76249cc
PS
3006 * @package core_access
3007 * @category access
3008 *
33ebaf7c 3009 * @param mixed $courseorid The course object or id in question
bbd3f2c4 3010 * @param bool $autologinguest Allow autologin guests if that is wanted
4febb58f 3011 * @param object $cm Course activity module if known
f4013c10 3012 * @param bool $setwantsurltome Define if we want to set $SESSION->wantsurl, defaults to
3013 * true. Used to avoid (=false) some scripts (file.php...) to set that variable,
3014 * in order to keep redirects working properly. MDL-14495
df997f84
PS
3015 * @param bool $preventredirect set to true in scripts that can not redirect (CLI, rss feeds, etc.), throws exceptions
3016 * @return void
ac7af0da 3017 * @throws coding_exception
7cf1c7bd 3018 */
ac7af0da 3019function require_course_login($courseorid, $autologinguest = true, $cm = null, $setwantsurltome = true, $preventredirect = false) {
862940c0 3020 global $CFG, $PAGE, $SITE;
9d202aed
PS
3021 $issite = ((is_object($courseorid) and $courseorid->id == SITEID)
3022 or (!is_object($courseorid) and $courseorid == SITEID));
d4fb0e26 3023 if ($issite && !empty($cm) && !($cm instanceof cm_info)) {
ac7af0da 3024 // Note: nearly all pages call get_fast_modinfo anyway and it does not make any
0d8b6a69 3025 // db queries so this is not really a performance concern, however it is obviously
3026 // better if you use get_fast_modinfo to get the cm before calling this.
3027 if (is_object($courseorid)) {
3028 $course = $courseorid;
3029 } else {
3030 $course = clone($SITE);
3031 }
3032 $modinfo = get_fast_modinfo($course);
3033 $cm = $modinfo->get_cm($cm->id);
3034 }
1596edff 3035 if (!empty($CFG->forcelogin)) {
ac7af0da 3036 // Login required for both SITE and courses.
df997f84 3037 require_login($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
63c9ee99 3038
0d8b6a69 3039 } else if ($issite && !empty($cm) and !$cm->uservisible) {
ac7af0da 3040 // Always login for hidden activities.
df997f84 3041 require_login($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
ce3f8046
MG
3042
3043 } else if (isloggedin() && !isguestuser()) {
3044 // User is already logged in. Make sure the login is complete (user is fully setup, policies agreed).
3045 require_login($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
63c9ee99 3046
0d8b6a69 3047 } else if ($issite) {
ac7af0da 3048 // Login for SITE not required.
48c79eb3 3049 // We still need to instatiate PAGE vars properly so that things that rely on it like navigation function correctly.
3050 if (!empty($courseorid)) {
3051 if (is_object($courseorid)) {
3052 $course = $courseorid;
3053 } else {
3054 $course = clone $SITE;
3055 }
3056 if ($cm) {
3057 if ($cm->course != $course->id) {
3058 throw new coding_exception('course and cm parameters in require_course_login() call do not match!!');
862940c0 3059 }
48c79eb3 3060 $PAGE->set_cm($cm, $course);
3061 $PAGE->set_pagelayout('incourse');
862940c0 3062 } else {
48c79eb3 3063 $PAGE->set_course($course);
862940c0 3064 }
48c79eb3 3065 } else {
3066 // If $PAGE->course, and hence $PAGE->context, have not already been set up properly, set them up now.
3067