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