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