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