/lib/moodlelib.php
PHP | 9965 lines | 5787 code | 1274 blank | 2904 comment | 1353 complexity | 45dc033818c0dcbdeda38730183a6082 MD5 | raw file
Possible License(s): GPL-3.0, LGPL-2.1, BSD-3-Clause, AGPL-3.0, MPL-2.0-no-copyleft-exception, Apache-2.0
Large files files are truncated, but you can click here to view the full file
- <?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. use only for text in HTML format. This cleaning may fix xhtml strictness too.
- */
- 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.
- */
- 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
- */
- 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
- */
- define('PARAM_INTEGER', 'int');
- /**
- * PARAM_NUMBER - deprecated alias of PARAM_FLOAT
- */
- 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
- */
- define('PARAM_ACTION', 'alphanumext');
- /**
- * PARAM_FORMAT - deprecated alias for PARAM_ALPHANUMEXT, use for names of plugins, formats, etc.
- * NOTE: originally alias for PARAM_APLHA
- */
- define('PARAM_FORMAT', 'alphanumext');
- /**
- * PARAM_MULTILANG - deprecated alias of PARAM_TEXT.
- */
- define('PARAM_MULTILANG', 'text');
- /**
- * PARAM_CLEANFILE - deprecated alias of PARAM_FILE; originally was removing regional chars too
- */
- define('PARAM_CLEANFILE', 'file');
- /// 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 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 if module supports outcomes */
- 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 */
- 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');
- /** 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);
- /**
- * 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', "http://hubdirectory.moodle.org");
- /**
- * Moodle.org url (should be moodle.org)
- */
- define('HUB_MOODLEORGHUBURL', "http://hub.moodle.org");
- /// 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,
- * for now PARAM_CLEAN is used for backwards compatibility only.
- *
- * @param string $parname the name of the page parameter we want
- * @param string $type expected type of parameter
- * @return mixed
- */
- function required_param($parname, $type) {
- if (!isset($type)) {
- debugging('required_param() requires $type to be specified.');
- $type = PARAM_CLEAN; // for now let's use this deprecated type
- }
- if (isset($_POST[$parname])) { // POST has precedence
- $param = $_POST[$parname];
- } else if (isset($_GET[$parname])) {
- $param = $_GET[$parname];
- } else {
- print_error('missingparam', '', '', $parname);
- }
- return clean_param($param, $type);
- }
- /**
- * 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 $default and $type parameters are now required,
- * for now PARAM_CLEAN is used for backwards compatibility only.
- *
- * @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
- */
- function optional_param($parname, $default, $type) {
- if (!isset($type)) {
- debugging('optional_param() requires $default and $type to be specified.');
- $type = PARAM_CLEAN; // for now let's use this deprecated type
- }
- if (!isset($default)) {
- $default = null;
- }
- if (isset($_POST[$parname])) { // POST has precedence
- $param = $_POST[$parname];
- } else if (isset($_GET[$parname])) {
- $param = $_GET[$parname];
- } else {
- return $default;
- }
- return clean_param($param, $type);
- }
- /**
- * 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 int $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 or invalid_parameter_exception
- */
- 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 ((string)$param !== (string)$cleaned) {
- // conversion to string is usually lossless
- throw new invalid_parameter_exception($debuginfo);
- }
- return $cleaned;
- }
- /**
- * 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);
- * $selectedgrade_item = clean_param($selectedgrade_item, PARAM_INT);
- * </code>
- *
- * @param mixed $param the variable we are cleaning
- * @param int $type expected format of param after cleaning.
- * @return mixed
- */
- function clean_param($param, $type) {
- global $CFG;
- if (is_array($param)) { // Let's loop
- $newparam = array();
- foreach ($param as $key => $value) {
- $newparam[$key] = clean_param($value, $type);
- }
- return $newparam;
- }
- switch ($type) {
- case PARAM_RAW: // no cleaning at all
- return $param;
- case PARAM_RAW_TRIMMED: // no cleaning, but strip leading and trailing whitespace.
- 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;
- }
- return clean_text($param); // Sweep for scripts, etc
- case PARAM_CLEANHTML: // clean html fragment
- $param = clean_text($param, FORMAT_HTML); // Sweep for scripts, etc
- return trim($param);
- case PARAM_INT:
- return (int)$param; // Convert to integer
- case PARAM_FLOAT:
- case PARAM_NUMBER:
- return (float)$param; // Convert to float
- 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
- return strip_tags($param);
- case PARAM_TEXT: // leave only tags needed for multilang
- // 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_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 = preg_replace('~[[:cntrl:]]|[&<>"`\|\':\\\\/]~u', '', $param);
- $param = preg_replace('~\.\.+~', '', $param);
- if ($param === '.') {
- $param = '';
- }
- return $param;
- case PARAM_PATH: // Strip all suspicious characters from file path
- $param = str_replace('\\', '/', $param);
- $param = preg_replace('~[[:cntrl:]]|[&<>"`\|\':]~u', '', $param);
- $param = preg_replace('~\.\.+~', '', $param);
- $param = preg_replace('~//+~', '/', $param);
- return preg_replace('~/(\./)+~', '/', $param);
- case PARAM_HOST: // allow FQDN or IPv4 dotted quad
- $param = preg_replace('/[^\.\d\w-]/','', $param ); // only allowed chars
- // 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 = '';
- }
- } elseif ( 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 ftp, http, mailto urls
- 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 {
- $param =''; // not really ok
- }
- 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 (preg_match(':^/:', $param)) {
- // root-relative, ok!
- } elseif (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:
- // 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+/', ' ', $param);
- $textlib = textlib_get_instance();
- $param = $textlib->substr(trim($param), 0, TAG_MAX_LENGTH);
- return $param;
- case PARAM_TAGLIST:
- $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_SAFEDIR);
- 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 {
- return ''; // Specified language is not installed or param malformed
- }
- case PARAM_THEME:
- $param = clean_param($param, PARAM_SAFEDIR);
- 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 {
- return ''; // Specified theme is not installed
- }
- case PARAM_USERNAME:
- $param = str_replace(" " , "", $param);
- $param = moodle_strtolower($param); // Convert uppercase to lowercase MDL-16919
- if (empty($CFG->extendedusernamechars)) {
- // 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:
- 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 '';
- }
- default: // throw error, switched parameters in optional_param or another serious problem
- print_error("unknownparamtype", '', '', $type);
- }
- }
- /**
- * 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.
- *
- * @global object
- * @global object
- * @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 {
- $CFG->$name = (string)$value; // settings from db are always strings
- }
- }
- 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);
- }
- }
- } 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);
- }
- }
- }
- 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.
- *
- * @param string $plugin full component name
- * @param string $name default NULL
- * @return mixed hash-like object or single value, return false no config found
- */
- function get_config($plugin, $name = NULL) {
- global $CFG, $DB;
- // normalise component name
- if ($plugin === 'moodle' or $plugin === 'core') {
- $plugin = NULL;
- }
- if (!empty($name)) { // the user is asking for a specific value
- if (!empty($plugin)) {
- if (isset($CFG->forced_plugin_settings[$plugin]) and array_key_exists($name, $CFG->forced_plugin_settings[$plugin])) {
- // setting forced in config file
- return $CFG->forced_plugin_settings[$plugin][$name];
- } else {
- return $DB->get_field('config_plugins', 'value', array('plugin'=>$plugin, 'name'=>$name));
- }
- } else {
- if (array_key_exists($name, $CFG->config_php_settings)) {
- // setting force in config file
- return $CFG->config_php_settings[$name];
- } else {
- return $DB->get_field('config', 'value', array('name'=>$name));
- }
- }
- }
- // the user is after a recordset
- if ($plugin) {
- $localcfg = $DB->get_records_menu('config_plugins', array('plugin'=>$plugin), '', 'name,value');
- if (isset($CFG->forced_plugin_settings[$plugin])) {
- foreach($CFG->forced_plugin_settings[$plugin] as $n=>$v) {
- if (is_null($v) or is_array($v) or is_object($v)) {
- // we do not want any extra mess here, just real settings that could be saved in db
- unset($localcfg[$n]);
- } else {
- //convert to string as if it went through the DB
- $localcfg[$n] = (string)$v;
- }
- }
- }
- if ($localcfg) {
- return (object)$localcfg;
- } else {
- return null;
- }
- } else {
- // this part is not really used any more, but anyway...
- $localcfg = $DB->get_records_menu('config', array(), '', 'name,value');
- foreach($CFG->config_php_settings as $n=>$v) {
- if (is_null($v) or is_array($v) or is_object($v)) {
- // we do not want any extra mess here, just real settings that could be saved in db
- unset($localcfg[$n]);
- } else {
- //convert to string as if it went through the DB
- $localcfg[$n] = (string)$v;
- }
- }
- return (object)$localcfg;
- }
- }
- /**
- * Removes a key from global configuration
- *
- * @param string $name the key to set
- * @param string $plugin (optional) the plugin scope
- * @global object
- * @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));
- } else {
- $DB->delete_records('config_plugins', array('name'=>$name, 'plugin'=>$plugin));
- }
- return true;
- }
- /**
- * Remove all the config variables for a given plugin.
- *
- * @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;
- $DB->delete_records('config_plugins', array('plugin' => $plugin));
- $DB->delete_records_select('config', 'name LIKE ?', array($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 $include admins, include administrators
- * @return array of user objects.
- */
- function get_users_from_config($value, $capability, $includeadmins = true) {
- global $CFG, $DB;
- 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(get_context_instance(CONTEXT_SYSTEM), $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() {
- global $CFG;
- reset_text_filters_cache();
- js_reset_all_caches();
- theme_reset_all_caches();
- get_string_manager()->reset_caches();
- // purge all other caches: rss, simplepie, etc.
- remove_dir($CFG->dataroot.'/cache', true);
- // make sure cache dir is writable, throws exception if not
- make_upload_directory('cache');
- clearstatcache();
- }
- /**
- * Get volatile flags
- *
- * @param string $type
- * @param int $changedsince default null
- * @return 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 records array
- */
- 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; helps rcache too
- }
- $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
- *
- * @global object
- * @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;
- }
- /// FUNCTIONS FOR HANDLING USER PREFERENCES ////////////////////////////////////
- /**
- * 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.
- *
- * @param stdClass $user user object, preferences are preloaded into ->preference property
- * @param int $cachelifetime cache life time on the current page (ins seconds)
- * @return void
- */
- function check_user_preferences_loaded(stdClass $user, $cachelifetime = 120) {
- global $DB;
- static $loadedusers = array(); // Static cache, we need to check on each page load, not only every 2 minutes.
- 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/delete_user_preferences, so that the prefs can
- * be correctly reloaded in different sessions.
- *
- * NOTE: internal function, do not call from other code.
- *
- * @param integer $userid the user whose prefs were changed.
- * @return void
- */
- 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 user object submitted, 'preference' property contains the preferences cache.
- *
- * @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 $user A moodle user object or id, null means current user
- * @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 = (string)$value;
- if (is_null($user)) {
- $user = $USER;
- } else if (isset($user->id)) {
- // $user is 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;
- // 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 user object submitted, 'preference' property contains the preferences cache.
- *
- * @param array $prefarray An array of key/value pairs to be set
- * @param stdClass|int $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 user object submitted, 'preference' property contains the preferences cache.
- *
- * @param string $name The key to unset as preference for the specified user
- * @param stdClass|int $user A moodle user object or id, null means current user
- * @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)) {
- // $user is 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]);
- // set reload flag for other sessions
- mark_user_preferences_changed($use…
Large files files are truncated, but you can click here to view the full file