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