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