· 9 years ago · Dec 01, 2016, 05:48 AM
1<?php
2// This file is part of Moodle - http://moodle.org/
3//
4// Moodle is free software: you can redistribute it and/or modify
5// it under the terms of the GNU General Public License as published by
6// the Free Software Foundation, either version 3 of the License, or
7// (at your option) any later version.
8//
9// Moodle is distributed in the hope that it will be useful,
10// but WITHOUT ANY WARRANTY; without even the implied warranty of
11// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12// GNU General Public License for more details.
13//
14// You should have received a copy of the GNU General Public License
15// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
16
17/**
18 * moodlelib.php - Moodle main library
19 *
20 * Main library file of miscellaneous general-purpose Moodle functions.
21 * Other main libraries:
22 * - weblib.php - functions that produce web output
23 * - datalib.php - functions that access the database
24 *
25 * @package core
26 * @subpackage lib
27 * @copyright 1999 onwards Martin Dougiamas http://dougiamas.com
28 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
29 */
30
31defined('MOODLE_INTERNAL') || die();
32
33// CONSTANTS (Encased in phpdoc proper comments).
34
35// Date and time constants.
36/**
37 * Time constant - the number of seconds in a year
38 */
39define('YEARSECS', 31536000);
40
41/**
42 * Time constant - the number of seconds in a week
43 */
44define('WEEKSECS', 604800);
45
46/**
47 * Time constant - the number of seconds in a day
48 */
49define('DAYSECS', 86400);
50
51/**
52 * Time constant - the number of seconds in an hour
53 */
54define('HOURSECS', 3600);
55
56/**
57 * Time constant - the number of seconds in a minute
58 */
59define('MINSECS', 60);
60
61/**
62 * Time constant - the number of minutes in a day
63 */
64define('DAYMINS', 1440);
65
66/**
67 * Time constant - the number of minutes in an hour
68 */
69define('HOURMINS', 60);
70
71// Parameter constants - every call to optional_param(), required_param()
72// or clean_param() should have a specified type of parameter.
73
74/**
75 * PARAM_ALPHA - contains only english ascii letters a-zA-Z.
76 */
77define('PARAM_ALPHA', 'alpha');
78
79/**
80 * PARAM_ALPHAEXT the same contents as PARAM_ALPHA plus the chars in quotes: "_-" allowed
81 * NOTE: originally this allowed "/" too, please use PARAM_SAFEPATH if "/" needed
82 */
83define('PARAM_ALPHAEXT', 'alphaext');
84
85/**
86 * PARAM_ALPHANUM - expected numbers and letters only.
87 */
88define('PARAM_ALPHANUM', 'alphanum');
89
90/**
91 * PARAM_ALPHANUMEXT - expected numbers, letters only and _-.
92 */
93define('PARAM_ALPHANUMEXT', 'alphanumext');
94
95/**
96 * PARAM_AUTH - actually checks to make sure the string is a valid auth plugin
97 */
98define('PARAM_AUTH', 'auth');
99
100/**
101 * PARAM_BASE64 - Base 64 encoded format
102 */
103define('PARAM_BASE64', 'base64');
104
105/**
106 * PARAM_BOOL - converts input into 0 or 1, use for switches in forms and urls.
107 */
108define('PARAM_BOOL', 'bool');
109
110/**
111 * PARAM_CAPABILITY - A capability name, like 'moodle/role:manage'. Actually
112 * checked against the list of capabilities in the database.
113 */
114define('PARAM_CAPABILITY', 'capability');
115
116/**
117 * PARAM_CLEANHTML - cleans submitted HTML code. Note that you almost never want
118 * to use this. The normal mode of operation is to use PARAM_RAW when recieving
119 * the input (required/optional_param or formslib) and then sanitse the HTML
120 * using format_text on output. This is for the rare cases when you want to
121 * sanitise the HTML on input. This cleaning may also fix xhtml strictness.
122 */
123define('PARAM_CLEANHTML', 'cleanhtml');
124
125/**
126 * PARAM_EMAIL - an email address following the RFC
127 */
128define('PARAM_EMAIL', 'email');
129
130/**
131 * PARAM_FILE - safe file name, all dangerous chars are stripped, protects against XSS, SQL injections and directory traversals
132 */
133define('PARAM_FILE', 'file');
134
135/**
136 * PARAM_FLOAT - a real/floating point number.
137 *
138 * Note that you should not use PARAM_FLOAT for numbers typed in by the user.
139 * It does not work for languages that use , as a decimal separator.
140 * Instead, do something like
141 * $rawvalue = required_param('name', PARAM_RAW);
142 * // ... other code including require_login, which sets current lang ...
143 * $realvalue = unformat_float($rawvalue);
144 * // ... then use $realvalue
145 */
146define('PARAM_FLOAT', 'float');
147
148/**
149 * PARAM_HOST - expected fully qualified domain name (FQDN) or an IPv4 dotted quad (IP address)
150 */
151define('PARAM_HOST', 'host');
152
153/**
154 * PARAM_INT - integers only, use when expecting only numbers.
155 */
156define('PARAM_INT', 'int');
157
158/**
159 * PARAM_LANG - checks to see if the string is a valid installed language in the current site.
160 */
161define('PARAM_LANG', 'lang');
162
163/**
164 * PARAM_LOCALURL - expected properly formatted URL as well as one that refers to the local server itself. (NOT orthogonal to the
165 * others! Implies PARAM_URL!)
166 */
167define('PARAM_LOCALURL', 'localurl');
168
169/**
170 * PARAM_NOTAGS - all html tags are stripped from the text. Do not abuse this type.
171 */
172define('PARAM_NOTAGS', 'notags');
173
174/**
175 * PARAM_PATH - safe relative path name, all dangerous chars are stripped, protects against XSS, SQL injections and directory
176 * traversals note: the leading slash is not removed, window drive letter is not allowed
177 */
178define('PARAM_PATH', 'path');
179
180/**
181 * PARAM_PEM - Privacy Enhanced Mail format
182 */
183define('PARAM_PEM', 'pem');
184
185/**
186 * PARAM_PERMISSION - A permission, one of CAP_INHERIT, CAP_ALLOW, CAP_PREVENT or CAP_PROHIBIT.
187 */
188define('PARAM_PERMISSION', 'permission');
189
190/**
191 * PARAM_RAW specifies a parameter that is not cleaned/processed in any way except the discarding of the invalid utf-8 characters
192 */
193define('PARAM_RAW', 'raw');
194
195/**
196 * PARAM_RAW_TRIMMED like PARAM_RAW but leading and trailing whitespace is stripped.
197 */
198define('PARAM_RAW_TRIMMED', 'raw_trimmed');
199
200/**
201 * PARAM_SAFEDIR - safe directory name, suitable for include() and require()
202 */
203define('PARAM_SAFEDIR', 'safedir');
204
205/**
206 * PARAM_SAFEPATH - several PARAM_SAFEDIR joined by "/", suitable for include() and require(), plugin paths, etc.
207 */
208define('PARAM_SAFEPATH', 'safepath');
209
210/**
211 * PARAM_SEQUENCE - expects a sequence of numbers like 8 to 1,5,6,4,6,8,9. Numbers and comma only.
212 */
213define('PARAM_SEQUENCE', 'sequence');
214
215/**
216 * PARAM_TAG - one tag (interests, blogs, etc.) - mostly international characters and space, <> not supported
217 */
218define('PARAM_TAG', 'tag');
219
220/**
221 * PARAM_TAGLIST - list of tags separated by commas (interests, blogs, etc.)
222 */
223define('PARAM_TAGLIST', 'taglist');
224
225/**
226 * PARAM_TEXT - general plain text compatible with multilang filter, no other html tags. Please note '<', or '>' are allowed here.
227 */
228define('PARAM_TEXT', 'text');
229
230/**
231 * PARAM_THEME - Checks to see if the string is a valid theme name in the current site
232 */
233define('PARAM_THEME', 'theme');
234
235/**
236 * PARAM_URL - expected properly formatted URL. Please note that domain part is required, http://localhost/ is not accepted but
237 * http://localhost.localdomain/ is ok.
238 */
239define('PARAM_URL', 'url');
240
241/**
242 * PARAM_USERNAME - Clean username to only contains allowed characters. This is to be used ONLY when manually creating user
243 * accounts, do NOT use when syncing with external systems!!
244 */
245define('PARAM_USERNAME', 'username');
246
247/**
248 * PARAM_STRINGID - used to check if the given string is valid string identifier for get_string()
249 */
250define('PARAM_STRINGID', 'stringid');
251
252// DEPRECATED PARAM TYPES OR ALIASES - DO NOT USE FOR NEW CODE.
253/**
254 * PARAM_CLEAN - obsoleted, please use a more specific type of parameter.
255 * It was one of the first types, that is why it is abused so much ;-)
256 * @deprecated since 2.0
257 */
258define('PARAM_CLEAN', 'clean');
259
260/**
261 * PARAM_INTEGER - deprecated alias for PARAM_INT
262 * @deprecated since 2.0
263 */
264define('PARAM_INTEGER', 'int');
265
266/**
267 * PARAM_NUMBER - deprecated alias of PARAM_FLOAT
268 * @deprecated since 2.0
269 */
270define('PARAM_NUMBER', 'float');
271
272/**
273 * PARAM_ACTION - deprecated alias for PARAM_ALPHANUMEXT, use for various actions in forms and urls
274 * NOTE: originally alias for PARAM_APLHA
275 * @deprecated since 2.0
276 */
277define('PARAM_ACTION', 'alphanumext');
278
279/**
280 * PARAM_FORMAT - deprecated alias for PARAM_ALPHANUMEXT, use for names of plugins, formats, etc.
281 * NOTE: originally alias for PARAM_APLHA
282 * @deprecated since 2.0
283 */
284define('PARAM_FORMAT', 'alphanumext');
285
286/**
287 * PARAM_MULTILANG - deprecated alias of PARAM_TEXT.
288 * @deprecated since 2.0
289 */
290define('PARAM_MULTILANG', 'text');
291
292/**
293 * PARAM_TIMEZONE - expected timezone. Timezone can be int +-(0-13) or float +-(0.5-12.5) or
294 * string separated by '/' and can have '-' &/ '_' (eg. America/North_Dakota/New_Salem
295 * America/Port-au-Prince)
296 */
297define('PARAM_TIMEZONE', 'timezone');
298
299/**
300 * PARAM_CLEANFILE - deprecated alias of PARAM_FILE; originally was removing regional chars too
301 */
302define('PARAM_CLEANFILE', 'file');
303
304/**
305 * PARAM_COMPONENT is used for full component names (aka frankenstyle) such as 'mod_forum', 'core_rating', 'auth_ldap'.
306 * Short legacy subsystem names and module names are accepted too ex: 'forum', 'rating', 'user'.
307 * Only lowercase ascii letters, numbers and underscores are allowed, it has to start with a letter.
308 * NOTE: numbers and underscores are strongly discouraged in plugin names!
309 */
310define('PARAM_COMPONENT', 'component');
311
312/**
313 * PARAM_AREA is a name of area used when addressing files, comments, ratings, etc.
314 * It is usually used together with context id and component.
315 * Only lowercase ascii letters, numbers and underscores are allowed, it has to start with a letter.
316 */
317define('PARAM_AREA', 'area');
318
319/**
320 * PARAM_PLUGIN is used for plugin names such as 'forum', 'glossary', 'ldap', 'radius', 'paypal', 'completionstatus'.
321 * Only lowercase ascii letters, numbers and underscores are allowed, it has to start with a letter.
322 * NOTE: numbers and underscores are strongly discouraged in plugin names! Underscores are forbidden in module names.
323 */
324define('PARAM_PLUGIN', 'plugin');
325
326
327// Web Services.
328
329/**
330 * VALUE_REQUIRED - if the parameter is not supplied, there is an error
331 */
332define('VALUE_REQUIRED', 1);
333
334/**
335 * VALUE_OPTIONAL - if the parameter is not supplied, then the param has no value
336 */
337define('VALUE_OPTIONAL', 2);
338
339/**
340 * VALUE_DEFAULT - if the parameter is not supplied, then the default value is used
341 */
342define('VALUE_DEFAULT', 0);
343
344/**
345 * NULL_NOT_ALLOWED - the parameter can not be set to null in the database
346 */
347define('NULL_NOT_ALLOWED', false);
348
349/**
350 * NULL_ALLOWED - the parameter can be set to null in the database
351 */
352define('NULL_ALLOWED', true);
353
354// Page types.
355
356/**
357 * PAGE_COURSE_VIEW is a definition of a page type. For more information on the page class see moodle/lib/pagelib.php.
358 */
359define('PAGE_COURSE_VIEW', 'course-view');
360
361/** Get remote addr constant */
362define('GETREMOTEADDR_SKIP_HTTP_CLIENT_IP', '1');
363/** Get remote addr constant */
364define('GETREMOTEADDR_SKIP_HTTP_X_FORWARDED_FOR', '2');
365
366// Blog access level constant declaration.
367define ('BLOG_USER_LEVEL', 1);
368define ('BLOG_GROUP_LEVEL', 2);
369define ('BLOG_COURSE_LEVEL', 3);
370define ('BLOG_SITE_LEVEL', 4);
371define ('BLOG_GLOBAL_LEVEL', 5);
372
373
374// Tag constants.
375/**
376 * To prevent problems with multibytes strings,Flag updating in nav not working on the review page. this should not exceed the
377 * length of "varchar(255) / 3 (bytes / utf-8 character) = 85".
378 * TODO: this is not correct, varchar(255) are 255 unicode chars ;-)
379 *
380 * @todo define(TAG_MAX_LENGTH) this is not correct, varchar(255) are 255 unicode chars ;-)
381 */
382define('TAG_MAX_LENGTH', 50);
383
384// Password policy constants.
385define ('PASSWORD_LOWER', 'abcdefghijklmnopqrstuvwxyz');
386define ('PASSWORD_UPPER', 'ABCDEFGHIJKLMNOPQRSTUVWXYZ');
387define ('PASSWORD_DIGITS', '0123456789');
388define ('PASSWORD_NONALPHANUM', '.,;:!?_-+/*@#&$');
389
390// Feature constants.
391// Used for plugin_supports() to report features that are, or are not, supported by a module.
392
393/** True if module can provide a grade */
394define('FEATURE_GRADE_HAS_GRADE', 'grade_has_grade');
395/** True if module supports outcomes */
396define('FEATURE_GRADE_OUTCOMES', 'outcomes');
397/** True if module supports advanced grading methods */
398define('FEATURE_ADVANCED_GRADING', 'grade_advanced_grading');
399/** True if module controls the grade visibility over the gradebook */
400define('FEATURE_CONTROLS_GRADE_VISIBILITY', 'controlsgradevisbility');
401/** True if module supports plagiarism plugins */
402define('FEATURE_PLAGIARISM', 'plagiarism');
403
404/** True if module has code to track whether somebody viewed it */
405define('FEATURE_COMPLETION_TRACKS_VIEWS', 'completion_tracks_views');
406/** True if module has custom completion rules */
407define('FEATURE_COMPLETION_HAS_RULES', 'completion_has_rules');
408
409/** True if module has no 'view' page (like label) */
410define('FEATURE_NO_VIEW_LINK', 'viewlink');
411/** True if module supports outcomes */
412define('FEATURE_IDNUMBER', 'idnumber');
413/** True if module supports groups */
414define('FEATURE_GROUPS', 'groups');
415/** True if module supports groupings */
416define('FEATURE_GROUPINGS', 'groupings');
417/**
418 * True if module supports groupmembersonly (which no longer exists)
419 * @deprecated Since Moodle 2.8
420 */
421define('FEATURE_GROUPMEMBERSONLY', 'groupmembersonly');
422
423/** Type of module */
424define('FEATURE_MOD_ARCHETYPE', 'mod_archetype');
425/** True if module supports intro editor */
426define('FEATURE_MOD_INTRO', 'mod_intro');
427/** True if module has default completion */
428define('FEATURE_MODEDIT_DEFAULT_COMPLETION', 'modedit_default_completion');
429
430define('FEATURE_COMMENT', 'comment');
431
432define('FEATURE_RATE', 'rate');
433/** True if module supports backup/restore of moodle2 format */
434define('FEATURE_BACKUP_MOODLE2', 'backup_moodle2');
435
436/** True if module can show description on course main page */
437define('FEATURE_SHOW_DESCRIPTION', 'showdescription');
438
439/** True if module uses the question bank */
440define('FEATURE_USES_QUESTIONS', 'usesquestions');
441
442/** Unspecified module archetype */
443define('MOD_ARCHETYPE_OTHER', 0);
444/** Resource-like type module */
445define('MOD_ARCHETYPE_RESOURCE', 1);
446/** Assignment module archetype */
447define('MOD_ARCHETYPE_ASSIGNMENT', 2);
448/** System (not user-addable) module archetype */
449define('MOD_ARCHETYPE_SYSTEM', 3);
450
451/** Return this from modname_get_types callback to use default display in activity chooser */
452define('MOD_SUBTYPE_NO_CHILDREN', 'modsubtypenochildren');
453
454/**
455 * Security token used for allowing access
456 * from external application such as web services.
457 * Scripts do not use any session, performance is relatively
458 * low because we need to load access info in each request.
459 * Scripts are executed in parallel.
460 */
461define('EXTERNAL_TOKEN_PERMANENT', 0);
462
463/**
464 * Security token used for allowing access
465 * of embedded applications, the code is executed in the
466 * active user session. Token is invalidated after user logs out.
467 * Scripts are executed serially - normal session locking is used.
468 */
469define('EXTERNAL_TOKEN_EMBEDDED', 1);
470
471/**
472 * The home page should be the site home
473 */
474define('HOMEPAGE_SITE', 0);
475/**
476 * The home page should be the users my page
477 */
478define('HOMEPAGE_MY', 1);
479/**
480 * The home page can be chosen by the user
481 */
482define('HOMEPAGE_USER', 2);
483
484/**
485 * Hub directory url (should be moodle.org)
486 */
487define('HUB_HUBDIRECTORYURL', "http://hubdirectory.moodle.org");
488
489
490/**
491 * Moodle.org url (should be moodle.org)
492 */
493define('HUB_MOODLEORGHUBURL', "http://hub.moodle.org");
494
495/**
496 * Moodle mobile app service name
497 */
498define('MOODLE_OFFICIAL_MOBILE_SERVICE', 'moodle_mobile_app');
499
500/**
501 * Indicates the user has the capabilities required to ignore activity and course file size restrictions
502 */
503define('USER_CAN_IGNORE_FILE_SIZE_LIMITS', -1);
504
505/**
506 * Course display settings: display all sections on one page.
507 */
508define('COURSE_DISPLAY_SINGLEPAGE', 0);
509/**
510 * Course display settings: split pages into a page per section.
511 */
512define('COURSE_DISPLAY_MULTIPAGE', 1);
513
514/**
515 * Authentication constant: String used in password field when password is not stored.
516 */
517define('AUTH_PASSWORD_NOT_CACHED', 'not cached');
518
519// PARAMETER HANDLING.
520
521/**
522 * Returns a particular value for the named variable, taken from
523 * POST or GET. If the parameter doesn't exist then an error is
524 * thrown because we require this variable.
525 *
526 * This function should be used to initialise all required values
527 * in a script that are based on parameters. Usually it will be
528 * used like this:
529 * $id = required_param('id', PARAM_INT);
530 *
531 * Please note the $type parameter is now required and the value can not be array.
532 *
533 * @param string $parname the name of the page parameter we want
534 * @param string $type expected type of parameter
535 * @return mixed
536 * @throws coding_exception
537 */
538function required_param($parname, $type) {
539 if (func_num_args() != 2 or empty($parname) or empty($type)) {
540 throw new coding_exception('required_param() requires $parname and $type to be specified (parameter: '.$parname.')');
541 }
542 // POST has precedence.
543 if (isset($_POST[$parname])) {
544 $param = $_POST[$parname];
545 } else if (isset($_GET[$parname])) {
546 $param = $_GET[$parname];
547 } else {
548 print_error('missingparam', '', '', $parname);
549 }
550
551 if (is_array($param)) {
552 debugging('Invalid array parameter detected in required_param(): '.$parname);
553 // TODO: switch to fatal error in Moodle 2.3.
554 return required_param_array($parname, $type);
555 }
556
557 return clean_param($param, $type);
558}
559
560/**
561 * Returns a particular array value for the named variable, taken from
562 * POST or GET. If the parameter doesn't exist then an error is
563 * thrown because we require this variable.
564 *
565 * This function should be used to initialise all required values
566 * in a script that are based on parameters. Usually it will be
567 * used like this:
568 * $ids = required_param_array('ids', PARAM_INT);
569 *
570 * Note: arrays of arrays are not supported, only alphanumeric keys with _ and - are supported
571 *
572 * @param string $parname the name of the page parameter we want
573 * @param string $type expected type of parameter
574 * @return array
575 * @throws coding_exception
576 */
577function required_param_array($parname, $type) {
578 if (func_num_args() != 2 or empty($parname) or empty($type)) {
579 throw new coding_exception('required_param_array() requires $parname and $type to be specified (parameter: '.$parname.')');
580 }
581 // POST has precedence.
582 if (isset($_POST[$parname])) {
583 $param = $_POST[$parname];
584 } else if (isset($_GET[$parname])) {
585 $param = $_GET[$parname];
586 } else {
587 print_error('missingparam', '', '', $parname);
588 }
589 if (!is_array($param)) {
590 print_error('missingparam', '', '', $parname);
591 }
592
593 $result = array();
594 foreach ($param as $key => $value) {
595 if (!preg_match('/^[a-z0-9_-]+$/i', $key)) {
596 debugging('Invalid key name in required_param_array() detected: '.$key.', parameter: '.$parname);
597 continue;
598 }
599 $result[$key] = clean_param($value, $type);
600 }
601
602 return $result;
603}
604
605/**
606 * Returns a particular value for the named variable, taken from
607 * POST or GET, otherwise returning a given default.
608 *
609 * This function should be used to initialise all optional values
610 * in a script that are based on parameters. Usually it will be
611 * used like this:
612 * $name = optional_param('name', 'Fred', PARAM_TEXT);
613 *
614 * Please note the $type parameter is now required and the value can not be array.
615 *
616 * @param string $parname the name of the page parameter we want
617 * @param mixed $default the default value to return if nothing is found
618 * @param string $type expected type of parameter
619 * @return mixed
620 * @throws coding_exception
621 */
622function optional_param($parname, $default, $type) {
623 if (func_num_args() != 3 or empty($parname) or empty($type)) {
624 throw new coding_exception('optional_param requires $parname, $default + $type to be specified (parameter: '.$parname.')');
625 }
626 if (!isset($default)) {
627 $default = null;
628 }
629
630 // POST has precedence.
631 if (isset($_POST[$parname])) {
632 $param = $_POST[$parname];
633 } else if (isset($_GET[$parname])) {
634 $param = $_GET[$parname];
635 } else {
636 return $default;
637 }
638
639 if (is_array($param)) {
640 debugging('Invalid array parameter detected in required_param(): '.$parname);
641 // TODO: switch to $default in Moodle 2.3.
642 return optional_param_array($parname, $default, $type);
643 }
644
645 return clean_param($param, $type);
646}
647
648/**
649 * Returns a particular array value for the named variable, taken from
650 * POST or GET, otherwise returning a given default.
651 *
652 * This function should be used to initialise all optional values
653 * in a script that are based on parameters. Usually it will be
654 * used like this:
655 * $ids = optional_param('id', array(), PARAM_INT);
656 *
657 * Note: arrays of arrays are not supported, only alphanumeric keys with _ and - are supported
658 *
659 * @param string $parname the name of the page parameter we want
660 * @param mixed $default the default value to return if nothing is found
661 * @param string $type expected type of parameter
662 * @return array
663 * @throws coding_exception
664 */
665function optional_param_array($parname, $default, $type) {
666 if (func_num_args() != 3 or empty($parname) or empty($type)) {
667 throw new coding_exception('optional_param_array requires $parname, $default + $type to be specified (parameter: '.$parname.')');
668 }
669
670 // POST has precedence.
671 if (isset($_POST[$parname])) {
672 $param = $_POST[$parname];
673 } else if (isset($_GET[$parname])) {
674 $param = $_GET[$parname];
675 } else {
676 return $default;
677 }
678 if (!is_array($param)) {
679 debugging('optional_param_array() expects array parameters only: '.$parname);
680 return $default;
681 }
682
683 $result = array();
684 foreach ($param as $key => $value) {
685 if (!preg_match('/^[a-z0-9_-]+$/i', $key)) {
686 debugging('Invalid key name in optional_param_array() detected: '.$key.', parameter: '.$parname);
687 continue;
688 }
689 $result[$key] = clean_param($value, $type);
690 }
691
692 return $result;
693}
694
695/**
696 * Strict validation of parameter values, the values are only converted
697 * to requested PHP type. Internally it is using clean_param, the values
698 * before and after cleaning must be equal - otherwise
699 * an invalid_parameter_exception is thrown.
700 * Objects and classes are not accepted.
701 *
702 * @param mixed $param
703 * @param string $type PARAM_ constant
704 * @param bool $allownull are nulls valid value?
705 * @param string $debuginfo optional debug information
706 * @return mixed the $param value converted to PHP type
707 * @throws invalid_parameter_exception if $param is not of given type
708 */
709function validate_param($param, $type, $allownull=NULL_NOT_ALLOWED, $debuginfo='') {
710 if (is_null($param)) {
711 if ($allownull == NULL_ALLOWED) {
712 return null;
713 } else {
714 throw new invalid_parameter_exception($debuginfo);
715 }
716 }
717 if (is_array($param) or is_object($param)) {
718 throw new invalid_parameter_exception($debuginfo);
719 }
720
721 $cleaned = clean_param($param, $type);
722
723 if ($type == PARAM_FLOAT) {
724 // Do not detect precision loss here.
725 if (is_float($param) or is_int($param)) {
726 // These always fit.
727 } else if (!is_numeric($param) or !preg_match('/^[\+-]?[0-9]*\.?[0-9]*(e[-+]?[0-9]+)?$/i', (string)$param)) {
728 throw new invalid_parameter_exception($debuginfo);
729 }
730 } else if ((string)$param !== (string)$cleaned) {
731 // Conversion to string is usually lossless.
732 throw new invalid_parameter_exception($debuginfo);
733 }
734
735 return $cleaned;
736}
737
738/**
739 * Makes sure array contains only the allowed types, this function does not validate array key names!
740 *
741 * <code>
742 * $options = clean_param($options, PARAM_INT);
743 * </code>
744 *
745 * @param array $param the variable array we are cleaning
746 * @param string $type expected format of param after cleaning.
747 * @param bool $recursive clean recursive arrays
748 * @return array
749 * @throws coding_exception
750 */
751function clean_param_array(array $param = null, $type, $recursive = false) {
752 // Convert null to empty array.
753 $param = (array)$param;
754 foreach ($param as $key => $value) {
755 if (is_array($value)) {
756 if ($recursive) {
757 $param[$key] = clean_param_array($value, $type, true);
758 } else {
759 throw new coding_exception('clean_param_array can not process multidimensional arrays when $recursive is false.');
760 }
761 } else {
762 $param[$key] = clean_param($value, $type);
763 }
764 }
765 return $param;
766}
767
768/**
769 * Used by {@link optional_param()} and {@link required_param()} to
770 * clean the variables and/or cast to specific types, based on
771 * an options field.
772 * <code>
773 * $course->format = clean_param($course->format, PARAM_ALPHA);
774 * $selectedgradeitem = clean_param($selectedgradeitem, PARAM_INT);
775 * </code>
776 *
777 * @param mixed $param the variable we are cleaning
778 * @param string $type expected format of param after cleaning.
779 * @return mixed
780 * @throws coding_exception
781 */
782function clean_param($param, $type) {
783 global $CFG;
784
785 if (is_array($param)) {
786 throw new coding_exception('clean_param() can not process arrays, please use clean_param_array() instead.');
787 } else if (is_object($param)) {
788 if (method_exists($param, '__toString')) {
789 $param = $param->__toString();
790 } else {
791 throw new coding_exception('clean_param() can not process objects, please use clean_param_array() instead.');
792 }
793 }
794
795 switch ($type) {
796 case PARAM_RAW:
797 // No cleaning at all.
798 $param = fix_utf8($param);
799 return $param;
800
801 case PARAM_RAW_TRIMMED:
802 // No cleaning, but strip leading and trailing whitespace.
803 $param = fix_utf8($param);
804 return trim($param);
805
806 case PARAM_CLEAN:
807 // General HTML cleaning, try to use more specific type if possible this is deprecated!
808 // Please use more specific type instead.
809 if (is_numeric($param)) {
810 return $param;
811 }
812 $param = fix_utf8($param);
813 // Sweep for scripts, etc.
814 return clean_text($param);
815
816 case PARAM_CLEANHTML:
817 // Clean html fragment.
818 $param = fix_utf8($param);
819 // Sweep for scripts, etc.
820 $param = clean_text($param, FORMAT_HTML);
821 return trim($param);
822
823 case PARAM_INT:
824 // Convert to integer.
825 return (int)$param;
826
827 case PARAM_FLOAT:
828 // Convert to float.
829 return (float)$param;
830
831 case PARAM_ALPHA:
832 // Remove everything not `a-z`.
833 return preg_replace('/[^a-zA-Z]/i', '', $param);
834
835 case PARAM_ALPHAEXT:
836 // Remove everything not `a-zA-Z_-` (originally allowed "/" too).
837 return preg_replace('/[^a-zA-Z_-]/i', '', $param);
838
839 case PARAM_ALPHANUM:
840 // Remove everything not `a-zA-Z0-9`.
841 return preg_replace('/[^A-Za-z0-9]/i', '', $param);
842
843 case PARAM_ALPHANUMEXT:
844 // Remove everything not `a-zA-Z0-9_-`.
845 return preg_replace('/[^A-Za-z0-9_-]/i', '', $param);
846
847 case PARAM_SEQUENCE:
848 // Remove everything not `0-9,`.
849 return preg_replace('/[^0-9,]/i', '', $param);
850
851 case PARAM_BOOL:
852 // Convert to 1 or 0.
853 $tempstr = strtolower($param);
854 if ($tempstr === 'on' or $tempstr === 'yes' or $tempstr === 'true') {
855 $param = 1;
856 } else if ($tempstr === 'off' or $tempstr === 'no' or $tempstr === 'false') {
857 $param = 0;
858 } else {
859 $param = empty($param) ? 0 : 1;
860 }
861 return $param;
862
863 case PARAM_NOTAGS:
864 // Strip all tags.
865 $param = fix_utf8($param);
866 return strip_tags($param);
867
868 case PARAM_TEXT:
869 // Leave only tags needed for multilang.
870 $param = fix_utf8($param);
871 // If the multilang syntax is not correct we strip all tags because it would break xhtml strict which is required
872 // for accessibility standards please note this cleaning does not strip unbalanced '>' for BC compatibility reasons.
873 do {
874 if (strpos($param, '</lang>') !== false) {
875 // Old and future mutilang syntax.
876 $param = strip_tags($param, '<lang>');
877 if (!preg_match_all('/<.*>/suU', $param, $matches)) {
878 break;
879 }
880 $open = false;
881 foreach ($matches[0] as $match) {
882 if ($match === '</lang>') {
883 if ($open) {
884 $open = false;
885 continue;
886 } else {
887 break 2;
888 }
889 }
890 if (!preg_match('/^<lang lang="[a-zA-Z0-9_-]+"\s*>$/u', $match)) {
891 break 2;
892 } else {
893 $open = true;
894 }
895 }
896 if ($open) {
897 break;
898 }
899 return $param;
900
901 } else if (strpos($param, '</span>') !== false) {
902 // Current problematic multilang syntax.
903 $param = strip_tags($param, '<span>');
904 if (!preg_match_all('/<.*>/suU', $param, $matches)) {
905 break;
906 }
907 $open = false;
908 foreach ($matches[0] as $match) {
909 if ($match === '</span>') {
910 if ($open) {
911 $open = false;
912 continue;
913 } else {
914 break 2;
915 }
916 }
917 if (!preg_match('/^<span(\s+lang="[a-zA-Z0-9_-]+"|\s+class="multilang"){2}\s*>$/u', $match)) {
918 break 2;
919 } else {
920 $open = true;
921 }
922 }
923 if ($open) {
924 break;
925 }
926 return $param;
927 }
928 } while (false);
929 // Easy, just strip all tags, if we ever want to fix orphaned '&' we have to do that in format_string().
930 return strip_tags($param);
931
932 case PARAM_COMPONENT:
933 // We do not want any guessing here, either the name is correct or not
934 // please note only normalised component names are accepted.
935 if (!preg_match('/^[a-z]+(_[a-z][a-z0-9_]*)?[a-z0-9]+$/', $param)) {
936 return '';
937 }
938 if (strpos($param, '__') !== false) {
939 return '';
940 }
941 if (strpos($param, 'mod_') === 0) {
942 // Module names must not contain underscores because we need to differentiate them from invalid plugin types.
943 if (substr_count($param, '_') != 1) {
944 return '';
945 }
946 }
947 return $param;
948
949 case PARAM_PLUGIN:
950 case PARAM_AREA:
951 // We do not want any guessing here, either the name is correct or not.
952 if (!is_valid_plugin_name($param)) {
953 return '';
954 }
955 return $param;
956
957 case PARAM_SAFEDIR:
958 // Remove everything not a-zA-Z0-9_- .
959 return preg_replace('/[^a-zA-Z0-9_-]/i', '', $param);
960
961 case PARAM_SAFEPATH:
962 // Remove everything not a-zA-Z0-9/_- .
963 return preg_replace('/[^a-zA-Z0-9\/_-]/i', '', $param);
964
965 case PARAM_FILE:
966 // Strip all suspicious characters from filename.
967 $param = fix_utf8($param);
968 $param = preg_replace('~[[:cntrl:]]|[&<>"`\|\':\\\\/]~u', '', $param);
969 if ($param === '.' || $param === '..') {
970 $param = '';
971 }
972 return $param;
973
974 case PARAM_PATH:
975 // Strip all suspicious characters from file path.
976 $param = fix_utf8($param);
977 $param = str_replace('\\', '/', $param);
978
979 // Explode the path and clean each element using the PARAM_FILE rules.
980 $breadcrumb = explode('/', $param);
981 foreach ($breadcrumb as $key => $crumb) {
982 if ($crumb === '.' && $key === 0) {
983 // Special condition to allow for relative current path such as ./currentdirfile.txt.
984 } else {
985 $crumb = clean_param($crumb, PARAM_FILE);
986 }
987 $breadcrumb[$key] = $crumb;
988 }
989 $param = implode('/', $breadcrumb);
990
991 // Remove multiple current path (./././) and multiple slashes (///).
992 $param = preg_replace('~//+~', '/', $param);
993 $param = preg_replace('~/(\./)+~', '/', $param);
994 return $param;
995
996 case PARAM_HOST:
997 // Allow FQDN or IPv4 dotted quad.
998 $param = preg_replace('/[^\.\d\w-]/', '', $param );
999 // Match ipv4 dotted quad.
1000 if (preg_match('/(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})/', $param, $match)) {
1001 // Confirm values are ok.
1002 if ( $match[0] > 255
1003 || $match[1] > 255
1004 || $match[3] > 255
1005 || $match[4] > 255 ) {
1006 // Hmmm, what kind of dotted quad is this?
1007 $param = '';
1008 }
1009 } else if ( preg_match('/^[\w\d\.-]+$/', $param) // Dots, hyphens, numbers.
1010 && !preg_match('/^[\.-]/', $param) // No leading dots/hyphens.
1011 && !preg_match('/[\.-]$/', $param) // No trailing dots/hyphens.
1012 ) {
1013 // All is ok - $param is respected.
1014 } else {
1015 // All is not ok...
1016 $param='';
1017 }
1018 return $param;
1019
1020 case PARAM_URL: // Allow safe ftp, http, mailto urls.
1021 $param = fix_utf8($param);
1022 include_once($CFG->dirroot . '/lib/validateurlsyntax.php');
1023 if (!empty($param) && validateUrlSyntax($param, 's?H?S?F?E?u-P-a?I?p?f?q?r?')) {
1024 // All is ok, param is respected.
1025 } else {
1026 // Not really ok.
1027 $param ='';
1028 }
1029 return $param;
1030
1031 case PARAM_LOCALURL:
1032 // Allow http absolute, root relative and relative URLs within wwwroot.
1033 $param = clean_param($param, PARAM_URL);
1034 if (!empty($param)) {
1035 if (preg_match(':^/:', $param)) {
1036 // Root-relative, ok!
1037 } else if (preg_match('/^'.preg_quote($CFG->wwwroot, '/').'/i', $param)) {
1038 // Absolute, and matches our wwwroot.
1039 } else {
1040 // Relative - let's make sure there are no tricks.
1041 if (validateUrlSyntax('/' . $param, 's-u-P-a-p-f+q?r?')) {
1042 // Looks ok.
1043 } else {
1044 $param = '';
1045 }
1046 }
1047 }
1048 return $param;
1049
1050 case PARAM_PEM:
1051 $param = trim($param);
1052 // PEM formatted strings may contain letters/numbers and the symbols:
1053 // forward slash: /
1054 // plus sign: +
1055 // equal sign: =
1056 // , surrounded by BEGIN and END CERTIFICATE prefix and suffixes.
1057 if (preg_match('/^-----BEGIN CERTIFICATE-----([\s\w\/\+=]+)-----END CERTIFICATE-----$/', trim($param), $matches)) {
1058 list($wholething, $body) = $matches;
1059 unset($wholething, $matches);
1060 $b64 = clean_param($body, PARAM_BASE64);
1061 if (!empty($b64)) {
1062 return "-----BEGIN CERTIFICATE-----\n$b64\n-----END CERTIFICATE-----\n";
1063 } else {
1064 return '';
1065 }
1066 }
1067 return '';
1068
1069 case PARAM_BASE64:
1070 if (!empty($param)) {
1071 // PEM formatted strings may contain letters/numbers and the symbols
1072 // forward slash: /
1073 // plus sign: +
1074 // equal sign: =.
1075 if (0 >= preg_match('/^([\s\w\/\+=]+)$/', trim($param))) {
1076 return '';
1077 }
1078 $lines = preg_split('/[\s]+/', $param, -1, PREG_SPLIT_NO_EMPTY);
1079 // Each line of base64 encoded data must be 64 characters in length, except for the last line which may be less
1080 // than (or equal to) 64 characters long.
1081 for ($i=0, $j=count($lines); $i < $j; $i++) {
1082 if ($i + 1 == $j) {
1083 if (64 < strlen($lines[$i])) {
1084 return '';
1085 }
1086 continue;
1087 }
1088
1089 if (64 != strlen($lines[$i])) {
1090 return '';
1091 }
1092 }
1093 return implode("\n", $lines);
1094 } else {
1095 return '';
1096 }
1097
1098 case PARAM_TAG:
1099 $param = fix_utf8($param);
1100 // Please note it is not safe to use the tag name directly anywhere,
1101 // it must be processed with s(), urlencode() before embedding anywhere.
1102 // Remove some nasties.
1103 $param = preg_replace('~[[:cntrl:]]|[<>`]~u', '', $param);
1104 // Convert many whitespace chars into one.
1105 $param = preg_replace('/\s+/', ' ', $param);
1106 $param = core_text::substr(trim($param), 0, TAG_MAX_LENGTH);
1107 return $param;
1108
1109 case PARAM_TAGLIST:
1110 $param = fix_utf8($param);
1111 $tags = explode(',', $param);
1112 $result = array();
1113 foreach ($tags as $tag) {
1114 $res = clean_param($tag, PARAM_TAG);
1115 if ($res !== '') {
1116 $result[] = $res;
1117 }
1118 }
1119 if ($result) {
1120 return implode(',', $result);
1121 } else {
1122 return '';
1123 }
1124
1125 case PARAM_CAPABILITY:
1126 if (get_capability_info($param)) {
1127 return $param;
1128 } else {
1129 return '';
1130 }
1131
1132 case PARAM_PERMISSION:
1133 $param = (int)$param;
1134 if (in_array($param, array(CAP_INHERIT, CAP_ALLOW, CAP_PREVENT, CAP_PROHIBIT))) {
1135 return $param;
1136 } else {
1137 return CAP_INHERIT;
1138 }
1139
1140 case PARAM_AUTH:
1141 $param = clean_param($param, PARAM_PLUGIN);
1142 if (empty($param)) {
1143 return '';
1144 } else if (exists_auth_plugin($param)) {
1145 return $param;
1146 } else {
1147 return '';
1148 }
1149
1150 case PARAM_LANG:
1151 $param = clean_param($param, PARAM_SAFEDIR);
1152 if (get_string_manager()->translation_exists($param)) {
1153 return $param;
1154 } else {
1155 // Specified language is not installed or param malformed.
1156 return '';
1157 }
1158
1159 case PARAM_THEME:
1160 $param = clean_param($param, PARAM_PLUGIN);
1161 if (empty($param)) {
1162 return '';
1163 } else if (file_exists("$CFG->dirroot/theme/$param/config.php")) {
1164 return $param;
1165 } else if (!empty($CFG->themedir) and file_exists("$CFG->themedir/$param/config.php")) {
1166 return $param;
1167 } else {
1168 // Specified theme is not installed.
1169 return '';
1170 }
1171
1172 case PARAM_USERNAME:
1173 $param = fix_utf8($param);
1174 $param = trim($param);
1175 // Convert uppercase to lowercase MDL-16919.
1176 $param = core_text::strtolower($param);
1177 if (empty($CFG->extendedusernamechars)) {
1178 $param = str_replace(" " , "", $param);
1179 // Regular expression, eliminate all chars EXCEPT:
1180 // alphanum, dash (-), underscore (_), at sign (@) and period (.) characters.
1181 $param = preg_replace('/[^-\.@_a-z0-9]/', '', $param);
1182 }
1183 return $param;
1184
1185 case PARAM_EMAIL:
1186 $param = fix_utf8($param);
1187 if (validate_email($param)) {
1188 return $param;
1189 } else {
1190 return '';
1191 }
1192
1193 case PARAM_STRINGID:
1194 if (preg_match('|^[a-zA-Z][a-zA-Z0-9\.:/_-]*$|', $param)) {
1195 return $param;
1196 } else {
1197 return '';
1198 }
1199
1200 case PARAM_TIMEZONE:
1201 // Can be int, float(with .5 or .0) or string seperated by '/' and can have '-_'.
1202 $param = fix_utf8($param);
1203 $timezonepattern = '/^(([+-]?(0?[0-9](\.[5|0])?|1[0-3](\.0)?|1[0-2]\.5))|(99)|[[:alnum:]]+(\/?[[:alpha:]_-])+)$/';
1204 if (preg_match($timezonepattern, $param)) {
1205 return $param;
1206 } else {
1207 return '';
1208 }
1209
1210 default:
1211 // Doh! throw error, switched parameters in optional_param or another serious problem.
1212 print_error("unknownparamtype", '', '', $type);
1213 }
1214}
1215
1216/**
1217 * Makes sure the data is using valid utf8, invalid characters are discarded.
1218 *
1219 * Note: this function is not intended for full objects with methods and private properties.
1220 *
1221 * @param mixed $value
1222 * @return mixed with proper utf-8 encoding
1223 */
1224function fix_utf8($value) {
1225 if (is_null($value) or $value === '') {
1226 return $value;
1227
1228 } else if (is_string($value)) {
1229 if ((string)(int)$value === $value) {
1230 // Shortcut.
1231 return $value;
1232 }
1233 // No null bytes expected in our data, so let's remove it.
1234 $value = str_replace("\0", '', $value);
1235
1236 // Note: this duplicates min_fix_utf8() intentionally.
1237 static $buggyiconv = null;
1238 if ($buggyiconv === null) {
1239 $buggyiconv = (!function_exists('iconv') or @iconv('UTF-8', 'UTF-8//IGNORE', '100'.chr(130).'€') !== '100€');
1240 }
1241
1242 if ($buggyiconv) {
1243 if (function_exists('mb_convert_encoding')) {
1244 $subst = mb_substitute_character();
1245 mb_substitute_character('');
1246 $result = mb_convert_encoding($value, 'utf-8', 'utf-8');
1247 mb_substitute_character($subst);
1248
1249 } else {
1250 // Warn admins on admin/index.php page.
1251 $result = $value;
1252 }
1253
1254 } else {
1255 $result = @iconv('UTF-8', 'UTF-8//IGNORE', $value);
1256 }
1257
1258 return $result;
1259
1260 } else if (is_array($value)) {
1261 foreach ($value as $k => $v) {
1262 $value[$k] = fix_utf8($v);
1263 }
1264 return $value;
1265
1266 } else if (is_object($value)) {
1267 // Do not modify original.
1268 $value = clone($value);
1269 foreach ($value as $k => $v) {
1270 $value->$k = fix_utf8($v);
1271 }
1272 return $value;
1273
1274 } else {
1275 // This is some other type, no utf-8 here.
1276 return $value;
1277 }
1278}
1279
1280/**
1281 * Return true if given value is integer or string with integer value
1282 *
1283 * @param mixed $value String or Int
1284 * @return bool true if number, false if not
1285 */
1286function is_number($value) {
1287 if (is_int($value)) {
1288 return true;
1289 } else if (is_string($value)) {
1290 return ((string)(int)$value) === $value;
1291 } else {
1292 return false;
1293 }
1294}
1295
1296/**
1297 * Returns host part from url.
1298 *
1299 * @param string $url full url
1300 * @return string host, null if not found
1301 */
1302function get_host_from_url($url) {
1303 preg_match('|^[a-z]+://([a-zA-Z0-9-.]+)|i', $url, $matches);
1304 if ($matches) {
1305 return $matches[1];
1306 }
1307 return null;
1308}
1309
1310/**
1311 * Tests whether anything was returned by text editor
1312 *
1313 * This function is useful for testing whether something you got back from
1314 * the HTML editor actually contains anything. Sometimes the HTML editor
1315 * appear to be empty, but actually you get back a <br> tag or something.
1316 *
1317 * @param string $string a string containing HTML.
1318 * @return boolean does the string contain any actual content - that is text,
1319 * images, objects, etc.
1320 */
1321function html_is_blank($string) {
1322 return trim(strip_tags($string, '<img><object><applet><input><select><textarea><hr>')) == '';
1323}
1324
1325/**
1326 * Set a key in global configuration
1327 *
1328 * Set a key/value pair in both this session's {@link $CFG} global variable
1329 * and in the 'config' database table for future sessions.
1330 *
1331 * Can also be used to update keys for plugin-scoped configs in config_plugin table.
1332 * In that case it doesn't affect $CFG.
1333 *
1334 * A NULL value will delete the entry.
1335 *
1336 * NOTE: this function is called from lib/db/upgrade.php
1337 *
1338 * @param string $name the key to set
1339 * @param string $value the value to set (without magic quotes)
1340 * @param string $plugin (optional) the plugin scope, default null
1341 * @return bool true or exception
1342 */
1343function set_config($name, $value, $plugin=null) {
1344 global $CFG, $DB;
1345
1346 if (empty($plugin)) {
1347 if (!array_key_exists($name, $CFG->config_php_settings)) {
1348 // So it's defined for this invocation at least.
1349 if (is_null($value)) {
1350 unset($CFG->$name);
1351 } else {
1352 // Settings from db are always strings.
1353 $CFG->$name = (string)$value;
1354 }
1355 }
1356
1357 if ($DB->get_field('config', 'name', array('name' => $name))) {
1358 if ($value === null) {
1359 $DB->delete_records('config', array('name' => $name));
1360 } else {
1361 $DB->set_field('config', 'value', $value, array('name' => $name));
1362 }
1363 } else {
1364 if ($value !== null) {
1365 $config = new stdClass();
1366 $config->name = $name;
1367 $config->value = $value;
1368 $DB->insert_record('config', $config, false);
1369 }
1370 }
1371 if ($name === 'siteidentifier') {
1372 cache_helper::update_site_identifier($value);
1373 }
1374 cache_helper::invalidate_by_definition('core', 'config', array(), 'core');
1375 } else {
1376 // Plugin scope.
1377 if ($id = $DB->get_field('config_plugins', 'id', array('name' => $name, 'plugin' => $plugin))) {
1378 if ($value===null) {
1379 $DB->delete_records('config_plugins', array('name' => $name, 'plugin' => $plugin));
1380 } else {
1381 $DB->set_field('config_plugins', 'value', $value, array('id' => $id));
1382 }
1383 } else {
1384 if ($value !== null) {
1385 $config = new stdClass();
1386 $config->plugin = $plugin;
1387 $config->name = $name;
1388 $config->value = $value;
1389 $DB->insert_record('config_plugins', $config, false);
1390 }
1391 }
1392 cache_helper::invalidate_by_definition('core', 'config', array(), $plugin);
1393 }
1394
1395 return true;
1396}
1397
1398/**
1399 * Get configuration values from the global config table
1400 * or the config_plugins table.
1401 *
1402 * If called with one parameter, it will load all the config
1403 * variables for one plugin, and return them as an object.
1404 *
1405 * If called with 2 parameters it will return a string single
1406 * value or false if the value is not found.
1407 *
1408 * NOTE: this function is called from lib/db/upgrade.php
1409 *
1410 * @static string|false $siteidentifier The site identifier is not cached. We use this static cache so
1411 * that we need only fetch it once per request.
1412 * @param string $plugin full component name
1413 * @param string $name default null
1414 * @return mixed hash-like object or single value, return false no config found
1415 * @throws dml_exception
1416 */
1417function get_config($plugin, $name = null) {
1418 global $CFG, $DB;
1419
1420 static $siteidentifier = null;
1421
1422 if ($plugin === 'moodle' || $plugin === 'core' || empty($plugin)) {
1423 $forced =& $CFG->config_php_settings;
1424 $iscore = true;
1425 $plugin = 'core';
1426 } else {
1427 if (array_key_exists($plugin, $CFG->forced_plugin_settings)) {
1428 $forced =& $CFG->forced_plugin_settings[$plugin];
1429 } else {
1430 $forced = array();
1431 }
1432 $iscore = false;
1433 }
1434
1435 if ($siteidentifier === null) {
1436 try {
1437 // This may fail during installation.
1438 // If you have a look at {@link initialise_cfg()} you will see that this is how we detect the need to
1439 // install the database.
1440 $siteidentifier = $DB->get_field('config', 'value', array('name' => 'siteidentifier'));
1441 } catch (dml_exception $ex) {
1442 // Set siteidentifier to false. We don't want to trip this continually.
1443 $siteidentifier = false;
1444 throw $ex;
1445 }
1446 }
1447
1448 if (!empty($name)) {
1449 if (array_key_exists($name, $forced)) {
1450 return (string)$forced[$name];
1451 } else if ($name === 'siteidentifier' && $plugin == 'core') {
1452 return $siteidentifier;
1453 }
1454 }
1455
1456 $cache = cache::make('core', 'config');
1457 $result = $cache->get($plugin);
1458 if ($result === false) {
1459 // The user is after a recordset.
1460 if (!$iscore) {
1461 $result = $DB->get_records_menu('config_plugins', array('plugin' => $plugin), '', 'name,value');
1462 } else {
1463 // This part is not really used any more, but anyway...
1464 $result = $DB->get_records_menu('config', array(), '', 'name,value');;
1465 }
1466 $cache->set($plugin, $result);
1467 }
1468
1469 if (!empty($name)) {
1470 if (array_key_exists($name, $result)) {
1471 return $result[$name];
1472 }
1473 return false;
1474 }
1475
1476 if ($plugin === 'core') {
1477 $result['siteidentifier'] = $siteidentifier;
1478 }
1479
1480 foreach ($forced as $key => $value) {
1481 if (is_null($value) or is_array($value) or is_object($value)) {
1482 // We do not want any extra mess here, just real settings that could be saved in db.
1483 unset($result[$key]);
1484 } else {
1485 // Convert to string as if it went through the DB.
1486 $result[$key] = (string)$value;
1487 }
1488 }
1489
1490 return (object)$result;
1491}
1492
1493/**
1494 * Removes a key from global configuration.
1495 *
1496 * NOTE: this function is called from lib/db/upgrade.php
1497 *
1498 * @param string $name the key to set
1499 * @param string $plugin (optional) the plugin scope
1500 * @return boolean whether the operation succeeded.
1501 */
1502function unset_config($name, $plugin=null) {
1503 global $CFG, $DB;
1504
1505 if (empty($plugin)) {
1506 unset($CFG->$name);
1507 $DB->delete_records('config', array('name' => $name));
1508 cache_helper::invalidate_by_definition('core', 'config', array(), 'core');
1509 } else {
1510 $DB->delete_records('config_plugins', array('name' => $name, 'plugin' => $plugin));
1511 cache_helper::invalidate_by_definition('core', 'config', array(), $plugin);
1512 }
1513
1514 return true;
1515}
1516
1517/**
1518 * Remove all the config variables for a given plugin.
1519 *
1520 * NOTE: this function is called from lib/db/upgrade.php
1521 *
1522 * @param string $plugin a plugin, for example 'quiz' or 'qtype_multichoice';
1523 * @return boolean whether the operation succeeded.
1524 */
1525function unset_all_config_for_plugin($plugin) {
1526 global $DB;
1527 // Delete from the obvious config_plugins first.
1528 $DB->delete_records('config_plugins', array('plugin' => $plugin));
1529 // Next delete any suspect settings from config.
1530 $like = $DB->sql_like('name', '?', true, true, false, '|');
1531 $params = array($DB->sql_like_escape($plugin.'_', '|') . '%');
1532 $DB->delete_records_select('config', $like, $params);
1533 // Finally clear both the plugin cache and the core cache (suspect settings now removed from core).
1534 cache_helper::invalidate_by_definition('core', 'config', array(), array('core', $plugin));
1535
1536 return true;
1537}
1538
1539/**
1540 * Use this function to get a list of users from a config setting of type admin_setting_users_with_capability.
1541 *
1542 * All users are verified if they still have the necessary capability.
1543 *
1544 * @param string $value the value of the config setting.
1545 * @param string $capability the capability - must match the one passed to the admin_setting_users_with_capability constructor.
1546 * @param bool $includeadmins include administrators.
1547 * @return array of user objects.
1548 */
1549function get_users_from_config($value, $capability, $includeadmins = true) {
1550 if (empty($value) or $value === '$@NONE@$') {
1551 return array();
1552 }
1553
1554 // We have to make sure that users still have the necessary capability,
1555 // it should be faster to fetch them all first and then test if they are present
1556 // instead of validating them one-by-one.
1557 $users = get_users_by_capability(context_system::instance(), $capability);
1558 if ($includeadmins) {
1559 $admins = get_admins();
1560 foreach ($admins as $admin) {
1561 $users[$admin->id] = $admin;
1562 }
1563 }
1564
1565 if ($value === '$@ALL@$') {
1566 return $users;
1567 }
1568
1569 $result = array(); // Result in correct order.
1570 $allowed = explode(',', $value);
1571 foreach ($allowed as $uid) {
1572 if (isset($users[$uid])) {
1573 $user = $users[$uid];
1574 $result[$user->id] = $user;
1575 }
1576 }
1577
1578 return $result;
1579}
1580
1581
1582/**
1583 * Invalidates browser caches and cached data in temp.
1584 *
1585 * IMPORTANT - If you are adding anything here to do with the cache directory you should also have a look at
1586 * {@link phpunit_util::reset_dataroot()}
1587 *
1588 * @return void
1589 */
1590function purge_all_caches() {
1591 global $CFG, $DB;
1592
1593 reset_text_filters_cache();
1594 js_reset_all_caches();
1595 theme_reset_all_caches();
1596 get_string_manager()->reset_caches();
1597 core_text::reset_caches();
1598 if (class_exists('core_plugin_manager')) {
1599 core_plugin_manager::reset_caches();
1600 }
1601
1602 // Bump up cacherev field for all courses.
1603 try {
1604 increment_revision_number('course', 'cacherev', '');
1605 } catch (moodle_exception $e) {
1606 // Ignore exception since this function is also called before upgrade script when field course.cacherev does not exist yet.
1607 }
1608
1609 $DB->reset_caches();
1610 cache_helper::purge_all();
1611
1612 // Purge all other caches: rss, simplepie, etc.
1613 remove_dir($CFG->cachedir.'', true);
1614
1615 // Make sure cache dir is writable, throws exception if not.
1616 make_cache_directory('');
1617
1618 // This is the only place where we purge local caches, we are only adding files there.
1619 // The $CFG->localcachedirpurged flag forces local directories to be purged on cluster nodes.
1620 remove_dir($CFG->localcachedir, true);
1621 set_config('localcachedirpurged', time());
1622 make_localcache_directory('', true);
1623 \core\task\manager::clear_static_caches();
1624}
1625
1626/**
1627 * Get volatile flags
1628 *
1629 * @param string $type
1630 * @param int $changedsince default null
1631 * @return array records array
1632 */
1633function get_cache_flags($type, $changedsince = null) {
1634 global $DB;
1635
1636 $params = array('type' => $type, 'expiry' => time());
1637 $sqlwhere = "flagtype = :type AND expiry >= :expiry";
1638 if ($changedsince !== null) {
1639 $params['changedsince'] = $changedsince;
1640 $sqlwhere .= " AND timemodified > :changedsince";
1641 }
1642 $cf = array();
1643 if ($flags = $DB->get_records_select('cache_flags', $sqlwhere, $params, '', 'name,value')) {
1644 foreach ($flags as $flag) {
1645 $cf[$flag->name] = $flag->value;
1646 }
1647 }
1648 return $cf;
1649}
1650
1651/**
1652 * Get volatile flags
1653 *
1654 * @param string $type
1655 * @param string $name
1656 * @param int $changedsince default null
1657 * @return string|false The cache flag value or false
1658 */
1659function get_cache_flag($type, $name, $changedsince=null) {
1660 global $DB;
1661
1662 $params = array('type' => $type, 'name' => $name, 'expiry' => time());
1663
1664 $sqlwhere = "flagtype = :type AND name = :name AND expiry >= :expiry";
1665 if ($changedsince !== null) {
1666 $params['changedsince'] = $changedsince;
1667 $sqlwhere .= " AND timemodified > :changedsince";
1668 }
1669
1670 return $DB->get_field_select('cache_flags', 'value', $sqlwhere, $params);
1671}
1672
1673/**
1674 * Set a volatile flag
1675 *
1676 * @param string $type the "type" namespace for the key
1677 * @param string $name the key to set
1678 * @param string $value the value to set (without magic quotes) - null will remove the flag
1679 * @param int $expiry (optional) epoch indicating expiry - defaults to now()+ 24hs
1680 * @return bool Always returns true
1681 */
1682function set_cache_flag($type, $name, $value, $expiry = null) {
1683 global $DB;
1684
1685 $timemodified = time();
1686 if ($expiry === null || $expiry < $timemodified) {
1687 $expiry = $timemodified + 24 * 60 * 60;
1688 } else {
1689 $expiry = (int)$expiry;
1690 }
1691
1692 if ($value === null) {
1693 unset_cache_flag($type, $name);
1694 return true;
1695 }
1696
1697 if ($f = $DB->get_record('cache_flags', array('name' => $name, 'flagtype' => $type), '*', IGNORE_MULTIPLE)) {
1698 // This is a potential problem in DEBUG_DEVELOPER.
1699 if ($f->value == $value and $f->expiry == $expiry and $f->timemodified == $timemodified) {
1700 return true; // No need to update.
1701 }
1702 $f->value = $value;
1703 $f->expiry = $expiry;
1704 $f->timemodified = $timemodified;
1705 $DB->update_record('cache_flags', $f);
1706 } else {
1707 $f = new stdClass();
1708 $f->flagtype = $type;
1709 $f->name = $name;
1710 $f->value = $value;
1711 $f->expiry = $expiry;
1712 $f->timemodified = $timemodified;
1713 $DB->insert_record('cache_flags', $f);
1714 }
1715 return true;
1716}
1717
1718/**
1719 * Removes a single volatile flag
1720 *
1721 * @param string $type the "type" namespace for the key
1722 * @param string $name the key to set
1723 * @return bool
1724 */
1725function unset_cache_flag($type, $name) {
1726 global $DB;
1727 $DB->delete_records('cache_flags', array('name' => $name, 'flagtype' => $type));
1728 return true;
1729}
1730
1731/**
1732 * Garbage-collect volatile flags
1733 *
1734 * @return bool Always returns true
1735 */
1736function gc_cache_flags() {
1737 global $DB;
1738 $DB->delete_records_select('cache_flags', 'expiry < ?', array(time()));
1739 return true;
1740}
1741
1742// USER PREFERENCE API.
1743
1744/**
1745 * Refresh user preference cache. This is used most often for $USER
1746 * object that is stored in session, but it also helps with performance in cron script.
1747 *
1748 * Preferences for each user are loaded on first use on every page, then again after the timeout expires.
1749 *
1750 * @package core
1751 * @category preference
1752 * @access public
1753 * @param stdClass $user User object. Preferences are preloaded into 'preference' property
1754 * @param int $cachelifetime Cache life time on the current page (in seconds)
1755 * @throws coding_exception
1756 * @return null
1757 */
1758function check_user_preferences_loaded(stdClass $user, $cachelifetime = 120) {
1759 global $DB;
1760 // Static cache, we need to check on each page load, not only every 2 minutes.
1761 static $loadedusers = array();
1762
1763 if (!isset($user->id)) {
1764 throw new coding_exception('Invalid $user parameter in check_user_preferences_loaded() call, missing id field');
1765 }
1766
1767 if (empty($user->id) or isguestuser($user->id)) {
1768 // No permanent storage for not-logged-in users and guest.
1769 if (!isset($user->preference)) {
1770 $user->preference = array();
1771 }
1772 return;
1773 }
1774
1775 $timenow = time();
1776
1777 if (isset($loadedusers[$user->id]) and isset($user->preference) and isset($user->preference['_lastloaded'])) {
1778 // Already loaded at least once on this page. Are we up to date?
1779 if ($user->preference['_lastloaded'] + $cachelifetime > $timenow) {
1780 // No need to reload - we are on the same page and we loaded prefs just a moment ago.
1781 return;
1782
1783 } else if (!get_cache_flag('userpreferenceschanged', $user->id, $user->preference['_lastloaded'])) {
1784 // No change since the lastcheck on this page.
1785 $user->preference['_lastloaded'] = $timenow;
1786 return;
1787 }
1788 }
1789
1790 // OK, so we have to reload all preferences.
1791 $loadedusers[$user->id] = true;
1792 $user->preference = $DB->get_records_menu('user_preferences', array('userid' => $user->id), '', 'name,value'); // All values.
1793 $user->preference['_lastloaded'] = $timenow;
1794}
1795
1796/**
1797 * Called from set/unset_user_preferences, so that the prefs can be correctly reloaded in different sessions.
1798 *
1799 * NOTE: internal function, do not call from other code.
1800 *
1801 * @package core
1802 * @access private
1803 * @param integer $userid the user whose prefs were changed.
1804 */
1805function mark_user_preferences_changed($userid) {
1806 global $CFG;
1807
1808 if (empty($userid) or isguestuser($userid)) {
1809 // No cache flags for guest and not-logged-in users.
1810 return;
1811 }
1812
1813 set_cache_flag('userpreferenceschanged', $userid, 1, time() + $CFG->sessiontimeout);
1814}
1815
1816/**
1817 * Sets a preference for the specified user.
1818 *
1819 * If a $user object is submitted it's 'preference' property is used for the preferences cache.
1820 *
1821 * @package core
1822 * @category preference
1823 * @access public
1824 * @param string $name The key to set as preference for the specified user
1825 * @param string $value The value to set for the $name key in the specified user's
1826 * record, null means delete current value.
1827 * @param stdClass|int|null $user A moodle user object or id, null means current user
1828 * @throws coding_exception
1829 * @return bool Always true or exception
1830 */
1831function set_user_preference($name, $value, $user = null) {
1832 global $USER, $DB;
1833
1834 if (empty($name) or is_numeric($name) or $name === '_lastloaded') {
1835 throw new coding_exception('Invalid preference name in set_user_preference() call');
1836 }
1837
1838 if (is_null($value)) {
1839 // Null means delete current.
1840 return unset_user_preference($name, $user);
1841 } else if (is_object($value)) {
1842 throw new coding_exception('Invalid value in set_user_preference() call, objects are not allowed');
1843 } else if (is_array($value)) {
1844 throw new coding_exception('Invalid value in set_user_preference() call, arrays are not allowed');
1845 }
1846 // Value column maximum length is 1333 characters.
1847 $value = (string)$value;
1848 if (core_text::strlen($value) > 1333) {
1849 throw new coding_exception('Invalid value in set_user_preference() call, value is is too long for the value column');
1850 }
1851
1852 if (is_null($user)) {
1853 $user = $USER;
1854 } else if (isset($user->id)) {
1855 // It is a valid object.
1856 } else if (is_numeric($user)) {
1857 $user = (object)array('id' => (int)$user);
1858 } else {
1859 throw new coding_exception('Invalid $user parameter in set_user_preference() call');
1860 }
1861
1862 check_user_preferences_loaded($user);
1863
1864 if (empty($user->id) or isguestuser($user->id)) {
1865 // No permanent storage for not-logged-in users and guest.
1866 $user->preference[$name] = $value;
1867 return true;
1868 }
1869
1870 if ($preference = $DB->get_record('user_preferences', array('userid' => $user->id, 'name' => $name))) {
1871 if ($preference->value === $value and isset($user->preference[$name]) and $user->preference[$name] === $value) {
1872 // Preference already set to this value.
1873 return true;
1874 }
1875 $DB->set_field('user_preferences', 'value', $value, array('id' => $preference->id));
1876
1877 } else {
1878 $preference = new stdClass();
1879 $preference->userid = $user->id;
1880 $preference->name = $name;
1881 $preference->value = $value;
1882 $DB->insert_record('user_preferences', $preference);
1883 }
1884
1885 // Update value in cache.
1886 $user->preference[$name] = $value;
1887
1888 // Set reload flag for other sessions.
1889 mark_user_preferences_changed($user->id);
1890
1891 return true;
1892}
1893
1894/**
1895 * Sets a whole array of preferences for the current user
1896 *
1897 * If a $user object is submitted it's 'preference' property is used for the preferences cache.
1898 *
1899 * @package core
1900 * @category preference
1901 * @access public
1902 * @param array $prefarray An array of key/value pairs to be set
1903 * @param stdClass|int|null $user A moodle user object or id, null means current user
1904 * @return bool Always true or exception
1905 */
1906function set_user_preferences(array $prefarray, $user = null) {
1907 foreach ($prefarray as $name => $value) {
1908 set_user_preference($name, $value, $user);
1909 }
1910 return true;
1911}
1912
1913/**
1914 * Unsets a preference completely by deleting it from the database
1915 *
1916 * If a $user object is submitted it's 'preference' property is used for the preferences cache.
1917 *
1918 * @package core
1919 * @category preference
1920 * @access public
1921 * @param string $name The key to unset as preference for the specified user
1922 * @param stdClass|int|null $user A moodle user object or id, null means current user
1923 * @throws coding_exception
1924 * @return bool Always true or exception
1925 */
1926function unset_user_preference($name, $user = null) {
1927 global $USER, $DB;
1928
1929 if (empty($name) or is_numeric($name) or $name === '_lastloaded') {
1930 throw new coding_exception('Invalid preference name in unset_user_preference() call');
1931 }
1932
1933 if (is_null($user)) {
1934 $user = $USER;
1935 } else if (isset($user->id)) {
1936 // It is a valid object.
1937 } else if (is_numeric($user)) {
1938 $user = (object)array('id' => (int)$user);
1939 } else {
1940 throw new coding_exception('Invalid $user parameter in unset_user_preference() call');
1941 }
1942
1943 check_user_preferences_loaded($user);
1944
1945 if (empty($user->id) or isguestuser($user->id)) {
1946 // No permanent storage for not-logged-in user and guest.
1947 unset($user->preference[$name]);
1948 return true;
1949 }
1950
1951 // Delete from DB.
1952 $DB->delete_records('user_preferences', array('userid' => $user->id, 'name' => $name));
1953
1954 // Delete the preference from cache.
1955 unset($user->preference[$name]);
1956
1957 // Set reload flag for other sessions.
1958 mark_user_preferences_changed($user->id);
1959
1960 return true;
1961}
1962
1963/**
1964 * Used to fetch user preference(s)
1965 *
1966 * If no arguments are supplied this function will return
1967 * all of the current user preferences as an array.
1968 *
1969 * If a name is specified then this function
1970 * attempts to return that particular preference value. If
1971 * none is found, then the optional value $default is returned,
1972 * otherwise null.
1973 *
1974 * If a $user object is submitted it's 'preference' property is used for the preferences cache.
1975 *
1976 * @package core
1977 * @category preference
1978 * @access public
1979 * @param string $name Name of the key to use in finding a preference value
1980 * @param mixed|null $default Value to be returned if the $name key is not set in the user preferences
1981 * @param stdClass|int|null $user A moodle user object or id, null means current user
1982 * @throws coding_exception
1983 * @return string|mixed|null A string containing the value of a single preference. An
1984 * array with all of the preferences or null
1985 */
1986function get_user_preferences($name = null, $default = null, $user = null) {
1987 global $USER;
1988
1989 if (is_null($name)) {
1990 // All prefs.
1991 } else if (is_numeric($name) or $name === '_lastloaded') {
1992 throw new coding_exception('Invalid preference name in get_user_preferences() call');
1993 }
1994
1995 if (is_null($user)) {
1996 $user = $USER;
1997 } else if (isset($user->id)) {
1998 // Is a valid object.
1999 } else if (is_numeric($user)) {
2000 $user = (object)array('id' => (int)$user);
2001 } else {
2002 throw new coding_exception('Invalid $user parameter in get_user_preferences() call');
2003 }
2004
2005 check_user_preferences_loaded($user);
2006
2007 if (empty($name)) {
2008 // All values.
2009 return $user->preference;
2010 } else if (isset($user->preference[$name])) {
2011 // The single string value.
2012 return $user->preference[$name];
2013 } else {
2014 // Default value (null if not specified).
2015 return $default;
2016 }
2017}
2018
2019// FUNCTIONS FOR HANDLING TIME.
2020
2021/**
2022 * Given date parts in user time produce a GMT timestamp.
2023 *
2024 * @package core
2025 * @category time
2026 * @param int $year The year part to create timestamp of
2027 * @param int $month The month part to create timestamp of
2028 * @param int $day The day part to create timestamp of
2029 * @param int $hour The hour part to create timestamp of
2030 * @param int $minute The minute part to create timestamp of
2031 * @param int $second The second part to create timestamp of
2032 * @param int|float|string $timezone Timezone modifier, used to calculate GMT time offset.
2033 * if 99 then default user's timezone is used {@link http://docs.moodle.org/dev/Time_API#Timezone}
2034 * @param bool $applydst Toggle Daylight Saving Time, default true, will be
2035 * applied only if timezone is 99 or string.
2036 * @return int GMT timestamp
2037 */
2038function make_timestamp($year, $month=1, $day=1, $hour=0, $minute=0, $second=0, $timezone=99, $applydst=true) {
2039
2040 // Save input timezone, required for dst offset check.
2041 $passedtimezone = $timezone;
2042
2043 $timezone = get_user_timezone_offset($timezone);
2044
2045 if (abs($timezone) > 13) {
2046 // Server time.
2047 $time = mktime((int)$hour, (int)$minute, (int)$second, (int)$month, (int)$day, (int)$year);
2048 } else {
2049 $time = gmmktime((int)$hour, (int)$minute, (int)$second, (int)$month, (int)$day, (int)$year);
2050 $time = usertime($time, $timezone);
2051
2052 // Apply dst for string timezones or if 99 then try dst offset with user's default timezone.
2053 if ($applydst && ((99 == $passedtimezone) || !is_numeric($passedtimezone))) {
2054 $time -= dst_offset_on($time, $passedtimezone);
2055 }
2056 }
2057
2058 return $time;
2059
2060}
2061
2062/**
2063 * Format a date/time (seconds) as weeks, days, hours etc as needed
2064 *
2065 * Given an amount of time in seconds, returns string
2066 * formatted nicely as weeks, days, hours etc as needed
2067 *
2068 * @package core
2069 * @category time
2070 * @uses MINSECS
2071 * @uses HOURSECS
2072 * @uses DAYSECS
2073 * @uses YEARSECS
2074 * @param int $totalsecs Time in seconds
2075 * @param stdClass $str Should be a time object
2076 * @return string A nicely formatted date/time string
2077 */
2078function format_time($totalsecs, $str = null) {
2079
2080 $totalsecs = abs($totalsecs);
2081
2082 if (!$str) {
2083 // Create the str structure the slow way.
2084 $str = new stdClass();
2085 $str->day = get_string('day');
2086 $str->days = get_string('days');
2087 $str->hour = get_string('hour');
2088 $str->hours = get_string('hours');
2089 $str->min = get_string('min');
2090 $str->mins = get_string('mins');
2091 $str->sec = get_string('sec');
2092 $str->secs = get_string('secs');
2093 $str->year = get_string('year');
2094 $str->years = get_string('years');
2095 }
2096
2097 $years = floor($totalsecs/YEARSECS);
2098 $remainder = $totalsecs - ($years*YEARSECS);
2099 $days = floor($remainder/DAYSECS);
2100 $remainder = $totalsecs - ($days*DAYSECS);
2101 $hours = floor($remainder/HOURSECS);
2102 $remainder = $remainder - ($hours*HOURSECS);
2103 $mins = floor($remainder/MINSECS);
2104 $secs = $remainder - ($mins*MINSECS);
2105
2106 $ss = ($secs == 1) ? $str->sec : $str->secs;
2107 $sm = ($mins == 1) ? $str->min : $str->mins;
2108 $sh = ($hours == 1) ? $str->hour : $str->hours;
2109 $sd = ($days == 1) ? $str->day : $str->days;
2110 $sy = ($years == 1) ? $str->year : $str->years;
2111
2112 $oyears = '';
2113 $odays = '';
2114 $ohours = '';
2115 $omins = '';
2116 $osecs = '';
2117
2118 if ($years) {
2119 $oyears = $years .' '. $sy;
2120 }
2121 if ($days) {
2122 $odays = $days .' '. $sd;
2123 }
2124 if ($hours) {
2125 $ohours = $hours .' '. $sh;
2126 }
2127 if ($mins) {
2128 $omins = $mins .' '. $sm;
2129 }
2130 if ($secs) {
2131 $osecs = $secs .' '. $ss;
2132 }
2133
2134 if ($years) {
2135 return trim($oyears .' '. $odays);
2136 }
2137 if ($days) {
2138 return trim($odays .' '. $ohours);
2139 }
2140 if ($hours) {
2141 return trim($ohours .' '. $omins);
2142 }
2143 if ($mins) {
2144 return trim($omins .' '. $osecs);
2145 }
2146 if ($secs) {
2147 return $osecs;
2148 }
2149 return get_string('now');
2150}
2151
2152/**
2153 * Returns a formatted string that represents a date in user time.
2154 *
2155 * @package core
2156 * @category time
2157 * @param int $date the timestamp in UTC, as obtained from the database.
2158 * @param string $format strftime format. You should probably get this using
2159 * get_string('strftime...', 'langconfig');
2160 * @param int|float|string $timezone by default, uses the user's time zone. if numeric and
2161 * not 99 then daylight saving will not be added.
2162 * {@link http://docs.moodle.org/dev/Time_API#Timezone}
2163 * @param bool $fixday If true (default) then the leading zero from %d is removed.
2164 * If false then the leading zero is maintained.
2165 * @param bool $fixhour If true (default) then the leading zero from %I is removed.
2166 * @return string the formatted date/time.
2167 */
2168function userdate($date, $format = '', $timezone = 99, $fixday = true, $fixhour = true) {
2169 $calendartype = \core_calendar\type_factory::get_calendar_instance();
2170 return $calendartype->timestamp_to_date_string($date, $format, $timezone, $fixday, $fixhour);
2171}
2172
2173/**
2174 * Returns a formatted date ensuring it is UTF-8.
2175 *
2176 * If we are running under Windows convert to Windows encoding and then back to UTF-8
2177 * (because it's impossible to specify UTF-8 to fetch locale info in Win32).
2178 *
2179 * This function does not do any calculation regarding the user preferences and should
2180 * therefore receive the final date timestamp, format and timezone. Timezone being only used
2181 * to differentiate the use of server time or not (strftime() against gmstrftime()).
2182 *
2183 * @param int $date the timestamp.
2184 * @param string $format strftime format.
2185 * @param int|float $tz the numerical timezone, typically returned by {@link get_user_timezone_offset()}.
2186 * @return string the formatted date/time.
2187 * @since Moodle 2.3.3
2188 */
2189function date_format_string($date, $format, $tz = 99) {
2190 global $CFG;
2191
2192 $localewincharset = null;
2193 // Get the calendar type user is using.
2194 if ($CFG->ostype == 'WINDOWS') {
2195 $calendartype = \core_calendar\type_factory::get_calendar_instance();
2196 $localewincharset = $calendartype->locale_win_charset();
2197 }
2198
2199 if (abs($tz) > 13) {
2200 if ($localewincharset) {
2201 $format = core_text::convert($format, 'utf-8', $localewincharset);
2202 $datestring = strftime($format, $date);
2203 $datestring = core_text::convert($datestring, $localewincharset, 'utf-8');
2204 } else {
2205 $datestring = strftime($format, $date);
2206 }
2207 } else {
2208 if ($localewincharset) {
2209 $format = core_text::convert($format, 'utf-8', $localewincharset);
2210 $datestring = gmstrftime($format, $date);
2211 $datestring = core_text::convert($datestring, $localewincharset, 'utf-8');
2212 } else {
2213 $datestring = gmstrftime($format, $date);
2214 }
2215 }
2216 return $datestring;
2217}
2218
2219/**
2220 * Given a $time timestamp in GMT (seconds since epoch),
2221 * returns an array that represents the date in user time
2222 *
2223 * @package core
2224 * @category time
2225 * @uses HOURSECS
2226 * @param int $time Timestamp in GMT
2227 * @param float|int|string $timezone offset's time with timezone, if float and not 99, then no
2228 * dst offset is applied {@link http://docs.moodle.org/dev/Time_API#Timezone}
2229 * @return array An array that represents the date in user time
2230 */
2231function usergetdate($time, $timezone=99) {
2232
2233 // Save input timezone, required for dst offset check.
2234 $passedtimezone = $timezone;
2235
2236 $timezone = get_user_timezone_offset($timezone);
2237
2238 if (abs($timezone) > 13) {
2239 // Server time.
2240 return getdate($time);
2241 }
2242
2243 // Add daylight saving offset for string timezones only, as we can't get dst for
2244 // float values. if timezone is 99 (user default timezone), then try update dst.
2245 if ($passedtimezone == 99 || !is_numeric($passedtimezone)) {
2246 $time += dst_offset_on($time, $passedtimezone);
2247 }
2248
2249 $time += intval((float)$timezone * HOURSECS);
2250
2251 $datestring = gmstrftime('%B_%A_%j_%Y_%m_%w_%d_%H_%M_%S', $time);
2252
2253 // Be careful to ensure the returned array matches that produced by getdate() above.
2254 list(
2255 $getdate['month'],
2256 $getdate['weekday'],
2257 $getdate['yday'],
2258 $getdate['year'],
2259 $getdate['mon'],
2260 $getdate['wday'],
2261 $getdate['mday'],
2262 $getdate['hours'],
2263 $getdate['minutes'],
2264 $getdate['seconds']
2265 ) = explode('_', $datestring);
2266
2267 // Set correct datatype to match with getdate().
2268 $getdate['seconds'] = (int)$getdate['seconds'];
2269 $getdate['yday'] = (int)$getdate['yday'] - 1; // The function gmstrftime returns 0 through 365.
2270 $getdate['year'] = (int)$getdate['year'];
2271 $getdate['mon'] = (int)$getdate['mon'];
2272 $getdate['wday'] = (int)$getdate['wday'];
2273 $getdate['mday'] = (int)$getdate['mday'];
2274 $getdate['hours'] = (int)$getdate['hours'];
2275 $getdate['minutes'] = (int)$getdate['minutes'];
2276 return $getdate;
2277}
2278
2279/**
2280 * Given a GMT timestamp (seconds since epoch), offsets it by
2281 * the timezone. eg 3pm in India is 3pm GMT - 7 * 3600 seconds
2282 *
2283 * @package core
2284 * @category time
2285 * @uses HOURSECS
2286 * @param int $date Timestamp in GMT
2287 * @param float|int|string $timezone timezone to calculate GMT time offset before
2288 * calculating user time, 99 is default user timezone
2289 * {@link http://docs.moodle.org/dev/Time_API#Timezone}
2290 * @return int
2291 */
2292function usertime($date, $timezone=99) {
2293
2294 $timezone = get_user_timezone_offset($timezone);
2295
2296 if (abs($timezone) > 13) {
2297 return $date;
2298 }
2299 return $date - (int)($timezone * HOURSECS);
2300}
2301
2302/**
2303 * Given a time, return the GMT timestamp of the most recent midnight
2304 * for the current user.
2305 *
2306 * @package core
2307 * @category time
2308 * @param int $date Timestamp in GMT
2309 * @param float|int|string $timezone timezone to calculate GMT time offset before
2310 * calculating user midnight time, 99 is default user timezone
2311 * {@link http://docs.moodle.org/dev/Time_API#Timezone}
2312 * @return int Returns a GMT timestamp
2313 */
2314function usergetmidnight($date, $timezone=99) {
2315
2316 $userdate = usergetdate($date, $timezone);
2317
2318 // Time of midnight of this user's day, in GMT.
2319 return make_timestamp($userdate['year'], $userdate['mon'], $userdate['mday'], 0, 0, 0, $timezone);
2320
2321}
2322
2323/**
2324 * Returns a string that prints the user's timezone
2325 *
2326 * @package core
2327 * @category time
2328 * @param float|int|string $timezone timezone to calculate GMT time offset before
2329 * calculating user timezone, 99 is default user timezone
2330 * {@link http://docs.moodle.org/dev/Time_API#Timezone}
2331 * @return string
2332 */
2333function usertimezone($timezone=99) {
2334
2335 $tz = get_user_timezone($timezone);
2336
2337 if (!is_float($tz)) {
2338 return $tz;
2339 }
2340
2341 if (abs($tz) > 13) {
2342 // Server time.
2343 return get_string('serverlocaltime');
2344 }
2345
2346 if ($tz == intval($tz)) {
2347 // Don't show .0 for whole hours.
2348 $tz = intval($tz);
2349 }
2350
2351 if ($tz == 0) {
2352 return 'UTC';
2353 } else if ($tz > 0) {
2354 return 'UTC+'.$tz;
2355 } else {
2356 return 'UTC'.$tz;
2357 }
2358
2359}
2360
2361/**
2362 * Returns a float which represents the user's timezone difference from GMT in hours
2363 * Checks various settings and picks the most dominant of those which have a value
2364 *
2365 * @package core
2366 * @category time
2367 * @param float|int|string $tz timezone to calculate GMT time offset for user,
2368 * 99 is default user timezone
2369 * {@link http://docs.moodle.org/dev/Time_API#Timezone}
2370 * @return float
2371 */
2372function get_user_timezone_offset($tz = 99) {
2373 $tz = get_user_timezone($tz);
2374
2375 if (is_float($tz)) {
2376 return $tz;
2377 } else {
2378 $tzrecord = get_timezone_record($tz);
2379 if (empty($tzrecord)) {
2380 return 99.0;
2381 }
2382 return (float)$tzrecord->gmtoff / HOURMINS;
2383 }
2384}
2385
2386/**
2387 * Returns an int which represents the systems's timezone difference from GMT in seconds
2388 *
2389 * @package core
2390 * @category time
2391 * @param float|int|string $tz timezone for which offset is required.
2392 * {@link http://docs.moodle.org/dev/Time_API#Timezone}
2393 * @return int|bool if found, false is timezone 99 or error
2394 */
2395function get_timezone_offset($tz) {
2396 if ($tz == 99) {
2397 return false;
2398 }
2399
2400 if (is_numeric($tz)) {
2401 return intval($tz * 60*60);
2402 }
2403
2404 if (!$tzrecord = get_timezone_record($tz)) {
2405 return false;
2406 }
2407 return intval($tzrecord->gmtoff * 60);
2408}
2409
2410/**
2411 * Returns a float or a string which denotes the user's timezone
2412 * 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)
2413 * means that for this timezone there are also DST rules to be taken into account
2414 * Checks various settings and picks the most dominant of those which have a value
2415 *
2416 * @package core
2417 * @category time
2418 * @param float|int|string $tz timezone to calculate GMT time offset before
2419 * calculating user timezone, 99 is default user timezone
2420 * {@link http://docs.moodle.org/dev/Time_API#Timezone}
2421 * @return float|string
2422 */
2423function get_user_timezone($tz = 99) {
2424 global $USER, $CFG;
2425
2426 $timezones = array(
2427 $tz,
2428 isset($CFG->forcetimezone) ? $CFG->forcetimezone : 99,
2429 isset($USER->timezone) ? $USER->timezone : 99,
2430 isset($CFG->timezone) ? $CFG->timezone : 99,
2431 );
2432
2433 $tz = 99;
2434
2435 // Loop while $tz is, empty but not zero, or 99, and there is another timezone is the array.
2436 while (((empty($tz) && !is_numeric($tz)) || $tz == 99) && $next = each($timezones)) {
2437 $tz = $next['value'];
2438 }
2439 return is_numeric($tz) ? (float) $tz : $tz;
2440}
2441
2442/**
2443 * Returns cached timezone record for given $timezonename
2444 *
2445 * @package core
2446 * @param string $timezonename name of the timezone
2447 * @return stdClass|bool timezonerecord or false
2448 */
2449function get_timezone_record($timezonename) {
2450 global $DB;
2451 static $cache = null;
2452
2453 if ($cache === null) {
2454 $cache = array();
2455 }
2456
2457 if (isset($cache[$timezonename])) {
2458 return $cache[$timezonename];
2459 }
2460
2461 return $cache[$timezonename] = $DB->get_record_sql('SELECT * FROM {timezone}
2462 WHERE name = ? ORDER BY year DESC', array($timezonename), IGNORE_MULTIPLE);
2463}
2464
2465/**
2466 * Build and store the users Daylight Saving Time (DST) table
2467 *
2468 * @package core
2469 * @param int $fromyear Start year for the table, defaults to 1971
2470 * @param int $toyear End year for the table, defaults to 2035
2471 * @param int|float|string $strtimezone timezone to check if dst should be applied.
2472 * @return bool
2473 */
2474function calculate_user_dst_table($fromyear = null, $toyear = null, $strtimezone = null) {
2475 global $SESSION, $DB;
2476
2477 $usertz = get_user_timezone($strtimezone);
2478
2479 if (is_float($usertz)) {
2480 // Trivial timezone, no DST.
2481 return false;
2482 }
2483
2484 if (!empty($SESSION->dst_offsettz) && $SESSION->dst_offsettz != $usertz) {
2485 // We have pre-calculated values, but the user's effective TZ has changed in the meantime, so reset.
2486 unset($SESSION->dst_offsets);
2487 unset($SESSION->dst_range);
2488 }
2489
2490 if (!empty($SESSION->dst_offsets) && empty($fromyear) && empty($toyear)) {
2491 // Repeat calls which do not request specific year ranges stop here, we have already calculated the table.
2492 // This will be the return path most of the time, pretty light computationally.
2493 return true;
2494 }
2495
2496 // Reaching here means we either need to extend our table or create it from scratch.
2497
2498 // Remember which TZ we calculated these changes for.
2499 $SESSION->dst_offsettz = $usertz;
2500
2501 if (empty($SESSION->dst_offsets)) {
2502 // If we 're creating from scratch, put the two guard elements in there.
2503 $SESSION->dst_offsets = array(1 => null, 0 => null);
2504 }
2505 if (empty($SESSION->dst_range)) {
2506 // If creating from scratch.
2507 $from = max((empty($fromyear) ? intval(date('Y')) - 3 : $fromyear), 1971);
2508 $to = min((empty($toyear) ? intval(date('Y')) + 3 : $toyear), 2035);
2509
2510 // Fill in the array with the extra years we need to process.
2511 $yearstoprocess = array();
2512 for ($i = $from; $i <= $to; ++$i) {
2513 $yearstoprocess[] = $i;
2514 }
2515
2516 // Take note of which years we have processed for future calls.
2517 $SESSION->dst_range = array($from, $to);
2518 } else {
2519 // If needing to extend the table, do the same.
2520 $yearstoprocess = array();
2521
2522 $from = max((empty($fromyear) ? $SESSION->dst_range[0] : $fromyear), 1971);
2523 $to = min((empty($toyear) ? $SESSION->dst_range[1] : $toyear), 2035);
2524
2525 if ($from < $SESSION->dst_range[0]) {
2526 // Take note of which years we need to process and then note that we have processed them for future calls.
2527 for ($i = $from; $i < $SESSION->dst_range[0]; ++$i) {
2528 $yearstoprocess[] = $i;
2529 }
2530 $SESSION->dst_range[0] = $from;
2531 }
2532 if ($to > $SESSION->dst_range[1]) {
2533 // Take note of which years we need to process and then note that we have processed them for future calls.
2534 for ($i = $SESSION->dst_range[1] + 1; $i <= $to; ++$i) {
2535 $yearstoprocess[] = $i;
2536 }
2537 $SESSION->dst_range[1] = $to;
2538 }
2539 }
2540
2541 if (empty($yearstoprocess)) {
2542 // This means that there was a call requesting a SMALLER range than we have already calculated.
2543 return true;
2544 }
2545
2546 // From now on, we know that the array has at least the two guard elements, and $yearstoprocess has the years we need
2547 // Also, the array is sorted in descending timestamp order!
2548
2549 // Get DB data.
2550
2551 static $presetscache = array();
2552 if (!isset($presetscache[$usertz])) {
2553 $presetscache[$usertz] = $DB->get_records('timezone', array('name' => $usertz),
2554 'year DESC', 'year, gmtoff, dstoff, dst_month, dst_startday, dst_weekday, dst_skipweeks, dst_time, std_month, '.
2555 'std_startday, std_weekday, std_skipweeks, std_time');
2556 }
2557 if (empty($presetscache[$usertz])) {
2558 return false;
2559 }
2560
2561 // Remove ending guard (first element of the array).
2562 reset($SESSION->dst_offsets);
2563 unset($SESSION->dst_offsets[key($SESSION->dst_offsets)]);
2564
2565 // Add all required change timestamps.
2566 foreach ($yearstoprocess as $y) {
2567 // Find the record which is in effect for the year $y.
2568 foreach ($presetscache[$usertz] as $year => $preset) {
2569 if ($year <= $y) {
2570 break;
2571 }
2572 }
2573
2574 $changes = dst_changes_for_year($y, $preset);
2575
2576 if ($changes === null) {
2577 continue;
2578 }
2579 if ($changes['dst'] != 0) {
2580 $SESSION->dst_offsets[$changes['dst']] = $preset->dstoff * MINSECS;
2581 }
2582 if ($changes['std'] != 0) {
2583 $SESSION->dst_offsets[$changes['std']] = 0;
2584 }
2585 }
2586
2587 // Put in a guard element at the top.
2588 $maxtimestamp = max(array_keys($SESSION->dst_offsets));
2589 $SESSION->dst_offsets[($maxtimestamp + DAYSECS)] = null; // DAYSECS is arbitrary, any "small" number will do.
2590
2591 // Sort again.
2592 krsort($SESSION->dst_offsets);
2593
2594 return true;
2595}
2596
2597/**
2598 * Calculates the required DST change and returns a Timestamp Array
2599 *
2600 * @package core
2601 * @category time
2602 * @uses HOURSECS
2603 * @uses MINSECS
2604 * @param int|string $year Int or String Year to focus on
2605 * @param object $timezone Instatiated Timezone object
2606 * @return array|null Array dst => xx, 0 => xx, std => yy, 1 => yy or null
2607 */
2608function dst_changes_for_year($year, $timezone) {
2609
2610 if ($timezone->dst_startday == 0 && $timezone->dst_weekday == 0 &&
2611 $timezone->std_startday == 0 && $timezone->std_weekday == 0) {
2612 return null;
2613 }
2614
2615 $monthdaydst = find_day_in_month($timezone->dst_startday, $timezone->dst_weekday, $timezone->dst_month, $year);
2616 $monthdaystd = find_day_in_month($timezone->std_startday, $timezone->std_weekday, $timezone->std_month, $year);
2617
2618 list($dsthour, $dstmin) = explode(':', $timezone->dst_time);
2619 list($stdhour, $stdmin) = explode(':', $timezone->std_time);
2620
2621 $timedst = make_timestamp($year, $timezone->dst_month, $monthdaydst, 0, 0, 0, 99, false);
2622 $timestd = make_timestamp($year, $timezone->std_month, $monthdaystd, 0, 0, 0, 99, false);
2623
2624 // Instead of putting hour and minute in make_timestamp(), we add them afterwards.
2625 // This has the advantage of being able to have negative values for hour, i.e. for timezones
2626 // where GMT time would be in the PREVIOUS day than the local one on which DST changes.
2627
2628 $timedst += $dsthour * HOURSECS + $dstmin * MINSECS;
2629 $timestd += $stdhour * HOURSECS + $stdmin * MINSECS;
2630
2631 return array('dst' => $timedst, 0 => $timedst, 'std' => $timestd, 1 => $timestd);
2632}
2633
2634/**
2635 * Calculates the Daylight Saving Offset for a given date/time (timestamp)
2636 * - Note: Daylight saving only works for string timezones and not for float.
2637 *
2638 * @package core
2639 * @category time
2640 * @param int $time must NOT be compensated at all, it has to be a pure timestamp
2641 * @param int|float|string $strtimezone timezone for which offset is expected, if 99 or null
2642 * then user's default timezone is used. {@link http://docs.moodle.org/dev/Time_API#Timezone}
2643 * @return int
2644 */
2645function dst_offset_on($time, $strtimezone = null) {
2646 global $SESSION;
2647
2648 if (!calculate_user_dst_table(null, null, $strtimezone) || empty($SESSION->dst_offsets)) {
2649 return 0;
2650 }
2651
2652 reset($SESSION->dst_offsets);
2653 while (list($from, $offset) = each($SESSION->dst_offsets)) {
2654 if ($from <= $time) {
2655 break;
2656 }
2657 }
2658
2659 // This is the normal return path.
2660 if ($offset !== null) {
2661 return $offset;
2662 }
2663
2664 // Reaching this point means we haven't calculated far enough, do it now:
2665 // Calculate extra DST changes if needed and recurse. The recursion always
2666 // moves toward the stopping condition, so will always end.
2667
2668 if ($from == 0) {
2669 // We need a year smaller than $SESSION->dst_range[0].
2670 if ($SESSION->dst_range[0] == 1971) {
2671 return 0;
2672 }
2673 calculate_user_dst_table($SESSION->dst_range[0] - 5, null, $strtimezone);
2674 return dst_offset_on($time, $strtimezone);
2675 } else {
2676 // We need a year larger than $SESSION->dst_range[1].
2677 if ($SESSION->dst_range[1] == 2035) {
2678 return 0;
2679 }
2680 calculate_user_dst_table(null, $SESSION->dst_range[1] + 5, $strtimezone);
2681 return dst_offset_on($time, $strtimezone);
2682 }
2683}
2684
2685/**
2686 * Calculates when the day appears in specific month
2687 *
2688 * @package core
2689 * @category time
2690 * @param int $startday starting day of the month
2691 * @param int $weekday The day when week starts (normally taken from user preferences)
2692 * @param int $month The month whose day is sought
2693 * @param int $year The year of the month whose day is sought
2694 * @return int
2695 */
2696function find_day_in_month($startday, $weekday, $month, $year) {
2697 $calendartype = \core_calendar\type_factory::get_calendar_instance();
2698
2699 $daysinmonth = days_in_month($month, $year);
2700 $daysinweek = count($calendartype->get_weekdays());
2701
2702 if ($weekday == -1) {
2703 // Don't care about weekday, so return:
2704 // abs($startday) if $startday != -1
2705 // $daysinmonth otherwise.
2706 return ($startday == -1) ? $daysinmonth : abs($startday);
2707 }
2708
2709 // From now on we 're looking for a specific weekday.
2710 // Give "end of month" its actual value, since we know it.
2711 if ($startday == -1) {
2712 $startday = -1 * $daysinmonth;
2713 }
2714
2715 // Starting from day $startday, the sign is the direction.
2716 if ($startday < 1) {
2717 $startday = abs($startday);
2718 $lastmonthweekday = dayofweek($daysinmonth, $month, $year);
2719
2720 // This is the last such weekday of the month.
2721 $lastinmonth = $daysinmonth + $weekday - $lastmonthweekday;
2722 if ($lastinmonth > $daysinmonth) {
2723 $lastinmonth -= $daysinweek;
2724 }
2725
2726 // Find the first such weekday <= $startday.
2727 while ($lastinmonth > $startday) {
2728 $lastinmonth -= $daysinweek;
2729 }
2730
2731 return $lastinmonth;
2732 } else {
2733 $indexweekday = dayofweek($startday, $month, $year);
2734
2735 $diff = $weekday - $indexweekday;
2736 if ($diff < 0) {
2737 $diff += $daysinweek;
2738 }
2739
2740 // This is the first such weekday of the month equal to or after $startday.
2741 $firstfromindex = $startday + $diff;
2742
2743 return $firstfromindex;
2744 }
2745}
2746
2747/**
2748 * Calculate the number of days in a given month
2749 *
2750 * @package core
2751 * @category time
2752 * @param int $month The month whose day count is sought
2753 * @param int $year The year of the month whose day count is sought
2754 * @return int
2755 */
2756function days_in_month($month, $year) {
2757 $calendartype = \core_calendar\type_factory::get_calendar_instance();
2758 return $calendartype->get_num_days_in_month($year, $month);
2759}
2760
2761/**
2762 * Calculate the position in the week of a specific calendar day
2763 *
2764 * @package core
2765 * @category time
2766 * @param int $day The day of the date whose position in the week is sought
2767 * @param int $month The month of the date whose position in the week is sought
2768 * @param int $year The year of the date whose position in the week is sought
2769 * @return int
2770 */
2771function dayofweek($day, $month, $year) {
2772 $calendartype = \core_calendar\type_factory::get_calendar_instance();
2773 return $calendartype->get_weekday($year, $month, $day);
2774}
2775
2776// USER AUTHENTICATION AND LOGIN.
2777
2778/**
2779 * Returns full login url.
2780 *
2781 * @return string login url
2782 */
2783function get_login_url() {
2784 global $CFG;
2785
2786 $url = "$CFG->wwwroot/login/index.php";
2787
2788 if (!empty($CFG->loginhttps)) {
2789 $url = str_replace('http:', 'https:', $url);
2790 }
2791
2792 return $url;
2793}
2794
2795/**
2796 * This function checks that the current user is logged in and has the
2797 * required privileges
2798 *
2799 * This function checks that the current user is logged in, and optionally
2800 * whether they are allowed to be in a particular course and view a particular
2801 * course module.
2802 * If they are not logged in, then it redirects them to the site login unless
2803 * $autologinguest is set and {@link $CFG}->autologinguests is set to 1 in which
2804 * case they are automatically logged in as guests.
2805 * If $courseid is given and the user is not enrolled in that course then the
2806 * user is redirected to the course enrolment page.
2807 * If $cm is given and the course module is hidden and the user is not a teacher
2808 * in the course then the user is redirected to the course home page.
2809 *
2810 * When $cm parameter specified, this function sets page layout to 'module'.
2811 * You need to change it manually later if some other layout needed.
2812 *
2813 * @package core_access
2814 * @category access
2815 *
2816 * @param mixed $courseorid id of the course or course object
2817 * @param bool $autologinguest default true
2818 * @param object $cm course module object
2819 * @param bool $setwantsurltome Define if we want to set $SESSION->wantsurl, defaults to
2820 * true. Used to avoid (=false) some scripts (file.php...) to set that variable,
2821 * in order to keep redirects working properly. MDL-14495
2822 * @param bool $preventredirect set to true in scripts that can not redirect (CLI, rss feeds, etc.), throws exceptions
2823 * @return mixed Void, exit, and die depending on path
2824 * @throws coding_exception
2825 * @throws require_login_exception
2826 */
2827function require_login($courseorid = null, $autologinguest = true, $cm = null, $setwantsurltome = true, $preventredirect = false) {
2828 global $CFG, $SESSION, $USER, $PAGE, $SITE, $DB, $OUTPUT;
2829
2830 // Must not redirect when byteserving already started.
2831 if (!empty($_SERVER['HTTP_RANGE'])) {
2832 $preventredirect = true;
2833 }
2834
2835 // Setup global $COURSE, themes, language and locale.
2836 if (!empty($courseorid)) {
2837 if (is_object($courseorid)) {
2838 $course = $courseorid;
2839 } else if ($courseorid == SITEID) {
2840 $course = clone($SITE);
2841 } else {
2842 $course = $DB->get_record('course', array('id' => $courseorid), '*', MUST_EXIST);
2843 }
2844 if ($cm) {
2845 if ($cm->course != $course->id) {
2846 throw new coding_exception('course and cm parameters in require_login() call do not match!!');
2847 }
2848 // Make sure we have a $cm from get_fast_modinfo as this contains activity access details.
2849 if (!($cm instanceof cm_info)) {
2850 // Note: nearly all pages call get_fast_modinfo anyway and it does not make any
2851 // db queries so this is not really a performance concern, however it is obviously
2852 // better if you use get_fast_modinfo to get the cm before calling this.
2853 $modinfo = get_fast_modinfo($course);
2854 $cm = $modinfo->get_cm($cm->id);
2855 }
2856 $PAGE->set_cm($cm, $course); // Set's up global $COURSE.
2857 $PAGE->set_pagelayout('incourse');
2858 } else {
2859 $PAGE->set_course($course); // Set's up global $COURSE.
2860 }
2861 } else {
2862 // Do not touch global $COURSE via $PAGE->set_course(),
2863 // the reasons is we need to be able to call require_login() at any time!!
2864 $course = $SITE;
2865 if ($cm) {
2866 throw new coding_exception('cm parameter in require_login() requires valid course parameter!');
2867 }
2868 }
2869
2870 // If this is an AJAX request and $setwantsurltome is true then we need to override it and set it to false.
2871 // Otherwise the AJAX request URL will be set to $SESSION->wantsurl and events such as self enrolment in the future
2872 // risk leading the user back to the AJAX request URL.
2873 if ($setwantsurltome && defined('AJAX_SCRIPT') && AJAX_SCRIPT) {
2874 $setwantsurltome = false;
2875 }
2876
2877 // Redirect to the login page if session has expired, only with dbsessions enabled (MDL-35029) to maintain current behaviour.
2878 if ((!isloggedin() or isguestuser()) && !empty($SESSION->has_timed_out) && !$preventredirect && !empty($CFG->dbsessions)) {
2879 if ($setwantsurltome) {
2880 $SESSION->wantsurl = qualified_me();
2881 }
2882 redirect(get_login_url());
2883 }
2884
2885 // If the user is not even logged in yet then make sure they are.
2886 if (!isloggedin()) {
2887 if ($autologinguest and !empty($CFG->guestloginbutton) and !empty($CFG->autologinguests)) {
2888 if (!$guest = get_complete_user_data('id', $CFG->siteguest)) {
2889 // Misconfigured site guest, just redirect to login page.
2890 redirect(get_login_url());
2891 exit; // Never reached.
2892 }
2893 $lang = isset($SESSION->lang) ? $SESSION->lang : $CFG->lang;
2894 complete_user_login($guest);
2895 $USER->autologinguest = true;
2896 $SESSION->lang = $lang;
2897 } else {
2898 // NOTE: $USER->site check was obsoleted by session test cookie, $USER->confirmed test is in login/index.php.
2899 if ($preventredirect) {
2900 throw new require_login_exception('You are not logged in');
2901 }
2902
2903 if ($setwantsurltome) {
2904 $SESSION->wantsurl = qualified_me();
2905 }
2906 if (!empty($_SERVER['HTTP_REFERER'])) {
2907 $SESSION->fromurl = $_SERVER['HTTP_REFERER'];
2908 }
2909 redirect(get_login_url());
2910 exit; // Never reached.
2911 }
2912 }
2913
2914 // Loginas as redirection if needed.
2915 if ($course->id != SITEID and \core\session\manager::is_loggedinas()) {
2916 if ($USER->loginascontext->contextlevel == CONTEXT_COURSE) {
2917 if ($USER->loginascontext->instanceid != $course->id) {
2918 print_error('loginasonecourse', '', $CFG->wwwroot.'/course/view.php?id='.$USER->loginascontext->instanceid);
2919 }
2920 }
2921 }
2922
2923 // Check whether the user should be changing password (but only if it is REALLY them).
2924 if (get_user_preferences('auth_forcepasswordchange') && !\core\session\manager::is_loggedinas()) {
2925 $userauth = get_auth_plugin($USER->auth);
2926 if ($userauth->can_change_password() and !$preventredirect) {
2927 if ($setwantsurltome) {
2928 $SESSION->wantsurl = qualified_me();
2929 }
2930 if ($changeurl = $userauth->change_password_url()) {
2931 // Use plugin custom url.
2932 redirect($changeurl);
2933 } else {
2934 // Use moodle internal method.
2935 if (empty($CFG->loginhttps)) {
2936 redirect($CFG->wwwroot .'/login/change_password.php');
2937 } else {
2938 $wwwroot = str_replace('http:', 'https:', $CFG->wwwroot);
2939 redirect($wwwroot .'/login/change_password.php');
2940 }
2941 }
2942 } else {
2943 print_error('nopasswordchangeforced', 'auth');
2944 }
2945 }
2946
2947 // Check that the user account is properly set up.
2948 if (user_not_fully_set_up($USER)) {
2949 if ($preventredirect) {
2950 throw new require_login_exception('User not fully set-up');
2951 }
2952 if ($setwantsurltome) {
2953 $SESSION->wantsurl = qualified_me();
2954 }
2955 redirect($CFG->wwwroot .'/user/edit.php?id='. $USER->id .'&course='. SITEID);
2956 }
2957
2958 // Make sure the USER has a sesskey set up. Used for CSRF protection.
2959 sesskey();
2960
2961 // Do not bother admins with any formalities.
2962 if (is_siteadmin()) {
2963 // Set accesstime or the user will appear offline which messes up messaging.
2964 user_accesstime_log($course->id);
2965 return;
2966 }
2967
2968 // Check that the user has agreed to a site policy if there is one - do not test in case of admins.
2969 if (!$USER->policyagreed and !is_siteadmin()) {
2970 if (!empty($CFG->sitepolicy) and !isguestuser()) {
2971 if ($preventredirect) {
2972 throw new require_login_exception('Policy not agreed');
2973 }
2974 if ($setwantsurltome) {
2975 $SESSION->wantsurl = qualified_me();
2976 }
2977 redirect($CFG->wwwroot .'/user/policy.php');
2978 } else if (!empty($CFG->sitepolicyguest) and isguestuser()) {
2979 if ($preventredirect) {
2980 throw new require_login_exception('Policy not agreed');
2981 }
2982 if ($setwantsurltome) {
2983 $SESSION->wantsurl = qualified_me();
2984 }
2985 redirect($CFG->wwwroot .'/user/policy.php');
2986 }
2987 }
2988
2989 // Fetch the system context, the course context, and prefetch its child contexts.
2990 $sysctx = context_system::instance();
2991 $coursecontext = context_course::instance($course->id, MUST_EXIST);
2992 if ($cm) {
2993 $cmcontext = context_module::instance($cm->id, MUST_EXIST);
2994 } else {
2995 $cmcontext = null;
2996 }
2997
2998 // If the site is currently under maintenance, then print a message.
2999 if (!empty($CFG->maintenance_enabled) and !has_capability('moodle/site:config', $sysctx)) {
3000 if ($preventredirect) {
3001 throw new require_login_exception('Maintenance in progress');
3002 }
3003
3004 print_maintenance_message();
3005 }
3006
3007 // Make sure the course itself is not hidden.
3008 if ($course->id == SITEID) {
3009 // Frontpage can not be hidden.
3010 } else {
3011 if (is_role_switched($course->id)) {
3012 // When switching roles ignore the hidden flag - user had to be in course to do the switch.
3013 } else {
3014 if (!$course->visible and !has_capability('moodle/course:viewhiddencourses', $coursecontext)) {
3015 // Originally there was also test of parent category visibility, BUT is was very slow in complex queries
3016 // involving "my courses" now it is also possible to simply hide all courses user is not enrolled in :-).
3017 if ($preventredirect) {
3018 throw new require_login_exception('Course is hidden');
3019 }
3020 // We need to override the navigation URL as the course won't have been added to the navigation and thus
3021 // the navigation will mess up when trying to find it.
3022 navigation_node::override_active_url(new moodle_url('/'));
3023 notice(get_string('coursehidden'), $CFG->wwwroot .'/');
3024 }
3025 }
3026 }
3027
3028 // Is the user enrolled?
3029 if ($course->id == SITEID) {
3030 // Everybody is enrolled on the frontpage.
3031 } else {
3032 if (\core\session\manager::is_loggedinas()) {
3033 // Make sure the REAL person can access this course first.
3034 $realuser = \core\session\manager::get_realuser();
3035 if (!is_enrolled($coursecontext, $realuser->id, '', true) and
3036 !is_viewing($coursecontext, $realuser->id) and !is_siteadmin($realuser->id)) {
3037 if ($preventredirect) {
3038 throw new require_login_exception('Invalid course login-as access');
3039 }
3040 echo $OUTPUT->header();
3041 notice(get_string('studentnotallowed', '', fullname($USER, true)), $CFG->wwwroot .'/');
3042 }
3043 }
3044
3045 $access = false;
3046
3047 if (is_role_switched($course->id)) {
3048 // Ok, user had to be inside this course before the switch.
3049 $access = true;
3050
3051 } else if (is_viewing($coursecontext, $USER)) {
3052 // Ok, no need to mess with enrol.
3053 $access = true;
3054
3055 } else {
3056 if (isset($USER->enrol['enrolled'][$course->id])) {
3057 if ($USER->enrol['enrolled'][$course->id] > time()) {
3058 $access = true;
3059 if (isset($USER->enrol['tempguest'][$course->id])) {
3060 unset($USER->enrol['tempguest'][$course->id]);
3061 remove_temp_course_roles($coursecontext);
3062 }
3063 } else {
3064 // Expired.
3065 unset($USER->enrol['enrolled'][$course->id]);
3066 }
3067 }
3068 if (isset($USER->enrol['tempguest'][$course->id])) {
3069 if ($USER->enrol['tempguest'][$course->id] == 0) {
3070 $access = true;
3071 } else if ($USER->enrol['tempguest'][$course->id] > time()) {
3072 $access = true;
3073 } else {
3074 // Expired.
3075 unset($USER->enrol['tempguest'][$course->id]);
3076 remove_temp_course_roles($coursecontext);
3077 }
3078 }
3079
3080 if (!$access) {
3081 // Cache not ok.
3082 $until = enrol_get_enrolment_end($coursecontext->instanceid, $USER->id);
3083 if ($until !== false) {
3084 // Active participants may always access, a timestamp in the future, 0 (always) or false.
3085 if ($until == 0) {
3086 $until = ENROL_MAX_TIMESTAMP;
3087 }
3088 $USER->enrol['enrolled'][$course->id] = $until;
3089 $access = true;
3090
3091 } else {
3092 $params = array('courseid' => $course->id, 'status' => ENROL_INSTANCE_ENABLED);
3093 $instances = $DB->get_records('enrol', $params, 'sortorder, id ASC');
3094 $enrols = enrol_get_plugins(true);
3095 // First ask all enabled enrol instances in course if they want to auto enrol user.
3096 foreach ($instances as $instance) {
3097 if (!isset($enrols[$instance->enrol])) {
3098 continue;
3099 }
3100 // Get a duration for the enrolment, a timestamp in the future, 0 (always) or false.
3101 $until = $enrols[$instance->enrol]->try_autoenrol($instance);
3102 if ($until !== false) {
3103 if ($until == 0) {
3104 $until = ENROL_MAX_TIMESTAMP;
3105 }
3106 $USER->enrol['enrolled'][$course->id] = $until;
3107 $access = true;
3108 break;
3109 }
3110 }
3111 // If not enrolled yet try to gain temporary guest access.
3112 if (!$access) {
3113 foreach ($instances as $instance) {
3114 if (!isset($enrols[$instance->enrol])) {
3115 continue;
3116 }
3117 // Get a duration for the guest access, a timestamp in the future or false.
3118 $until = $enrols[$instance->enrol]->try_guestaccess($instance);
3119 if ($until !== false and $until > time()) {
3120 $USER->enrol['tempguest'][$course->id] = $until;
3121 $access = true;
3122 break;
3123 }
3124 }
3125 }
3126 }
3127 }
3128 }
3129
3130 if (!$access) {
3131 if ($preventredirect) {
3132 throw new require_login_exception('Not enrolled');
3133 }
3134 if ($setwantsurltome) {
3135 $SESSION->wantsurl = qualified_me();
3136 }
3137 redirect($CFG->wwwroot .'/enrol/index.php?id='. $course->id);
3138 }
3139 }
3140
3141 // Check visibility of activity to current user; includes visible flag, conditional availability, etc.
3142 if ($cm && !$cm->uservisible) {
3143 if ($preventredirect) {
3144 throw new require_login_exception('Activity is hidden');
3145 }
3146 if ($course->id != SITEID) {
3147 $url = new moodle_url('/course/view.php', array('id' => $course->id));
3148 } else {
3149 $url = new moodle_url('/');
3150 }
3151 redirect($url, get_string('activityiscurrentlyhidden'));
3152 }
3153
3154 // Finally access granted, update lastaccess times.
3155 user_accesstime_log($course->id);
3156}
3157
3158
3159/**
3160 * This function just makes sure a user is logged out.
3161 *
3162 * @package core_access
3163 * @category access
3164 */
3165function require_logout() {
3166 global $USER, $DB;
3167
3168 if (!isloggedin()) {
3169 // This should not happen often, no need for hooks or events here.
3170 \core\session\manager::terminate_current();
3171 return;
3172 }
3173
3174 // Execute hooks before action.
3175 $authplugins = array();
3176 $authsequence = get_enabled_auth_plugins();
3177 foreach ($authsequence as $authname) {
3178 $authplugins[$authname] = get_auth_plugin($authname);
3179 $authplugins[$authname]->prelogout_hook();
3180 }
3181
3182 // Store info that gets removed during logout.
3183 $sid = session_id();
3184 $event = \core\event\user_loggedout::create(
3185 array(
3186 'userid' => $USER->id,
3187 'objectid' => $USER->id,
3188 'other' => array('sessionid' => $sid),
3189 )
3190 );
3191 if ($session = $DB->get_record('sessions', array('sid'=>$sid))) {
3192 $event->add_record_snapshot('sessions', $session);
3193 }
3194
3195 // Clone of $USER object to be used by auth plugins.
3196 $user = fullclone($USER);
3197
3198 // Delete session record and drop $_SESSION content.
3199 \core\session\manager::terminate_current();
3200
3201 // Trigger event AFTER action.
3202 $event->trigger();
3203
3204 // Hook to execute auth plugins redirection after event trigger.
3205 foreach ($authplugins as $authplugin) {
3206 $authplugin->postlogout_hook($user);
3207 }
3208}
3209
3210/**
3211 * Weaker version of require_login()
3212 *
3213 * This is a weaker version of {@link require_login()} which only requires login
3214 * when called from within a course rather than the site page, unless
3215 * the forcelogin option is turned on.
3216 * @see require_login()
3217 *
3218 * @package core_access
3219 * @category access
3220 *
3221 * @param mixed $courseorid The course object or id in question
3222 * @param bool $autologinguest Allow autologin guests if that is wanted
3223 * @param object $cm Course activity module if known
3224 * @param bool $setwantsurltome Define if we want to set $SESSION->wantsurl, defaults to
3225 * true. Used to avoid (=false) some scripts (file.php...) to set that variable,
3226 * in order to keep redirects working properly. MDL-14495
3227 * @param bool $preventredirect set to true in scripts that can not redirect (CLI, rss feeds, etc.), throws exceptions
3228 * @return void
3229 * @throws coding_exception
3230 */
3231function require_course_login($courseorid, $autologinguest = true, $cm = null, $setwantsurltome = true, $preventredirect = false) {
3232 global $CFG, $PAGE, $SITE;
3233 $issite = ((is_object($courseorid) and $courseorid->id == SITEID)
3234 or (!is_object($courseorid) and $courseorid == SITEID));
3235 if ($issite && !empty($cm) && !($cm instanceof cm_info)) {
3236 // Note: nearly all pages call get_fast_modinfo anyway and it does not make any
3237 // db queries so this is not really a performance concern, however it is obviously
3238 // better if you use get_fast_modinfo to get the cm before calling this.
3239 if (is_object($courseorid)) {
3240 $course = $courseorid;
3241 } else {
3242 $course = clone($SITE);
3243 }
3244 $modinfo = get_fast_modinfo($course);
3245 $cm = $modinfo->get_cm($cm->id);
3246 }
3247 if (!empty($CFG->forcelogin)) {
3248 // Login required for both SITE and courses.
3249 require_login($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
3250
3251 } else if ($issite && !empty($cm) and !$cm->uservisible) {
3252 // Always login for hidden activities.
3253 require_login($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
3254
3255 } else if ($issite) {
3256 // Login for SITE not required.
3257 // We still need to instatiate PAGE vars properly so that things that rely on it like navigation function correctly.
3258 if (!empty($courseorid)) {
3259 if (is_object($courseorid)) {
3260 $course = $courseorid;
3261 } else {
3262 $course = clone $SITE;
3263 }
3264 if ($cm) {
3265 if ($cm->course != $course->id) {
3266 throw new coding_exception('course and cm parameters in require_course_login() call do not match!!');
3267 }
3268 $PAGE->set_cm($cm, $course);
3269 $PAGE->set_pagelayout('incourse');
3270 } else {
3271 $PAGE->set_course($course);
3272 }
3273 } else {
3274 // If $PAGE->course, and hence $PAGE->context, have not already been set up properly, set them up now.
3275 $PAGE->set_course($PAGE->course);
3276 }
3277 user_accesstime_log(SITEID);
3278 return;
3279
3280 } else {
3281 // Course login always required.
3282 require_login($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
3283 }
3284}
3285
3286/**
3287 * Require key login. Function terminates with error if key not found or incorrect.
3288 *
3289 * @uses NO_MOODLE_COOKIES
3290 * @uses PARAM_ALPHANUM
3291 * @param string $script unique script identifier
3292 * @param int $instance optional instance id
3293 * @return int Instance ID
3294 */
3295function require_user_key_login($script, $instance=null) {
3296 global $DB;
3297
3298 if (!NO_MOODLE_COOKIES) {
3299 print_error('sessioncookiesdisable');
3300 }
3301
3302 // Extra safety.
3303 \core\session\manager::write_close();
3304
3305 $keyvalue = required_param('key', PARAM_ALPHANUM);
3306
3307 if (!$key = $DB->get_record('user_private_key', array('script' => $script, 'value' => $keyvalue, 'instance' => $instance))) {
3308 print_error('invalidkey');
3309 }
3310
3311 if (!empty($key->validuntil) and $key->validuntil < time()) {
3312 print_error('expiredkey');
3313 }
3314
3315 if ($key->iprestriction) {
3316 $remoteaddr = getremoteaddr(null);
3317 if (empty($remoteaddr) or !address_in_subnet($remoteaddr, $key->iprestriction)) {
3318 print_error('ipmismatch');
3319 }
3320 }
3321
3322 if (!$user = $DB->get_record('user', array('id' => $key->userid))) {
3323 print_error('invaliduserid');
3324 }
3325
3326 // Emulate normal session.
3327 enrol_check_plugins($user);
3328 \core\session\manager::set_user($user);
3329
3330 // Note we are not using normal login.
3331 if (!defined('USER_KEY_LOGIN')) {
3332 define('USER_KEY_LOGIN', true);
3333 }
3334
3335 // Return instance id - it might be empty.
3336 return $key->instance;
3337}
3338
3339/**
3340 * Creates a new private user access key.
3341 *
3342 * @param string $script unique target identifier
3343 * @param int $userid
3344 * @param int $instance optional instance id
3345 * @param string $iprestriction optional ip restricted access
3346 * @param timestamp $validuntil key valid only until given data
3347 * @return string access key value
3348 */
3349function create_user_key($script, $userid, $instance=null, $iprestriction=null, $validuntil=null) {
3350 global $DB;
3351
3352 $key = new stdClass();
3353 $key->script = $script;
3354 $key->userid = $userid;
3355 $key->instance = $instance;
3356 $key->iprestriction = $iprestriction;
3357 $key->validuntil = $validuntil;
3358 $key->timecreated = time();
3359
3360 // Something long and unique.
3361 $key->value = md5($userid.'_'.time().random_string(40));
3362 while ($DB->record_exists('user_private_key', array('value' => $key->value))) {
3363 // Must be unique.
3364 $key->value = md5($userid.'_'.time().random_string(40));
3365 }
3366 $DB->insert_record('user_private_key', $key);
3367 return $key->value;
3368}
3369
3370/**
3371 * Delete the user's new private user access keys for a particular script.
3372 *
3373 * @param string $script unique target identifier
3374 * @param int $userid
3375 * @return void
3376 */
3377function delete_user_key($script, $userid) {
3378 global $DB;
3379 $DB->delete_records('user_private_key', array('script' => $script, 'userid' => $userid));
3380}
3381
3382/**
3383 * Gets a private user access key (and creates one if one doesn't exist).
3384 *
3385 * @param string $script unique target identifier
3386 * @param int $userid
3387 * @param int $instance optional instance id
3388 * @param string $iprestriction optional ip restricted access
3389 * @param timestamp $validuntil key valid only until given data
3390 * @return string access key value
3391 */
3392function get_user_key($script, $userid, $instance=null, $iprestriction=null, $validuntil=null) {
3393 global $DB;
3394
3395 if ($key = $DB->get_record('user_private_key', array('script' => $script, 'userid' => $userid,
3396 'instance' => $instance, 'iprestriction' => $iprestriction,
3397 'validuntil' => $validuntil))) {
3398 return $key->value;
3399 } else {
3400 return create_user_key($script, $userid, $instance, $iprestriction, $validuntil);
3401 }
3402}
3403
3404
3405/**
3406 * Modify the user table by setting the currently logged in user's last login to now.
3407 *
3408 * @return bool Always returns true
3409 */
3410function update_user_login_times() {
3411 global $USER, $DB;
3412
3413 if (isguestuser()) {
3414 // Do not update guest access times/ips for performance.
3415 return true;
3416 }
3417
3418 $now = time();
3419
3420 $user = new stdClass();
3421 $user->id = $USER->id;
3422
3423 // Make sure all users that logged in have some firstaccess.
3424 if ($USER->firstaccess == 0) {
3425 $USER->firstaccess = $user->firstaccess = $now;
3426 }
3427
3428 // Store the previous current as lastlogin.
3429 $USER->lastlogin = $user->lastlogin = $USER->currentlogin;
3430
3431 $USER->currentlogin = $user->currentlogin = $now;
3432
3433 // Function user_accesstime_log() may not update immediately, better do it here.
3434 $USER->lastaccess = $user->lastaccess = $now;
3435 $USER->lastip = $user->lastip = getremoteaddr();
3436
3437 // Note: do not call user_update_user() here because this is part of the login process,
3438 // the login event means that these fields were updated.
3439 $DB->update_record('user', $user);
3440 return true;
3441}
3442
3443/**
3444 * Determines if a user has completed setting up their account.
3445 *
3446 * @param stdClass $user A {@link $USER} object to test for the existence of a valid name and email
3447 * @return bool
3448 */
3449function user_not_fully_set_up($user) {
3450 if (isguestuser($user)) {
3451 return false;
3452 }
3453 return (empty($user->firstname) or empty($user->lastname) or empty($user->email) or over_bounce_threshold($user));
3454}
3455
3456/**
3457 * Check whether the user has exceeded the bounce threshold
3458 *
3459 * @param stdClass $user A {@link $USER} object
3460 * @return bool true => User has exceeded bounce threshold
3461 */
3462function over_bounce_threshold($user) {
3463 global $CFG, $DB;
3464
3465 if (empty($CFG->handlebounces)) {
3466 return false;
3467 }
3468
3469 if (empty($user->id)) {
3470 // No real (DB) user, nothing to do here.
3471 return false;
3472 }
3473
3474 // Set sensible defaults.
3475 if (empty($CFG->minbounces)) {
3476 $CFG->minbounces = 10;
3477 }
3478 if (empty($CFG->bounceratio)) {
3479 $CFG->bounceratio = .20;
3480 }
3481 $bouncecount = 0;
3482 $sendcount = 0;
3483 if ($bounce = $DB->get_record('user_preferences', array ('userid' => $user->id, 'name' => 'email_bounce_count'))) {
3484 $bouncecount = $bounce->value;
3485 }
3486 if ($send = $DB->get_record('user_preferences', array('userid' => $user->id, 'name' => 'email_send_count'))) {
3487 $sendcount = $send->value;
3488 }
3489 return ($bouncecount >= $CFG->minbounces && $bouncecount/$sendcount >= $CFG->bounceratio);
3490}
3491
3492/**
3493 * Used to increment or reset email sent count
3494 *
3495 * @param stdClass $user object containing an id
3496 * @param bool $reset will reset the count to 0
3497 * @return void
3498 */
3499function set_send_count($user, $reset=false) {
3500 global $DB;
3501
3502 if (empty($user->id)) {
3503 // No real (DB) user, nothing to do here.
3504 return;
3505 }
3506
3507 if ($pref = $DB->get_record('user_preferences', array('userid' => $user->id, 'name' => 'email_send_count'))) {
3508 $pref->value = (!empty($reset)) ? 0 : $pref->value+1;
3509 $DB->update_record('user_preferences', $pref);
3510 } else if (!empty($reset)) {
3511 // If it's not there and we're resetting, don't bother. Make a new one.
3512 $pref = new stdClass();
3513 $pref->name = 'email_send_count';
3514 $pref->value = 1;
3515 $pref->userid = $user->id;
3516 $DB->insert_record('user_preferences', $pref, false);
3517 }
3518}
3519
3520/**
3521 * Increment or reset user's email bounce count
3522 *
3523 * @param stdClass $user object containing an id
3524 * @param bool $reset will reset the count to 0
3525 */
3526function set_bounce_count($user, $reset=false) {
3527 global $DB;
3528
3529 if ($pref = $DB->get_record('user_preferences', array('userid' => $user->id, 'name' => 'email_bounce_count'))) {
3530 $pref->value = (!empty($reset)) ? 0 : $pref->value+1;
3531 $DB->update_record('user_preferences', $pref);
3532 } else if (!empty($reset)) {
3533 // If it's not there and we're resetting, don't bother. Make a new one.
3534 $pref = new stdClass();
3535 $pref->name = 'email_bounce_count';
3536 $pref->value = 1;
3537 $pref->userid = $user->id;
3538 $DB->insert_record('user_preferences', $pref, false);
3539 }
3540}
3541
3542/**
3543 * Determines if the logged in user is currently moving an activity
3544 *
3545 * @param int $courseid The id of the course being tested
3546 * @return bool
3547 */
3548function ismoving($courseid) {
3549 global $USER;
3550
3551 if (!empty($USER->activitycopy)) {
3552 return ($USER->activitycopycourse == $courseid);
3553 }
3554 return false;
3555}
3556
3557/**
3558 * Returns a persons full name
3559 *
3560 * Given an object containing all of the users name values, this function returns a string with the full name of the person.
3561 * The result may depend on system settings or language. 'override' will force both names to be used even if system settings
3562 * specify one.
3563 *
3564 * @param stdClass $user A {@link $USER} object to get full name of.
3565 * @param bool $override If true then the name will be firstname followed by lastname rather than adhering to fullnamedisplay.
3566 * @return string
3567 */
3568function fullname($user, $override=false) {
3569 global $CFG, $SESSION;
3570
3571 if (!isset($user->firstname) and !isset($user->lastname)) {
3572 return '';
3573 }
3574
3575 // Get all of the name fields.
3576 $allnames = get_all_user_name_fields();
3577 if ($CFG->debugdeveloper) {
3578 foreach ($allnames as $allname) {
3579 if (!array_key_exists($allname, $user)) {
3580 // If all the user name fields are not set in the user object, then notify the programmer that it needs to be fixed.
3581 debugging('You need to update your sql to include additional name fields in the user object.', DEBUG_DEVELOPER);
3582 // Message has been sent, no point in sending the message multiple times.
3583 break;
3584 }
3585 }
3586 }
3587
3588 if (!$override) {
3589 if (!empty($CFG->forcefirstname)) {
3590 $user->firstname = $CFG->forcefirstname;
3591 }
3592 if (!empty($CFG->forcelastname)) {
3593 $user->lastname = $CFG->forcelastname;
3594 }
3595 }
3596
3597 if (!empty($SESSION->fullnamedisplay)) {
3598 $CFG->fullnamedisplay = $SESSION->fullnamedisplay;
3599 }
3600
3601 $template = null;
3602 // If the fullnamedisplay setting is available, set the template to that.
3603 if (isset($CFG->fullnamedisplay)) {
3604 $template = $CFG->fullnamedisplay;
3605 }
3606 // If the template is empty, or set to language, return the language string.
3607 if ((empty($template) || $template == 'language') && !$override) {
3608 return get_string('fullnamedisplay', null, $user);
3609 }
3610
3611 // Check to see if we are displaying according to the alternative full name format.
3612 if ($override) {
3613 if (empty($CFG->alternativefullnameformat) || $CFG->alternativefullnameformat == 'language') {
3614 // Default to show just the user names according to the fullnamedisplay string.
3615 return get_string('fullnamedisplay', null, $user);
3616 } else {
3617 // If the override is true, then change the template to use the complete name.
3618 $template = $CFG->alternativefullnameformat;
3619 }
3620 }
3621
3622 $requirednames = array();
3623 // With each name, see if it is in the display name template, and add it to the required names array if it is.
3624 foreach ($allnames as $allname) {
3625 if (strpos($template, $allname) !== false) {
3626 $requirednames[] = $allname;
3627 }
3628 }
3629
3630 $displayname = $template;
3631 // Switch in the actual data into the template.
3632 foreach ($requirednames as $altname) {
3633 if (isset($user->$altname)) {
3634 // Using empty() on the below if statement causes breakages.
3635 if ((string)$user->$altname == '') {
3636 $displayname = str_replace($altname, 'EMPTY', $displayname);
3637 } else {
3638 $displayname = str_replace($altname, $user->$altname, $displayname);
3639 }
3640 } else {
3641 $displayname = str_replace($altname, 'EMPTY', $displayname);
3642 }
3643 }
3644 // Tidy up any misc. characters (Not perfect, but gets most characters).
3645 // Don't remove the "u" at the end of the first expression unless you want garbled characters when combining hiragana or
3646 // katakana and parenthesis.
3647 $patterns = array();
3648 // This regular expression replacement is to fix problems such as 'James () Kirk' Where 'Tiberius' (middlename) has not been
3649 // filled in by a user.
3650 // The special characters are Japanese brackets that are common enough to make allowances for them (not covered by :punct:).
3651 $patterns[] = '/[[:punct:]гЂЊгЂЌ]*EMPTY[[:punct:]гЂЊгЂЌ]*/u';
3652 // This regular expression is to remove any double spaces in the display name.
3653 $patterns[] = '/\s{2,}/u';
3654 foreach ($patterns as $pattern) {
3655 $displayname = preg_replace($pattern, ' ', $displayname);
3656 }
3657
3658 // Trimming $displayname will help the next check to ensure that we don't have a display name with spaces.
3659 $displayname = trim($displayname);
3660 if (empty($displayname)) {
3661 // Going with just the first name if no alternate fields are filled out. May be changed later depending on what
3662 // people in general feel is a good setting to fall back on.
3663 $displayname = $user->firstname;
3664 }
3665 return $displayname;
3666}
3667
3668/**
3669 * A centralised location for the all name fields. Returns an array / sql string snippet.
3670 *
3671 * @param bool $returnsql True for an sql select field snippet.
3672 * @param string $tableprefix table query prefix to use in front of each field.
3673 * @param string $prefix prefix added to the name fields e.g. authorfirstname.
3674 * @param string $fieldprefix sql field prefix e.g. id AS userid.
3675 * @param bool $order moves firstname and lastname to the top of the array / start of the string.
3676 * @return array|string All name fields.
3677 */
3678function get_all_user_name_fields($returnsql = false, $tableprefix = null, $prefix = null, $fieldprefix = null, $order = false) {
3679 // This array is provided in this order because when called by fullname() (above) if firstname is before
3680 // firstnamephonetic str_replace() will change the wrong placeholder.
3681 $alternatenames = array('firstnamephonetic' => 'firstnamephonetic',
3682 'lastnamephonetic' => 'lastnamephonetic',
3683 'middlename' => 'middlename',
3684 'alternatename' => 'alternatename',
3685 'firstname' => 'firstname',
3686 'lastname' => 'lastname');
3687
3688 // Let's add a prefix to the array of user name fields if provided.
3689 if ($prefix) {
3690 foreach ($alternatenames as $key => $altname) {
3691 $alternatenames[$key] = $prefix . $altname;
3692 }
3693 }
3694
3695 // If we want the end result to have firstname and lastname at the front / top of the result.
3696 if ($order) {
3697 // Move the last two elements (firstname, lastname) off the array and put them at the top.
3698 for ($i = 0; $i < 2; $i++) {
3699 // Get the last element.
3700 $lastelement = end($alternatenames);
3701 // Remove it from the array.
3702 unset($alternatenames[$lastelement]);
3703 // Put the element back on the top of the array.
3704 $alternatenames = array_merge(array($lastelement => $lastelement), $alternatenames);
3705 }
3706 }
3707
3708 // Create an sql field snippet if requested.
3709 if ($returnsql) {
3710 if ($tableprefix) {
3711 if ($fieldprefix) {
3712 foreach ($alternatenames as $key => $altname) {
3713 $alternatenames[$key] = $tableprefix . '.' . $altname . ' AS ' . $fieldprefix . $altname;
3714 }
3715 } else {
3716 foreach ($alternatenames as $key => $altname) {
3717 $alternatenames[$key] = $tableprefix . '.' . $altname;
3718 }
3719 }
3720 }
3721 $alternatenames = implode(',', $alternatenames);
3722 }
3723 return $alternatenames;
3724}
3725
3726/**
3727 * Reduces lines of duplicated code for getting user name fields.
3728 *
3729 * See also {@link user_picture::unalias()}
3730 *
3731 * @param object $addtoobject Object to add user name fields to.
3732 * @param object $secondobject Object that contains user name field information.
3733 * @param string $prefix prefix to be added to all fields (including $additionalfields) e.g. authorfirstname.
3734 * @param array $additionalfields Additional fields to be matched with data in the second object.
3735 * The key can be set to the user table field name.
3736 * @return object User name fields.
3737 */
3738function username_load_fields_from_object($addtoobject, $secondobject, $prefix = null, $additionalfields = null) {
3739 $fields = get_all_user_name_fields(false, null, $prefix);
3740 if ($additionalfields) {
3741 // Additional fields can specify their own 'alias' such as 'id' => 'userid'. This checks to see if
3742 // the key is a number and then sets the key to the array value.
3743 foreach ($additionalfields as $key => $value) {
3744 if (is_numeric($key)) {
3745 $additionalfields[$value] = $prefix . $value;
3746 unset($additionalfields[$key]);
3747 } else {
3748 $additionalfields[$key] = $prefix . $value;
3749 }
3750 }
3751 $fields = array_merge($fields, $additionalfields);
3752 }
3753 foreach ($fields as $key => $field) {
3754 // Important that we have all of the user name fields present in the object that we are sending back.
3755 $addtoobject->$key = '';
3756 if (isset($secondobject->$field)) {
3757 $addtoobject->$key = $secondobject->$field;
3758 }
3759 }
3760 return $addtoobject;
3761}
3762
3763/**
3764 * Returns an array of values in order of occurance in a provided string.
3765 * The key in the result is the character postion in the string.
3766 *
3767 * @param array $values Values to be found in the string format
3768 * @param string $stringformat The string which may contain values being searched for.
3769 * @return array An array of values in order according to placement in the string format.
3770 */
3771function order_in_string($values, $stringformat) {
3772 $valuearray = array();
3773 foreach ($values as $value) {
3774 $pattern = "/$value\b/";
3775 // Using preg_match as strpos() may match values that are similar e.g. firstname and firstnamephonetic.
3776 if (preg_match($pattern, $stringformat)) {
3777 $replacement = "thing";
3778 // Replace the value with something more unique to ensure we get the right position when using strpos().
3779 $newformat = preg_replace($pattern, $replacement, $stringformat);
3780 $position = strpos($newformat, $replacement);
3781 $valuearray[$position] = $value;
3782 }
3783 }
3784 ksort($valuearray);
3785 return $valuearray;
3786}
3787
3788/**
3789 * Checks if current user is shown any extra fields when listing users.
3790 *
3791 * @param object $context Context
3792 * @param array $already Array of fields that we're going to show anyway
3793 * so don't bother listing them
3794 * @return array Array of field names from user table, not including anything
3795 * listed in $already
3796 */
3797function get_extra_user_fields($context, $already = array()) {
3798 global $CFG;
3799
3800 // Only users with permission get the extra fields.
3801 if (!has_capability('moodle/site:viewuseridentity', $context)) {
3802 return array();
3803 }
3804
3805 // Split showuseridentity on comma.
3806 if (empty($CFG->showuseridentity)) {
3807 // Explode gives wrong result with empty string.
3808 $extra = array();
3809 } else {
3810 $extra = explode(',', $CFG->showuseridentity);
3811 }
3812 $renumber = false;
3813 foreach ($extra as $key => $field) {
3814 if (in_array($field, $already)) {
3815 unset($extra[$key]);
3816 $renumber = true;
3817 }
3818 }
3819 if ($renumber) {
3820 // For consistency, if entries are removed from array, renumber it
3821 // so they are numbered as you would expect.
3822 $extra = array_merge($extra);
3823 }
3824 return $extra;
3825}
3826
3827/**
3828 * If the current user is to be shown extra user fields when listing or
3829 * selecting users, returns a string suitable for including in an SQL select
3830 * clause to retrieve those fields.
3831 *
3832 * @param context $context Context
3833 * @param string $alias Alias of user table, e.g. 'u' (default none)
3834 * @param string $prefix Prefix for field names using AS, e.g. 'u_' (default none)
3835 * @param array $already Array of fields that we're going to include anyway so don't list them (default none)
3836 * @return string Partial SQL select clause, beginning with comma, for example ',u.idnumber,u.department' unless it is blank
3837 */
3838function get_extra_user_fields_sql($context, $alias='', $prefix='', $already = array()) {
3839 $fields = get_extra_user_fields($context, $already);
3840 $result = '';
3841 // Add punctuation for alias.
3842 if ($alias !== '') {
3843 $alias .= '.';
3844 }
3845 foreach ($fields as $field) {
3846 $result .= ', ' . $alias . $field;
3847 if ($prefix) {
3848 $result .= ' AS ' . $prefix . $field;
3849 }
3850 }
3851 return $result;
3852}
3853
3854/**
3855 * Returns the display name of a field in the user table. Works for most fields that are commonly displayed to users.
3856 * @param string $field Field name, e.g. 'phone1'
3857 * @return string Text description taken from language file, e.g. 'Phone number'
3858 */
3859function get_user_field_name($field) {
3860 // Some fields have language strings which are not the same as field name.
3861 switch ($field) {
3862 case 'phone1' : {
3863 return get_string('phone');
3864 }
3865 case 'url' : {
3866 return get_string('webpage');
3867 }
3868 case 'icq' : {
3869 return get_string('icqnumber');
3870 }
3871 case 'skype' : {
3872 return get_string('skypeid');
3873 }
3874 case 'aim' : {
3875 return get_string('aimid');
3876 }
3877 case 'yahoo' : {
3878 return get_string('yahooid');
3879 }
3880 case 'msn' : {
3881 return get_string('msnid');
3882 }
3883 }
3884 // Otherwise just use the same lang string.
3885 return get_string($field);
3886}
3887
3888/**
3889 * Returns whether a given authentication plugin exists.
3890 *
3891 * @param string $auth Form of authentication to check for. Defaults to the global setting in {@link $CFG}.
3892 * @return boolean Whether the plugin is available.
3893 */
3894function exists_auth_plugin($auth) {
3895 global $CFG;
3896
3897 if (file_exists("{$CFG->dirroot}/auth/$auth/auth.php")) {
3898 return is_readable("{$CFG->dirroot}/auth/$auth/auth.php");
3899 }
3900 return false;
3901}
3902
3903/**
3904 * Checks if a given plugin is in the list of enabled authentication plugins.
3905 *
3906 * @param string $auth Authentication plugin.
3907 * @return boolean Whether the plugin is enabled.
3908 */
3909function is_enabled_auth($auth) {
3910 if (empty($auth)) {
3911 return false;
3912 }
3913
3914 $enabled = get_enabled_auth_plugins();
3915
3916 return in_array($auth, $enabled);
3917}
3918
3919/**
3920 * Returns an authentication plugin instance.
3921 *
3922 * @param string $auth name of authentication plugin
3923 * @return auth_plugin_base An instance of the required authentication plugin.
3924 */
3925function get_auth_plugin($auth) {
3926 global $CFG;
3927
3928 // Check the plugin exists first.
3929 if (! exists_auth_plugin($auth)) {
3930 print_error('authpluginnotfound', 'debug', '', $auth);
3931 }
3932
3933 // Return auth plugin instance.
3934 require_once("{$CFG->dirroot}/auth/$auth/auth.php");
3935 $class = "auth_plugin_$auth";
3936 return new $class;
3937}
3938
3939/**
3940 * Returns array of active auth plugins.
3941 *
3942 * @param bool $fix fix $CFG->auth if needed
3943 * @return array
3944 */
3945function get_enabled_auth_plugins($fix=false) {
3946 global $CFG;
3947
3948 $default = array('manual', 'nologin');
3949
3950 if (empty($CFG->auth)) {
3951 $auths = array();
3952 } else {
3953 $auths = explode(',', $CFG->auth);
3954 }
3955
3956 if ($fix) {
3957 $auths = array_unique($auths);
3958 foreach ($auths as $k => $authname) {
3959 if (!exists_auth_plugin($authname) or in_array($authname, $default)) {
3960 unset($auths[$k]);
3961 }
3962 }
3963 $newconfig = implode(',', $auths);
3964 if (!isset($CFG->auth) or $newconfig != $CFG->auth) {
3965 set_config('auth', $newconfig);
3966 }
3967 }
3968
3969 return (array_merge($default, $auths));
3970}
3971
3972/**
3973 * Returns true if an internal authentication method is being used.
3974 * if method not specified then, global default is assumed
3975 *
3976 * @param string $auth Form of authentication required
3977 * @return bool
3978 */
3979function is_internal_auth($auth) {
3980 // Throws error if bad $auth.
3981 $authplugin = get_auth_plugin($auth);
3982 return $authplugin->is_internal();
3983}
3984
3985/**
3986 * Returns true if the user is a 'restored' one.
3987 *
3988 * Used in the login process to inform the user and allow him/her to reset the password
3989 *
3990 * @param string $username username to be checked
3991 * @return bool
3992 */
3993function is_restored_user($username) {
3994 global $CFG, $DB;
3995
3996 return $DB->record_exists('user', array('username' => $username, 'mnethostid' => $CFG->mnet_localhost_id, 'password' => 'restored'));
3997}
3998
3999/**
4000 * Returns an array of user fields
4001 *
4002 * @return array User field/column names
4003 */
4004function get_user_fieldnames() {
4005 global $DB;
4006
4007 $fieldarray = $DB->get_columns('user');
4008 unset($fieldarray['id']);
4009 $fieldarray = array_keys($fieldarray);
4010
4011 return $fieldarray;
4012}
4013
4014/**
4015 * Creates a bare-bones user record
4016 *
4017 * @todo Outline auth types and provide code example
4018 *
4019 * @param string $username New user's username to add to record
4020 * @param string $password New user's password to add to record
4021 * @param string $auth Form of authentication required
4022 * @return stdClass A complete user object
4023 */
4024function create_user_record($username, $password, $auth = 'manual') {
4025 global $CFG, $DB;
4026 require_once($CFG->dirroot.'/user/profile/lib.php');
4027 require_once($CFG->dirroot.'/user/lib.php');
4028
4029 // Just in case check text case.
4030 $username = trim(core_text::strtolower($username));
4031
4032 $authplugin = get_auth_plugin($auth);
4033 $customfields = $authplugin->get_custom_user_profile_fields();
4034 $newuser = new stdClass();
4035 if ($newinfo = $authplugin->get_userinfo($username)) {
4036 $newinfo = truncate_userinfo($newinfo);
4037 foreach ($newinfo as $key => $value) {
4038 if (in_array($key, $authplugin->userfields) || (in_array($key, $customfields))) {
4039 $newuser->$key = $value;
4040 }
4041 }
4042 }
4043
4044 if (!empty($newuser->email)) {
4045 if (email_is_not_allowed($newuser->email)) {
4046 unset($newuser->email);
4047 }
4048 }
4049
4050 if (!isset($newuser->city)) {
4051 $newuser->city = '';
4052 }
4053
4054 $newuser->auth = $auth;
4055 $newuser->username = $username;
4056
4057 // Fix for MDL-8480
4058 // user CFG lang for user if $newuser->lang is empty
4059 // or $user->lang is not an installed language.
4060 if (empty($newuser->lang) || !get_string_manager()->translation_exists($newuser->lang)) {
4061 $newuser->lang = $CFG->lang;
4062 }
4063 $newuser->confirmed = 1;
4064 $newuser->lastip = getremoteaddr();
4065 $newuser->timecreated = time();
4066 $newuser->timemodified = $newuser->timecreated;
4067 $newuser->mnethostid = $CFG->mnet_localhost_id;
4068
4069 $newuser->id = user_create_user($newuser, false, false);
4070
4071 // Save user profile data.
4072 profile_save_data($newuser);
4073
4074 $user = get_complete_user_data('id', $newuser->id);
4075 if (!empty($CFG->{'auth_'.$newuser->auth.'_forcechangepassword'})) {
4076 set_user_preference('auth_forcepasswordchange', 1, $user);
4077 }
4078 // Set the password.
4079 update_internal_user_password($user, $password);
4080
4081 // Trigger event.
4082 \core\event\user_created::create_from_userid($newuser->id)->trigger();
4083
4084 return $user;
4085}
4086
4087/**
4088 * Will update a local user record from an external source (MNET users can not be updated using this method!).
4089 *
4090 * @param string $username user's username to update the record
4091 * @return stdClass A complete user object
4092 */
4093function update_user_record($username) {
4094 global $DB, $CFG;
4095 // Just in case check text case.
4096 $username = trim(core_text::strtolower($username));
4097
4098 $oldinfo = $DB->get_record('user', array('username' => $username, 'mnethostid' => $CFG->mnet_localhost_id), '*', MUST_EXIST);
4099 return update_user_record_by_id($oldinfo->id);
4100}
4101
4102/**
4103 * Will update a local user record from an external source (MNET users can not be updated using this method!).
4104 *
4105 * @param int $id user id
4106 * @return stdClass A complete user object
4107 */
4108function update_user_record_by_id($id) {
4109 global $DB, $CFG;
4110 require_once($CFG->dirroot."/user/profile/lib.php");
4111 require_once($CFG->dirroot.'/user/lib.php');
4112
4113 $params = array('mnethostid' => $CFG->mnet_localhost_id, 'id' => $id, 'deleted' => 0);
4114 $oldinfo = $DB->get_record('user', $params, '*', MUST_EXIST);
4115
4116 $newuser = array();
4117 $userauth = get_auth_plugin($oldinfo->auth);
4118
4119 if ($newinfo = $userauth->get_userinfo($oldinfo->username)) {
4120 $newinfo = truncate_userinfo($newinfo);
4121 $customfields = $userauth->get_custom_user_profile_fields();
4122
4123 foreach ($newinfo as $key => $value) {
4124 $key = strtolower($key);
4125 $iscustom = in_array($key, $customfields);
4126 if ((!property_exists($oldinfo, $key) && !$iscustom) or $key === 'username' or $key === 'id'
4127 or $key === 'auth' or $key === 'mnethostid' or $key === 'deleted') {
4128 // Unknown or must not be changed.
4129 continue;
4130 }
4131 $confval = $userauth->config->{'field_updatelocal_' . $key};
4132 $lockval = $userauth->config->{'field_lock_' . $key};
4133 if (empty($confval) || empty($lockval)) {
4134 continue;
4135 }
4136 if ($confval === 'onlogin') {
4137 // MDL-4207 Don't overwrite modified user profile values with
4138 // empty LDAP values when 'unlocked if empty' is set. The purpose
4139 // of the setting 'unlocked if empty' is to allow the user to fill
4140 // in a value for the selected field _if LDAP is giving
4141 // nothing_ for this field. Thus it makes sense to let this value
4142 // stand in until LDAP is giving a value for this field.
4143 if (!(empty($value) && $lockval === 'unlockedifempty')) {
4144 if ($iscustom || (in_array($key, $userauth->userfields) &&
4145 ((string)$oldinfo->$key !== (string)$value))) {
4146 $newuser[$key] = (string)$value;
4147 }
4148 }
4149 }
4150 }
4151 if ($newuser) {
4152 $newuser['id'] = $oldinfo->id;
4153 $newuser['timemodified'] = time();
4154 user_update_user((object) $newuser, false, false);
4155
4156 // Save user profile data.
4157 profile_save_data((object) $newuser);
4158
4159 // Trigger event.
4160 \core\event\user_updated::create_from_userid($newuser['id'])->trigger();
4161 }
4162 }
4163
4164 return get_complete_user_data('id', $oldinfo->id);
4165}
4166
4167/**
4168 * Will truncate userinfo as it comes from auth_get_userinfo (from external auth) which may have large fields.
4169 *
4170 * @param array $info Array of user properties to truncate if needed
4171 * @return array The now truncated information that was passed in
4172 */
4173function truncate_userinfo(array $info) {
4174 // Define the limits.
4175 $limit = array(
4176 'username' => 100,
4177 'idnumber' => 255,
4178 'firstname' => 100,
4179 'lastname' => 100,
4180 'email' => 100,
4181 'icq' => 15,
4182 'phone1' => 20,
4183 'phone2' => 20,
4184 'institution' => 255,
4185 'department' => 255,
4186 'address' => 255,
4187 'city' => 120,
4188 'country' => 2,
4189 'url' => 255,
4190 );
4191
4192 // Apply where needed.
4193 foreach (array_keys($info) as $key) {
4194 if (!empty($limit[$key])) {
4195 $info[$key] = trim(core_text::substr($info[$key], 0, $limit[$key]));
4196 }
4197 }
4198
4199 return $info;
4200}
4201
4202/**
4203 * Marks user deleted in internal user database and notifies the auth plugin.
4204 * Also unenrols user from all roles and does other cleanup.
4205 *
4206 * Any plugin that needs to purge user data should register the 'user_deleted' event.
4207 *
4208 * @param stdClass $user full user object before delete
4209 * @return boolean success
4210 * @throws coding_exception if invalid $user parameter detected
4211 */
4212function delete_user(stdClass $user) {
4213 global $CFG, $DB;
4214 require_once($CFG->libdir.'/grouplib.php');
4215 require_once($CFG->libdir.'/gradelib.php');
4216 require_once($CFG->dirroot.'/message/lib.php');
4217 require_once($CFG->dirroot.'/tag/lib.php');
4218 require_once($CFG->dirroot.'/user/lib.php');
4219
4220 // Make sure nobody sends bogus record type as parameter.
4221 if (!property_exists($user, 'id') or !property_exists($user, 'username')) {
4222 throw new coding_exception('Invalid $user parameter in delete_user() detected');
4223 }
4224
4225 // Better not trust the parameter and fetch the latest info this will be very expensive anyway.
4226 if (!$user = $DB->get_record('user', array('id' => $user->id))) {
4227 debugging('Attempt to delete unknown user account.');
4228 return false;
4229 }
4230
4231 // There must be always exactly one guest record, originally the guest account was identified by username only,
4232 // now we use $CFG->siteguest for performance reasons.
4233 if ($user->username === 'guest' or isguestuser($user)) {
4234 debugging('Guest user account can not be deleted.');
4235 return false;
4236 }
4237
4238 // Admin can be theoretically from different auth plugin, but we want to prevent deletion of internal accoutns only,
4239 // if anything goes wrong ppl may force somebody to be admin via config.php setting $CFG->siteadmins.
4240 if ($user->auth === 'manual' and is_siteadmin($user)) {
4241 debugging('Local administrator accounts can not be deleted.');
4242 return false;
4243 }
4244
4245 // Keep user record before updating it, as we have to pass this to user_deleted event.
4246 $olduser = clone $user;
4247
4248 // Keep a copy of user context, we need it for event.
4249 $usercontext = context_user::instance($user->id);
4250
4251 // Delete all grades - backup is kept in grade_grades_history table.
4252 grade_user_delete($user->id);
4253
4254 // Move unread messages from this user to read.
4255 message_move_userfrom_unread2read($user->id);
4256
4257 // TODO: remove from cohorts using standard API here.
4258
4259 // Remove user tags.
4260 tag_set('user', $user->id, array(), 'core', $usercontext->id);
4261
4262 // Unconditionally unenrol from all courses.
4263 enrol_user_delete($user);
4264
4265 // Unenrol from all roles in all contexts.
4266 // This might be slow but it is really needed - modules might do some extra cleanup!
4267 role_unassign_all(array('userid' => $user->id));
4268
4269 // Now do a brute force cleanup.
4270
4271 // Remove from all cohorts.
4272 $DB->delete_records('cohort_members', array('userid' => $user->id));
4273
4274 // Remove from all groups.
4275 $DB->delete_records('groups_members', array('userid' => $user->id));
4276
4277 // Brute force unenrol from all courses.
4278 $DB->delete_records('user_enrolments', array('userid' => $user->id));
4279
4280 // Purge user preferences.
4281 $DB->delete_records('user_preferences', array('userid' => $user->id));
4282
4283 // Purge user extra profile info.
4284 $DB->delete_records('user_info_data', array('userid' => $user->id));
4285
4286 // Last course access not necessary either.
4287 $DB->delete_records('user_lastaccess', array('userid' => $user->id));
4288 // Remove all user tokens.
4289 $DB->delete_records('external_tokens', array('userid' => $user->id));
4290
4291 // Unauthorise the user for all services.
4292 $DB->delete_records('external_services_users', array('userid' => $user->id));
4293
4294 // Remove users private keys.
4295 $DB->delete_records('user_private_key', array('userid' => $user->id));
4296
4297 // Remove users customised pages.
4298 $DB->delete_records('my_pages', array('userid' => $user->id, 'private' => 1));
4299
4300 // Force logout - may fail if file based sessions used, sorry.
4301 \core\session\manager::kill_user_sessions($user->id);
4302
4303 // Workaround for bulk deletes of users with the same email address.
4304 $delname = clean_param($user->email . "." . time(), PARAM_USERNAME);
4305 while ($DB->record_exists('user', array('username' => $delname))) { // No need to use mnethostid here.
4306 $delname++;
4307 }
4308
4309 // Mark internal user record as "deleted".
4310 $updateuser = new stdClass();
4311 $updateuser->id = $user->id;
4312 $updateuser->deleted = 1;
4313 $updateuser->username = $delname; // Remember it just in case.
4314 $updateuser->email = md5($user->username);// Store hash of username, useful importing/restoring users.
4315 $updateuser->idnumber = ''; // Clear this field to free it up.
4316 $updateuser->picture = 0;
4317 $updateuser->timemodified = time();
4318
4319 // Don't trigger update event, as user is being deleted.
4320 user_update_user($updateuser, false, false);
4321
4322 // Now do a final accesslib cleanup - removes all role assignments in user context and context itself.
4323 context_helper::delete_instance(CONTEXT_USER, $user->id);
4324
4325 // Any plugin that needs to cleanup should register this event.
4326 // Trigger event.
4327 $event = \core\event\user_deleted::create(
4328 array(
4329 'objectid' => $user->id,
4330 'relateduserid' => $user->id,
4331 'context' => $usercontext,
4332 'other' => array(
4333 'username' => $user->username,
4334 'email' => $user->email,
4335 'idnumber' => $user->idnumber,
4336 'picture' => $user->picture,
4337 'mnethostid' => $user->mnethostid
4338 )
4339 )
4340 );
4341 $event->add_record_snapshot('user', $olduser);
4342 $event->trigger();
4343
4344 // We will update the user's timemodified, as it will be passed to the user_deleted event, which
4345 // should know about this updated property persisted to the user's table.
4346 $user->timemodified = $updateuser->timemodified;
4347
4348 // Notify auth plugin - do not block the delete even when plugin fails.
4349 $authplugin = get_auth_plugin($user->auth);
4350 $authplugin->user_delete($user);
4351
4352 return true;
4353}
4354
4355/**
4356 * Retrieve the guest user object.
4357 *
4358 * @return stdClass A {@link $USER} object
4359 */
4360function guest_user() {
4361 global $CFG, $DB;
4362
4363 if ($newuser = $DB->get_record('user', array('id' => $CFG->siteguest))) {
4364 $newuser->confirmed = 1;
4365 $newuser->lang = $CFG->lang;
4366 $newuser->lastip = getremoteaddr();
4367 }
4368
4369 return $newuser;
4370}
4371
4372/**
4373 * Authenticates a user against the chosen authentication mechanism
4374 *
4375 * Given a username and password, this function looks them
4376 * up using the currently selected authentication mechanism,
4377 * and if the authentication is successful, it returns a
4378 * valid $user object from the 'user' table.
4379 *
4380 * Uses auth_ functions from the currently active auth module
4381 *
4382 * After authenticate_user_login() returns success, you will need to
4383 * log that the user has logged in, and call complete_user_login() to set
4384 * the session up.
4385 *
4386 * Note: this function works only with non-mnet accounts!
4387 *
4388 * @param string $username User's username (or also email if $CFG->authloginviaemail enabled)
4389 * @param string $password User's password
4390 * @param bool $ignorelockout useful when guessing is prevented by other mechanism such as captcha or SSO
4391 * @param int $failurereason login failure reason, can be used in renderers (it may disclose if account exists)
4392 * @return stdClass|false A {@link $USER} object or false if error
4393 */
4394function authenticate_user_login($username, $password, $ignorelockout=false, &$failurereason=null) {
4395 global $CFG, $DB;
4396 require_once("$CFG->libdir/authlib.php");
4397
4398 if ($user = get_complete_user_data('username', $username, $CFG->mnet_localhost_id)) {
4399 // we have found the user
4400
4401 } else if (!empty($CFG->authloginviaemail)) {
4402 if ($email = clean_param($username, PARAM_EMAIL)) {
4403 $select = "mnethostid = :mnethostid AND LOWER(email) = LOWER(:email) AND deleted = 0";
4404 $params = array('mnethostid' => $CFG->mnet_localhost_id, 'email' => $email);
4405 $users = $DB->get_records_select('user', $select, $params, 'id', 'id', 0, 2);
4406 if (count($users) === 1) {
4407 // Use email for login only if unique.
4408 $user = reset($users);
4409 $user = get_complete_user_data('id', $user->id);
4410 $username = $user->username;
4411 }
4412 unset($users);
4413 }
4414 }
4415
4416 $authsenabled = get_enabled_auth_plugins();
4417
4418 if ($user) {
4419 // Use manual if auth not set.
4420 $auth = empty($user->auth) ? 'manual' : $user->auth;
4421 if (!empty($user->suspended)) {
4422 $failurereason = AUTH_LOGIN_SUSPENDED;
4423
4424 // Trigger login failed event.
4425 $event = \core\event\user_login_failed::create(array('userid' => $user->id,
4426 'other' => array('username' => $username, 'reason' => $failurereason)));
4427 $event->trigger();
4428 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Suspended Login: $username ".$_SERVER['HTTP_USER_AGENT']);
4429 return false;
4430 }
4431 if ($auth=='nologin' or !is_enabled_auth($auth)) {
4432 // Legacy way to suspend user.
4433 $failurereason = AUTH_LOGIN_SUSPENDED;
4434
4435 // Trigger login failed event.
4436 $event = \core\event\user_login_failed::create(array('userid' => $user->id,
4437 'other' => array('username' => $username, 'reason' => $failurereason)));
4438 $event->trigger();
4439 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Disabled Login: $username ".$_SERVER['HTTP_USER_AGENT']);
4440 return false;
4441 }
4442 $auths = array($auth);
4443
4444 } else {
4445 // Check if there's a deleted record (cheaply), this should not happen because we mangle usernames in delete_user().
4446 if ($DB->get_field('user', 'id', array('username' => $username, 'mnethostid' => $CFG->mnet_localhost_id, 'deleted' => 1))) {
4447 $failurereason = AUTH_LOGIN_NOUSER;
4448
4449 // Trigger login failed event.
4450 $event = \core\event\user_login_failed::create(array('other' => array('username' => $username,
4451 'reason' => $failurereason)));
4452 $event->trigger();
4453 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Deleted Login: $username ".$_SERVER['HTTP_USER_AGENT']);
4454 return false;
4455 }
4456
4457 // User does not exist.
4458 $auths = $authsenabled;
4459 $user = new stdClass();
4460 $user->id = 0;
4461 }
4462
4463 if ($ignorelockout) {
4464 // Some other mechanism protects against brute force password guessing, for example login form might include reCAPTCHA
4465 // or this function is called from a SSO script.
4466 } else if ($user->id) {
4467 // Verify login lockout after other ways that may prevent user login.
4468 if (login_is_lockedout($user)) {
4469 $failurereason = AUTH_LOGIN_LOCKOUT;
4470
4471 // Trigger login failed event.
4472 $event = \core\event\user_login_failed::create(array('userid' => $user->id,
4473 'other' => array('username' => $username, 'reason' => $failurereason)));
4474 $event->trigger();
4475
4476 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Login lockout: $username ".$_SERVER['HTTP_USER_AGENT']);
4477 return false;
4478 }
4479 } else {
4480 // We can not lockout non-existing accounts.
4481 }
4482
4483 foreach ($auths as $auth) {
4484 $authplugin = get_auth_plugin($auth);
4485
4486 // On auth fail fall through to the next plugin.
4487 if (!$authplugin->user_login($username, $password)) {
4488 continue;
4489 }
4490
4491 // Successful authentication.
4492 if ($user->id) {
4493 // User already exists in database.
4494 if (empty($user->auth)) {
4495 // For some reason auth isn't set yet.
4496 $DB->set_field('user', 'auth', $auth, array('id' => $user->id));
4497 $user->auth = $auth;
4498 }
4499
4500 // If the existing hash is using an out-of-date algorithm (or the legacy md5 algorithm), then we should update to
4501 // the current hash algorithm while we have access to the user's password.
4502 update_internal_user_password($user, $password);
4503
4504 if ($authplugin->is_synchronised_with_external()) {
4505 // Update user record from external DB.
4506 $user = update_user_record_by_id($user->id);
4507 }
4508 } else {
4509 // The user is authenticated but user creation may be disabled.
4510 if (!empty($CFG->authpreventaccountcreation)) {
4511 $failurereason = AUTH_LOGIN_UNAUTHORISED;
4512
4513 // Trigger login failed event.
4514 $event = \core\event\user_login_failed::create(array('other' => array('username' => $username,
4515 'reason' => $failurereason)));
4516 $event->trigger();
4517
4518 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Unknown user, can not create new accounts: $username ".
4519 $_SERVER['HTTP_USER_AGENT']);
4520 return false;
4521 } else {
4522 $user = create_user_record($username, $password, $auth);
4523 }
4524 }
4525
4526 $authplugin->sync_roles($user);
4527
4528 foreach ($authsenabled as $hau) {
4529 $hauth = get_auth_plugin($hau);
4530 $hauth->user_authenticated_hook($user, $username, $password);
4531 }
4532
4533 if (empty($user->id)) {
4534 $failurereason = AUTH_LOGIN_NOUSER;
4535 // Trigger login failed event.
4536 $event = \core\event\user_login_failed::create(array('other' => array('username' => $username,
4537 'reason' => $failurereason)));
4538 $event->trigger();
4539 return false;
4540 }
4541
4542 if (!empty($user->suspended)) {
4543 // Just in case some auth plugin suspended account.
4544 $failurereason = AUTH_LOGIN_SUSPENDED;
4545 // Trigger login failed event.
4546 $event = \core\event\user_login_failed::create(array('userid' => $user->id,
4547 'other' => array('username' => $username, 'reason' => $failurereason)));
4548 $event->trigger();
4549 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Suspended Login: $username ".$_SERVER['HTTP_USER_AGENT']);
4550 return false;
4551 }
4552
4553 login_attempt_valid($user);
4554 $failurereason = AUTH_LOGIN_OK;
4555 return $user;
4556 }
4557
4558 // Failed if all the plugins have failed.
4559 if (debugging('', DEBUG_ALL)) {
4560 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Failed Login: $username ".$_SERVER['HTTP_USER_AGENT']);
4561 }
4562
4563 if ($user->id) {
4564 login_attempt_failed($user);
4565 $failurereason = AUTH_LOGIN_FAILED;
4566 // Trigger login failed event.
4567 $event = \core\event\user_login_failed::create(array('userid' => $user->id,
4568 'other' => array('username' => $username, 'reason' => $failurereason)));
4569 $event->trigger();
4570 } else {
4571 $failurereason = AUTH_LOGIN_NOUSER;
4572 // Trigger login failed event.
4573 $event = \core\event\user_login_failed::create(array('other' => array('username' => $username,
4574 'reason' => $failurereason)));
4575 $event->trigger();
4576 }
4577
4578 return false;
4579}
4580
4581/**
4582 * Call to complete the user login process after authenticate_user_login()
4583 * has succeeded. It will setup the $USER variable and other required bits
4584 * and pieces.
4585 *
4586 * NOTE:
4587 * - It will NOT log anything -- up to the caller to decide what to log.
4588 * - this function does not set any cookies any more!
4589 *
4590 * @param stdClass $user
4591 * @return stdClass A {@link $USER} object - BC only, do not use
4592 */
4593function complete_user_login($user) {
4594 global $CFG, $USER;
4595
4596 \core\session\manager::login_user($user);
4597
4598 // Reload preferences from DB.
4599 unset($USER->preference);
4600 check_user_preferences_loaded($USER);
4601
4602 // Update login times.
4603 update_user_login_times();
4604
4605 // Extra session prefs init.
4606 set_login_session_preferences();
4607
4608 // Trigger login event.
4609 $event = \core\event\user_loggedin::create(
4610 array(
4611 'userid' => $USER->id,
4612 'objectid' => $USER->id,
4613 'other' => array('username' => $USER->username),
4614 )
4615 );
4616 $event->trigger();
4617
4618 if (isguestuser()) {
4619 // No need to continue when user is THE guest.
4620 return $USER;
4621 }
4622
4623 if (CLI_SCRIPT) {
4624 // We can redirect to password change URL only in browser.
4625 return $USER;
4626 }
4627
4628 // Select password change url.
4629 $userauth = get_auth_plugin($USER->auth);
4630
4631 // Check whether the user should be changing password.
4632 if (get_user_preferences('auth_forcepasswordchange', false)) {
4633 if ($userauth->can_change_password()) {
4634 if ($changeurl = $userauth->change_password_url()) {
4635 redirect($changeurl);
4636 } else {
4637 redirect($CFG->httpswwwroot.'/login/change_password.php');
4638 }
4639 } else {
4640 print_error('nopasswordchangeforced', 'auth');
4641 }
4642 }
4643 return $USER;
4644}
4645
4646/**
4647 * Check a password hash to see if it was hashed using the legacy hash algorithm (md5).
4648 *
4649 * @param string $password String to check.
4650 * @return boolean True if the $password matches the format of an md5 sum.
4651 */
4652function password_is_legacy_hash($password) {
4653 return (bool) preg_match('/^[0-9a-f]{32}$/', $password);
4654}
4655
4656/**
4657 * Compare password against hash stored in user object to determine if it is valid.
4658 *
4659 * If necessary it also updates the stored hash to the current format.
4660 *
4661 * @param stdClass $user (Password property may be updated).
4662 * @param string $password Plain text password.
4663 * @return bool True if password is valid.
4664 */
4665function validate_internal_user_password($user, $password) {
4666 global $CFG;
4667 require_once($CFG->libdir.'/password_compat/lib/password.php');
4668
4669 if ($user->password === AUTH_PASSWORD_NOT_CACHED) {
4670 // Internal password is not used at all, it can not validate.
4671 return false;
4672 }
4673
4674 // If hash isn't a legacy (md5) hash, validate using the library function.
4675 if (!password_is_legacy_hash($user->password)) {
4676 return password_verify($password, $user->password);
4677 }
4678
4679 // Otherwise we need to check for a legacy (md5) hash instead. If the hash
4680 // is valid we can then update it to the new algorithm.
4681
4682 $sitesalt = isset($CFG->passwordsaltmain) ? $CFG->passwordsaltmain : '';
4683 $validated = false;
4684
4685 if ($user->password === md5($password.$sitesalt)
4686 or $user->password === md5($password)
4687 or $user->password === md5(addslashes($password).$sitesalt)
4688 or $user->password === md5(addslashes($password))) {
4689 // Note: we are intentionally using the addslashes() here because we
4690 // need to accept old password hashes of passwords with magic quotes.
4691 $validated = true;
4692
4693 } else {
4694 for ($i=1; $i<=20; $i++) { // 20 alternative salts should be enough, right?
4695 $alt = 'passwordsaltalt'.$i;
4696 if (!empty($CFG->$alt)) {
4697 if ($user->password === md5($password.$CFG->$alt) or $user->password === md5(addslashes($password).$CFG->$alt)) {
4698 $validated = true;
4699 break;
4700 }
4701 }
4702 }
4703 }
4704
4705 if ($validated) {
4706 // If the password matches the existing md5 hash, update to the
4707 // current hash algorithm while we have access to the user's password.
4708 update_internal_user_password($user, $password);
4709 }
4710
4711 return $validated;
4712}
4713
4714/**
4715 * Calculate hash for a plain text password.
4716 *
4717 * @param string $password Plain text password to be hashed.
4718 * @param bool $fasthash If true, use a low cost factor when generating the hash
4719 * This is much faster to generate but makes the hash
4720 * less secure. It is used when lots of hashes need to
4721 * be generated quickly.
4722 * @return string The hashed password.
4723 *
4724 * @throws moodle_exception If a problem occurs while generating the hash.
4725 */
4726function hash_internal_user_password($password, $fasthash = false) {
4727 global $CFG;
4728 require_once($CFG->libdir.'/password_compat/lib/password.php');
4729
4730 // Set the cost factor to 4 for fast hashing, otherwise use default cost.
4731 $options = ($fasthash) ? array('cost' => 4) : array();
4732
4733 $generatedhash = password_hash($password, PASSWORD_DEFAULT, $options);
4734
4735 if ($generatedhash === false || $generatedhash === null) {
4736 throw new moodle_exception('Failed to generate password hash.');
4737 }
4738
4739 return $generatedhash;
4740}
4741
4742/**
4743 * Update password hash in user object (if necessary).
4744 *
4745 * The password is updated if:
4746 * 1. The password has changed (the hash of $user->password is different
4747 * to the hash of $password).
4748 * 2. The existing hash is using an out-of-date algorithm (or the legacy
4749 * md5 algorithm).
4750 *
4751 * Updating the password will modify the $user object and the database
4752 * record to use the current hashing algorithm.
4753 *
4754 * @param stdClass $user User object (password property may be updated).
4755 * @param string $password Plain text password.
4756 * @param bool $fasthash If true, use a low cost factor when generating the hash
4757 * This is much faster to generate but makes the hash
4758 * less secure. It is used when lots of hashes need to
4759 * be generated quickly.
4760 * @return bool Always returns true.
4761 */
4762function update_internal_user_password($user, $password, $fasthash = false) {
4763 global $CFG, $DB;
4764 require_once($CFG->libdir.'/password_compat/lib/password.php');
4765
4766 // Figure out what the hashed password should be.
4767 if (!isset($user->auth)) {
4768 debugging('User record in update_internal_user_password() must include field auth',
4769 DEBUG_DEVELOPER);
4770 $user->auth = $DB->get_field('user', 'auth', array('id' => $user->id));
4771 }
4772 $authplugin = get_auth_plugin($user->auth);
4773 if ($authplugin->prevent_local_passwords()) {
4774 $hashedpassword = AUTH_PASSWORD_NOT_CACHED;
4775 } else {
4776 $hashedpassword = hash_internal_user_password($password, $fasthash);
4777 }
4778
4779 $algorithmchanged = false;
4780
4781 if ($hashedpassword === AUTH_PASSWORD_NOT_CACHED) {
4782 // Password is not cached, update it if not set to AUTH_PASSWORD_NOT_CACHED.
4783 $passwordchanged = ($user->password !== $hashedpassword);
4784
4785 } else if (isset($user->password)) {
4786 // If verification fails then it means the password has changed.
4787 $passwordchanged = !password_verify($password, $user->password);
4788 $algorithmchanged = password_needs_rehash($user->password, PASSWORD_DEFAULT);
4789 } else {
4790 // While creating new user, password in unset in $user object, to avoid
4791 // saving it with user_create()
4792 $passwordchanged = true;
4793 }
4794
4795 if ($passwordchanged || $algorithmchanged) {
4796 $DB->set_field('user', 'password', $hashedpassword, array('id' => $user->id));
4797 $user->password = $hashedpassword;
4798
4799 // Trigger event.
4800 $user = $DB->get_record('user', array('id' => $user->id));
4801 \core\event\user_password_updated::create_from_user($user)->trigger();
4802 }
4803
4804 return true;
4805}
4806
4807/**
4808 * Get a complete user record, which includes all the info in the user record.
4809 *
4810 * Intended for setting as $USER session variable
4811 *
4812 * @param string $field The user field to be checked for a given value.
4813 * @param string $value The value to match for $field.
4814 * @param int $mnethostid
4815 * @return mixed False, or A {@link $USER} object.
4816 */
4817function get_complete_user_data($field, $value, $mnethostid = null) {
4818 global $CFG, $DB;
4819
4820 if (!$field || !$value) {
4821 return false;
4822 }
4823
4824 // Build the WHERE clause for an SQL query.
4825 $params = array('fieldval' => $value);
4826 $constraints = "$field = :fieldval AND deleted <> 1";
4827
4828 // If we are loading user data based on anything other than id,
4829 // we must also restrict our search based on mnet host.
4830 if ($field != 'id') {
4831 if (empty($mnethostid)) {
4832 // If empty, we restrict to local users.
4833 $mnethostid = $CFG->mnet_localhost_id;
4834 }
4835 }
4836 if (!empty($mnethostid)) {
4837 $params['mnethostid'] = $mnethostid;
4838 $constraints .= " AND mnethostid = :mnethostid";
4839 }
4840
4841 // Get all the basic user data.
4842 if (! $user = $DB->get_record_select('user', $constraints, $params)) {
4843 return false;
4844 }
4845
4846 // Get various settings and preferences.
4847
4848 // Preload preference cache.
4849 check_user_preferences_loaded($user);
4850
4851 // Load course enrolment related stuff.
4852 $user->lastcourseaccess = array(); // During last session.
4853 $user->currentcourseaccess = array(); // During current session.
4854 if ($lastaccesses = $DB->get_records('user_lastaccess', array('userid' => $user->id))) {
4855 foreach ($lastaccesses as $lastaccess) {
4856 $user->lastcourseaccess[$lastaccess->courseid] = $lastaccess->timeaccess;
4857 }
4858 }
4859
4860 $sql = "SELECT g.id, g.courseid
4861 FROM {groups} g, {groups_members} gm
4862 WHERE gm.groupid=g.id AND gm.userid=?";
4863
4864 // This is a special hack to speedup calendar display.
4865 $user->groupmember = array();
4866 if (!isguestuser($user)) {
4867 if ($groups = $DB->get_records_sql($sql, array($user->id))) {
4868 foreach ($groups as $group) {
4869 if (!array_key_exists($group->courseid, $user->groupmember)) {
4870 $user->groupmember[$group->courseid] = array();
4871 }
4872 $user->groupmember[$group->courseid][$group->id] = $group->id;
4873 }
4874 }
4875 }
4876
4877 // Add the custom profile fields to the user record.
4878 $user->profile = array();
4879 if (!isguestuser($user)) {
4880 require_once($CFG->dirroot.'/user/profile/lib.php');
4881 profile_load_custom_fields($user);
4882 }
4883
4884 // Rewrite some variables if necessary.
4885 if (!empty($user->description)) {
4886 // No need to cart all of it around.
4887 $user->description = true;
4888 }
4889 if (isguestuser($user)) {
4890 // Guest language always same as site.
4891 $user->lang = $CFG->lang;
4892 // Name always in current language.
4893 $user->firstname = get_string('guestuser');
4894 $user->lastname = ' ';
4895 }
4896
4897 return $user;
4898}
4899
4900/**
4901 * Validate a password against the configured password policy
4902 *
4903 * @param string $password the password to be checked against the password policy
4904 * @param string $errmsg the error message to display when the password doesn't comply with the policy.
4905 * @return bool true if the password is valid according to the policy. false otherwise.
4906 */
4907function check_password_policy($password, &$errmsg) {
4908 global $CFG;
4909
4910 if (empty($CFG->passwordpolicy)) {
4911 return true;
4912 }
4913
4914 $errmsg = '';
4915 if (core_text::strlen($password) < $CFG->minpasswordlength) {
4916 $errmsg .= '<div>'. get_string('errorminpasswordlength', 'auth', $CFG->minpasswordlength) .'</div>';
4917
4918 }
4919 if (preg_match_all('/[[:digit:]]/u', $password, $matches) < $CFG->minpassworddigits) {
4920 $errmsg .= '<div>'. get_string('errorminpassworddigits', 'auth', $CFG->minpassworddigits) .'</div>';
4921
4922 }
4923 if (preg_match_all('/[[:lower:]]/u', $password, $matches) < $CFG->minpasswordlower) {
4924 $errmsg .= '<div>'. get_string('errorminpasswordlower', 'auth', $CFG->minpasswordlower) .'</div>';
4925
4926 }
4927 if (preg_match_all('/[[:upper:]]/u', $password, $matches) < $CFG->minpasswordupper) {
4928 $errmsg .= '<div>'. get_string('errorminpasswordupper', 'auth', $CFG->minpasswordupper) .'</div>';
4929
4930 }
4931 if (preg_match_all('/[^[:upper:][:lower:][:digit:]]/u', $password, $matches) < $CFG->minpasswordnonalphanum) {
4932 $errmsg .= '<div>'. get_string('errorminpasswordnonalphanum', 'auth', $CFG->minpasswordnonalphanum) .'</div>';
4933 }
4934 if (!check_consecutive_identical_characters($password, $CFG->maxconsecutiveidentchars)) {
4935 $errmsg .= '<div>'. get_string('errormaxconsecutiveidentchars', 'auth', $CFG->maxconsecutiveidentchars) .'</div>';
4936 }
4937
4938 if ($errmsg == '') {
4939 return true;
4940 } else {
4941 return false;
4942 }
4943}
4944
4945
4946/**
4947 * When logging in, this function is run to set certain preferences for the current SESSION.
4948 */
4949function set_login_session_preferences() {
4950 global $SESSION;
4951
4952 $SESSION->justloggedin = true;
4953
4954 unset($SESSION->lang);
4955 unset($SESSION->forcelang);
4956 unset($SESSION->load_navigation_admin);
4957}
4958
4959
4960/**
4961 * Delete a course, including all related data from the database, and any associated files.
4962 *
4963 * @param mixed $courseorid The id of the course or course object to delete.
4964 * @param bool $showfeedback Whether to display notifications of each action the function performs.
4965 * @return bool true if all the removals succeeded. false if there were any failures. If this
4966 * method returns false, some of the removals will probably have succeeded, and others
4967 * failed, but you have no way of knowing which.
4968 */
4969function delete_course($courseorid, $showfeedback = true) {
4970 global $DB;
4971
4972 if (is_object($courseorid)) {
4973 $courseid = $courseorid->id;
4974 $course = $courseorid;
4975 } else {
4976 $courseid = $courseorid;
4977 if (!$course = $DB->get_record('course', array('id' => $courseid))) {
4978 return false;
4979 }
4980 }
4981 $context = context_course::instance($courseid);
4982
4983 // Frontpage course can not be deleted!!
4984 if ($courseid == SITEID) {
4985 return false;
4986 }
4987
4988 // Make the course completely empty.
4989 remove_course_contents($courseid, $showfeedback);
4990
4991 // Delete the course and related context instance.
4992 context_helper::delete_instance(CONTEXT_COURSE, $courseid);
4993
4994 $DB->delete_records("course", array("id" => $courseid));
4995 $DB->delete_records("course_format_options", array("courseid" => $courseid));
4996
4997 // Reset all course related caches here.
4998 if (class_exists('format_base', false)) {
4999 format_base::reset_course_cache($courseid);
5000 }
5001
5002 // Trigger a course deleted event.
5003 $event = \core\event\course_deleted::create(array(
5004 'objectid' => $course->id,
5005 'context' => $context,
5006 'other' => array(
5007 'shortname' => $course->shortname,
5008 'fullname' => $course->fullname,
5009 'idnumber' => $course->idnumber
5010 )
5011 ));
5012 $event->add_record_snapshot('course', $course);
5013 $event->trigger();
5014
5015 return true;
5016}
5017
5018/**
5019 * Clear a course out completely, deleting all content but don't delete the course itself.
5020 *
5021 * This function does not verify any permissions.
5022 *
5023 * Please note this function also deletes all user enrolments,
5024 * enrolment instances and role assignments by default.
5025 *
5026 * $options:
5027 * - 'keep_roles_and_enrolments' - false by default
5028 * - 'keep_groups_and_groupings' - false by default
5029 *
5030 * @param int $courseid The id of the course that is being deleted
5031 * @param bool $showfeedback Whether to display notifications of each action the function performs.
5032 * @param array $options extra options
5033 * @return bool true if all the removals succeeded. false if there were any failures. If this
5034 * method returns false, some of the removals will probably have succeeded, and others
5035 * failed, but you have no way of knowing which.
5036 */
5037function remove_course_contents($courseid, $showfeedback = true, array $options = null) {
5038 global $CFG, $DB, $OUTPUT;
5039
5040 require_once($CFG->libdir.'/badgeslib.php');
5041 require_once($CFG->libdir.'/completionlib.php');
5042 require_once($CFG->libdir.'/questionlib.php');
5043 require_once($CFG->libdir.'/gradelib.php');
5044 require_once($CFG->dirroot.'/group/lib.php');
5045 require_once($CFG->dirroot.'/tag/coursetagslib.php');
5046 require_once($CFG->dirroot.'/comment/lib.php');
5047 require_once($CFG->dirroot.'/rating/lib.php');
5048 require_once($CFG->dirroot.'/notes/lib.php');
5049
5050 // Handle course badges.
5051 badges_handle_course_deletion($courseid);
5052
5053 // NOTE: these concatenated strings are suboptimal, but it is just extra info...
5054 $strdeleted = get_string('deleted').' - ';
5055
5056 // Some crazy wishlist of stuff we should skip during purging of course content.
5057 $options = (array)$options;
5058
5059 $course = $DB->get_record('course', array('id' => $courseid), '*', MUST_EXIST);
5060 $coursecontext = context_course::instance($courseid);
5061 $fs = get_file_storage();
5062
5063 // Delete course completion information, this has to be done before grades and enrols.
5064 $cc = new completion_info($course);
5065 $cc->clear_criteria();
5066 if ($showfeedback) {
5067 echo $OUTPUT->notification($strdeleted.get_string('completion', 'completion'), 'notifysuccess');
5068 }
5069
5070 // Remove all data from gradebook - this needs to be done before course modules
5071 // because while deleting this information, the system may need to reference
5072 // the course modules that own the grades.
5073 remove_course_grades($courseid, $showfeedback);
5074 remove_grade_letters($coursecontext, $showfeedback);
5075
5076 // Delete course blocks in any all child contexts,
5077 // they may depend on modules so delete them first.
5078 $childcontexts = $coursecontext->get_child_contexts(); // Returns all subcontexts since 2.2.
5079 foreach ($childcontexts as $childcontext) {
5080 blocks_delete_all_for_context($childcontext->id);
5081 }
5082 unset($childcontexts);
5083 blocks_delete_all_for_context($coursecontext->id);
5084 if ($showfeedback) {
5085 echo $OUTPUT->notification($strdeleted.get_string('type_block_plural', 'plugin'), 'notifysuccess');
5086 }
5087
5088 // Delete every instance of every module,
5089 // this has to be done before deleting of course level stuff.
5090 $locations = core_component::get_plugin_list('mod');
5091 foreach ($locations as $modname => $moddir) {
5092 if ($modname === 'NEWMODULE') {
5093 continue;
5094 }
5095 if ($module = $DB->get_record('modules', array('name' => $modname))) {
5096 include_once("$moddir/lib.php"); // Shows php warning only if plugin defective.
5097 $moddelete = $modname .'_delete_instance'; // Delete everything connected to an instance.
5098 $moddeletecourse = $modname .'_delete_course'; // Delete other stray stuff (uncommon).
5099
5100 if ($instances = $DB->get_records($modname, array('course' => $course->id))) {
5101 foreach ($instances as $instance) {
5102 if ($cm = get_coursemodule_from_instance($modname, $instance->id, $course->id)) {
5103 // Delete activity context questions and question categories.
5104 question_delete_activity($cm, $showfeedback);
5105 }
5106 if (function_exists($moddelete)) {
5107 // This purges all module data in related tables, extra user prefs, settings, etc.
5108 $moddelete($instance->id);
5109 } else {
5110 // NOTE: we should not allow installation of modules with missing delete support!
5111 debugging("Defective module '$modname' detected when deleting course contents: missing function $moddelete()!");
5112 $DB->delete_records($modname, array('id' => $instance->id));
5113 }
5114
5115 if ($cm) {
5116 // Delete cm and its context - orphaned contexts are purged in cron in case of any race condition.
5117 context_helper::delete_instance(CONTEXT_MODULE, $cm->id);
5118 $DB->delete_records('course_modules', array('id' => $cm->id));
5119 }
5120 }
5121 }
5122 if (function_exists($moddeletecourse)) {
5123 // Execute ptional course cleanup callback.
5124 $moddeletecourse($course, $showfeedback);
5125 }
5126 if ($instances and $showfeedback) {
5127 echo $OUTPUT->notification($strdeleted.get_string('pluginname', $modname), 'notifysuccess');
5128 }
5129 } else {
5130 // Ooops, this module is not properly installed, force-delete it in the next block.
5131 }
5132 }
5133
5134 // We have tried to delete everything the nice way - now let's force-delete any remaining module data.
5135
5136 // Remove all data from availability and completion tables that is associated
5137 // with course-modules belonging to this course. Note this is done even if the
5138 // features are not enabled now, in case they were enabled previously.
5139 $DB->delete_records_select('course_modules_completion',
5140 'coursemoduleid IN (SELECT id from {course_modules} WHERE course=?)',
5141 array($courseid));
5142
5143 // Remove course-module data.
5144 $cms = $DB->get_records('course_modules', array('course' => $course->id));
5145 foreach ($cms as $cm) {
5146 if ($module = $DB->get_record('modules', array('id' => $cm->module))) {
5147 try {
5148 $DB->delete_records($module->name, array('id' => $cm->instance));
5149 } catch (Exception $e) {
5150 // Ignore weird or missing table problems.
5151 }
5152 }
5153 context_helper::delete_instance(CONTEXT_MODULE, $cm->id);
5154 $DB->delete_records('course_modules', array('id' => $cm->id));
5155 }
5156
5157 if ($showfeedback) {
5158 echo $OUTPUT->notification($strdeleted.get_string('type_mod_plural', 'plugin'), 'notifysuccess');
5159 }
5160
5161 // Cleanup the rest of plugins.
5162 $cleanuplugintypes = array('report', 'coursereport', 'format');
5163 foreach ($cleanuplugintypes as $type) {
5164 $plugins = get_plugin_list_with_function($type, 'delete_course', 'lib.php');
5165 foreach ($plugins as $plugin => $pluginfunction) {
5166 $pluginfunction($course->id, $showfeedback);
5167 }
5168 if ($showfeedback) {
5169 echo $OUTPUT->notification($strdeleted.get_string('type_'.$type.'_plural', 'plugin'), 'notifysuccess');
5170 }
5171 }
5172
5173 // Delete questions and question categories.
5174 question_delete_course($course, $showfeedback);
5175 if ($showfeedback) {
5176 echo $OUTPUT->notification($strdeleted.get_string('questions', 'question'), 'notifysuccess');
5177 }
5178
5179 // Make sure there are no subcontexts left - all valid blocks and modules should be already gone.
5180 $childcontexts = $coursecontext->get_child_contexts(); // Returns all subcontexts since 2.2.
5181 foreach ($childcontexts as $childcontext) {
5182 $childcontext->delete();
5183 }
5184 unset($childcontexts);
5185
5186 // Remove all roles and enrolments by default.
5187 if (empty($options['keep_roles_and_enrolments'])) {
5188 // This hack is used in restore when deleting contents of existing course.
5189 role_unassign_all(array('contextid' => $coursecontext->id, 'component' => ''), true);
5190 enrol_course_delete($course);
5191 if ($showfeedback) {
5192 echo $OUTPUT->notification($strdeleted.get_string('type_enrol_plural', 'plugin'), 'notifysuccess');
5193 }
5194 }
5195
5196 // Delete any groups, removing members and grouping/course links first.
5197 if (empty($options['keep_groups_and_groupings'])) {
5198 groups_delete_groupings($course->id, $showfeedback);
5199 groups_delete_groups($course->id, $showfeedback);
5200 }
5201
5202 // Filters be gone!
5203 filter_delete_all_for_context($coursecontext->id);
5204
5205 // Notes, you shall not pass!
5206 note_delete_all($course->id);
5207
5208 // Die comments!
5209 comment::delete_comments($coursecontext->id);
5210
5211 // Ratings are history too.
5212 $delopt = new stdclass();
5213 $delopt->contextid = $coursecontext->id;
5214 $rm = new rating_manager();
5215 $rm->delete_ratings($delopt);
5216
5217 // Delete course tags.
5218 coursetag_delete_course_tags($course->id, $showfeedback);
5219
5220 // Delete calendar events.
5221 $DB->delete_records('event', array('courseid' => $course->id));
5222 $fs->delete_area_files($coursecontext->id, 'calendar');
5223
5224 // Delete all related records in other core tables that may have a courseid
5225 // This array stores the tables that need to be cleared, as
5226 // table_name => column_name that contains the course id.
5227 $tablestoclear = array(
5228 'backup_courses' => 'courseid', // Scheduled backup stuff.
5229 'user_lastaccess' => 'courseid', // User access info.
5230 );
5231 foreach ($tablestoclear as $table => $col) {
5232 $DB->delete_records($table, array($col => $course->id));
5233 }
5234
5235 // Delete all course backup files.
5236 $fs->delete_area_files($coursecontext->id, 'backup');
5237
5238 // Cleanup course record - remove links to deleted stuff.
5239 $oldcourse = new stdClass();
5240 $oldcourse->id = $course->id;
5241 $oldcourse->summary = '';
5242 $oldcourse->cacherev = 0;
5243 $oldcourse->legacyfiles = 0;
5244 $oldcourse->enablecompletion = 0;
5245 if (!empty($options['keep_groups_and_groupings'])) {
5246 $oldcourse->defaultgroupingid = 0;
5247 }
5248 $DB->update_record('course', $oldcourse);
5249
5250 // Delete course sections.
5251 $DB->delete_records('course_sections', array('course' => $course->id));
5252
5253 // Delete legacy, section and any other course files.
5254 $fs->delete_area_files($coursecontext->id, 'course'); // Files from summary and section.
5255
5256 // Delete all remaining stuff linked to context such as files, comments, ratings, etc.
5257 if (empty($options['keep_roles_and_enrolments']) and empty($options['keep_groups_and_groupings'])) {
5258 // Easy, do not delete the context itself...
5259 $coursecontext->delete_content();
5260 } else {
5261 // Hack alert!!!!
5262 // We can not drop all context stuff because it would bork enrolments and roles,
5263 // there might be also files used by enrol plugins...
5264 }
5265
5266 // Delete legacy files - just in case some files are still left there after conversion to new file api,
5267 // also some non-standard unsupported plugins may try to store something there.
5268 fulldelete($CFG->dataroot.'/'.$course->id);
5269
5270 // Delete from cache to reduce the cache size especially makes sense in case of bulk course deletion.
5271 $cachemodinfo = cache::make('core', 'coursemodinfo');
5272 $cachemodinfo->delete($courseid);
5273
5274 // Trigger a course content deleted event.
5275 $event = \core\event\course_content_deleted::create(array(
5276 'objectid' => $course->id,
5277 'context' => $coursecontext,
5278 'other' => array('shortname' => $course->shortname,
5279 'fullname' => $course->fullname,
5280 'options' => $options) // Passing this for legacy reasons.
5281 ));
5282 $event->add_record_snapshot('course', $course);
5283 $event->trigger();
5284
5285 return true;
5286}
5287
5288/**
5289 * Change dates in module - used from course reset.
5290 *
5291 * @param string $modname forum, assignment, etc
5292 * @param array $fields array of date fields from mod table
5293 * @param int $timeshift time difference
5294 * @param int $courseid
5295 * @param int $modid (Optional) passed if specific mod instance in course needs to be updated.
5296 * @return bool success
5297 */
5298function shift_course_mod_dates($modname, $fields, $timeshift, $courseid, $modid = 0) {
5299 global $CFG, $DB;
5300 include_once($CFG->dirroot.'/mod/'.$modname.'/lib.php');
5301
5302 $return = true;
5303 $params = array($timeshift, $courseid);
5304 foreach ($fields as $field) {
5305 $updatesql = "UPDATE {".$modname."}
5306 SET $field = $field + ?
5307 WHERE course=? AND $field<>0";
5308 if ($modid) {
5309 $updatesql .= ' AND id=?';
5310 $params[] = $modid;
5311 }
5312 $return = $DB->execute($updatesql, $params) && $return;
5313 }
5314
5315 $refreshfunction = $modname.'_refresh_events';
5316 if (function_exists($refreshfunction)) {
5317 $refreshfunction($courseid);
5318 }
5319
5320 return $return;
5321}
5322
5323/**
5324 * This function will empty a course of user data.
5325 * It will retain the activities and the structure of the course.
5326 *
5327 * @param object $data an object containing all the settings including courseid (without magic quotes)
5328 * @return array status array of array component, item, error
5329 */
5330function reset_course_userdata($data) {
5331 global $CFG, $DB;
5332 require_once($CFG->libdir.'/gradelib.php');
5333 require_once($CFG->libdir.'/completionlib.php');
5334 require_once($CFG->dirroot.'/group/lib.php');
5335
5336 $data->courseid = $data->id;
5337 $context = context_course::instance($data->courseid);
5338
5339 $eventparams = array(
5340 'context' => $context,
5341 'courseid' => $data->id,
5342 'other' => array(
5343 'reset_options' => (array) $data
5344 )
5345 );
5346 $event = \core\event\course_reset_started::create($eventparams);
5347 $event->trigger();
5348
5349 // Calculate the time shift of dates.
5350 if (!empty($data->reset_start_date)) {
5351 // Time part of course startdate should be zero.
5352 $data->timeshift = $data->reset_start_date - usergetmidnight($data->reset_start_date_old);
5353 } else {
5354 $data->timeshift = 0;
5355 }
5356
5357 // Result array: component, item, error.
5358 $status = array();
5359
5360 // Start the resetting.
5361 $componentstr = get_string('general');
5362
5363 // Move the course start time.
5364 if (!empty($data->reset_start_date) and $data->timeshift) {
5365 // Change course start data.
5366 $DB->set_field('course', 'startdate', $data->reset_start_date, array('id' => $data->courseid));
5367 // Update all course and group events - do not move activity events.
5368 $updatesql = "UPDATE {event}
5369 SET timestart = timestart + ?
5370 WHERE courseid=? AND instance=0";
5371 $DB->execute($updatesql, array($data->timeshift, $data->courseid));
5372
5373 $status[] = array('component' => $componentstr, 'item' => get_string('datechanged'), 'error' => false);
5374 }
5375
5376 if (!empty($data->reset_events)) {
5377 $DB->delete_records('event', array('courseid' => $data->courseid));
5378 $status[] = array('component' => $componentstr, 'item' => get_string('deleteevents', 'calendar'), 'error' => false);
5379 }
5380
5381 if (!empty($data->reset_notes)) {
5382 require_once($CFG->dirroot.'/notes/lib.php');
5383 note_delete_all($data->courseid);
5384 $status[] = array('component' => $componentstr, 'item' => get_string('deletenotes', 'notes'), 'error' => false);
5385 }
5386
5387 if (!empty($data->delete_blog_associations)) {
5388 require_once($CFG->dirroot.'/blog/lib.php');
5389 blog_remove_associations_for_course($data->courseid);
5390 $status[] = array('component' => $componentstr, 'item' => get_string('deleteblogassociations', 'blog'), 'error' => false);
5391 }
5392
5393 if (!empty($data->reset_completion)) {
5394 // Delete course and activity completion information.
5395 $course = $DB->get_record('course', array('id' => $data->courseid));
5396 $cc = new completion_info($course);
5397 $cc->delete_all_completion_data();
5398 $status[] = array('component' => $componentstr,
5399 'item' => get_string('deletecompletiondata', 'completion'), 'error' => false);
5400 }
5401
5402 $componentstr = get_string('roles');
5403
5404 if (!empty($data->reset_roles_overrides)) {
5405 $children = $context->get_child_contexts();
5406 foreach ($children as $child) {
5407 $DB->delete_records('role_capabilities', array('contextid' => $child->id));
5408 }
5409 $DB->delete_records('role_capabilities', array('contextid' => $context->id));
5410 // Force refresh for logged in users.
5411 $context->mark_dirty();
5412 $status[] = array('component' => $componentstr, 'item' => get_string('deletecourseoverrides', 'role'), 'error' => false);
5413 }
5414
5415 if (!empty($data->reset_roles_local)) {
5416 $children = $context->get_child_contexts();
5417 foreach ($children as $child) {
5418 role_unassign_all(array('contextid' => $child->id));
5419 }
5420 // Force refresh for logged in users.
5421 $context->mark_dirty();
5422 $status[] = array('component' => $componentstr, 'item' => get_string('deletelocalroles', 'role'), 'error' => false);
5423 }
5424
5425 // First unenrol users - this cleans some of related user data too, such as forum subscriptions, tracking, etc.
5426 $data->unenrolled = array();
5427 if (!empty($data->unenrol_users)) {
5428 $plugins = enrol_get_plugins(true);
5429 $instances = enrol_get_instances($data->courseid, true);
5430 foreach ($instances as $key => $instance) {
5431 if (!isset($plugins[$instance->enrol])) {
5432 unset($instances[$key]);
5433 continue;
5434 }
5435 }
5436
5437 foreach ($data->unenrol_users as $withroleid) {
5438 if ($withroleid) {
5439 $sql = "SELECT ue.*
5440 FROM {user_enrolments} ue
5441 JOIN {enrol} e ON (e.id = ue.enrolid AND e.courseid = :courseid)
5442 JOIN {context} c ON (c.contextlevel = :courselevel AND c.instanceid = e.courseid)
5443 JOIN {role_assignments} ra ON (ra.contextid = c.id AND ra.roleid = :roleid AND ra.userid = ue.userid)";
5444 $params = array('courseid' => $data->courseid, 'roleid' => $withroleid, 'courselevel' => CONTEXT_COURSE);
5445
5446 } else {
5447 // Without any role assigned at course context.
5448 $sql = "SELECT ue.*
5449 FROM {user_enrolments} ue
5450 JOIN {enrol} e ON (e.id = ue.enrolid AND e.courseid = :courseid)
5451 JOIN {context} c ON (c.contextlevel = :courselevel AND c.instanceid = e.courseid)
5452 LEFT JOIN {role_assignments} ra ON (ra.contextid = c.id AND ra.userid = ue.userid)
5453 WHERE ra.id IS null";
5454 $params = array('courseid' => $data->courseid, 'courselevel' => CONTEXT_COURSE);
5455 }
5456
5457 $rs = $DB->get_recordset_sql($sql, $params);
5458 foreach ($rs as $ue) {
5459 if (!isset($instances[$ue->enrolid])) {
5460 continue;
5461 }
5462 $instance = $instances[$ue->enrolid];
5463 $plugin = $plugins[$instance->enrol];
5464 if (!$plugin->allow_unenrol($instance) and !$plugin->allow_unenrol_user($instance, $ue)) {
5465 continue;
5466 }
5467
5468 $plugin->unenrol_user($instance, $ue->userid);
5469 $data->unenrolled[$ue->userid] = $ue->userid;
5470 }
5471 $rs->close();
5472 }
5473 }
5474 if (!empty($data->unenrolled)) {
5475 $status[] = array(
5476 'component' => $componentstr,
5477 'item' => get_string('unenrol', 'enrol').' ('.count($data->unenrolled).')',
5478 'error' => false
5479 );
5480 }
5481
5482 $componentstr = get_string('groups');
5483
5484 // Remove all group members.
5485 if (!empty($data->reset_groups_members)) {
5486 groups_delete_group_members($data->courseid);
5487 $status[] = array('component' => $componentstr, 'item' => get_string('removegroupsmembers', 'group'), 'error' => false);
5488 }
5489
5490 // Remove all groups.
5491 if (!empty($data->reset_groups_remove)) {
5492 groups_delete_groups($data->courseid, false);
5493 $status[] = array('component' => $componentstr, 'item' => get_string('deleteallgroups', 'group'), 'error' => false);
5494 }
5495
5496 // Remove all grouping members.
5497 if (!empty($data->reset_groupings_members)) {
5498 groups_delete_groupings_groups($data->courseid, false);
5499 $status[] = array('component' => $componentstr, 'item' => get_string('removegroupingsmembers', 'group'), 'error' => false);
5500 }
5501
5502 // Remove all groupings.
5503 if (!empty($data->reset_groupings_remove)) {
5504 groups_delete_groupings($data->courseid, false);
5505 $status[] = array('component' => $componentstr, 'item' => get_string('deleteallgroupings', 'group'), 'error' => false);
5506 }
5507
5508 // Look in every instance of every module for data to delete.
5509 $unsupportedmods = array();
5510 if ($allmods = $DB->get_records('modules') ) {
5511 foreach ($allmods as $mod) {
5512 $modname = $mod->name;
5513 $modfile = $CFG->dirroot.'/mod/'. $modname.'/lib.php';
5514 $moddeleteuserdata = $modname.'_reset_userdata'; // Function to delete user data.
5515 if (file_exists($modfile)) {
5516 if (!$DB->count_records($modname, array('course' => $data->courseid))) {
5517 continue; // Skip mods with no instances.
5518 }
5519 include_once($modfile);
5520 if (function_exists($moddeleteuserdata)) {
5521 $modstatus = $moddeleteuserdata($data);
5522 if (is_array($modstatus)) {
5523 $status = array_merge($status, $modstatus);
5524 } else {
5525 debugging('Module '.$modname.' returned incorrect staus - must be an array!');
5526 }
5527 } else {
5528 $unsupportedmods[] = $mod;
5529 }
5530 } else {
5531 debugging('Missing lib.php in '.$modname.' module!');
5532 }
5533 }
5534 }
5535
5536 // Mention unsupported mods.
5537 if (!empty($unsupportedmods)) {
5538 foreach ($unsupportedmods as $mod) {
5539 $status[] = array(
5540 'component' => get_string('modulenameplural', $mod->name),
5541 'item' => '',
5542 'error' => get_string('resetnotimplemented')
5543 );
5544 }
5545 }
5546
5547 $componentstr = get_string('gradebook', 'grades');
5548 // Reset gradebook,.
5549 if (!empty($data->reset_gradebook_items)) {
5550 remove_course_grades($data->courseid, false);
5551 grade_grab_course_grades($data->courseid);
5552 grade_regrade_final_grades($data->courseid);
5553 $status[] = array('component' => $componentstr, 'item' => get_string('removeallcourseitems', 'grades'), 'error' => false);
5554
5555 } else if (!empty($data->reset_gradebook_grades)) {
5556 grade_course_reset($data->courseid);
5557 $status[] = array('component' => $componentstr, 'item' => get_string('removeallcoursegrades', 'grades'), 'error' => false);
5558 }
5559 // Reset comments.
5560 if (!empty($data->reset_comments)) {
5561 require_once($CFG->dirroot.'/comment/lib.php');
5562 comment::reset_course_page_comments($context);
5563 }
5564
5565 $event = \core\event\course_reset_ended::create($eventparams);
5566 $event->trigger();
5567
5568 return $status;
5569}
5570
5571/**
5572 * Generate an email processing address.
5573 *
5574 * @param int $modid
5575 * @param string $modargs
5576 * @return string Returns email processing address
5577 */
5578function generate_email_processing_address($modid, $modargs) {
5579 global $CFG;
5580
5581 $header = $CFG->mailprefix . substr(base64_encode(pack('C', $modid)), 0, 2).$modargs;
5582 return $header . substr(md5($header.get_site_identifier()), 0, 16).'@'.$CFG->maildomain;
5583}
5584
5585/**
5586 * ?
5587 *
5588 * @todo Finish documenting this function
5589 *
5590 * @param string $modargs
5591 * @param string $body Currently unused
5592 */
5593function moodle_process_email($modargs, $body) {
5594 global $DB;
5595
5596 // The first char should be an unencoded letter. We'll take this as an action.
5597 switch ($modargs{0}) {
5598 case 'B': { // Bounce.
5599 list(, $userid) = unpack('V', base64_decode(substr($modargs, 1, 8)));
5600 if ($user = $DB->get_record("user", array('id' => $userid), "id,email")) {
5601 // Check the half md5 of their email.
5602 $md5check = substr(md5($user->email), 0, 16);
5603 if ($md5check == substr($modargs, -16)) {
5604 set_bounce_count($user);
5605 }
5606 // Else maybe they've already changed it?
5607 }
5608 }
5609 break;
5610 // Maybe more later?
5611 }
5612}
5613
5614// CORRESPONDENCE.
5615
5616/**
5617 * Get mailer instance, enable buffering, flush buffer or disable buffering.
5618 *
5619 * @param string $action 'get', 'buffer', 'close' or 'flush'
5620 * @return moodle_phpmailer|null mailer instance if 'get' used or nothing
5621 */
5622function get_mailer($action='get') {
5623 global $CFG;
5624
5625 /** @var moodle_phpmailer $mailer */
5626 static $mailer = null;
5627 static $counter = 0;
5628
5629 if (!isset($CFG->smtpmaxbulk)) {
5630 $CFG->smtpmaxbulk = 1;
5631 }
5632
5633 if ($action == 'get') {
5634 $prevkeepalive = false;
5635
5636 if (isset($mailer) and $mailer->Mailer == 'smtp') {
5637 if ($counter < $CFG->smtpmaxbulk and !$mailer->isError()) {
5638 $counter++;
5639 // Reset the mailer.
5640 $mailer->Priority = 3;
5641 $mailer->CharSet = 'UTF-8'; // Our default.
5642 $mailer->ContentType = "text/plain";
5643 $mailer->Encoding = "8bit";
5644 $mailer->From = "root@localhost";
5645 $mailer->FromName = "Root User";
5646 $mailer->Sender = "";
5647 $mailer->Subject = "";
5648 $mailer->Body = "";
5649 $mailer->AltBody = "";
5650 $mailer->ConfirmReadingTo = "";
5651
5652 $mailer->clearAllRecipients();
5653 $mailer->clearReplyTos();
5654 $mailer->clearAttachments();
5655 $mailer->clearCustomHeaders();
5656 return $mailer;
5657 }
5658
5659 $prevkeepalive = $mailer->SMTPKeepAlive;
5660 get_mailer('flush');
5661 }
5662
5663 require_once($CFG->libdir.'/phpmailer/moodle_phpmailer.php');
5664 $mailer = new moodle_phpmailer();
5665
5666 $counter = 1;
5667
5668 if ($CFG->smtphosts == 'qmail') {
5669 // Use Qmail system.
5670 $mailer->isQmail();
5671
5672 } else if (empty($CFG->smtphosts)) {
5673 // Use PHP mail() = sendmail.
5674 $mailer->isMail();
5675
5676 } else {
5677 // Use SMTP directly.
5678 $mailer->isSMTP();
5679 if (!empty($CFG->debugsmtp)) {
5680 $mailer->SMTPDebug = true;
5681 }
5682 // Specify main and backup servers.
5683 $mailer->Host = $CFG->smtphosts;
5684 // Specify secure connection protocol.
5685 $mailer->SMTPSecure = $CFG->smtpsecure;
5686 // Use previous keepalive.
5687 $mailer->SMTPKeepAlive = $prevkeepalive;
5688
5689 if ($CFG->smtpuser) {
5690 // Use SMTP authentication.
5691 $mailer->SMTPAuth = true;
5692 $mailer->Username = $CFG->smtpuser;
5693 $mailer->Password = $CFG->smtppass;
5694 }
5695 }
5696
5697 return $mailer;
5698 }
5699
5700 $nothing = null;
5701
5702 // Keep smtp session open after sending.
5703 if ($action == 'buffer') {
5704 if (!empty($CFG->smtpmaxbulk)) {
5705 get_mailer('flush');
5706 $m = get_mailer();
5707 if ($m->Mailer == 'smtp') {
5708 $m->SMTPKeepAlive = true;
5709 }
5710 }
5711 return $nothing;
5712 }
5713
5714 // Close smtp session, but continue buffering.
5715 if ($action == 'flush') {
5716 if (isset($mailer) and $mailer->Mailer == 'smtp') {
5717 if (!empty($mailer->SMTPDebug)) {
5718 echo '<pre>'."\n";
5719 }
5720 $mailer->SmtpClose();
5721 if (!empty($mailer->SMTPDebug)) {
5722 echo '</pre>';
5723 }
5724 }
5725 return $nothing;
5726 }
5727
5728 // Close smtp session, do not buffer anymore.
5729 if ($action == 'close') {
5730 if (isset($mailer) and $mailer->Mailer == 'smtp') {
5731 get_mailer('flush');
5732 $mailer->SMTPKeepAlive = false;
5733 }
5734 $mailer = null; // Better force new instance.
5735 return $nothing;
5736 }
5737}
5738
5739/**
5740 * Send an email to a specified user
5741 *
5742 * @param stdClass $user A {@link $USER} object
5743 * @param stdClass $from A {@link $USER} object
5744 * @param string $subject plain text subject line of the email
5745 * @param string $messagetext plain text version of the message
5746 * @param string $messagehtml complete html version of the message (optional)
5747 * @param string $attachment a file on the filesystem, either relative to $CFG->dataroot or a full path to a file in $CFG->tempdir
5748 * @param string $attachname the name of the file (extension indicates MIME)
5749 * @param bool $usetrueaddress determines whether $from email address should
5750 * be sent out. Will be overruled by user profile setting for maildisplay
5751 * @param string $replyto Email address to reply to
5752 * @param string $replytoname Name of reply to recipient
5753 * @param int $wordwrapwidth custom word wrap width, default 79
5754 * @return bool Returns true if mail was sent OK and false if there was an error.
5755 */
5756function email_to_user($user, $from, $subject, $messagetext, $messagehtml = '', $attachment = '', $attachname = '',
5757 $usetrueaddress = true, $replyto = '', $replytoname = '', $wordwrapwidth = 79) {
5758
5759 global $CFG;
5760
5761 if (empty($user) or empty($user->id)) {
5762 debugging('Can not send email to null user', DEBUG_DEVELOPER);
5763 return false;
5764 }
5765
5766 if (empty($user->email)) {
5767 debugging('Can not send email to user without email: '.$user->id, DEBUG_DEVELOPER);
5768 return false;
5769 }
5770
5771 if (!empty($user->deleted)) {
5772 debugging('Can not send email to deleted user: '.$user->id, DEBUG_DEVELOPER);
5773 return false;
5774 }
5775
5776 if (defined('BEHAT_SITE_RUNNING')) {
5777 // Fake email sending in behat.
5778 return true;
5779 }
5780
5781 if (!empty($CFG->noemailever)) {
5782 // Hidden setting for development sites, set in config.php if needed.
5783 debugging('Not sending email due to $CFG->noemailever config setting', DEBUG_NORMAL);
5784 return true;
5785 }
5786
5787 if (!empty($CFG->divertallemailsto)) {
5788 $subject = "[DIVERTED {$user->email}] $subject";
5789 $user = clone($user);
5790 $user->email = $CFG->divertallemailsto;
5791 }
5792
5793 // Skip mail to suspended users.
5794 if ((isset($user->auth) && $user->auth=='nologin') or (isset($user->suspended) && $user->suspended)) {
5795 return true;
5796 }
5797
5798 if (!validate_email($user->email)) {
5799 // We can not send emails to invalid addresses - it might create security issue or confuse the mailer.
5800 $invalidemail = "User $user->id (".fullname($user).") email ($user->email) is invalid! Not sending.";
5801 error_log($invalidemail);
5802 if (CLI_SCRIPT) {
5803 mtrace('Error: lib/moodlelib.php email_to_user(): '.$invalidemail);
5804 }
5805 return false;
5806 }
5807
5808 if (over_bounce_threshold($user)) {
5809 $bouncemsg = "User $user->id (".fullname($user).") is over bounce threshold! Not sending.";
5810 error_log($bouncemsg);
5811 if (CLI_SCRIPT) {
5812 mtrace('Error: lib/moodlelib.php email_to_user(): '.$bouncemsg);
5813 }
5814 return false;
5815 }
5816
5817 // If the user is a remote mnet user, parse the email text for URL to the
5818 // wwwroot and modify the url to direct the user's browser to login at their
5819 // home site (identity provider - idp) before hitting the link itself.
5820 if (is_mnet_remote_user($user)) {
5821 require_once($CFG->dirroot.'/mnet/lib.php');
5822
5823 $jumpurl = mnet_get_idp_jump_url($user);
5824 $callback = partial('mnet_sso_apply_indirection', $jumpurl);
5825
5826 $messagetext = preg_replace_callback("%($CFG->wwwroot[^[:space:]]*)%",
5827 $callback,
5828 $messagetext);
5829 $messagehtml = preg_replace_callback("%href=[\"'`]($CFG->wwwroot[\w_:\?=#&@/;.~-]*)[\"'`]%",
5830 $callback,
5831 $messagehtml);
5832 }
5833 $mail = get_mailer();
5834
5835 if (!empty($mail->SMTPDebug)) {
5836 echo '<pre>' . "\n";
5837 }
5838
5839 $temprecipients = array();
5840 $tempreplyto = array();
5841
5842 $supportuser = core_user::get_support_user();
5843
5844 // Make up an email address for handling bounces.
5845 if (!empty($CFG->handlebounces)) {
5846 $modargs = 'B'.base64_encode(pack('V', $user->id)).substr(md5($user->email), 0, 16);
5847 $mail->Sender = generate_email_processing_address(0, $modargs);
5848 } else {
5849 $mail->Sender = $supportuser->email;
5850 }
5851
5852 if (!empty($CFG->emailonlyfromnoreplyaddress)) {
5853 $usetrueaddress = false;
5854 if (empty($replyto) && $from->maildisplay) {
5855 $replyto = $from->email;
5856 $replytoname = fullname($from);
5857 }
5858 }
5859
5860 if (is_string($from)) { // So we can pass whatever we want if there is need.
5861 $mail->From = $CFG->noreplyaddress;
5862 $mail->FromName = $from;
5863 } else if ($usetrueaddress and $from->maildisplay) {
5864 $mail->From = $from->email;
5865 $mail->FromName = fullname($from);
5866 } else {
5867 $mail->From = $CFG->noreplyaddress;
5868 $mail->FromName = fullname($from);
5869 if (empty($replyto)) {
5870 $tempreplyto[] = array($CFG->noreplyaddress, get_string('noreplyname'));
5871 }
5872 }
5873
5874 if (!empty($replyto)) {
5875 $tempreplyto[] = array($replyto, $replytoname);
5876 }
5877
5878 $mail->Subject = substr($subject, 0, 900);
5879
5880 $temprecipients[] = array($user->email, fullname($user));
5881
5882 // Set word wrap.
5883 $mail->WordWrap = $wordwrapwidth;
5884
5885 if (!empty($from->customheaders)) {
5886 // Add custom headers.
5887 if (is_array($from->customheaders)) {
5888 foreach ($from->customheaders as $customheader) {
5889 $mail->addCustomHeader($customheader);
5890 }
5891 } else {
5892 $mail->addCustomHeader($from->customheaders);
5893 }
5894 }
5895
5896 if (!empty($from->priority)) {
5897 $mail->Priority = $from->priority;
5898 }
5899
5900 if ($messagehtml && !empty($user->mailformat) && $user->mailformat == 1) {
5901 // Don't ever send HTML to users who don't want it.
5902 $mail->isHTML(true);
5903 $mail->Encoding = 'quoted-printable';
5904 $mail->Body = $messagehtml;
5905 $mail->AltBody = "\n$messagetext\n";
5906 } else {
5907 $mail->IsHTML(false);
5908 $mail->Body = "\n$messagetext\n";
5909 }
5910
5911 if ($attachment && $attachname) {
5912 if (preg_match( "~\\.\\.~" , $attachment )) {
5913 // Security check for ".." in dir path.
5914 $temprecipients[] = array($supportuser->email, fullname($supportuser, true));
5915 $mail->addStringAttachment('Error in attachment. User attempted to attach a filename with a unsafe name.', 'error.txt', '8bit', 'text/plain');
5916 } else {
5917 require_once($CFG->libdir.'/filelib.php');
5918 $mimetype = mimeinfo('type', $attachname);
5919
5920 $attachmentpath = $attachment;
5921
5922 // Before doing the comparison, make sure that the paths are correct (Windows uses slashes in the other direction).
5923 $attachpath = str_replace('\\', '/', $attachmentpath);
5924 // Make sure both variables are normalised before comparing.
5925 $temppath = str_replace('\\', '/', $CFG->tempdir);
5926
5927 // If the attachment is a full path to a file in the tempdir, use it as is,
5928 // otherwise assume it is a relative path from the dataroot (for backwards compatibility reasons).
5929 if (strpos($attachpath, $temppath) !== 0) {
5930 $attachmentpath = $CFG->dataroot . '/' . $attachmentpath;
5931 }
5932
5933 $mail->addAttachment($attachmentpath, $attachname, 'base64', $mimetype);
5934 }
5935 }
5936
5937 // Check if the email should be sent in an other charset then the default UTF-8.
5938 if ((!empty($CFG->sitemailcharset) || !empty($CFG->allowusermailcharset))) {
5939
5940 // Use the defined site mail charset or eventually the one preferred by the recipient.
5941 $charset = $CFG->sitemailcharset;
5942 if (!empty($CFG->allowusermailcharset)) {
5943 if ($useremailcharset = get_user_preferences('mailcharset', '0', $user->id)) {
5944 $charset = $useremailcharset;
5945 }
5946 }
5947
5948 // Convert all the necessary strings if the charset is supported.
5949 $charsets = get_list_of_charsets();
5950 unset($charsets['UTF-8']);
5951 if (in_array($charset, $charsets)) {
5952 $mail->CharSet = $charset;
5953 $mail->FromName = core_text::convert($mail->FromName, 'utf-8', strtolower($charset));
5954 $mail->Subject = core_text::convert($mail->Subject, 'utf-8', strtolower($charset));
5955 $mail->Body = core_text::convert($mail->Body, 'utf-8', strtolower($charset));
5956 $mail->AltBody = core_text::convert($mail->AltBody, 'utf-8', strtolower($charset));
5957
5958 foreach ($temprecipients as $key => $values) {
5959 $temprecipients[$key][1] = core_text::convert($values[1], 'utf-8', strtolower($charset));
5960 }
5961 foreach ($tempreplyto as $key => $values) {
5962 $tempreplyto[$key][1] = core_text::convert($values[1], 'utf-8', strtolower($charset));
5963 }
5964 }
5965 }
5966
5967 foreach ($temprecipients as $values) {
5968 $mail->addAddress($values[0], $values[1]);
5969 }
5970 foreach ($tempreplyto as $values) {
5971 $mail->addReplyTo($values[0], $values[1]);
5972 }
5973
5974 if ($mail->send()) {
5975 set_send_count($user);
5976 if (!empty($mail->SMTPDebug)) {
5977 echo '</pre>';
5978 }
5979 return true;
5980 } else {
5981 // Trigger event for failing to send email.
5982 $event = \core\event\email_failed::create(array(
5983 'context' => context_system::instance(),
5984 'userid' => $from->id,
5985 'relateduserid' => $user->id,
5986 'other' => array(
5987 'subject' => $subject,
5988 'message' => $messagetext,
5989 'errorinfo' => $mail->ErrorInfo
5990 )
5991 ));
5992 $event->trigger();
5993 if (CLI_SCRIPT) {
5994 mtrace('Error: lib/moodlelib.php email_to_user(): '.$mail->ErrorInfo);
5995 }
5996 if (!empty($mail->SMTPDebug)) {
5997 echo '</pre>';
5998 }
5999 return false;
6000 }
6001}
6002
6003/**
6004 * Generate a signoff for emails based on support settings
6005 *
6006 * @return string
6007 */
6008function generate_email_signoff() {
6009 global $CFG;
6010
6011 $signoff = "\n";
6012 if (!empty($CFG->supportname)) {
6013 $signoff .= $CFG->supportname."\n";
6014 }
6015 if (!empty($CFG->supportemail)) {
6016 $signoff .= $CFG->supportemail."\n";
6017 }
6018 if (!empty($CFG->supportpage)) {
6019 $signoff .= $CFG->supportpage."\n";
6020 }
6021 return $signoff;
6022}
6023
6024/**
6025 * Sets specified user's password and send the new password to the user via email.
6026 *
6027 * @param stdClass $user A {@link $USER} object
6028 * @param bool $fasthash If true, use a low cost factor when generating the hash for speed.
6029 * @return bool|string Returns "true" if mail was sent OK and "false" if there was an error
6030 */
6031function setnew_password_and_mail($user, $fasthash = false) {
6032 global $CFG, $DB;
6033
6034 // We try to send the mail in language the user understands,
6035 // unfortunately the filter_string() does not support alternative langs yet
6036 // so multilang will not work properly for site->fullname.
6037 $lang = empty($user->lang) ? $CFG->lang : $user->lang;
6038
6039 $site = get_site();
6040
6041 $supportuser = core_user::get_support_user();
6042
6043 $newpassword = generate_password();
6044
6045 update_internal_user_password($user, $newpassword, $fasthash);
6046
6047 $a = new stdClass();
6048 $a->firstname = fullname($user, true);
6049 $a->sitename = format_string($site->fullname);
6050 $a->username = $user->username;
6051 $a->newpassword = $newpassword;
6052 $a->link = $CFG->wwwroot .'/login/';
6053 $a->signoff = generate_email_signoff();
6054
6055 $message = (string)new lang_string('newusernewpasswordtext', '', $a, $lang);
6056
6057 $subject = format_string($site->fullname) .': '. (string)new lang_string('newusernewpasswordsubj', '', $a, $lang);
6058
6059 // Directly email rather than using the messaging system to ensure its not routed to a popup or jabber.
6060 return email_to_user($user, $supportuser, $subject, $message);
6061
6062}
6063
6064/**
6065 * Resets specified user's password and send the new password to the user via email.
6066 *
6067 * @param stdClass $user A {@link $USER} object
6068 * @return bool Returns true if mail was sent OK and false if there was an error.
6069 */
6070function reset_password_and_mail($user) {
6071 global $CFG;
6072
6073 $site = get_site();
6074 $supportuser = core_user::get_support_user();
6075
6076 $userauth = get_auth_plugin($user->auth);
6077 if (!$userauth->can_reset_password() or !is_enabled_auth($user->auth)) {
6078 trigger_error("Attempt to reset user password for user $user->username with Auth $user->auth.");
6079 return false;
6080 }
6081
6082 $newpassword = generate_password();
6083
6084 if (!$userauth->user_update_password($user, $newpassword)) {
6085 print_error("cannotsetpassword");
6086 }
6087
6088 $a = new stdClass();
6089 $a->firstname = $user->firstname;
6090 $a->lastname = $user->lastname;
6091 $a->sitename = format_string($site->fullname);
6092 $a->username = $user->username;
6093 $a->newpassword = $newpassword;
6094 $a->link = $CFG->httpswwwroot .'/login/change_password.php';
6095 $a->signoff = generate_email_signoff();
6096
6097 $message = get_string('newpasswordtext', '', $a);
6098
6099 $subject = format_string($site->fullname) .': '. get_string('changedpassword');
6100
6101 unset_user_preference('create_password', $user); // Prevent cron from generating the password.
6102
6103 // Directly email rather than using the messaging system to ensure its not routed to a popup or jabber.
6104 return email_to_user($user, $supportuser, $subject, $message);
6105}
6106
6107/**
6108 * Send email to specified user with confirmation text and activation link.
6109 *
6110 * @param stdClass $user A {@link $USER} object
6111 * @return bool Returns true if mail was sent OK and false if there was an error.
6112 */
6113function send_confirmation_email($user) {
6114 global $CFG;
6115
6116 $site = get_site();
6117 $supportuser = core_user::get_support_user();
6118
6119 $data = new stdClass();
6120 $data->firstname = fullname($user);
6121 $data->sitename = format_string($site->fullname);
6122 $data->admin = generate_email_signoff();
6123
6124 $subject = get_string('emailconfirmationsubject', '', format_string($site->fullname));
6125
6126 $username = urlencode($user->username);
6127 $username = str_replace('.', '%2E', $username); // Prevent problems with trailing dots.
6128 $data->link = $CFG->wwwroot .'/login/confirm.php?data='. $user->secret .'/'. $username;
6129 $message = get_string('emailconfirmation', '', $data);
6130 $messagehtml = text_to_html(get_string('emailconfirmation', '', $data), false, false, true);
6131
6132 $user->mailformat = 1; // Always send HTML version as well.
6133
6134 // Directly email rather than using the messaging system to ensure its not routed to a popup or jabber.
6135 return email_to_user($user, $supportuser, $subject, $message, $messagehtml);
6136}
6137
6138/**
6139 * Sends a password change confirmation email.
6140 *
6141 * @param stdClass $user A {@link $USER} object
6142 * @param stdClass $resetrecord An object tracking metadata regarding password reset request
6143 * @return bool Returns true if mail was sent OK and false if there was an error.
6144 */
6145function send_password_change_confirmation_email($user, $resetrecord) {
6146 global $CFG;
6147
6148 $site = get_site();
6149 $supportuser = core_user::get_support_user();
6150 $pwresetmins = isset($CFG->pwresettime) ? floor($CFG->pwresettime / MINSECS) : 30;
6151
6152 $data = new stdClass();
6153 $data->firstname = $user->firstname;
6154 $data->lastname = $user->lastname;
6155 $data->username = $user->username;
6156 $data->sitename = format_string($site->fullname);
6157 $data->link = $CFG->httpswwwroot .'/login/forgot_password.php?token='. $resetrecord->token;
6158 $data->admin = generate_email_signoff();
6159 $data->resetminutes = $pwresetmins;
6160
6161 $message = get_string('emailresetconfirmation', '', $data);
6162 $subject = get_string('emailresetconfirmationsubject', '', format_string($site->fullname));
6163
6164 // Directly email rather than using the messaging system to ensure its not routed to a popup or jabber.
6165 return email_to_user($user, $supportuser, $subject, $message);
6166
6167}
6168
6169/**
6170 * Sends an email containinginformation on how to change your password.
6171 *
6172 * @param stdClass $user A {@link $USER} object
6173 * @return bool Returns true if mail was sent OK and false if there was an error.
6174 */
6175function send_password_change_info($user) {
6176 global $CFG;
6177
6178 $site = get_site();
6179 $supportuser = core_user::get_support_user();
6180 $systemcontext = context_system::instance();
6181
6182 $data = new stdClass();
6183 $data->firstname = $user->firstname;
6184 $data->lastname = $user->lastname;
6185 $data->sitename = format_string($site->fullname);
6186 $data->admin = generate_email_signoff();
6187
6188 $userauth = get_auth_plugin($user->auth);
6189
6190 if (!is_enabled_auth($user->auth) or $user->auth == 'nologin') {
6191 $message = get_string('emailpasswordchangeinfodisabled', '', $data);
6192 $subject = get_string('emailpasswordchangeinfosubject', '', format_string($site->fullname));
6193 // Directly email rather than using the messaging system to ensure its not routed to a popup or jabber.
6194 return email_to_user($user, $supportuser, $subject, $message);
6195 }
6196
6197 if ($userauth->can_change_password() and $userauth->change_password_url()) {
6198 // We have some external url for password changing.
6199 $data->link .= $userauth->change_password_url();
6200
6201 } else {
6202 // No way to change password, sorry.
6203 $data->link = '';
6204 }
6205
6206 if (!empty($data->link) and has_capability('moodle/user:changeownpassword', $systemcontext, $user->id)) {
6207 $message = get_string('emailpasswordchangeinfo', '', $data);
6208 $subject = get_string('emailpasswordchangeinfosubject', '', format_string($site->fullname));
6209 } else {
6210 $message = get_string('emailpasswordchangeinfofail', '', $data);
6211 $subject = get_string('emailpasswordchangeinfosubject', '', format_string($site->fullname));
6212 }
6213
6214 // Directly email rather than using the messaging system to ensure its not routed to a popup or jabber.
6215 return email_to_user($user, $supportuser, $subject, $message);
6216
6217}
6218
6219/**
6220 * Check that an email is allowed. It returns an error message if there was a problem.
6221 *
6222 * @param string $email Content of email
6223 * @return string|false
6224 */
6225function email_is_not_allowed($email) {
6226 global $CFG;
6227
6228 if (!empty($CFG->allowemailaddresses)) {
6229 $allowed = explode(' ', $CFG->allowemailaddresses);
6230 foreach ($allowed as $allowedpattern) {
6231 $allowedpattern = trim($allowedpattern);
6232 if (!$allowedpattern) {
6233 continue;
6234 }
6235 if (strpos($allowedpattern, '.') === 0) {
6236 if (strpos(strrev($email), strrev($allowedpattern)) === 0) {
6237 // Subdomains are in a form ".example.com" - matches "xxx@anything.example.com".
6238 return false;
6239 }
6240
6241 } else if (strpos(strrev($email), strrev('@'.$allowedpattern)) === 0) {
6242 return false;
6243 }
6244 }
6245 return get_string('emailonlyallowed', '', $CFG->allowemailaddresses);
6246
6247 } else if (!empty($CFG->denyemailaddresses)) {
6248 $denied = explode(' ', $CFG->denyemailaddresses);
6249 foreach ($denied as $deniedpattern) {
6250 $deniedpattern = trim($deniedpattern);
6251 if (!$deniedpattern) {
6252 continue;
6253 }
6254 if (strpos($deniedpattern, '.') === 0) {
6255 if (strpos(strrev($email), strrev($deniedpattern)) === 0) {
6256 // Subdomains are in a form ".example.com" - matches "xxx@anything.example.com".
6257 return get_string('emailnotallowed', '', $CFG->denyemailaddresses);
6258 }
6259
6260 } else if (strpos(strrev($email), strrev('@'.$deniedpattern)) === 0) {
6261 return get_string('emailnotallowed', '', $CFG->denyemailaddresses);
6262 }
6263 }
6264 }
6265
6266 return false;
6267}
6268
6269// FILE HANDLING.
6270
6271/**
6272 * Returns local file storage instance
6273 *
6274 * @return file_storage
6275 */
6276function get_file_storage() {
6277 global $CFG;
6278
6279 static $fs = null;
6280
6281 if ($fs) {
6282 return $fs;
6283 }
6284
6285 require_once("$CFG->libdir/filelib.php");
6286
6287 if (isset($CFG->filedir)) {
6288 $filedir = $CFG->filedir;
6289 } else {
6290 $filedir = $CFG->dataroot.'/filedir';
6291 }
6292
6293 if (isset($CFG->trashdir)) {
6294 $trashdirdir = $CFG->trashdir;
6295 } else {
6296 $trashdirdir = $CFG->dataroot.'/trashdir';
6297 }
6298
6299 $fs = new file_storage($filedir, $trashdirdir, "$CFG->tempdir/filestorage", $CFG->directorypermissions, $CFG->filepermissions);
6300
6301 return $fs;
6302}
6303
6304/**
6305 * Returns local file storage instance
6306 *
6307 * @return file_browser
6308 */
6309function get_file_browser() {
6310 global $CFG;
6311
6312 static $fb = null;
6313
6314 if ($fb) {
6315 return $fb;
6316 }
6317
6318 require_once("$CFG->libdir/filelib.php");
6319
6320 $fb = new file_browser();
6321
6322 return $fb;
6323}
6324
6325/**
6326 * Returns file packer
6327 *
6328 * @param string $mimetype default application/zip
6329 * @return file_packer
6330 */
6331function get_file_packer($mimetype='application/zip') {
6332 global $CFG;
6333
6334 static $fp = array();
6335
6336 if (isset($fp[$mimetype])) {
6337 return $fp[$mimetype];
6338 }
6339
6340 switch ($mimetype) {
6341 case 'application/zip':
6342 case 'application/vnd.moodle.profiling':
6343 $classname = 'zip_packer';
6344 break;
6345
6346 case 'application/x-gzip' :
6347 $classname = 'tgz_packer';
6348 break;
6349
6350 case 'application/vnd.moodle.backup':
6351 $classname = 'mbz_packer';
6352 break;
6353
6354 default:
6355 return false;
6356 }
6357
6358 require_once("$CFG->libdir/filestorage/$classname.php");
6359 $fp[$mimetype] = new $classname();
6360
6361 return $fp[$mimetype];
6362}
6363
6364/**
6365 * Returns current name of file on disk if it exists.
6366 *
6367 * @param string $newfile File to be verified
6368 * @return string Current name of file on disk if true
6369 */
6370function valid_uploaded_file($newfile) {
6371 if (empty($newfile)) {
6372 return '';
6373 }
6374 if (is_uploaded_file($newfile['tmp_name']) and $newfile['size'] > 0) {
6375 return $newfile['tmp_name'];
6376 } else {
6377 return '';
6378 }
6379}
6380
6381/**
6382 * Returns the maximum size for uploading files.
6383 *
6384 * There are seven possible upload limits:
6385 * 1. in Apache using LimitRequestBody (no way of checking or changing this)
6386 * 2. in php.ini for 'upload_max_filesize' (can not be changed inside PHP)
6387 * 3. in .htaccess for 'upload_max_filesize' (can not be changed inside PHP)
6388 * 4. in php.ini for 'post_max_size' (can not be changed inside PHP)
6389 * 5. by the Moodle admin in $CFG->maxbytes
6390 * 6. by the teacher in the current course $course->maxbytes
6391 * 7. by the teacher for the current module, eg $assignment->maxbytes
6392 *
6393 * These last two are passed to this function as arguments (in bytes).
6394 * Anything defined as 0 is ignored.
6395 * The smallest of all the non-zero numbers is returned.
6396 *
6397 * @todo Finish documenting this function
6398 *
6399 * @param int $sitebytes Set maximum size
6400 * @param int $coursebytes Current course $course->maxbytes (in bytes)
6401 * @param int $modulebytes Current module ->maxbytes (in bytes)
6402 * @return int The maximum size for uploading files.
6403 */
6404function get_max_upload_file_size($sitebytes=0, $coursebytes=0, $modulebytes=0) {
6405
6406 if (! $filesize = ini_get('upload_max_filesize')) {
6407 $filesize = '5M';
6408 }
6409 $minimumsize = get_real_size($filesize);
6410
6411 if ($postsize = ini_get('post_max_size')) {
6412 $postsize = get_real_size($postsize);
6413 if ($postsize < $minimumsize) {
6414 $minimumsize = $postsize;
6415 }
6416 }
6417
6418 if (($sitebytes > 0) and ($sitebytes < $minimumsize)) {
6419 $minimumsize = $sitebytes;
6420 }
6421
6422 if (($coursebytes > 0) and ($coursebytes < $minimumsize)) {
6423 $minimumsize = $coursebytes;
6424 }
6425
6426 if (($modulebytes > 0) and ($modulebytes < $minimumsize)) {
6427 $minimumsize = $modulebytes;
6428 }
6429
6430 return $minimumsize;
6431}
6432
6433/**
6434 * Returns the maximum size for uploading files for the current user
6435 *
6436 * This function takes in account {@link get_max_upload_file_size()} the user's capabilities
6437 *
6438 * @param context $context The context in which to check user capabilities
6439 * @param int $sitebytes Set maximum size
6440 * @param int $coursebytes Current course $course->maxbytes (in bytes)
6441 * @param int $modulebytes Current module ->maxbytes (in bytes)
6442 * @param stdClass $user The user
6443 * @return int The maximum size for uploading files.
6444 */
6445function get_user_max_upload_file_size($context, $sitebytes = 0, $coursebytes = 0, $modulebytes = 0, $user = null) {
6446 global $USER;
6447
6448 if (empty($user)) {
6449 $user = $USER;
6450 }
6451
6452 if (has_capability('moodle/course:ignorefilesizelimits', $context, $user)) {
6453 return USER_CAN_IGNORE_FILE_SIZE_LIMITS;
6454 }
6455
6456 return get_max_upload_file_size($sitebytes, $coursebytes, $modulebytes);
6457}
6458
6459/**
6460 * Returns an array of possible sizes in local language
6461 *
6462 * Related to {@link get_max_upload_file_size()} - this function returns an
6463 * array of possible sizes in an array, translated to the
6464 * local language.
6465 *
6466 * The list of options will go up to the minimum of $sitebytes, $coursebytes or $modulebytes.
6467 *
6468 * If $coursebytes or $sitebytes is not 0, an option will be included for "Course/Site upload limit (X)"
6469 * with the value set to 0. This option will be the first in the list.
6470 *
6471 * @uses SORT_NUMERIC
6472 * @param int $sitebytes Set maximum size
6473 * @param int $coursebytes Current course $course->maxbytes (in bytes)
6474 * @param int $modulebytes Current module ->maxbytes (in bytes)
6475 * @param int|array $custombytes custom upload size/s which will be added to list,
6476 * Only value/s smaller then maxsize will be added to list.
6477 * @return array
6478 */
6479function get_max_upload_sizes($sitebytes = 0, $coursebytes = 0, $modulebytes = 0, $custombytes = null) {
6480 global $CFG;
6481
6482 if (!$maxsize = get_max_upload_file_size($sitebytes, $coursebytes, $modulebytes)) {
6483 return array();
6484 }
6485
6486 if ($sitebytes == 0) {
6487 // Will get the minimum of upload_max_filesize or post_max_size.
6488 $sitebytes = get_max_upload_file_size();
6489 }
6490
6491 $filesize = array();
6492 $sizelist = array(10240, 51200, 102400, 512000, 1048576, 2097152,
6493 5242880, 10485760, 20971520, 52428800, 104857600);
6494
6495 // If custombytes is given and is valid then add it to the list.
6496 if (is_number($custombytes) and $custombytes > 0) {
6497 $custombytes = (int)$custombytes;
6498 if (!in_array($custombytes, $sizelist)) {
6499 $sizelist[] = $custombytes;
6500 }
6501 } else if (is_array($custombytes)) {
6502 $sizelist = array_unique(array_merge($sizelist, $custombytes));
6503 }
6504
6505 // Allow maxbytes to be selected if it falls outside the above boundaries.
6506 if (isset($CFG->maxbytes) && !in_array(get_real_size($CFG->maxbytes), $sizelist)) {
6507 // Note: get_real_size() is used in order to prevent problems with invalid values.
6508 $sizelist[] = get_real_size($CFG->maxbytes);
6509 }
6510
6511 foreach ($sizelist as $sizebytes) {
6512 if ($sizebytes < $maxsize && $sizebytes > 0) {
6513 $filesize[(string)intval($sizebytes)] = display_size($sizebytes);
6514 }
6515 }
6516
6517 $limitlevel = '';
6518 $displaysize = '';
6519 if ($modulebytes &&
6520 (($modulebytes < $coursebytes || $coursebytes == 0) &&
6521 ($modulebytes < $sitebytes || $sitebytes == 0))) {
6522 $limitlevel = get_string('activity', 'core');
6523 $displaysize = display_size($modulebytes);
6524 $filesize[$modulebytes] = $displaysize; // Make sure the limit is also included in the list.
6525
6526 } else if ($coursebytes && ($coursebytes < $sitebytes || $sitebytes == 0)) {
6527 $limitlevel = get_string('course', 'core');
6528 $displaysize = display_size($coursebytes);
6529 $filesize[$coursebytes] = $displaysize; // Make sure the limit is also included in the list.
6530
6531 } else if ($sitebytes) {
6532 $limitlevel = get_string('site', 'core');
6533 $displaysize = display_size($sitebytes);
6534 $filesize[$sitebytes] = $displaysize; // Make sure the limit is also included in the list.
6535 }
6536
6537 krsort($filesize, SORT_NUMERIC);
6538 if ($limitlevel) {
6539 $params = (object) array('contextname' => $limitlevel, 'displaysize' => $displaysize);
6540 $filesize = array('0' => get_string('uploadlimitwithsize', 'core', $params)) + $filesize;
6541 }
6542
6543 return $filesize;
6544}
6545
6546/**
6547 * Returns an array with all the filenames in all subdirectories, relative to the given rootdir.
6548 *
6549 * If excludefiles is defined, then that file/directory is ignored
6550 * If getdirs is true, then (sub)directories are included in the output
6551 * If getfiles is true, then files are included in the output
6552 * (at least one of these must be true!)
6553 *
6554 * @todo Finish documenting this function. Add examples of $excludefile usage.
6555 *
6556 * @param string $rootdir A given root directory to start from
6557 * @param string|array $excludefiles If defined then the specified file/directory is ignored
6558 * @param bool $descend If true then subdirectories are recursed as well
6559 * @param bool $getdirs If true then (sub)directories are included in the output
6560 * @param bool $getfiles If true then files are included in the output
6561 * @return array An array with all the filenames in all subdirectories, relative to the given rootdir
6562 */
6563function get_directory_list($rootdir, $excludefiles='', $descend=true, $getdirs=false, $getfiles=true) {
6564
6565 $dirs = array();
6566
6567 if (!$getdirs and !$getfiles) { // Nothing to show.
6568 return $dirs;
6569 }
6570
6571 if (!is_dir($rootdir)) { // Must be a directory.
6572 return $dirs;
6573 }
6574
6575 if (!$dir = opendir($rootdir)) { // Can't open it for some reason.
6576 return $dirs;
6577 }
6578
6579 if (!is_array($excludefiles)) {
6580 $excludefiles = array($excludefiles);
6581 }
6582
6583 while (false !== ($file = readdir($dir))) {
6584 $firstchar = substr($file, 0, 1);
6585 if ($firstchar == '.' or $file == 'CVS' or in_array($file, $excludefiles)) {
6586 continue;
6587 }
6588 $fullfile = $rootdir .'/'. $file;
6589 if (filetype($fullfile) == 'dir') {
6590 if ($getdirs) {
6591 $dirs[] = $file;
6592 }
6593 if ($descend) {
6594 $subdirs = get_directory_list($fullfile, $excludefiles, $descend, $getdirs, $getfiles);
6595 foreach ($subdirs as $subdir) {
6596 $dirs[] = $file .'/'. $subdir;
6597 }
6598 }
6599 } else if ($getfiles) {
6600 $dirs[] = $file;
6601 }
6602 }
6603 closedir($dir);
6604
6605 asort($dirs);
6606
6607 return $dirs;
6608}
6609
6610
6611/**
6612 * Adds up all the files in a directory and works out the size.
6613 *
6614 * @param string $rootdir The directory to start from
6615 * @param string $excludefile A file to exclude when summing directory size
6616 * @return int The summed size of all files and subfiles within the root directory
6617 */
6618function get_directory_size($rootdir, $excludefile='') {
6619 global $CFG;
6620
6621 // Do it this way if we can, it's much faster.
6622 if (!empty($CFG->pathtodu) && is_executable(trim($CFG->pathtodu))) {
6623 $command = trim($CFG->pathtodu).' -sk '.escapeshellarg($rootdir);
6624 $output = null;
6625 $return = null;
6626 exec($command, $output, $return);
6627 if (is_array($output)) {
6628 // We told it to return k.
6629 return get_real_size(intval($output[0]).'k');
6630 }
6631 }
6632
6633 if (!is_dir($rootdir)) {
6634 // Must be a directory.
6635 return 0;
6636 }
6637
6638 if (!$dir = @opendir($rootdir)) {
6639 // Can't open it for some reason.
6640 return 0;
6641 }
6642
6643 $size = 0;
6644
6645 while (false !== ($file = readdir($dir))) {
6646 $firstchar = substr($file, 0, 1);
6647 if ($firstchar == '.' or $file == 'CVS' or $file == $excludefile) {
6648 continue;
6649 }
6650 $fullfile = $rootdir .'/'. $file;
6651 if (filetype($fullfile) == 'dir') {
6652 $size += get_directory_size($fullfile, $excludefile);
6653 } else {
6654 $size += filesize($fullfile);
6655 }
6656 }
6657 closedir($dir);
6658
6659 return $size;
6660}
6661
6662/**
6663 * Converts bytes into display form
6664 *
6665 * @static string $gb Localized string for size in gigabytes
6666 * @static string $mb Localized string for size in megabytes
6667 * @static string $kb Localized string for size in kilobytes
6668 * @static string $b Localized string for size in bytes
6669 * @param int $size The size to convert to human readable form
6670 * @return string
6671 */
6672function display_size($size) {
6673
6674 static $gb, $mb, $kb, $b;
6675
6676 if ($size === USER_CAN_IGNORE_FILE_SIZE_LIMITS) {
6677 return get_string('unlimited');
6678 }
6679
6680 if (empty($gb)) {
6681 $gb = get_string('sizegb');
6682 $mb = get_string('sizemb');
6683 $kb = get_string('sizekb');
6684 $b = get_string('sizeb');
6685 }
6686
6687 if ($size >= 1073741824) {
6688 $size = round($size / 1073741824 * 10) / 10 . $gb;
6689 } else if ($size >= 1048576) {
6690 $size = round($size / 1048576 * 10) / 10 . $mb;
6691 } else if ($size >= 1024) {
6692 $size = round($size / 1024 * 10) / 10 . $kb;
6693 } else {
6694 $size = intval($size) .' '. $b; // File sizes over 2GB can not work in 32bit PHP anyway.
6695 }
6696 return $size;
6697}
6698
6699/**
6700 * Cleans a given filename by removing suspicious or troublesome characters
6701 *
6702 * @see clean_param()
6703 * @param string $string file name
6704 * @return string cleaned file name
6705 */
6706function clean_filename($string) {
6707 return clean_param($string, PARAM_FILE);
6708}
6709
6710
6711// STRING TRANSLATION.
6712
6713/**
6714 * Returns the code for the current language
6715 *
6716 * @category string
6717 * @return string
6718 */
6719function current_language() {
6720 global $CFG, $USER, $SESSION, $COURSE;
6721
6722 if (!empty($SESSION->forcelang)) {
6723 // Allows overriding course-forced language (useful for admins to check
6724 // issues in courses whose language they don't understand).
6725 // Also used by some code to temporarily get language-related information in a
6726 // specific language (see force_current_language()).
6727 $return = $SESSION->forcelang;
6728
6729 } else if (!empty($COURSE->id) and $COURSE->id != SITEID and !empty($COURSE->lang)) {
6730 // Course language can override all other settings for this page.
6731 $return = $COURSE->lang;
6732
6733 } else if (!empty($SESSION->lang)) {
6734 // Session language can override other settings.
6735 $return = $SESSION->lang;
6736
6737 } else if (!empty($USER->lang)) {
6738 $return = $USER->lang;
6739
6740 } else if (isset($CFG->lang)) {
6741 $return = $CFG->lang;
6742
6743 } else {
6744 $return = 'en';
6745 }
6746
6747 // Just in case this slipped in from somewhere by accident.
6748 $return = str_replace('_utf8', '', $return);
6749
6750 return $return;
6751}
6752
6753/**
6754 * Returns parent language of current active language if defined
6755 *
6756 * @category string
6757 * @param string $lang null means current language
6758 * @return string
6759 */
6760function get_parent_language($lang=null) {
6761
6762 // Let's hack around the current language.
6763 if (!empty($lang)) {
6764 $oldforcelang = force_current_language($lang);
6765 }
6766
6767 $parentlang = get_string('parentlanguage', 'langconfig');
6768 if ($parentlang === 'en') {
6769 $parentlang = '';
6770 }
6771
6772 // Let's hack around the current language.
6773 if (!empty($lang)) {
6774 force_current_language($oldforcelang);
6775 }
6776
6777 return $parentlang;
6778}
6779
6780/**
6781 * Force the current language to get strings and dates localised in the given language.
6782 *
6783 * After calling this function, all strings will be provided in the given language
6784 * until this function is called again, or equivalent code is run.
6785 *
6786 * @param string $language
6787 * @return string previous $SESSION->forcelang value
6788 */
6789function force_current_language($language) {
6790 global $SESSION;
6791 $sessionforcelang = isset($SESSION->forcelang) ? $SESSION->forcelang : '';
6792 if ($language !== $sessionforcelang) {
6793 // Seting forcelang to null or an empty string disables it's effect.
6794 if (empty($language) || get_string_manager()->translation_exists($language, false)) {
6795 $SESSION->forcelang = $language;
6796 moodle_setlocale();
6797 }
6798 }
6799 return $sessionforcelang;
6800}
6801
6802/**
6803 * Returns current string_manager instance.
6804 *
6805 * The param $forcereload is needed for CLI installer only where the string_manager instance
6806 * must be replaced during the install.php script life time.
6807 *
6808 * @category string
6809 * @param bool $forcereload shall the singleton be released and new instance created instead?
6810 * @return core_string_manager
6811 */
6812function get_string_manager($forcereload=false) {
6813 global $CFG;
6814
6815 static $singleton = null;
6816
6817 if ($forcereload) {
6818 $singleton = null;
6819 }
6820 if ($singleton === null) {
6821 if (empty($CFG->early_install_lang)) {
6822
6823 if (empty($CFG->langlist)) {
6824 $translist = array();
6825 } else {
6826 $translist = explode(',', $CFG->langlist);
6827 }
6828
6829 $singleton = new core_string_manager_standard($CFG->langotherroot, $CFG->langlocalroot, $translist);
6830
6831 } else {
6832 $singleton = new core_string_manager_install();
6833 }
6834 }
6835
6836 return $singleton;
6837}
6838
6839/**
6840 * Returns a localized string.
6841 *
6842 * Returns the translated string specified by $identifier as
6843 * for $module. Uses the same format files as STphp.
6844 * $a is an object, string or number that can be used
6845 * within translation strings
6846 *
6847 * eg 'hello {$a->firstname} {$a->lastname}'
6848 * or 'hello {$a}'
6849 *
6850 * If you would like to directly echo the localized string use
6851 * the function {@link print_string()}
6852 *
6853 * Example usage of this function involves finding the string you would
6854 * like a local equivalent of and using its identifier and module information
6855 * to retrieve it.<br/>
6856 * If you open moodle/lang/en/moodle.php and look near line 278
6857 * you will find a string to prompt a user for their word for 'course'
6858 * <code>
6859 * $string['course'] = 'Course';
6860 * </code>
6861 * So if you want to display the string 'Course'
6862 * in any language that supports it on your site
6863 * you just need to use the identifier 'course'
6864 * <code>
6865 * $mystring = '<strong>'. get_string('course') .'</strong>';
6866 * or
6867 * </code>
6868 * If the string you want is in another file you'd take a slightly
6869 * different approach. Looking in moodle/lang/en/calendar.php you find
6870 * around line 75:
6871 * <code>
6872 * $string['typecourse'] = 'Course event';
6873 * </code>
6874 * If you want to display the string "Course event" in any language
6875 * supported you would use the identifier 'typecourse' and the module 'calendar'
6876 * (because it is in the file calendar.php):
6877 * <code>
6878 * $mystring = '<h1>'. get_string('typecourse', 'calendar') .'</h1>';
6879 * </code>
6880 *
6881 * As a last resort, should the identifier fail to map to a string
6882 * the returned string will be [[ $identifier ]]
6883 *
6884 * In Moodle 2.3 there is a new argument to this function $lazyload.
6885 * Setting $lazyload to true causes get_string to return a lang_string object
6886 * rather than the string itself. The fetching of the string is then put off until
6887 * the string object is first used. The object can be used by calling it's out
6888 * method or by casting the object to a string, either directly e.g.
6889 * (string)$stringobject
6890 * or indirectly by using the string within another string or echoing it out e.g.
6891 * echo $stringobject
6892 * return "<p>{$stringobject}</p>";
6893 * It is worth noting that using $lazyload and attempting to use the string as an
6894 * array key will cause a fatal error as objects cannot be used as array keys.
6895 * But you should never do that anyway!
6896 * For more information {@link lang_string}
6897 *
6898 * @category string
6899 * @param string $identifier The key identifier for the localized string
6900 * @param string $component The module where the key identifier is stored,
6901 * usually expressed as the filename in the language pack without the
6902 * .php on the end but can also be written as mod/forum or grade/export/xls.
6903 * If none is specified then moodle.php is used.
6904 * @param string|object|array $a An object, string or number that can be used
6905 * within translation strings
6906 * @param bool $lazyload If set to true a string object is returned instead of
6907 * the string itself. The string then isn't calculated until it is first used.
6908 * @return string The localized string.
6909 * @throws coding_exception
6910 */
6911function get_string($identifier, $component = '', $a = null, $lazyload = false) {
6912 global $CFG;
6913
6914 // If the lazy load argument has been supplied return a lang_string object
6915 // instead.
6916 // We need to make sure it is true (and a bool) as you will see below there
6917 // used to be a forth argument at one point.
6918 if ($lazyload === true) {
6919 return new lang_string($identifier, $component, $a);
6920 }
6921
6922 if ($CFG->debugdeveloper && clean_param($identifier, PARAM_STRINGID) === '') {
6923 throw new coding_exception('Invalid string identifier. The identifier cannot be empty. Please fix your get_string() call.', DEBUG_DEVELOPER);
6924 }
6925
6926 // There is now a forth argument again, this time it is a boolean however so
6927 // we can still check for the old extralocations parameter.
6928 if (!is_bool($lazyload) && !empty($lazyload)) {
6929 debugging('extralocations parameter in get_string() is not supported any more, please use standard lang locations only.');
6930 }
6931
6932 if (strpos($component, '/') !== false) {
6933 debugging('The module name you passed to get_string is the deprecated format ' .
6934 'like mod/mymod or block/myblock. The correct form looks like mymod, or block_myblock.' , DEBUG_DEVELOPER);
6935 $componentpath = explode('/', $component);
6936
6937 switch ($componentpath[0]) {
6938 case 'mod':
6939 $component = $componentpath[1];
6940 break;
6941 case 'blocks':
6942 case 'block':
6943 $component = 'block_'.$componentpath[1];
6944 break;
6945 case 'enrol':
6946 $component = 'enrol_'.$componentpath[1];
6947 break;
6948 case 'format':
6949 $component = 'format_'.$componentpath[1];
6950 break;
6951 case 'grade':
6952 $component = 'grade'.$componentpath[1].'_'.$componentpath[2];
6953 break;
6954 }
6955 }
6956
6957 $result = get_string_manager()->get_string($identifier, $component, $a);
6958
6959 // Debugging feature lets you display string identifier and component.
6960 if (isset($CFG->debugstringids) && $CFG->debugstringids && optional_param('strings', 0, PARAM_INT)) {
6961 $result .= ' {' . $identifier . '/' . $component . '}';
6962 }
6963 return $result;
6964}
6965
6966/**
6967 * Converts an array of strings to their localized value.
6968 *
6969 * @param array $array An array of strings
6970 * @param string $component The language module that these strings can be found in.
6971 * @return stdClass translated strings.
6972 */
6973function get_strings($array, $component = '') {
6974 $string = new stdClass;
6975 foreach ($array as $item) {
6976 $string->$item = get_string($item, $component);
6977 }
6978 return $string;
6979}
6980
6981/**
6982 * Prints out a translated string.
6983 *
6984 * Prints out a translated string using the return value from the {@link get_string()} function.
6985 *
6986 * Example usage of this function when the string is in the moodle.php file:<br/>
6987 * <code>
6988 * echo '<strong>';
6989 * print_string('course');
6990 * echo '</strong>';
6991 * </code>
6992 *
6993 * Example usage of this function when the string is not in the moodle.php file:<br/>
6994 * <code>
6995 * echo '<h1>';
6996 * print_string('typecourse', 'calendar');
6997 * echo '</h1>';
6998 * </code>
6999 *
7000 * @category string
7001 * @param string $identifier The key identifier for the localized string
7002 * @param string $component The module where the key identifier is stored. If none is specified then moodle.php is used.
7003 * @param string|object|array $a An object, string or number that can be used within translation strings
7004 */
7005function print_string($identifier, $component = '', $a = null) {
7006 echo get_string($identifier, $component, $a);
7007}
7008
7009/**
7010 * Returns a list of charset codes
7011 *
7012 * Returns a list of charset codes. It's hardcoded, so they should be added manually
7013 * (checking that such charset is supported by the texlib library!)
7014 *
7015 * @return array And associative array with contents in the form of charset => charset
7016 */
7017function get_list_of_charsets() {
7018
7019 $charsets = array(
7020 'EUC-JP' => 'EUC-JP',
7021 'ISO-2022-JP'=> 'ISO-2022-JP',
7022 'ISO-8859-1' => 'ISO-8859-1',
7023 'SHIFT-JIS' => 'SHIFT-JIS',
7024 'GB2312' => 'GB2312',
7025 'GB18030' => 'GB18030', // GB18030 not supported by typo and mbstring.
7026 'UTF-8' => 'UTF-8');
7027
7028 asort($charsets);
7029
7030 return $charsets;
7031}
7032
7033/**
7034 * Returns a list of valid and compatible themes
7035 *
7036 * @return array
7037 */
7038function get_list_of_themes() {
7039 global $CFG;
7040
7041 $themes = array();
7042
7043 if (!empty($CFG->themelist)) { // Use admin's list of themes.
7044 $themelist = explode(',', $CFG->themelist);
7045 } else {
7046 $themelist = array_keys(core_component::get_plugin_list("theme"));
7047 }
7048
7049 foreach ($themelist as $key => $themename) {
7050 $theme = theme_config::load($themename);
7051 $themes[$themename] = $theme;
7052 }
7053
7054 core_collator::asort_objects_by_method($themes, 'get_theme_name');
7055
7056 return $themes;
7057}
7058
7059/**
7060 * Returns a list of timezones in the current language
7061 *
7062 * @return array
7063 */
7064function get_list_of_timezones() {
7065 global $DB;
7066
7067 static $timezones;
7068
7069 if (!empty($timezones)) { // This function has been called recently.
7070 return $timezones;
7071 }
7072
7073 $timezones = array();
7074
7075 if ($rawtimezones = $DB->get_records_sql("SELECT MAX(id), name FROM {timezone} GROUP BY name")) {
7076 foreach ($rawtimezones as $timezone) {
7077 if (!empty($timezone->name)) {
7078 if (get_string_manager()->string_exists(strtolower($timezone->name), 'timezones')) {
7079 $timezones[$timezone->name] = get_string(strtolower($timezone->name), 'timezones');
7080 } else {
7081 $timezones[$timezone->name] = $timezone->name;
7082 }
7083 if (substr($timezones[$timezone->name], 0, 1) == '[') { // No translation found.
7084 $timezones[$timezone->name] = $timezone->name;
7085 }
7086 }
7087 }
7088 }
7089
7090 asort($timezones);
7091
7092 for ($i = -13; $i <= 13; $i += .5) {
7093 $tzstring = 'UTC';
7094 if ($i < 0) {
7095 $timezones[sprintf("%.1f", $i)] = $tzstring . $i;
7096 } else if ($i > 0) {
7097 $timezones[sprintf("%.1f", $i)] = $tzstring . '+' . $i;
7098 } else {
7099 $timezones[sprintf("%.1f", $i)] = $tzstring;
7100 }
7101 }
7102
7103 return $timezones;
7104}
7105
7106/**
7107 * Factory function for emoticon_manager
7108 *
7109 * @return emoticon_manager singleton
7110 */
7111function get_emoticon_manager() {
7112 static $singleton = null;
7113
7114 if (is_null($singleton)) {
7115 $singleton = new emoticon_manager();
7116 }
7117
7118 return $singleton;
7119}
7120
7121/**
7122 * Provides core support for plugins that have to deal with emoticons (like HTML editor or emoticon filter).
7123 *
7124 * Whenever this manager mentiones 'emoticon object', the following data
7125 * structure is expected: stdClass with properties text, imagename, imagecomponent,
7126 * altidentifier and altcomponent
7127 *
7128 * @see admin_setting_emoticons
7129 *
7130 * @copyright 2010 David Mudrak
7131 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
7132 */
7133class emoticon_manager {
7134
7135 /**
7136 * Returns the currently enabled emoticons
7137 *
7138 * @return array of emoticon objects
7139 */
7140 public function get_emoticons() {
7141 global $CFG;
7142
7143 if (empty($CFG->emoticons)) {
7144 return array();
7145 }
7146
7147 $emoticons = $this->decode_stored_config($CFG->emoticons);
7148
7149 if (!is_array($emoticons)) {
7150 // Something is wrong with the format of stored setting.
7151 debugging('Invalid format of emoticons setting, please resave the emoticons settings form', DEBUG_NORMAL);
7152 return array();
7153 }
7154
7155 return $emoticons;
7156 }
7157
7158 /**
7159 * Converts emoticon object into renderable pix_emoticon object
7160 *
7161 * @param stdClass $emoticon emoticon object
7162 * @param array $attributes explicit HTML attributes to set
7163 * @return pix_emoticon
7164 */
7165 public function prepare_renderable_emoticon(stdClass $emoticon, array $attributes = array()) {
7166 $stringmanager = get_string_manager();
7167 if ($stringmanager->string_exists($emoticon->altidentifier, $emoticon->altcomponent)) {
7168 $alt = get_string($emoticon->altidentifier, $emoticon->altcomponent);
7169 } else {
7170 $alt = s($emoticon->text);
7171 }
7172 return new pix_emoticon($emoticon->imagename, $alt, $emoticon->imagecomponent, $attributes);
7173 }
7174
7175 /**
7176 * Encodes the array of emoticon objects into a string storable in config table
7177 *
7178 * @see self::decode_stored_config()
7179 * @param array $emoticons array of emtocion objects
7180 * @return string
7181 */
7182 public function encode_stored_config(array $emoticons) {
7183 return json_encode($emoticons);
7184 }
7185
7186 /**
7187 * Decodes the string into an array of emoticon objects
7188 *
7189 * @see self::encode_stored_config()
7190 * @param string $encoded
7191 * @return string|null
7192 */
7193 public function decode_stored_config($encoded) {
7194 $decoded = json_decode($encoded);
7195 if (!is_array($decoded)) {
7196 return null;
7197 }
7198 return $decoded;
7199 }
7200
7201 /**
7202 * Returns default set of emoticons supported by Moodle
7203 *
7204 * @return array of sdtClasses
7205 */
7206 public function default_emoticons() {
7207 return array(
7208 $this->prepare_emoticon_object(":-)", 's/smiley', 'smiley'),
7209 $this->prepare_emoticon_object(":)", 's/smiley', 'smiley'),
7210 $this->prepare_emoticon_object(":-D", 's/biggrin', 'biggrin'),
7211 $this->prepare_emoticon_object(";-)", 's/wink', 'wink'),
7212 $this->prepare_emoticon_object(":-/", 's/mixed', 'mixed'),
7213 $this->prepare_emoticon_object("V-.", 's/thoughtful', 'thoughtful'),
7214 $this->prepare_emoticon_object(":-P", 's/tongueout', 'tongueout'),
7215 $this->prepare_emoticon_object(":-p", 's/tongueout', 'tongueout'),
7216 $this->prepare_emoticon_object("B-)", 's/cool', 'cool'),
7217 $this->prepare_emoticon_object("^-)", 's/approve', 'approve'),
7218 $this->prepare_emoticon_object("8-)", 's/wideeyes', 'wideeyes'),
7219 $this->prepare_emoticon_object(":o)", 's/clown', 'clown'),
7220 $this->prepare_emoticon_object(":-(", 's/sad', 'sad'),
7221 $this->prepare_emoticon_object(":(", 's/sad', 'sad'),
7222 $this->prepare_emoticon_object("8-.", 's/shy', 'shy'),
7223 $this->prepare_emoticon_object(":-I", 's/blush', 'blush'),
7224 $this->prepare_emoticon_object(":-X", 's/kiss', 'kiss'),
7225 $this->prepare_emoticon_object("8-o", 's/surprise', 'surprise'),
7226 $this->prepare_emoticon_object("P-|", 's/blackeye', 'blackeye'),
7227 $this->prepare_emoticon_object("8-[", 's/angry', 'angry'),
7228 $this->prepare_emoticon_object("(grr)", 's/angry', 'angry'),
7229 $this->prepare_emoticon_object("xx-P", 's/dead', 'dead'),
7230 $this->prepare_emoticon_object("|-.", 's/sleepy', 'sleepy'),
7231 $this->prepare_emoticon_object("}-]", 's/evil', 'evil'),
7232 $this->prepare_emoticon_object("(h)", 's/heart', 'heart'),
7233 $this->prepare_emoticon_object("(heart)", 's/heart', 'heart'),
7234 $this->prepare_emoticon_object("(y)", 's/yes', 'yes', 'core'),
7235 $this->prepare_emoticon_object("(n)", 's/no', 'no', 'core'),
7236 $this->prepare_emoticon_object("(martin)", 's/martin', 'martin'),
7237 $this->prepare_emoticon_object("( )", 's/egg', 'egg'),
7238 );
7239 }
7240
7241 /**
7242 * Helper method preparing the stdClass with the emoticon properties
7243 *
7244 * @param string|array $text or array of strings
7245 * @param string $imagename to be used by {@link pix_emoticon}
7246 * @param string $altidentifier alternative string identifier, null for no alt
7247 * @param string $altcomponent where the alternative string is defined
7248 * @param string $imagecomponent to be used by {@link pix_emoticon}
7249 * @return stdClass
7250 */
7251 protected function prepare_emoticon_object($text, $imagename, $altidentifier = null,
7252 $altcomponent = 'core_pix', $imagecomponent = 'core') {
7253 return (object)array(
7254 'text' => $text,
7255 'imagename' => $imagename,
7256 'imagecomponent' => $imagecomponent,
7257 'altidentifier' => $altidentifier,
7258 'altcomponent' => $altcomponent,
7259 );
7260 }
7261}
7262
7263// ENCRYPTION.
7264
7265/**
7266 * rc4encrypt
7267 *
7268 * @param string $data Data to encrypt.
7269 * @return string The now encrypted data.
7270 */
7271function rc4encrypt($data) {
7272 return endecrypt(get_site_identifier(), $data, '');
7273}
7274
7275/**
7276 * rc4decrypt
7277 *
7278 * @param string $data Data to decrypt.
7279 * @return string The now decrypted data.
7280 */
7281function rc4decrypt($data) {
7282 return endecrypt(get_site_identifier(), $data, 'de');
7283}
7284
7285/**
7286 * Based on a class by Mukul Sabharwal [mukulsabharwal @ yahoo.com]
7287 *
7288 * @todo Finish documenting this function
7289 *
7290 * @param string $pwd The password to use when encrypting or decrypting
7291 * @param string $data The data to be decrypted/encrypted
7292 * @param string $case Either 'de' for decrypt or '' for encrypt
7293 * @return string
7294 */
7295function endecrypt ($pwd, $data, $case) {
7296
7297 if ($case == 'de') {
7298 $data = urldecode($data);
7299 }
7300
7301 $key[] = '';
7302 $box[] = '';
7303 $pwdlength = strlen($pwd);
7304
7305 for ($i = 0; $i <= 255; $i++) {
7306 $key[$i] = ord(substr($pwd, ($i % $pwdlength), 1));
7307 $box[$i] = $i;
7308 }
7309
7310 $x = 0;
7311
7312 for ($i = 0; $i <= 255; $i++) {
7313 $x = ($x + $box[$i] + $key[$i]) % 256;
7314 $tempswap = $box[$i];
7315 $box[$i] = $box[$x];
7316 $box[$x] = $tempswap;
7317 }
7318
7319 $cipher = '';
7320
7321 $a = 0;
7322 $j = 0;
7323
7324 for ($i = 0; $i < strlen($data); $i++) {
7325 $a = ($a + 1) % 256;
7326 $j = ($j + $box[$a]) % 256;
7327 $temp = $box[$a];
7328 $box[$a] = $box[$j];
7329 $box[$j] = $temp;
7330 $k = $box[(($box[$a] + $box[$j]) % 256)];
7331 $cipherby = ord(substr($data, $i, 1)) ^ $k;
7332 $cipher .= chr($cipherby);
7333 }
7334
7335 if ($case == 'de') {
7336 $cipher = urldecode(urlencode($cipher));
7337 } else {
7338 $cipher = urlencode($cipher);
7339 }
7340
7341 return $cipher;
7342}
7343
7344// ENVIRONMENT CHECKING.
7345
7346/**
7347 * This method validates a plug name. It is much faster than calling clean_param.
7348 *
7349 * @param string $name a string that might be a plugin name.
7350 * @return bool if this string is a valid plugin name.
7351 */
7352function is_valid_plugin_name($name) {
7353 // This does not work for 'mod', bad luck, use any other type.
7354 return core_component::is_valid_plugin_name('tool', $name);
7355}
7356
7357/**
7358 * Get a list of all the plugins of a given type that define a certain API function
7359 * in a certain file. The plugin component names and function names are returned.
7360 *
7361 * @param string $plugintype the type of plugin, e.g. 'mod' or 'report'.
7362 * @param string $function the part of the name of the function after the
7363 * frankenstyle prefix. e.g 'hook' if you are looking for functions with
7364 * names like report_courselist_hook.
7365 * @param string $file the name of file within the plugin that defines the
7366 * function. Defaults to lib.php.
7367 * @return array with frankenstyle plugin names as keys (e.g. 'report_courselist', 'mod_forum')
7368 * and the function names as values (e.g. 'report_courselist_hook', 'forum_hook').
7369 */
7370function get_plugin_list_with_function($plugintype, $function, $file = 'lib.php') {
7371 $pluginfunctions = array();
7372 $pluginswithfile = core_component::get_plugin_list_with_file($plugintype, $file, true);
7373 foreach ($pluginswithfile as $plugin => $notused) {
7374 $fullfunction = $plugintype . '_' . $plugin . '_' . $function;
7375
7376 if (function_exists($fullfunction)) {
7377 // Function exists with standard name. Store, indexed by frankenstyle name of plugin.
7378 $pluginfunctions[$plugintype . '_' . $plugin] = $fullfunction;
7379
7380 } else if ($plugintype === 'mod') {
7381 // For modules, we also allow plugin without full frankenstyle but just starting with the module name.
7382 $shortfunction = $plugin . '_' . $function;
7383 if (function_exists($shortfunction)) {
7384 $pluginfunctions[$plugintype . '_' . $plugin] = $shortfunction;
7385 }
7386 }
7387 }
7388 return $pluginfunctions;
7389}
7390
7391/**
7392 * Lists plugin-like directories within specified directory
7393 *
7394 * This function was originally used for standard Moodle plugins, please use
7395 * new core_component::get_plugin_list() now.
7396 *
7397 * This function is used for general directory listing and backwards compatility.
7398 *
7399 * @param string $directory relative directory from root
7400 * @param string $exclude dir name to exclude from the list (defaults to none)
7401 * @param string $basedir full path to the base dir where $plugin resides (defaults to $CFG->dirroot)
7402 * @return array Sorted array of directory names found under the requested parameters
7403 */
7404function get_list_of_plugins($directory='mod', $exclude='', $basedir='') {
7405 global $CFG;
7406
7407 $plugins = array();
7408
7409 if (empty($basedir)) {
7410 $basedir = $CFG->dirroot .'/'. $directory;
7411
7412 } else {
7413 $basedir = $basedir .'/'. $directory;
7414 }
7415
7416 if ($CFG->debugdeveloper and empty($exclude)) {
7417 // Make sure devs do not use this to list normal plugins,
7418 // this is intended for general directories that are not plugins!
7419
7420 $subtypes = core_component::get_plugin_types();
7421 if (in_array($basedir, $subtypes)) {
7422 debugging('get_list_of_plugins() should not be used to list real plugins, use core_component::get_plugin_list() instead!', DEBUG_DEVELOPER);
7423 }
7424 unset($subtypes);
7425 }
7426
7427 if (file_exists($basedir) && filetype($basedir) == 'dir') {
7428 if (!$dirhandle = opendir($basedir)) {
7429 debugging("Directory permission error for plugin ({$directory}). Directory exists but cannot be read.", DEBUG_DEVELOPER);
7430 return array();
7431 }
7432 while (false !== ($dir = readdir($dirhandle))) {
7433 // Func: strpos is marginally but reliably faster than substr($dir, 0, 1).
7434 if (strpos($dir, '.') === 0 or $dir === 'CVS' or $dir === '_vti_cnf' or $dir === 'simpletest' or $dir === 'yui' or
7435 $dir === 'tests' or $dir === 'classes' or $dir === $exclude) {
7436 continue;
7437 }
7438 if (filetype($basedir .'/'. $dir) != 'dir') {
7439 continue;
7440 }
7441 $plugins[] = $dir;
7442 }
7443 closedir($dirhandle);
7444 }
7445 if ($plugins) {
7446 asort($plugins);
7447 }
7448 return $plugins;
7449}
7450
7451/**
7452 * Invoke plugin's callback functions
7453 *
7454 * @param string $type plugin type e.g. 'mod'
7455 * @param string $name plugin name
7456 * @param string $feature feature name
7457 * @param string $action feature's action
7458 * @param array $params parameters of callback function, should be an array
7459 * @param mixed $default default value if callback function hasn't been defined, or if it retursn null.
7460 * @return mixed
7461 *
7462 * @todo Decide about to deprecate and drop plugin_callback() - MDL-30743
7463 */
7464function plugin_callback($type, $name, $feature, $action, $params = null, $default = null) {
7465 return component_callback($type . '_' . $name, $feature . '_' . $action, (array) $params, $default);
7466}
7467
7468/**
7469 * Invoke component's callback functions
7470 *
7471 * @param string $component frankenstyle component name, e.g. 'mod_quiz'
7472 * @param string $function the rest of the function name, e.g. 'cron' will end up calling 'mod_quiz_cron'
7473 * @param array $params parameters of callback function
7474 * @param mixed $default default value if callback function hasn't been defined, or if it retursn null.
7475 * @return mixed
7476 */
7477function component_callback($component, $function, array $params = array(), $default = null) {
7478
7479 $functionname = component_callback_exists($component, $function);
7480
7481 if ($functionname) {
7482 // Function exists, so just return function result.
7483 $ret = call_user_func_array($functionname, $params);
7484 if (is_null($ret)) {
7485 return $default;
7486 } else {
7487 return $ret;
7488 }
7489 }
7490 return $default;
7491}
7492
7493/**
7494 * Determine if a component callback exists and return the function name to call. Note that this
7495 * function will include the required library files so that the functioname returned can be
7496 * called directly.
7497 *
7498 * @param string $component frankenstyle component name, e.g. 'mod_quiz'
7499 * @param string $function the rest of the function name, e.g. 'cron' will end up calling 'mod_quiz_cron'
7500 * @return mixed Complete function name to call if the callback exists or false if it doesn't.
7501 * @throws coding_exception if invalid component specfied
7502 */
7503function component_callback_exists($component, $function) {
7504 global $CFG; // This is needed for the inclusions.
7505
7506 $cleancomponent = clean_param($component, PARAM_COMPONENT);
7507 if (empty($cleancomponent)) {
7508 throw new coding_exception('Invalid component used in plugin/component_callback():' . $component);
7509 }
7510 $component = $cleancomponent;
7511
7512 list($type, $name) = core_component::normalize_component($component);
7513 $component = $type . '_' . $name;
7514
7515 $oldfunction = $name.'_'.$function;
7516 $function = $component.'_'.$function;
7517
7518 $dir = core_component::get_component_directory($component);
7519 if (empty($dir)) {
7520 throw new coding_exception('Invalid component used in plugin/component_callback():' . $component);
7521 }
7522
7523 // Load library and look for function.
7524 if (file_exists($dir.'/lib.php')) {
7525 require_once($dir.'/lib.php');
7526 }
7527
7528 if (!function_exists($function) and function_exists($oldfunction)) {
7529 if ($type !== 'mod' and $type !== 'core') {
7530 debugging("Please use new function name $function instead of legacy $oldfunction", DEBUG_DEVELOPER);
7531 }
7532 $function = $oldfunction;
7533 }
7534
7535 if (function_exists($function)) {
7536 return $function;
7537 }
7538 return false;
7539}
7540
7541/**
7542 * Checks whether a plugin supports a specified feature.
7543 *
7544 * @param string $type Plugin type e.g. 'mod'
7545 * @param string $name Plugin name e.g. 'forum'
7546 * @param string $feature Feature code (FEATURE_xx constant)
7547 * @param mixed $default default value if feature support unknown
7548 * @return mixed Feature result (false if not supported, null if feature is unknown,
7549 * otherwise usually true but may have other feature-specific value such as array)
7550 * @throws coding_exception
7551 */
7552function plugin_supports($type, $name, $feature, $default = null) {
7553 global $CFG;
7554
7555 if ($type === 'mod' and $name === 'NEWMODULE') {
7556 // Somebody forgot to rename the module template.
7557 return false;
7558 }
7559
7560 $component = clean_param($type . '_' . $name, PARAM_COMPONENT);
7561 if (empty($component)) {
7562 throw new coding_exception('Invalid component used in plugin_supports():' . $type . '_' . $name);
7563 }
7564
7565 $function = null;
7566
7567 if ($type === 'mod') {
7568 // We need this special case because we support subplugins in modules,
7569 // otherwise it would end up in infinite loop.
7570 if (file_exists("$CFG->dirroot/mod/$name/lib.php")) {
7571 include_once("$CFG->dirroot/mod/$name/lib.php");
7572 $function = $component.'_supports';
7573 if (!function_exists($function)) {
7574 // Legacy non-frankenstyle function name.
7575 $function = $name.'_supports';
7576 }
7577 }
7578
7579 } else {
7580 if (!$path = core_component::get_plugin_directory($type, $name)) {
7581 // Non existent plugin type.
7582 return false;
7583 }
7584 if (file_exists("$path/lib.php")) {
7585 include_once("$path/lib.php");
7586 $function = $component.'_supports';
7587 }
7588 }
7589
7590 if ($function and function_exists($function)) {
7591 $supports = $function($feature);
7592 if (is_null($supports)) {
7593 // Plugin does not know - use default.
7594 return $default;
7595 } else {
7596 return $supports;
7597 }
7598 }
7599
7600 // Plugin does not care, so use default.
7601 return $default;
7602}
7603
7604/**
7605 * Returns true if the current version of PHP is greater that the specified one.
7606 *
7607 * @todo Check PHP version being required here is it too low?
7608 *
7609 * @param string $version The version of php being tested.
7610 * @return bool
7611 */
7612function check_php_version($version='5.2.4') {
7613 return (version_compare(phpversion(), $version) >= 0);
7614}
7615
7616/**
7617 * Determine if moodle installation requires update.
7618 *
7619 * Checks version numbers of main code and all plugins to see
7620 * if there are any mismatches.
7621 *
7622 * @return bool
7623 */
7624function moodle_needs_upgrading() {
7625 global $CFG;
7626
7627 if (empty($CFG->version)) {
7628 return true;
7629 }
7630
7631 // There is no need to purge plugininfo caches here because
7632 // these caches are not used during upgrade and they are purged after
7633 // every upgrade.
7634
7635 if (empty($CFG->allversionshash)) {
7636 return true;
7637 }
7638
7639 $hash = core_component::get_all_versions_hash();
7640
7641 return ($hash !== $CFG->allversionshash);
7642}
7643
7644/**
7645 * Returns the major version of this site
7646 *
7647 * Moodle version numbers consist of three numbers separated by a dot, for
7648 * example 1.9.11 or 2.0.2. The first two numbers, like 1.9 or 2.0, represent so
7649 * called major version. This function extracts the major version from either
7650 * $CFG->release (default) or eventually from the $release variable defined in
7651 * the main version.php.
7652 *
7653 * @param bool $fromdisk should the version if source code files be used
7654 * @return string|false the major version like '2.3', false if could not be determined
7655 */
7656function moodle_major_version($fromdisk = false) {
7657 global $CFG;
7658
7659 if ($fromdisk) {
7660 $release = null;
7661 require($CFG->dirroot.'/version.php');
7662 if (empty($release)) {
7663 return false;
7664 }
7665
7666 } else {
7667 if (empty($CFG->release)) {
7668 return false;
7669 }
7670 $release = $CFG->release;
7671 }
7672
7673 if (preg_match('/^[0-9]+\.[0-9]+/', $release, $matches)) {
7674 return $matches[0];
7675 } else {
7676 return false;
7677 }
7678}
7679
7680// MISCELLANEOUS.
7681
7682/**
7683 * Sets the system locale
7684 *
7685 * @category string
7686 * @param string $locale Can be used to force a locale
7687 */
7688function moodle_setlocale($locale='') {
7689 global $CFG;
7690
7691 static $currentlocale = ''; // Last locale caching.
7692
7693 $oldlocale = $currentlocale;
7694
7695 // Fetch the correct locale based on ostype.
7696 if ($CFG->ostype == 'WINDOWS') {
7697 $stringtofetch = 'localewin';
7698 } else {
7699 $stringtofetch = 'locale';
7700 }
7701
7702 // The priority is the same as in get_string() - parameter, config, course, session, user, global language.
7703 if (!empty($locale)) {
7704 $currentlocale = $locale;
7705 } else if (!empty($CFG->locale)) { // Override locale for all language packs.
7706 $currentlocale = $CFG->locale;
7707 } else {
7708 $currentlocale = get_string($stringtofetch, 'langconfig');
7709 }
7710
7711 // Do nothing if locale already set up.
7712 if ($oldlocale == $currentlocale) {
7713 return;
7714 }
7715
7716 // Due to some strange BUG we cannot set the LC_TIME directly, so we fetch current values,
7717 // set LC_ALL and then set values again. Just wondering why we cannot set LC_ALL only??? - stronk7
7718 // Some day, numeric, monetary and other categories should be set too, I think. :-/.
7719
7720 // Get current values.
7721 $monetary= setlocale (LC_MONETARY, 0);
7722 $numeric = setlocale (LC_NUMERIC, 0);
7723 $ctype = setlocale (LC_CTYPE, 0);
7724 if ($CFG->ostype != 'WINDOWS') {
7725 $messages= setlocale (LC_MESSAGES, 0);
7726 }
7727 // Set locale to all.
7728 $result = setlocale (LC_ALL, $currentlocale);
7729 // If setting of locale fails try the other utf8 or utf-8 variant,
7730 // some operating systems support both (Debian), others just one (OSX).
7731 if ($result === false) {
7732 if (stripos($currentlocale, '.UTF-8') !== false) {
7733 $newlocale = str_ireplace('.UTF-8', '.UTF8', $currentlocale);
7734 setlocale (LC_ALL, $newlocale);
7735 } else if (stripos($currentlocale, '.UTF8') !== false) {
7736 $newlocale = str_ireplace('.UTF8', '.UTF-8', $currentlocale);
7737 setlocale (LC_ALL, $newlocale);
7738 }
7739 }
7740 // Set old values.
7741 setlocale (LC_MONETARY, $monetary);
7742 setlocale (LC_NUMERIC, $numeric);
7743 if ($CFG->ostype != 'WINDOWS') {
7744 setlocale (LC_MESSAGES, $messages);
7745 }
7746 if ($currentlocale == 'tr_TR' or $currentlocale == 'tr_TR.UTF-8') {
7747 // To workaround a well-known PHP problem with Turkish letter Ii.
7748 setlocale (LC_CTYPE, $ctype);
7749 }
7750}
7751
7752/**
7753 * Count words in a string.
7754 *
7755 * Words are defined as things between whitespace.
7756 *
7757 * @category string
7758 * @param string $string The text to be searched for words.
7759 * @return int The count of words in the specified string
7760 */
7761function count_words($string) {
7762 $string = strip_tags($string);
7763 // Decode HTML entities.
7764 $string = html_entity_decode($string);
7765 // Replace underscores (which are classed as word characters) with spaces.
7766 $string = preg_replace('/_/u', ' ', $string);
7767 // Remove any characters that shouldn't be treated as word boundaries.
7768 $string = preg_replace('/[\'’-]/u', '', $string);
7769 // Remove dots and commas from within numbers only.
7770 $string = preg_replace('/([0-9])[.,]([0-9])/u', '$1$2', $string);
7771
7772 return count(preg_split('/\w\b/u', $string)) - 1;
7773}
7774
7775/**
7776 * Count letters in a string.
7777 *
7778 * Letters are defined as chars not in tags and different from whitespace.
7779 *
7780 * @category string
7781 * @param string $string The text to be searched for letters.
7782 * @return int The count of letters in the specified text.
7783 */
7784function count_letters($string) {
7785 $string = strip_tags($string); // Tags are out now.
7786 $string = preg_replace('/[[:space:]]*/', '', $string); // Whitespace are out now.
7787
7788 return core_text::strlen($string);
7789}
7790
7791/**
7792 * Generate and return a random string of the specified length.
7793 *
7794 * @param int $length The length of the string to be created.
7795 * @return string
7796 */
7797function random_string ($length=15) {
7798 $pool = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
7799 $pool .= 'abcdefghijklmnopqrstuvwxyz';
7800 $pool .= '0123456789';
7801 $poollen = strlen($pool);
7802 $string = '';
7803 for ($i = 0; $i < $length; $i++) {
7804 $string .= substr($pool, (mt_rand()%($poollen)), 1);
7805 }
7806 return $string;
7807}
7808
7809/**
7810 * Generate a complex random string (useful for md5 salts)
7811 *
7812 * This function is based on the above {@link random_string()} however it uses a
7813 * larger pool of characters and generates a string between 24 and 32 characters
7814 *
7815 * @param int $length Optional if set generates a string to exactly this length
7816 * @return string
7817 */
7818function complex_random_string($length=null) {
7819 $pool = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
7820 $pool .= '`~!@#%^&*()_+-=[];,./<>?:{} ';
7821 $poollen = strlen($pool);
7822 if ($length===null) {
7823 $length = floor(rand(24, 32));
7824 }
7825 $string = '';
7826 for ($i = 0; $i < $length; $i++) {
7827 $string .= $pool[(mt_rand()%$poollen)];
7828 }
7829 return $string;
7830}
7831
7832/**
7833 * Given some text (which may contain HTML) and an ideal length,
7834 * this function truncates the text neatly on a word boundary if possible
7835 *
7836 * @category string
7837 * @param string $text text to be shortened
7838 * @param int $ideal ideal string length
7839 * @param boolean $exact if false, $text will not be cut mid-word
7840 * @param string $ending The string to append if the passed string is truncated
7841 * @return string $truncate shortened string
7842 */
7843function shorten_text($text, $ideal=30, $exact = false, $ending='...') {
7844 // If the plain text is shorter than the maximum length, return the whole text.
7845 if (core_text::strlen(preg_replace('/<.*?>/', '', $text)) <= $ideal) {
7846 return $text;
7847 }
7848
7849 // Splits on HTML tags. Each open/close/empty tag will be the first thing
7850 // and only tag in its 'line'.
7851 preg_match_all('/(<.+?>)?([^<>]*)/s', $text, $lines, PREG_SET_ORDER);
7852
7853 $totallength = core_text::strlen($ending);
7854 $truncate = '';
7855
7856 // This array stores information about open and close tags and their position
7857 // in the truncated string. Each item in the array is an object with fields
7858 // ->open (true if open), ->tag (tag name in lower case), and ->pos
7859 // (byte position in truncated text).
7860 $tagdetails = array();
7861
7862 foreach ($lines as $linematchings) {
7863 // If there is any html-tag in this line, handle it and add it (uncounted) to the output.
7864 if (!empty($linematchings[1])) {
7865 // If it's an "empty element" with or without xhtml-conform closing slash (f.e. <br/>).
7866 if (!preg_match('/^<(\s*.+?\/\s*|\s*(img|br|input|hr|area|base|basefont|col|frame|isindex|link|meta|param)(\s.+?)?)>$/is', $linematchings[1])) {
7867 if (preg_match('/^<\s*\/([^\s]+?)\s*>$/s', $linematchings[1], $tagmatchings)) {
7868 // Record closing tag.
7869 $tagdetails[] = (object) array(
7870 'open' => false,
7871 'tag' => core_text::strtolower($tagmatchings[1]),
7872 'pos' => core_text::strlen($truncate),
7873 );
7874
7875 } else if (preg_match('/^<\s*([^\s>!]+).*?>$/s', $linematchings[1], $tagmatchings)) {
7876 // Record opening tag.
7877 $tagdetails[] = (object) array(
7878 'open' => true,
7879 'tag' => core_text::strtolower($tagmatchings[1]),
7880 'pos' => core_text::strlen($truncate),
7881 );
7882 }
7883 }
7884 // Add html-tag to $truncate'd text.
7885 $truncate .= $linematchings[1];
7886 }
7887
7888 // Calculate the length of the plain text part of the line; handle entities as one character.
7889 $contentlength = core_text::strlen(preg_replace('/&[0-9a-z]{2,8};|&#[0-9]{1,7};|&#x[0-9a-f]{1,6};/i', ' ', $linematchings[2]));
7890 if ($totallength + $contentlength > $ideal) {
7891 // The number of characters which are left.
7892 $left = $ideal - $totallength;
7893 $entitieslength = 0;
7894 // Search for html entities.
7895 if (preg_match_all('/&[0-9a-z]{2,8};|&#[0-9]{1,7};|&#x[0-9a-f]{1,6};/i', $linematchings[2], $entities, PREG_OFFSET_CAPTURE)) {
7896 // Calculate the real length of all entities in the legal range.
7897 foreach ($entities[0] as $entity) {
7898 if ($entity[1]+1-$entitieslength <= $left) {
7899 $left--;
7900 $entitieslength += core_text::strlen($entity[0]);
7901 } else {
7902 // No more characters left.
7903 break;
7904 }
7905 }
7906 }
7907 $breakpos = $left + $entitieslength;
7908
7909 // If the words shouldn't be cut in the middle...
7910 if (!$exact) {
7911 // Search the last occurence of a space.
7912 for (; $breakpos > 0; $breakpos--) {
7913 if ($char = core_text::substr($linematchings[2], $breakpos, 1)) {
7914 if ($char === '.' or $char === ' ') {
7915 $breakpos += 1;
7916 break;
7917 } else if (strlen($char) > 2) {
7918 // Chinese/Japanese/Korean text can be truncated at any UTF-8 character boundary.
7919 $breakpos += 1;
7920 break;
7921 }
7922 }
7923 }
7924 }
7925 if ($breakpos == 0) {
7926 // This deals with the test_shorten_text_no_spaces case.
7927 $breakpos = $left + $entitieslength;
7928 } else if ($breakpos > $left + $entitieslength) {
7929 // This deals with the previous for loop breaking on the first char.
7930 $breakpos = $left + $entitieslength;
7931 }
7932
7933 $truncate .= core_text::substr($linematchings[2], 0, $breakpos);
7934 // Maximum length is reached, so get off the loop.
7935 break;
7936 } else {
7937 $truncate .= $linematchings[2];
7938 $totallength += $contentlength;
7939 }
7940
7941 // If the maximum length is reached, get off the loop.
7942 if ($totallength >= $ideal) {
7943 break;
7944 }
7945 }
7946
7947 // Add the defined ending to the text.
7948 $truncate .= $ending;
7949
7950 // Now calculate the list of open html tags based on the truncate position.
7951 $opentags = array();
7952 foreach ($tagdetails as $taginfo) {
7953 if ($taginfo->open) {
7954 // Add tag to the beginning of $opentags list.
7955 array_unshift($opentags, $taginfo->tag);
7956 } else {
7957 // Can have multiple exact same open tags, close the last one.
7958 $pos = array_search($taginfo->tag, array_reverse($opentags, true));
7959 if ($pos !== false) {
7960 unset($opentags[$pos]);
7961 }
7962 }
7963 }
7964
7965 // Close all unclosed html-tags.
7966 foreach ($opentags as $tag) {
7967 $truncate .= '</' . $tag . '>';
7968 }
7969
7970 return $truncate;
7971}
7972
7973
7974/**
7975 * Given dates in seconds, how many weeks is the date from startdate
7976 * The first week is 1, the second 2 etc ...
7977 *
7978 * @param int $startdate Timestamp for the start date
7979 * @param int $thedate Timestamp for the end date
7980 * @return string
7981 */
7982function getweek ($startdate, $thedate) {
7983 if ($thedate < $startdate) {
7984 return 0;
7985 }
7986
7987 return floor(($thedate - $startdate) / WEEKSECS) + 1;
7988}
7989
7990/**
7991 * Returns a randomly generated password of length $maxlen. inspired by
7992 *
7993 * {@link http://www.phpbuilder.com/columns/jesus19990502.php3} and
7994 * {@link http://es2.php.net/manual/en/function.str-shuffle.php#73254}
7995 *
7996 * @param int $maxlen The maximum size of the password being generated.
7997 * @return string
7998 */
7999function generate_password($maxlen=10) {
8000 global $CFG;
8001
8002 if (empty($CFG->passwordpolicy)) {
8003 $fillers = PASSWORD_DIGITS;
8004 $wordlist = file($CFG->wordlist);
8005 $word1 = trim($wordlist[rand(0, count($wordlist) - 1)]);
8006 $word2 = trim($wordlist[rand(0, count($wordlist) - 1)]);
8007 $filler1 = $fillers[rand(0, strlen($fillers) - 1)];
8008 $password = $word1 . $filler1 . $word2;
8009 } else {
8010 $minlen = !empty($CFG->minpasswordlength) ? $CFG->minpasswordlength : 0;
8011 $digits = $CFG->minpassworddigits;
8012 $lower = $CFG->minpasswordlower;
8013 $upper = $CFG->minpasswordupper;
8014 $nonalphanum = $CFG->minpasswordnonalphanum;
8015 $total = $lower + $upper + $digits + $nonalphanum;
8016 // Var minlength should be the greater one of the two ( $minlen and $total ).
8017 $minlen = $minlen < $total ? $total : $minlen;
8018 // Var maxlen can never be smaller than minlen.
8019 $maxlen = $minlen > $maxlen ? $minlen : $maxlen;
8020 $additional = $maxlen - $total;
8021
8022 // Make sure we have enough characters to fulfill
8023 // complexity requirements.
8024 $passworddigits = PASSWORD_DIGITS;
8025 while ($digits > strlen($passworddigits)) {
8026 $passworddigits .= PASSWORD_DIGITS;
8027 }
8028 $passwordlower = PASSWORD_LOWER;
8029 while ($lower > strlen($passwordlower)) {
8030 $passwordlower .= PASSWORD_LOWER;
8031 }
8032 $passwordupper = PASSWORD_UPPER;
8033 while ($upper > strlen($passwordupper)) {
8034 $passwordupper .= PASSWORD_UPPER;
8035 }
8036 $passwordnonalphanum = PASSWORD_NONALPHANUM;
8037 while ($nonalphanum > strlen($passwordnonalphanum)) {
8038 $passwordnonalphanum .= PASSWORD_NONALPHANUM;
8039 }
8040
8041 // Now mix and shuffle it all.
8042 $password = str_shuffle (substr(str_shuffle ($passwordlower), 0, $lower) .
8043 substr(str_shuffle ($passwordupper), 0, $upper) .
8044 substr(str_shuffle ($passworddigits), 0, $digits) .
8045 substr(str_shuffle ($passwordnonalphanum), 0 , $nonalphanum) .
8046 substr(str_shuffle ($passwordlower .
8047 $passwordupper .
8048 $passworddigits .
8049 $passwordnonalphanum), 0 , $additional));
8050 }
8051
8052 return substr ($password, 0, $maxlen);
8053}
8054
8055/**
8056 * Given a float, prints it nicely.
8057 * Localized floats must not be used in calculations!
8058 *
8059 * The stripzeros feature is intended for making numbers look nicer in small
8060 * areas where it is not necessary to indicate the degree of accuracy by showing
8061 * ending zeros. If you turn it on with $decimalpoints set to 3, for example,
8062 * then it will display '5.4' instead of '5.400' or '5' instead of '5.000'.
8063 *
8064 * @param float $float The float to print
8065 * @param int $decimalpoints The number of decimal places to print.
8066 * @param bool $localized use localized decimal separator
8067 * @param bool $stripzeros If true, removes final zeros after decimal point
8068 * @return string locale float
8069 */
8070function format_float($float, $decimalpoints=1, $localized=true, $stripzeros=false) {
8071 if (is_null($float)) {
8072 return '';
8073 }
8074 if ($localized) {
8075 $separator = get_string('decsep', 'langconfig');
8076 } else {
8077 $separator = '.';
8078 }
8079 $result = number_format($float, $decimalpoints, $separator, '');
8080 if ($stripzeros) {
8081 // Remove zeros and final dot if not needed.
8082 $result = preg_replace('~(' . preg_quote($separator) . ')?0+$~', '', $result);
8083 }
8084 return $result;
8085}
8086
8087/**
8088 * Converts locale specific floating point/comma number back to standard PHP float value
8089 * Do NOT try to do any math operations before this conversion on any user submitted floats!
8090 *
8091 * @param string $localefloat locale aware float representation
8092 * @param bool $strict If true, then check the input and return false if it is not a valid number.
8093 * @return mixed float|bool - false or the parsed float.
8094 */
8095function unformat_float($localefloat, $strict = false) {
8096 $localefloat = trim($localefloat);
8097
8098 if ($localefloat == '') {
8099 return null;
8100 }
8101
8102 $localefloat = str_replace(' ', '', $localefloat); // No spaces - those might be used as thousand separators.
8103 $localefloat = str_replace(get_string('decsep', 'langconfig'), '.', $localefloat);
8104
8105 if ($strict && !is_numeric($localefloat)) {
8106 return false;
8107 }
8108
8109 return (float)$localefloat;
8110}
8111
8112/**
8113 * Given a simple array, this shuffles it up just like shuffle()
8114 * Unlike PHP's shuffle() this function works on any machine.
8115 *
8116 * @param array $array The array to be rearranged
8117 * @return array
8118 */
8119function swapshuffle($array) {
8120
8121 $last = count($array) - 1;
8122 for ($i = 0; $i <= $last; $i++) {
8123 $from = rand(0, $last);
8124 $curr = $array[$i];
8125 $array[$i] = $array[$from];
8126 $array[$from] = $curr;
8127 }
8128 return $array;
8129}
8130
8131/**
8132 * Like {@link swapshuffle()}, but works on associative arrays
8133 *
8134 * @param array $array The associative array to be rearranged
8135 * @return array
8136 */
8137function swapshuffle_assoc($array) {
8138
8139 $newarray = array();
8140 $newkeys = swapshuffle(array_keys($array));
8141
8142 foreach ($newkeys as $newkey) {
8143 $newarray[$newkey] = $array[$newkey];
8144 }
8145 return $newarray;
8146}
8147
8148/**
8149 * Given an arbitrary array, and a number of draws,
8150 * this function returns an array with that amount
8151 * of items. The indexes are retained.
8152 *
8153 * @todo Finish documenting this function
8154 *
8155 * @param array $array
8156 * @param int $draws
8157 * @return array
8158 */
8159function draw_rand_array($array, $draws) {
8160
8161 $return = array();
8162
8163 $last = count($array);
8164
8165 if ($draws > $last) {
8166 $draws = $last;
8167 }
8168
8169 while ($draws > 0) {
8170 $last--;
8171
8172 $keys = array_keys($array);
8173 $rand = rand(0, $last);
8174
8175 $return[$keys[$rand]] = $array[$keys[$rand]];
8176 unset($array[$keys[$rand]]);
8177
8178 $draws--;
8179 }
8180
8181 return $return;
8182}
8183
8184/**
8185 * Calculate the difference between two microtimes
8186 *
8187 * @param string $a The first Microtime
8188 * @param string $b The second Microtime
8189 * @return string
8190 */
8191function microtime_diff($a, $b) {
8192 list($adec, $asec) = explode(' ', $a);
8193 list($bdec, $bsec) = explode(' ', $b);
8194 return $bsec - $asec + $bdec - $adec;
8195}
8196
8197/**
8198 * Given a list (eg a,b,c,d,e) this function returns
8199 * an array of 1->a, 2->b, 3->c etc
8200 *
8201 * @param string $list The string to explode into array bits
8202 * @param string $separator The separator used within the list string
8203 * @return array The now assembled array
8204 */
8205function make_menu_from_list($list, $separator=',') {
8206
8207 $array = array_reverse(explode($separator, $list), true);
8208 foreach ($array as $key => $item) {
8209 $outarray[$key+1] = trim($item);
8210 }
8211 return $outarray;
8212}
8213
8214/**
8215 * Creates an array that represents all the current grades that
8216 * can be chosen using the given grading type.
8217 *
8218 * Negative numbers
8219 * are scales, zero is no grade, and positive numbers are maximum
8220 * grades.
8221 *
8222 * @todo Finish documenting this function or better deprecated this completely!
8223 *
8224 * @param int $gradingtype
8225 * @return array
8226 */
8227function make_grades_menu($gradingtype) {
8228 global $DB;
8229
8230 $grades = array();
8231 if ($gradingtype < 0) {
8232 if ($scale = $DB->get_record('scale', array('id'=> (-$gradingtype)))) {
8233 return make_menu_from_list($scale->scale);
8234 }
8235 } else if ($gradingtype > 0) {
8236 for ($i=$gradingtype; $i>=0; $i--) {
8237 $grades[$i] = $i .' / '. $gradingtype;
8238 }
8239 return $grades;
8240 }
8241 return $grades;
8242}
8243
8244/**
8245 * This function returns the number of activities using the given scale in the given course.
8246 *
8247 * @param int $courseid The course ID to check.
8248 * @param int $scaleid The scale ID to check
8249 * @return int
8250 */
8251function course_scale_used($courseid, $scaleid) {
8252 global $CFG, $DB;
8253
8254 $return = 0;
8255
8256 if (!empty($scaleid)) {
8257 if ($cms = get_course_mods($courseid)) {
8258 foreach ($cms as $cm) {
8259 // Check cm->name/lib.php exists.
8260 if (file_exists($CFG->dirroot.'/mod/'.$cm->modname.'/lib.php')) {
8261 include_once($CFG->dirroot.'/mod/'.$cm->modname.'/lib.php');
8262 $functionname = $cm->modname.'_scale_used';
8263 if (function_exists($functionname)) {
8264 if ($functionname($cm->instance, $scaleid)) {
8265 $return++;
8266 }
8267 }
8268 }
8269 }
8270 }
8271
8272 // Check if any course grade item makes use of the scale.
8273 $return += $DB->count_records('grade_items', array('courseid' => $courseid, 'scaleid' => $scaleid));
8274
8275 // Check if any outcome in the course makes use of the scale.
8276 $return += $DB->count_records_sql("SELECT COUNT('x')
8277 FROM {grade_outcomes_courses} goc,
8278 {grade_outcomes} go
8279 WHERE go.id = goc.outcomeid
8280 AND go.scaleid = ? AND goc.courseid = ?",
8281 array($scaleid, $courseid));
8282 }
8283 return $return;
8284}
8285
8286/**
8287 * This function returns the number of activities using scaleid in the entire site
8288 *
8289 * @param int $scaleid
8290 * @param array $courses
8291 * @return int
8292 */
8293function site_scale_used($scaleid, &$courses) {
8294 $return = 0;
8295
8296 if (!is_array($courses) || count($courses) == 0) {
8297 $courses = get_courses("all", false, "c.id, c.shortname");
8298 }
8299
8300 if (!empty($scaleid)) {
8301 if (is_array($courses) && count($courses) > 0) {
8302 foreach ($courses as $course) {
8303 $return += course_scale_used($course->id, $scaleid);
8304 }
8305 }
8306 }
8307 return $return;
8308}
8309
8310/**
8311 * make_unique_id_code
8312 *
8313 * @todo Finish documenting this function
8314 *
8315 * @uses $_SERVER
8316 * @param string $extra Extra string to append to the end of the code
8317 * @return string
8318 */
8319function make_unique_id_code($extra = '') {
8320
8321 $hostname = 'unknownhost';
8322 if (!empty($_SERVER['HTTP_HOST'])) {
8323 $hostname = $_SERVER['HTTP_HOST'];
8324 } else if (!empty($_ENV['HTTP_HOST'])) {
8325 $hostname = $_ENV['HTTP_HOST'];
8326 } else if (!empty($_SERVER['SERVER_NAME'])) {
8327 $hostname = $_SERVER['SERVER_NAME'];
8328 } else if (!empty($_ENV['SERVER_NAME'])) {
8329 $hostname = $_ENV['SERVER_NAME'];
8330 }
8331
8332 $date = gmdate("ymdHis");
8333
8334 $random = random_string(6);
8335
8336 if ($extra) {
8337 return $hostname .'+'. $date .'+'. $random .'+'. $extra;
8338 } else {
8339 return $hostname .'+'. $date .'+'. $random;
8340 }
8341}
8342
8343
8344/**
8345 * Function to check the passed address is within the passed subnet
8346 *
8347 * The parameter is a comma separated string of subnet definitions.
8348 * Subnet strings can be in one of three formats:
8349 * 1: xxx.xxx.xxx.xxx/nn or xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx/nnn (number of bits in net mask)
8350 * 2: xxx.xxx.xxx.xxx-yyy or xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx::xxxx-yyyy (a range of IP addresses in the last group)
8351 * 3: xxx.xxx or xxx.xxx. or xxx:xxx:xxxx or xxx:xxx:xxxx. (incomplete address, a bit non-technical ;-)
8352 * Code for type 1 modified from user posted comments by mediator at
8353 * {@link http://au.php.net/manual/en/function.ip2long.php}
8354 *
8355 * @param string $addr The address you are checking
8356 * @param string $subnetstr The string of subnet addresses
8357 * @return bool
8358 */
8359function address_in_subnet($addr, $subnetstr) {
8360
8361 if ($addr == '0.0.0.0') {
8362 return false;
8363 }
8364 $subnets = explode(',', $subnetstr);
8365 $found = false;
8366 $addr = trim($addr);
8367 $addr = cleanremoteaddr($addr, false); // Normalise.
8368 if ($addr === null) {
8369 return false;
8370 }
8371 $addrparts = explode(':', $addr);
8372
8373 $ipv6 = strpos($addr, ':');
8374
8375 foreach ($subnets as $subnet) {
8376 $subnet = trim($subnet);
8377 if ($subnet === '') {
8378 continue;
8379 }
8380
8381 if (strpos($subnet, '/') !== false) {
8382 // 1: xxx.xxx.xxx.xxx/nn or xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx/nnn.
8383 list($ip, $mask) = explode('/', $subnet);
8384 $mask = trim($mask);
8385 if (!is_number($mask)) {
8386 continue; // Incorect mask number, eh?
8387 }
8388 $ip = cleanremoteaddr($ip, false); // Normalise.
8389 if ($ip === null) {
8390 continue;
8391 }
8392 if (strpos($ip, ':') !== false) {
8393 // IPv6.
8394 if (!$ipv6) {
8395 continue;
8396 }
8397 if ($mask > 128 or $mask < 0) {
8398 continue; // Nonsense.
8399 }
8400 if ($mask == 0) {
8401 return true; // Any address.
8402 }
8403 if ($mask == 128) {
8404 if ($ip === $addr) {
8405 return true;
8406 }
8407 continue;
8408 }
8409 $ipparts = explode(':', $ip);
8410 $modulo = $mask % 16;
8411 $ipnet = array_slice($ipparts, 0, ($mask-$modulo)/16);
8412 $addrnet = array_slice($addrparts, 0, ($mask-$modulo)/16);
8413 if (implode(':', $ipnet) === implode(':', $addrnet)) {
8414 if ($modulo == 0) {
8415 return true;
8416 }
8417 $pos = ($mask-$modulo)/16;
8418 $ipnet = hexdec($ipparts[$pos]);
8419 $addrnet = hexdec($addrparts[$pos]);
8420 $mask = 0xffff << (16 - $modulo);
8421 if (($addrnet & $mask) == ($ipnet & $mask)) {
8422 return true;
8423 }
8424 }
8425
8426 } else {
8427 // IPv4.
8428 if ($ipv6) {
8429 continue;
8430 }
8431 if ($mask > 32 or $mask < 0) {
8432 continue; // Nonsense.
8433 }
8434 if ($mask == 0) {
8435 return true;
8436 }
8437 if ($mask == 32) {
8438 if ($ip === $addr) {
8439 return true;
8440 }
8441 continue;
8442 }
8443 $mask = 0xffffffff << (32 - $mask);
8444 if (((ip2long($addr) & $mask) == (ip2long($ip) & $mask))) {
8445 return true;
8446 }
8447 }
8448
8449 } else if (strpos($subnet, '-') !== false) {
8450 // 2: xxx.xxx.xxx.xxx-yyy or xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx::xxxx-yyyy. A range of IP addresses in the last group.
8451 $parts = explode('-', $subnet);
8452 if (count($parts) != 2) {
8453 continue;
8454 }
8455
8456 if (strpos($subnet, ':') !== false) {
8457 // IPv6.
8458 if (!$ipv6) {
8459 continue;
8460 }
8461 $ipstart = cleanremoteaddr(trim($parts[0]), false); // Normalise.
8462 if ($ipstart === null) {
8463 continue;
8464 }
8465 $ipparts = explode(':', $ipstart);
8466 $start = hexdec(array_pop($ipparts));
8467 $ipparts[] = trim($parts[1]);
8468 $ipend = cleanremoteaddr(implode(':', $ipparts), false); // Normalise.
8469 if ($ipend === null) {
8470 continue;
8471 }
8472 $ipparts[7] = '';
8473 $ipnet = implode(':', $ipparts);
8474 if (strpos($addr, $ipnet) !== 0) {
8475 continue;
8476 }
8477 $ipparts = explode(':', $ipend);
8478 $end = hexdec($ipparts[7]);
8479
8480 $addrend = hexdec($addrparts[7]);
8481
8482 if (($addrend >= $start) and ($addrend <= $end)) {
8483 return true;
8484 }
8485
8486 } else {
8487 // IPv4.
8488 if ($ipv6) {
8489 continue;
8490 }
8491 $ipstart = cleanremoteaddr(trim($parts[0]), false); // Normalise.
8492 if ($ipstart === null) {
8493 continue;
8494 }
8495 $ipparts = explode('.', $ipstart);
8496 $ipparts[3] = trim($parts[1]);
8497 $ipend = cleanremoteaddr(implode('.', $ipparts), false); // Normalise.
8498 if ($ipend === null) {
8499 continue;
8500 }
8501
8502 if ((ip2long($addr) >= ip2long($ipstart)) and (ip2long($addr) <= ip2long($ipend))) {
8503 return true;
8504 }
8505 }
8506
8507 } else {
8508 // 3: xxx.xxx or xxx.xxx. or xxx:xxx:xxxx or xxx:xxx:xxxx.
8509 if (strpos($subnet, ':') !== false) {
8510 // IPv6.
8511 if (!$ipv6) {
8512 continue;
8513 }
8514 $parts = explode(':', $subnet);
8515 $count = count($parts);
8516 if ($parts[$count-1] === '') {
8517 unset($parts[$count-1]); // Trim trailing :'s.
8518 $count--;
8519 $subnet = implode('.', $parts);
8520 }
8521 $isip = cleanremoteaddr($subnet, false); // Normalise.
8522 if ($isip !== null) {
8523 if ($isip === $addr) {
8524 return true;
8525 }
8526 continue;
8527 } else if ($count > 8) {
8528 continue;
8529 }
8530 $zeros = array_fill(0, 8-$count, '0');
8531 $subnet = $subnet.':'.implode(':', $zeros).'/'.($count*16);
8532 if (address_in_subnet($addr, $subnet)) {
8533 return true;
8534 }
8535
8536 } else {
8537 // IPv4.
8538 if ($ipv6) {
8539 continue;
8540 }
8541 $parts = explode('.', $subnet);
8542 $count = count($parts);
8543 if ($parts[$count-1] === '') {
8544 unset($parts[$count-1]); // Trim trailing .
8545 $count--;
8546 $subnet = implode('.', $parts);
8547 }
8548 if ($count == 4) {
8549 $subnet = cleanremoteaddr($subnet, false); // Normalise.
8550 if ($subnet === $addr) {
8551 return true;
8552 }
8553 continue;
8554 } else if ($count > 4) {
8555 continue;
8556 }
8557 $zeros = array_fill(0, 4-$count, '0');
8558 $subnet = $subnet.'.'.implode('.', $zeros).'/'.($count*8);
8559 if (address_in_subnet($addr, $subnet)) {
8560 return true;
8561 }
8562 }
8563 }
8564 }
8565
8566 return false;
8567}
8568
8569/**
8570 * For outputting debugging info
8571 *
8572 * @param string $string The string to write
8573 * @param string $eol The end of line char(s) to use
8574 * @param string $sleep Period to make the application sleep
8575 * This ensures any messages have time to display before redirect
8576 */
8577function mtrace($string, $eol="\n", $sleep=0) {
8578
8579 if (defined('STDOUT') and !PHPUNIT_TEST) {
8580 fwrite(STDOUT, $string.$eol);
8581 } else {
8582 echo $string . $eol;
8583 }
8584
8585 flush();
8586
8587 // Delay to keep message on user's screen in case of subsequent redirect.
8588 if ($sleep) {
8589 sleep($sleep);
8590 }
8591}
8592
8593/**
8594 * Replace 1 or more slashes or backslashes to 1 slash
8595 *
8596 * @param string $path The path to strip
8597 * @return string the path with double slashes removed
8598 */
8599function cleardoubleslashes ($path) {
8600 return preg_replace('/(\/|\\\){1,}/', '/', $path);
8601}
8602
8603/**
8604 * Is current ip in give list?
8605 *
8606 * @param string $list
8607 * @return bool
8608 */
8609function remoteip_in_list($list) {
8610 $inlist = false;
8611 $clientip = getremoteaddr(null);
8612
8613 if (!$clientip) {
8614 // Ensure access on cli.
8615 return true;
8616 }
8617
8618 $list = explode("\n", $list);
8619 foreach ($list as $subnet) {
8620 $subnet = trim($subnet);
8621 if (address_in_subnet($clientip, $subnet)) {
8622 $inlist = true;
8623 break;
8624 }
8625 }
8626 return $inlist;
8627}
8628
8629/**
8630 * Returns most reliable client address
8631 *
8632 * @param string $default If an address can't be determined, then return this
8633 * @return string The remote IP address
8634 */
8635function getremoteaddr($default='0.0.0.0') {
8636 global $CFG;
8637
8638 if (empty($CFG->getremoteaddrconf)) {
8639 // This will happen, for example, before just after the upgrade, as the
8640 // user is redirected to the admin screen.
8641 $variablestoskip = 0;
8642 } else {
8643 $variablestoskip = $CFG->getremoteaddrconf;
8644 }
8645 if (!($variablestoskip & GETREMOTEADDR_SKIP_HTTP_CLIENT_IP)) {
8646 if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
8647 $address = cleanremoteaddr($_SERVER['HTTP_CLIENT_IP']);
8648 return $address ? $address : $default;
8649 }
8650 }
8651 if (!($variablestoskip & GETREMOTEADDR_SKIP_HTTP_X_FORWARDED_FOR)) {
8652 if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
8653 $forwardedaddresses = explode(",", $_SERVER['HTTP_X_FORWARDED_FOR']);
8654 $address = $forwardedaddresses[0];
8655
8656 if (substr_count($address, ":") > 1) {
8657 // Remove port and brackets from IPv6.
8658 if (preg_match("/\[(.*)\]:/", $address, $matches)) {
8659 $address = $matches[1];
8660 }
8661 } else {
8662 // Remove port from IPv4.
8663 if (substr_count($address, ":") == 1) {
8664 $parts = explode(":", $address);
8665 $address = $parts[0];
8666 }
8667 }
8668
8669 $address = cleanremoteaddr($address);
8670 return $address ? $address : $default;
8671 }
8672 }
8673 if (!empty($_SERVER['REMOTE_ADDR'])) {
8674 $address = cleanremoteaddr($_SERVER['REMOTE_ADDR']);
8675 return $address ? $address : $default;
8676 } else {
8677 return $default;
8678 }
8679}
8680
8681/**
8682 * Cleans an ip address. Internal addresses are now allowed.
8683 * (Originally local addresses were not allowed.)
8684 *
8685 * @param string $addr IPv4 or IPv6 address
8686 * @param bool $compress use IPv6 address compression
8687 * @return string normalised ip address string, null if error
8688 */
8689function cleanremoteaddr($addr, $compress=false) {
8690 $addr = trim($addr);
8691
8692 // TODO: maybe add a separate function is_addr_public() or something like this.
8693
8694 if (strpos($addr, ':') !== false) {
8695 // Can be only IPv6.
8696 $parts = explode(':', $addr);
8697 $count = count($parts);
8698
8699 if (strpos($parts[$count-1], '.') !== false) {
8700 // Legacy ipv4 notation.
8701 $last = array_pop($parts);
8702 $ipv4 = cleanremoteaddr($last, true);
8703 if ($ipv4 === null) {
8704 return null;
8705 }
8706 $bits = explode('.', $ipv4);
8707 $parts[] = dechex($bits[0]).dechex($bits[1]);
8708 $parts[] = dechex($bits[2]).dechex($bits[3]);
8709 $count = count($parts);
8710 $addr = implode(':', $parts);
8711 }
8712
8713 if ($count < 3 or $count > 8) {
8714 return null; // Severly malformed.
8715 }
8716
8717 if ($count != 8) {
8718 if (strpos($addr, '::') === false) {
8719 return null; // Malformed.
8720 }
8721 // Uncompress.
8722 $insertat = array_search('', $parts, true);
8723 $missing = array_fill(0, 1 + 8 - $count, '0');
8724 array_splice($parts, $insertat, 1, $missing);
8725 foreach ($parts as $key => $part) {
8726 if ($part === '') {
8727 $parts[$key] = '0';
8728 }
8729 }
8730 }
8731
8732 $adr = implode(':', $parts);
8733 if (!preg_match('/^([0-9a-f]{1,4})(:[0-9a-f]{1,4})*$/i', $adr)) {
8734 return null; // Incorrect format - sorry.
8735 }
8736
8737 // Normalise 0s and case.
8738 $parts = array_map('hexdec', $parts);
8739 $parts = array_map('dechex', $parts);
8740
8741 $result = implode(':', $parts);
8742
8743 if (!$compress) {
8744 return $result;
8745 }
8746
8747 if ($result === '0:0:0:0:0:0:0:0') {
8748 return '::'; // All addresses.
8749 }
8750
8751 $compressed = preg_replace('/(:0)+:0$/', '::', $result, 1);
8752 if ($compressed !== $result) {
8753 return $compressed;
8754 }
8755
8756 $compressed = preg_replace('/^(0:){2,7}/', '::', $result, 1);
8757 if ($compressed !== $result) {
8758 return $compressed;
8759 }
8760
8761 $compressed = preg_replace('/(:0){2,6}:/', '::', $result, 1);
8762 if ($compressed !== $result) {
8763 return $compressed;
8764 }
8765
8766 return $result;
8767 }
8768
8769 // First get all things that look like IPv4 addresses.
8770 $parts = array();
8771 if (!preg_match('/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/', $addr, $parts)) {
8772 return null;
8773 }
8774 unset($parts[0]);
8775
8776 foreach ($parts as $key => $match) {
8777 if ($match > 255) {
8778 return null;
8779 }
8780 $parts[$key] = (int)$match; // Normalise 0s.
8781 }
8782
8783 return implode('.', $parts);
8784}
8785
8786/**
8787 * This function will make a complete copy of anything it's given,
8788 * regardless of whether it's an object or not.
8789 *
8790 * @param mixed $thing Something you want cloned
8791 * @return mixed What ever it is you passed it
8792 */
8793function fullclone($thing) {
8794 return unserialize(serialize($thing));
8795}
8796
8797 /**
8798 * If new messages are waiting for the current user, then insert
8799 * JavaScript to pop up the messaging window into the page
8800 *
8801 * @return void
8802 */
8803function message_popup_window() {
8804 global $USER, $DB, $PAGE, $CFG;
8805
8806 if (!$PAGE->get_popup_notification_allowed() || empty($CFG->messaging)) {
8807 return;
8808 }
8809
8810 if (!isloggedin() || isguestuser()) {
8811 return;
8812 }
8813
8814 if (!isset($USER->message_lastpopup)) {
8815 $USER->message_lastpopup = 0;
8816 } else if ($USER->message_lastpopup > (time()-120)) {
8817 // Don't run the query to check whether to display a popup if its been run in the last 2 minutes.
8818 return;
8819 }
8820
8821 // A quick query to check whether the user has new messages.
8822 $messagecount = $DB->count_records('message', array('useridto' => $USER->id));
8823 if ($messagecount < 1) {
8824 return;
8825 }
8826
8827 // There are unread messages so now do a more complex but slower query.
8828 $messagesql = "SELECT m.id, c.blocked
8829 FROM {message} m
8830 JOIN {message_working} mw ON m.id=mw.unreadmessageid
8831 JOIN {message_processors} p ON mw.processorid=p.id
8832 JOIN {user} u ON m.useridfrom=u.id
8833 LEFT JOIN {message_contacts} c ON c.contactid = m.useridfrom
8834 AND c.userid = m.useridto
8835 WHERE m.useridto = :userid
8836 AND p.name='popup'";
8837
8838 // If the user was last notified over an hour ago we can re-notify them of old messages
8839 // so don't worry about when the new message was sent.
8840 $lastnotifiedlongago = $USER->message_lastpopup < (time()-3600);
8841 if (!$lastnotifiedlongago) {
8842 $messagesql .= 'AND m.timecreated > :lastpopuptime';
8843 }
8844
8845 $waitingmessages = $DB->get_records_sql($messagesql, array('userid' => $USER->id, 'lastpopuptime' => $USER->message_lastpopup));
8846
8847 $validmessages = 0;
8848 foreach ($waitingmessages as $messageinfo) {
8849 if ($messageinfo->blocked) {
8850 // Message is from a user who has since been blocked so just mark it read.
8851 // Get the full message to mark as read.
8852 $messageobject = $DB->get_record('message', array('id' => $messageinfo->id));
8853 message_mark_message_read($messageobject, time());
8854 } else {
8855 $validmessages++;
8856 }
8857 }
8858
8859 if ($validmessages > 0) {
8860 $strmessages = get_string('unreadnewmessages', 'message', $validmessages);
8861 $strgomessage = get_string('gotomessages', 'message');
8862 $strstaymessage = get_string('ignore', 'admin');
8863
8864 $notificationsound = null;
8865 $beep = get_user_preferences('message_beepnewmessage', '');
8866 if (!empty($beep)) {
8867 // Browsers will work down this list until they find something they support.
8868 $sourcetags = html_writer::empty_tag('source', array('src' => $CFG->wwwroot.'/message/bell.wav', 'type' => 'audio/wav'));
8869 $sourcetags .= html_writer::empty_tag('source', array('src' => $CFG->wwwroot.'/message/bell.ogg', 'type' => 'audio/ogg'));
8870 $sourcetags .= html_writer::empty_tag('source', array('src' => $CFG->wwwroot.'/message/bell.mp3', 'type' => 'audio/mpeg'));
8871 $sourcetags .= html_writer::empty_tag('embed', array('src' => $CFG->wwwroot.'/message/bell.wav', 'autostart' => 'true', 'hidden' => 'true'));
8872
8873 $notificationsound = html_writer::tag('audio', $sourcetags, array('preload' => 'auto', 'autoplay' => 'autoplay'));
8874 }
8875
8876 $url = $CFG->wwwroot.'/message/index.php';
8877 $content = html_writer::start_tag('div', array('id' => 'newmessageoverlay', 'class' => 'mdl-align')).
8878 html_writer::start_tag('div', array('id' => 'newmessagetext')).
8879 $strmessages.
8880 html_writer::end_tag('div').
8881
8882 $notificationsound.
8883 html_writer::start_tag('div', array('id' => 'newmessagelinks')).
8884 html_writer::link($url, $strgomessage, array('id' => 'notificationyes')).' '.
8885 html_writer::link('', $strstaymessage, array('id' => 'notificationno')).
8886 html_writer::end_tag('div');
8887 html_writer::end_tag('div');
8888
8889 $PAGE->requires->js_init_call('M.core_message.init_notification', array('', $content, $url));
8890
8891 $USER->message_lastpopup = time();
8892 }
8893}
8894
8895/**
8896 * Used to make sure that $min <= $value <= $max
8897 *
8898 * Make sure that value is between min, and max
8899 *
8900 * @param int $min The minimum value
8901 * @param int $value The value to check
8902 * @param int $max The maximum value
8903 * @return int
8904 */
8905function bounded_number($min, $value, $max) {
8906 if ($value < $min) {
8907 return $min;
8908 }
8909 if ($value > $max) {
8910 return $max;
8911 }
8912 return $value;
8913}
8914
8915/**
8916 * Check if there is a nested array within the passed array
8917 *
8918 * @param array $array
8919 * @return bool true if there is a nested array false otherwise
8920 */
8921function array_is_nested($array) {
8922 foreach ($array as $value) {
8923 if (is_array($value)) {
8924 return true;
8925 }
8926 }
8927 return false;
8928}
8929
8930/**
8931 * get_performance_info() pairs up with init_performance_info()
8932 * loaded in setup.php. Returns an array with 'html' and 'txt'
8933 * values ready for use, and each of the individual stats provided
8934 * separately as well.
8935 *
8936 * @return array
8937 */
8938function get_performance_info() {
8939 global $CFG, $PERF, $DB, $PAGE;
8940
8941 $info = array();
8942 $info['html'] = ''; // Holds userfriendly HTML representation.
8943 $info['txt'] = me() . ' '; // Holds log-friendly representation.
8944
8945 $info['realtime'] = microtime_diff($PERF->starttime, microtime());
8946
8947 $info['html'] .= '<span class="timeused">'.$info['realtime'].' secs</span> ';
8948 $info['txt'] .= 'time: '.$info['realtime'].'s ';
8949
8950 if (function_exists('memory_get_usage')) {
8951 $info['memory_total'] = memory_get_usage();
8952 $info['memory_growth'] = memory_get_usage() - $PERF->startmemory;
8953 $info['html'] .= '<span class="memoryused">RAM: '.display_size($info['memory_total']).'</span> ';
8954 $info['txt'] .= 'memory_total: '.$info['memory_total'].'B (' . display_size($info['memory_total']).') memory_growth: '.
8955 $info['memory_growth'].'B ('.display_size($info['memory_growth']).') ';
8956 }
8957
8958 if (function_exists('memory_get_peak_usage')) {
8959 $info['memory_peak'] = memory_get_peak_usage();
8960 $info['html'] .= '<span class="memoryused">RAM peak: '.display_size($info['memory_peak']).'</span> ';
8961 $info['txt'] .= 'memory_peak: '.$info['memory_peak'].'B (' . display_size($info['memory_peak']).') ';
8962 }
8963
8964 $inc = get_included_files();
8965 $info['includecount'] = count($inc);
8966 $info['html'] .= '<span class="included">Included '.$info['includecount'].' files</span> ';
8967 $info['txt'] .= 'includecount: '.$info['includecount'].' ';
8968
8969 if (!empty($CFG->early_install_lang) or empty($PAGE)) {
8970 // We can not track more performance before installation or before PAGE init, sorry.
8971 return $info;
8972 }
8973
8974 $filtermanager = filter_manager::instance();
8975 if (method_exists($filtermanager, 'get_performance_summary')) {
8976 list($filterinfo, $nicenames) = $filtermanager->get_performance_summary();
8977 $info = array_merge($filterinfo, $info);
8978 foreach ($filterinfo as $key => $value) {
8979 $info['html'] .= "<span class='$key'>$nicenames[$key]: $value </span> ";
8980 $info['txt'] .= "$key: $value ";
8981 }
8982 }
8983
8984 $stringmanager = get_string_manager();
8985 if (method_exists($stringmanager, 'get_performance_summary')) {
8986 list($filterinfo, $nicenames) = $stringmanager->get_performance_summary();
8987 $info = array_merge($filterinfo, $info);
8988 foreach ($filterinfo as $key => $value) {
8989 $info['html'] .= "<span class='$key'>$nicenames[$key]: $value </span> ";
8990 $info['txt'] .= "$key: $value ";
8991 }
8992 }
8993
8994 if (!empty($PERF->logwrites)) {
8995 $info['logwrites'] = $PERF->logwrites;
8996 $info['html'] .= '<span class="logwrites">Log DB writes '.$info['logwrites'].'</span> ';
8997 $info['txt'] .= 'logwrites: '.$info['logwrites'].' ';
8998 }
8999
9000 $info['dbqueries'] = $DB->perf_get_reads().'/'.($DB->perf_get_writes() - $PERF->logwrites);
9001 $info['html'] .= '<span class="dbqueries">DB reads/writes: '.$info['dbqueries'].'</span> ';
9002 $info['txt'] .= 'db reads/writes: '.$info['dbqueries'].' ';
9003
9004 $info['dbtime'] = round($DB->perf_get_queries_time(), 5);
9005 $info['html'] .= '<span class="dbtime">DB queries time: '.$info['dbtime'].' secs</span> ';
9006 $info['txt'] .= 'db queries time: ' . $info['dbtime'] . 's ';
9007
9008 if (function_exists('posix_times')) {
9009 $ptimes = posix_times();
9010 if (is_array($ptimes)) {
9011 foreach ($ptimes as $key => $val) {
9012 $info[$key] = $ptimes[$key] - $PERF->startposixtimes[$key];
9013 }
9014 $info['html'] .= "<span class=\"posixtimes\">ticks: $info[ticks] user: $info[utime] sys: $info[stime] cuser: $info[cutime] csys: $info[cstime]</span> ";
9015 $info['txt'] .= "ticks: $info[ticks] user: $info[utime] sys: $info[stime] cuser: $info[cutime] csys: $info[cstime] ";
9016 }
9017 }
9018
9019 // Grab the load average for the last minute.
9020 // /proc will only work under some linux configurations
9021 // while uptime is there under MacOSX/Darwin and other unices.
9022 if (is_readable('/proc/loadavg') && $loadavg = @file('/proc/loadavg')) {
9023 list($serverload) = explode(' ', $loadavg[0]);
9024 unset($loadavg);
9025 } else if ( function_exists('is_executable') && is_executable('/usr/bin/uptime') && $loadavg = `/usr/bin/uptime` ) {
9026 if (preg_match('/load averages?: (\d+[\.,:]\d+)/', $loadavg, $matches)) {
9027 $serverload = $matches[1];
9028 } else {
9029 trigger_error('Could not parse uptime output!');
9030 }
9031 }
9032 if (!empty($serverload)) {
9033 $info['serverload'] = $serverload;
9034 $info['html'] .= '<span class="serverload">Load average: '.$info['serverload'].'</span> ';
9035 $info['txt'] .= "serverload: {$info['serverload']} ";
9036 }
9037
9038 // Display size of session if session started.
9039 if ($si = \core\session\manager::get_performance_info()) {
9040 $info['sessionsize'] = $si['size'];
9041 $info['html'] .= $si['html'];
9042 $info['txt'] .= $si['txt'];
9043 }
9044
9045 if ($stats = cache_helper::get_stats()) {
9046 $html = '<span class="cachesused">';
9047 $html .= '<span class="cache-stats-heading">Caches used (hits/misses/sets)</span>';
9048 $text = 'Caches used (hits/misses/sets): ';
9049 $hits = 0;
9050 $misses = 0;
9051 $sets = 0;
9052 foreach ($stats as $definition => $stores) {
9053 $html .= '<span class="cache-definition-stats">';
9054 $html .= '<span class="cache-definition-stats-heading">'.$definition.'</span>';
9055 $text .= "$definition {";
9056 foreach ($stores as $store => $data) {
9057 $hits += $data['hits'];
9058 $misses += $data['misses'];
9059 $sets += $data['sets'];
9060 if ($data['hits'] == 0 and $data['misses'] > 0) {
9061 $cachestoreclass = 'nohits';
9062 } else if ($data['hits'] < $data['misses']) {
9063 $cachestoreclass = 'lowhits';
9064 } else {
9065 $cachestoreclass = 'hihits';
9066 }
9067 $text .= "$store($data[hits]/$data[misses]/$data[sets]) ";
9068 $html .= "<span class=\"cache-store-stats $cachestoreclass\">$store: $data[hits] / $data[misses] / $data[sets]</span>";
9069 }
9070 $html .= '</span>';
9071 $text .= '} ';
9072 }
9073 $html .= "<span class='cache-total-stats'>Total: $hits / $misses / $sets</span>";
9074 $html .= '</span> ';
9075 $info['cachesused'] = "$hits / $misses / $sets";
9076 $info['html'] .= $html;
9077 $info['txt'] .= $text.'. ';
9078 } else {
9079 $info['cachesused'] = '0 / 0 / 0';
9080 $info['html'] .= '<span class="cachesused">Caches used (hits/misses/sets): 0/0/0</span>';
9081 $info['txt'] .= 'Caches used (hits/misses/sets): 0/0/0 ';
9082 }
9083
9084 $info['html'] = '<div class="performanceinfo siteinfo">'.$info['html'].'</div>';
9085 return $info;
9086}
9087
9088/**
9089 * Legacy function.
9090 *
9091 * @todo Document this function linux people
9092 */
9093function apd_get_profiling() {
9094 return shell_exec('pprofp -u ' . ini_get('apd.dumpdir') . '/pprof.' . getmypid() . '.*');
9095}
9096
9097/**
9098 * Delete directory or only its content
9099 *
9100 * @param string $dir directory path
9101 * @param bool $contentonly
9102 * @return bool success, true also if dir does not exist
9103 */
9104function remove_dir($dir, $contentonly=false) {
9105 if (!file_exists($dir)) {
9106 // Nothing to do.
9107 return true;
9108 }
9109 if (!$handle = opendir($dir)) {
9110 return false;
9111 }
9112 $result = true;
9113 while (false!==($item = readdir($handle))) {
9114 if ($item != '.' && $item != '..') {
9115 if (is_dir($dir.'/'.$item)) {
9116 $result = remove_dir($dir.'/'.$item) && $result;
9117 } else {
9118 $result = unlink($dir.'/'.$item) && $result;
9119 }
9120 }
9121 }
9122 closedir($handle);
9123 if ($contentonly) {
9124 clearstatcache(); // Make sure file stat cache is properly invalidated.
9125 return $result;
9126 }
9127 $result = rmdir($dir); // If anything left the result will be false, no need for && $result.
9128 clearstatcache(); // Make sure file stat cache is properly invalidated.
9129 return $result;
9130}
9131
9132/**
9133 * Detect if an object or a class contains a given property
9134 * will take an actual object or the name of a class
9135 *
9136 * @param mix $obj Name of class or real object to test
9137 * @param string $property name of property to find
9138 * @return bool true if property exists
9139 */
9140function object_property_exists( $obj, $property ) {
9141 if (is_string( $obj )) {
9142 $properties = get_class_vars( $obj );
9143 } else {
9144 $properties = get_object_vars( $obj );
9145 }
9146 return array_key_exists( $property, $properties );
9147}
9148
9149/**
9150 * Converts an object into an associative array
9151 *
9152 * This function converts an object into an associative array by iterating
9153 * over its public properties. Because this function uses the foreach
9154 * construct, Iterators are respected. It works recursively on arrays of objects.
9155 * Arrays and simple values are returned as is.
9156 *
9157 * If class has magic properties, it can implement IteratorAggregate
9158 * and return all available properties in getIterator()
9159 *
9160 * @param mixed $var
9161 * @return array
9162 */
9163function convert_to_array($var) {
9164 $result = array();
9165
9166 // Loop over elements/properties.
9167 foreach ($var as $key => $value) {
9168 // Recursively convert objects.
9169 if (is_object($value) || is_array($value)) {
9170 $result[$key] = convert_to_array($value);
9171 } else {
9172 // Simple values are untouched.
9173 $result[$key] = $value;
9174 }
9175 }
9176 return $result;
9177}
9178
9179/**
9180 * Detect a custom script replacement in the data directory that will
9181 * replace an existing moodle script
9182 *
9183 * @return string|bool full path name if a custom script exists, false if no custom script exists
9184 */
9185function custom_script_path() {
9186 global $CFG, $SCRIPT;
9187
9188 if ($SCRIPT === null) {
9189 // Probably some weird external script.
9190 return false;
9191 }
9192
9193 $scriptpath = $CFG->customscripts . $SCRIPT;
9194
9195 // Check the custom script exists.
9196 if (file_exists($scriptpath) and is_file($scriptpath)) {
9197 return $scriptpath;
9198 } else {
9199 return false;
9200 }
9201}
9202
9203/**
9204 * Returns whether or not the user object is a remote MNET user. This function
9205 * is in moodlelib because it does not rely on loading any of the MNET code.
9206 *
9207 * @param object $user A valid user object
9208 * @return bool True if the user is from a remote Moodle.
9209 */
9210function is_mnet_remote_user($user) {
9211 global $CFG;
9212
9213 if (!isset($CFG->mnet_localhost_id)) {
9214 include_once($CFG->dirroot . '/mnet/lib.php');
9215 $env = new mnet_environment();
9216 $env->init();
9217 unset($env);
9218 }
9219
9220 return (!empty($user->mnethostid) && $user->mnethostid != $CFG->mnet_localhost_id);
9221}
9222
9223/**
9224 * This function will search for browser prefereed languages, setting Moodle
9225 * to use the best one available if $SESSION->lang is undefined
9226 */
9227function setup_lang_from_browser() {
9228 global $CFG, $SESSION, $USER;
9229
9230 if (!empty($SESSION->lang) or !empty($USER->lang) or empty($CFG->autolang)) {
9231 // Lang is defined in session or user profile, nothing to do.
9232 return;
9233 }
9234
9235 if (!isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])) { // There isn't list of browser langs, nothing to do.
9236 return;
9237 }
9238
9239 // Extract and clean langs from headers.
9240 $rawlangs = $_SERVER['HTTP_ACCEPT_LANGUAGE'];
9241 $rawlangs = str_replace('-', '_', $rawlangs); // We are using underscores.
9242 $rawlangs = explode(',', $rawlangs); // Convert to array.
9243 $langs = array();
9244
9245 $order = 1.0;
9246 foreach ($rawlangs as $lang) {
9247 if (strpos($lang, ';') === false) {
9248 $langs[(string)$order] = $lang;
9249 $order = $order-0.01;
9250 } else {
9251 $parts = explode(';', $lang);
9252 $pos = strpos($parts[1], '=');
9253 $langs[substr($parts[1], $pos+1)] = $parts[0];
9254 }
9255 }
9256 krsort($langs, SORT_NUMERIC);
9257
9258 // Look for such langs under standard locations.
9259 foreach ($langs as $lang) {
9260 // Clean it properly for include.
9261 $lang = strtolower(clean_param($lang, PARAM_SAFEDIR));
9262 if (get_string_manager()->translation_exists($lang, false)) {
9263 // Lang exists, set it in session.
9264 $SESSION->lang = $lang;
9265 // We have finished. Go out.
9266 break;
9267 }
9268 }
9269 return;
9270}
9271
9272/**
9273 * Check if $url matches anything in proxybypass list
9274 *
9275 * Any errors just result in the proxy being used (least bad)
9276 *
9277 * @param string $url url to check
9278 * @return boolean true if we should bypass the proxy
9279 */
9280function is_proxybypass( $url ) {
9281 global $CFG;
9282
9283 // Sanity check.
9284 if (empty($CFG->proxyhost) or empty($CFG->proxybypass)) {
9285 return false;
9286 }
9287
9288 // Get the host part out of the url.
9289 if (!$host = parse_url( $url, PHP_URL_HOST )) {
9290 return false;
9291 }
9292
9293 // Get the possible bypass hosts into an array.
9294 $matches = explode( ',', $CFG->proxybypass );
9295
9296 // Check for a match.
9297 // (IPs need to match the left hand side and hosts the right of the url,
9298 // but we can recklessly check both as there can't be a false +ve).
9299 foreach ($matches as $match) {
9300 $match = trim($match);
9301
9302 // Try for IP match (Left side).
9303 $lhs = substr($host, 0, strlen($match));
9304 if (strcasecmp($match, $lhs)==0) {
9305 return true;
9306 }
9307
9308 // Try for host match (Right side).
9309 $rhs = substr($host, -strlen($match));
9310 if (strcasecmp($match, $rhs)==0) {
9311 return true;
9312 }
9313 }
9314
9315 // Nothing matched.
9316 return false;
9317}
9318
9319/**
9320 * Check if the passed navigation is of the new style
9321 *
9322 * @param mixed $navigation
9323 * @return bool true for yes false for no
9324 */
9325function is_newnav($navigation) {
9326 if (is_array($navigation) && !empty($navigation['newnav'])) {
9327 return true;
9328 } else {
9329 return false;
9330 }
9331}
9332
9333/**
9334 * Checks whether the given variable name is defined as a variable within the given object.
9335 *
9336 * This will NOT work with stdClass objects, which have no class variables.
9337 *
9338 * @param string $var The variable name
9339 * @param object $object The object to check
9340 * @return boolean
9341 */
9342function in_object_vars($var, $object) {
9343 $classvars = get_class_vars(get_class($object));
9344 $classvars = array_keys($classvars);
9345 return in_array($var, $classvars);
9346}
9347
9348/**
9349 * Returns an array without repeated objects.
9350 * This function is similar to array_unique, but for arrays that have objects as values
9351 *
9352 * @param array $array
9353 * @param bool $keepkeyassoc
9354 * @return array
9355 */
9356function object_array_unique($array, $keepkeyassoc = true) {
9357 $duplicatekeys = array();
9358 $tmp = array();
9359
9360 foreach ($array as $key => $val) {
9361 // Convert objects to arrays, in_array() does not support objects.
9362 if (is_object($val)) {
9363 $val = (array)$val;
9364 }
9365
9366 if (!in_array($val, $tmp)) {
9367 $tmp[] = $val;
9368 } else {
9369 $duplicatekeys[] = $key;
9370 }
9371 }
9372
9373 foreach ($duplicatekeys as $key) {
9374 unset($array[$key]);
9375 }
9376
9377 return $keepkeyassoc ? $array : array_values($array);
9378}
9379
9380/**
9381 * Is a userid the primary administrator?
9382 *
9383 * @param int $userid int id of user to check
9384 * @return boolean
9385 */
9386function is_primary_admin($userid) {
9387 $primaryadmin = get_admin();
9388
9389 if ($userid == $primaryadmin->id) {
9390 return true;
9391 } else {
9392 return false;
9393 }
9394}
9395
9396/**
9397 * Returns the site identifier
9398 *
9399 * @return string $CFG->siteidentifier, first making sure it is properly initialised.
9400 */
9401function get_site_identifier() {
9402 global $CFG;
9403 // Check to see if it is missing. If so, initialise it.
9404 if (empty($CFG->siteidentifier)) {
9405 set_config('siteidentifier', random_string(32) . $_SERVER['HTTP_HOST']);
9406 }
9407 // Return it.
9408 return $CFG->siteidentifier;
9409}
9410
9411/**
9412 * Check whether the given password has no more than the specified
9413 * number of consecutive identical characters.
9414 *
9415 * @param string $password password to be checked against the password policy
9416 * @param integer $maxchars maximum number of consecutive identical characters
9417 * @return bool
9418 */
9419function check_consecutive_identical_characters($password, $maxchars) {
9420
9421 if ($maxchars < 1) {
9422 return true; // Zero 0 is to disable this check.
9423 }
9424 if (strlen($password) <= $maxchars) {
9425 return true; // Too short to fail this test.
9426 }
9427
9428 $previouschar = '';
9429 $consecutivecount = 1;
9430 foreach (str_split($password) as $char) {
9431 if ($char != $previouschar) {
9432 $consecutivecount = 1;
9433 } else {
9434 $consecutivecount++;
9435 if ($consecutivecount > $maxchars) {
9436 return false; // Check failed already.
9437 }
9438 }
9439
9440 $previouschar = $char;
9441 }
9442
9443 return true;
9444}
9445
9446/**
9447 * Helper function to do partial function binding.
9448 * so we can use it for preg_replace_callback, for example
9449 * this works with php functions, user functions, static methods and class methods
9450 * it returns you a callback that you can pass on like so:
9451 *
9452 * $callback = partial('somefunction', $arg1, $arg2);
9453 * or
9454 * $callback = partial(array('someclass', 'somestaticmethod'), $arg1, $arg2);
9455 * or even
9456 * $obj = new someclass();
9457 * $callback = partial(array($obj, 'somemethod'), $arg1, $arg2);
9458 *
9459 * and then the arguments that are passed through at calltime are appended to the argument list.
9460 *
9461 * @param mixed $function a php callback
9462 * @param mixed $arg1,... $argv arguments to partially bind with
9463 * @return array Array callback
9464 */
9465function partial() {
9466 if (!class_exists('partial')) {
9467 /**
9468 * Used to manage function binding.
9469 * @copyright 2009 Penny Leach
9470 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
9471 */
9472 class partial{
9473 /** @var array */
9474 public $values = array();
9475 /** @var string The function to call as a callback. */
9476 public $func;
9477 /**
9478 * Constructor
9479 * @param string $func
9480 * @param array $args
9481 */
9482 public function __construct($func, $args) {
9483 $this->values = $args;
9484 $this->func = $func;
9485 }
9486 /**
9487 * Calls the callback function.
9488 * @return mixed
9489 */
9490 public function method() {
9491 $args = func_get_args();
9492 return call_user_func_array($this->func, array_merge($this->values, $args));
9493 }
9494 }
9495 }
9496 $args = func_get_args();
9497 $func = array_shift($args);
9498 $p = new partial($func, $args);
9499 return array($p, 'method');
9500}
9501
9502/**
9503 * helper function to load up and initialise the mnet environment
9504 * this must be called before you use mnet functions.
9505 *
9506 * @return mnet_environment the equivalent of old $MNET global
9507 */
9508function get_mnet_environment() {
9509 global $CFG;
9510 require_once($CFG->dirroot . '/mnet/lib.php');
9511 static $instance = null;
9512 if (empty($instance)) {
9513 $instance = new mnet_environment();
9514 $instance->init();
9515 }
9516 return $instance;
9517}
9518
9519/**
9520 * during xmlrpc server code execution, any code wishing to access
9521 * information about the remote peer must use this to get it.
9522 *
9523 * @return mnet_remote_client the equivalent of old $MNETREMOTE_CLIENT global
9524 */
9525function get_mnet_remote_client() {
9526 if (!defined('MNET_SERVER')) {
9527 debugging(get_string('notinxmlrpcserver', 'mnet'));
9528 return false;
9529 }
9530 global $MNET_REMOTE_CLIENT;
9531 if (isset($MNET_REMOTE_CLIENT)) {
9532 return $MNET_REMOTE_CLIENT;
9533 }
9534 return false;
9535}
9536
9537/**
9538 * during the xmlrpc server code execution, this will be called
9539 * to setup the object returned by {@link get_mnet_remote_client}
9540 *
9541 * @param mnet_remote_client $client the client to set up
9542 * @throws moodle_exception
9543 */
9544function set_mnet_remote_client($client) {
9545 if (!defined('MNET_SERVER')) {
9546 throw new moodle_exception('notinxmlrpcserver', 'mnet');
9547 }
9548 global $MNET_REMOTE_CLIENT;
9549 $MNET_REMOTE_CLIENT = $client;
9550}
9551
9552/**
9553 * return the jump url for a given remote user
9554 * this is used for rewriting forum post links in emails, etc
9555 *
9556 * @param stdclass $user the user to get the idp url for
9557 */
9558function mnet_get_idp_jump_url($user) {
9559 global $CFG;
9560
9561 static $mnetjumps = array();
9562 if (!array_key_exists($user->mnethostid, $mnetjumps)) {
9563 $idp = mnet_get_peer_host($user->mnethostid);
9564 $idpjumppath = mnet_get_app_jumppath($idp->applicationid);
9565 $mnetjumps[$user->mnethostid] = $idp->wwwroot . $idpjumppath . '?hostwwwroot=' . $CFG->wwwroot . '&wantsurl=';
9566 }
9567 return $mnetjumps[$user->mnethostid];
9568}
9569
9570/**
9571 * Gets the homepage to use for the current user
9572 *
9573 * @return int One of HOMEPAGE_*
9574 */
9575function get_home_page() {
9576 global $CFG;
9577
9578 if (isloggedin() && !isguestuser() && !empty($CFG->defaulthomepage)) {
9579 if ($CFG->defaulthomepage == HOMEPAGE_MY) {
9580 return HOMEPAGE_MY;
9581 } else {
9582 return (int)get_user_preferences('user_home_page_preference', HOMEPAGE_MY);
9583 }
9584 }
9585 return HOMEPAGE_SITE;
9586}
9587
9588/**
9589 * Gets the name of a course to be displayed when showing a list of courses.
9590 * By default this is just $course->fullname but user can configure it. The
9591 * result of this function should be passed through print_string.
9592 * @param stdClass|course_in_list $course Moodle course object
9593 * @return string Display name of course (either fullname or short + fullname)
9594 */
9595function get_course_display_name_for_list($course) {
9596 global $CFG;
9597 if (!empty($CFG->courselistshortnames)) {
9598 if (!($course instanceof stdClass)) {
9599 $course = (object)convert_to_array($course);
9600 }
9601 return get_string('courseextendednamedisplay', '', $course);
9602 } else {
9603 return $course->fullname;
9604 }
9605}
9606
9607/**
9608 * The lang_string class
9609 *
9610 * This special class is used to create an object representation of a string request.
9611 * It is special because processing doesn't occur until the object is first used.
9612 * The class was created especially to aid performance in areas where strings were
9613 * required to be generated but were not necessarily used.
9614 * As an example the admin tree when generated uses over 1500 strings, of which
9615 * normally only 1/3 are ever actually printed at any time.
9616 * The performance advantage is achieved by not actually processing strings that
9617 * arn't being used, as such reducing the processing required for the page.
9618 *
9619 * How to use the lang_string class?
9620 * There are two methods of using the lang_string class, first through the
9621 * forth argument of the get_string function, and secondly directly.
9622 * The following are examples of both.
9623 * 1. Through get_string calls e.g.
9624 * $string = get_string($identifier, $component, $a, true);
9625 * $string = get_string('yes', 'moodle', null, true);
9626 * 2. Direct instantiation
9627 * $string = new lang_string($identifier, $component, $a, $lang);
9628 * $string = new lang_string('yes');
9629 *
9630 * How do I use a lang_string object?
9631 * The lang_string object makes use of a magic __toString method so that you
9632 * are able to use the object exactly as you would use a string in most cases.
9633 * This means you are able to collect it into a variable and then directly
9634 * echo it, or concatenate it into another string, or similar.
9635 * The other thing you can do is manually get the string by calling the
9636 * lang_strings out method e.g.
9637 * $string = new lang_string('yes');
9638 * $string->out();
9639 * Also worth noting is that the out method can take one argument, $lang which
9640 * allows the developer to change the language on the fly.
9641 *
9642 * When should I use a lang_string object?
9643 * The lang_string object is designed to be used in any situation where a
9644 * string may not be needed, but needs to be generated.
9645 * The admin tree is a good example of where lang_string objects should be
9646 * used.
9647 * A more practical example would be any class that requries strings that may
9648 * not be printed (after all classes get renderer by renderers and who knows
9649 * what they will do ;))
9650 *
9651 * When should I not use a lang_string object?
9652 * Don't use lang_strings when you are going to use a string immediately.
9653 * There is no need as it will be processed immediately and there will be no
9654 * advantage, and in fact perhaps a negative hit as a class has to be
9655 * instantiated for a lang_string object, however get_string won't require
9656 * that.
9657 *
9658 * Limitations:
9659 * 1. You cannot use a lang_string object as an array offset. Doing so will
9660 * result in PHP throwing an error. (You can use it as an object property!)
9661 *
9662 * @package core
9663 * @category string
9664 * @copyright 2011 Sam Hemelryk
9665 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
9666 */
9667class lang_string {
9668
9669 /** @var string The strings identifier */
9670 protected $identifier;
9671 /** @var string The strings component. Default '' */
9672 protected $component = '';
9673 /** @var array|stdClass Any arguments required for the string. Default null */
9674 protected $a = null;
9675 /** @var string The language to use when processing the string. Default null */
9676 protected $lang = null;
9677
9678 /** @var string The processed string (once processed) */
9679 protected $string = null;
9680
9681 /**
9682 * A special boolean. If set to true then the object has been woken up and
9683 * cannot be regenerated. If this is set then $this->string MUST be used.
9684 * @var bool
9685 */
9686 protected $forcedstring = false;
9687
9688 /**
9689 * Constructs a lang_string object
9690 *
9691 * This function should do as little processing as possible to ensure the best
9692 * performance for strings that won't be used.
9693 *
9694 * @param string $identifier The strings identifier
9695 * @param string $component The strings component
9696 * @param stdClass|array $a Any arguments the string requires
9697 * @param string $lang The language to use when processing the string.
9698 * @throws coding_exception
9699 */
9700 public function __construct($identifier, $component = '', $a = null, $lang = null) {
9701 if (empty($component)) {
9702 $component = 'moodle';
9703 }
9704
9705 $this->identifier = $identifier;
9706 $this->component = $component;
9707 $this->lang = $lang;
9708
9709 // We MUST duplicate $a to ensure that it if it changes by reference those
9710 // changes are not carried across.
9711 // To do this we always ensure $a or its properties/values are strings
9712 // and that any properties/values that arn't convertable are forgotten.
9713 if (!empty($a)) {
9714 if (is_scalar($a)) {
9715 $this->a = $a;
9716 } else if ($a instanceof lang_string) {
9717 $this->a = $a->out();
9718 } else if (is_object($a) or is_array($a)) {
9719 $a = (array)$a;
9720 $this->a = array();
9721 foreach ($a as $key => $value) {
9722 // Make sure conversion errors don't get displayed (results in '').
9723 if (is_array($value)) {
9724 $this->a[$key] = '';
9725 } else if (is_object($value)) {
9726 if (method_exists($value, '__toString')) {
9727 $this->a[$key] = $value->__toString();
9728 } else {
9729 $this->a[$key] = '';
9730 }
9731 } else {
9732 $this->a[$key] = (string)$value;
9733 }
9734 }
9735 }
9736 }
9737
9738 if (debugging(false, DEBUG_DEVELOPER)) {
9739 if (clean_param($this->identifier, PARAM_STRINGID) == '') {
9740 throw new coding_exception('Invalid string identifier. Most probably some illegal character is part of the string identifier. Please check your string definition');
9741 }
9742 if (!empty($this->component) && clean_param($this->component, PARAM_COMPONENT) == '') {
9743 throw new coding_exception('Invalid string compontent. Please check your string definition');
9744 }
9745 if (!get_string_manager()->string_exists($this->identifier, $this->component)) {
9746 debugging('String does not exist. Please check your string definition for '.$this->identifier.'/'.$this->component, DEBUG_DEVELOPER);
9747 }
9748 }
9749 }
9750
9751 /**
9752 * Processes the string.
9753 *
9754 * This function actually processes the string, stores it in the string property
9755 * and then returns it.
9756 * You will notice that this function is VERY similar to the get_string method.
9757 * That is because it is pretty much doing the same thing.
9758 * However as this function is an upgrade it isn't as tolerant to backwards
9759 * compatibility.
9760 *
9761 * @return string
9762 * @throws coding_exception
9763 */
9764 protected function get_string() {
9765 global $CFG;
9766
9767 // Check if we need to process the string.
9768 if ($this->string === null) {
9769 // Check the quality of the identifier.
9770 if ($CFG->debugdeveloper && clean_param($this->identifier, PARAM_STRINGID) === '') {
9771 throw new coding_exception('Invalid string identifier. Most probably some illegal character is part of the string identifier. Please check your string definition', DEBUG_DEVELOPER);
9772 }
9773
9774 // Process the string.
9775 $this->string = get_string_manager()->get_string($this->identifier, $this->component, $this->a, $this->lang);
9776 // Debugging feature lets you display string identifier and component.
9777 if (isset($CFG->debugstringids) && $CFG->debugstringids && optional_param('strings', 0, PARAM_INT)) {
9778 $this->string .= ' {' . $this->identifier . '/' . $this->component . '}';
9779 }
9780 }
9781 // Return the string.
9782 return $this->string;
9783 }
9784
9785 /**
9786 * Returns the string
9787 *
9788 * @param string $lang The langauge to use when processing the string
9789 * @return string
9790 */
9791 public function out($lang = null) {
9792 if ($lang !== null && $lang != $this->lang && ($this->lang == null && $lang != current_language())) {
9793 if ($this->forcedstring) {
9794 debugging('lang_string objects that have been used cannot be printed in another language. ('.$this->lang.' used)', DEBUG_DEVELOPER);
9795 return $this->get_string();
9796 }
9797 $translatedstring = new lang_string($this->identifier, $this->component, $this->a, $lang);
9798 return $translatedstring->out();
9799 }
9800 return $this->get_string();
9801 }
9802
9803 /**
9804 * Magic __toString method for printing a string
9805 *
9806 * @return string
9807 */
9808 public function __toString() {
9809 return $this->get_string();
9810 }
9811
9812 /**
9813 * Magic __set_state method used for var_export
9814 *
9815 * @return string
9816 */
9817 public function __set_state() {
9818 return $this->get_string();
9819 }
9820
9821 /**
9822 * Prepares the lang_string for sleep and stores only the forcedstring and
9823 * string properties... the string cannot be regenerated so we need to ensure
9824 * it is generated for this.
9825 *
9826 * @return string
9827 */
9828 public function __sleep() {
9829 $this->get_string();
9830 $this->forcedstring = true;
9831 return array('forcedstring', 'string', 'lang');
9832 }
9833}