weekly release 2.5dev
[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
915 if (!preg_match('/^[a-z][a-z0-9_]*[a-z0-9]$/', $param)) {
916 return '';
917 }
918 if (strpos($param, '__') !== false) {
919 return '';
920 }
921 return $param;
922
a083b93c 923 case PARAM_SAFEDIR: // Remove everything not a-zA-Z0-9_-
6dbcacee 924 return preg_replace('/[^a-zA-Z0-9_-]/i', '', $param);
95bfd207 925
6e73ae10 926 case PARAM_SAFEPATH: // Remove everything not a-zA-Z0-9/_-
6759ad2f 927 return preg_replace('/[^a-zA-Z0-9\/_-]/i', '', $param);
6e73ae10 928
a083b93c 929 case PARAM_FILE: // Strip all suspicious characters from filename
78fcdb5f 930 $param = fix_utf8($param);
14f3ad15 931 $param = preg_replace('~[[:cntrl:]]|[&<>"`\|\':\\\\/]~u', '', $param);
caf16a57 932 if ($param === '.' || $param === '..') {
371a2ed0 933 $param = '';
934 }
a083b93c 935 return $param;
936
937 case PARAM_PATH: // Strip all suspicious characters from file path
78fcdb5f 938 $param = fix_utf8($param);
a083b93c 939 $param = str_replace('\\', '/', $param);
caf16a57
FM
940
941 // Explode the path and clean each element using the PARAM_FILE rules.
942 $breadcrumb = explode('/', $param);
943 foreach ($breadcrumb as $key => $crumb) {
944 if ($crumb === '.' && $key === 0) {
945 // Special condition to allow for relative current path such as ./currentdirfile.txt.
946 } else {
947 $crumb = clean_param($crumb, PARAM_FILE);
948 }
949 $breadcrumb[$key] = $crumb;
950 }
951 $param = implode('/', $breadcrumb);
952
953 // Remove multiple current path (./././) and multiple slashes (///).
6dbcacee 954 $param = preg_replace('~//+~', '/', $param);
caf16a57
FM
955 $param = preg_replace('~/(\./)+~', '/', $param);
956 return $param;
a083b93c 957
958 case PARAM_HOST: // allow FQDN or IPv4 dotted quad
3e475991 959 $param = preg_replace('/[^\.\d\w-]/','', $param ); // only allowed chars
a083b93c 960 // match ipv4 dotted quad
961 if (preg_match('/(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})/',$param, $match)){
962 // confirm values are ok
963 if ( $match[0] > 255
964 || $match[1] > 255
965 || $match[3] > 255
966 || $match[4] > 255 ) {
967 // hmmm, what kind of dotted quad is this?
968 $param = '';
969 }
970 } elseif ( preg_match('/^[\w\d\.-]+$/', $param) // dots, hyphens, numbers
971 && !preg_match('/^[\.-]/', $param) // no leading dots/hyphens
972 && !preg_match('/[\.-]$/', $param) // no trailing dots/hyphens
973 ) {
974 // all is ok - $param is respected
975 } else {
976 // all is not ok...
977 $param='';
978 }
979 return $param;
7744ea12 980
a083b93c 981 case PARAM_URL: // allow safe ftp, http, mailto urls
78fcdb5f 982 $param = fix_utf8($param);
a083b93c 983 include_once($CFG->dirroot . '/lib/validateurlsyntax.php');
5301205a 984 if (!empty($param) && validateUrlSyntax($param, 's?H?S?F?E?u-P-a?I?p?f?q?r?')) {
a083b93c 985 // all is ok, param is respected
d2a9f7cc 986 } else {
a083b93c 987 $param =''; // not really ok
988 }
989 return $param;
990
991 case PARAM_LOCALURL: // allow http absolute, root relative and relative URLs within wwwroot
93684765 992 $param = clean_param($param, PARAM_URL);
a083b93c 993 if (!empty($param)) {
994 if (preg_match(':^/:', $param)) {
995 // root-relative, ok!
996 } elseif (preg_match('/^'.preg_quote($CFG->wwwroot, '/').'/i',$param)) {
997 // absolute, and matches our wwwroot
7744ea12 998 } else {
a083b93c 999 // relative - let's make sure there are no tricks
4bea5e85 1000 if (validateUrlSyntax('/' . $param, 's-u-P-a-p-f+q?r?')) {
a083b93c 1001 // looks ok.
1002 } else {
1003 $param = '';
1004 }
d2a9f7cc 1005 }
7744ea12 1006 }
a083b93c 1007 return $param;
bcef0319 1008
03d820c7 1009 case PARAM_PEM:
1010 $param = trim($param);
1011 // PEM formatted strings may contain letters/numbers and the symbols
1012 // forward slash: /
1013 // plus sign: +
1014 // equal sign: =
1015 // , surrounded by BEGIN and END CERTIFICATE prefix and suffixes
1016 if (preg_match('/^-----BEGIN CERTIFICATE-----([\s\w\/\+=]+)-----END CERTIFICATE-----$/', trim($param), $matches)) {
1017 list($wholething, $body) = $matches;
1018 unset($wholething, $matches);
1019 $b64 = clean_param($body, PARAM_BASE64);
1020 if (!empty($b64)) {
1021 return "-----BEGIN CERTIFICATE-----\n$b64\n-----END CERTIFICATE-----\n";
1022 } else {
1023 return '';
1024 }
1025 }
1026 return '';
bcef0319 1027
03d820c7 1028 case PARAM_BASE64:
1029 if (!empty($param)) {
1030 // PEM formatted strings may contain letters/numbers and the symbols
1031 // forward slash: /
1032 // plus sign: +
1033 // equal sign: =
03d820c7 1034 if (0 >= preg_match('/^([\s\w\/\+=]+)$/', trim($param))) {
1035 return '';
1036 }
1037 $lines = preg_split('/[\s]+/', $param, -1, PREG_SPLIT_NO_EMPTY);
1038 // Each line of base64 encoded data must be 64 characters in
1039 // length, except for the last line which may be less than (or
1040 // equal to) 64 characters long.
1041 for ($i=0, $j=count($lines); $i < $j; $i++) {
1042 if ($i + 1 == $j) {
1043 if (64 < strlen($lines[$i])) {
1044 return '';
1045 }
1046 continue;
1047 }
7744ea12 1048
03d820c7 1049 if (64 != strlen($lines[$i])) {
1050 return '';
1051 }
1052 }
1053 return implode("\n",$lines);
1054 } else {
1055 return '';
1056 }
bcef0319 1057
1058 case PARAM_TAG:
78fcdb5f 1059 $param = fix_utf8($param);
34b93e39
PS
1060 // Please note it is not safe to use the tag name directly anywhere,
1061 // it must be processed with s(), urlencode() before embedding anywhere.
1062 // remove some nasties
6b24e35e 1063 $param = preg_replace('~[[:cntrl:]]|[<>`]~u', '', $param);
3d535996 1064 //convert many whitespace chars into one
bcef0319 1065 $param = preg_replace('/\s+/', ' ', $param);
f8311def 1066 $param = textlib::substr(trim($param), 0, TAG_MAX_LENGTH);
c93c6b3b 1067 return $param;
bcef0319 1068
ae040d4b 1069 case PARAM_TAGLIST:
78fcdb5f 1070 $param = fix_utf8($param);
ae040d4b 1071 $tags = explode(',', $param);
1072 $result = array();
1073 foreach ($tags as $tag) {
1074 $res = clean_param($tag, PARAM_TAG);
6e73ae10 1075 if ($res !== '') {
ae040d4b 1076 $result[] = $res;
1077 }
1078 }
1079 if ($result) {
1080 return implode(',', $result);
1081 } else {
1082 return '';
0d626493 1083 }
1084
ad944e78 1085 case PARAM_CAPABILITY:
4f0c2d00 1086 if (get_capability_info($param)) {
ad944e78 1087 return $param;
1088 } else {
1089 return '';
1090 }
1091
faf75fe7 1092 case PARAM_PERMISSION:
1093 $param = (int)$param;
1094 if (in_array($param, array(CAP_INHERIT, CAP_ALLOW, CAP_PREVENT, CAP_PROHIBIT))) {
1095 return $param;
1096 } else {
1097 return CAP_INHERIT;
1098 }
1099
03b31ea3 1100 case PARAM_AUTH:
aff24313
PS
1101 $param = clean_param($param, PARAM_PLUGIN);
1102 if (empty($param)) {
1103 return '';
1104 } else if (exists_auth_plugin($param)) {
03b31ea3 1105 return $param;
1106 } else {
1107 return '';
1108 }
1109
1110 case PARAM_LANG:
1111 $param = clean_param($param, PARAM_SAFEDIR);
ef686eb5 1112 if (get_string_manager()->translation_exists($param)) {
03b31ea3 1113 return $param;
1114 } else {
ef686eb5 1115 return ''; // Specified language is not installed or param malformed
03b31ea3 1116 }
1117
1118 case PARAM_THEME:
aff24313
PS
1119 $param = clean_param($param, PARAM_PLUGIN);
1120 if (empty($param)) {
1121 return '';
1122 } else if (file_exists("$CFG->dirroot/theme/$param/config.php")) {
73e504bc
PS
1123 return $param;
1124 } else if (!empty($CFG->themedir) and file_exists("$CFG->themedir/$param/config.php")) {
03b31ea3 1125 return $param;
1126 } else {
1127 return ''; // Specified theme is not installed
1128 }
1129
07ed083e 1130 case PARAM_USERNAME:
78fcdb5f 1131 $param = fix_utf8($param);
07ed083e 1132 $param = str_replace(" " , "", $param);
6f3451e5 1133 $param = textlib::strtolower($param); // Convert uppercase to lowercase MDL-16919
34d2b19a 1134 if (empty($CFG->extendedusernamechars)) {
07ed083e
RW
1135 // regular expression, eliminate all chars EXCEPT:
1136 // alphanum, dash (-), underscore (_), at sign (@) and period (.) characters.
1137 $param = preg_replace('/[^-\.@_a-z0-9]/', '', $param);
4f0c2d00 1138 }
07ed083e
RW
1139 return $param;
1140
79f1d953 1141 case PARAM_EMAIL:
78fcdb5f 1142 $param = fix_utf8($param);
79f1d953 1143 if (validate_email($param)) {
1144 return $param;
1145 } else {
1146 return '';
1147 }
1148
fe6a248f
DM
1149 case PARAM_STRINGID:
1150 if (preg_match('|^[a-zA-Z][a-zA-Z0-9\.:/_-]*$|', $param)) {
1151 return $param;
1152 } else {
1153 return '';
1154 }
1155
ccc77f91 1156 case PARAM_TIMEZONE: //can be int, float(with .5 or .0) or string seperated by '/' and can have '-_'
78fcdb5f 1157 $param = fix_utf8($param);
8158ce79 1158 $timezonepattern = '/^(([+-]?(0?[0-9](\.[5|0])?|1[0-3](\.0)?|1[0-2]\.5))|(99)|[[:alnum:]]+(\/?[[:alpha:]_-])+)$/';
ccc77f91
RT
1159 if (preg_match($timezonepattern, $param)) {
1160 return $param;
1161 } else {
1162 return '';
1163 }
1164
a083b93c 1165 default: // throw error, switched parameters in optional_param or another serious problem
03b31ea3 1166 print_error("unknownparamtype", '', '', $type);
2ae28153 1167 }
e0d346ff 1168}
1169
78fcdb5f
PS
1170/**
1171 * Makes sure the data is using valid utf8, invalid characters are discarded.
1172 *
1173 * Note: this function is not intended for full objects with methods and private properties.
1174 *
1175 * @param mixed $value
1176 * @return mixed with proper utf-8 encoding
1177 */
1178function fix_utf8($value) {
1179 if (is_null($value) or $value === '') {
1180 return $value;
1181
1182 } else if (is_string($value)) {
1183 if ((string)(int)$value === $value) {
1184 // shortcut
1185 return $value;
1186 }
0aff15c2
PS
1187
1188 // Lower error reporting because glibc throws bogus notices.
51b7297b
PS
1189 $olderror = error_reporting();
1190 if ($olderror & E_NOTICE) {
1191 error_reporting($olderror ^ E_NOTICE);
1192 }
0aff15c2
PS
1193
1194 // Note: this duplicates min_fix_utf8() intentionally.
1195 static $buggyiconv = null;
1196 if ($buggyiconv === null) {
1197 $buggyiconv = (!function_exists('iconv') or iconv('UTF-8', 'UTF-8//IGNORE', '100'.chr(130).'€') !== '100€');
1198 }
1199
1200 if ($buggyiconv) {
1201 if (function_exists('mb_convert_encoding')) {
1202 $subst = mb_substitute_character();
1203 mb_substitute_character('');
1204 $result = mb_convert_encoding($value, 'utf-8', 'utf-8');
1205 mb_substitute_character($subst);
1206
1207 } else {
1208 // Warn admins on admin/index.php page.
1209 $result = $value;
1210 }
1211
1212 } else {
1213 $result = iconv('UTF-8', 'UTF-8//IGNORE', $value);
1214 }
1215
51b7297b
PS
1216 if ($olderror & E_NOTICE) {
1217 error_reporting($olderror);
1218 }
0aff15c2 1219
51b7297b 1220 return $result;
78fcdb5f
PS
1221
1222 } else if (is_array($value)) {
1223 foreach ($value as $k=>$v) {
1224 $value[$k] = fix_utf8($v);
1225 }
1226 return $value;
1227
1228 } else if (is_object($value)) {
1229 $value = clone($value); // do not modify original
1230 foreach ($value as $k=>$v) {
1231 $value->$k = fix_utf8($v);
1232 }
1233 return $value;
1234
1235 } else {
1236 // this is some other type, no utf-8 here
1237 return $value;
1238 }
1239}
1240
6e73ae10 1241/**
1242 * Return true if given value is integer or string with integer value
0d0a8bf6 1243 *
1244 * @param mixed $value String or Int
1245 * @return bool true if number, false if not
6e73ae10 1246 */
1247function is_number($value) {
1248 if (is_int($value)) {
1249 return true;
1250 } else if (is_string($value)) {
1251 return ((string)(int)$value) === $value;
1252 } else {
1253 return false;
1254 }
1255}
7a530277 1256
aa282b10 1257/**
1258 * Returns host part from url
1259 * @param string $url full url
1260 * @return string host, null if not found
1261 */
1262function get_host_from_url($url) {
1263 preg_match('|^[a-z]+://([a-zA-Z0-9-.]+)|i', $url, $matches);
1264 if ($matches) {
1265 return $matches[1];
1266 }
1267 return null;
1268}
1269
94a6d656 1270/**
0d0a8bf6 1271 * Tests whether anything was returned by text editor
1272 *
94a6d656 1273 * This function is useful for testing whether something you got back from
1274 * the HTML editor actually contains anything. Sometimes the HTML editor
1275 * appear to be empty, but actually you get back a <br> tag or something.
1276 *
1277 * @param string $string a string containing HTML.
1278 * @return boolean does the string contain any actual content - that is text,
efb8c375 1279 * images, objects, etc.
94a6d656 1280 */
1281function html_is_blank($string) {
1282 return trim(strip_tags($string, '<img><object><applet><input><select><textarea><hr>')) == '';
1283}
1284
7cf1c7bd 1285/**
1286 * Set a key in global configuration
1287 *
89dcb99d 1288 * Set a key/value pair in both this session's {@link $CFG} global variable
7cf1c7bd 1289 * and in the 'config' database table for future sessions.
e1ecf0a0 1290 *
1291 * Can also be used to update keys for plugin-scoped configs in config_plugin table.
1292 * In that case it doesn't affect $CFG.
7cf1c7bd 1293 *
6fd511eb 1294 * A NULL value will delete the entry.
1295 *
0d0a8bf6 1296 * @global object
1297 * @global object
7cf1c7bd 1298 * @param string $name the key to set
9cdb766d 1299 * @param string $value the value to set (without magic quotes)
0d0a8bf6 1300 * @param string $plugin (optional) the plugin scope, default NULL
5e2f308b 1301 * @return bool true or exception
7cf1c7bd 1302 */
a4080313 1303function set_config($name, $value, $plugin=NULL) {
ae040d4b 1304 global $CFG, $DB;
42282810 1305
a4080313 1306 if (empty($plugin)) {
220a90c5 1307 if (!array_key_exists($name, $CFG->config_php_settings)) {
1308 // So it's defined for this invocation at least
1309 if (is_null($value)) {
1310 unset($CFG->$name);
1311 } else {
9c305ba1 1312 $CFG->$name = (string)$value; // settings from db are always strings
220a90c5 1313 }
1314 }
e1ecf0a0 1315
ae040d4b 1316 if ($DB->get_field('config', 'name', array('name'=>$name))) {
5e2f308b 1317 if ($value === null) {
1318 $DB->delete_records('config', array('name'=>$name));
6fd511eb 1319 } else {
5e2f308b 1320 $DB->set_field('config', 'value', $value, array('name'=>$name));
6fd511eb 1321 }
a4080313 1322 } else {
5e2f308b 1323 if ($value !== null) {
365a5941 1324 $config = new stdClass();
5e2f308b 1325 $config->name = $name;
1326 $config->value = $value;
1327 $DB->insert_record('config', $config, false);
6fd511eb 1328 }
a4080313 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 *
12bb0c3e 1363 * @param string $plugin full component name
0d0a8bf6 1364 * @param string $name default NULL
07ab0c80 1365 * @return mixed hash-like object or single value, return false no config found
a4080313 1366 */
12bb0c3e 1367function get_config($plugin, $name = NULL) {
ae040d4b 1368 global $CFG, $DB;
dfc9ba9b 1369
007bfe8b
SH
1370 if ($plugin === 'moodle' || $plugin === 'core' || empty($plugin)) {
1371 $forced =& $CFG->config_php_settings;
1372 $iscore = true;
1373 $plugin = 'core';
1374 } else {
1375 if (array_key_exists($plugin, $CFG->forced_plugin_settings)) {
1376 $forced =& $CFG->forced_plugin_settings[$plugin];
1377 } else {
1378 $forced = array();
1379 }
1380 $iscore = false;
12bb0c3e
PS
1381 }
1382
007bfe8b
SH
1383 if (!empty($name) && array_key_exists($name, $forced)) {
1384 return (string)$forced[$name];
1385 }
1386
1387 $cache = cache::make('core', 'config');
1388 $result = $cache->get($plugin);
1389 if (!$result) {
1390 // the user is after a recordset
1391 $result = new stdClass;
1392 if (!$iscore) {
1393 $result = $DB->get_records_menu('config_plugins', array('plugin'=>$plugin), '', 'name,value');
a4080313 1394 } else {
007bfe8b
SH
1395 // this part is not really used any more, but anyway...
1396 $result = $DB->get_records_menu('config', array(), '', 'name,value');;
a4080313 1397 }
007bfe8b 1398 $cache->set($plugin, $result);
a4080313 1399 }
1400
007bfe8b
SH
1401 if (!empty($name)) {
1402 if (array_key_exists($name, $result)) {
1403 return $result[$name];
bfb82da3 1404 }
007bfe8b
SH
1405 return false;
1406 }
e1ecf0a0 1407
007bfe8b
SH
1408 foreach ($forced as $key => $value) {
1409 if (is_null($value) or is_array($value) or is_object($value)) {
1410 // we do not want any extra mess here, just real settings that could be saved in db
1411 unset($result[$key]);
1412 } else {
1413 //convert to string as if it went through the DB
1414 $result[$key] = (string)$value;
12bb0c3e 1415 }
39917a09 1416 }
007bfe8b
SH
1417
1418 return (object)$result;
39917a09 1419}
1420
b0270f84 1421/**
1422 * Removes a key from global configuration
1423 *
1424 * @param string $name the key to set
1425 * @param string $plugin (optional) the plugin scope
0d0a8bf6 1426 * @global object
4b600aa0 1427 * @return boolean whether the operation succeeded.
b0270f84 1428 */
1429function unset_config($name, $plugin=NULL) {
ae040d4b 1430 global $CFG, $DB;
b0270f84 1431
b0270f84 1432 if (empty($plugin)) {
4b600aa0 1433 unset($CFG->$name);
013376de 1434 $DB->delete_records('config', array('name'=>$name));
007bfe8b 1435 cache_helper::invalidate_by_definition('core', 'config', array(), 'core');
5e623a33 1436 } else {
013376de 1437 $DB->delete_records('config_plugins', array('name'=>$name, 'plugin'=>$plugin));
007bfe8b 1438 cache_helper::invalidate_by_definition('core', 'config', array(), $plugin);
b0270f84 1439 }
013376de 1440
1441 return true;
b0270f84 1442}
1443
4b600aa0 1444/**
1445 * Remove all the config variables for a given plugin.
1446 *
1447 * @param string $plugin a plugin, for example 'quiz' or 'qtype_multichoice';
1448 * @return boolean whether the operation succeeded.
1449 */
1450function unset_all_config_for_plugin($plugin) {
1451 global $DB;
007bfe8b 1452 // Delete from the obvious config_plugins first
013376de 1453 $DB->delete_records('config_plugins', array('plugin' => $plugin));
007bfe8b 1454 // Next delete any suspect settings from config
a4193166
PS
1455 $like = $DB->sql_like('name', '?', true, true, false, '|');
1456 $params = array($DB->sql_like_escape($plugin.'_', '|') . '%');
1457 $DB->delete_records_select('config', $like, $params);
007bfe8b
SH
1458 // Finally clear both the plugin cache and the core cache (suspect settings now removed from core).
1459 cache_helper::invalidate_by_definition('core', 'config', array(), array('core', $plugin));
1460
013376de 1461 return true;
4b600aa0 1462}
1463
4413941f 1464/**
efb8c375 1465 * Use this function to get a list of users from a config setting of type admin_setting_users_with_capability.
adf176d7
PS
1466 *
1467 * All users are verified if they still have the necessary capability.
1468 *
b3d960e6 1469 * @param string $value the value of the config setting.
4413941f 1470 * @param string $capability the capability - must match the one passed to the admin_setting_users_with_capability constructor.
efb8c375 1471 * @param bool $include admins, include administrators
4413941f 1472 * @return array of user objects.
1473 */
adf176d7
PS
1474function get_users_from_config($value, $capability, $includeadmins = true) {
1475 global $CFG, $DB;
1476
1477 if (empty($value) or $value === '$@NONE@$') {
1478 return array();
4413941f 1479 }
adf176d7
PS
1480
1481 // we have to make sure that users still have the necessary capability,
1482 // it should be faster to fetch them all first and then test if they are present
6b8ad965 1483 // instead of validating them one-by-one
b0c6dc1c 1484 $users = get_users_by_capability(context_system::instance(), $capability);
adf176d7
PS
1485 if ($includeadmins) {
1486 $admins = get_admins();
1487 foreach ($admins as $admin) {
1488 $users[$admin->id] = $admin;
1489 }
1490 }
1491
1492 if ($value === '$@ALL@$') {
1493 return $users;
1494 }
1495
1496 $result = array(); // result in correct order
1497 $allowed = explode(',', $value);
1498 foreach ($allowed as $uid) {
1499 if (isset($users[$uid])) {
1500 $user = $users[$uid];
1501 $result[$user->id] = $user;
1502 }
1503 }
1504
1505 return $result;
4413941f 1506}
1507
f87eab7e
PS
1508
1509/**
1510 * Invalidates browser caches and cached data in temp
52642d0d
SH
1511 *
1512 * IMPORTANT - If you are adding anything here to do with the cache directory you should also have a look at
1513 * {@see phpunit_util::reset_dataroot()}
1514 *
f87eab7e
PS
1515 * @return void
1516 */
1517function purge_all_caches() {
1518 global $CFG;
1519
f87eab7e
PS
1520 reset_text_filters_cache();
1521 js_reset_all_caches();
1522 theme_reset_all_caches();
1523 get_string_manager()->reset_caches();
bc5c10f6 1524 textlib::reset_caches();
f87eab7e 1525
d6a1f63b
SH
1526 cache_helper::purge_all();
1527
dc2c9bd7 1528 // purge all other caches: rss, simplepie, etc.
365bec4c 1529 remove_dir($CFG->cachedir.'', true);
f87eab7e 1530
c426ef3a 1531 // make sure cache dir is writable, throws exception if not
5a87c912 1532 make_cache_directory('');
f87eab7e 1533
b216a820
PS
1534 // hack: this script may get called after the purifier was initialised,
1535 // but we do not want to verify repeatedly this exists in each call
5a87c912 1536 make_cache_directory('htmlpurifier');
f87eab7e
PS
1537}
1538
bafd7e78 1539/**
1540 * Get volatile flags
1541 *
1542 * @param string $type
0d0a8bf6 1543 * @param int $changedsince default null
bafd7e78 1544 * @return records array
bafd7e78 1545 */
1546function get_cache_flags($type, $changedsince=NULL) {
ae040d4b 1547 global $DB;
bafd7e78 1548
ae040d4b 1549 $params = array('type'=>$type, 'expiry'=>time());
1550 $sqlwhere = "flagtype = :type AND expiry >= :expiry";
bafd7e78 1551 if ($changedsince !== NULL) {
ae040d4b 1552 $params['changedsince'] = $changedsince;
1553 $sqlwhere .= " AND timemodified > :changedsince";
bafd7e78 1554 }
1555 $cf = array();
ae040d4b 1556
1557 if ($flags = $DB->get_records_select('cache_flags', $sqlwhere, $params, '', 'name,value')) {
bafd7e78 1558 foreach ($flags as $flag) {
1559 $cf[$flag->name] = $flag->value;
1560 }
1561 }
1562 return $cf;
1563}
1564
a489cf72 1565/**
1566 * Get volatile flags
1567 *
1568 * @param string $type
1569 * @param string $name
0d0a8bf6 1570 * @param int $changedsince default null
a489cf72 1571 * @return records array
a489cf72 1572 */
1573function get_cache_flag($type, $name, $changedsince=NULL) {
ae040d4b 1574 global $DB;
a489cf72 1575
ae040d4b 1576 $params = array('type'=>$type, 'name'=>$name, 'expiry'=>time());
a489cf72 1577
ae040d4b 1578 $sqlwhere = "flagtype = :type AND name = :name AND expiry >= :expiry";
a489cf72 1579 if ($changedsince !== NULL) {
ae040d4b 1580 $params['changedsince'] = $changedsince;
1581 $sqlwhere .= " AND timemodified > :changedsince";
a489cf72 1582 }
ae040d4b 1583
1584 return $DB->get_field_select('cache_flags', 'value', $sqlwhere, $params);
a489cf72 1585}
bafd7e78 1586
1587/**
1588 * Set a volatile flag
1589 *
1590 * @param string $type the "type" namespace for the key
1591 * @param string $name the key to set
1592 * @param string $value the value to set (without magic quotes) - NULL will remove the flag
1593 * @param int $expiry (optional) epoch indicating expiry - defaults to now()+ 24hs
0d0a8bf6 1594 * @return bool Always returns true
bafd7e78 1595 */
1596function set_cache_flag($type, $name, $value, $expiry=NULL) {
ae040d4b 1597 global $DB;
bafd7e78 1598
1599 $timemodified = time();
1600 if ($expiry===NULL || $expiry < $timemodified) {
1601 $expiry = $timemodified + 24 * 60 * 60;
1602 } else {
1603 $expiry = (int)$expiry;
1604 }
1605
1606 if ($value === NULL) {
013376de 1607 unset_cache_flag($type,$name);
1608 return true;
bafd7e78 1609 }
1610
39461de3 1611 if ($f = $DB->get_record('cache_flags', array('name'=>$name, 'flagtype'=>$type), '*', IGNORE_MULTIPLE)) { // this is a potential problem in DEBUG_DEVELOPER
128f0984 1612 if ($f->value == $value and $f->expiry == $expiry and $f->timemodified == $timemodified) {
0b37fe46 1613 return true; //no need to update
128f0984 1614 }
ae040d4b 1615 $f->value = $value;
bafd7e78 1616 $f->expiry = $expiry;
1617 $f->timemodified = $timemodified;
013376de 1618 $DB->update_record('cache_flags', $f);
bafd7e78 1619 } else {
365a5941 1620 $f = new stdClass();
bafd7e78 1621 $f->flagtype = $type;
1622 $f->name = $name;
ae040d4b 1623 $f->value = $value;
bafd7e78 1624 $f->expiry = $expiry;
1625 $f->timemodified = $timemodified;
013376de 1626 $DB->insert_record('cache_flags', $f);
bafd7e78 1627 }
013376de 1628 return true;
bafd7e78 1629}
1630
1631/**
1632 * Removes a single volatile flag
1633 *
0d0a8bf6 1634 * @global object
bafd7e78 1635 * @param string $type the "type" namespace for the key
1636 * @param string $name the key to set
bafd7e78 1637 * @return bool
1638 */
1639function unset_cache_flag($type, $name) {
ae040d4b 1640 global $DB;
013376de 1641 $DB->delete_records('cache_flags', array('name'=>$name, 'flagtype'=>$type));
1642 return true;
bafd7e78 1643}
1644
1645/**
1646 * Garbage-collect volatile flags
1647 *
0d0a8bf6 1648 * @return bool Always returns true
bafd7e78 1649 */
1650function gc_cache_flags() {
ae040d4b 1651 global $DB;
013376de 1652 $DB->delete_records_select('cache_flags', 'expiry < ?', array(time()));
1653 return true;
bafd7e78 1654}
a4080313 1655
4d6b40a0 1656// USER PREFERENCE API
2660377f 1657
7cf1c7bd 1658/**
39461de3
PS
1659 * Refresh user preference cache. This is used most often for $USER
1660 * object that is stored in session, but it also helps with performance in cron script.
0d0a8bf6 1661 *
39461de3
PS
1662 * Preferences for each user are loaded on first use on every page, then again after the timeout expires.
1663 *
4d6b40a0
GGC
1664 * @package core
1665 * @category preference
1666 * @access public
1667 * @param stdClass $user User object. Preferences are preloaded into 'preference' property
1668 * @param int $cachelifetime Cache life time on the current page (in seconds)
1669 * @throws coding_exception
1670 * @return null
7cf1c7bd 1671 */
39461de3
PS
1672function check_user_preferences_loaded(stdClass $user, $cachelifetime = 120) {
1673 global $DB;
1674 static $loadedusers = array(); // Static cache, we need to check on each page load, not only every 2 minutes.
2660377f 1675
39461de3
PS
1676 if (!isset($user->id)) {
1677 throw new coding_exception('Invalid $user parameter in check_user_preferences_loaded() call, missing id field');
1678 }
2660377f 1679
39461de3
PS
1680 if (empty($user->id) or isguestuser($user->id)) {
1681 // No permanent storage for not-logged-in users and guest
1682 if (!isset($user->preference)) {
1683 $user->preference = array();
2660377f 1684 }
39461de3 1685 return;
2660377f 1686 }
70812e39 1687
39461de3 1688 $timenow = time();
070e2616 1689
39461de3
PS
1690 if (isset($loadedusers[$user->id]) and isset($user->preference) and isset($user->preference['_lastloaded'])) {
1691 // Already loaded at least once on this page. Are we up to date?
1692 if ($user->preference['_lastloaded'] + $cachelifetime > $timenow) {
1693 // no need to reload - we are on the same page and we loaded prefs just a moment ago
1694 return;
70812e39 1695
39461de3
PS
1696 } else if (!get_cache_flag('userpreferenceschanged', $user->id, $user->preference['_lastloaded'])) {
1697 // no change since the lastcheck on this page
1698 $user->preference['_lastloaded'] = $timenow;
1699 return;
70812e39 1700 }
c6d15803 1701 }
346c3e2f 1702
39461de3
PS
1703 // OK, so we have to reload all preferences
1704 $loadedusers[$user->id] = true;
1705 $user->preference = $DB->get_records_menu('user_preferences', array('userid'=>$user->id), '', 'name,value'); // All values
1706 $user->preference['_lastloaded'] = $timenow;
2660377f 1707}
1708
1709/**
4d6b40a0 1710 * Called from set/unset_user_preferences, so that the prefs can
39461de3
PS
1711 * be correctly reloaded in different sessions.
1712 *
1713 * NOTE: internal function, do not call from other code.
0d0a8bf6 1714 *
4d6b40a0
GGC
1715 * @package core
1716 * @access private
1717 * @param integer $userid the user whose prefs were changed.
2660377f 1718 */
1719function mark_user_preferences_changed($userid) {
39461de3
PS
1720 global $CFG;
1721
1722 if (empty($userid) or isguestuser($userid)) {
1723 // no cache flags for guest and not-logged-in users
1724 return;
2660377f 1725 }
39461de3 1726
2660377f 1727 set_cache_flag('userpreferenceschanged', $userid, 1, time() + $CFG->sessiontimeout);
70812e39 1728}
1729
7cf1c7bd 1730/**
39461de3 1731 * Sets a preference for the specified user.
0d0a8bf6 1732 *
4d6b40a0 1733 * If a $user object is submitted it's 'preference' property is used for the preferences cache.
0d0a8bf6 1734 *
4d6b40a0
GGC
1735 * @package core
1736 * @category preference
1737 * @access public
1738 * @param string $name The key to set as preference for the specified user
1739 * @param string $value The value to set for the $name key in the specified user's
1740 * record, null means delete current value.
1741 * @param stdClass|int|null $user A moodle user object or id, null means current user
1742 * @throws coding_exception
1743 * @return bool Always true or exception
7cf1c7bd 1744 */
39461de3 1745function set_user_preference($name, $value, $user = null) {
ae040d4b 1746 global $USER, $DB;
70812e39 1747
39461de3
PS
1748 if (empty($name) or is_numeric($name) or $name === '_lastloaded') {
1749 throw new coding_exception('Invalid preference name in set_user_preference() call');
70812e39 1750 }
1751
39461de3
PS
1752 if (is_null($value)) {
1753 // null means delete current
1754 return unset_user_preference($name, $user);
1755 } else if (is_object($value)) {
1756 throw new coding_exception('Invalid value in set_user_preference() call, objects are not allowed');
1757 } else if (is_array($value)) {
1758 throw new coding_exception('Invalid value in set_user_preference() call, arrays are not allowed');
1759 }
1760 $value = (string)$value;
8e54ce97
AD
1761 if (textlib::strlen($value) > 1333) { //value column maximum length is 1333 characters
1762 throw new coding_exception('Invalid value in set_user_preference() call, value is is too long for the value column');
1763 }
39461de3
PS
1764
1765 if (is_null($user)) {
1766 $user = $USER;
1767 } else if (isset($user->id)) {
1768 // $user is valid object
1769 } else if (is_numeric($user)) {
1770 $user = (object)array('id'=>(int)$user);
346c3e2f 1771 } else {
39461de3 1772 throw new coding_exception('Invalid $user parameter in set_user_preference() call');
346c3e2f 1773 }
1774
39461de3
PS
1775 check_user_preferences_loaded($user);
1776
1777 if (empty($user->id) or isguestuser($user->id)) {
1778 // no permanent storage for not-logged-in users and guest
1779 $user->preference[$name] = $value;
1780 return true;
1781 }
346c3e2f 1782
39461de3
PS
1783 if ($preference = $DB->get_record('user_preferences', array('userid'=>$user->id, 'name'=>$name))) {
1784 if ($preference->value === $value and isset($user->preference[$name]) and $user->preference[$name] === $value) {
1785 // preference already set to this value
a1244706 1786 return true;
1787 }
39461de3 1788 $DB->set_field('user_preferences', 'value', $value, array('id'=>$preference->id));
70812e39 1789
1790 } else {
365a5941 1791 $preference = new stdClass();
39461de3 1792 $preference->userid = $user->id;
ae040d4b 1793 $preference->name = $name;
39461de3 1794 $preference->value = $value;
013376de 1795 $DB->insert_record('user_preferences', $preference);
2660377f 1796 }
1797
39461de3
PS
1798 // update value in cache
1799 $user->preference[$name] = $value;
1800
1801 // set reload flag for other sessions
1802 mark_user_preferences_changed($user->id);
346c3e2f 1803
013376de 1804 return true;
2660377f 1805}
1806
1807/**
1808 * Sets a whole array of preferences for the current user
0d0a8bf6 1809 *
4d6b40a0 1810 * If a $user object is submitted it's 'preference' property is used for the preferences cache.
39461de3 1811 *
4d6b40a0
GGC
1812 * @package core
1813 * @category preference
1814 * @access public
1815 * @param array $prefarray An array of key/value pairs to be set
1816 * @param stdClass|int|null $user A moodle user object or id, null means current user
1817 * @return bool Always true or exception
2660377f 1818 */
39461de3 1819function set_user_preferences(array $prefarray, $user = null) {
2660377f 1820 foreach ($prefarray as $name => $value) {
39461de3 1821 set_user_preference($name, $value, $user);
2660377f 1822 }
013376de 1823 return true;
70812e39 1824}
1825
6eb3e776 1826/**
1827 * Unsets a preference completely by deleting it from the database
0d0a8bf6 1828 *
4d6b40a0 1829 * If a $user object is submitted it's 'preference' property is used for the preferences cache.
0d0a8bf6 1830 *
4d6b40a0
GGC
1831 * @package core
1832 * @category preference
1833 * @access public
1834 * @param string $name The key to unset as preference for the specified user
1835 * @param stdClass|int|null $user A moodle user object or id, null means current user
1836 * @throws coding_exception
1837 * @return bool Always true or exception
6eb3e776 1838 */
39461de3 1839function unset_user_preference($name, $user = null) {
ae040d4b 1840 global $USER, $DB;
6eb3e776 1841
39461de3
PS
1842 if (empty($name) or is_numeric($name) or $name === '_lastloaded') {
1843 throw new coding_exception('Invalid preference name in unset_user_preference() call');
1844 }
1845
1846 if (is_null($user)) {
1847 $user = $USER;
1848 } else if (isset($user->id)) {
1849 // $user is valid object
1850 } else if (is_numeric($user)) {
1851 $user = (object)array('id'=>(int)$user);
346c3e2f 1852 } else {
39461de3 1853 throw new coding_exception('Invalid $user parameter in unset_user_preference() call');
346c3e2f 1854 }
1855
39461de3 1856 check_user_preferences_loaded($user);
013376de 1857
39461de3
PS
1858 if (empty($user->id) or isguestuser($user->id)) {
1859 // no permanent storage for not-logged-in user and guest
1860 unset($user->preference[$name]);
1861 return true;
70812e39 1862 }
1863
39461de3
PS
1864 // delete from DB
1865 $DB->delete_records('user_preferences', array('userid'=>$user->id, 'name'=>$name));
1866
1867 // delete the preference from cache
1868 unset($user->preference[$name]);
1869
1870 // set reload flag for other sessions
1871 mark_user_preferences_changed($user->id);
1872
013376de 1873 return true;
70812e39 1874}
1875
7cf1c7bd 1876/**
0d0a8bf6 1877 * Used to fetch user preference(s)
1878 *
7cf1c7bd 1879 * If no arguments are supplied this function will return
361855e6 1880 * all of the current user preferences as an array.
0d0a8bf6 1881 *
7cf1c7bd 1882 * If a name is specified then this function
1883 * attempts to return that particular preference value. If
1884 * none is found, then the optional value $default is returned,
1885 * otherwise NULL.
0d0a8bf6 1886 *
4d6b40a0 1887 * If a $user object is submitted it's 'preference' property is used for the preferences cache.
39461de3 1888 *
4d6b40a0
GGC
1889 * @package core
1890 * @category preference
1891 * @access public
1892 * @param string $name Name of the key to use in finding a preference value
1893 * @param mixed|null $default Value to be returned if the $name key is not set in the user preferences
1894 * @param stdClass|int|null $user A moodle user object or id, null means current user
1895 * @throws coding_exception
1896 * @return string|mixed|null A string containing the value of a single preference. An
1897 * array with all of the preferences or null
7cf1c7bd 1898 */
39461de3
PS
1899function get_user_preferences($name = null, $default = null, $user = null) {
1900 global $USER;
70812e39 1901
39461de3
PS
1902 if (is_null($name)) {
1903 // all prefs
1904 } else if (is_numeric($name) or $name === '_lastloaded') {
1905 throw new coding_exception('Invalid preference name in get_user_preferences() call');
1906 }
346c3e2f 1907
39461de3
PS
1908 if (is_null($user)) {
1909 $user = $USER;
1910 } else if (isset($user->id)) {
1911 // $user is valid object
1912 } else if (is_numeric($user)) {
1913 $user = (object)array('id'=>(int)$user);
1914 } else {
1915 throw new coding_exception('Invalid $user parameter in get_user_preferences() call');
1916 }
1917
1918 check_user_preferences_loaded($user);
346c3e2f 1919
39461de3
PS
1920 if (empty($name)) {
1921 return $user->preference; // All values
1922 } else if (isset($user->preference[$name])) {
1923 return $user->preference[$name]; // The single string value
346c3e2f 1924 } else {
39461de3 1925 return $default; // Default value (null if not specified)
70812e39 1926 }
70812e39 1927}
1928
9fa49e22 1929/// FUNCTIONS FOR HANDLING TIME ////////////////////////////////////////////
39917a09 1930
7cf1c7bd 1931/**
c6d15803 1932 * Given date parts in user time produce a GMT timestamp.
7cf1c7bd 1933 *
9df12115
RT
1934 * @package core
1935 * @category time
68fbd8e1 1936 * @param int $year The year part to create timestamp of
1937 * @param int $month The month part to create timestamp of
1938 * @param int $day The day part to create timestamp of
1939 * @param int $hour The hour part to create timestamp of
1940 * @param int $minute The minute part to create timestamp of
1941 * @param int $second The second part to create timestamp of
9df12115
RT
1942 * @param int|float|string $timezone Timezone modifier, used to calculate GMT time offset.
1943 * if 99 then default user's timezone is used {@link http://docs.moodle.org/dev/Time_API#Timezone}
6a0bf5c4
RT
1944 * @param bool $applydst Toggle Daylight Saving Time, default true, will be
1945 * applied only if timezone is 99 or string.
9df12115 1946 * @return int GMT timestamp
7cf1c7bd 1947 */
9f1f6daf 1948function make_timestamp($year, $month=1, $day=1, $hour=0, $minute=0, $second=0, $timezone=99, $applydst=true) {
39917a09 1949
6a0bf5c4
RT
1950 //save input timezone, required for dst offset check.
1951 $passedtimezone = $timezone;
33998d30 1952
dddb014a 1953 $timezone = get_user_timezone_offset($timezone);
1954
6a0bf5c4 1955 if (abs($timezone) > 13) { //server time
68fbd8e1 1956 $time = mktime((int)$hour, (int)$minute, (int)$second, (int)$month, (int)$day, (int)$year);
03c17ddf 1957 } else {
68fbd8e1 1958 $time = gmmktime((int)$hour, (int)$minute, (int)$second, (int)$month, (int)$day, (int)$year);
196f2619 1959 $time = usertime($time, $timezone);
6a0bf5c4
RT
1960
1961 //Apply dst for string timezones or if 99 then try dst offset with user's default timezone
1962 if ($applydst && ((99 == $passedtimezone) || !is_numeric($passedtimezone))) {
1963 $time -= dst_offset_on($time, $passedtimezone);
28c66824 1964 }
9f1f6daf 1965 }
1966
196f2619 1967 return $time;
85cafb3e 1968
39917a09 1969}
1970
7cf1c7bd 1971/**
0d0a8bf6 1972 * Format a date/time (seconds) as weeks, days, hours etc as needed
1973 *
7cf1c7bd 1974 * Given an amount of time in seconds, returns string
5602f7cf 1975 * formatted nicely as weeks, days, hours etc as needed
7cf1c7bd 1976 *
9df12115
RT
1977 * @package core
1978 * @category time
2f87145b 1979 * @uses MINSECS
1980 * @uses HOURSECS
1981 * @uses DAYSECS
5602f7cf 1982 * @uses YEARSECS
0d0a8bf6 1983 * @param int $totalsecs Time in seconds
1984 * @param object $str Should be a time object
1985 * @return string A nicely formatted date/time string
7cf1c7bd 1986 */
1987 function format_time($totalsecs, $str=NULL) {
c7e3ac2a 1988
6b174680 1989 $totalsecs = abs($totalsecs);
c7e3ac2a 1990
8dbed6be 1991 if (!$str) { // Create the str structure the slow way
b85b25eb 1992 $str = new stdClass();
b0ccd3fb 1993 $str->day = get_string('day');
1994 $str->days = get_string('days');
1995 $str->hour = get_string('hour');
1996 $str->hours = get_string('hours');
1997 $str->min = get_string('min');
1998 $str->mins = get_string('mins');
1999 $str->sec = get_string('sec');
2000 $str->secs = get_string('secs');
5602f7cf 2001 $str->year = get_string('year');
2002 $str->years = get_string('years');
8dbed6be 2003 }
2004
5602f7cf 2005
2006 $years = floor($totalsecs/YEARSECS);
2007 $remainder = $totalsecs - ($years*YEARSECS);
5602f7cf 2008 $days = floor($remainder/DAYSECS);
7a5672c9 2009 $remainder = $totalsecs - ($days*DAYSECS);
2010 $hours = floor($remainder/HOURSECS);
2011 $remainder = $remainder - ($hours*HOURSECS);
2012 $mins = floor($remainder/MINSECS);
2013 $secs = $remainder - ($mins*MINSECS);
8dbed6be 2014
2015 $ss = ($secs == 1) ? $str->sec : $str->secs;
2016 $sm = ($mins == 1) ? $str->min : $str->mins;
2017 $sh = ($hours == 1) ? $str->hour : $str->hours;
2018 $sd = ($days == 1) ? $str->day : $str->days;
5602f7cf 2019 $sy = ($years == 1) ? $str->year : $str->years;
8dbed6be 2020
5602f7cf 2021 $oyears = '';
b0ccd3fb 2022 $odays = '';
2023 $ohours = '';
2024 $omins = '';
2025 $osecs = '';
9c9f7d77 2026
5602f7cf 2027 if ($years) $oyears = $years .' '. $sy;
b0ccd3fb 2028 if ($days) $odays = $days .' '. $sd;
2029 if ($hours) $ohours = $hours .' '. $sh;
2030 if ($mins) $omins = $mins .' '. $sm;
2031 if ($secs) $osecs = $secs .' '. $ss;
6b174680 2032
77ac808e 2033 if ($years) return trim($oyears .' '. $odays);
2034 if ($days) return trim($odays .' '. $ohours);
2035 if ($hours) return trim($ohours .' '. $omins);
2036 if ($mins) return trim($omins .' '. $osecs);
b0ccd3fb 2037 if ($secs) return $osecs;
2038 return get_string('now');
6b174680 2039}
f9903ed0 2040
7cf1c7bd 2041/**
0d0a8bf6 2042 * Returns a formatted string that represents a date in user time
2043 *
7cf1c7bd 2044 * Returns a formatted string that represents a date in user time
2045 * <b>WARNING: note that the format is for strftime(), not date().</b>
2046 * Because of a bug in most Windows time libraries, we can't use
2047 * the nicer %e, so we have to use %d which has leading zeroes.
2048 * A lot of the fuss in the function is just getting rid of these leading
2049 * zeroes as efficiently as possible.
361855e6 2050 *
8c3dba73 2051 * If parameter fixday = true (default), then take off leading
efb8c375 2052 * zero from %d, else maintain it.
7cf1c7bd 2053 *
9df12115
RT
2054 * @package core
2055 * @category time
0a0cf09a 2056 * @param int $date the timestamp in UTC, as obtained from the database.
2057 * @param string $format strftime format. You should probably get this using
9df12115
RT
2058 * get_string('strftime...', 'langconfig');
2059 * @param int|float|string $timezone by default, uses the user's time zone. if numeric and
2060 * not 99 then daylight saving will not be added.
2061 * {@link http://docs.moodle.org/dev/Time_API#Timezone}
0a0cf09a 2062 * @param bool $fixday If true (default) then the leading zero from %d is removed.
9df12115 2063 * If false then the leading zero is maintained.
d9498b38 2064 * @param bool $fixhour If true (default) then the leading zero from %I is removed.
0a0cf09a 2065 * @return string the formatted date/time.
7cf1c7bd 2066 */
d9498b38 2067function userdate($date, $format = '', $timezone = 99, $fixday = true, $fixhour = true) {
7a302afc 2068
1ac7ee24 2069 global $CFG;
2070
1306c5ea 2071 if (empty($format)) {
0a0cf09a 2072 $format = get_string('strftimedaydatetime', 'langconfig');
5fa51a39 2073 }
035cdbff 2074
c3a3c5b8 2075 if (!empty($CFG->nofixday)) { // Config.php can force %d not to be fixed.
2076 $fixday = false;
2077 } else if ($fixday) {
2078 $formatnoday = str_replace('%d', 'DD', $format);
61ae5d36 2079 $fixday = ($formatnoday != $format);
d9498b38 2080 $format = $formatnoday;
2081 }
2082
2083 // Note: This logic about fixing 12-hour time to remove unnecessary leading
2084 // zero is required because on Windows, PHP strftime function does not
2085 // support the correct 'hour without leading zero' parameter (%l).
2086 if (!empty($CFG->nofixhour)) {
2087 // Config.php can force %I not to be fixed.
2088 $fixhour = false;
2089 } else if ($fixhour) {
2090 $formatnohour = str_replace('%I', 'HH', $format);
2091 $fixhour = ($formatnohour != $format);
2092 $format = $formatnohour;
61ae5d36 2093 }
dcde9f02 2094
6a0bf5c4
RT
2095 //add daylight saving offset for string timezones only, as we can't get dst for
2096 //float values. if timezone is 99 (user default timezone), then try update dst.
2097 if ((99 == $timezone) || !is_numeric($timezone)) {
2098 $date += dst_offset_on($date, $timezone);
2099 }
85351042 2100
494b9296 2101 $timezone = get_user_timezone_offset($timezone);
102dc313 2102
63d59875
PS
2103 // If we are running under Windows convert to windows encoding and then back to UTF-8
2104 // (because it's impossible to specify UTF-8 to fetch locale info in Win32)
2105
102dc313 2106 if (abs($timezone) > 13) { /// Server time
15396bba 2107 $datestring = date_format_string($date, $format, $timezone);
d2a9f7cc 2108 if ($fixday) {
35f7287f 2109 $daystring = ltrim(str_replace(array(' 0', ' '), '', strftime(' %d', $date)));
102dc313 2110 $datestring = str_replace('DD', $daystring, $datestring);
d9498b38 2111 }
2112 if ($fixhour) {
2113 $hourstring = ltrim(str_replace(array(' 0', ' '), '', strftime(' %I', $date)));
2114 $datestring = str_replace('HH', $hourstring, $datestring);
102dc313 2115 }
63d59875 2116
88ec5b7c 2117 } else {
102dc313 2118 $date += (int)($timezone * 3600);
15396bba 2119 $datestring = date_format_string($date, $format, $timezone);
102dc313 2120 if ($fixday) {
35f7287f 2121 $daystring = ltrim(str_replace(array(' 0', ' '), '', gmstrftime(' %d', $date)));
102dc313 2122 $datestring = str_replace('DD', $daystring, $datestring);
d9498b38 2123 }
2124 if ($fixhour) {
2125 $hourstring = ltrim(str_replace(array(' 0', ' '), '', gmstrftime(' %I', $date)));
2126 $datestring = str_replace('HH', $hourstring, $datestring);
102dc313 2127 }
88ec5b7c 2128 }
102dc313 2129
035cdbff 2130 return $datestring;
873960de 2131}
2132
15396bba
FM
2133/**
2134 * Returns a formatted date ensuring it is UTF-8.
2135 *
2136 * If we are running under Windows convert to Windows encoding and then back to UTF-8
2137 * (because it's impossible to specify UTF-8 to fetch locale info in Win32).
2138 *
2139 * This function does not do any calculation regarding the user preferences and should
2140 * therefore receive the final date timestamp, format and timezone. Timezone being only used
2141 * to differenciate the use of server time or not (strftime() against gmstrftime()).
2142 *
2143 * @param int $date the timestamp.
2144 * @param string $format strftime format.
2145 * @param int|float $timezone the numerical timezone, typically returned by {@link get_user_timezone_offset()}.
2146 * @return string the formatted date/time.
2147 * @since 2.3.3
2148 */
2149function date_format_string($date, $format, $tz = 99) {
2150 global $CFG;
2151 if (abs($tz) > 13) {
73d20f36 2152 if ($CFG->ostype == 'WINDOWS' and $localewincharset = get_string('localewincharset', 'langconfig')) {
15396bba
FM
2153 $format = textlib::convert($format, 'utf-8', $localewincharset);
2154 $datestring = strftime($format, $date);
2155 $datestring = textlib::convert($datestring, $localewincharset, 'utf-8');
2156 } else {
2157 $datestring = strftime($format, $date);
2158 }
2159 } else {
73d20f36 2160 if ($CFG->ostype == 'WINDOWS' and $localewincharset = get_string('localewincharset', 'langconfig')) {
15396bba
FM
2161 $format = textlib::convert($format, 'utf-8', $localewincharset);
2162 $datestring = gmstrftime($format, $date);
2163 $datestring = textlib::convert($datestring, $localewincharset, 'utf-8');
2164 } else {
2165 $datestring = gmstrftime($format, $date);
2166 }
2167 }
2168 return $datestring;
2169}
2170
7cf1c7bd 2171/**
196f2619 2172 * Given a $time timestamp in GMT (seconds since epoch),
c6d15803 2173 * returns an array that represents the date in user time
7cf1c7bd 2174 *
9df12115
RT
2175 * @package core
2176 * @category time
2f87145b 2177 * @uses HOURSECS
196f2619 2178 * @param int $time Timestamp in GMT
9df12115
RT
2179 * @param float|int|string $timezone offset's time with timezone, if float and not 99, then no
2180 * dst offset is applyed {@link http://docs.moodle.org/dev/Time_API#Timezone}
c6d15803 2181 * @return array An array that represents the date in user time
7cf1c7bd 2182 */
196f2619 2183function usergetdate($time, $timezone=99) {
6b174680 2184
6a0bf5c4
RT
2185 //save input timezone, required for dst offset check.
2186 $passedtimezone = $timezone;
94c82430 2187
494b9296 2188 $timezone = get_user_timezone_offset($timezone);
a36166d3 2189
e34d817e 2190 if (abs($timezone) > 13) { // Server time
ed1f69b0 2191 return getdate($time);
d2a9f7cc 2192 }
2193
6a0bf5c4
RT
2194 //add daylight saving offset for string timezones only, as we can't get dst for
2195 //float values. if timezone is 99 (user default timezone), then try update dst.
2196 if ($passedtimezone == 99 || !is_numeric($passedtimezone)) {
2197 $time += dst_offset_on($time, $passedtimezone);
2198 }
2199
e34d817e 2200 $time += intval((float)$timezone * HOURSECS);
3bba1e6e 2201
24d38a6e 2202 $datestring = gmstrftime('%B_%A_%j_%Y_%m_%w_%d_%H_%M_%S', $time);
02f0527d 2203
24d38a6e 2204 //be careful to ensure the returned array matches that produced by getdate() above
9f1f6daf 2205 list(
24d38a6e
AD
2206 $getdate['month'],
2207 $getdate['weekday'],
2208 $getdate['yday'],
9f1f6daf 2209 $getdate['year'],
24d38a6e 2210 $getdate['mon'],
9f1f6daf 2211 $getdate['wday'],
24d38a6e
AD
2212 $getdate['mday'],
2213 $getdate['hours'],
2214 $getdate['minutes'],
2215 $getdate['seconds']
3bba1e6e 2216 ) = explode('_', $datestring);
9f1f6daf 2217
4a9c429b
RT
2218 // set correct datatype to match with getdate()
2219 $getdate['seconds'] = (int)$getdate['seconds'];
2220 $getdate['yday'] = (int)$getdate['yday'] - 1; // gettime returns 0 through 365
2221 $getdate['year'] = (int)$getdate['year'];
2222 $getdate['mon'] = (int)$getdate['mon'];
2223 $getdate['wday'] = (int)$getdate['wday'];
2224 $getdate['mday'] = (int)$getdate['mday'];
2225 $getdate['hours'] = (int)$getdate['hours'];
2226 $getdate['minutes'] = (int)$getdate['minutes'];
d2d6171f 2227 return $getdate;
d552ead0 2228}
2229
7cf1c7bd 2230/**
2231 * Given a GMT timestamp (seconds since epoch), offsets it by
2232 * the timezone. eg 3pm in India is 3pm GMT - 7 * 3600 seconds
2233 *
9df12115
RT
2234 * @package core
2235 * @category time
2f87145b 2236 * @uses HOURSECS
9df12115
RT
2237 * @param int $date Timestamp in GMT
2238 * @param float|int|string $timezone timezone to calculate GMT time offset before
2239 * calculating user time, 99 is default user timezone
2240 * {@link http://docs.moodle.org/dev/Time_API#Timezone}
c6d15803 2241 * @return int
7cf1c7bd 2242 */
d552ead0 2243function usertime($date, $timezone=99) {
a36166d3 2244
494b9296 2245 $timezone = get_user_timezone_offset($timezone);
2665e47a 2246
0431bd7c 2247 if (abs($timezone) > 13) {
d552ead0 2248 return $date;
2249 }
7a5672c9 2250 return $date - (int)($timezone * HOURSECS);
d552ead0 2251}
2252
8c3dba73 2253/**
2254 * Given a time, return the GMT timestamp of the most recent midnight
2255 * for the current user.
2256 *
9df12115
RT
2257 * @package core
2258 * @category time
e34d817e 2259 * @param int $date Timestamp in GMT
9df12115
RT
2260 * @param float|int|string $timezone timezone to calculate GMT time offset before
2261 * calculating user midnight time, 99 is default user timezone
2262 * {@link http://docs.moodle.org/dev/Time_API#Timezone}
0d0a8bf6 2263 * @return int Returns a GMT timestamp
8c3dba73 2264 */
edf7fe8c 2265function usergetmidnight($date, $timezone=99) {
edf7fe8c 2266
edf7fe8c 2267 $userdate = usergetdate($date, $timezone);
4606d9bb 2268
02f0527d 2269 // Time of midnight of this user's day, in GMT
2270 return make_timestamp($userdate['year'], $userdate['mon'], $userdate['mday'], 0, 0, 0, $timezone);
edf7fe8c 2271
2272}
2273
7cf1c7bd 2274/**
2275 * Returns a string that prints the user's timezone
2276 *
9df12115
RT
2277 * @package core
2278 * @category time
2279 * @param float|int|string $timezone timezone to calculate GMT time offset before
2280 * calculating user timezone, 99 is default user timezone
2281 * {@link http://docs.moodle.org/dev/Time_API#Timezone}
7cf1c7bd 2282 * @return string
2283 */
d552ead0 2284function usertimezone($timezone=99) {
d552ead0 2285
0c244315 2286 $tz = get_user_timezone($timezone);
f30fe8d0 2287
0c244315 2288 if (!is_float($tz)) {
2289 return $tz;
d552ead0 2290 }
0c244315 2291
2292 if(abs($tz) > 13) { // Server time
2293 return get_string('serverlocaltime');
2294 }
2295
2296 if($tz == intval($tz)) {
2297 // Don't show .0 for whole hours
2298 $tz = intval($tz);
2299 }
2300
2301 if($tz == 0) {
61b420ac 2302 return 'UTC';
d552ead0 2303 }
0c244315 2304 else if($tz > 0) {
61b420ac 2305 return 'UTC+'.$tz;
0c244315 2306 }
2307 else {
61b420ac 2308 return 'UTC'.$tz;
d552ead0 2309 }
e1ecf0a0 2310
f9903ed0 2311}
2312
7cf1c7bd 2313/**
2314 * Returns a float which represents the user's timezone difference from GMT in hours
2315 * Checks various settings and picks the most dominant of those which have a value
2316 *
9df12115
RT
2317 * @package core
2318 * @category time
2319 * @param float|int|string $tz timezone to calculate GMT time offset for user,
2320 * 99 is default user timezone
2321 * {@link http://docs.moodle.org/dev/Time_API#Timezone}
0d0a8bf6 2322 * @return float
7cf1c7bd 2323 */
494b9296 2324function get_user_timezone_offset($tz = 99) {
f30fe8d0 2325
43b59916 2326 global $USER, $CFG;
2327
e8904995 2328 $tz = get_user_timezone($tz);
c9e55a25 2329
7b9e355e 2330 if (is_float($tz)) {
2331 return $tz;
2332 } else {
e8904995 2333 $tzrecord = get_timezone_record($tz);
7b9e355e 2334 if (empty($tzrecord)) {
e8904995 2335 return 99.0;
2336 }
4f2dbde9 2337 return (float)$tzrecord->gmtoff / HOURMINS;
e8904995 2338 }
2339}
2340
61460dd6 2341/**
2342 * Returns an int which represents the systems's timezone difference from GMT in seconds
0d0a8bf6 2343 *
9df12115
RT
2344 * @package core
2345 * @category time
2346 * @param float|int|string $tz timezone for which offset is required.
2347 * {@link http://docs.moodle.org/dev/Time_API#Timezone}
2348 * @return int|bool if found, false is timezone 99 or error
61460dd6 2349 */
2350function get_timezone_offset($tz) {
2351 global $CFG;
2352
2353 if ($tz == 99) {
2354 return false;
2355 }
2356
2357 if (is_numeric($tz)) {
2358 return intval($tz * 60*60);
2359 }
2360
2361 if (!$tzrecord = get_timezone_record($tz)) {
2362 return false;
2363 }
2364 return intval($tzrecord->gmtoff * 60);
2365}
2366
bbd3f2c4 2367/**
b2b68362 2368 * Returns a float or a string which denotes the user's timezone
2369 * 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)
2370 * means that for this timezone there are also DST rules to be taken into account
2371 * Checks various settings and picks the most dominant of those which have a value
bbd3f2c4 2372 *
9df12115
RT
2373 * @package core
2374 * @category time
2375 * @param float|int|string $tz timezone to calculate GMT time offset before
2376 * calculating user timezone, 99 is default user timezone
2377 * {@link http://docs.moodle.org/dev/Time_API#Timezone}
2378 * @return float|string
bbd3f2c4 2379 */
e8904995 2380function get_user_timezone($tz = 99) {
2381 global $USER, $CFG;
43b59916 2382
f30fe8d0 2383 $timezones = array(
e8904995 2384 $tz,
2385 isset($CFG->forcetimezone) ? $CFG->forcetimezone : 99,
43b59916 2386 isset($USER->timezone) ? $USER->timezone : 99,
2387 isset($CFG->timezone) ? $CFG->timezone : 99,
f30fe8d0 2388 );
43b59916 2389
e8904995 2390 $tz = 99;
43b59916 2391
4d91f735
FM
2392 // Loop while $tz is, empty but not zero, or 99, and there is another timezone is the array
2393 while(((empty($tz) && !is_numeric($tz)) || $tz == 99) && $next = each($timezones)) {
e8904995 2394 $tz = $next['value'];
43b59916 2395 }
e8904995 2396 return is_numeric($tz) ? (float) $tz : $tz;
43b59916 2397}
2398
bbd3f2c4 2399/**
f33e1ed4 2400 * Returns cached timezone record for given $timezonename
bbd3f2c4 2401 *
9df12115
RT
2402 * @package core
2403 * @param string $timezonename name of the timezone
2404 * @return stdClass|bool timezonerecord or false
bbd3f2c4 2405 */
43b59916 2406function get_timezone_record($timezonename) {
f33e1ed4 2407 global $CFG, $DB;
43b59916 2408 static $cache = NULL;
2409
8edffd15 2410 if ($cache === NULL) {
43b59916 2411 $cache = array();
2412 }
2413
8edffd15 2414 if (isset($cache[$timezonename])) {
43b59916 2415 return $cache[$timezonename];
f30fe8d0 2416 }
2417
f33e1ed4 2418 return $cache[$timezonename] = $DB->get_record_sql('SELECT * FROM {timezone}
daac3835 2419 WHERE name = ? ORDER BY year DESC', array($timezonename), IGNORE_MULTIPLE);
f30fe8d0 2420}
f9903ed0 2421
bbd3f2c4 2422/**
0d0a8bf6 2423 * Build and store the users Daylight Saving Time (DST) table
bbd3f2c4 2424 *
9df12115
RT
2425 * @package core
2426 * @param int $from_year Start year for the table, defaults to 1971
2427 * @param int $to_year End year for the table, defaults to 2035
2428 * @param int|float|string $strtimezone, timezone to check if dst should be applyed.
bbd3f2c4 2429 * @return bool
2430 */
94c82430 2431function calculate_user_dst_table($from_year = NULL, $to_year = NULL, $strtimezone = NULL) {
ae040d4b 2432 global $CFG, $SESSION, $DB;
85cafb3e 2433
33998d30 2434 $usertz = get_user_timezone($strtimezone);
7cb29a3d 2435
989585e9 2436 if (is_float($usertz)) {
2437 // Trivial timezone, no DST
2438 return false;
2439 }
2440
2280ecf5 2441 if (!empty($SESSION->dst_offsettz) && $SESSION->dst_offsettz != $usertz) {
989585e9 2442 // We have precalculated values, but the user's effective TZ has changed in the meantime, so reset
2280ecf5 2443 unset($SESSION->dst_offsets);
2444 unset($SESSION->dst_range);
830a2bbd 2445 }
2446
2280ecf5 2447 if (!empty($SESSION->dst_offsets) && empty($from_year) && empty($to_year)) {
830a2bbd 2448 // Repeat calls which do not request specific year ranges stop here, we have already calculated the table
2449 // This will be the return path most of the time, pretty light computationally
2450 return true;
85cafb3e 2451 }
2452
830a2bbd 2453 // Reaching here means we either need to extend our table or create it from scratch
989585e9 2454
2455 // Remember which TZ we calculated these changes for
2280ecf5 2456 $SESSION->dst_offsettz = $usertz;
989585e9 2457
2280ecf5 2458 if(empty($SESSION->dst_offsets)) {
830a2bbd 2459 // If we 're creating from scratch, put the two guard elements in there
2280ecf5 2460 $SESSION->dst_offsets = array(1 => NULL, 0 => NULL);
830a2bbd 2461 }
2280ecf5 2462 if(empty($SESSION->dst_range)) {
830a2bbd 2463 // If creating from scratch
2464 $from = max((empty($from_year) ? intval(date('Y')) - 3 : $from_year), 1971);
2465 $to = min((empty($to_year) ? intval(date('Y')) + 3 : $to_year), 2035);
2466
2467 // Fill in the array with the extra years we need to process
2468 $yearstoprocess = array();
2469 for($i = $from; $i <= $to; ++$i) {
2470 $yearstoprocess[] = $i;
2471 }
2472
2473 // Take note of which years we have processed for future calls
2280ecf5 2474 $SESSION->dst_range = array($from, $to);
830a2bbd 2475 }
2476 else {
2477 // If needing to extend the table, do the same
2478 $yearstoprocess = array();
2479
2280ecf5 2480 $from = max((empty($from_year) ? $SESSION->dst_range[0] : $from_year), 1971);
2481 $to = min((empty($to_year) ? $SESSION->dst_range[1] : $to_year), 2035);
830a2bbd 2482
2280ecf5 2483 if($from < $SESSION->dst_range[0]) {
830a2bbd 2484 // Take note of which years we need to process and then note that we have processed them for future calls
2280ecf5 2485 for($i = $from; $i < $SESSION->dst_range[0]; ++$i) {
830a2bbd 2486 $yearstoprocess[] = $i;
2487 }
2280ecf5 2488 $SESSION->dst_range[0] = $from;
830a2bbd 2489 }
2280ecf5 2490 if($to > $SESSION->dst_range[1]) {
830a2bbd 2491 // Take note of which years we need to process and then note that we have processed them for future calls
2280ecf5 2492 for($i = $SESSION->dst_range[1] + 1; $i <= $to; ++$i) {
830a2bbd 2493 $yearstoprocess[] = $i;
2494 }
2280ecf5 2495 $SESSION->dst_range[1] = $to;
830a2bbd 2496 }
2497 }
2498
2499 if(empty($yearstoprocess)) {
2500 // This means that there was a call requesting a SMALLER range than we have already calculated
2501 return true;
2502 }
2503
2504 // From now on, we know that the array has at least the two guard elements, and $yearstoprocess has the years we need
2505 // Also, the array is sorted in descending timestamp order!
2506
2507 // Get DB data
6a5dc27c 2508
2509 static $presets_cache = array();
2510 if (!isset($presets_cache[$usertz])) {
ae040d4b 2511 $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 2512 }
2513 if(empty($presets_cache[$usertz])) {
e789650d 2514 return false;
2515 }
57f1191c 2516
830a2bbd 2517 // Remove ending guard (first element of the array)
2280ecf5 2518 reset($SESSION->dst_offsets);
2519 unset($SESSION->dst_offsets[key($SESSION->dst_offsets)]);
830a2bbd 2520
2521 // Add all required change timestamps
2522 foreach($yearstoprocess as $y) {
2523 // Find the record which is in effect for the year $y
6a5dc27c 2524 foreach($presets_cache[$usertz] as $year => $preset) {
830a2bbd 2525 if($year <= $y) {
2526 break;
c9e72798 2527 }
830a2bbd 2528 }
2529
2530 $changes = dst_changes_for_year($y, $preset);
2531
2532 if($changes === NULL) {
2533 continue;
2534 }
2535 if($changes['dst'] != 0) {
2280ecf5 2536 $SESSION->dst_offsets[$changes['dst']] = $preset->dstoff * MINSECS;
830a2bbd 2537 }
2538 if($changes['std'] != 0) {
2280ecf5 2539 $SESSION->dst_offsets[$changes['std']] = 0;
c9e72798 2540 }
85cafb3e 2541 }
42d36497 2542
830a2bbd 2543 // Put in a guard element at the top
2280ecf5 2544 $maxtimestamp = max(array_keys($SESSION->dst_offsets));
2545 $SESSION->dst_offsets[($maxtimestamp + DAYSECS)] = NULL; // DAYSECS is arbitrary, any "small" number will do
830a2bbd 2546
2547 // Sort again
2280ecf5 2548 krsort($SESSION->dst_offsets);
830a2bbd 2549
e789650d 2550 return true;
2551}
42d36497 2552
0d0a8bf6 2553/**
2554 * Calculates the required DST change and returns a Timestamp Array
2555 *
9df12115
RT
2556 * @package core
2557 * @category time
0d0a8bf6 2558 * @uses HOURSECS
2559 * @uses MINSECS
9df12115 2560 * @param int|string $year Int or String Year to focus on
0d0a8bf6 2561 * @param object $timezone Instatiated Timezone object
9df12115 2562 * @return array|null Array dst=>xx, 0=>xx, std=>yy, 1=>yy or NULL
0d0a8bf6 2563 */
e789650d 2564function dst_changes_for_year($year, $timezone) {
7cb29a3d 2565
e789650d 2566 if($timezone->dst_startday == 0 && $timezone->dst_weekday == 0 && $timezone->std_startday == 0 && $timezone->std_weekday == 0) {
2567 return NULL;
42d36497 2568 }
7cb29a3d 2569
e789650d 2570 $monthdaydst = find_day_in_month($timezone->dst_startday, $timezone->dst_weekday, $timezone->dst_month, $year);
2571 $monthdaystd = find_day_in_month($timezone->std_startday, $timezone->std_weekday, $timezone->std_month, $year);
2572
2573 list($dst_hour, $dst_min) = explode(':', $timezone->dst_time);
2574 list($std_hour, $std_min) = explode(':', $timezone->std_time);
d2a9f7cc 2575
6dc8dddc 2576 $timedst = make_timestamp($year, $timezone->dst_month, $monthdaydst, 0, 0, 0, 99, false);
2577 $timestd = make_timestamp($year, $timezone->std_month, $monthdaystd, 0, 0, 0, 99, false);
830a2bbd 2578
2579 // Instead of putting hour and minute in make_timestamp(), we add them afterwards.
2580 // This has the advantage of being able to have negative values for hour, i.e. for timezones
2581 // where GMT time would be in the PREVIOUS day than the local one on which DST changes.
2582
2583 $timedst += $dst_hour * HOURSECS + $dst_min * MINSECS;
2584 $timestd += $std_hour * HOURSECS + $std_min * MINSECS;
42d36497 2585
e789650d 2586 return array('dst' => $timedst, 0 => $timedst, 'std' => $timestd, 1 => $timestd);
42d36497 2587}
2588
0d0a8bf6 2589/**
efb8c375 2590 * Calculates the Daylight Saving Offset for a given date/time (timestamp)
6a0bf5c4 2591 * - Note: Daylight saving only works for string timezones and not for float.
0d0a8bf6 2592 *
9df12115
RT
2593 * @package core
2594 * @category time
0d0a8bf6 2595 * @param int $time must NOT be compensated at all, it has to be a pure timestamp
9df12115
RT
2596 * @param int|float|string $strtimezone timezone for which offset is expected, if 99 or null
2597 * then user's default timezone is used. {@link http://docs.moodle.org/dev/Time_API#Timezone}
0d0a8bf6 2598 * @return int
2599 */
94c82430 2600function dst_offset_on($time, $strtimezone = NULL) {
2280ecf5 2601 global $SESSION;
02f0527d 2602
94c82430 2603 if(!calculate_user_dst_table(NULL, NULL, $strtimezone) || empty($SESSION->dst_offsets)) {
c9e72798 2604 return 0;
85cafb3e 2605 }
2606
2280ecf5 2607 reset($SESSION->dst_offsets);
2608 while(list($from, $offset) = each($SESSION->dst_offsets)) {
59556d48 2609 if($from <= $time) {
c9e72798 2610 break;
2611 }
2612 }
2613
830a2bbd 2614 // This is the normal return path
2615 if($offset !== NULL) {
2616 return $offset;
02f0527d 2617 }
02f0527d 2618
830a2bbd 2619 // Reaching this point means we haven't calculated far enough, do it now:
2620 // Calculate extra DST changes if needed and recurse. The recursion always
2621 // moves toward the stopping condition, so will always end.
2622
2623 if($from == 0) {
2280ecf5 2624 // We need a year smaller than $SESSION->dst_range[0]
2625 if($SESSION->dst_range[0] == 1971) {
830a2bbd 2626 return 0;
2627 }
94c82430 2628 calculate_user_dst_table($SESSION->dst_range[0] - 5, NULL, $strtimezone);
2629 return dst_offset_on($time, $strtimezone);
830a2bbd 2630 }
2631 else {
2280ecf5 2632 // We need a year larger than $SESSION->dst_range[1]
2633 if($SESSION->dst_range[1] == 2035) {
830a2bbd 2634 return 0;
2635 }
94c82430 2636 calculate_user_dst_table(NULL, $SESSION->dst_range[1] + 5, $strtimezone);
2637 return dst_offset_on($time, $strtimezone);
830a2bbd 2638 }
85cafb3e 2639}
02f0527d 2640
0d0a8bf6 2641/**
9df12115 2642 * Calculates when the day appears in specific month
0d0a8bf6 2643 *
9df12115
RT
2644 * @package core
2645 * @category time
2646 * @param int $startday starting day of the month
2647 * @param int $weekday The day when week starts (normally taken from user preferences)
2648 * @param int $month The month whose day is sought
2649 * @param int $year The year of the month whose day is sought
0d0a8bf6 2650 * @return int
2651 */
28902d99 2652function find_day_in_month($startday, $weekday, $month, $year) {
8dc3f6cf 2653
2654 $daysinmonth = days_in_month($month, $year);
2655
42d36497 2656 if($weekday == -1) {
28902d99 2657 // Don't care about weekday, so return:
2658 // abs($startday) if $startday != -1
2659 // $daysinmonth otherwise
2660 return ($startday == -1) ? $daysinmonth : abs($startday);
8dc3f6cf 2661 }
2662
2663 // From now on we 're looking for a specific weekday
8dc3f6cf 2664
28902d99 2665 // Give "end of month" its actual value, since we know it
2666 if($startday == -1) {
2667 $startday = -1 * $daysinmonth;
2668 }
2669
2670 // Starting from day $startday, the sign is the direction
8dc3f6cf 2671
28902d99 2672 if($startday < 1) {
8dc3f6cf 2673
28902d99 2674 $startday = abs($startday);
ef7af3dd 2675 $lastmonthweekday = strftime('%w', mktime(12, 0, 0, $month, $daysinmonth, $year));
8dc3f6cf 2676
2677 // This is the last such weekday of the month
2678 $lastinmonth = $daysinmonth + $weekday - $lastmonthweekday;
2679 if($lastinmonth > $daysinmonth) {
2680 $lastinmonth -= 7;
42d36497 2681 }
8dc3f6cf 2682
28902d99 2683 // Find the first such weekday <= $startday
2684 while($lastinmonth > $startday) {
8dc3f6cf 2685 $lastinmonth -= 7;
42d36497 2686 }
8dc3f6cf 2687
2688 return $lastinmonth;
e1ecf0a0 2689
42d36497 2690 }
2691 else {
42d36497 2692
ef7af3dd 2693 $indexweekday = strftime('%w', mktime(12, 0, 0, $month, $startday, $year));
42d36497 2694
8dc3f6cf 2695 $diff = $weekday - $indexweekday;
2696 if($diff < 0) {
2697 $diff += 7;
42d36497 2698 }
42d36497 2699
28902d99 2700 // This is the first such weekday of the month equal to or after $startday
2701 $firstfromindex = $startday + $diff;
42d36497 2702
8dc3f6cf 2703 return $firstfromindex;
2704
2705 }
42d36497 2706}
2707
bbd3f2c4 2708/**
2709 * Calculate the number of days in a given month
2710 *
9df12115
RT
2711 * @package core
2712 * @category time
bbd3f2c4 2713 * @param int $month The month whose day count is sought
2714 * @param int $year The year of the month whose day count is sought
2715 * @return int
2716 */
42d36497 2717function days_in_month($month, $year) {
ef7af3dd 2718 return intval(date('t', mktime(12, 0, 0, $month, 1, $year)));
42d36497 2719}
2720
bbd3f2c4 2721/**
2722 * Calculate the position in the week of a specific calendar day
2723 *
9df12115
RT
2724 * @package core
2725 * @category time
bbd3f2c4 2726 * @param int $day The day of the date whose position in the week is sought
2727 * @param int $month The month of the date whose position in the week is sought
2728 * @param int $year The year of the date whose position in the week is sought
2729 * @return int
2730 */
8dc3f6cf 2731function dayofweek($day, $month, $year) {
2732 // I wonder if this is any different from
2733 // strftime('%w', mktime(12, 0, 0, $month, $daysinmonth, $year, 0));
d7eeb39e 2734 return intval(date('w', mktime(12, 0, 0, $month, $day, $year)));
8dc3f6cf 2735}
2736
9fa49e22 2737/// USER AUTHENTICATION AND LOGIN ////////////////////////////////////////
f9903ed0 2738
93f66983 2739/**
2740 * Returns full login url.
2741 *
93f66983 2742 * @return string login url
2743 */
999b54af 2744function get_login_url() {
93f66983 2745 global $CFG;
2746
999b54af 2747 $url = "$CFG->wwwroot/login/index.php";
93f66983 2748
999b54af
PS
2749 if (!empty($CFG->loginhttps)) {
2750 $url = str_replace('http:', 'https:', $url);
93f66983 2751 }
2752
2753 return $url;
2754}
2755
7cf1c7bd 2756/**
ec81373f 2757 * This function checks that the current user is logged in and has the
2758 * required privileges
2759 *
7cf1c7bd 2760 * This function checks that the current user is logged in, and optionally
ec81373f 2761 * whether they are allowed to be in a particular course and view a particular
2762 * course module.
2763 * If they are not logged in, then it redirects them to the site login unless
d2a9f7cc 2764 * $autologinguest is set and {@link $CFG}->autologinguests is set to 1 in which
ec81373f 2765 * case they are automatically logged in as guests.
2766 * If $courseid is given and the user is not enrolled in that course then the
2767 * user is redirected to the course enrolment page.
efb8c375 2768 * If $cm is given and the course module is hidden and the user is not a teacher
ec81373f 2769 * in the course then the user is redirected to the course home page.
7cf1c7bd 2770 *
191b267b 2771 * When $cm parameter specified, this function sets page layout to 'module'.
4f0c2d00 2772 * You need to change it manually later if some other layout needed.
191b267b 2773 *
f76249cc
PS
2774 * @package core_access
2775 * @category access
2776 *
33ebaf7c 2777 * @param mixed $courseorid id of the course or course object
0d0a8bf6 2778 * @param bool $autologinguest default true
bbd3f2c4 2779 * @param object $cm course module object
f4013c10 2780 * @param bool $setwantsurltome Define if we want to set $SESSION->wantsurl, defaults to
2781 * true. Used to avoid (=false) some scripts (file.php...) to set that variable,
2782 * in order to keep redirects working properly. MDL-14495
df997f84 2783 * @param bool $preventredirect set to true in scripts that can not redirect (CLI, rss feeds, etc.), throws exceptions
0d0a8bf6 2784 * @return mixed Void, exit, and die depending on path
7cf1c7bd 2785 */
df997f84 2786function require_login($courseorid = NULL, $autologinguest = true, $cm = NULL, $setwantsurltome = true, $preventredirect = false) {
f0202ae9 2787 global $CFG, $SESSION, $USER, $PAGE, $SITE, $DB, $OUTPUT;
d8ba183c 2788
df997f84 2789 // setup global $COURSE, themes, language and locale
c13a5e71 2790 if (!empty($courseorid)) {
2791 if (is_object($courseorid)) {
2792 $course = $courseorid;
2793 } else if ($courseorid == SITEID) {
2794 $course = clone($SITE);
2795 } else {
df997f84 2796 $course = $DB->get_record('course', array('id' => $courseorid), '*', MUST_EXIST);
c13a5e71 2797 }
95d28870 2798 if ($cm) {
df997f84
PS
2799 if ($cm->course != $course->id) {
2800 throw new coding_exception('course and cm parameters in require_login() call do not match!!');
2801 }
0d8b6a69 2802 // make sure we have a $cm from get_fast_modinfo as this contains activity access details
47148151 2803 if (!($cm instanceof cm_info)) {
0d8b6a69 2804 // note: nearly all pages call get_fast_modinfo anyway and it does not make any
2805 // db queries so this is not really a performance concern, however it is obviously
2806 // better if you use get_fast_modinfo to get the cm before calling this.
2807 $modinfo = get_fast_modinfo($course);
2808 $cm = $modinfo->get_cm($cm->id);
2809 }
00dadbe1 2810 $PAGE->set_cm($cm, $course); // set's up global $COURSE
191b267b 2811 $PAGE->set_pagelayout('incourse');
95d28870 2812 } else {
00dadbe1 2813 $PAGE->set_course($course); // set's up global $COURSE
95d28870 2814 }
e88462a0 2815 } else {
df997f84
PS
2816 // do not touch global $COURSE via $PAGE->set_course(),
2817 // the reasons is we need to be able to call require_login() at any time!!
2818 $course = $SITE;
2819 if ($cm) {
2820 throw new coding_exception('cm parameter in require_login() requires valid course parameter!');
2821 }
c13a5e71 2822 }
be933850 2823
aa4a6566
SH
2824 // If this is an AJAX request and $setwantsurltome is true then we need to override it and set it to false.
2825 // Otherwise the AJAX request URL will be set to $SESSION->wantsurl and events such as self enrolment in the future
2826 // risk leading the user back to the AJAX request URL.
2827 if ($setwantsurltome && defined('AJAX_SCRIPT') && AJAX_SCRIPT) {
2828 $setwantsurltome = false;
2829 }
2830
12fc11e7 2831 // Redirect to the login page if session has expired, only with dbsessions enabled (MDL-35029) to maintain current behaviour.
8cd6d1aa 2832 if ((!isloggedin() or isguestuser()) && !empty($SESSION->has_timed_out) && !$preventredirect && !empty($CFG->dbsessions)) {
12fc11e7
DM
2833 if ($setwantsurltome) {
2834 $SESSION->wantsurl = qualified_me();
2835 }
2836 redirect(get_login_url());
2837 }
2838
df997f84 2839 // If the user is not even logged in yet then make sure they are
083c3743 2840 if (!isloggedin()) {
df997f84 2841 if ($autologinguest and !empty($CFG->guestloginbutton) and !empty($CFG->autologinguests)) {
999b54af
PS
2842 if (!$guest = get_complete_user_data('id', $CFG->siteguest)) {
2843 // misconfigured site guest, just redirect to login page
2844 redirect(get_login_url());
2845 exit; // never reached
df997f84 2846 }
999b54af 2847 $lang = isset($SESSION->lang) ? $SESSION->lang : $CFG->lang;
0342fc36 2848 complete_user_login($guest);
d9e07264 2849 $USER->autologinguest = true;
999b54af 2850 $SESSION->lang = $lang;
8a33e371 2851 } else {
999b54af
PS
2852 //NOTE: $USER->site check was obsoleted by session test cookie,
2853 // $USER->confirmed test is in login/index.php
2854 if ($preventredirect) {
2855 throw new require_login_exception('You are not logged in');
2856 }
2857
2858 if ($setwantsurltome) {
f0202ae9 2859 $SESSION->wantsurl = qualified_me();
999b54af
PS
2860 }
2861 if (!empty($_SERVER['HTTP_REFERER'])) {
2862 $SESSION->fromurl = $_SERVER['HTTP_REFERER'];
2863 }
2864 redirect(get_login_url());
2865 exit; // never reached
8a33e371 2866 }
f9903ed0 2867 }
808a3baa 2868
df997f84
PS
2869 // loginas as redirection if needed
2870 if ($course->id != SITEID and session_is_loggedinas()) {
f6f66b03 2871 if ($USER->loginascontext->contextlevel == CONTEXT_COURSE) {
df997f84 2872 if ($USER->loginascontext->instanceid != $course->id) {
3887fe4a 2873 print_error('loginasonecourse', '', $CFG->wwwroot.'/course/view.php?id='.$USER->loginascontext->instanceid);
5e623a33 2874 }
f6f66b03 2875 }
2876 }
2877
df997f84 2878 // check whether the user should be changing password (but only if it is REALLY them)
b7b64ff2 2879 if (get_user_preferences('auth_forcepasswordchange') && !session_is_loggedinas()) {
21e2dcd9 2880 $userauth = get_auth_plugin($USER->auth);
df997f84 2881 if ($userauth->can_change_password() and !$preventredirect) {
af572078 2882 if ($setwantsurltome) {
f0202ae9 2883 $SESSION->wantsurl = qualified_me();
af572078 2884 }
80274abf 2885 if ($changeurl = $userauth->change_password_url()) {
9696bd89 2886 //use plugin custom url
80274abf 2887 redirect($changeurl);
1437f0a5 2888 } else {
9696bd89 2889 //use moodle internal method
2890 if (empty($CFG->loginhttps)) {
2891 redirect($CFG->wwwroot .'/login/change_password.php');
2892 } else {
2893 $wwwroot = str_replace('http:','https:', $CFG->wwwroot);
2894 redirect($wwwroot .'/login/change_password.php');
2895 }
1437f0a5 2896 }
d35757eb 2897 } else {
a8ee7194 2898 print_error('nopasswordchangeforced', 'auth');
d35757eb 2899 }
2900 }
083c3743 2901
df997f84 2902 // Check that the user account is properly set up
808a3baa 2903 if (user_not_fully_set_up($USER)) {
df997f84
PS
2904 if ($preventredirect) {
2905 throw new require_login_exception('User not fully set-up');
2906 }
af572078 2907 if ($setwantsurltome) {
f0202ae9 2908 $SESSION->wantsurl = qualified_me();
af572078 2909 }
b0ccd3fb 2910 redirect($CFG->wwwroot .'/user/edit.php?id='. $USER->id .'&amp;course='. SITEID);
808a3baa 2911 }
d8ba183c 2912
df997f84 2913 // Make sure the USER has a sesskey set up. Used for CSRF protection.
04280e85 2914 sesskey();
366dfa60 2915
1560760f 2916 // Do not bother admins with any formalities
df997f84 2917 if (is_siteadmin()) {
1560760f
AD
2918 //set accesstime or the user will appear offline which messes up messaging
2919 user_accesstime_log($course->id);
df997f84
PS
2920 return;
2921 }
2922
b593d49d
PS
2923 // Check that the user has agreed to a site policy if there is one - do not test in case of admins
2924 if (!$USER->policyagreed and !is_siteadmin()) {
2925 if (!empty($CFG->sitepolicy) and !isguestuser()) {
2926 if ($preventredirect) {
2927 throw new require_login_exception('Policy not agreed');
2928 }
af572078 2929 if ($setwantsurltome) {
f0202ae9 2930 $SESSION->wantsurl = qualified_me();
af572078 2931 }
b593d49d
PS
2932 redirect($CFG->wwwroot .'/user/policy.php');
2933 } else if (!empty($CFG->sitepolicyguest) and isguestuser()) {
2934 if ($preventredirect) {
2935 throw new require_login_exception('Policy not agreed');
2936 }
af572078 2937 if ($setwantsurltome) {
f0202ae9 2938 $SESSION->wantsurl = qualified_me();
af572078 2939 }
027a1604 2940 redirect($CFG->wwwroot .'/user/policy.php');
027a1604 2941 }
1695b680 2942 }
2943
df997f84 2944 // Fetch the system context, the course context, and prefetch its child contexts
b0c6dc1c
AG
2945 $sysctx = context_system::instance();
2946 $coursecontext = context_course::instance($course->id, MUST_EXIST);
df997f84 2947 if ($cm) {
b0c6dc1c 2948 $cmcontext = context_module::instance($cm->id, MUST_EXIST);
df997f84
PS
2949 } else {
2950 $cmcontext = null;
2951 }
21e2dcd9 2952
df997f84 2953 // If the site is currently under maintenance, then print a message
4fe2250a 2954 if (!empty($CFG->maintenance_enabled) and !has_capability('moodle/site:config', $sysctx)) {
df997f84
PS
2955 if ($preventredirect) {
2956 throw new require_login_exception('Maintenance in progress');
2957 }
2958
4fe2250a 2959 print_maintenance_message();
027a1604 2960 }
2961
df997f84
PS
2962 // make sure the course itself is not hidden
2963 if ($course->id == SITEID) {
2964 // frontpage can not be hidden
2965 } else {
f5c1e621 2966 if (is_role_switched($course->id)) {
df997f84
PS
2967 // when switching roles ignore the hidden flag - user had to be in course to do the switch
2968 } else {
2969 if (!$course->visible and !has_capability('moodle/course:viewhiddencourses', $coursecontext)) {
2970 // originally there was also test of parent category visibility,
2971 // BUT is was very slow in complex queries involving "my courses"
2972 // now it is also possible to simply hide all courses user is not enrolled in :-)
2973 if ($preventredirect) {
2974 throw new require_login_exception('Course is hidden');
2975 }
a0a39b0d
SH
2976 // We need to override the navigation URL as the course won't have
2977 // been added to the navigation and thus the navigation will mess up
2978 // when trying to find it.
2979 navigation_node::override_active_url(new moodle_url('/'));
df997f84
PS
2980 notice(get_string('coursehidden'), $CFG->wwwroot .'/');
2981 }
2982 }
2983 }
2984
2985 // is the user enrolled?
2986 if ($course->id == SITEID) {
2987 // everybody is enrolled on the frontpage
2988
2989 } else {
2990 if (session_is_loggedinas()) {
2991 // Make sure the REAL person can access this course first
2992 $realuser = session_get_realuser();
2993 if (!is_enrolled($coursecontext, $realuser->id, '', true) and !is_viewing($coursecontext, $realuser->id) and !is_siteadmin($realuser->id)) {
2994 if ($preventredirect) {
2995 throw new require_login_exception('Invalid course login-as access');
2996 }
2997 echo $OUTPUT->header();
2998 notice(get_string('studentnotallowed', '', fullname($USER, true)), $CFG->wwwroot .'/');
2999 }
3000 }
3001
df997f84
PS
3002 $access = false;
3003
dbd7282c
PS
3004 if (is_role_switched($course->id)) {
3005 // ok, user had to be inside this course before the switch
3006 $access = true;
3007
3008 } else if (is_viewing($coursecontext, $USER)) {
df997f84
PS
3009 // ok, no need to mess with enrol
3010 $access = true;
3011
3012 } else {
3013 if (isset($USER->enrol['enrolled'][$course->id])) {
bbfdff34 3014 if ($USER->enrol['enrolled'][$course->id] > time()) {
df997f84 3015 $access = true;
bbfdff34
PS
3016 if (isset($USER->enrol['tempguest'][$course->id])) {
3017 unset($USER->enrol['tempguest'][$course->id]);
3018 remove_temp_course_roles($coursecontext);
3019 }
df997f84
PS
3020 } else {
3021 //expired
3022 unset($USER->enrol['enrolled'][$course->id]);
3023 }
3024 }
3025 if (isset($USER->enrol['tempguest'][$course->id])) {
3026 if ($USER->enrol['tempguest'][$course->id] == 0) {
3027 $access = true;
3028 } else if ($USER->enrol['tempguest'][$course->id] > time()) {
3029 $access = true;
3030 } else {
3031 //expired
3032 unset($USER->enrol['tempguest'][$course->id]);
e922fe23 3033 remove_temp_course_roles($coursecontext);
df997f84
PS
3034 }
3035 }
3036
3037 if ($access) {
3038 // cache ok
df997f84 3039 } else {
bbfdff34
PS
3040 $until = enrol_get_enrolment_end($coursecontext->instanceid, $USER->id);
3041 if ($until !== false) {
3042 // active participants may always access, a timestamp in the future, 0 (always) or false.
3043 if ($until == 0) {
3044 $until = ENROL_MAX_TIMESTAMP;
df997f84 3045 }
bbfdff34
PS
3046 $USER->enrol['enrolled'][$course->id] = $until;
3047 $access = true;
3048
3049 } else {
3050 $instances = $DB->get_records('enrol', array('courseid'=>$course->id, 'status'=>ENROL_INSTANCE_ENABLED), 'sortorder, id ASC');
3051 $enrols = enrol_get_plugins(true);
3052 // first ask all enabled enrol instances in course if they want to auto enrol user
df997f84
PS
3053 foreach($instances as $instance) {
3054 if (!isset($enrols[$instance->enrol])) {
3055 continue;
3056 }
bbfdff34
PS
3057 // Get a duration for the enrolment, a timestamp in the future, 0 (always) or false.
3058 $until = $enrols[$instance->enrol]->try_autoenrol($instance);
df997f84 3059 if ($until !== false) {
bbfdff34
PS
3060 if ($until == 0) {
3061 $until = ENROL_MAX_TIMESTAMP;
3062 }
3063 $USER->enrol['enrolled'][$course->id] = $until;
df997f84
PS
3064 $access = true;
3065 break;
3066 }
3067 }
bbfdff34
PS
3068 // if not enrolled yet try to gain temporary guest access
3069 if (!$access) {
3070 foreach($instances as $instance) {
3071 if (!isset($enrols[$instance->enrol])) {
3072 continue;
3073 }
3074 // Get a duration for the guest access, a timestamp in the future or false.
3075 $until = $enrols[$instance->enrol]->try_guestaccess($instance);
3076 if ($until !== false and $until > time()) {
3077 $USER->enrol['tempguest'][$course->id] = $until;
3078 $access = true;
3079 break;
3080 }
3081 }
3082 }
df997f84
PS
3083 }
3084 }
3085 }
3086
3087 if (!$access) {
3088 if ($preventredirect) {
3089 throw new require_login_exception('Not enrolled');
3090 }
af572078 3091 if ($setwantsurltome) {
f0202ae9 3092 $SESSION->wantsurl = qualified_me();
af572078 3093 }
df997f84
PS
3094 redirect($CFG->wwwroot .'/enrol/index.php?id='. $course->id);
3095 }
3096 }
3097
0d8b6a69 3098 // Check visibility of activity to current user; includes visible flag, groupmembersonly,
3099 // conditional availability, etc
3100 if ($cm && !$cm->uservisible) {
df997f84
PS
3101 if ($preventredirect) {
3102 throw new require_login_exception('Activity is hidden');
3103 }
ee17c773
PS
3104 if ($course->id != SITEID) {
3105 $url = new moodle_url('/course/view.php', array('id'=>$course->id));
3106 } else {
3107 $url = new moodle_url('/');
3108 }
3109 redirect($url, get_string('activityiscurrentlyhidden'));
df997f84
PS
3110 }
3111
df997f84
PS
3112 // Finally access granted, update lastaccess times
3113 user_accesstime_log($course->id);
f9903ed0 3114}
3115
c4d0753b 3116
c4d0753b 3117/**
3118 * This function just makes sure a user is logged out.
3119 *
f76249cc 3120 * @package core_access
c4d0753b 3121 */
3122function require_logout() {
dd9e22f8 3123 global $USER;
c4d0753b 3124
a8e3b008
DC
3125 $params = $USER;
3126
111e2360 3127 if (isloggedin()) {
c4d0753b 3128 add_to_log(SITEID, "user", "logout", "view.php?id=$USER->id&course=".SITEID, $USER->id, 0, $USER->id);
3129
533f7910 3130 $authsequence = get_enabled_auth_plugins(); // auths, in sequence
3131 foreach($authsequence as $authname) {
3132 $authplugin = get_auth_plugin($authname);
3133 $authplugin->prelogout_hook();
81693ac7 3134 }
c4d0753b 3135 }
3136
a8e3b008 3137 events_trigger('user_logout', $params);
56949c17 3138 session_get_instance()->terminate_current();
a8e3b008 3139 unset($params);
c4d0753b 3140}
3141
7cf1c7bd 3142/**
0d0a8bf6 3143 * Weaker version of require_login()
3144 *
7cf1c7bd 3145 * This is a weaker version of {@link require_login()} which only requires login
3146 * when called from within a course rather than the site page, unless
3147 * the forcelogin option is turned on.
0d0a8bf6 3148 * @see require_login()
7cf1c7bd 3149 *
f76249cc
PS
3150 * @package core_access
3151 * @category access
3152 *
33ebaf7c 3153 * @param mixed $courseorid The course object or id in question
bbd3f2c4 3154 * @param bool $autologinguest Allow autologin guests if that is wanted
4febb58f 3155 * @param object $cm Course activity module if known
f4013c10 3156 * @param bool $setwantsurltome Define if we want to set $SESSION->wantsurl, defaults to
3157 * true. Used to avoid (=false) some scripts (file.php...) to set that variable,
3158 * in order to keep redirects working properly. MDL-14495
df997f84
PS
3159 * @param bool $preventredirect set to true in scripts that can not redirect (CLI, rss feeds, etc.), throws exceptions
3160 * @return void
7cf1c7bd 3161 */
df997f84 3162function require_course_login($courseorid, $autologinguest = true, $cm = NULL, $setwantsurltome = true, $preventredirect = false) {
862940c0 3163 global $CFG, $PAGE, $SITE;
0d8b6a69 3164 $issite = (is_object($courseorid) and $courseorid->id == SITEID)
3165 or (!is_object($courseorid) and $courseorid == SITEID);
d4fb0e26 3166 if ($issite && !empty($cm) && !($cm instanceof cm_info)) {