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