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