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.
29 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
30 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
35 /// Define text formatting types ... eventually we can add Wiki, BBcode etc
38 * Does all sorts of transformations and filtering
40 define('FORMAT_MOODLE', '0'); // Does all sorts of transformations and filtering
43 * Plain HTML (with some tags stripped)
45 define('FORMAT_HTML', '1'); // Plain HTML (with some tags stripped)
48 * Plain text (even tags are printed in full)
50 define('FORMAT_PLAIN', '2'); // Plain text (even tags are printed in full)
54 * Deprecated: left here just to note that '3' is not used (at the moment)
55 * and to catch any latent wiki-like text (which generates an error)
57 define('FORMAT_WIKI', '3'); // Wiki-formatted text
60 * Markdown-formatted text http://daringfireball.net/projects/markdown/
62 define('FORMAT_MARKDOWN', '4'); // Markdown-formatted text http://daringfireball.net/projects/markdown/
65 * TRUSTTEXT marker - if present in text, text cleaning should be bypassed
67 define('TRUSTTEXT', '#####TRUSTTEXT#####');
70 * A moodle_url comparison using this flag will return true if the base URLs match, params are ignored
72 define('URL_MATCH_BASE', 0);
74 * A moodle_url comparison using this flag will return true if the base URLs match and the params of url1 are part of url2
76 define('URL_MATCH_PARAMS', 1);
78 * A moodle_url comparison using this flag will return true if the two URLs are identical, except for the order of the params
80 define('URL_MATCH_EXACT', 2);
83 * Allowed tags - string of html tags that can be tested against for safe html tags
84 * @global string $ALLOWED_TAGS
89 '<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>';
92 * Allowed protocols - array of protocols that are safe to use in links and so on
93 * @global string $ALLOWED_PROTOCOLS
94 * @name $ALLOWED_PROTOCOLS
96 $ALLOWED_PROTOCOLS = array('http', 'https', 'ftp', 'news', 'mailto', 'rtsp', 'teamspeak', 'gopher', 'mms',
97 'color', 'callto', 'cursor', 'text-align', 'font-size', 'font-weight', 'font-style', 'font-family',
98 'border', 'margin', 'padding', 'background', 'background-color', 'text-decoration'); // CSS as well to get through kses
104 * Add quotes to HTML characters
106 * Returns $var with HTML characters (like "<", ">", etc.) properly quoted.
107 * This function is very similar to {@link p()}
109 * @todo Remove obsolete param $obsolete if not used anywhere
111 * @param string $var the string potentially containing HTML characters
112 * @param boolean $obsolete no longer used.
115 function s($var, $obsolete = false) {
117 if ($var === '0' or $var === false or $var === 0) {
121 return preg_replace("/&(#\d+);/i", "&$1;", htmlspecialchars($var));
125 * Add quotes to HTML characters
127 * Prints $var with HTML characters (like "<", ">", etc.) properly quoted.
128 * This function simply calls {@link s()}
131 * @todo Remove obsolete param $obsolete if not used anywhere
133 * @param string $var the string potentially containing HTML characters
134 * @param boolean $obsolete no longer used.
137 function p($var, $obsolete = false) {
138 echo s($var, $obsolete);
142 * Does proper javascript quoting.
144 * Do not use addslashes anymore, because it does not work when magic_quotes_sybase is enabled.
146 * @param mixed $var String, Array, or Object to add slashes to
147 * @return mixed quoted result
149 function addslashes_js($var) {
150 if (is_string($var)) {
151 $var = str_replace('\\', '\\\\', $var);
152 $var = str_replace(array('\'', '"', "\n", "\r", "\0"), array('\\\'', '\\"', '\\n', '\\r', '\\0'), $var);
153 $var = str_replace('</', '<\/', $var); // XHTML compliance
154 } else if (is_array($var)) {
155 $var = array_map('addslashes_js', $var);
156 } else if (is_object($var)) {
157 $a = get_object_vars($var);
158 foreach ($a as $key=>$value) {
159 $a[$key] = addslashes_js($value);
167 * Remove query string from url
169 * Takes in a URL and returns it without the querystring portion
171 * @param string $url the url which may have a query string attached
172 * @return string The remaining URL
174 function strip_querystring($url) {
176 if ($commapos = strpos($url, '?')) {
177 return substr($url, 0, $commapos);
184 * Returns the URL of the HTTP_REFERER, less the querystring portion if required
187 * @param boolean $stripquery if true, also removes the query part of the url.
188 * @return string The resulting referer or empty string
190 function get_referer($stripquery=true) {
191 if (isset($_SERVER['HTTP_REFERER'])) {
193 return strip_querystring($_SERVER['HTTP_REFERER']);
195 return $_SERVER['HTTP_REFERER'];
204 * Returns the name of the current script, WITH the querystring portion.
206 * This function is necessary because PHP_SELF and REQUEST_URI and SCRIPT_NAME
207 * return different things depending on a lot of things like your OS, Web
208 * server, and the way PHP is compiled (ie. as a CGI, module, ISAPI, etc.)
209 * <b>NOTE:</b> This function returns false if the global variables needed are not set.
212 * @return mixed String, or false if the global variables needed are not set
220 * Returns the name of the current script, WITH the full URL.
222 * This function is necessary because PHP_SELF and REQUEST_URI and SCRIPT_NAME
223 * return different things depending on a lot of things like your OS, Web
224 * server, and the way PHP is compiled (ie. as a CGI, module, ISAPI, etc.
225 * <b>NOTE:</b> This function returns false if the global variables needed are not set.
227 * Like {@link me()} but returns a full URL
231 * @return mixed String, or false if the global variables needed are not set
233 function qualified_me() {
239 * Class for creating and manipulating urls.
241 * It can be used in moodle pages where config.php has been included without any further includes.
243 * It is useful for manipulating urls with long lists of params.
244 * One situation where it will be useful is a page which links to itself to perform various actions
245 * and / or to process form data. A moodle_url object :
246 * can be created for a page to refer to itself with all the proper get params being passed from page call to
247 * page call and methods can be used to output a url including all the params, optionally adding and overriding
248 * params and can also be used to
249 * - output the url without any get params
250 * - and output the params as hidden fields to be output within a form
252 * @link http://docs.moodle.org/en/Development:lib/weblib.php_moodle_url See short write up here
253 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
254 * @package moodlecore
258 * Scheme, ex.: http, https
261 protected $scheme = '';
266 protected $host = '';
268 * Port number, empty means default 80 or 443 in case of http
271 protected $port = '';
273 * Username for http auth
276 protected $user = '';
278 * Password for http auth
281 protected $pass = '';
286 protected $path = '';
288 * Optional slash argument value
291 protected $slashargument = '';
293 * Anchor, may be also empty, null means none
296 protected $anchor = null;
298 * Url parameters as associative array
301 protected $params = array(); // Associative array of query string params
304 * Create new instance of moodle_url.
306 * @param moodle_url|string $url - moodle_url means make a copy of another
307 * moodle_url and change parameters, string means full url or shortened
308 * form (ex.: '/course/view.php'). It is strongly encouraged to not include
309 * query string because it may result in double encoded values
310 * @param array $params these params override current params or add new
312 public function __construct($url, array $params = null) {
315 if ($url instanceof moodle_url) {
316 $this->scheme = $url->scheme;
317 $this->host = $url->host;
318 $this->port = $url->port;
319 $this->user = $url->user;
320 $this->pass = $url->pass;
321 $this->path = $url->path;
322 $this->slashargument = $url->slashargument;
323 $this->params = $url->params;
324 $this->anchor = $url->anchor;
327 // detect if anchor used
328 $apos = strpos($url, '#');
329 if ($apos !== false) {
330 $anchor = substr($url, $apos);
331 $anchor = ltrim($anchor, '#');
332 $this->set_anchor($anchor);
333 $url = substr($url, 0, $apos);
336 // normalise shortened form of our url ex.: '/course/view.php'
337 if (strpos($url, '/') === 0) {
338 // we must not use httpswwwroot here, because it might be url of other page,
339 // devs have to use httpswwwroot explicitly when creating new moodle_url
340 $url = $CFG->wwwroot.$url;
343 // now fix the admin links if needed, no need to mess with httpswwwroot
344 if ($CFG->admin !== 'admin') {
345 if (strpos($url, "$CFG->wwwroot/admin/") === 0) {
346 $url = str_replace("$CFG->wwwroot/admin/", "$CFG->wwwroot/$CFG->admin/", $url);
351 $parts = parse_url($url);
352 if ($parts === false) {
353 throw new moodle_exception('invalidurl');
355 if (isset($parts['query'])) {
356 // note: the values may not be correctly decoded,
357 // url parameters should be always passed as array
358 parse_str(str_replace('&', '&', $parts['query']), $this->params);
360 unset($parts['query']);
361 foreach ($parts as $key => $value) {
362 $this->$key = $value;
365 // detect slashargument value from path - we do not support directory names ending with .php
366 $pos = strpos($this->path, '.php/');
367 if ($pos !== false) {
368 $this->slashargument = substr($this->path, $pos + 4);
369 $this->path = substr($this->path, 0, $pos + 4);
373 $this->params($params);
377 * Add an array of params to the params for this url.
379 * The added params override existing ones if they have the same name.
381 * @param array $params Defaults to null. If null then returns all params.
382 * @return array Array of Params for url.
384 public function params(array $params = null) {
385 $params = (array)$params;
387 foreach ($params as $key=>$value) {
389 throw new coding_exception('Url parameters can not have numeric keys!');
391 if (is_array($value)) {
392 throw new coding_exception('Url parameters values can not be arrays!');
394 if (is_object($value) and !method_exists($value, '__toString')) {
395 throw new coding_exception('Url parameters values can not be objects, unless __toString() is defined!');
397 $this->params[$key] = (string)$value;
399 return $this->params;
403 * Remove all params if no arguments passed.
404 * Remove selected params if arguments are passed.
406 * Can be called as either remove_params('param1', 'param2')
407 * or remove_params(array('param1', 'param2')).
409 * @param mixed $params either an array of param names, or a string param name,
410 * @param string $params,... any number of additional param names.
411 * @return array url parameters
413 public function remove_params($params = null) {
414 if (!is_array($params)) {
415 $params = func_get_args();
417 foreach ($params as $param) {
418 unset($this->params[$param]);
420 return $this->params;
424 * Remove all url parameters
428 public function remove_all_params($params = null) {
429 $this->params = array();
430 $this->slashargument = '';
434 * Add a param to the params for this url.
436 * The added param overrides existing one if they have the same name.
438 * @param string $paramname name
439 * @param string $newvalue Param value. If new value specified current value is overriden or parameter is added
440 * @return mixed string parameter value, null if parameter does not exist
442 public function param($paramname, $newvalue = '') {
443 if (func_num_args() > 1) {
445 $this->params(array($paramname=>$newvalue));
447 if (isset($this->params[$paramname])) {
448 return $this->params[$paramname];
455 * Merges parameters and validates them
456 * @param array $overrideparams
457 * @return array merged parameters
459 protected function merge_overrideparams(array $overrideparams = null) {
460 $overrideparams = (array)$overrideparams;
461 $params = $this->params;
462 foreach ($overrideparams as $key=>$value) {
464 throw new coding_error('Overriden parameters can not have numeric keys!');
466 if (is_array($value)) {
467 throw new coding_error('Overriden parameters values can not be arrays!');
469 if (is_object($value) and !method_exists($value, '__toString')) {
470 throw new coding_error('Overriden parameters values can not be objects, unless __toString() is defined!');
472 $params[$key] = (string)$value;
478 * Get the params as as a query string.
479 * This method should not be used outside of this method.
481 * @param boolean $escaped Use & as params separator instead of plain &
482 * @param array $overrideparams params to add to the output params, these
483 * override existing ones with the same name.
484 * @return string query string that can be added to a url.
486 public function get_query_string($escaped = true, array $overrideparams = null) {
488 $params = $this->merge_overrideparams($overrideparams);
489 foreach ($params as $key => $val) {
490 $arr[] = rawurlencode($key)."=".rawurlencode($val);
493 return implode('&', $arr);
495 return implode('&', $arr);
500 * Shortcut for printing of encoded URL.
503 public function __toString() {
504 return $this->out(true);
510 * If you use the returned URL in HTML code, you want the escaped ampersands. If you use
511 * the returned URL in HTTP headers, you want $escaped=false.
513 * @param boolean $escaped Use & as params separator instead of plain &
514 * @param array $overrideparams params to add to the output url, these override existing ones with the same name.
515 * @return string Resulting URL
517 public function out($escaped = true, array $overrideparams = null) {
518 if (!is_bool($escaped)) {
519 debugging('Escape parameter must be of type boolean, '.gettype($escaped).' given instead.');
522 $uri = $this->out_omit_querystring().$this->slashargument;
524 $querystring = $this->get_query_string($escaped, $overrideparams);
525 if ($querystring !== '') {
526 $uri .= '?' . $querystring;
528 if (!is_null($this->anchor)) {
529 $uri .= '#'.$this->anchor;
536 * Returns url without parameters, everything before '?'.
539 public function out_omit_querystring() {
540 $uri = $this->scheme ? $this->scheme.':'.((strtolower($this->scheme) == 'mailto') ? '':'//'): '';
541 $uri .= $this->user ? $this->user.($this->pass? ':'.$this->pass:'').'@':'';
542 $uri .= $this->host ? $this->host : '';
543 $uri .= $this->port ? ':'.$this->port : '';
544 $uri .= $this->path ? $this->path : '';
549 * Compares this moodle_url with another
550 * See documentation of constants for an explanation of the comparison flags.
551 * @param moodle_url $url The moodle_url object to compare
552 * @param int $matchtype The type of comparison (URL_MATCH_BASE, URL_MATCH_PARAMS, URL_MATCH_EXACT)
555 public function compare(moodle_url $url, $matchtype = URL_MATCH_EXACT) {
557 $baseself = $this->out_omit_querystring();
558 $baseother = $url->out_omit_querystring();
560 // Append index.php if there is no specific file
561 if (substr($baseself,-1)=='/') {
562 $baseself .= 'index.php';
564 if (substr($baseother,-1)=='/') {
565 $baseother .= 'index.php';
568 // Compare the two base URLs
569 if ($baseself != $baseother) {
573 if ($matchtype == URL_MATCH_BASE) {
577 $urlparams = $url->params();
578 foreach ($this->params() as $param => $value) {
579 if ($param == 'sesskey') {
582 if (!array_key_exists($param, $urlparams) || $urlparams[$param] != $value) {
587 if ($matchtype == URL_MATCH_PARAMS) {
591 foreach ($urlparams as $param => $value) {
592 if ($param == 'sesskey') {
595 if (!array_key_exists($param, $this->params()) || $this->param($param) != $value) {
604 * Sets the anchor for the URI (the bit after the hash)
605 * @param string $anchor null means remove previous
607 public function set_anchor($anchor) {
608 if (is_null($anchor)) {
610 $this->anchor = null;
611 } else if ($anchor === '') {
612 // special case, used as empty link
614 } else if (preg_match('|[a-zA-Z\_\:][a-zA-Z0-9\_\-\.\:]*|', $anchor)) {
615 // Match the anchor against the NMTOKEN spec
616 $this->anchor = $anchor;
618 // bad luck, no valid anchor found
619 $this->anchor = null;
624 * Sets the url slashargument value
625 * @param string $path usually file path
626 * @param string $parameter name of page parameter if slasharguments not supported
627 * @param bool $supported usually null, then it depends on $CFG->slasharguments, use true or false for other servers
630 public function set_slashargument($path, $parameter = 'file', $supported = NULL) {
632 if (is_null($supported)) {
633 $supported = $CFG->slasharguments;
637 $parts = explode('/', $path);
638 $parts = array_map('rawurlencode', $parts);
639 $path = implode('/', $parts);
640 $this->slashargument = $path;
641 unset($this->params[$parameter]);
644 $this->slashargument = '';
645 $this->params[$parameter] = $path;
649 // == static factory methods ==
652 * General moodle file url.
653 * @param string $urlbase the script serving the file
654 * @param string $path
655 * @param bool $forcedownload
658 public static function make_file_url($urlbase, $path, $forcedownload = false) {
662 if ($forcedownload) {
663 $params['forcedownload'] = 1;
666 $url = new moodle_url($urlbase, $params);
667 $url->set_slashargument($path);
673 * Factory method for creation of url pointing to plugin file.
674 * Please note this method can be used only from the plugins to
675 * create urls of own files, it must not be used outside of plugins!
676 * @param int $contextid
677 * @param string $component
678 * @param string $area
680 * @param string $pathname
681 * @param string $filename
682 * @param bool $forcedownload
685 public static function make_pluginfile_url($contextid, $component, $area, $itemid, $pathname, $filename, $forcedownload = false) {
687 $urlbase = "$CFG->httpswwwroot/pluginfile.php";
688 if ($itemid === NULL) {
689 return self::make_file_url($urlbase, "/$contextid/$component/$area".$pathname.$filename, $forcedownload);
691 return self::make_file_url($urlbase, "/$contextid/$component/$area/$itemid".$pathname.$filename, $forcedownload);
696 * Factory method for creation of url pointing to draft
697 * file of current user.
698 * @param int $draftid draft item id
699 * @param string $pathname
700 * @param string $filename
701 * @param bool $forcedownload
704 public static function make_draftfile_url($draftid, $pathname, $filename, $forcedownload = false) {
706 $urlbase = "$CFG->httpswwwroot/draftfile.php";
707 $context = get_context_instance(CONTEXT_USER, $USER->id);
709 return self::make_file_url($urlbase, "/$context->id/user/draft/$draftid".$pathname.$filename, $forcedownload);
713 * Factory method for creating of links to legacy
715 * @param int $courseid
716 * @param string $filepath
717 * @param bool $forcedownload
720 public static function make_legacyfile_url($courseid, $filepath, $forcedownload = false) {
723 $urlbase = "$CFG->wwwroot/file.php";
724 return self::make_file_url($urlbase, '/'.$courseid.'/'.$filepath, $forcedownload);
729 * Determine if there is data waiting to be processed from a form
731 * Used on most forms in Moodle to check for data
732 * Returns the data as an object, if it's found.
733 * This object can be used in foreach loops without
734 * casting because it's cast to (array) automatically
736 * Checks that submitted POST data exists and returns it as object.
739 * @return mixed false or object
741 function data_submitted() {
746 return (object)$_POST;
751 * Given some normal text this function will break up any
752 * long words to a given size by inserting the given character
754 * It's multibyte savvy and doesn't change anything inside html tags.
756 * @param string $string the string to be modified
757 * @param int $maxsize maximum length of the string to be returned
758 * @param string $cutchar the string used to represent word breaks
761 function break_up_long_words($string, $maxsize=20, $cutchar=' ') {
763 /// Loading the textlib singleton instance. We are going to need it.
764 $textlib = textlib_get_instance();
766 /// First of all, save all the tags inside the text to skip them
768 filter_save_tags($string,$tags);
770 /// Process the string adding the cut when necessary
772 $length = $textlib->strlen($string);
775 for ($i=0; $i<$length; $i++) {
776 $char = $textlib->substr($string, $i, 1);
777 if ($char == ' ' or $char == "\t" or $char == "\n" or $char == "\r" or $char == "<" or $char == ">") {
781 if ($wordlength > $maxsize) {
789 /// Finally load the tags back again
791 $output = str_replace(array_keys($tags), $tags, $output);
798 * Try and close the current window using JavaScript, either immediately, or after a delay.
800 * Echo's out the resulting XHTML & javascript
804 * @param integer $delay a delay in seconds before closing the window. Default 0.
805 * @param boolean $reloadopener if true, we will see if this window was a pop-up, and try
806 * to reload the parent window before this one closes.
808 function close_window($delay = 0, $reloadopener = false) {
809 global $PAGE, $OUTPUT;
811 if (!$PAGE->headerprinted) {
812 $PAGE->set_title(get_string('closewindow'));
813 echo $OUTPUT->header();
815 $OUTPUT->container_end_all(false);
819 $function = 'close_window_reloading_opener';
821 $function = 'close_window';
823 echo '<p class="centerpara">' . get_string('windowclosing') . '</p>';
825 $PAGE->requires->js_function_call($function, null, false, $delay);
827 echo $OUTPUT->footer();
832 * Returns a string containing a link to the user documentation for the current
833 * page. Also contains an icon by default. Shown to teachers and admin only.
837 * @param string $text The text to be displayed for the link
838 * @param string $iconpath The path to the icon to be displayed
839 * @return string The link to user documentation for this current page
841 function page_doc_link($text='') {
842 global $CFG, $PAGE, $OUTPUT;
844 if (empty($CFG->docroot) || during_initial_install()) {
847 if (!has_capability('moodle/site:doclinks', $PAGE->context)) {
851 $path = $PAGE->docspath;
855 return $OUTPUT->doc_link($path, $text);
860 * Validates an email to make sure it makes sense.
862 * @param string $address The email address to validate.
865 function validate_email($address) {
867 return (preg_match('#^[-!\#$%&\'*+\\/0-9=?A-Z^_`a-z{|}~]+'.
868 '(\.[-!\#$%&\'*+\\/0-9=?A-Z^_`a-z{|}~]+)*'.
870 '[-!\#$%&\'*+\\/0-9=?A-Z^_`a-z{|}~]+\.'.
871 '[-!\#$%&\'*+\\./0-9=?A-Z^_`a-z{|}~]+$#',
876 * Extracts file argument either from file parameter or PATH_INFO
877 * Note: $scriptname parameter is not needed anymore
882 * @return string file path (only safe characters)
884 function get_file_argument() {
887 $relativepath = optional_param('file', FALSE, PARAM_PATH);
889 // then try extract file from PATH_INFO (slasharguments method)
890 if ($relativepath === false and isset($_SERVER['PATH_INFO']) and $_SERVER['PATH_INFO'] !== '') {
891 // check that PATH_INFO works == must not contain the script name
892 if (strpos($_SERVER['PATH_INFO'], $SCRIPT) === false) {
893 $relativepath = clean_param(urldecode($_SERVER['PATH_INFO']), PARAM_PATH);
897 // note: we are not using any other way because they are not compatible with unicode file names ;-)
899 return $relativepath;
903 * Just returns an array of text formats suitable for a popup menu
905 * @uses FORMAT_MOODLE
908 * @uses FORMAT_MARKDOWN
911 function format_text_menu() {
913 return array (FORMAT_MOODLE => get_string('formattext'),
914 FORMAT_HTML => get_string('formathtml'),
915 FORMAT_PLAIN => get_string('formatplain'),
916 FORMAT_MARKDOWN => get_string('formatmarkdown'));
920 * Given text in a variety of format codings, this function returns
921 * the text as safe HTML.
923 * This function should mainly be used for long strings like posts,
924 * answers, glossary items etc. For short strings @see format_string().
926 * @todo Finish documenting this function
932 * @uses FORMAT_MOODLE
936 * @uses FORMAT_MARKDOWN
938 * @staticvar array $croncache
939 * @param string $text The text to be formatted. This is raw text originally from user input.
940 * @param int $format Identifier of the text format to be used
941 * [FORMAT_MOODLE, FORMAT_HTML, FORMAT_PLAIN, FORMAT_WIKI, FORMAT_MARKDOWN]
942 * @param object $options ?
943 * @param int $courseid The courseid to use, defaults to $COURSE->courseid
946 function format_text($text, $format=FORMAT_MOODLE, $options=NULL, $courseid=NULL) {
947 global $CFG, $COURSE, $DB, $PAGE;
949 static $croncache = array();
954 return ''; // no need to do any filters and cleaning
956 if (!empty($options->comments) && !empty($CFG->usecomments)) {
957 require_once($CFG->dirroot . '/comment/lib.php');
958 $comment = new comment($options->comments);
959 $cmt = $comment->output(true);
965 if (!isset($options->trusted)) {
966 $options->trusted = false;
968 if (!isset($options->noclean)) {
969 if ($options->trusted and trusttext_active()) {
970 // no cleaning if text trusted and noclean not specified
971 $options->noclean=true;
973 $options->noclean=false;
976 if (!isset($options->nocache)) {
977 $options->nocache=false;
979 if (!isset($options->smiley)) {
980 $options->smiley=true;
982 if (!isset($options->filter)) {
983 $options->filter=true;
985 if (!isset($options->para)) {
988 if (!isset($options->newlines)) {
989 $options->newlines=true;
991 if (empty($courseid)) {
992 $courseid = $COURSE->id;
995 if ($options->filter) {
996 $filtermanager = filter_manager::instance();
998 $filtermanager = new null_filter_manager();
1000 $context = $PAGE->context;
1002 if (!empty($CFG->cachetext) and empty($options->nocache)) {
1003 $hashstr .= $text.'-'.$filtermanager->text_filtering_hash($context, $courseid).'-'.(int)$courseid.'-'.current_language().'-'.
1004 (int)$format.(int)$options->trusted.(int)$options->noclean.(int)$options->smiley.
1005 (int)$options->filter.(int)$options->para.(int)$options->newlines;
1007 $time = time() - $CFG->cachetext;
1008 $md5key = md5($hashstr);
1010 if (isset($croncache[$md5key])) {
1011 return $croncache[$md5key].$cmt;
1015 if ($oldcacheitem = $DB->get_record('cache_text', array('md5key'=>$md5key), '*', IGNORE_MULTIPLE)) {
1016 if ($oldcacheitem->timemodified >= $time) {
1018 if (count($croncache) > 150) {
1020 $key = key($croncache);
1021 unset($croncache[$key]);
1023 $croncache[$md5key] = $oldcacheitem->formattedtext;
1025 return $oldcacheitem->formattedtext.$cmt;
1032 if ($options->smiley) {
1033 replace_smilies($text);
1035 if (!$options->noclean) {
1036 $text = clean_text($text, FORMAT_HTML);
1038 $text = $filtermanager->filter_text($text, $context, $courseid);
1042 $text = s($text); // cleans dangerous JS
1043 $text = rebuildnolinktag($text);
1044 $text = str_replace(' ', ' ', $text);
1045 $text = nl2br($text);
1049 // this format is deprecated
1050 $text = '<p>NOTICE: Wiki-like formatting has been removed from Moodle. You should not be seeing
1051 this message as all texts should have been converted to Markdown format instead.
1052 Please post a bug report to http://moodle.org/bugs with information about where you
1053 saw this message.</p>'.s($text);
1056 case FORMAT_MARKDOWN:
1057 $text = markdown_to_html($text);
1058 if ($options->smiley) {
1059 replace_smilies($text);
1061 if (!$options->noclean) {
1062 $text = clean_text($text, FORMAT_HTML);
1064 $text = $filtermanager->filter_text($text, $context, $courseid);
1067 default: // FORMAT_MOODLE or anything else
1068 $text = text_to_html($text, $options->smiley, $options->para, $options->newlines);
1069 if (!$options->noclean) {
1070 $text = clean_text($text, FORMAT_HTML);
1072 $text = $filtermanager->filter_text($text, $context, $courseid);
1076 // Warn people that we have removed this old mechanism, just in case they
1077 // were stupid enough to rely on it.
1078 if (isset($CFG->currenttextiscacheable)) {
1079 debugging('Once upon a time, Moodle had a truly evil use of global variables ' .
1080 'called $CFG->currenttextiscacheable. The good news is that this no ' .
1081 'longer exists. The bad news is that you seem to be using a filter that '.
1082 'relies on it. Please seek out and destroy that filter code.', DEBUG_DEVELOPER);
1085 if (empty($options->nocache) and !empty($CFG->cachetext)) {
1087 // special static cron cache - no need to store it in db if its not already there
1088 if (count($croncache) > 150) {
1090 $key = key($croncache);
1091 unset($croncache[$key]);
1093 $croncache[$md5key] = $text;
1097 $newcacheitem = new object();
1098 $newcacheitem->md5key = $md5key;
1099 $newcacheitem->formattedtext = $text;
1100 $newcacheitem->timemodified = time();
1101 if ($oldcacheitem) { // See bug 4677 for discussion
1102 $newcacheitem->id = $oldcacheitem->id;
1104 $DB->update_record('cache_text', $newcacheitem); // Update existing record in the cache table
1105 } catch (dml_exception $e) {
1106 // It's unlikely that the cron cache cleaner could have
1107 // deleted this entry in the meantime, as it allows
1108 // some extra time to cover these cases.
1112 $DB->insert_record('cache_text', $newcacheitem); // Insert a new record in the cache table
1113 } catch (dml_exception $e) {
1114 // Again, it's possible that another user has caused this
1115 // record to be created already in the time that it took
1116 // to traverse this function. That's OK too, as the
1117 // call above handles duplicate entries, and eventually
1118 // the cron cleaner will delete them.
1127 * Converts the text format from the value to the 'internal'
1128 * name or vice versa.
1130 * $key can either be the value or the name and you get the other back.
1132 * @uses FORMAT_MOODLE
1134 * @uses FORMAT_PLAIN
1135 * @uses FORMAT_MARKDOWN
1136 * @param mixed $key int 0-4 or string one of 'moodle','html','plain','markdown'
1137 * @return mixed as above but the other way around!
1139 function text_format_name( $key ) {
1141 $lookup[FORMAT_MOODLE] = 'moodle';
1142 $lookup[FORMAT_HTML] = 'html';
1143 $lookup[FORMAT_PLAIN] = 'plain';
1144 $lookup[FORMAT_MARKDOWN] = 'markdown';
1146 if (!is_numeric($key)) {
1147 $key = strtolower( $key );
1148 $value = array_search( $key, $lookup );
1151 if (isset( $lookup[$key] )) {
1152 $value = $lookup[ $key ];
1159 * Resets all data related to filters, called during upgrade or when filter settings change.
1165 function reset_text_filters_cache() {
1168 $DB->delete_records('cache_text');
1169 $purifdir = $CFG->dataroot.'/cache/htmlpurifier';
1170 remove_dir($purifdir, true);
1174 * Given a simple string, this function returns the string
1175 * processed by enabled string filters if $CFG->filterall is enabled
1177 * This function should be used to print short strings (non html) that
1178 * need filter processing e.g. activity titles, post subjects,
1179 * glossary concepts.
1184 * @staticvar bool $strcache
1185 * @param string $string The string to be filtered.
1186 * @param boolean $striplinks To strip any link in the result text.
1187 Moodle 1.8 default changed from false to true! MDL-8713
1188 * @param int $courseid Current course as filters can, potentially, use it
1191 function format_string($string, $striplinks=true, $courseid=NULL ) {
1192 global $CFG, $COURSE, $PAGE;
1194 //We'll use a in-memory cache here to speed up repeated strings
1195 static $strcache = false;
1197 if ($strcache === false or count($strcache) > 2000 ) { // this number might need some tuning to limit memory usage in cron
1198 $strcache = array();
1202 if (empty($courseid)) {
1203 $courseid = $COURSE->id;
1207 $md5 = md5($string.'<+>'.$striplinks.'<+>'.$courseid.'<+>'.current_language());
1209 //Fetch from cache if possible
1210 if (isset($strcache[$md5])) {
1211 return $strcache[$md5];
1214 // First replace all ampersands not followed by html entity code
1215 // Regular expression moved to its own method for easier unit testing
1216 $string = replace_ampersands_not_followed_by_entity($string);
1218 if (!empty($CFG->filterall) && $CFG->version >= 2009040600) { // Avoid errors during the upgrade to the new system.
1219 $context = $PAGE->context;
1220 $string = filter_manager::instance()->filter_string($string, $context, $courseid);
1223 // If the site requires it, strip ALL tags from this string
1224 if (!empty($CFG->formatstringstriptags)) {
1225 $string = strip_tags($string);
1228 // Otherwise strip just links if that is required (default)
1229 if ($striplinks) { //strip links in string
1230 $string = strip_links($string);
1232 $string = clean_text($string);
1236 $strcache[$md5] = $string;
1242 * Given a string, performs a negative lookahead looking for any ampersand character
1243 * that is not followed by a proper HTML entity. If any is found, it is replaced
1244 * by &. The string is then returned.
1246 * @param string $string
1249 function replace_ampersands_not_followed_by_entity($string) {
1250 return preg_replace("/\&(?![a-zA-Z0-9#]{1,8};)/", "&", $string);
1254 * Given a string, replaces all <a>.*</a> by .* and returns the string.
1256 * @param string $string
1259 function strip_links($string) {
1260 return preg_replace('/(<a\s[^>]+?>)(.+?)(<\/a>)/is','$2',$string);
1264 * This expression turns links into something nice in a text format. (Russell Jungwirth)
1266 * @param string $string
1269 function wikify_links($string) {
1270 return preg_replace('~(<a [^<]*href=["|\']?([^ "\']*)["|\']?[^>]*>([^<]*)</a>)~i','$3 [ $2 ]', $string);
1274 * Replaces non-standard HTML entities
1276 * @param string $string
1279 function fix_non_standard_entities($string) {
1280 $text = preg_replace('/�*([0-9]+);?/', '&#$1;', $string);
1281 $text = preg_replace('/�*([0-9a-fA-F]+);?/', '&#x$1;', $text);
1286 * Given text in a variety of format codings, this function returns
1287 * the text as plain text suitable for plain email.
1289 * @uses FORMAT_MOODLE
1291 * @uses FORMAT_PLAIN
1293 * @uses FORMAT_MARKDOWN
1294 * @param string $text The text to be formatted. This is raw text originally from user input.
1295 * @param int $format Identifier of the text format to be used
1296 * [FORMAT_MOODLE, FORMAT_HTML, FORMAT_PLAIN, FORMAT_WIKI, FORMAT_MARKDOWN]
1299 function format_text_email($text, $format) {
1308 $text = wiki_to_html($text);
1309 $text = wikify_links($text);
1310 return strtr(strip_tags($text), array_flip(get_html_translation_table(HTML_ENTITIES)));
1314 return html_to_text($text);
1318 case FORMAT_MARKDOWN:
1320 $text = wikify_links($text);
1321 return strtr(strip_tags($text), array_flip(get_html_translation_table(HTML_ENTITIES)));
1327 * Given some text in HTML format, this function will pass it
1328 * through any filters that have been configured for this context.
1333 * @param string $text The text to be passed through format filters
1334 * @param int $courseid The current course.
1335 * @return string the filtered string.
1337 function filter_text($text, $courseid=NULL) {
1338 global $CFG, $COURSE, $PAGE;
1340 if (empty($courseid)) {
1341 $courseid = $COURSE->id; // (copied from format_text)
1344 $context = $PAGE->context;
1346 return filter_manager::instance()->filter_text($text, $context, $courseid);
1349 * Formats activity intro text
1352 * @uses CONTEXT_MODULE
1353 * @param string $module name of module
1354 * @param object $activity instance of activity
1355 * @param int $cmid course module id
1356 * @param bool $filter filter resulting html text
1359 function format_module_intro($module, $activity, $cmid, $filter=true) {
1361 require_once("$CFG->libdir/filelib.php");
1362 $options = (object)array('noclean'=>true, 'para'=>false, 'filter'=>false);
1363 $context = get_context_instance(CONTEXT_MODULE, $cmid);
1364 $intro = file_rewrite_pluginfile_urls($activity->intro, 'pluginfile.php', $context->id, 'mod_'.$module, 'intro', null);
1365 return trim(format_text($intro, $activity->introformat, $options));
1369 * Legacy function, used for cleaning of old forum and glossary text only.
1372 * @param string $text text that may contain TRUSTTEXT marker
1373 * @return text without any TRUSTTEXT marker
1375 function trusttext_strip($text) {
1378 while (true) { //removing nested TRUSTTEXT
1380 $text = str_replace('#####TRUSTTEXT#####', '', $text);
1381 if (strcmp($orig, $text) === 0) {
1388 * Must be called before editing of all texts
1389 * with trust flag. Removes all XSS nasties
1390 * from texts stored in database if needed.
1392 * @param object $object data object with xxx, xxxformat and xxxtrust fields
1393 * @param string $field name of text field
1394 * @param object $context active context
1395 * @return object updated $object
1397 function trusttext_pre_edit($object, $field, $context) {
1398 $trustfield = $field.'trust';
1399 $formatfield = $field.'format';
1401 if (!$object->$trustfield or !trusttext_trusted($context)) {
1402 $object->$field = clean_text($object->$field, $object->$formatfield);
1409 * Is current user trusted to enter no dangerous XSS in this context?
1411 * Please note the user must be in fact trusted everywhere on this server!!
1413 * @param object $context
1414 * @return bool true if user trusted
1416 function trusttext_trusted($context) {
1417 return (trusttext_active() and has_capability('moodle/site:trustcontent', $context));
1421 * Is trusttext feature active?
1424 * @param object $context
1427 function trusttext_active() {
1430 return !empty($CFG->enabletrusttext);
1434 * Given raw text (eg typed in by a user), this function cleans it up
1435 * and removes any nasty tags that could mess up Moodle pages.
1437 * @uses FORMAT_MOODLE
1438 * @uses FORMAT_PLAIN
1441 * @param string $text The text to be cleaned
1442 * @param int $format Identifier of the text format to be used
1443 * [FORMAT_MOODLE, FORMAT_HTML, FORMAT_PLAIN, FORMAT_WIKI, FORMAT_MARKDOWN]
1444 * @return string The cleaned up text
1446 function clean_text($text, $format=FORMAT_MOODLE) {
1448 global $ALLOWED_TAGS, $CFG;
1450 if (empty($text) or is_numeric($text)) {
1451 return (string)$text;
1456 case FORMAT_MARKDOWN:
1461 if (!empty($CFG->enablehtmlpurifier)) {
1462 $text = purify_html($text);
1464 /// Fix non standard entity notations
1465 $text = fix_non_standard_entities($text);
1467 /// Remove tags that are not allowed
1468 $text = strip_tags($text, $ALLOWED_TAGS);
1470 /// Clean up embedded scripts and , using kses
1471 $text = cleanAttributes($text);
1473 /// Again remove tags that are not allowed
1474 $text = strip_tags($text, $ALLOWED_TAGS);
1478 /// Remove potential script events - some extra protection for undiscovered bugs in our code
1479 $text = preg_replace("~([^a-z])language([[:space:]]*)=~i", "$1Xlanguage=", $text);
1480 $text = preg_replace("~([^a-z])on([a-z]+)([[:space:]]*)=~i", "$1Xon$2=", $text);
1487 * KSES replacement cleaning function - uses HTML Purifier.
1490 * @param string $text The (X)HTML string to purify
1492 function purify_html($text) {
1495 // this can not be done only once because we sometimes need to reset the cache
1496 $cachedir = $CFG->dataroot.'/cache/htmlpurifier';
1497 $status = check_dir_exists($cachedir, true, true);
1499 static $purifier = false;
1501 if ($purifier === false) {
1502 require_once $CFG->libdir.'/htmlpurifier/HTMLPurifier.safe-includes.php';
1503 $config = HTMLPurifier_Config::createDefault();
1504 $config->set('Output.Newline', "\n");
1505 $config->set('Core.ConvertDocumentToFragment', true);
1506 $config->set('Core.Encoding', 'UTF-8');
1507 $config->set('HTML.Doctype', 'XHTML 1.0 Transitional');
1508 $config->set('Cache.SerializerPath', $cachedir);
1509 $config->set('URI.AllowedSchemes', array('http'=>1, 'https'=>1, 'ftp'=>1, 'irc'=>1, 'nntp'=>1, 'news'=>1, 'rtsp'=>1, 'teamspeak'=>1, 'gopher'=>1, 'mms'=>1));
1510 $config->set('Attr.AllowedFrameTargets', array('_blank'));
1511 $purifier = new HTMLPurifier($config);
1513 return $purifier->purify($text);
1517 * This function takes a string and examines it for HTML tags.
1519 * If tags are detected it passes the string to a helper function {@link cleanAttributes2()}
1520 * which checks for attributes and filters them for malicious content
1522 * @param string $str The string to be examined for html tags
1525 function cleanAttributes($str){
1526 $result = preg_replace_callback(
1527 '%(<[^>]*(>|$)|>)%m', #search for html tags
1535 * This function takes a string with an html tag and strips out any unallowed
1536 * protocols e.g. javascript:
1538 * It calls ancillary functions in kses which are prefixed by kses
1542 * @param array $htmlArray An array from {@link cleanAttributes()}, containing in its 1st
1543 * element the html to be cleared
1546 function cleanAttributes2($htmlArray){
1548 global $CFG, $ALLOWED_PROTOCOLS;
1549 require_once($CFG->libdir .'/kses.php');
1551 $htmlTag = $htmlArray[1];
1552 if (substr($htmlTag, 0, 1) != '<') {
1553 return '>'; //a single character ">" detected
1555 if (!preg_match('%^<\s*(/\s*)?([a-zA-Z0-9]+)([^>]*)>?$%', $htmlTag, $matches)) {
1556 return ''; // It's seriously malformed
1558 $slash = trim($matches[1]); //trailing xhtml slash
1559 $elem = $matches[2]; //the element name
1560 $attrlist = $matches[3]; // the list of attributes as a string
1562 $attrArray = kses_hair($attrlist, $ALLOWED_PROTOCOLS);
1565 foreach ($attrArray as $arreach) {
1566 $arreach['name'] = strtolower($arreach['name']);
1567 if ($arreach['name'] == 'style') {
1568 $value = $arreach['value'];
1570 $prevvalue = $value;
1571 $value = kses_no_null($value);
1572 $value = preg_replace("/\/\*.*\*\//Us", '', $value);
1573 $value = kses_decode_entities($value);
1574 $value = preg_replace('/(&#[0-9]+)(;?)/', "\\1;", $value);
1575 $value = preg_replace('/(&#x[0-9a-fA-F]+)(;?)/', "\\1;", $value);
1576 if ($value === $prevvalue) {
1577 $arreach['value'] = $value;
1581 $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']);
1582 $arreach['value'] = preg_replace("/v\s*b\s*s\s*c\s*r\s*i\s*p\s*t/i", "Xvbscript", $arreach['value']);
1583 $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']);
1584 $arreach['value'] = preg_replace("/b\s*i\s*n\s*d\s*i\s*n\s*g/i", "Xbinding", $arreach['value']);
1585 } else if ($arreach['name'] == 'href') {
1586 //Adobe Acrobat Reader XSS protection
1587 $arreach['value'] = preg_replace('/(\.(pdf|fdf|xfdf|xdp|xfd)[^#]*)#.*$/i', '$1', $arreach['value']);
1589 $attStr .= ' '.$arreach['name'].'="'.$arreach['value'].'"';
1593 if (preg_match('%/\s*$%', $attrlist)) {
1594 $xhtml_slash = ' /';
1596 return '<'. $slash . $elem . $attStr . $xhtml_slash .'>';
1600 * Replaces all known smileys in the text with image equivalents
1603 * @staticvar array $e
1604 * @staticvar array $img
1605 * @staticvar array $emoticons
1606 * @param string $text Passed by reference. The string to search for smiley strings.
1609 function replace_smilies(&$text) {
1610 global $CFG, $OUTPUT;
1612 if (empty($CFG->emoticons)) { /// No emoticons defined, nothing to process here
1616 $lang = current_language();
1617 $emoticonstring = $CFG->emoticons;
1618 static $e = array();
1619 static $img = array();
1620 static $emoticons = null;
1622 if (is_null($emoticons)) {
1623 $emoticons = array();
1624 if ($emoticonstring) {
1625 $items = explode('{;}', $CFG->emoticons);
1626 foreach ($items as $item) {
1627 $item = explode('{:}', $item);
1628 $emoticons[$item[0]] = $item[1];
1633 if (empty($img[$lang])) { /// After the first time this is not run again
1634 $e[$lang] = array();
1635 $img[$lang] = array();
1636 foreach ($emoticons as $emoticon => $image){
1637 $alttext = get_string($image, 'pix');
1638 if ($alttext === '') {
1641 $e[$lang][] = $emoticon;
1642 $img[$lang][] = '<img alt="'. $alttext .'" width="15" height="15" src="'. $OUTPUT->pix_url('s/' . $image) . '" />';
1646 // Exclude from transformations all the code inside <script> tags
1647 // Needed to solve Bug 1185. Thanks to jouse 2001 detecting it. :-)
1648 // Based on code from glossary filter by Williams Castillo.
1651 // Detect all the <script> zones to take out
1652 $excludes = array();
1653 preg_match_all('/<script language(.+?)<\/script>/is',$text,$list_of_excludes);
1655 // Take out all the <script> zones from text
1656 foreach (array_unique($list_of_excludes[0]) as $key=>$value) {
1657 $excludes['<+'.$key.'+>'] = $value;
1660 $text = str_replace($excludes,array_keys($excludes),$text);
1663 /// this is the meat of the code - this is run every time
1664 $text = str_replace($e[$lang], $img[$lang], $text);
1666 // Recover all the <script> zones to text
1668 $text = str_replace(array_keys($excludes),$excludes,$text);
1673 * This code is called from help.php to inject a list of smilies into the
1674 * emoticons help file.
1678 * @return string HTML for a list of smilies.
1680 function get_emoticons_list_for_help_file() {
1681 global $CFG, $SESSION, $PAGE, $OUTPUT;
1682 if (empty($CFG->emoticons)) {
1686 $items = explode('{;}', $CFG->emoticons);
1687 $output = '<ul id="emoticonlist">';
1688 foreach ($items as $item) {
1689 $item = explode('{:}', $item);
1690 $output .= '<li><img src="' . $OUTPUT->pix_url('s/' . $item[1]) . '" alt="' .
1691 $item[0] . '" /><code>' . $item[0] . '</code></li>';
1694 if (!empty($SESSION->inserttextform)) {
1695 $formname = $SESSION->inserttextform;
1696 $fieldname = $SESSION->inserttextfield;
1698 $formname = 'theform';
1699 $fieldname = 'message';
1702 $PAGE->requires->yui2_lib('event');
1703 $PAGE->requires->js_function_call('emoticons_help.init', array($formname, $fieldname, 'emoticonlist'));
1709 * Given plain text, makes it into HTML as nicely as possible.
1710 * May contain HTML tags already
1713 * @param string $text The string to convert.
1714 * @param boolean $smiley Convert any smiley characters to smiley images?
1715 * @param boolean $para If true then the returned string will be wrapped in div tags
1716 * @param boolean $newlines If true then lines newline breaks will be converted to HTML newline breaks.
1720 function text_to_html($text, $smiley=true, $para=true, $newlines=true) {
1725 /// Remove any whitespace that may be between HTML tags
1726 $text = preg_replace("~>([[:space:]]+)<~i", "><", $text);
1728 /// Remove any returns that precede or follow HTML tags
1729 $text = preg_replace("~([\n\r])<~i", " <", $text);
1730 $text = preg_replace("~>([\n\r])~i", "> ", $text);
1732 convert_urls_into_links($text);
1734 /// Make returns into HTML newlines.
1736 $text = nl2br($text);
1739 /// Turn smileys into images.
1741 replace_smilies($text);
1744 /// Wrap the whole thing in a div if required
1746 //return '<p>'.$text.'</p>'; //1.9 version
1747 return '<div class="text_to_html">'.$text.'</div>';
1754 * Given Markdown formatted text, make it into XHTML using external function
1757 * @param string $text The markdown formatted text to be converted.
1758 * @return string Converted text
1760 function markdown_to_html($text) {
1763 if ($text === '' or $text === NULL) {
1767 require_once($CFG->libdir .'/markdown.php');
1769 return Markdown($text);
1773 * Given HTML text, make it into plain text using external function
1776 * @param string $html The text to be converted.
1779 function html_to_text($html) {
1783 require_once($CFG->libdir .'/html2text.php');
1785 $h2t = new html2text($html);
1786 $result = $h2t->get_text();
1792 * Given some text this function converts any URLs it finds into HTML links
1794 * @param string $text Passed in by reference. The string to be searched for urls.
1796 function convert_urls_into_links(&$text) {
1797 //I've added img tags to this list of tags to ignore.
1798 //See MDL-21168 for more info. A better way to ignore tags whether or not
1799 //they are escaped partially or completely would be desirable. For example:
1801 //<a href="blah">
1802 //<a href="blah">
1803 $filterignoretagsopen = array('<a\s[^>]+?>');
1804 $filterignoretagsclose = array('</a>');
1805 filter_save_ignore_tags($text,$filterignoretagsopen,$filterignoretagsclose,$ignoretags);
1807 // Check if we support unicode modifiers in regular expressions. Cache it.
1808 // TODO: this check should be a environment requirement in Moodle 2.0, as far as unicode
1809 // chars are going to arrive to URLs officially really soon (2010?)
1810 // Original RFC regex from: http://www.bytemycode.com/snippets/snippet/796/
1811 // Various ideas from: http://alanstorm.com/url_regex_explained
1812 // Unicode check, negative assertion and other bits from Moodle.
1813 static $unicoderegexp;
1814 if (!isset($unicoderegexp)) {
1815 $unicoderegexp = @preg_match('/\pL/u', 'a'); // This will fail silently, returning false,
1818 //todo: MDL-21296 - use of unicode modifiers may cause a timeout
1819 if ($unicoderegexp) { //We can use unicode modifiers
1820 $text = preg_replace('#(?<!=["\'])(((http(s?))://)(((([\pLl0-9]([\pLl0-9]|-)*[\pLl0-9]|[\pLl0-9])\.)+([\pLl]([\pLl0-9]|-)*[\pLl0-9]|[\pLl]))|(([0-9]{1,3}\.){3}[0-9]{1,3}))(:[\pL0-9]*)?(/([\pLl0-9\.!$&\'\(\)*+,;=_~:@-]|%[a-fA-F0-9]{2})*)*(\?([\pLl0-9\.!$&\'\(\)*+,;=_~:@/?-]|%[a-fA-F0-9]{2})*)?(\#[\pLl0-9\.!$&\'\(\)*+,;=_~:@/?-]*)?)(?<![,.;])#iu',
1821 '<a href="\\1" class="_blanktarget">\\1</a>', $text);
1822 $text = preg_replace('#(?<!=["\']|//)((www\.([\pLl0-9]([\pLl0-9]|-)*[\pLl0-9]|[\pLl0-9])\.)+([\pLl]([\pLl0-9]|-)*[\pLl0-9]|[\pLl])(:[\pL0-9]*)?(/([\pLl0-9\.!$&\'\(\)*+,;=_~:@-]|%[a-fA-F0-9]{2})*)*(\?([\pLl0-9\.!$&\'\(\)*+,;=_~:@/?-]|%[a-fA-F0-9]{2})*)?(\#[\pLl0-9\.!$&\'\(\)*+,;=_~:@/?-]*)?)(?<![,.;])#iu',
1823 '<a href="http://\\1" class="_blanktarget">\\1</a>', $text);
1824 } else { //We cannot use unicode modifiers
1825 $text = preg_replace('#(?<!=["\'])(((http(s?))://)(((([a-z0-9]([a-z0-9]|-)*[a-z0-9]|[a-z0-9])\.)+([a-z]([a-z0-9]|-)*[a-z0-9]|[a-z]))|(([0-9]{1,3}\.){3}[0-9]{1,3}))(:[a-zA-Z0-9]*)?(/([a-z0-9\.!$&\'\(\)*+,;=_~:@-]|%[a-f0-9]{2})*)*(\?([a-z0-9\.!$&\'\(\)*+,;=_~:@/?-]|%[a-fA-F0-9]{2})*)?(\#[a-z0-9\.!$&\'\(\)*+,;=_~:@/?-]*)?)(?<![,.;])#i',
1826 '<a href="\\1" class="_blanktarget">\\1</a>', $text);
1827 $text = preg_replace('#(?<!=["\']|//)((www\.([a-z0-9]([a-z0-9]|-)*[a-z0-9]|[a-z0-9])\.)+([a-z]([a-z0-9]|-)*[a-z0-9]|[a-z])(:[a-zA-Z0-9]*)?(/([a-z0-9\.!$&\'\(\)*+,;=_~:@-]|%[a-f0-9]{2})*)*(\?([a-z0-9\.!$&\'\(\)*+,;=_~:@/?-]|%[a-fA-F0-9]{2})*)?(\#[a-z0-9\.!$&\'\(\)*+,;=_~:@/?-]*)?)(?<![,.;])#i',
1828 '<a href="http://\\1" class="_blanktarget">\\1</a>', $text);
1831 if (!empty($ignoretags)) {
1832 $ignoretags = array_reverse($ignoretags); /// Reversed so "progressive" str_replace() will solve some nesting problems.
1833 $text = str_replace(array_keys($ignoretags),$ignoretags,$text);
1838 * This function will highlight search words in a given string
1840 * It cares about HTML and will not ruin links. It's best to use
1841 * this function after performing any conversions to HTML.
1843 * @param string $needle The search string. Syntax like "word1 +word2 -word3" is dealt with correctly.
1844 * @param string $haystack The string (HTML) within which to highlight the search terms.
1845 * @param boolean $matchcase whether to do case-sensitive. Default case-insensitive.
1846 * @param string $prefix the string to put before each search term found.
1847 * @param string $suffix the string to put after each search term found.
1848 * @return string The highlighted HTML.
1850 function highlight($needle, $haystack, $matchcase = false,
1851 $prefix = '<span class="highlight">', $suffix = '</span>') {
1853 /// Quick bail-out in trivial cases.
1854 if (empty($needle) or empty($haystack)) {
1858 /// Break up the search term into words, discard any -words and build a regexp.
1859 $words = preg_split('/ +/', trim($needle));
1860 foreach ($words as $index => $word) {
1861 if (strpos($word, '-') === 0) {
1862 unset($words[$index]);
1863 } else if (strpos($word, '+') === 0) {
1864 $words[$index] = '\b' . preg_quote(ltrim($word, '+'), '/') . '\b'; // Match only as a complete word.
1866 $words[$index] = preg_quote($word, '/');
1869 $regexp = '/(' . implode('|', $words) . ')/u'; // u is do UTF-8 matching.
1874 /// Another chance to bail-out if $search was only -words
1875 if (empty($words)) {
1879 /// Find all the HTML tags in the input, and store them in a placeholders array.
1880 $placeholders = array();
1882 preg_match_all('/<[^>]*>/', $haystack, $matches);
1883 foreach (array_unique($matches[0]) as $key => $htmltag) {
1884 $placeholders['<|' . $key . '|>'] = $htmltag;
1887 /// In $hastack, replace each HTML tag with the corresponding placeholder.
1888 $haystack = str_replace($placeholders, array_keys($placeholders), $haystack);
1890 /// In the resulting string, Do the highlighting.
1891 $haystack = preg_replace($regexp, $prefix . '$1' . $suffix, $haystack);
1893 /// Turn the placeholders back into HTML tags.
1894 $haystack = str_replace(array_keys($placeholders), $placeholders, $haystack);
1900 * This function will highlight instances of $needle in $haystack
1902 * It's faster that the above function {@link highlight()} and doesn't care about
1905 * @param string $needle The string to search for
1906 * @param string $haystack The string to search for $needle in
1907 * @return string The highlighted HTML
1909 function highlightfast($needle, $haystack) {
1911 if (empty($needle) or empty($haystack)) {
1915 $parts = explode(moodle_strtolower($needle), moodle_strtolower($haystack));
1917 if (count($parts) === 1) {
1923 foreach ($parts as $key => $part) {
1924 $parts[$key] = substr($haystack, $pos, strlen($part));
1925 $pos += strlen($part);
1927 $parts[$key] .= '<span class="highlight">'.substr($haystack, $pos, strlen($needle)).'</span>';
1928 $pos += strlen($needle);
1931 return str_replace('<span class="highlight"></span>', '', join('', $parts));
1935 * Return a string containing 'lang', xml:lang and optionally 'dir' HTML attributes.
1936 * Internationalisation, for print_header and backup/restorelib.
1938 * @param bool $dir Default false
1939 * @return string Attributes
1941 function get_html_lang($dir = false) {
1944 if (right_to_left()) {
1945 $direction = ' dir="rtl"';
1947 $direction = ' dir="ltr"';
1950 //Accessibility: added the 'lang' attribute to $direction, used in theme <html> tag.
1951 $language = str_replace('_', '-', current_language());
1952 @header('Content-Language: '.$language);
1953 return ($direction.' lang="'.$language.'" xml:lang="'.$language.'"');
1957 /// STANDARD WEB PAGE PARTS ///////////////////////////////////////////////////
1960 * Send the HTTP headers that Moodle requires.
1961 * @param $cacheable Can this page be cached on back?
1963 function send_headers($contenttype, $cacheable = true) {
1964 @header('Content-Type: ' . $contenttype);
1965 @header('Content-Script-Type: text/javascript');
1966 @header('Content-Style-Type: text/css');
1969 // Allow caching on "back" (but not on normal clicks)
1970 @header('Cache-Control: private, pre-check=0, post-check=0, max-age=0');
1971 @header('Pragma: no-cache');
1972 @header('Expires: ');
1974 // Do everything we can to always prevent clients and proxies caching
1975 @header('Cache-Control: no-store, no-cache, must-revalidate');
1976 @header('Cache-Control: post-check=0, pre-check=0', false);
1977 @header('Pragma: no-cache');
1978 @header('Expires: Mon, 20 Aug 1969 09:23:00 GMT');
1979 @header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
1981 @header('Accept-Ranges: none');
1985 * Return the right arrow with text ('next'), and optionally embedded in a link.
1988 * @param string $text HTML/plain text label (set to blank only for breadcrumb separator cases).
1989 * @param string $url An optional link to use in a surrounding HTML anchor.
1990 * @param bool $accesshide True if text should be hidden (for screen readers only).
1991 * @param string $addclass Additional class names for the link, or the arrow character.
1992 * @return string HTML string.
1994 function link_arrow_right($text, $url='', $accesshide=false, $addclass='') {
1995 global $OUTPUT; //TODO: move to output renderer
1996 $arrowclass = 'arrow ';
1998 $arrowclass .= $addclass;
2000 $arrow = '<span class="'.$arrowclass.'">'.$OUTPUT->rarrow().'</span>';
2003 $htmltext = '<span class="arrow_text">'.$text.'</span> ';
2005 $htmltext = get_accesshide($htmltext);
2009 $class = 'arrow_link';
2011 $class .= ' '.$addclass;
2013 return '<a class="'.$class.'" href="'.$url.'" title="'.preg_replace('/<.*?>/','',$text).'">'.$htmltext.$arrow.'</a>';
2015 return $htmltext.$arrow;
2019 * Return the left arrow with text ('previous'), and optionally embedded in a link.
2022 * @param string $text HTML/plain text label (set to blank only for breadcrumb separator cases).
2023 * @param string $url An optional link to use in a surrounding HTML anchor.
2024 * @param bool $accesshide True if text should be hidden (for screen readers only).
2025 * @param string $addclass Additional class names for the link, or the arrow character.
2026 * @return string HTML string.
2028 function link_arrow_left($text, $url='', $accesshide=false, $addclass='') {
2029 global $OUTPUT; // TODO: move to utput renderer
2030 $arrowclass = 'arrow ';
2032 $arrowclass .= $addclass;
2034 $arrow = '<span class="'.$arrowclass.'">'.$OUTPUT->larrow().'</span>';
2037 $htmltext = ' <span class="arrow_text">'.$text.'</span>';
2039 $htmltext = get_accesshide($htmltext);
2043 $class = 'arrow_link';
2045 $class .= ' '.$addclass;
2047 return '<a class="'.$class.'" href="'.$url.'" title="'.preg_replace('/<.*?>/','',$text).'">'.$arrow.$htmltext.'</a>';
2049 return $arrow.$htmltext;
2053 * Return a HTML element with the class "accesshide", for accessibility.
2054 * Please use cautiously - where possible, text should be visible!
2056 * @param string $text Plain text.
2057 * @param string $elem Lowercase element name, default "span".
2058 * @param string $class Additional classes for the element.
2059 * @param string $attrs Additional attributes string in the form, "name='value' name2='value2'"
2060 * @return string HTML string.
2062 function get_accesshide($text, $elem='span', $class='', $attrs='') {
2063 return "<$elem class=\"accesshide $class\" $attrs>$text</$elem>";
2067 * Return the breadcrumb trail navigation separator.
2069 * @return string HTML string.
2071 function get_separator() {
2072 //Accessibility: the 'hidden' slash is preferred for screen readers.
2073 return ' '.link_arrow_right($text='/', $url='', $accesshide=true, 'sep').' ';
2077 * Print (or return) a collapsible region, that has a caption that can
2078 * be clicked to expand or collapse the region.
2080 * If JavaScript is off, then the region will always be expanded.
2082 * @param string $contents the contents of the box.
2083 * @param string $classes class names added to the div that is output.
2084 * @param string $id id added to the div that is output. Must not be blank.
2085 * @param string $caption text displayed at the top. Clicking on this will cause the region to expand or contract.
2086 * @param string $userpref the name of the user preference that stores the user's preferred default state.
2087 * (May be blank if you do not wish the state to be persisted.
2088 * @param boolean $default Initial collapsed state to use if the user_preference it not set.
2089 * @param boolean $return if true, return the HTML as a string, rather than printing it.
2090 * @return string|void If $return is false, returns nothing, otherwise returns a string of HTML.
2092 function print_collapsible_region($contents, $classes, $id, $caption, $userpref = '', $default = false, $return = false) {
2093 $output = print_collapsible_region_start($classes, $id, $caption, $userpref, true, true);
2094 $output .= $contents;
2095 $output .= print_collapsible_region_end(true);
2105 * Print (or return) the start of a collapsible region, that has a caption that can
2106 * be clicked to expand or collapse the region. If JavaScript is off, then the region
2107 * will always be expanded.
2110 * @param string $classes class names added to the div that is output.
2111 * @param string $id id added to the div that is output. Must not be blank.
2112 * @param string $caption text displayed at the top. Clicking on this will cause the region to expand or contract.
2113 * @param boolean $userpref the name of the user preference that stores the user's preferred default state.
2114 * (May be blank if you do not wish the state to be persisted.
2115 * @param boolean $default Initial collapsed state to use if the user_preference it not set.
2116 * @param boolean $return if true, return the HTML as a string, rather than printing it.
2117 * @return string|void if $return is false, returns nothing, otherwise returns a string of HTML.
2119 function print_collapsible_region_start($classes, $id, $caption, $userpref = false, $default = false, $return = false) {
2120 global $CFG, $PAGE, $OUTPUT;
2122 // Work out the initial state.
2123 if (is_string($userpref)) {
2124 user_preference_allow_ajax_update($userpref, PARAM_BOOL);
2125 $collapsed = get_user_preferences($userpref, $default);
2127 $collapsed = $default;
2132 $classes .= ' collapsed';
2136 $output .= '<div id="' . $id . '" class="collapsibleregion ' . $classes . '">';
2137 $output .= '<div id="' . $id . '_sizer">';
2138 $output .= '<div id="' . $id . '_caption" class="collapsibleregioncaption">';
2139 $output .= $caption . ' ';
2140 $output .= '</div><div id="' . $id . '_inner" class="collapsibleregioninner">';
2141 $PAGE->requires->js_init_call('M.util.init_collapsible_region', array($id, $userpref, get_string('clicktohideshow')));
2151 * Close a region started with print_collapsible_region_start.
2153 * @param boolean $return if true, return the HTML as a string, rather than printing it.
2154 * @return string|void if $return is false, returns nothing, otherwise returns a string of HTML.
2156 function print_collapsible_region_end($return = false) {
2157 $output = '</div></div></div>';
2167 * Print a specified group's avatar.
2170 * @uses CONTEXT_COURSE
2171 * @param array $group A single {@link group} object OR array of groups.
2172 * @param int $courseid The course ID.
2173 * @param boolean $large Default small picture, or large.
2174 * @param boolean $return If false print picture, otherwise return the output as string
2175 * @param boolean $link Enclose image in a link to view specified course?
2176 * @return string|void Depending on the setting of $return
2178 function print_group_picture($group, $courseid, $large=false, $return=false, $link=true) {
2181 if (is_array($group)) {
2183 foreach($group as $g) {
2184 $output .= print_group_picture($g, $courseid, $large, true, $link);
2194 $context = get_context_instance(CONTEXT_COURSE, $courseid);
2196 // If there is no picture, do nothing
2197 if (!$group->picture) {
2201 // If picture is hidden, only show to those with course:managegroups
2202 if ($group->hidepicture and !has_capability('moodle/course:managegroups', $context)) {
2206 if ($link or has_capability('moodle/site:accessallgroups', $context)) {
2207 $output = '<a href="'. $CFG->wwwroot .'/user/index.php?id='. $courseid .'&group='. $group->id .'">';
2217 // Print custom group picture
2218 require_once($CFG->libdir.'/filelib.php');
2219 $grouppictureurl = get_file_url($group->id.'/'.$file.'.jpg', null, 'usergroup');
2220 $output .= '<img class="grouppicture" src="'.$grouppictureurl.'"'.
2221 ' alt="'.s(get_string('group').' '.$group->name).'" title="'.s($group->name).'"/>';
2223 if ($link or has_capability('moodle/site:accessallgroups', $context)) {
2236 * Display a recent activity note
2238 * @uses CONTEXT_SYSTEM
2239 * @staticvar string $strftimerecent
2240 * @param object A time object
2241 * @param object A user object
2242 * @param string $text Text for display for the note
2243 * @param string $link The link to wrap around the text
2244 * @param bool $return If set to true the HTML is returned rather than echo'd
2245 * @param string $viewfullnames
2247 function print_recent_activity_note($time, $user, $text, $link, $return=false, $viewfullnames=null) {
2248 static $strftimerecent = null;
2251 if (is_null($viewfullnames)) {
2252 $context = get_context_instance(CONTEXT_SYSTEM);
2253 $viewfullnames = has_capability('moodle/site:viewfullnames', $context);
2256 if (is_null($strftimerecent)) {
2257 $strftimerecent = get_string('strftimerecent');
2260 $output .= '<div class="head">';
2261 $output .= '<div class="date">'.userdate($time, $strftimerecent).'</div>';
2262 $output .= '<div class="name">'.fullname($user, $viewfullnames).'</div>';
2263 $output .= '</div>';
2264 $output .= '<div class="info"><a href="'.$link.'">'.format_string($text,true).'</a></div>';
2274 * Returns a popup menu with course activity modules
2277 * This function returns a small popup menu with all the
2278 * course activity modules in it, as a navigation menu
2279 * outputs a simple list structure in XHTML
2280 * The data is taken from the serialised array stored in
2283 * @todo Finish documenting this function
2286 * @uses CONTEXT_COURSE
2287 * @param course $course A {@link $COURSE} object.
2288 * @param string $sections
2289 * @param string $modinfo
2290 * @param string $strsection
2291 * @param string $strjumpto
2293 * @param string $cmid
2294 * @return string The HTML block
2296 function navmenulist($course, $sections, $modinfo, $strsection, $strjumpto, $width=50, $cmid=0) {
2303 $doneheading = false;
2305 $coursecontext = get_context_instance(CONTEXT_COURSE, $course->id);
2307 $menu[] = '<ul class="navmenulist"><li class="jumpto section"><span>'.$strjumpto.'</span><ul>';
2308 foreach ($modinfo->cms as $mod) {
2309 if ($mod->modname == 'label') {
2313 if ($mod->sectionnum > $course->numsections) { /// Don't show excess hidden sections
2317 if (!$mod->uservisible) { // do not icnlude empty sections at all
2321 if ($mod->sectionnum >= 0 and $section != $mod->sectionnum) {
2322 $thissection = $sections[$mod->sectionnum];
2324 if ($thissection->visible or !$course->hiddensections or
2325 has_capability('moodle/course:viewhiddensections', $coursecontext)) {
2326 $thissection->summary = strip_tags(format_string($thissection->summary,true));
2327 if (!$doneheading) {
2328 $menu[] = '</ul></li>';
2330 if ($course->format == 'weeks' or empty($thissection->summary)) {
2331 $item = $strsection ." ". $mod->sectionnum;
2333 if (strlen($thissection->summary) < ($width-3)) {
2334 $item = $thissection->summary;
2336 $item = substr($thissection->summary, 0, $width).'...';
2339 $menu[] = '<li class="section"><span>'.$item.'</span>';
2341 $doneheading = true;
2343 $section = $mod->sectionnum;
2345 // no activities from this hidden section shown
2350 $url = $mod->modname .'/view.php?id='. $mod->id;
2351 $mod->name = strip_tags(format_string($mod->name ,true));
2352 if (strlen($mod->name) > ($width+5)) {
2353 $mod->name = substr($mod->name, 0, $width).'...';
2355 if (!$mod->visible) {
2356 $mod->name = '('.$mod->name.')';
2358 $class = 'activity '.$mod->modname;
2359 $class .= ($cmid == $mod->id) ? ' selected' : '';
2360 $menu[] = '<li class="'.$class.'">'.
2361 '<img src="'.$OUTPUT->pix_url('icon', $mod->modname) . '" alt="" />'.
2362 '<a href="'.$CFG->wwwroot.'/mod/'.$url.'">'.$mod->name.'</a></li>';
2366 $menu[] = '</ul></li>';
2368 $menu[] = '</ul></li></ul>';
2370 return implode("\n", $menu);
2374 * Prints a grade menu (as part of an existing form) with help
2375 * Showing all possible numerical grades and scales
2377 * @todo Finish documenting this function
2378 * @todo Deprecate: this is only used in a few contrib modules
2381 * @param int $courseid The course ID
2382 * @param string $name
2383 * @param string $current
2384 * @param boolean $includenograde Include those with no grades
2385 * @param boolean $return If set to true returns rather than echo's
2386 * @return string|bool Depending on value of $return
2388 function print_grade_menu($courseid, $name, $current, $includenograde=true, $return=false) {
2390 global $CFG, $OUTPUT;
2393 $strscale = get_string('scale');
2394 $strscales = get_string('scales');
2396 $scales = get_scales_menu($courseid);
2397 foreach ($scales as $i => $scalename) {
2398 $grades[-$i] = $strscale .': '. $scalename;
2400 if ($includenograde) {
2401 $grades[0] = get_string('nograde');
2403 for ($i=100; $i>=1; $i--) {
2406 $output .= html_writer::select($grades, $name, $current, false);
2408 $linkobject = '<span class="helplink"><img class="iconhelp" alt="'.$strscales.'" src="'.$OUTPUT->pix_url('help') . '" /></span>';
2409 $link = new moodle_url('/course/scales.php', array('id'=>$courseid, 'list'=>1));
2410 $action = new popup_action('click', $link->url, 'ratingscales', array('height' => 400, 'width' => 500));
2411 $output .= $OUTPUT->action_link($link, $linkobject, $action, array('title'=>$strscales));
2421 * Print an error to STDOUT and exit with a non-zero code. For commandline scripts.
2422 * Default errorcode is 1.
2424 * Very useful for perl-like error-handling:
2426 * do_somethting() or mdie("Something went wrong");
2428 * @param string $msg Error message
2429 * @param integer $errorcode Error code to emit
2431 function mdie($msg='', $errorcode=1) {
2432 trigger_error($msg);
2437 * Returns html code to be used as help icon of modgrade form element
2439 * Is used as a callback in modgrade setHelpButton()
2441 * @param int $courseid id of the course the scales should be shown from
2442 * @return string to be echoed
2444 function modgradehelpbutton($courseid){
2445 global $CFG, $OUTPUT;
2447 $url = new moodle_url('/course/scales.php', array('id' => $courseid, 'list' => true));
2448 $text = '<span class="helplink"><img alt="' . get_string('scales') . '" class="iconhelp" src="' . $OUTPUT->pix_url('help') . '" /></span>';
2449 $action = new popup_action('click', $link->url, 'ratingscales', array('height' => 400, 'width' => 500));
2451 return $OUTPUT->action_link($url, $text, $action, array('title'=>get_string('newwindow')));
2455 * Print a message and exit.
2457 * @param string $message The message to print in the notice
2458 * @param string $link The link to use for the continue button
2459 * @param object $course A course object
2460 * @return void This function simply exits
2462 function notice ($message, $link='', $course=NULL) {
2463 global $CFG, $SITE, $COURSE, $PAGE, $OUTPUT;
2465 $message = clean_text($message); // In case nasties are in here
2468 echo("!!$message!!\n");
2469 exit(1); // no success
2472 if (!$PAGE->headerprinted) {
2473 //header not yet printed
2474 $PAGE->set_title(get_string('notice'));
2475 echo $OUTPUT->header();
2477 echo $OUTPUT->container_end_all(false);
2480 echo $OUTPUT->box($message, 'generalbox', 'notice');
2481 echo $OUTPUT->continue_button($link);
2483 echo $OUTPUT->footer();
2484 exit(1); // general error code
2488 * Redirects the user to another page, after printing a notice
2490 * This function calls the OUTPUT redirect method, echo's the output
2491 * and then dies to ensure nothing else happens.
2493 * <strong>Good practice:</strong> You should call this method before starting page
2494 * output by using any of the OUTPUT methods.
2496 * @param moodle_url $url A moodle_url to redirect to. Strings are not to be trusted!
2497 * @param string $message The message to display to the user
2498 * @param int $delay The delay before redirecting
2501 function redirect($url, $message='', $delay=-1) {
2502 global $OUTPUT, $PAGE, $SESSION, $CFG;
2504 if (CLI_SCRIPT or AJAX_SCRIPT) {
2505 // this is wrong - developers should not use redirect in these scripts,
2506 // but it should not be very likely
2507 throw new moodle_exception('redirecterrordetected', 'error');
2510 if ($url instanceof moodle_url) {
2511 $url = $url->out(false);
2514 if (!empty($CFG->usesid) && !isset($_COOKIE[session_name()])) {
2515 $url = $SESSION->sid_process_url($url);
2518 if (function_exists('error_get_last')) {
2519 $lasterror = error_get_last();
2521 $debugdisableredirect = defined('DEBUGGING_PRINTED') ||
2522 (!empty($CFG->debugdisplay) && !empty($lasterror) && ($lasterror['type'] & DEBUG_DEVELOPER));
2525 if (!empty($message)) {
2526 if ($delay === -1 || !is_numeric($delay)) {
2529 $message = clean_text($message);
2531 $message = get_string('pageshouldredirect');
2533 // We are going to try to use a HTTP redirect, so we need a full URL.
2534 if (!preg_match('|^[a-z]+:|', $url)) {
2535 // Get host name http://www.wherever.com
2536 $hostpart = preg_replace('|^(.*?[^:/])/.*$|', '$1', $CFG->wwwroot);
2537 if (preg_match('|^/|', $url)) {
2538 // URLs beginning with / are relative to web server root so we just add them in
2539 $url = $hostpart.$url;
2541 // URLs not beginning with / are relative to path of current script, so add that on.
2542 $url = $hostpart.preg_replace('|\?.*$|','',me()).'/../'.$url;
2546 $newurl = preg_replace('|/(?!\.\.)[^/]*/\.\./|', '/', $url);
2547 if ($newurl == $url) {
2555 if (defined('MDL_PERF') || (!empty($CFG->perfdebug) and $CFG->perfdebug > 7)) {
2556 if (defined('MDL_PERFTOLOG') && !function_exists('register_shutdown_function')) {
2557 $perf = get_performance_info();
2558 error_log("PERF: " . $perf['txt']);
2562 $encodedurl = preg_replace("/\&(?![a-zA-Z0-9#]{1,8};)/", "&", $url);
2563 $encodedurl = preg_replace('/^.*href="([^"]*)".*$/', "\\1", clean_text('<a href="'.$encodedurl.'" />'));
2565 if ($delay == 0 && !$debugdisableredirect && !headers_sent()) {
2566 //302 might not work for POST requests, 303 is ignored by obsolete clients.
2567 @header($_SERVER['SERVER_PROTOCOL'] . ' 303 See Other');
2568 @header('Location: '.$url);
2569 echo bootstrap_renderer::plain_redirect_message($encodedurl);
2573 // Include a redirect message, even with a HTTP redirect, because that is recommended practice.
2574 $PAGE->set_pagelayout('embedded'); // No header and footer needed
2575 $CFG->docroot = false; // to prevent the link to moodle docs from being displayed on redirect page.
2576 echo $OUTPUT->redirect_message($encodedurl, $message, $delay, $debugdisableredirect);
2581 * Given an email address, this function will return an obfuscated version of it
2583 * @param string $email The email address to obfuscate
2584 * @return string The obfuscated email address
2586 function obfuscate_email($email) {
2589 $length = strlen($email);
2591 while ($i < $length) {
2592 if (rand(0,2) && $email{$i}!='@') { //MDL-20619 some browsers have problems unobfuscating @
2593 $obfuscated.='%'.dechex(ord($email{$i}));
2595 $obfuscated.=$email{$i};
2603 * This function takes some text and replaces about half of the characters
2604 * with HTML entity equivalents. Return string is obviously longer.
2606 * @param string $plaintext The text to be obfuscated
2607 * @return string The obfuscated text
2609 function obfuscate_text($plaintext) {
2612 $length = strlen($plaintext);
2614 $prev_obfuscated = false;
2615 while ($i < $length) {
2616 $c = ord($plaintext{$i});
2617 $numerical = ($c >= ord('0')) && ($c <= ord('9'));
2618 if ($prev_obfuscated and $numerical ) {
2619 $obfuscated.='&#'.ord($plaintext{$i}).';';
2620 } else if (rand(0,2)) {
2621 $obfuscated.='&#'.ord($plaintext{$i}).';';
2622 $prev_obfuscated = true;
2624 $obfuscated.=$plaintext{$i};
2625 $prev_obfuscated = false;
2633 * This function uses the {@link obfuscate_email()} and {@link obfuscate_text()}
2634 * to generate a fully obfuscated email link, ready to use.
2636 * @param string $email The email address to display
2637 * @param string $label The text to displayed as hyperlink to $email
2638 * @param boolean $dimmed If true then use css class 'dimmed' for hyperlink
2639 * @return string The obfuscated mailto link
2641 function obfuscate_mailto($email, $label='', $dimmed=false) {
2643 if (empty($label)) {
2647 $title = get_string('emaildisable');
2648 $dimmed = ' class="dimmed"';
2653 return sprintf("<a href=\"%s:%s\" $dimmed title=\"$title\">%s</a>",
2654 obfuscate_text('mailto'), obfuscate_email($email),
2655 obfuscate_text($label));
2659 * This function is used to rebuild the <nolink> tag because some formats (PLAIN and WIKI)
2660 * will transform it to html entities
2662 * @param string $text Text to search for nolink tag in
2665 function rebuildnolinktag($text) {
2667 $text = preg_replace('/<(\/*nolink)>/i','<$1>',$text);
2673 * Prints a maintenance message from $CFG->maintenance_message or default if empty
2676 function print_maintenance_message() {
2677 global $CFG, $SITE, $PAGE, $OUTPUT;
2679 $PAGE->set_pagetype('maintenance-message');
2680 $PAGE->set_pagelayout('maintenance');
2681 $PAGE->set_title(strip_tags($SITE->fullname));
2682 $PAGE->set_heading($SITE->fullname);
2683 echo $OUTPUT->header();
2684 echo $OUTPUT->heading(get_string('sitemaintenance', 'admin'));
2685 if (isset($CFG->maintenance_message) and !html_is_blank($CFG->maintenance_message)) {
2686 echo $OUTPUT->box_start('maintenance_message generalbox boxwidthwide boxaligncenter');
2687 echo $CFG->maintenance_message;
2688 echo $OUTPUT->box_end();
2690 echo $OUTPUT->footer();
2695 * Adjust the list of allowed tags based on $CFG->allowobjectembed and user roles (admin)
2701 function adjust_allowed_tags() {
2703 global $CFG, $ALLOWED_TAGS;
2705 if (!empty($CFG->allowobjectembed)) {
2706 $ALLOWED_TAGS .= '<embed><object>';
2711 * A class for tabs, Some code to print tabs
2713 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2714 * @package moodlecore
2726 var $linkedwhenselected;
2729 * A constructor just because I like constructors
2732 * @param string $link
2733 * @param string $text
2734 * @param string $title
2735 * @param bool $linkedwhenselected
2737 function tabobject ($id, $link='', $text='', $title='', $linkedwhenselected=false) {
2739 $this->link = $link;
2740 $this->text = $text;
2741 $this->title = $title ? $title : $text;
2742 $this->linkedwhenselected = $linkedwhenselected;
2749 * Returns a string containing a nested list, suitable for formatting into tabs with CSS.
2752 * @param array $tabrows An array of rows where each row is an array of tab objects
2753 * @param string $selected The id of the selected tab (whatever row it's on)
2754 * @param array $inactive An array of ids of inactive tabs that are not selectable.
2755 * @param array $activated An array of ids of other tabs that are currently activated
2756 * @param bool $return If true output is returned rather then echo'd
2758 function print_tabs($tabrows, $selected=NULL, $inactive=NULL, $activated=NULL, $return=false) {
2761 /// $inactive must be an array
2762 if (!is_array($inactive)) {
2763 $inactive = array();
2766 /// $activated must be an array
2767 if (!is_array($activated)) {
2768 $activated = array();
2771 /// Convert the tab rows into a tree that's easier to process
2772 if (!$tree = convert_tabrows_to_tree($tabrows, $selected, $inactive, $activated)) {
2776 /// Print out the current tree of tabs (this function is recursive)
2778 $output = convert_tree_to_html($tree);
2780 $output = "\n\n".'<div class="tabtree">'.$output.'</div><div class="clearer"> </div>'."\n\n";
2791 * Converts a nested array tree into HTML ul:li [recursive]
2793 * @param array $tree A tree array to convert
2794 * @param int $row Used in identifying the iteration level and in ul classes
2795 * @return string HTML structure
2797 function convert_tree_to_html($tree, $row=0) {
2799 $str = "\n".'<ul class="tabrow'.$row.'">'."\n";
2802 $count = count($tree);
2804 foreach ($tree as $tab) {
2805 $count--; // countdown to zero
2809 if ($first && ($count == 0)) { // Just one in the row
2810 $liclass = 'first last';
2812 } else if ($first) {
2815 } else if ($count == 0) {
2819 if ((empty($tab->subtree)) && (!empty($tab->selected))) {
2820 $liclass .= (empty($liclass)) ? 'onerow' : ' onerow';
2823 if ($tab->inactive || $tab->active || $tab->selected) {
2824 if ($tab->selected) {
2825 $liclass .= (empty($liclass)) ? 'here selected' : ' here selected';
2826 } else if ($tab->active) {
2827 $liclass .= (empty($liclass)) ? 'here active' : ' here active';
2831 $str .= (!empty($liclass)) ? '<li class="'.$liclass.'">' : '<li>';
2833 if ($tab->inactive || $tab->active || ($tab->selected && !$tab->linkedwhenselected)) {
2834 // The a tag is used for styling
2835 $str .= '<a class="nolink"><span>'.$tab->text.'</span></a>';
2837 $str .= '<a href="'.$tab->link.'" title="'.$tab->title.'"><span>'.$tab->text.'</span></a>';
2840 if (!empty($tab->subtree)) {
2841 $str .= convert_tree_to_html($tab->subtree, $row+1);
2842 } else if ($tab->selected) {
2843 $str .= '<div class="tabrow'.($row+1).' empty"> </div>'."\n";
2846 $str .= ' </li>'."\n";
2848 $str .= '</ul>'."\n";
2854 * Convert nested tabrows to a nested array
2856 * @param array $tabrows A [nested] array of tab row objects
2857 * @param string $selected The tabrow to select (by id)
2858 * @param array $inactive An array of tabrow id's to make inactive
2859 * @param array $activated An array of tabrow id's to make active
2860 * @return array The nested array
2862 function convert_tabrows_to_tree($tabrows, $selected, $inactive, $activated) {
2864 /// Work backwards through the rows (bottom to top) collecting the tree as we go.
2866 $tabrows = array_reverse($tabrows);
2870 foreach ($tabrows as $row) {
2873 foreach ($row as $tab) {
2874 $tab->inactive = in_array((string)$tab->id, $inactive);
2875 $tab->active = in_array((string)$tab->id, $activated);
2876 $tab->selected = (string)$tab->id == $selected;
2878 if ($tab->active || $tab->selected) {
2880 $tab->subtree = $subtree;
2892 * Returns the Moodle Docs URL in the users language
2895 * @param string $path the end of the URL.
2896 * @return string The MoodleDocs URL in the user's language. for example {@link http://docs.moodle.org/en/ http://docs.moodle.org/en/$path}
2898 function get_docs_url($path) {
2900 return $CFG->docroot . '/' . current_language() . '/' . $path;
2905 * Standard Debugging Function
2907 * Returns true if the current site debugging settings are equal or above specified level.
2908 * If passed a parameter it will emit a debugging notice similar to trigger_error(). The
2909 * routing of notices is controlled by $CFG->debugdisplay
2912 * 1) debugging('a normal debug notice');
2913 * 2) debugging('something really picky', DEBUG_ALL);
2914 * 3) debugging('annoying debug message only for developers', DEBUG_DEVELOPER);
2915 * 4) if (debugging()) { perform extra debugging operations (do not use print or echo) }
2917 * In code blocks controlled by debugging() (such as example 4)
2918 * any output should be routed via debugging() itself, or the lower-level
2919 * trigger_error() or error_log(). Using echo or print will break XHTML
2920 * JS and HTTP headers.
2922 * It is also possible to define NO_DEBUG_DISPLAY which redirects the message to error_log.
2924 * @uses DEBUG_NORMAL
2925 * @param string $message a message to print
2926 * @param int $level the level at which this debugging statement should show
2927 * @param array $backtrace use different backtrace
2930 function debugging($message = '', $level = DEBUG_NORMAL, $backtrace = null) {
2931 global $CFG, $UNITTEST;
2933 if (empty($CFG->debug) || $CFG->debug < $level) {
2937 if (!isset($CFG->debugdisplay)) {
2938 $CFG->debugdisplay = ini_get_bool('display_errors');
2943 $backtrace = debug_backtrace();
2945 $from = format_backtrace($backtrace, CLI_SCRIPT);
2946 if (!empty($UNITTEST->running)) {
2947 // When the unit tests are running, any call to trigger_error
2948 // is intercepted by the test framework and reported as an exception.
2949 // Therefore, we cannot use trigger_error during unit tests.
2950 // At the same time I do not think we should just discard those messages,
2951 // so displaying them on-screen seems like the only option. (MDL-20398)
2952 echo '<div class="notifytiny">' . $message . $from . '</div>';
2954 } else if (NO_DEBUG_DISPLAY) {
2955 // script does not want any errors or debugging in output,
2956 // we send the info to error log instead
2957 error_log('Debugging: ' . $message . $from);
2959 } else if ($CFG->debugdisplay) {
2960 if (!defined('DEBUGGING_PRINTED')) {
2961 define('DEBUGGING_PRINTED', 1); // indicates we have printed something
2963 echo '<div class="notifytiny">' . $message . $from . '</div>';
2966 trigger_error($message . $from, E_USER_NOTICE);
2973 * Outputs a HTML comment to the browser. This is used for those hard-to-debug
2974 * pages that use bits from many different files in very confusing ways (e.g. blocks).
2976 * <code>print_location_comment(__FILE__, __LINE__);</code>
2978 * @param string $file
2979 * @param integer $line
2980 * @param boolean $return Whether to return or print the comment
2981 * @return string|void Void unless true given as third parameter
2983 function print_location_comment($file, $line, $return = false)
2986 return "<!-- $file at line $line -->\n";
2988 echo "<!-- $file at line $line -->\n";
2994 * @return boolean true if the current language is right-to-left (Hebrew, Arabic etc)
2996 function right_to_left() {
2997 return (get_string('thisdirection', 'langconfig') === 'rtl');
3002 * Returns swapped left<=>right if in RTL environment.
3003 * part of RTL support
3005 * @param string $align align to check
3008 function fix_align_rtl($align) {
3009 if (!right_to_left()) {
3012 if ($align=='left') { return 'right'; }
3013 if ($align=='right') { return 'left'; }
3019 * Returns true if the page is displayed in a popup window.
3020 * Gets the information from the URL parameter inpopup.
3022 * @todo Use a central function to create the popup calls all over Moodle and
3023 * In the moment only works with resources and probably questions.
3027 function is_in_popup() {
3028 $inpopup = optional_param('inpopup', '', PARAM_BOOL);
3034 * To use this class.
3036 * - call create (or use the 3rd param to the constructor)
3037 * - call update or update_full repeatedly
3039 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3040 * @package moodlecore
3042 class progress_bar {
3043 /** @var string html id */
3052 private $time_start;
3053 private $minimum_time = 2; //min time between updates.
3057 * @param string $html_id
3059 * @param bool $autostart Default to false
3061 public function __construct($html_id = '', $width = 500, $autostart = false){
3062 if (!empty($html_id)) {
3063 $this->html_id = $html_id;
3065 $this->html_id = uniqid();
3067 $this->width = $width;
3074 * Create a new progress bar, this function will output html.
3076 * @return void Echo's output
3078 public function create(){
3080 $this->lastcall->pt = 0;
3081 $this->lastcall->time = microtime(true);
3083 return; // temporary solution for cli scripts
3086 <div style="text-align:center;width:{$this->width}px;clear:both;padding:0;margin:0 auto;">
3087 <h2 id="status_{$this->html_id}" style="text-align: center;margin:0 auto"></h2>
3088 <p id="time_{$this->html_id}"></p>
3089 <div id="bar_{$this->html_id}" style="border-style:solid;border-width:1px;width:500px;height:50px;">
3090 <div id="progress_{$this->html_id}"
3091 style="text-align:center;background:#FFCC66;width:4px;border:1px
3092 solid gray;height:38px; padding-top:10px;"> <span id="pt_{$this->html_id}"></span>
3101 * Update the progress bar
3103 * @param int $percent from 1-100
3104 * @param string $msg
3106 * @return void Echo's output
3108 private function _update($percent, $msg, $es){
3110 if(empty($this->time_start)){
3111 $this->time_start = microtime(true);
3113 $this->percent = $percent;
3114 $this->lastcall->time = microtime(true);
3115 $this->lastcall->pt = $percent;
3116 $w = $this->percent * $this->width;
3118 return; // temporary solution for cli scripts
3123 echo html_writer::script(js_writer::function_call('update_progress_bar', Array($this->html_id, $w, $this->percent, $msg, $es)));
3129 * @param int $curtime the time call this function
3130 * @param int $percent from 1-100
3131 * @return mixed Null, or int
3133 private function estimate($curtime, $pt){
3134 $consume = $curtime - $this->time_start;
3135 $one = $curtime - $this->lastcall->time;
3136 $this->percent = $pt;
3137 $percent = $pt - $this->lastcall->pt;
3138 if ($percent != 0) {
3139 $left = ($one / $percent) - $consume;
3150 * Update progress bar according percent
3152 * @param int $percent from 1-100
3153 * @param string $msg the message needed to be shown
3155 public function update_full($percent, $msg){
3156 $percent = max(min($percent, 100), 0);
3157 if ($percent != 100 && ($this->lastcall->time + $this->minimum_time) > microtime(true)){
3160 $this->_update($percent/100, $msg);
3163 * Update progress bar according the number of tasks
3165 * @param int $cur current task number
3166 * @param int $total total task number
3167 * @param string $msg message
3169 public function update($cur, $total, $msg){
3170 $cur = max($cur, 0);
3171 if ($cur >= $total){
3174 $percent = $cur / $total;
3177 if ($percent != 1 && ($this->lastcall->time + $this->minimum_time) > microtime(true)){
3181 $es = $this->estimate(microtime(true), $percent);
3182 $this->_update($percent, $msg, $es);
3185 * Restart the progress bar.
3187 public function restart(){
3189 $this->lastcall = new stdClass;
3190 $this->lastcall->pt = 0;
3191 $this->lastcall->time = microtime(true);
3192 $this->time_start = 0;
3197 * Use this class from long operations where you want to output occasional information about
3198 * what is going on, but don't know if, or in what format, the output should be.
3200 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3201 * @package moodlecore
3203 abstract class progress_trace {
3205 * Ouput an progress message in whatever format.
3206 * @param string $message the message to output.
3207 * @param integer $depth indent depth for this message.
3209 abstract public function output($message, $depth = 0);
3212 * Called when the processing is finished.
3214 public function finished() {
3219 * This subclass of progress_trace does not ouput anything.
3221 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3222 * @package moodlecore
3224 class null_progress_trace extends progress_trace {
3228 * @param string $message
3230 * @return void Does Nothing
3232 public function output($message, $depth = 0) {
3237 * This subclass of progress_trace outputs to plain text.
3239 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3240 * @package moodlecore
3242 class text_progress_trace extends progress_trace {
3244 * Output the trace message
3246 * @param string $message
3248 * @return void Output is echo'd
3250 public function output($message, $depth = 0) {
3251 echo str_repeat(' ', $depth), $message, "\n";
3257 * This subclass of progress_trace outputs as HTML.
3259 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3260 * @package moodlecore
3262 class html_progress_trace extends progress_trace {
3264 * Output the trace message
3266 * @param string $message
3268 * @return void Output is echo'd
3270 public function output($message, $depth = 0) {
3271 echo '<p>', str_repeat('  ', $depth), htmlspecialchars($message), "</p>\n";
3277 * HTML List Progress Tree
3279 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3280 * @package moodlecore
3282 class html_list_progress_trace extends progress_trace {
3284 protected $currentdepth = -1;
3289 * @param string $message The message to display
3291 * @return void Output is echoed
3293 public function output($message, $depth = 0) {
3295 while ($this->currentdepth > $depth) {
3296 echo "</li>\n</ul>\n";
3297 $this->currentdepth -= 1;
3298 if ($this->currentdepth == $depth) {
3303 while ($this->currentdepth < $depth) {
3305 $this->currentdepth += 1;
3311 echo htmlspecialchars($message);
3316 * Called when the processing is finished.
3318 public function finished() {
3319 while ($this->currentdepth >= 0) {
3320 echo "</li>\n</ul>\n";
3321 $this->currentdepth -= 1;
3327 * Returns a localized sentence in the current language summarizing the current password policy
3329 * @todo this should be handled by a function/method in the language pack library once we have a support for it
3333 function print_password_policy() {
3337 if (!empty($CFG->passwordpolicy)) {
3338 $messages = array();
3339 $messages[] = get_string('informminpasswordlength', 'auth', $CFG->minpasswordlength);
3340 if (!empty($CFG->minpassworddigits)) {
3341 $messages[] = get_string('informminpassworddigits', 'auth', $CFG->minpassworddigits);
3343 if (!empty($CFG->minpasswordlower)) {
3344 $messages[] = get_string('informminpasswordlower', 'auth', $CFG->minpasswordlower);
3346 if (!empty($CFG->minpasswordupper)) {
3347 $messages[] = get_string('informminpasswordupper', 'auth', $CFG->minpasswordupper);
3349 if (!empty($CFG->minpasswordnonalphanum)) {
3350 $messages[] = get_string('informminpasswordnonalphanum', 'auth', $CFG->minpasswordnonalphanum);
3353 $messages = join(', ', $messages); // this is ugly but we do not have anything better yet...
3354 $message = get_string('informpasswordpolicy', 'auth', $messages);
3359 function create_ufo_inline($id, $args) {
3361 // must not use $PAGE, $THEME, $COURSE etc. because the result is cached!
3362 // unfortunately this ufo.js can not be cached properly because we do not have access to current $CFG either
3363 $jsoutput = html_writer::script('', $CFG->wwwroot.'/lib/ufo.js');
3364 $jsoutput .= html_writer::script(js_writer::function_call('M.util.create_UFO_object', array($id, $args)));