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