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