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