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