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