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