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