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 | // // |
56a1a882 |
10 | // Copyright (C) 1999 onwards 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 |
89dcb99d |
34 | * @license http://www.gnu.org/copyleft/gpl.html GNU Public License |
7cf1c7bd |
35 | * @package moodlecore |
36 | */ |
e1ecf0a0 |
37 | |
bbd3f2c4 |
38 | /// CONSTANTS (Encased in phpdoc proper comments)///////////////////////// |
f374fb10 |
39 | |
6b94a807 |
40 | /** |
41 | * Used by some scripts to check they are being called by Moodle |
42 | */ |
43 | define('MOODLE_INTERNAL', true); |
44 | |
bbd3f2c4 |
45 | /// Date and time constants /// |
5602f7cf |
46 | /** |
47 | * Time constant - the number of seconds in a year |
48 | */ |
5602f7cf |
49 | define('YEARSECS', 31536000); |
50 | |
7a5672c9 |
51 | /** |
2f87145b |
52 | * Time constant - the number of seconds in a week |
7a5672c9 |
53 | */ |
361855e6 |
54 | define('WEEKSECS', 604800); |
2f87145b |
55 | |
56 | /** |
57 | * Time constant - the number of seconds in a day |
58 | */ |
7a5672c9 |
59 | define('DAYSECS', 86400); |
2f87145b |
60 | |
61 | /** |
62 | * Time constant - the number of seconds in an hour |
63 | */ |
7a5672c9 |
64 | define('HOURSECS', 3600); |
2f87145b |
65 | |
66 | /** |
67 | * Time constant - the number of seconds in a minute |
68 | */ |
7a5672c9 |
69 | define('MINSECS', 60); |
2f87145b |
70 | |
71 | /** |
72 | * Time constant - the number of minutes in a day |
73 | */ |
7a5672c9 |
74 | define('DAYMINS', 1440); |
2f87145b |
75 | |
76 | /** |
77 | * Time constant - the number of minutes in an hour |
78 | */ |
7a5672c9 |
79 | define('HOURMINS', 60); |
f9903ed0 |
80 | |
c59733ef |
81 | /// Parameter constants - every call to optional_param(), required_param() /// |
82 | /// or clean_param() should have a specified type of parameter. ////////////// |
83 | |
e0d346ff |
84 | /** |
038ba6aa |
85 | * PARAM_RAW specifies a parameter that is not cleaned/processed in any way; |
86 | * originally was 0, but changed because we need to detect unknown |
87 | * parameter types and swiched order in clean_param(). |
e0d346ff |
88 | */ |
038ba6aa |
89 | define('PARAM_RAW', 666); |
bbd3f2c4 |
90 | |
91 | /** |
c59733ef |
92 | * PARAM_CLEAN - obsoleted, please try to use more specific type of parameter. |
93 | * It was one of the first types, that is why it is abused so much ;-) |
bbd3f2c4 |
94 | */ |
2ae28153 |
95 | define('PARAM_CLEAN', 0x0001); |
bbd3f2c4 |
96 | |
97 | /** |
c59733ef |
98 | * PARAM_INT - integers only, use when expecting only numbers. |
bbd3f2c4 |
99 | */ |
2ae28153 |
100 | define('PARAM_INT', 0x0002); |
bbd3f2c4 |
101 | |
102 | /** |
103 | * PARAM_INTEGER - an alias for PARAM_INT |
104 | */ |
105 | define('PARAM_INTEGER', 0x0002); |
106 | |
9dae915a |
107 | /** |
6e73ae10 |
108 | * PARAM_FLOAT - a real/floating point number. |
109 | */ |
110 | define('PARAM_FLOAT', 0x000a); |
111 | |
112 | /** |
113 | * PARAM_NUMBER - alias of PARAM_FLOAT, deprecated - do not use |
9dae915a |
114 | */ |
115 | define('PARAM_NUMBER', 0x000a); |
116 | |
bbd3f2c4 |
117 | /** |
6e73ae10 |
118 | * PARAM_ALPHA - contains only english ascii letters a-zA-Z. |
bbd3f2c4 |
119 | */ |
2ae28153 |
120 | define('PARAM_ALPHA', 0x0004); |
bbd3f2c4 |
121 | |
122 | /** |
285b83ad |
123 | * PARAM_ALPHAEXT the same contents as PARAM_ALPHA plus the chars in quotes: "_-" allowed |
6e73ae10 |
124 | * NOTE: originally this allowed "/" too, please use PARAM_SAFEPATH if "/" needed |
125 | */ |
126 | define('PARAM_ALPHAEXT', 0x2000); |
127 | |
128 | /** |
129 | * PARAM_ALPHANUM - expected numbers and letters only. |
bbd3f2c4 |
130 | */ |
6e73ae10 |
131 | define('PARAM_ALPHANUM', 0x0400); |
bbd3f2c4 |
132 | |
133 | /** |
6e73ae10 |
134 | * PARAM_ALPHANUMEXT - expected numbers, letters only and _-. |
bbd3f2c4 |
135 | */ |
db4f63e9 |
136 | define('PARAM_ALPHANUMEXT', 0x4000); |
6e73ae10 |
137 | |
138 | /** |
139 | * PARAM_ACTION - an alias for PARAM_ALPHANUMEXT, use for various actions in formas and urls |
140 | * NOTE: originally alias for PARAM_APLHA |
141 | */ |
db4f63e9 |
142 | define('PARAM_ACTION', 0x4000); |
6e73ae10 |
143 | |
144 | /** |
145 | * PARAM_FORMAT - an alias for PARAM_ALPHANUMEXT, use for names of plugins, formats, etc. |
146 | * NOTE: originally alias for PARAM_APLHA |
147 | */ |
db4f63e9 |
148 | define('PARAM_FORMAT', 0x4000); |
bbd3f2c4 |
149 | |
150 | /** |
c59733ef |
151 | * PARAM_NOTAGS - all html tags are stripped from the text. Do not abuse this type. |
bbd3f2c4 |
152 | */ |
2ae28153 |
153 | define('PARAM_NOTAGS', 0x0008); |
bbd3f2c4 |
154 | |
6e73ae10 |
155 | /** |
c4ea5e78 |
156 | * PARAM_MULTILANG - alias of PARAM_TEXT. |
31f26796 |
157 | */ |
158 | define('PARAM_MULTILANG', 0x0009); |
159 | |
6e73ae10 |
160 | /** |
c4ea5e78 |
161 | * PARAM_TEXT - general plain text compatible with multilang filter, no other html tags. |
162 | */ |
163 | define('PARAM_TEXT', 0x0009); |
164 | |
bbd3f2c4 |
165 | /** |
c59733ef |
166 | * PARAM_FILE - safe file name, all dangerous chars are stripped, protects against XSS, SQL injections and directory traversals |
bbd3f2c4 |
167 | */ |
2ae28153 |
168 | define('PARAM_FILE', 0x0010); |
bbd3f2c4 |
169 | |
bed79931 |
170 | /** |
171 | * PARAM_CLEANFILE - alias of PARAM_FILE; originally was removing regional chars too |
172 | * NOTE: obsoleted do not use anymore |
173 | */ |
174 | define('PARAM_CLEANFILE',0x0010); |
175 | |
bcef0319 |
176 | /** |
6e73ae10 |
177 | * PARAM_TAG - one tag (interests, blogs, etc.) - mostly international characters and space, <> not supported |
bcef0319 |
178 | */ |
179 | define('PARAM_TAG', 0x0011); |
180 | |
e032888c |
181 | /** |
38fb8190 |
182 | * PARAM_TAGLIST - list of tags separated by commas (interests, blogs, etc.) |
183 | */ |
e032888c |
184 | define('PARAM_TAGLIST', 0x0012); |
185 | |
bbd3f2c4 |
186 | /** |
c59733ef |
187 | * PARAM_PATH - safe relative path name, all dangerous chars are stripped, protects against XSS, SQL injections and directory traversals |
188 | * note: the leading slash is not removed, window drive letter is not allowed |
bbd3f2c4 |
189 | */ |
2ae28153 |
190 | define('PARAM_PATH', 0x0020); |
bbd3f2c4 |
191 | |
192 | /** |
c59733ef |
193 | * PARAM_HOST - expected fully qualified domain name (FQDN) or an IPv4 dotted quad (IP address) |
bbd3f2c4 |
194 | */ |
195 | define('PARAM_HOST', 0x0040); |
196 | |
197 | /** |
41b7618b |
198 | * PARAM_URL - expected properly formatted URL. Please note that domain part is required, http://localhost/ is not acceppted but http://localhost.localdomain/ is ok. |
bbd3f2c4 |
199 | */ |
2ae28153 |
200 | define('PARAM_URL', 0x0080); |
bbd3f2c4 |
201 | |
202 | /** |
c59733ef |
203 | * 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 |
204 | */ |
205 | define('PARAM_LOCALURL', 0x0180); |
206 | |
bbd3f2c4 |
207 | /** |
c59733ef |
208 | * PARAM_BOOL - converts input into 0 or 1, use for switches in forms and urls. |
bbd3f2c4 |
209 | */ |
210 | define('PARAM_BOOL', 0x0800); |
211 | |
212 | /** |
c59733ef |
213 | * PARAM_CLEANHTML - cleans submitted HTML code and removes slashes |
bbd3f2c4 |
214 | */ |
215 | define('PARAM_CLEANHTML',0x1000); |
216 | |
217 | /** |
6e73ae10 |
218 | * PARAM_SAFEDIR - safe directory name, suitable for include() and require() |
bbd3f2c4 |
219 | */ |
6e73ae10 |
220 | define('PARAM_SAFEDIR', 0x4000); |
bbd3f2c4 |
221 | |
222 | /** |
6e73ae10 |
223 | * PARAM_SAFEPATH - several PARAM_SAFEDIR joined by "/", suitable for include() and require(), plugin paths, etc. |
bbd3f2c4 |
224 | */ |
6e73ae10 |
225 | define('PARAM_SAFEPATH', 0x4001); |
bbd3f2c4 |
226 | |
0e4af166 |
227 | /** |
228 | * PARAM_SEQUENCE - expects a sequence of numbers like 8 to 1,5,6,4,6,8,9. Numbers and comma only. |
229 | */ |
230 | define('PARAM_SEQUENCE', 0x8000); |
231 | |
03d820c7 |
232 | /** |
233 | * PARAM_PEM - Privacy Enhanced Mail format |
234 | */ |
235 | define('PARAM_PEM', 0x10000); |
236 | |
237 | /** |
238 | * PARAM_BASE64 - Base 64 encoded format |
239 | */ |
240 | define('PARAM_BASE64', 0x20000); |
241 | |
ad944e78 |
242 | /** |
243 | * PARAM_CAPABILITY - A capability name, like 'moodle/role:manage'. Actually |
244 | * checked against the list of capabilties in the database. |
245 | */ |
246 | define('PARAM_CAPABILITY', 0x40000); |
03d820c7 |
247 | |
faf75fe7 |
248 | /** |
249 | * PARAM_PERMISSION - A permission, one of CAP_INHERIT, CAP_ALLOW, CAP_PREVENT or CAP_PROHIBIT. |
250 | */ |
251 | define('PARAM_PERMISSION', 0x80000); |
252 | |
bbd3f2c4 |
253 | /// Page types /// |
254 | /** |
255 | * PAGE_COURSE_VIEW is a definition of a page type. For more information on the page class see moodle/lib/pagelib.php. |
8bd3fad3 |
256 | */ |
257 | define('PAGE_COURSE_VIEW', 'course-view'); |
8bd3fad3 |
258 | |
7eb0b60a |
259 | /// Debug levels /// |
260 | /** no warnings at all */ |
261 | define ('DEBUG_NONE', 0); |
262 | /** E_ERROR | E_PARSE */ |
263 | define ('DEBUG_MINIMAL', 5); |
264 | /** E_ERROR | E_PARSE | E_WARNING | E_NOTICE */ |
265 | define ('DEBUG_NORMAL', 15); |
e69499c8 |
266 | /** E_ALL without E_STRICT for now, do show recoverable fatal errors */ |
267 | define ('DEBUG_ALL', 6143); |
74a28ec4 |
268 | /** DEBUG_ALL with extra Moodle debug messages - (DEBUG_ALL | 32768) */ |
e69499c8 |
269 | define ('DEBUG_DEVELOPER', 38911); |
bbd3f2c4 |
270 | |
9bda43e6 |
271 | /** Get remote addr constant */ |
272 | define('GETREMOTEADDR_SKIP_HTTP_CLIENT_IP', '1'); |
273 | /** Get remote addr constant */ |
274 | define('GETREMOTEADDR_SKIP_HTTP_X_FORWARDED_FOR', '2'); |
6e73ae10 |
275 | |
276 | /// Blog access level constant declaration /// |
feaf5d06 |
277 | define ('BLOG_USER_LEVEL', 1); |
278 | define ('BLOG_GROUP_LEVEL', 2); |
279 | define ('BLOG_COURSE_LEVEL', 3); |
280 | define ('BLOG_SITE_LEVEL', 4); |
281 | define ('BLOG_GLOBAL_LEVEL', 5); |
282 | |
6e73ae10 |
283 | |
284 | ///Tag constants/// |
4eb718d8 |
285 | /** |
a905364a |
286 | * To prevent problems with multibytes strings,Flag updating in nav not working on the review page. this should not exceed the |
6e73ae10 |
287 | * length of "varchar(255) / 3 (bytes / utf-8 character) = 85". |
288 | * TODO: this is not correct, varchar(255) are 255 unicode chars ;-) |
4eb718d8 |
289 | */ |
ae040d4b |
290 | define('TAG_MAX_LENGTH', 50); |
4eb718d8 |
291 | |
6e73ae10 |
292 | /// Password policy constants /// |
6499395e |
293 | define ('PASSWORD_LOWER', 'abcdefghijklmnopqrstuvwxyz'); |
294 | define ('PASSWORD_UPPER', 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'); |
295 | define ('PASSWORD_DIGITS', '0123456789'); |
296 | define ('PASSWORD_NONALPHANUM', '.,;:!?_-+/*@#&$'); |
297 | |
6e73ae10 |
298 | /// Feature constants /// |
299 | // Used for plugin_supports() to report features that are, or are not, supported by a module. |
49f6e5f4 |
300 | |
301 | /** True if module can provide a grade */ |
61fceb86 |
302 | define('FEATURE_GRADE_HAS_GRADE', 'grade_has_grade'); |
42f103be |
303 | /** True if module supports outcomes */ |
304 | define('FEATURE_GRADE_OUTCOMES', 'outcomes'); |
305 | |
49f6e5f4 |
306 | /** True if module has code to track whether somebody viewed it */ |
61fceb86 |
307 | define('FEATURE_COMPLETION_TRACKS_VIEWS', 'completion_tracks_views'); |
49f6e5f4 |
308 | /** True if module has custom completion rules */ |
61fceb86 |
309 | define('FEATURE_COMPLETION_HAS_RULES', 'completion_has_rules'); |
49f6e5f4 |
310 | |
42f103be |
311 | /** True if module supports outcomes */ |
312 | define('FEATURE_IDNUMBER', 'idnumber'); |
313 | /** True if module supports groups */ |
314 | define('FEATURE_GROUPS', 'groups'); |
315 | /** True if module supports groupings */ |
316 | define('FEATURE_GROUPINGS', 'groupings'); |
317 | /** True if module supports groupmembersonly */ |
318 | define('FEATURE_GROUPMEMBERSONLY', 'groupmembersonly'); |
319 | |
320 | /** True if module supports intro editor */ |
dc5c2bd9 |
321 | define('FEATURE_MOD_INTRO', 'mod_intro'); |
42f103be |
322 | /** True if module has default completion */ |
323 | define('FEATURE_MODEDIT_DEFAULT_COMPLETION', 'modedit_default_completion'); |
49f6e5f4 |
324 | |
325 | |
9fa49e22 |
326 | /// PARAMETER HANDLING //////////////////////////////////////////////////// |
6b174680 |
327 | |
e0d346ff |
328 | /** |
361855e6 |
329 | * Returns a particular value for the named variable, taken from |
330 | * POST or GET. If the parameter doesn't exist then an error is |
e0d346ff |
331 | * thrown because we require this variable. |
332 | * |
361855e6 |
333 | * This function should be used to initialise all required values |
334 | * in a script that are based on parameters. Usually it will be |
e0d346ff |
335 | * used like this: |
336 | * $id = required_param('id'); |
337 | * |
a083b93c |
338 | * @param string $parname the name of the page parameter we want |
339 | * @param int $type expected type of parameter |
e0d346ff |
340 | * @return mixed |
341 | */ |
a083b93c |
342 | function required_param($parname, $type=PARAM_CLEAN) { |
a083b93c |
343 | if (isset($_POST[$parname])) { // POST has precedence |
344 | $param = $_POST[$parname]; |
345 | } else if (isset($_GET[$parname])) { |
346 | $param = $_GET[$parname]; |
e0d346ff |
347 | } else { |
2f137aa1 |
348 | print_error('missingparam', '', '', $parname); |
e0d346ff |
349 | } |
350 | |
a083b93c |
351 | return clean_param($param, $type); |
e0d346ff |
352 | } |
353 | |
354 | /** |
361855e6 |
355 | * Returns a particular value for the named variable, taken from |
e0d346ff |
356 | * POST or GET, otherwise returning a given default. |
357 | * |
361855e6 |
358 | * This function should be used to initialise all optional values |
359 | * in a script that are based on parameters. Usually it will be |
e0d346ff |
360 | * used like this: |
361 | * $name = optional_param('name', 'Fred'); |
362 | * |
a083b93c |
363 | * @param string $parname the name of the page parameter we want |
e0d346ff |
364 | * @param mixed $default the default value to return if nothing is found |
a083b93c |
365 | * @param int $type expected type of parameter |
e0d346ff |
366 | * @return mixed |
367 | */ |
a083b93c |
368 | function optional_param($parname, $default=NULL, $type=PARAM_CLEAN) { |
a083b93c |
369 | if (isset($_POST[$parname])) { // POST has precedence |
370 | $param = $_POST[$parname]; |
371 | } else if (isset($_GET[$parname])) { |
372 | $param = $_GET[$parname]; |
e0d346ff |
373 | } else { |
374 | return $default; |
375 | } |
376 | |
a083b93c |
377 | return clean_param($param, $type); |
e0d346ff |
378 | } |
379 | |
380 | /** |
361855e6 |
381 | * Used by {@link optional_param()} and {@link required_param()} to |
382 | * clean the variables and/or cast to specific types, based on |
e0d346ff |
383 | * an options field. |
bbd3f2c4 |
384 | * <code> |
385 | * $course->format = clean_param($course->format, PARAM_ALPHA); |
386 | * $selectedgrade_item = clean_param($selectedgrade_item, PARAM_CLEAN); |
387 | * </code> |
e0d346ff |
388 | * |
bbd3f2c4 |
389 | * @uses $CFG |
4928b5cf |
390 | * @uses PARAM_RAW |
bbd3f2c4 |
391 | * @uses PARAM_CLEAN |
4928b5cf |
392 | * @uses PARAM_CLEANHTML |
bbd3f2c4 |
393 | * @uses PARAM_INT |
6e73ae10 |
394 | * @uses PARAM_FLOAT |
4928b5cf |
395 | * @uses PARAM_NUMBER |
bbd3f2c4 |
396 | * @uses PARAM_ALPHA |
f4f65990 |
397 | * @uses PARAM_ALPHAEXT |
6e73ae10 |
398 | * @uses PARAM_ALPHANUM |
399 | * @uses PARAM_ALPHANUMEXT |
4928b5cf |
400 | * @uses PARAM_SEQUENCE |
bbd3f2c4 |
401 | * @uses PARAM_BOOL |
4928b5cf |
402 | * @uses PARAM_NOTAGS |
403 | * @uses PARAM_TEXT |
bbd3f2c4 |
404 | * @uses PARAM_SAFEDIR |
6e73ae10 |
405 | * @uses PARAM_SAFEPATH |
bbd3f2c4 |
406 | * @uses PARAM_FILE |
407 | * @uses PARAM_PATH |
408 | * @uses PARAM_HOST |
409 | * @uses PARAM_URL |
410 | * @uses PARAM_LOCALURL |
4928b5cf |
411 | * @uses PARAM_PEM |
412 | * @uses PARAM_BASE64 |
413 | * @uses PARAM_TAG |
0e4af166 |
414 | * @uses PARAM_SEQUENCE |
e0d346ff |
415 | * @param mixed $param the variable we are cleaning |
a083b93c |
416 | * @param int $type expected format of param after cleaning. |
e0d346ff |
417 | * @return mixed |
418 | */ |
a083b93c |
419 | function clean_param($param, $type) { |
e0d346ff |
420 | |
7744ea12 |
421 | global $CFG; |
422 | |
80bfd470 |
423 | if (is_array($param)) { // Let's loop |
424 | $newparam = array(); |
425 | foreach ($param as $key => $value) { |
a083b93c |
426 | $newparam[$key] = clean_param($value, $type); |
80bfd470 |
427 | } |
428 | return $newparam; |
429 | } |
430 | |
a083b93c |
431 | switch ($type) { |
96e98ea6 |
432 | case PARAM_RAW: // no cleaning at all |
433 | return $param; |
434 | |
a083b93c |
435 | case PARAM_CLEAN: // General HTML cleaning, try to use more specific type if possible |
436 | if (is_numeric($param)) { |
437 | return $param; |
438 | } |
294ce987 |
439 | return clean_text($param); // Sweep for scripts, etc |
3af57507 |
440 | |
a083b93c |
441 | case PARAM_CLEANHTML: // prepare html fragment for display, do not store it into db!! |
a083b93c |
442 | $param = clean_text($param); // Sweep for scripts, etc |
443 | return trim($param); |
e0d346ff |
444 | |
a083b93c |
445 | case PARAM_INT: |
446 | return (int)$param; // Convert to integer |
e0d346ff |
447 | |
6e73ae10 |
448 | case PARAM_FLOAT: |
9dae915a |
449 | case PARAM_NUMBER: |
6e73ae10 |
450 | return (float)$param; // Convert to float |
9dae915a |
451 | |
a083b93c |
452 | case PARAM_ALPHA: // Remove everything not a-z |
453 | return eregi_replace('[^a-zA-Z]', '', $param); |
e0d346ff |
454 | |
6e73ae10 |
455 | case PARAM_ALPHAEXT: // Remove everything not a-zA-Z_- (originally allowed "/" too) |
456 | return eregi_replace('[^a-zA-Z_-]', '', $param); |
457 | |
a083b93c |
458 | case PARAM_ALPHANUM: // Remove everything not a-zA-Z0-9 |
459 | return eregi_replace('[^A-Za-z0-9]', '', $param); |
f24148ef |
460 | |
6e73ae10 |
461 | case PARAM_ALPHANUMEXT: // Remove everything not a-zA-Z0-9_- |
462 | return eregi_replace('[^A-Za-z0-9_-]', '', $param); |
0ed442f8 |
463 | |
0e4af166 |
464 | case PARAM_SEQUENCE: // Remove everything not 0-9, |
465 | return eregi_replace('[^0-9,]', '', $param); |
466 | |
a083b93c |
467 | case PARAM_BOOL: // Convert to 1 or 0 |
468 | $tempstr = strtolower($param); |
6e73ae10 |
469 | if ($tempstr === 'on' or $tempstr === 'yes' or $tempstr === 'true') { |
a083b93c |
470 | $param = 1; |
6e73ae10 |
471 | } else if ($tempstr === 'off' or $tempstr === 'no' or $tempstr === 'false') { |
a083b93c |
472 | $param = 0; |
473 | } else { |
474 | $param = empty($param) ? 0 : 1; |
475 | } |
476 | return $param; |
f24148ef |
477 | |
a083b93c |
478 | case PARAM_NOTAGS: // Strip all tags |
479 | return strip_tags($param); |
3af57507 |
480 | |
c4ea5e78 |
481 | case PARAM_TEXT: // leave only tags needed for multilang |
31f26796 |
482 | return clean_param(strip_tags($param, '<lang><span>'), PARAM_CLEAN); |
483 | |
a083b93c |
484 | case PARAM_SAFEDIR: // Remove everything not a-zA-Z0-9_- |
485 | return eregi_replace('[^a-zA-Z0-9_-]', '', $param); |
95bfd207 |
486 | |
6e73ae10 |
487 | case PARAM_SAFEPATH: // Remove everything not a-zA-Z0-9/_- |
488 | return eregi_replace('[^a-zA-Z0-9/_-]', '', $param); |
489 | |
a083b93c |
490 | case PARAM_FILE: // Strip all suspicious characters from filename |
6e73ae10 |
491 | $param = ereg_replace('[[:cntrl:]]|[&<>"`\|\':\\/]', '', $param); |
a083b93c |
492 | $param = ereg_replace('\.\.+', '', $param); |
6e73ae10 |
493 | if ($param === '.') { |
371a2ed0 |
494 | $param = ''; |
495 | } |
a083b93c |
496 | return $param; |
497 | |
498 | case PARAM_PATH: // Strip all suspicious characters from file path |
a083b93c |
499 | $param = str_replace('\\', '/', $param); |
6e73ae10 |
500 | $param = ereg_replace('[[:cntrl:]]|[&<>"`\|\':]', '', $param); |
a083b93c |
501 | $param = ereg_replace('\.\.+', '', $param); |
502 | $param = ereg_replace('//+', '/', $param); |
503 | return ereg_replace('/(\./)+', '/', $param); |
504 | |
505 | case PARAM_HOST: // allow FQDN or IPv4 dotted quad |
3e475991 |
506 | $param = preg_replace('/[^\.\d\w-]/','', $param ); // only allowed chars |
a083b93c |
507 | // match ipv4 dotted quad |
508 | if (preg_match('/(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})/',$param, $match)){ |
509 | // confirm values are ok |
510 | if ( $match[0] > 255 |
511 | || $match[1] > 255 |
512 | || $match[3] > 255 |
513 | || $match[4] > 255 ) { |
514 | // hmmm, what kind of dotted quad is this? |
515 | $param = ''; |
516 | } |
517 | } elseif ( preg_match('/^[\w\d\.-]+$/', $param) // dots, hyphens, numbers |
518 | && !preg_match('/^[\.-]/', $param) // no leading dots/hyphens |
519 | && !preg_match('/[\.-]$/', $param) // no trailing dots/hyphens |
520 | ) { |
521 | // all is ok - $param is respected |
522 | } else { |
523 | // all is not ok... |
524 | $param=''; |
525 | } |
526 | return $param; |
7744ea12 |
527 | |
a083b93c |
528 | case PARAM_URL: // allow safe ftp, http, mailto urls |
529 | include_once($CFG->dirroot . '/lib/validateurlsyntax.php'); |
5301205a |
530 | if (!empty($param) && validateUrlSyntax($param, 's?H?S?F?E?u-P-a?I?p?f?q?r?')) { |
a083b93c |
531 | // all is ok, param is respected |
d2a9f7cc |
532 | } else { |
a083b93c |
533 | $param =''; // not really ok |
534 | } |
535 | return $param; |
536 | |
537 | case PARAM_LOCALURL: // allow http absolute, root relative and relative URLs within wwwroot |
93684765 |
538 | $param = clean_param($param, PARAM_URL); |
a083b93c |
539 | if (!empty($param)) { |
540 | if (preg_match(':^/:', $param)) { |
541 | // root-relative, ok! |
542 | } elseif (preg_match('/^'.preg_quote($CFG->wwwroot, '/').'/i',$param)) { |
543 | // absolute, and matches our wwwroot |
7744ea12 |
544 | } else { |
a083b93c |
545 | // relative - let's make sure there are no tricks |
546 | if (validateUrlSyntax($param, 's-u-P-a-p-f+q?r?')) { |
547 | // looks ok. |
548 | } else { |
549 | $param = ''; |
550 | } |
d2a9f7cc |
551 | } |
7744ea12 |
552 | } |
a083b93c |
553 | return $param; |
bcef0319 |
554 | |
03d820c7 |
555 | case PARAM_PEM: |
556 | $param = trim($param); |
557 | // PEM formatted strings may contain letters/numbers and the symbols |
558 | // forward slash: / |
559 | // plus sign: + |
560 | // equal sign: = |
561 | // , surrounded by BEGIN and END CERTIFICATE prefix and suffixes |
562 | if (preg_match('/^-----BEGIN CERTIFICATE-----([\s\w\/\+=]+)-----END CERTIFICATE-----$/', trim($param), $matches)) { |
563 | list($wholething, $body) = $matches; |
564 | unset($wholething, $matches); |
565 | $b64 = clean_param($body, PARAM_BASE64); |
566 | if (!empty($b64)) { |
567 | return "-----BEGIN CERTIFICATE-----\n$b64\n-----END CERTIFICATE-----\n"; |
568 | } else { |
569 | return ''; |
570 | } |
571 | } |
572 | return ''; |
bcef0319 |
573 | |
03d820c7 |
574 | case PARAM_BASE64: |
575 | if (!empty($param)) { |
576 | // PEM formatted strings may contain letters/numbers and the symbols |
577 | // forward slash: / |
578 | // plus sign: + |
579 | // equal sign: = |
03d820c7 |
580 | if (0 >= preg_match('/^([\s\w\/\+=]+)$/', trim($param))) { |
581 | return ''; |
582 | } |
583 | $lines = preg_split('/[\s]+/', $param, -1, PREG_SPLIT_NO_EMPTY); |
584 | // Each line of base64 encoded data must be 64 characters in |
585 | // length, except for the last line which may be less than (or |
586 | // equal to) 64 characters long. |
587 | for ($i=0, $j=count($lines); $i < $j; $i++) { |
588 | if ($i + 1 == $j) { |
589 | if (64 < strlen($lines[$i])) { |
590 | return ''; |
591 | } |
592 | continue; |
593 | } |
7744ea12 |
594 | |
03d820c7 |
595 | if (64 != strlen($lines[$i])) { |
596 | return ''; |
597 | } |
598 | } |
599 | return implode("\n",$lines); |
600 | } else { |
601 | return ''; |
602 | } |
bcef0319 |
603 | |
604 | case PARAM_TAG: |
ae040d4b |
605 | //as long as magic_quotes_gpc is used, a backslash will be a |
3d535996 |
606 | //problem, so remove *all* backslash. |
6e73ae10 |
607 | //$param = str_replace('\\', '', $param); |
608 | //remove some nasties |
609 | $param = ereg_replace('[[:cntrl:]]|[<>`]', '', $param); |
3d535996 |
610 | //convert many whitespace chars into one |
bcef0319 |
611 | $param = preg_replace('/\s+/', ' ', $param); |
8e1ec6be |
612 | $textlib = textlib_get_instance(); |
3d535996 |
613 | $param = $textlib->substr(trim($param), 0, TAG_MAX_LENGTH); |
c93c6b3b |
614 | return $param; |
bcef0319 |
615 | |
0d626493 |
616 | |
ae040d4b |
617 | case PARAM_TAGLIST: |
618 | $tags = explode(',', $param); |
619 | $result = array(); |
620 | foreach ($tags as $tag) { |
621 | $res = clean_param($tag, PARAM_TAG); |
6e73ae10 |
622 | if ($res !== '') { |
ae040d4b |
623 | $result[] = $res; |
624 | } |
625 | } |
626 | if ($result) { |
627 | return implode(',', $result); |
628 | } else { |
629 | return ''; |
0d626493 |
630 | } |
631 | |
ad944e78 |
632 | case PARAM_CAPABILITY: |
633 | if (is_valid_capability($param)) { |
634 | return $param; |
635 | } else { |
636 | return ''; |
637 | } |
638 | |
faf75fe7 |
639 | case PARAM_PERMISSION: |
640 | $param = (int)$param; |
641 | if (in_array($param, array(CAP_INHERIT, CAP_ALLOW, CAP_PREVENT, CAP_PROHIBIT))) { |
642 | return $param; |
643 | } else { |
644 | return CAP_INHERIT; |
645 | } |
646 | |
a083b93c |
647 | default: // throw error, switched parameters in optional_param or another serious problem |
2f137aa1 |
648 | print_error("unknowparamtype", '', '', $type); |
2ae28153 |
649 | } |
e0d346ff |
650 | } |
651 | |
6e73ae10 |
652 | /** |
653 | * Return true if given value is integer or string with integer value |
654 | */ |
655 | function is_number($value) { |
656 | if (is_int($value)) { |
657 | return true; |
658 | } else if (is_string($value)) { |
659 | return ((string)(int)$value) === $value; |
660 | } else { |
661 | return false; |
662 | } |
663 | } |
7a530277 |
664 | |
94a6d656 |
665 | /** |
666 | * This function is useful for testing whether something you got back from |
667 | * the HTML editor actually contains anything. Sometimes the HTML editor |
668 | * appear to be empty, but actually you get back a <br> tag or something. |
669 | * |
670 | * @param string $string a string containing HTML. |
671 | * @return boolean does the string contain any actual content - that is text, |
672 | * images, objcts, etc. |
673 | */ |
674 | function html_is_blank($string) { |
675 | return trim(strip_tags($string, '<img><object><applet><input><select><textarea><hr>')) == ''; |
676 | } |
677 | |
7cf1c7bd |
678 | /** |
679 | * Set a key in global configuration |
680 | * |
89dcb99d |
681 | * Set a key/value pair in both this session's {@link $CFG} global variable |
7cf1c7bd |
682 | * and in the 'config' database table for future sessions. |
e1ecf0a0 |
683 | * |
684 | * Can also be used to update keys for plugin-scoped configs in config_plugin table. |
685 | * In that case it doesn't affect $CFG. |
7cf1c7bd |
686 | * |
6fd511eb |
687 | * A NULL value will delete the entry. |
688 | * |
7cf1c7bd |
689 | * @param string $name the key to set |
9cdb766d |
690 | * @param string $value the value to set (without magic quotes) |
a4080313 |
691 | * @param string $plugin (optional) the plugin scope |
7cf1c7bd |
692 | * @uses $CFG |
5e2f308b |
693 | * @return bool true or exception |
7cf1c7bd |
694 | */ |
a4080313 |
695 | function set_config($name, $value, $plugin=NULL) { |
ae040d4b |
696 | global $CFG, $DB; |
42282810 |
697 | |
a4080313 |
698 | if (empty($plugin)) { |
220a90c5 |
699 | if (!array_key_exists($name, $CFG->config_php_settings)) { |
700 | // So it's defined for this invocation at least |
701 | if (is_null($value)) { |
702 | unset($CFG->$name); |
703 | } else { |
9c305ba1 |
704 | $CFG->$name = (string)$value; // settings from db are always strings |
220a90c5 |
705 | } |
706 | } |
e1ecf0a0 |
707 | |
ae040d4b |
708 | if ($DB->get_field('config', 'name', array('name'=>$name))) { |
5e2f308b |
709 | if ($value === null) { |
710 | $DB->delete_records('config', array('name'=>$name)); |
6fd511eb |
711 | } else { |
5e2f308b |
712 | $DB->set_field('config', 'value', $value, array('name'=>$name)); |
6fd511eb |
713 | } |
a4080313 |
714 | } else { |
5e2f308b |
715 | if ($value !== null) { |
716 | $config = new object(); |
717 | $config->name = $name; |
718 | $config->value = $value; |
719 | $DB->insert_record('config', $config, false); |
6fd511eb |
720 | } |
a4080313 |
721 | } |
ae040d4b |
722 | |
a4080313 |
723 | } else { // plugin scope |
ae040d4b |
724 | if ($id = $DB->get_field('config_plugins', 'id', array('name'=>$name, 'plugin'=>$plugin))) { |
6fd511eb |
725 | if ($value===null) { |
5e2f308b |
726 | $DB->delete_records('config_plugins', array('name'=>$name, 'plugin'=>$plugin)); |
6fd511eb |
727 | } else { |
5e2f308b |
728 | $DB->set_field('config_plugins', 'value', $value, array('id'=>$id)); |
6fd511eb |
729 | } |
a4080313 |
730 | } else { |
5e2f308b |
731 | if ($value !== null) { |
732 | $config = new object(); |
733 | $config->plugin = $plugin; |
734 | $config->name = $name; |
735 | $config->value = $value; |
736 | $DB->insert_record('config_plugins', $config, false); |
6fd511eb |
737 | } |
a4080313 |
738 | } |
739 | } |
5e2f308b |
740 | |
741 | return true; |
a4080313 |
742 | } |
743 | |
744 | /** |
e1ecf0a0 |
745 | * Get configuration values from the global config table |
a4080313 |
746 | * or the config_plugins table. |
747 | * |
748 | * If called with no parameters it will do the right thing |
749 | * generating $CFG safely from the database without overwriting |
e1ecf0a0 |
750 | * existing values. |
a4080313 |
751 | * |
13daf6a2 |
752 | * If called with one parameter, it will load all the config |
753 | * variables for one pugin, and return them as an object. |
754 | * |
9220fba5 |
755 | * If called with 2 parameters it will return a $string single |
756 | * value or false of the value is not found. |
757 | * |
e1ecf0a0 |
758 | * @param string $plugin |
759 | * @param string $name |
a4080313 |
760 | * @uses $CFG |
761 | * @return hash-like object or single value |
762 | * |
763 | */ |
764 | function get_config($plugin=NULL, $name=NULL) { |
ae040d4b |
765 | global $CFG, $DB; |
dfc9ba9b |
766 | |
a4080313 |
767 | if (!empty($name)) { // the user is asking for a specific value |
768 | if (!empty($plugin)) { |
ae040d4b |
769 | return $DB->get_field('config_plugins', 'value', array('plugin'=>$plugin, 'name'=>$name)); |
a4080313 |
770 | } else { |
ae040d4b |
771 | return $DB->get_field('config', 'value', array('name'=>$name)); |
a4080313 |
772 | } |
773 | } |
774 | |
775 | // the user is after a recordset |
776 | if (!empty($plugin)) { |
13daf6a2 |
777 | $localcfg = $DB->get_records_menu('config_plugins', array('plugin'=>$plugin), '', 'name,value'); |
778 | if (!empty($localcfg)) { |
a4080313 |
779 | return (object)$localcfg; |
780 | } else { |
781 | return false; |
782 | } |
d897cae4 |
783 | } else { |
a4080313 |
784 | // this was originally in setup.php |
ae040d4b |
785 | if ($configs = $DB->get_records('config')) { |
a4080313 |
786 | $localcfg = (array)$CFG; |
787 | foreach ($configs as $config) { |
788 | if (!isset($localcfg[$config->name])) { |
789 | $localcfg[$config->name] = $config->value; |
a4080313 |
790 | } |
220a90c5 |
791 | // do not complain anymore if config.php overrides settings from db |
a4080313 |
792 | } |
e1ecf0a0 |
793 | |
a4080313 |
794 | $localcfg = (object)$localcfg; |
795 | return $localcfg; |
796 | } else { |
797 | // preserve $CFG if DB returns nothing or error |
798 | return $CFG; |
799 | } |
e1ecf0a0 |
800 | |
39917a09 |
801 | } |
39917a09 |
802 | } |
803 | |
b0270f84 |
804 | /** |
805 | * Removes a key from global configuration |
806 | * |
807 | * @param string $name the key to set |
808 | * @param string $plugin (optional) the plugin scope |
809 | * @uses $CFG |
4b600aa0 |
810 | * @return boolean whether the operation succeeded. |
b0270f84 |
811 | */ |
812 | function unset_config($name, $plugin=NULL) { |
ae040d4b |
813 | global $CFG, $DB; |
b0270f84 |
814 | |
b0270f84 |
815 | if (empty($plugin)) { |
4b600aa0 |
816 | unset($CFG->$name); |
013376de |
817 | $DB->delete_records('config', array('name'=>$name)); |
5e623a33 |
818 | } else { |
013376de |
819 | $DB->delete_records('config_plugins', array('name'=>$name, 'plugin'=>$plugin)); |
b0270f84 |
820 | } |
013376de |
821 | |
822 | return true; |
b0270f84 |
823 | } |
824 | |
4b600aa0 |
825 | /** |
826 | * Remove all the config variables for a given plugin. |
827 | * |
828 | * @param string $plugin a plugin, for example 'quiz' or 'qtype_multichoice'; |
829 | * @return boolean whether the operation succeeded. |
830 | */ |
831 | function unset_all_config_for_plugin($plugin) { |
832 | global $DB; |
013376de |
833 | $DB->delete_records('config_plugins', array('plugin' => $plugin)); |
834 | $DB->delete_records_select('config', 'name LIKE ?', array($plugin . '_%')); |
835 | return true; |
4b600aa0 |
836 | } |
837 | |
4413941f |
838 | /** |
839 | * Use this funciton to get a list of users from a config setting of type admin_setting_users_with_capability. |
b3d960e6 |
840 | * @param string $value the value of the config setting. |
4413941f |
841 | * @param string $capability the capability - must match the one passed to the admin_setting_users_with_capability constructor. |
842 | * @return array of user objects. |
843 | */ |
844 | function get_users_from_config($value, $capability) { |
845 | global $CFG; |
846 | if ($value == '$@ALL@$') { |
847 | $users = get_users_by_capability(get_context_instance(CONTEXT_SYSTEM), $capability); |
848 | } else { |
849 | list($where, $params) = $DB->get_in_or_equal(explode(',', $CFG->courserequestnotify)); |
850 | $params[] = $CFG->mnet_localhost_id; |
851 | $users = $DB->get_records_select('user', 'username ' . $where . ' AND mnethostid = ?', $params); |
852 | } |
853 | return $users; |
854 | } |
855 | |
bafd7e78 |
856 | /** |
857 | * Get volatile flags |
858 | * |
859 | * @param string $type |
860 | * @param int $changedsince |
861 | * @return records array |
862 | * |
863 | */ |
864 | function get_cache_flags($type, $changedsince=NULL) { |
ae040d4b |
865 | global $DB; |
bafd7e78 |
866 | |
ae040d4b |
867 | $params = array('type'=>$type, 'expiry'=>time()); |
868 | $sqlwhere = "flagtype = :type AND expiry >= :expiry"; |
bafd7e78 |
869 | if ($changedsince !== NULL) { |
ae040d4b |
870 | $params['changedsince'] = $changedsince; |
871 | $sqlwhere .= " AND timemodified > :changedsince"; |
bafd7e78 |
872 | } |
873 | $cf = array(); |
ae040d4b |
874 | |
875 | if ($flags = $DB->get_records_select('cache_flags', $sqlwhere, $params, '', 'name,value')) { |
bafd7e78 |
876 | foreach ($flags as $flag) { |
877 | $cf[$flag->name] = $flag->value; |
878 | } |
879 | } |
880 | return $cf; |
881 | } |
882 | |
a489cf72 |
883 | /** |
884 | * Get volatile flags |
885 | * |
886 | * @param string $type |
887 | * @param string $name |
888 | * @param int $changedsince |
889 | * @return records array |
890 | * |
891 | */ |
892 | function get_cache_flag($type, $name, $changedsince=NULL) { |
ae040d4b |
893 | global $DB; |
a489cf72 |
894 | |
ae040d4b |
895 | $params = array('type'=>$type, 'name'=>$name, 'expiry'=>time()); |
a489cf72 |
896 | |
ae040d4b |
897 | $sqlwhere = "flagtype = :type AND name = :name AND expiry >= :expiry"; |
a489cf72 |
898 | if ($changedsince !== NULL) { |
ae040d4b |
899 | $params['changedsince'] = $changedsince; |
900 | $sqlwhere .= " AND timemodified > :changedsince"; |
a489cf72 |
901 | } |
ae040d4b |
902 | |
903 | return $DB->get_field_select('cache_flags', 'value', $sqlwhere, $params); |
a489cf72 |
904 | } |
bafd7e78 |
905 | |
906 | /** |
907 | * Set a volatile flag |
908 | * |
909 | * @param string $type the "type" namespace for the key |
910 | * @param string $name the key to set |
911 | * @param string $value the value to set (without magic quotes) - NULL will remove the flag |
912 | * @param int $expiry (optional) epoch indicating expiry - defaults to now()+ 24hs |
913 | * @return bool |
914 | */ |
915 | function set_cache_flag($type, $name, $value, $expiry=NULL) { |
ae040d4b |
916 | global $DB; |
bafd7e78 |
917 | |
918 | $timemodified = time(); |
919 | if ($expiry===NULL || $expiry < $timemodified) { |
920 | $expiry = $timemodified + 24 * 60 * 60; |
921 | } else { |
922 | $expiry = (int)$expiry; |
923 | } |
924 | |
925 | if ($value === NULL) { |
013376de |
926 | unset_cache_flag($type,$name); |
927 | return true; |
bafd7e78 |
928 | } |
929 | |
ae040d4b |
930 | if ($f = $DB->get_record('cache_flags', array('name'=>$name, 'flagtype'=>$type))) { // this is a potentail problem in DEBUG_DEVELOPER |
128f0984 |
931 | if ($f->value == $value and $f->expiry == $expiry and $f->timemodified == $timemodified) { |
932 | return true; //no need to update; helps rcache too |
933 | } |
ae040d4b |
934 | $f->value = $value; |
bafd7e78 |
935 | $f->expiry = $expiry; |
936 | $f->timemodified = $timemodified; |
013376de |
937 | $DB->update_record('cache_flags', $f); |
bafd7e78 |
938 | } else { |
128f0984 |
939 | $f = new object(); |
bafd7e78 |
940 | $f->flagtype = $type; |
941 | $f->name = $name; |
ae040d4b |
942 | $f->value = $value; |
bafd7e78 |
943 | $f->expiry = $expiry; |
944 | $f->timemodified = $timemodified; |
013376de |
945 | $DB->insert_record('cache_flags', $f); |
bafd7e78 |
946 | } |
013376de |
947 | return true; |
bafd7e78 |
948 | } |
949 | |
950 | /** |
951 | * Removes a single volatile flag |
952 | * |
953 | * @param string $type the "type" namespace for the key |
954 | * @param string $name the key to set |
955 | * @uses $CFG |
956 | * @return bool |
957 | */ |
958 | function unset_cache_flag($type, $name) { |
ae040d4b |
959 | global $DB; |
013376de |
960 | $DB->delete_records('cache_flags', array('name'=>$name, 'flagtype'=>$type)); |
961 | return true; |
bafd7e78 |
962 | } |
963 | |
964 | /** |
965 | * Garbage-collect volatile flags |
966 | * |
967 | */ |
968 | function gc_cache_flags() { |
ae040d4b |
969 | global $DB; |
013376de |
970 | $DB->delete_records_select('cache_flags', 'expiry < ?', array(time())); |
971 | return true; |
bafd7e78 |
972 | } |
a4080313 |
973 | |
2660377f |
974 | /// FUNCTIONS FOR HANDLING USER PREFERENCES //////////////////////////////////// |
975 | |
7cf1c7bd |
976 | /** |
977 | * Refresh current $USER session global variable with all their current preferences. |
978 | * @uses $USER |
979 | */ |
2660377f |
980 | function check_user_preferences_loaded($time = null) { |
ae040d4b |
981 | global $USER, $DB; |
2660377f |
982 | static $timenow = null; // Static cache, so we only check up-to-dateness once per request. |
983 | |
2e3adc25 |
984 | if (!empty($USER->preference) && isset($USER->preference['_lastloaded'])) { |
2660377f |
985 | // Already loaded. Are we up to date? |
986 | |
987 | if (is_null($timenow) || (!is_null($time) && $time != $timenow)) { |
988 | $timenow = time(); |
989 | if (!get_cache_flag('userpreferenceschanged', $USER->id, $USER->preference['_lastloaded'])) { |
990 | // We are up-to-date. |
991 | return; |
992 | } |
993 | } else { |
994 | // Already checked for up-to-date-ness. |
995 | return; |
996 | } |
997 | } |
70812e39 |
998 | |
2660377f |
999 | // OK, so we have to reload. Reset preference |
346c3e2f |
1000 | $USER->preference = array(); |
070e2616 |
1001 | |
346c3e2f |
1002 | if (!isloggedin() or isguestuser()) { |
2660377f |
1003 | // No permanent storage for not-logged-in user and guest |
70812e39 |
1004 | |
ae040d4b |
1005 | } else if ($preferences = $DB->get_records('user_preferences', array('userid'=>$USER->id))) { |
70812e39 |
1006 | foreach ($preferences as $preference) { |
1007 | $USER->preference[$preference->name] = $preference->value; |
1008 | } |
c6d15803 |
1009 | } |
346c3e2f |
1010 | |
2660377f |
1011 | $USER->preference['_lastloaded'] = $timenow; |
1012 | } |
1013 | |
1014 | /** |
1015 | * Called from set/delete_user_preferences, so that the prefs can be correctly reloaded. |
1016 | * @param integer $userid the user whose prefs were changed. |
1017 | */ |
1018 | function mark_user_preferences_changed($userid) { |
1019 | global $CFG, $USER; |
1020 | if ($userid == $USER->id) { |
1021 | check_user_preferences_loaded(time()); |
1022 | } |
1023 | set_cache_flag('userpreferenceschanged', $userid, 1, time() + $CFG->sessiontimeout); |
70812e39 |
1024 | } |
1025 | |
7cf1c7bd |
1026 | /** |
1027 | * Sets a preference for the current user |
1028 | * Optionally, can set a preference for a different user object |
1029 | * @uses $USER |
68fbd8e1 |
1030 | * @todo Add a better description and include usage examples. Add inline links to $USER and user functions in above line. |
1031 | |
7cf1c7bd |
1032 | * @param string $name The key to set as preference for the specified user |
1033 | * @param string $value The value to set forthe $name key in the specified user's record |
346c3e2f |
1034 | * @param int $otheruserid A moodle user ID |
bbd3f2c4 |
1035 | * @return bool |
7cf1c7bd |
1036 | */ |
346c3e2f |
1037 | function set_user_preference($name, $value, $otheruserid=NULL) { |
ae040d4b |
1038 | global $USER, $DB; |
70812e39 |
1039 | |
1040 | if (empty($name)) { |
1041 | return false; |
1042 | } |
1043 | |
346c3e2f |
1044 | $nostore = false; |
346c3e2f |
1045 | if (empty($otheruserid)){ |
1046 | if (!isloggedin() or isguestuser()) { |
1047 | $nostore = true; |
1048 | } |
1049 | $userid = $USER->id; |
1050 | } else { |
1051 | if (isguestuser($otheruserid)) { |
1052 | $nostore = true; |
1053 | } |
1054 | $userid = $otheruserid; |
1055 | } |
1056 | |
346c3e2f |
1057 | if ($nostore) { |
114201c8 |
1058 | // no permanent storage for not-logged-in user and guest |
346c3e2f |
1059 | |
ae040d4b |
1060 | } else if ($preference = $DB->get_record('user_preferences', array('userid'=>$userid, 'name'=>$name))) { |
a1244706 |
1061 | if ($preference->value === $value) { |
1062 | return true; |
1063 | } |
013376de |
1064 | $DB->set_field('user_preferences', 'value', (string)$value, array('id'=>$preference->id)); |
70812e39 |
1065 | |
1066 | } else { |
346c3e2f |
1067 | $preference = new object(); |
a3f1f815 |
1068 | $preference->userid = $userid; |
ae040d4b |
1069 | $preference->name = $name; |
1070 | $preference->value = (string)$value; |
013376de |
1071 | $DB->insert_record('user_preferences', $preference); |
2660377f |
1072 | } |
1073 | |
013376de |
1074 | mark_user_preferences_changed($userid); |
1075 | // update value in USER session if needed |
1076 | if ($userid == $USER->id) { |
1077 | $USER->preference[$name] = (string)$value; |
1078 | $USER->preference['_lastloaded'] = time(); |
70812e39 |
1079 | } |
346c3e2f |
1080 | |
013376de |
1081 | return true; |
2660377f |
1082 | } |
1083 | |
1084 | /** |
1085 | * Sets a whole array of preferences for the current user |
1086 | * @param array $prefarray An array of key/value pairs to be set |
1087 | * @param int $otheruserid A moodle user ID |
1088 | * @return bool |
1089 | */ |
1090 | function set_user_preferences($prefarray, $otheruserid=NULL) { |
1091 | |
1092 | if (!is_array($prefarray) or empty($prefarray)) { |
1093 | return false; |
346c3e2f |
1094 | } |
1095 | |
2660377f |
1096 | foreach ($prefarray as $name => $value) { |
013376de |
1097 | set_user_preference($name, $value, $otheruserid); |
2660377f |
1098 | } |
013376de |
1099 | return true; |
70812e39 |
1100 | } |
1101 | |
6eb3e776 |
1102 | /** |
1103 | * Unsets a preference completely by deleting it from the database |
1104 | * Optionally, can set a preference for a different user id |
1105 | * @uses $USER |
1106 | * @param string $name The key to unset as preference for the specified user |
346c3e2f |
1107 | * @param int $otheruserid A moodle user ID |
6eb3e776 |
1108 | */ |
346c3e2f |
1109 | function unset_user_preference($name, $otheruserid=NULL) { |
ae040d4b |
1110 | global $USER, $DB; |
6eb3e776 |
1111 | |
346c3e2f |
1112 | if (empty($otheruserid)){ |
1113 | $userid = $USER->id; |
2660377f |
1114 | check_user_preferences_loaded(); |
346c3e2f |
1115 | } else { |
1116 | $userid = $otheruserid; |
1117 | } |
1118 | |
49d005ee |
1119 | //Then from DB |
013376de |
1120 | $DB->delete_records('user_preferences', array('userid'=>$userid, 'name'=>$name)); |
1121 | |
1122 | mark_user_preferences_changed($userid); |
1123 | //Delete the preference from $USER if needed |
1124 | if ($userid == $USER->id) { |
1125 | unset($USER->preference[$name]); |
1126 | $USER->preference['_lastloaded'] = time(); |
70812e39 |
1127 | } |
1128 | |
013376de |
1129 | return true; |
70812e39 |
1130 | } |
1131 | |
7cf1c7bd |
1132 | /** |
1133 | * If no arguments are supplied this function will return |
361855e6 |
1134 | * all of the current user preferences as an array. |
7cf1c7bd |
1135 | * If a name is specified then this function |
1136 | * attempts to return that particular preference value. If |
1137 | * none is found, then the optional value $default is returned, |
1138 | * otherwise NULL. |
1139 | * @param string $name Name of the key to use in finding a preference value |
1140 | * @param string $default Value to be returned if the $name key is not set in the user preferences |
346c3e2f |
1141 | * @param int $otheruserid A moodle user ID |
7cf1c7bd |
1142 | * @uses $USER |
1143 | * @return string |
1144 | */ |
346c3e2f |
1145 | function get_user_preferences($name=NULL, $default=NULL, $otheruserid=NULL) { |
ae040d4b |
1146 | global $USER, $DB; |
70812e39 |
1147 | |
46933753 |
1148 | if (empty($otheruserid) || (!empty($USER->id) && ($USER->id == $otheruserid))){ |
2660377f |
1149 | check_user_preferences_loaded(); |
346c3e2f |
1150 | |
2660377f |
1151 | if (empty($name)) { |
1152 | return $USER->preference; // All values |
1153 | } else if (array_key_exists($name, $USER->preference)) { |
1154 | return $USER->preference[$name]; // The single value |
1155 | } else { |
1156 | return $default; // Default value (or NULL) |
a3f1f815 |
1157 | } |
346c3e2f |
1158 | |
1159 | } else { |
2660377f |
1160 | if (empty($name)) { |
1161 | return $DB->get_records_menu('user_preferences', array('userid'=>$otheruserid), '', 'name,value'); // All values |
46933753 |
1162 | } else if ($value = $DB->get_field('user_preferences', 'value', array('userid'=>$otheruserid, 'name'=>$name))) { |
2660377f |
1163 | return $value; // The single value |
1164 | } else { |
1165 | return $default; // Default value (or NULL) |
1166 | } |
70812e39 |
1167 | } |
70812e39 |
1168 | } |
1169 | |
bd1884fe |
1170 | /** |
1171 | * You need to call this function if you wish to use the set_user_preference |
1172 | * method in javascript_static.php, to white-list the preference you want to update |
1173 | * from JavaScript, and to specify the type of cleaning you expect to be done on |
1174 | * values. |
1175 | * |
1176 | * @param string $name the name of the user_perference we should allow to be |
1177 | * updated by remote calls. |
1178 | * @param integer $paramtype one of the PARAM_{TYPE} constants, user to clean |
1179 | * submitted values before set_user_preference is called. |
1180 | */ |
1181 | function user_preference_allow_ajax_update($name, $paramtype) { |
1182 | global $USER; |
f2eb5002 |
1183 | |
1184 | // Make sure that the required JavaScript libraries are loaded. |
bd1884fe |
1185 | require_js(array('yui_yahoo', 'yui_connection')); |
f2eb5002 |
1186 | |
1187 | // Record in the session that this user_preference is allowed to updated remotely. |
bd1884fe |
1188 | $USER->ajax_updatable_user_prefs[$name] = $paramtype; |
1189 | } |
70812e39 |
1190 | |
9fa49e22 |
1191 | /// FUNCTIONS FOR HANDLING TIME //////////////////////////////////////////// |
39917a09 |
1192 | |
7cf1c7bd |
1193 | /** |
c6d15803 |
1194 | * Given date parts in user time produce a GMT timestamp. |
7cf1c7bd |
1195 | * |
68fbd8e1 |
1196 | * @param int $year The year part to create timestamp of |
1197 | * @param int $month The month part to create timestamp of |
1198 | * @param int $day The day part to create timestamp of |
1199 | * @param int $hour The hour part to create timestamp of |
1200 | * @param int $minute The minute part to create timestamp of |
1201 | * @param int $second The second part to create timestamp of |
1202 | * @param float $timezone ? |
1203 | * @param bool $applydst ? |
e34d817e |
1204 | * @return int timestamp |
7cf1c7bd |
1205 | * @todo Finish documenting this function |
1206 | */ |
9f1f6daf |
1207 | function make_timestamp($year, $month=1, $day=1, $hour=0, $minute=0, $second=0, $timezone=99, $applydst=true) { |
39917a09 |
1208 | |
33998d30 |
1209 | $strtimezone = NULL; |
1210 | if (!is_numeric($timezone)) { |
1211 | $strtimezone = $timezone; |
1212 | } |
1213 | |
dddb014a |
1214 | $timezone = get_user_timezone_offset($timezone); |
1215 | |
94e34118 |
1216 | if (abs($timezone) > 13) { |
68fbd8e1 |
1217 | $time = mktime((int)$hour, (int)$minute, (int)$second, (int)$month, (int)$day, (int)$year); |
03c17ddf |
1218 | } else { |
68fbd8e1 |
1219 | $time = gmmktime((int)$hour, (int)$minute, (int)$second, (int)$month, (int)$day, (int)$year); |
196f2619 |
1220 | $time = usertime($time, $timezone); |
28c66824 |
1221 | if($applydst) { |
33998d30 |
1222 | $time -= dst_offset_on($time, $strtimezone); |
28c66824 |
1223 | } |
9f1f6daf |
1224 | } |
1225 | |
196f2619 |
1226 | return $time; |
85cafb3e |
1227 | |
39917a09 |
1228 | } |
1229 | |
7cf1c7bd |
1230 | /** |
1231 | * Given an amount of time in seconds, returns string |
5602f7cf |
1232 | * formatted nicely as weeks, days, hours etc as needed |
7cf1c7bd |
1233 | * |
2f87145b |
1234 | * @uses MINSECS |
1235 | * @uses HOURSECS |
1236 | * @uses DAYSECS |
5602f7cf |
1237 | * @uses YEARSECS |
c6d15803 |
1238 | * @param int $totalsecs ? |
1239 | * @param array $str ? |
89dcb99d |
1240 | * @return string |
7cf1c7bd |
1241 | */ |
1242 | function format_time($totalsecs, $str=NULL) { |
c7e3ac2a |
1243 | |
6b174680 |
1244 | $totalsecs = abs($totalsecs); |
c7e3ac2a |
1245 | |
8dbed6be |
1246 | if (!$str) { // Create the str structure the slow way |
b0ccd3fb |
1247 | $str->day = get_string('day'); |
1248 | $str->days = get_string('days'); |
1249 | $str->hour = get_string('hour'); |
1250 | $str->hours = get_string('hours'); |
1251 | $str->min = get_string('min'); |
1252 | $str->mins = get_string('mins'); |
1253 | $str->sec = get_string('sec'); |
1254 | $str->secs = get_string('secs'); |
5602f7cf |
1255 | $str->year = get_string('year'); |
1256 | $str->years = get_string('years'); |
8dbed6be |
1257 | } |
1258 | |
5602f7cf |
1259 | |
1260 | $years = floor($totalsecs/YEARSECS); |
1261 | $remainder = $totalsecs - ($years*YEARSECS); |
5602f7cf |
1262 | $days = floor($remainder/DAYSECS); |
7a5672c9 |
1263 | $remainder = $totalsecs - ($days*DAYSECS); |
1264 | $hours = floor($remainder/HOURSECS); |
1265 | $remainder = $remainder - ($hours*HOURSECS); |
1266 | $mins = floor($remainder/MINSECS); |
1267 | $secs = $remainder - ($mins*MINSECS); |
8dbed6be |
1268 | |
1269 | $ss = ($secs == 1) ? $str->sec : $str->secs; |
1270 | $sm = ($mins == 1) ? $str->min : $str->mins; |
1271 | $sh = ($hours == 1) ? $str->hour : $str->hours; |
1272 | $sd = ($days == 1) ? $str->day : $str->days; |
5602f7cf |
1273 | $sy = ($years == 1) ? $str->year : $str->years; |
8dbed6be |
1274 | |
5602f7cf |
1275 | $oyears = ''; |
b0ccd3fb |
1276 | $odays = ''; |
1277 | $ohours = ''; |
1278 | $omins = ''; |
1279 | $osecs = ''; |
9c9f7d77 |
1280 | |
5602f7cf |
1281 | if ($years) $oyears = $years .' '. $sy; |
b0ccd3fb |
1282 | if ($days) $odays = $days .' '. $sd; |
1283 | if ($hours) $ohours = $hours .' '. $sh; |
1284 | if ($mins) $omins = $mins .' '. $sm; |
1285 | if ($secs) $osecs = $secs .' '. $ss; |
6b174680 |
1286 | |
77ac808e |
1287 | if ($years) return trim($oyears .' '. $odays); |
1288 | if ($days) return trim($odays .' '. $ohours); |
1289 | if ($hours) return trim($ohours .' '. $omins); |
1290 | if ($mins) return trim($omins .' '. $osecs); |
b0ccd3fb |
1291 | if ($secs) return $osecs; |
1292 | return get_string('now'); |
6b174680 |
1293 | } |
f9903ed0 |
1294 | |
7cf1c7bd |
1295 | /** |
1296 | * Returns a formatted string that represents a date in user time |
1297 | * <b>WARNING: note that the format is for strftime(), not date().</b> |
1298 | * Because of a bug in most Windows time libraries, we can't use |
1299 | * the nicer %e, so we have to use %d which has leading zeroes. |
1300 | * A lot of the fuss in the function is just getting rid of these leading |
1301 | * zeroes as efficiently as possible. |
361855e6 |
1302 | * |
8c3dba73 |
1303 | * If parameter fixday = true (default), then take off leading |
7cf1c7bd |
1304 | * zero from %d, else mantain it. |
1305 | * |
0a0cf09a |
1306 | * @param int $date the timestamp in UTC, as obtained from the database. |
1307 | * @param string $format strftime format. You should probably get this using |
1308 | * get_string('strftime...', 'langconfig'); |
1309 | * @param float $timezone by default, uses the user's time zone. |
1310 | * @param bool $fixday If true (default) then the leading zero from %d is removed. |
1311 | * If false then the leading zero is mantained. |
1312 | * @return string the formatted date/time. |
7cf1c7bd |
1313 | */ |
0a0cf09a |
1314 | function userdate($date, $format = '', $timezone = 99, $fixday = true) { |
7a302afc |
1315 | |
1ac7ee24 |
1316 | global $CFG; |
1317 | |
33998d30 |
1318 | $strtimezone = NULL; |
1319 | if (!is_numeric($timezone)) { |
1320 | $strtimezone = $timezone; |
1321 | } |
1322 | |
1306c5ea |
1323 | if (empty($format)) { |
0a0cf09a |
1324 | $format = get_string('strftimedaydatetime', 'langconfig'); |
5fa51a39 |
1325 | } |
035cdbff |
1326 | |
c3a3c5b8 |
1327 | if (!empty($CFG->nofixday)) { // Config.php can force %d not to be fixed. |
1328 | $fixday = false; |
1329 | } else if ($fixday) { |
1330 | $formatnoday = str_replace('%d', 'DD', $format); |
61ae5d36 |
1331 | $fixday = ($formatnoday != $format); |
1332 | } |
dcde9f02 |
1333 | |
33998d30 |
1334 | $date += dst_offset_on($date, $strtimezone); |
85351042 |
1335 | |
494b9296 |
1336 | $timezone = get_user_timezone_offset($timezone); |
102dc313 |
1337 | |
1338 | if (abs($timezone) > 13) { /// Server time |
d2a9f7cc |
1339 | if ($fixday) { |
102dc313 |
1340 | $datestring = strftime($formatnoday, $date); |
3e95343a |
1341 | $daystring = str_replace(array(' 0', ' '), '', strftime(' %d', $date)); |
102dc313 |
1342 | $datestring = str_replace('DD', $daystring, $datestring); |
1343 | } else { |
1344 | $datestring = strftime($format, $date); |
1345 | } |
88ec5b7c |
1346 | } else { |
102dc313 |
1347 | $date += (int)($timezone * 3600); |
1348 | if ($fixday) { |
1349 | $datestring = gmstrftime($formatnoday, $date); |
9db3992a |
1350 | $daystring = str_replace(array(' 0', ' '), '', gmstrftime(' %d', $date)); |
102dc313 |
1351 | $datestring = str_replace('DD', $daystring, $datestring); |
1352 | } else { |
1353 | $datestring = gmstrftime($format, $date); |
1354 | } |
88ec5b7c |
1355 | } |
102dc313 |
1356 | |
fb773106 |
1357 | /// If we are running under Windows convert from windows encoding to UTF-8 |
1358 | /// (because it's impossible to specify UTF-8 to fetch locale info in Win32) |
11f7b25d |
1359 | |
fb773106 |
1360 | if ($CFG->ostype == 'WINDOWS') { |
11f7b25d |
1361 | if ($localewincharset = get_string('localewincharset')) { |
1362 | $textlib = textlib_get_instance(); |
810944af |
1363 | $datestring = $textlib->convert($datestring, $localewincharset, 'utf-8'); |
11f7b25d |
1364 | } |
1365 | } |
1366 | |
035cdbff |
1367 | return $datestring; |
873960de |
1368 | } |
1369 | |
7cf1c7bd |
1370 | /** |
196f2619 |
1371 | * Given a $time timestamp in GMT (seconds since epoch), |
c6d15803 |
1372 | * returns an array that represents the date in user time |
7cf1c7bd |
1373 | * |
2f87145b |
1374 | * @uses HOURSECS |
196f2619 |
1375 | * @param int $time Timestamp in GMT |
68fbd8e1 |
1376 | * @param float $timezone ? |
c6d15803 |
1377 | * @return array An array that represents the date in user time |
7cf1c7bd |
1378 | * @todo Finish documenting this function |
1379 | */ |
196f2619 |
1380 | function usergetdate($time, $timezone=99) { |
6b174680 |
1381 | |
94c82430 |
1382 | $strtimezone = NULL; |
1383 | if (!is_numeric($timezone)) { |
1384 | $strtimezone = $timezone; |
1385 | } |
1386 | |
494b9296 |
1387 | $timezone = get_user_timezone_offset($timezone); |
a36166d3 |
1388 | |
e34d817e |
1389 | if (abs($timezone) > 13) { // Server time |
ed1f69b0 |
1390 | return getdate($time); |
d2a9f7cc |
1391 | } |
1392 | |
e34d817e |
1393 | // There is no gmgetdate so we use gmdate instead |
94c82430 |
1394 | $time += dst_offset_on($time, $strtimezone); |
e34d817e |
1395 | $time += intval((float)$timezone * HOURSECS); |
3bba1e6e |
1396 | |
1397 | $datestring = gmstrftime('%S_%M_%H_%d_%m_%Y_%w_%j_%A_%B', $time); |
02f0527d |
1398 | |
9f1f6daf |
1399 | list( |
1400 | $getdate['seconds'], |
1401 | $getdate['minutes'], |
1402 | $getdate['hours'], |
1403 | $getdate['mday'], |
1404 | $getdate['mon'], |
1405 | $getdate['year'], |
1406 | $getdate['wday'], |
1407 | $getdate['yday'], |
1408 | $getdate['weekday'], |
1409 | $getdate['month'] |
3bba1e6e |
1410 | ) = explode('_', $datestring); |
9f1f6daf |
1411 | |
d2d6171f |
1412 | return $getdate; |
d552ead0 |
1413 | } |
1414 | |
7cf1c7bd |
1415 | /** |
1416 | * Given a GMT timestamp (seconds since epoch), offsets it by |
1417 | * the timezone. eg 3pm in India is 3pm GMT - 7 * 3600 seconds |
1418 | * |
2f87145b |
1419 | * @uses HOURSECS |
c6d15803 |
1420 | * @param int $date Timestamp in GMT |
e34d817e |
1421 | * @param float $timezone |
c6d15803 |
1422 | * @return int |
7cf1c7bd |
1423 | */ |
d552ead0 |
1424 | function usertime($date, $timezone=99) { |
a36166d3 |
1425 | |
494b9296 |
1426 | $timezone = get_user_timezone_offset($timezone); |
2665e47a |
1427 | |
0431bd7c |
1428 | if (abs($timezone) > 13) { |
d552ead0 |
1429 | return $date; |
1430 | } |
7a5672c9 |
1431 | return $date - (int)($timezone * HOURSECS); |
d552ead0 |
1432 | } |
1433 | |
8c3dba73 |
1434 | /** |
1435 | * Given a time, return the GMT timestamp of the most recent midnight |
1436 | * for the current user. |
1437 | * |
e34d817e |
1438 | * @param int $date Timestamp in GMT |
1439 | * @param float $timezone ? |
c6d15803 |
1440 | * @return ? |
8c3dba73 |
1441 | */ |
edf7fe8c |
1442 | function usergetmidnight($date, $timezone=99) { |
edf7fe8c |
1443 | |
edf7fe8c |
1444 | $userdate = usergetdate($date, $timezone); |
4606d9bb |
1445 | |
02f0527d |
1446 | // Time of midnight of this user's day, in GMT |
1447 | return make_timestamp($userdate['year'], $userdate['mon'], $userdate['mday'], 0, 0, 0, $timezone); |
edf7fe8c |
1448 | |
1449 | } |
1450 | |
7cf1c7bd |
1451 | /** |
1452 | * Returns a string that prints the user's timezone |
1453 | * |
1454 | * @param float $timezone The user's timezone |
1455 | * @return string |
1456 | */ |
d552ead0 |
1457 | function usertimezone($timezone=99) { |
d552ead0 |
1458 | |
0c244315 |
1459 | $tz = get_user_timezone($timezone); |
f30fe8d0 |
1460 | |
0c244315 |
1461 | if (!is_float($tz)) { |
1462 | return $tz; |
d552ead0 |
1463 | } |
0c244315 |
1464 | |
1465 | if(abs($tz) > 13) { // Server time |
1466 | return get_string('serverlocaltime'); |
1467 | } |
1468 | |
1469 | if($tz == intval($tz)) { |
1470 | // Don't show .0 for whole hours |
1471 | $tz = intval($tz); |
1472 | } |
1473 | |
1474 | if($tz == 0) { |
61b420ac |
1475 | return 'UTC'; |
d552ead0 |
1476 | } |
0c244315 |
1477 | else if($tz > 0) { |
61b420ac |
1478 | return 'UTC+'.$tz; |
0c244315 |
1479 | } |
1480 | else { |
61b420ac |
1481 | return 'UTC'.$tz; |
d552ead0 |
1482 | } |
e1ecf0a0 |
1483 | |
f9903ed0 |
1484 | } |
1485 | |
7cf1c7bd |
1486 | /** |
1487 | * Returns a float which represents the user's timezone difference from GMT in hours |
1488 | * Checks various settings and picks the most dominant of those which have a value |
1489 | * |
7cf1c7bd |
1490 | * @uses $CFG |
1491 | * @uses $USER |
b2b68362 |
1492 | * @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 |
1493 | * @return int |
7cf1c7bd |
1494 | */ |
494b9296 |
1495 | function get_user_timezone_offset($tz = 99) { |
f30fe8d0 |
1496 | |
43b59916 |
1497 | global $USER, $CFG; |
1498 | |
e8904995 |
1499 | $tz = get_user_timezone($tz); |
c9e55a25 |
1500 | |
7b9e355e |
1501 | if (is_float($tz)) { |
1502 | return $tz; |
1503 | } else { |
e8904995 |
1504 | $tzrecord = get_timezone_record($tz); |
7b9e355e |
1505 | if (empty($tzrecord)) { |
e8904995 |
1506 | return 99.0; |
1507 | } |
4f2dbde9 |
1508 | return (float)$tzrecord->gmtoff / HOURMINS; |
e8904995 |
1509 | } |
1510 | } |
1511 | |
61460dd6 |
1512 | /** |
1513 | * Returns an int which represents the systems's timezone difference from GMT in seconds |
1514 | * @param mixed $tz timezone |
1515 | * @return int if found, false is timezone 99 or error |
1516 | */ |
1517 | function get_timezone_offset($tz) { |
1518 | global $CFG; |
1519 | |
1520 | if ($tz == 99) { |
1521 | return false; |
1522 | } |
1523 | |
1524 | if (is_numeric($tz)) { |
1525 | return intval($tz * 60*60); |
1526 | } |
1527 | |
1528 | if (!$tzrecord = get_timezone_record($tz)) { |
1529 | return false; |
1530 | } |
1531 | return intval($tzrecord->gmtoff * 60); |
1532 | } |
1533 | |
bbd3f2c4 |
1534 | /** |
b2b68362 |
1535 | * Returns a float or a string which denotes the user's timezone |
1536 | * 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) |
1537 | * means that for this timezone there are also DST rules to be taken into account |
1538 | * Checks various settings and picks the most dominant of those which have a value |
bbd3f2c4 |
1539 | * |
1540 | * @uses $USER |
1541 | * @uses $CFG |
b2b68362 |
1542 | * @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 |
1543 | * @return mixed |
bbd3f2c4 |
1544 | */ |
e8904995 |
1545 | function get_user_timezone($tz = 99) { |
1546 | global $USER, $CFG; |
43b59916 |
1547 | |
f30fe8d0 |
1548 | $timezones = array( |
e8904995 |
1549 | $tz, |
1550 | isset($CFG->forcetimezone) ? $CFG->forcetimezone : 99, |
43b59916 |
1551 | isset($USER->timezone) ? $USER->timezone : 99, |
1552 | isset($CFG->timezone) ? $CFG->timezone : 99, |
f30fe8d0 |
1553 | ); |
43b59916 |
1554 | |
e8904995 |
1555 | $tz = 99; |
43b59916 |
1556 | |
33998d30 |
1557 | while(($tz == '' || $tz == 99 || $tz == NULL) && $next = each($timezones)) { |
e8904995 |
1558 | $tz = $next['value']; |
43b59916 |
1559 | } |
e8904995 |
1560 | |
1561 | return is_numeric($tz) ? (float) $tz : $tz; |
43b59916 |
1562 | } |
1563 | |
bbd3f2c4 |
1564 | /** |
f33e1ed4 |
1565 | * Returns cached timezone record for given $timezonename |
bbd3f2c4 |
1566 | * |
f33e1ed4 |
1567 | * @param string $timezonename |
1568 | * @return mixed timezonerecord object or false |
bbd3f2c4 |
1569 | */ |
43b59916 |
1570 | function get_timezone_record($timezonename) { |
f33e1ed4 |
1571 | global $CFG, $DB; |
43b59916 |
1572 | static $cache = NULL; |
1573 | |
8edffd15 |
1574 | if ($cache === NULL) { |
43b59916 |
1575 | $cache = array(); |
1576 | } |
1577 | |
8edffd15 |
1578 | if (isset($cache[$timezonename])) { |
43b59916 |
1579 | return $cache[$timezonename]; |
f30fe8d0 |
1580 | } |
1581 | |
f33e1ed4 |
1582 | return $cache[$timezonename] = $DB->get_record_sql('SELECT * FROM {timezone} |
ae040d4b |
1583 | WHERE name = ? ORDER BY year DESC', array($timezonename), true); |
f30fe8d0 |
1584 | } |
f9903ed0 |
1585 | |
bbd3f2c4 |
1586 | /** |
1587 | * ? |
1588 | * |
1589 | * @uses $CFG |
1590 | * @uses $USER |
1591 | * @param ? $fromyear ? |
1592 | * @param ? $to_year ? |
1593 | * @return bool |
1594 | */ |
94c82430 |
1595 | function calculate_user_dst_table($from_year = NULL, $to_year = NULL, $strtimezone = NULL) { |
ae040d4b |
1596 | global $CFG, $SESSION, $DB; |
85cafb3e |
1597 | |
33998d30 |
1598 | $usertz = get_user_timezone($strtimezone); |
7cb29a3d |
1599 | |
989585e9 |
1600 | if (is_float($usertz)) { |
1601 | // Trivial timezone, no DST |
1602 | return false; |
1603 | } |
1604 | |
2280ecf5 |
1605 | if (!empty($SESSION->dst_offsettz) && $SESSION->dst_offsettz != $usertz) { |
989585e9 |
1606 | // We have precalculated values, but the user's effective TZ has changed in the meantime, so reset |
2280ecf5 |
1607 | unset($SESSION->dst_offsets); |
1608 | unset($SESSION->dst_range); |
830a2bbd |
1609 | } |
1610 | |
2280ecf5 |
1611 | if (!empty($SESSION->dst_offsets) && empty($from_year) && empty($to_year)) { |
830a2bbd |
1612 | // Repeat calls which do not request specific year ranges stop here, we have already calculated the table |
1613 | // This will be the return path most of the time, pretty light computationally |
1614 | return true; |
85cafb3e |
1615 | } |
1616 | |
830a2bbd |
1617 | // Reaching here means we either need to extend our table or create it from scratch |
989585e9 |
1618 | |
1619 | // Remember which TZ we calculated these changes for |
2280ecf5 |
1620 | $SESSION->dst_offsettz = $usertz; |
989585e9 |
1621 | |
2280ecf5 |
1622 | if(empty($SESSION->dst_offsets)) { |
830a2bbd |
1623 | // If we 're creating from scratch, put the two guard elements in there |
2280ecf5 |
1624 | $SESSION->dst_offsets = array(1 => NULL, 0 => NULL); |
830a2bbd |
1625 | } |
2280ecf5 |
1626 | if(empty($SESSION->dst_range)) { |
830a2bbd |
1627 | // If creating from scratch |
1628 | $from = max((empty($from_year) ? intval(date('Y')) - 3 : $from_year), 1971); |
1629 | $to = min((empty($to_year) ? intval(date('Y')) + 3 : $to_year), 2035); |
1630 | |
1631 | // Fill in the array with the extra years we need to process |
1632 | $yearstoprocess = array(); |
1633 | for($i = $from; $i <= $to; ++$i) { |
1634 | $yearstoprocess[] = $i; |
1635 | } |
1636 | |
1637 | // Take note of which years we have processed for future calls |
2280ecf5 |
1638 | $SESSION->dst_range = array($from, $to); |
830a2bbd |
1639 | } |
1640 | else { |
1641 | // If needing to extend the table, do the same |
1642 | $yearstoprocess = array(); |
1643 | |
2280ecf5 |
1644 | $from = max((empty($from_year) ? $SESSION->dst_range[0] : $from_year), 1971); |
1645 | $to = min((empty($to_year) ? $SESSION->dst_range[1] : $to_year), 2035); |
830a2bbd |
1646 | |
2280ecf5 |
1647 | if($from < $SESSION->dst_range[0]) { |
830a2bbd |
1648 | // Take note of which years we need to process and then note that we have processed them for future calls |
2280ecf5 |
1649 | for($i = $from; $i < $SESSION->dst_range[0]; ++$i) { |
830a2bbd |
1650 | $yearstoprocess[] = $i; |
1651 | } |
2280ecf5 |
1652 | $SESSION->dst_range[0] = $from; |
830a2bbd |
1653 | } |
2280ecf5 |
1654 | if($to > $SESSION->dst_range[1]) { |
830a2bbd |
1655 | // Take note of which years we need to process and then note that we have processed them for future calls |
2280ecf5 |
1656 | for($i = $SESSION->dst_range[1] + 1; $i <= $to; ++$i) { |
830a2bbd |
1657 | $yearstoprocess[] = $i; |
1658 | } |
2280ecf5 |
1659 | $SESSION->dst_range[1] = $to; |
830a2bbd |
1660 | } |
1661 | } |
1662 | |
1663 | if(empty($yearstoprocess)) { |
1664 | // This means that there was a call requesting a SMALLER range than we have already calculated |
1665 | return true; |
1666 | } |
1667 | |
1668 | // From now on, we know that the array has at least the two guard elements, and $yearstoprocess has the years we need |
1669 | // Also, the array is sorted in descending timestamp order! |
1670 | |
1671 | // Get DB data |
6a5dc27c |
1672 | |
1673 | static $presets_cache = array(); |
1674 | if (!isset($presets_cache[$usertz])) { |
ae040d4b |
1675 | $presets_cache[$usertz] = $DB->get_records('timezone', array('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'); |
6a5dc27c |
1676 | } |
1677 | if(empty($presets_cache[$usertz])) { |
e789650d |
1678 | return false; |
1679 | } |
57f1191c |
1680 | |
830a2bbd |
1681 | // Remove ending guard (first element of the array) |
2280ecf5 |
1682 | reset($SESSION->dst_offsets); |
1683 | unset($SESSION->dst_offsets[key($SESSION->dst_offsets)]); |
830a2bbd |
1684 | |
1685 | // Add all required change timestamps |
1686 | foreach($yearstoprocess as $y) { |
1687 | // Find the record which is in effect for the year $y |
6a5dc27c |
1688 | foreach($presets_cache[$usertz] as $year => $preset) { |
830a2bbd |
1689 | if($year <= $y) { |
1690 | break; |
c9e72798 |
1691 | } |
830a2bbd |
1692 | } |
1693 | |
1694 | $changes = dst_changes_for_year($y, $preset); |
1695 | |
1696 | if($changes === NULL) { |
1697 | continue; |
1698 | } |
1699 | if($changes['dst'] != 0) { |
2280ecf5 |
1700 | $SESSION->dst_offsets[$changes['dst']] = $preset->dstoff * MINSECS; |
830a2bbd |
1701 | } |
1702 | if($changes['std'] != 0) { |
2280ecf5 |
1703 | $SESSION->dst_offsets[$changes['std']] = 0; |
c9e72798 |
1704 | } |
85cafb3e |
1705 | } |
42d36497 |
1706 | |
830a2bbd |
1707 | // Put in a guard element at the top |
2280ecf5 |
1708 | $maxtimestamp = max(array_keys($SESSION->dst_offsets)); |
1709 | $SESSION->dst_offsets[($maxtimestamp + DAYSECS)] = NULL; // DAYSECS is arbitrary, any "small" number will do |
830a2bbd |
1710 | |
1711 | // Sort again |
2280ecf5 |
1712 | krsort($SESSION->dst_offsets); |
830a2bbd |
1713 | |
e789650d |
1714 | return true; |
1715 | } |
42d36497 |
1716 | |
e789650d |
1717 | function dst_changes_for_year($year, $timezone) { |
7cb29a3d |
1718 | |
e789650d |
1719 | if($timezone->dst_startday == 0 && $timezone->dst_weekday == 0 && $timezone->std_startday == 0 && $timezone->std_weekday == 0) { |
1720 | return NULL; |
42d36497 |
1721 | } |
7cb29a3d |
1722 | |
e789650d |
1723 | $monthdaydst = find_day_in_month($timezone->dst_startday, $timezone->dst_weekday, $timezone->dst_month, $year); |
1724 | $monthdaystd = find_day_in_month($timezone->std_startday, $timezone->std_weekday, $timezone->std_month, $year); |
1725 | |
1726 | list($dst_hour, $dst_min) = explode(':', $timezone->dst_time); |
1727 | list($std_hour, $std_min) = explode(':', $timezone->std_time); |
d2a9f7cc |
1728 | |
6dc8dddc |
1729 | $timedst = make_timestamp($year, $timezone->dst_month, $monthdaydst, 0, 0, 0, 99, false); |
1730 | $timestd = make_timestamp($year, $timezone->std_month, $monthdaystd, 0, 0, 0, 99, false); |
830a2bbd |
1731 | |
1732 | // Instead of putting hour and minute in make_timestamp(), we add them afterwards. |
1733 | // This has the advantage of being able to have negative values for hour, i.e. for timezones |
1734 | // where GMT time would be in the PREVIOUS day than the local one on which DST changes. |
1735 | |
1736 | $timedst += $dst_hour * HOURSECS + $dst_min * MINSECS; |
1737 | $timestd += $std_hour * HOURSECS + $std_min * MINSECS; |
42d36497 |
1738 | |
e789650d |
1739 | return array('dst' => $timedst, 0 => $timedst, 'std' => $timestd, 1 => $timestd); |
42d36497 |
1740 | } |
1741 | |
02f0527d |
1742 | // $time must NOT be compensated at all, it has to be a pure timestamp |
94c82430 |
1743 | function dst_offset_on($time, $strtimezone = NULL) { |
2280ecf5 |
1744 | global $SESSION; |
02f0527d |
1745 | |
94c82430 |
1746 | if(!calculate_user_dst_table(NULL, NULL, $strtimezone) || empty($SESSION->dst_offsets)) { |
c9e72798 |
1747 | return 0; |
85cafb3e |
1748 | } |
1749 | |
2280ecf5 |
1750 | reset($SESSION->dst_offsets); |
1751 | while(list($from, $offset) = each($SESSION->dst_offsets)) { |
59556d48 |
1752 | if($from <= $time) { |
c9e72798 |
1753 | break; |
1754 | } |
1755 | } |
1756 | |
830a2bbd |
1757 | // This is the normal return path |
1758 | if($offset !== NULL) { |
1759 | return $offset; |
02f0527d |
1760 | } |
02f0527d |
1761 | |
830a2bbd |
1762 | // Reaching this point means we haven't calculated far enough, do it now: |
1763 | // Calculate extra DST changes if needed and recurse. The recursion always |
1764 | // moves toward the stopping condition, so will always end. |
1765 | |
1766 | if($from == 0) { |
2280ecf5 |
1767 | // We need a year smaller than $SESSION->dst_range[0] |
1768 | if($SESSION->dst_range[0] == 1971) { |
830a2bbd |
1769 | return 0; |
1770 | } |
94c82430 |
1771 | calculate_user_dst_table($SESSION->dst_range[0] - 5, NULL, $strtimezone); |
1772 | return dst_offset_on($time, $strtimezone); |
830a2bbd |
1773 | } |
1774 | else { |
2280ecf5 |
1775 | // We need a year larger than $SESSION->dst_range[1] |
1776 | if($SESSION->dst_range[1] == 2035) { |
830a2bbd |
1777 | return 0; |
1778 | } |
94c82430 |
1779 | calculate_user_dst_table(NULL, $SESSION->dst_range[1] + 5, $strtimezone); |
1780 | return dst_offset_on($time, $strtimezone); |
830a2bbd |
1781 | } |
85cafb3e |
1782 | } |
02f0527d |
1783 | |
28902d99 |
1784 | function find_day_in_month($startday, $weekday, $month, $year) { |
8dc3f6cf |
1785 | |
1786 | $daysinmonth = days_in_month($month, $year); |
1787 | |
42d36497 |
1788 | if($weekday == -1) { |
28902d99 |
1789 | // Don't care about weekday, so return: |
1790 | // abs($startday) if $startday != -1 |
1791 | // $daysinmonth otherwise |
1792 | return ($startday == -1) ? $daysinmonth : abs($startday); |
8dc3f6cf |
1793 | } |
1794 | |
1795 | // From now on we 're looking for a specific weekday |
8dc3f6cf |
1796 | |
28902d99 |
1797 | // Give "end of month" its actual value, since we know it |
1798 | if($startday == -1) { |
1799 | $startday = -1 * $daysinmonth; |
1800 | } |
1801 | |
1802 | // Starting from day $startday, the sign is the direction |
8dc3f6cf |
1803 | |
28902d99 |
1804 | if($startday < 1) { |
8dc3f6cf |
1805 | |
28902d99 |
1806 | $startday = abs($startday); |
8dc3f6cf |
1807 | $lastmonthweekday = strftime('%w', mktime(12, 0, 0, $month, $daysinmonth, $year, 0)); |
1808 | |
1809 | // This is the last such weekday of the month |
1810 | $lastinmonth = $daysinmonth + $weekday - $lastmonthweekday; |
1811 | if($lastinmonth > $daysinmonth) { |
1812 | $lastinmonth -= 7; |
42d36497 |
1813 | } |
8dc3f6cf |
1814 | |
28902d99 |
1815 | // Find the first such weekday <= $startday |
1816 | while($lastinmonth > $startday) { |
8dc3f6cf |
1817 | $lastinmonth -= 7; |
42d36497 |
1818 | } |
8dc3f6cf |
1819 | |
1820 | return $lastinmonth; |
e1ecf0a0 |
1821 | |
42d36497 |
1822 | } |
1823 | else { |
42d36497 |
1824 | |
28902d99 |
1825 | $indexweekday = strftime('%w', mktime(12, 0, 0, $month, $startday, $year, 0)); |
42d36497 |
1826 | |
8dc3f6cf |
1827 | $diff = $weekday - $indexweekday; |
1828 | if($diff < 0) { |
1829 | $diff += 7; |
42d36497 |
1830 | } |
42d36497 |
1831 | |
28902d99 |
1832 | // This is the first such weekday of the month equal to or after $startday |
1833 | $firstfromindex = $startday + $diff; |
42d36497 |
1834 | |
8dc3f6cf |
1835 | return $firstfromindex; |
1836 | |
1837 | } |
42d36497 |
1838 | } |
1839 | |
bbd3f2c4 |
1840 | /** |
1841 | * Calculate the number of days in a given month |
1842 | * |
1843 | * @param int $month The month whose day count is sought |
1844 | * @param int $year The year of the month whose day count is sought |
1845 | * @return int |
1846 | */ |
42d36497 |
1847 | function days_in_month($month, $year) { |
1848 | return intval(date('t', mktime(12, 0, 0, $month, 1, $year, 0))); |
1849 | } |
1850 | |
bbd3f2c4 |
1851 | /** |
1852 | * Calculate the position in the week of a specific calendar day |
1853 | * |
1854 | * @param int $day The day of the date whose position in the week is sought |
1855 | * @param int $month The month of the date whose position in the week is sought |
1856 | * @param int $year The year of the date whose position in the week is sought |
1857 | * @return int |
1858 | */ |
8dc3f6cf |
1859 | function dayofweek($day, $month, $year) { |
1860 | // I wonder if this is any different from |
1861 | // strftime('%w', mktime(12, 0, 0, $month, $daysinmonth, $year, 0)); |
1862 | return intval(date('w', mktime(12, 0, 0, $month, $day, $year, 0))); |
1863 | } |
1864 | |
9fa49e22 |
1865 | /// USER AUTHENTICATION AND LOGIN //////////////////////////////////////// |
f9903ed0 |
1866 | |
93f66983 |
1867 | /** |
1868 | * Returns full login url. |
1869 | * |
1870 | * @param bool $loginguest add login guest param |
1871 | * @return string login url |
1872 | */ |
1873 | function get_login_url($loginguest=false) { |
1874 | global $CFG; |
1875 | |
1876 | if (empty($CFG->loginhttps) or $loginguest) { //do not require https for guest logins |
1877 | $loginguest = $loginguest ? '?loginguest=true' : ''; |
1878 | $url = "$CFG->wwwroot/login/index.php$loginguest"; |
1879 | |
1880 | } else { |
1881 | $wwwroot = str_replace('http:','https:', $CFG->wwwroot); |
1882 | $url = "$wwwroot/login/index.php"; |
1883 | } |
1884 | |
1885 | return $url; |
1886 | } |
1887 | |
7cf1c7bd |
1888 | /** |
ec81373f |
1889 | * This function checks that the current user is logged in and has the |
1890 | * required privileges |
1891 | * |
7cf1c7bd |
1892 | * This function checks that the current user is logged in, and optionally |
ec81373f |
1893 | * whether they are allowed to be in a particular course and view a particular |
1894 | * course module. |
1895 | * If they are not logged in, then it redirects them to the site login unless |
d2a9f7cc |
1896 | * $autologinguest is set and {@link $CFG}->autologinguests is set to 1 in which |
ec81373f |
1897 | * case they are automatically logged in as guests. |
1898 | * If $courseid is given and the user is not enrolled in that course then the |
1899 | * user is redirected to the course enrolment page. |
1900 | * If $cm is given and the coursemodule is hidden and the user is not a teacher |
1901 | * in the course then the user is redirected to the course home page. |
7cf1c7bd |
1902 | * |
7cf1c7bd |
1903 | * @uses $CFG |
c6d15803 |
1904 | * @uses $SESSION |
7cf1c7bd |
1905 | * @uses $USER |
1906 | * @uses $FULLME |
c6d15803 |
1907 | * @uses SITEID |
f07fa644 |
1908 | * @uses $COURSE |
33ebaf7c |
1909 | * @param mixed $courseorid id of the course or course object |
bbd3f2c4 |
1910 | * @param bool $autologinguest |
1911 | * @param object $cm course module object |
f4013c10 |
1912 | * @param bool $setwantsurltome Define if we want to set $SESSION->wantsurl, defaults to |
1913 | * true. Used to avoid (=false) some scripts (file.php...) to set that variable, |
1914 | * in order to keep redirects working properly. MDL-14495 |
7cf1c7bd |
1915 | */ |
f4013c10 |
1916 | function require_login($courseorid=0, $autologinguest=true, $cm=null, $setwantsurltome=true) { |
948203a5 |
1917 | global $CFG, $SESSION, $USER, $COURSE, $FULLME, $PAGE, $SITE, $DB; |
d8ba183c |
1918 | |
083c3743 |
1919 | /// setup global $COURSE, themes, language and locale |
c13a5e71 |
1920 | if (!empty($courseorid)) { |
1921 | if (is_object($courseorid)) { |
1922 | $course = $courseorid; |
1923 | } else if ($courseorid == SITEID) { |
1924 | $course = clone($SITE); |
1925 | } else { |
1926 | $course = $DB->get_record('course', array('id' => $courseorid)); |
1927 | if (!$course) { |
1928 | throw new moodle_exception('invalidcourseid'); |
1929 | } |
1930 | } |
1931 | $PAGE->set_course($course); |
e88462a0 |
1932 | } else { |
1933 | // If $PAGE->course, and hence $PAGE->context, have not already been set |
1934 | // up properly, set them up now. |
1935 | $PAGE->set_course($PAGE->course); |
c13a5e71 |
1936 | } |
be933850 |
1937 | |
1845f8b8 |
1938 | /// If the user is not even logged in yet then make sure they are |
083c3743 |
1939 | if (!isloggedin()) { |
1940 | //NOTE: $USER->site check was obsoleted by session test cookie, |
1941 | // $USER->confirmed test is in login/index.php |
f4013c10 |
1942 | if ($setwantsurltome) { |
1943 | $SESSION->wantsurl = $FULLME; |
1944 | } |
b0ccd3fb |
1945 | if (!empty($_SERVER['HTTP_REFERER'])) { |
1946 | $SESSION->fromurl = $_SERVER['HTTP_REFERER']; |
9f44d972 |
1947 | } |
ad56b737 |
1948 | if ($autologinguest and !empty($CFG->guestloginbutton) and !empty($CFG->autologinguests) and ($COURSE->id == SITEID or $COURSE->guest) ) { |
93f66983 |
1949 | $loginguest = true; |
8a33e371 |
1950 | } else { |
93f66983 |
1951 | $loginguest = false; |
8a33e371 |
1952 | } |
93f66983 |
1953 | redirect(get_login_url($loginguest)); |
1954 | exit; // never reached |
f9903ed0 |
1955 | } |
808a3baa |
1956 | |
f6f66b03 |
1957 | /// loginas as redirection if needed |
b7b64ff2 |
1958 | if ($COURSE->id != SITEID and session_is_loggedinas()) { |
f6f66b03 |
1959 | if ($USER->loginascontext->contextlevel == CONTEXT_COURSE) { |
1960 | if ($USER->loginascontext->instanceid != $COURSE->id) { |
3887fe4a |
1961 | print_error('loginasonecourse', '', $CFG->wwwroot.'/course/view.php?id='.$USER->loginascontext->instanceid); |
5e623a33 |
1962 | } |
f6f66b03 |
1963 | } |
1964 | } |
1965 | |
5602f7cf |
1966 | /// check whether the user should be changing password (but only if it is REALLY them) |
b7b64ff2 |
1967 | if (get_user_preferences('auth_forcepasswordchange') && !session_is_loggedinas()) { |
21e2dcd9 |
1968 | $userauth = get_auth_plugin($USER->auth); |
03d820c7 |
1969 | if ($userauth->can_change_password()) { |
20fde7b1 |
1970 | $SESSION->wantsurl = $FULLME; |
80274abf |
1971 | if ($changeurl = $userauth->change_password_url()) { |
9696bd89 |
1972 | //use plugin custom url |
80274abf |
1973 | redirect($changeurl); |
1437f0a5 |
1974 | } else { |
9696bd89 |
1975 | //use moodle internal method |
1976 | if (empty($CFG->loginhttps)) { |
1977 | redirect($CFG->wwwroot .'/login/change_password.php'); |
1978 | } else { |
1979 | $wwwroot = str_replace('http:','https:', $CFG->wwwroot); |
1980 | redirect($wwwroot .'/login/change_password.php'); |
1981 | } |
1437f0a5 |
1982 | } |
d35757eb |
1983 | } else { |
a8ee7194 |
1984 | print_error('nopasswordchangeforced', 'auth'); |
d35757eb |
1985 | } |
1986 | } |
083c3743 |
1987 | |
1845f8b8 |
1988 | /// Check that the user account is properly set up |
808a3baa |
1989 | if (user_not_fully_set_up($USER)) { |
20fde7b1 |
1990 | $SESSION->wantsurl = $FULLME; |
b0ccd3fb |
1991 | redirect($CFG->wwwroot .'/user/edit.php?id='. $USER->id .'&course='. SITEID); |
808a3baa |
1992 | } |
d8ba183c |
1993 | |
1845f8b8 |
1994 | /// Make sure the USER has a sesskey set up. Used for checking script parameters. |
04280e85 |
1995 | sesskey(); |
366dfa60 |
1996 | |
027a1604 |
1997 | // Check that the user has agreed to a site policy if there is one |
1998 | if (!empty($CFG->sitepolicy)) { |
1999 | if (!$USER->policyagreed) { |
957b5198 |
2000 | $SESSION->wantsurl = $FULLME; |
027a1604 |
2001 | redirect($CFG->wwwroot .'/user/policy.php'); |
027a1604 |
2002 | } |
1695b680 |
2003 | } |
2004 | |
21e2dcd9 |
2005 | // Fetch the system context, we are going to use it a lot. |
2006 | $sysctx = get_context_instance(CONTEXT_SYSTEM); |
2007 | |
1845f8b8 |
2008 | /// If the site is currently under maintenance, then print a message |
21e2dcd9 |
2009 | if (!has_capability('moodle/site:config', $sysctx)) { |
eeefd0b0 |
2010 | if (file_exists($CFG->dataroot.'/'.SITEID.'/maintenance.html')) { |
1695b680 |
2011 | print_maintenance_message(); |
20fde7b1 |
2012 | exit; |
1695b680 |
2013 | } |
027a1604 |
2014 | } |
2015 | |
f8e3d5f0 |
2016 | /// groupmembersonly access control |
2017 | if (!empty($CFG->enablegroupings) and $cm and $cm->groupmembersonly and !has_capability('moodle/site:accessallgroups', get_context_instance(CONTEXT_MODULE, $cm->id))) { |
2018 | if (isguestuser() or !groups_has_membership($cm)) { |
a8ee7194 |
2019 | print_error('groupmembersonlyerror', 'group', $CFG->wwwroot.'/course/view.php?id='.$cm->course); |
f8e3d5f0 |
2020 | } |
2021 | } |
1845f8b8 |
2022 | |
21e2dcd9 |
2023 | // Fetch the course context, and prefetch its child contexts |
2024 | if (!isset($COURSE->context)) { |
2025 | if ( ! $COURSE->context = get_context_instance(CONTEXT_COURSE, $COURSE->id) ) { |
ae040d4b |
2026 | print_error('nocontext'); |
21e2dcd9 |
2027 | } |
2028 | } |
48f9c073 |
2029 | if (!empty($cm) && !isset($cm->context)) { |
2030 | if ( ! $cm->context = get_context_instance(CONTEXT_MODULE, $cm->id) ) { |
2031 | print_error('nocontext'); |
2032 | } |
2033 | } |
82bd6a5e |
2034 | |
2035 | // Conditional activity access control |
2036 | if(!empty($CFG->enableavailability) and $cm) { |
2037 | // We cache conditional access in session |
2038 | if(!isset($SESSION->conditionaccessok)) { |
013376de |
2039 | $SESSION->conditionaccessok = array(); |
82bd6a5e |
2040 | } |
2041 | // If you have been allowed into the module once then you are allowed |
2042 | // in for rest of session, no need to do conditional checks |
013376de |
2043 | if (!array_key_exists($cm->id, $SESSION->conditionaccessok)) { |
82bd6a5e |
2044 | // Get condition info (does a query for the availability table) |
b3d960e6 |
2045 | require_once($CFG->libdir.'/conditionlib.php'); |
013376de |
2046 | $ci = new condition_info($cm, CONDITION_MISSING_EXTRATABLE); |
82bd6a5e |
2047 | // Check condition for user (this will do a query if the availability |
2048 | // information depends on grade or completion information) |
013376de |
2049 | if ($ci->is_available($junk) || |
48f9c073 |
2050 | has_capability('moodle/course:viewhiddenactivities', $cm->context)) { |
013376de |
2051 | $SESSION->conditionaccessok[$cm->id] = true; |
82bd6a5e |
2052 | } else { |
2053 | print_error('activityiscurrentlyhidden'); |
2054 | } |
2055 | } |
2056 | } |
2057 | |
33ebaf7c |
2058 | if ($COURSE->id == SITEID) { |
21e2dcd9 |
2059 | /// Eliminate hidden site activities straight away |
ae040d4b |
2060 | if (!empty($cm) && !$cm->visible |
48f9c073 |
2061 | && !has_capability('moodle/course:viewhiddenactivities', $cm->context)) { |
33ebaf7c |
2062 | redirect($CFG->wwwroot, get_string('activityiscurrentlyhidden')); |
e3512050 |
2063 | } |
341b5ed2 |
2064 | user_accesstime_log($COURSE->id); /// Access granted, update lastaccess times |
33ebaf7c |
2065 | return; |
881a77bf |
2066 | |
5e623a33 |
2067 | } else { |
1845f8b8 |
2068 | |
21e2dcd9 |
2069 | /// Check if the user can be in a particular course |
2070 | if (empty($USER->access['rsw'][$COURSE->context->path])) { |
1cf2e21b |
2071 | // |
a8ee7194 |
2072 | // MDL-13900 - If the course or the parent category are hidden |
2073 | // and the user hasn't the 'course:viewhiddencourses' capability, prevent access |
1cf2e21b |
2074 | // |
a8ee7194 |
2075 | if ( !($COURSE->visible && course_parent_visible($COURSE)) && |
2076 | !has_capability('moodle/course:viewhiddencourses', $COURSE->context)) { |
1cf2e21b |
2077 | print_header_simple(); |
2078 | notice(get_string('coursehidden'), $CFG->wwwroot .'/'); |
2079 | } |
a8ee7194 |
2080 | } |
2081 | |
f71346e2 |
2082 | /// Non-guests who don't currently have access, check if they can be allowed in as a guest |
2083 | |
21e2dcd9 |
2084 | if ($USER->username != 'guest' and !has_capability('moodle/course:view', $COURSE->context)) { |
33ebaf7c |
2085 | if ($COURSE->guest == 1) { |
eef879ec |
2086 | // Temporarily assign them guest role for this context, if it fails later user is asked to enrol |
21e2dcd9 |
2087 | $USER->access = load_temp_role($COURSE->context, $CFG->guestroleid, $USER->access); |
f71346e2 |
2088 | } |
2089 | } |
2090 | |
1845f8b8 |
2091 | /// If the user is a guest then treat them according to the course policy about guests |
2092 | |
21e2dcd9 |
2093 | if (has_capability('moodle/legacy:guest', $COURSE->context, NULL, false)) { |
5f431c1b |
2094 | if (has_capability('moodle/site:doanything', $sysctx)) { |
2095 | // administrators must be able to access any course - even if somebody gives them guest access |
341b5ed2 |
2096 | user_accesstime_log($COURSE->id); /// Access granted, update lastaccess times |
b03f7215 |
2097 | return; |
5f431c1b |
2098 | } |
2099 | |
33ebaf7c |
2100 | switch ($COURSE->guest) { /// Check course policy about guest access |
1845f8b8 |
2101 | |
ae040d4b |
2102 | case 1: /// Guests always allowed |
21e2dcd9 |
2103 | if (!has_capability('moodle/course:view', $COURSE->context)) { // Prohibited by capability |
1845f8b8 |
2104 | print_header_simple(); |
93f66983 |
2105 | notice(get_string('guestsnotallowed', '', format_string($COURSE->fullname)), get_login_url()); |
1845f8b8 |
2106 | } |
2107 | if (!empty($cm) and !$cm->visible) { // Not allowed to see module, send to course page |
5e623a33 |
2108 | redirect($CFG->wwwroot.'/course/view.php?id='.$cm->course, |
1845f8b8 |
2109 | get_string('activityiscurrentlyhidden')); |
2110 | } |
2111 | |
341b5ed2 |
2112 | user_accesstime_log($COURSE->id); /// Access granted, update lastaccess times |
1845f8b8 |
2113 | return; // User is allowed to see this course |
2114 | |
2115 | break; |
2116 | |
5e623a33 |
2117 | case 2: /// Guests allowed with key |
33ebaf7c |
2118 | if (!empty($USER->enrolkey[$COURSE->id])) { // Set by enrol/manual/enrol.php |
341b5ed2 |
2119 | user_accesstime_log($COURSE->id); /// Access granted, update lastaccess times |
b1f318a6 |
2120 | return true; |
2121 | } |
2122 | // otherwise drop through to logic below (--> enrol.php) |
1845f8b8 |
2123 | break; |
bbbf2d40 |
2124 | |
1845f8b8 |
2125 | default: /// Guests not allowed |
0be6f678 |
2126 | $strloggedinasguest = get_string('loggedinasguest'); |
2127 | print_header_simple('', '', |
2128 | build_navigation(array(array('name' => $strloggedinasguest, 'link' => null, 'type' => 'misc')))); |
21e2dcd9 |
2129 | if (empty($USER->access['rsw'][$COURSE->context->path])) { // Normal guest |
93f66983 |
2130 | notice(get_string('guestsnotallowed', '', format_string($COURSE->fullname)), get_login_url()); |
21596567 |
2131 | } else { |
6ba65fa0 |
2132 | notify(get_string('guestsnotallowed', '', format_string($COURSE->fullname))); |
33ebaf7c |
2133 | echo '<div class="notifyproblem">'.switchroles_form($COURSE->id).'</div>'; |
2134 | print_footer($COURSE); |
21596567 |
2135 | exit; |
2136 | } |
1845f8b8 |
2137 | break; |
2138 | } |
2139 | |
2140 | /// For non-guests, check if they have course view access |
2141 | |
21e2dcd9 |
2142 | } else if (has_capability('moodle/course:view', $COURSE->context)) { |
b7b64ff2 |
2143 | if (session_is_loggedinas()) { // Make sure the REAL person can also access this course |
2144 | $realuser = session_get_realuser(); |
6132768e |
2145 | if (!has_capability('moodle/course:view', $COURSE->context, $realuser->id)) { |
1845f8b8 |
2146 | print_header_simple(); |
b0ccd3fb |
2147 | notice(get_string('studentnotallowed', '', fullname($USER, true)), $CFG->wwwroot .'/'); |
cb909d74 |
2148 | } |
3ce2f1e0 |
2149 | } |
1845f8b8 |
2150 | |
2151 | /// Make sure they can read this activity too, if specified |
2152 | |
2bf69a85 |
2153 | if (!empty($cm) && !$cm->visible && !has_capability('moodle/course:viewhiddenactivities', $cm->context)) { |
ec81373f |
2154 | redirect($CFG->wwwroot.'/course/view.php?id='.$cm->course, get_string('activityiscurrentlyhidden')); |
2155 | } |
341b5ed2 |
2156 | user_accesstime_log($COURSE->id); /// Access granted, update lastaccess times |
1845f8b8 |
2157 | return; // User is allowed to see this course |
2158 | |
da5c172a |
2159 | } |
f9903ed0 |
2160 | |
9ca3b4f3 |
2161 | |
1845f8b8 |
2162 | /// Currently not enrolled in the course, so see if they want to enrol |
da5c172a |
2163 | $SESSION->wantsurl = $FULLME; |
33ebaf7c |
2164 | redirect($CFG->wwwroot .'/course/enrol.php?id='. $COURSE->id); |
da5c172a |
2165 | die; |
2166 | } |
f9903ed0 |
2167 | } |
2168 | |
c4d0753b |
2169 | |
2170 | |
2171 | /** |
2172 | * This function just makes sure a user is logged out. |
2173 | * |
2174 | * @uses $CFG |
2175 | * @uses $USER |
2176 | */ |
2177 | function require_logout() { |
dd9e22f8 |
2178 | global $USER; |
c4d0753b |
2179 | |
111e2360 |
2180 | if (isloggedin()) { |
c4d0753b |
2181 | add_to_log(SITEID, "user", "logout", "view.php?id=$USER->id&course=".SITEID, $USER->id, 0, $USER->id); |
2182 | |
533f7910 |
2183 | $authsequence = get_enabled_auth_plugins(); // auths, in sequence |
2184 | foreach($authsequence as $authname) { |
2185 | $authplugin = get_auth_plugin($authname); |
2186 | $authplugin->prelogout_hook(); |
81693ac7 |
2187 | } |
c4d0753b |
2188 | } |
2189 | |
56949c17 |
2190 | session_get_instance()->terminate_current(); |
c4d0753b |
2191 | } |
2192 | |
7cf1c7bd |
2193 | /** |
2194 | * This is a weaker version of {@link require_login()} which only requires login |
2195 | * when called from within a course rather than the site page, unless |
2196 | * the forcelogin option is turned on. |
2197 | * |
2198 | * @uses $CFG |
33ebaf7c |
2199 | * @param mixed $courseorid The course object or id in question |
bbd3f2c4 |
2200 | * @param bool $autologinguest Allow autologin guests if that is wanted |
4febb58f |
2201 | * @param object $cm Course activity module if known |
f4013c10 |
2202 | * @param bool $setwantsurltome Define if we want to set $SESSION->wantsurl, defaults to |
2203 | * true. Used to avoid (=false) some scripts (file.php...) to set that variable, |
2204 | * in order to keep redirects working properly. MDL-14495 |
7cf1c7bd |
2205 | */ |
f4013c10 |
2206 | function require_course_login($courseorid, $autologinguest=true, $cm=null, $setwantsurltome=true) { |
f950af3c |
2207 | global $CFG; |
1596edff |
2208 | if (!empty($CFG->forcelogin)) { |
33ebaf7c |
2209 | // login required for both SITE and courses |
f4013c10 |
2210 | require_login($courseorid, $autologinguest, $cm, $setwantsurltome); |
63c9ee99 |
2211 | |
2212 | } else if (!empty($cm) and !$cm->visible) { |
2213 | // always login for hidden activities |
f4013c10 |
2214 | require_login($courseorid, $autologinguest, $cm, $setwantsurltome); |
63c9ee99 |
2215 | |
39de90ac |
2216 | } else if ((is_object($courseorid) and $courseorid->id == SITEID) |
2217 | or (!is_object($courseorid) and $courseorid == SITEID)) { |
33ebaf7c |
2218 | //login for SITE not required |
341b5ed2 |
2219 | user_accesstime_log(SITEID); |
63c9ee99 |
2220 | return; |
2221 | |
33ebaf7c |
2222 | } else { |
2223 | // course login always required |
f4013c10 |
2224 | require_login($courseorid, $autologinguest, $cm, $setwantsurltome); |
f950af3c |
2225 | } |
2226 | } |
2227 | |
61c6071f |
2228 | /** |
2229 | * Require key login. Function terminates with error if key not found or incorrect. |
2230 | * @param string $script unique script identifier |
2231 | * @param int $instance optional instance id |
2232 | */ |
2233 | function require_user_key_login($script, $instance=null) { |
82dd4f42 |
2234 | global $USER, $SESSION, $CFG, $DB; |
61c6071f |
2235 | |
82dd4f42 |
2236 | if (!NO_MOODLE_COOKIES) { |
2f137aa1 |
2237 | print_error('sessioncookiesdisable'); |
61c6071f |
2238 | } |
2239 | |
2240 | /// extra safety |
2241 | @session_write_close(); |
2242 | |
2243 | $keyvalue = required_param('key', PARAM_ALPHANUM); |
2244 | |
ae040d4b |
2245 | if (!$key = $DB->get_record('user_private_key', array('script'=>$script, 'value'=>$keyvalue, 'instance'=>$instance))) { |
2f137aa1 |
2246 | print_error('invalidkey'); |
61c6071f |
2247 | } |
2248 | |
2249 | if (!empty($key->validuntil) and $key->validuntil < time()) { |
2f137aa1 |
2250 | print_error('expiredkey'); |
61c6071f |
2251 | } |
2252 | |
e436033f |
2253 | if ($key->iprestriction) { |
2254 | $remoteaddr = getremoteaddr(); |
2255 | if ($remoteaddr == '' or !address_in_subnet($remoteaddr, $key->iprestriction)) { |
2f137aa1 |
2256 | print_error('ipmismatch'); |
e436033f |
2257 | } |
61c6071f |
2258 | } |
2259 | |
ae040d4b |
2260 | if (!$user = $DB->get_record('user', array('id'=>$key->userid))) { |
2f137aa1 |
2261 | print_error('invaliduserid'); |
61c6071f |
2262 | } |
2263 | |
2264 | /// emulate normal session |
27df7ae8 |
2265 | session_set_user($user); |
61c6071f |
2266 | |
e2fa911b |
2267 | /// note we are not using normal login |
2268 | if (!defined('USER_KEY_LOGIN')) { |
2269 | define('USER_KEY_LOGIN', true); |
2270 | } |
2271 | |
61c6071f |
2272 | /// return isntance id - it might be empty |
2273 | return $key->instance; |
2274 | } |
2275 | |
2276 | /** |
2277 | * Creates a new private user access key. |
2278 | * @param string $script unique target identifier |
2279 | * @param int $userid |
2280 | * @param instance $int optional instance id |
2281 | * @param string $iprestriction optional ip restricted access |
2282 | * @param timestamp $validuntil key valid only until given data |
2283 | * @return string access key value |
2284 | */ |
2285 | function create_user_key($script, $userid, $instance=null, $iprestriction=null, $validuntil=null) { |
ae040d4b |
2286 | global $DB; |
2287 | |
61c6071f |
2288 | $key = new object(); |
2289 | $key->script = $script; |
2290 | $key->userid = $userid; |
2291 | $key->instance = $instance; |
2292 | $key->iprestriction = $iprestriction; |
2293 | $key->validuntil = $validuntil; |
2294 | $key->timecreated = time(); |
2295 | |
2296 | $key->value = md5($userid.'_'.time().random_string(40)); // something long and unique |
ae040d4b |
2297 | while ($DB->record_exists('user_private_key', array('value'=>$key->value))) { |
61c6071f |
2298 | // must be unique |
2299 | $key->value = md5($userid.'_'.time().random_string(40)); |
2300 | } |
2301 | |
ae040d4b |
2302 | if (!$DB->insert_record('user_private_key', $key)) { |
2f137aa1 |
2303 | print_error('cannotinsertkey'); |
61c6071f |
2304 | } |
2305 | |
2306 | return $key->value; |
2307 | } |
2308 | |
7cf1c7bd |
2309 | /** |
2310 | * Modify the user table by setting the currently logged in user's |
2311 | * last login to now. |
2312 | * |
2313 | * @uses $USER |
bbd3f2c4 |
2314 | * @return bool |
7cf1c7bd |
2315 | */ |
1d881d92 |
2316 | function update_user_login_times() { |
ae040d4b |
2317 | global $USER, $DB; |
1d881d92 |
2318 | |
53467aa6 |
2319 | $user = new object(); |
1d881d92 |
2320 | $USER->lastlogin = $user->lastlogin = $USER->currentlogin; |
2a2f5f11 |
2321 | $USER->currentlogin = $user->lastaccess = $user->currentlogin = time(); |
1d881d92 |
2322 | |
2323 | $user->id = $USER->id; |
2324 | |
013376de |
2325 | $DB->update_record('user', $user); |
2326 | return true; |
1d881d92 |
2327 | } |
2328 | |
7cf1c7bd |
2329 | /** |
2330 | * Determines if a user has completed setting up their account. |
2331 | * |
89dcb99d |
2332 | * @param user $user A {@link $USER} object to test for the existance of a valid name and email |
bbd3f2c4 |
2333 | * @return bool |
7cf1c7bd |
2334 | */ |
808a3baa |
2335 | function user_not_fully_set_up($user) { |
bb64b51a |
2336 | return ($user->username != 'guest' and (empty($user->firstname) or empty($user->lastname) or empty($user->email) or over_bounce_threshold($user))); |
2337 | } |
2338 | |
2339 | function over_bounce_threshold($user) { |
ae040d4b |
2340 | global $CFG, $DB; |
d2a9f7cc |
2341 | |
bb64b51a |
2342 | if (empty($CFG->handlebounces)) { |
2343 | return false; |
2344 | } |
e0ec2d45 |
2345 | |
2346 | if (empty($user->id)) { /// No real (DB) user, nothing to do here. |
2347 | return false; |
2348 | } |
2349 | |
bb64b51a |
2350 | // set sensible defaults |
2351 | if (empty($CFG->minbounces)) { |
2352 | $CFG->minbounces = 10; |
2353 | } |
2354 | if (empty($CFG->bounceratio)) { |
2355 | $CFG->bounceratio = .20; |
2356 | } |
2357 | $bouncecount = 0; |
2358 | $sendcount = 0; |
ae040d4b |
2359 | if ($bounce = $DB->get_record('user_preferences', array ('userid'=>$user->id, 'name'=>'email_bounce_count'))) { |
bb64b51a |
2360 | $bouncecount = $bounce->value; |
2361 | } |
ae040d4b |
2362 | if ($send = $DB->get_record('user_preferences', array('userid'=>$user->id, 'name'=>'email_send_count'))) { |
bb64b51a |
2363 | $sendcount = $send->value; |
2364 | } |
2365 | return ($bouncecount >= $CFG->minbounces && $bouncecount/$sendcount >= $CFG->bounceratio); |
2366 | } |
2367 | |
d2a9f7cc |
2368 | /** |
bb64b51a |
2369 | * @param $user - object containing an id |
2370 | * @param $reset - will reset the count to 0 |
2371 | */ |
2372 | function set_send_count($user,$reset=false) { |
ae040d4b |
2373 | global $DB; |
2374 | |
e0ec2d45 |
2375 | if (empty($user->id)) { /// No real (DB) user, nothing to do here. |
2376 | return; |
2377 | } |
2378 | |
ae040d4b |
2379 | if ($pref = $DB->get_record('user_preferences', array('userid'=>$user->id, 'name'=>'email_send_count'))) { |
bb64b51a |
2380 | $pref->value = (!empty($reset)) ? 0 : $pref->value+1; |
ae040d4b |
2381 | $DB->update_record('user_preferences', $pref); |
bb64b51a |
2382 | } |
2383 | else if (!empty($reset)) { // if it's not there and we're resetting, don't bother. |
2384 | // make a new one |
ae040d4b |
2385 | $pref = new object(); |
2386 | $pref->name = 'email_send_count'; |
2387 | $pref->value = 1; |
bb64b51a |
2388 | $pref->userid = $user->id; |
ae040d4b |
2389 | $DB->insert_record('user_preferences', $pref, false); |
bb64b51a |
2390 | } |
2391 | } |
2392 | |
d2a9f7cc |
2393 | /** |
bb64b51a |
2394 | * @param $user - object containing an id |
2395 | * @param $reset - will reset the count to 0 |
2396 | */ |
2397 | function set_bounce_count($user,$reset=false) { |
ae040d4b |
2398 | global $DB; |
2399 | |
2400 | if ($pref = $DB->get_record('user_preferences', array('userid'=>$user->id, 'name'=>'email_bounce_count'))) { |
bb64b51a |
2401 | $pref->value = (!empty($reset)) ? 0 : $pref->value+1; |
ae040d4b |
2402 | $DB->update_record('user_preferences', $pref); |
bb64b51a |
2403 | } |
2404 | else if (!empty($reset)) { // if it's not there and we're resetting, don't bother. |
2405 | // make a new one |
ae040d4b |
2406 | $pref = new object(); |
2407 | $pref->name = 'email_bounce_count'; |
2408 | $pref->value = 1; |
bb64b51a |
2409 | $pref->userid = $user->id; |
ae040d4b |
2410 | $DB->insert_record('user_preferences', $pref, false); |
bb64b51a |
2411 | } |
808a3baa |
2412 | } |
f9903ed0 |
2413 | |
7cf1c7bd |
2414 | /** |
2415 | * Keeps track of login attempts |
2416 | * |
2417 | * @uses $SESSION |
2418 | */ |
f9903ed0 |
2419 | function update_login_count() { |
2420 | global $SESSION; |
2421 | |
2422 | $max_logins = 10; |
2423 | |
2424 | if (empty($SESSION->logincount)) { |
2425 | $SESSION->logincount = 1; |
2426 | } else { |
2427 | $SESSION->logincount++; |
2428 | } |
2429 | |
2430 | if ($SESSION->logincount > $max_logins) { |
9fa49e22 |
2431 | unset($SESSION->wantsurl); |
a8ee7194 |
2432 | print_error('errortoomanylogins'); |
d578afc8 |
2433 | } |
2434 | } |
2435 | |
7cf1c7bd |
2436 | /** |
2437 | * Resets login attempts |
2438 | * |
2439 | * @uses $SESSION |
2440 | */ |
9fa49e22 |
2441 | function reset_login_count() { |
9fa49e22 |
2442 | global $SESSION; |
d578afc8 |
2443 | |
9fa49e22 |
2444 | $SESSION->logincount = 0; |
d578afc8 |
2445 | } |
2446 | |
b61efafb |
2447 | function sync_metacourses() { |
ae040d4b |
2448 | global $DB; |
b61efafb |
2449 | |
ae040d4b |
2450 | if (!$courses = $DB->get_records('course', array('metacourse'=>1))) { |
b61efafb |
2451 | return; |
2452 | } |
d2a9f7cc |
2453 | |
b61efafb |
2454 | foreach ($courses as $course) { |
1aad4310 |
2455 | sync_metacourse($course); |
b61efafb |
2456 | } |
2457 | } |
2458 | |
73efeff6 |
2459 | /** |
2460 | * Returns reference to full info about modules in course (including visibility). |
2461 | * Cached and as fast as possible (0 or 1 db query). |
2462 | * @param $course object or 'reset' string to reset caches, modinfo may be updated in db |
2463 | * @return mixed courseinfo object or nothing if resetting |
2464 | */ |
2465 | function &get_fast_modinfo(&$course, $userid=0) { |
2466 | global $CFG, $USER, $DB; |
2467 | require_once($CFG->dirroot.'/course/lib.php'); |
2468 | |
2469 | if (!empty($CFG->enableavailability)) { |
2470 | require_once($CFG->libdir.'/conditionlib.php'); |
2471 | } |
2472 | |
2473 | static $cache = array(); |
2474 | |
2475 | if ($course === 'reset') { |
2476 | $cache = array(); |
2477 | $nothing = null; |
2478 | return $nothing; // we must return some reference |
2479 | } |
2480 | |
2481 | if (empty($userid)) { |
2482 | $userid = $USER->id; |
2483 | } |
2484 | |
2485 | if (array_key_exists($course->id, $cache) and $cache[$course->id]->userid == $userid) { |
2486 | return $cache[$course->id]; |
2487 | } |
2488 | |
2489 | if (empty($course->modinfo)) { |
2490 | // no modinfo yet - load it |
2491 | rebuild_course_cache($course->id); |
2492 | $course->modinfo = $DB->get_field('course', 'modinfo', array('id'=>$course->id)); |
2493 | } |
2494 | |
2495 | $modinfo = new object(); |
2496 | $modinfo->courseid = $course->id; |
2497 | $modinfo->userid = $userid; |
2498 | $modinfo->sections = array(); |
2499 | $modinfo->cms = array(); |
2500 | $modinfo->instances = array(); |
2501 | $modinfo->groups = null; // loaded only when really needed - the only one db query |
2502 | |
2503 | $info = unserialize($course->modinfo); |
2504 | if (!is_array($info)) { |
2505 | // hmm, something is wrong - lets try to fix it |
2506 | rebuild_course_cache($course->id); |
2507 | $course->modinfo = $DB->get_field('course', 'modinfo', array('id'=>$course->id)); |
2508 | $info = unserialize($course->modinfo); |
2509 | if (!is_array($info)) { |
2510 | return $modinfo; |
2511 | } |
2512 | } |
2513 | |
2514 | if ($info) { |
2515 | // detect if upgrade required |
2516 | $first = reset($info); |
2517 | if (!isset($first->id)) { |
2518 | rebuild_course_cache($course->id); |
2519 | $course->modinfo = $DB->get_field('course', 'modinfo', array('id'=>$course->id)); |
2520 | $info = unserialize($course->modinfo); |
2521 | if (!is_array($info)) { |
2522 | return $modinfo; |
2523 | } |
2524 | } |
2525 | } |
2526 | |
2527 | $modlurals = array(); |
2528 | |
2529 | // If we haven't already preloaded contexts for the course, do it now |
2530 | preload_course_contexts($course->id); |
2531 | |
2532 | foreach ($info as $mod) { |
2533 | if (empty($mod->name)) { |
2534 | // something is wrong here |
2535 | continue; |
2536 | } |
2537 | // reconstruct minimalistic $cm |
2538 | $cm = new object(); |
2539 | $cm->id = $mod->cm; |
2540 | $cm->instance = $mod->id; |
2541 | $cm->course = $course->id; |
2542 | $cm->modname = $mod->mod; |
2543 | $cm->name = urldecode($mod->name); |
2544 | $cm->visible = $mod->visible; |
2545 | $cm->sectionnum = $mod->section; |
2546 | $cm->groupmode = $mod->groupmode; |
2547 | $cm->groupingid = $mod->groupingid; |
2548 | $cm->groupmembersonly = $mod->groupmembersonly; |
2549 | $cm->indent = $mod->indent; |
2550 | $cm->completion = $mod->completion; |
2551 | $cm->extra = isset($mod->extra) ? urldecode($mod->extra) : ''; |
2552 | $cm->icon = isset($mod->icon) ? $mod->icon : ''; |
2553 | $cm->uservisible = true; |
2554 | if(!empty($CFG->enableavailability)) { |
2555 | // We must have completion information from modinfo. If it's not |
2556 | // there, cache needs rebuilding |
2557 | if(!isset($mod->availablefrom)) { |
2558 | debugging('enableavailability option was changed; rebuilding '. |
2559 | 'cache for course '.$course->id); |
2560 | rebuild_course_cache($course->id,true); |
2561 | // Re-enter this routine to do it all properly |
2562 | return get_fast_modinfo($course,$userid); |
2563 | } |
2564 | $cm->availablefrom = $mod->availablefrom; |
2565 | $cm->availableuntil = $mod->availableuntil; |
2566 | $cm->showavailability = $mod->showavailability; |
2567 | $cm->conditionscompletion = $mod->conditionscompletion; |
2568 | $cm->conditionsgrade = $mod->conditionsgrade; |
2569 | } |
2570 | |
2571 | // preload long names plurals and also check module is installed properly |
2572 | if (!isset($modlurals[$cm->modname])) { |
2573 | if (!file_exists("$CFG->dirroot/mod/$cm->modname/lib.php")) { |
2574 | continue; |
2575 | } |
2576 | $modlurals[$cm->modname] = get_string('modulenameplural', $cm->modname); |
2577 | } |
2578 | $cm->modplural = $modlurals[$cm->modname]; |
2579 | $modcontext = get_context_instance(CONTEXT_MODULE,$cm->id); |
2580 | |
2581 | if(!empty($CFG->enableavailability)) { |
2582 | // Unfortunately the next call really wants to call |
2583 | // get_fast_modinfo, but that would be recursive, so we fake up a |
2584 | // modinfo for it already |
2585 | if(empty($minimalmodinfo)) { |
2586 | $minimalmodinfo=new stdClass(); |
2587 | $minimalmodinfo->cms=array(); |
2588 | foreach($info as $mod) { |
2589 | $minimalcm=new stdClass(); |
2590 | $minimalcm->id=$mod->cm; |
2591 | $minimalcm->name=urldecode($mod->name); |
2592 | $minimalmodinfo->cms[$minimalcm->id]=$minimalcm; |
2593 | } |
2594 | } |
2595 | |
2596 | // Get availability information |
2597 | $ci = new condition_info($cm); |
2598 | $cm->available=$ci->is_available($cm->availableinfo,true,$userid, |
2599 | $minimalmodinfo); |
2600 | } else { |
2601 | $cm->available=true; |
2602 | } |
2603 | if ((!$cm->visible or !$cm->available) and !has_capability('moodle/course:viewhiddenactivities', $modcontext, $userid)) { |
2604 | $cm->uservisible = false; |
2605 | |
2606 | } else if (!empty($CFG->enablegroupings) and !empty($cm->groupmembersonly) |
2607 | and !has_capability('moodle/site:accessallgroups', $modcontext, $userid)) { |
2608 | if (is_null($modinfo->groups)) { |
2609 | $modinfo->groups = groups_get_user_groups($course->id, $userid); |
2610 | } |
2611 | if (empty($modinfo->groups[$cm->groupingid])) { |
2612 | $cm->uservisible = false; |
2613 | } |
2614 | } |
2615 | |
2616 | if (!isset($modinfo->instances[$cm->modname])) { |
2617 | $modinfo->instances[$cm->modname] = array(); |
2618 | } |
2619 | $modinfo->instances[$cm->modname][$cm->instance] =& $cm; |
2620 | $modinfo->cms[$cm->id] =& $cm; |
2621 | |
2622 | // reconstruct sections |
2623 | if (!isset($modinfo->sections[$cm->sectionnum])) { |
2624 | $modinfo->sections[$cm->sectionnum] = array(); |
2625 | } |
2626 | $modinfo->sections[$cm->sectionnum][] = $cm->id; |
2627 | |
2628 | unset($cm); |
2629 | } |
2630 | |
2631 | unset($cache[$course->id]); // prevent potential reference problems when switching users |
2632 | $cache[$course->id] = $modinfo; |
2633 | |
2634 | // Ensure cache does not use too much RAM |
2635 | if (count($cache) > MAX_MODINFO_CACHE_SIZE) { |
2636 | array_shift($cache); |
2637 | } |
2638 | |
2639 | return $cache[$course->id]; |
2640 | } |
2641 | |
b61efafb |
2642 | /** |
2643 | * Goes through all enrolment records for the courses inside the metacourse and sync with them. |
5e623a33 |
2644 | * |
123545bc |
2645 | * @param mixed $course the metacourse to synch. Either the course object itself, or the courseid. |
d2a9f7cc |
2646 | */ |
1aad4310 |
2647 | function sync_metacourse($course) { |
ae040d4b |
2648 | global $CFG, $DB; |
b61efafb |
2649 | |
123545bc |
2650 | // Check the course is valid. |
1aad4310 |
2651 | if (!is_object($course)) { |
ae040d4b |
2652 | if (!$course = $DB->get_record('course', array('id'=>$course))) { |
1aad4310 |
2653 | return false; // invalid course id |
b61efafb |
2654 | } |
b61efafb |
2655 | } |
5e623a33 |
2656 | |
123545bc |
2657 | // Check that we actually have a metacourse. |
1aad4310 |
2658 | if (empty($course->metacourse)) { |
123545bc |
2659 | return false; |
755c8d58 |
2660 | } |
87671466 |
2661 | |
b3170072 |
2662 | // Get a list of roles that should not be synced. |
4db9bff7 |
2663 | if (!empty($CFG->nonmetacoursesyncroleids)) { |
b3170072 |
2664 | $roleexclusions = 'ra.roleid NOT IN (' . $CFG->nonmetacoursesyncroleids . ') AND'; |
5e623a33 |
2665 | } else { |
b3170072 |
2666 | $roleexclusions = ''; |
2667 | } |
2668 | |
123545bc |
2669 | // Get the context of the metacourse. |
1aad4310 |
2670 | $context = get_context_instance(CONTEXT_COURSE, $course->id); // SITEID can not be a metacourse |
e1ecf0a0 |
2671 | |
123545bc |
2672 | // We do not ever want to unassign the list of metacourse manager, so get a list of them. |
b79da3ac |
2673 | if ($users = get_users_by_capability($context, 'moodle/course:managemetacourse')) { |
1aad4310 |
2674 | $managers = array_keys($users); |
2675 | } else { |
2676 | $managers = array(); |
b61efafb |
2677 | } |
2678 | |
123545bc |
2679 | // Get assignments of a user to a role that exist in a child course, but |
2680 | // not in the meta coure. That is, get a list of the assignments that need to be made. |
ae040d4b |
2681 | if (!$assignments = $DB->get_records_sql(" |
2682 | SELECT ra.id, ra.roleid, ra.userid |
2683 | FROM {role_assignments} ra, {context} con, {course_meta} cm |
2684 | WHERE ra.contextid = con.id AND |
2685 | con.contextlevel = ".CONTEXT_COURSE." AND |
2686 | con.instanceid = cm.child_course AND |
2687 | cm.parent_course = ? AND |
2688 | $roleexclusions |
2689 | NOT EXISTS ( |
2690 | SELECT 1 |
2691 | FROM {role_assignments} ra2 |
2692 | WHERE ra2.userid = ra.userid AND |
2693 | ra2.roleid = ra.roleid AND |
2694 | ra2.contextid = ? |
2695 | )", array($course->id, $context->id))) { |
123545bc |
2696 | $assignments = array(); |
2697 | } |
2698 | |
2699 | // Get assignments of a user to a role that exist in the meta course, but |
2700 | // not in any child courses. That is, get a list of the unassignments that need to be made. |
ae040d4b |
2701 | if (!$unassignments = $DB->get_records_sql(" |
2702 | SELECT ra.id, ra.roleid, ra.userid |
2703 | FROM {role_assignments} ra |
2704 | WHERE ra.contextid = ? AND |
2705 | $roleexclusions |
2706 | NOT EXISTS ( |
2707 | SELECT 1 |
2708 | FROM {role_assignments} ra2, {context} con2, {course_meta} cm |
2709 | WHERE ra2.userid = ra.userid AND |
2710 | ra2.roleid = ra.roleid AND |
2711 | ra2.contextid = con2.id AND |
2712 | con2.contextlevel = " . CONTEXT_COURSE . " AND |
2713 | con2.instanceid = cm.child_course AND |
2714 | cm.parent_course = ? |
2715 | )", array($context->id, $course->id))) { |
123545bc |
2716 | $unassignments = array(); |
2717 | } |
2718 | |
2719 | $success = true; |
2720 | |
2721 | // Make the unassignments, if they are not managers. |
2722 | foreach ($unassignments as $unassignment) { |
2723 | if (!in_array($unassignment->userid, $managers)) { |
2724 | $success = role_unassign($unassignment->roleid, $unassignment->userid, 0, $context->id) && $success; |
1aad4310 |
2725 | } |
755c8d58 |
2726 | } |
e1ecf0a0 |
2727 | |
123545bc |
2728 | // Make the assignments. |
2729 | foreach ($assignments as $assignment) { |
2730 | $success = role_assign($assignment->roleid, $assignment->userid, 0, $context->id) && $success; |
b61efafb |
2731 | } |
755c8d58 |
2732 | |
123545bc |
2733 | return $success; |
5e623a33 |
2734 | |
1aad4310 |
2735 | // TODO: finish timeend and timestart |
2736 | // maybe we could rely on cron job to do the cleaning from time to time |
b61efafb |
2737 | } |
2738 | |
d2a9f7cc |
2739 | /** |
b61efafb |
2740 | * Adds a record to the metacourse table and calls sync_metacoures |
2741 | */ |
2742 | function add_to_metacourse ($metacourseid, $courseid) { |
ae040d4b |
2743 | global $DB; |
d2a9f7cc |
2744 | |
ae040d4b |
2745 | if (!$metacourse = $DB->get_record("course", array("id"=>$metacourseid))) { |
b61efafb |
2746 | return false; |
2747 | } |
d2a9f7cc |
2748 | |
ae040d4b |
2749 | if (!$course = $DB->get_record("course", array("id"=>$courseid))) { |
b61efafb |
2750 | return false; |
2751 | } |
2752 | |
ae040d4b |
2753 | if (!$record = $DB->get_record("course_meta", array("parent_course"=>$metacourseid, "child_course"=>$courseid))) { |
53467aa6 |
2754 | $rec = new object(); |
b61efafb |
2755 | $rec->parent_course = $metacourseid; |
ae040d4b |
2756 | $rec->child_course = $courseid; |
013376de |
2757 | $DB->insert_record('course_meta', $rec); |
b61efafb |
2758 | return sync_metacourse($metacourseid); |
2759 | } |
2760 | return true; |
d2a9f7cc |
2761 | |
b61efafb |
2762 | } |
2763 | |
d2a9f7cc |
2764 | /** |
b61efafb |
2765 | * Removes the record from the metacourse table and calls sync_metacourse |
2766 | */ |
2767 | function remove_from_metacourse($metacourseid, $courseid) { |
ae040d4b |
2768 | global $DB; |
b61efafb |
2769 | |
ae040d4b |
2770 | if ($DB->delete_records('course_meta', array('parent_course'=>$metacourseid, 'child_course'=>$courseid))) { |
b61efafb |
2771 | return sync_metacourse($metacourseid); |
2772 | } |
2773 | return false; |
2774 | } |
2775 | |
2776 | |
7c12949d |
2777 | /** |
2778 | * Determines if a user is currently logged in |
2779 | * |
2780 | * @uses $USER |
bbd3f2c4 |
2781 | * @return bool |
7c12949d |
2782 | */ |
2783 | function isloggedin() { |
2784 | global $USER; |
2785 | |
2786 | return (!empty($USER->id)); |
2787 | } |
2788 | |
2a919fd7 |
2789 | /** |
2790 | * Determines if a user is logged in as real guest user with username 'guest'. |
2791 | * This function is similar to original isguest() in 1.6 and earlier. |
2792 | * Current isguest() is deprecated - do not use it anymore. |
2793 | * |
2794 | * @param $user mixed user object or id, $USER if not specified |
2795 | * @return bool true if user is the real guest user, false if not logged in or other user |
2796 | */ |
2797 | function isguestuser($user=NULL) { |
ae040d4b |
2798 | global $USER, $DB; |
2799 | |
2a919fd7 |
2800 | if ($user === NULL) { |
2801 | $user = $USER; |
2802 | } else if (is_numeric($user)) { |
ae040d4b |
2803 | $user = $DB->get_record('user', array('id'=>$user), 'id, username'); |
2a919fd7 |
2804 | } |
2805 | |
2806 | if (empty($user->id)) { |
2807 | return false; // not logged in, can not be guest |
2808 | } |
2809 | |
2810 | return ($user->username == 'guest'); |
2811 | } |
7c12949d |
2812 | |
7cf1c7bd |
2813 | /** |
830dd6e9 |
2814 | * @deprecated since Moodle 2.0 - use $PAGE->user_is_editing() instead. |
e6260a45 |
2815 | * Determines if the currently logged in user is in editing mode. |
2816 | * Note: originally this function had $userid parameter - it was not usable anyway |
7cf1c7bd |
2817 | * |
0df35335 |
2818 | * @uses $USER, $PAGE |
bbd3f2c4 |
2819 | * @return bool |
7cf1c7bd |
2820 | */ |
0df35335 |
2821 | function isediting() { |
830dd6e9 |
2822 | global $PAGE; |
2823 | debugging('call to deprecated function isediting(). Please use $PAGE->user_is_editing() instead', DEBUG_DEVELOPER); |
2824 | return $PAGE->user_is_editing(); |
2c309dc2 |
2825 | } |
2826 | |
7cf1c7bd |
2827 | /** |
2828 | * Determines if the logged in user is currently moving an activity |
2829 | * |
2830 | * @uses $USER |
c6d15803 |
2831 | * @param int $courseid The id of the course being tested |
bbd3f2c4 |
2832 | * @return bool |
7cf1c7bd |
2833 | */ |
7977cffd |
2834 | function ismoving($courseid) { |
7977cffd |
2835 | global $USER; |
2836 | |
2837 | if (!empty($USER->activitycopy)) { |
2838 | return ($USER->activitycopycourse == $courseid); |
2839 | } |
2840 | return false; |
2841 | } |
2842 | |
7cf1c7bd |
2843 | /** |
2844 | * Given an object containing firstname and lastname |
2845 | * values, this function returns a string with the |
2846 | * full name of the person. |
2847 | * The result may depend on system settings |
2848 | * or language. 'override' will force both names |
361855e6 |
2849 | * to be used even if system settings specify one. |
68fbd8e1 |
2850 | * |
7cf1c7bd |
2851 | * @uses $CFG |
2852 | * @uses $SESSION |
68fbd8e1 |
2853 | * @param object $user A {@link $USER} object to get full name of |
2854 | * @param bool $override If true then the name will be first name followed by last name rather than adhering to fullnamedisplay setting. |
7cf1c7bd |
2855 | */ |
e2cd5065 |
2856 | function fullname($user, $override=false) { |
f374fb10 |
2857 | global $CFG, $SESSION; |
2858 | |
6527c077 |
2859 | if (!isset($user->firstname) and !isset($user->lastname)) { |
2860 | return ''; |
2861 | } |
2862 | |
4c202228 |
2863 | if (!$override) { |
2864 | if (!empty($CFG->forcefirstname)) { |
2865 | $user->firstname = $CFG->forcefirstname; |
2866 | } |
2867 | if (!empty($CFG->forcelastname)) { |
2868 | $user->lastname = $CFG->forcelastname; |
2869 | } |
2870 | } |
2871 | |
f374fb10 |
2872 | if (!empty($SESSION->fullnamedisplay)) { |
2873 | $CFG->fullnamedisplay = $SESSION->fullnamedisplay; |
2874 | } |
e2cd5065 |
2875 | |
775f811a |
2876 | if (!isset($CFG->fullnamedisplay) or $CFG->fullnamedisplay === 'firstname lastname') { |
b0ccd3fb |
2877 | return $user->firstname .' '. $user->lastname; |
b5cbb64d |
2878 | |
2879 | } else if ($CFG->fullnamedisplay == 'lastname firstname') { |
b0ccd3fb |
2880 | return $user->lastname .' '. $user->firstname; |
e2cd5065 |
2881 | |
b5cbb64d |
2882 | } else if ($CFG->fullnamedisplay == 'firstname') { |
2883 | if ($override) { |
2884 | return get_string('fullnamedisplay', '', $user); |
2885 | } else { |
2886 | return $user->firstname; |
2887 | } |
2888 | } |
e2cd5065 |
2889 | |
b5cbb64d |
2890 | return get_string('fullnamedisplay', '', $user); |
e2cd5065 |
2891 | } |
2892 | |
7cf1c7bd |
2893 | /** |
03d820c7 |
2894 | * Returns whether a given authentication plugin exists. |
7cf1c7bd |
2895 | * |
2896 | * @uses $CFG |
03d820c7 |
2897 | * @param string $auth Form of authentication to check for. Defaults to the |
2898 | * global setting in {@link $CFG}. |
2899 | * @return boolean Whether the plugin is available. |
7cf1c7bd |
2900 | */ |
16793340 |
2901 | function exists_auth_plugin($auth) { |
03d820c7 |
2902 | global $CFG; |
5e623a33 |
2903 | |
03d820c7 |
2904 | if (file_exists("{$CFG->dirroot}/auth/$auth/auth.php")) { |
2905 | return is_readable("{$CFG->dirroot}/auth/$auth/auth.php"); |
2906 | } |
2907 | return false; |
2908 | } |
ba7166c3 |
2909 | |
03d820c7 |
2910 | /** |
2911 | * Checks if a given plugin is in the list of enabled authentication plugins. |
5e623a33 |
2912 | * |
03d820c7 |
2913 | * @param string $auth Authentication plugin. |
2914 | * @return boolean Whether the plugin is enabled. |
2915 | */ |
16793340 |
2916 | function is_enabled_auth($auth) { |
16793340 |
2917 | if (empty($auth)) { |
2918 | return false; |
03d820c7 |
2919 | } |
16793340 |
2920 | |
c7b10b5f |
2921 | $enabled = get_enabled_auth_plugins(); |
2922 | |
2923 | return in_array($auth, $enabled); |
03d820c7 |
2924 | } |
2925 | |
2926 | /** |
2927 | * Returns an authentication plugin instance. |
2928 | * |
2929 | * @uses $CFG |
9696bd89 |
2930 | * @param string $auth name of authentication plugin |
03d820c7 |
2931 | * @return object An instance of the required authentication plugin. |
2932 | */ |
9696bd89 |
2933 | function get_auth_plugin($auth) { |
03d820c7 |
2934 | global $CFG; |
5e623a33 |
2935 | |
03d820c7 |
2936 | // check the plugin exists first |
2937 | if (! exists_auth_plugin($auth)) { |
2f137aa1 |
2938 | print_error('authpluginnotfound', 'debug', '', $auth); |
03d820c7 |
2939 | } |
5e623a33 |
2940 | |
03d820c7 |
2941 | // return auth plugin instance |
2942 | require_once "{$CFG->dirroot}/auth/$auth/auth.php"; |
2943 | $class = "auth_plugin_$auth"; |
2944 | return new $class; |
2945 | } |
2946 | |
c7b10b5f |
2947 | /** |
2948 | * Returns array of active auth plugins. |
2949 | * |
2950 | * @param bool $fix fix $CFG->auth if needed |
2951 | * @return array |
2952 | */ |
2953 | function get_enabled_auth_plugins($fix=false) { |
2954 | global $CFG; |
2955 | |
2956 | $default = array('manual', 'nologin'); |
2957 | |
2958 | if (empty($CFG->auth)) { |
2959 | $auths = array(); |
2960 | } else { |
2961 | $auths = explode(',', $CFG->auth); |
2962 | } |
2963 | |
2964 | if ($fix) { |
2965 | $auths = array_unique($auths); |
2966 | foreach($auths as $k=>$authname) { |
2967 | if (!exists_auth_plugin($authname) or in_array($authname, $default)) { |
2968 | unset($auths[$k]); |
2969 | } |
2970 | } |
2971 | $newconfig = implode(',', $auths); |
2972 | if (!isset($CFG->auth) or $newconfig != $CFG->auth) { |
2973 | set_config('auth', $newconfig); |
2974 | } |
2975 | } |
2976 | |
2977 | return (array_merge($default, $auths)); |
2978 | } |
2979 | |
03d820c7 |
2980 | /** |
2981 | * Returns true if an internal authentication method is being used. |
2982 | * if method not specified then, global default is assumed |
2983 | * |
2984 | * @uses $CFG |
2985 | * @param string $auth Form of authentication required |
2986 | * @return bool |
03d820c7 |
2987 | */ |
16793340 |
2988 | function is_internal_auth($auth) { |
03d820c7 |
2989 | $authplugin = get_auth_plugin($auth); // throws error if bad $auth |
2990 | return $authplugin->is_internal(); |
a3f1f815 |
2991 | } |
2992 | |
8c3dba73 |
2993 | /** |
2994 | * Returns an array of user fields |
2995 | * |
c6d15803 |
2996 | * @return array User field/column names |
8c3dba73 |
2997 | */ |
a3f1f815 |
2998 | function get_user_fieldnames() { |
f33e1ed4 |
2999 | global $DB; |
a3f1f815 |
3000 | |
f33e1ed4 |
3001 | $fieldarray = $DB->get_columns('user'); |
3002 | unset($fieldarray['id']); |
3003 | $fieldarray = array_keys($fieldarray); |
a3f1f815 |
3004 | |
3005 | return $fieldarray; |
ba7166c3 |
3006 | } |
f9903ed0 |
3007 | |
7cf1c7bd |
3008 | /** |
3009 | * Creates a bare-bones user record |
3010 | * |
3011 | * @uses $CFG |
7cf1c7bd |
3012 | * @param string $username New user's username to add to record |
3013 | * @param string $password New user's password to add to record |
3014 | * @param string $auth Form of authentication required |
68fbd8e1 |
3015 | * @return object A {@link $USER} object |
7cf1c7bd |
3016 | * @todo Outline auth types and provide code example |
3017 | */ |
f76cfc7a |
3018 | function create_user_record($username, $password, $auth='manual') { |
ae040d4b |
3019 | global $CFG, $DB; |
71f9abf9 |
3020 | |
1e22bc9c |
3021 | //just in case check text case |
3022 | $username = trim(moodle_strtolower($username)); |
71f9abf9 |
3023 | |
03d820c7 |
3024 | $authplugin = get_auth_plugin($auth); |
3025 | |
ae040d4b |
3026 | $newuser = new object(); |
3027 | |
6bc1e5d5 |
3028 | if ($newinfo = $authplugin->get_userinfo($username)) { |
3029 | $newinfo = truncate_userinfo($newinfo); |
3030 | foreach ($newinfo as $key => $value){ |
ae040d4b |
3031 | $newuser->$key = $value; |
e858f9da |
3032 | } |
3033 | } |
f9903ed0 |
3034 | |
85a1d4c9 |
3035 | if (!empty($newuser->email)) { |
3036 | if (email_is_not_allowed($newuser->email)) { |
3037 | unset($newuser->email); |
3038 | } |
3039 | } |
3040 | |
27134b7d |
3041 | if (!isset($newuser->city)) { |
3042 | $newuser->city = ''; |
3043 | } |
3044 | |
f76cfc7a |
3045 | $newuser->auth = $auth; |
faebaf0f |
3046 | $newuser->username = $username; |
5e623a33 |
3047 | |
e51917eb |
3048 | // fix for MDL-8480 |
3049 | // user CFG lang for user if $newuser->lang is empty |
3050 | // or $user->lang is not an installed language |
3051 | $sitelangs = array_keys(get_list_of_languages()); |
3052 | if (empty($newuser->lang) || !in_array($newuser->lang, $sitelangs)) { |
9c6972d6 |
3053 | $newuser->lang = $CFG->lang; |
5e623a33 |
3054 | } |
faebaf0f |
3055 | $newuser->confirmed = 1; |
d96466d2 |
3056 | $newuser->lastip = getremoteaddr(); |
faebaf0f |
3057 | $newuser->timemodified = time(); |
03d820c7 |
3058 | $newuser->mnethostid = $CFG->mnet_localhost_id; |
f9903ed0 |
3059 | |
9c6972d6 |
3060 | $DB->insert_record('user', $newuser); |
3061 | $user = get_complete_user_data('username', $newuser->username); |
3062 | if(!empty($CFG->{'auth_'.$newuser->auth.'_forcechangepassword'})){ |
3063 | set_user_preference('auth_forcepasswordchange', 1, $user->id); |
faebaf0f |
3064 | } |
9c6972d6 |
3065 | update_internal_user_password($user, $password); |
3066 | return $user; |
faebaf0f |
3067 | } |
3068 | |
7cf1c7bd |
3069 | /** |
3070 | * Will update a local user record from an external source |
3071 | * |
3072 | * @uses $CFG |
3073 | * @param string $username New user's username to add to record |
89dcb99d |
3074 | * @return user A {@link $USER} object |
7cf1c7bd |
3075 | */ |
03d820c7 |
3076 | function update_user_record($username, $authplugin) { |
ae040d4b |
3077 | global $DB; |
3078 | |
6bc1e5d5 |
3079 | $username = trim(moodle_strtolower($username)); /// just in case check text case |
3080 | |
ae040d4b |
3081 | $oldinfo = $DB->get_record('user', array('username'=>$username), 'username, auth'); |
6bc1e5d5 |
3082 | $userauth = get_auth_plugin($oldinfo->auth); |
3083 | |
3084 | if ($newinfo = $userauth->get_userinfo($username)) { |
3085 | $newinfo = truncate_userinfo($newinfo); |
3086 | foreach ($newinfo as $key => $value){ |
5261baf1 |
3087 | if ($key === 'username') { |
3088 | // 'username' is not a mapped updateable/lockable field, so skip it. |
3089 | continue; |
3090 | } |
6ceb0cd0 |
3091 | $confval = $userauth->config->{'field_updatelocal_' . $key}; |
3092 | $lockval = $userauth->config->{'field_lock_' . $key}; |
3093 | if (empty($confval) || empty($lockval)) { |
3094 | continue; |
3095 | } |
3096 | if ($confval === 'onlogin') { |
6ceb0cd0 |
3097 | // MDL-4207 Don't overwrite modified user profile values with |
3098 | // empty LDAP values when 'unlocked if empty' is set. The purpose |
3099 | // of the setting 'unlocked if empty' is to allow the user to fill |
3100 | // in a value for the selected field _if LDAP is giving |
3101 | // nothing_ for this field. Thus it makes sense to let this value |
3102 | // stand in until LDAP is giving a value for this field. |
3103 | if (!(empty($value) && $lockval === 'unlockedifempty')) { |
8f0632f0 |
3104 | $DB->set_field('user', $key, $value, array('username'=>$username)); |
6ceb0cd0 |
3105 | } |
d35757eb |
3106 | } |
3107 | } |
3108 | } |
6bc1e5d5 |
3109 | |
7c12949d |
3110 | return get_complete_user_data('username', $username); |
d35757eb |
3111 | } |
0609562b |
3112 | |
be544ec3 |
3113 | /** |
38fb8190 |
3114 | * will truncate userinfo as it comes from auth_get_userinfo (from external auth) |
be544ec3 |
3115 | * which may have large fields |
3116 | */ |
b36a8fc4 |
3117 | function truncate_userinfo($info) { |
b36a8fc4 |
3118 | // define the limits |
3119 | $limit = array( |
3120 | 'username' => 100, |
8b9cfac4 |
3121 | 'idnumber' => 255, |
8bcd295c |
3122 | 'firstname' => 100, |
3123 | 'lastname' => 100, |
b36a8fc4 |
3124 | 'email' => 100, |
3125 | 'icq' => 15, |
3126 | 'phone1' => 20, |
3127 | 'phone2' => 20, |
3128 | 'institution' => 40, |
3129 | 'department' => 30, |
3130 | 'address' => 70, |
3131 | 'city' => 20, |
3132 | 'country' => 2, |
3133 | 'url' => 255, |
3134 | ); |
361855e6 |
3135 | |
b36a8fc4 |
3136 | // apply where needed |
3137 | foreach (array_keys($info) as $key) { |
3138 | if (!empty($limit[$key])) { |
adfc03f9 |
3139 | $info[$key] = trim(substr($info[$key],0, $limit[$key])); |
361855e6 |
3140 | } |
b36a8fc4 |
3141 | } |
361855e6 |
3142 | |
b36a8fc4 |
3143 | return $info; |
90afcf32 |
3144 | } |
3145 | |
3146 | /** |
3147 | * Marks user deleted in internal user database and notifies the auth plugin. |
3148 | * Also unenrols user from all roles and does other cleanup. |
3149 | * @param object $user Userobject before delete (without system magic quotes) |
3150 | * @return boolean success |
3151 | */ |
3152 | function delete_user($user) { |
ae040d4b |
3153 | global $CFG, $DB; |
90afcf32 |
3154 | require_once($CFG->libdir.'/grouplib.php'); |
ece966f0 |
3155 | require_once($CFG->libdir.'/gradelib.php'); |
6bdf4c99 |
3156 | require_once($CFG->dirroot.'/message/lib.php'); |
90afcf32 |
3157 | |
9c6972d6 |
3158 | // TODO: decide if this transaction is really needed |
ae040d4b |
3159 | $DB->begin_sql(); |
90afcf32 |
3160 | |
9c6972d6 |
3161 | try { |
3162 | // delete all grades - backup is kept in grade_grades_history table |
3163 | if ($grades = grade_grade::fetch_all(array('userid'=>$user->id))) { |
3164 | foreach ($grades as $grade) { |
3165 | $grade->delete('userdelete'); |
3166 | } |
90afcf32 |
3167 | } |
90afcf32 |
3168 | |
6bdf4c99 |
3169 | //move unread messages from this user to read |
3170 | message_move_userfrom_unread2read($user->id); |
3171 | |
9c6972d6 |
3172 | // remove from all groups |
3173 | $DB->delete_records('groups_members', array('userid'=>$user->id)); |
90afcf32 |
3174 | |
9c6972d6 |
3175 | // unenrol from all roles in all contexts |
3176 | role_unassign(0, $user->id); // this might be slow but it is really needed - modules might do some extra cleanup! |
90afcf32 |
3177 | |
9c6972d6 |
3178 | // now do a final accesslib cleanup - removes all role assingments in user context and context itself |
3179 | delete_context(CONTEXT_USER, $user->id); |
90afcf32 |
3180 | |
9c6972d6 |
3181 | require_once($CFG->dirroot.'/tag/lib.php'); |
3182 | tag_set('user', $user->id, array()); |
13b31d6f |
3183 | |
9c6972d6 |
3184 | // workaround for bulk deletes of users with the same email address |
3185 | $delname = "$user->email.".time(); |
3186 | while ($DB->record_exists('user', array('username'=>$delname))) { // no need to use mnethostid here |
3187 | $delname++; |
3188 | } |
3189 | |
3190 | // mark internal user record as "deleted" |
3191 | $updateuser = new object(); |
3192 | $updateuser->id = $user->id; |
3193 | $updateuser->deleted = 1; |
3194 | $updateuser->username = $delname; // Remember it just in case |
3195 | $updateuser->email = ''; // Clear this field to free it up |
3196 | $updateuser->idnumber = ''; // Clear this field to free it up |
3197 | $updateuser->timemodified = time(); |
6d11d0ee |
3198 | |
9c6972d6 |
3199 | $DB->update_record('user', $updateuser); |
90afcf32 |
3200 | |
ae040d4b |
3201 | $DB->commi |