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