MDL-24060 Need a way to control whether html_to_text lists all links in the HTML
[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
c426ef3a
PS
1082 // make sure cache dir is writable, throws exception if not
1083 make_upload_directory('cache');
f87eab7e
PS
1084
1085 clearstatcache();
1086}
1087
bafd7e78 1088/**
1089 * Get volatile flags
1090 *
1091 * @param string $type
0d0a8bf6 1092 * @param int $changedsince default null
bafd7e78 1093 * @return records array
bafd7e78 1094 */
1095function get_cache_flags($type, $changedsince=NULL) {
ae040d4b 1096 global $DB;
bafd7e78 1097
ae040d4b 1098 $params = array('type'=>$type, 'expiry'=>time());
1099 $sqlwhere = "flagtype = :type AND expiry >= :expiry";
bafd7e78 1100 if ($changedsince !== NULL) {
ae040d4b 1101 $params['changedsince'] = $changedsince;
1102 $sqlwhere .= " AND timemodified > :changedsince";
bafd7e78 1103 }
1104 $cf = array();
ae040d4b 1105
1106 if ($flags = $DB->get_records_select('cache_flags', $sqlwhere, $params, '', 'name,value')) {
bafd7e78 1107 foreach ($flags as $flag) {
1108 $cf[$flag->name] = $flag->value;
1109 }
1110 }
1111 return $cf;
1112}
1113
a489cf72 1114/**
1115 * Get volatile flags
1116 *
1117 * @param string $type
1118 * @param string $name
0d0a8bf6 1119 * @param int $changedsince default null
a489cf72 1120 * @return records array
a489cf72 1121 */
1122function get_cache_flag($type, $name, $changedsince=NULL) {
ae040d4b 1123 global $DB;
a489cf72 1124
ae040d4b 1125 $params = array('type'=>$type, 'name'=>$name, 'expiry'=>time());
a489cf72 1126
ae040d4b 1127 $sqlwhere = "flagtype = :type AND name = :name AND expiry >= :expiry";
a489cf72 1128 if ($changedsince !== NULL) {
ae040d4b 1129 $params['changedsince'] = $changedsince;
1130 $sqlwhere .= " AND timemodified > :changedsince";
a489cf72 1131 }
ae040d4b 1132
1133 return $DB->get_field_select('cache_flags', 'value', $sqlwhere, $params);
a489cf72 1134}
bafd7e78 1135
1136/**
1137 * Set a volatile flag
1138 *
1139 * @param string $type the "type" namespace for the key
1140 * @param string $name the key to set
1141 * @param string $value the value to set (without magic quotes) - NULL will remove the flag
1142 * @param int $expiry (optional) epoch indicating expiry - defaults to now()+ 24hs
0d0a8bf6 1143 * @return bool Always returns true
bafd7e78 1144 */
1145function set_cache_flag($type, $name, $value, $expiry=NULL) {
ae040d4b 1146 global $DB;
bafd7e78 1147
1148 $timemodified = time();
1149 if ($expiry===NULL || $expiry < $timemodified) {
1150 $expiry = $timemodified + 24 * 60 * 60;
1151 } else {
1152 $expiry = (int)$expiry;
1153 }
1154
1155 if ($value === NULL) {
013376de 1156 unset_cache_flag($type,$name);
1157 return true;
bafd7e78 1158 }
1159
6c7f5374 1160 if ($f = $DB->get_record('cache_flags', array('name'=>$name, 'flagtype'=>$type), '*', IGNORE_MULTIPLE)) { // this is a potentail problem in DEBUG_DEVELOPER
128f0984 1161 if ($f->value == $value and $f->expiry == $expiry and $f->timemodified == $timemodified) {
1162 return true; //no need to update; helps rcache too
1163 }
ae040d4b 1164 $f->value = $value;
bafd7e78 1165 $f->expiry = $expiry;
1166 $f->timemodified = $timemodified;
013376de 1167 $DB->update_record('cache_flags', $f);
bafd7e78 1168 } else {
128f0984 1169 $f = new object();
bafd7e78 1170 $f->flagtype = $type;
1171 $f->name = $name;
ae040d4b 1172 $f->value = $value;
bafd7e78 1173 $f->expiry = $expiry;
1174 $f->timemodified = $timemodified;
013376de 1175 $DB->insert_record('cache_flags', $f);
bafd7e78 1176 }
013376de 1177 return true;
bafd7e78 1178}
1179
1180/**
1181 * Removes a single volatile flag
1182 *
0d0a8bf6 1183 * @global object
bafd7e78 1184 * @param string $type the "type" namespace for the key
1185 * @param string $name the key to set
bafd7e78 1186 * @return bool
1187 */
1188function unset_cache_flag($type, $name) {
ae040d4b 1189 global $DB;
013376de 1190 $DB->delete_records('cache_flags', array('name'=>$name, 'flagtype'=>$type));
1191 return true;
bafd7e78 1192}
1193
1194/**
1195 * Garbage-collect volatile flags
1196 *
0d0a8bf6 1197 * @return bool Always returns true
bafd7e78 1198 */
1199function gc_cache_flags() {
ae040d4b 1200 global $DB;
013376de 1201 $DB->delete_records_select('cache_flags', 'expiry < ?', array(time()));
1202 return true;
bafd7e78 1203}
a4080313 1204
2660377f 1205/// FUNCTIONS FOR HANDLING USER PREFERENCES ////////////////////////////////////
1206
7cf1c7bd 1207/**
1208 * Refresh current $USER session global variable with all their current preferences.
0d0a8bf6 1209 *
1210 * @global object
1211 * @param mixed $time default null
1212 * @return void
7cf1c7bd 1213 */
2660377f 1214function check_user_preferences_loaded($time = null) {
ae040d4b 1215 global $USER, $DB;
2660377f 1216 static $timenow = null; // Static cache, so we only check up-to-dateness once per request.
1217
2e3adc25 1218 if (!empty($USER->preference) && isset($USER->preference['_lastloaded'])) {
2660377f 1219 // Already loaded. Are we up to date?
1220
1221 if (is_null($timenow) || (!is_null($time) && $time != $timenow)) {
1222 $timenow = time();
1223 if (!get_cache_flag('userpreferenceschanged', $USER->id, $USER->preference['_lastloaded'])) {
1224 // We are up-to-date.
1225 return;
1226 }
1227 } else {
1228 // Already checked for up-to-date-ness.
1229 return;
1230 }
1231 }
70812e39 1232
2660377f 1233 // OK, so we have to reload. Reset preference
346c3e2f 1234 $USER->preference = array();
070e2616 1235
346c3e2f 1236 if (!isloggedin() or isguestuser()) {
2660377f 1237 // No permanent storage for not-logged-in user and guest
70812e39 1238
ae040d4b 1239 } else if ($preferences = $DB->get_records('user_preferences', array('userid'=>$USER->id))) {
70812e39 1240 foreach ($preferences as $preference) {
1241 $USER->preference[$preference->name] = $preference->value;
1242 }
c6d15803 1243 }
346c3e2f 1244
2660377f 1245 $USER->preference['_lastloaded'] = $timenow;
1246}
1247
1248/**
1249 * Called from set/delete_user_preferences, so that the prefs can be correctly reloaded.
0d0a8bf6 1250 *
1251 * @global object
1252 * @global object
2660377f 1253 * @param integer $userid the user whose prefs were changed.
1254 */
1255function mark_user_preferences_changed($userid) {
1256 global $CFG, $USER;
1257 if ($userid == $USER->id) {
1258 check_user_preferences_loaded(time());
1259 }
1260 set_cache_flag('userpreferenceschanged', $userid, 1, time() + $CFG->sessiontimeout);
70812e39 1261}
1262
7cf1c7bd 1263/**
1264 * Sets a preference for the current user
0d0a8bf6 1265 *
7cf1c7bd 1266 * Optionally, can set a preference for a different user object
0d0a8bf6 1267 *
68fbd8e1 1268 * @todo Add a better description and include usage examples. Add inline links to $USER and user functions in above line.
0d0a8bf6 1269 *
1270 * @global object
1271 * @global object
7cf1c7bd 1272 * @param string $name The key to set as preference for the specified user
efb8c375 1273 * @param string $value The value to set for the $name key in the specified user's record
0d0a8bf6 1274 * @param int $otheruserid A moodle user ID, default null
bbd3f2c4 1275 * @return bool
7cf1c7bd 1276 */
346c3e2f 1277function set_user_preference($name, $value, $otheruserid=NULL) {
ae040d4b 1278 global $USER, $DB;
70812e39 1279
1280 if (empty($name)) {
1281 return false;
1282 }
1283
346c3e2f 1284 $nostore = false;
346c3e2f 1285 if (empty($otheruserid)){
1286 if (!isloggedin() or isguestuser()) {
1287 $nostore = true;
1288 }
1289 $userid = $USER->id;
1290 } else {
1291 if (isguestuser($otheruserid)) {
1292 $nostore = true;
1293 }
1294 $userid = $otheruserid;
1295 }
1296
346c3e2f 1297 if ($nostore) {
114201c8 1298 // no permanent storage for not-logged-in user and guest
346c3e2f 1299
ae040d4b 1300 } else if ($preference = $DB->get_record('user_preferences', array('userid'=>$userid, 'name'=>$name))) {
a1244706 1301 if ($preference->value === $value) {
1302 return true;
1303 }
013376de 1304 $DB->set_field('user_preferences', 'value', (string)$value, array('id'=>$preference->id));
70812e39 1305
1306 } else {
346c3e2f 1307 $preference = new object();
a3f1f815 1308 $preference->userid = $userid;
ae040d4b 1309 $preference->name = $name;
1310 $preference->value = (string)$value;
013376de 1311 $DB->insert_record('user_preferences', $preference);
2660377f 1312 }
1313
013376de 1314 mark_user_preferences_changed($userid);
1315 // update value in USER session if needed
1316 if ($userid == $USER->id) {
1317 $USER->preference[$name] = (string)$value;
1318 $USER->preference['_lastloaded'] = time();
70812e39 1319 }
346c3e2f 1320
013376de 1321 return true;
2660377f 1322}
1323
1324/**
1325 * Sets a whole array of preferences for the current user
0d0a8bf6 1326 *
2660377f 1327 * @param array $prefarray An array of key/value pairs to be set
1328 * @param int $otheruserid A moodle user ID
1329 * @return bool
1330 */
1331function set_user_preferences($prefarray, $otheruserid=NULL) {
1332
1333 if (!is_array($prefarray) or empty($prefarray)) {
1334 return false;
346c3e2f 1335 }
1336
2660377f 1337 foreach ($prefarray as $name => $value) {
013376de 1338 set_user_preference($name, $value, $otheruserid);
2660377f 1339 }
013376de 1340 return true;
70812e39 1341}
1342
6eb3e776 1343/**
1344 * Unsets a preference completely by deleting it from the database
0d0a8bf6 1345 *
6eb3e776 1346 * Optionally, can set a preference for a different user id
0d0a8bf6 1347 *
1348 * @global object
6eb3e776 1349 * @param string $name The key to unset as preference for the specified user
346c3e2f 1350 * @param int $otheruserid A moodle user ID
6eb3e776 1351 */
346c3e2f 1352function unset_user_preference($name, $otheruserid=NULL) {
ae040d4b 1353 global $USER, $DB;
6eb3e776 1354
346c3e2f 1355 if (empty($otheruserid)){
1356 $userid = $USER->id;
2660377f 1357 check_user_preferences_loaded();
346c3e2f 1358 } else {
1359 $userid = $otheruserid;
1360 }
1361
49d005ee 1362 //Then from DB
013376de 1363 $DB->delete_records('user_preferences', array('userid'=>$userid, 'name'=>$name));
1364
1365 mark_user_preferences_changed($userid);
1366 //Delete the preference from $USER if needed
1367 if ($userid == $USER->id) {
1368 unset($USER->preference[$name]);
1369 $USER->preference['_lastloaded'] = time();
70812e39 1370 }
1371
013376de 1372 return true;
70812e39 1373}
1374
7cf1c7bd 1375/**
0d0a8bf6 1376 * Used to fetch user preference(s)
1377 *
7cf1c7bd 1378 * If no arguments are supplied this function will return
361855e6 1379 * all of the current user preferences as an array.
0d0a8bf6 1380 *
7cf1c7bd 1381 * If a name is specified then this function
1382 * attempts to return that particular preference value. If
1383 * none is found, then the optional value $default is returned,
1384 * otherwise NULL.
0d0a8bf6 1385 *
1386 * @global object
1387 * @global object
7cf1c7bd 1388 * @param string $name Name of the key to use in finding a preference value
1389 * @param string $default Value to be returned if the $name key is not set in the user preferences
346c3e2f 1390 * @param int $otheruserid A moodle user ID
7cf1c7bd 1391 * @return string
1392 */
346c3e2f 1393function get_user_preferences($name=NULL, $default=NULL, $otheruserid=NULL) {
ae040d4b 1394 global $USER, $DB;
70812e39 1395
4f0c2d00 1396 if (empty($otheruserid) || (isloggedin() && ($USER->id == $otheruserid))){
2660377f 1397 check_user_preferences_loaded();
346c3e2f 1398
2660377f 1399 if (empty($name)) {
1400 return $USER->preference; // All values
1401 } else if (array_key_exists($name, $USER->preference)) {
1402 return $USER->preference[$name]; // The single value
1403 } else {
1404 return $default; // Default value (or NULL)
a3f1f815 1405 }
346c3e2f 1406
1407 } else {
2660377f 1408 if (empty($name)) {
1409 return $DB->get_records_menu('user_preferences', array('userid'=>$otheruserid), '', 'name,value'); // All values
46933753 1410 } else if ($value = $DB->get_field('user_preferences', 'value', array('userid'=>$otheruserid, 'name'=>$name))) {
2660377f 1411 return $value; // The single value
1412 } else {
1413 return $default; // Default value (or NULL)
1414 }
70812e39 1415 }
70812e39 1416}
1417
9fa49e22 1418/// FUNCTIONS FOR HANDLING TIME ////////////////////////////////////////////
39917a09 1419
7cf1c7bd 1420/**
c6d15803 1421 * Given date parts in user time produce a GMT timestamp.
7cf1c7bd 1422 *
0d0a8bf6 1423 * @todo Finish documenting this function
68fbd8e1 1424 * @param int $year The year part to create timestamp of
1425 * @param int $month The month part to create timestamp of
1426 * @param int $day The day part to create timestamp of
1427 * @param int $hour The hour part to create timestamp of
1428 * @param int $minute The minute part to create timestamp of
1429 * @param int $second The second part to create timestamp of
0d0a8bf6 1430 * @param float $timezone Timezone modifier
1431 * @param bool $applydst Toggle Daylight Saving Time, default true
e34d817e 1432 * @return int timestamp
7cf1c7bd 1433 */
9f1f6daf 1434function make_timestamp($year, $month=1, $day=1, $hour=0, $minute=0, $second=0, $timezone=99, $applydst=true) {
39917a09 1435
33998d30 1436 $strtimezone = NULL;
1437 if (!is_numeric($timezone)) {
1438 $strtimezone = $timezone;
1439 }
1440
dddb014a 1441 $timezone = get_user_timezone_offset($timezone);
1442
94e34118 1443 if (abs($timezone) > 13) {
68fbd8e1 1444 $time = mktime((int)$hour, (int)$minute, (int)$second, (int)$month, (int)$day, (int)$year);
03c17ddf 1445 } else {
68fbd8e1 1446 $time = gmmktime((int)$hour, (int)$minute, (int)$second, (int)$month, (int)$day, (int)$year);
196f2619 1447 $time = usertime($time, $timezone);
28c66824 1448 if($applydst) {
33998d30 1449 $time -= dst_offset_on($time, $strtimezone);
28c66824 1450 }
9f1f6daf 1451 }
1452
196f2619 1453 return $time;
85cafb3e 1454
39917a09 1455}
1456
7cf1c7bd 1457/**
0d0a8bf6 1458 * Format a date/time (seconds) as weeks, days, hours etc as needed
1459 *
7cf1c7bd 1460 * Given an amount of time in seconds, returns string
5602f7cf 1461 * formatted nicely as weeks, days, hours etc as needed
7cf1c7bd 1462 *
2f87145b 1463 * @uses MINSECS
1464 * @uses HOURSECS
1465 * @uses DAYSECS
5602f7cf 1466 * @uses YEARSECS
0d0a8bf6 1467 * @param int $totalsecs Time in seconds
1468 * @param object $str Should be a time object
1469 * @return string A nicely formatted date/time string
7cf1c7bd 1470 */
1471 function format_time($totalsecs, $str=NULL) {
c7e3ac2a 1472
6b174680 1473 $totalsecs = abs($totalsecs);
c7e3ac2a 1474
8dbed6be 1475 if (!$str) { // Create the str structure the slow way
b0ccd3fb 1476 $str->day = get_string('day');
1477 $str->days = get_string('days');
1478 $str->hour = get_string('hour');
1479 $str->hours = get_string('hours');
1480 $str->min = get_string('min');
1481 $str->mins = get_string('mins');
1482 $str->sec = get_string('sec');
1483 $str->secs = get_string('secs');
5602f7cf 1484 $str->year = get_string('year');
1485 $str->years = get_string('years');
8dbed6be 1486 }
1487
5602f7cf 1488
1489 $years = floor($totalsecs/YEARSECS);
1490 $remainder = $totalsecs - ($years*YEARSECS);
5602f7cf 1491 $days = floor($remainder/DAYSECS);
7a5672c9 1492 $remainder = $totalsecs - ($days*DAYSECS);
1493 $hours = floor($remainder/HOURSECS);
1494 $remainder = $remainder - ($hours*HOURSECS);
1495 $mins = floor($remainder/MINSECS);
1496 $secs = $remainder - ($mins*MINSECS);
8dbed6be 1497
1498 $ss = ($secs == 1) ? $str->sec : $str->secs;
1499 $sm = ($mins == 1) ? $str->min : $str->mins;
1500 $sh = ($hours == 1) ? $str->hour : $str->hours;
1501 $sd = ($days == 1) ? $str->day : $str->days;
5602f7cf 1502 $sy = ($years == 1) ? $str->year : $str->years;
8dbed6be 1503
5602f7cf 1504 $oyears = '';
b0ccd3fb 1505 $odays = '';
1506 $ohours = '';
1507 $omins = '';
1508 $osecs = '';
9c9f7d77 1509
5602f7cf 1510 if ($years) $oyears = $years .' '. $sy;
b0ccd3fb 1511 if ($days) $odays = $days .' '. $sd;
1512 if ($hours) $ohours = $hours .' '. $sh;
1513 if ($mins) $omins = $mins .' '. $sm;
1514 if ($secs) $osecs = $secs .' '. $ss;
6b174680 1515
77ac808e 1516 if ($years) return trim($oyears .' '. $odays);
1517 if ($days) return trim($odays .' '. $ohours);
1518 if ($hours) return trim($ohours .' '. $omins);
1519 if ($mins) return trim($omins .' '. $osecs);
b0ccd3fb 1520 if ($secs) return $osecs;
1521 return get_string('now');
6b174680 1522}
f9903ed0 1523
7cf1c7bd 1524/**
0d0a8bf6 1525 * Returns a formatted string that represents a date in user time
1526 *
7cf1c7bd 1527 * Returns a formatted string that represents a date in user time
1528 * <b>WARNING: note that the format is for strftime(), not date().</b>
1529 * Because of a bug in most Windows time libraries, we can't use
1530 * the nicer %e, so we have to use %d which has leading zeroes.
1531 * A lot of the fuss in the function is just getting rid of these leading
1532 * zeroes as efficiently as possible.
361855e6 1533 *
8c3dba73 1534 * If parameter fixday = true (default), then take off leading
efb8c375 1535 * zero from %d, else maintain it.
7cf1c7bd 1536 *
0a0cf09a 1537 * @param int $date the timestamp in UTC, as obtained from the database.
1538 * @param string $format strftime format. You should probably get this using
1539 * get_string('strftime...', 'langconfig');
1540 * @param float $timezone by default, uses the user's time zone.
1541 * @param bool $fixday If true (default) then the leading zero from %d is removed.
efb8c375 1542 * If false then the leading zero is maintained.
0a0cf09a 1543 * @return string the formatted date/time.
7cf1c7bd 1544 */
0a0cf09a 1545function userdate($date, $format = '', $timezone = 99, $fixday = true) {
7a302afc 1546
1ac7ee24 1547 global $CFG;
1548
33998d30 1549 $strtimezone = NULL;
1550 if (!is_numeric($timezone)) {
1551 $strtimezone = $timezone;
1552 }
1553
1306c5ea 1554 if (empty($format)) {
0a0cf09a 1555 $format = get_string('strftimedaydatetime', 'langconfig');
5fa51a39 1556 }
035cdbff 1557
c3a3c5b8 1558 if (!empty($CFG->nofixday)) { // Config.php can force %d not to be fixed.
1559 $fixday = false;
1560 } else if ($fixday) {
1561 $formatnoday = str_replace('%d', 'DD', $format);
61ae5d36 1562 $fixday = ($formatnoday != $format);
1563 }
dcde9f02 1564
33998d30 1565 $date += dst_offset_on($date, $strtimezone);
85351042 1566
494b9296 1567 $timezone = get_user_timezone_offset($timezone);
102dc313 1568
1569 if (abs($timezone) > 13) { /// Server time
d2a9f7cc 1570 if ($fixday) {
102dc313 1571 $datestring = strftime($formatnoday, $date);
35f7287f 1572 $daystring = ltrim(str_replace(array(' 0', ' '), '', strftime(' %d', $date)));
102dc313 1573 $datestring = str_replace('DD', $daystring, $datestring);
1574 } else {
1575 $datestring = strftime($format, $date);
1576 }
88ec5b7c 1577 } else {
102dc313 1578 $date += (int)($timezone * 3600);
1579 if ($fixday) {
1580 $datestring = gmstrftime($formatnoday, $date);
35f7287f 1581 $daystring = ltrim(str_replace(array(' 0', ' '), '', gmstrftime(' %d', $date)));
102dc313 1582 $datestring = str_replace('DD', $daystring, $datestring);
1583 } else {
1584 $datestring = gmstrftime($format, $date);
1585 }
88ec5b7c 1586 }
102dc313 1587
fb773106 1588/// If we are running under Windows convert from windows encoding to UTF-8
1589/// (because it's impossible to specify UTF-8 to fetch locale info in Win32)
11f7b25d 1590
fb773106 1591 if ($CFG->ostype == 'WINDOWS') {
bf69b06d 1592 if ($localewincharset = get_string('localewincharset', 'langconfig')) {
11f7b25d 1593 $textlib = textlib_get_instance();
810944af 1594 $datestring = $textlib->convert($datestring, $localewincharset, 'utf-8');
11f7b25d 1595 }
1596 }
1597
035cdbff 1598 return $datestring;
873960de 1599}
1600
7cf1c7bd 1601/**
196f2619 1602 * Given a $time timestamp in GMT (seconds since epoch),
c6d15803 1603 * returns an array that represents the date in user time
7cf1c7bd 1604 *
0d0a8bf6 1605 * @todo Finish documenting this function
2f87145b 1606 * @uses HOURSECS
196f2619 1607 * @param int $time Timestamp in GMT
68fbd8e1 1608 * @param float $timezone ?
c6d15803 1609 * @return array An array that represents the date in user time
7cf1c7bd 1610 */
196f2619 1611function usergetdate($time, $timezone=99) {
6b174680 1612
94c82430 1613 $strtimezone = NULL;
1614 if (!is_numeric($timezone)) {
1615 $strtimezone = $timezone;
1616 }
1617
494b9296 1618 $timezone = get_user_timezone_offset($timezone);
a36166d3 1619
e34d817e 1620 if (abs($timezone) > 13) { // Server time
ed1f69b0 1621 return getdate($time);
d2a9f7cc 1622 }
1623
e34d817e 1624 // There is no gmgetdate so we use gmdate instead
94c82430 1625 $time += dst_offset_on($time, $strtimezone);
e34d817e 1626 $time += intval((float)$timezone * HOURSECS);
3bba1e6e 1627
24d38a6e 1628 $datestring = gmstrftime('%B_%A_%j_%Y_%m_%w_%d_%H_%M_%S', $time);
02f0527d 1629
24d38a6e 1630 //be careful to ensure the returned array matches that produced by getdate() above
9f1f6daf 1631 list(
24d38a6e
AD
1632 $getdate['month'],
1633 $getdate['weekday'],
1634 $getdate['yday'],
9f1f6daf 1635 $getdate['year'],
24d38a6e 1636 $getdate['mon'],
9f1f6daf 1637 $getdate['wday'],
24d38a6e
AD
1638 $getdate['mday'],
1639 $getdate['hours'],
1640 $getdate['minutes'],
1641 $getdate['seconds']
3bba1e6e 1642 ) = explode('_', $datestring);
9f1f6daf 1643
d2d6171f 1644 return $getdate;
d552ead0 1645}
1646
7cf1c7bd 1647/**
1648 * Given a GMT timestamp (seconds since epoch), offsets it by
1649 * the timezone. eg 3pm in India is 3pm GMT - 7 * 3600 seconds
1650 *
2f87145b 1651 * @uses HOURSECS
c6d15803 1652 * @param int $date Timestamp in GMT
e34d817e 1653 * @param float $timezone
c6d15803 1654 * @return int
7cf1c7bd 1655 */
d552ead0 1656function usertime($date, $timezone=99) {
a36166d3 1657
494b9296 1658 $timezone = get_user_timezone_offset($timezone);
2665e47a 1659
0431bd7c 1660 if (abs($timezone) > 13) {
d552ead0 1661 return $date;
1662 }
7a5672c9 1663 return $date - (int)($timezone * HOURSECS);
d552ead0 1664}
1665
8c3dba73 1666/**
1667 * Given a time, return the GMT timestamp of the most recent midnight
1668 * for the current user.
1669 *
e34d817e 1670 * @param int $date Timestamp in GMT
0d0a8bf6 1671 * @param float $timezone Defaults to user's timezone
1672 * @return int Returns a GMT timestamp
8c3dba73 1673 */
edf7fe8c 1674function usergetmidnight($date, $timezone=99) {
edf7fe8c 1675
edf7fe8c 1676 $userdate = usergetdate($date, $timezone);
4606d9bb 1677
02f0527d 1678 // Time of midnight of this user's day, in GMT
1679 return make_timestamp($userdate['year'], $userdate['mon'], $userdate['mday'], 0, 0, 0, $timezone);
edf7fe8c 1680
1681}
1682
7cf1c7bd 1683/**
1684 * Returns a string that prints the user's timezone
1685 *
1686 * @param float $timezone The user's timezone
1687 * @return string
1688 */
d552ead0 1689function usertimezone($timezone=99) {
d552ead0 1690
0c244315 1691 $tz = get_user_timezone($timezone);
f30fe8d0 1692
0c244315 1693 if (!is_float($tz)) {
1694 return $tz;
d552ead0 1695 }
0c244315 1696
1697 if(abs($tz) > 13) { // Server time
1698 return get_string('serverlocaltime');
1699 }
1700
1701 if($tz == intval($tz)) {
1702 // Don't show .0 for whole hours
1703 $tz = intval($tz);
1704 }
1705
1706 if($tz == 0) {
61b420ac 1707 return 'UTC';
d552ead0 1708 }
0c244315 1709 else if($tz > 0) {
61b420ac 1710 return 'UTC+'.$tz;
0c244315 1711 }
1712 else {
61b420ac 1713 return 'UTC'.$tz;
d552ead0 1714 }
e1ecf0a0 1715
f9903ed0 1716}
1717
7cf1c7bd 1718/**
1719 * Returns a float which represents the user's timezone difference from GMT in hours
1720 * Checks various settings and picks the most dominant of those which have a value
1721 *
0d0a8bf6 1722 * @global object
1723 * @global object
b2b68362 1724 * @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 1725 * @return float
7cf1c7bd 1726 */
494b9296 1727function get_user_timezone_offset($tz = 99) {
f30fe8d0 1728
43b59916 1729 global $USER, $CFG;
1730
e8904995 1731 $tz = get_user_timezone($tz);
c9e55a25 1732
7b9e355e 1733 if (is_float($tz)) {
1734 return $tz;
1735 } else {
e8904995 1736 $tzrecord = get_timezone_record($tz);
7b9e355e 1737 if (empty($tzrecord)) {
e8904995 1738 return 99.0;
1739 }
4f2dbde9 1740 return (float)$tzrecord->gmtoff / HOURMINS;
e8904995 1741 }
1742}
1743
61460dd6 1744/**
1745 * Returns an int which represents the systems's timezone difference from GMT in seconds
0d0a8bf6 1746 *
1747 * @global object
61460dd6 1748 * @param mixed $tz timezone
1749 * @return int if found, false is timezone 99 or error
1750 */
1751function get_timezone_offset($tz) {
1752 global $CFG;
1753
1754 if ($tz == 99) {
1755 return false;
1756 }
1757
1758 if (is_numeric($tz)) {
1759 return intval($tz * 60*60);
1760 }
1761
1762 if (!$tzrecord = get_timezone_record($tz)) {
1763 return false;
1764 }
1765 return intval($tzrecord->gmtoff * 60);
1766}
1767
bbd3f2c4 1768/**
b2b68362 1769 * Returns a float or a string which denotes the user's timezone
1770 * 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)
1771 * means that for this timezone there are also DST rules to be taken into account
1772 * Checks various settings and picks the most dominant of those which have a value
bbd3f2c4 1773 *
0d0a8bf6 1774 * @global object
1775 * @global object
b2b68362 1776 * @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
1777 * @return mixed
bbd3f2c4 1778 */
e8904995 1779function get_user_timezone($tz = 99) {
1780 global $USER, $CFG;
43b59916 1781
f30fe8d0 1782 $timezones = array(
e8904995 1783 $tz,
1784 isset($CFG->forcetimezone) ? $CFG->forcetimezone : 99,
43b59916 1785 isset($USER->timezone) ? $USER->timezone : 99,
1786 isset($CFG->timezone) ? $CFG->timezone : 99,
f30fe8d0 1787 );
43b59916 1788
e8904995 1789 $tz = 99;
43b59916 1790
33998d30 1791 while(($tz == '' || $tz == 99 || $tz == NULL) && $next = each($timezones)) {
e8904995 1792 $tz = $next['value'];
43b59916 1793 }
e8904995 1794
1795 return is_numeric($tz) ? (float) $tz : $tz;
43b59916 1796}
1797
bbd3f2c4 1798/**
f33e1ed4 1799 * Returns cached timezone record for given $timezonename
bbd3f2c4 1800 *
0d0a8bf6 1801 * @global object
1802 * @global object
f33e1ed4 1803 * @param string $timezonename
1804 * @return mixed timezonerecord object or false
bbd3f2c4 1805 */
43b59916 1806function get_timezone_record($timezonename) {
f33e1ed4 1807 global $CFG, $DB;
43b59916 1808 static $cache = NULL;
1809
8edffd15 1810 if ($cache === NULL) {
43b59916 1811 $cache = array();
1812 }
1813
8edffd15 1814 if (isset($cache[$timezonename])) {
43b59916 1815 return $cache[$timezonename];
f30fe8d0 1816 }
1817
f33e1ed4 1818 return $cache[$timezonename] = $DB->get_record_sql('SELECT * FROM {timezone}
ae040d4b 1819 WHERE name = ? ORDER BY year DESC', array($timezonename), true);
f30fe8d0 1820}
f9903ed0 1821
bbd3f2c4 1822/**
0d0a8bf6 1823 * Build and store the users Daylight Saving Time (DST) table
bbd3f2c4 1824 *
0d0a8bf6 1825 * @global object
1826 * @global object
1827 * @global object
1828 * @param mixed $from_year Start year for the table, defaults to 1971
1829 * @param mixed $to_year End year for the table, defaults to 2035
1830 * @param mixed $strtimezone
bbd3f2c4 1831 * @return bool
1832 */
94c82430 1833function calculate_user_dst_table($from_year = NULL, $to_year = NULL, $strtimezone = NULL) {
ae040d4b 1834 global $CFG, $SESSION, $DB;
85cafb3e 1835
33998d30 1836 $usertz = get_user_timezone($strtimezone);
7cb29a3d 1837
989585e9 1838 if (is_float($usertz)) {
1839 // Trivial timezone, no DST
1840 return false;
1841 }
1842
2280ecf5 1843 if (!empty($SESSION->dst_offsettz) && $SESSION->dst_offsettz != $usertz) {
989585e9 1844 // We have precalculated values, but the user's effective TZ has changed in the meantime, so reset
2280ecf5 1845 unset($SESSION->dst_offsets);
1846 unset($SESSION->dst_range);
830a2bbd 1847 }
1848
2280ecf5 1849 if (!empty($SESSION->dst_offsets) && empty($from_year) && empty($to_year)) {
830a2bbd 1850 // Repeat calls which do not request specific year ranges stop here, we have already calculated the table
1851 // This will be the return path most of the time, pretty light computationally
1852 return true;
85cafb3e 1853 }
1854
830a2bbd 1855 // Reaching here means we either need to extend our table or create it from scratch
989585e9 1856
1857 // Remember which TZ we calculated these changes for
2280ecf5 1858 $SESSION->dst_offsettz = $usertz;
989585e9 1859
2280ecf5 1860 if(empty($SESSION->dst_offsets)) {
830a2bbd 1861 // If we 're creating from scratch, put the two guard elements in there
2280ecf5 1862 $SESSION->dst_offsets = array(1 => NULL, 0 => NULL);
830a2bbd 1863 }
2280ecf5 1864 if(empty($SESSION->dst_range)) {
830a2bbd 1865 // If creating from scratch
1866 $from = max((empty($from_year) ? intval(date('Y')) - 3 : $from_year), 1971);
1867 $to = min((empty($to_year) ? intval(date('Y')) + 3 : $to_year), 2035);
1868
1869 // Fill in the array with the extra years we need to process
1870 $yearstoprocess = array();
1871 for($i = $from; $i <= $to; ++$i) {
1872 $yearstoprocess[] = $i;
1873 }
1874
1875 // Take note of which years we have processed for future calls
2280ecf5 1876 $SESSION->dst_range = array($from, $to);
830a2bbd 1877 }
1878 else {
1879 // If needing to extend the table, do the same
1880 $yearstoprocess = array();
1881
2280ecf5 1882 $from = max((empty($from_year) ? $SESSION->dst_range[0] : $from_year), 1971);
1883 $to = min((empty($to_year) ? $SESSION->dst_range[1] : $to_year), 2035);
830a2bbd 1884
2280ecf5 1885 if($from < $SESSION->dst_range[0]) {
830a2bbd 1886 // Take note of which years we need to process and then note that we have processed them for future calls
2280ecf5 1887 for($i = $from; $i < $SESSION->dst_range[0]; ++$i) {
830a2bbd 1888 $yearstoprocess[] = $i;
1889 }
2280ecf5 1890 $SESSION->dst_range[0] = $from;
830a2bbd 1891 }
2280ecf5 1892 if($to > $SESSION->dst_range[1]) {
830a2bbd 1893 // Take note of which years we need to process and then note that we have processed them for future calls
2280ecf5 1894 for($i = $SESSION->dst_range[1] + 1; $i <= $to; ++$i) {
830a2bbd 1895 $yearstoprocess[] = $i;
1896 }
2280ecf5 1897 $SESSION->dst_range[1] = $to;
830a2bbd 1898 }
1899 }
1900
1901 if(empty($yearstoprocess)) {
1902 // This means that there was a call requesting a SMALLER range than we have already calculated
1903 return true;
1904 }
1905
1906 // From now on, we know that the array has at least the two guard elements, and $yearstoprocess has the years we need
1907 // Also, the array is sorted in descending timestamp order!
1908
1909 // Get DB data
6a5dc27c 1910
1911 static $presets_cache = array();
1912 if (!isset($presets_cache[$usertz])) {
ae040d4b 1913 $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 1914 }
1915 if(empty($presets_cache[$usertz])) {
e789650d 1916 return false;
1917 }
57f1191c 1918
830a2bbd 1919 // Remove ending guard (first element of the array)
2280ecf5 1920 reset($SESSION->dst_offsets);
1921 unset($SESSION->dst_offsets[key($SESSION->dst_offsets)]);
830a2bbd 1922
1923 // Add all required change timestamps
1924 foreach($yearstoprocess as $y) {
1925 // Find the record which is in effect for the year $y
6a5dc27c 1926 foreach($presets_cache[$usertz] as $year => $preset) {
830a2bbd 1927 if($year <= $y) {
1928 break;
c9e72798 1929 }
830a2bbd 1930 }
1931
1932 $changes = dst_changes_for_year($y, $preset);
1933
1934 if($changes === NULL) {
1935 continue;
1936 }
1937 if($changes['dst'] != 0) {
2280ecf5 1938 $SESSION->dst_offsets[$changes['dst']] = $preset->dstoff * MINSECS;
830a2bbd 1939 }
1940 if($changes['std'] != 0) {
2280ecf5 1941 $SESSION->dst_offsets[$changes['std']] = 0;
c9e72798 1942 }
85cafb3e 1943 }
42d36497 1944
830a2bbd 1945 // Put in a guard element at the top
2280ecf5 1946 $maxtimestamp = max(array_keys($SESSION->dst_offsets));
1947 $SESSION->dst_offsets[($maxtimestamp + DAYSECS)] = NULL; // DAYSECS is arbitrary, any "small" number will do
830a2bbd 1948
1949 // Sort again
2280ecf5 1950 krsort($SESSION->dst_offsets);
830a2bbd 1951
e789650d 1952 return true;
1953}
42d36497 1954
0d0a8bf6 1955/**
1956 * Calculates the required DST change and returns a Timestamp Array
1957 *
1958 * @uses HOURSECS
1959 * @uses MINSECS
1960 * @param mixed $year Int or String Year to focus on
1961 * @param object $timezone Instatiated Timezone object
1962 * @return mixed Null, or Array dst=>xx, 0=>xx, std=>yy, 1=>yy
1963 */
e789650d 1964function dst_changes_for_year($year, $timezone) {
7cb29a3d 1965
e789650d 1966 if($timezone->dst_startday == 0 && $timezone->dst_weekday == 0 && $timezone->std_startday == 0 && $timezone->std_weekday == 0) {
1967 return NULL;
42d36497 1968 }
7cb29a3d 1969
e789650d 1970 $monthdaydst = find_day_in_month($timezone->dst_startday, $timezone->dst_weekday, $timezone->dst_month, $year);
1971 $monthdaystd = find_day_in_month($timezone->std_startday, $timezone->std_weekday, $timezone->std_month, $year);
1972
1973 list($dst_hour, $dst_min) = explode(':', $timezone->dst_time);
1974 list($std_hour, $std_min) = explode(':', $timezone->std_time);
d2a9f7cc 1975
6dc8dddc 1976 $timedst = make_timestamp($year, $timezone->dst_month, $monthdaydst, 0, 0, 0, 99, false);
1977 $timestd = make_timestamp($year, $timezone->std_month, $monthdaystd, 0, 0, 0, 99, false);
830a2bbd 1978
1979 // Instead of putting hour and minute in make_timestamp(), we add them afterwards.
1980 // This has the advantage of being able to have negative values for hour, i.e. for timezones
1981 // where GMT time would be in the PREVIOUS day than the local one on which DST changes.
1982
1983 $timedst += $dst_hour * HOURSECS + $dst_min * MINSECS;
1984 $timestd += $std_hour * HOURSECS + $std_min * MINSECS;
42d36497 1985
e789650d 1986 return array('dst' => $timedst, 0 => $timedst, 'std' => $timestd, 1 => $timestd);
42d36497 1987}
1988
0d0a8bf6 1989/**
efb8c375 1990 * Calculates the Daylight Saving Offset for a given date/time (timestamp)
0d0a8bf6 1991 *
1992 * @global object
1993 * @param int $time must NOT be compensated at all, it has to be a pure timestamp
1994 * @return int
1995 */
94c82430 1996function dst_offset_on($time, $strtimezone = NULL) {
2280ecf5 1997 global $SESSION;
02f0527d 1998
94c82430 1999 if(!calculate_user_dst_table(NULL, NULL, $strtimezone) || empty($SESSION->dst_offsets)) {
c9e72798 2000 return 0;
85cafb3e 2001 }
2002
2280ecf5 2003 reset($SESSION->dst_offsets);
2004 while(list($from, $offset) = each($SESSION->dst_offsets)) {
59556d48 2005 if($from <= $time) {
c9e72798 2006 break;
2007 }
2008 }
2009
830a2bbd 2010 // This is the normal return path
2011 if($offset !== NULL) {
2012 return $offset;
02f0527d 2013 }
02f0527d 2014
830a2bbd 2015 // Reaching this point means we haven't calculated far enough, do it now:
2016 // Calculate extra DST changes if needed and recurse. The recursion always
2017 // moves toward the stopping condition, so will always end.
2018
2019 if($from == 0) {
2280ecf5 2020 // We need a year smaller than $SESSION->dst_range[0]
2021 if($SESSION->dst_range[0] == 1971) {
830a2bbd 2022 return 0;
2023 }
94c82430 2024 calculate_user_dst_table($SESSION->dst_range[0] - 5, NULL, $strtimezone);
2025 return dst_offset_on($time, $strtimezone);
830a2bbd 2026 }
2027 else {
2280ecf5 2028 // We need a year larger than $SESSION->dst_range[1]
2029 if($SESSION->dst_range[1] == 2035) {
830a2bbd 2030 return 0;
2031 }
94c82430 2032 calculate_user_dst_table(NULL, $SESSION->dst_range[1] + 5, $strtimezone);
2033 return dst_offset_on($time, $strtimezone);
830a2bbd 2034 }
85cafb3e 2035}
02f0527d 2036
0d0a8bf6 2037/**
2038 * ?
2039 *
2040 * @todo Document what this function does
2041 * @param int $startday
2042 * @param int $weekday
2043 * @param int $month
2044 * @param int $year
2045 * @return int
2046 */
28902d99 2047function find_day_in_month($startday, $weekday, $month, $year) {
8dc3f6cf 2048
2049 $daysinmonth = days_in_month($month, $year);
2050
42d36497 2051 if($weekday == -1) {
28902d99 2052 // Don't care about weekday, so return:
2053 // abs($startday) if $startday != -1
2054 // $daysinmonth otherwise
2055 return ($startday == -1) ? $daysinmonth : abs($startday);
8dc3f6cf 2056 }
2057
2058 // From now on we 're looking for a specific weekday
8dc3f6cf 2059
28902d99 2060 // Give "end of month" its actual value, since we know it
2061 if($startday == -1) {
2062 $startday = -1 * $daysinmonth;
2063 }
2064
2065 // Starting from day $startday, the sign is the direction
8dc3f6cf 2066
28902d99 2067 if($startday < 1) {
8dc3f6cf 2068
28902d99 2069 $startday = abs($startday);
8dc3f6cf 2070 $lastmonthweekday = strftime('%w', mktime(12, 0, 0, $month, $daysinmonth, $year, 0));
2071
2072 // This is the last such weekday of the month
2073 $lastinmonth = $daysinmonth + $weekday - $lastmonthweekday;
2074 if($lastinmonth > $daysinmonth) {
2075 $lastinmonth -= 7;
42d36497 2076 }
8dc3f6cf 2077
28902d99 2078 // Find the first such weekday <= $startday
2079 while($lastinmonth > $startday) {
8dc3f6cf 2080 $lastinmonth -= 7;
42d36497 2081 }
8dc3f6cf 2082
2083 return $lastinmonth;
e1ecf0a0 2084
42d36497 2085 }
2086 else {
42d36497 2087
28902d99 2088 $indexweekday = strftime('%w', mktime(12, 0, 0, $month, $startday, $year, 0));
42d36497 2089
8dc3f6cf 2090 $diff = $weekday - $indexweekday;
2091 if($diff < 0) {
2092 $diff += 7;
42d36497 2093 }
42d36497 2094
28902d99 2095 // This is the first such weekday of the month equal to or after $startday
2096 $firstfromindex = $startday + $diff;
42d36497 2097
8dc3f6cf 2098 return $firstfromindex;
2099
2100 }
42d36497 2101}
2102
bbd3f2c4 2103/**
2104 * Calculate the number of days in a given month
2105 *
2106 * @param int $month The month whose day count is sought
2107 * @param int $year The year of the month whose day count is sought
2108 * @return int
2109 */
42d36497 2110function days_in_month($month, $year) {
2111 return intval(date('t', mktime(12, 0, 0, $month, 1, $year, 0)));
2112}
2113
bbd3f2c4 2114/**
2115 * Calculate the position in the week of a specific calendar day
2116 *
2117 * @param int $day The day of the date whose position in the week is sought
2118 * @param int $month The month of the date whose position in the week is sought
2119 * @param int $year The year of the date whose position in the week is sought
2120 * @return int
2121 */
8dc3f6cf 2122function dayofweek($day, $month, $year) {
2123 // I wonder if this is any different from
2124 // strftime('%w', mktime(12, 0, 0, $month, $daysinmonth, $year, 0));
2125 return intval(date('w', mktime(12, 0, 0, $month, $day, $year, 0)));
2126}
2127
9fa49e22 2128/// USER AUTHENTICATION AND LOGIN ////////////////////////////////////////
f9903ed0 2129
93f66983 2130/**
2131 * Returns full login url.
2132 *
93f66983 2133 * @return string login url
2134 */
999b54af 2135function get_login_url() {
93f66983 2136 global $CFG;
2137
999b54af 2138 $url = "$CFG->wwwroot/login/index.php";
93f66983 2139
999b54af
PS
2140 if (!empty($CFG->loginhttps)) {
2141 $url = str_replace('http:', 'https:', $url);
93f66983 2142 }
2143
2144 return $url;
2145}
2146
7cf1c7bd 2147/**
ec81373f 2148 * This function checks that the current user is logged in and has the
2149 * required privileges
2150 *
7cf1c7bd 2151 * This function checks that the current user is logged in, and optionally
ec81373f 2152 * whether they are allowed to be in a particular course and view a particular
2153 * course module.
2154 * If they are not logged in, then it redirects them to the site login unless
d2a9f7cc 2155 * $autologinguest is set and {@link $CFG}->autologinguests is set to 1 in which
ec81373f 2156 * case they are automatically logged in as guests.
2157 * If $courseid is given and the user is not enrolled in that course then the
2158 * user is redirected to the course enrolment page.
efb8c375 2159 * If $cm is given and the course module is hidden and the user is not a teacher
ec81373f 2160 * in the course then the user is redirected to the course home page.
7cf1c7bd 2161 *
191b267b 2162 * When $cm parameter specified, this function sets page layout to 'module'.
4f0c2d00 2163 * You need to change it manually later if some other layout needed.
191b267b 2164 *
33ebaf7c 2165 * @param mixed $courseorid id of the course or course object
0d0a8bf6 2166 * @param bool $autologinguest default true
bbd3f2c4 2167 * @param object $cm course module object
f4013c10 2168 * @param bool $setwantsurltome Define if we want to set $SESSION->wantsurl, defaults to
2169 * true. Used to avoid (=false) some scripts (file.php...) to set that variable,
2170 * in order to keep redirects working properly. MDL-14495
df997f84 2171 * @param bool $preventredirect set to true in scripts that can not redirect (CLI, rss feeds, etc.), throws exceptions
0d0a8bf6 2172 * @return mixed Void, exit, and die depending on path
7cf1c7bd 2173 */
df997f84
PS
2174function require_login($courseorid = NULL, $autologinguest = true, $cm = NULL, $setwantsurltome = true, $preventredirect = false) {
2175 global $CFG, $SESSION, $USER, $FULLME, $PAGE, $SITE, $DB, $OUTPUT;
d8ba183c 2176
df997f84 2177 // setup global $COURSE, themes, language and locale
c13a5e71 2178 if (!empty($courseorid)) {
2179 if (is_object($courseorid)) {
2180 $course = $courseorid;
2181 } else if ($courseorid == SITEID) {
2182 $course = clone($SITE);
2183 } else {
df997f84 2184 $course = $DB->get_record('course', array('id' => $courseorid), '*', MUST_EXIST);
c13a5e71 2185 }
95d28870 2186 if ($cm) {
df997f84
PS
2187 if ($cm->course != $course->id) {
2188 throw new coding_exception('course and cm parameters in require_login() call do not match!!');
2189 }
00dadbe1 2190 $PAGE->set_cm($cm, $course); // set's up global $COURSE
191b267b 2191 $PAGE->set_pagelayout('incourse');
95d28870 2192 } else {
00dadbe1 2193 $PAGE->set_course($course); // set's up global $COURSE
95d28870 2194 }
e88462a0 2195 } else {
df997f84
PS
2196 // do not touch global $COURSE via $PAGE->set_course(),
2197 // the reasons is we need to be able to call require_login() at any time!!
2198 $course = $SITE;
2199 if ($cm) {
2200 throw new coding_exception('cm parameter in require_login() requires valid course parameter!');
2201 }
c13a5e71 2202 }
be933850 2203
df997f84 2204 // If the user is not even logged in yet then make sure they are
083c3743 2205 if (!isloggedin()) {
df997f84 2206 if ($autologinguest and !empty($CFG->guestloginbutton) and !empty($CFG->autologinguests)) {
999b54af
PS
2207 if (!$guest = get_complete_user_data('id', $CFG->siteguest)) {
2208 // misconfigured site guest, just redirect to login page
2209 redirect(get_login_url());
2210 exit; // never reached
df997f84 2211 }
999b54af
PS
2212 $lang = isset($SESSION->lang) ? $SESSION->lang : $CFG->lang;
2213 complete_user_login($guest, false);
2214 $SESSION->lang = $lang;
8a33e371 2215 } else {
999b54af
PS
2216 //NOTE: $USER->site check was obsoleted by session test cookie,
2217 // $USER->confirmed test is in login/index.php
2218 if ($preventredirect) {
2219 throw new require_login_exception('You are not logged in');
2220 }
2221
2222 if ($setwantsurltome) {
2223 // TODO: switch to PAGE->url
2224 $SESSION->wantsurl = $FULLME;
2225 }
2226 if (!empty($_SERVER['HTTP_REFERER'])) {
2227 $SESSION->fromurl = $_SERVER['HTTP_REFERER'];
2228 }
2229 redirect(get_login_url());
2230 exit; // never reached
8a33e371 2231 }
f9903ed0 2232 }
808a3baa 2233
df997f84
PS
2234 // loginas as redirection if needed
2235 if ($course->id != SITEID and session_is_loggedinas()) {
f6f66b03 2236 if ($USER->loginascontext->contextlevel == CONTEXT_COURSE) {
df997f84 2237 if ($USER->loginascontext->instanceid != $course->id) {
3887fe4a 2238 print_error('loginasonecourse', '', $CFG->wwwroot.'/course/view.php?id='.$USER->loginascontext->instanceid);
5e623a33 2239 }
f6f66b03 2240 }
2241 }
2242
df997f84 2243 // check whether the user should be changing password (but only if it is REALLY them)
b7b64ff2 2244 if (get_user_preferences('auth_forcepasswordchange') && !session_is_loggedinas()) {
21e2dcd9 2245 $userauth = get_auth_plugin($USER->auth);
df997f84 2246 if ($userauth->can_change_password() and !$preventredirect) {
20fde7b1 2247 $SESSION->wantsurl = $FULLME;
80274abf 2248 if ($changeurl = $userauth->change_password_url()) {
9696bd89 2249 //use plugin custom url
80274abf 2250 redirect($changeurl);
1437f0a5 2251 } else {
9696bd89 2252 //use moodle internal method
2253 if (empty($CFG->loginhttps)) {
2254 redirect($CFG->wwwroot .'/login/change_password.php');
2255 } else {
2256 $wwwroot = str_replace('http:','https:', $CFG->wwwroot);
2257 redirect($wwwroot .'/login/change_password.php');
2258 }
1437f0a5 2259 }
d35757eb 2260 } else {
a8ee7194 2261 print_error('nopasswordchangeforced', 'auth');
d35757eb 2262 }
2263 }
083c3743 2264
df997f84 2265 // Check that the user account is properly set up
808a3baa 2266 if (user_not_fully_set_up($USER)) {
df997f84
PS
2267 if ($preventredirect) {
2268 throw new require_login_exception('User not fully set-up');
2269 }
20fde7b1 2270 $SESSION->wantsurl = $FULLME;
b0ccd3fb 2271 redirect($CFG->wwwroot .'/user/edit.php?id='. $USER->id .'&amp;course='. SITEID);
808a3baa 2272 }
d8ba183c 2273
df997f84 2274 // Make sure the USER has a sesskey set up. Used for CSRF protection.
04280e85 2275 sesskey();
366dfa60 2276
1560760f 2277 // Do not bother admins with any formalities
df997f84 2278 if (is_siteadmin()) {
1560760f
AD
2279 //set accesstime or the user will appear offline which messes up messaging
2280 user_accesstime_log($course->id);
df997f84
PS
2281 return;
2282 }
2283
027a1604 2284 // Check that the user has agreed to a site policy if there is one
2285 if (!empty($CFG->sitepolicy)) {
df997f84
PS
2286 if ($preventredirect) {
2287 throw new require_login_exception('Policy not agreed');
2288 }
027a1604 2289 if (!$USER->policyagreed) {
957b5198 2290 $SESSION->wantsurl = $FULLME;
027a1604 2291 redirect($CFG->wwwroot .'/user/policy.php');
027a1604 2292 }
1695b680 2293 }
2294
df997f84 2295 // Fetch the system context, the course context, and prefetch its child contexts
21e2dcd9 2296 $sysctx = get_context_instance(CONTEXT_SYSTEM);
df997f84
PS
2297 $coursecontext = get_context_instance(CONTEXT_COURSE, $course->id, MUST_EXIST);
2298 if ($cm) {
2299 $cmcontext = get_context_instance(CONTEXT_MODULE, $cm->id, MUST_EXIST);
2300 } else {
2301 $cmcontext = null;
2302 }
21e2dcd9 2303
df997f84 2304 // If the site is currently under maintenance, then print a message
4fe2250a 2305 if (!empty($CFG->maintenance_enabled) and !has_capability('moodle/site:config', $sysctx)) {
df997f84
PS
2306 if ($preventredirect) {
2307 throw new require_login_exception('Maintenance in progress');
2308 }
2309
4fe2250a 2310 print_maintenance_message();
027a1604 2311 }
2312
df997f84
PS
2313 // make sure the course itself is not hidden
2314 if ($course->id == SITEID) {
2315 // frontpage can not be hidden
2316 } else {
f5c1e621 2317 if (is_role_switched($course->id)) {
df997f84
PS
2318 // when switching roles ignore the hidden flag - user had to be in course to do the switch
2319 } else {
2320 if (!$course->visible and !has_capability('moodle/course:viewhiddencourses', $coursecontext)) {
2321 // originally there was also test of parent category visibility,
2322 // BUT is was very slow in complex queries involving "my courses"
2323 // now it is also possible to simply hide all courses user is not enrolled in :-)
2324 if ($preventredirect) {
2325 throw new require_login_exception('Course is hidden');
2326 }
2327 notice(get_string('coursehidden'), $CFG->wwwroot .'/');
2328 }
2329 }
2330 }
2331
2332 // is the user enrolled?
2333 if ($course->id == SITEID) {
2334 // everybody is enrolled on the frontpage
2335
2336 } else {
2337 if (session_is_loggedinas()) {
2338 // Make sure the REAL person can access this course first
2339 $realuser = session_get_realuser();
2340 if (!is_enrolled($coursecontext, $realuser->id, '', true) and !is_viewing($coursecontext, $realuser->id) and !is_siteadmin($realuser->id)) {
2341 if ($preventredirect) {
2342 throw new require_login_exception('Invalid course login-as access');
2343 }
2344 echo $OUTPUT->header();
2345 notice(get_string('studentnotallowed', '', fullname($USER, true)), $CFG->wwwroot .'/');
2346 }
2347 }
2348
2349 // very simple enrolment caching - changes in course setting are not reflected immediately
2350 if (!isset($USER->enrol)) {
2351 $USER->enrol = array();
2352 $USER->enrol['enrolled'] = array();
2353 $USER->enrol['tempguest'] = array();
2354 }
2355
2356 $access = false;
2357
2358 if (is_viewing($coursecontext, $USER)) {
2359 // ok, no need to mess with enrol
2360 $access = true;
2361
2362 } else {
2363 if (isset($USER->enrol['enrolled'][$course->id])) {
2364 if ($USER->enrol['enrolled'][$course->id] == 0) {
2365 $access = true;
2366 } else if ($USER->enrol['enrolled'][$course->id] > time()) {
2367 $access = true;
2368 } else {
2369 //expired
2370 unset($USER->enrol['enrolled'][$course->id]);
2371 }
2372 }
2373 if (isset($USER->enrol['tempguest'][$course->id])) {
2374 if ($USER->enrol['tempguest'][$course->id] == 0) {
2375 $access = true;
2376 } else if ($USER->enrol['tempguest'][$course->id] > time()) {
2377 $access = true;
2378 } else {
2379 //expired
2380 unset($USER->enrol['tempguest'][$course->id]);
2381 $USER->access = remove_temp_roles($coursecontext, $USER->access);
2382 }
2383 }
2384
2385 if ($access) {
2386 // cache ok
2387 } else if (is_enrolled($coursecontext, $USER, '', true)) {
2388 // active participants may always access
2389 // TODO: refactor this into some new function
2390 $now = time();
2391 $sql = "SELECT MAX(ue.timeend)
2392 FROM {user_enrolments} ue
2393 JOIN {enrol} e ON (e.id = ue.enrolid AND e.courseid = :courseid)
2394 JOIN {user} u ON u.id = ue.userid
2395 WHERE ue.userid = :userid AND ue.status = :active AND e.status = :enabled AND u.deleted = 0
2396 AND ue.timestart < :now1 AND (ue.timeend = 0 OR ue.timeend > :now2)";
2397 $params = array('enabled'=>ENROL_INSTANCE_ENABLED, 'active'=>ENROL_USER_ACTIVE,
2398 'userid'=>$USER->id, 'courseid'=>$coursecontext->instanceid, 'now1'=>$now, 'now2'=>$now);
2399 $until = $DB->get_field_sql($sql, $params);
2400 if (!$until or $until > time() + ENROL_REQUIRE_LOGIN_CACHE_PERIOD) {
2401 $until = time() + ENROL_REQUIRE_LOGIN_CACHE_PERIOD;
2402 }
2403
2404 $USER->enrol['enrolled'][$course->id] = $until;
2405 $access = true;
2406
2407 // remove traces of previous temp guest access
2408 $USER->access = remove_temp_roles($coursecontext, $USER->access);
2409
2410 } else {
2411 $instances = $DB->get_records('enrol', array('courseid'=>$course->id, 'status'=>ENROL_INSTANCE_ENABLED), 'sortorder, id ASC');
2412 $enrols = enrol_get_plugins(true);
2413 // first ask all enabled enrol instances in course if they want to auto enrol user
2414 foreach($instances as $instance) {
2415 if (!isset($enrols[$instance->enrol])) {
2416 continue;
2417 }
2418 $until = $enrols[$instance->enrol]->try_autoenrol($instance);
2419 if ($until !== false) {
2420 $USER->enrol['enrolled'][$course->id] = $until;
2421 $USER->access = remove_temp_roles($coursecontext, $USER->access);
2422 $access = true;
2423 break;
2424 }
2425 }
2426 // if not enrolled yet try to gain temporary guest access
2427 if (!$access) {
2428 foreach($instances as $instance) {
2429 if (!isset($enrols[$instance->enrol])) {
2430 continue;
2431 }
2432 $until = $enrols[$instance->enrol]->try_guestaccess($instance);
2433 if ($until !== false) {
2434 $USER->enrol['tempguest'][$course->id] = $until;
2435 $access = true;
2436 break;
2437 }
2438 }
2439 }
2440 }
2441 }
2442
2443 if (!$access) {
2444 if ($preventredirect) {
2445 throw new require_login_exception('Not enrolled');
2446 }
2447 $SESSION->wantsurl = $FULLME;
2448 redirect($CFG->wwwroot .'/enrol/index.php?id='. $course->id);
2449 }
2450 }
2451
2452 // test visibility
2453 if ($cm && !$cm->visible && !has_capability('moodle/course:viewhiddenactivities', $cmcontext)) {
2454 if ($preventredirect) {
2455 throw new require_login_exception('Activity is hidden');
2456 }
2457 redirect($CFG->wwwroot, get_string('activityiscurrentlyhidden'));
2458 }
2459
2460 // groupmembersonly access control
98da6021 2461 if (!empty($CFG->enablegroupmembersonly) and $cm and $cm->groupmembersonly and !has_capability('moodle/site:accessallgroups', get_context_instance(CONTEXT_MODULE, $cm->id))) {
f8e3d5f0 2462 if (isguestuser() or !groups_has_membership($cm)) {
df997f84
PS
2463 if ($preventredirect) {
2464 throw new require_login_exception('Not member of a group');
2465 }
a8ee7194 2466 print_error('groupmembersonlyerror', 'group', $CFG->wwwroot.'/course/view.php?id='.$cm->course);
f8e3d5f0 2467 }
2468 }
1845f8b8 2469
82bd6a5e 2470 // Conditional activity access control
4f0c2d00 2471 if (!empty($CFG->enableavailability) and $cm) {
df997f84 2472 // TODO: this is going to work with login-as-user, sorry!
82bd6a5e 2473 // We cache conditional access in session
4f0c2d00 2474 if (!isset($SESSION->conditionaccessok)) {
013376de 2475 $SESSION->conditionaccessok = array();
82bd6a5e 2476 }
2477 // If you have been allowed into the module once then you are allowed
2478 // in for rest of session, no need to do conditional checks
013376de 2479 if (!array_key_exists($cm->id, $SESSION->conditionaccessok)) {
82bd6a5e 2480 // Get condition info (does a query for the availability table)
b3d960e6 2481 require_once($CFG->libdir.'/conditionlib.php');
013376de 2482 $ci = new condition_info($cm, CONDITION_MISSING_EXTRATABLE);
82bd6a5e 2483 // Check condition for user (this will do a query if the availability
2484 // information depends on grade or completion information)
4f0c2d00 2485 if ($ci->is_available($junk) || has_capability('moodle/course:viewhiddenactivities', $cmcontext)) {
013376de 2486 $SESSION->conditionaccessok[$cm->id] = true;
82bd6a5e 2487 } else {
2488 print_error('activityiscurrentlyhidden');
2489 }
2490 }
2491 }
2492
df997f84
PS
2493 // Finally access granted, update lastaccess times
2494 user_accesstime_log($course->id);
f9903ed0 2495}
2496
c4d0753b 2497
c4d0753b 2498/**
2499 * This function just makes sure a user is logged out.
2500 *
0d0a8bf6 2501 * @global object
c4d0753b 2502 */
2503function require_logout() {
dd9e22f8 2504 global $USER;
c4d0753b 2505
111e2360 2506 if (isloggedin()) {
c4d0753b 2507 add_to_log(SITEID, "user", "logout", "view.php?id=$USER->id&course=".SITEID, $USER->id, 0, $USER->id);
2508
533f7910 2509 $authsequence = get_enabled_auth_plugins(); // auths, in sequence
2510 foreach($authsequence as $authname) {
2511 $authplugin = get_auth_plugin($authname);
2512 $authplugin->prelogout_hook();
81693ac7 2513 }
c4d0753b 2514 }
2515
56949c17 2516 session_get_instance()->terminate_current();
c4d0753b 2517}
2518
7cf1c7bd 2519/**
0d0a8bf6 2520 * Weaker version of require_login()
2521 *
7cf1c7bd 2522 * This is a weaker version of {@link require_login()} which only requires login
2523 * when called from within a course rather than the site page, unless
2524 * the forcelogin option is turned on.
0d0a8bf6 2525 * @see require_login()
7cf1c7bd 2526 *
0d0a8bf6 2527 * @global object
33ebaf7c 2528 * @param mixed $courseorid The course object or id in question
bbd3f2c4 2529 * @param bool $autologinguest Allow autologin guests if that is wanted
4febb58f 2530 * @param object $cm Course activity module if known
f4013c10 2531 * @param bool $setwantsurltome Define if we want to set $SESSION->wantsurl, defaults to
2532 * true. Used to avoid (=false) some scripts (file.php...) to set that variable,
2533 * in order to keep redirects working properly. MDL-14495
df997f84
PS
2534 * @param bool $preventredirect set to true in scripts that can not redirect (CLI, rss feeds, etc.), throws exceptions
2535 * @return void
7cf1c7bd 2536 */
df997f84 2537function require_course_login($courseorid, $autologinguest = true, $cm = NULL, $setwantsurltome = true, $preventredirect = false) {
862940c0 2538 global $CFG, $PAGE, $SITE;
1596edff 2539 if (!empty($CFG->forcelogin)) {
33ebaf7c 2540 // login required for both SITE and courses
df997f84 2541 require_login($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
63c9ee99 2542
2543 } else if (!empty($cm) and !$cm->visible) {
2544 // always login for hidden activities
df997f84 2545 require_login($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
63c9ee99 2546
39de90ac 2547 } else if ((is_object($courseorid) and $courseorid->id == SITEID)
2548 or (!is_object($courseorid) and $courseorid == SITEID)) {
9950c88f 2549 //login for SITE not required
2550 if ($cm and empty($cm->visible)) {
2551 // hidden activities are not accessible without login
df997f84 2552 require_login($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
98da6021 2553 } else if ($cm and !empty($CFG->enablegroupmembersonly) and $cm->groupmembersonly) {
9950c88f 2554 // not-logged-in users do not have any group membership
df997f84 2555 require_login($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
9950c88f 2556 } else {
862940c0
SH
2557 // We still need to instatiate PAGE vars properly so that things
2558 // that rely on it like navigation function correctly.
2559 if (!empty($courseorid)) {
2560 if (is_object($courseorid)) {
2561 $course = $courseorid;
2562 } else {
2563 $course = clone($SITE);
2564 }
2565 if ($cm) {
df997f84
PS
2566 if ($cm->course != $course->id) {
2567 throw new coding_exception('course and cm parameters in require_course_login() call do not match!!');
2568 }
862940c0 2569 $PAGE->set_cm($cm, $course);
191b267b 2570 $PAGE->set_pagelayout('incourse');
862940c0
SH
2571 } else {
2572 $PAGE->set_course($course);
2573 }
2574 } else {
2575 // If $PAGE->course, and hence $PAGE->context, have not already been set
2576 // up properly, set them up now.
2577 $PAGE->set_course($PAGE->course);
2578 }
9950c88f 2579 //TODO: verify conditional activities here
2580 user_accesstime_log(SITEID);
2581 return;
2582 }
63c9ee99 2583
33ebaf7c 2584 } else {
2585 // course login always required
df997f84 2586 require_login($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
f950af3c 2587 }
2588}
2589
61c6071f 2590/**
2591 * Require key login. Function terminates with error if key not found or incorrect.
0d0a8bf6 2592 *
2593 * @global object
2594 * @global object
2595 * @global object
2596 * @global object
2597 * @uses NO_MOODLE_COOKIES
2598 * @uses PARAM_ALPHANUM
61c6071f 2599 * @param string $script unique script identifier
2600 * @param int $instance optional instance id
0d0a8bf6 2601 * @return int Instance ID
61c6071f 2602 */
2603function require_user_key_login($script, $instance=null) {
82dd4f42 2604 global $USER, $SESSION, $CFG, $DB;
61c6071f 2605
82dd4f42 2606 if (!NO_MOODLE_COOKIES) {
2f137aa1 2607 print_error('sessioncookiesdisable');
61c6071f 2608 }
2609
2610/// extra safety
2611 @session_write_close();
2612
2613 $keyvalue = required_param('key', PARAM_ALPHANUM);
2614
ae040d4b 2615 if (!$key = $DB->get_record('user_private_key', array('script'=>$script, 'value'=>$keyvalue, 'instance'=>$instance))) {
2f137aa1 2616 print_error('invalidkey');
61c6071f 2617 }
2618
2619 if (!empty($key->validuntil) and $key->validuntil < time()) {
2f137aa1 2620 print_error('expiredkey');
61c6071f 2621 }
2622
e436033f 2623 if ($key->iprestriction) {
765a1d4b
MD
2624 $remoteaddr = getremoteaddr(null);
2625 if (empty($remoteaddr) or !address_in_subnet($remoteaddr, $key->iprestriction)) {
2f137aa1 2626 print_error('ipmismatch');
e436033f 2627 }
61c6071f 2628 }
2629
ae040d4b 2630 if (!$user = $DB->get_record('user', array('id'=>$key->userid))) {
2f137aa1 2631 print_error('invaliduserid');
61c6071f 2632 }
2633
2634/// emulate normal session
27df7ae8 2635 session_set_user($user);
61c6071f 2636
e2fa911b 2637/// note we are not using normal login
2638 if (!defined('USER_KEY_LOGIN')) {
2639 define('USER_KEY_LOGIN', true);
2640 }
2641
792881f0 2642/// return instance id - it might be empty
61c6071f 2643 return $key->instance;
2644}
2645
2646/**
2647 * Creates a new private user access key.
0d0a8bf6 2648 *
2649 * @global object
61c6071f 2650 * @param string $script unique target identifier
2651 * @param int $userid
0d0a8bf6 2652 * @param int $instance optional instance id
61c6071f 2653 * @param string $iprestriction optional ip restricted access
2654 * @param timestamp $validuntil key valid only until given data
2655 * @return string access key value
2656 */
2657function create_user_key($script, $userid, $instance=null, $iprestriction=null, $validuntil=null) {
ae040d4b 2658 global $DB;
2659
61c6071f 2660 $key = new object();
2661 $key->script = $script;
2662 $key->userid = $userid;
2663 $key->instance = $instance;
2664 $key->iprestriction = $iprestriction;
2665 $key->validuntil = $validuntil;
2666 $key->timecreated = time();
2667
2668 $key->value = md5($userid.'_'.time().random_string(40)); // something long and unique
ae040d4b 2669 while ($DB->record_exists('user_private_key', array('value'=>$key->value))) {
61c6071f 2670 // must be unique
2671 $key->value = md5($userid.'_'.time().random_string(40));
2672 }
a8d6ef8c 2673 $DB->insert_record('user_private_key', $key);
61c6071f 2674 return $key->value;
2675}
2676
ffa3bfb3
AD
2677/**
2678 * Delete the user's new private user access keys for a particular script.
2679 *
2680 * @global object
2681 * @param string $script unique target identifier
2682 * @param int $userid
2683 * @return void
2684 */
2685function delete_user_key($script,$userid) {
2686 global $DB;
2687 $DB->delete_records('user_private_key', array('script'=>$script, 'userid'=>$userid));
2688}
2689
fe67f492
MD
2690/**
2691 * Gets a private user access key (and creates one if one doesn't exist).
2692 *
2693 * @global object
2694 * @param string $script unique target identifier
2695 * @param int $userid
2696 * @param int $instance optional instance id
2697 * @param string $iprestriction optional ip restricted access
2698 * @param timestamp $validuntil key valid only until given data
2699 * @return string access key value
2700 */
2701function get_user_key($script, $userid, $instance=null, $iprestriction=null, $validuntil=null) {
2702 global $DB;
2703
6b8ad965
PS
2704 if ($key = $DB->get_record('user_private_key', array('script'=>$script, 'userid'=>$userid,
2705 'instance'=>$instance, 'iprestriction'=>$iprestriction,
fe67f492
MD
2706 'validuntil'=>$validuntil))) {
2707 return $key->value;
2708 } else {
2709 return create_user_key($script, $userid, $instance, $iprestriction, $validuntil);
2710 }
2711}
2712
2713
7cf1c7bd 2714/**
2715 * Modify the user table by setting the currently logged in user's
2716 * last login to now.
2717 *
0d0a8bf6 2718 * @global object
2719 * @global object
2720 * @return bool Always returns true
7cf1c7bd 2721 */
1d881d92 2722function update_user_login_times() {
ae040d4b 2723 global $USER, $DB;
1d881d92 2724
53467aa6 2725 $user = new object();
1d881d92 2726 $USER->lastlogin = $user->lastlogin = $USER->currentlogin;
2a2f5f11 2727 $USER->currentlogin = $user->lastaccess = $user->currentlogin = time();
1d881d92 2728
2729 $user->id = $USER->id;
2730
013376de 2731 $DB->update_record('user', $user);
2732 return true;
1d881d92 2733}
2734
7cf1c7bd 2735/**
2736 * Determines if a user has completed setting up their account.
2737 *
efb8c375 2738 * @param user $user A {@link $USER} object to test for the existence of a valid name and email
bbd3f2c4 2739 * @return bool
7cf1c7bd 2740 */
808a3baa 2741function user_not_fully_set_up($user) {
999b54af
PS
2742 if (isguestuser($user)) {
2743 return false;
2744 }
2745 return (empty($user->firstname) or empty($user->lastname) or empty($user->email) or over_bounce_threshold($user));
bb64b51a 2746}
2747
0d0a8bf6 2748/**
2749 * Check whether the user has exceeded the bounce threshold
2750 *
2751 * @global object
2752 * @global object
2753 * @param user $user A {@link $USER} object
2754 * @return bool true=>User has exceeded bounce threshold
2755 */
bb64b51a 2756function over_bounce_threshold($user) {
ae040d4b 2757 global $CFG, $DB;
d2a9f7cc 2758
bb64b51a 2759 if (empty($CFG->handlebounces)) {
2760 return false;
2761 }
e0ec2d45 2762
2763 if (empty($user->id)) { /// No real (DB) user, nothing to do here.
2764 return false;
2765 }
2766
bb64b51a 2767 // set sensible defaults
2768 if (empty($CFG->minbounces)) {
2769 $CFG->minbounces = 10;
2770 }
2771 if (empty($CFG->bounceratio)) {
2772 $CFG->bounceratio = .20;
2773 }
2774 $bouncecount = 0;
2775 $sendcount = 0;
ae040d4b 2776 if ($bounce = $DB->get_record('user_preferences', array ('userid'=>$user->id, 'name'=>'email_bounce_count'))) {
bb64b51a 2777 $bouncecount = $bounce->value;
2778 }
ae040d4b 2779 if ($send = $DB->get_record('user_preferences', array('userid'=>$user->id, 'name'=>'email_send_count'))) {
bb64b51a 2780 $sendcount = $send->value;
2781 }
2782 return ($bouncecount >= $CFG->minbounces && $bouncecount/$sendcount >= $CFG->bounceratio);
2783}
2784
d2a9f7cc 2785/**
6759ad2f 2786 * Used to increment or reset email sent count
0d0a8bf6 2787 *
2788 * @global object
2789 * @param user $user object containing an id
2790 * @param bool $reset will reset the count to 0
2791 * @return void
bb64b51a 2792 */
2793function set_send_count($user,$reset=false) {
ae040d4b 2794 global $DB;
2795
e0ec2d45 2796 if (empty($user->id)) { /// No real (DB) user, nothing to do here.
2797 return;
2798 }
2799
ae040d4b 2800 if ($pref = $DB->get_record('user_preferences', array('userid'=>$user->id, 'name'=>'email_send_count'))) {
bb64b51a 2801 $pref->value = (!empty($reset)) ? 0 : $pref->value+1;
ae040d4b 2802 $DB->update_record('user_preferences', $pref);
bb64b51a 2803 }
2804 else if (!empty($reset)) { // if it's not there and we're resetting, don't bother.
2805 // make a new one
ae040d4b 2806 $pref = new object();
2807 $pref->name = 'email_send_count';
2808 $pref->value = 1;
bb64b51a 2809 $pref->userid = $user->id;
ae040d4b 2810 $DB->insert_record('user_preferences', $pref, false);
bb64b51a 2811 }
2812}
2813
d2a9f7cc 2814/**
6759ad2f 2815 * Increment or reset user's email bounce count
0d0a8bf6 2816 *
2817 * @global object
2818 * @param user $user object containing an id
2819 * @param bool $reset will reset the count to 0
bb64b51a 2820 */
2821function set_bounce_count($user,$reset=false) {
ae040d4b 2822 global $DB;
2823
2824 if ($pref = $DB->get_record('user_preferences', array('userid'=>$user->id, 'name'=>'email_bounce_count'))) {
bb64b51a 2825 $pref->value = (!empty($reset)) ? 0 : $pref->value+1;
ae040d4b 2826 $DB->update_record('user_preferences', $pref);
bb64b51a 2827 }
2828 else if (!empty($reset)) { // if it's not there and we're resetting, don't bother.
2829 // make a new one
ae040d4b 2830 $pref = new object();
2831 $pref->name = 'email_bounce_count';
2832 $pref->value = 1;
bb64b51a 2833 $pref->userid = $user->id;
ae040d4b 2834 $DB->insert_record('user_preferences', $pref, false);
bb64b51a 2835 }
808a3baa 2836}
f9903ed0 2837
7cf1c7bd 2838/**
2839 * Keeps track of login attempts
2840 *
0d0a8bf6 2841 * @global object
7cf1c7bd 2842 */
f9903ed0 2843function update_login_count() {
2844 global $SESSION;
2845
2846 $max_logins = 10;
2847
2848 if (empty($SESSION->logincount)) {
2849 $SESSION->logincount = 1;
2850 } else {
2851 $SESSION->logincount++;
2852 }
2853
2854 if ($SESSION->logincount > $max_logins) {
9fa49e22 2855 unset($SESSION->wantsurl);
a8ee7194 2856 print_error('errortoomanylogins');
d578afc8 2857 }
2858}
2859
7cf1c7bd 2860/**
2861 * Resets login attempts
2862 *
0d0a8bf6 2863 * @global object
7cf1c7bd 2864 */
9fa49e22 2865function reset_login_count() {
9fa49e22 2866 global $SESSION;
d578afc8 2867
9fa49e22 2868 $SESSION->logincount = 0;
d578afc8 2869}
2870
73efeff6 2871/**
2872 * Returns reference to full info about modules in course (including visibility).
2873 * Cached and as fast as possible (0 or 1 db query).
0d0a8bf6 2874 *
2875 * @global object
2876 * @global object
2877 * @global object
2878 * @uses CONTEXT_MODULE
2879 * @uses MAX_MODINFO_CACHE_SIZE
2880 * @param mixed $course object or 'reset' string to reset caches, modinfo may be updated in db
2881 * @param int $userid Defaults to current user id
73efeff6 2882 * @return mixed courseinfo object or nothing if resetting
2883 */
2884function &get_fast_modinfo(&$course, $userid=0) {
2885 global $CFG, $USER, $DB;
2886 require_once($CFG->dirroot.'/course/lib.php');
2887
2888 if (!empty($CFG->enableavailability)) {
2889 require_once($CFG->libdir.'/conditionlib.php');
2890 }
2891
2892 static $cache = array();
2893
2894 if ($course === 'reset') {
2895 $cache = array();
2896 $nothing = null;
2897 return $nothing; // we must return some reference
2898 }
2899
2900 if (empty($userid)) {
2901 $userid = $USER->id;
2902 }
2903
2904 if (array_key_exists($course->id, $cache) and $cache[$course->id]->userid == $userid) {
2905 return $cache[$course->id];
2906 }
2907
2908 if (empty($course->modinfo)) {
2909 // no modinfo yet - load it
2910 rebuild_course_cache($course->id);
2911 $course->modinfo = $DB->get_field('course', 'modinfo', array('id'=>$course->id));
2912 }
2913
2914 $modinfo = new object();
2915 $modinfo->courseid = $course->id;
2916 $modinfo->userid = $userid;
2917 $modinfo->sections = array();
2918 $modinfo->cms = array();
2919 $modinfo->instances = array();
2920 $modinfo->groups = null; // loaded only when really needed - the only one db query
2921
2922 $info = unserialize($course->modinfo);
2923 if (!is_array($info)) {
2924 // hmm, something is wrong - lets try to fix it
2925 rebuild_course_cache($course->id);
2926 $course->modinfo = $DB->get_field('course', 'modinfo', array('id'=>$course->id));
2927 $info = unserialize($course->modinfo);
2928 if (!is_array($info)) {
2929 return $modinfo;
2930 }
2931 }
2932
2933 if ($info) {
2934 // detect if upgrade required
2935 $first = reset($info);
2936 if (!isset($first->id)) {
2937 rebuild_course_cache($course->id);
2938 $course->modinfo = $DB->get_field('course', 'modinfo', array('id'=>$course->id));
2939 $info = unserialize($course->modinfo);
2940 if (!is_array($info)) {
2941 return $modinfo;
2942 }
2943 }
2944 }
2945
2946 $modlurals = array();
2947
2948 // If we haven't already preloaded contexts for the course, do it now
2949 preload_course_contexts($course->id);
2950
2951 foreach ($info as $mod) {
2952 if (empty($mod->name)) {
2953 // something is wrong here
2954 continue;
2955 }
2956 // reconstruct minimalistic $cm
2957 $cm = new object();
2958 $cm->id = $mod->cm;
2959 $cm->instance = $mod->id;
2960 $cm->course = $course->id;
2961 $cm->modname = $mod->mod;
66b250fd 2962 $cm->idnumber = $mod->idnumber;
9a9012dc 2963 $cm->name = $mod->name;
73efeff6 2964 $cm->visible = $mod->visible;
2965 $cm->sectionnum = $mod->section;
2966 $cm->groupmode = $mod->groupmode;
2967 $cm->groupingid = $mod->groupingid;
2968 $cm->groupmembersonly = $mod->groupmembersonly;
2969 $cm->indent = $mod->indent;
2970 $cm->completion = $mod->completion;
9a9012dc 2971 $cm->extra = isset($mod->extra) ? $mod->extra : '';
73efeff6 2972 $cm->icon = isset($mod->icon) ? $mod->icon : '';
9a9012dc 2973 $cm->iconcomponent = isset($mod->iconcomponent) ? $mod->iconcomponent : '';
73efeff6 2974 $cm->uservisible = true;
2975 if(!empty($CFG->enableavailability)) {
2976 // We must have completion information from modinfo. If it's not
2977 // there, cache needs rebuilding
2978 if(!isset($mod->availablefrom)) {
2979 debugging('enableavailability option was changed; rebuilding '.
2980 'cache for course '.$course->id);
2981 rebuild_course_cache($course->id,true);
2982 // Re-enter this routine to do it all properly
2983 return get_fast_modinfo($course,$userid);
2984 }
2985 $cm->availablefrom = $mod->availablefrom;
2986 $cm->availableuntil = $mod->availableuntil;
2987 $cm->showavailability = $mod->showavailability;
2988 $cm->conditionscompletion = $mod->conditionscompletion;
2989 $cm->conditionsgrade = $mod->conditionsgrade;
2990 }
2991
2992 // preload long names plurals and also check module is installed properly
2993 if (!isset($modlurals[$cm->modname])) {
2994 if (!file_exists("$CFG->dirroot/mod/$cm->modname/lib.php")) {
2995 continue;
2996 }
2997 $modlurals[$cm->modname] = get_string('modulenameplural', $cm->modname);
2998 }
2999 $cm->modplural = $modlurals[$cm->modname];
3000 $modcontext = get_context_instance(CONTEXT_MODULE,$cm->id);
6759ad2f 3001
73efeff6 3002 if(!empty($CFG->enableavailability)) {
6759ad2f 3003 // Unfortunately the next call really wants to call
3004 // get_fast_modinfo, but that would be recursive, so we fake up a
73efeff6 3005 // modinfo for it already
3006 if(empty($minimalmodinfo)) {
3007 $minimalmodinfo=new stdClass();
3008 $minimalmodinfo->cms=array();
3009 foreach($info as $mod) {
fc61cecd
PS
3010 if (empty($mod->name)) {
3011 // something is wrong here
3012 continue;
3013 }
9a9012dc
PS
3014 $minimalcm = new stdClass();
3015 $minimalcm->id = $mod->cm;
3016 $minimalcm->name = $mod->name;
73efeff6 3017 $minimalmodinfo->cms[$minimalcm->id]=$minimalcm;
3018 }
3019 }
3020
3021 // Get availability information
3022 $ci = new condition_info($cm);
9a9012dc 3023 $cm->available=$ci->is_available($cm->availableinfo, true, $userid, $minimalmodinfo);
73efeff6 3024 } else {
3025 $cm->available=true;
3026 }
3027 if ((!$cm->visible or !$cm->available) and !has_capability('moodle/course:viewhiddenactivities', $modcontext, $userid)) {
3028 $cm->uservisible = false;
3029
98da6021 3030 } else if (!empty($CFG->enablegroupmembersonly) and !empty($cm->groupmembersonly)
73efeff6 3031 and !has_capability('moodle/site:accessallgroups', $modcontext, $userid)) {
3032 if (is_null($modinfo->groups)) {
3033 $modinfo->groups = groups_get_user_groups($course->id, $userid);
3034 }
3035 if (empty($modinfo->groups[$cm->groupingid])) {
3036 $cm->uservisible = false;
3037 }
3038 }
3039
3040 if (!isset($modinfo->instances[$cm->modname])) {
3041 $modinfo->instances[$cm->modname] = array();
3042 }
3043 $modinfo->instances[$cm->modname][$cm->instance] =& $cm;
3044 $modinfo->cms[$cm->id] =& $cm;
3045
3046 // reconstruct sections
3047 if (!isset($modinfo->sections[$cm->sectionnum])) {
3048 $modinfo->sections[$cm->sectionnum] = array();
3049 }
3050 $modinfo->sections[$cm->sectionnum][] = $cm->id;
3051
3052 unset($cm);
3053 }
3054
3055 unset($cache[$course->id]); // prevent potential reference problems when switching users
3056 $cache[$course->id] = $modinfo;
3057
3058 // Ensure cache does not use too much RAM
3059 if (count($cache) > MAX_MODINFO_CACHE_SIZE) {
d4ff178f 3060 reset($cache);
3061 $key = key($cache);
3062 unset($cache[$key]);
73efeff6 3063 }
3064
3065 return $cache[$course->id];
3066}
3067
7cf1c7bd 3068/**
e6260a45 3069 * Determines if the currently logged in user is in editing mode.
3070 * Note: originally this function had $userid parameter - it was not usable anyway
7cf1c7bd 3071 *
0d0a8bf6 3072 * @deprecated since Moodle 2.0 - use $PAGE->user_is_editing() instead.
3073 * @todo Deprecated function remove when ready
3074 *
3075 * @global object
3076 * @uses DEBUG_DEVELOPER
bbd3f2c4 3077 * @return bool
7cf1c7bd 3078 */
0df35335 3079function isediting() {
830dd6e9 3080 global $PAGE;
3081 debugging('call to deprecated function isediting(). Please use $PAGE->user_is_editing() instead', DEBUG_DEVELOPER);
3082 return $PAGE->user_is_editing();
2c309dc2 3083}
3084
7cf1c7bd 3085/**
3086 * Determines if the logged in user is currently moving an activity
3087 *
0d0a8bf6 3088 * @global object
c6d15803 3089 * @param int $courseid The id of the course being tested
bbd3f2c4 3090 * @return bool
7cf1c7bd 3091 */
7977cffd 3092function ismoving($courseid) {
7977cffd 3093 global $USER;
3094
3095 if (!empty($USER->activitycopy)) {
3096 return ($USER->activitycopycourse == $courseid);
3097 }
3098 return false;
3099}
3100
7cf1c7bd 3101/**
0d0a8bf6 3102 * Returns a persons full name
3103 *
7cf1c7bd 3104 * Given an object containing firstname and lastname
3105 * values, this function returns a string with the
3106 * full name of the person.
3107 * The result may depend on system settings
3108 * or language. 'override' will force both names
361855e6 3109 * to be used even if system settings specify one.
68fbd8e1 3110 *
0d0a8bf6 3111 * @global object
3112 * @global object
68fbd8e1 3113 * @param object $user A {@link $USER} object to get full name of
3114 * @param bool $override If true then the name will be first name followed by last name rather than adhering to fullnamedisplay setting.
0d0a8bf6 3115 * @return string
7cf1c7bd 3116 */
e2cd5065 3117function fullname($user, $override=false) {
f374fb10 3118 global $CFG, $SESSION;
3119
6527c077 3120 if (!isset($user->firstname) and !isset($user->lastname)) {
3121 return '';
3122 }
3123
4c202228 3124 if (!$override) {
3125 if (!empty($CFG->forcefirstname)) {
3126 $user->firstname = $CFG->forcefirstname;
3127 }
3128 if (!empty($CFG->forcelastname)) {
3129 $user->lastname = $CFG->forcelastname;
3130 }
3131 }
3132
f374fb10 3133 if (!empty($SESSION->fullnamedisplay)) {
3134 $CFG->fullnamedisplay = $SESSION->fullnamedisplay;
3135 }
e2cd5065 3136
775f811a 3137 if (!isset($CFG->fullnamedisplay) or $CFG->fullnamedisplay === 'firstname lastname') {
b0ccd3fb 3138 return $user->firstname .' '. $user->lastname;
b5cbb64d 3139
3140 } else if ($CFG->fullnamedisplay == 'lastname firstname') {
b0ccd3fb 3141 return $user->lastname .' '. $user->firstname;
e2cd5065 3142
b5cbb64d 3143 } else if ($CFG->fullnamedisplay == 'firstname') {
3144 if ($override) {
3145 return get_string('fullnamedisplay', '', $user);
3146 } else {
3147 return $user->firstname;
3148 }
3149 }
e2cd5065 3150
b5cbb64d 3151 return get_string('fullnamedisplay', '', $user);
e2cd5065 3152}
3153
7cf1c7bd 3154/**
03d820c7 3155 * Returns whether a given authentication plugin exists.
7cf1c7bd 3156 *
0d0a8bf6 3157 * @global object
03d820c7 3158 * @param string $auth Form of authentication to check for. Defaults to the
3159 * global setting in {@link $CFG}.
3160 * @return boolean Whether the plugin is available.
7cf1c7bd 3161 */
16793340 3162function exists_auth_plugin($auth) {
03d820c7 3163 global $CFG;
5e623a33 3164
03d820c7 3165 if (file_exists("{$CFG->dirroot}/auth/$auth/auth.php")) {
3166 return is_readable("{$CFG->dirroot}/auth/$auth/auth.php");
3167 }
3168 return false;
3169}
ba7166c3 3170
03d820c7 3171/**
3172 * Checks if a given plugin is in the list of enabled authentication plugins.
5e623a33 3173 *
03d820c7 3174 * @param string $auth Authentication plugin.
3175 * @return boolean Whether the plugin is enabled.
3176 */
16793340 3177function is_enabled_auth($auth) {
16793340 3178 if (empty($auth)) {
3179 return false;
03d820c7 3180 }
16793340 3181
c7b10b5f 3182 $enabled = get_enabled_auth_plugins();
3183
3184 return in_array($auth, $enabled);
03d820c7 3185}
3186
3187/**
3188 * Returns an authentication plugin instance.
3189 *
0d0a8bf6 3190 * @global object