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