Permalink
Find file Copy path
10239 lines (8974 sloc) 358 KB
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* moodlelib.php - Moodle main library
*
* Main library file of miscellaneous general-purpose Moodle functions.
* Other main libraries:
* - weblib.php - functions that produce web output
* - datalib.php - functions that access the database
*
* @package core
* @subpackage lib
* @copyright 1999 onwards Martin Dougiamas http://dougiamas.com
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
defined('MOODLE_INTERNAL') || die();
// CONSTANTS (Encased in phpdoc proper comments).
// Date and time constants.
/**
* Time constant - the number of seconds in a year
*/
define('YEARSECS', 31536000);
/**
* Time constant - the number of seconds in a week
*/
define('WEEKSECS', 604800);
/**
* Time constant - the number of seconds in a day
*/
define('DAYSECS', 86400);
/**
* Time constant - the number of seconds in an hour
*/
define('HOURSECS', 3600);
/**
* Time constant - the number of seconds in a minute
*/
define('MINSECS', 60);
/**
* Time constant - the number of minutes in a day
*/
define('DAYMINS', 1440);
/**
* Time constant - the number of minutes in an hour
*/
define('HOURMINS', 60);
// Parameter constants - every call to optional_param(), required_param()
// or clean_param() should have a specified type of parameter.
/**
* PARAM_ALPHA - contains only english ascii letters a-zA-Z.
*/
define('PARAM_ALPHA', 'alpha');
/**
* PARAM_ALPHAEXT the same contents as PARAM_ALPHA plus the chars in quotes: "_-" allowed
* NOTE: originally this allowed "/" too, please use PARAM_SAFEPATH if "/" needed
*/
define('PARAM_ALPHAEXT', 'alphaext');
/**
* PARAM_ALPHANUM - expected numbers and letters only.
*/
define('PARAM_ALPHANUM', 'alphanum');
/**
* PARAM_ALPHANUMEXT - expected numbers, letters only and _-.
*/
define('PARAM_ALPHANUMEXT', 'alphanumext');
/**
* PARAM_AUTH - actually checks to make sure the string is a valid auth plugin
*/
define('PARAM_AUTH', 'auth');
/**
* PARAM_BASE64 - Base 64 encoded format
*/
define('PARAM_BASE64', 'base64');
/**
* PARAM_BOOL - converts input into 0 or 1, use for switches in forms and urls.
*/
define('PARAM_BOOL', 'bool');
/**
* PARAM_CAPABILITY - A capability name, like 'moodle/role:manage'. Actually
* checked against the list of capabilities in the database.
*/
define('PARAM_CAPABILITY', 'capability');
/**
* PARAM_CLEANHTML - cleans submitted HTML code. Note that you almost never want
* to use this. The normal mode of operation is to use PARAM_RAW when receiving
* the input (required/optional_param or formslib) and then sanitise the HTML
* using format_text on output. This is for the rare cases when you want to
* sanitise the HTML on input. This cleaning may also fix xhtml strictness.
*/
define('PARAM_CLEANHTML', 'cleanhtml');
/**
* PARAM_EMAIL - an email address following the RFC
*/
define('PARAM_EMAIL', 'email');
/**
* PARAM_FILE - safe file name, all dangerous chars are stripped, protects against XSS, SQL injections and directory traversals
*/
define('PARAM_FILE', 'file');
/**
* PARAM_FLOAT - a real/floating point number.
*
* Note that you should not use PARAM_FLOAT for numbers typed in by the user.
* It does not work for languages that use , as a decimal separator.
* Instead, do something like
* $rawvalue = required_param('name', PARAM_RAW);
* // ... other code including require_login, which sets current lang ...
* $realvalue = unformat_float($rawvalue);
* // ... then use $realvalue
*/
define('PARAM_FLOAT', 'float');
/**
* PARAM_HOST - expected fully qualified domain name (FQDN) or an IPv4 dotted quad (IP address)
*/
define('PARAM_HOST', 'host');
/**
* PARAM_INT - integers only, use when expecting only numbers.
*/
define('PARAM_INT', 'int');
/**
* PARAM_LANG - checks to see if the string is a valid installed language in the current site.
*/
define('PARAM_LANG', 'lang');
/**
* PARAM_LOCALURL - expected properly formatted URL as well as one that refers to the local server itself. (NOT orthogonal to the
* others! Implies PARAM_URL!)
*/
define('PARAM_LOCALURL', 'localurl');
/**
* PARAM_NOTAGS - all html tags are stripped from the text. Do not abuse this type.
*/
define('PARAM_NOTAGS', 'notags');
/**
* PARAM_PATH - safe relative path name, all dangerous chars are stripped, protects against XSS, SQL injections and directory
* traversals note: the leading slash is not removed, window drive letter is not allowed
*/
define('PARAM_PATH', 'path');
/**
* PARAM_PEM - Privacy Enhanced Mail format
*/
define('PARAM_PEM', 'pem');
/**
* PARAM_PERMISSION - A permission, one of CAP_INHERIT, CAP_ALLOW, CAP_PREVENT or CAP_PROHIBIT.
*/
define('PARAM_PERMISSION', 'permission');
/**
* PARAM_RAW specifies a parameter that is not cleaned/processed in any way except the discarding of the invalid utf-8 characters
*/
define('PARAM_RAW', 'raw');
/**
* PARAM_RAW_TRIMMED like PARAM_RAW but leading and trailing whitespace is stripped.
*/
define('PARAM_RAW_TRIMMED', 'raw_trimmed');
/**
* PARAM_SAFEDIR - safe directory name, suitable for include() and require()
*/
define('PARAM_SAFEDIR', 'safedir');
/**
* PARAM_SAFEPATH - several PARAM_SAFEDIR joined by "/", suitable for include() and require(), plugin paths, etc.
*/
define('PARAM_SAFEPATH', 'safepath');
/**
* PARAM_SEQUENCE - expects a sequence of numbers like 8 to 1,5,6,4,6,8,9. Numbers and comma only.
*/
define('PARAM_SEQUENCE', 'sequence');
/**
* PARAM_TAG - one tag (interests, blogs, etc.) - mostly international characters and space, <> not supported
*/
define('PARAM_TAG', 'tag');
/**
* PARAM_TAGLIST - list of tags separated by commas (interests, blogs, etc.)
*/
define('PARAM_TAGLIST', 'taglist');
/**
* PARAM_TEXT - general plain text compatible with multilang filter, no other html tags. Please note '<', or '>' are allowed here.
*/
define('PARAM_TEXT', 'text');
/**
* PARAM_THEME - Checks to see if the string is a valid theme name in the current site
*/
define('PARAM_THEME', 'theme');
/**
* PARAM_URL - expected properly formatted URL. Please note that domain part is required, http://localhost/ is not accepted but
* http://localhost.localdomain/ is ok.
*/
define('PARAM_URL', 'url');
/**
* PARAM_USERNAME - Clean username to only contains allowed characters. This is to be used ONLY when manually creating user
* accounts, do NOT use when syncing with external systems!!
*/
define('PARAM_USERNAME', 'username');
/**
* PARAM_STRINGID - used to check if the given string is valid string identifier for get_string()
*/
define('PARAM_STRINGID', 'stringid');
// DEPRECATED PARAM TYPES OR ALIASES - DO NOT USE FOR NEW CODE.
/**
* PARAM_CLEAN - obsoleted, please use a more specific type of parameter.
* It was one of the first types, that is why it is abused so much ;-)
* @deprecated since 2.0
*/
define('PARAM_CLEAN', 'clean');
/**
* PARAM_INTEGER - deprecated alias for PARAM_INT
* @deprecated since 2.0
*/
define('PARAM_INTEGER', 'int');
/**
* PARAM_NUMBER - deprecated alias of PARAM_FLOAT
* @deprecated since 2.0
*/
define('PARAM_NUMBER', 'float');
/**
* PARAM_ACTION - deprecated alias for PARAM_ALPHANUMEXT, use for various actions in forms and urls
* NOTE: originally alias for PARAM_APLHA
* @deprecated since 2.0
*/
define('PARAM_ACTION', 'alphanumext');
/**
* PARAM_FORMAT - deprecated alias for PARAM_ALPHANUMEXT, use for names of plugins, formats, etc.
* NOTE: originally alias for PARAM_APLHA
* @deprecated since 2.0
*/
define('PARAM_FORMAT', 'alphanumext');
/**
* PARAM_MULTILANG - deprecated alias of PARAM_TEXT.
* @deprecated since 2.0
*/
define('PARAM_MULTILANG', 'text');
/**
* PARAM_TIMEZONE - expected timezone. Timezone can be int +-(0-13) or float +-(0.5-12.5) or
* string separated by '/' and can have '-' &/ '_' (eg. America/North_Dakota/New_Salem
* America/Port-au-Prince)
*/
define('PARAM_TIMEZONE', 'timezone');
/**
* PARAM_CLEANFILE - deprecated alias of PARAM_FILE; originally was removing regional chars too
*/
define('PARAM_CLEANFILE', 'file');
/**
* PARAM_COMPONENT is used for full component names (aka frankenstyle) such as 'mod_forum', 'core_rating', 'auth_ldap'.
* Short legacy subsystem names and module names are accepted too ex: 'forum', 'rating', 'user'.
* Only lowercase ascii letters, numbers and underscores are allowed, it has to start with a letter.
* NOTE: numbers and underscores are strongly discouraged in plugin names!
*/
define('PARAM_COMPONENT', 'component');
/**
* PARAM_AREA is a name of area used when addressing files, comments, ratings, etc.
* It is usually used together with context id and component.
* Only lowercase ascii letters, numbers and underscores are allowed, it has to start with a letter.
*/
define('PARAM_AREA', 'area');
/**
* PARAM_PLUGIN is used for plugin names such as 'forum', 'glossary', 'ldap', 'paypal', 'completionstatus'.
* Only lowercase ascii letters, numbers and underscores are allowed, it has to start with a letter.
* NOTE: numbers and underscores are strongly discouraged in plugin names! Underscores are forbidden in module names.
*/
define('PARAM_PLUGIN', 'plugin');
// Web Services.
/**
* VALUE_REQUIRED - if the parameter is not supplied, there is an error
*/
define('VALUE_REQUIRED', 1);
/**
* VALUE_OPTIONAL - if the parameter is not supplied, then the param has no value
*/
define('VALUE_OPTIONAL', 2);
/**
* VALUE_DEFAULT - if the parameter is not supplied, then the default value is used
*/
define('VALUE_DEFAULT', 0);
/**
* NULL_NOT_ALLOWED - the parameter can not be set to null in the database
*/
define('NULL_NOT_ALLOWED', false);
/**
* NULL_ALLOWED - the parameter can be set to null in the database
*/
define('NULL_ALLOWED', true);
// Page types.
/**
* PAGE_COURSE_VIEW is a definition of a page type. For more information on the page class see moodle/lib/pagelib.php.
*/
define('PAGE_COURSE_VIEW', 'course-view');
/** Get remote addr constant */
define('GETREMOTEADDR_SKIP_HTTP_CLIENT_IP', '1');
/** Get remote addr constant */
define('GETREMOTEADDR_SKIP_HTTP_X_FORWARDED_FOR', '2');
// Blog access level constant declaration.
define ('BLOG_USER_LEVEL', 1);
define ('BLOG_GROUP_LEVEL', 2);
define ('BLOG_COURSE_LEVEL', 3);
define ('BLOG_SITE_LEVEL', 4);
define ('BLOG_GLOBAL_LEVEL', 5);
// Tag constants.
/**
* To prevent problems with multibytes strings,Flag updating in nav not working on the review page. this should not exceed the
* length of "varchar(255) / 3 (bytes / utf-8 character) = 85".
* TODO: this is not correct, varchar(255) are 255 unicode chars ;-)
*
* @todo define(TAG_MAX_LENGTH) this is not correct, varchar(255) are 255 unicode chars ;-)
*/
define('TAG_MAX_LENGTH', 50);
// Password policy constants.
define ('PASSWORD_LOWER', 'abcdefghijklmnopqrstuvwxyz');
define ('PASSWORD_UPPER', 'ABCDEFGHIJKLMNOPQRSTUVWXYZ');
define ('PASSWORD_DIGITS', '0123456789');
define ('PASSWORD_NONALPHANUM', '.,;:!?_-+/*@#&$');
// Feature constants.
// Used for plugin_supports() to report features that are, or are not, supported by a module.
/** True if module can provide a grade */
define('FEATURE_GRADE_HAS_GRADE', 'grade_has_grade');
/** True if module supports outcomes */
define('FEATURE_GRADE_OUTCOMES', 'outcomes');
/** True if module supports advanced grading methods */
define('FEATURE_ADVANCED_GRADING', 'grade_advanced_grading');
/** True if module controls the grade visibility over the gradebook */
define('FEATURE_CONTROLS_GRADE_VISIBILITY', 'controlsgradevisbility');
/** True if module supports plagiarism plugins */
define('FEATURE_PLAGIARISM', 'plagiarism');
/** True if module has code to track whether somebody viewed it */
define('FEATURE_COMPLETION_TRACKS_VIEWS', 'completion_tracks_views');
/** True if module has custom completion rules */
define('FEATURE_COMPLETION_HAS_RULES', 'completion_has_rules');
/** True if module has no 'view' page (like label) */
define('FEATURE_NO_VIEW_LINK', 'viewlink');
/** True (which is default) if the module wants support for setting the ID number for grade calculation purposes. */
define('FEATURE_IDNUMBER', 'idnumber');
/** True if module supports groups */
define('FEATURE_GROUPS', 'groups');
/** True if module supports groupings */
define('FEATURE_GROUPINGS', 'groupings');
/**
* True if module supports groupmembersonly (which no longer exists)
* @deprecated Since Moodle 2.8
*/
define('FEATURE_GROUPMEMBERSONLY', 'groupmembersonly');
/** Type of module */
define('FEATURE_MOD_ARCHETYPE', 'mod_archetype');
/** True if module supports intro editor */
define('FEATURE_MOD_INTRO', 'mod_intro');
/** True if module has default completion */
define('FEATURE_MODEDIT_DEFAULT_COMPLETION', 'modedit_default_completion');
define('FEATURE_COMMENT', 'comment');
define('FEATURE_RATE', 'rate');
/** True if module supports backup/restore of moodle2 format */
define('FEATURE_BACKUP_MOODLE2', 'backup_moodle2');
/** True if module can show description on course main page */
define('FEATURE_SHOW_DESCRIPTION', 'showdescription');
/** True if module uses the question bank */
define('FEATURE_USES_QUESTIONS', 'usesquestions');
/**
* Maximum filename char size
*/
define('MAX_FILENAME_SIZE', 100);
/** Unspecified module archetype */
define('MOD_ARCHETYPE_OTHER', 0);
/** Resource-like type module */
define('MOD_ARCHETYPE_RESOURCE', 1);
/** Assignment module archetype */
define('MOD_ARCHETYPE_ASSIGNMENT', 2);
/** System (not user-addable) module archetype */
define('MOD_ARCHETYPE_SYSTEM', 3);
/**
* Security token used for allowing access
* from external application such as web services.
* Scripts do not use any session, performance is relatively
* low because we need to load access info in each request.
* Scripts are executed in parallel.
*/
define('EXTERNAL_TOKEN_PERMANENT', 0);
/**
* Security token used for allowing access
* of embedded applications, the code is executed in the
* active user session. Token is invalidated after user logs out.
* Scripts are executed serially - normal session locking is used.
*/
define('EXTERNAL_TOKEN_EMBEDDED', 1);
/**
* The home page should be the site home
*/
define('HOMEPAGE_SITE', 0);
/**
* The home page should be the users my page
*/
define('HOMEPAGE_MY', 1);
/**
* The home page can be chosen by the user
*/
define('HOMEPAGE_USER', 2);
/**
* Hub directory url (should be moodle.org)
*/
define('HUB_HUBDIRECTORYURL', "https://hubdirectory.moodle.org");
/**
* Moodle.net url (should be moodle.net)
*/
define('HUB_MOODLEORGHUBURL', "https://moodle.net");
define('HUB_OLDMOODLEORGHUBURL', "http://hub.moodle.org");
/**
* Moodle mobile app service name
*/
define('MOODLE_OFFICIAL_MOBILE_SERVICE', 'moodle_mobile_app');
/**
* Indicates the user has the capabilities required to ignore activity and course file size restrictions
*/
define('USER_CAN_IGNORE_FILE_SIZE_LIMITS', -1);
/**
* Course display settings: display all sections on one page.
*/
define('COURSE_DISPLAY_SINGLEPAGE', 0);
/**
* Course display settings: split pages into a page per section.
*/
define('COURSE_DISPLAY_MULTIPAGE', 1);
/**
* Authentication constant: String used in password field when password is not stored.
*/
define('AUTH_PASSWORD_NOT_CACHED', 'not cached');
/**
* Email from header to never include via information.
*/
define('EMAIL_VIA_NEVER', 0);
/**
* Email from header to always include via information.
*/
define('EMAIL_VIA_ALWAYS', 1);
/**
* Email from header to only include via information if the address is no-reply.
*/
define('EMAIL_VIA_NO_REPLY_ONLY', 2);
// PARAMETER HANDLING.
/**
* Returns a particular value for the named variable, taken from
* POST or GET. If the parameter doesn't exist then an error is
* thrown because we require this variable.
*
* This function should be used to initialise all required values
* in a script that are based on parameters. Usually it will be
* used like this:
* $id = required_param('id', PARAM_INT);
*
* Please note the $type parameter is now required and the value can not be array.
*
* @param string $parname the name of the page parameter we want
* @param string $type expected type of parameter
* @return mixed
* @throws coding_exception
*/
function required_param($parname, $type) {
if (func_num_args() != 2 or empty($parname) or empty($type)) {
throw new coding_exception('required_param() requires $parname and $type to be specified (parameter: '.$parname.')');
}
// POST has precedence.
if (isset($_POST[$parname])) {
$param = $_POST[$parname];
} else if (isset($_GET[$parname])) {
$param = $_GET[$parname];
} else {
print_error('missingparam', '', '', $parname);
}
if (is_array($param)) {
debugging('Invalid array parameter detected in required_param(): '.$parname);
// TODO: switch to fatal error in Moodle 2.3.
return required_param_array($parname, $type);
}
return clean_param($param, $type);
}
/**
* Returns a particular array value for the named variable, taken from
* POST or GET. If the parameter doesn't exist then an error is
* thrown because we require this variable.
*
* This function should be used to initialise all required values
* in a script that are based on parameters. Usually it will be
* used like this:
* $ids = required_param_array('ids', PARAM_INT);
*
* Note: arrays of arrays are not supported, only alphanumeric keys with _ and - are supported
*
* @param string $parname the name of the page parameter we want
* @param string $type expected type of parameter
* @return array
* @throws coding_exception
*/
function required_param_array($parname, $type) {
if (func_num_args() != 2 or empty($parname) or empty($type)) {
throw new coding_exception('required_param_array() requires $parname and $type to be specified (parameter: '.$parname.')');
}
// POST has precedence.
if (isset($_POST[$parname])) {
$param = $_POST[$parname];
} else if (isset($_GET[$parname])) {
$param = $_GET[$parname];
} else {
print_error('missingparam', '', '', $parname);
}
if (!is_array($param)) {
print_error('missingparam', '', '', $parname);
}
$result = array();
foreach ($param as $key => $value) {
if (!preg_match('/^[a-z0-9_-]+$/i', $key)) {
debugging('Invalid key name in required_param_array() detected: '.$key.', parameter: '.$parname);
continue;
}
$result[$key] = clean_param($value, $type);
}
return $result;
}
/**
* Returns a particular value for the named variable, taken from
* POST or GET, otherwise returning a given default.
*
* This function should be used to initialise all optional values
* in a script that are based on parameters. Usually it will be
* used like this:
* $name = optional_param('name', 'Fred', PARAM_TEXT);
*
* Please note the $type parameter is now required and the value can not be array.
*
* @param string $parname the name of the page parameter we want
* @param mixed $default the default value to return if nothing is found
* @param string $type expected type of parameter
* @return mixed
* @throws coding_exception
*/
function optional_param($parname, $default, $type) {
if (func_num_args() != 3 or empty($parname) or empty($type)) {
throw new coding_exception('optional_param requires $parname, $default + $type to be specified (parameter: '.$parname.')');
}
// POST has precedence.
if (isset($_POST[$parname])) {
$param = $_POST[$parname];
} else if (isset($_GET[$parname])) {
$param = $_GET[$parname];
} else {
return $default;
}
if (is_array($param)) {
debugging('Invalid array parameter detected in required_param(): '.$parname);
// TODO: switch to $default in Moodle 2.3.
return optional_param_array($parname, $default, $type);
}
return clean_param($param, $type);
}
/**
* Returns a particular array value for the named variable, taken from
* POST or GET, otherwise returning a given default.
*
* This function should be used to initialise all optional values
* in a script that are based on parameters. Usually it will be
* used like this:
* $ids = optional_param('id', array(), PARAM_INT);
*
* Note: arrays of arrays are not supported, only alphanumeric keys with _ and - are supported
*
* @param string $parname the name of the page parameter we want
* @param mixed $default the default value to return if nothing is found
* @param string $type expected type of parameter
* @return array
* @throws coding_exception
*/
function optional_param_array($parname, $default, $type) {
if (func_num_args() != 3 or empty($parname) or empty($type)) {
throw new coding_exception('optional_param_array requires $parname, $default + $type to be specified (parameter: '.$parname.')');
}
// POST has precedence.
if (isset($_POST[$parname])) {
$param = $_POST[$parname];
} else if (isset($_GET[$parname])) {
$param = $_GET[$parname];
} else {
return $default;
}
if (!is_array($param)) {
debugging('optional_param_array() expects array parameters only: '.$parname);
return $default;
}
$result = array();
foreach ($param as $key => $value) {
if (!preg_match('/^[a-z0-9_-]+$/i', $key)) {
debugging('Invalid key name in optional_param_array() detected: '.$key.', parameter: '.$parname);
continue;
}
$result[$key] = clean_param($value, $type);
}
return $result;
}
/**
* Strict validation of parameter values, the values are only converted
* to requested PHP type. Internally it is using clean_param, the values
* before and after cleaning must be equal - otherwise
* an invalid_parameter_exception is thrown.
* Objects and classes are not accepted.
*
* @param mixed $param
* @param string $type PARAM_ constant
* @param bool $allownull are nulls valid value?
* @param string $debuginfo optional debug information
* @return mixed the $param value converted to PHP type
* @throws invalid_parameter_exception if $param is not of given type
*/
function validate_param($param, $type, $allownull=NULL_NOT_ALLOWED, $debuginfo='') {
if (is_null($param)) {
if ($allownull == NULL_ALLOWED) {
return null;
} else {
throw new invalid_parameter_exception($debuginfo);
}
}
if (is_array($param) or is_object($param)) {
throw new invalid_parameter_exception($debuginfo);
}
$cleaned = clean_param($param, $type);
if ($type == PARAM_FLOAT) {
// Do not detect precision loss here.
if (is_float($param) or is_int($param)) {
// These always fit.
} else if (!is_numeric($param) or !preg_match('/^[\+-]?[0-9]*\.?[0-9]*(e[-+]?[0-9]+)?$/i', (string)$param)) {
throw new invalid_parameter_exception($debuginfo);
}
} else if ((string)$param !== (string)$cleaned) {
// Conversion to string is usually lossless.
throw new invalid_parameter_exception($debuginfo);
}
return $cleaned;
}
/**
* Makes sure array contains only the allowed types, this function does not validate array key names!
*
* <code>
* $options = clean_param($options, PARAM_INT);
* </code>
*
* @param array $param the variable array we are cleaning
* @param string $type expected format of param after cleaning.
* @param bool $recursive clean recursive arrays
* @return array
* @throws coding_exception
*/
function clean_param_array(array $param = null, $type, $recursive = false) {
// Convert null to empty array.
$param = (array)$param;
foreach ($param as $key => $value) {
if (is_array($value)) {
if ($recursive) {
$param[$key] = clean_param_array($value, $type, true);
} else {
throw new coding_exception('clean_param_array can not process multidimensional arrays when $recursive is false.');
}
} else {
$param[$key] = clean_param($value, $type);
}
}
return $param;
}
/**
* Used by {@link optional_param()} and {@link required_param()} to
* clean the variables and/or cast to specific types, based on
* an options field.
* <code>
* $course->format = clean_param($course->format, PARAM_ALPHA);
* $selectedgradeitem = clean_param($selectedgradeitem, PARAM_INT);
* </code>
*
* @param mixed $param the variable we are cleaning
* @param string $type expected format of param after cleaning.
* @return mixed
* @throws coding_exception
*/
function clean_param($param, $type) {
global $CFG;
if (is_array($param)) {
throw new coding_exception('clean_param() can not process arrays, please use clean_param_array() instead.');
} else if (is_object($param)) {
if (method_exists($param, '__toString')) {
$param = $param->__toString();
} else {
throw new coding_exception('clean_param() can not process objects, please use clean_param_array() instead.');
}
}
switch ($type) {
case PARAM_RAW:
// No cleaning at all.
$param = fix_utf8($param);
return $param;
case PARAM_RAW_TRIMMED:
// No cleaning, but strip leading and trailing whitespace.
$param = fix_utf8($param);
return trim($param);
case PARAM_CLEAN:
// General HTML cleaning, try to use more specific type if possible this is deprecated!
// Please use more specific type instead.
if (is_numeric($param)) {
return $param;
}
$param = fix_utf8($param);
// Sweep for scripts, etc.
return clean_text($param);
case PARAM_CLEANHTML:
// Clean html fragment.
$param = fix_utf8($param);
// Sweep for scripts, etc.
$param = clean_text($param, FORMAT_HTML);
return trim($param);
case PARAM_INT:
// Convert to integer.
return (int)$param;
case PARAM_FLOAT:
// Convert to float.
return (float)$param;
case PARAM_ALPHA:
// Remove everything not `a-z`.
return preg_replace('/[^a-zA-Z]/i', '', $param);
case PARAM_ALPHAEXT:
// Remove everything not `a-zA-Z_-` (originally allowed "/" too).
return preg_replace('/[^a-zA-Z_-]/i', '', $param);
case PARAM_ALPHANUM:
// Remove everything not `a-zA-Z0-9`.
return preg_replace('/[^A-Za-z0-9]/i', '', $param);
case PARAM_ALPHANUMEXT:
// Remove everything not `a-zA-Z0-9_-`.
return preg_replace('/[^A-Za-z0-9_-]/i', '', $param);
case PARAM_SEQUENCE:
// Remove everything not `0-9,`.
return preg_replace('/[^0-9,]/i', '', $param);
case PARAM_BOOL:
// Convert to 1 or 0.
$tempstr = strtolower($param);
if ($tempstr === 'on' or $tempstr === 'yes' or $tempstr === 'true') {
$param = 1;
} else if ($tempstr === 'off' or $tempstr === 'no' or $tempstr === 'false') {
$param = 0;
} else {
$param = empty($param) ? 0 : 1;
}
return $param;
case PARAM_NOTAGS:
// Strip all tags.
$param = fix_utf8($param);
return strip_tags($param);
case PARAM_TEXT:
// Leave only tags needed for multilang.
$param = fix_utf8($param);
// If the multilang syntax is not correct we strip all tags because it would break xhtml strict which is required
// for accessibility standards please note this cleaning does not strip unbalanced '>' for BC compatibility reasons.
do {
if (strpos($param, '</lang>') !== false) {
// Old and future mutilang syntax.
$param = strip_tags($param, '<lang>');
if (!preg_match_all('/<.*>/suU', $param, $matches)) {
break;
}
$open = false;
foreach ($matches[0] as $match) {
if ($match === '</lang>') {
if ($open) {
$open = false;
continue;
} else {
break 2;
}
}
if (!preg_match('/^<lang lang="[a-zA-Z0-9_-]+"\s*>$/u', $match)) {
break 2;
} else {
$open = true;
}
}
if ($open) {
break;
}
return $param;
} else if (strpos($param, '</span>') !== false) {
// Current problematic multilang syntax.
$param = strip_tags($param, '<span>');
if (!preg_match_all('/<.*>/suU', $param, $matches)) {
break;
}
$open = false;
foreach ($matches[0] as $match) {
if ($match === '</span>') {
if ($open) {
$open = false;
continue;
} else {
break 2;
}
}
if (!preg_match('/^<span(\s+lang="[a-zA-Z0-9_-]+"|\s+class="multilang"){2}\s*>$/u', $match)) {
break 2;
} else {
$open = true;
}
}
if ($open) {
break;
}
return $param;
}
} while (false);
// Easy, just strip all tags, if we ever want to fix orphaned '&' we have to do that in format_string().
return strip_tags($param);
case PARAM_COMPONENT:
// We do not want any guessing here, either the name is correct or not
// please note only normalised component names are accepted.
if (!preg_match('/^[a-z]+(_[a-z][a-z0-9_]*)?[a-z0-9]+$/', $param)) {
return '';
}
if (strpos($param, '__') !== false) {
return '';
}
if (strpos($param, 'mod_') === 0) {
// Module names must not contain underscores because we need to differentiate them from invalid plugin types.
if (substr_count($param, '_') != 1) {
return '';
}
}
return $param;
case PARAM_PLUGIN:
case PARAM_AREA:
// We do not want any guessing here, either the name is correct or not.
if (!is_valid_plugin_name($param)) {
return '';
}
return $param;
case PARAM_SAFEDIR:
// Remove everything not a-zA-Z0-9_- .
return preg_replace('/[^a-zA-Z0-9_-]/i', '', $param);
case PARAM_SAFEPATH:
// Remove everything not a-zA-Z0-9/_- .
return preg_replace('/[^a-zA-Z0-9\/_-]/i', '', $param);
case PARAM_FILE:
// Strip all suspicious characters from filename.
$param = fix_utf8($param);
$param = preg_replace('~[[:cntrl:]]|[&<>"`\|\':\\\\/]~u', '', $param);
if ($param === '.' || $param === '..') {
$param = '';
}
return $param;
case PARAM_PATH:
// Strip all suspicious characters from file path.
$param = fix_utf8($param);
$param = str_replace('\\', '/', $param);
// Explode the path and clean each element using the PARAM_FILE rules.
$breadcrumb = explode('/', $param);
foreach ($breadcrumb as $key => $crumb) {
if ($crumb === '.' && $key === 0) {
// Special condition to allow for relative current path such as ./currentdirfile.txt.
} else {
$crumb = clean_param($crumb, PARAM_FILE);
}
$breadcrumb[$key] = $crumb;
}
$param = implode('/', $breadcrumb);
// Remove multiple current path (./././) and multiple slashes (///).
$param = preg_replace('~//+~', '/', $param);
$param = preg_replace('~/(\./)+~', '/', $param);
return $param;
case PARAM_HOST:
// Allow FQDN or IPv4 dotted quad.
$param = preg_replace('/[^\.\d\w-]/', '', $param );
// Match ipv4 dotted quad.
if (preg_match('/(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})/', $param, $match)) {
// Confirm values are ok.
if ( $match[0] > 255
|| $match[1] > 255
|| $match[3] > 255
|| $match[4] > 255 ) {
// Hmmm, what kind of dotted quad is this?
$param = '';
}
} else if ( preg_match('/^[\w\d\.-]+$/', $param) // Dots, hyphens, numbers.
&& !preg_match('/^[\.-]/', $param) // No leading dots/hyphens.
&& !preg_match('/[\.-]$/', $param) // No trailing dots/hyphens.
) {
// All is ok - $param is respected.
} else {
// All is not ok...
$param='';
}
return $param;
case PARAM_URL:
// Allow safe urls.
$param = fix_utf8($param);
include_once($CFG->dirroot . '/lib/validateurlsyntax.php');
if (!empty($param) && validateUrlSyntax($param, 's?H?S?F?E-u-P-a?I?p?f?q?r?')) {
// All is ok, param is respected.
} else {
// Not really ok.
$param ='';
}
return $param;
case PARAM_LOCALURL:
// Allow http absolute, root relative and relative URLs within wwwroot.
$param = clean_param($param, PARAM_URL);
if (!empty($param)) {
if ($param === $CFG->wwwroot) {
// Exact match;
} else if (preg_match(':^/:', $param)) {
// Root-relative, ok!
} else if (preg_match('/^' . preg_quote($CFG->wwwroot . '/', '/') . '/i', $param)) {
// Absolute, and matches our wwwroot.
} else {
// Relative - let's make sure there are no tricks.
if (validateUrlSyntax('/' . $param, 's-u-P-a-p-f+q?r?')) {
// Looks ok.
} else {
$param = '';
}
}
}
return $param;
case PARAM_PEM:
$param = trim($param);
// PEM formatted strings may contain letters/numbers and the symbols:
// forward slash: /
// plus sign: +
// equal sign: =
// , surrounded by BEGIN and END CERTIFICATE prefix and suffixes.
if (preg_match('/^-----BEGIN CERTIFICATE-----([\s\w\/\+=]+)-----END CERTIFICATE-----$/', trim($param), $matches)) {
list($wholething, $body) = $matches;
unset($wholething, $matches);
$b64 = clean_param($body, PARAM_BASE64);
if (!empty($b64)) {
return "-----BEGIN CERTIFICATE-----\n$b64\n-----END CERTIFICATE-----\n";
} else {
return '';
}
}
return '';
case PARAM_BASE64:
if (!empty($param)) {
// PEM formatted strings may contain letters/numbers and the symbols
// forward slash: /
// plus sign: +
// equal sign: =.
if (0 >= preg_match('/^([\s\w\/\+=]+)$/', trim($param))) {
return '';
}
$lines = preg_split('/[\s]+/', $param, -1, PREG_SPLIT_NO_EMPTY);
// Each line of base64 encoded data must be 64 characters in length, except for the last line which may be less
// than (or equal to) 64 characters long.
for ($i=0, $j=count($lines); $i < $j; $i++) {
if ($i + 1 == $j) {
if (64 < strlen($lines[$i])) {
return '';
}
continue;
}
if (64 != strlen($lines[$i])) {
return '';
}
}
return implode("\n", $lines);
} else {
return '';
}
case PARAM_TAG:
$param = fix_utf8($param);
// Please note it is not safe to use the tag name directly anywhere,
// it must be processed with s(), urlencode() before embedding anywhere.
// Remove some nasties.
$param = preg_replace('~[[:cntrl:]]|[<>`]~u', '', $param);
// Convert many whitespace chars into one.
$param = preg_replace('/\s+/u', ' ', $param);
$param = core_text::substr(trim($param), 0, TAG_MAX_LENGTH);
return $param;
case PARAM_TAGLIST:
$param = fix_utf8($param);
$tags = explode(',', $param);
$result = array();
foreach ($tags as $tag) {
$res = clean_param($tag, PARAM_TAG);
if ($res !== '') {
$result[] = $res;
}
}
if ($result) {
return implode(',', $result);
} else {
return '';
}
case PARAM_CAPABILITY:
if (get_capability_info($param)) {
return $param;
} else {
return '';
}
case PARAM_PERMISSION:
$param = (int)$param;
if (in_array($param, array(CAP_INHERIT, CAP_ALLOW, CAP_PREVENT, CAP_PROHIBIT))) {
return $param;
} else {
return CAP_INHERIT;
}
case PARAM_AUTH:
$param = clean_param($param, PARAM_PLUGIN);
if (empty($param)) {
return '';
} else if (exists_auth_plugin($param)) {
return $param;
} else {
return '';
}
case PARAM_LANG:
$param = clean_param($param, PARAM_SAFEDIR);
if (get_string_manager()->translation_exists($param)) {
return $param;
} else {
// Specified language is not installed or param malformed.
return '';
}
case PARAM_THEME:
$param = clean_param($param, PARAM_PLUGIN);
if (empty($param)) {
return '';
} else if (file_exists("$CFG->dirroot/theme/$param/config.php")) {
return $param;
} else if (!empty($CFG->themedir) and file_exists("$CFG->themedir/$param/config.php")) {
return $param;
} else {
// Specified theme is not installed.
return '';
}
case PARAM_USERNAME:
$param = fix_utf8($param);
$param = trim($param);
// Convert uppercase to lowercase MDL-16919.
$param = core_text::strtolower($param);
if (empty($CFG->extendedusernamechars)) {
$param = str_replace(" " , "", $param);
// Regular expression, eliminate all chars EXCEPT:
// alphanum, dash (-), underscore (_), at sign (@) and period (.) characters.
$param = preg_replace('/[^-\.@_a-z0-9]/', '', $param);
}
return $param;
case PARAM_EMAIL:
$param = fix_utf8($param);
if (validate_email($param)) {
return $param;
} else {
return '';
}
case PARAM_STRINGID:
if (preg_match('|^[a-zA-Z][a-zA-Z0-9\.:/_-]*$|', $param)) {
return $param;
} else {
return '';
}
case PARAM_TIMEZONE:
// Can be int, float(with .5 or .0) or string seperated by '/' and can have '-_'.
$param = fix_utf8($param);
$timezonepattern = '/^(([+-]?(0?[0-9](\.[5|0])?|1[0-3](\.0)?|1[0-2]\.5))|(99)|[[:alnum:]]+(\/?[[:alpha:]_-])+)$/';
if (preg_match($timezonepattern, $param)) {
return $param;
} else {
return '';
}
default:
// Doh! throw error, switched parameters in optional_param or another serious problem.
print_error("unknownparamtype", '', '', $type);
}
}
/**
* Whether the PARAM_* type is compatible in RTL.
*
* Being compatible with RTL means that the data they contain can flow
* from right-to-left or left-to-right without compromising the user experience.
*
* Take URLs for example, they are not RTL compatible as they should always
* flow from the left to the right. This also applies to numbers, email addresses,
* configuration snippets, base64 strings, etc...
*
* This function tries to best guess which parameters can contain localised strings.
*
* @param string $paramtype Constant PARAM_*.
* @return bool
*/
function is_rtl_compatible($paramtype) {
return $paramtype == PARAM_TEXT || $paramtype == PARAM_NOTAGS;
}
/**
* Makes sure the data is using valid utf8, invalid characters are discarded.
*
* Note: this function is not intended for full objects with methods and private properties.
*
* @param mixed $value
* @return mixed with proper utf-8 encoding
*/
function fix_utf8($value) {
if (is_null($value) or $value === '') {
return $value;
} else if (is_string($value)) {
if ((string)(int)$value === $value) {
// Shortcut.
return $value;
}
// No null bytes expected in our data, so let's remove it.
$value = str_replace("\0", '', $value);
// Note: this duplicates min_fix_utf8() intentionally.
static $buggyiconv = null;
if ($buggyiconv === null) {
$buggyiconv = (!function_exists('iconv') or @iconv('UTF-8', 'UTF-8//IGNORE', '100'.chr(130).'') !== '100€');
}
if ($buggyiconv) {
if (function_exists('mb_convert_encoding')) {
$subst = mb_substitute_character();
mb_substitute_character('');
$result = mb_convert_encoding($value, 'utf-8', 'utf-8');
mb_substitute_character($subst);
} else {
// Warn admins on admin/index.php page.
$result = $value;
}
} else {
$result = @iconv('UTF-8', 'UTF-8//IGNORE', $value);
}
return $result;
} else if (is_array($value)) {
foreach ($value as $k => $v) {
$value[$k] = fix_utf8($v);
}
return $value;
} else if (is_object($value)) {
// Do not modify original.
$value = clone($value);
foreach ($value as $k => $v) {
$value->$k = fix_utf8($v);
}
return $value;
} else {
// This is some other type, no utf-8 here.
return $value;
}
}
/**
* Return true if given value is integer or string with integer value
*
* @param mixed $value String or Int
* @return bool true if number, false if not
*/
function is_number($value) {
if (is_int($value)) {
return true;
} else if (is_string($value)) {
return ((string)(int)$value) === $value;
} else {
return false;
}
}
/**
* Returns host part from url.
*
* @param string $url full url
* @return string host, null if not found
*/
function get_host_from_url($url) {
preg_match('|^[a-z]+://([a-zA-Z0-9-.]+)|i', $url, $matches);
if ($matches) {
return $matches[1];
}
return null;
}
/**
* Tests whether anything was returned by text editor
*
* This function is useful for testing whether something you got back from
* the HTML editor actually contains anything. Sometimes the HTML editor
* appear to be empty, but actually you get back a <br> tag or something.
*
* @param string $string a string containing HTML.
* @return boolean does the string contain any actual content - that is text,
* images, objects, etc.
*/
function html_is_blank($string) {
return trim(strip_tags($string, '<img><object><applet><input><select><textarea><hr>')) == '';
}
/**
* Set a key in global configuration
*
* Set a key/value pair in both this session's {@link $CFG} global variable
* and in the 'config' database table for future sessions.
*
* Can also be used to update keys for plugin-scoped configs in config_plugin table.
* In that case it doesn't affect $CFG.
*
* A NULL value will delete the entry.
*
* NOTE: this function is called from lib/db/upgrade.php
*
* @param string $name the key to set
* @param string $value the value to set (without magic quotes)
* @param string $plugin (optional) the plugin scope, default null
* @return bool true or exception
*/
function set_config($name, $value, $plugin=null) {
global $CFG, $DB;
if (empty($plugin)) {
if (!array_key_exists($name, $CFG->config_php_settings)) {
// So it's defined for this invocation at least.
if (is_null($value)) {
unset($CFG->$name);
} else {
// Settings from db are always strings.
$CFG->$name = (string)$value;
}
}
if ($DB->get_field('config', 'name', array('name' => $name))) {
if ($value === null) {
$DB->delete_records('config', array('name' => $name));
} else {
$DB->set_field('config', 'value', $value, array('name' => $name));
}
} else {
if ($value !== null) {
$config = new stdClass();
$config->name = $name;
$config->value = $value;
$DB->insert_record('config', $config, false);
}
}
if ($name === 'siteidentifier') {
cache_helper::update_site_identifier($value);
}
cache_helper::invalidate_by_definition('core', 'config', array(), 'core');
} else {
// Plugin scope.
if ($id = $DB->get_field('config_plugins', 'id', array('name' => $name, 'plugin' => $plugin))) {
if ($value===null) {
$DB->delete_records('config_plugins', array('name' => $name, 'plugin' => $plugin));
} else {
$DB->set_field('config_plugins', 'value', $value, array('id' => $id));
}
} else {
if ($value !== null) {
$config = new stdClass();
$config->plugin = $plugin;
$config->name = $name;
$config->value = $value;
$DB->insert_record('config_plugins', $config, false);
}
}
cache_helper::invalidate_by_definition('core', 'config', array(), $plugin);
}
return true;
}
/**
* Get configuration values from the global config table
* or the config_plugins table.
*
* If called with one parameter, it will load all the config
* variables for one plugin, and return them as an object.
*
* If called with 2 parameters it will return a string single
* value or false if the value is not found.
*
* NOTE: this function is called from lib/db/upgrade.php
*
* @static string|false $siteidentifier The site identifier is not cached. We use this static cache so
* that we need only fetch it once per request.
* @param string $plugin full component name
* @param string $name default null
* @return mixed hash-like object or single value, return false no config found
* @throws dml_exception
*/
function get_config($plugin, $name = null) {
global $CFG, $DB;
static $siteidentifier = null;
if ($plugin === 'moodle' || $plugin === 'core' || empty($plugin)) {
$forced =& $CFG->config_php_settings;
$iscore = true;
$plugin = 'core';
} else {
if (array_key_exists($plugin, $CFG->forced_plugin_settings)) {
$forced =& $CFG->forced_plugin_settings[$plugin];
} else {
$forced = array();
}
$iscore = false;
}
if ($siteidentifier === null) {
try {
// This may fail during installation.
// If you have a look at {@link initialise_cfg()} you will see that this is how we detect the need to
// install the database.
$siteidentifier = $DB->get_field('config', 'value', array('name' => 'siteidentifier'));
} catch (dml_exception $ex) {
// Set siteidentifier to false. We don't want to trip this continually.
$siteidentifier = false;
throw $ex;
}
}
if (!empty($name)) {
if (array_key_exists($name, $forced)) {
return (string)$forced[$name];
} else if ($name === 'siteidentifier' && $plugin == 'core') {
return $siteidentifier;
}
}
$cache = cache::make('core', 'config');
$result = $cache->get($plugin);
if ($result === false) {
// The user is after a recordset.
if (!$iscore) {
$result = $DB->get_records_menu('config_plugins', array('plugin' => $plugin), '', 'name,value');
} else {
// This part is not really used any more, but anyway...
$result = $DB->get_records_menu('config', array(), '', 'name,value');;
}
$cache->set($plugin, $result);
}
if (!empty($name)) {
if (array_key_exists($name, $result)) {
return $result[$name];
}
return false;
}
if ($plugin === 'core') {
$result['siteidentifier'] = $siteidentifier;
}
foreach ($forced as $key => $value) {
if (is_null($value) or is_array($value) or is_object($value)) {
// We do not want any extra mess here, just real settings that could be saved in db.
unset($result[$key]);
} else {
// Convert to string as if it went through the DB.
$result[$key] = (string)$value;
}
}
return (object)$result;
}
/**
* Removes a key from global configuration.
*
* NOTE: this function is called from lib/db/upgrade.php
*
* @param string $name the key to set
* @param string $plugin (optional) the plugin scope
* @return boolean whether the operation succeeded.
*/
function unset_config($name, $plugin=null) {
global $CFG, $DB;
if (empty($plugin)) {
unset($CFG->$name);
$DB->delete_records('config', array('name' => $name));
cache_helper::invalidate_by_definition('core', 'config', array(), 'core');
} else {
$DB->delete_records('config_plugins', array('name' => $name, 'plugin' => $plugin));
cache_helper::invalidate_by_definition('core', 'config', array(), $plugin);
}
return true;
}
/**
* Remove all the config variables for a given plugin.
*
* NOTE: this function is called from lib/db/upgrade.php
*
* @param string $plugin a plugin, for example 'quiz' or 'qtype_multichoice';
* @return boolean whether the operation succeeded.
*/
function unset_all_config_for_plugin($plugin) {
global $DB;
// Delete from the obvious config_plugins first.
$DB->delete_records('config_plugins', array('plugin' => $plugin));
// Next delete any suspect settings from config.
$like = $DB->sql_like('name', '?', true, true, false, '|');
$params = array($DB->sql_like_escape($plugin.'_', '|') . '%');
$DB->delete_records_select('config', $like, $params);
// Finally clear both the plugin cache and the core cache (suspect settings now removed from core).
cache_helper::invalidate_by_definition('core', 'config', array(), array('core', $plugin));
return true;
}
/**
* Use this function to get a list of users from a config setting of type admin_setting_users_with_capability.
*
* All users are verified if they still have the necessary capability.
*
* @param string $value the value of the config setting.
* @param string $capability the capability - must match the one passed to the admin_setting_users_with_capability constructor.
* @param bool $includeadmins include administrators.
* @return array of user objects.
*/
function get_users_from_config($value, $capability, $includeadmins = true) {
if (empty($value) or $value === '$@NONE@$') {
return array();
}
// We have to make sure that users still have the necessary capability,
// it should be faster to fetch them all first and then test if they are present
// instead of validating them one-by-one.
$users = get_users_by_capability(context_system::instance(), $capability);
if ($includeadmins) {
$admins = get_admins();
foreach ($admins as $admin) {
$users[$admin->id] = $admin;
}
}
if ($value === '$@ALL@$') {
return $users;
}
$result = array(); // Result in correct order.
$allowed = explode(',', $value);
foreach ($allowed as $uid) {
if (isset($users[$uid])) {
$user = $users[$uid];
$result[$user->id] = $user;
}
}
return $result;
}
/**
* Invalidates browser caches and cached data in temp.
*
* @return void
*/
function purge_all_caches() {
purge_caches();
}
/**
* Selectively invalidate different types of cache.
*
* Purges the cache areas specified. By default, this will purge all caches but can selectively purge specific
* areas alone or in combination.
*
* @param bool[] $options Specific parts of the cache to purge. Valid options are:
* 'muc' Purge MUC caches?
* 'theme' Purge theme cache?
* 'lang' Purge language string cache?
* 'js' Purge javascript cache?
* 'filter' Purge text filter cache?
* 'other' Purge all other caches?
*/
function purge_caches($options = []) {
$defaults = array_fill_keys(['muc', 'theme', 'lang', 'js', 'filter', 'other'], false);
if (empty(array_filter($options))) {
$options = array_fill_keys(array_keys($defaults), true); // Set all options to true.
} else {
$options = array_merge($defaults, array_intersect_key($options, $defaults)); // Override defaults with specified options.
}
if ($options['muc']) {
cache_helper::purge_all();
}
if ($options['theme']) {
theme_reset_all_caches();
}
if ($options['lang']) {
get_string_manager()->reset_caches();
}
if ($options['js']) {
js_reset_all_caches();
}
if ($options['filter']) {
reset_text_filters_cache();
}
if ($options['other']) {
purge_other_caches();
}
}
/**
* Purge all non-MUC caches not otherwise purged in purge_caches.
*
* IMPORTANT - If you are adding anything here to do with the cache directory you should also have a look at
* {@link phpunit_util::reset_dataroot()}
*/
function purge_other_caches() {
global $DB, $CFG;
core_text::reset_caches();
if (class_exists('core_plugin_manager')) {
core_plugin_manager::reset_caches();
}
// Bump up cacherev field for all courses.
try {
increment_revision_number('course', 'cacherev', '');
} catch (moodle_exception $e) {
// Ignore exception since this function is also called before upgrade script when field course.cacherev does not exist yet.
}
$DB->reset_caches();
// Purge all other caches: rss, simplepie, etc.
clearstatcache();
remove_dir($CFG->cachedir.'', true);
// Make sure cache dir is writable, throws exception if not.
make_cache_directory('');
// This is the only place where we purge local caches, we are only adding files there.
// The $CFG->localcachedirpurged flag forces local directories to be purged on cluster nodes.
remove_dir($CFG->localcachedir, true);
set_config('localcachedirpurged', time());
make_localcache_directory('', true);
\core\task\manager::clear_static_caches();
}
/**
* Get volatile flags
*
* @param string $type
* @param int $changedsince default null
* @return array records array
*/
function get_cache_flags($type, $changedsince = null) {
global $DB;
$params = array('type' => $type, 'expiry' => time());
$sqlwhere = "flagtype = :type AND expiry >= :expiry";
if ($changedsince !== null) {
$params['changedsince'] = $changedsince;
$sqlwhere .= " AND timemodified > :changedsince";
}
$cf = array();
if ($flags = $DB->get_records_select('cache_flags', $sqlwhere, $params, '', 'name,value')) {
foreach ($flags as $flag) {
$cf[$flag->name] = $flag->value;
}
}
return $cf;
}
/**
* Get volatile flags
*
* @param string $type
* @param string $name
* @param int $changedsince default null
* @return string|false The cache flag value or false
*/
function get_cache_flag($type, $name, $changedsince=null) {
global $DB;
$params = array('type' => $type, 'name' => $name, 'expiry' => time());
$sqlwhere = "flagtype = :type AND name = :name AND expiry >= :expiry";
if ($changedsince !== null) {
$params['changedsince'] = $changedsince;
$sqlwhere .= " AND timemodified > :changedsince";
}
return $DB->get_field_select('cache_flags', 'value', $sqlwhere, $params);
}
/**
* Set a volatile flag
*
* @param string $type the "type" namespace for the key
* @param string $name the key to set
* @param string $value the value to set (without magic quotes) - null will remove the flag
* @param int $expiry (optional) epoch indicating expiry - defaults to now()+ 24hs
* @return bool Always returns true
*/
function set_cache_flag($type, $name, $value, $expiry = null) {
global $DB;
$timemodified = time();
if ($expiry === null || $expiry < $timemodified) {
$expiry = $timemodified + 24 * 60 * 60;
} else {
$expiry = (int)$expiry;
}
if ($value === null) {
unset_cache_flag($type, $name);
return true;
}
if ($f = $DB->get_record('cache_flags', array('name' => $name, 'flagtype' => $type), '*', IGNORE_MULTIPLE)) {
// This is a potential problem in DEBUG_DEVELOPER.
if ($f->value == $value and $f->expiry == $expiry and $f->timemodified == $timemodified) {
return true; // No need to update.
}
$f->value = $value;
$f->expiry = $expiry;
$f->timemodified = $timemodified;
$DB->update_record('cache_flags', $f);
} else {
$f = new stdClass();
$f->flagtype = $type;
$f->name = $name;
$f->value = $value;
$f->expiry = $expiry;
$f->timemodified = $timemodified;
$DB->insert_record('cache_flags', $f);
}
return true;
}
/**
* Removes a single volatile flag
*
* @param string $type the "type" namespace for the key
* @param string $name the key to set
* @return bool
*/
function unset_cache_flag($type, $name) {
global $DB;
$DB->delete_records('cache_flags', array('name' => $name, 'flagtype' => $type));
return true;
}
/**
* Garbage-collect volatile flags
*
* @return bool Always returns true
*/
function gc_cache_flags() {
global $DB;
$DB->delete_records_select('cache_flags', 'expiry < ?', array(time()));
return true;
}
// USER PREFERENCE API.
/**
* Refresh user preference cache. This is used most often for $USER
* object that is stored in session, but it also helps with performance in cron script.
*
* Preferences for each user are loaded on first use on every page, then again after the timeout expires.
*
* @package core
* @category preference
* @access public
* @param stdClass $user User object. Preferences are preloaded into 'preference' property
* @param int $cachelifetime Cache life time on the current page (in seconds)
* @throws coding_exception
* @return null
*/
function check_user_preferences_loaded(stdClass $user, $cachelifetime = 120) {
global $DB;
// Static cache, we need to check on each page load, not only every 2 minutes.
static $loadedusers = array();
if (!isset($user->id)) {
throw new coding_exception('Invalid $user parameter in check_user_preferences_loaded() call, missing id field');
}
if (empty($user->id) or isguestuser($user->id)) {
// No permanent storage for not-logged-in users and guest.
if (!isset($user->preference)) {
$user->preference = array();
}
return;
}
$timenow = time();
if (isset($loadedusers[$user->id]) and isset($user->preference) and isset($user->preference['_lastloaded'])) {
// Already loaded at least once on this page. Are we up to date?
if ($user->preference['_lastloaded'] + $cachelifetime > $timenow) {
// No need to reload - we are on the same page and we loaded prefs just a moment ago.
return;
} else if (!get_cache_flag('userpreferenceschanged', $user->id, $user->preference['_lastloaded'])) {
// No change since the lastcheck on this page.
$user->preference['_lastloaded'] = $timenow;
return;
}
}
// OK, so we have to reload all preferences.
$loadedusers[$user->id] = true;
$user->preference = $DB->get_records_menu('user_preferences', array('userid' => $user->id), '', 'name,value'); // All values.
$user->preference['_lastloaded'] = $timenow;
}
/**
* Called from set/unset_user_preferences, so that the prefs can be correctly reloaded in different sessions.
*
* NOTE: internal function, do not call from other code.
*
* @package core
* @access private
* @param integer $userid the user whose prefs were changed.
*/
function mark_user_preferences_changed($userid) {
global $CFG;
if (empty($userid) or isguestuser($userid)) {
// No cache flags for guest and not-logged-in users.
return;
}
set_cache_flag('userpreferenceschanged', $userid, 1, time() + $CFG->sessiontimeout);
}
/**
* Sets a preference for the specified user.
*
* If a $user object is submitted it's 'preference' property is used for the preferences cache.
*
* When additional validation/permission check is needed it is better to use {@see useredit_update_user_preference()}
*
* @package core
* @category preference
* @access public
* @param string $name The key to set as preference for the specified user
* @param string $value The value to set for the $name key in the specified user's
* record, null means delete current value.
* @param stdClass|int|null $user A moodle user object or id, null means current user
* @throws coding_exception
* @return bool Always true or exception
*/
function set_user_preference($name, $value, $user = null) {
global $USER, $DB;
if (empty($name) or is_numeric($name) or $name === '_lastloaded') {
throw new coding_exception('Invalid preference name in set_user_preference() call');
}
if (is_null($value)) {
// Null means delete current.
return unset_user_preference($name, $user);
} else if (is_object($value)) {
throw new coding_exception('Invalid value in set_user_preference() call, objects are not allowed');
} else if (is_array($value)) {
throw new coding_exception('Invalid value in set_user_preference() call, arrays are not allowed');
}
// Value column maximum length is 1333 characters.
$value = (string)$value;
if (core_text::strlen($value) > 1333) {
throw new coding_exception('Invalid value in set_user_preference() call, value is is too long for the value column');
}
if (is_null($user)) {
$user = $USER;
} else if (isset($user->id)) {
// It is a valid object.
} else if (is_numeric($user)) {
$user = (object)array('id' => (int)$user);
} else {
throw new coding_exception('Invalid $user parameter in set_user_preference() call');
}
check_user_preferences_loaded($user);
if (empty($user->id) or isguestuser($user->id)) {
// No permanent storage for not-logged-in users and guest.
$user->preference[$name] = $value;
return true;
}
if ($preference = $DB->get_record('user_preferences', array('userid' => $user->id, 'name' => $name))) {
if ($preference->value === $value and isset($user->preference[$name]) and $user->preference[$name] === $value) {
// Preference already set to this value.
return true;
}
$DB->set_field('user_preferences', 'value', $value, array('id' => $preference->id));
} else {
$preference = new stdClass();
$preference->userid = $user->id;
$preference->name = $name;
$preference->value = $value;
$DB->insert_record('user_preferences', $preference);
}
// Update value in cache.
$user->preference[$name] = $value;
// Update the $USER in case where we've not a direct reference to $USER.
if ($user !== $USER && $user->id == $USER->id) {
$USER->preference[$name] = $value;
}
// Set reload flag for other sessions.
mark_user_preferences_changed($user->id);
return true;
}
/**
* Sets a whole array of preferences for the current user
*
* If a $user object is submitted it's 'preference' property is used for the preferences cache.
*
* @package core
* @category preference
* @access public
* @param array $prefarray An array of key/value pairs to be set
* @param stdClass|int|null $user A moodle user object or id, null means current user
* @return bool Always true or exception
*/
function set_user_preferences(array $prefarray, $user = null) {
foreach ($prefarray as $name => $value) {
set_user_preference($name, $value, $user);
}
return true;
}
/**
* Unsets a preference completely by deleting it from the database
*
* If a $user object is submitted it's 'preference' property is used for the preferences cache.
*
* @package core
* @category preference
* @access public
* @param string $name The key to unset as preference for the specified user
* @param stdClass|int|null $user A moodle user object or id, null means current user
* @throws coding_exception
* @return bool Always true or exception
*/
function unset_user_preference($name, $user = null) {
global $USER, $DB;
if (empty($name) or is_numeric($name) or $name === '_lastloaded') {
throw new coding_exception('Invalid preference name in unset_user_preference() call');
}
if (is_null($user)) {
$user = $USER;
} else if (isset($user->id)) {
// It is a valid object.
} else if (is_numeric($user)) {
$user = (object)array('id' => (int)$user);
} else {
throw new coding_exception('Invalid $user parameter in unset_user_preference() call');
}
check_user_preferences_loaded($user);
if (empty($user->id) or isguestuser($user->id)) {
// No permanent storage for not-logged-in user and guest.
unset($user->preference[$name]);
return true;
}
// Delete from DB.
$DB->delete_records('user_preferences', array('userid' => $user->id, 'name' => $name));
// Delete the preference from cache.
unset($user->preference[$name]);
// Update the $USER in case where we've not a direct reference to $USER.
if ($user !== $USER && $user->id == $USER->id) {
unset($USER->preference[$name]);
}
// Set reload flag for other sessions.
mark_user_preferences_changed($user->id);
return true;
}
/**
* Used to fetch user preference(s)
*
* If no arguments are supplied this function will return
* all of the current user preferences as an array.
*
* If a name is specified then this function
* attempts to return that particular preference value. If
* none is found, then the optional value $default is returned,
* otherwise null.
*
* If a $user object is submitted it's 'preference' property is used for the preferences cache.
*
* @package core
* @category preference
* @access public
* @param string $name Name of the key to use in finding a preference value
* @param mixed|null $default Value to be returned if the $name key is not set in the user preferences
* @param stdClass|int|null $user A moodle user object or id, null means current user
* @throws coding_exception
* @return string|mixed|null A string containing the value of a single preference. An
* array with all of the preferences or null
*/
function get_user_preferences($name = null, $default = null, $user = null) {
global $USER;
if (is_null($name)) {
// All prefs.
} else if (is_numeric($name) or $name === '_lastloaded') {
throw new coding_exception('Invalid preference name in get_user_preferences() call');
}
if (is_null($user)) {
$user = $USER;
} else if (isset($user->id)) {
// Is a valid object.
} else if (is_numeric($user)) {
if ($USER->id == $user) {
$user = $USER;
} else {
$user = (object)array('id' => (int)$user);
}
} else {
throw new coding_exception('Invalid $user parameter in get_user_preferences() call');
}
check_user_preferences_loaded($user);
if (empty($name)) {
// All values.
return $user->preference;
} else if (isset($user->preference[$name])) {
// The single string value.
return $user->preference[$name];
} else {
// Default value (null if not specified).
return $default;
}
}
// FUNCTIONS FOR HANDLING TIME.
/**
* Given Gregorian date parts in user time produce a GMT timestamp.
*
* @package core
* @category time
* @param int $year The year part to create timestamp of
* @param int $month The month part to create timestamp of
* @param int $day The day part to create timestamp of
* @param int $hour The hour part to create timestamp of
* @param int $minute The minute part to create timestamp of
* @param int $second The second part to create timestamp of
* @param int|float|string $timezone Timezone modifier, used to calculate GMT time offset.
* if 99 then default user's timezone is used {@link http://docs.moodle.org/dev/Time_API#Timezone}
* @param bool $applydst Toggle Daylight Saving Time, default true, will be
* applied only if timezone is 99 or string.
* @return int GMT timestamp
*/
function make_timestamp($year, $month=1, $day=1, $hour=0, $minute=0, $second=0, $timezone=99, $applydst=true) {
$date = new DateTime('now', core_date::get_user_timezone_object($timezone));
$date->setDate((int)$year, (int)$month, (int)$day);
$date->setTime((int)$hour, (int)$minute, (int)$second);
$time = $date->getTimestamp();
if ($time === false) {
throw new coding_exception('getTimestamp() returned false, please ensure you have passed correct values.'.
' This can fail if year is more than 2038 and OS is 32 bit windows');
}
// Moodle BC DST stuff.
if (!$applydst) {
$time += dst_offset_on($time, $timezone);
}
return $time;
}
/**
* Format a date/time (seconds) as weeks, days, hours etc as needed
*
* Given an amount of time in seconds, returns string
* formatted nicely as years, days, hours etc as needed
*
* @package core
* @category time
* @uses MINSECS
* @uses HOURSECS
* @uses DAYSECS
* @uses YEARSECS
* @param int $totalsecs Time in seconds
* @param stdClass $str Should be a time object
* @return string A nicely formatted date/time string
*/
function format_time($totalsecs, $str = null) {
$totalsecs = abs($totalsecs);
if (!$str) {
// Create the str structure the slow way.
$str = new stdClass();
$str->day = get_string('day');
$str->days = get_string('days');
$str->hour = get_string('hour');
$str->hours = get_string('hours');
$str->min = get_string('min');
$str->mins = get_string('mins');
$str->sec = get_string('sec');
$str->secs = get_string('secs');
$str->year = get_string('year');
$str->years = get_string('years');
}
$years = floor($totalsecs/YEARSECS);
$remainder = $totalsecs - ($years*YEARSECS);
$days = floor($remainder/DAYSECS);
$remainder = $totalsecs - ($days*DAYSECS);
$hours = floor($remainder/HOURSECS);
$remainder = $remainder - ($hours*HOURSECS);
$mins = floor($remainder/MINSECS);
$secs = $remainder - ($mins*MINSECS);
$ss = ($secs == 1) ? $str->sec : $str->secs;
$sm = ($mins == 1) ? $str->min : $str->mins;
$sh = ($hours == 1) ? $str->hour : $str->hours;
$sd = ($days == 1) ? $str->day : $str->days;
$sy = ($years == 1) ? $str->year : $str->years;
$oyears = '';
$odays = '';
$ohours = '';
$omins = '';
$osecs = '';
if ($years) {
$oyears = $years .' '. $sy;
}
if ($days) {
$odays = $days .' '. $sd;
}
if ($hours) {
$ohours = $hours .' '. $sh;
}
if ($mins) {
$omins = $mins .' '. $sm;
}
if ($secs) {
$osecs = $secs .' '. $ss;
}
if ($years) {
return trim($oyears .' '. $odays);
}
if ($days) {
return trim($odays .' '. $ohours);
}
if ($hours) {
return trim($ohours .' '. $omins);
}
if ($mins) {
return trim($omins .' '. $osecs);
}
if ($secs) {
return $osecs;
}
return get_string('now');
}
/**
* Returns a formatted string that represents a date in user time.
*
* @package core
* @category time
* @param int $date the timestamp in UTC, as obtained from the database.
* @param string $format strftime format. You should probably get this using
* get_string('strftime...', 'langconfig');
* @param int|float|string $timezone by default, uses the user's time zone. if numeric and
* not 99 then daylight saving will not be added.
* {@link http://docs.moodle.org/dev/Time_API#Timezone}
* @param bool $fixday If true (default) then the leading zero from %d is removed.
* If false then the leading zero is maintained.
* @param bool $fixhour If true (default) then the leading zero from %I is removed.
* @return string the formatted date/time.
*/
function userdate($date, $format = '', $timezone = 99, $fixday = true, $fixhour = true) {
$calendartype = \core_calendar\type_factory::get_calendar_instance();
return $calendartype->timestamp_to_date_string($date, $format, $timezone, $fixday, $fixhour);
}
/**
* Returns a html "time" tag with both the exact user date with timezone information
* as a datetime attribute in the W3C format, and the user readable date and time as text.
*
* @package core
* @category time
* @param int $date the timestamp in UTC, as obtained from the database.
* @param string $format strftime format. You should probably get this using
* get_string('strftime...', 'langconfig');
* @param int|float|string $timezone by default, uses the user's time zone. if numeric and
* not 99 then daylight saving will not be added.
* {@link http://docs.moodle.org/dev/Time_API#Timezone}
* @param bool $fixday If true (default) then the leading zero from %d is removed.
* If false then the leading zero is maintained.
* @param bool $fixhour If true (default) then the leading zero from %I is removed.
* @return string the formatted date/time.
*/
function userdate_htmltime($date, $format = '', $timezone = 99, $fixday = true, $fixhour = true) {
$userdatestr = userdate($date, $format, $timezone, $fixday, $fixhour);
if (CLI_SCRIPT && !PHPUNIT_TEST) {
return $userdatestr;
}
$machinedate = new DateTime();
$machinedate->setTimestamp(intval($date));
$machinedate->setTimezone(core_date::get_user_timezone_object());
return html_writer::tag('time', $userdatestr, ['datetime' => $machinedate->format(DateTime::W3C)]);
}
/**
* Returns a formatted date ensuring it is UTF-8.
*
* If we are running under Windows convert to Windows encoding and then back to UTF-8
* (because it's impossible to specify UTF-8 to fetch locale info in Win32).
*
* @param int $date the timestamp - since Moodle 2.9 this is a real UTC timestamp
* @param string $format strftime format.
* @param int|float|string $tz the user timezone
* @return string the formatted date/time.
* @since Moodle 2.3.3
*/
function date_format_string($date, $format, $tz = 99) {
global $CFG;
$localewincharset = null;
// Get the calendar type user is using.
if ($CFG->ostype == 'WINDOWS') {
$calendartype = \core_calendar\type_factory::get_calendar_instance();
$localewincharset = $calendartype->locale_win_charset();
}
if ($localewincharset) {
$format = core_text::convert($format, 'utf-8', $localewincharset);
}
date_default_timezone_set(core_date::get_user_timezone($tz));
$datestring = strftime($format, $date);
core_date::set_default_server_timezone();
if ($localewincharset) {
$datestring = core_text::convert($datestring, $localewincharset, 'utf-8');
}
return $datestring;
}
/**
* Given a $time timestamp in GMT (seconds since epoch),
* returns an array that represents the Gregorian date in user time
*
* @package core
* @category time
* @param int $time Timestamp in GMT
* @param float|int|string $timezone user timezone
* @return array An array that represents the date in user time
*/
function usergetdate($time, $timezone=99) {
date_default_timezone_set(core_date::get_user_timezone($timezone));
$result = getdate($time);
core_date::set_default_server_timezone();
return $result;
}
/**
* Given a GMT timestamp (seconds since epoch), offsets it by
* the timezone. eg 3pm in India is 3pm GMT - 7 * 3600 seconds
*
* NOTE: this function does not include DST properly,
* you should use the PHP date stuff instead!
*
* @package core
* @category time
* @param int $date Timestamp in GMT
* @param float|int|string $timezone user timezone
* @return int
*/
function usertime($date, $timezone=99) {
$userdate = new DateTime('@' . $date);
$userdate->setTimezone(core_date::get_user_timezone_object($timezone));
$dst = dst_offset_on($date, $timezone);
return $date - $userdate->getOffset() + $dst;
}
/**
* Given a time, return the GMT timestamp of the most recent midnight
* for the current user.
*
* @package core
* @category time
* @param int $date Timestamp in GMT
* @param float|int|string $timezone user timezone
* @return int Returns a GMT timestamp
*/
function usergetmidnight($date, $timezone=99) {
$userdate = usergetdate($date, $timezone);
// Time of midnight of this user's day, in GMT.
return make_timestamp($userdate['year'], $userdate['mon'], $userdate['mday'], 0, 0, 0, $timezone);
}
/**
* Returns a string that prints the user's timezone
*
* @package core
* @category time
* @param float|int|string $timezone user timezone
* @return string
*/
function usertimezone($timezone=99) {
$tz = core_date::get_user_timezone($timezone);
return core_date::get_localised_timezone($tz);
}
/**
* Returns a float or a string which denotes the user's timezone
* 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)
* means that for this timezone there are also DST rules to be taken into account
* Checks various settings and picks the most dominant of those which have a value
*
* @package core
* @category time
* @param float|int|string $tz timezone to calculate GMT time offset before
* calculating user timezone, 99 is default user timezone
* {@link http://docs.moodle.org/dev/Time_API#Timezone}
* @return float|string
*/
function get_user_timezone($tz = 99) {
global $USER, $CFG;
$timezones = array(
$tz,
isset($CFG->forcetimezone) ? $CFG->forcetimezone : 99,
isset($USER->timezone) ? $USER->timezone : 99,
isset($CFG->timezone) ? $CFG->timezone : 99,
);
$tz = 99;
// Loop while $tz is, empty but not zero, or 99, and there is another timezone is the array.
foreach ($timezones as $nextvalue) {
if ((empty($tz) && !is_numeric($tz)) || $tz == 99) {
$tz = $nextvalue;
}
}
return is_numeric($tz) ? (float) $tz : $tz;
}
/**
* Calculates the Daylight Saving Offset for a given date/time (timestamp)
* - Note: Daylight saving only works for string timezones and not for float.
*
* @package core
* @category time
* @param int $time must NOT be compensated at all, it has to be a pure timestamp
* @param int|float|string $strtimezone user timezone
* @return int
*/
function dst_offset_on($time, $strtimezone = null) {
$tz = core_date::get_user_timezone($strtimezone);
$date = new DateTime('@' . $time);
$date->setTimezone(new DateTimeZone($tz));
if ($date->format('I') == '1') {
if ($tz === 'Australia/Lord_Howe') {
return 1800;
}
return 3600;
}
return 0;
}
/**
* Calculates when the day appears in specific month
*
* @package core
* @category time
* @param int $startday starting day of the month
* @param int $weekday The day when week starts (normally taken from user preferences)
* @param int $month The month whose day is sought
* @param int $year The year of the month whose day is sought
* @return int
*/
function find_day_in_month($startday, $weekday, $month, $year) {
$calendartype = \core_calendar\type_factory::get_calendar_instance();
$daysinmonth = days_in_month($month, $year);
$daysinweek = count($calendartype->get_weekdays());
if ($weekday == -1) {
// Don't care about weekday, so return:
// abs($startday) if $startday != -1
// $daysinmonth otherwise.
return ($startday == -1) ? $daysinmonth : abs($startday);
}
// From now on we 're looking for a specific weekday.
// Give "end of month" its actual value, since we know it.
if ($startday == -1) {
$startday = -1 * $daysinmonth;
}
// Starting from day $startday, the sign is the direction.
if ($startday < 1) {
$startday = abs($startday);
$lastmonthweekday = dayofweek($daysinmonth, $month, $year);
// This is the last such weekday of the month.
$lastinmonth = $daysinmonth + $weekday - $lastmonthweekday;
if ($lastinmonth > $daysinmonth) {
$lastinmonth -= $daysinweek;
}
// Find the first such weekday <= $startday.
while ($lastinmonth > $startday) {
$lastinmonth -= $daysinweek;
}
return $lastinmonth;
} else {
$indexweekday = dayofweek($startday, $month, $year);
$diff = $weekday - $indexweekday;
if ($diff < 0) {
$diff += $daysinweek;
}
// This is the first such weekday of the month equal to or after $startday.
$firstfromindex = $startday + $diff;
return $firstfromindex;
}
}
/**
* Calculate the number of days in a given month
*
* @package core
* @category time
* @param int $month The month whose day count is sought
* @param int $year The year of the month whose day count is sought
* @return int
*/
function days_in_month($month, $year) {
$calendartype = \core_calendar\type_factory::get_calendar_instance();
return $calendartype->get_num_days_in_month($year, $month);
}
/**
* Calculate the position in the week of a specific calendar day
*
* @package core
* @category time
* @param int $day The day of the date whose position in the week is sought
* @param int $month The month of the date whose position in the week is sought
* @param int $year The year of the date whose position in the week is sought
* @return int
*/
function dayofweek($day, $month, $year) {
$calendartype = \core_calendar\type_factory::get_calendar_instance();
return $calendartype->get_weekday($year, $month, $day);
}
// USER AUTHENTICATION AND LOGIN.
/**
* Returns full login url.
*
* Any form submissions for authentication to this URL must include username,
* password as well as a logintoken generated by \core\session\manager::get_login_token().
*
* @return string login url
*/
function get_login_url() {
global $CFG;
return "$CFG->wwwroot/login/index.php";
}
/**
* This function checks that the current user is logged in and has the
* required privileges
*
* This function checks that the current user is logged in, and optionally
* whether they are allowed to be in a particular course and view a particular
* course module.
* If they are not logged in, then it redirects them to the site login unless
* $autologinguest is set and {@link $CFG}->autologinguests is set to 1 in which
* case they are automatically logged in as guests.
* If $courseid is given and the user is not enrolled in that course then the
* user is redirected to the course enrolment page.
* If $cm is given and the course module is hidden and the user is not a teacher
* in the course then the user is redirected to the course home page.
*
* When $cm parameter specified, this function sets page layout to 'module'.
* You need to change it manually later if some other layout needed.
*
* @package core_access
* @category access
*
* @param mixed $courseorid id of the course or course object
* @param bool $autologinguest default true
* @param object $cm course module object
* @param bool $setwantsurltome Define if we want to set $SESSION->wantsurl, defaults to
* true. Used to avoid (=false) some scripts (file.php...) to set that variable,
* in order to keep redirects working properly. MDL-14495
* @param bool $preventredirect set to true in scripts that can not redirect (CLI, rss feeds, etc.), throws exceptions
* @return mixed Void, exit, and die depending on path
* @throws coding_exception
* @throws require_login_exception
* @throws moodle_exception
*/
function require_login($courseorid = null, $autologinguest = true, $cm = null, $setwantsurltome = true, $preventredirect = false) {
global $CFG, $SESSION, $USER, $PAGE, $SITE, $DB, $OUTPUT;
// Must not redirect when byteserving already started.
if (!empty($_SERVER['HTTP_RANGE'])) {
$preventredirect = true;
}
if (AJAX_SCRIPT) {
// We cannot redirect for AJAX scripts either.
$preventredirect = true;
}
// Setup global $COURSE, themes, language and locale.
if (!empty($courseorid)) {
if (is_object($courseorid)) {
$course = $courseorid;
} else if ($courseorid == SITEID) {
$course = clone($SITE);
} else {
$course = $DB->get_record('course', array('id' => $courseorid), '*', MUST_EXIST);
}
if ($cm) {
if ($cm->course != $course->id) {
throw new coding_exception('course and cm parameters in require_login() call do not match!!');
}
// Make sure we have a $cm from get_fast_modinfo as this contains activity access details.
if (!($cm instanceof cm_info)) {
// Note: nearly all pages call get_fast_modinfo anyway and it does not make any
// db queries so this is not really a performance concern, however it is obviously
// better if you use get_fast_modinfo to get the cm before calling this.
$modinfo = get_fast_modinfo($course);
$cm = $modinfo->get_cm($cm->id);
}
}
} else {
// Do not touch global $COURSE via $PAGE->set_course(),
// the reasons is we need to be able to call require_login() at any time!!
$course = $SITE;
if ($cm) {
throw new coding_exception('cm parameter in require_login() requires valid course parameter!');
}
}
// If this is an AJAX request and $setwantsurltome is true then we need to override it and set it to false.
// Otherwise the AJAX request URL will be set to $SESSION->wantsurl and events such as self enrolment in the future
// risk leading the user back to the AJAX request URL.
if ($setwantsurltome && defined('AJAX_SCRIPT') && AJAX_SCRIPT) {
$setwantsurltome = false;
}
// Redirect to the login page if session has expired, only with dbsessions enabled (MDL-35029) to maintain current behaviour.
if ((!isloggedin() or isguestuser()) && !empty($SESSION->has_timed_out) && !empty($CFG->dbsessions)) {
if ($preventredirect) {
throw new require_login_session_timeout_exception();
} else {
if ($setwantsurltome) {
$SESSION->wantsurl = qualified_me();
}
redirect(get_login_url());
}
}
// If the user is not even logged in yet then make sure they are.
if (!isloggedin()) {
if ($autologinguest and !empty($CFG->guestloginbutton) and !empty($CFG->autologinguests)) {
if (!$guest = get_complete_user_data('id', $CFG->siteguest)) {
// Misconfigured site guest, just redirect to login page.
redirect(get_login_url());
exit; // Never reached.
}
$lang = isset($SESSION->lang) ? $SESSION->lang : $CFG->lang;
complete_user_login($guest);
$USER->autologinguest = true;
$SESSION->lang = $lang;
} else {
// NOTE: $USER->site check was obsoleted by session test cookie, $USER->confirmed test is in login/index.php.
if ($preventredirect) {
throw new require_login_exception('You are not logged in');
}
if ($setwantsurltome) {
$SESSION->wantsurl = qualified_me();
}
$referer = get_local_referer(false);
if (!empty($referer)) {
$SESSION->fromurl = $referer;
}
// Give auth plugins an opportunity to authenticate or redirect to an external login page
$authsequence = get_enabled_auth_plugins(true); // auths, in sequence
foreach($authsequence as $authname) {
$authplugin = get_auth_plugin($authname);
$authplugin->pre_loginpage_hook();
if (isloggedin()) {
break;
}
}
// If we're still not logged in then go to the login page
if (!isloggedin()) {
redirect(get_login_url());
exit; // Never reached.
}
}
}
// Loginas as redirection if needed.
if ($course->id != SITEID and \core\session\manager::is_loggedinas()) {
if ($USER->loginascontext->contextlevel == CONTEXT_COURSE) {
if ($USER->loginascontext->instanceid != $course->id) {
print_error('loginasonecourse', '', $CFG->wwwroot.'/course/view.php?id='.$USER->loginascontext->instanceid);
}
}
}
// Check whether the user should be changing password (but only if it is REALLY them).
if (get_user_preferences('auth_forcepasswordchange') && !\core\session\manager::is_loggedinas()) {
$userauth = get_auth_plugin($USER->auth);
if ($userauth->can_change_password() and !$preventredirect) {
if ($setwantsurltome) {
$SESSION->wantsurl = qualified_me();
}
if ($changeurl = $userauth->change_password_url()) {
// Use plugin custom url.
redirect($changeurl);
} else {
// Use moodle internal method.
redirect($CFG->wwwroot .'/login/change_password.php');
}
} else if ($userauth->can_change_password()) {
throw new moodle_exception('forcepasswordchangenotice');
} else {
throw new moodle_exception('nopasswordchangeforced', 'auth');
}
}
// Check that the user account is properly set up. If we can't redirect to
// edit their profile and this is not a WS request, perform just the lax check.
// It will allow them to use filepicker on the profile edit page.
if ($preventredirect && !WS_SERVER) {
$usernotfullysetup = user_not_fully_set_up($USER, false);
} else {
$usernotfullysetup = user_not_fully_set_up($USER, true);
}
if ($usernotfullysetup) {
if ($preventredirect) {
throw new moodle_exception('usernotfullysetup');
}
if ($setwantsurltome) {
$SESSION->wantsurl = qualified_me();
}
redirect($CFG->wwwroot .'/user/edit.php?id='. $USER->id .'&amp;course='. SITEID);
}
// Make sure the USER has a sesskey set up. Used for CSRF protection.
sesskey();
// Do not bother admins with any formalities, except for activities pending deletion.
if (is_siteadmin() && !($cm && $cm->deletioninprogress)) {
// Set the global $COURSE.
if ($cm) {
$PAGE->set_cm($cm, $course);
$PAGE->set_pagelayout('incourse');
} else if (!empty($courseorid)) {
$PAGE->set_course($course);
}
// Set accesstime or the user will appear offline which messes up messaging.
// Do not update access time for webservice or ajax requests.
if (!WS_SERVER && !AJAX_SCRIPT) {
user_accesstime_log($course->id);
}
return;
}
// Scripts have a chance to declare that $USER->policyagreed should not be checked.
// This is mostly for places where users are actually accepting the policies, to avoid the redirect loop.
if (!defined('NO_SITEPOLICY_CHECK')) {
define('NO_SITEPOLICY_CHECK', false);
}
// Check that the user has agreed to a site policy if there is one - do not test in case of admins.
// Do not test if the script explicitly asked for skipping the site policies check.
if (!$USER->policyagreed && !is_siteadmin() && !NO_SITEPOLICY_CHECK) {
$manager = new \core_privacy\local\sitepolicy\manager();
if ($policyurl = $manager->get_redirect_url(isguestuser())) {
if ($preventredirect) {
throw new moodle_exception('sitepolicynotagreed', 'error', '', $policyurl->out());
}
if ($setwantsurltome) {
$SESSION->wantsurl = qualified_me();
}
redirect($policyurl);
}
}
// Fetch the system context, the course context, and prefetch its child contexts.
$sysctx = context_system::instance();
$coursecontext = context_course::instance($course->id, MUST_EXIST);
if ($cm) {
$cmcontext = context_module::instance($cm->id, MUST_EXIST);
} else {
$cmcontext = null;
}
// If the site is currently under maintenance, then print a message.
if (!empty($CFG->maintenance_enabled) and !has_capability('moodle/site:maintenanceaccess', $sysctx)) {
if ($preventredirect) {
throw new require_login_exception('Maintenance in progress');
}
$PAGE->set_context(null);
print_maintenance_message();
}
// Make sure the course itself is not hidden.
if ($course->id == SITEID) {
// Frontpage can not be hidden.
} else {
if (is_role_switched($course->id)) {
// When switching roles ignore the hidden flag - user had to be in course to do the switch.
} else {
if (!$course->visible and !has_capability('moodle/course:viewhiddencourses', $coursecontext)) {
// Originally there was also test of parent category visibility, BUT is was very slow in complex queries
// involving "my courses" now it is also possible to simply hide all courses user is not enrolled in :-).
if ($preventredirect) {
throw new require_login_exception('Course is hidden');
}
$PAGE->set_context(null);
// We need to override the navigation URL as the course won't have been added to the navigation and thus
// the navigation will mess up when trying to find it.
navigation_node::override_active_url(new moodle_url('/'));
notice(get_string('coursehidden'), $CFG->wwwroot .'/');
}
}
}
// Is the user enrolled?
if ($course->id == SITEID) {
// Everybody is enrolled on the frontpage.
} else {
if (\core\session\manager::is_loggedinas()) {
// Make sure the REAL person can access this course first.
$realuser = \core\session\manager::get_realuser();
if (!is_enrolled($coursecontext, $realuser->id, '', true) and
!is_viewing($coursecontext, $realuser->id) and !is_siteadmin($realuser->id)) {
if ($preventredirect) {
throw new require_login_exception('Invalid course login-as access');
}
$PAGE->set_context(null);
echo $OUTPUT->header();
notice(get_string('studentnotallowed', '', fullname($USER, true)), $CFG->wwwroot .'/');
}
}
$access = false;
if (is_role_switched($course->id)) {
// Ok, user had to be inside this course before the switch.
$access = true;
} else if (is_viewing($coursecontext, $USER)) {
// Ok, no need to mess with enrol.
$access = true;
} else {
if (isset($USER->enrol['enrolled'][$course->id])) {
if ($USER->enrol['enrolled'][$course->id] > time()) {
$access = true;
if (isset($USER->enrol['tempguest'][$course->id])) {
unset($USER->enrol['tempguest'][$course->id]);
remove_temp_course_roles($coursecontext);
}
} else {
// Expired.
unset($USER->enrol['enrolled'][$course->id]);
}
}
if (isset($USER->enrol['tempguest'][$course->id])) {
if ($USER->enrol['tempguest'][$course->id] == 0) {
$access = true;
} else if ($USER->enrol['tempguest'][$course->id] > time()) {
$access = true;
} else {
// Expired.
unset($USER->enrol['tempguest'][$course->id]);
remove_temp_course_roles($coursecontext);
}
}
if (!$access) {
// Cache not ok.
$until = enrol_get_enrolment_end($coursecontext->instanceid, $USER->id);
if ($until !== false) {
// Active participants may always access, a timestamp in the future, 0 (always) or false.
if ($until == 0) {
$until = ENROL_MAX_TIMESTAMP;
}
$USER->enrol['enrolled'][$course->id] = $until;
$access = true;
} else {
$params = array('courseid' => $course->id, 'status' => ENROL_INSTANCE_ENABLED);
$instances = $DB->get_records('enrol', $params, 'sortorder, id ASC');
$enrols = enrol_get_plugins(true);
// First ask all enabled enrol instances in course if they want to auto enrol user.
foreach ($instances as $instance) {
if (!isset($enrols[$instance->enrol])) {
continue;
}
// Get a duration for the enrolment, a timestamp in the future, 0 (always) or false.
$until = $enrols[$instance->enrol]->try_autoenrol($instance);
if ($until !== false) {
if ($until == 0) {
$until = ENROL_MAX_TIMESTAMP;
}
$USER->enrol['enrolled'][$course->id] = $until;
$access = true;
break;
}
}
// If not enrolled yet try to gain temporary guest access.
if (!$access) {
foreach ($instances as $instance) {
if (!isset($enrols[$instance->enrol])) {
continue;
}
// Get a duration for the guest access, a timestamp in the future or false.
$until = $enrols[$instance->enrol]->try_guestaccess($instance);
if ($until !== false and $until > time()) {
$USER->enrol['tempguest'][$course->id] = $until;
$access = true;
break;
}
}
}
}
}
}
if (!$access) {
if ($preventredirect) {
throw new require_login_exception('Not enrolled');
}
if ($setwantsurltome) {
$SESSION->wantsurl = qualified_me();
}
redirect($CFG->wwwroot .'/enrol/index.php?id='. $course->id);
}
}
// Check whether the activity has been scheduled for deletion. If so, then deny access, even for admins.
if ($cm && $cm->deletioninprogress) {
if ($preventredirect) {
throw new moodle_exception('activityisscheduledfordeletion');
}
require_once($CFG->dirroot . '/course/lib.php');
redirect(course_get_url($course), get_string('activityisscheduledfordeletion', 'error'));
}
// Check visibility of activity to current user; includes visible flag, conditional availability, etc.
if ($cm && !$cm->uservisible) {
if ($preventredirect) {
throw new require_login_exception('Activity is hidden');
}
// Get the error message that activity is not available and why (if explanation can be shown to the user).
$PAGE->set_course($course);
$renderer = $PAGE->get_renderer('course');
$message = $renderer->course_section_cm_unavailable_error_message($cm);
redirect(course_get_url($course), $message, null, \core\output\notification::NOTIFY_ERROR);
}
// Set the global $COURSE.
if ($cm) {
$PAGE->set_cm($cm, $course);
$PAGE->set_pagelayout('incourse');
} else if (!empty($courseorid)) {
$PAGE->set_course($course);
}
// Finally access granted, update lastaccess times.
// Do not update access time for webservice or ajax requests.
if (!WS_SERVER && !AJAX_SCRIPT) {
user_accesstime_log($course->id);
}
}
/**
* This function just makes sure a user is logged out.
*
* @package core_access
* @category access
*/
function require_logout() {
global $USER, $DB;
if (!isloggedin()) {
// This should not happen often, no need for hooks or events here.
\core\session\manager::terminate_current();
return;
}
// Execute hooks before action.
$authplugins = array();
$authsequence = get_enabled_auth_plugins();
foreach ($authsequence as $authname) {
$authplugins[$authname] = get_auth_plugin($authname);
$authplugins[$authname]->prelogout_hook();
}
// Store info that gets removed during logout.
$sid = session_id();
$event = \core\event\user_loggedout::create(
array(
'userid' => $USER->id,
'objectid' => $USER->id,
'other' => array('sessionid' => $sid),
)
);
if ($session = $DB->get_record('sessions', array('sid'=>$sid))) {
$event->add_record_snapshot(