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