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