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