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