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