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