3 // This file is part of Moodle - http://moodle.org/
5 // Moodle is free software: you can redistribute it and/or modify
6 // it under the terms of the GNU General Public License as published by
7 // the Free Software Foundation, either version 3 of the License, or
8 // (at your option) any later version.
10 // Moodle is distributed in the hope that it will be useful,
11 // but WITHOUT ANY WARRANTY; without even the implied warranty of
12 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 // GNU General Public License for more details.
15 // You should have received a copy of the GNU General Public License
16 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
19 * Library of functions for web output
21 * Library of all general-purpose Moodle PHP functions and constants
22 * that produce HTML output
24 * Other main libraries:
25 * - datalib.php - functions that access the database.
26 * - moodlelib.php - general-purpose Moodle functions.
30 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
31 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
34 defined('MOODLE_INTERNAL') || die();
38 /// Define text formatting types ... eventually we can add Wiki, BBcode etc
41 * Does all sorts of transformations and filtering
43 define('FORMAT_MOODLE', '0'); // Does all sorts of transformations and filtering
46 * Plain HTML (with some tags stripped)
48 define('FORMAT_HTML', '1'); // Plain HTML (with some tags stripped)
51 * Plain text (even tags are printed in full)
53 define('FORMAT_PLAIN', '2'); // Plain text (even tags are printed in full)
57 * Deprecated: left here just to note that '3' is not used (at the moment)
58 * and to catch any latent wiki-like text (which generates an error)
60 define('FORMAT_WIKI', '3'); // Wiki-formatted text
63 * Markdown-formatted text http://daringfireball.net/projects/markdown/
65 define('FORMAT_MARKDOWN', '4'); // Markdown-formatted text http://daringfireball.net/projects/markdown/
68 * A moodle_url comparison using this flag will return true if the base URLs match, params are ignored
70 define('URL_MATCH_BASE', 0);
72 * A moodle_url comparison using this flag will return true if the base URLs match and the params of url1 are part of url2
74 define('URL_MATCH_PARAMS', 1);
76 * A moodle_url comparison using this flag will return true if the two URLs are identical, except for the order of the params
78 define('URL_MATCH_EXACT', 2);
81 * Allowed tags - string of html tags that can be tested against for safe html tags
82 * @global string $ALLOWED_TAGS
87 '<p><br><b><i><u><font><table><tbody><thead><tfoot><span><div><tr><td><th><ol><ul><dl><li><dt><dd><h1><h2><h3><h4><h5><h6><hr><img><a><strong><emphasis><em><sup><sub><address><cite><blockquote><pre><strike><param><acronym><nolink><lang><tex><algebra><math><mi><mn><mo><mtext><mspace><ms><mrow><mfrac><msqrt><mroot><mstyle><merror><mpadded><mphantom><mfenced><msub><msup><msubsup><munder><mover><munderover><mmultiscripts><mtable><mtr><mtd><maligngroup><malignmark><maction><cn><ci><apply><reln><fn><interval><inverse><sep><condition><declare><lambda><compose><ident><quotient><exp><factorial><divide><max><min><minus><plus><power><rem><times><root><gcd><and><or><xor><not><implies><forall><exists><abs><conjugate><eq><neq><gt><lt><geq><leq><ln><log><int><diff><partialdiff><lowlimit><uplimit><bvar><degree><set><list><union><intersect><in><notin><subset><prsubset><notsubset><notprsubset><setdiff><sum><product><limit><tendsto><mean><sdev><variance><median><mode><moment><vector><matrix><matrixrow><determinant><transpose><selector><annotation><semantics><annotation-xml><tt><code>';
90 * Allowed protocols - array of protocols that are safe to use in links and so on
91 * @global string $ALLOWED_PROTOCOLS
93 $ALLOWED_PROTOCOLS = array('http', 'https', 'ftp', 'news', 'mailto', 'rtsp', 'teamspeak', 'gopher', 'mms',
94 'color', 'callto', 'cursor', 'text-align', 'font-size', 'font-weight', 'font-style', 'font-family',
95 'border', 'border-bottom', 'border-left', 'border-top', 'border-right', 'margin', 'margin-bottom', 'margin-left', 'margin-top', 'margin-right',
96 'padding', 'padding-bottom', 'padding-left', 'padding-top', 'padding-right', 'vertical-align',
97 'background', 'background-color', 'text-decoration'); // CSS as well to get through kses
103 * Add quotes to HTML characters
105 * Returns $var with HTML characters (like "<", ">", etc.) properly quoted.
106 * This function is very similar to {@link p()}
108 * @todo Remove obsolete param $obsolete if not used anywhere
110 * @param string $var the string potentially containing HTML characters
111 * @param boolean $obsolete no longer used.
114 function s($var, $obsolete = false) {
116 if ($var === '0' or $var === false or $var === 0) {
120 return preg_replace("/&#(\d+|x[0-7a-fA-F]+);/i", "&#$1;", htmlspecialchars($var, ENT_QUOTES, 'UTF-8', true));
124 * Add quotes to HTML characters
126 * Prints $var with HTML characters (like "<", ">", etc.) properly quoted.
127 * This function simply calls {@link s()}
130 * @todo Remove obsolete param $obsolete if not used anywhere
132 * @param string $var the string potentially containing HTML characters
133 * @param boolean $obsolete no longer used.
136 function p($var, $obsolete = false) {
137 echo s($var, $obsolete);
141 * Does proper javascript quoting.
143 * Do not use addslashes anymore, because it does not work when magic_quotes_sybase is enabled.
145 * @param mixed $var String, Array, or Object to add slashes to
146 * @return mixed quoted result
148 function addslashes_js($var) {
149 if (is_string($var)) {
150 $var = str_replace('\\', '\\\\', $var);
151 $var = str_replace(array('\'', '"', "\n", "\r", "\0"), array('\\\'', '\\"', '\\n', '\\r', '\\0'), $var);
152 $var = str_replace('</', '<\/', $var); // XHTML compliance
153 } else if (is_array($var)) {
154 $var = array_map('addslashes_js', $var);
155 } else if (is_object($var)) {
156 $a = get_object_vars($var);
157 foreach ($a as $key=>$value) {
158 $a[$key] = addslashes_js($value);
166 * Remove query string from url
168 * Takes in a URL and returns it without the querystring portion
170 * @param string $url the url which may have a query string attached
171 * @return string The remaining URL
173 function strip_querystring($url) {
175 if ($commapos = strpos($url, '?')) {
176 return substr($url, 0, $commapos);
183 * Returns the URL of the HTTP_REFERER, less the querystring portion if required
186 * @param boolean $stripquery if true, also removes the query part of the url.
187 * @return string The resulting referer or empty string
189 function get_referer($stripquery=true) {
190 if (isset($_SERVER['HTTP_REFERER'])) {
192 return strip_querystring($_SERVER['HTTP_REFERER']);
194 return $_SERVER['HTTP_REFERER'];
203 * Returns the name of the current script, WITH the querystring portion.
205 * This function is necessary because PHP_SELF and REQUEST_URI and SCRIPT_NAME
206 * return different things depending on a lot of things like your OS, Web
207 * server, and the way PHP is compiled (ie. as a CGI, module, ISAPI, etc.)
208 * <b>NOTE:</b> This function returns false if the global variables needed are not set.
211 * @return mixed String, or false if the global variables needed are not set
219 * Returns the name of the current script, WITH the full URL.
221 * This function is necessary because PHP_SELF and REQUEST_URI and SCRIPT_NAME
222 * return different things depending on a lot of things like your OS, Web
223 * server, and the way PHP is compiled (ie. as a CGI, module, ISAPI, etc.
224 * <b>NOTE:</b> This function returns false if the global variables needed are not set.
226 * Like {@link me()} but returns a full URL
230 * @return mixed String, or false if the global variables needed are not set
232 function qualified_me() {
238 * Class for creating and manipulating urls.
240 * It can be used in moodle pages where config.php has been included without any further includes.
242 * It is useful for manipulating urls with long lists of params.
243 * One situation where it will be useful is a page which links to itself to perform various actions
244 * and / or to process form data. A moodle_url object :
245 * can be created for a page to refer to itself with all the proper get params being passed from page call to
246 * page call and methods can be used to output a url including all the params, optionally adding and overriding
247 * params and can also be used to
248 * - output the url without any get params
249 * - and output the params as hidden fields to be output within a form
251 * @link http://docs.moodle.org/en/Development:lib/weblib.php_moodle_url See short write up here
252 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
253 * @package moodlecore
257 * Scheme, ex.: http, https
260 protected $scheme = '';
265 protected $host = '';
267 * Port number, empty means default 80 or 443 in case of http
270 protected $port = '';
272 * Username for http auth
275 protected $user = '';
277 * Password for http auth
280 protected $pass = '';
285 protected $path = '';
287 * Optional slash argument value
290 protected $slashargument = '';
292 * Anchor, may be also empty, null means none
295 protected $anchor = null;
297 * Url parameters as associative array
300 protected $params = array(); // Associative array of query string params
303 * Create new instance of moodle_url.
305 * @param moodle_url|string $url - moodle_url means make a copy of another
306 * moodle_url and change parameters, string means full url or shortened
307 * form (ex.: '/course/view.php'). It is strongly encouraged to not include
308 * query string because it may result in double encoded values. Use the
309 * $params instead. For admin URLs, just use /admin/script.php, this
310 * class takes care of the $CFG->admin issue.
311 * @param array $params these params override current params or add new
313 public function __construct($url, array $params = null) {
316 if ($url instanceof moodle_url) {
317 $this->scheme = $url->scheme;
318 $this->host = $url->host;
319 $this->port = $url->port;
320 $this->user = $url->user;
321 $this->pass = $url->pass;
322 $this->path = $url->path;
323 $this->slashargument = $url->slashargument;
324 $this->params = $url->params;
325 $this->anchor = $url->anchor;
328 // detect if anchor used
329 $apos = strpos($url, '#');
330 if ($apos !== false) {
331 $anchor = substr($url, $apos);
332 $anchor = ltrim($anchor, '#');
333 $this->set_anchor($anchor);
334 $url = substr($url, 0, $apos);
337 // normalise shortened form of our url ex.: '/course/view.php'
338 if (strpos($url, '/') === 0) {
339 // we must not use httpswwwroot here, because it might be url of other page,
340 // devs have to use httpswwwroot explicitly when creating new moodle_url
341 $url = $CFG->wwwroot.$url;
344 // now fix the admin links if needed, no need to mess with httpswwwroot
345 if ($CFG->admin !== 'admin') {
346 if (strpos($url, "$CFG->wwwroot/admin/") === 0) {
347 $url = str_replace("$CFG->wwwroot/admin/", "$CFG->wwwroot/$CFG->admin/", $url);
352 $parts = parse_url($url);
353 if ($parts === false) {
354 throw new moodle_exception('invalidurl');
356 if (isset($parts['query'])) {
357 // note: the values may not be correctly decoded,
358 // url parameters should be always passed as array
359 parse_str(str_replace('&', '&', $parts['query']), $this->params);
361 unset($parts['query']);
362 foreach ($parts as $key => $value) {
363 $this->$key = $value;
366 // detect slashargument value from path - we do not support directory names ending with .php
367 $pos = strpos($this->path, '.php/');
368 if ($pos !== false) {
369 $this->slashargument = substr($this->path, $pos + 4);
370 $this->path = substr($this->path, 0, $pos + 4);
374 $this->params($params);
378 * Add an array of params to the params for this url.
380 * The added params override existing ones if they have the same name.
382 * @param array $params Defaults to null. If null then returns all params.
383 * @return array Array of Params for url.
385 public function params(array $params = null) {
386 $params = (array)$params;
388 foreach ($params as $key=>$value) {
390 throw new coding_exception('Url parameters can not have numeric keys!');
392 if (!is_string($value)) {
393 if (is_array($value)) {
394 throw new coding_exception('Url parameters values can not be arrays!');
396 if (is_object($value) and !method_exists($value, '__toString')) {
397 throw new coding_exception('Url parameters values can not be objects, unless __toString() is defined!');
400 $this->params[$key] = (string)$value;
402 return $this->params;
406 * Remove all params if no arguments passed.
407 * Remove selected params if arguments are passed.
409 * Can be called as either remove_params('param1', 'param2')
410 * or remove_params(array('param1', 'param2')).
412 * @param mixed $params either an array of param names, or a string param name,
413 * @param string $params,... any number of additional param names.
414 * @return array url parameters
416 public function remove_params($params = null) {
417 if (!is_array($params)) {
418 $params = func_get_args();
420 foreach ($params as $param) {
421 unset($this->params[$param]);
423 return $this->params;
427 * Remove all url parameters
431 public function remove_all_params($params = null) {
432 $this->params = array();
433 $this->slashargument = '';
437 * Add a param to the params for this url.
439 * The added param overrides existing one if they have the same name.
441 * @param string $paramname name
442 * @param string $newvalue Param value. If new value specified current value is overriden or parameter is added
443 * @return mixed string parameter value, null if parameter does not exist
445 public function param($paramname, $newvalue = '') {
446 if (func_num_args() > 1) {
448 $this->params(array($paramname=>$newvalue));
450 if (isset($this->params[$paramname])) {
451 return $this->params[$paramname];
458 * Merges parameters and validates them
459 * @param array $overrideparams
460 * @return array merged parameters
462 protected function merge_overrideparams(array $overrideparams = null) {
463 $overrideparams = (array)$overrideparams;
464 $params = $this->params;
465 foreach ($overrideparams as $key=>$value) {
467 throw new coding_exception('Overridden parameters can not have numeric keys!');
469 if (is_array($value)) {
470 throw new coding_exception('Overridden parameters values can not be arrays!');
472 if (is_object($value) and !method_exists($value, '__toString')) {
473 throw new coding_exception('Overridden parameters values can not be objects, unless __toString() is defined!');
475 $params[$key] = (string)$value;
481 * Get the params as as a query string.
482 * This method should not be used outside of this method.
484 * @param boolean $escaped Use & as params separator instead of plain &
485 * @param array $overrideparams params to add to the output params, these
486 * override existing ones with the same name.
487 * @return string query string that can be added to a url.
489 public function get_query_string($escaped = true, array $overrideparams = null) {
491 if ($overrideparams !== null) {
492 $params = $this->merge_overrideparams($overrideparams);
494 $params = $this->params;
496 foreach ($params as $key => $val) {
497 $arr[] = rawurlencode($key)."=".rawurlencode($val);
500 return implode('&', $arr);
502 return implode('&', $arr);
507 * Shortcut for printing of encoded URL.
510 public function __toString() {
511 return $this->out(true);
517 * If you use the returned URL in HTML code, you want the escaped ampersands. If you use
518 * the returned URL in HTTP headers, you want $escaped=false.
520 * @param boolean $escaped Use & as params separator instead of plain &
521 * @param array $overrideparams params to add to the output url, these override existing ones with the same name.
522 * @return string Resulting URL
524 public function out($escaped = true, array $overrideparams = null) {
525 if (!is_bool($escaped)) {
526 debugging('Escape parameter must be of type boolean, '.gettype($escaped).' given instead.');
529 $uri = $this->out_omit_querystring().$this->slashargument;
531 $querystring = $this->get_query_string($escaped, $overrideparams);
532 if ($querystring !== '') {
533 $uri .= '?' . $querystring;
535 if (!is_null($this->anchor)) {
536 $uri .= '#'.$this->anchor;
543 * Returns url without parameters, everything before '?'.
546 public function out_omit_querystring() {
547 $uri = $this->scheme ? $this->scheme.':'.((strtolower($this->scheme) == 'mailto') ? '':'//'): '';
548 $uri .= $this->user ? $this->user.($this->pass? ':'.$this->pass:'').'@':'';
549 $uri .= $this->host ? $this->host : '';
550 $uri .= $this->port ? ':'.$this->port : '';
551 $uri .= $this->path ? $this->path : '';
556 * Compares this moodle_url with another
557 * See documentation of constants for an explanation of the comparison flags.
558 * @param moodle_url $url The moodle_url object to compare
559 * @param int $matchtype The type of comparison (URL_MATCH_BASE, URL_MATCH_PARAMS, URL_MATCH_EXACT)
562 public function compare(moodle_url $url, $matchtype = URL_MATCH_EXACT) {
564 $baseself = $this->out_omit_querystring();
565 $baseother = $url->out_omit_querystring();
567 // Append index.php if there is no specific file
568 if (substr($baseself,-1)=='/') {
569 $baseself .= 'index.php';
571 if (substr($baseother,-1)=='/') {
572 $baseother .= 'index.php';
575 // Compare the two base URLs
576 if ($baseself != $baseother) {
580 if ($matchtype == URL_MATCH_BASE) {
584 $urlparams = $url->params();
585 foreach ($this->params() as $param => $value) {
586 if ($param == 'sesskey') {
589 if (!array_key_exists($param, $urlparams) || $urlparams[$param] != $value) {
594 if ($matchtype == URL_MATCH_PARAMS) {
598 foreach ($urlparams as $param => $value) {
599 if ($param == 'sesskey') {
602 if (!array_key_exists($param, $this->params()) || $this->param($param) != $value) {
611 * Sets the anchor for the URI (the bit after the hash)
612 * @param string $anchor null means remove previous
614 public function set_anchor($anchor) {
615 if (is_null($anchor)) {
617 $this->anchor = null;
618 } else if ($anchor === '') {
619 // special case, used as empty link
621 } else if (preg_match('|[a-zA-Z\_\:][a-zA-Z0-9\_\-\.\:]*|', $anchor)) {
622 // Match the anchor against the NMTOKEN spec
623 $this->anchor = $anchor;
625 // bad luck, no valid anchor found
626 $this->anchor = null;
631 * Sets the url slashargument value
632 * @param string $path usually file path
633 * @param string $parameter name of page parameter if slasharguments not supported
634 * @param bool $supported usually null, then it depends on $CFG->slasharguments, use true or false for other servers
637 public function set_slashargument($path, $parameter = 'file', $supported = NULL) {
639 if (is_null($supported)) {
640 $supported = $CFG->slasharguments;
644 $parts = explode('/', $path);
645 $parts = array_map('rawurlencode', $parts);
646 $path = implode('/', $parts);
647 $this->slashargument = $path;
648 unset($this->params[$parameter]);
651 $this->slashargument = '';
652 $this->params[$parameter] = $path;
656 // == static factory methods ==
659 * General moodle file url.
660 * @param string $urlbase the script serving the file
661 * @param string $path
662 * @param bool $forcedownload
665 public static function make_file_url($urlbase, $path, $forcedownload = false) {
669 if ($forcedownload) {
670 $params['forcedownload'] = 1;
673 $url = new moodle_url($urlbase, $params);
674 $url->set_slashargument($path);
680 * Factory method for creation of url pointing to plugin file.
681 * Please note this method can be used only from the plugins to
682 * create urls of own files, it must not be used outside of plugins!
683 * @param int $contextid
684 * @param string $component
685 * @param string $area
687 * @param string $pathname
688 * @param string $filename
689 * @param bool $forcedownload
692 public static function make_pluginfile_url($contextid, $component, $area, $itemid, $pathname, $filename, $forcedownload = false) {
694 $urlbase = "$CFG->httpswwwroot/pluginfile.php";
695 if ($itemid === NULL) {
696 return self::make_file_url($urlbase, "/$contextid/$component/$area".$pathname.$filename, $forcedownload);
698 return self::make_file_url($urlbase, "/$contextid/$component/$area/$itemid".$pathname.$filename, $forcedownload);
703 * Factory method for creation of url pointing to draft
704 * file of current user.
705 * @param int $draftid draft item id
706 * @param string $pathname
707 * @param string $filename
708 * @param bool $forcedownload
711 public static function make_draftfile_url($draftid, $pathname, $filename, $forcedownload = false) {
713 $urlbase = "$CFG->httpswwwroot/draftfile.php";
714 $context = get_context_instance(CONTEXT_USER, $USER->id);
716 return self::make_file_url($urlbase, "/$context->id/user/draft/$draftid".$pathname.$filename, $forcedownload);
720 * Factory method for creating of links to legacy
722 * @param int $courseid
723 * @param string $filepath
724 * @param bool $forcedownload
727 public static function make_legacyfile_url($courseid, $filepath, $forcedownload = false) {
730 $urlbase = "$CFG->wwwroot/file.php";
731 return self::make_file_url($urlbase, '/'.$courseid.'/'.$filepath, $forcedownload);
736 * Determine if there is data waiting to be processed from a form
738 * Used on most forms in Moodle to check for data
739 * Returns the data as an object, if it's found.
740 * This object can be used in foreach loops without
741 * casting because it's cast to (array) automatically
743 * Checks that submitted POST data exists and returns it as object.
746 * @return mixed false or object
748 function data_submitted() {
753 return (object)$_POST;
758 * Given some normal text this function will break up any
759 * long words to a given size by inserting the given character
761 * It's multibyte savvy and doesn't change anything inside html tags.
763 * @param string $string the string to be modified
764 * @param int $maxsize maximum length of the string to be returned
765 * @param string $cutchar the string used to represent word breaks
768 function break_up_long_words($string, $maxsize=20, $cutchar=' ') {
770 /// Loading the textlib singleton instance. We are going to need it.
771 $textlib = textlib_get_instance();
773 /// First of all, save all the tags inside the text to skip them
775 filter_save_tags($string,$tags);
777 /// Process the string adding the cut when necessary
779 $length = $textlib->strlen($string);
782 for ($i=0; $i<$length; $i++) {
783 $char = $textlib->substr($string, $i, 1);
784 if ($char == ' ' or $char == "\t" or $char == "\n" or $char == "\r" or $char == "<" or $char == ">") {
788 if ($wordlength > $maxsize) {
796 /// Finally load the tags back again
798 $output = str_replace(array_keys($tags), $tags, $output);
805 * Try and close the current window using JavaScript, either immediately, or after a delay.
807 * Echo's out the resulting XHTML & javascript
811 * @param integer $delay a delay in seconds before closing the window. Default 0.
812 * @param boolean $reloadopener if true, we will see if this window was a pop-up, and try
813 * to reload the parent window before this one closes.
815 function close_window($delay = 0, $reloadopener = false) {
816 global $PAGE, $OUTPUT;
818 if (!$PAGE->headerprinted) {
819 $PAGE->set_title(get_string('closewindow'));
820 echo $OUTPUT->header();
822 $OUTPUT->container_end_all(false);
826 $function = 'close_window_reloading_opener';
828 $function = 'close_window';
830 echo '<p class="centerpara">' . get_string('windowclosing') . '</p>';
832 $PAGE->requires->js_function_call($function, null, false, $delay);
834 echo $OUTPUT->footer();
839 * Returns a string containing a link to the user documentation for the current
840 * page. Also contains an icon by default. Shown to teachers and admin only.
844 * @param string $text The text to be displayed for the link
845 * @param string $iconpath The path to the icon to be displayed
846 * @return string The link to user documentation for this current page
848 function page_doc_link($text='') {
849 global $CFG, $PAGE, $OUTPUT;
851 if (empty($CFG->docroot) || during_initial_install()) {
854 if (!has_capability('moodle/site:doclinks', $PAGE->context)) {
858 $path = $PAGE->docspath;
862 return $OUTPUT->doc_link($path, $text);
867 * Validates an email to make sure it makes sense.
869 * @param string $address The email address to validate.
872 function validate_email($address) {
874 return (preg_match('#^[-!\#$%&\'*+\\/0-9=?A-Z^_`a-z{|}~]+'.
875 '(\.[-!\#$%&\'*+\\/0-9=?A-Z^_`a-z{|}~]+)*'.
877 '[-!\#$%&\'*+\\/0-9=?A-Z^_`a-z{|}~]+\.'.
878 '[-!\#$%&\'*+\\./0-9=?A-Z^_`a-z{|}~]+$#',
883 * Extracts file argument either from file parameter or PATH_INFO
884 * Note: $scriptname parameter is not needed anymore
889 * @return string file path (only safe characters)
891 function get_file_argument() {
894 $relativepath = optional_param('file', FALSE, PARAM_PATH);
896 if ($relativepath !== false and $relativepath !== '') {
897 return $relativepath;
899 $relativepath = false;
901 // then try extract file from the slasharguments
902 if (stripos($_SERVER['SERVER_SOFTWARE'], 'iis') !== false) {
903 // NOTE: ISS tends to convert all file paths to single byte DOS encoding,
904 // we can not use other methods because they break unicode chars,
905 // the only way is to use URL rewriting
906 if (isset($_SERVER['PATH_INFO']) and $_SERVER['PATH_INFO'] !== '') {
907 // check that PATH_INFO works == must not contain the script name
908 if (strpos($_SERVER['PATH_INFO'], $SCRIPT) === false) {
909 $relativepath = clean_param(urldecode($_SERVER['PATH_INFO']), PARAM_PATH);
913 // all other apache-like servers depend on PATH_INFO
914 if (isset($_SERVER['PATH_INFO'])) {
915 if (isset($_SERVER['SCRIPT_NAME']) and strpos($_SERVER['PATH_INFO'], $_SERVER['SCRIPT_NAME']) === 0) {
916 $relativepath = substr($_SERVER['PATH_INFO'], strlen($_SERVER['SCRIPT_NAME']));
918 $relativepath = $_SERVER['PATH_INFO'];
920 $relativepath = clean_param($relativepath, PARAM_PATH);
925 return $relativepath;
929 * Just returns an array of text formats suitable for a popup menu
931 * @uses FORMAT_MOODLE
934 * @uses FORMAT_MARKDOWN
937 function format_text_menu() {
938 return array (FORMAT_MOODLE => get_string('formattext'),
939 FORMAT_HTML => get_string('formathtml'),
940 FORMAT_PLAIN => get_string('formatplain'),
941 FORMAT_MARKDOWN => get_string('formatmarkdown'));
945 * Given text in a variety of format codings, this function returns
946 * the text as safe HTML.
948 * This function should mainly be used for long strings like posts,
949 * answers, glossary items etc. For short strings @see format_string().
953 * trusted : If true the string won't be cleaned. Default false required noclean=true.
954 * noclean : If true the string won't be cleaned. Default false required trusted=true.
955 * nocache : If true the strign will not be cached and will be formatted every call. Default false.
956 * filter : If true the string will be run through applicable filters as well. Default true.
957 * para : If true then the returned string will be wrapped in div tags. Default true.
958 * newlines : If true then lines newline breaks will be converted to HTML newline breaks. Default true.
959 * context : The context that will be used for filtering.
960 * overflowdiv : If set to true the formatted text will be encased in a div
961 * with the class no-overflow before being returned. Default false.
964 * @todo Finish documenting this function
966 * @staticvar array $croncache
967 * @param string $text The text to be formatted. This is raw text originally from user input.
968 * @param int $format Identifier of the text format to be used
969 * [FORMAT_MOODLE, FORMAT_HTML, FORMAT_PLAIN, FORMAT_MARKDOWN]
970 * @param object/array $options text formatting options
971 * @param int $courseid_do_not_use deprecated course id, use context option instead
974 function format_text($text, $format = FORMAT_MOODLE, $options = NULL, $courseid_do_not_use = NULL) {
975 global $CFG, $COURSE, $DB, $PAGE;
976 static $croncache = array();
979 return ''; // no need to do any filters and cleaning
982 $options = (array)$options; // detach object, we can not modify it
984 if (!isset($options['trusted'])) {
985 $options['trusted'] = false;
987 if (!isset($options['noclean'])) {
988 if ($options['trusted'] and trusttext_active()) {
989 // no cleaning if text trusted and noclean not specified
990 $options['noclean'] = true;
992 $options['noclean'] = false;
995 if (!isset($options['nocache'])) {
996 $options['nocache'] = false;
998 if (!isset($options['filter'])) {
999 $options['filter'] = true;
1001 if (!isset($options['para'])) {
1002 $options['para'] = true;
1004 if (!isset($options['newlines'])) {
1005 $options['newlines'] = true;
1007 if (!isset($options['overflowdiv'])) {
1008 $options['overflowdiv'] = false;
1011 // Calculate best context
1012 if (empty($CFG->version) or $CFG->version < 2010072800 or during_initial_install()) {
1013 // do not filter anything during installation or before upgrade completes
1016 } else if (isset($options['context'])) { // first by explicit passed context option
1017 if (is_object($options['context'])) {
1018 $context = $options['context'];
1020 $context = get_context_instance_by_id($context);
1022 } else if ($courseid_do_not_use) {
1024 $context = get_context_instance(CONTEXT_COURSE, $courseid_do_not_use);
1026 // fallback to $PAGE->context this may be problematic in CLI and other non-standard pages :-(
1027 $context = $PAGE->context;
1031 // either install/upgrade or something has gone really wrong because context does not exist (yet?)
1032 $options['nocache'] = true;
1033 $options['filter'] = false;
1036 if ($options['filter']) {
1037 $filtermanager = filter_manager::instance();
1039 $filtermanager = new null_filter_manager();
1042 if (!empty($CFG->cachetext) and empty($options['nocache'])) {
1043 $hashstr = $text.'-'.$filtermanager->text_filtering_hash($context).'-'.$context->id.'-'.current_language().'-'.
1044 (int)$format.(int)$options['trusted'].(int)$options['noclean'].
1045 (int)$options['para'].(int)$options['newlines'];
1047 $time = time() - $CFG->cachetext;
1048 $md5key = md5($hashstr);
1050 if (isset($croncache[$md5key])) {
1051 return $croncache[$md5key];
1055 if ($oldcacheitem = $DB->get_record('cache_text', array('md5key'=>$md5key), '*', IGNORE_MULTIPLE)) {
1056 if ($oldcacheitem->timemodified >= $time) {
1058 if (count($croncache) > 150) {
1060 $key = key($croncache);
1061 unset($croncache[$key]);
1063 $croncache[$md5key] = $oldcacheitem->formattedtext;
1065 return $oldcacheitem->formattedtext;
1072 if (!$options['noclean']) {
1073 $text = clean_text($text, FORMAT_HTML);
1075 $text = $filtermanager->filter_text($text, $context, array('originalformat' => FORMAT_HTML));
1079 $text = s($text); // cleans dangerous JS
1080 $text = rebuildnolinktag($text);
1081 $text = str_replace(' ', ' ', $text);
1082 $text = nl2br($text);
1086 // this format is deprecated
1087 $text = '<p>NOTICE: Wiki-like formatting has been removed from Moodle. You should not be seeing
1088 this message as all texts should have been converted to Markdown format instead.
1089 Please post a bug report to http://moodle.org/bugs with information about where you
1090 saw this message.</p>'.s($text);
1093 case FORMAT_MARKDOWN:
1094 $text = markdown_to_html($text);
1095 if (!$options['noclean']) {
1096 $text = clean_text($text, FORMAT_HTML);
1098 $text = $filtermanager->filter_text($text, $context, array('originalformat' => FORMAT_MARKDOWN));
1101 default: // FORMAT_MOODLE or anything else
1102 $text = text_to_html($text, null, $options['para'], $options['newlines']);
1103 if (!$options['noclean']) {
1104 $text = clean_text($text, FORMAT_HTML);
1106 $text = $filtermanager->filter_text($text, $context, array('originalformat' => $format));
1109 if ($options['filter']) {
1110 // at this point there should not be any draftfile links any more,
1111 // this happens when developers forget to post process the text.
1112 // The only potential problem is that somebody might try to format
1113 // the text before storing into database which would be itself big bug.
1114 $text = str_replace("\"$CFG->httpswwwroot/draftfile.php", "\"$CFG->httpswwwroot/brokenfile.php#", $text);
1117 // Warn people that we have removed this old mechanism, just in case they
1118 // were stupid enough to rely on it.
1119 if (isset($CFG->currenttextiscacheable)) {
1120 debugging('Once upon a time, Moodle had a truly evil use of global variables ' .
1121 'called $CFG->currenttextiscacheable. The good news is that this no ' .
1122 'longer exists. The bad news is that you seem to be using a filter that '.
1123 'relies on it. Please seek out and destroy that filter code.', DEBUG_DEVELOPER);
1126 if (!empty($options['overflowdiv'])) {
1127 $text = html_writer::tag('div', $text, array('class'=>'no-overflow'));
1130 if (empty($options['nocache']) and !empty($CFG->cachetext)) {
1132 // special static cron cache - no need to store it in db if its not already there
1133 if (count($croncache) > 150) {
1135 $key = key($croncache);
1136 unset($croncache[$key]);
1138 $croncache[$md5key] = $text;
1142 $newcacheitem = new stdClass();
1143 $newcacheitem->md5key = $md5key;
1144 $newcacheitem->formattedtext = $text;
1145 $newcacheitem->timemodified = time();
1146 if ($oldcacheitem) { // See bug 4677 for discussion
1147 $newcacheitem->id = $oldcacheitem->id;
1149 $DB->update_record('cache_text', $newcacheitem); // Update existing record in the cache table
1150 } catch (dml_exception $e) {
1151 // It's unlikely that the cron cache cleaner could have
1152 // deleted this entry in the meantime, as it allows
1153 // some extra time to cover these cases.
1157 $DB->insert_record('cache_text', $newcacheitem); // Insert a new record in the cache table
1158 } catch (dml_exception $e) {
1159 // Again, it's possible that another user has caused this
1160 // record to be created already in the time that it took
1161 // to traverse this function. That's OK too, as the
1162 // call above handles duplicate entries, and eventually
1163 // the cron cleaner will delete them.
1172 * Resets all data related to filters, called during upgrade or when filter settings change.
1178 function reset_text_filters_cache() {
1181 $DB->delete_records('cache_text');
1182 $purifdir = $CFG->dataroot.'/cache/htmlpurifier';
1183 remove_dir($purifdir, true);
1187 * Given a simple string, this function returns the string
1188 * processed by enabled string filters if $CFG->filterall is enabled
1190 * This function should be used to print short strings (non html) that
1191 * need filter processing e.g. activity titles, post subjects,
1192 * glossary concepts.
1197 * @staticvar bool $strcache
1198 * @param string $string The string to be filtered.
1199 * @param boolean $striplinks To strip any link in the result text.
1200 Moodle 1.8 default changed from false to true! MDL-8713
1201 * @param array $options options array/object or courseid
1204 function format_string($string, $striplinks = true, $options = NULL) {
1205 global $CFG, $COURSE, $PAGE;
1207 //We'll use a in-memory cache here to speed up repeated strings
1208 static $strcache = false;
1210 if (empty($CFG->version) or $CFG->version < 2010072800 or during_initial_install()) {
1211 // do not filter anything during installation or before upgrade completes
1212 return $string = strip_tags($string);
1215 if ($strcache === false or count($strcache) > 2000) { // this number might need some tuning to limit memory usage in cron
1216 $strcache = array();
1219 if (is_numeric($options)) {
1220 // legacy courseid usage
1221 $options = array('context'=>get_context_instance(CONTEXT_COURSE, $options));
1223 $options = (array)$options; // detach object, we can not modify it
1226 if (empty($options['context'])) {
1227 // fallback to $PAGE->context this may be problematic in CLI and other non-standard pages :-(
1228 $options['context'] = $PAGE->context;
1229 } else if (is_numeric($options['context'])) {
1230 $options['context'] = get_context_instance_by_id($options['context']);
1233 if (!$options['context']) {
1234 // we did not find any context? weird
1235 return $string = strip_tags($string);
1239 $md5 = md5($string.'<+>'.$striplinks.'<+>'.$options['context']->id.'<+>'.current_language());
1241 //Fetch from cache if possible
1242 if (isset($strcache[$md5])) {
1243 return $strcache[$md5];
1246 // First replace all ampersands not followed by html entity code
1247 // Regular expression moved to its own method for easier unit testing
1248 $string = replace_ampersands_not_followed_by_entity($string);
1250 if (!empty($CFG->filterall)) {
1251 $string = filter_manager::instance()->filter_string($string, $options['context']);
1254 // If the site requires it, strip ALL tags from this string
1255 if (!empty($CFG->formatstringstriptags)) {
1256 $string = strip_tags($string);
1259 // Otherwise strip just links if that is required (default)
1260 if ($striplinks) { //strip links in string
1261 $string = strip_links($string);
1263 $string = clean_text($string);
1267 $strcache[$md5] = $string;
1273 * Given a string, performs a negative lookahead looking for any ampersand character
1274 * that is not followed by a proper HTML entity. If any is found, it is replaced
1275 * by &. The string is then returned.
1277 * @param string $string
1280 function replace_ampersands_not_followed_by_entity($string) {
1281 return preg_replace("/\&(?![a-zA-Z0-9#]{1,8};)/", "&", $string);
1285 * Given a string, replaces all <a>.*</a> by .* and returns the string.
1287 * @param string $string
1290 function strip_links($string) {
1291 return preg_replace('/(<a\s[^>]+?>)(.+?)(<\/a>)/is','$2',$string);
1295 * This expression turns links into something nice in a text format. (Russell Jungwirth)
1297 * @param string $string
1300 function wikify_links($string) {
1301 return preg_replace('~(<a [^<]*href=["|\']?([^ "\']*)["|\']?[^>]*>([^<]*)</a>)~i','$3 [ $2 ]', $string);
1305 * Replaces non-standard HTML entities
1307 * @param string $string
1310 function fix_non_standard_entities($string) {
1311 $text = preg_replace('/�*([0-9]+);?/', '&#$1;', $string);
1312 $text = preg_replace('/�*([0-9a-fA-F]+);?/', '&#x$1;', $text);
1313 $text = preg_replace('[\x00-\x08\x0b-\x0c\x0e-\x1f]', '', $text);
1318 * Given text in a variety of format codings, this function returns
1319 * the text as plain text suitable for plain email.
1321 * @uses FORMAT_MOODLE
1323 * @uses FORMAT_PLAIN
1325 * @uses FORMAT_MARKDOWN
1326 * @param string $text The text to be formatted. This is raw text originally from user input.
1327 * @param int $format Identifier of the text format to be used
1328 * [FORMAT_MOODLE, FORMAT_HTML, FORMAT_PLAIN, FORMAT_WIKI, FORMAT_MARKDOWN]
1331 function format_text_email($text, $format) {
1340 // there should not be any of these any more!
1341 $text = wikify_links($text);
1342 return strtr(strip_tags($text), array_flip(get_html_translation_table(HTML_ENTITIES)));
1346 return html_to_text($text);
1350 case FORMAT_MARKDOWN:
1352 $text = wikify_links($text);
1353 return strtr(strip_tags($text), array_flip(get_html_translation_table(HTML_ENTITIES)));
1359 * Formats activity intro text
1362 * @uses CONTEXT_MODULE
1363 * @param string $module name of module
1364 * @param object $activity instance of activity
1365 * @param int $cmid course module id
1366 * @param bool $filter filter resulting html text
1369 function format_module_intro($module, $activity, $cmid, $filter=true) {
1371 require_once("$CFG->libdir/filelib.php");
1372 $context = get_context_instance(CONTEXT_MODULE, $cmid);
1373 $options = array('noclean'=>true, 'para'=>false, 'filter'=>$filter, 'context'=>$context, 'overflowdiv'=>true);
1374 $intro = file_rewrite_pluginfile_urls($activity->intro, 'pluginfile.php', $context->id, 'mod_'.$module, 'intro', null);
1375 return trim(format_text($intro, $activity->introformat, $options, null));
1379 * Legacy function, used for cleaning of old forum and glossary text only.
1382 * @param string $text text that may contain legacy TRUSTTEXT marker
1383 * @return text without legacy TRUSTTEXT marker
1385 function trusttext_strip($text) {
1386 while (true) { //removing nested TRUSTTEXT
1388 $text = str_replace('#####TRUSTTEXT#####', '', $text);
1389 if (strcmp($orig, $text) === 0) {
1396 * Must be called before editing of all texts
1397 * with trust flag. Removes all XSS nasties
1398 * from texts stored in database if needed.
1400 * @param object $object data object with xxx, xxxformat and xxxtrust fields
1401 * @param string $field name of text field
1402 * @param object $context active context
1403 * @return object updated $object
1405 function trusttext_pre_edit($object, $field, $context) {
1406 $trustfield = $field.'trust';
1407 $formatfield = $field.'format';
1409 if (!$object->$trustfield or !trusttext_trusted($context)) {
1410 $object->$field = clean_text($object->$field, $object->$formatfield);
1417 * Is current user trusted to enter no dangerous XSS in this context?
1419 * Please note the user must be in fact trusted everywhere on this server!!
1421 * @param object $context
1422 * @return bool true if user trusted
1424 function trusttext_trusted($context) {
1425 return (trusttext_active() and has_capability('moodle/site:trustcontent', $context));
1429 * Is trusttext feature active?
1432 * @param object $context
1435 function trusttext_active() {
1438 return !empty($CFG->enabletrusttext);
1442 * Given raw text (eg typed in by a user), this function cleans it up
1443 * and removes any nasty tags that could mess up Moodle pages.
1445 * NOTE: the format parameter was deprecated because we can safely clean only HTML.
1447 * @param string $text The text to be cleaned
1448 * @param int $format deprecated parameter, should always contain FORMAT_HTML or FORMAT_MOODLE
1449 * @return string The cleaned up text
1451 function clean_text($text, $format = FORMAT_HTML) {
1452 global $ALLOWED_TAGS, $CFG;
1454 if (empty($text) or is_numeric($text)) {
1455 return (string)$text;
1458 if ($format != FORMAT_HTML and $format != FORMAT_HTML) {
1459 // TODO: we need to standardise cleanup of text when loading it into editor first
1460 //debugging('clean_text() is designed to work only with html');
1463 if ($format == FORMAT_PLAIN) {
1467 if (!empty($CFG->enablehtmlpurifier)) {
1468 $text = purify_html($text);
1470 /// Fix non standard entity notations
1471 $text = fix_non_standard_entities($text);
1473 /// Remove tags that are not allowed
1474 $text = strip_tags($text, $ALLOWED_TAGS);
1476 /// Clean up embedded scripts and , using kses
1477 $text = cleanAttributes($text);
1479 /// Again remove tags that are not allowed
1480 $text = strip_tags($text, $ALLOWED_TAGS);
1484 // Remove potential script events - some extra protection for undiscovered bugs in our code
1485 $text = preg_replace("~([^a-z])language([[:space:]]*)=~i", "$1Xlanguage=", $text);
1486 $text = preg_replace("~([^a-z])on([a-z]+)([[:space:]]*)=~i", "$1Xon$2=", $text);
1492 * KSES replacement cleaning function - uses HTML Purifier.
1495 * @param string $text The (X)HTML string to purify
1497 function purify_html($text) {
1500 // this can not be done only once because we sometimes need to reset the cache
1501 $cachedir = $CFG->dataroot.'/cache/htmlpurifier';
1502 check_dir_exists($cachedir);
1504 static $purifier = false;
1505 if ($purifier === false) {
1506 require_once $CFG->libdir.'/htmlpurifier/HTMLPurifier.safe-includes.php';
1507 $config = HTMLPurifier_Config::createDefault();
1509 $config->set('HTML.DefinitionID', 'moodlehtml');
1510 $config->set('HTML.DefinitionRev', 1);
1511 $config->set('Cache.SerializerPath', $cachedir);
1512 //$config->set('Cache.SerializerPermission', $CFG->directorypermissions); // it would be nice to get this upstream
1513 $config->set('Core.NormalizeNewlines', false);
1514 $config->set('Core.ConvertDocumentToFragment', true);
1515 $config->set('Core.Encoding', 'UTF-8');
1516 $config->set('HTML.Doctype', 'XHTML 1.0 Transitional');
1517 $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));
1518 $config->set('Attr.AllowedFrameTargets', array('_blank'));
1520 if (!empty($CFG->allowobjectembed)) {
1521 $config->set('HTML.SafeObject', true);
1522 $config->set('Output.FlashCompat', true);
1523 $config->set('HTML.SafeEmbed', true);
1526 $def = $config->getHTMLDefinition(true);
1527 $def->addElement('nolink', 'Block', 'Flow', array()); // skip our filters inside
1528 $def->addElement('tex', 'Inline', 'Inline', array()); // tex syntax, equivalent to $$xx$$
1529 $def->addElement('algebra', 'Inline', 'Inline', array()); // algebra syntax, equivalent to @@xx@@
1530 $def->addElement('lang', 'Block', 'Flow', array(), array('lang'=>'CDATA')); // old anf future style multilang - only our hacked lang attribute
1531 $def->addAttribute('span', 'xxxlang', 'CDATA'); // current problematic multilang
1533 $purifier = new HTMLPurifier($config);
1536 $multilang = (strpos($text, 'class="multilang"') !== false);
1539 $text = preg_replace('/<span(\s+lang="([a-zA-Z0-9_-]+)"|\s+class="multilang"){2}\s*>/', '<span xxxlang="${2}">', $text);
1541 $text = $purifier->purify($text);
1543 $text = preg_replace('/<span xxxlang="([a-zA-Z0-9_-]+)">/', '<span lang="${1}" class="multilang">', $text);
1550 * This function takes a string and examines it for HTML tags.
1552 * If tags are detected it passes the string to a helper function {@link cleanAttributes2()}
1553 * which checks for attributes and filters them for malicious content
1555 * @param string $str The string to be examined for html tags
1558 function cleanAttributes($str){
1559 $result = preg_replace_callback(
1560 '%(<[^>]*(>|$)|>)%m', #search for html tags
1568 * This function takes a string with an html tag and strips out any unallowed
1569 * protocols e.g. javascript:
1571 * It calls ancillary functions in kses which are prefixed by kses
1575 * @param array $htmlArray An array from {@link cleanAttributes()}, containing in its 1st
1576 * element the html to be cleared
1579 function cleanAttributes2($htmlArray){
1581 global $CFG, $ALLOWED_PROTOCOLS;
1582 require_once($CFG->libdir .'/kses.php');
1584 $htmlTag = $htmlArray[1];
1585 if (substr($htmlTag, 0, 1) != '<') {
1586 return '>'; //a single character ">" detected
1588 if (!preg_match('%^<\s*(/\s*)?([a-zA-Z0-9]+)([^>]*)>?$%', $htmlTag, $matches)) {
1589 return ''; // It's seriously malformed
1591 $slash = trim($matches[1]); //trailing xhtml slash
1592 $elem = $matches[2]; //the element name
1593 $attrlist = $matches[3]; // the list of attributes as a string
1595 $attrArray = kses_hair($attrlist, $ALLOWED_PROTOCOLS);
1598 foreach ($attrArray as $arreach) {
1599 $arreach['name'] = strtolower($arreach['name']);
1600 if ($arreach['name'] == 'style') {
1601 $value = $arreach['value'];
1603 $prevvalue = $value;
1604 $value = kses_no_null($value);
1605 $value = preg_replace("/\/\*.*\*\//Us", '', $value);
1606 $value = kses_decode_entities($value);
1607 $value = preg_replace('/(&#[0-9]+)(;?)/', "\\1;", $value);
1608 $value = preg_replace('/(&#x[0-9a-fA-F]+)(;?)/', "\\1;", $value);
1609 if ($value === $prevvalue) {
1610 $arreach['value'] = $value;
1614 $arreach['value'] = preg_replace("/j\s*a\s*v\s*a\s*s\s*c\s*r\s*i\s*p\s*t/i", "Xjavascript", $arreach['value']);
1615 $arreach['value'] = preg_replace("/v\s*b\s*s\s*c\s*r\s*i\s*p\s*t/i", "Xvbscript", $arreach['value']);
1616 $arreach['value'] = preg_replace("/e\s*x\s*p\s*r\s*e\s*s\s*s\s*i\s*o\s*n/i", "Xexpression", $arreach['value']);
1617 $arreach['value'] = preg_replace("/b\s*i\s*n\s*d\s*i\s*n\s*g/i", "Xbinding", $arreach['value']);
1618 } else if ($arreach['name'] == 'href') {
1619 //Adobe Acrobat Reader XSS protection
1620 $arreach['value'] = preg_replace('/(\.(pdf|fdf|xfdf|xdp|xfd)[^#]*)#.*$/i', '$1', $arreach['value']);
1622 $attStr .= ' '.$arreach['name'].'="'.$arreach['value'].'"';
1626 if (preg_match('%/\s*$%', $attrlist)) {
1627 $xhtml_slash = ' /';
1629 return '<'. $slash . $elem . $attStr . $xhtml_slash .'>';
1633 * Given plain text, makes it into HTML as nicely as possible.
1634 * May contain HTML tags already
1636 * Do not abuse this function. It is intended as lower level formatting feature used
1637 * by {@see format_text()} to convert FORMAT_MOODLE to HTML. You are supposed
1638 * to call format_text() in most of cases.
1641 * @param string $text The string to convert.
1642 * @param boolean $smiley_ignored Was used to determine if smiley characters should convert to smiley images, ignored now
1643 * @param boolean $para If true then the returned string will be wrapped in div tags
1644 * @param boolean $newlines If true then lines newline breaks will be converted to HTML newline breaks.
1648 function text_to_html($text, $smiley_ignored=null, $para=true, $newlines=true) {
1651 /// Remove any whitespace that may be between HTML tags
1652 $text = preg_replace("~>([[:space:]]+)<~i", "><", $text);
1654 /// Remove any returns that precede or follow HTML tags
1655 $text = preg_replace("~([\n\r])<~i", " <", $text);
1656 $text = preg_replace("~>([\n\r])~i", "> ", $text);
1658 /// Make returns into HTML newlines.
1660 $text = nl2br($text);
1663 /// Wrap the whole thing in a div if required
1665 //return '<p>'.$text.'</p>'; //1.9 version
1666 return '<div class="text_to_html">'.$text.'</div>';
1673 * Given Markdown formatted text, make it into XHTML using external function
1676 * @param string $text The markdown formatted text to be converted.
1677 * @return string Converted text
1679 function markdown_to_html($text) {
1682 if ($text === '' or $text === NULL) {
1686 require_once($CFG->libdir .'/markdown.php');
1688 return Markdown($text);
1692 * Given HTML text, make it into plain text using external function
1694 * @param string $html The text to be converted.
1695 * @param integer $width Width to wrap the text at. (optional, default 75 which
1696 * is a good value for email. 0 means do not limit line length.)
1697 * @param boolean $dolinks By default, any links in the HTML are collected, and
1698 * printed as a list at the end of the HTML. If you don't want that, set this
1699 * argument to false.
1700 * @return string plain text equivalent of the HTML.
1702 function html_to_text($html, $width = 75, $dolinks = true) {
1706 require_once($CFG->libdir .'/html2text.php');
1708 $h2t = new html2text($html, false, $dolinks, $width);
1709 $result = $h2t->get_text();
1715 * This function will highlight search words in a given string
1717 * It cares about HTML and will not ruin links. It's best to use
1718 * this function after performing any conversions to HTML.
1720 * @param string $needle The search string. Syntax like "word1 +word2 -word3" is dealt with correctly.
1721 * @param string $haystack The string (HTML) within which to highlight the search terms.
1722 * @param boolean $matchcase whether to do case-sensitive. Default case-insensitive.
1723 * @param string $prefix the string to put before each search term found.
1724 * @param string $suffix the string to put after each search term found.
1725 * @return string The highlighted HTML.
1727 function highlight($needle, $haystack, $matchcase = false,
1728 $prefix = '<span class="highlight">', $suffix = '</span>') {
1730 /// Quick bail-out in trivial cases.
1731 if (empty($needle) or empty($haystack)) {
1735 /// Break up the search term into words, discard any -words and build a regexp.
1736 $words = preg_split('/ +/', trim($needle));
1737 foreach ($words as $index => $word) {
1738 if (strpos($word, '-') === 0) {
1739 unset($words[$index]);
1740 } else if (strpos($word, '+') === 0) {
1741 $words[$index] = '\b' . preg_quote(ltrim($word, '+'), '/') . '\b'; // Match only as a complete word.
1743 $words[$index] = preg_quote($word, '/');
1746 $regexp = '/(' . implode('|', $words) . ')/u'; // u is do UTF-8 matching.
1751 /// Another chance to bail-out if $search was only -words
1752 if (empty($words)) {
1756 /// Find all the HTML tags in the input, and store them in a placeholders array.
1757 $placeholders = array();
1759 preg_match_all('/<[^>]*>/', $haystack, $matches);
1760 foreach (array_unique($matches[0]) as $key => $htmltag) {
1761 $placeholders['<|' . $key . '|>'] = $htmltag;
1764 /// In $hastack, replace each HTML tag with the corresponding placeholder.
1765 $haystack = str_replace($placeholders, array_keys($placeholders), $haystack);
1767 /// In the resulting string, Do the highlighting.
1768 $haystack = preg_replace($regexp, $prefix . '$1' . $suffix, $haystack);
1770 /// Turn the placeholders back into HTML tags.
1771 $haystack = str_replace(array_keys($placeholders), $placeholders, $haystack);
1777 * This function will highlight instances of $needle in $haystack
1779 * It's faster that the above function {@link highlight()} and doesn't care about
1782 * @param string $needle The string to search for
1783 * @param string $haystack The string to search for $needle in
1784 * @return string The highlighted HTML
1786 function highlightfast($needle, $haystack) {
1788 if (empty($needle) or empty($haystack)) {
1792 $parts = explode(moodle_strtolower($needle), moodle_strtolower($haystack));
1794 if (count($parts) === 1) {
1800 foreach ($parts as $key => $part) {
1801 $parts[$key] = substr($haystack, $pos, strlen($part));
1802 $pos += strlen($part);
1804 $parts[$key] .= '<span class="highlight">'.substr($haystack, $pos, strlen($needle)).'</span>';
1805 $pos += strlen($needle);
1808 return str_replace('<span class="highlight"></span>', '', join('', $parts));
1812 * Return a string containing 'lang', xml:lang and optionally 'dir' HTML attributes.
1813 * Internationalisation, for print_header and backup/restorelib.
1815 * @param bool $dir Default false
1816 * @return string Attributes
1818 function get_html_lang($dir = false) {
1821 if (right_to_left()) {
1822 $direction = ' dir="rtl"';
1824 $direction = ' dir="ltr"';
1827 //Accessibility: added the 'lang' attribute to $direction, used in theme <html> tag.
1828 $language = str_replace('_', '-', current_language());
1829 @header('Content-Language: '.$language);
1830 return ($direction.' lang="'.$language.'" xml:lang="'.$language.'"');
1834 /// STANDARD WEB PAGE PARTS ///////////////////////////////////////////////////
1837 * Send the HTTP headers that Moodle requires.
1838 * @param $cacheable Can this page be cached on back?
1840 function send_headers($contenttype, $cacheable = true) {
1841 @header('Content-Type: ' . $contenttype);
1842 @header('Content-Script-Type: text/javascript');
1843 @header('Content-Style-Type: text/css');
1846 // Allow caching on "back" (but not on normal clicks)
1847 @header('Cache-Control: private, pre-check=0, post-check=0, max-age=0');
1848 @header('Pragma: no-cache');
1849 @header('Expires: ');
1851 // Do everything we can to always prevent clients and proxies caching
1852 @header('Cache-Control: no-store, no-cache, must-revalidate');
1853 @header('Cache-Control: post-check=0, pre-check=0', false);
1854 @header('Pragma: no-cache');
1855 @header('Expires: Mon, 20 Aug 1969 09:23:00 GMT');
1856 @header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
1858 @header('Accept-Ranges: none');
1862 * Return the right arrow with text ('next'), and optionally embedded in a link.
1865 * @param string $text HTML/plain text label (set to blank only for breadcrumb separator cases).
1866 * @param string $url An optional link to use in a surrounding HTML anchor.
1867 * @param bool $accesshide True if text should be hidden (for screen readers only).
1868 * @param string $addclass Additional class names for the link, or the arrow character.
1869 * @return string HTML string.
1871 function link_arrow_right($text, $url='', $accesshide=false, $addclass='') {
1872 global $OUTPUT; //TODO: move to output renderer
1873 $arrowclass = 'arrow ';
1875 $arrowclass .= $addclass;
1877 $arrow = '<span class="'.$arrowclass.'">'.$OUTPUT->rarrow().'</span>';
1880 $htmltext = '<span class="arrow_text">'.$text.'</span> ';
1882 $htmltext = get_accesshide($htmltext);
1886 $class = 'arrow_link';
1888 $class .= ' '.$addclass;
1890 return '<a class="'.$class.'" href="'.$url.'" title="'.preg_replace('/<.*?>/','',$text).'">'.$htmltext.$arrow.'</a>';
1892 return $htmltext.$arrow;
1896 * Return the left arrow with text ('previous'), and optionally embedded in a link.
1899 * @param string $text HTML/plain text label (set to blank only for breadcrumb separator cases).
1900 * @param string $url An optional link to use in a surrounding HTML anchor.
1901 * @param bool $accesshide True if text should be hidden (for screen readers only).
1902 * @param string $addclass Additional class names for the link, or the arrow character.
1903 * @return string HTML string.
1905 function link_arrow_left($text, $url='', $accesshide=false, $addclass='') {
1906 global $OUTPUT; // TODO: move to utput renderer
1907 $arrowclass = 'arrow ';
1909 $arrowclass .= $addclass;
1911 $arrow = '<span class="'.$arrowclass.'">'.$OUTPUT->larrow().'</span>';
1914 $htmltext = ' <span class="arrow_text">'.$text.'</span>';
1916 $htmltext = get_accesshide($htmltext);
1920 $class = 'arrow_link';
1922 $class .= ' '.$addclass;
1924 return '<a class="'.$class.'" href="'.$url.'" title="'.preg_replace('/<.*?>/','',$text).'">'.$arrow.$htmltext.'</a>';
1926 return $arrow.$htmltext;
1930 * Return a HTML element with the class "accesshide", for accessibility.
1931 * Please use cautiously - where possible, text should be visible!
1933 * @param string $text Plain text.
1934 * @param string $elem Lowercase element name, default "span".
1935 * @param string $class Additional classes for the element.
1936 * @param string $attrs Additional attributes string in the form, "name='value' name2='value2'"
1937 * @return string HTML string.
1939 function get_accesshide($text, $elem='span', $class='', $attrs='') {
1940 return "<$elem class=\"accesshide $class\" $attrs>$text</$elem>";
1944 * Return the breadcrumb trail navigation separator.
1946 * @return string HTML string.
1948 function get_separator() {
1949 //Accessibility: the 'hidden' slash is preferred for screen readers.
1950 return ' '.link_arrow_right($text='/', $url='', $accesshide=true, 'sep').' ';
1954 * Print (or return) a collapsible region, that has a caption that can
1955 * be clicked to expand or collapse the region.
1957 * If JavaScript is off, then the region will always be expanded.
1959 * @param string $contents the contents of the box.
1960 * @param string $classes class names added to the div that is output.
1961 * @param string $id id added to the div that is output. Must not be blank.
1962 * @param string $caption text displayed at the top. Clicking on this will cause the region to expand or contract.
1963 * @param string $userpref the name of the user preference that stores the user's preferred default state.
1964 * (May be blank if you do not wish the state to be persisted.
1965 * @param boolean $default Initial collapsed state to use if the user_preference it not set.
1966 * @param boolean $return if true, return the HTML as a string, rather than printing it.
1967 * @return string|void If $return is false, returns nothing, otherwise returns a string of HTML.
1969 function print_collapsible_region($contents, $classes, $id, $caption, $userpref = '', $default = false, $return = false) {
1970 $output = print_collapsible_region_start($classes, $id, $caption, $userpref, true, true);
1971 $output .= $contents;
1972 $output .= print_collapsible_region_end(true);
1982 * Print (or return) the start of a collapsible region, that has a caption that can
1983 * be clicked to expand or collapse the region. If JavaScript is off, then the region
1984 * will always be expanded.
1987 * @param string $classes class names added to the div that is output.
1988 * @param string $id id added to the div that is output. Must not be blank.
1989 * @param string $caption text displayed at the top. Clicking on this will cause the region to expand or contract.
1990 * @param boolean $userpref the name of the user preference that stores the user's preferred default state.
1991 * (May be blank if you do not wish the state to be persisted.
1992 * @param boolean $default Initial collapsed state to use if the user_preference it not set.
1993 * @param boolean $return if true, return the HTML as a string, rather than printing it.
1994 * @return string|void if $return is false, returns nothing, otherwise returns a string of HTML.
1996 function print_collapsible_region_start($classes, $id, $caption, $userpref = false, $default = false, $return = false) {
1997 global $CFG, $PAGE, $OUTPUT;
1999 // Work out the initial state.
2000 if (is_string($userpref)) {
2001 user_preference_allow_ajax_update($userpref, PARAM_BOOL);
2002 $collapsed = get_user_preferences($userpref, $default);
2004 $collapsed = $default;
2009 $classes .= ' collapsed';
2013 $output .= '<div id="' . $id . '" class="collapsibleregion ' . $classes . '">';
2014 $output .= '<div id="' . $id . '_sizer">';
2015 $output .= '<div id="' . $id . '_caption" class="collapsibleregioncaption">';
2016 $output .= $caption . ' ';
2017 $output .= '</div><div id="' . $id . '_inner" class="collapsibleregioninner">';
2018 $PAGE->requires->js_init_call('M.util.init_collapsible_region', array($id, $userpref, get_string('clicktohideshow')));
2028 * Close a region started with print_collapsible_region_start.
2030 * @param boolean $return if true, return the HTML as a string, rather than printing it.
2031 * @return string|void if $return is false, returns nothing, otherwise returns a string of HTML.
2033 function print_collapsible_region_end($return = false) {
2034 $output = '</div></div></div>';
2044 * Print a specified group's avatar.
2047 * @uses CONTEXT_COURSE
2048 * @param array|stdClass $group A single {@link group} object OR array of groups.
2049 * @param int $courseid The course ID.
2050 * @param boolean $large Default small picture, or large.
2051 * @param boolean $return If false print picture, otherwise return the output as string
2052 * @param boolean $link Enclose image in a link to view specified course?
2053 * @return string|void Depending on the setting of $return
2055 function print_group_picture($group, $courseid, $large=false, $return=false, $link=true) {
2058 if (is_array($group)) {
2060 foreach($group as $g) {
2061 $output .= print_group_picture($g, $courseid, $large, true, $link);
2071 $context = get_context_instance(CONTEXT_COURSE, $courseid);
2073 // If there is no picture, do nothing
2074 if (!$group->picture) {
2078 // If picture is hidden, only show to those with course:managegroups
2079 if ($group->hidepicture and !has_capability('moodle/course:managegroups', $context)) {
2083 if ($link or has_capability('moodle/site:accessallgroups', $context)) {
2084 $output = '<a href="'. $CFG->wwwroot .'/user/index.php?id='. $courseid .'&group='. $group->id .'">';
2094 $grouppictureurl = moodle_url::make_pluginfile_url($context->id, 'group', 'icon', $group->id, '/', $file);
2095 $output .= '<img class="grouppicture" src="'.$grouppictureurl.'"'.
2096 ' alt="'.s(get_string('group').' '.$group->name).'" title="'.s($group->name).'"/>';
2098 if ($link or has_capability('moodle/site:accessallgroups', $context)) {
2111 * Display a recent activity note
2113 * @uses CONTEXT_SYSTEM
2114 * @staticvar string $strftimerecent
2115 * @param object A time object
2116 * @param object A user object
2117 * @param string $text Text for display for the note
2118 * @param string $link The link to wrap around the text
2119 * @param bool $return If set to true the HTML is returned rather than echo'd
2120 * @param string $viewfullnames
2122 function print_recent_activity_note($time, $user, $text, $link, $return=false, $viewfullnames=null) {
2123 static $strftimerecent = null;
2126 if (is_null($viewfullnames)) {
2127 $context = get_context_instance(CONTEXT_SYSTEM);
2128 $viewfullnames = has_capability('moodle/site:viewfullnames', $context);
2131 if (is_null($strftimerecent)) {
2132 $strftimerecent = get_string('strftimerecent');
2135 $output .= '<div class="head">';
2136 $output .= '<div class="date">'.userdate($time, $strftimerecent).'</div>';
2137 $output .= '<div class="name">'.fullname($user, $viewfullnames).'</div>';
2138 $output .= '</div>';
2139 $output .= '<div class="info"><a href="'.$link.'">'.format_string($text,true).'</a></div>';
2149 * Returns a popup menu with course activity modules
2152 * This function returns a small popup menu with all the
2153 * course activity modules in it, as a navigation menu
2154 * outputs a simple list structure in XHTML
2155 * The data is taken from the serialised array stored in
2158 * @todo Finish documenting this function
2161 * @uses CONTEXT_COURSE
2162 * @param course $course A {@link $COURSE} object.
2163 * @param string $sections
2164 * @param string $modinfo
2165 * @param string $strsection
2166 * @param string $strjumpto
2168 * @param string $cmid
2169 * @return string The HTML block
2171 function navmenulist($course, $sections, $modinfo, $strsection, $strjumpto, $width=50, $cmid=0) {
2173 global $CFG, $OUTPUT;
2178 $doneheading = false;
2180 $coursecontext = get_context_instance(CONTEXT_COURSE, $course->id);
2182 $menu[] = '<ul class="navmenulist"><li class="jumpto section"><span>'.$strjumpto.'</span><ul>';
2183 foreach ($modinfo->cms as $mod) {
2184 if ($mod->modname == 'label') {
2188 if ($mod->sectionnum > $course->numsections) { /// Don't show excess hidden sections
2192 if (!$mod->uservisible) { // do not icnlude empty sections at all
2196 if ($mod->sectionnum >= 0 and $section != $mod->sectionnum) {
2197 $thissection = $sections[$mod->sectionnum];
2199 if ($thissection->visible or !$course->hiddensections or
2200 has_capability('moodle/course:viewhiddensections', $coursecontext)) {
2201 $thissection->summary = strip_tags(format_string($thissection->summary,true));
2202 if (!$doneheading) {
2203 $menu[] = '</ul></li>';
2205 if ($course->format == 'weeks' or empty($thissection->summary)) {
2206 $item = $strsection ." ". $mod->sectionnum;
2208 if (strlen($thissection->summary) < ($width-3)) {
2209 $item = $thissection->summary;
2211 $item = substr($thissection->summary, 0, $width).'...';
2214 $menu[] = '<li class="section"><span>'.$item.'</span>';
2216 $doneheading = true;
2218 $section = $mod->sectionnum;
2220 // no activities from this hidden section shown
2225 $url = $mod->modname .'/view.php?id='. $mod->id;
2226 $mod->name = strip_tags(format_string($mod->name ,true));
2227 if (strlen($mod->name) > ($width+5)) {
2228 $mod->name = substr($mod->name, 0, $width).'...';
2230 if (!$mod->visible) {
2231 $mod->name = '('.$mod->name.')';
2233 $class = 'activity '.$mod->modname;
2234 $class .= ($cmid == $mod->id) ? ' selected' : '';
2235 $menu[] = '<li class="'.$class.'">'.
2236 '<img src="'.$OUTPUT->pix_url('icon', $mod->modname) . '" alt="" />'.
2237 '<a href="'.$CFG->wwwroot.'/mod/'.$url.'">'.$mod->name.'</a></li>';
2241 $menu[] = '</ul></li>';
2243 $menu[] = '</ul></li></ul>';
2245 return implode("\n", $menu);
2249 * Prints a grade menu (as part of an existing form) with help
2250 * Showing all possible numerical grades and scales
2252 * @todo Finish documenting this function
2253 * @todo Deprecate: this is only used in a few contrib modules
2256 * @param int $courseid The course ID
2257 * @param string $name
2258 * @param string $current
2259 * @param boolean $includenograde Include those with no grades
2260 * @param boolean $return If set to true returns rather than echo's
2261 * @return string|bool Depending on value of $return
2263 function print_grade_menu($courseid, $name, $current, $includenograde=true, $return=false) {
2265 global $CFG, $OUTPUT;
2268 $strscale = get_string('scale');
2269 $strscales = get_string('scales');
2271 $scales = get_scales_menu($courseid);
2272 foreach ($scales as $i => $scalename) {
2273 $grades[-$i] = $strscale .': '. $scalename;
2275 if ($includenograde) {
2276 $grades[0] = get_string('nograde');
2278 for ($i=100; $i>=1; $i--) {
2281 $output .= html_writer::select($grades, $name, $current, false);
2283 $linkobject = '<span class="helplink"><img class="iconhelp" alt="'.$strscales.'" src="'.$OUTPUT->pix_url('help') . '" /></span>';
2284 $link = new moodle_url('/course/scales.php', array('id'=>$courseid, 'list'=>1));
2285 $action = new popup_action('click', $link, 'ratingscales', array('height' => 400, 'width' => 500));
2286 $output .= $OUTPUT->action_link($link, $linkobject, $action, array('title'=>$strscales));
2296 * Print an error to STDOUT and exit with a non-zero code. For commandline scripts.
2297 * Default errorcode is 1.
2299 * Very useful for perl-like error-handling:
2301 * do_somethting() or mdie("Something went wrong");
2303 * @param string $msg Error message
2304 * @param integer $errorcode Error code to emit
2306 function mdie($msg='', $errorcode=1) {
2307 trigger_error($msg);
2312 * Print a message and exit.
2314 * @param string $message The message to print in the notice
2315 * @param string $link The link to use for the continue button
2316 * @param object $course A course object
2317 * @return void This function simply exits
2319 function notice ($message, $link='', $course=NULL) {
2320 global $CFG, $SITE, $COURSE, $PAGE, $OUTPUT;
2322 $message = clean_text($message); // In case nasties are in here
2325 echo("!!$message!!\n");
2326 exit(1); // no success
2329 if (!$PAGE->headerprinted) {
2330 //header not yet printed
2331 $PAGE->set_title(get_string('notice'));
2332 echo $OUTPUT->header();
2334 echo $OUTPUT->container_end_all(false);
2337 echo $OUTPUT->box($message, 'generalbox', 'notice');
2338 echo $OUTPUT->continue_button($link);
2340 echo $OUTPUT->footer();
2341 exit(1); // general error code
2345 * Redirects the user to another page, after printing a notice
2347 * This function calls the OUTPUT redirect method, echo's the output
2348 * and then dies to ensure nothing else happens.
2350 * <strong>Good practice:</strong> You should call this method before starting page
2351 * output by using any of the OUTPUT methods.
2353 * @param moodle_url|string $url A moodle_url to redirect to. Strings are not to be trusted!
2354 * @param string $message The message to display to the user
2355 * @param int $delay The delay before redirecting
2356 * @return void - does not return!
2358 function redirect($url, $message='', $delay=-1) {
2359 global $OUTPUT, $PAGE, $SESSION, $CFG;
2361 if (CLI_SCRIPT or AJAX_SCRIPT) {
2362 // this is wrong - developers should not use redirect in these scripts,
2363 // but it should not be very likely
2364 throw new moodle_exception('redirecterrordetected', 'error');
2367 // prevent debug errors - make sure context is properly initialised
2369 $PAGE->set_context(null);
2372 if ($url instanceof moodle_url) {
2373 $url = $url->out(false);
2376 if (!empty($CFG->usesid) && !isset($_COOKIE[session_name()])) {
2377 $url = $SESSION->sid_process_url($url);
2380 $debugdisableredirect = false;
2382 if (defined('DEBUGGING_PRINTED')) {
2383 // some debugging already printed, no need to look more
2384 $debugdisableredirect = true;
2388 if (empty($CFG->debugdisplay) or empty($CFG->debug)) {
2389 // no errors should be displayed
2393 if (!function_exists('error_get_last') or !$lasterror = error_get_last()) {
2397 if (!($lasterror['type'] & $CFG->debug)) {
2398 //last error not interesting
2402 // watch out here, @hidden() errors are returned from error_get_last() too
2403 if (headers_sent()) {
2404 //we already started printing something - that means errors likely printed
2405 $debugdisableredirect = true;
2409 if (ob_get_level() and ob_get_contents()) {
2410 // there is something waiting to be printed, hopefully it is the errors,
2411 // but it might be some error hidden by @ too - such as the timezone mess from setup.php
2412 $debugdisableredirect = true;
2417 if (!empty($message)) {
2418 if ($delay === -1 || !is_numeric($delay)) {
2421 $message = clean_text($message);
2423 $message = get_string('pageshouldredirect');
2425 // We are going to try to use a HTTP redirect, so we need a full URL.
2426 if (!preg_match('|^[a-z]+:|', $url)) {
2427 // Get host name http://www.wherever.com
2428 $hostpart = preg_replace('|^(.*?[^:/])/.*$|', '$1', $CFG->wwwroot);
2429 if (preg_match('|^/|', $url)) {
2430 // URLs beginning with / are relative to web server root so we just add them in
2431 $url = $hostpart.$url;
2433 // URLs not beginning with / are relative to path of current script, so add that on.
2434 $url = $hostpart.preg_replace('|\?.*$|','',me()).'/../'.$url;
2438 $newurl = preg_replace('|/(?!\.\.)[^/]*/\.\./|', '/', $url);
2439 if ($newurl == $url) {
2447 if (defined('MDL_PERF') || (!empty($CFG->perfdebug) and $CFG->perfdebug > 7)) {
2448 if (defined('MDL_PERFTOLOG') && !function_exists('register_shutdown_function')) {
2449 $perf = get_performance_info();
2450 error_log("PERF: " . $perf['txt']);
2454 $encodedurl = preg_replace("/\&(?![a-zA-Z0-9#]{1,8};)/", "&", $url);
2455 $encodedurl = preg_replace('/^.*href="([^"]*)".*$/', "\\1", clean_text('<a href="'.$encodedurl.'" />'));
2457 if ($delay == 0 && !$debugdisableredirect && !headers_sent()) {
2458 //302 might not work for POST requests, 303 is ignored by obsolete clients.
2459 @header($_SERVER['SERVER_PROTOCOL'] . ' 303 See Other');
2460 @header('Location: '.$url);
2461 echo bootstrap_renderer::plain_redirect_message($encodedurl);
2465 // Include a redirect message, even with a HTTP redirect, because that is recommended practice.
2466 $PAGE->set_pagelayout('redirect'); // No header and footer needed
2467 $CFG->docroot = false; // to prevent the link to moodle docs from being displayed on redirect page.
2468 echo $OUTPUT->redirect_message($encodedurl, $message, $delay, $debugdisableredirect);
2473 * Given an email address, this function will return an obfuscated version of it
2475 * @param string $email The email address to obfuscate
2476 * @return string The obfuscated email address
2478 function obfuscate_email($email) {
2481 $length = strlen($email);
2483 while ($i < $length) {
2484 if (rand(0,2) && $email{$i}!='@') { //MDL-20619 some browsers have problems unobfuscating @
2485 $obfuscated.='%'.dechex(ord($email{$i}));
2487 $obfuscated.=$email{$i};
2495 * This function takes some text and replaces about half of the characters
2496 * with HTML entity equivalents. Return string is obviously longer.
2498 * @param string $plaintext The text to be obfuscated
2499 * @return string The obfuscated text
2501 function obfuscate_text($plaintext) {
2504 $length = strlen($plaintext);
2506 $prev_obfuscated = false;
2507 while ($i < $length) {
2508 $c = ord($plaintext{$i});
2509 $numerical = ($c >= ord('0')) && ($c <= ord('9'));
2510 if ($prev_obfuscated and $numerical ) {
2511 $obfuscated.='&#'.ord($plaintext{$i}).';';
2512 } else if (rand(0,2)) {
2513 $obfuscated.='&#'.ord($plaintext{$i}).';';
2514 $prev_obfuscated = true;
2516 $obfuscated.=$plaintext{$i};
2517 $prev_obfuscated = false;
2525 * This function uses the {@link obfuscate_email()} and {@link obfuscate_text()}
2526 * to generate a fully obfuscated email link, ready to use.
2528 * @param string $email The email address to display
2529 * @param string $label The text to displayed as hyperlink to $email
2530 * @param boolean $dimmed If true then use css class 'dimmed' for hyperlink
2531 * @return string The obfuscated mailto link
2533 function obfuscate_mailto($email, $label='', $dimmed=false) {
2535 if (empty($label)) {
2539 $title = get_string('emaildisable');
2540 $dimmed = ' class="dimmed"';
2545 return sprintf("<a href=\"%s:%s\" $dimmed title=\"$title\">%s</a>",
2546 obfuscate_text('mailto'), obfuscate_email($email),
2547 obfuscate_text($label));
2551 * This function is used to rebuild the <nolink> tag because some formats (PLAIN and WIKI)
2552 * will transform it to html entities
2554 * @param string $text Text to search for nolink tag in
2557 function rebuildnolinktag($text) {
2559 $text = preg_replace('/<(\/*nolink)>/i','<$1>',$text);
2565 * Prints a maintenance message from $CFG->maintenance_message or default if empty
2568 function print_maintenance_message() {
2569 global $CFG, $SITE, $PAGE, $OUTPUT;
2571 $PAGE->set_pagetype('maintenance-message');
2572 $PAGE->set_pagelayout('maintenance');
2573 $PAGE->set_title(strip_tags($SITE->fullname));
2574 $PAGE->set_heading($SITE->fullname);
2575 echo $OUTPUT->header();
2576 echo $OUTPUT->heading(get_string('sitemaintenance', 'admin'));
2577 if (isset($CFG->maintenance_message) and !html_is_blank($CFG->maintenance_message)) {
2578 echo $OUTPUT->box_start('maintenance_message generalbox boxwidthwide boxaligncenter');
2579 echo $CFG->maintenance_message;
2580 echo $OUTPUT->box_end();
2582 echo $OUTPUT->footer();
2587 * Adjust the list of allowed tags based on $CFG->allowobjectembed and user roles (admin)
2593 function adjust_allowed_tags() {
2595 global $CFG, $ALLOWED_TAGS;
2597 if (!empty($CFG->allowobjectembed)) {
2598 $ALLOWED_TAGS .= '<embed><object>';
2603 * A class for tabs, Some code to print tabs
2605 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2606 * @package moodlecore
2618 var $linkedwhenselected;
2621 * A constructor just because I like constructors
2624 * @param string $link
2625 * @param string $text
2626 * @param string $title
2627 * @param bool $linkedwhenselected
2629 function tabobject ($id, $link='', $text='', $title='', $linkedwhenselected=false) {
2631 $this->link = $link;
2632 $this->text = $text;
2633 $this->title = $title ? $title : $text;
2634 $this->linkedwhenselected = $linkedwhenselected;
2641 * Returns a string containing a nested list, suitable for formatting into tabs with CSS.
2644 * @param array $tabrows An array of rows where each row is an array of tab objects
2645 * @param string $selected The id of the selected tab (whatever row it's on)
2646 * @param array $inactive An array of ids of inactive tabs that are not selectable.
2647 * @param array $activated An array of ids of other tabs that are currently activated
2648 * @param bool $return If true output is returned rather then echo'd
2650 function print_tabs($tabrows, $selected=NULL, $inactive=NULL, $activated=NULL, $return=false) {
2653 /// $inactive must be an array
2654 if (!is_array($inactive)) {
2655 $inactive = array();
2658 /// $activated must be an array
2659 if (!is_array($activated)) {
2660 $activated = array();
2663 /// Convert the tab rows into a tree that's easier to process
2664 if (!$tree = convert_tabrows_to_tree($tabrows, $selected, $inactive, $activated)) {
2668 /// Print out the current tree of tabs (this function is recursive)
2670 $output = convert_tree_to_html($tree);
2672 $output = "\n\n".'<div class="tabtree">'.$output.'</div><div class="clearer"> </div>'."\n\n";
2683 * Converts a nested array tree into HTML ul:li [recursive]
2685 * @param array $tree A tree array to convert
2686 * @param int $row Used in identifying the iteration level and in ul classes
2687 * @return string HTML structure
2689 function convert_tree_to_html($tree, $row=0) {
2691 $str = "\n".'<ul class="tabrow'.$row.'">'."\n";
2694 $count = count($tree);
2696 foreach ($tree as $tab) {
2697 $count--; // countdown to zero
2701 if ($first && ($count == 0)) { // Just one in the row
2702 $liclass = 'first last';
2704 } else if ($first) {
2707 } else if ($count == 0) {
2711 if ((empty($tab->subtree)) && (!empty($tab->selected))) {
2712 $liclass .= (empty($liclass)) ? 'onerow' : ' onerow';
2715 if ($tab->inactive || $tab->active || $tab->selected) {
2716 if ($tab->selected) {
2717 $liclass .= (empty($liclass)) ? 'here selected' : ' here selected';
2718 } else if ($tab->active) {
2719 $liclass .= (empty($liclass)) ? 'here active' : ' here active';
2723 $str .= (!empty($liclass)) ? '<li class="'.$liclass.'">' : '<li>';
2725 if ($tab->inactive || $tab->active || ($tab->selected && !$tab->linkedwhenselected)) {
2726 // The a tag is used for styling
2727 $str .= '<a class="nolink"><span>'.$tab->text.'</span></a>';
2729 $str .= '<a href="'.$tab->link.'" title="'.$tab->title.'"><span>'.$tab->text.'</span></a>';
2732 if (!empty($tab->subtree)) {
2733 $str .= convert_tree_to_html($tab->subtree, $row+1);
2734 } else if ($tab->selected) {
2735 $str .= '<div class="tabrow'.($row+1).' empty"> </div>'."\n";
2738 $str .= ' </li>'."\n";
2740 $str .= '</ul>'."\n";
2746 * Convert nested tabrows to a nested array
2748 * @param array $tabrows A [nested] array of tab row objects
2749 * @param string $selected The tabrow to select (by id)
2750 * @param array $inactive An array of tabrow id's to make inactive
2751 * @param array $activated An array of tabrow id's to make active
2752 * @return array The nested array
2754 function convert_tabrows_to_tree($tabrows, $selected, $inactive, $activated) {
2756 /// Work backwards through the rows (bottom to top) collecting the tree as we go.
2758 $tabrows = array_reverse($tabrows);
2762 foreach ($tabrows as $row) {
2765 foreach ($row as $tab) {
2766 $tab->inactive = in_array((string)$tab->id, $inactive);
2767 $tab->active = in_array((string)$tab->id, $activated);
2768 $tab->selected = (string)$tab->id == $selected;
2770 if ($tab->active || $tab->selected) {
2772 $tab->subtree = $subtree;
2784 * Returns the Moodle Docs URL in the users language
2787 * @param string $path the end of the URL.
2788 * @return string The MoodleDocs URL in the user's language. for example {@link http://docs.moodle.org/en/ http://docs.moodle.org/en/$path}
2790 function get_docs_url($path) {
2792 if (!empty($CFG->docroot)) {
2793 return $CFG->docroot . '/' . current_language() . '/' . $path;
2795 return 'http://docs.moodle.org/en/'.$path;
2801 * Standard Debugging Function
2803 * Returns true if the current site debugging settings are equal or above specified level.
2804 * If passed a parameter it will emit a debugging notice similar to trigger_error(). The
2805 * routing of notices is controlled by $CFG->debugdisplay
2808 * 1) debugging('a normal debug notice');
2809 * 2) debugging('something really picky', DEBUG_ALL);
2810 * 3) debugging('annoying debug message only for developers', DEBUG_DEVELOPER);
2811 * 4) if (debugging()) { perform extra debugging operations (do not use print or echo) }
2813 * In code blocks controlled by debugging() (such as example 4)
2814 * any output should be routed via debugging() itself, or the lower-level
2815 * trigger_error() or error_log(). Using echo or print will break XHTML
2816 * JS and HTTP headers.
2818 * It is also possible to define NO_DEBUG_DISPLAY which redirects the message to error_log.
2820 * @uses DEBUG_NORMAL
2821 * @param string $message a message to print
2822 * @param int $level the level at which this debugging statement should show
2823 * @param array $backtrace use different backtrace
2826 function debugging($message = '', $level = DEBUG_NORMAL, $backtrace = null) {
2827 global $CFG, $USER, $UNITTEST;
2829 $forcedebug = false;
2830 if (!empty($CFG->debugusers)) {
2831 $debugusers = explode(',', $CFG->debugusers);
2832 $forcedebug = in_array($USER->id, $debugusers);
2835 if (!$forcedebug and (empty($CFG->debug) || $CFG->debug < $level)) {
2839 if (!isset($CFG->debugdisplay)) {
2840 $CFG->debugdisplay = ini_get_bool('display_errors');
2845 $backtrace = debug_backtrace();
2847 $from = format_backtrace($backtrace, CLI_SCRIPT);
2848 if (!empty($UNITTEST->running)) {
2849 // When the unit tests are running, any call to trigger_error
2850 // is intercepted by the test framework and reported as an exception.
2851 // Therefore, we cannot use trigger_error during unit tests.
2852 // At the same time I do not think we should just discard those messages,
2853 // so displaying them on-screen seems like the only option. (MDL-20398)
2854 echo '<div class="notifytiny">' . $message . $from . '</div>';
2856 } else if (NO_DEBUG_DISPLAY) {
2857 // script does not want any errors or debugging in output,
2858 // we send the info to error log instead
2859 error_log('Debugging: ' . $message . $from);
2861 } else if ($forcedebug or $CFG->debugdisplay) {
2862 if (!defined('DEBUGGING_PRINTED')) {
2863 define('DEBUGGING_PRINTED', 1); // indicates we have printed something
2866 echo "++ $message ++\n$from";
2868 echo '<div class="notifytiny">' . $message . $from . '</div>';
2872 trigger_error($message . $from, E_USER_NOTICE);
2879 * Outputs a HTML comment to the browser. This is used for those hard-to-debug
2880 * pages that use bits from many different files in very confusing ways (e.g. blocks).
2882 * <code>print_location_comment(__FILE__, __LINE__);</code>
2884 * @param string $file
2885 * @param integer $line
2886 * @param boolean $return Whether to return or print the comment
2887 * @return string|void Void unless true given as third parameter
2889 function print_location_comment($file, $line, $return = false)
2892 return "<!-- $file at line $line -->\n";
2894 echo "<!-- $file at line $line -->\n";
2900 * @return boolean true if the current language is right-to-left (Hebrew, Arabic etc)
2902 function right_to_left() {
2903 return (get_string('thisdirection', 'langconfig') === 'rtl');
2908 * Returns swapped left<=>right if in RTL environment.
2909 * part of RTL support
2911 * @param string $align align to check
2914 function fix_align_rtl($align) {
2915 if (!right_to_left()) {
2918 if ($align=='left') { return 'right'; }
2919 if ($align=='right') { return 'left'; }
2925 * Returns true if the page is displayed in a popup window.
2926 * Gets the information from the URL parameter inpopup.
2928 * @todo Use a central function to create the popup calls all over Moodle and
2929 * In the moment only works with resources and probably questions.
2933 function is_in_popup() {
2934 $inpopup = optional_param('inpopup', '', PARAM_BOOL);
2940 * To use this class.
2942 * - call create (or use the 3rd param to the constructor)
2943 * - call update or update_full() or update() repeatedly
2945 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2946 * @package moodlecore
2948 class progress_bar {
2949 /** @var string html id */
2951 /** @var int total width */
2953 /** @var int last percentage printed */
2954 private $percent = 0;
2955 /** @var int time when last printed */
2956 private $lastupdate = 0;
2957 /** @var int when did we start printing this */
2958 private $time_start = 0;
2963 * @param string $html_id
2965 * @param bool $autostart Default to false
2966 * @return void, prints JS code if $autostart true
2968 public function __construct($html_id = '', $width = 500, $autostart = false) {
2969 if (!empty($html_id)) {
2970 $this->html_id = $html_id;
2972 $this->html_id = 'pbar_'.uniqid();
2975 $this->width = $width;
2983 * Create a new progress bar, this function will output html.
2985 * @return void Echo's output
2987 public function create() {
2988 $this->time_start = microtime(true);
2990 return; // temporary solution for cli scripts
2993 <div style="text-align:center;width:{$this->width}px;clear:both;padding:0;margin:0 auto;">
2994 <h2 id="status_{$this->html_id}" style="text-align: center;margin:0 auto"></h2>
2995 <p id="time_{$this->html_id}"></p>
2996 <div id="bar_{$this->html_id}" style="border-style:solid;border-width:1px;width:500px;height:50px;">
2997 <div id="progress_{$this->html_id}"
2998 style="text-align:center;background:#FFCC66;width:4px;border:1px
2999 solid gray;height:38px; padding-top:10px;"> <span id="pt_{$this->html_id}"></span>
3010 * Update the progress bar
3012 * @param int $percent from 1-100
3013 * @param string $msg
3014 * @return void Echo's output
3016 private function _update($percent, $msg) {
3017 if (empty($this->time_start)){
3018 $this->time_start = microtime(true);
3022 return; // temporary solution for cli scripts
3025 $es = $this->estimate($percent);
3028 // always do the first and last updates
3030 } else if ($es == 0) {
3031 // always do the last updates
3032 } else if ($this->lastupdate + 20 < time()) {
3033 // we must update otherwise browser would time out
3034 } else if (round($this->percent, 2) === round($percent, 2)) {
3035 // no significant change, no need to update anything
3039 $this->percent = $percent;
3040 $this->lastupdate = microtime(true);
3042 $w = ($this->percent/100) * $this->width;
3043 echo html_writer::script(js_writer::function_call('update_progress_bar', array($this->html_id, $w, $this->percent, $msg, $es)));
3048 * Estimate how much time it is going to take.
3050 * @param int $curtime the time call this function
3051 * @param int $percent from 1-100
3052 * @return mixed Null (unknown), or int
3054 private function estimate($pt) {
3055 if ($this->lastupdate == 0) {
3058 if ($pt < 0.00001) {
3059 return null; // we do not know yet how long it will take
3061 if ($pt > 99.99999) {
3062 return 0; // nearly done, right?
3064 $consumed = microtime(true) - $this->time_start;
3065 if ($consumed < 0.001) {
3069 return (100 - $pt) * ($consumed / $pt);
3073 * Update progress bar according percent
3075 * @param int $percent from 1-100
3076 * @param string $msg the message needed to be shown
3078 public function update_full($percent, $msg) {
3079 $percent = max(min($percent, 100), 0);
3080 $this->_update($percent, $msg);
3084 * Update progress bar according the number of tasks
3086 * @param int $cur current task number
3087 * @param int $total total task number
3088 * @param string $msg message
3090 public function update($cur, $total, $msg) {
3091 $percent = ($cur / $total) * 100;
3092 $this->update_full($percent, $msg);
3096 * Restart the progress bar.
3098 public function restart() {
3100 $this->lastupdate = 0;
3101 $this->time_start = 0;
3106 * Use this class from long operations where you want to output occasional information about
3107 * what is going on, but don't know if, or in what format, the output should be.
3109 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3110 * @package moodlecore
3112 abstract class progress_trace {
3114 * Ouput an progress message in whatever format.
3115 * @param string $message the message to output.
3116 * @param integer $depth indent depth for this message.
3118 abstract public function output($message, $depth = 0);
3121 * Called when the processing is finished.
3123 public function finished() {
3128 * This subclass of progress_trace does not ouput anything.
3130 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3131 * @package moodlecore
3133 class null_progress_trace extends progress_trace {
3137 * @param string $message
3139 * @return void Does Nothing
3141 public function output($message, $depth = 0) {
3146 * This subclass of progress_trace outputs to plain text.
3148 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3149 * @package moodlecore
3151 class text_progress_trace extends progress_trace {
3153 * Output the trace message
3155 * @param string $message
3157 * @return void Output is echo'd
3159 public function output($message, $depth = 0) {
3160 echo str_repeat(' ', $depth), $message, "\n";
3166 * This subclass of progress_trace outputs as HTML.
3168 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3169 * @package moodlecore
3171 class html_progress_trace extends progress_trace {
3173 * Output the trace message
3175 * @param string $message
3177 * @return void Output is echo'd
3179 public function output($message, $depth = 0) {
3180 echo '<p>', str_repeat('  ', $depth), htmlspecialchars($message), "</p>\n";
3186 * HTML List Progress Tree
3188 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3189 * @package moodlecore
3191 class html_list_progress_trace extends progress_trace {
3193 protected $currentdepth = -1;
3198 * @param string $message The message to display
3200 * @return void Output is echoed
3202 public function output($message, $depth = 0) {
3204 while ($this->currentdepth > $depth) {
3205 echo "</li>\n</ul>\n";
3206 $this->currentdepth -= 1;
3207 if ($this->currentdepth == $depth) {
3212 while ($this->currentdepth < $depth) {
3214 $this->currentdepth += 1;
3220 echo htmlspecialchars($message);
3225 * Called when the processing is finished.
3227 public function finished() {
3228 while ($this->currentdepth >= 0) {
3229 echo "</li>\n</ul>\n";
3230 $this->currentdepth -= 1;
3236 * Returns a localized sentence in the current language summarizing the current password policy
3238 * @todo this should be handled by a function/method in the language pack library once we have a support for it
3242 function print_password_policy() {
3246 if (!empty($CFG->passwordpolicy)) {
3247 $messages = array();
3248 $messages[] = get_string('informminpasswordlength', 'auth', $CFG->minpasswordlength);
3249 if (!empty($CFG->minpassworddigits)) {
3250 $messages[] = get_string('informminpassworddigits', 'auth', $CFG->minpassworddigits);
3252 if (!empty($CFG->minpasswordlower)) {
3253 $messages[] = get_string('informminpasswordlower', 'auth', $CFG->minpasswordlower);
3255 if (!empty($CFG->minpasswordupper)) {
3256 $messages[] = get_string('informminpasswordupper', 'auth', $CFG->minpasswordupper);
3258 if (!empty($CFG->minpasswordnonalphanum)) {
3259 $messages[] = get_string('informminpasswordnonalphanum', 'auth', $CFG->minpasswordnonalphanum);
3262 $messages = join(', ', $messages); // this is ugly but we do not have anything better yet...
3263 $message = get_string('informpasswordpolicy', 'auth', $messages);
3268 function create_ufo_inline($id, $args) {
3270 // must not use $PAGE, $THEME, $COURSE etc. because the result is cached!
3271 // unfortunately this ufo.js can not be cached properly because we do not have access to current $CFG either
3272 $jsoutput = html_writer::script('', $CFG->wwwroot.'/lib/ufo.js');
3273 $jsoutput .= html_writer::script(js_writer::function_call('M.util.create_UFO_object', array($id, $args)));
3277 function create_flowplayer($id, $fileurl, $type='flv', $color='#000000') {
3280 $playerpath = $CFG->wwwroot.'/filter/mediaplugin/'.$type.'player.swf';
3281 $jsoutput = html_writer::script('', $CFG->wwwroot.'/lib/flowplayer.js');
3283 if ($type == 'flv') {
3284 $jsoutput .= html_writer::script(js_writer::function_call('M.util.init_flvflowplayer', array($id, $playerpath, $fileurl)));
3285 } else if ($type == 'mp3') {
3286 $audioplayerpath = $CFG->wwwroot .'/filter/mediaplugin/flowplayer.audio.swf';
3287 $jsoutput .= html_writer::script(js_writer::function_call('M.util.init_mp3flowplayerplugin', array($id, $playerpath, $audioplayerpath, $fileurl, $color)));