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