/lib/moodlelib.php
PHP | 8638 lines | 5266 code | 1197 blank | 2175 comment | 1270 complexity | 12a22e63472578b4f37557a8a5fa5727 MD5 | raw file
Possible License(s): BSD-3-Clause, LGPL-2.0, LGPL-2.1
Large files files are truncated, but you can click here to view the full file
- <?php // $Id$
-
- ///////////////////////////////////////////////////////////////////////////
- // //
- // NOTICE OF COPYRIGHT //
- // //
- // Moodle - Modular Object-Oriented Dynamic Learning Environment //
- // http://moodle.org //
- // //
- // Copyright (C) 1999 onwards Martin Dougiamas http://dougiamas.com //
- // //
- // This program 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 2 of the License, or //
- // (at your option) any later version. //
- // //
- // This program 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: //
- // //
- // http://www.gnu.org/copyleft/gpl.html //
- // //
- ///////////////////////////////////////////////////////////////////////////
-
- /**
- * 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
- * @author Martin Dougiamas
- * @license http://www.gnu.org/copyleft/gpl.html GNU Public License
- * @package moodlecore
- */
-
- /// CONSTANTS (Encased in phpdoc proper comments)/////////////////////////
-
- /**
- * Used by some scripts to check they are being called by Moodle
- */
- define('MOODLE_INTERNAL', true);
-
- /// 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_RAW specifies a parameter that is not cleaned/processed in any way;
- * originally was 0, but changed because we need to detect unknown
- * parameter types and swiched order in clean_param().
- */
- define('PARAM_RAW', 666);
-
- /**
- * PARAM_CLEAN - obsoleted, please try to use more specific type of parameter.
- * It was one of the first types, that is why it is abused so much ;-)
- */
- define('PARAM_CLEAN', 0x0001);
-
- /**
- * PARAM_INT - integers only, use when expecting only numbers.
- */
- define('PARAM_INT', 0x0002);
-
- /**
- * PARAM_INTEGER - an alias for PARAM_INT
- */
- define('PARAM_INTEGER', 0x0002);
-
- /**
- * PARAM_NUMBER - a real/floating point number.
- */
- define('PARAM_NUMBER', 0x000a);
-
- /**
- * PARAM_ALPHA - contains only english letters.
- */
- define('PARAM_ALPHA', 0x0004);
-
- /**
- * PARAM_ACTION - an alias for PARAM_ALPHA, use for various actions in formas and urls
- * @TODO: should we alias it to PARAM_ALPHANUM ?
- */
- define('PARAM_ACTION', 0x0004);
-
- /**
- * PARAM_FORMAT - an alias for PARAM_ALPHA, use for names of plugins, formats, etc.
- * @TODO: should we alias it to PARAM_ALPHANUM ?
- */
- define('PARAM_FORMAT', 0x0004);
-
- /**
- * PARAM_NOTAGS - all html tags are stripped from the text. Do not abuse this type.
- */
- define('PARAM_NOTAGS', 0x0008);
-
- /**
- * PARAM_MULTILANG - alias of PARAM_TEXT.
- */
- define('PARAM_MULTILANG', 0x0009);
-
- /**
- * PARAM_TEXT - general plain text compatible with multilang filter, no other html tags.
- */
- define('PARAM_TEXT', 0x0009);
-
- /**
- * PARAM_FILE - safe file name, all dangerous chars are stripped, protects against XSS, SQL injections and directory traversals
- */
- define('PARAM_FILE', 0x0010);
-
- /**
- * PARAM_TAG - one tag (interests, blogs, etc.) - mostly international alphanumeric with spaces
- */
- define('PARAM_TAG', 0x0011);
-
- /**
- * PARAM_TAGLIST - list of tags separated by commas (interests, blogs, etc.)
- */
- define('PARAM_TAGLIST', 0x0012);
-
- /**
- * 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', 0x0020);
-
- /**
- * PARAM_HOST - expected fully qualified domain name (FQDN) or an IPv4 dotted quad (IP address)
- */
- define('PARAM_HOST', 0x0040);
-
- /**
- * PARAM_URL - expected properly formatted URL. Please note that domain part is required, http://localhost/ is not acceppted but http://localhost.localdomain/ is ok.
- */
- define('PARAM_URL', 0x0080);
-
- /**
- * 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', 0x0180);
-
- /**
- * PARAM_CLEANFILE - safe file name, all dangerous and regional chars are removed,
- * use when you want to store a new file submitted by students
- */
- define('PARAM_CLEANFILE',0x0200);
-
- /**
- * PARAM_ALPHANUM - expected numbers and letters only.
- */
- define('PARAM_ALPHANUM', 0x0400);
-
- /**
- * PARAM_BOOL - converts input into 0 or 1, use for switches in forms and urls.
- */
- define('PARAM_BOOL', 0x0800);
-
- /**
- * PARAM_CLEANHTML - cleans submitted HTML code and removes slashes
- * note: do not forget to addslashes() before storing into database!
- */
- define('PARAM_CLEANHTML',0x1000);
-
- /**
- * PARAM_ALPHAEXT the same contents as PARAM_ALPHA plus the chars in quotes: "/-_" allowed,
- * suitable for include() and require()
- * @TODO: should we rename this function to PARAM_SAFEDIRS??
- */
- define('PARAM_ALPHAEXT', 0x2000);
-
- /**
- * PARAM_SAFEDIR - safe directory name, suitable for include() and require()
- */
- define('PARAM_SAFEDIR', 0x4000);
-
- /**
- * PARAM_SEQUENCE - expects a sequence of numbers like 8 to 1,5,6,4,6,8,9. Numbers and comma only.
- */
- define('PARAM_SEQUENCE', 0x8000);
-
- /**
- * PARAM_PEM - Privacy Enhanced Mail format
- */
- define('PARAM_PEM', 0x10000);
-
- /**
- * PARAM_BASE64 - Base 64 encoded format
- */
- define('PARAM_BASE64', 0x20000);
-
-
- /// 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');
-
- /// Debug levels ///
- /** no warnings at all */
- define ('DEBUG_NONE', 0);
- /** E_ERROR | E_PARSE */
- define ('DEBUG_MINIMAL', 5);
- /** E_ERROR | E_PARSE | E_WARNING | E_NOTICE */
- define ('DEBUG_NORMAL', 15);
- /** E_ALL without E_STRICT for now, do show recoverable fatal errors */
- define ('DEBUG_ALL', 6143);
- /** DEBUG_ALL with extra Moodle debug messages - (DEBUG_ALL |Â 32768) */
- define ('DEBUG_DEVELOPER', 38911);
-
- /**
- * 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 constanst
- */
- //To prevent problems with multibytes strings, this should not exceed the
- //length of "varchar(255) / 3 (bytes / utf-8 character) = 85".
- define('TAG_MAX_LENGTH', 50);
-
- /**
- * Password policy constants
- */
- define ('PASSWORD_LOWER', 'abcdefghijklmnopqrstuvwxyz');
- define ('PASSWORD_UPPER', 'ABCDEFGHIJKLMNOPQRSTUVWXYZ');
- define ('PASSWORD_DIGITS', '0123456789');
- define ('PASSWORD_NONALPHANUM', '.,;:!?_-+/*@#&$');
-
- if (!defined('SORT_LOCALE_STRING')) { // PHP < 4.4.0 - TODO: remove in 2.0
- define('SORT_LOCALE_STRING', SORT_STRING);
- }
-
-
- /// 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 string $parname the name of the page parameter we want
- * @param int $type expected type of parameter
- * @return mixed
- */
- function required_param($parname, $type=PARAM_CLEAN) {
-
- // detect_unchecked_vars addition
- global $CFG;
- if (!empty($CFG->detect_unchecked_vars)) {
- global $UNCHECKED_VARS;
- unset ($UNCHECKED_VARS->vars[$parname]);
- }
-
- if (isset($_POST[$parname])) { // POST has precedence
- $param = $_POST[$parname];
- } else if (isset($_GET[$parname])) {
- $param = $_GET[$parname];
- } else {
- error('A required parameter ('.$parname.') was missing');
- }
-
- 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 string $parname the name of the page parameter we want
- * @param mixed $default the default value to return if nothing is found
- * @param int $type expected type of parameter
- * @return mixed
- */
- function optional_param($parname, $default=NULL, $type=PARAM_CLEAN) {
-
- // detect_unchecked_vars addition
- global $CFG;
- if (!empty($CFG->detect_unchecked_vars)) {
- global $UNCHECKED_VARS;
- unset ($UNCHECKED_VARS->vars[$parname]);
- }
-
- 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);
- }
-
- /**
- * 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_CLEAN);
- * </code>
- *
- * @uses $CFG
- * @uses PARAM_RAW
- * @uses PARAM_CLEAN
- * @uses PARAM_CLEANHTML
- * @uses PARAM_INT
- * @uses PARAM_NUMBER
- * @uses PARAM_ALPHA
- * @uses PARAM_ALPHANUM
- * @uses PARAM_ALPHAEXT
- * @uses PARAM_SEQUENCE
- * @uses PARAM_BOOL
- * @uses PARAM_NOTAGS
- * @uses PARAM_TEXT
- * @uses PARAM_SAFEDIR
- * @uses PARAM_CLEANFILE
- * @uses PARAM_FILE
- * @uses PARAM_PATH
- * @uses PARAM_HOST
- * @uses PARAM_URL
- * @uses PARAM_LOCALURL
- * @uses PARAM_PEM
- * @uses PARAM_BASE64
- * @uses PARAM_TAG
- * @uses PARAM_SEQUENCE
- * @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_CLEAN: // General HTML cleaning, try to use more specific type if possible
- if (is_numeric($param)) {
- return $param;
- }
- $param = stripslashes($param); // Needed for kses to work fine
- $param = clean_text($param); // Sweep for scripts, etc
- return addslashes($param); // Restore original request parameter slashes
-
- case PARAM_CLEANHTML: // prepare html fragment for display, do not store it into db!!
- $param = stripslashes($param); // Remove any slashes
- $param = clean_text($param); // Sweep for scripts, etc
- return trim($param);
-
- case PARAM_INT:
- return (int)$param; // Convert to integer
-
- case PARAM_NUMBER:
- return (float)$param; // Convert to integer
-
- case PARAM_ALPHA: // Remove everything not a-z
- 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_ALPHAEXT: // Remove everything not a-zA-Z/_-
- return preg_replace('/[^a-zA-Z\/_-]/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' ) {
- $param = 1;
- } else if ($tempstr == 'off' or $tempstr == 'no') {
- $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
- return clean_param(strip_tags($param, '<lang><span>'), PARAM_CLEAN);
-
- case PARAM_SAFEDIR: // Remove everything not a-zA-Z0-9_-
- return preg_replace('/[^a-zA-Z0-9_-]/i', '', $param);
-
- case PARAM_CLEANFILE: // allow only safe characters
- return clean_filename($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);
- //as long as magic_quotes_gpc is used, a backslash will be a
- //problem, so remove *all* backslash - BUT watch out for SQL injections caused by this sloppy design (skodak)
- $param = str_replace('\\', '', $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 '';
- }
-
- default: // throw error, switched parameters in optional_param or another serious problem
- error("Unknown parameter type: $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;
- }
- }
-
- /**
- * 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, objcts, 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.
- *
- * @param string $name the key to set
- * @param string $value the value to set (without magic quotes)
- * @param string $plugin (optional) the plugin scope
- * @uses $CFG
- * @return bool
- */
- function set_config($name, $value, $plugin=NULL) {
- /// No need for get_config because they are usually always available in $CFG
-
- global $CFG;
-
- 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 (get_field('config', 'name', 'name', $name)) {
- if ($value===null) {
- return delete_records('config', 'name', $name);
- } else {
- return set_field('config', 'value', addslashes($value), 'name', $name);
- }
- } else {
- if ($value===null) {
- return true;
- }
- $config = new object();
- $config->name = $name;
- $config->value = addslashes($value);
- return insert_record('config', $config);
- }
- } else { // plugin scope
- if ($id = get_field('config_plugins', 'id', 'name', $name, 'plugin', $plugin)) {
- if ($value===null) {
- return delete_records('config_plugins', 'name', $name, 'plugin', $plugin);
- } else {
- return set_field('config_plugins', 'value', addslashes($value), 'id', $id);
- }
- } else {
- if ($value===null) {
- return true;
- }
- $config = new object();
- $config->plugin = addslashes($plugin);
- $config->name = $name;
- $config->value = addslashes($value);
- return insert_record('config_plugins', $config);
- }
- }
- }
-
- /**
- * Get configuration values from the global config table
- * or the config_plugins table.
- *
- * If called with no parameters it will do the right thing
- * generating $CFG safely from the database without overwriting
- * existing values.
- *
- * If called with 2 parameters it will return a $string single
- * value or false of the value is not found.
- *
- * @param string $plugin
- * @param string $name
- * @uses $CFG
- * @return hash-like object or single value
- *
- */
- function get_config($plugin=NULL, $name=NULL) {
-
- global $CFG;
-
- if (!empty($name)) { // the user is asking for a specific value
- if (!empty($plugin)) {
- return get_field('config_plugins', 'value', 'plugin' , $plugin, 'name', $name);
- } else {
- return get_field('config', 'value', 'name', $name);
- }
- }
-
- // the user is after a recordset
- if (!empty($plugin)) {
- if ($configs=get_records('config_plugins', 'plugin', $plugin, '', 'name,value')) {
- $configs = (array)$configs;
- $localcfg = array();
- foreach ($configs as $config) {
- $localcfg[$config->name] = $config->value;
- }
- return (object)$localcfg;
- } else {
- return false;
- }
- } else {
- // this was originally in setup.php
- if ($configs = get_records('config')) {
- $localcfg = (array)$CFG;
- foreach ($configs as $config) {
- if (!isset($localcfg[$config->name])) {
- $localcfg[$config->name] = $config->value;
- }
- // do not complain anymore if config.php overrides settings from db
- }
-
- $localcfg = (object)$localcfg;
- return $localcfg;
- } else {
- // preserve $CFG if DB returns nothing or error
- return $CFG;
- }
-
- }
- }
-
- /**
- * Removes a key from global configuration
- *
- * @param string $name the key to set
- * @param string $plugin (optional) the plugin scope
- * @uses $CFG
- * @return bool
- */
- function unset_config($name, $plugin=NULL) {
-
- global $CFG;
-
- unset($CFG->$name);
-
- if (empty($plugin)) {
- return delete_records('config', 'name', $name);
- } else {
- return delete_records('config_plugins', 'name', $name, 'plugin', $plugin);
- }
- }
-
- /**
- * Get volatile flags
- *
- * @param string $type
- * @param int $changedsince
- * @return records array
- *
- */
- function get_cache_flags($type, $changedsince=NULL) {
-
- $type = addslashes($type);
-
- $sqlwhere = 'flagtype=\'' . $type . '\' AND expiry >= ' . time();
- if ($changedsince !== NULL) {
- $changedsince = (int)$changedsince;
- $sqlwhere .= ' AND timemodified > ' . $changedsince;
- }
- $cf = array();
- if ($flags=get_records_select('cache_flags', $sqlwhere, '', 'name,value')) {
- foreach ($flags as $flag) {
- $cf[$flag->name] = $flag->value;
- }
- }
- return $cf;
- }
-
- /**
- * Use this funciton to get a list of users from a config setting of type admin_setting_users_with_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.
- * @return array of user objects.
- */
- function get_users_from_config($value, $capability) {
- global $CFG;
- if ($value == '$@ALL@$') {
- $users = get_users_by_capability(get_context_instance(CONTEXT_SYSTEM), $capability);
- } else if ($value) {
- $usernames = explode(',', $value);
- $users = get_records_select('user', "username IN ('" . implode("','", $usernames) . "') AND mnethostid = " . $CFG->mnet_localhost_id);
- } else {
- $users = array();
- }
- return $users;
- }
-
- /**
- * Get volatile flags
- *
- * @param string $type
- * @param string $name
- * @param int $changedsince
- * @return records array
- *
- */
- function get_cache_flag($type, $name, $changedsince=NULL) {
-
- $type = addslashes($type);
- $name = addslashes($name);
-
- $sqlwhere = 'flagtype=\'' . $type . '\' AND name=\'' . $name . '\' AND expiry >= ' . time();
- if ($changedsince !== NULL) {
- $changedsince = (int)$changedsince;
- $sqlwhere .= ' AND timemodified > ' . $changedsince;
- }
- return get_field_select('cache_flags', 'value', $sqlwhere);
- }
-
- /**
- * 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
- */
- function set_cache_flag($type, $name, $value, $expiry=NULL) {
-
-
- $timemodified = time();
- if ($expiry===NULL || $expiry < $timemodified) {
- $expiry = $timemodified + 24 * 60 * 60;
- } else {
- $expiry = (int)$expiry;
- }
-
- if ($value === NULL) {
- return unset_cache_flag($type,$name);
- }
-
- $type = addslashes($type);
- $name = addslashes($name);
- if ($f = get_record('cache_flags', 'name', $name, 'flagtype', $type)) { // this is a potentail 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 = addslashes($value);
- $f->expiry = $expiry;
- $f->timemodified = $timemodified;
- return update_record('cache_flags', $f);
- } else {
- $f = new object();
- $f->flagtype = $type;
- $f->name = $name;
- $f->value = addslashes($value);
- $f->expiry = $expiry;
- $f->timemodified = $timemodified;
- return (bool)insert_record('cache_flags', $f);
- }
- }
-
- /**
- * Removes a single volatile flag
- *
- * @param string $type the "type" namespace for the key
- * @param string $name the key to set
- * @uses $CFG
- * @return bool
- */
- function unset_cache_flag($type, $name) {
-
- return delete_records('cache_flags',
- 'name', addslashes($name),
- 'flagtype', addslashes($type));
- }
-
- /**
- * Garbage-collect volatile flags
- *
- */
- function gc_cache_flags() {
- return delete_records_select('cache_flags', 'expiry < ' . time());
- }
-
- /**
- * Refresh current $USER session global variable with all their current preferences.
- * @uses $USER
- */
- function reload_user_preferences() {
-
- global $USER;
-
- //reset preference
- $USER->preference = array();
-
- if (!isloggedin() or isguestuser()) {
- // no permanent storage for not-logged-in user and guest
-
- } else if ($preferences = get_records('user_preferences', 'userid', $USER->id)) {
- foreach ($preferences as $preference) {
- $USER->preference[$preference->name] = $preference->value;
- }
- }
-
- return true;
- }
-
- /**
- * Sets a preference for the current user
- * Optionally, can set a preference for a different user object
- * @uses $USER
- * @todo Add a better description and include usage examples. Add inline links to $USER and user functions in above line.
-
- * @param string $name The key to set as preference for the specified user
- * @param string $value The value to set forthe $name key in the specified user's record
- * @param int $otheruserid A moodle user ID
- * @return bool
- */
- function set_user_preference($name, $value, $otheruserid=NULL) {
-
- global $USER;
-
- if (!isset($USER->preference)) {
- reload_user_preferences();
- }
-
- if (empty($name)) {
- return false;
- }
-
- $nostore = false;
-
- if (empty($otheruserid)){
- if (!isloggedin() or isguestuser()) {
- $nostore = true;
- }
- $userid = $USER->id;
- } else {
- if (isguestuser($otheruserid)) {
- $nostore = true;
- }
- $userid = $otheruserid;
- }
-
- $return = true;
- if ($nostore) {
- // no permanent storage for not-logged-in user and guest
-
- } else if ($preference = get_record('user_preferences', 'userid', $userid, 'name', addslashes($name))) {
- if ($preference->value === $value) {
- return true;
- }
- if (!set_field('user_preferences', 'value', addslashes((string)$value), 'id', $preference->id)) {
- $return = false;
- }
-
- } else {
- $preference = new object();
- $preference->userid = $userid;
- $preference->name = addslashes($name);
- $preference->value = addslashes((string)$value);
- if (!insert_record('user_preferences', $preference)) {
- $return = false;
- }
- }
-
- // update value in USER session if needed
- if ($userid == $USER->id) {
- $USER->preference[$name] = (string)$value;
- }
-
- return $return;
- }
-
- /**
- * Unsets a preference completely by deleting it from the database
- * Optionally, can set a preference for a different user id
- * @uses $USER
- * @param string $name The key to unset as preference for the specified user
- * @param int $otheruserid A moodle user ID
- */
- function unset_user_preference($name, $otheruserid=NULL) {
-
- global $USER;
-
- if (!isset($USER->preference)) {
- reload_user_preferences();
- }
-
- if (empty($otheruserid)){
- $userid = $USER->id;
- } else {
- $userid = $otheruserid;
- }
-
- //Delete the preference from $USER if needed
- if ($userid == $USER->id) {
- unset($USER->preference[$name]);
- }
-
- //Then from DB
- return delete_records('user_preferences', 'userid', $userid, 'name', addslashes($name));
- }
-
-
- /**
- * Sets a whole array of preferences for the current user
- * @param array $prefarray An array of key/value pairs to be set
- * @param int $otheruserid A moodle user ID
- * @return bool
- */
- function set_user_preferences($prefarray, $otheruserid=NULL) {
-
- if (!is_array($prefarray) or empty($prefarray)) {
- return false;
- }
-
- $return = true;
- foreach ($prefarray as $name => $value) {
- // The order is important; test for return is done first
- $return = (set_user_preference($name, $value, $otheruserid) && $return);
- }
- return $return;
- }
-
- /**
- * 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.
- * @param string $name Name of the key to use in finding a preference value
- * @param string $default Value to be returned if the $name key is not set in the user preferences
- * @param int $otheruserid A moodle user ID
- * @uses $USER
- * @return string
- */
- function get_user_preferences($name=NULL, $default=NULL, $otheruserid=NULL) {
- global $USER;
-
- if (!isset($USER->preference)) {
- reload_user_preferences();
- }
-
- if (empty($otheruserid)){
- $userid = $USER->id;
- } else {
- $userid = $otheruserid;
- }
-
- if ($userid == $USER->id) {
- $preference = $USER->preference;
-
- } else {
- $preference = array();
- if ($prefdata = get_records('user_preferences', 'userid', $userid)) {
- foreach ($prefdata as $pref) {
- $preference[$pref->name] = $pref->value;
- }
- }
- }
-
- if (empty($name)) {
- return $preference; // All values
-
- } else if (array_key_exists($name, $preference)) {
- return $preference[$name]; // The single value
-
- } else {
- return $default; // Default value (or NULL)
- }
- }
-
-
- /// FUNCTIONS FOR HANDLING TIME ////////////////////////////////////////////
-
- /**
- * Given date parts in user time produce a GMT timestamp.
- *
- * @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 mixed $timezone Timezone modifier, if 99 then use default user's timezone
- * @param bool $applydst Toggle Daylight Saving Time, default true, will be
- * applied only if timezone is 99 or string.
- * @return int timestamp
- * @todo Finish documenting this function
- */
- function make_timestamp($year, $month=1, $day=1, $hour=0, $minute=0, $second=0, $timezone=99, $applydst=true) {
-
- //save input timezone, required for dst offset check.
- $passedtimezone = $timezone;
-
- $timezone = get_user_timezone_offset($timezone);
-
- if (abs($timezone) > 13) { //server time
- $time = mktime((int)$hour, (int)$minute, (int)$second, (int)$month, (int)$day, (int)$year);
- } else {
- $time = gmmktime((int)$hour, (int)$minute, (int)$second, (int)$month, (int)$day, (int)$year);
- $time = usertime($time, $timezone);
-
- //Apply dst for string timezones or if 99 then try dst offset with user's default timezone
- if ($applydst && ((99 == $passedtimezone) || !is_numeric($passedtimezone))) {
- $time -= dst_offset_on($time, $passedtimezone);
- }
- }
-
- return $time;
-
- }
-
- /**
- * Given an amount of time in seconds, returns string
- * formatted nicely as weeks, days, hours etc as needed
- *
- * @uses MINSECS
- * @uses HOURSECS
- * @uses DAYSECS
- * @uses YEARSECS
- * @param int $totalsecs ?
- * @param array $str ?
- * @return string
- */
- function format_time($totalsecs, $str=NULL) {
-
- $totalsecs = abs($totalsecs);
-
- if (!$str) { // Create the str structure the slow way
- $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
- * <b>WARNING: note that the format is for strftime(), not date().</b>
- * Because of a bug in most Windows time libraries, we can't use
- * the nicer %e, so we have to use %d which has leading zeroes.
- * A lot of the fuss in the function is just getting rid of these leading
- * zeroes as efficiently as possible.
- *
- * If parameter fixday = true (default), then take off leading
- * zero from %d, else mantain it.
- *
- * @uses HOURSECS
- * @param int $date timestamp in GMT
- * @param string $format strftime format
- * @param mixed $timezone by default, uses the user's time zone. if numeric and
- * not 99 then daylight saving will not be added.
- * @param bool $fixday If true (default) then the leading
- * zero from %d is removed. If false then the leading zero is mantained.
- * @return string
- */
- function userdate($date, $format='', $timezone=99, $fixday = true) {
-
- global $CFG;
-
- if (empty($format)) {
- $format = get_string('strftimedaydatetime');
- }
-
- if (!empty($CFG->nofixday)) { // Config.php can force %d not to be fixed.
- $fixday = false;
- } else if ($fixday) {
- $formatnoday = str_replace('%d', 'DD', $format);
- $fixday = ($formatnoday != $format);
- }
-
- //add daylight saving offset for string timezones only, as we can't get dst for
- //float values. if timezone is 99 (user default timezone), then try update dst.
- if ((99 == $timezone) || !is_numeric($timezone)) {
- $date += dst_offset_on($date, $timezone);
- }
-
- $timezone = get_user_timezone_offset($timezone);
-
- if (abs($timezone) > 13) { /// Server time
- if ($fixday) {
- $datestring = strftime($formatnoday, $date);
- $daystring = str_replace(' 0', '', strftime(' %d', $date));
- $datestring = str_replace('DD', $daystring, $datestring);
- } else {
- $datestring = strftime($format, $date);
- }
- } else {
- $date += (int)($timezone * 3600);
- if ($fixday) {
- $datestring = gmstrftime($formatnoday, $date);
- $daystring = str_replace(' 0', '', gmstrftime(' %d', $date));
- $datestring = str_replace('DD', $daystring, $datestring);
- } else {
- $datestring = gmstrftime($format, $date);
- }
- }
-
- /// If we are running under Windows convert from windows encoding to UTF-8
- /// (because it's impossible to specify UTF-8 to fetch locale info in Win32)
-
- if ($CFG->ostype == 'WINDOWS') {
- if ($localewincharset = get_string('localewincharset')) {
- $textlib = textlib_get_instance();
- $datestring = $textlib->convert($datestring, $localewincharset, 'utf-8');
- }
- }
-
- return $datestring;
- }
-
- /**
- * Given a $time timestamp in GMT (seconds since epoch),
- * returns an array that represents the date in user time
- *
- * @uses HOURSECS
- * @param int $time Timestamp in GMT
- * @param mixed $timezone offset time with timezone, if float and not 99, then no
- * dst offset is applyed
- * @return array An array that represents the date in user time
- * @todo Finish documenting this function
- */
- function usergetdate($time, $timezone=99) {
-
- //save input timezone, required for dst offset check.
- $passedtimezone = $timezone;
-
- $timezone = get_user_timezone_offset($timezone);
-
- if (abs($timezone) > 13) { // Server time
- return getdate($time);
- }
-
- //add daylight saving offset for string timezones only, as we can't get dst for
- //float values. if timezone is 99 (user default timezone), then try update dst.
- if ($passedtimezone == 99 || !is_numeric($passedtimezone)) {
- $time += dst_offset_on($time, $passedtimezone);
- }
-
- $time += intval((float)$timezone * HOURSECS);
-
- $datestring = gmstrftime('%B_%A_%j_%Y_%m_%w_%d_%H_%M_%S', $time);
-
- //be careful to ensure the returned array matches that produced by getdate() above
- list(
- $getdate['month'],
- $getdate['weekday'],
- $getdate['yday'],
- $getdate['year'],
- $getdate['mon'],
- $getdate['wday'],
- $getdate['mday'],
- $getdate['hours'],
- $getdate['minutes'],
- $getdate['seconds']
- ) = explode('_', $datestring);
-
- return $getdate;
- }
-
- /**
- * Given a GMT timestamp (seconds since epoch), offsets it by
- * the timezone. eg 3pm in India is 3pm GMT - 7 * 3600 seconds
- *
- * @uses HOURSECS
- * @param int $date Timestamp in GMT
- * @param float $timezone
- * @return int
- */
- function usertime($date, $timezone=99) {
-
- $timezone = get_user_timezone_offset($timezone);
-
- if (abs($timezone) > 13) {
- return $date;
- }
- return $date - (int)($timezone * HOURSECS);
- }
-
- /**
- * Given a time, return the GMT timestamp of the most recent midnight
- * for the current user.
- *
- * @param int $date Timestamp in GMT
- * @param float $timezone ?
- * @return ?
- */
- 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
- *
- * @param float $timezone The user's timezone
- * @return string
- */
- function usertimezone($timezone=99) {
-
- $tz = get_user_timezone($timezone);
-
- if (!is_float($tz)) {
- return $tz;
- }
-
- if(abs($tz) > 13) { // Server time
- return get_string('serverlocaltime');
- }
-
- if($tz == intval($tz)) {
- // Don't show .0 for whole hours
- $tz = intval($tz);
- }
-
- if($tz == 0) {
- return 'UTC';
- }
- else if($tz > 0) {
- return 'UTC+'.$tz;
- }
- else {
- return 'UTC'.$tz;
- }
-
- }
-
- /**
- * Returns a float which represents the user's timezone difference from GMT in hours
- * Checks various settings and picks the most dominant of those which have a value
- *
- * @uses $CFG
- * @uses $USER
- * @param float $tz If this value is provided and not equal to 99, it will be returned as is and no other settings will be checked
- * @return int
- */
- function get_user_timezone_offset($tz = 99) {
-
- global $USER, $CFG;
-
- $tz = get_user_timezone($tz);
-
- if (is_float($tz)) {
- return $tz;
- } else {
- $tzrecord = get_timezone_record($tz);
- if (empty($tzrecord)) {
- return 99.0;
- }
- return (float)$tzrecord->gmtoff / HOURMINS;
- }
- }
-
- /**
- * Returns an int which represents the systems's timezone difference from GMT in seconds
- * @param mixed $tz timezone
- * @return int if found, false is timezone 99 or error
- */
- function get_timezone_offset($tz) {
- global $CFG;
-
- if ($tz == 99) {
- return false;
- }
-
- if (is_numeric($tz)) {
- return intval($tz * 60*60);
- }
-
- if (!$tzrecord = get_timezone_record($tz)) {
- return false;
- }
- return intval($tzrecord->gmtoff * 60);
- }
-
- /**
- * 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
- *
- * @uses $USER
- * @uses $CFG
- * @param mixed $tz If this value is provided and not equal to 99, it will be returned as is and no other settings will be checked
- * @return mixed
- */
- 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;
-
- while(($tz == '' || $tz == 99 || $tz == NULL) && $next = each($timezones)) {
- $tz = $next['value'];
- }
-
- return is_numeric($tz) ? (float) $tz : $tz;
- }
-
- /**
- * ?
- *
- * @uses $CFG
- * @uses $db
- * @param string $timezonename ?
- * @return object
- */
- function get_timezone_record($timezonename) {
- global $CFG, $db;
- static $cache = NULL;
-
- if ($cache === NULL) {
- $cache = array();
- }
-
- if (isset($cache[$timezonename])) {
- return $cache[$timezonename];
- }
-
- return $cache[$timezonename] = get_record_sql('SELECT * FROM '.$CFG->prefix.'timezone
- WHERE name = '.$db->qstr($timezonename).' ORDER BY year DESC', true);
- }
-
- /**
- * ?
- *
- * @uses $CFG
- * @uses $USER
- * @param ? $fromyear ?
- * @param ? $to_year ?
- * @return bool
- */
- function calculate_user_dst_table($from_year = NULL, $to_year = NULL, $strtimezone = NULL) {
- global $CFG, $SESSION;
-
- $usertz = get_user_timezone($strtimezone);
-
- if (is_float($usertz)) {
- // Trivial timezone, no DST
- return false;
- }
-
- if (!empty($SESSION->dst_offsettz) && $SESSION->dst_offsettz != $usertz) {
- // We have precalculated values, but the user's effective TZ has changed in the meantime, so reset
- unset($SESSION->dst_offsets);
- unset($SESSION->dst_range);
- }
-
- if (!empty($SESSION->dst_offsets) && empty($from_year) && empty($to_year)) {
- // Repeat calls which do not request specific year ranges stop here, we have already calculated the table
- // This will be the return path most of the time, pretty light compu…
Large files files are truncated, but you can click here to view the full file