MDL-28466 remove the enrol_authorize data
[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
6ab62db6
RT
1554 // Clear course cache for all courses.
1555 rebuild_course_cache(0, true);
1556
dc2c9bd7 1557 // purge all other caches: rss, simplepie, etc.
365bec4c 1558 remove_dir($CFG->cachedir.'', true);
f87eab7e 1559
c426ef3a 1560 // make sure cache dir is writable, throws exception if not
5a87c912 1561 make_cache_directory('');
f87eab7e 1562
b216a820
PS
1563 // hack: this script may get called after the purifier was initialised,
1564 // but we do not want to verify repeatedly this exists in each call
5a87c912 1565 make_cache_directory('htmlpurifier');
f87eab7e
PS
1566}
1567
bafd7e78 1568/**
1569 * Get volatile flags
1570 *
1571 * @param string $type
0d0a8bf6 1572 * @param int $changedsince default null
bafd7e78 1573 * @return records array
bafd7e78 1574 */
1575function get_cache_flags($type, $changedsince=NULL) {
ae040d4b 1576 global $DB;
bafd7e78 1577
ae040d4b 1578 $params = array('type'=>$type, 'expiry'=>time());
1579 $sqlwhere = "flagtype = :type AND expiry >= :expiry";
bafd7e78 1580 if ($changedsince !== NULL) {
ae040d4b 1581 $params['changedsince'] = $changedsince;
1582 $sqlwhere .= " AND timemodified > :changedsince";
bafd7e78 1583 }
1584 $cf = array();
ae040d4b 1585
1586 if ($flags = $DB->get_records_select('cache_flags', $sqlwhere, $params, '', 'name,value')) {
bafd7e78 1587 foreach ($flags as $flag) {
1588 $cf[$flag->name] = $flag->value;
1589 }
1590 }
1591 return $cf;
1592}
1593
a489cf72 1594/**
1595 * Get volatile flags
1596 *
1597 * @param string $type
1598 * @param string $name
0d0a8bf6 1599 * @param int $changedsince default null
a489cf72 1600 * @return records array
a489cf72 1601 */
1602function get_cache_flag($type, $name, $changedsince=NULL) {
ae040d4b 1603 global $DB;
a489cf72 1604
ae040d4b 1605 $params = array('type'=>$type, 'name'=>$name, 'expiry'=>time());
a489cf72 1606
ae040d4b 1607 $sqlwhere = "flagtype = :type AND name = :name AND expiry >= :expiry";
a489cf72 1608 if ($changedsince !== NULL) {
ae040d4b 1609 $params['changedsince'] = $changedsince;
1610 $sqlwhere .= " AND timemodified > :changedsince";
a489cf72 1611 }
ae040d4b 1612
1613 return $DB->get_field_select('cache_flags', 'value', $sqlwhere, $params);
a489cf72 1614}
bafd7e78 1615
1616/**
1617 * Set a volatile flag
1618 *
1619 * @param string $type the "type" namespace for the key
1620 * @param string $name the key to set
1621 * @param string $value the value to set (without magic quotes) - NULL will remove the flag
1622 * @param int $expiry (optional) epoch indicating expiry - defaults to now()+ 24hs
0d0a8bf6 1623 * @return bool Always returns true
bafd7e78 1624 */
1625function set_cache_flag($type, $name, $value, $expiry=NULL) {
ae040d4b 1626 global $DB;
bafd7e78 1627
1628 $timemodified = time();
1629 if ($expiry===NULL || $expiry < $timemodified) {
1630 $expiry = $timemodified + 24 * 60 * 60;
1631 } else {
1632 $expiry = (int)$expiry;
1633 }
1634
1635 if ($value === NULL) {
013376de 1636 unset_cache_flag($type,$name);
1637 return true;
bafd7e78 1638 }
1639
39461de3 1640 if ($f = $DB->get_record('cache_flags', array('name'=>$name, 'flagtype'=>$type), '*', IGNORE_MULTIPLE)) { // this is a potential problem in DEBUG_DEVELOPER
128f0984 1641 if ($f->value == $value and $f->expiry == $expiry and $f->timemodified == $timemodified) {
0b37fe46 1642 return true; //no need to update
128f0984 1643 }
ae040d4b 1644 $f->value = $value;
bafd7e78 1645 $f->expiry = $expiry;
1646 $f->timemodified = $timemodified;
013376de 1647 $DB->update_record('cache_flags', $f);
bafd7e78 1648 } else {
365a5941 1649 $f = new stdClass();
bafd7e78 1650 $f->flagtype = $type;
1651 $f->name = $name;
ae040d4b 1652 $f->value = $value;
bafd7e78 1653 $f->expiry = $expiry;
1654 $f->timemodified = $timemodified;
013376de 1655 $DB->insert_record('cache_flags', $f);
bafd7e78 1656 }
013376de 1657 return true;
bafd7e78 1658}
1659
1660/**
1661 * Removes a single volatile flag
1662 *
0d0a8bf6 1663 * @global object
bafd7e78 1664 * @param string $type the "type" namespace for the key
1665 * @param string $name the key to set
bafd7e78 1666 * @return bool
1667 */
1668function unset_cache_flag($type, $name) {
ae040d4b 1669 global $DB;
013376de 1670 $DB->delete_records('cache_flags', array('name'=>$name, 'flagtype'=>$type));
1671 return true;
bafd7e78 1672}
1673
1674/**
1675 * Garbage-collect volatile flags
1676 *
0d0a8bf6 1677 * @return bool Always returns true
bafd7e78 1678 */
1679function gc_cache_flags() {
ae040d4b 1680 global $DB;
013376de 1681 $DB->delete_records_select('cache_flags', 'expiry < ?', array(time()));
1682 return true;
bafd7e78 1683}
a4080313 1684
4d6b40a0 1685// USER PREFERENCE API
2660377f 1686
7cf1c7bd 1687/**
39461de3
PS
1688 * Refresh user preference cache. This is used most often for $USER
1689 * object that is stored in session, but it also helps with performance in cron script.
0d0a8bf6 1690 *
39461de3
PS
1691 * Preferences for each user are loaded on first use on every page, then again after the timeout expires.
1692 *
4d6b40a0
GGC
1693 * @package core
1694 * @category preference
1695 * @access public
1696 * @param stdClass $user User object. Preferences are preloaded into 'preference' property
1697 * @param int $cachelifetime Cache life time on the current page (in seconds)
1698 * @throws coding_exception
1699 * @return null
7cf1c7bd 1700 */
39461de3
PS
1701function check_user_preferences_loaded(stdClass $user, $cachelifetime = 120) {
1702 global $DB;
1703 static $loadedusers = array(); // Static cache, we need to check on each page load, not only every 2 minutes.
2660377f 1704
39461de3
PS
1705 if (!isset($user->id)) {
1706 throw new coding_exception('Invalid $user parameter in check_user_preferences_loaded() call, missing id field');
1707 }
2660377f 1708
39461de3
PS
1709 if (empty($user->id) or isguestuser($user->id)) {
1710 // No permanent storage for not-logged-in users and guest
1711 if (!isset($user->preference)) {
1712 $user->preference = array();
2660377f 1713 }
39461de3 1714 return;
2660377f 1715 }
70812e39 1716
39461de3 1717 $timenow = time();
070e2616 1718
39461de3
PS
1719 if (isset($loadedusers[$user->id]) and isset($user->preference) and isset($user->preference['_lastloaded'])) {
1720 // Already loaded at least once on this page. Are we up to date?
1721 if ($user->preference['_lastloaded'] + $cachelifetime > $timenow) {
1722 // no need to reload - we are on the same page and we loaded prefs just a moment ago
1723 return;
70812e39 1724
39461de3
PS
1725 } else if (!get_cache_flag('userpreferenceschanged', $user->id, $user->preference['_lastloaded'])) {
1726 // no change since the lastcheck on this page
1727 $user->preference['_lastloaded'] = $timenow;
1728 return;
70812e39 1729 }
c6d15803 1730 }
346c3e2f 1731
39461de3
PS
1732 // OK, so we have to reload all preferences
1733 $loadedusers[$user->id] = true;
1734 $user->preference = $DB->get_records_menu('user_preferences', array('userid'=>$user->id), '', 'name,value'); // All values
1735 $user->preference['_lastloaded'] = $timenow;
2660377f 1736}
1737
1738/**
4d6b40a0 1739 * Called from set/unset_user_preferences, so that the prefs can
39461de3
PS
1740 * be correctly reloaded in different sessions.
1741 *
1742 * NOTE: internal function, do not call from other code.
0d0a8bf6 1743 *
4d6b40a0
GGC
1744 * @package core
1745 * @access private
1746 * @param integer $userid the user whose prefs were changed.
2660377f 1747 */
1748function mark_user_preferences_changed($userid) {
39461de3
PS
1749 global $CFG;
1750
1751 if (empty($userid) or isguestuser($userid)) {
1752 // no cache flags for guest and not-logged-in users
1753 return;
2660377f 1754 }
39461de3 1755
2660377f 1756 set_cache_flag('userpreferenceschanged', $userid, 1, time() + $CFG->sessiontimeout);
70812e39 1757}
1758
7cf1c7bd 1759/**
39461de3 1760 * Sets a preference for the specified user.
0d0a8bf6 1761 *
4d6b40a0 1762 * If a $user object is submitted it's 'preference' property is used for the preferences cache.
0d0a8bf6 1763 *
4d6b40a0
GGC
1764 * @package core
1765 * @category preference
1766 * @access public
1767 * @param string $name The key to set as preference for the specified user
1768 * @param string $value The value to set for the $name key in the specified user's
1769 * record, null means delete current value.
1770 * @param stdClass|int|null $user A moodle user object or id, null means current user
1771 * @throws coding_exception
1772 * @return bool Always true or exception
7cf1c7bd 1773 */
39461de3 1774function set_user_preference($name, $value, $user = null) {
ae040d4b 1775 global $USER, $DB;
70812e39 1776
39461de3
PS
1777 if (empty($name) or is_numeric($name) or $name === '_lastloaded') {
1778 throw new coding_exception('Invalid preference name in set_user_preference() call');
70812e39 1779 }
1780
39461de3
PS
1781 if (is_null($value)) {
1782 // null means delete current
1783 return unset_user_preference($name, $user);
1784 } else if (is_object($value)) {
1785 throw new coding_exception('Invalid value in set_user_preference() call, objects are not allowed');
1786 } else if (is_array($value)) {
1787 throw new coding_exception('Invalid value in set_user_preference() call, arrays are not allowed');
1788 }
1789 $value = (string)$value;
8e54ce97
AD
1790 if (textlib::strlen($value) > 1333) { //value column maximum length is 1333 characters
1791 throw new coding_exception('Invalid value in set_user_preference() call, value is is too long for the value column');
1792 }
39461de3
PS
1793
1794 if (is_null($user)) {
1795 $user = $USER;
1796 } else if (isset($user->id)) {
1797 // $user is valid object
1798 } else if (is_numeric($user)) {
1799 $user = (object)array('id'=>(int)$user);
346c3e2f 1800 } else {
39461de3 1801 throw new coding_exception('Invalid $user parameter in set_user_preference() call');
346c3e2f 1802 }
1803
39461de3
PS
1804 check_user_preferences_loaded($user);
1805
1806 if (empty($user->id) or isguestuser($user->id)) {
1807 // no permanent storage for not-logged-in users and guest
1808 $user->preference[$name] = $value;
1809 return true;
1810 }
346c3e2f 1811
39461de3
PS
1812 if ($preference = $DB->get_record('user_preferences', array('userid'=>$user->id, 'name'=>$name))) {
1813 if ($preference->value === $value and isset($user->preference[$name]) and $user->preference[$name] === $value) {
1814 // preference already set to this value
a1244706 1815 return true;
1816 }
39461de3 1817 $DB->set_field('user_preferences', 'value', $value, array('id'=>$preference->id));
70812e39 1818
1819 } else {
365a5941 1820 $preference = new stdClass();
39461de3 1821 $preference->userid = $user->id;
ae040d4b 1822 $preference->name = $name;
39461de3 1823 $preference->value = $value;
013376de 1824 $DB->insert_record('user_preferences', $preference);
2660377f 1825 }
1826
39461de3
PS
1827 // update value in cache
1828 $user->preference[$name] = $value;
1829
1830 // set reload flag for other sessions
1831 mark_user_preferences_changed($user->id);
346c3e2f 1832
013376de 1833 return true;
2660377f 1834}
1835
1836/**
1837 * Sets a whole array of preferences for the current user
0d0a8bf6 1838 *
4d6b40a0 1839 * If a $user object is submitted it's 'preference' property is used for the preferences cache.
39461de3 1840 *
4d6b40a0
GGC
1841 * @package core
1842 * @category preference
1843 * @access public
1844 * @param array $prefarray An array of key/value pairs to be set
1845 * @param stdClass|int|null $user A moodle user object or id, null means current user
1846 * @return bool Always true or exception
2660377f 1847 */
39461de3 1848function set_user_preferences(array $prefarray, $user = null) {
2660377f 1849 foreach ($prefarray as $name => $value) {
39461de3 1850 set_user_preference($name, $value, $user);
2660377f 1851 }
013376de 1852 return true;
70812e39 1853}
1854
6eb3e776 1855/**
1856 * Unsets a preference completely by deleting it from the database
0d0a8bf6 1857 *
4d6b40a0 1858 * If a $user object is submitted it's 'preference' property is used for the preferences cache.
0d0a8bf6 1859 *
4d6b40a0
GGC
1860 * @package core
1861 * @category preference
1862 * @access public
1863 * @param string $name The key to unset as preference for the specified user
1864 * @param stdClass|int|null $user A moodle user object or id, null means current user
1865 * @throws coding_exception
1866 * @return bool Always true or exception
6eb3e776 1867 */
39461de3 1868function unset_user_preference($name, $user = null) {
ae040d4b 1869 global $USER, $DB;
6eb3e776 1870
39461de3
PS
1871 if (empty($name) or is_numeric($name) or $name === '_lastloaded') {
1872 throw new coding_exception('Invalid preference name in unset_user_preference() call');
1873 }
1874
1875 if (is_null($user)) {
1876 $user = $USER;
1877 } else if (isset($user->id)) {
1878 // $user is valid object
1879 } else if (is_numeric($user)) {
1880 $user = (object)array('id'=>(int)$user);
346c3e2f 1881 } else {
39461de3 1882 throw new coding_exception('Invalid $user parameter in unset_user_preference() call');
346c3e2f 1883 }
1884
39461de3 1885 check_user_preferences_loaded($user);
013376de 1886
39461de3
PS
1887 if (empty($user->id) or isguestuser($user->id)) {
1888 // no permanent storage for not-logged-in user and guest
1889 unset($user->preference[$name]);
1890 return true;
70812e39 1891 }
1892
39461de3
PS
1893 // delete from DB
1894 $DB->delete_records('user_preferences', array('userid'=>$user->id, 'name'=>$name));
1895
1896 // delete the preference from cache
1897 unset($user->preference[$name]);
1898
1899 // set reload flag for other sessions
1900 mark_user_preferences_changed($user->id);
1901
013376de 1902 return true;
70812e39 1903}
1904
7cf1c7bd 1905/**
0d0a8bf6 1906 * Used to fetch user preference(s)
1907 *
7cf1c7bd 1908 * If no arguments are supplied this function will return
361855e6 1909 * all of the current user preferences as an array.
0d0a8bf6 1910 *
7cf1c7bd 1911 * If a name is specified then this function
1912 * attempts to return that particular preference value. If
1913 * none is found, then the optional value $default is returned,
1914 * otherwise NULL.
0d0a8bf6 1915 *
4d6b40a0 1916 * If a $user object is submitted it's 'preference' property is used for the preferences cache.
39461de3 1917 *
4d6b40a0
GGC
1918 * @package core
1919 * @category preference
1920 * @access public
1921 * @param string $name Name of the key to use in finding a preference value
1922 * @param mixed|null $default Value to be returned if the $name key is not set in the user preferences
1923 * @param stdClass|int|null $user A moodle user object or id, null means current user
1924 * @throws coding_exception
1925 * @return string|mixed|null A string containing the value of a single preference. An
1926 * array with all of the preferences or null
7cf1c7bd 1927 */
39461de3
PS
1928function get_user_preferences($name = null, $default = null, $user = null) {
1929 global $USER;
70812e39 1930
39461de3
PS
1931 if (is_null($name)) {
1932 // all prefs
1933 } else if (is_numeric($name) or $name === '_lastloaded') {
1934 throw new coding_exception('Invalid preference name in get_user_preferences() call');
1935 }
346c3e2f 1936
39461de3
PS
1937 if (is_null($user)) {
1938 $user = $USER;
1939 } else if (isset($user->id)) {
1940 // $user is valid object
1941 } else if (is_numeric($user)) {
1942 $user = (object)array('id'=>(int)$user);
1943 } else {
1944 throw new coding_exception('Invalid $user parameter in get_user_preferences() call');
1945 }
1946
1947 check_user_preferences_loaded($user);
346c3e2f 1948
39461de3
PS
1949 if (empty($name)) {
1950 return $user->preference; // All values
1951 } else if (isset($user->preference[$name])) {
1952 return $user->preference[$name]; // The single string value
346c3e2f 1953 } else {
39461de3 1954 return $default; // Default value (null if not specified)
70812e39 1955 }
70812e39 1956}
1957
9fa49e22 1958/// FUNCTIONS FOR HANDLING TIME ////////////////////////////////////////////
39917a09 1959
7cf1c7bd 1960/**
c6d15803 1961 * Given date parts in user time produce a GMT timestamp.
7cf1c7bd 1962 *
9df12115
RT
1963 * @package core
1964 * @category time
68fbd8e1 1965 * @param int $year The year part to create timestamp of
1966 * @param int $month The month part to create timestamp of
1967 * @param int $day The day part to create timestamp of
1968 * @param int $hour The hour part to create timestamp of
1969 * @param int $minute The minute part to create timestamp of
1970 * @param int $second The second part to create timestamp of
9df12115
RT
1971 * @param int|float|string $timezone Timezone modifier, used to calculate GMT time offset.
1972 * if 99 then default user's timezone is used {@link http://docs.moodle.org/dev/Time_API#Timezone}
6a0bf5c4
RT
1973 * @param bool $applydst Toggle Daylight Saving Time, default true, will be
1974 * applied only if timezone is 99 or string.
9df12115 1975 * @return int GMT timestamp
7cf1c7bd 1976 */
9f1f6daf 1977function make_timestamp($year, $month=1, $day=1, $hour=0, $minute=0, $second=0, $timezone=99, $applydst=true) {
39917a09 1978
6a0bf5c4
RT
1979 //save input timezone, required for dst offset check.
1980 $passedtimezone = $timezone;
33998d30 1981
dddb014a 1982 $timezone = get_user_timezone_offset($timezone);
1983
6a0bf5c4 1984 if (abs($timezone) > 13) { //server time
68fbd8e1 1985 $time = mktime((int)$hour, (int)$minute, (int)$second, (int)$month, (int)$day, (int)$year);
03c17ddf 1986 } else {
68fbd8e1 1987 $time = gmmktime((int)$hour, (int)$minute, (int)$second, (int)$month, (int)$day, (int)$year);
196f2619 1988 $time = usertime($time, $timezone);
6a0bf5c4
RT
1989
1990 //Apply dst for string timezones or if 99 then try dst offset with user's default timezone
1991 if ($applydst && ((99 == $passedtimezone) || !is_numeric($passedtimezone))) {
1992 $time -= dst_offset_on($time, $passedtimezone);
28c66824 1993 }
9f1f6daf 1994 }
1995
196f2619 1996 return $time;
85cafb3e 1997
39917a09 1998}
1999
7cf1c7bd 2000/**
0d0a8bf6 2001 * Format a date/time (seconds) as weeks, days, hours etc as needed
2002 *
7cf1c7bd 2003 * Given an amount of time in seconds, returns string
5602f7cf 2004 * formatted nicely as weeks, days, hours etc as needed
7cf1c7bd 2005 *
9df12115
RT
2006 * @package core
2007 * @category time
2f87145b 2008 * @uses MINSECS
2009 * @uses HOURSECS
2010 * @uses DAYSECS
5602f7cf 2011 * @uses YEARSECS
0d0a8bf6 2012 * @param int $totalsecs Time in seconds
2013 * @param object $str Should be a time object
2014 * @return string A nicely formatted date/time string
7cf1c7bd 2015 */
2016 function format_time($totalsecs, $str=NULL) {
c7e3ac2a 2017
6b174680 2018 $totalsecs = abs($totalsecs);
c7e3ac2a 2019
8dbed6be 2020 if (!$str) { // Create the str structure the slow way
b85b25eb 2021 $str = new stdClass();
b0ccd3fb 2022 $str->day = get_string('day');
2023 $str->days = get_string('days');
2024 $str->hour = get_string('hour');
2025 $str->hours = get_string('hours');
2026 $str->min = get_string('min');
2027 $str->mins = get_string('mins');
2028 $str->sec = get_string('sec');
2029 $str->secs = get_string('secs');
5602f7cf 2030 $str->year = get_string('year');
2031 $str->years = get_string('years');
8dbed6be 2032 }
2033
5602f7cf 2034
2035 $years = floor($totalsecs/YEARSECS);
2036 $remainder = $totalsecs - ($years*YEARSECS);
5602f7cf 2037 $days = floor($remainder/DAYSECS);
7a5672c9 2038 $remainder = $totalsecs - ($days*DAYSECS);
2039 $hours = floor($remainder/HOURSECS);
2040 $remainder = $remainder - ($hours*HOURSECS);
2041 $mins = floor($remainder/MINSECS);
2042 $secs = $remainder - ($mins*MINSECS);
8dbed6be 2043
2044 $ss = ($secs == 1) ? $str->sec : $str->secs;
2045 $sm = ($mins == 1) ? $str->min : $str->mins;
2046 $sh = ($hours == 1) ? $str->hour : $str->hours;
2047 $sd = ($days == 1) ? $str->day : $str->days;
5602f7cf 2048 $sy = ($years == 1) ? $str->year : $str->years;
8dbed6be 2049
5602f7cf 2050 $oyears = '';
b0ccd3fb 2051 $odays = '';
2052 $ohours = '';
2053 $omins = '';
2054 $osecs = '';
9c9f7d77 2055
5602f7cf 2056 if ($years) $oyears = $years .' '. $sy;
b0ccd3fb 2057 if ($days) $odays = $days .' '. $sd;
2058 if ($hours) $ohours = $hours .' '. $sh;
2059 if ($mins) $omins = $mins .' '. $sm;
2060 if ($secs) $osecs = $secs .' '. $ss;
6b174680 2061
77ac808e 2062 if ($years) return trim($oyears .' '. $odays);
2063 if ($days) return trim($odays .' '. $ohours);
2064 if ($hours) return trim($ohours .' '. $omins);
2065 if ($mins) return trim($omins .' '. $osecs);
b0ccd3fb 2066 if ($secs) return $osecs;
2067 return get_string('now');
6b174680 2068}
f9903ed0 2069
7cf1c7bd 2070/**
0d0a8bf6 2071 * Returns a formatted string that represents a date in user time
2072 *
7cf1c7bd 2073 * Returns a formatted string that represents a date in user time
2074 * <b>WARNING: note that the format is for strftime(), not date().</b>
2075 * Because of a bug in most Windows time libraries, we can't use
2076 * the nicer %e, so we have to use %d which has leading zeroes.
2077 * A lot of the fuss in the function is just getting rid of these leading
2078 * zeroes as efficiently as possible.
361855e6 2079 *
8c3dba73 2080 * If parameter fixday = true (default), then take off leading
efb8c375 2081 * zero from %d, else maintain it.
7cf1c7bd 2082 *
9df12115
RT
2083 * @package core
2084 * @category time
0a0cf09a 2085 * @param int $date the timestamp in UTC, as obtained from the database.
2086 * @param string $format strftime format. You should probably get this using
9df12115
RT
2087 * get_string('strftime...', 'langconfig');
2088 * @param int|float|string $timezone by default, uses the user's time zone. if numeric and
2089 * not 99 then daylight saving will not be added.
2090 * {@link http://docs.moodle.org/dev/Time_API#Timezone}
0a0cf09a 2091 * @param bool $fixday If true (default) then the leading zero from %d is removed.
9df12115 2092 * If false then the leading zero is maintained.
d9498b38 2093 * @param bool $fixhour If true (default) then the leading zero from %I is removed.
0a0cf09a 2094 * @return string the formatted date/time.
7cf1c7bd 2095 */
d9498b38 2096function userdate($date, $format = '', $timezone = 99, $fixday = true, $fixhour = true) {
7a302afc 2097
1ac7ee24 2098 global $CFG;
2099
1306c5ea 2100 if (empty($format)) {
0a0cf09a 2101 $format = get_string('strftimedaydatetime', 'langconfig');
5fa51a39 2102 }
035cdbff 2103
c3a3c5b8 2104 if (!empty($CFG->nofixday)) { // Config.php can force %d not to be fixed.
2105 $fixday = false;
2106 } else if ($fixday) {
2107 $formatnoday = str_replace('%d', 'DD', $format);
61ae5d36 2108 $fixday = ($formatnoday != $format);
d9498b38 2109 $format = $formatnoday;
2110 }
2111
2112 // Note: This logic about fixing 12-hour time to remove unnecessary leading
2113 // zero is required because on Windows, PHP strftime function does not
2114 // support the correct 'hour without leading zero' parameter (%l).
2115 if (!empty($CFG->nofixhour)) {
2116 // Config.php can force %I not to be fixed.
2117 $fixhour = false;
2118 } else if ($fixhour) {
2119 $formatnohour = str_replace('%I', 'HH', $format);
2120 $fixhour = ($formatnohour != $format);
2121 $format = $formatnohour;
61ae5d36 2122 }
dcde9f02 2123
6a0bf5c4
RT
2124 //add daylight saving offset for string timezones only, as we can't get dst for
2125 //float values. if timezone is 99 (user default timezone), then try update dst.
2126 if ((99 == $timezone) || !is_numeric($timezone)) {
2127 $date += dst_offset_on($date, $timezone);
2128 }
85351042 2129
494b9296 2130 $timezone = get_user_timezone_offset($timezone);
102dc313 2131
63d59875
PS
2132 // If we are running under Windows convert to windows encoding and then back to UTF-8
2133 // (because it's impossible to specify UTF-8 to fetch locale info in Win32)
2134
102dc313 2135 if (abs($timezone) > 13) { /// Server time
15396bba 2136 $datestring = date_format_string($date, $format, $timezone);
d2a9f7cc 2137 if ($fixday) {
35f7287f 2138 $daystring = ltrim(str_replace(array(' 0', ' '), '', strftime(' %d', $date)));
102dc313 2139 $datestring = str_replace('DD', $daystring, $datestring);
d9498b38 2140 }
2141 if ($fixhour) {
2142 $hourstring = ltrim(str_replace(array(' 0', ' '), '', strftime(' %I', $date)));
2143 $datestring = str_replace('HH', $hourstring, $datestring);
102dc313 2144 }
63d59875 2145
88ec5b7c 2146 } else {
102dc313 2147 $date += (int)($timezone * 3600);
15396bba 2148 $datestring = date_format_string($date, $format, $timezone);
102dc313 2149 if ($fixday) {
35f7287f 2150 $daystring = ltrim(str_replace(array(' 0', ' '), '', gmstrftime(' %d', $date)));
102dc313 2151 $datestring = str_replace('DD', $daystring, $datestring);
d9498b38 2152 }
2153 if ($fixhour) {
2154 $hourstring = ltrim(str_replace(array(' 0', ' '), '', gmstrftime(' %I', $date)));
2155 $datestring = str_replace('HH', $hourstring, $datestring);
102dc313 2156 }
88ec5b7c 2157 }
102dc313 2158
035cdbff 2159 return $datestring;
873960de 2160}
2161
15396bba
FM
2162/**
2163 * Returns a formatted date ensuring it is UTF-8.
2164 *
2165 * If we are running under Windows convert to Windows encoding and then back to UTF-8
2166 * (because it's impossible to specify UTF-8 to fetch locale info in Win32).
2167 *
2168 * This function does not do any calculation regarding the user preferences and should
2169 * therefore receive the final date timestamp, format and timezone. Timezone being only used
2170 * to differenciate the use of server time or not (strftime() against gmstrftime()).
2171 *
2172 * @param int $date the timestamp.
2173 * @param string $format strftime format.
2174 * @param int|float $timezone the numerical timezone, typically returned by {@link get_user_timezone_offset()}.
2175 * @return string the formatted date/time.
2176 * @since 2.3.3
2177 */
2178function date_format_string($date, $format, $tz = 99) {
2179 global $CFG;
2180 if (abs($tz) > 13) {
73d20f36 2181 if ($CFG->ostype == 'WINDOWS' and $localewincharset = get_string('localewincharset', 'langconfig')) {
15396bba
FM
2182 $format = textlib::convert($format, 'utf-8', $localewincharset);
2183 $datestring = strftime($format, $date);
2184 $datestring = textlib::convert($datestring, $localewincharset, 'utf-8');
2185 } else {
2186 $datestring = strftime($format, $date);
2187 }
2188 } else {
73d20f36 2189 if ($CFG->ostype == 'WINDOWS' and $localewincharset = get_string('localewincharset', 'langconfig')) {
15396bba
FM
2190 $format = textlib::convert($format, 'utf-8', $localewincharset);
2191 $datestring = gmstrftime($format, $date);
2192 $datestring = textlib::convert($datestring, $localewincharset, 'utf-8');
2193 } else {
2194 $datestring = gmstrftime($format, $date);
2195 }
2196 }
2197 return $datestring;
2198}
2199
7cf1c7bd 2200/**
196f2619 2201 * Given a $time timestamp in GMT (seconds since epoch),
c6d15803 2202 * returns an array that represents the date in user time
7cf1c7bd 2203 *
9df12115
RT
2204 * @package core
2205 * @category time
2f87145b 2206 * @uses HOURSECS
196f2619 2207 * @param int $time Timestamp in GMT
9df12115
RT
2208 * @param float|int|string $timezone offset's time with timezone, if float and not 99, then no
2209 * dst offset is applyed {@link http://docs.moodle.org/dev/Time_API#Timezone}
c6d15803 2210 * @return array An array that represents the date in user time
7cf1c7bd 2211 */
196f2619 2212function usergetdate($time, $timezone=99) {
6b174680 2213
6a0bf5c4
RT
2214 //save input timezone, required for dst offset check.
2215 $passedtimezone = $timezone;
94c82430 2216
494b9296 2217 $timezone = get_user_timezone_offset($timezone);
a36166d3 2218
e34d817e 2219 if (abs($timezone) > 13) { // Server time
ed1f69b0 2220 return getdate($time);
d2a9f7cc 2221 }
2222
6a0bf5c4
RT
2223 //add daylight saving offset for string timezones only, as we can't get dst for
2224 //float values. if timezone is 99 (user default timezone), then try update dst.
2225 if ($passedtimezone == 99 || !is_numeric($passedtimezone)) {
2226 $time += dst_offset_on($time, $passedtimezone);
2227 }
2228
e34d817e 2229 $time += intval((float)$timezone * HOURSECS);
3bba1e6e 2230
24d38a6e 2231 $datestring = gmstrftime('%B_%A_%j_%Y_%m_%w_%d_%H_%M_%S', $time);
02f0527d 2232
24d38a6e 2233 //be careful to ensure the returned array matches that produced by getdate() above
9f1f6daf 2234 list(
24d38a6e
AD
2235 $getdate['month'],
2236 $getdate['weekday'],
2237 $getdate['yday'],
9f1f6daf 2238 $getdate['year'],
24d38a6e 2239 $getdate['mon'],
9f1f6daf 2240 $getdate['wday'],
24d38a6e
AD
2241 $getdate['mday'],
2242 $getdate['hours'],
2243 $getdate['minutes'],
2244 $getdate['seconds']
3bba1e6e 2245 ) = explode('_', $datestring);
9f1f6daf 2246
4a9c429b
RT
2247 // set correct datatype to match with getdate()
2248 $getdate['seconds'] = (int)$getdate['seconds'];
2249 $getdate['yday'] = (int)$getdate['yday'] - 1; // gettime returns 0 through 365
2250 $getdate['year'] = (int)$getdate['year'];
2251 $getdate['mon'] = (int)$getdate['mon'];
2252 $getdate['wday'] = (int)$getdate['wday'];
2253 $getdate['mday'] = (int)$getdate['mday'];
2254 $getdate['hours'] = (int)$getdate['hours'];
2255 $getdate['minutes'] = (int)$getdate['minutes'];
d2d6171f 2256 return $getdate;
d552ead0 2257}
2258
7cf1c7bd 2259/**
2260 * Given a GMT timestamp (seconds since epoch), offsets it by
2261 * the timezone. eg 3pm in India is 3pm GMT - 7 * 3600 seconds
2262 *
9df12115
RT
2263 * @package core
2264 * @category time
2f87145b 2265 * @uses HOURSECS
9df12115
RT
2266 * @param int $date Timestamp in GMT
2267 * @param float|int|string $timezone timezone to calculate GMT time offset before
2268 * calculating user time, 99 is default user timezone
2269 * {@link http://docs.moodle.org/dev/Time_API#Timezone}
c6d15803 2270 * @return int
7cf1c7bd 2271 */
d552ead0 2272function usertime($date, $timezone=99) {
a36166d3 2273
494b9296 2274 $timezone = get_user_timezone_offset($timezone);
2665e47a 2275
0431bd7c 2276 if (abs($timezone) > 13) {
d552ead0 2277 return $date;
2278 }
7a5672c9 2279 return $date - (int)($timezone * HOURSECS);
d552ead0 2280}
2281
8c3dba73 2282/**
2283 * Given a time, return the GMT timestamp of the most recent midnight
2284 * for the current user.
2285 *
9df12115
RT
2286 * @package core
2287 * @category time
e34d817e 2288 * @param int $date Timestamp in GMT
9df12115
RT
2289 * @param float|int|string $timezone timezone to calculate GMT time offset before
2290 * calculating user midnight time, 99 is default user timezone
2291 * {@link http://docs.moodle.org/dev/Time_API#Timezone}
0d0a8bf6 2292 * @return int Returns a GMT timestamp
8c3dba73 2293 */
edf7fe8c 2294function usergetmidnight($date, $timezone=99) {
edf7fe8c 2295
edf7fe8c 2296 $userdate = usergetdate($date, $timezone);
4606d9bb 2297
02f0527d 2298 // Time of midnight of this user's day, in GMT
2299 return make_timestamp($userdate['year'], $userdate['mon'], $userdate['mday'], 0, 0, 0, $timezone);
edf7fe8c 2300
2301}
2302
7cf1c7bd 2303/**
2304 * Returns a string that prints the user's timezone
2305 *
9df12115
RT
2306 * @package core
2307 * @category time
2308 * @param float|int|string $timezone timezone to calculate GMT time offset before
2309 * calculating user timezone, 99 is default user timezone
2310 * {@link http://docs.moodle.org/dev/Time_API#Timezone}
7cf1c7bd 2311 * @return string
2312 */
d552ead0 2313function usertimezone($timezone=99) {
d552ead0 2314
0c244315 2315 $tz = get_user_timezone($timezone);
f30fe8d0 2316
0c244315 2317 if (!is_float($tz)) {
2318 return $tz;
d552ead0 2319 }
0c244315 2320
2321 if(abs($tz) > 13) { // Server time
2322 return get_string('serverlocaltime');
2323 }
2324
2325 if($tz == intval($tz)) {
2326 // Don't show .0 for whole hours
2327 $tz = intval($tz);
2328 }
2329
2330 if($tz == 0) {
61b420ac 2331 return 'UTC';
d552ead0 2332 }
0c244315 2333 else if($tz > 0) {
61b420ac 2334 return 'UTC+'.$tz;
0c244315 2335 }
2336 else {
61b420ac 2337 return 'UTC'.$tz;
d552ead0 2338 }
e1ecf0a0 2339
f9903ed0 2340}
2341
7cf1c7bd 2342/**
2343 * Returns a float which represents the user's timezone difference from GMT in hours
2344 * Checks various settings and picks the most dominant of those which have a value
2345 *
9df12115
RT
2346 * @package core
2347 * @category time
2348 * @param float|int|string $tz timezone to calculate GMT time offset for user,
2349 * 99 is default user timezone
2350 * {@link http://docs.moodle.org/dev/Time_API#Timezone}
0d0a8bf6 2351 * @return float
7cf1c7bd 2352 */
494b9296 2353function get_user_timezone_offset($tz = 99) {
f30fe8d0 2354
43b59916 2355 global $USER, $CFG;
2356
e8904995 2357 $tz = get_user_timezone($tz);
c9e55a25 2358
7b9e355e 2359 if (is_float($tz)) {
2360 return $tz;
2361 } else {
e8904995 2362 $tzrecord = get_timezone_record($tz);
7b9e355e 2363 if (empty($tzrecord)) {
e8904995 2364 return 99.0;
2365 }
4f2dbde9 2366 return (float)$tzrecord->gmtoff / HOURMINS;
e8904995 2367 }
2368}
2369
61460dd6 2370/**
2371 * Returns an int which represents the systems's timezone difference from GMT in seconds
0d0a8bf6 2372 *
9df12115
RT
2373 * @package core
2374 * @category time
2375 * @param float|int|string $tz timezone for which offset is required.
2376 * {@link http://docs.moodle.org/dev/Time_API#Timezone}
2377 * @return int|bool if found, false is timezone 99 or error
61460dd6 2378 */
2379function get_timezone_offset($tz) {
2380 global $CFG;
2381
2382 if ($tz == 99) {
2383 return false;
2384 }
2385
2386 if (is_numeric($tz)) {
2387 return intval($tz * 60*60);
2388 }
2389
2390 if (!$tzrecord = get_timezone_record($tz)) {
2391 return false;
2392 }
2393 return intval($tzrecord->gmtoff * 60);
2394}
2395
bbd3f2c4 2396/**
b2b68362 2397 * Returns a float or a string which denotes the user's timezone
2398 * 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)
2399 * means that for this timezone there are also DST rules to be taken into account
2400 * Checks various settings and picks the most dominant of those which have a value
bbd3f2c4 2401 *
9df12115
RT
2402 * @package core
2403 * @category time
2404 * @param float|int|string $tz timezone to calculate GMT time offset before
2405 * calculating user timezone, 99 is default user timezone
2406 * {@link http://docs.moodle.org/dev/Time_API#Timezone}
2407 * @return float|string
bbd3f2c4 2408 */
e8904995 2409function get_user_timezone($tz = 99) {
2410 global $USER, $CFG;
43b59916 2411
f30fe8d0 2412 $timezones = array(
e8904995 2413 $tz,
2414 isset($CFG->forcetimezone) ? $CFG->forcetimezone : 99,
43b59916 2415 isset($USER->timezone) ? $USER->timezone : 99,
2416 isset($CFG->timezone) ? $CFG->timezone : 99,
f30fe8d0 2417 );
43b59916 2418
e8904995 2419 $tz = 99;
43b59916 2420
4d91f735
FM
2421 // Loop while $tz is, empty but not zero, or 99, and there is another timezone is the array
2422 while(((empty($tz) && !is_numeric($tz)) || $tz == 99) && $next = each($timezones)) {
e8904995 2423 $tz = $next['value'];
43b59916 2424 }
e8904995 2425 return is_numeric($tz) ? (float) $tz : $tz;
43b59916 2426}
2427
bbd3f2c4 2428/**
f33e1ed4 2429 * Returns cached timezone record for given $timezonename
bbd3f2c4 2430 *
9df12115
RT
2431 * @package core
2432 * @param string $timezonename name of the timezone
2433 * @return stdClass|bool timezonerecord or false
bbd3f2c4 2434 */
43b59916 2435function get_timezone_record($timezonename) {
f33e1ed4 2436 global $CFG, $DB;
43b59916 2437 static $cache = NULL;
2438
8edffd15 2439 if ($cache === NULL) {
43b59916 2440 $cache = array();
2441 }
2442
8edffd15 2443 if (isset($cache[$timezonename])) {
43b59916 2444 return $cache[$timezonename];
f30fe8d0 2445 }
2446
f33e1ed4 2447 return $cache[$timezonename] = $DB->get_record_sql('SELECT * FROM {timezone}
daac3835 2448 WHERE name = ? ORDER BY year DESC', array($timezonename), IGNORE_MULTIPLE);
f30fe8d0 2449}
f9903ed0 2450
bbd3f2c4 2451/**
0d0a8bf6 2452 * Build and store the users Daylight Saving Time (DST) table
bbd3f2c4 2453 *
9df12115
RT
2454 * @package core
2455 * @param int $from_year Start year for the table, defaults to 1971
2456 * @param int $to_year End year for the table, defaults to 2035
2457 * @param int|float|string $strtimezone, timezone to check if dst should be applyed.
bbd3f2c4 2458 * @return bool
2459 */
94c82430 2460function calculate_user_dst_table($from_year = NULL, $to_year = NULL, $strtimezone = NULL) {
ae040d4b 2461 global $CFG, $SESSION, $DB;
85cafb3e 2462
33998d30 2463 $usertz = get_user_timezone($strtimezone);
7cb29a3d 2464
989585e9 2465 if (is_float($usertz)) {
2466 // Trivial timezone, no DST
2467 return false;
2468 }
2469
2280ecf5 2470 if (!empty($SESSION->dst_offsettz) && $SESSION->dst_offsettz != $usertz) {
989585e9 2471 // We have precalculated values, but the user's effective TZ has changed in the meantime, so reset
2280ecf5 2472 unset($SESSION->dst_offsets);
2473 unset($SESSION->dst_range);
830a2bbd 2474 }
2475
2280ecf5 2476 if (!empty($SESSION->dst_offsets) && empty($from_year) && empty($to_year)) {
830a2bbd 2477 // Repeat calls which do not request specific year ranges stop here, we have already calculated the table
2478 // This will be the return path most of the time, pretty light computationally
2479 return true;
85cafb3e 2480 }
2481
830a2bbd 2482 // Reaching here means we either need to extend our table or create it from scratch
989585e9 2483
2484 // Remember which TZ we calculated these changes for
2280ecf5 2485 $SESSION->dst_offsettz = $usertz;
989585e9 2486
2280ecf5 2487 if(empty($SESSION->dst_offsets)) {
830a2bbd 2488 // If we 're creating from scratch, put the two guard elements in there
2280ecf5 2489 $SESSION->dst_offsets = array(1 => NULL, 0 => NULL);
830a2bbd 2490 }
2280ecf5 2491 if(empty($SESSION->dst_range)) {
830a2bbd 2492 // If creating from scratch
2493 $from = max((empty($from_year) ? intval(date('Y')) - 3 : $from_year), 1971);
2494 $to = min((empty($to_year) ? intval(date('Y')) + 3 : $to_year), 2035);
2495
2496 // Fill in the array with the extra years we need to process
2497 $yearstoprocess = array();
2498 for($i = $from; $i <= $to; ++$i) {
2499 $yearstoprocess[] = $i;
2500 }
2501
2502 // Take note of which years we have processed for future calls
2280ecf5 2503 $SESSION->dst_range = array($from, $to);
830a2bbd 2504 }
2505 else {
2506 // If needing to extend the table, do the same
2507 $yearstoprocess = array();
2508
2280ecf5 2509 $from = max((empty($from_year) ? $SESSION->dst_range[0] : $from_year), 1971);
2510 $to = min((empty($to_year) ? $SESSION->dst_range[1] : $to_year), 2035);
830a2bbd 2511
2280ecf5 2512 if($from < $SESSION->dst_range[0]) {
830a2bbd 2513 // Take note of which years we need to process and then note that we have processed them for future calls
2280ecf5 2514 for($i = $from; $i < $SESSION->dst_range[0]; ++$i) {
830a2bbd 2515 $yearstoprocess[] = $i;
2516 }
2280ecf5 2517 $SESSION->dst_range[0] = $from;
830a2bbd 2518 }
2280ecf5 2519 if($to > $SESSION->dst_range[1]) {
830a2bbd 2520 // Take note of which years we need to process and then note that we have processed them for future calls
2280ecf5 2521 for($i = $SESSION->dst_range[1] + 1; $i <= $to; ++$i) {
830a2bbd 2522 $yearstoprocess[] = $i;
2523 }
2280ecf5 2524 $SESSION->dst_range[1] = $to;
830a2bbd 2525 }
2526 }
2527
2528 if(empty($yearstoprocess)) {
2529 // This means that there was a call requesting a SMALLER range than we have already calculated
2530 return true;
2531 }
2532
2533 // From now on, we know that the array has at least the two guard elements, and $yearstoprocess has the years we need
2534 // Also, the array is sorted in descending timestamp order!
2535
2536 // Get DB data
6a5dc27c 2537
2538 static $presets_cache = array();
2539 if (!isset($presets_cache[$usertz])) {
ae040d4b 2540 $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 2541 }
2542 if(empty($presets_cache[$usertz])) {
e789650d 2543 return false;
2544 }
57f1191c 2545
830a2bbd 2546 // Remove ending guard (first element of the array)
2280ecf5 2547 reset($SESSION->dst_offsets);
2548 unset($SESSION->dst_offsets[key($SESSION->dst_offsets)]);
830a2bbd 2549
2550 // Add all required change timestamps
2551 foreach($yearstoprocess as $y) {
2552 // Find the record which is in effect for the year $y
6a5dc27c 2553 foreach($presets_cache[$usertz] as $year => $preset) {
830a2bbd 2554 if($year <= $y) {
2555 break;
c9e72798 2556 }
830a2bbd 2557 }
2558
2559 $changes = dst_changes_for_year($y, $preset);
2560
2561 if($changes === NULL) {
2562 continue;
2563 }
2564 if($changes['dst'] != 0) {
2280ecf5 2565 $SESSION->dst_offsets[$changes['dst']] = $preset->dstoff * MINSECS;
830a2bbd 2566 }
2567 if($changes['std'] != 0) {
2280ecf5 2568 $SESSION->dst_offsets[$changes['std']] = 0;
c9e72798 2569 }
85cafb3e 2570 }
42d36497 2571
830a2bbd 2572 // Put in a guard element at the top
2280ecf5 2573 $maxtimestamp = max(array_keys($SESSION->dst_offsets));
2574 $SESSION->dst_offsets[($maxtimestamp + DAYSECS)] = NULL; // DAYSECS is arbitrary, any "small" number will do
830a2bbd 2575
2576 // Sort again
2280ecf5 2577 krsort($SESSION->dst_offsets);
830a2bbd 2578
e789650d 2579 return true;
2580}
42d36497 2581
0d0a8bf6 2582/**
2583 * Calculates the required DST change and returns a Timestamp Array
2584 *
9df12115
RT
2585 * @package core
2586 * @category time
0d0a8bf6 2587 * @uses HOURSECS
2588 * @uses MINSECS
9df12115 2589 * @param int|string $year Int or String Year to focus on
0d0a8bf6 2590 * @param object $timezone Instatiated Timezone object
9df12115 2591 * @return array|null Array dst=>xx, 0=>xx, std=>yy, 1=>yy or NULL
0d0a8bf6 2592 */
e789650d 2593function dst_changes_for_year($year, $timezone) {
7cb29a3d 2594
e789650d 2595 if($timezone->dst_startday == 0 && $timezone->dst_weekday == 0 && $timezone->std_startday == 0 && $timezone->std_weekday == 0) {
2596 return NULL;
42d36497 2597 }
7cb29a3d 2598
e789650d 2599 $monthdaydst = find_day_in_month($timezone->dst_startday, $timezone->dst_weekday, $timezone->dst_month, $year);
2600 $monthdaystd = find_day_in_month($timezone->std_startday, $timezone->std_weekday, $timezone->std_month, $year);
2601
2602 list($dst_hour, $dst_min) = explode(':', $timezone->dst_time);
2603 list($std_hour, $std_min) = explode(':', $timezone->std_time);
d2a9f7cc 2604
6dc8dddc 2605 $timedst = make_timestamp($year, $timezone->dst_month, $monthdaydst, 0, 0, 0, 99, false);
2606 $timestd = make_timestamp($year, $timezone->std_month, $monthdaystd, 0, 0, 0, 99, false);
830a2bbd 2607
2608 // Instead of putting hour and minute in make_timestamp(), we add them afterwards.
2609 // This has the advantage of being able to have negative values for hour, i.e. for timezones
2610 // where GMT time would be in the PREVIOUS day than the local one on which DST changes.
2611
2612 $timedst += $dst_hour * HOURSECS + $dst_min * MINSECS;
2613 $timestd += $std_hour * HOURSECS + $std_min * MINSECS;
42d36497 2614
e789650d 2615 return array('dst' => $timedst, 0 => $timedst, 'std' => $timestd, 1 => $timestd);
42d36497 2616}
2617
0d0a8bf6 2618/**
efb8c375 2619 * Calculates the Daylight Saving Offset for a given date/time (timestamp)
6a0bf5c4 2620 * - Note: Daylight saving only works for string timezones and not for float.
0d0a8bf6 2621 *
9df12115
RT
2622 * @package core
2623 * @category time
0d0a8bf6 2624 * @param int $time must NOT be compensated at all, it has to be a pure timestamp
9df12115
RT
2625 * @param int|float|string $strtimezone timezone for which offset is expected, if 99 or null
2626 * then user's default timezone is used. {@link http://docs.moodle.org/dev/Time_API#Timezone}
0d0a8bf6 2627 * @return int
2628 */
94c82430 2629function dst_offset_on($time, $strtimezone = NULL) {
2280ecf5 2630 global $SESSION;
02f0527d 2631
94c82430 2632 if(!calculate_user_dst_table(NULL, NULL, $strtimezone) || empty($SESSION->dst_offsets)) {
c9e72798 2633 return 0;
85cafb3e 2634 }
2635
2280ecf5 2636 reset($SESSION->dst_offsets);
2637 while(list($from, $offset) = each($SESSION->dst_offsets)) {
59556d48 2638 if($from <= $time) {
c9e72798 2639 break;
2640 }
2641 }
2642
830a2bbd 2643 // This is the normal return path
2644 if($offset !== NULL) {
2645 return $offset;
02f0527d 2646 }
02f0527d 2647
830a2bbd 2648 // Reaching this point means we haven't calculated far enough, do it now:
2649 // Calculate extra DST changes if needed and recurse. The recursion always
2650 // moves toward the stopping condition, so will always end.
2651
2652 if($from == 0) {
2280ecf5 2653 // We need a year smaller than $SESSION->dst_range[0]
2654 if($SESSION->dst_range[0] == 1971) {
830a2bbd 2655 return 0;
2656 }
94c82430 2657 calculate_user_dst_table($SESSION->dst_range[0] - 5, NULL, $strtimezone);
2658 return dst_offset_on($time, $strtimezone);
830a2bbd 2659 }
2660 else {
2280ecf5 2661 // We need a year larger than $SESSION->dst_range[1]
2662 if($SESSION->dst_range[1] == 2035) {
830a2bbd 2663 return 0;
2664 }
94c82430 2665 calculate_user_dst_table(NULL, $SESSION->dst_range[1] + 5, $strtimezone);
2666 return dst_offset_on($time, $strtimezone);
830a2bbd 2667 }
85cafb3e 2668}
02f0527d 2669
0d0a8bf6 2670/**
9df12115 2671 * Calculates when the day appears in specific month
0d0a8bf6 2672 *
9df12115
RT
2673 * @package core
2674 * @category time
2675 * @param int $startday starting day of the month
2676 * @param int $weekday The day when week starts (normally taken from user preferences)
2677 * @param int $month The month whose day is sought
2678 * @param int $year The year of the month whose day is sought
0d0a8bf6 2679 * @return int
2680 */
28902d99 2681function find_day_in_month($startday, $weekday, $month, $year) {
8dc3f6cf 2682
2683 $daysinmonth = days_in_month($month, $year);
2684
42d36497 2685 if($weekday == -1) {
28902d99 2686 // Don't care about weekday, so return:
2687 // abs($startday) if $startday != -1
2688 // $daysinmonth otherwise
2689 return ($startday == -1) ? $daysinmonth : abs($startday);
8dc3f6cf 2690 }
2691
2692 // From now on we 're looking for a specific weekday
8dc3f6cf 2693
28902d99 2694 // Give "end of month" its actual value, since we know it
2695 if($startday == -1) {
2696 $startday = -1 * $daysinmonth;
2697 }
2698
2699 // Starting from day $startday, the sign is the direction
8dc3f6cf 2700
28902d99 2701 if($startday < 1) {
8dc3f6cf 2702
28902d99 2703 $startday = abs($startday);
ef7af3dd 2704 $lastmonthweekday = strftime('%w', mktime(12, 0, 0, $month, $daysinmonth, $year));
8dc3f6cf 2705
2706 // This is the last such weekday of the month
2707 $lastinmonth = $daysinmonth + $weekday - $lastmonthweekday;
2708 if($lastinmonth > $daysinmonth) {
2709 $lastinmonth -= 7;
42d36497 2710 }
8dc3f6cf 2711
28902d99 2712 // Find the first such weekday <= $startday
2713 while($lastinmonth > $startday) {
8dc3f6cf 2714 $lastinmonth -= 7;
42d36497 2715 }
8dc3f6cf 2716
2717 return $lastinmonth;
e1ecf0a0 2718
42d36497 2719 }
2720 else {
42d36497 2721
ef7af3dd 2722 $indexweekday = strftime('%w', mktime(12, 0, 0, $month, $startday, $year));
42d36497 2723
8dc3f6cf 2724 $diff = $weekday - $indexweekday;
2725 if($diff < 0) {
2726 $diff += 7;
42d36497 2727 }
42d36497 2728
28902d99 2729 // This is the first such weekday of the month equal to or after $startday
2730 $firstfromindex = $startday + $diff;
42d36497 2731
8dc3f6cf 2732 return $firstfromindex;
2733
2734 }
42d36497 2735}
2736
bbd3f2c4 2737/**
2738 * Calculate the number of days in a given month
2739 *
9df12115
RT
2740 * @package core
2741 * @category time
bbd3f2c4 2742 * @param int $month The month whose day count is sought
2743 * @param int $year The year of the month whose day count is sought
2744 * @return int
2745 */
42d36497 2746function days_in_month($month, $year) {
ef7af3dd 2747 return intval(date('t', mktime(12, 0, 0, $month, 1, $year)));
42d36497 2748}
2749
bbd3f2c4 2750/**
2751 * Calculate the position in the week of a specific calendar day
2752 *
9df12115
RT
2753 * @package core
2754 * @category time
bbd3f2c4 2755 * @param int $day The day of the date whose position in the week is sought
2756 * @param int $month The month of the date whose position in the week is sought
2757 * @param int $year The year of the date whose position in the week is sought
2758 * @return int
2759 */
8dc3f6cf 2760function dayofweek($day, $month, $year) {
2761 // I wonder if this is any different from
2762 // strftime('%w', mktime(12, 0, 0, $month, $daysinmonth, $year, 0));
d7eeb39e 2763 return intval(date('w', mktime(12, 0, 0, $month, $day, $year)));
8dc3f6cf 2764}
2765
9fa49e22 2766/// USER AUTHENTICATION AND LOGIN ////////////////////////////////////////
f9903ed0 2767
93f66983 2768/**
2769 * Returns full login url.
2770 *
93f66983 2771 * @return string login url
2772 */
999b54af 2773function get_login_url() {
93f66983 2774 global $CFG;
2775
999b54af 2776 $url = "$CFG->wwwroot/login/index.php";
93f66983 2777
999b54af
PS
2778 if (!empty($CFG->loginhttps)) {
2779 $url = str_replace('http:', 'https:', $url);
93f66983 2780 }
2781
2782 return $url;
2783}
2784
7cf1c7bd 2785/**
ec81373f 2786 * This function checks that the current user is logged in and has the
2787 * required privileges
2788 *
7cf1c7bd 2789 * This function checks that the current user is logged in, and optionally
ec81373f 2790 * whether they are allowed to be in a particular course and view a particular
2791 * course module.
2792 * If they are not logged in, then it redirects them to the site login unless
d2a9f7cc 2793 * $autologinguest is set and {@link $CFG}->autologinguests is set to 1 in which
ec81373f 2794 * case they are automatically logged in as guests.
2795 * If $courseid is given and the user is not enrolled in that course then the
2796 * user is redirected to the course enrolment page.
efb8c375 2797 * If $cm is given and the course module is hidden and the user is not a teacher
ec81373f 2798 * in the course then the user is redirected to the course home page.
7cf1c7bd 2799 *
191b267b 2800 * When $cm parameter specified, this function sets page layout to 'module'.
4f0c2d00 2801 * You need to change it manually later if some other layout needed.
191b267b 2802 *
f76249cc
PS
2803 * @package core_access
2804 * @category access
2805 *
33ebaf7c 2806 * @param mixed $courseorid id of the course or course object
0d0a8bf6 2807 * @param bool $autologinguest default true
bbd3f2c4 2808 * @param object $cm course module object
f4013c10 2809 * @param bool $setwantsurltome Define if we want to set $SESSION->wantsurl, defaults to
2810 * true. Used to avoid (=false) some scripts (file.php...) to set that variable,
2811 * in order to keep redirects working properly. MDL-14495
df997f84 2812 * @param bool $preventredirect set to true in scripts that can not redirect (CLI, rss feeds, etc.), throws exceptions
0d0a8bf6 2813 * @return mixed Void, exit, and die depending on path
7cf1c7bd 2814 */
df997f84 2815function require_login($courseorid = NULL, $autologinguest = true, $cm = NULL, $setwantsurltome = true, $preventredirect = false) {
f0202ae9 2816 global $CFG, $SESSION, $USER, $PAGE, $SITE, $DB, $OUTPUT;
d8ba183c 2817
f22f1caf
PS
2818 // Must not redirect when byteserving already started.
2819 if (!empty($_SERVER['HTTP_RANGE'])) {
2820 $preventredirect = true;
2821 }
2822
df997f84 2823 // setup global $COURSE, themes, language and locale
c13a5e71 2824 if (!empty($courseorid)) {
2825 if (is_object($courseorid)) {
2826 $course = $courseorid;
2827 } else if ($courseorid == SITEID) {
2828 $course = clone($SITE);
2829 } else {
df997f84 2830 $course = $DB->get_record('course', array('id' => $courseorid), '*', MUST_EXIST);
c13a5e71 2831 }
95d28870 2832 if ($cm) {
df997f84
PS
2833 if ($cm->course != $course->id) {
2834 throw new coding_exception('course and cm parameters in require_login() call do not match!!');
2835 }
0d8b6a69 2836 // make sure we have a $cm from get_fast_modinfo as this contains activity access details
47148151 2837 if (!($cm instanceof cm_info)) {
0d8b6a69 2838 // note: nearly all pages call get_fast_modinfo anyway and it does not make any
2839 // db queries so this is not really a performance concern, however it is obviously
2840 // better if you use get_fast_modinfo to get the cm before calling this.
2841 $modinfo = get_fast_modinfo($course);
2842 $cm = $modinfo->get_cm($cm->id);
2843 }
00dadbe1 2844 $PAGE->set_cm($cm, $course); // set's up global $COURSE
191b267b 2845 $PAGE->set_pagelayout('incourse');
95d28870 2846 } else {
00dadbe1 2847 $PAGE->set_course($course); // set's up global $COURSE
95d28870 2848 }
e88462a0 2849 } else {
df997f84
PS
2850 // do not touch global $COURSE via $PAGE->set_course(),
2851 // the reasons is we need to be able to call require_login() at any time!!
2852 $course = $SITE;
2853 if ($cm) {
2854 throw new coding_exception('cm parameter in require_login() requires valid course parameter!');
2855 }
c13a5e71 2856 }
be933850 2857
aa4a6566
SH
2858 // If this is an AJAX request and $setwantsurltome is true then we need to override it and set it to false.
2859 // Otherwise the AJAX request URL will be set to $SESSION->wantsurl and events such as self enrolment in the future
2860 // risk leading the user back to the AJAX request URL.
2861 if ($setwantsurltome && defined('AJAX_SCRIPT') && AJAX_SCRIPT) {
2862 $setwantsurltome = false;
2863 }
2864
12fc11e7 2865 // Redirect to the login page if session has expired, only with dbsessions enabled (MDL-35029) to maintain current behaviour.
8cd6d1aa 2866 if ((!isloggedin() or isguestuser()) && !empty($SESSION->has_timed_out) && !$preventredirect && !empty($CFG->dbsessions)) {
12fc11e7
DM
2867 if ($setwantsurltome) {
2868 $SESSION->wantsurl = qualified_me();
2869 }
2870 redirect(get_login_url());
2871 }
2872
df997f84 2873 // If the user is not even logged in yet then make sure they are
083c3743 2874 if (!isloggedin()) {
df997f84 2875 if ($autologinguest and !empty($CFG->guestloginbutton) and !empty($CFG->autologinguests)) {
999b54af
PS
2876 if (!$guest = get_complete_user_data('id', $CFG->siteguest)) {
2877 // misconfigured site guest, just redirect to login page
2878 redirect(get_login_url());
2879 exit; // never reached
df997f84 2880 }
999b54af 2881 $lang = isset($SESSION->lang) ? $SESSION->lang : $CFG->lang;
0342fc36 2882 complete_user_login($guest);
d9e07264 2883 $USER->autologinguest = true;
999b54af 2884 $SESSION->lang = $lang;
8a33e371 2885 } else {
999b54af
PS
2886 //NOTE: $USER->site check was obsoleted by session test cookie,
2887 // $USER->confirmed test is in login/index.php
2888 if ($preventredirect) {
2889 throw new require_login_exception('You are not logged in');
2890 }
2891
2892 if ($setwantsurltome) {
f0202ae9 2893 $SESSION->wantsurl = qualified_me();
999b54af
PS
2894 }
2895 if (!empty($_SERVER['HTTP_REFERER'])) {
2896 $SESSION->fromurl = $_SERVER['HTTP_REFERER'];
2897 }
2898 redirect(get_login_url());
2899 exit; // never reached
8a33e371 2900 }
f9903ed0 2901 }
808a3baa 2902
df997f84
PS
2903 // loginas as redirection if needed
2904 if ($course->id != SITEID and session_is_loggedinas()) {
f6f66b03 2905 if ($USER->loginascontext->contextlevel == CONTEXT_COURSE) {
df997f84 2906 if ($USER->loginascontext->instanceid != $course->id) {
3887fe4a 2907 print_error('loginasonecourse', '', $CFG->wwwroot.'/course/view.php?id='.$USER->loginascontext->instanceid);
5e623a33 2908 }
f6f66b03 2909 }
2910 }
2911
df997f84 2912 // check whether the user should be changing password (but only if it is REALLY them)
b7b64ff2 2913 if (get_user_preferences('auth_forcepasswordchange') && !session_is_loggedinas()) {
21e2dcd9 2914 $userauth = get_auth_plugin($USER->auth);
df997f84 2915 if ($userauth->can_change_password() and !$preventredirect) {
af572078 2916 if ($setwantsurltome) {
f0202ae9 2917 $SESSION->wantsurl = qualified_me();
af572078 2918 }
80274abf 2919 if ($changeurl = $userauth->change_password_url()) {
9696bd89 2920 //use plugin custom url
80274abf 2921 redirect($changeurl);
1437f0a5 2922 } else {
9696bd89 2923 //use moodle internal method
2924 if (empty($CFG->loginhttps)) {
2925 redirect($CFG->wwwroot .'/login/change_password.php');
2926 } else {
2927 $wwwroot = str_replace('http:','https:', $CFG->wwwroot);
2928 redirect($wwwroot .'/login/change_password.php');
2929 }
1437f0a5 2930 }
d35757eb 2931 } else {
a8ee7194 2932 print_error('nopasswordchangeforced', 'auth');
d35757eb 2933 }
2934 }
083c3743 2935
df997f84 2936 // Check that the user account is properly set up
808a3baa 2937 if (user_not_fully_set_up($USER)) {
df997f84
PS
2938 if ($preventredirect) {
2939 throw new require_login_exception('User not fully set-up');
2940 }
af572078 2941 if ($setwantsurltome) {
f0202ae9 2942 $SESSION->wantsurl = qualified_me();
af572078 2943 }
b0ccd3fb 2944 redirect($CFG->wwwroot .'/user/edit.php?id='. $USER->id .'&amp;course='. SITEID);
808a3baa 2945 }
d8ba183c 2946
df997f84 2947 // Make sure the USER has a sesskey set up. Used for CSRF protection.
04280e85 2948 sesskey();
366dfa60 2949
1560760f 2950 // Do not bother admins with any formalities
df997f84 2951 if (is_siteadmin()) {
1560760f
AD
2952 //set accesstime or the user will appear offline which messes up messaging
2953 user_accesstime_log($course->id);
df997f84
PS
2954 return;
2955 }
2956
b593d49d
PS
2957 // Check that the user has agreed to a site policy if there is one - do not test in case of admins
2958 if (!$USER->policyagreed and !is_siteadmin()) {
2959 if (!empty($CFG->sitepolicy) and !isguestuser()) {
2960 if ($preventredirect) {
2961 throw new require_login_exception('Policy not agreed');
2962 }
af572078 2963 if ($setwantsurltome) {
f0202ae9 2964 $SESSION->wantsurl = qualified_me();
af572078 2965 }
b593d49d
PS
2966 redirect($CFG->wwwroot .'/user/policy.php');
2967 } else if (!empty($CFG->sitepolicyguest) and isguestuser()) {
2968 if ($preventredirect) {
2969 throw new require_login_exception('Policy not agreed');
2970 }
af572078 2971 if ($setwantsurltome) {
f0202ae9 2972 $SESSION->wantsurl = qualified_me();
af572078 2973 }
027a1604 2974 redirect($CFG->wwwroot .'/user/policy.php');
027a1604 2975 }
1695b680 2976 }
2977
df997f84 2978 // Fetch the system context, the course context, and prefetch its child contexts
b0c6dc1c
AG
2979 $sysctx = context_system::instance();
2980 $coursecontext = context_course::instance($course->id, MUST_EXIST);
df997f84 2981 if ($cm) {
b0c6dc1c 2982 $cmcontext = context_module::instance($cm->id, MUST_EXIST);
df997f84
PS
2983 } else {
2984 $cmcontext = null;
2985 }
21e2dcd9 2986
df997f84 2987 // If the site is currently under maintenance, then print a message
4fe2250a 2988 if (!empty($CFG->maintenance_enabled) and !has_capability('moodle/site:config', $sysctx)) {
df997f84
PS
2989 if ($preventredirect) {
2990 throw new require_login_exception('Maintenance in progress');
2991 }
2992
4fe2250a 2993 print_maintenance_message();
027a1604 2994 }
2995
df997f84
PS
2996 // make sure the course itself is not hidden
2997 if ($course->id == SITEID) {
2998 // frontpage can not be hidden
2999 } else {
f5c1e621 3000 if (is_role_switched($course->id)) {
df997f84
PS
3001 // when switching roles ignore the hidden flag - user had to be in course to do the switch
3002 } else {
3003 if (!$course->visible and !has_capability('moodle/course:viewhiddencourses', $coursecontext)) {
3004 // originally there was also test of parent category visibility,
3005 // BUT is was very slow in complex queries involving "my courses"
3006 // now it is also possible to simply hide all courses user is not enrolled in :-)
3007 if ($preventredirect) {
3008 throw new require_login_exception('Course is hidden');
3009 }
a0a39b0d
SH
3010 // We need to override the navigation URL as the course won't have
3011 // been added to the navigation and thus the navigation will mess up
3012 // when trying to find it.
3013 navigation_node::override_active_url(new moodle_url('/'));
df997f84
PS
3014 notice(get_string('coursehidden'), $CFG->wwwroot .'/');
3015 }
3016 }
3017 }
3018
3019 // is the user enrolled?
3020 if ($course->id == SITEID) {
3021 // everybody is enrolled on the frontpage
3022
3023 } else {
3024 if (session_is_loggedinas()) {
3025 // Make sure the REAL person can access this course first
3026 $realuser = session_get_realuser();
3027 if (!is_enrolled($coursecontext, $realuser->id, '', true) and !is_viewing($coursecontext, $realuser->id) and !is_siteadmin($realuser->id)) {
3028 if ($preventredirect) {
3029 throw new require_login_exception('Invalid course login-as access');
3030 }
3031 echo $OUTPUT->header();
3032 notice(get_string('studentnotallowed', '', fullname($USER, true)), $CFG->wwwroot .'/');
3033 }
3034 }
3035
df997f84
PS
3036 $access = false;
3037
dbd7282c
PS
3038 if (is_role_switched($course->id)) {
3039 // ok, user had to be inside this course before the switch
3040 $access = true;
3041
3042 } else if (is_viewing($coursecontext, $USER)) {
df997f84
PS
3043 // ok, no need to mess with enrol
3044 $access = true;
3045
3046 } else {
3047 if (isset($USER->enrol['enrolled'][$course->id])) {
bbfdff34 3048 if ($USER->enrol['enrolled'][$course->id] > time()) {
df997f84 3049 $access = true;
bbfdff34
PS
3050 if (isset($USER->enrol['tempguest'][$course->id])) {
3051 unset($USER->enrol['tempguest'][$course->id]);
3052 remove_temp_course_roles($coursecontext);
3053 }
df997f84
PS
3054 } else {
3055 //expired
3056 unset($USER->enrol['enrolled'][$course->id]);
3057 }
3058 }
3059 if (isset($USER->enrol['tempguest'][$course->id])) {
3060 if ($USER->enrol['tempguest'][$course->id] == 0) {
3061 $access = true;
3062 } else if ($USER->enrol['tempguest'][$course->id] > time()) {
3063 $access = true;
3064 } else {
3065 //expired
3066 unset($USER->enrol['tempguest'][$course->id]);
e922fe23 3067 remove_temp_course_roles($coursecontext);
df997f84
PS
3068 }
3069 }
3070
3071 if ($access) {
3072 // cache ok
df997f84 3073 } else {
bbfdff34
PS
3074 $until = enrol_get_enrolment_end($coursecontext->instanceid, $USER->id);
3075 if ($until !== false) {
3076 // active participants may always access, a timestamp in the future, 0 (always) or false.
3077 if ($until == 0) {
3078 $until = ENROL_MAX_TIMESTAMP;
df997f84 3079 }
bbfdff34
PS
3080 $USER->enrol['enrolled'][$course->id] = $until;
3081 $access = true;
3082
3083 } else {
3084 $instances = $DB->get_records('enrol', array('courseid'=>$course->id, 'status'=>ENROL_INSTANCE_ENABLED), 'sortorder, id ASC');
3085 $enrols = enrol_get_plugins(true);
3086 // first ask all enabled enrol instances in course if they want to auto enrol user
df997f84
PS
3087 foreach($instances as $instance) {
3088 if (!isset($enrols[$instance->enrol])) {
3089 continue;
3090 }
bbfdff34
PS
3091 // Get a duration for the enrolment, a timestamp in the future, 0 (always) or false.
3092 $until = $enrols[$instance->enrol]->try_autoenrol($instance);
df997f84 3093 if ($until !== false) {
bbfdff34
PS
3094 if ($until == 0) {
3095 $until = ENROL_MAX_TIMESTAMP;
3096 }
3097 $USER->enrol['enrolled'][$course->id] = $until;
df997f84
PS
3098 $access = true;
3099 break;
3100 }
3101 }
bbfdff34
PS
3102 // if not enrolled yet try to gain temporary guest access
3103 if (!$access) {
3104 foreach($instances as $instance) {
3105 if (!isset($enrols[$instance->enrol])) {
3106 continue;
3107 }
3108 // Get a duration for the guest access, a timestamp in the future or false.
3109 $until = $enrols[$instance->enrol]->try_guestaccess($instance);
3110 if ($until !== false and $until > time()) {
3111 $USER->enrol['tempguest'][$course->id] = $until;
3112 $access = true;
3113 break;
3114 }
3115 }
3116 }
df997f84
PS
3117 }
3118 }
3119 }
3120
3121 if (!$access) {
3122 if ($preventredirect) {
3123 throw new require_login_exception('Not enrolled');
3124 }
af572078 3125 if ($setwantsurltome) {
f0202ae9 3126 $SESSION->wantsurl = qualified_me();
af572078 3127 }
df997f84
PS
3128 redirect($CFG->wwwroot .'/enrol/index.php?id='. $course->id);
3129 }
3130 }
3131
0d8b6a69 3132 // Check visibility of activity to current user; includes visible flag, groupmembersonly,
3133 // conditional availability, etc
3134 if ($cm && !$cm->uservisible) {
df997f84
PS
3135 if ($preventredirect) {
3136 throw new require_login_exception('Activity is hidden');
3137 }
ee17c773
PS
3138 if ($course->id != SITEID) {
3139 $url = new moodle_url('/course/view.php', array('id'=>$course->id));
3140 } else {
3141 $url = new moodle_url('/');
3142 }
3143 redirect($url, get_string('activityiscurrentlyhidden'));
df997f84
PS
3144 }
3145
df997f84
PS
3146 // Finally access granted, update lastaccess times
3147 user_accesstime_log($course->id);
f9903ed0 3148}
3149
c4d0753b 3150
c4d0753b 3151/**
3152 * This function just makes sure a user is logged out.
3153 *
f76249cc 3154 * @package core_access
c4d0753b 3155 */
3156function require_logout() {
dd9e22f8 3157 global $USER;
c4d0753b 3158
a8e3b008
DC
3159 $params = $USER;
3160
111e2360 3161 if (isloggedin()) {
c4d0753b 3162 add_to_log(SITEID, "user", "logout", "view.php?id=$USER->id&course=".SITEID, $USER->id, 0, $USER->id);
3163
533f7910 3164 $authsequence = get_enabled_auth_plugins(); // auths, in sequence
3165 foreach($authsequence as $authname) {
3166 $authplugin = get_auth_plugin($authname);
3167 $authplugin->prelogout_hook();
81693ac7 3168 }
c4d0753b 3169 }
3170
a8e3b008