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