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