Tidy-ups
[moodle.git] / lib / moodlelib.php
CommitLineData
ef1e97c7 1<?php // $Id$
f9903ed0 2
bbbf2d40 3// this needs to be changed back
4require_once('accesslib.php');
5
9fa49e22 6///////////////////////////////////////////////////////////////////////////
7// //
8// NOTICE OF COPYRIGHT //
9// //
10// Moodle - Modular Object-Oriented Dynamic Learning Environment //
abc3b857 11// http://moodle.org //
9fa49e22 12// //
abc3b857 13// Copyright (C) 1999-2004 Martin Dougiamas http://dougiamas.com //
9fa49e22 14// //
15// This program is free software; you can redistribute it and/or modify //
16// it under the terms of the GNU General Public License as published by //
17// the Free Software Foundation; either version 2 of the License, or //
18// (at your option) any later version. //
19// //
20// This program is distributed in the hope that it will be useful, //
21// but WITHOUT ANY WARRANTY; without even the implied warranty of //
22// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the //
23// GNU General Public License for more details: //
24// //
25// http://www.gnu.org/copyleft/gpl.html //
26// //
27///////////////////////////////////////////////////////////////////////////
65ccdd8c 28
7cf1c7bd 29/**
89dcb99d 30 * moodlelib.php - Moodle main library
7cf1c7bd 31 *
32 * Main library file of miscellaneous general-purpose Moodle functions.
33 * Other main libraries:
8c3dba73 34 * - weblib.php - functions that produce web output
35 * - datalib.php - functions that access the database
7cf1c7bd 36 * @author Martin Dougiamas
37 * @version $Id$
89dcb99d 38 * @license http://www.gnu.org/copyleft/gpl.html GNU Public License
7cf1c7bd 39 * @package moodlecore
40 */
e1ecf0a0 41
bbd3f2c4 42/// CONSTANTS (Encased in phpdoc proper comments)/////////////////////////
f374fb10 43
6b94a807 44/**
45 * Used by some scripts to check they are being called by Moodle
46 */
47define('MOODLE_INTERNAL', true);
48
7cf1c7bd 49/**
50 * No groups used?
51 */
d8ba183c 52define('NOGROUPS', 0);
7cf1c7bd 53
54/**
55 * Groups used?
56 */
f374fb10 57define('SEPARATEGROUPS', 1);
7cf1c7bd 58
59/**
60 * Groups visible?
61 */
f374fb10 62define('VISIBLEGROUPS', 2);
63
bbd3f2c4 64/// Date and time constants ///
7a5672c9 65/**
2f87145b 66 * Time constant - the number of seconds in a week
7a5672c9 67 */
361855e6 68define('WEEKSECS', 604800);
2f87145b 69
70/**
71 * Time constant - the number of seconds in a day
72 */
7a5672c9 73define('DAYSECS', 86400);
2f87145b 74
75/**
76 * Time constant - the number of seconds in an hour
77 */
7a5672c9 78define('HOURSECS', 3600);
2f87145b 79
80/**
81 * Time constant - the number of seconds in a minute
82 */
7a5672c9 83define('MINSECS', 60);
2f87145b 84
85/**
86 * Time constant - the number of minutes in a day
87 */
7a5672c9 88define('DAYMINS', 1440);
2f87145b 89
90/**
91 * Time constant - the number of minutes in an hour
92 */
7a5672c9 93define('HOURMINS', 60);
f9903ed0 94
c59733ef 95/// Parameter constants - every call to optional_param(), required_param() ///
96/// or clean_param() should have a specified type of parameter. //////////////
97
e0d346ff 98/**
038ba6aa 99 * PARAM_RAW specifies a parameter that is not cleaned/processed in any way;
100 * originally was 0, but changed because we need to detect unknown
101 * parameter types and swiched order in clean_param().
e0d346ff 102 */
038ba6aa 103define('PARAM_RAW', 666);
bbd3f2c4 104
105/**
c59733ef 106 * PARAM_CLEAN - obsoleted, please try to use more specific type of parameter.
107 * It was one of the first types, that is why it is abused so much ;-)
bbd3f2c4 108 */
2ae28153 109define('PARAM_CLEAN', 0x0001);
bbd3f2c4 110
111/**
c59733ef 112 * PARAM_INT - integers only, use when expecting only numbers.
bbd3f2c4 113 */
2ae28153 114define('PARAM_INT', 0x0002);
bbd3f2c4 115
116/**
117 * PARAM_INTEGER - an alias for PARAM_INT
118 */
119define('PARAM_INTEGER', 0x0002);
120
121/**
c59733ef 122 * PARAM_ALPHA - contains only english letters.
bbd3f2c4 123 */
2ae28153 124define('PARAM_ALPHA', 0x0004);
bbd3f2c4 125
126/**
c59733ef 127 * PARAM_ACTION - an alias for PARAM_ALPHA, use for various actions in formas and urls
128 * @TODO: should we alias it to PARAM_ALPHANUM ?
bbd3f2c4 129 */
130define('PARAM_ACTION', 0x0004);
131
132/**
c59733ef 133 * PARAM_FORMAT - an alias for PARAM_ALPHA, use for names of plugins, formats, etc.
134 * @TODO: should we alias it to PARAM_ALPHANUM ?
bbd3f2c4 135 */
136define('PARAM_FORMAT', 0x0004);
137
138/**
c59733ef 139 * PARAM_NOTAGS - all html tags are stripped from the text. Do not abuse this type.
bbd3f2c4 140 */
2ae28153 141define('PARAM_NOTAGS', 0x0008);
bbd3f2c4 142
143/**
c59733ef 144 * PARAM_FILE - safe file name, all dangerous chars are stripped, protects against XSS, SQL injections and directory traversals
bbd3f2c4 145 */
2ae28153 146define('PARAM_FILE', 0x0010);
bbd3f2c4 147
148/**
c59733ef 149 * PARAM_PATH - safe relative path name, all dangerous chars are stripped, protects against XSS, SQL injections and directory traversals
150 * note: the leading slash is not removed, window drive letter is not allowed
bbd3f2c4 151 */
2ae28153 152define('PARAM_PATH', 0x0020);
bbd3f2c4 153
154/**
c59733ef 155 * PARAM_HOST - expected fully qualified domain name (FQDN) or an IPv4 dotted quad (IP address)
bbd3f2c4 156 */
157define('PARAM_HOST', 0x0040);
158
159/**
c59733ef 160 * PARAM_URL - expected properly formatted URL.
bbd3f2c4 161 */
2ae28153 162define('PARAM_URL', 0x0080);
bbd3f2c4 163
164/**
c59733ef 165 * 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 166 */
167define('PARAM_LOCALURL', 0x0180);
168
169/**
c59733ef 170 * PARAM_CLEANFILE - safe file name, all dangerous and regional chars are removed,
171 * use when you want to store a new file submitted by students
bbd3f2c4 172 */
14d6c233 173define('PARAM_CLEANFILE',0x0200);
e0d346ff 174
8bd3fad3 175/**
c59733ef 176 * PARAM_ALPHANUM - expected numbers and letters only.
bbd3f2c4 177 */
178define('PARAM_ALPHANUM', 0x0400);
179
180/**
c59733ef 181 * PARAM_BOOL - converts input into 0 or 1, use for switches in forms and urls.
bbd3f2c4 182 */
183define('PARAM_BOOL', 0x0800);
184
185/**
c59733ef 186 * PARAM_CLEANHTML - cleans submitted HTML code and removes slashes
187 * note: do not forget to addslashes() before storing into database!
bbd3f2c4 188 */
189define('PARAM_CLEANHTML',0x1000);
190
191/**
c59733ef 192 * PARAM_ALPHAEXT the same contents as PARAM_ALPHA plus the chars in quotes: "/-_" allowed,
193 * suitable for include() and require()
194 * @TODO: should we rename this function to PARAM_SAFEDIRS??
bbd3f2c4 195 */
196define('PARAM_ALPHAEXT', 0x2000);
197
198/**
c59733ef 199 * PARAM_SAFEDIR - safe directory name, suitable for include() and require()
bbd3f2c4 200 */
201define('PARAM_SAFEDIR', 0x4000);
202
0e4af166 203/**
204 * PARAM_SEQUENCE - expects a sequence of numbers like 8 to 1,5,6,4,6,8,9. Numbers and comma only.
205 */
206define('PARAM_SEQUENCE', 0x8000);
207
bbd3f2c4 208/// Page types ///
209/**
210 * PAGE_COURSE_VIEW is a definition of a page type. For more information on the page class see moodle/lib/pagelib.php.
8bd3fad3 211 */
212define('PAGE_COURSE_VIEW', 'course-view');
8bd3fad3 213
bbd3f2c4 214
9fa49e22 215/// PARAMETER HANDLING ////////////////////////////////////////////////////
6b174680 216
e0d346ff 217/**
361855e6 218 * Returns a particular value for the named variable, taken from
219 * POST or GET. If the parameter doesn't exist then an error is
e0d346ff 220 * thrown because we require this variable.
221 *
361855e6 222 * This function should be used to initialise all required values
223 * in a script that are based on parameters. Usually it will be
e0d346ff 224 * used like this:
225 * $id = required_param('id');
226 *
a083b93c 227 * @param string $parname the name of the page parameter we want
228 * @param int $type expected type of parameter
e0d346ff 229 * @return mixed
230 */
a083b93c 231function required_param($parname, $type=PARAM_CLEAN) {
e0d346ff 232
5d7a9f56 233 // detect_unchecked_vars addition
234 global $CFG;
235 if (!empty($CFG->detect_unchecked_vars)) {
236 global $UNCHECKED_VARS;
a083b93c 237 unset ($UNCHECKED_VARS->vars[$parname]);
5d7a9f56 238 }
239
a083b93c 240 if (isset($_POST[$parname])) { // POST has precedence
241 $param = $_POST[$parname];
242 } else if (isset($_GET[$parname])) {
243 $param = $_GET[$parname];
e0d346ff 244 } else {
a083b93c 245 error('A required parameter ('.$parname.') was missing');
e0d346ff 246 }
247
a083b93c 248 return clean_param($param, $type);
e0d346ff 249}
250
251/**
361855e6 252 * Returns a particular value for the named variable, taken from
e0d346ff 253 * POST or GET, otherwise returning a given default.
254 *
361855e6 255 * This function should be used to initialise all optional values
256 * in a script that are based on parameters. Usually it will be
e0d346ff 257 * used like this:
258 * $name = optional_param('name', 'Fred');
259 *
a083b93c 260 * @param string $parname the name of the page parameter we want
e0d346ff 261 * @param mixed $default the default value to return if nothing is found
a083b93c 262 * @param int $type expected type of parameter
e0d346ff 263 * @return mixed
264 */
a083b93c 265function optional_param($parname, $default=NULL, $type=PARAM_CLEAN) {
e0d346ff 266
5d7a9f56 267 // detect_unchecked_vars addition
268 global $CFG;
269 if (!empty($CFG->detect_unchecked_vars)) {
270 global $UNCHECKED_VARS;
a083b93c 271 unset ($UNCHECKED_VARS->vars[$parname]);
5d7a9f56 272 }
273
a083b93c 274 if (isset($_POST[$parname])) { // POST has precedence
275 $param = $_POST[$parname];
276 } else if (isset($_GET[$parname])) {
277 $param = $_GET[$parname];
e0d346ff 278 } else {
279 return $default;
280 }
281
a083b93c 282 return clean_param($param, $type);
e0d346ff 283}
284
285/**
361855e6 286 * Used by {@link optional_param()} and {@link required_param()} to
287 * clean the variables and/or cast to specific types, based on
e0d346ff 288 * an options field.
bbd3f2c4 289 * <code>
290 * $course->format = clean_param($course->format, PARAM_ALPHA);
291 * $selectedgrade_item = clean_param($selectedgrade_item, PARAM_CLEAN);
292 * </code>
e0d346ff 293 *
bbd3f2c4 294 * @uses $CFG
295 * @uses PARAM_CLEAN
296 * @uses PARAM_INT
297 * @uses PARAM_INTEGER
298 * @uses PARAM_ALPHA
299 * @uses PARAM_ALPHANUM
300 * @uses PARAM_NOTAGS
f4f65990 301 * @uses PARAM_ALPHAEXT
bbd3f2c4 302 * @uses PARAM_BOOL
303 * @uses PARAM_SAFEDIR
304 * @uses PARAM_CLEANFILE
305 * @uses PARAM_FILE
306 * @uses PARAM_PATH
307 * @uses PARAM_HOST
308 * @uses PARAM_URL
309 * @uses PARAM_LOCALURL
310 * @uses PARAM_CLEANHTML
0e4af166 311 * @uses PARAM_SEQUENCE
e0d346ff 312 * @param mixed $param the variable we are cleaning
a083b93c 313 * @param int $type expected format of param after cleaning.
e0d346ff 314 * @return mixed
315 */
a083b93c 316function clean_param($param, $type) {
e0d346ff 317
7744ea12 318 global $CFG;
319
80bfd470 320 if (is_array($param)) { // Let's loop
321 $newparam = array();
322 foreach ($param as $key => $value) {
a083b93c 323 $newparam[$key] = clean_param($value, $type);
80bfd470 324 }
325 return $newparam;
326 }
327
a083b93c 328 switch ($type) {
96e98ea6 329 case PARAM_RAW: // no cleaning at all
330 return $param;
331
a083b93c 332 case PARAM_CLEAN: // General HTML cleaning, try to use more specific type if possible
333 if (is_numeric($param)) {
334 return $param;
335 }
336 $param = stripslashes($param); // Needed for kses to work fine
337 $param = clean_text($param); // Sweep for scripts, etc
338 return addslashes($param); // Restore original request parameter slashes
3af57507 339
a083b93c 340 case PARAM_CLEANHTML: // prepare html fragment for display, do not store it into db!!
341 $param = stripslashes($param); // Remove any slashes
342 $param = clean_text($param); // Sweep for scripts, etc
343 return trim($param);
e0d346ff 344
a083b93c 345 case PARAM_INT:
346 return (int)$param; // Convert to integer
e0d346ff 347
a083b93c 348 case PARAM_ALPHA: // Remove everything not a-z
349 return eregi_replace('[^a-zA-Z]', '', $param);
e0d346ff 350
a083b93c 351 case PARAM_ALPHANUM: // Remove everything not a-zA-Z0-9
352 return eregi_replace('[^A-Za-z0-9]', '', $param);
f24148ef 353
a083b93c 354 case PARAM_ALPHAEXT: // Remove everything not a-zA-Z/_-
355 return eregi_replace('[^a-zA-Z/_-]', '', $param);
0ed442f8 356
0e4af166 357 case PARAM_SEQUENCE: // Remove everything not 0-9,
358 return eregi_replace('[^0-9,]', '', $param);
359
a083b93c 360 case PARAM_BOOL: // Convert to 1 or 0
361 $tempstr = strtolower($param);
eb59ac27 362 if ($tempstr == 'on' or $tempstr == 'yes' ) {
a083b93c 363 $param = 1;
eb59ac27 364 } else if ($tempstr == 'off' or $tempstr == 'no') {
a083b93c 365 $param = 0;
366 } else {
367 $param = empty($param) ? 0 : 1;
368 }
369 return $param;
f24148ef 370
a083b93c 371 case PARAM_NOTAGS: // Strip all tags
372 return strip_tags($param);
3af57507 373
a083b93c 374 case PARAM_SAFEDIR: // Remove everything not a-zA-Z0-9_-
375 return eregi_replace('[^a-zA-Z0-9_-]', '', $param);
95bfd207 376
a083b93c 377 case PARAM_CLEANFILE: // allow only safe characters
378 return clean_filename($param);
14d6c233 379
a083b93c 380 case PARAM_FILE: // Strip all suspicious characters from filename
381 $param = ereg_replace('[[:cntrl:]]|[<>"`\|\':\\/]', '', $param);
382 $param = ereg_replace('\.\.+', '', $param);
383 if($param == '.') {
371a2ed0 384 $param = '';
385 }
a083b93c 386 return $param;
387
388 case PARAM_PATH: // Strip all suspicious characters from file path
389 $param = str_replace('\\\'', '\'', $param);
390 $param = str_replace('\\"', '"', $param);
391 $param = str_replace('\\', '/', $param);
392 $param = ereg_replace('[[:cntrl:]]|[<>"`\|\':]', '', $param);
393 $param = ereg_replace('\.\.+', '', $param);
394 $param = ereg_replace('//+', '/', $param);
395 return ereg_replace('/(\./)+', '/', $param);
396
397 case PARAM_HOST: // allow FQDN or IPv4 dotted quad
398 preg_replace('/[^\.\d\w-]/','', $param ); // only allowed chars
399 // match ipv4 dotted quad
400 if (preg_match('/(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})/',$param, $match)){
401 // confirm values are ok
402 if ( $match[0] > 255
403 || $match[1] > 255
404 || $match[3] > 255
405 || $match[4] > 255 ) {
406 // hmmm, what kind of dotted quad is this?
407 $param = '';
408 }
409 } elseif ( preg_match('/^[\w\d\.-]+$/', $param) // dots, hyphens, numbers
410 && !preg_match('/^[\.-]/', $param) // no leading dots/hyphens
411 && !preg_match('/[\.-]$/', $param) // no trailing dots/hyphens
412 ) {
413 // all is ok - $param is respected
414 } else {
415 // all is not ok...
416 $param='';
417 }
418 return $param;
7744ea12 419
a083b93c 420 case PARAM_URL: // allow safe ftp, http, mailto urls
421 include_once($CFG->dirroot . '/lib/validateurlsyntax.php');
422 if (!empty($param) && validateUrlSyntax($param, 's?H?S?F?E?u-P-a?I?p-f?q?r?')) {
423 // all is ok, param is respected
d2a9f7cc 424 } else {
a083b93c 425 $param =''; // not really ok
426 }
427 return $param;
428
429 case PARAM_LOCALURL: // allow http absolute, root relative and relative URLs within wwwroot
430 clean_param($param, PARAM_URL);
431 if (!empty($param)) {
432 if (preg_match(':^/:', $param)) {
433 // root-relative, ok!
434 } elseif (preg_match('/^'.preg_quote($CFG->wwwroot, '/').'/i',$param)) {
435 // absolute, and matches our wwwroot
7744ea12 436 } else {
a083b93c 437 // relative - let's make sure there are no tricks
438 if (validateUrlSyntax($param, 's-u-P-a-p-f+q?r?')) {
439 // looks ok.
440 } else {
441 $param = '';
442 }
d2a9f7cc 443 }
7744ea12 444 }
a083b93c 445 return $param;
7744ea12 446
a083b93c 447 default: // throw error, switched parameters in optional_param or another serious problem
448 error("Unknown parameter type: $type");
2ae28153 449 }
e0d346ff 450}
451
7cf1c7bd 452/**
7228f796 453 * For security purposes, this function will check that the currently
454 * given sesskey (passed as a parameter to the script or this function)
455 * matches that of the current user.
7cf1c7bd 456 *
7228f796 457 * @param string $sesskey optionally provided sesskey
bbd3f2c4 458 * @return bool
7228f796 459 */
460function confirm_sesskey($sesskey=NULL) {
461 global $USER;
462
c6a4e7e5 463 if (!empty($USER->ignoresesskey) || !empty($CFG->ignoresesskey)) {
089e9eae 464 return true;
465 }
466
7228f796 467 if (empty($sesskey)) {
2451dcc3 468 $sesskey = required_param('sesskey', PARAM_RAW); // Check script parameters
7228f796 469 }
470
471 if (!isset($USER->sesskey)) {
472 return false;
473 }
474
475 return ($USER->sesskey === $sesskey);
476}
477
3a61ccbe 478
7228f796 479/**
480 * Ensure that a variable is set
481 *
482 * If $var is undefined throw an error, otherwise return $var.
483 * This function will soon be made obsolete by {@link required_param()}
7cf1c7bd 484 *
7228f796 485 * @param mixed $var the variable which may be unset
486 * @param mixed $default the value to return if $var is unset
7cf1c7bd 487 */
9fa49e22 488function require_variable($var) {
373da1d4 489 global $CFG;
490 if (!empty($CFG->disableglobalshack)) {
491 error( 'The require_variable() function is deprecated.' );
492 }
9fa49e22 493 if (! isset($var)) {
b0ccd3fb 494 error('A required parameter was missing');
6b174680 495 }
496}
497
7cf1c7bd 498
499/**
500 * Ensure that a variable is set
501 *
502 * If $var is undefined set it (by reference), otherwise return $var.
7cf1c7bd 503 *
504 * @param mixed $var the variable which may be unset
505 * @param mixed $default the value to return if $var is unset
506 */
9fa49e22 507function optional_variable(&$var, $default=0) {
373da1d4 508 global $CFG;
509 if (!empty($CFG->disableglobalshack)) {
7a530277 510 error( "The optional_variable() function is deprecated ($var, $default)." );
373da1d4 511 }
9fa49e22 512 if (! isset($var)) {
513 $var = $default;
6b174680 514 }
515}
516
7a530277 517
7cf1c7bd 518/**
519 * Set a key in global configuration
520 *
89dcb99d 521 * Set a key/value pair in both this session's {@link $CFG} global variable
7cf1c7bd 522 * and in the 'config' database table for future sessions.
e1ecf0a0 523 *
524 * Can also be used to update keys for plugin-scoped configs in config_plugin table.
525 * In that case it doesn't affect $CFG.
7cf1c7bd 526 *
527 * @param string $name the key to set
528 * @param string $value the value to set
a4080313 529 * @param string $plugin (optional) the plugin scope
7cf1c7bd 530 * @uses $CFG
531 * @return bool
532 */
a4080313 533function set_config($name, $value, $plugin=NULL) {
9fa49e22 534/// No need for get_config because they are usually always available in $CFG
70812e39 535
42282810 536 global $CFG;
537
a4080313 538 if (empty($plugin)) {
539 $CFG->$name = $value; // So it's defined for this invocation at least
e1ecf0a0 540
a4080313 541 if (get_field('config', 'name', 'name', $name)) {
542 return set_field('config', 'value', $value, 'name', $name);
543 } else {
544 $config->name = $name;
545 $config->value = $value;
546 return insert_record('config', $config);
547 }
548 } else { // plugin scope
549 if ($id = get_field('config_plugins', 'id', 'name', $name, 'plugin', $plugin)) {
550 return set_field('config_plugins', 'value', $value, 'id', $id);
551 } else {
552 $config->plugin = $plugin;
553 $config->name = $name;
554 $config->value = $value;
555 return insert_record('config_plugins', $config);
556 }
557 }
558}
559
560/**
e1ecf0a0 561 * Get configuration values from the global config table
a4080313 562 * or the config_plugins table.
563 *
564 * If called with no parameters it will do the right thing
565 * generating $CFG safely from the database without overwriting
e1ecf0a0 566 * existing values.
a4080313 567 *
e1ecf0a0 568 * @param string $plugin
569 * @param string $name
a4080313 570 * @uses $CFG
571 * @return hash-like object or single value
572 *
573 */
574function get_config($plugin=NULL, $name=NULL) {
7cf1c7bd 575
a4080313 576 global $CFG;
dfc9ba9b 577
a4080313 578 if (!empty($name)) { // the user is asking for a specific value
579 if (!empty($plugin)) {
580 return get_record('config_plugins', 'plugin' , $plugin, 'name', $name);
581 } else {
582 return get_record('config', 'name', $name);
583 }
584 }
585
586 // the user is after a recordset
587 if (!empty($plugin)) {
588 if ($configs=get_records('config_plugins', 'plugin', $plugin, '', 'name,value')) {
589 $configs = (array)$configs;
590 $localcfg = array();
591 foreach ($configs as $config) {
592 $localcfg[$config->name] = $config->value;
593 }
594 return (object)$localcfg;
595 } else {
596 return false;
597 }
d897cae4 598 } else {
a4080313 599 // this was originally in setup.php
600 if ($configs = get_records('config')) {
601 $localcfg = (array)$CFG;
602 foreach ($configs as $config) {
603 if (!isset($localcfg[$config->name])) {
604 $localcfg[$config->name] = $config->value;
605 } else {
e1ecf0a0 606 if ($localcfg[$config->name] != $config->value ) {
a4080313 607 // complain if the DB has a different
608 // value than config.php does
609 error_log("\$CFG->{$config->name} in config.php ({$localcfg[$config->name]}) overrides database setting ({$config->value})");
610 }
611 }
612 }
e1ecf0a0 613
a4080313 614 $localcfg = (object)$localcfg;
615 return $localcfg;
616 } else {
617 // preserve $CFG if DB returns nothing or error
618 return $CFG;
619 }
e1ecf0a0 620
39917a09 621 }
39917a09 622}
623
a4080313 624
7cf1c7bd 625/**
626 * Refresh current $USER session global variable with all their current preferences.
627 * @uses $USER
628 */
70812e39 629function reload_user_preferences() {
70812e39 630
631 global $USER;
632
070e2616 633 if(empty($USER) || empty($USER->id)) {
634 return false;
635 }
636
d8ba183c 637 unset($USER->preference);
70812e39 638
639 if ($preferences = get_records('user_preferences', 'userid', $USER->id)) {
640 foreach ($preferences as $preference) {
641 $USER->preference[$preference->name] = $preference->value;
642 }
4586d60c 643 } else {
644 //return empty preference array to hold new values
645 $USER->preference = array();
c6d15803 646 }
70812e39 647}
648
7cf1c7bd 649/**
650 * Sets a preference for the current user
651 * Optionally, can set a preference for a different user object
652 * @uses $USER
68fbd8e1 653 * @todo Add a better description and include usage examples. Add inline links to $USER and user functions in above line.
654
7cf1c7bd 655 * @param string $name The key to set as preference for the specified user
656 * @param string $value The value to set forthe $name key in the specified user's record
c6d15803 657 * @param int $userid A moodle user ID
bbd3f2c4 658 * @return bool
7cf1c7bd 659 */
13af52a6 660function set_user_preference($name, $value, $otheruser=NULL) {
70812e39 661
662 global $USER;
663
13af52a6 664 if (empty($otheruser)){
665 if (!empty($USER) && !empty($USER->id)) {
070e2616 666 $userid = $USER->id;
13af52a6 667 } else {
070e2616 668 return false;
669 }
13af52a6 670 } else {
671 $userid = $otheruser;
d35757eb 672 }
673
70812e39 674 if (empty($name)) {
675 return false;
676 }
677
a3f1f815 678 if ($preference = get_record('user_preferences', 'userid', $userid, 'name', $name)) {
b0ccd3fb 679 if (set_field('user_preferences', 'value', $value, 'id', $preference->id)) {
13af52a6 680 if (empty($otheruser) and !empty($USER)) {
070e2616 681 $USER->preference[$name] = $value;
682 }
066af654 683 return true;
684 } else {
685 return false;
686 }
70812e39 687
688 } else {
a3f1f815 689 $preference->userid = $userid;
70812e39 690 $preference->name = $name;
691 $preference->value = (string)$value;
066af654 692 if (insert_record('user_preferences', $preference)) {
13af52a6 693 if (empty($otheruser) and !empty($USER)) {
070e2616 694 $USER->preference[$name] = $value;
695 }
70812e39 696 return true;
697 } else {
698 return false;
699 }
700 }
701}
702
6eb3e776 703/**
704 * Unsets a preference completely by deleting it from the database
705 * Optionally, can set a preference for a different user id
706 * @uses $USER
707 * @param string $name The key to unset as preference for the specified user
c6d15803 708 * @param int $userid A moodle user ID
bbd3f2c4 709 * @return bool
6eb3e776 710 */
711function unset_user_preference($name, $userid=NULL) {
712
713 global $USER;
714
361855e6 715 if (empty($userid)){
070e2616 716 if(!empty($USER) && !empty($USER->id)) {
717 $userid = $USER->id;
718 }
719 else {
720 return false;
721 }
6eb3e776 722 }
723
49d005ee 724 //Delete the preference from $USER
725 if (isset($USER->preference[$name])) {
726 unset($USER->preference[$name]);
727 }
e1ecf0a0 728
49d005ee 729 //Then from DB
6eb3e776 730 return delete_records('user_preferences', 'userid', $userid, 'name', $name);
731}
732
733
7cf1c7bd 734/**
735 * Sets a whole array of preferences for the current user
736 * @param array $prefarray An array of key/value pairs to be set
c6d15803 737 * @param int $userid A moodle user ID
bbd3f2c4 738 * @return bool
7cf1c7bd 739 */
a3f1f815 740function set_user_preferences($prefarray, $userid=NULL) {
741
742 global $USER;
70812e39 743
744 if (!is_array($prefarray) or empty($prefarray)) {
745 return false;
746 }
747
361855e6 748 if (empty($userid)){
108adee2 749 if (!empty($USER) && !empty($USER->id)) {
750 $userid = NULL; // Continue with the current user below
751 } else {
752 return false; // No-one to set!
070e2616 753 }
a3f1f815 754 }
755
70812e39 756 $return = true;
757 foreach ($prefarray as $name => $value) {
070e2616 758 // The order is important; if the test for return is done first, then
759 // if one function call fails all the remaining ones will be "optimized away"
a3f1f815 760 $return = set_user_preference($name, $value, $userid) and $return;
70812e39 761 }
762 return $return;
763}
764
7cf1c7bd 765/**
766 * If no arguments are supplied this function will return
361855e6 767 * all of the current user preferences as an array.
7cf1c7bd 768 * If a name is specified then this function
769 * attempts to return that particular preference value. If
770 * none is found, then the optional value $default is returned,
771 * otherwise NULL.
772 * @param string $name Name of the key to use in finding a preference value
773 * @param string $default Value to be returned if the $name key is not set in the user preferences
c6d15803 774 * @param int $userid A moodle user ID
7cf1c7bd 775 * @uses $USER
776 * @return string
777 */
a3f1f815 778function get_user_preferences($name=NULL, $default=NULL, $userid=NULL) {
70812e39 779
780 global $USER;
781
a3f1f815 782 if (empty($userid)) { // assume current user
783 if (empty($USER->preference)) {
784 return $default; // Default value (or NULL)
785 }
786 if (empty($name)) {
787 return $USER->preference; // Whole array
788 }
789 if (!isset($USER->preference[$name])) {
790 return $default; // Default value (or NULL)
791 }
792 return $USER->preference[$name]; // The single value
793
794 } else {
795 $preference = get_records_menu('user_preferences', 'userid', $userid, 'name', 'name,value');
796
797 if (empty($name)) {
798 return $preference;
799 }
800 if (!isset($preference[$name])) {
801 return $default; // Default value (or NULL)
802 }
803 return $preference[$name]; // The single value
70812e39 804 }
70812e39 805}
806
807
9fa49e22 808/// FUNCTIONS FOR HANDLING TIME ////////////////////////////////////////////
39917a09 809
7cf1c7bd 810/**
c6d15803 811 * Given date parts in user time produce a GMT timestamp.
7cf1c7bd 812 *
68fbd8e1 813 * @param int $year The year part to create timestamp of
814 * @param int $month The month part to create timestamp of
815 * @param int $day The day part to create timestamp of
816 * @param int $hour The hour part to create timestamp of
817 * @param int $minute The minute part to create timestamp of
818 * @param int $second The second part to create timestamp of
819 * @param float $timezone ?
820 * @param bool $applydst ?
e34d817e 821 * @return int timestamp
7cf1c7bd 822 * @todo Finish documenting this function
823 */
9f1f6daf 824function make_timestamp($year, $month=1, $day=1, $hour=0, $minute=0, $second=0, $timezone=99, $applydst=true) {
39917a09 825
dddb014a 826 $timezone = get_user_timezone_offset($timezone);
827
94e34118 828 if (abs($timezone) > 13) {
68fbd8e1 829 $time = mktime((int)$hour, (int)$minute, (int)$second, (int)$month, (int)$day, (int)$year);
03c17ddf 830 } else {
68fbd8e1 831 $time = gmmktime((int)$hour, (int)$minute, (int)$second, (int)$month, (int)$day, (int)$year);
196f2619 832 $time = usertime($time, $timezone);
28c66824 833 if($applydst) {
834 $time -= dst_offset_on($time);
835 }
9f1f6daf 836 }
837
196f2619 838 return $time;
85cafb3e 839
39917a09 840}
841
7cf1c7bd 842/**
843 * Given an amount of time in seconds, returns string
844 * formatted nicely as months, days, hours etc as needed
845 *
2f87145b 846 * @uses MINSECS
847 * @uses HOURSECS
848 * @uses DAYSECS
c6d15803 849 * @param int $totalsecs ?
850 * @param array $str ?
89dcb99d 851 * @return string
7cf1c7bd 852 * @todo Finish documenting this function
853 */
854 function format_time($totalsecs, $str=NULL) {
c7e3ac2a 855
6b174680 856 $totalsecs = abs($totalsecs);
c7e3ac2a 857
8dbed6be 858 if (!$str) { // Create the str structure the slow way
b0ccd3fb 859 $str->day = get_string('day');
860 $str->days = get_string('days');
861 $str->hour = get_string('hour');
862 $str->hours = get_string('hours');
863 $str->min = get_string('min');
864 $str->mins = get_string('mins');
865 $str->sec = get_string('sec');
866 $str->secs = get_string('secs');
8dbed6be 867 }
868
7a5672c9 869 $days = floor($totalsecs/DAYSECS);
870 $remainder = $totalsecs - ($days*DAYSECS);
871 $hours = floor($remainder/HOURSECS);
872 $remainder = $remainder - ($hours*HOURSECS);
873 $mins = floor($remainder/MINSECS);
874 $secs = $remainder - ($mins*MINSECS);
8dbed6be 875
876 $ss = ($secs == 1) ? $str->sec : $str->secs;
877 $sm = ($mins == 1) ? $str->min : $str->mins;
878 $sh = ($hours == 1) ? $str->hour : $str->hours;
879 $sd = ($days == 1) ? $str->day : $str->days;
880
b0ccd3fb 881 $odays = '';
882 $ohours = '';
883 $omins = '';
884 $osecs = '';
9c9f7d77 885
b0ccd3fb 886 if ($days) $odays = $days .' '. $sd;
887 if ($hours) $ohours = $hours .' '. $sh;
888 if ($mins) $omins = $mins .' '. $sm;
889 if ($secs) $osecs = $secs .' '. $ss;
6b174680 890
b0ccd3fb 891 if ($days) return $odays .' '. $ohours;
892 if ($hours) return $ohours .' '. $omins;
893 if ($mins) return $omins .' '. $osecs;
894 if ($secs) return $osecs;
895 return get_string('now');
6b174680 896}
f9903ed0 897
7cf1c7bd 898/**
899 * Returns a formatted string that represents a date in user time
900 * <b>WARNING: note that the format is for strftime(), not date().</b>
901 * Because of a bug in most Windows time libraries, we can't use
902 * the nicer %e, so we have to use %d which has leading zeroes.
903 * A lot of the fuss in the function is just getting rid of these leading
904 * zeroes as efficiently as possible.
361855e6 905 *
8c3dba73 906 * If parameter fixday = true (default), then take off leading
7cf1c7bd 907 * zero from %d, else mantain it.
908 *
2f87145b 909 * @uses HOURSECS
e34d817e 910 * @param int $date timestamp in GMT
911 * @param string $format strftime format
d2a9f7cc 912 * @param float $timezone
bbd3f2c4 913 * @param bool $fixday If true (default) then the leading
c6d15803 914 * zero from %d is removed. If false then the leading zero is mantained.
915 * @return string
7cf1c7bd 916 */
b0ccd3fb 917function userdate($date, $format='', $timezone=99, $fixday = true) {
7a302afc 918
1ac7ee24 919 global $CFG;
920
921 static $strftimedaydatetime;
102dc313 922
b0ccd3fb 923 if ($format == '') {
1ac7ee24 924 if (empty($strftimedaydatetime)) {
925 $strftimedaydatetime = get_string('strftimedaydatetime');
926 }
927 $format = $strftimedaydatetime;
5fa51a39 928 }
035cdbff 929
c3a3c5b8 930 if (!empty($CFG->nofixday)) { // Config.php can force %d not to be fixed.
931 $fixday = false;
932 } else if ($fixday) {
933 $formatnoday = str_replace('%d', 'DD', $format);
61ae5d36 934 $fixday = ($formatnoday != $format);
935 }
dcde9f02 936
88ec5b7c 937 $date += dst_offset_on($date);
85351042 938
494b9296 939 $timezone = get_user_timezone_offset($timezone);
102dc313 940
941 if (abs($timezone) > 13) { /// Server time
d2a9f7cc 942 if ($fixday) {
102dc313 943 $datestring = strftime($formatnoday, $date);
944 $daystring = str_replace(' 0', '', strftime(' %d', $date));
945 $datestring = str_replace('DD', $daystring, $datestring);
946 } else {
947 $datestring = strftime($format, $date);
948 }
88ec5b7c 949 } else {
102dc313 950 $date += (int)($timezone * 3600);
951 if ($fixday) {
952 $datestring = gmstrftime($formatnoday, $date);
953 $daystring = str_replace(' 0', '', gmstrftime(' %d', $date));
954 $datestring = str_replace('DD', $daystring, $datestring);
955 } else {
956 $datestring = gmstrftime($format, $date);
957 }
88ec5b7c 958 }
102dc313 959
11f7b25d 960/// If we are running under Windows and unicode is enabled, try to convert the datestring
961/// to current_charset() (because it's impossible to specify UTF-8 to fetch locale info in Win32)
962
963 if (!empty($CFG->unicodedb) && $CFG->ostype == 'WINDOWS') {
964 if ($localewincharset = get_string('localewincharset')) {
965 $textlib = textlib_get_instance();
966 $datestring = $textlib->convert($datestring, $localewincharset, current_charset());
967 }
968 }
969
035cdbff 970 return $datestring;
873960de 971}
972
7cf1c7bd 973/**
196f2619 974 * Given a $time timestamp in GMT (seconds since epoch),
c6d15803 975 * returns an array that represents the date in user time
7cf1c7bd 976 *
2f87145b 977 * @uses HOURSECS
196f2619 978 * @param int $time Timestamp in GMT
68fbd8e1 979 * @param float $timezone ?
c6d15803 980 * @return array An array that represents the date in user time
7cf1c7bd 981 * @todo Finish documenting this function
982 */
196f2619 983function usergetdate($time, $timezone=99) {
6b174680 984
494b9296 985 $timezone = get_user_timezone_offset($timezone);
a36166d3 986
e34d817e 987 if (abs($timezone) > 13) { // Server time
ed1f69b0 988 return getdate($time);
d2a9f7cc 989 }
990
e34d817e 991 // There is no gmgetdate so we use gmdate instead
02f0527d 992 $time += dst_offset_on($time);
e34d817e 993 $time += intval((float)$timezone * HOURSECS);
3bba1e6e 994
995 $datestring = gmstrftime('%S_%M_%H_%d_%m_%Y_%w_%j_%A_%B', $time);
02f0527d 996
9f1f6daf 997 list(
998 $getdate['seconds'],
999 $getdate['minutes'],
1000 $getdate['hours'],
1001 $getdate['mday'],
1002 $getdate['mon'],
1003 $getdate['year'],
1004 $getdate['wday'],
1005 $getdate['yday'],
1006 $getdate['weekday'],
1007 $getdate['month']
3bba1e6e 1008 ) = explode('_', $datestring);
9f1f6daf 1009
d2d6171f 1010 return $getdate;
d552ead0 1011}
1012
7cf1c7bd 1013/**
1014 * Given a GMT timestamp (seconds since epoch), offsets it by
1015 * the timezone. eg 3pm in India is 3pm GMT - 7 * 3600 seconds
1016 *
2f87145b 1017 * @uses HOURSECS
c6d15803 1018 * @param int $date Timestamp in GMT
e34d817e 1019 * @param float $timezone
c6d15803 1020 * @return int
7cf1c7bd 1021 */
d552ead0 1022function usertime($date, $timezone=99) {
a36166d3 1023
494b9296 1024 $timezone = get_user_timezone_offset($timezone);
2665e47a 1025
0431bd7c 1026 if (abs($timezone) > 13) {
d552ead0 1027 return $date;
1028 }
7a5672c9 1029 return $date - (int)($timezone * HOURSECS);
d552ead0 1030}
1031
8c3dba73 1032/**
1033 * Given a time, return the GMT timestamp of the most recent midnight
1034 * for the current user.
1035 *
e34d817e 1036 * @param int $date Timestamp in GMT
1037 * @param float $timezone ?
c6d15803 1038 * @return ?
8c3dba73 1039 */
edf7fe8c 1040function usergetmidnight($date, $timezone=99) {
edf7fe8c 1041
494b9296 1042 $timezone = get_user_timezone_offset($timezone);
edf7fe8c 1043 $userdate = usergetdate($date, $timezone);
4606d9bb 1044
02f0527d 1045 // Time of midnight of this user's day, in GMT
1046 return make_timestamp($userdate['year'], $userdate['mon'], $userdate['mday'], 0, 0, 0, $timezone);
edf7fe8c 1047
1048}
1049
7cf1c7bd 1050/**
1051 * Returns a string that prints the user's timezone
1052 *
1053 * @param float $timezone The user's timezone
1054 * @return string
1055 */
d552ead0 1056function usertimezone($timezone=99) {
d552ead0 1057
0c244315 1058 $tz = get_user_timezone($timezone);
f30fe8d0 1059
0c244315 1060 if (!is_float($tz)) {
1061 return $tz;
d552ead0 1062 }
0c244315 1063
1064 if(abs($tz) > 13) { // Server time
1065 return get_string('serverlocaltime');
1066 }
1067
1068 if($tz == intval($tz)) {
1069 // Don't show .0 for whole hours
1070 $tz = intval($tz);
1071 }
1072
1073 if($tz == 0) {
b0ccd3fb 1074 return 'GMT';
d552ead0 1075 }
0c244315 1076 else if($tz > 0) {
1077 return 'GMT+'.$tz;
1078 }
1079 else {
1080 return 'GMT'.$tz;
d552ead0 1081 }
e1ecf0a0 1082
f9903ed0 1083}
1084
7cf1c7bd 1085/**
1086 * Returns a float which represents the user's timezone difference from GMT in hours
1087 * Checks various settings and picks the most dominant of those which have a value
1088 *
7cf1c7bd 1089 * @uses $CFG
1090 * @uses $USER
b2b68362 1091 * @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
c6d15803 1092 * @return int
7cf1c7bd 1093 */
494b9296 1094function get_user_timezone_offset($tz = 99) {
f30fe8d0 1095
43b59916 1096 global $USER, $CFG;
1097
e8904995 1098 $tz = get_user_timezone($tz);
c9e55a25 1099
7b9e355e 1100 if (is_float($tz)) {
1101 return $tz;
1102 } else {
e8904995 1103 $tzrecord = get_timezone_record($tz);
7b9e355e 1104 if (empty($tzrecord)) {
e8904995 1105 return 99.0;
1106 }
4f2dbde9 1107 return (float)$tzrecord->gmtoff / HOURMINS;
e8904995 1108 }
1109}
1110
bbd3f2c4 1111/**
b2b68362 1112 * Returns a float or a string which denotes the user's timezone
1113 * 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)
1114 * means that for this timezone there are also DST rules to be taken into account
1115 * Checks various settings and picks the most dominant of those which have a value
bbd3f2c4 1116 *
1117 * @uses $USER
1118 * @uses $CFG
b2b68362 1119 * @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
1120 * @return mixed
bbd3f2c4 1121 */
e8904995 1122function get_user_timezone($tz = 99) {
1123 global $USER, $CFG;
43b59916 1124
f30fe8d0 1125 $timezones = array(
e8904995 1126 $tz,
1127 isset($CFG->forcetimezone) ? $CFG->forcetimezone : 99,
43b59916 1128 isset($USER->timezone) ? $USER->timezone : 99,
1129 isset($CFG->timezone) ? $CFG->timezone : 99,
f30fe8d0 1130 );
43b59916 1131
e8904995 1132 $tz = 99;
43b59916 1133
e8904995 1134 while(($tz == '' || $tz == 99) && $next = each($timezones)) {
1135 $tz = $next['value'];
43b59916 1136 }
e8904995 1137
1138 return is_numeric($tz) ? (float) $tz : $tz;
43b59916 1139}
1140
bbd3f2c4 1141/**
1142 * ?
1143 *
1144 * @uses $CFG
1145 * @uses $db
1146 * @param string $timezonename ?
1147 * @return object
1148 */
43b59916 1149function get_timezone_record($timezonename) {
1150 global $CFG, $db;
1151 static $cache = NULL;
1152
8edffd15 1153 if ($cache === NULL) {
43b59916 1154 $cache = array();
1155 }
1156
8edffd15 1157 if (isset($cache[$timezonename])) {
43b59916 1158 return $cache[$timezonename];
f30fe8d0 1159 }
1160
952d8dc8 1161 return $cache[$timezonename] = get_record_sql('SELECT * FROM '.$CFG->prefix.'timezone
1162 WHERE name = '.$db->qstr($timezonename).' ORDER BY year DESC', true);
f30fe8d0 1163}
f9903ed0 1164
bbd3f2c4 1165/**
1166 * ?
1167 *
1168 * @uses $CFG
1169 * @uses $USER
1170 * @param ? $fromyear ?
1171 * @param ? $to_year ?
1172 * @return bool
1173 */
830a2bbd 1174function calculate_user_dst_table($from_year = NULL, $to_year = NULL) {
2280ecf5 1175 global $CFG, $SESSION;
85cafb3e 1176
989585e9 1177 $usertz = get_user_timezone();
7cb29a3d 1178
989585e9 1179 if (is_float($usertz)) {
1180 // Trivial timezone, no DST
1181 return false;
1182 }
1183
2280ecf5 1184 if (!empty($SESSION->dst_offsettz) && $SESSION->dst_offsettz != $usertz) {
989585e9 1185 // We have precalculated values, but the user's effective TZ has changed in the meantime, so reset
2280ecf5 1186 unset($SESSION->dst_offsets);
1187 unset($SESSION->dst_range);
830a2bbd 1188 }
1189
2280ecf5 1190 if (!empty($SESSION->dst_offsets) && empty($from_year) && empty($to_year)) {
830a2bbd 1191 // Repeat calls which do not request specific year ranges stop here, we have already calculated the table
1192 // This will be the return path most of the time, pretty light computationally
1193 return true;
85cafb3e 1194 }
1195
830a2bbd 1196 // Reaching here means we either need to extend our table or create it from scratch
989585e9 1197
1198 // Remember which TZ we calculated these changes for
2280ecf5 1199 $SESSION->dst_offsettz = $usertz;
989585e9 1200
2280ecf5 1201 if(empty($SESSION->dst_offsets)) {
830a2bbd 1202 // If we 're creating from scratch, put the two guard elements in there
2280ecf5 1203 $SESSION->dst_offsets = array(1 => NULL, 0 => NULL);
830a2bbd 1204 }
2280ecf5 1205 if(empty($SESSION->dst_range)) {
830a2bbd 1206 // If creating from scratch
1207 $from = max((empty($from_year) ? intval(date('Y')) - 3 : $from_year), 1971);
1208 $to = min((empty($to_year) ? intval(date('Y')) + 3 : $to_year), 2035);
1209
1210 // Fill in the array with the extra years we need to process
1211 $yearstoprocess = array();
1212 for($i = $from; $i <= $to; ++$i) {
1213 $yearstoprocess[] = $i;
1214 }
1215
1216 // Take note of which years we have processed for future calls
2280ecf5 1217 $SESSION->dst_range = array($from, $to);
830a2bbd 1218 }
1219 else {
1220 // If needing to extend the table, do the same
1221 $yearstoprocess = array();
1222
2280ecf5 1223 $from = max((empty($from_year) ? $SESSION->dst_range[0] : $from_year), 1971);
1224 $to = min((empty($to_year) ? $SESSION->dst_range[1] : $to_year), 2035);
830a2bbd 1225
2280ecf5 1226 if($from < $SESSION->dst_range[0]) {
830a2bbd 1227 // Take note of which years we need to process and then note that we have processed them for future calls
2280ecf5 1228 for($i = $from; $i < $SESSION->dst_range[0]; ++$i) {
830a2bbd 1229 $yearstoprocess[] = $i;
1230 }
2280ecf5 1231 $SESSION->dst_range[0] = $from;
830a2bbd 1232 }
2280ecf5 1233 if($to > $SESSION->dst_range[1]) {
830a2bbd 1234 // Take note of which years we need to process and then note that we have processed them for future calls
2280ecf5 1235 for($i = $SESSION->dst_range[1] + 1; $i <= $to; ++$i) {
830a2bbd 1236 $yearstoprocess[] = $i;
1237 }
2280ecf5 1238 $SESSION->dst_range[1] = $to;
830a2bbd 1239 }
1240 }
1241
1242 if(empty($yearstoprocess)) {
1243 // This means that there was a call requesting a SMALLER range than we have already calculated
1244 return true;
1245 }
1246
1247 // From now on, we know that the array has at least the two guard elements, and $yearstoprocess has the years we need
1248 // Also, the array is sorted in descending timestamp order!
1249
1250 // Get DB data
989585e9 1251 $presetrecords = get_records('timezone', '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');
e789650d 1252 if(empty($presetrecords)) {
1253 return false;
1254 }
57f1191c 1255
830a2bbd 1256 // Remove ending guard (first element of the array)
2280ecf5 1257 reset($SESSION->dst_offsets);
1258 unset($SESSION->dst_offsets[key($SESSION->dst_offsets)]);
830a2bbd 1259
1260 // Add all required change timestamps
1261 foreach($yearstoprocess as $y) {
1262 // Find the record which is in effect for the year $y
1263 foreach($presetrecords as $year => $preset) {
1264 if($year <= $y) {
1265 break;
c9e72798 1266 }
830a2bbd 1267 }
1268
1269 $changes = dst_changes_for_year($y, $preset);
1270
1271 if($changes === NULL) {
1272 continue;
1273 }
1274 if($changes['dst'] != 0) {
2280ecf5 1275 $SESSION->dst_offsets[$changes['dst']] = $preset->dstoff * MINSECS;
830a2bbd 1276 }
1277 if($changes['std'] != 0) {
2280ecf5 1278 $SESSION->dst_offsets[$changes['std']] = 0;
c9e72798 1279 }
85cafb3e 1280 }
42d36497 1281
830a2bbd 1282 // Put in a guard element at the top
2280ecf5 1283 $maxtimestamp = max(array_keys($SESSION->dst_offsets));
1284 $SESSION->dst_offsets[($maxtimestamp + DAYSECS)] = NULL; // DAYSECS is arbitrary, any "small" number will do
830a2bbd 1285
1286 // Sort again
2280ecf5 1287 krsort($SESSION->dst_offsets);
830a2bbd 1288
e789650d 1289 return true;
1290}
42d36497 1291
e789650d 1292function dst_changes_for_year($year, $timezone) {
7cb29a3d 1293
e789650d 1294 if($timezone->dst_startday == 0 && $timezone->dst_weekday == 0 && $timezone->std_startday == 0 && $timezone->std_weekday == 0) {
1295 return NULL;
42d36497 1296 }
7cb29a3d 1297
e789650d 1298 $monthdaydst = find_day_in_month($timezone->dst_startday, $timezone->dst_weekday, $timezone->dst_month, $year);
1299 $monthdaystd = find_day_in_month($timezone->std_startday, $timezone->std_weekday, $timezone->std_month, $year);
1300
1301 list($dst_hour, $dst_min) = explode(':', $timezone->dst_time);
1302 list($std_hour, $std_min) = explode(':', $timezone->std_time);
d2a9f7cc 1303
6dc8dddc 1304 $timedst = make_timestamp($year, $timezone->dst_month, $monthdaydst, 0, 0, 0, 99, false);
1305 $timestd = make_timestamp($year, $timezone->std_month, $monthdaystd, 0, 0, 0, 99, false);
830a2bbd 1306
1307 // Instead of putting hour and minute in make_timestamp(), we add them afterwards.
1308 // This has the advantage of being able to have negative values for hour, i.e. for timezones
1309 // where GMT time would be in the PREVIOUS day than the local one on which DST changes.
1310
1311 $timedst += $dst_hour * HOURSECS + $dst_min * MINSECS;
1312 $timestd += $std_hour * HOURSECS + $std_min * MINSECS;
42d36497 1313
e789650d 1314 return array('dst' => $timedst, 0 => $timedst, 'std' => $timestd, 1 => $timestd);
42d36497 1315}
1316
02f0527d 1317// $time must NOT be compensated at all, it has to be a pure timestamp
1318function dst_offset_on($time) {
2280ecf5 1319 global $SESSION;
02f0527d 1320
2280ecf5 1321 if(!calculate_user_dst_table() || empty($SESSION->dst_offsets)) {
c9e72798 1322 return 0;
85cafb3e 1323 }
1324
2280ecf5 1325 reset($SESSION->dst_offsets);
1326 while(list($from, $offset) = each($SESSION->dst_offsets)) {
59556d48 1327 if($from <= $time) {
c9e72798 1328 break;
1329 }
1330 }
1331
830a2bbd 1332 // This is the normal return path
1333 if($offset !== NULL) {
1334 return $offset;
02f0527d 1335 }
02f0527d 1336
830a2bbd 1337 // Reaching this point means we haven't calculated far enough, do it now:
1338 // Calculate extra DST changes if needed and recurse. The recursion always
1339 // moves toward the stopping condition, so will always end.
1340
1341 if($from == 0) {
2280ecf5 1342 // We need a year smaller than $SESSION->dst_range[0]
1343 if($SESSION->dst_range[0] == 1971) {
830a2bbd 1344 return 0;
1345 }
2280ecf5 1346 calculate_user_dst_table($SESSION->dst_range[0] - 5, NULL);
830a2bbd 1347 return dst_offset_on($time);
1348 }
1349 else {
2280ecf5 1350 // We need a year larger than $SESSION->dst_range[1]
1351 if($SESSION->dst_range[1] == 2035) {
830a2bbd 1352 return 0;
1353 }
2280ecf5 1354 calculate_user_dst_table(NULL, $SESSION->dst_range[1] + 5);
830a2bbd 1355 return dst_offset_on($time);
1356 }
85cafb3e 1357}
02f0527d 1358
28902d99 1359function find_day_in_month($startday, $weekday, $month, $year) {
8dc3f6cf 1360
1361 $daysinmonth = days_in_month($month, $year);
1362
42d36497 1363 if($weekday == -1) {
28902d99 1364 // Don't care about weekday, so return:
1365 // abs($startday) if $startday != -1
1366 // $daysinmonth otherwise
1367 return ($startday == -1) ? $daysinmonth : abs($startday);
8dc3f6cf 1368 }
1369
1370 // From now on we 're looking for a specific weekday
8dc3f6cf 1371
28902d99 1372 // Give "end of month" its actual value, since we know it
1373 if($startday == -1) {
1374 $startday = -1 * $daysinmonth;
1375 }
1376
1377 // Starting from day $startday, the sign is the direction
8dc3f6cf 1378
28902d99 1379 if($startday < 1) {
8dc3f6cf 1380
28902d99 1381 $startday = abs($startday);
8dc3f6cf 1382 $lastmonthweekday = strftime('%w', mktime(12, 0, 0, $month, $daysinmonth, $year, 0));
1383
1384 // This is the last such weekday of the month
1385 $lastinmonth = $daysinmonth + $weekday - $lastmonthweekday;
1386 if($lastinmonth > $daysinmonth) {
1387 $lastinmonth -= 7;
42d36497 1388 }
8dc3f6cf 1389
28902d99 1390 // Find the first such weekday <= $startday
1391 while($lastinmonth > $startday) {
8dc3f6cf 1392 $lastinmonth -= 7;
42d36497 1393 }
8dc3f6cf 1394
1395 return $lastinmonth;
e1ecf0a0 1396
42d36497 1397 }
1398 else {
42d36497 1399
28902d99 1400 $indexweekday = strftime('%w', mktime(12, 0, 0, $month, $startday, $year, 0));
42d36497 1401
8dc3f6cf 1402 $diff = $weekday - $indexweekday;
1403 if($diff < 0) {
1404 $diff += 7;
42d36497 1405 }
42d36497 1406
28902d99 1407 // This is the first such weekday of the month equal to or after $startday
1408 $firstfromindex = $startday + $diff;
42d36497 1409
8dc3f6cf 1410 return $firstfromindex;
1411
1412 }
42d36497 1413}
1414
bbd3f2c4 1415/**
1416 * Calculate the number of days in a given month
1417 *
1418 * @param int $month The month whose day count is sought
1419 * @param int $year The year of the month whose day count is sought
1420 * @return int
1421 */
42d36497 1422function days_in_month($month, $year) {
1423 return intval(date('t', mktime(12, 0, 0, $month, 1, $year, 0)));
1424}
1425
bbd3f2c4 1426/**
1427 * Calculate the position in the week of a specific calendar day
1428 *
1429 * @param int $day The day of the date whose position in the week is sought
1430 * @param int $month The month of the date whose position in the week is sought
1431 * @param int $year The year of the date whose position in the week is sought
1432 * @return int
1433 */
8dc3f6cf 1434function dayofweek($day, $month, $year) {
1435 // I wonder if this is any different from
1436 // strftime('%w', mktime(12, 0, 0, $month, $daysinmonth, $year, 0));
1437 return intval(date('w', mktime(12, 0, 0, $month, $day, $year, 0)));
1438}
1439
9fa49e22 1440/// USER AUTHENTICATION AND LOGIN ////////////////////////////////////////
f9903ed0 1441
bbd3f2c4 1442/**
1443 * Makes sure that $USER->sesskey exists, if $USER itself exists. It sets a new sesskey
1444 * if one does not already exist, but does not overwrite existing sesskeys. Returns the
1445 * sesskey string if $USER exists, or boolean false if not.
1446 *
1447 * @uses $USER
1448 * @return string
1449 */
04280e85 1450function sesskey() {
1a33f699 1451 global $USER;
1452
1453 if(!isset($USER)) {
1454 return false;
1455 }
1456
1457 if (empty($USER->sesskey)) {
1458 $USER->sesskey = random_string(10);
1459 }
1460
1461 return $USER->sesskey;
1462}
1463
0302c52f 1464/* this function forces a user to log out */
1465
1466function require_logout() {
527ec51a 1467 global $USER, $CFG;
86a1ba04 1468 if (!empty($USER->id)) {
0302c52f 1469 add_to_log(SITEID, "user", "logout", "view.php?id=$USER->id&course=".SITEID, $USER->id, 0, $USER->id);
1470
1471 if ($USER->auth == 'cas' && !empty($CFG->cas_enabled)) {
1472 require($CFG->dirroot.'/auth/cas/logout.php');
1473 }
1474 }
1475
1476 if (ini_get_bool("register_globals") and check_php_version("4.3.0")) {
1477 // This method is just to try to avoid silly warnings from PHP 4.3.0
1478 session_unregister("USER");
1479 session_unregister("SESSION");
1480 }
1481
1ae655b1 1482 setcookie('MoodleSessionTest'.$CFG->sessioncookie, '', time() - 3600, $CFG->sessioncookiepath);
0302c52f 1483 unset($_SESSION['USER']);
1484 unset($_SESSION['SESSION']);
1485
1486 unset($SESSION);
1487 unset($USER);
1488
1489}
7cf1c7bd 1490/**
ec81373f 1491 * This function checks that the current user is logged in and has the
1492 * required privileges
1493 *
7cf1c7bd 1494 * This function checks that the current user is logged in, and optionally
ec81373f 1495 * whether they are allowed to be in a particular course and view a particular
1496 * course module.
1497 * If they are not logged in, then it redirects them to the site login unless
d2a9f7cc 1498 * $autologinguest is set and {@link $CFG}->autologinguests is set to 1 in which
ec81373f 1499 * case they are automatically logged in as guests.
1500 * If $courseid is given and the user is not enrolled in that course then the
1501 * user is redirected to the course enrolment page.
1502 * If $cm is given and the coursemodule is hidden and the user is not a teacher
1503 * in the course then the user is redirected to the course home page.
7cf1c7bd 1504 *
7cf1c7bd 1505 * @uses $CFG
c6d15803 1506 * @uses $SESSION
7cf1c7bd 1507 * @uses $USER
1508 * @uses $FULLME
c6d15803 1509 * @uses SITEID
f07fa644 1510 * @uses $COURSE
7cf1c7bd 1511 * @uses $MoodleSession
ec81373f 1512 * @param int $courseid id of the course
bbd3f2c4 1513 * @param bool $autologinguest
1514 * @param object $cm course module object
7cf1c7bd 1515 */
ec81373f 1516function require_login($courseid=0, $autologinguest=true, $cm=null) {
f9903ed0 1517
f07fa644 1518 global $CFG, $SESSION, $USER, $COURSE, $FULLME, $MoodleSession;
d8ba183c 1519
45fc1f75 1520 // Redefine global $COURSE if we can
1521 global $course; // We use the global hack once here so it doesn't need to be used again
be933850 1522 if (is_object($course) and !empty($course->id) and ($courseid == 0 or $course->id == $courseid)) {
45fc1f75 1523 $COURSE = clone($course);
1524 } else if ($courseid) {
1525 $COURSE = get_record('course', 'id', $courseid);
8a58a8e1 1526 }
1527
be933850 1528 if (!empty($COURSE->lang)) {
1529 $CFG->courselang = $COURSE->lang;
1530 moodle_setlocale();
1531 }
1532
da5c172a 1533 // First check that the user is logged in to the site.
c21c671d 1534 if (! (isset($USER->loggedin) and $USER->confirmed and ($USER->site == $CFG->wwwroot)) ) { // They're not
f9903ed0 1535 $SESSION->wantsurl = $FULLME;
b0ccd3fb 1536 if (!empty($_SERVER['HTTP_REFERER'])) {
1537 $SESSION->fromurl = $_SERVER['HTTP_REFERER'];
9f44d972 1538 }
c21c671d 1539 $USER = NULL;
8f23e33b 1540 if ($autologinguest and $CFG->autologinguests and $courseid and ($courseid == SITEID or get_field('course','guest','id',$courseid)) ) {
8e8d0524 1541 $loginguest = '?loginguest=true';
1542 } else {
1543 $loginguest = '';
a2ebe6a5 1544 }
8a33e371 1545 if (empty($CFG->loginhttps)) {
b0ccd3fb 1546 redirect($CFG->wwwroot .'/login/index.php'. $loginguest);
8a33e371 1547 } else {
2c3432e6 1548 $wwwroot = str_replace('http:','https:', $CFG->wwwroot);
b0ccd3fb 1549 redirect($wwwroot .'/login/index.php'. $loginguest);
8a33e371 1550 }
20fde7b1 1551 exit;
f9903ed0 1552 }
808a3baa 1553
d35757eb 1554 // check whether the user should be changing password
027a1604 1555 // reload_user_preferences(); // Why is this necessary? Seems wasteful. - MD
a3f1f815 1556 if (!empty($USER->preference['auth_forcepasswordchange'])){
d35757eb 1557 if (is_internal_auth() || $CFG->{'auth_'.$USER->auth.'_stdchangepassword'}){
20fde7b1 1558 $SESSION->wantsurl = $FULLME;
b0ccd3fb 1559 redirect($CFG->wwwroot .'/login/change_password.php');
d35757eb 1560 } elseif($CFG->changepassword) {
1561 redirect($CFG->changepassword);
1562 } else {
361855e6 1563 error('You cannot proceed without changing your password.
d35757eb 1564 However there is no available page for changing it.
b0ccd3fb 1565 Please contact your Moodle Administrator.');
d35757eb 1566 }
1567 }
808a3baa 1568 // Check that the user account is properly set up
1569 if (user_not_fully_set_up($USER)) {
20fde7b1 1570 $SESSION->wantsurl = $FULLME;
b0ccd3fb 1571 redirect($CFG->wwwroot .'/user/edit.php?id='. $USER->id .'&amp;course='. SITEID);
808a3baa 1572 }
d8ba183c 1573
366dfa60 1574 // Make sure current IP matches the one for this session (if required)
361855e6 1575 if (!empty($CFG->tracksessionip)) {
366dfa60 1576 if ($USER->sessionIP != md5(getremoteaddr())) {
1577 error(get_string('sessionipnomatch', 'error'));
1578 }
1579 }
6d8f47d6 1580
1581 // Make sure the USER has a sesskey set up. Used for checking script parameters.
04280e85 1582 sesskey();
366dfa60 1583
027a1604 1584 // Check that the user has agreed to a site policy if there is one
1585 if (!empty($CFG->sitepolicy)) {
1586 if (!$USER->policyagreed) {
957b5198 1587 $SESSION->wantsurl = $FULLME;
027a1604 1588 redirect($CFG->wwwroot .'/user/policy.php');
027a1604 1589 }
1695b680 1590 }
1591
1592 // If the site is currently under maintenance, then print a message
1593 if (!isadmin()) {
eeefd0b0 1594 if (file_exists($CFG->dataroot.'/'.SITEID.'/maintenance.html')) {
1695b680 1595 print_maintenance_message();
20fde7b1 1596 exit;
1695b680 1597 }
027a1604 1598 }
1599
da5c172a 1600 // Next, check if the user can be in a particular course
1601 if ($courseid) {
ec81373f 1602 if ($courseid == SITEID) { // Anyone can be in the site course
1603 if (isset($cm) and !$cm->visible and !isteacher(SITEID)) { // Not allowed to see module, send to course page
1604 redirect($CFG->wwwroot.'/course/view.php?id='.$cm->course, get_string('activityiscurrentlyhidden'));
1605 }
d2a9f7cc 1606 return;
e3512050 1607 }
7fb0fec7 1608 if (! $course = get_record('course', 'id', $courseid)) {
1609 error('That course doesn\'t exist');
1610 }
fa145ae1 1611 if (!isteacher($courseid) && !($course->visible && course_parent_visible($course))) {
7fb0fec7 1612 print_header();
1613 notice(get_string('coursehidden'), $CFG->wwwroot .'/');
bbbf2d40 1614 }
1615
5ec8a4f0 1616 $context = get_context_instance(CONTEXT_COURSE, $courseid);
bbbf2d40 1617
0468976c 1618 if (has_capability('moodle/course:view', $context)) {
cb909d74 1619 if (isset($USER->realuser)) { // Make sure the REAL person can also access this course
1620 if (!isteacher($courseid, $USER->realuser)) {
1621 print_header();
b0ccd3fb 1622 notice(get_string('studentnotallowed', '', fullname($USER, true)), $CFG->wwwroot .'/');
cb909d74 1623 }
3ce2f1e0 1624 }
ec81373f 1625 if (isset($cm) and !$cm->visible and !isteacher($courseid)) { // Not allowed to see module, send to course page
1626 redirect($CFG->wwwroot.'/course/view.php?id='.$cm->course, get_string('activityiscurrentlyhidden'));
1627 }
da5c172a 1628 return; // user is a member of this course.
1629 }
b0ccd3fb 1630 if ($USER->username == 'guest') {
7363ff91 1631 switch ($course->guest) {
1632 case 0: // Guests not allowed
1633 print_header();
ea971152 1634 notice(get_string('guestsnotallowed', '', $course->fullname), "$CFG->wwwroot/login/index.php");
7363ff91 1635 break;
1636 case 1: // Guests allowed
ec81373f 1637 if (isset($cm) and !$cm->visible) { // Not allowed to see module, send to course page
1638 redirect($CFG->wwwroot.'/course/view.php?id='.$cm->course, get_string('activityiscurrentlyhidden'));
1639 }
7363ff91 1640 return;
1641 case 2: // Guests allowed with key (drop through)
1642 break;
1643 }
da5c172a 1644 }
f9903ed0 1645
9ca3b4f3 1646 //User is not enrolled in the course, wants to access course content
4a10c387 1647 //as a guest, and course setting allow unlimited guest access;
1648 //do not autologin as guest when $autologinguest is false
9ca3b4f3 1649 //Code cribbed from course/loginas.php
4a10c387 1650 if (strstr($FULLME,"username=guest") and ($course->guest==1) and $autologinguest) {
b56ccdd9 1651 $realuser = $USER->id;
1652 $realname = fullname($USER, true);
1653 $USER = guest_user();
1654 $USER->loggedin = true;
1655 $USER->site = $CFG->wwwroot;
1656 $USER->realuser = $realuser;
5f357fb6 1657 $USER->sessionIP = md5(getremoteaddr()); // Store the current IP in the session
1658 if (isset($SESSION->currentgroup)) { // Remember current cache setting for later
1659 $SESSION->oldcurrentgroup = $SESSION->currentgroup;
1660 unset($SESSION->currentgroup);
b56ccdd9 1661 }
1662 $guest_name = fullname($USER, true);
1663 add_to_log($course->id, "course", "loginas", "../user/view.php?id=$course->id&$USER->id$", "$realname -> $guest_name");
ec81373f 1664 if (isset($cm) and !$cm->visible) { // Not allowed to see module, send to course page
1665 redirect($CFG->wwwroot.'/course/view.php?id='.$cm->course, get_string('activityiscurrentlyhidden'));
1666 }
b56ccdd9 1667 return;
9ca3b4f3 1668 }
1669
7363ff91 1670 // Currently not enrolled in the course, so see if they want to enrol
da5c172a 1671 $SESSION->wantsurl = $FULLME;
b0ccd3fb 1672 redirect($CFG->wwwroot .'/course/enrol.php?id='. $courseid);
da5c172a 1673 die;
1674 }
f9903ed0 1675}
1676
7cf1c7bd 1677/**
1678 * This is a weaker version of {@link require_login()} which only requires login
1679 * when called from within a course rather than the site page, unless
1680 * the forcelogin option is turned on.
1681 *
1682 * @uses $CFG
4febb58f 1683 * @param object $course The course object in question
bbd3f2c4 1684 * @param bool $autologinguest Allow autologin guests if that is wanted
4febb58f 1685 * @param object $cm Course activity module if known
7cf1c7bd 1686 */
ec81373f 1687function require_course_login($course, $autologinguest=true, $cm=null) {
f950af3c 1688 global $CFG;
1596edff 1689 if (!empty($CFG->forcelogin)) {
b56ccdd9 1690 require_login();
f950af3c 1691 }
4febb58f 1692 if ($course->id != SITEID) {
ec81373f 1693 require_login($course->id, $autologinguest, $cm);
f950af3c 1694 }
1695}
1696
7cf1c7bd 1697/**
1698 * Modify the user table by setting the currently logged in user's
1699 * last login to now.
1700 *
1701 * @uses $USER
bbd3f2c4 1702 * @return bool
7cf1c7bd 1703 */
1d881d92 1704function update_user_login_times() {
1705 global $USER;
1706
1707 $USER->lastlogin = $user->lastlogin = $USER->currentlogin;
2a2f5f11 1708 $USER->currentlogin = $user->lastaccess = $user->currentlogin = time();
1d881d92 1709
1710 $user->id = $USER->id;
1711
b0ccd3fb 1712 return update_record('user', $user);
1d881d92 1713}
1714
7cf1c7bd 1715/**
1716 * Determines if a user has completed setting up their account.
1717 *
89dcb99d 1718 * @param user $user A {@link $USER} object to test for the existance of a valid name and email
bbd3f2c4 1719 * @return bool
7cf1c7bd 1720 */
808a3baa 1721function user_not_fully_set_up($user) {
bb64b51a 1722 return ($user->username != 'guest' and (empty($user->firstname) or empty($user->lastname) or empty($user->email) or over_bounce_threshold($user)));
1723}
1724
1725function over_bounce_threshold($user) {
d2a9f7cc 1726
bb64b51a 1727 global $CFG;
d2a9f7cc 1728
bb64b51a 1729 if (empty($CFG->handlebounces)) {
1730 return false;
1731 }
1732 // set sensible defaults
1733 if (empty($CFG->minbounces)) {
1734 $CFG->minbounces = 10;
1735 }
1736 if (empty($CFG->bounceratio)) {
1737 $CFG->bounceratio = .20;
1738 }
1739 $bouncecount = 0;
1740 $sendcount = 0;
1741 if ($bounce = get_record('user_preferences','userid',$user->id,'name','email_bounce_count')) {
1742 $bouncecount = $bounce->value;
1743 }
1744 if ($send = get_record('user_preferences','userid',$user->id,'name','email_send_count')) {
1745 $sendcount = $send->value;
1746 }
1747 return ($bouncecount >= $CFG->minbounces && $bouncecount/$sendcount >= $CFG->bounceratio);
1748}
1749
d2a9f7cc 1750/**
bb64b51a 1751 * @param $user - object containing an id
1752 * @param $reset - will reset the count to 0
1753 */
1754function set_send_count($user,$reset=false) {
d2a9f7cc 1755 if ($pref = get_record('user_preferences','userid',$user->id,'name','email_send_count')) {
bb64b51a 1756 $pref->value = (!empty($reset)) ? 0 : $pref->value+1;
1757 update_record('user_preferences',$pref);
1758 }
1759 else if (!empty($reset)) { // if it's not there and we're resetting, don't bother.
1760 // make a new one
1761 $pref->name = 'email_send_count';
1762 $pref->value = 1;
1763 $pref->userid = $user->id;
06ba0b04 1764 insert_record('user_preferences',$pref, false);
bb64b51a 1765 }
1766}
1767
d2a9f7cc 1768/**
bb64b51a 1769* @param $user - object containing an id
1770 * @param $reset - will reset the count to 0
1771 */
1772function set_bounce_count($user,$reset=false) {
d2a9f7cc 1773 if ($pref = get_record('user_preferences','userid',$user->id,'name','email_bounce_count')) {
bb64b51a 1774 $pref->value = (!empty($reset)) ? 0 : $pref->value+1;
1775 update_record('user_preferences',$pref);
1776 }
1777 else if (!empty($reset)) { // if it's not there and we're resetting, don't bother.
1778 // make a new one
1779 $pref->name = 'email_bounce_count';
1780 $pref->value = 1;
1781 $pref->userid = $user->id;
06ba0b04 1782 insert_record('user_preferences',$pref, false);
bb64b51a 1783 }
808a3baa 1784}
f9903ed0 1785
7cf1c7bd 1786/**
1787 * Keeps track of login attempts
1788 *
1789 * @uses $SESSION
1790 */
f9903ed0 1791function update_login_count() {
9fa49e22 1792
f9903ed0 1793 global $SESSION;
1794
1795 $max_logins = 10;
1796
1797 if (empty($SESSION->logincount)) {
1798 $SESSION->logincount = 1;
1799 } else {
1800 $SESSION->logincount++;
1801 }
1802
1803 if ($SESSION->logincount > $max_logins) {
9fa49e22 1804 unset($SESSION->wantsurl);
b0ccd3fb 1805 error(get_string('errortoomanylogins'));
d578afc8 1806 }
1807}
1808
7cf1c7bd 1809/**
1810 * Resets login attempts
1811 *
1812 * @uses $SESSION
1813 */
9fa49e22 1814function reset_login_count() {
9fa49e22 1815 global $SESSION;
d578afc8 1816
9fa49e22 1817 $SESSION->logincount = 0;
d578afc8 1818}
1819
b61efafb 1820function sync_metacourses() {
1821
1822 global $CFG;
1823
5f37b628 1824 if (!$courses = get_records_sql("SELECT DISTINCT parent_course,1 FROM {$CFG->prefix}course_meta")) {
b61efafb 1825 return;
1826 }
d2a9f7cc 1827
b61efafb 1828 foreach ($courses as $course) {
1829 sync_metacourse($course->parent_course);
1830 }
1831}
1832
1833
1834/**
1835 * Goes through all enrolment records for the courses inside the metacourse and sync with them.
d2a9f7cc 1836 */
b61efafb 1837
1838function sync_metacourse($metacourseid) {
1839
755c8d58 1840 global $CFG;
b61efafb 1841
1842 if (!$metacourse = get_record("course","id",$metacourseid)) {
1843 return false;
1844 }
1845
755c8d58 1846 if (count_records('course_meta','parent_course',$metacourseid) == 0) {
1847 // if there are no child courses for this meta course, nuke the enrolments
b61efafb 1848 if ($enrolments = get_records('user_students','course',$metacourseid,'','userid,1')) {
1849 foreach ($enrolments as $enrolment) {
1850 unenrol_student($enrolment->userid,$metacourseid);
1851 }
1852 }
1853 return true;
1854 }
1855
755c8d58 1856 // first get the list of child courses
1857 $c_courses = get_records('course_meta','parent_course',$metacourseid);
1858 $instr = '';
1859 foreach ($c_courses as $c) {
1860 $instr .= $c->child_course.',';
1861 }
1862 $instr = substr($instr,0,-1);
87671466 1863
755c8d58 1864 // now get the list of valid enrolments in the child courses
1865 $sql = 'SELECT DISTINCT userid,1 FROM '.$CFG->prefix.'user_students WHERE course IN ('.$instr.')';
1866 $enrolments = get_records_sql($sql);
e1ecf0a0 1867
755c8d58 1868 // put it into a nice array we can happily use array_diff on.
1869 $ce = array();
1870 if (!empty($enrolments)) {
1871 foreach ($enrolments as $en) {
1872 $ce[] = $en->userid;
b61efafb 1873 }
1874 }
1875
755c8d58 1876 // now get the list of current enrolments in the meta course.
1877 $sql = 'SELECT userid,1 FROM '.$CFG->prefix.'user_students WHERE course = '.$metacourseid;
1878 $enrolments = get_records_sql($sql);
b61efafb 1879
755c8d58 1880 $me = array();
1881 if (!empty($enrolments)) {
1882 foreach ($enrolments as $en) {
1883 $me[] = $en->userid;
b61efafb 1884 }
1885 }
d2a9f7cc 1886
755c8d58 1887 $enrolmentstodelete = array_diff($me,$ce);
1888 $userstoadd = array_diff($ce,$me);
1889
1890 foreach ($enrolmentstodelete as $userid) {
1891 unenrol_student($userid,$metacourseid);
1892 }
1893 foreach ($userstoadd as $userid) {
1894 enrol_student($userid,$metacourseid,0,0,'metacourse');
1895 }
e1ecf0a0 1896
b61efafb 1897 // and next make sure that we have the right start time and end time (ie max and min) for them all.
1898 if ($enrolments = get_records('user_students','course',$metacourseid,'','id,userid')) {
1899 foreach ($enrolments as $enrol) {
1900 if ($maxmin = get_record_sql("SELECT min(timestart) AS timestart, max(timeend) AS timeend
755c8d58 1901 FROM {$CFG->prefix}user_students u,
e1ecf0a0 1902 {$CFG->prefix}course_meta mc
1903 WHERE u.course = mc.child_course
755c8d58 1904 AND userid = $enrol->userid
b61efafb 1905 AND mc.parent_course = $metacourseid")) {
1906 $enrol->timestart = $maxmin->timestart;
1907 $enrol->timeend = $maxmin->timeend;
755c8d58 1908 $enrol->enrol = 'metacourse'; // just in case it wasn't there earlier.
b61efafb 1909 update_record('user_students',$enrol);
1910 }
1911 }
1912 }
1913 return true;
755c8d58 1914
b61efafb 1915}
1916
d2a9f7cc 1917/**
b61efafb 1918 * Adds a record to the metacourse table and calls sync_metacoures
1919 */
1920function add_to_metacourse ($metacourseid, $courseid) {
d2a9f7cc 1921
b61efafb 1922 if (!$metacourse = get_record("course","id",$metacourseid)) {
1923 return false;
1924 }
d2a9f7cc 1925
b61efafb 1926 if (!$course = get_record("course","id",$courseid)) {
1927 return false;
1928 }
1929
5f37b628 1930 if (!$record = get_record("course_meta","parent_course",$metacourseid,"child_course",$courseid)) {
b61efafb 1931 $rec->parent_course = $metacourseid;
1932 $rec->child_course = $courseid;
5f37b628 1933 if (!insert_record('course_meta',$rec)) {
b61efafb 1934 return false;
1935 }
1936 return sync_metacourse($metacourseid);
1937 }
1938 return true;
d2a9f7cc 1939
b61efafb 1940}
1941
d2a9f7cc 1942/**
b61efafb 1943 * Removes the record from the metacourse table and calls sync_metacourse
1944 */
1945function remove_from_metacourse($metacourseid, $courseid) {
1946
5f37b628 1947 if (delete_records('course_meta','parent_course',$metacourseid,'child_course',$courseid)) {
b61efafb 1948 return sync_metacourse($metacourseid);
1949 }
1950 return false;
1951}
1952
1953
7c12949d 1954/**
1955 * Determines if a user is currently logged in
1956 *
1957 * @uses $USER
bbd3f2c4 1958 * @return bool
7c12949d 1959 */
1960function isloggedin() {
1961 global $USER;
1962
1963 return (!empty($USER->id));
1964}
1965
1966
7cf1c7bd 1967/**
1968 * Determines if a user an admin
1969 *
1970 * @uses $USER
c6d15803 1971 * @param int $userid The id of the user as is found in the 'user' table
bbd3f2c4 1972 * @staticvar array $admins List of users who have been found to be admins by user id
1973 * @staticvar array $nonadmins List of users who have been found not to be admins by user id
1974 * @return bool
7cf1c7bd 1975 */
581d7b49 1976function isadmin($userid=0) {
0468976c 1977 global $USER, $CFG;
1978
5e04ee0c 1979 static $admins, $nonadmins;
1980
9425b25f 1981 if (!empty($CFG->rolesactive)) {
0468976c 1982
1983 $context = get_context_instance(CONTEXT_SYSTEM, SITEID);
5ec8a4f0 1984 if (!$userid) {
35a518c5 1985 if (empty($USER->id)) {
1986 return false;
1987 } else {
1988 return has_capability('moodle/legacy:admin', $context, $USER->id, false);
1989 }
5ec8a4f0 1990 } else {
20aeb4b8 1991 return has_capability('moodle/legacy:admin', $context, false, $userid, false);
5ec8a4f0 1992 }
1993
1994 }
bbbf2d40 1995
5e04ee0c 1996 if (!isset($admins)) {
1997 $admins = array();
1998 $nonadmins = array();
1999 }
f9903ed0 2000
581d7b49 2001 if (!$userid){
2002 if (empty($USER->id)) {
2003 return false;
2004 }
2005 $userid = $USER->id;
9bd2c874 2006 }
2007
dcc17b63 2008 if (!empty($USER->id) and ($userid == $USER->id)) { // Check session cache
2009 return !empty($USER->admin);
2010 }
2011
581d7b49 2012 if (in_array($userid, $admins)) {
aa095969 2013 return true;
581d7b49 2014 } else if (in_array($userid, $nonadmins)) {
aa095969 2015 return false;
b0ccd3fb 2016 } else if (record_exists('user_admins', 'userid', $userid)){
581d7b49 2017 $admins[] = $userid;
aa095969 2018 return true;
2019 } else {
581d7b49 2020 $nonadmins[] = $userid;
aa095969 2021 return false;
f9903ed0 2022 }
f9903ed0 2023}
2024
7cf1c7bd 2025/**
5e04ee0c 2026 * Determines if a user is a teacher (or better)
7cf1c7bd 2027 *
9407d456 2028 * @uses $USER
bbd3f2c4 2029 * @uses $CFG
c6d15803 2030 * @param int $courseid The id of the course that is being viewed, if any
2031 * @param int $userid The id of the user that is being tested against. Set this to 0 if you would just like to test against the currently logged in user.
bbd3f2c4 2032 * @param bool $includeadmin If true this function will return true when it encounters an admin user.
2033 * @return bool
7cf1c7bd 2034 */
0468976c 2035
fb830a1b 2036function isteacher($courseid=0, $userid=0, $includeadmin=true) {
5e04ee0c 2037/// Is the user able to access this course as a teacher?
fb830a1b 2038 global $USER, $CFG;
f9903ed0 2039
9425b25f 2040 if (!empty($CFG->rolesactive)) {
5ec8a4f0 2041
2042 if ($courseid == 0) {
2043 $context = get_context_instance(CONTEXT_SYSTEM, SITEID);
2044 } else {
2045 $context = get_context_instance(CONTEXT_COURSE, $courseid);
2046 }
9425b25f 2047
5ec8a4f0 2048 if (!$userid) {
35a518c5 2049 if (empty($USER->id)) {
2050 return false;
2051 } else {
2052 return (has_capability('moodle/legacy:teacher', $context, $USER->id, false)
20aeb4b8 2053 or has_capability('moodle/legacy:editingteacher', $context, $USER->id, false)
2054 or has_capability('moodle/legacy:admin', $context, $USER->id, false));
35a518c5 2055 }
5ec8a4f0 2056 } else {
20aeb4b8 2057 return (has_capability('moodle/legacy:teacher', $context, $userid, false)
2058 or has_capability('moodle/legacy:editingteacher', $context, $userid, false)
2059 or has_capability('moodle/legacy:admin', $context, $userid, false));
5ec8a4f0 2060 }
2061 }
bbbf2d40 2062
0468976c 2063 // Old code follows, will be removed before 1.7 because it shouldn't run XXX TODO
bbbf2d40 2064
5e04ee0c 2065 if (empty($userid)) { // we are relying on $USER
2066 if (empty($USER) or empty($USER->id)) { // not logged in so can't be a teacher
2067 return false;
2068 }
57bc53c6 2069 if (!empty($USER->studentview)) {
2070 return false;
2071 }
dcc17b63 2072 if (!empty($USER->teacher) and $courseid) { // look in session cache
2073 if (!empty($USER->teacher[$courseid])) { // Explicitly a teacher, good
57bc53c6 2074 return true;
dcc17b63 2075 }
5e04ee0c 2076 }
dcc17b63 2077 $userid = $USER->id; // we need to make further checks
5e04ee0c 2078 }
2079
dcc17b63 2080 if ($includeadmin and isadmin($userid)) { // admins can do anything the teacher can
d115a57f 2081 return true;
2082 }
2083
dcc17b63 2084 if (empty($courseid)) { // should not happen, but we handle it
fb830a1b 2085 if (isadmin() or $CFG->debug > 7) {
dcc17b63 2086 notify('Coding error: isteacher() should not be used without a valid course id '.
2087 'as argument. Please notify the developer for this module.');
fb830a1b 2088 }
9407d456 2089 return isteacherinanycourse($userid, $includeadmin);
2090 }
2091
dcc17b63 2092/// Last resort, check the database
2093
9407d456 2094 return record_exists('user_teachers', 'userid', $userid, 'course', $courseid);
2095}
2096
2097/**
2098 * Determines if a user is a teacher in any course, or an admin
2099 *
2100 * @uses $USER
2101 * @param int $userid The id of the user that is being tested against. Set this to 0 if you would just like to test against the currently logged in user.
bbd3f2c4 2102 * @param bool $includeadmin If true this function will return true when it encounters an admin user.
2103 * @return bool
9407d456 2104 */
5e04ee0c 2105function isteacherinanycourse($userid=0, $includeadmin=true) {
fddbcf9c 2106 global $USER;
2107
5e04ee0c 2108 if (empty($userid)) {
2109 if (empty($USER) or empty($USER->id)) {
9407d456 2110 return false;
2111 }
dcc17b63 2112 if (!empty($USER->teacher)) { // look in session cache
2113 return true;
2114 }
9407d456 2115 $userid = $USER->id;
9d3c795c 2116 }
2117
5e04ee0c 2118 if ($includeadmin and isadmin($userid)) { // admins can do anything
fddbcf9c 2119 return true;
2120 }
2121
9407d456 2122 return record_exists('user_teachers', 'userid', $userid);
f9903ed0 2123}
2124
7cf1c7bd 2125/**
2126 * Determines if a user is allowed to edit a given course
2127 *
2128 * @uses $USER
c6d15803 2129 * @param int $courseid The id of the course that is being edited
2130 * @param int $userid The id of the user that is being tested against. Set this to 0 if you would just like to test against the currently logged in user.
367b8413 2131 * @param bool $ignorestudentview true = don't do check for studentview mode
bbd3f2c4 2132 * @return boo
7cf1c7bd 2133 */
367b8413 2134function isteacheredit($courseid, $userid=0, $ignorestudentview=false) {
9425b25f 2135 global $USER, $CFG;
2136
2137 if (!empty($CFG->rolesactive)) {
5ec8a4f0 2138
2139 if ($courseid == 0) {
2140 $context = get_context_instance(CONTEXT_SYSTEM, SITEID);
2141 } else {
2142 $context = get_context_instance(CONTEXT_COURSE, $courseid);
2143 }
9425b25f 2144
5ec8a4f0 2145 if (!$userid) {
35a518c5 2146 if (empty($USER->id)) {
2147 return false;
2148 } else {
2149 return (has_capability('moodle/legacy:editingteacher', $context, $USER->id, false)
20aeb4b8 2150 or has_capability('moodle/legacy:admin', $context, $USER->id, false));
35a518c5 2151 }
5ec8a4f0 2152 } else {
20aeb4b8 2153 return (has_capability('moodle/legacy:editingteacher', $context, $userid, false)
2154 or has_capability('moodle/legacy:admin', $context, $userid, false));
5ec8a4f0 2155 }
5ec8a4f0 2156 }
367b8413 2157 // we can't edit in studentview
2158 if (!empty($USER->studentview) and !$ignorestudentview) {
2159 return false;
2160 }
2161
d8ba183c 2162 if (isadmin($userid)) { // admins can do anything
73047f2f 2163 return true;
2164 }
2165
2166 if (!$userid) {
ddd7a47a 2167 if (empty($USER) or empty($USER->id)) { // not logged in so can't be a teacher
2168 return false;
2169 }
2170 if (empty($USER->teacheredit)) { // we are relying on session cache
2171 return false;
2172 }
73047f2f 2173 return !empty($USER->teacheredit[$courseid]);
2174 }
2175
b0ccd3fb 2176 return get_field('user_teachers', 'editall', 'userid', $userid, 'course', $courseid);
73047f2f 2177}
2178
7cf1c7bd 2179/**
2180 * Determines if a user can create new courses
2181 *
2182 * @uses $USER
361855e6 2183 * @param int $userid The user being tested. You can set this to 0 or leave it blank to test the currently logged in user.
bbd3f2c4 2184 * @return bool
7cf1c7bd 2185 */
1924074c 2186function iscreator ($userid=0) {
9425b25f 2187 global $USER, $CFG;
2188
2189 if (!empty($CFG->rolesactive)) {
2190
2191 $context = get_context_instance(CONTEXT_SYSTEM, SITEID);
bbbf2d40 2192
5ec8a4f0 2193 if (!$userid) {
35a518c5 2194 if (empty($USER->id)) {
2195 return false;
2196 } else {
2197 return (has_capability('moodle/legacy:coursecreator', $context, $USER->id, false)
20aeb4b8 2198 or has_capability('moodle/legacy:admin', $context, $USER->id, false));
35a518c5 2199 }
5ec8a4f0 2200 } else {
20aeb4b8 2201 return (has_capability('moodle/legacy:coursecreator', $context, $userid, false)
2202 or has_capability('moodle/legacy:admin', $context, $userid, false));
5ec8a4f0 2203 }
2204
2205 }
8a205861 2206 if (empty($USER->id)) {
2207 return false;
2208 }
1924074c 2209 if (isadmin($userid)) { // admins can do anything
2210 return true;
2211 }
8a205861 2212 if (empty($userid)) {
b0ccd3fb 2213 return record_exists('user_coursecreators', 'userid', $USER->id);
1924074c 2214 }
2215
b0ccd3fb 2216 return record_exists('user_coursecreators', 'userid', $userid);
1924074c 2217}
2218
7cf1c7bd 2219/**
2220 * Determines if a user is a student in the specified course
361855e6 2221 *
7cf1c7bd 2222 * If the course id specifies the site then the function determines
2223 * if the user is a confirmed and valid user of this site.
2224 *
2225 * @uses $USER
2226 * @uses $CFG
c6d15803 2227 * @uses SITEID
2228 * @param int $courseid The id of the course being tested
361855e6 2229 * @param int $userid The user being tested. You can set this to 0 or leave it blank to test the currently logged in user.
bbd3f2c4 2230 * @return bool
7cf1c7bd 2231 */
8a9e3fd7 2232function isstudent($courseid, $userid=0) {
71f9abf9 2233 global $USER, $CFG;
9425b25f 2234
2235 if (!empty($CFG->rolesactive)) {
5ec8a4f0 2236
2237 if ($courseid == 0) {
2238 $context = get_context_instance(CONTEXT_SYSTEM, SITEID);
2239 } else {
2240 $context = get_context_instance(CONTEXT_COURSE, $courseid);
2241 }
9425b25f 2242
5ec8a4f0 2243 if (!$userid) {
35a518c5 2244 if (empty($USER->id)) {
2245 return false;
2246 } else {
2247 return has_capability('moodle/legacy:student', $context, $USER->id, false);
2248 }
5ec8a4f0 2249 } else {
20aeb4b8 2250 return has_capability('moodle/legacy:student', $context, $userid, false);
5ec8a4f0 2251 }
5ec8a4f0 2252 }
f9903ed0 2253
2700d113 2254 if (empty($USER->id) and !$userid) {
7064e18f 2255 return false;
2256 }
2257
222ac91b 2258 if ($courseid == SITEID) {
2cc72e84 2259 if (!$userid) {
2260 $userid = $USER->id;
2261 }
2262 if (isguest($userid)) {
2263 return false;
2264 }
71f9abf9 2265 // a site teacher can never be a site student
2266 if (isteacher($courseid, $userid)) {
2267 return false;
2268 }
2700d113 2269 if ($CFG->allusersaresitestudents) {
2270 return record_exists('user', 'id', $userid);
2271 } else {
2272 return (record_exists('user_students', 'userid', $userid)
71f9abf9 2273 or record_exists('user_teachers', 'userid', $userid));
2700d113 2274 }
8f0cd6ef 2275 }
2cc72e84 2276
f9903ed0 2277 if (!$userid) {
1c349f7f 2278 if (empty($USER->studentview)) {
2279 return (!empty($USER->student[$courseid]));
2280 } else {
2281 return(!empty($USER->teacher[$courseid]) or isadmin());
2282 }
f9903ed0 2283 }
2284
ebc3bd2b 2285 // $timenow = time(); // todo: add time check below
f9903ed0 2286
b0ccd3fb 2287 return record_exists('user_students', 'userid', $userid, 'course', $courseid);
f9903ed0 2288}
2289
7cf1c7bd 2290/**
2291 * Determines if the specified user is logged in as guest.
2292 *
2293 * @uses $USER
361855e6 2294 * @param int $userid The user being tested. You can set this to 0 or leave it blank to test the currently logged in user.
bbd3f2c4 2295 * @return bool
7cf1c7bd 2296 */
da5c172a 2297function isguest($userid=0) {
18d8a6a7 2298 global $USER, $CFG;
2299
168fa2c1 2300// can not be used because admin has guest capability :-(
2301/*
18d8a6a7 2302 if (!empty($CFG->rolesactive)) {
2303
2304 $context = get_context_instance(CONTEXT_SYSTEM, SITEID);
2305
2306 if (!$userid) {
2307 return has_capability('moodle/legacy:guest', $context);
2308 } else {
2309 return has_capability('moodle/legacy:guest', $context, $userid);
2310 }
2311 }
168fa2c1 2312*/
da5c172a 2313 if (!$userid) {
b35e8568 2314 if (empty($USER->username)) {
2315 return false;
2316 }
b0ccd3fb 2317 return ($USER->username == 'guest');
da5c172a 2318 }
2319
b0ccd3fb 2320 return record_exists('user', 'id', $userid, 'username', 'guest');
da5c172a 2321}
2322
7cf1c7bd 2323/**
2324 * Determines if the currently logged in user is in editing mode
2325 *
2326 * @uses $USER
c6d15803 2327 * @param int $courseid The id of the course being tested
89dcb99d 2328 * @param user $user A {@link $USER} object. If null then the currently logged in user is used.
bbd3f2c4 2329 * @return bool
7cf1c7bd 2330 */
2c309dc2 2331function isediting($courseid, $user=NULL) {
3cf4fa0c 2332 global $USER;
2333 if (!$user) {
2334 $user = $USER;
2c309dc2 2335 }
9c9f7d77 2336 if (empty($user->editing)) {
2337 return false;
2338 }
2c309dc2 2339 return ($user->editing and isteacher($courseid, $user->id));
2340}
2341
7cf1c7bd 2342/**
2343 * Determines if the logged in user is currently moving an activity
2344 *
2345 * @uses $USER
c6d15803 2346 * @param int $courseid The id of the course being tested
bbd3f2c4 2347 * @return bool
7cf1c7bd 2348 */
7977cffd 2349function ismoving($courseid) {
7977cffd 2350 global $USER;
2351
2352 if (!empty($USER->activitycopy)) {
2353 return ($USER->activitycopycourse == $courseid);
2354 }
2355 return false;
2356}
2357
7cf1c7bd 2358/**
2359 * Given an object containing firstname and lastname
2360 * values, this function returns a string with the
2361 * full name of the person.
2362 * The result may depend on system settings
2363 * or language. 'override' will force both names
361855e6 2364 * to be used even if system settings specify one.
68fbd8e1 2365 *
7cf1c7bd 2366 * @uses $CFG
2367 * @uses $SESSION
68fbd8e1 2368 * @param object $user A {@link $USER} object to get full name of
2369 * @param bool $override If true then the name will be first name followed by last name rather than adhering to fullnamedisplay setting.
7cf1c7bd 2370 */
e2cd5065 2371function fullname($user, $override=false) {
b5cbb64d 2372
f374fb10 2373 global $CFG, $SESSION;
2374
6527c077 2375 if (!isset($user->firstname) and !isset($user->lastname)) {
2376 return '';
2377 }
2378
4c202228 2379 if (!$override) {
2380 if (!empty($CFG->forcefirstname)) {
2381 $user->firstname = $CFG->forcefirstname;
2382 }
2383 if (!empty($CFG->forcelastname)) {
2384 $user->lastname = $CFG->forcelastname;
2385 }
2386 }
2387
f374fb10 2388 if (!empty($SESSION->fullnamedisplay)) {
2389 $CFG->fullnamedisplay = $SESSION->fullnamedisplay;
2390 }
e2cd5065 2391
b5cbb64d 2392 if ($CFG->fullnamedisplay == 'firstname lastname') {
b0ccd3fb 2393 return $user->firstname .' '. $user->lastname;
b5cbb64d 2394
2395 } else if ($CFG->fullnamedisplay == 'lastname firstname') {
b0ccd3fb 2396 return $user->lastname .' '. $user->firstname;
e2cd5065 2397
b5cbb64d 2398 } else if ($CFG->fullnamedisplay == 'firstname') {
2399 if ($override) {
2400 return get_string('fullnamedisplay', '', $user);
2401 } else {
2402 return $user->firstname;
2403 }
2404 }
e2cd5065 2405
b5cbb64d 2406 return get_string('fullnamedisplay', '', $user);
e2cd5065 2407}
2408
7cf1c7bd 2409/**
2410 * Sets a moodle cookie with an encrypted string
2411 *
2412 * @uses $CFG
2f87145b 2413 * @uses DAYSECS
2414 * @uses HOURSECS
7cf1c7bd 2415 * @param string $thing The string to encrypt and place in a cookie
2416 */
f9903ed0 2417function set_moodle_cookie($thing) {
7185e073 2418 global $CFG;
482b6e6e 2419
7cbe6afe 2420 if ($thing == 'guest') { // Ignore guest account
2421 return;
2422 }
2423
482b6e6e 2424 $cookiename = 'MOODLEID_'.$CFG->sessioncookie;
f9903ed0 2425
2426 $days = 60;
7a5672c9 2427 $seconds = DAYSECS*$days;
f9903ed0 2428
7a5672c9 2429 setCookie($cookiename, '', time() - HOURSECS, '/');
b0ccd3fb 2430 setCookie($cookiename, rc4encrypt($thing), time()+$seconds, '/');
f9903ed0 2431}
2432
7cf1c7bd 2433/**
2434 * Gets a moodle cookie with an encrypted string
2435 *
2436 * @uses $CFG
2437 * @return string
2438 */
f9903ed0 2439function get_moodle_cookie() {
7185e073 2440 global $CFG;
2441
482b6e6e 2442 $cookiename = 'MOODLEID_'.$CFG->sessioncookie;
7185e073 2443
1079c8a8 2444 if (empty($_COOKIE[$cookiename])) {
b0ccd3fb 2445 return '';
1079c8a8 2446 } else {
7cbe6afe 2447 $thing = rc4decrypt($_COOKIE[$cookiename]);
2448 return ($thing == 'guest') ? '': $thing; // Ignore guest account
1079c8a8 2449 }
f9903ed0 2450}
2451
7cf1c7bd 2452/**
2453 * Returns true if an internal authentication method is being used.
2454 * if method not specified then, global default is assumed
2455 *
2456 * @uses $CFG
2457 * @param string $auth Form of authentication required
bbd3f2c4 2458 * @return bool
7cf1c7bd 2459 * @todo Outline auth types and provide code example
2460 */
39a5a35d 2461function is_internal_auth($auth='') {
ba7166c3 2462/// Returns true if an internal authentication method is being used.
a3f1f815 2463/// If auth not specified then global default is assumed
ba7166c3 2464
2465 global $CFG;
2466
a3f1f815 2467 if (empty($auth)) {
2468 $auth = $CFG->auth;
39a5a35d 2469 }
2470
a3f1f815 2471 return ($auth == "email" || $auth == "none" || $auth == "manual");
2472}
2473
8c3dba73 2474/**
2475 * Returns an array of user fields
2476 *
c6d15803 2477 * @uses $CFG
2478 * @uses $db
2479 * @return array User field/column names
8c3dba73 2480 */
a3f1f815 2481function get_user_fieldnames() {
a3f1f815 2482
2483 global $CFG, $db;
2484
2485 $fieldarray = $db->MetaColumnNames($CFG->prefix.'user');
2486 unset($fieldarray['ID']);
2487
2488 return $fieldarray;
ba7166c3 2489}
f9903ed0 2490
7cf1c7bd 2491/**
2492 * Creates a bare-bones user record
2493 *
2494 * @uses $CFG
7cf1c7bd 2495 * @param string $username New user's username to add to record
2496 * @param string $password New user's password to add to record
2497 * @param string $auth Form of authentication required
68fbd8e1 2498 * @return object A {@link $USER} object
7cf1c7bd 2499 * @todo Outline auth types and provide code example
2500 */
71f9abf9 2501function create_user_record($username, $password, $auth='') {
366dfa60 2502 global $CFG;
71f9abf9 2503
1e22bc9c 2504 //just in case check text case
2505 $username = trim(moodle_strtolower($username));
71f9abf9 2506
3271b70f 2507 if (function_exists('auth_get_userinfo')) {
e858f9da 2508 if ($newinfo = auth_get_userinfo($username)) {
b36a8fc4 2509 $newinfo = truncate_userinfo($newinfo);
34daec9b 2510 foreach ($newinfo as $key => $value){
9f44d972 2511 $newuser->$key = addslashes(stripslashes($value)); // Just in case
e858f9da 2512 }
2513 }
2514 }
f9903ed0 2515
85a1d4c9 2516 if (!empty($newuser->email)) {
2517 if (email_is_not_allowed($newuser->email)) {
2518 unset($newuser->email);
2519 }
2520 }
2521
71f9abf9 2522 $newuser->auth = (empty($auth)) ? $CFG->auth : $auth;
faebaf0f 2523 $newuser->username = $username;
df193157 2524 update_internal_user_password($newuser, $password, false);
a0bac19d 2525 $newuser->lang = $CFG->lang;
faebaf0f 2526 $newuser->confirmed = 1;
d96466d2 2527 $newuser->lastip = getremoteaddr();
faebaf0f 2528 $newuser->timemodified = time();
f9903ed0 2529
b0ccd3fb 2530 if (insert_record('user', $newuser)) {
7c12949d 2531 $user = get_complete_user_data('username', $newuser->username);
d35757eb 2532 if($CFG->{'auth_'.$newuser->auth.'_forcechangepassword'}){
4b598ff4 2533 set_user_preference('auth_forcepasswordchange', 1, $user->id);
d35757eb 2534 }
2535 return $user;
faebaf0f 2536 }
2537 return false;
2538}
2539
7cf1c7bd 2540/**
2541 * Will update a local user record from an external source
2542 *
2543 * @uses $CFG
2544 * @param string $username New user's username to add to record
89dcb99d 2545 * @return user A {@link $USER} object
7cf1c7bd 2546 */
d35757eb 2547function update_user_record($username) {
d35757eb 2548 global $CFG;
2549
2550 if (function_exists('auth_get_userinfo')) {
2551 $username = trim(moodle_strtolower($username)); /// just in case check text case
2552
b78fbdac 2553 $oldinfo = get_record('user', 'username', $username, '','','','', 'username, auth');
2554 $authconfig = get_config('auth/' . $oldinfo->auth);
2555
d35757eb 2556 if ($newinfo = auth_get_userinfo($username)) {
4b598ff4 2557 $newinfo = truncate_userinfo($newinfo);
d35757eb 2558 foreach ($newinfo as $key => $value){
b78fbdac 2559 $confkey = 'field_updatelocal_' . $key;
2560 if (!empty($authconfig->$confkey) && $authconfig->$confkey === 'onlogin') {
d35757eb 2561 $value = addslashes(stripslashes($value)); // Just in case
e1ecf0a0 2562 set_field('user', $key, $value, 'username', $username)
4b598ff4 2563 || error_log("Error updating $key for $username");
d35757eb 2564 }
2565 }
2566 }
2567 }
7c12949d 2568 return get_complete_user_data('username', $username);
d35757eb 2569}
0609562b 2570
b36a8fc4 2571function truncate_userinfo($info) {
2572/// will truncate userinfo as it comes from auth_get_userinfo (from external auth)
2573/// which may have large fields
2574
2575 // define the limits
2576 $limit = array(
2577 'username' => 100,
1c66bf59 2578 'idnumber' => 64,
8bcd295c 2579 'firstname' => 100,
2580 'lastname' => 100,
b36a8fc4 2581 'email' => 100,
2582 'icq' => 15,
2583 'phone1' => 20,
2584 'phone2' => 20,
2585 'institution' => 40,
2586 'department' => 30,
2587 'address' => 70,
2588 'city' => 20,
2589 'country' => 2,
2590 'url' => 255,
2591 );
361855e6 2592
b36a8fc4 2593 // apply where needed
2594 foreach (array_keys($info) as $key) {
2595 if (!empty($limit[$key])) {
adfc03f9 2596 $info[$key] = trim(substr($info[$key],0, $limit[$key]));
361855e6 2597 }
b36a8fc4 2598 }
361855e6 2599
b36a8fc4 2600 return $info;
2601}
2602
7cf1c7bd 2603/**
2604 * Retrieve the guest user object
2605 *
2606 * @uses $CFG
89dcb99d 2607 * @return user A {@link $USER} object
7cf1c7bd 2608 */
0609562b 2609function guest_user() {
2610 global $CFG;
2611
b0ccd3fb 2612 if ($newuser = get_record('user', 'username', 'guest')) {
0609562b 2613 $newuser->loggedin = true;
2614 $newuser->confirmed = 1;
2615 $newuser->site = $CFG->wwwroot;
2616 $newuser->lang = $CFG->lang;
d96466d2 2617 $newuser->lastip = getremoteaddr();
0609562b 2618 }
2619
2620 return $newuser;
2621}
2622
7cf1c7bd 2623/**
2624 * Given a username and password, this function looks them
2625 * up using the currently selected authentication mechanism,
2626 * and if the authentication is successful, it returns a
2627 * valid $user object from the 'user' table.
361855e6 2628 *
7cf1c7bd 2629 * Uses auth_ functions from the currently active auth module
2630 *
2631 * @uses $CFG
361855e6 2632 * @param string $username User's username
2633 * @param string $password User's password
89dcb99d 2634 * @return user|flase A {@link $USER} object or false if error
7cf1c7bd 2635 */
faebaf0f 2636function authenticate_user_login($username, $password) {
faebaf0f 2637
2638 global $CFG;
2639
27286aeb 2640 // First try to find the user in the database
466558e3 2641
7c12949d 2642 if (!$user = get_complete_user_data('username', $username)) {
18f16d61 2643 $user->id = 0; // Not a user
2644 $user->auth = $CFG->auth;
2645 }
39a5a35d 2646
27286aeb 2647 // Sort out the authentication method we are using.
39a5a35d 2648
27286aeb 2649 if (empty($CFG->auth)) {
b0ccd3fb 2650 $CFG->auth = 'manual'; // Default authentication module
27286aeb 2651 }
39a5a35d 2652
27286aeb 2653 if (empty($user->auth)) { // For some reason it isn't set yet
ccb3585f 2654 if (!empty($user->id) && (isadmin($user->id) || isguest($user->id))) {
71f9abf9 2655 $auth = 'manual'; // Always assume these guys are internal
27286aeb 2656 } else {
71f9abf9 2657 $auth = $CFG->auth; // Normal users default to site method
27286aeb 2658 }
d35757eb 2659 // update user record from external DB
2660 if ($user->auth != 'manual' && $user->auth != 'email') {
2661 $user = update_user_record($username);
2662 }
71f9abf9 2663 } else {
2664 $auth = $user->auth;
27286aeb 2665 }
8f0cd6ef 2666
ce791f88 2667 if (detect_munged_arguments($auth, 0)) { // For safety on the next require
2668 return false;
2669 }
2670
b0ccd3fb 2671 if (!file_exists($CFG->dirroot .'/auth/'. $auth .'/lib.php')) {
2672 $auth = 'manual'; // Can't find auth module, default to internal
466558e3 2673 }
2674
b0ccd3fb 2675 require_once($CFG->dirroot .'/auth/'. $auth .'/lib.php');
faebaf0f 2676
2677 if (auth_user_login($username, $password)) { // Successful authentication
d613daf0 2678 if ($user->id) { // User already exists in database
71f9abf9 2679 if (empty($user->auth)) { // For some reason auth isn't set yet
2680 set_field('user', 'auth', $auth, 'username', $username);
2681 }
df193157 2682 update_internal_user_password($user, $password);
366dfa60 2683 if (!is_internal_auth()) { // update user record from external DB
d35757eb 2684 $user = update_user_record($username);
2685 }
faebaf0f 2686 } else {
71f9abf9 2687 $user = create_user_record($username, $password, $auth);
faebaf0f 2688 }
89b54325 2689
e582b65e 2690 if (function_exists('auth_iscreator')) { // Check if the user is a creator
f894a791 2691 $useriscreator = auth_iscreator($username);
2692 if (!is_null($useriscreator)) {
2693 if ($useriscreator) {
2694 if (! record_exists('user_coursecreators', 'userid', $user->id)) {
2695 $cdata->userid = $user->id;
2696 if (! insert_record('user_coursecreators', $cdata)) {
2697 error('Cannot add user to course creators.');
2698 }
39a5a35d 2699 }
f894a791 2700 } else {
2701 if (record_exists('user_coursecreators', 'userid', $user->id)) {
2702 if (! delete_records('user_coursecreators', 'userid', $user->id)) {
2703 error('Cannot remove user from course creators.');
2704 }
39a5a35d 2705 }
2706 }
361855e6 2707 }
39a5a35d 2708 }
01af6da6 2709
2710 /// Log in to a second system if necessary
2711 if (!empty($CFG->sso)) {
2712 include_once($CFG->dirroot .'/sso/'. $CFG->sso .'/lib.php');
2713 if (function_exists('sso_user_login')) {
2714 if (!sso_user_login($username, $password)) { // Perform the signon process
2715 notify('Second sign-on failed');
2716 }
2717 }
2718 }
2719
e582b65e 2720 return $user;
9d3c795c 2721
e582b65e 2722 } else {
f64c1ef6 2723 add_to_log(0, 'login', 'error', 'index.php', $username);
f52d48db 2724 error_log('[client '.$_SERVER['REMOTE_ADDR']."] $CFG->wwwroot Failed Login: $username ".$_SERVER['HTTP_USER_AGENT']);
e582b65e 2725 return false;
2726 }
f9903ed0 2727}
2728
df193157 2729/**
4908ad3e 2730 * Compare password against hash stored in internal user table.
df193157 2731 * If necessary it also updates the stored hash to new format.
2732 *
2733 * @param object user
2734 * @param string plain text password
2735 * @return bool is password valid?
2736 */
2737function validate_internal_user_password(&$user, $password) {
2738 global $CFG;
2739
4908ad3e 2740 if (!isset($CFG->passwordsaltmain)) {
2741 $CFG->passwordsaltmain = '';
2742 }
2743
df193157 2744 $validated = false;
2745
2746 if (!empty($CFG->unicodedb)) {
2747 $textlib = textlib_get_instance();
2748 $convpassword = $textlib->convert($password, 'UTF-8', get_string('oldcharset'));
2749 } else {
4908ad3e 2750 $convpassword = $password; //no conversion yet
df193157 2751 }
2752
4908ad3e 2753 if ($user->password == md5($password.$CFG->passwordsaltmain) or $user->password == md5($password)
2754 or $user->password == md5($convpassword.$CFG->passwordsaltmain) or $user->password == md5($convpassword)) {
df193157 2755 $validated = true;
4908ad3e 2756 } else {
aaeaa4b0 2757 for ($i=1; $i<=20; $i++) { //20 alternative salts should be enough, right?
4908ad3e 2758 $alt = 'passwordsaltalt'.$i;
2759 if (!empty($CFG->$alt)) {
2760 if ($user->password == md5($password.$CFG->$alt) or $user->password == md5($convpassword.$CFG->$alt)) {
2761 $validated = true;
2762 break;
2763 }
2764 }
2765 }
df193157 2766 }
2767
2768 if ($validated) {
4908ad3e 2769 // force update of password hash using latest main password salt and encoding if needed
df193157 2770 update_internal_user_password($user, $password);
2771 }
2772
2773 return $validated;
2774}
2775
2776/**
2777 * Calculate hashed value from password using current hash mechanism.
df193157 2778 *
2779 * @param string password
2780 * @return string password hash
2781 */
2782function hash_internal_user_password($password) {
4908ad3e 2783 global $CFG;
2784
2785 if (isset($CFG->passwordsaltmain)) {
2786 return md5($password.$CFG->passwordsaltmain);
2787 } else {
2788 return md5($password);
2789 }
df193157 2790}
2791
2792/**
2793 * Update pssword hash in user object.
2794 *
2795 * @param object user
2796 * @param string plain text password
2797 * @param bool store changes also in db, default true
2798 * @return true if hash changed
2799 */
2800function update_internal_user_password(&$user, $password, $storeindb=true) {
2801 global $CFG;
2802
2803 if (!empty($CFG->{$user->auth.'_preventpassindb'})) {
2804 $hashedpassword = 'not cached';
2805 } else {
2806 $hashedpassword = hash_internal_user_password($password);
2807 }
2808
2809 if ($user->password != $hashedpassword) {
2810 if ($storeindb) {
2811 if (!set_field('user', 'password', $hashedpassword, 'username', $user->username)) {
2812 return false;
2813 }
2814 }
2815 $user->password = $hashedpassword;
2816 }
2817 return true;
2818}
2819
7c12949d 2820/**
2821 * Get a complete user record, which includes all the info
2822 * in the user record, as well as membership information
2823 * Intended for setting as $USER session variable
2824 *
2825 * @uses $CFG
2826 * @uses SITEID
e1ecf0a0 2827 * @param string $field The user field to be checked for a given value.
7c12949d 2828 * @param string $value The value to match for $field.
2829 * @return user A {@link $USER} object.
2830 */
2831function get_complete_user_data($field, $value) {
2832
2833 global $CFG;
2834
2835 if (!$field || !$value) {
2836 return false;
2837 }
2838
2839/// Get all the basic user data
2840
2841 if (! $user = get_record_select('user', $field .' = \''. $value .'\' AND deleted <> \'1\'')) {
2842 return false;
2843 }
2844
2845/// Add membership information
2846
2847 if ($admins = get_records('user_admins', 'userid', $user->id)) {
2848 $user->admin = true;
2849 }
2850
2851 $user->student[SITEID] = isstudent(SITEID, $user->id);
2852
f9667a5a 2853/// Load the list of enrolment plugin enabled
7c12949d 2854
f9667a5a 2855 if (!($plugins = explode(',', $CFG->enrol_plugins_enabled))) {
2856 $plugins = array($CFG->enrol);
2857 }
2858 require_once($CFG->dirroot .'/enrol/enrol.class.php');
2859 foreach ($plugins as $p) {
2860 $enrol = enrolment_factory::factory($p);
2861 if (method_exists($enrol, 'get_student_courses')) {
2862 $enrol->get_student_courses($user);
2863 }
2864 if (method_exists($enrol, 'get_teacher_courses')) {
2865 $enrol->get_teacher_courses($user);
2866 }
2867 unset($enrol);
2868 }
7c12949d 2869
2870/// Get various settings and preferences
2871
2872 if ($displays = get_records('course_display', 'userid', $user->id)) {
2873 foreach ($displays as $display) {
2874 $user->display[$display->course] = $display->display;
2875 }
2876 }
2877
2878 if ($preferences = get_records('user_preferences', 'userid', $user->id)) {
2879 foreach ($preferences as $preference) {
2880 $user->preference[$preference->name] = $preference->value;
2881 }
2882 }
2883
2884 if ($groups = get_records('groups_members', 'userid', $user->id)) {
2885 foreach ($groups as $groupmember) {
2886 $courseid = get_field('groups', 'courseid', 'id', $groupmember->groupid);
fa22fd5f 2887 //change this to 2D array so we can put multiple groups in a course
2888 $user->groupmember[$courseid][] = $groupmember->groupid;
7c12949d 2889 }
2890 }
2891
2892/// Rewrite some variables if necessary
2893 if (!empty($user->description)) {
2894 $user->description = true; // No need to cart all of it around
2895 }
2896 if ($user->username == 'guest') {
2897 $user->lang = $CFG->lang; // Guest language always same as site
2898 $user->firstname = get_string('guestuser'); // Name always in current language
2899 $user->lastname = ' ';
2900 }
2901
2902 $user->loggedin = true;
2903 $user->site = $CFG->wwwroot; // for added security, store the site in the session
2904 $user->sesskey = random_string(10);
2905 $user->sessionIP = md5(getremoteaddr()); // Store the current IP in the session
2906
2907 return $user;
2908
2909}
2910
2911function get_user_info_from_db($field, $value) { // For backward compatibility
2912 return get_complete_user_data($field, $value);
2913}
2914
e1ecf0a0 2915/*
7c12949d 2916 * When logging in, this function is run to set certain preferences
2917 * for the current SESSION
2918 */
2919function set_login_session_preferences() {
7c7ca1b5 2920 global $SESSION, $CFG;
7c12949d 2921
2922 $SESSION->justloggedin = true;
2923
2924 unset($SESSION->lang);
7c12949d 2925
2926 // Restore the calendar filters, if saved
2927 if (intval(get_user_preferences('calendar_persistflt', 0))) {
2928 include_once($CFG->dirroot.'/calendar/lib.php');
a266c904 2929 calendar_set_filters_status(get_user_preferences('calendav_savedflt', 0xff));
7c12949d 2930 }
2931}
2932
2933
7cf1c7bd 2934/**
2935 * Enrols (or re-enrols) a student in a given course
2936 *
e1ecf0a0 2937 * NOTE: Defaults to 'manual' enrolment - enrolment plugins
a6d114e6 2938 * must set it explicitly.
2939 *
bbd3f2c4 2940 * @uses $CFG
c6d15803 2941 * @param int $userid The id of the user that is being tested against. Set this to 0 if you would just like to test against the currently logged in user.
bbd3f2c4 2942 * @param int $courseid The id of the course that is being viewed
c6d15803 2943 * @param int $timestart ?
2944 * @param int $timeend ?
bbd3f2c4 2945 * @param string $enrol ?
2946 * @return bool
7cf1c7bd 2947 * @todo Finish documenting this function
2948 */
a6d114e6 2949function enrol_student($userid, $courseid, $timestart=0, $timeend=0, $enrol='manual') {
b40bc478 2950
0a0bcdd2 2951 global $CFG, $USER;
75169b06 2952
b0ccd3fb 2953 if (!$course = get_record('course', 'id', $courseid)) { // Check course
3041b0f8 2954 return false;
4d312bbe 2955 }
b0ccd3fb 2956 if (!$user = get_record('user', 'id', $userid)) { // Check user
631cf796 2957 return false;
2958 }
b61efafb 2959 // enrol the student in any parent meta courses...
bbd3f2c4 2960 if ($parents = get_records('course_meta', 'child_course', $courseid)) {
b61efafb 2961 foreach ($parents as $parent) {
755c8d58 2962 enrol_student($userid, $parent->parent_course, $timestart, $timeend,'metacourse');
0a0bcdd2 2963 // if we're enrolling ourselves in the child course, add the parent courses to USER too
2964 // otherwise they'll have to logout and in again to get it
2965 // http://moodle.org/mod/forum/post.php?reply=185699
2966 if (!empty($USER) && $userid == $USER->id) {
2967 $USER->student[$parent->parent_course] = true;
2968 }
b61efafb 2969 }
2970 }
92318548 2971
b0ccd3fb 2972 if ($student = get_record('user_students', 'userid', $userid, 'course', $courseid)) {
631cf796 2973 $student->timestart = $timestart;
2974 $student->timeend = $timeend;
2975 $student->time = time();
6e8ca983 2976 $student->enrol = $enrol;
b0ccd3fb 2977 return update_record('user_students', $student);
361855e6 2978
631cf796 2979 } else {
75169b06 2980 require_once("$CFG->dirroot/mod/forum/lib.php");
2f3b54ae 2981 forum_add_user($userid, $courseid);
2982
631cf796 2983 $student->userid = $userid;
2984 $student->course = $courseid;
2985 $student->timestart = $timestart;
2986 $student->timeend = $timeend;
2987 $student->time = time();
6e8ca983 2988 $student->enrol = $enrol;
b0ccd3fb 2989 return insert_record('user_students', $student);
631cf796 2990 }
d7facad8 2991}
2992
7cf1c7bd 2993/**
2994 * Unenrols a student from a given course
2995 *
c6d15803 2996 * @param int $courseid The id of the course that is being viewed, if any
2997 * @param int $userid The id of the user that is being tested against.
bbd3f2c4 2998 * @return bool
7cf1c7bd 2999 */
9fa62805 3000function unenrol_student($userid, $courseid=0) {
79a10294 3001 global $CFG;
d7facad8 3002
9fa62805 3003 if ($courseid) {
9fa49e22 3004 /// First delete any crucial stuff that might still send mail
b0ccd3fb 3005 if ($forums = get_records('forum', 'course', $courseid)) {
9fa49e22 3006 foreach ($forums as $forum) {
b0ccd3fb 3007 delete_records('forum_subscriptions', 'forum', $forum->id, 'userid', $userid);
9fa62805 3008 }
3009 }
3010 if ($groups = get_groups($courseid, $userid)) {
3011 foreach ($groups as $group) {
b0ccd3fb 3012 delete_records('groups_members', 'groupid', $group->id, 'userid', $userid);
bb09fb11 3013 }
f9903ed0 3014 }
79a10294 3015 // unenrol the student from any parent meta courses...
5f37b628 3016 if ($parents = get_records('course_meta','child_course',$courseid)) {
b61efafb 3017 foreach ($parents as $parent) {
79a10294 3018 if (!record_exists_sql('SELECT us.id FROM '.$CFG->prefix.'user_students us, '
3019 .$CFG->prefix.'course_meta cm WHERE cm.child_course = us.course
3020 AND us.userid = '.$userid .' AND us.course != '.$courseid)) {
3021 unenrol_student($userid, $parent->parent_course);
3022 }
b61efafb 3023 }
3024 }
b0ccd3fb 3025 return delete_records('user_students', 'userid', $userid, 'course', $courseid);
9fa49e22 3026
f9903ed0 3027 } else {
b0ccd3fb 3028 delete_records('forum_subscriptions', 'userid', $userid);
3029 delete_records('groups_members', 'userid', $userid);
3030 return delete_records('user_students', 'userid', $userid);
f9903ed0 3031 }
3032}
3033
7cf1c7bd 3034/**
3035 * Add a teacher to a given course
3036 *
bbd3f2c4 3037 * @uses $USER
c6d15803 3038 * @param int $userid The id of the user that is being tested against. Set this to 0 if you would just like to test against the currently logged in user.
bbd3f2c4 3039 * @param int $courseid The id of the course that is being viewed, if any
c6d15803 3040 * @param int $editall ?
7cf1c7bd 3041 * @param string $role ?
c6d15803 3042 * @param int $timestart ?
3043 * @param int $timeend ?
bbd3f2c4 3044 * @param string $enrol ?
3045 * @return bool
7cf1c7bd 3046 * @todo Finish documenting this function
3047 */
6e8ca983 3048function add_teacher($userid, $courseid, $editall=1, $role='', $timestart=0, $timeend=0, $enrol='manual') {
7b5944cd 3049 global $CFG;
3041b0f8 3050
61451a36 3051 if ($teacher = get_record('user_teachers', 'userid', $userid, 'course', $courseid)) {
b40bc478 3052 $newteacher = NULL;
3053 $newteacher->id = $teacher->id;
3054 $newteacher->editall = $editall;
6e8ca983 3055 $newteacher->enrol = $enrol;
b40bc478 3056 if ($role) {
3057 $newteacher->role = $role;
3058 }
3059 if ($timestart) {
3060 $newteacher->timestart = $timestart;
3041b0f8 3061 }
b40bc478 3062 if ($timeend) {
3063 $newteacher->timeend = $timeend;
3064 }
3065 return update_record('user_teachers', $newteacher);
3041b0f8 3066 }
61451a36 3067
b0ccd3fb 3068 if (!record_exists('user', 'id', $userid)) {
61451a36 3069 return false; // no such user
3070 }
3071
b0ccd3fb 3072 if (!record_exists('course', 'id', $courseid)) {
61451a36 3073 return false; // no such course
3074 }
3075
3076 $teacher = NULL;
3077 $teacher->userid = $userid;
3078 $teacher->course = $courseid;
3079 $teacher->editall = $editall;
3080 $teacher->role = $role;
aef46c08 3081 $teacher->enrol = $enrol;
5a2dea02 3082 $teacher->timemodified = time();
aef46c08 3083 $teacher->timestart = $timestart;
3084 $teacher->timeend = $timeend;
b0ccd3fb 3085 if ($student = get_record('user_students', 'userid', $userid, 'course', $courseid)) {
5a2dea02 3086 $teacher->timestart = $student->timestart;
3087 $teacher->timeend = $student->timeend;
3088 $teacher->timeaccess = $student->timeaccess;
3089 }
61451a36 3090
b0ccd3fb 3091 if (record_exists('user_teachers', 'course', $courseid)) {
61451a36 3092 $teacher->authority = 2;
3093 } else {
3094 $teacher->authority = 1;
3095 }
b0ccd3fb 3096 delete_records('user_students', 'userid', $userid, 'course', $courseid); // Unenrol as student
8f0cd6ef 3097
709f0ec8 3098 /// Add forum subscriptions for new users
463a92db 3099 require_once($CFG->dirroot.'/mod/forum/lib.php');
7b5944cd 3100 forum_add_user($userid, $courseid);
61451a36 3101
b0ccd3fb 3102 return insert_record('user_teachers', $teacher);
61451a36 3103
3041b0f8 3104}
3105
7cf1c7bd 3106/**
3107 * Removes a teacher from a given course (or ALL courses)
3108 * Does not delete the user account
3109 *
c6d15803 3110 * @param int $courseid The id of the course that is being viewed, if any
361855e6 3111 * @param int $userid The id of the user that is being tested against.
bbd3f2c4 3112 * @return bool
7cf1c7bd 3113 */
3041b0f8 3114function remove_teacher($userid, $courseid=0) {
3041b0f8 3115 if ($courseid) {
9fa49e22 3116 /// First delete any crucial stuff that might still send mail
b0ccd3fb 3117 if ($forums = get_records('forum', 'course', $courseid)) {
9fa49e22 3118 foreach ($forums as $forum) {
b0ccd3fb 3119 delete_records('forum_subscriptions', 'forum', $forum->id, 'userid', $userid);
9fa49e22 3120 }
3121 }
b02193e6 3122
3123 /// Next if the teacher is not registered as a student, but is
3124 /// a member of a group, remove them from the group.
3125 if (!isstudent($courseid, $userid)) {
3126 if ($groups = get_groups($courseid, $userid)) {
3127 foreach ($groups as $group) {
b0ccd3fb 3128 delete_records('groups_members', 'groupid', $group->id, 'userid', $userid);
b02193e6 3129 }
3130 }
3131 }
3132
b0ccd3fb 3133 return delete_records('user_teachers', 'userid', $userid, 'course', $courseid);
57507290 3134 } else {
b0ccd3fb 3135 delete_records('forum_subscriptions', 'userid', $userid);
3136 return delete_records('user_teachers', 'userid', $userid);
57507290 3137 }
f9903ed0 3138}
3139
7cf1c7bd 3140/**
3141 * Add a creator to the site
3142 *
361855e6 3143 * @param int $userid The id of the user that is being tested against.
bbd3f2c4 3144 * @return bool
7cf1c7bd 3145 */
3041b0f8 3146function add_creator($userid) {
3041b0f8 3147
b0ccd3fb 3148 if (!record_exists('user_admins', 'userid', $userid)) {
3149 if (record_exists('user', 'id', $userid)) {
3041b0f8 3150 $creator->userid = $userid;
b0ccd3fb 3151 return insert_record('user_coursecreators', $creator);
3041b0f8 3152 }
3153 return false;
3154 }
3155 return true;
3156}
3157
7cf1c7bd 3158/**
3159 * Remove a creator from a site
3160 *
bbd3f2c4 3161 * @uses $db
c6d15803 3162 * @param int $userid The id of the user that is being tested against.
bbd3f2c4 3163 * @return bool
7cf1c7bd 3164 */
3041b0f8 3165function remove_creator($userid) {
3041b0f8 3166 global $db;
3167
b0ccd3fb 3168 return delete_records('user_coursecreators', 'userid', $userid);
3041b0f8 3169}
3170
7cf1c7bd 3171/**
3172 * Add an admin to a site
3173 *
3174 * @uses SITEID
c6d15803 3175 * @param int $userid The id of the user that is being tested against.
bbd3f2c4 3176 * @return bool
7cf1c7bd 3177 */
3041b0f8 3178function add_admin($userid) {
3041b0f8 3179
b0ccd3fb 3180 if (!record_exists('user_admins', 'userid', $userid)) {
3181 if (record_exists('user', 'id', $userid)) {
3041b0f8 3182 $admin->userid = $userid;
361855e6 3183
f950af3c 3184 // any admin is also a teacher on the site course
222ac91b 3185 if (!record_exists('user_teachers', 'course', SITEID, 'userid', $userid)) {
3186 if (!add_teacher($userid, SITEID)) {
f950af3c 3187 return false;
3188 }
3189 }
361855e6 3190
b0ccd3fb 3191 return insert_record('user_admins', $admin);
3041b0f8 3192 }
3193 return false;
3194 }
3195 return true;
3196}
3197
7cf1c7bd 3198/**
3199 * Removes an admin from a site
3200 *
bbd3f2c4 3201 * @uses $db
3202 * @uses SITEID
c6d15803 3203 * @param int $userid The id of the user that is being tested against.
bbd3f2c4 3204 * @return bool
7cf1c7bd