diff --git a/lib/weblib.php b/lib/weblib.php index 43e58092ea2..8455be0f9f4 100644 --- a/lib/weblib.php +++ b/lib/weblib.php @@ -1,5 +1,4 @@ ", etc.) properly quoted. * This function is very similar to {@link p()} @@ -101,7 +103,7 @@ function s($var) { } /** - * Add quotes to HTML characters + * Add quotes to HTML characters. * * Prints $var with HTML characters (like "<", ">", etc.) properly quoted. * This function simply calls {@link s()} @@ -129,13 +131,13 @@ function addslashes_js($var) { if (is_string($var)) { $var = str_replace('\\', '\\\\', $var); $var = str_replace(array('\'', '"', "\n", "\r", "\0"), array('\\\'', '\\"', '\\n', '\\r', '\\0'), $var); - $var = str_replace('', '<\/', $var); // XHTML compliance + $var = str_replace('', '<\/', $var); // XHTML compliance. } else if (is_array($var)) { $var = array_map('addslashes_js', $var); } else if (is_object($var)) { $a = get_object_vars($var); - foreach ($a as $key=>$value) { - $a[$key] = addslashes_js($value); + foreach ($a as $key => $value) { + $a[$key] = addslashes_js($value); } $var = (object)$a; } @@ -143,14 +145,14 @@ function addslashes_js($var) { } /** - * Remove query string from url + * Remove query string from url. * - * Takes in a URL and returns it without the querystring portion + * Takes in a URL and returns it without the querystring portion. * - * @param string $url the url which may have a query string attached - * @return string The remaining URL + * @param string $url the url which may have a query string attached. + * @return string The remaining URL. */ - function strip_querystring($url) { +function strip_querystring($url) { if ($commapos = strpos($url, '?')) { return substr($url, 0, $commapos); @@ -160,11 +162,10 @@ function addslashes_js($var) { } /** - * Returns the URL of the HTTP_REFERER, less the querystring portion if required + * Returns the URL of the HTTP_REFERER, less the querystring portion if required. * - * @uses $_SERVER * @param boolean $stripquery if true, also removes the query part of the url. - * @return string The resulting referer or empty string + * @return string The resulting referer or empty string. */ function get_referer($stripquery=true) { if (isset($_SERVER['HTTP_REFERER'])) { @@ -178,7 +179,6 @@ function get_referer($stripquery=true) { } } - /** * Returns the name of the current script, WITH the querystring portion. * @@ -187,7 +187,7 @@ function get_referer($stripquery=true) { * server, and the way PHP is compiled (ie. as a CGI, module, ISAPI, etc.) * NOTE: This function returns false if the global variables needed are not set. * - * @return mixed String, or false if the global variables needed are not set + * @return mixed String or false if the global variables needed are not set. */ function me() { global $ME; @@ -206,16 +206,16 @@ function qualified_me() { global $FULLME, $PAGE, $CFG; if (isset($PAGE) and $PAGE->has_set_url()) { - // this is the only recommended way to find out current page + // This is the only recommended way to find out current page. return $PAGE->url->out(false); } else { if ($FULLME === null) { - // CLI script most probably + // CLI script most probably. return false; } if (!empty($CFG->sslproxy)) { - // return only https links when using SSL proxy + // Return only https links when using SSL proxy. return preg_replace('/^http:/', 'https:', $FULLME, 1); } else { return $FULLME; @@ -237,56 +237,66 @@ function qualified_me() { * - output the url without any get params * - and output the params as hidden fields to be output within a form * + * @copyright 2007 jamiesensei * @link http://docs.moodle.org/dev/lib/weblib.php_moodle_url See short write up here * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later - * @package moodlecore + * @package core */ class moodle_url { + /** * Scheme, ex.: http, https * @var string */ protected $scheme = ''; + /** - * hostname + * Hostname. * @var string */ protected $host = ''; + /** - * Port number, empty means default 80 or 443 in case of http - * @var unknown_type + * Port number, empty means default 80 or 443 in case of http. + * @var int */ protected $port = ''; + /** - * Username for http auth + * Username for http auth. * @var string */ protected $user = ''; + /** - * Password for http auth + * Password for http auth. * @var string */ protected $pass = ''; + /** - * Script path + * Script path. * @var string */ protected $path = ''; + /** - * Optional slash argument value + * Optional slash argument value. * @var string */ protected $slashargument = ''; + /** - * Anchor, may be also empty, null means none + * Anchor, may be also empty, null means none. * @var string */ protected $anchor = null; + /** - * Url parameters as associative array + * Url parameters as associative array. * @var array */ - protected $params = array(); // Associative array of query string params + protected $params = array(); /** * Create new instance of moodle_url. @@ -299,6 +309,7 @@ class moodle_url { * class takes care of the $CFG->admin issue. * @param array $params these params override current params or add new * @param string $anchor The anchor to use as part of the URL if there is one. + * @throws moodle_exception */ public function __construct($url, array $params = null, $anchor = null) { global $CFG; @@ -315,7 +326,7 @@ class moodle_url { $this->anchor = $url->anchor; } else { - // detect if anchor used + // Detect if anchor used. $apos = strpos($url, '#'); if ($apos !== false) { $anchor = substr($url, $apos); @@ -324,28 +335,27 @@ class moodle_url { $url = substr($url, 0, $apos); } - // normalise shortened form of our url ex.: '/course/view.php' + // Normalise shortened form of our url ex.: '/course/view.php'. if (strpos($url, '/') === 0) { - // we must not use httpswwwroot here, because it might be url of other page, - // devs have to use httpswwwroot explicitly when creating new moodle_url + // We must not use httpswwwroot here, because it might be url of other page, + // devs have to use httpswwwroot explicitly when creating new moodle_url. $url = $CFG->wwwroot.$url; } - // now fix the admin links if needed, no need to mess with httpswwwroot + // Now fix the admin links if needed, no need to mess with httpswwwroot. if ($CFG->admin !== 'admin') { if (strpos($url, "$CFG->wwwroot/admin/") === 0) { $url = str_replace("$CFG->wwwroot/admin/", "$CFG->wwwroot/$CFG->admin/", $url); } } - // parse the $url + // Parse the $url. $parts = parse_url($url); if ($parts === false) { throw new moodle_exception('invalidurl'); } if (isset($parts['query'])) { - // note: the values may not be correctly decoded, - // url parameters should be always passed as array + // Note: the values may not be correctly decoded, url parameters should be always passed as array. parse_str(str_replace('&', '&', $parts['query']), $this->params); } unset($parts['query']); @@ -353,7 +363,7 @@ class moodle_url { $this->$key = $value; } - // detect slashargument value from path - we do not support directory names ending with .php + // Detect slashargument value from path - we do not support directory names ending with .php. $pos = strpos($this->path, '.php/'); if ($pos !== false) { $this->slashargument = substr($this->path, $pos + 4); @@ -374,11 +384,12 @@ class moodle_url { * * @param array $params Defaults to null. If null then returns all params. * @return array Array of Params for url. + * @throws coding_exception */ public function params(array $params = null) { $params = (array)$params; - foreach ($params as $key=>$value) { + foreach ($params as $key => $value) { if (is_int($key)) { throw new coding_exception('Url parameters can not have numeric keys!'); } @@ -402,8 +413,7 @@ class moodle_url { * Can be called as either remove_params('param1', 'param2') * or remove_params(array('param1', 'param2')). * - * @param mixed $params either an array of param names, or a string param name, - * @param string $params,... any number of additional param names. + * @param string[]|string $params,... either an array of param names, or 1..n string params to remove as args. * @return array url parameters */ public function remove_params($params = null) { @@ -417,8 +427,10 @@ class moodle_url { } /** - * Remove all url parameters - * @param $params + * Remove all url parameters. + * + * @todo remove the unused param. + * @param array $params Unused param * @return void */ public function remove_all_params($params = null) { @@ -437,8 +449,8 @@ class moodle_url { */ public function param($paramname, $newvalue = '') { if (func_num_args() > 1) { - // set new value - $this->params(array($paramname=>$newvalue)); + // Set new value. + $this->params(array($paramname => $newvalue)); } if (isset($this->params[$paramname])) { return $this->params[$paramname]; @@ -449,13 +461,15 @@ class moodle_url { /** * Merges parameters and validates them + * * @param array $overrideparams * @return array merged parameters + * @throws coding_exception */ protected function merge_overrideparams(array $overrideparams = null) { $overrideparams = (array)$overrideparams; $params = $this->params; - foreach ($overrideparams as $key=>$value) { + foreach ($overrideparams as $key => $value) { if (is_int($key)) { throw new coding_exception('Overridden parameters can not have numeric keys!'); } @@ -472,9 +486,10 @@ class moodle_url { /** * Get the params as as a query string. + * * This method should not be used outside of this method. * - * @param boolean $escaped Use & as params separator instead of plain & + * @param bool $escaped Use & as params separator instead of plain & * @param array $overrideparams params to add to the output params, these * override existing ones with the same name. * @return string query string that can be added to a url. @@ -508,6 +523,7 @@ class moodle_url { /** * Shortcut for printing of encoded URL. + * * @return string */ public function __toString() { @@ -515,12 +531,12 @@ class moodle_url { } /** - * Output url + * Output url. * * If you use the returned URL in HTML code, you want the escaped ampersands. If you use * the returned URL in HTTP headers, you want $escaped=false. * - * @param boolean $escaped Use & as params separator instead of plain & + * @param bool $escaped Use & as params separator instead of plain & * @param array $overrideparams params to add to the output url, these override existing ones with the same name. * @return string Resulting URL */ @@ -563,26 +579,28 @@ class moodle_url { } /** - * Compares this moodle_url with another + * Compares this moodle_url with another. + * * See documentation of constants for an explanation of the comparison flags. + * * @param moodle_url $url The moodle_url object to compare * @param int $matchtype The type of comparison (URL_MATCH_BASE, URL_MATCH_PARAMS, URL_MATCH_EXACT) - * @return boolean + * @return bool */ public function compare(moodle_url $url, $matchtype = URL_MATCH_EXACT) { $baseself = $this->out_omit_querystring(); $baseother = $url->out_omit_querystring(); - // Append index.php if there is no specific file - if (substr($baseself,-1)=='/') { + // Append index.php if there is no specific file. + if (substr($baseself, -1) == '/') { $baseself .= 'index.php'; } - if (substr($baseother,-1)=='/') { + if (substr($baseother, -1) == '/') { $baseother .= 'index.php'; } - // Compare the two base URLs + // Compare the two base URLs. if ($baseself != $baseother) { return false; } @@ -619,32 +637,34 @@ class moodle_url { /** * Sets the anchor for the URI (the bit after the hash) + * * @param string $anchor null means remove previous */ public function set_anchor($anchor) { if (is_null($anchor)) { - // remove + // Remove. $this->anchor = null; } else if ($anchor === '') { - // special case, used as empty link + // Special case, used as empty link. $this->anchor = ''; } else if (preg_match('|[a-zA-Z\_\:][a-zA-Z0-9\_\-\.\:]*|', $anchor)) { - // Match the anchor against the NMTOKEN spec + // Match the anchor against the NMTOKEN spec. $this->anchor = $anchor; } else { - // bad luck, no valid anchor found + // Bad luck, no valid anchor found. $this->anchor = null; } } /** - * Sets the url slashargument value + * Sets the url slashargument value. + * * @param string $path usually file path * @param string $parameter name of page parameter if slasharguments not supported * @param bool $supported usually null, then it depends on $CFG->slasharguments, use true or false for other servers * @return void */ - public function set_slashargument($path, $parameter = 'file', $supported = NULL) { + public function set_slashargument($path, $parameter = 'file', $supported = null) { global $CFG; if (is_null($supported)) { $supported = $CFG->slasharguments; @@ -663,18 +683,17 @@ class moodle_url { } } - // == static factory methods == + // Static factory methods. /** * General moodle file url. + * * @param string $urlbase the script serving the file * @param string $path * @param bool $forcedownload * @return moodle_url */ public static function make_file_url($urlbase, $path, $forcedownload = false) { - global $CFG; - $params = array(); if ($forcedownload) { $params['forcedownload'] = 1; @@ -682,14 +701,15 @@ class moodle_url { $url = new moodle_url($urlbase, $params); $url->set_slashargument($path); - return $url; } /** * Factory method for creation of url pointing to plugin file. + * * Please note this method can be used only from the plugins to * create urls of own files, it must not be used outside of plugins! + * * @param int $contextid * @param string $component * @param string $area @@ -699,10 +719,11 @@ class moodle_url { * @param bool $forcedownload * @return moodle_url */ - public static function make_pluginfile_url($contextid, $component, $area, $itemid, $pathname, $filename, $forcedownload = false) { + public static function make_pluginfile_url($contextid, $component, $area, $itemid, $pathname, $filename, + $forcedownload = false) { global $CFG; $urlbase = "$CFG->httpswwwroot/pluginfile.php"; - if ($itemid === NULL) { + if ($itemid === null) { return self::make_file_url($urlbase, "/$contextid/$component/$area".$pathname.$filename, $forcedownload); } else { return self::make_file_url($urlbase, "/$contextid/$component/$area/$itemid".$pathname.$filename, $forcedownload); @@ -710,8 +731,8 @@ class moodle_url { } /** - * Factory method for creation of url pointing to draft - * file of current user. + * Factory method for creation of url pointing to draft file of current user. + * * @param int $draftid draft item id * @param string $pathname * @param string $filename @@ -727,8 +748,8 @@ class moodle_url { } /** - * Factory method for creating of links to legacy - * course files. + * Factory method for creating of links to legacy course files. + * * @param int $courseid * @param string $filepath * @param bool $forcedownload @@ -757,7 +778,7 @@ class moodle_url { $url = $this->out($escaped, $overrideparams); $httpswwwroot = str_replace("http://", "https://", $CFG->wwwroot); - // $url should be equal to wwwroot or httpswwwroot. If not then throw exception. + // Url should be equal to wwwroot or httpswwwroot. If not then throw exception. if (($url === $CFG->wwwroot) || (strpos($url, $CFG->wwwroot.'/') === 0)) { $localurl = substr($url, strlen($CFG->wwwroot)); return !empty($localurl) ? $localurl : ''; @@ -813,7 +834,6 @@ class moodle_url { * * Checks that submitted POST data exists and returns it as object. * - * @uses $_POST * @return mixed false or object */ function data_submitted() { @@ -838,11 +858,11 @@ function data_submitted() { */ function break_up_long_words($string, $maxsize=20, $cutchar=' ') { -/// First of all, save all the tags inside the text to skip them + // First of all, save all the tags inside the text to skip them. $tags = array(); - filter_save_tags($string,$tags); + filter_save_tags($string, $tags); -/// Process the string adding the cut when necessary + // Process the string adding the cut when necessary. $output = ''; $length = textlib::strlen($string); $wordlength = 0; @@ -861,7 +881,7 @@ function break_up_long_words($string, $maxsize=20, $cutchar=' ') { $output .= $char; } -/// Finally load the tags back again + // Finally load the tags back again. if (!empty($tags)) { $output = str_replace(array_keys($tags), $tags, $output); } @@ -874,8 +894,6 @@ function break_up_long_words($string, $maxsize=20, $cutchar=' ') { * * Echo's out the resulting XHTML & javascript * - * @global object - * @global object * @param integer $delay a delay in seconds before closing the window. Default 0. * @param boolean $reloadopener if true, we will see if this window was a pop-up, and try * to reload the parent window before this one closes. @@ -903,13 +921,11 @@ function close_window($delay = 0, $reloadopener = false) { } /** - * Returns a string containing a link to the user documentation for the current - * page. Also contains an icon by default. Shown to teachers and admin only. + * Returns a string containing a link to the user documentation for the current page. + * + * Also contains an icon by default. Shown to teachers and admin only. * - * @global object - * @global object * @param string $text The text to be displayed for the link - * @param string $iconpath The path to the icon to be displayed * @return string The link to user documentation for this current page */ function page_doc_link($text='') { @@ -925,7 +941,6 @@ function page_doc_link($text='') { * Returns the path to use when constructing a link to the docs. * * @since 2.5.1 2.6 - * @global stdClass $CFG * @param moodle_page $page * @return string */ @@ -965,36 +980,34 @@ function validate_email($address) { /** * Extracts file argument either from file parameter or PATH_INFO + * * Note: $scriptname parameter is not needed anymore * - * @global string - * @uses $_SERVER - * @uses PARAM_PATH * @return string file path (only safe characters) */ function get_file_argument() { global $SCRIPT; - $relativepath = optional_param('file', FALSE, PARAM_PATH); + $relativepath = optional_param('file', false, PARAM_PATH); if ($relativepath !== false and $relativepath !== '') { return $relativepath; } $relativepath = false; - // then try extract file from the slasharguments + // Then try extract file from the slasharguments. if (stripos($_SERVER['SERVER_SOFTWARE'], 'iis') !== false) { // NOTE: ISS tends to convert all file paths to single byte DOS encoding, // we can not use other methods because they break unicode chars, - // the only way is to use URL rewriting + // the only way is to use URL rewriting. if (isset($_SERVER['PATH_INFO']) and $_SERVER['PATH_INFO'] !== '') { - // check that PATH_INFO works == must not contain the script name + // Check that PATH_INFO works == must not contain the script name. if (strpos($_SERVER['PATH_INFO'], $SCRIPT) === false) { $relativepath = clean_param(urldecode($_SERVER['PATH_INFO']), PARAM_PATH); } } } else { - // all other apache-like servers depend on PATH_INFO + // All other apache-like servers depend on PATH_INFO. if (isset($_SERVER['PATH_INFO'])) { if (isset($_SERVER['SCRIPT_NAME']) and strpos($_SERVER['PATH_INFO'], $_SERVER['SCRIPT_NAME']) === 0) { $relativepath = substr($_SERVER['PATH_INFO'], strlen($_SERVER['SCRIPT_NAME'])); @@ -1005,32 +1018,26 @@ function get_file_argument() { } } - return $relativepath; } /** * Just returns an array of text formats suitable for a popup menu * - * @uses FORMAT_MOODLE - * @uses FORMAT_HTML - * @uses FORMAT_PLAIN - * @uses FORMAT_MARKDOWN * @return array */ function format_text_menu() { return array (FORMAT_MOODLE => get_string('formattext'), - FORMAT_HTML => get_string('formathtml'), - FORMAT_PLAIN => get_string('formatplain'), - FORMAT_MARKDOWN => get_string('formatmarkdown')); + FORMAT_HTML => get_string('formathtml'), + FORMAT_PLAIN => get_string('formatplain'), + FORMAT_MARKDOWN => get_string('formatmarkdown')); } /** - * Given text in a variety of format codings, this function returns - * the text as safe HTML. + * Given text in a variety of format codings, this function returns the text as safe HTML. * * This function should mainly be used for long strings like posts, - * answers, glossary items etc. For short strings @see format_string(). + * answers, glossary items etc. For short strings {@link format_string()}. * *
* Options:
@@ -1047,32 +1054,32 @@ function format_text_menu() {
* using htmlpurifier. Default false.
*
*
- * @todo Finish documenting this function
- *
* @staticvar array $croncache
* @param string $text The text to be formatted. This is raw text originally from user input.
* @param int $format Identifier of the text format to be used
* [FORMAT_MOODLE, FORMAT_HTML, FORMAT_PLAIN, FORMAT_MARKDOWN]
* @param object/array $options text formatting options
- * @param int $courseid_do_not_use deprecated course id, use context option instead
+ * @param int $courseiddonotuse deprecated course id, use context option instead
* @return string
*/
-function format_text($text, $format = FORMAT_MOODLE, $options = NULL, $courseid_do_not_use = NULL) {
- global $CFG, $COURSE, $DB, $PAGE;
+function format_text($text, $format = FORMAT_MOODLE, $options = null, $courseiddonotuse = null) {
+ global $CFG, $DB, $PAGE;
static $croncache = array();
if ($text === '' || is_null($text)) {
- return ''; // no need to do any filters and cleaning
+ // No need to do any filters and cleaning.
+ return '';
}
- $options = (array)$options; // detach object, we can not modify it
+ // Detach object, we can not modify it.
+ $options = (array)$options;
if (!isset($options['trusted'])) {
$options['trusted'] = false;
}
if (!isset($options['noclean'])) {
if ($options['trusted'] and trusttext_active()) {
- // no cleaning if text trusted and noclean not specified
+ // No cleaning if text trusted and noclean not specified.
$options['noclean'] = true;
} else {
$options['noclean'] = false;
@@ -1094,27 +1101,27 @@ function format_text($text, $format = FORMAT_MOODLE, $options = NULL, $courseid_
$options['overflowdiv'] = false;
}
- // Calculate best context
+ // Calculate best context.
if (empty($CFG->version) or $CFG->version < 2013051400 or during_initial_install()) {
- // do not filter anything during installation or before upgrade completes
+ // Do not filter anything during installation or before upgrade completes.
$context = null;
- } else if (isset($options['context'])) { // first by explicit passed context option
+ } else if (isset($options['context'])) { // First by explicit passed context option.
if (is_object($options['context'])) {
$context = $options['context'];
} else {
$context = context::instance_by_id($options['context']);
}
- } else if ($courseid_do_not_use) {
- // legacy courseid
- $context = context_course::instance($courseid_do_not_use);
+ } else if ($courseiddonotuse) {
+ // Legacy courseid.
+ $context = context_course::instance($courseiddonotuse);
} else {
- // fallback to $PAGE->context this may be problematic in CLI and other non-standard pages :-(
+ // Fallback to $PAGE->context this may be problematic in CLI and other non-standard pages :-(.
$context = $PAGE->context;
}
if (!$context) {
- // either install/upgrade or something has gone really wrong because context does not exist (yet?)
+ // Either install/upgrade or something has gone really wrong because context does not exist (yet?).
$options['nocache'] = true;
$options['filter'] = false;
}
@@ -1139,7 +1146,7 @@ function format_text($text, $format = FORMAT_MOODLE, $options = NULL, $courseid_
}
}
- if ($oldcacheitem = $DB->get_record('cache_text', array('md5key'=>$md5key), '*', IGNORE_MULTIPLE)) {
+ if ($oldcacheitem = $DB->get_record('cache_text', array('md5key' => $md5key), '*', IGNORE_MULTIPLE)) {
if ($oldcacheitem->timemodified >= $time) {
if (CLI_SCRIPT) {
if (count($croncache) > 150) {
@@ -1159,18 +1166,21 @@ function format_text($text, $format = FORMAT_MOODLE, $options = NULL, $courseid_
if (!$options['noclean']) {
$text = clean_text($text, FORMAT_HTML, $options);
}
- $text = $filtermanager->filter_text($text, $context, array('originalformat' => FORMAT_HTML, 'noclean' => $options['noclean']));
+ $text = $filtermanager->filter_text($text, $context, array(
+ 'originalformat' => FORMAT_HTML,
+ 'noclean' => $options['noclean']
+ ));
break;
case FORMAT_PLAIN:
- $text = s($text); // cleans dangerous JS
+ $text = s($text); // Cleans dangerous JS.
$text = rebuildnolinktag($text);
$text = str_replace(' ', ' ', $text);
$text = nl2br($text);
break;
case FORMAT_WIKI:
- // this format is deprecated
+ // This format is deprecated.
$text = 'NOTICE: Wiki-like formatting has been removed from Moodle. You should not be seeing this message as all texts should have been converted to Markdown format instead. Please post a bug report to http://moodle.org/bugs with information about where you @@ -1182,27 +1192,34 @@ function format_text($text, $format = FORMAT_MOODLE, $options = NULL, $courseid_ if (!$options['noclean']) { $text = clean_text($text, FORMAT_HTML, $options); } - $text = $filtermanager->filter_text($text, $context, array('originalformat' => FORMAT_MARKDOWN, 'noclean' => $options['noclean'])); + $text = $filtermanager->filter_text($text, $context, array( + 'originalformat' => FORMAT_MARKDOWN, + 'noclean' => $options['noclean'] + )); break; - default: // FORMAT_MOODLE or anything else + default: // FORMAT_MOODLE or anything else. $text = text_to_html($text, null, $options['para'], $options['newlines']); if (!$options['noclean']) { $text = clean_text($text, FORMAT_HTML, $options); } - $text = $filtermanager->filter_text($text, $context, array('originalformat' => $format, 'noclean' => $options['noclean'])); + $text = $filtermanager->filter_text($text, $context, array( + 'originalformat' => $format, + 'noclean' => $options['noclean'] + )); break; } if ($options['filter']) { - // at this point there should not be any draftfile links any more, + // At this point there should not be any draftfile links any more, // this happens when developers forget to post process the text. // The only potential problem is that somebody might try to format - // the text before storing into database which would be itself big bug. + // the text before storing into database which would be itself big bug.. $text = str_replace("\"$CFG->httpswwwroot/draftfile.php", "\"$CFG->httpswwwroot/brokenfile.php#", $text); if (debugging('', DEBUG_DEVELOPER)) { if (strpos($text, '@@PLUGINFILE@@/') !== false) { - debugging('Before calling format_text(), the content must be processed with file_rewrite_pluginfile_urls()', DEBUG_DEVELOPER); + debugging('Before calling format_text(), the content must be processed with file_rewrite_pluginfile_urls()', + DEBUG_DEVELOPER); } } } @@ -1211,18 +1228,18 @@ function format_text($text, $format = FORMAT_MOODLE, $options = NULL, $courseid_ // were stupid enough to rely on it. if (isset($CFG->currenttextiscacheable)) { debugging('Once upon a time, Moodle had a truly evil use of global variables ' . - 'called $CFG->currenttextiscacheable. The good news is that this no ' . - 'longer exists. The bad news is that you seem to be using a filter that '. - 'relies on it. Please seek out and destroy that filter code.', DEBUG_DEVELOPER); + 'called $CFG->currenttextiscacheable. The good news is that this no ' . + 'longer exists. The bad news is that you seem to be using a filter that '. + 'relies on it. Please seek out and destroy that filter code.', DEBUG_DEVELOPER); } if (!empty($options['overflowdiv'])) { - $text = html_writer::tag('div', $text, array('class'=>'no-overflow')); + $text = html_writer::tag('div', $text, array('class' => 'no-overflow')); } if (empty($options['nocache']) and !empty($CFG->cachetext)) { if (CLI_SCRIPT) { - // special static cron cache - no need to store it in db if its not already there + // Special static cron cache - no need to store it in db if its not already there. if (count($croncache) > 150) { reset($croncache); $key = key($croncache); @@ -1236,24 +1253,27 @@ function format_text($text, $format = FORMAT_MOODLE, $options = NULL, $courseid_ $newcacheitem->md5key = $md5key; $newcacheitem->formattedtext = $text; $newcacheitem->timemodified = time(); - if ($oldcacheitem) { // See bug 4677 for discussion + if ($oldcacheitem) { + // See bug 4677 for discussion. $newcacheitem->id = $oldcacheitem->id; try { - $DB->update_record('cache_text', $newcacheitem); // Update existing record in the cache table + // Update existing record in the cache table. + $DB->update_record('cache_text', $newcacheitem); } catch (dml_exception $e) { - // It's unlikely that the cron cache cleaner could have - // deleted this entry in the meantime, as it allows - // some extra time to cover these cases. + // It's unlikely that the cron cache cleaner could have + // deleted this entry in the meantime, as it allows + // some extra time to cover these cases. } } else { try { - $DB->insert_record('cache_text', $newcacheitem); // Insert a new record in the cache table + // Insert a new record in the cache table. + $DB->insert_record('cache_text', $newcacheitem); } catch (dml_exception $e) { - // Again, it's possible that another user has caused this - // record to be created already in the time that it took - // to traverse this function. That's OK too, as the - // call above handles duplicate entries, and eventually - // the cron cleaner will delete them. + // Again, it's possible that another user has caused this + // record to be created already in the time that it took + // to traverse this function. That's OK too, as the + // call above handles duplicate entries, and eventually + // the cron cleaner will delete them. } } } @@ -1289,55 +1309,56 @@ function reset_text_filters_cache($phpunitreset = false) { * @staticvar bool $strcache * @param string $string The string to be filtered. Should be plain text, expect * possibly for multilang tags. - * @param boolean $striplinks To strip any link in the result text. - Moodle 1.8 default changed from false to true! MDL-8713 + * @param boolean $striplinks To strip any link in the result text. Moodle 1.8 default changed from false to true! MDL-8713 * @param array $options options array/object or courseid * @return string */ -function format_string($string, $striplinks = true, $options = NULL) { - global $CFG, $COURSE, $PAGE; +function format_string($string, $striplinks = true, $options = null) { + global $CFG, $PAGE; - //We'll use a in-memory cache here to speed up repeated strings + // We'll use a in-memory cache here to speed up repeated strings. static $strcache = false; if (empty($CFG->version) or $CFG->version < 2013051400 or during_initial_install()) { - // do not filter anything during installation or before upgrade completes + // Do not filter anything during installation or before upgrade completes. return $string = strip_tags($string); } - if ($strcache === false or count($strcache) > 2000) { // this number might need some tuning to limit memory usage in cron + if ($strcache === false or count($strcache) > 2000) { + // This number might need some tuning to limit memory usage in cron. $strcache = array(); } if (is_numeric($options)) { - // legacy courseid usage - $options = array('context'=>context_course::instance($options)); + // Legacy courseid usage. + $options = array('context' => context_course::instance($options)); } else { - $options = (array)$options; // detach object, we can not modify it + // Detach object, we can not modify it. + $options = (array)$options; } if (empty($options['context'])) { - // fallback to $PAGE->context this may be problematic in CLI and other non-standard pages :-( + // Fallback to $PAGE->context this may be problematic in CLI and other non-standard pages :-(. $options['context'] = $PAGE->context; } else if (is_numeric($options['context'])) { $options['context'] = context::instance_by_id($options['context']); } if (!$options['context']) { - // we did not find any context? weird + // We did not find any context? weird. return $string = strip_tags($string); } - //Calculate md5 + // Calculate md5. $md5 = md5($string.'<+>'.$striplinks.'<+>'.$options['context']->id.'<+>'.current_language()); - //Fetch from cache if possible + // Fetch from cache if possible. if (isset($strcache[$md5])) { return $strcache[$md5]; } // First replace all ampersands not followed by html entity code - // Regular expression moved to its own method for easier unit testing + // Regular expression moved to its own method for easier unit testing. $string = replace_ampersands_not_followed_by_entity($string); if (!empty($CFG->filterall)) { @@ -1346,19 +1367,20 @@ function format_string($string, $striplinks = true, $options = NULL) { $string = $filtermanager->filter_string($string, $options['context']); } - // If the site requires it, strip ALL tags from this string + // If the site requires it, strip ALL tags from this string. if (!empty($CFG->formatstringstriptags)) { $string = str_replace(array('<', '>'), array('<', '>'), strip_tags($string)); } else { - // Otherwise strip just links if that is required (default) - if ($striplinks) { //strip links in string + // Otherwise strip just links if that is required (default). + if ($striplinks) { + // Strip links in string. $string = strip_links($string); } $string = clean_text($string); } - //Store to cache + // Store to cache. $strcache[$md5] = $string; return $string; @@ -1383,7 +1405,7 @@ function replace_ampersands_not_followed_by_entity($string) { * @return string */ function strip_links($string) { - return preg_replace('/(]+?>)(.+?)(<\/a>)/is','$2',$string); + return preg_replace('/(]+?>)(.+?)(<\/a>)/is', '$2', $string); } /** @@ -1393,18 +1415,12 @@ function strip_links($string) { * @return string */ function wikify_links($string) { - return preg_replace('~(]*>([^<]*))~i','$3 [ $2 ]', $string); + return preg_replace('~(]*>([^<]*))~i', '$3 [ $2 ]', $string); } /** - * Given text in a variety of format codings, this function returns - * the text as plain text suitable for plain email. + * Given text in a variety of format codings, this function returns the text as plain text suitable for plain email. * - * @uses FORMAT_MOODLE - * @uses FORMAT_HTML - * @uses FORMAT_PLAIN - * @uses FORMAT_WIKI - * @uses FORMAT_MARKDOWN * @param string $text The text to be formatted. This is raw text originally from user input. * @param int $format Identifier of the text format to be used * [FORMAT_MOODLE, FORMAT_HTML, FORMAT_PLAIN, FORMAT_WIKI, FORMAT_MARKDOWN] @@ -1419,7 +1435,7 @@ function format_text_email($text, $format) { break; case FORMAT_WIKI: - // there should not be any of these any more! + // There should not be any of these any more! $text = wikify_links($text); return textlib::entities_to_utf8(strip_tags($text), true); break; @@ -1440,19 +1456,17 @@ function format_text_email($text, $format) { /** * Formats activity intro text * - * @global object - * @uses CONTEXT_MODULE * @param string $module name of module * @param object $activity instance of activity * @param int $cmid course module id * @param bool $filter filter resulting html text - * @return text + * @return string */ function format_module_intro($module, $activity, $cmid, $filter=true) { global $CFG; require_once("$CFG->libdir/filelib.php"); $context = context_module::instance($cmid); - $options = array('noclean'=>true, 'para'=>false, 'filter'=>$filter, 'context'=>$context, 'overflowdiv'=>true); + $options = array('noclean' => true, 'para' => false, 'filter' => $filter, 'context' => $context, 'overflowdiv' => true); $intro = file_rewrite_pluginfile_urls($activity->intro, 'pluginfile.php', $context->id, 'mod_'.$module, 'intro', null); return trim(format_text($intro, $activity->introformat, $options, null)); } @@ -1460,12 +1474,11 @@ function format_module_intro($module, $activity, $cmid, $filter=true) { /** * Legacy function, used for cleaning of old forum and glossary text only. * - * @global object * @param string $text text that may contain legacy TRUSTTEXT marker - * @return text without legacy TRUSTTEXT marker + * @return string text without legacy TRUSTTEXT marker */ function trusttext_strip($text) { - while (true) { //removing nested TRUSTTEXT + while (true) { // Removing nested TRUSTTEXT. $orig = $text; $text = str_replace('#####TRUSTTEXT#####', '', $text); if (strcmp($orig, $text) === 0) { @@ -1475,14 +1488,12 @@ function trusttext_strip($text) { } /** - * Must be called before editing of all texts - * with trust flag. Removes all XSS nasties - * from texts stored in database if needed. + * Must be called before editing of all texts with trust flag. Removes all XSS nasties from texts stored in database if needed. * - * @param object $object data object with xxx, xxxformat and xxxtrust fields + * @param stdClass $object data object with xxx, xxxformat and xxxtrust fields * @param string $field name of text field - * @param object $context active context - * @return object updated $object + * @param context $context active context + * @return stdClass updated $object */ function trusttext_pre_edit($object, $field, $context) { $trustfield = $field.'trust'; @@ -1500,7 +1511,7 @@ function trusttext_pre_edit($object, $field, $context) { * * Please note the user must be in fact trusted everywhere on this server!! * - * @param object $context + * @param context $context * @return bool true if user trusted */ function trusttext_trusted($context) { @@ -1519,8 +1530,10 @@ function trusttext_active() { } /** - * Given raw text (eg typed in by a user), this function cleans it up - * and removes any nasty tags that could mess up Moodle pages through XSS attacks. + * Cleans raw text removing nasties. + * + * Given raw text (eg typed in by a user) this function cleans it up and removes any nasty tags that could mess up + * Moodle pages through XSS attacks. * * The result must be used as a HTML text fragment, this function can not cleanup random * parts of html tags such as url or src attributes. @@ -1537,8 +1550,8 @@ function clean_text($text, $format = FORMAT_HTML, $options = array()) { $text = (string)$text; if ($format != FORMAT_HTML and $format != FORMAT_HTML) { - // TODO: we need to standardise cleanup of text when loading it into editor first - //debugging('clean_text() is designed to work only with html'); + // TODO: we need to standardise cleanup of text when loading it into editor first. + // debugging('clean_text() is designed to work only with html');. } if ($format == FORMAT_PLAIN) { @@ -1559,6 +1572,7 @@ function clean_text($text, $format = FORMAT_HTML, $options = array()) { /** * Is it necessary to use HTMLPurifier? + * * @private * @param string $text * @return bool false means html is safe and valid, true means use HTMLPurifier @@ -1573,17 +1587,17 @@ function is_purify_html_necessary($text) { } if (strpos($text, '&') !== false or preg_match('|<[^pesb/]|', $text)) { - // we need to normalise entities or other tags except p, em, strong and br present + // We need to normalise entities or other tags except p, em, strong and br present. return true; } $altered = htmlspecialchars($text, ENT_NOQUOTES, 'UTF-8', true); if ($altered === $text) { - // no < > or other special chars means this must be safe + // No < > or other special chars means this must be safe. return false; } - // let's try to convert back some safe html tags + // Let's try to convert back some safe html tags. $altered = preg_replace('|<p>(.*?)</p>|m', '
$1
', $altered); if ($altered === $text) { return false; @@ -1668,7 +1682,19 @@ function purify_html($text, $options = array()) { $config->set('Core.ConvertDocumentToFragment', true); $config->set('Core.Encoding', 'UTF-8'); $config->set('HTML.Doctype', 'XHTML 1.0 Transitional'); - $config->set('URI.AllowedSchemes', array('http'=>true, 'https'=>true, 'ftp'=>true, 'irc'=>true, 'nntp'=>true, 'news'=>true, 'rtsp'=>true, 'teamspeak'=>true, 'gopher'=>true, 'mms'=>true, 'mailto'=>true)); + $config->set('URI.AllowedSchemes', array( + 'http' => true, + 'https' => true, + 'ftp' => true, + 'irc' => true, + 'nntp' => true, + 'news' => true, + 'rtsp' => true, + 'teamspeak' => true, + 'gopher' => true, + 'mms' => true, + 'mailto' => true + )); $config->set('Attr.AllowedFrameTargets', array('_blank')); if ($allowobjectembed) { @@ -1699,7 +1725,8 @@ function purify_html($text, $options = array()) { $filteredtext = $text; if ($multilang) { - $filteredtext = preg_replace('//', '', $filteredtext); + $filteredtextregex = '//'; + $filteredtext = preg_replace($filteredtextregex, '', $filteredtext); } $filteredtext = (string)$purifier->purify($filteredtext); if ($multilang) { @@ -1719,34 +1746,35 @@ function purify_html($text, $options = array()) { /** * Given plain text, makes it into HTML as nicely as possible. - * May contain HTML tags already + * + * May contain HTML tags already. * * Do not abuse this function. It is intended as lower level formatting feature used - * by {@see format_text()} to convert FORMAT_MOODLE to HTML. You are supposed + * by {@link format_text()} to convert FORMAT_MOODLE to HTML. You are supposed * to call format_text() in most of cases. * * @param string $text The string to convert. - * @param boolean $smiley_ignored Was used to determine if smiley characters should convert to smiley images, ignored now + * @param boolean $smileyignored Was used to determine if smiley characters should convert to smiley images, ignored now * @param boolean $para If true then the returned string will be wrapped in div tags * @param boolean $newlines If true then lines newline breaks will be converted to HTML newline breaks. * @return string */ -function text_to_html($text, $smiley_ignored=null, $para=true, $newlines=true) { -/// Remove any whitespace that may be between HTML tags +function text_to_html($text, $smileyignored = null, $para = true, $newlines = true) { + // Remove any whitespace that may be between HTML tags. $text = preg_replace("~>([[:space:]]+)<~i", "><", $text); -/// Remove any returns that precede or follow HTML tags + // Remove any returns that precede or follow HTML tags. $text = preg_replace("~([\n\r])<~i", " <", $text); $text = preg_replace("~>([\n\r])~i", "> ", $text); -/// Make returns into HTML newlines. + // Make returns into HTML newlines. if ($newlines) { $text = nl2br($text); } -/// Wrap the whole thing in a div if required + // Wrap the whole thing in a div if required. if ($para) { - //return ''.$text.'
'; //1.9 version + // In 1.9 this was changed from a p => div. return 'print_location_comment(__FILE__, __LINE__);
-*
-* @param string $file
-* @param integer $line
-* @param boolean $return Whether to return or print the comment
-* @return string|void Void unless true given as third parameter
-*/
-function print_location_comment($file, $line, $return = false)
-{
+ * Outputs a HTML comment to the browser.
+ *
+ * This is used for those hard-to-debug pages that use bits from many different files in very confusing ways (e.g. blocks).
+ *
+ * print_location_comment(__FILE__, __LINE__);
+ *
+ * @param string $file
+ * @param integer $line
+ * @param boolean $return Whether to return or print the comment
+ * @return string|void Void unless true given as third parameter
+ */
+function print_location_comment($file, $line, $return = false) {
if ($return) {
return "\n";
} else {
@@ -2879,6 +2889,8 @@ function print_location_comment($file, $line, $return = false)
/**
+ * Returns true if the user is using a right-to-left language.
+ *
* @return boolean true if the current language is right-to-left (Hebrew, Arabic etc)
*/
function right_to_left() {
@@ -2887,8 +2899,9 @@ function right_to_left() {
/**
- * Returns swapped left<=>right if in RTL environment.
- * part of RTL support
+ * Returns swapped left<=> right if in RTL environment.
+ *
+ * Part of RTL Moodles support.
*
* @param string $align align to check
* @return string
@@ -2897,14 +2910,19 @@ function fix_align_rtl($align) {
if (!right_to_left()) {
return $align;
}
- if ($align=='left') { return 'right'; }
- if ($align=='right') { return 'left'; }
+ if ($align == 'left') {
+ return 'right';
+ }
+ if ($align == 'right') {
+ return 'left';
+ }
return $align;
}
/**
* Returns true if the page is displayed in a popup window.
+ *
* Gets the information from the URL parameter inpopup.
*
* @todo Use a central function to create the popup calls all over Moodle and
@@ -2919,13 +2937,18 @@ function is_in_popup() {
}
/**
+ * Progress bar class.
+ *
+ * Manages the display of a progress bar.
+ *
* To use this class.
* - construct
* - call create (or use the 3rd param to the constructor)
* - call update or update_full() or update() repeatedly
*
+ * @copyright 2008 jamiesensei
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
- * @package moodlecore
+ * @package core
*/
class progress_bar {
/** @var string html id */
@@ -2942,34 +2965,35 @@ class progress_bar {
/**
* Constructor
*
+ * Prints JS code if $autostart true.
+ *
* @param string $html_id
* @param int $width
* @param bool $autostart Default to false
- * @return void, prints JS code if $autostart true
*/
- public function __construct($html_id = '', $width = 500, $autostart = false) {
- if (!empty($html_id)) {
- $this->html_id = $html_id;
+ public function __construct($htmlid = '', $width = 500, $autostart = false) {
+ if (!empty($htmlid)) {
+ $this->html_id = $htmlid;
} else {
$this->html_id = 'pbar_'.uniqid();
}
$this->width = $width;
- if ($autostart){
+ if ($autostart) {
$this->create();
}
}
/**
- * Create a new progress bar, this function will output html.
- *
- * @return void Echo's output
- */
+ * Create a new progress bar, this function will output html.
+ *
+ * @return void Echo's output
+ */
public function create() {
$this->time_start = microtime(true);
if (CLI_SCRIPT) {
- return; // temporary solution for cli scripts
+ return; // Temporary solution for cli scripts.
}
$htmlcode = <<