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