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