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