2 // This file is part of Moodle - http://moodle.org/
4 // Moodle is free software: you can redistribute it and/or modify
5 // it under the terms of the GNU General Public License as published by
6 // the Free Software Foundation, either version 3 of the License, or
7 // (at your option) any later version.
9 // Moodle is distributed in the hope that it will be useful,
10 // but WITHOUT ANY WARRANTY; without even the implied warranty of
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 // GNU General Public License for more details.
14 // You should have received a copy of the GNU General Public License
15 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
18 * Library of functions for web output
20 * Library of all general-purpose Moodle PHP functions and constants
21 * that produce HTML output
23 * Other main libraries:
24 * - datalib.php - functions that access the database.
25 * - 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
33 defined('MOODLE_INTERNAL') ||
die();
37 // Define text formatting types ... eventually we can add Wiki, BBcode etc.
40 * Does all sorts of transformations and filtering.
42 define('FORMAT_MOODLE', '0');
45 * Plain HTML (with some tags stripped).
47 define('FORMAT_HTML', '1');
50 * Plain text (even tags are printed in full).
52 define('FORMAT_PLAIN', '2');
55 * Wiki-formatted text.
56 * Deprecated: left here just to note that '3' is not used (at the moment)
57 * and to catch any latent wiki-like text (which generates an error)
58 * @deprecated since 2005!
60 define('FORMAT_WIKI', '3');
63 * Markdown-formatted text http://daringfireball.net/projects/markdown/
65 define('FORMAT_MARKDOWN', '4');
68 * A moodle_url comparison using this flag will return true if the base URLs match, params are ignored.
70 define('URL_MATCH_BASE', 0);
73 * A moodle_url comparison using this flag will return true if the base URLs match and the params of url1 are part of url2.
75 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);
85 * Add quotes to HTML characters.
87 * Returns $var with HTML characters (like "<", ">", etc.) properly quoted.
88 * This function is very similar to {@link p()}
90 * @param string $var the string potentially containing HTML characters
99 // When we move to PHP 5.4 as a minimum version, change ENT_QUOTES on the
100 // next line to ENT_QUOTES | ENT_HTML5 | ENT_SUBSTITUTE, and remove the
101 // 'UTF-8' argument. Both bring a speed-increase.
102 return preg_replace('/&#(\d+|x[0-9a-f]+);/i', '&#$1;', htmlspecialchars($var, ENT_QUOTES
, 'UTF-8'));
106 * Add quotes to HTML characters.
108 * Prints $var with HTML characters (like "<", ">", etc.) properly quoted.
109 * This function simply calls {@link s()}
112 * @todo Remove obsolete param $obsolete if not used anywhere
114 * @param string $var the string potentially containing HTML characters
115 * @param boolean $obsolete no longer used.
118 function p($var, $obsolete = false) {
119 echo s($var, $obsolete);
123 * Does proper javascript quoting.
125 * Do not use addslashes anymore, because it does not work when magic_quotes_sybase is enabled.
127 * @param mixed $var String, Array, or Object to add slashes to
128 * @return mixed quoted result
130 function addslashes_js($var) {
131 if (is_string($var)) {
132 $var = str_replace('\\', '\\\\', $var);
133 $var = str_replace(array('\'', '"', "\n", "\r", "\0"), array('\\\'', '\\"', '\\n', '\\r', '\\0'), $var);
134 $var = str_replace('</', '<\/', $var); // XHTML compliance.
135 } else if (is_array($var)) {
136 $var = array_map('addslashes_js', $var);
137 } else if (is_object($var)) {
138 $a = get_object_vars($var);
139 foreach ($a as $key => $value) {
140 $a[$key] = addslashes_js($value);
148 * Remove query string from url.
150 * Takes in a URL and returns it without the querystring portion.
152 * @param string $url the url which may have a query string attached.
153 * @return string The remaining URL.
155 function strip_querystring($url) {
157 if ($commapos = strpos($url, '?')) {
158 return substr($url, 0, $commapos);
165 * Returns the URL of the HTTP_REFERER, less the querystring portion if required.
167 * @param boolean $stripquery if true, also removes the query part of the url.
168 * @return string The resulting referer or empty string.
170 function get_referer($stripquery=true) {
171 if (isset($_SERVER['HTTP_REFERER'])) {
173 return strip_querystring($_SERVER['HTTP_REFERER']);
175 return $_SERVER['HTTP_REFERER'];
183 * Returns the name of the current script, WITH the querystring portion.
185 * This function is necessary because PHP_SELF and REQUEST_URI and SCRIPT_NAME
186 * return different things depending on a lot of things like your OS, Web
187 * server, and the way PHP is compiled (ie. as a CGI, module, ISAPI, etc.)
188 * <b>NOTE:</b> This function returns false if the global variables needed are not set.
190 * @return mixed String or false if the global variables needed are not set.
198 * Guesses the full URL of the current script.
200 * This function is using $PAGE->url, but may fall back to $FULLME which
201 * is constructed from PHP_SELF and REQUEST_URI or SCRIPT_NAME
203 * @return mixed full page URL string or false if unknown
205 function qualified_me() {
206 global $FULLME, $PAGE, $CFG;
208 if (isset($PAGE) and $PAGE->has_set_url()) {
209 // This is the only recommended way to find out current page.
210 return $PAGE->url
->out(false);
213 if ($FULLME === null) {
214 // CLI script most probably.
217 if (!empty($CFG->sslproxy
)) {
218 // Return only https links when using SSL proxy.
219 return preg_replace('/^http:/', 'https:', $FULLME, 1);
227 * Class for creating and manipulating urls.
229 * It can be used in moodle pages where config.php has been included without any further includes.
231 * It is useful for manipulating urls with long lists of params.
232 * One situation where it will be useful is a page which links to itself to perform various actions
233 * and / or to process form data. A moodle_url object :
234 * can be created for a page to refer to itself with all the proper get params being passed from page call to
235 * page call and methods can be used to output a url including all the params, optionally adding and overriding
236 * params and can also be used to
237 * - output the url without any get params
238 * - and output the params as hidden fields to be output within a form
240 * @copyright 2007 jamiesensei
241 * @link http://docs.moodle.org/dev/lib/weblib.php_moodle_url See short write up here
242 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
248 * Scheme, ex.: http, https
251 protected $scheme = '';
257 protected $host = '';
260 * Port number, empty means default 80 or 443 in case of http.
263 protected $port = '';
266 * Username for http auth.
269 protected $user = '';
272 * Password for http auth.
275 protected $pass = '';
281 protected $path = '';
284 * Optional slash argument value.
287 protected $slashargument = '';
290 * Anchor, may be also empty, null means none.
293 protected $anchor = null;
296 * Url parameters as associative array.
299 protected $params = array();
302 * Create new instance of moodle_url.
304 * @param moodle_url|string $url - moodle_url means make a copy of another
305 * moodle_url and change parameters, string means full url or shortened
306 * form (ex.: '/course/view.php'). It is strongly encouraged to not include
307 * query string because it may result in double encoded values. Use the
308 * $params instead. For admin URLs, just use /admin/script.php, this
309 * class takes care of the $CFG->admin issue.
310 * @param array $params these params override current params or add new
311 * @param string $anchor The anchor to use as part of the URL if there is one.
312 * @throws moodle_exception
314 public function __construct($url, array $params = null, $anchor = null) {
317 if ($url instanceof moodle_url
) {
318 $this->scheme
= $url->scheme
;
319 $this->host
= $url->host
;
320 $this->port
= $url->port
;
321 $this->user
= $url->user
;
322 $this->pass
= $url->pass
;
323 $this->path
= $url->path
;
324 $this->slashargument
= $url->slashargument
;
325 $this->params
= $url->params
;
326 $this->anchor
= $url->anchor
;
329 // Detect if anchor used.
330 $apos = strpos($url, '#');
331 if ($apos !== false) {
332 $anchor = substr($url, $apos);
333 $anchor = ltrim($anchor, '#');
334 $this->set_anchor($anchor);
335 $url = substr($url, 0, $apos);
338 // Normalise shortened form of our url ex.: '/course/view.php'.
339 if (strpos($url, '/') === 0) {
340 // We must not use httpswwwroot here, because it might be url of other page,
341 // devs have to use httpswwwroot explicitly when creating new moodle_url.
342 $url = $CFG->wwwroot
.$url;
345 // Now fix the admin links if needed, no need to mess with httpswwwroot.
346 if ($CFG->admin
!== 'admin') {
347 if (strpos($url, "$CFG->wwwroot/admin/") === 0) {
348 $url = str_replace("$CFG->wwwroot/admin/", "$CFG->wwwroot/$CFG->admin/", $url);
353 $parts = parse_url($url);
354 if ($parts === false) {
355 throw new moodle_exception('invalidurl');
357 if (isset($parts['query'])) {
358 // Note: the values may not be correctly decoded, url parameters should be always passed as array.
359 parse_str(str_replace('&', '&', $parts['query']), $this->params
);
361 unset($parts['query']);
362 foreach ($parts as $key => $value) {
363 $this->$key = $value;
366 // Detect slashargument value from path - we do not support directory names ending with .php.
367 $pos = strpos($this->path
, '.php/');
368 if ($pos !== false) {
369 $this->slashargument
= substr($this->path
, $pos +
4);
370 $this->path
= substr($this->path
, 0, $pos +
4);
374 $this->params($params);
375 if ($anchor !== null) {
376 $this->anchor
= (string)$anchor;
381 * Add an array of params to the params for this url.
383 * The added params override existing ones if they have the same name.
385 * @param array $params Defaults to null. If null then returns all params.
386 * @return array Array of Params for url.
387 * @throws coding_exception
389 public function params(array $params = null) {
390 $params = (array)$params;
392 foreach ($params as $key => $value) {
394 throw new coding_exception('Url parameters can not have numeric keys!');
396 if (!is_string($value)) {
397 if (is_array($value)) {
398 throw new coding_exception('Url parameters values can not be arrays!');
400 if (is_object($value) and !method_exists($value, '__toString')) {
401 throw new coding_exception('Url parameters values can not be objects, unless __toString() is defined!');
404 $this->params
[$key] = (string)$value;
406 return $this->params
;
410 * Remove all params if no arguments passed.
411 * Remove selected params if arguments are passed.
413 * Can be called as either remove_params('param1', 'param2')
414 * or remove_params(array('param1', 'param2')).
416 * @param string[]|string $params,... either an array of param names, or 1..n string params to remove as args.
417 * @return array url parameters
419 public function remove_params($params = null) {
420 if (!is_array($params)) {
421 $params = func_get_args();
423 foreach ($params as $param) {
424 unset($this->params
[$param]);
426 return $this->params
;
430 * Remove all url parameters.
432 * @todo remove the unused param.
433 * @param array $params Unused param
436 public function remove_all_params($params = null) {
437 $this->params
= array();
438 $this->slashargument
= '';
442 * Add a param to the params for this url.
444 * The added param overrides existing one if they have the same name.
446 * @param string $paramname name
447 * @param string $newvalue Param value. If new value specified current value is overriden or parameter is added
448 * @return mixed string parameter value, null if parameter does not exist
450 public function param($paramname, $newvalue = '') {
451 if (func_num_args() > 1) {
453 $this->params(array($paramname => $newvalue));
455 if (isset($this->params
[$paramname])) {
456 return $this->params
[$paramname];
463 * Merges parameters and validates them
465 * @param array $overrideparams
466 * @return array merged parameters
467 * @throws coding_exception
469 protected function merge_overrideparams(array $overrideparams = null) {
470 $overrideparams = (array)$overrideparams;
471 $params = $this->params
;
472 foreach ($overrideparams as $key => $value) {
474 throw new coding_exception('Overridden parameters can not have numeric keys!');
476 if (is_array($value)) {
477 throw new coding_exception('Overridden parameters values can not be arrays!');
479 if (is_object($value) and !method_exists($value, '__toString')) {
480 throw new coding_exception('Overridden parameters values can not be objects, unless __toString() is defined!');
482 $params[$key] = (string)$value;
488 * Get the params as as a query string.
490 * This method should not be used outside of this method.
492 * @param bool $escaped Use & as params separator instead of plain &
493 * @param array $overrideparams params to add to the output params, these
494 * override existing ones with the same name.
495 * @return string query string that can be added to a url.
497 public function get_query_string($escaped = true, array $overrideparams = null) {
499 if ($overrideparams !== null) {
500 $params = $this->merge_overrideparams($overrideparams);
502 $params = $this->params
;
504 foreach ($params as $key => $val) {
505 if (is_array($val)) {
506 foreach ($val as $index => $value) {
507 $arr[] = rawurlencode($key.'['.$index.']')."=".rawurlencode($value);
510 if (isset($val) && $val !== '') {
511 $arr[] = rawurlencode($key)."=".rawurlencode($val);
513 $arr[] = rawurlencode($key);
518 return implode('&', $arr);
520 return implode('&', $arr);
525 * Shortcut for printing of encoded URL.
529 public function __toString() {
530 return $this->out(true);
536 * If you use the returned URL in HTML code, you want the escaped ampersands. If you use
537 * the returned URL in HTTP headers, you want $escaped=false.
539 * @param bool $escaped Use & as params separator instead of plain &
540 * @param array $overrideparams params to add to the output url, these override existing ones with the same name.
541 * @return string Resulting URL
543 public function out($escaped = true, array $overrideparams = null) {
544 if (!is_bool($escaped)) {
545 debugging('Escape parameter must be of type boolean, '.gettype($escaped).' given instead.');
548 $uri = $this->out_omit_querystring().$this->slashargument
;
550 $querystring = $this->get_query_string($escaped, $overrideparams);
551 if ($querystring !== '') {
552 $uri .= '?' . $querystring;
554 if (!is_null($this->anchor
)) {
555 $uri .= '#'.$this->anchor
;
562 * Returns url without parameters, everything before '?'.
564 * @param bool $includeanchor if {@link self::anchor} is defined, should it be returned?
567 public function out_omit_querystring($includeanchor = false) {
569 $uri = $this->scheme ?
$this->scheme
.':'.((strtolower($this->scheme
) == 'mailto') ?
'':'//'): '';
570 $uri .= $this->user ?
$this->user
.($this->pass?
':'.$this->pass
:'').'@':'';
571 $uri .= $this->host ?
$this->host
: '';
572 $uri .= $this->port ?
':'.$this->port
: '';
573 $uri .= $this->path ?
$this->path
: '';
574 if ($includeanchor and !is_null($this->anchor
)) {
575 $uri .= '#' . $this->anchor
;
582 * Compares this moodle_url with another.
584 * See documentation of constants for an explanation of the comparison flags.
586 * @param moodle_url $url The moodle_url object to compare
587 * @param int $matchtype The type of comparison (URL_MATCH_BASE, URL_MATCH_PARAMS, URL_MATCH_EXACT)
590 public function compare(moodle_url
$url, $matchtype = URL_MATCH_EXACT
) {
592 $baseself = $this->out_omit_querystring();
593 $baseother = $url->out_omit_querystring();
595 // Append index.php if there is no specific file.
596 if (substr($baseself, -1) == '/') {
597 $baseself .= 'index.php';
599 if (substr($baseother, -1) == '/') {
600 $baseother .= 'index.php';
603 // Compare the two base URLs.
604 if ($baseself != $baseother) {
608 if ($matchtype == URL_MATCH_BASE
) {
612 $urlparams = $url->params();
613 foreach ($this->params() as $param => $value) {
614 if ($param == 'sesskey') {
617 if (!array_key_exists($param, $urlparams) ||
$urlparams[$param] != $value) {
622 if ($matchtype == URL_MATCH_PARAMS
) {
626 foreach ($urlparams as $param => $value) {
627 if ($param == 'sesskey') {
630 if (!array_key_exists($param, $this->params()) ||
$this->param($param) != $value) {
635 if ($url->anchor
!== $this->anchor
) {
643 * Sets the anchor for the URI (the bit after the hash)
645 * @param string $anchor null means remove previous
647 public function set_anchor($anchor) {
648 if (is_null($anchor)) {
650 $this->anchor
= null;
651 } else if ($anchor === '') {
652 // Special case, used as empty link.
654 } else if (preg_match('|[a-zA-Z\_\:][a-zA-Z0-9\_\-\.\:]*|', $anchor)) {
655 // Match the anchor against the NMTOKEN spec.
656 $this->anchor
= $anchor;
658 // Bad luck, no valid anchor found.
659 $this->anchor
= null;
664 * Sets the url slashargument value.
666 * @param string $path usually file path
667 * @param string $parameter name of page parameter if slasharguments not supported
668 * @param bool $supported usually null, then it depends on $CFG->slasharguments, use true or false for other servers
671 public function set_slashargument($path, $parameter = 'file', $supported = null) {
673 if (is_null($supported)) {
674 $supported = $CFG->slasharguments
;
678 $parts = explode('/', $path);
679 $parts = array_map('rawurlencode', $parts);
680 $path = implode('/', $parts);
681 $this->slashargument
= $path;
682 unset($this->params
[$parameter]);
685 $this->slashargument
= '';
686 $this->params
[$parameter] = $path;
690 // Static factory methods.
693 * General moodle file url.
695 * @param string $urlbase the script serving the file
696 * @param string $path
697 * @param bool $forcedownload
700 public static function make_file_url($urlbase, $path, $forcedownload = false) {
702 if ($forcedownload) {
703 $params['forcedownload'] = 1;
706 $url = new moodle_url($urlbase, $params);
707 $url->set_slashargument($path);
712 * Factory method for creation of url pointing to plugin file.
714 * Please note this method can be used only from the plugins to
715 * create urls of own files, it must not be used outside of plugins!
717 * @param int $contextid
718 * @param string $component
719 * @param string $area
721 * @param string $pathname
722 * @param string $filename
723 * @param bool $forcedownload
726 public static function make_pluginfile_url($contextid, $component, $area, $itemid, $pathname, $filename,
727 $forcedownload = false) {
729 $urlbase = "$CFG->httpswwwroot/pluginfile.php";
730 if ($itemid === null) {
731 return self
::make_file_url($urlbase, "/$contextid/$component/$area".$pathname.$filename, $forcedownload);
733 return self
::make_file_url($urlbase, "/$contextid/$component/$area/$itemid".$pathname.$filename, $forcedownload);
738 * Factory method for creation of url pointing to draft file of current user.
740 * @param int $draftid draft item id
741 * @param string $pathname
742 * @param string $filename
743 * @param bool $forcedownload
746 public static function make_draftfile_url($draftid, $pathname, $filename, $forcedownload = false) {
748 $urlbase = "$CFG->httpswwwroot/draftfile.php";
749 $context = context_user
::instance($USER->id
);
751 return self
::make_file_url($urlbase, "/$context->id/user/draft/$draftid".$pathname.$filename, $forcedownload);
755 * Factory method for creating of links to legacy course files.
757 * @param int $courseid
758 * @param string $filepath
759 * @param bool $forcedownload
762 public static function make_legacyfile_url($courseid, $filepath, $forcedownload = false) {
765 $urlbase = "$CFG->wwwroot/file.php";
766 return self
::make_file_url($urlbase, '/'.$courseid.'/'.$filepath, $forcedownload);
770 * Returns URL a relative path from $CFG->wwwroot
772 * Can be used for passing around urls with the wwwroot stripped
774 * @param boolean $escaped Use & as params separator instead of plain &
775 * @param array $overrideparams params to add to the output url, these override existing ones with the same name.
776 * @return string Resulting URL
777 * @throws coding_exception if called on a non-local url
779 public function out_as_local_url($escaped = true, array $overrideparams = null) {
782 $url = $this->out($escaped, $overrideparams);
783 $httpswwwroot = str_replace("http://", "https://", $CFG->wwwroot
);
785 // Url should be equal to wwwroot or httpswwwroot. If not then throw exception.
786 if (($url === $CFG->wwwroot
) ||
(strpos($url, $CFG->wwwroot
.'/') === 0)) {
787 $localurl = substr($url, strlen($CFG->wwwroot
));
788 return !empty($localurl) ?
$localurl : '';
789 } else if (($url === $httpswwwroot) ||
(strpos($url, $httpswwwroot.'/') === 0)) {
790 $localurl = substr($url, strlen($httpswwwroot));
791 return !empty($localurl) ?
$localurl : '';
793 throw new coding_exception('out_as_local_url called on a non-local URL');
798 * Returns the 'path' portion of a URL. For example, if the URL is
799 * http://www.example.org:447/my/file/is/here.txt?really=1 then this will
800 * return '/my/file/is/here.txt'.
802 * By default the path includes slash-arguments (for example,
803 * '/myfile.php/extra/arguments') so it is what you would expect from a
804 * URL path. If you don't want this behaviour, you can opt to exclude the
805 * slash arguments. (Be careful: if the $CFG variable slasharguments is
806 * disabled, these URLs will have a different format and you may need to
807 * look at the 'file' parameter too.)
809 * @param bool $includeslashargument If true, includes slash arguments
810 * @return string Path of URL
812 public function get_path($includeslashargument = true) {
813 return $this->path
. ($includeslashargument ?
$this->slashargument
: '');
817 * Returns a given parameter value from the URL.
819 * @param string $name Name of parameter
820 * @return string Value of parameter or null if not set
822 public function get_param($name) {
823 if (array_key_exists($name, $this->params
)) {
824 return $this->params
[$name];
831 * Returns the 'scheme' portion of a URL. For example, if the URL is
832 * http://www.example.org:447/my/file/is/here.txt?really=1 then this will
833 * return 'http' (without the colon).
835 * @return string Scheme of the URL.
837 public function get_scheme() {
838 return $this->scheme
;
842 * Returns the 'host' portion of a URL. For example, if the URL is
843 * http://www.example.org:447/my/file/is/here.txt?really=1 then this will
844 * return 'www.example.org'.
846 * @return string Host of the URL.
848 public function get_host() {
853 * Returns the 'port' portion of a URL. For example, if the URL is
854 * http://www.example.org:447/my/file/is/here.txt?really=1 then this will
857 * @return string Port of the URL.
859 public function get_port() {
865 * Determine if there is data waiting to be processed from a form
867 * Used on most forms in Moodle to check for data
868 * Returns the data as an object, if it's found.
869 * This object can be used in foreach loops without
870 * casting because it's cast to (array) automatically
872 * Checks that submitted POST data exists and returns it as object.
874 * @return mixed false or object
876 function data_submitted() {
881 return (object)fix_utf8($_POST);
886 * Given some normal text this function will break up any
887 * long words to a given size by inserting the given character
889 * It's multibyte savvy and doesn't change anything inside html tags.
891 * @param string $string the string to be modified
892 * @param int $maxsize maximum length of the string to be returned
893 * @param string $cutchar the string used to represent word breaks
896 function break_up_long_words($string, $maxsize=20, $cutchar=' ') {
898 // First of all, save all the tags inside the text to skip them.
900 filter_save_tags($string, $tags);
902 // Process the string adding the cut when necessary.
904 $length = core_text
::strlen($string);
907 for ($i=0; $i<$length; $i++
) {
908 $char = core_text
::substr($string, $i, 1);
909 if ($char == ' ' or $char == "\t" or $char == "\n" or $char == "\r" or $char == "<" or $char == ">") {
913 if ($wordlength > $maxsize) {
921 // Finally load the tags back again.
923 $output = str_replace(array_keys($tags), $tags, $output);
930 * Try and close the current window using JavaScript, either immediately, or after a delay.
932 * Echo's out the resulting XHTML & javascript
934 * @param integer $delay a delay in seconds before closing the window. Default 0.
935 * @param boolean $reloadopener if true, we will see if this window was a pop-up, and try
936 * to reload the parent window before this one closes.
938 function close_window($delay = 0, $reloadopener = false) {
939 global $PAGE, $OUTPUT;
941 if (!$PAGE->headerprinted
) {
942 $PAGE->set_title(get_string('closewindow'));
943 echo $OUTPUT->header();
945 $OUTPUT->container_end_all(false);
949 // Trigger the reload immediately, even if the reload is after a delay.
950 $PAGE->requires
->js_function_call('window.opener.location.reload', array(true));
952 $OUTPUT->notification(get_string('windowclosing'), 'notifysuccess');
954 $PAGE->requires
->js_function_call('close_window', array(new stdClass()), false, $delay);
956 echo $OUTPUT->footer();
961 * Returns a string containing a link to the user documentation for the current page.
963 * Also contains an icon by default. Shown to teachers and admin only.
965 * @param string $text The text to be displayed for the link
966 * @return string The link to user documentation for this current page
968 function page_doc_link($text='') {
969 global $OUTPUT, $PAGE;
970 $path = page_get_doc_link_path($PAGE);
974 return $OUTPUT->doc_link($path, $text);
978 * Returns the path to use when constructing a link to the docs.
980 * @since Moodle 2.5.1 2.6
981 * @param moodle_page $page
984 function page_get_doc_link_path(moodle_page
$page) {
987 if (empty($CFG->docroot
) ||
during_initial_install()) {
990 if (!has_capability('moodle/site:doclinks', $page->context
)) {
994 $path = $page->docspath
;
1003 * Validates an email to make sure it makes sense.
1005 * @param string $address The email address to validate.
1008 function validate_email($address) {
1010 return (preg_match('#^[-!\#$%&\'*+\\/0-9=?A-Z^_`a-z{|}~]+'.
1011 '(\.[-!\#$%&\'*+\\/0-9=?A-Z^_`a-z{|}~]+)*'.
1013 '[-!\#$%&\'*+\\/0-9=?A-Z^_`a-z{|}~]+\.'.
1014 '[-!\#$%&\'*+\\./0-9=?A-Z^_`a-z{|}~]+$#',
1019 * Extracts file argument either from file parameter or PATH_INFO
1021 * Note: $scriptname parameter is not needed anymore
1023 * @return string file path (only safe characters)
1025 function get_file_argument() {
1028 $relativepath = optional_param('file', false, PARAM_PATH
);
1030 if ($relativepath !== false and $relativepath !== '') {
1031 return $relativepath;
1033 $relativepath = false;
1035 // Then try extract file from the slasharguments.
1036 if (stripos($_SERVER['SERVER_SOFTWARE'], 'iis') !== false) {
1037 // NOTE: IIS tends to convert all file paths to single byte DOS encoding,
1038 // we can not use other methods because they break unicode chars,
1039 // the only ways are to use URL rewriting
1041 // to properly set the 'FastCGIUtf8ServerVariables' registry key.
1042 if (isset($_SERVER['PATH_INFO']) and $_SERVER['PATH_INFO'] !== '') {
1043 // Check that PATH_INFO works == must not contain the script name.
1044 if (strpos($_SERVER['PATH_INFO'], $SCRIPT) === false) {
1045 $relativepath = clean_param(urldecode($_SERVER['PATH_INFO']), PARAM_PATH
);
1049 // All other apache-like servers depend on PATH_INFO.
1050 if (isset($_SERVER['PATH_INFO'])) {
1051 if (isset($_SERVER['SCRIPT_NAME']) and strpos($_SERVER['PATH_INFO'], $_SERVER['SCRIPT_NAME']) === 0) {
1052 $relativepath = substr($_SERVER['PATH_INFO'], strlen($_SERVER['SCRIPT_NAME']));
1054 $relativepath = $_SERVER['PATH_INFO'];
1056 $relativepath = clean_param($relativepath, PARAM_PATH
);
1060 return $relativepath;
1064 * Just returns an array of text formats suitable for a popup menu
1068 function format_text_menu() {
1069 return array (FORMAT_MOODLE
=> get_string('formattext'),
1070 FORMAT_HTML
=> get_string('formathtml'),
1071 FORMAT_PLAIN
=> get_string('formatplain'),
1072 FORMAT_MARKDOWN
=> get_string('formatmarkdown'));
1076 * Given text in a variety of format codings, this function returns the text as safe HTML.
1078 * This function should mainly be used for long strings like posts,
1079 * answers, glossary items etc. For short strings {@link format_string()}.
1083 * trusted : If true the string won't be cleaned. Default false required noclean=true.
1084 * noclean : If true the string won't be cleaned. Default false required trusted=true.
1085 * nocache : If true the strign will not be cached and will be formatted every call. Default false.
1086 * filter : If true the string will be run through applicable filters as well. Default true.
1087 * para : If true then the returned string will be wrapped in div tags. Default true.
1088 * newlines : If true then lines newline breaks will be converted to HTML newline breaks. Default true.
1089 * context : The context that will be used for filtering.
1090 * overflowdiv : If set to true the formatted text will be encased in a div
1091 * with the class no-overflow before being returned. Default false.
1092 * allowid : If true then id attributes will not be removed, even when
1093 * using htmlpurifier. Default false.
1096 * @staticvar array $croncache
1097 * @param string $text The text to be formatted. This is raw text originally from user input.
1098 * @param int $format Identifier of the text format to be used
1099 * [FORMAT_MOODLE, FORMAT_HTML, FORMAT_PLAIN, FORMAT_MARKDOWN]
1100 * @param object/array $options text formatting options
1101 * @param int $courseiddonotuse deprecated course id, use context option instead
1104 function format_text($text, $format = FORMAT_MOODLE
, $options = null, $courseiddonotuse = null) {
1105 global $CFG, $DB, $PAGE;
1107 if ($text === '' ||
is_null($text)) {
1108 // No need to do any filters and cleaning.
1112 // Detach object, we can not modify it.
1113 $options = (array)$options;
1115 if (!isset($options['trusted'])) {
1116 $options['trusted'] = false;
1118 if (!isset($options['noclean'])) {
1119 if ($options['trusted'] and trusttext_active()) {
1120 // No cleaning if text trusted and noclean not specified.
1121 $options['noclean'] = true;
1123 $options['noclean'] = false;
1126 if (!isset($options['nocache'])) {
1127 $options['nocache'] = false;
1129 if (!isset($options['filter'])) {
1130 $options['filter'] = true;
1132 if (!isset($options['para'])) {
1133 $options['para'] = true;
1135 if (!isset($options['newlines'])) {
1136 $options['newlines'] = true;
1138 if (!isset($options['overflowdiv'])) {
1139 $options['overflowdiv'] = false;
1142 // Calculate best context.
1143 if (empty($CFG->version
) or $CFG->version
< 2013051400 or during_initial_install()) {
1144 // Do not filter anything during installation or before upgrade completes.
1147 } else if (isset($options['context'])) { // First by explicit passed context option.
1148 if (is_object($options['context'])) {
1149 $context = $options['context'];
1151 $context = context
::instance_by_id($options['context']);
1153 } else if ($courseiddonotuse) {
1155 $context = context_course
::instance($courseiddonotuse);
1157 // Fallback to $PAGE->context this may be problematic in CLI and other non-standard pages :-(.
1158 $context = $PAGE->context
;
1162 // Either install/upgrade or something has gone really wrong because context does not exist (yet?).
1163 $options['nocache'] = true;
1164 $options['filter'] = false;
1167 if ($options['filter']) {
1168 $filtermanager = filter_manager
::instance();
1169 $filtermanager->setup_page_for_filters($PAGE, $context); // Setup global stuff filters may have.
1171 $filtermanager = new null_filter_manager();
1176 if (!$options['noclean']) {
1177 $text = clean_text($text, FORMAT_HTML
, $options);
1179 $text = $filtermanager->filter_text($text, $context, array(
1180 'originalformat' => FORMAT_HTML
,
1181 'noclean' => $options['noclean']
1186 $text = s($text); // Cleans dangerous JS.
1187 $text = rebuildnolinktag($text);
1188 $text = str_replace(' ', ' ', $text);
1189 $text = nl2br($text);
1193 // This format is deprecated.
1194 $text = '<p>NOTICE: Wiki-like formatting has been removed from Moodle. You should not be seeing
1195 this message as all texts should have been converted to Markdown format instead.
1196 Please post a bug report to http://moodle.org/bugs with information about where you
1197 saw this message.</p>'.s($text);
1200 case FORMAT_MARKDOWN
:
1201 $text = markdown_to_html($text);
1202 if (!$options['noclean']) {
1203 $text = clean_text($text, FORMAT_HTML
, $options);
1205 $text = $filtermanager->filter_text($text, $context, array(
1206 'originalformat' => FORMAT_MARKDOWN
,
1207 'noclean' => $options['noclean']
1211 default: // FORMAT_MOODLE or anything else.
1212 $text = text_to_html($text, null, $options['para'], $options['newlines']);
1213 if (!$options['noclean']) {
1214 $text = clean_text($text, FORMAT_HTML
, $options);
1216 $text = $filtermanager->filter_text($text, $context, array(
1217 'originalformat' => $format,
1218 'noclean' => $options['noclean']
1222 if ($options['filter']) {
1223 // At this point there should not be any draftfile links any more,
1224 // this happens when developers forget to post process the text.
1225 // The only potential problem is that somebody might try to format
1226 // the text before storing into database which would be itself big bug..
1227 $text = str_replace("\"$CFG->httpswwwroot/draftfile.php", "\"$CFG->httpswwwroot/brokenfile.php#", $text);
1229 if ($CFG->debugdeveloper
) {
1230 if (strpos($text, '@@PLUGINFILE@@/') !== false) {
1231 debugging('Before calling format_text(), the content must be processed with file_rewrite_pluginfile_urls()',
1237 if (!empty($options['overflowdiv'])) {
1238 $text = html_writer
::tag('div', $text, array('class' => 'no-overflow'));
1245 * Resets some data related to filters, called during upgrade or when general filter settings change.
1247 * @param bool $phpunitreset true means called from our PHPUnit integration test reset
1250 function reset_text_filters_cache($phpunitreset = false) {
1253 if ($phpunitreset) {
1254 // HTMLPurifier does not change, DB is already reset to defaults,
1255 // nothing to do here, the dataroot was cleared too.
1259 // The purge_all_caches() deals with cachedir and localcachedir purging,
1260 // the individual filter caches are invalidated as necessary elsewhere.
1262 // Update $CFG->filterall cache flag.
1263 if (empty($CFG->stringfilters
)) {
1264 set_config('filterall', 0);
1267 $installedfilters = core_component
::get_plugin_list('filter');
1268 $filters = explode(',', $CFG->stringfilters
);
1269 foreach ($filters as $filter) {
1270 if (isset($installedfilters[$filter])) {
1271 set_config('filterall', 1);
1275 set_config('filterall', 0);
1279 * Given a simple string, this function returns the string
1280 * processed by enabled string filters if $CFG->filterall is enabled
1282 * This function should be used to print short strings (non html) that
1283 * need filter processing e.g. activity titles, post subjects,
1284 * glossary concepts.
1286 * @staticvar bool $strcache
1287 * @param string $string The string to be filtered. Should be plain text, expect
1288 * possibly for multilang tags.
1289 * @param boolean $striplinks To strip any link in the result text. Moodle 1.8 default changed from false to true! MDL-8713
1290 * @param array $options options array/object or courseid
1293 function format_string($string, $striplinks = true, $options = null) {
1296 // We'll use a in-memory cache here to speed up repeated strings.
1297 static $strcache = false;
1299 if (empty($CFG->version
) or $CFG->version
< 2013051400 or during_initial_install()) {
1300 // Do not filter anything during installation or before upgrade completes.
1301 return $string = strip_tags($string);
1304 if ($strcache === false or count($strcache) > 2000) {
1305 // This number might need some tuning to limit memory usage in cron.
1306 $strcache = array();
1309 if (is_numeric($options)) {
1310 // Legacy courseid usage.
1311 $options = array('context' => context_course
::instance($options));
1313 // Detach object, we can not modify it.
1314 $options = (array)$options;
1317 if (empty($options['context'])) {
1318 // Fallback to $PAGE->context this may be problematic in CLI and other non-standard pages :-(.
1319 $options['context'] = $PAGE->context
;
1320 } else if (is_numeric($options['context'])) {
1321 $options['context'] = context
::instance_by_id($options['context']);
1324 if (!$options['context']) {
1325 // We did not find any context? weird.
1326 return $string = strip_tags($string);
1330 $md5 = md5($string.'<+>'.$striplinks.'<+>'.$options['context']->id
.'<+>'.current_language());
1332 // Fetch from cache if possible.
1333 if (isset($strcache[$md5])) {
1334 return $strcache[$md5];
1337 // First replace all ampersands not followed by html entity code
1338 // Regular expression moved to its own method for easier unit testing.
1339 $string = replace_ampersands_not_followed_by_entity($string);
1341 if (!empty($CFG->filterall
)) {
1342 $filtermanager = filter_manager
::instance();
1343 $filtermanager->setup_page_for_filters($PAGE, $options['context']); // Setup global stuff filters may have.
1344 $string = $filtermanager->filter_string($string, $options['context']);
1347 // If the site requires it, strip ALL tags from this string.
1348 if (!empty($CFG->formatstringstriptags
)) {
1349 $string = str_replace(array('<', '>'), array('<', '>'), strip_tags($string));
1352 // Otherwise strip just links if that is required (default).
1354 // Strip links in string.
1355 $string = strip_links($string);
1357 $string = clean_text($string);
1361 $strcache[$md5] = $string;
1367 * Given a string, performs a negative lookahead looking for any ampersand character
1368 * that is not followed by a proper HTML entity. If any is found, it is replaced
1369 * by &. The string is then returned.
1371 * @param string $string
1374 function replace_ampersands_not_followed_by_entity($string) {
1375 return preg_replace("/\&(?![a-zA-Z0-9#]{1,8};)/", "&", $string);
1379 * Given a string, replaces all <a>.*</a> by .* and returns the string.
1381 * @param string $string
1384 function strip_links($string) {
1385 return preg_replace('/(<a\s[^>]+?>)(.+?)(<\/a>)/is', '$2', $string);
1389 * This expression turns links into something nice in a text format. (Russell Jungwirth)
1391 * @param string $string
1394 function wikify_links($string) {
1395 return preg_replace('~(<a [^<]*href=["|\']?([^ "\']*)["|\']?[^>]*>([^<]*)</a>)~i', '$3 [ $2 ]', $string);
1399 * Given text in a variety of format codings, this function returns the text as plain text suitable for plain email.
1401 * @param string $text The text to be formatted. This is raw text originally from user input.
1402 * @param int $format Identifier of the text format to be used
1403 * [FORMAT_MOODLE, FORMAT_HTML, FORMAT_PLAIN, FORMAT_WIKI, FORMAT_MARKDOWN]
1406 function format_text_email($text, $format) {
1415 // There should not be any of these any more!
1416 $text = wikify_links($text);
1417 return core_text
::entities_to_utf8(strip_tags($text), true);
1421 return html_to_text($text);
1425 case FORMAT_MARKDOWN
:
1427 $text = wikify_links($text);
1428 return core_text
::entities_to_utf8(strip_tags($text), true);
1434 * Formats activity intro text
1436 * @param string $module name of module
1437 * @param object $activity instance of activity
1438 * @param int $cmid course module id
1439 * @param bool $filter filter resulting html text
1442 function format_module_intro($module, $activity, $cmid, $filter=true) {
1444 require_once("$CFG->libdir/filelib.php");
1445 $context = context_module
::instance($cmid);
1446 $options = array('noclean' => true, 'para' => false, 'filter' => $filter, 'context' => $context, 'overflowdiv' => true);
1447 $intro = file_rewrite_pluginfile_urls($activity->intro
, 'pluginfile.php', $context->id
, 'mod_'.$module, 'intro', null);
1448 return trim(format_text($intro, $activity->introformat
, $options, null));
1452 * Removes the usage of Moodle files from a text.
1454 * In some rare cases we need to re-use a text that already has embedded links
1455 * to some files hosted within Moodle. But the new area in which we will push
1456 * this content does not support files... therefore we need to remove those files.
1458 * @param string $source The text
1459 * @return string The stripped text
1461 function strip_pluginfile_content($source) {
1462 $baseurl = '@@PLUGINFILE@@';
1463 // Looking for something like < .* "@@pluginfile@@.*" .* >
1464 $pattern = '$<[^<>]+["\']' . $baseurl . '[^"\']*["\'][^<>]*>$';
1465 $stripped = preg_replace($pattern, '', $source);
1466 // Use purify html to rebalence potentially mismatched tags and generally cleanup.
1467 return purify_html($stripped);
1471 * Legacy function, used for cleaning of old forum and glossary text only.
1473 * @param string $text text that may contain legacy TRUSTTEXT marker
1474 * @return string text without legacy TRUSTTEXT marker
1476 function trusttext_strip($text) {
1477 while (true) { // Removing nested TRUSTTEXT.
1479 $text = str_replace('#####TRUSTTEXT#####', '', $text);
1480 if (strcmp($orig, $text) === 0) {
1487 * Must be called before editing of all texts with trust flag. Removes all XSS nasties from texts stored in database if needed.
1489 * @param stdClass $object data object with xxx, xxxformat and xxxtrust fields
1490 * @param string $field name of text field
1491 * @param context $context active context
1492 * @return stdClass updated $object
1494 function trusttext_pre_edit($object, $field, $context) {
1495 $trustfield = $field.'trust';
1496 $formatfield = $field.'format';
1498 if (!$object->$trustfield or !trusttext_trusted($context)) {
1499 $object->$field = clean_text($object->$field, $object->$formatfield);
1506 * Is current user trusted to enter no dangerous XSS in this context?
1508 * Please note the user must be in fact trusted everywhere on this server!!
1510 * @param context $context
1511 * @return bool true if user trusted
1513 function trusttext_trusted($context) {
1514 return (trusttext_active() and has_capability('moodle/site:trustcontent', $context));
1518 * Is trusttext feature active?
1522 function trusttext_active() {
1525 return !empty($CFG->enabletrusttext
);
1529 * Cleans raw text removing nasties.
1531 * Given raw text (eg typed in by a user) this function cleans it up and removes any nasty tags that could mess up
1532 * Moodle pages through XSS attacks.
1534 * The result must be used as a HTML text fragment, this function can not cleanup random
1535 * parts of html tags such as url or src attributes.
1537 * NOTE: the format parameter was deprecated because we can safely clean only HTML.
1539 * @param string $text The text to be cleaned
1540 * @param int|string $format deprecated parameter, should always contain FORMAT_HTML or FORMAT_MOODLE
1541 * @param array $options Array of options; currently only option supported is 'allowid' (if true,
1542 * does not remove id attributes when cleaning)
1543 * @return string The cleaned up text
1545 function clean_text($text, $format = FORMAT_HTML
, $options = array()) {
1546 $text = (string)$text;
1548 if ($format != FORMAT_HTML
and $format != FORMAT_HTML
) {
1549 // TODO: we need to standardise cleanup of text when loading it into editor first.
1550 // debugging('clean_text() is designed to work only with html');.
1553 if ($format == FORMAT_PLAIN
) {
1557 if (is_purify_html_necessary($text)) {
1558 $text = purify_html($text, $options);
1561 // Originally we tried to neutralise some script events here, it was a wrong approach because
1562 // it was trivial to work around that (for example using style based XSS exploits).
1563 // We must not give false sense of security here - all developers MUST understand how to use
1564 // rawurlencode(), htmlentities(), htmlspecialchars(), p(), s(), moodle_url, html_writer and friends!!!
1570 * Is it necessary to use HTMLPurifier?
1573 * @param string $text
1574 * @return bool false means html is safe and valid, true means use HTMLPurifier
1576 function is_purify_html_necessary($text) {
1581 if ($text === (string)((int)$text)) {
1585 if (strpos($text, '&') !== false or preg_match('|<[^pesb/]|', $text)) {
1586 // We need to normalise entities or other tags except p, em, strong and br present.
1590 $altered = htmlspecialchars($text, ENT_NOQUOTES
, 'UTF-8', true);
1591 if ($altered === $text) {
1592 // No < > or other special chars means this must be safe.
1596 // Let's try to convert back some safe html tags.
1597 $altered = preg_replace('|<p>(.*?)</p>|m', '<p>$1</p>', $altered);
1598 if ($altered === $text) {
1601 $altered = preg_replace('|<em>([^<>]+?)</em>|m', '<em>$1</em>', $altered);
1602 if ($altered === $text) {
1605 $altered = preg_replace('|<strong>([^<>]+?)</strong>|m', '<strong>$1</strong>', $altered);
1606 if ($altered === $text) {
1609 $altered = str_replace('<br />', '<br />', $altered);
1610 if ($altered === $text) {
1618 * KSES replacement cleaning function - uses HTML Purifier.
1620 * @param string $text The (X)HTML string to purify
1621 * @param array $options Array of options; currently only option supported is 'allowid' (if set,
1622 * does not remove id attributes when cleaning)
1625 function purify_html($text, $options = array()) {
1628 $text = (string)$text;
1630 static $purifiers = array();
1631 static $caches = array();
1633 // Purifier code can change only during major version upgrade.
1634 $version = empty($CFG->version
) ?
0 : $CFG->version
;
1635 $cachedir = "$CFG->localcachedir/htmlpurifier/$version";
1636 if (!file_exists($cachedir)) {
1637 // Purging of caches may remove the cache dir at any time,
1638 // luckily file_exists() results should be cached for all existing directories.
1639 $purifiers = array();
1641 gc_collect_cycles();
1643 make_localcache_directory('htmlpurifier', false);
1644 check_dir_exists($cachedir);
1647 $allowid = empty($options['allowid']) ?
0 : 1;
1648 $allowobjectembed = empty($CFG->allowobjectembed
) ?
0 : 1;
1650 $type = 'type_'.$allowid.'_'.$allowobjectembed;
1652 if (!array_key_exists($type, $caches)) {
1653 $caches[$type] = cache
::make('core', 'htmlpurifier', array('type' => $type));
1655 $cache = $caches[$type];
1657 // Add revision number and all options to the text key so that it is compatible with local cluster node caches.
1658 $key = "|$version|$allowobjectembed|$allowid|$text";
1659 $filteredtext = $cache->get($key);
1661 if ($filteredtext === true) {
1662 // The filtering did not change the text last time, no need to filter anything again.
1664 } else if ($filteredtext !== false) {
1665 return $filteredtext;
1668 if (empty($purifiers[$type])) {
1669 require_once $CFG->libdir
.'/htmlpurifier/HTMLPurifier.safe-includes.php';
1670 require_once $CFG->libdir
.'/htmlpurifier/locallib.php';
1671 $config = HTMLPurifier_Config
::createDefault();
1673 $config->set('HTML.DefinitionID', 'moodlehtml');
1674 $config->set('HTML.DefinitionRev', 2);
1675 $config->set('Cache.SerializerPath', $cachedir);
1676 $config->set('Cache.SerializerPermissions', $CFG->directorypermissions
);
1677 $config->set('Core.NormalizeNewlines', false);
1678 $config->set('Core.ConvertDocumentToFragment', true);
1679 $config->set('Core.Encoding', 'UTF-8');
1680 $config->set('HTML.Doctype', 'XHTML 1.0 Transitional');
1681 $config->set('URI.AllowedSchemes', array(
1689 'teamspeak' => true,
1694 $config->set('Attr.AllowedFrameTargets', array('_blank'));
1696 if ($allowobjectembed) {
1697 $config->set('HTML.SafeObject', true);
1698 $config->set('Output.FlashCompat', true);
1699 $config->set('HTML.SafeEmbed', true);
1703 $config->set('Attr.EnableID', true);
1706 if ($def = $config->maybeGetRawHTMLDefinition()) {
1707 $def->addElement('nolink', 'Block', 'Flow', array()); // Skip our filters inside.
1708 $def->addElement('tex', 'Inline', 'Inline', array()); // Tex syntax, equivalent to $$xx$$.
1709 $def->addElement('algebra', 'Inline', 'Inline', array()); // Algebra syntax, equivalent to @@xx@@.
1710 $def->addElement('lang', 'Block', 'Flow', array(), array('lang'=>'CDATA')); // Original multilang style - only our hacked lang attribute.
1711 $def->addAttribute('span', 'xxxlang', 'CDATA'); // Current very problematic multilang.
1714 $purifier = new HTMLPurifier($config);
1715 $purifiers[$type] = $purifier;
1717 $purifier = $purifiers[$type];
1720 $multilang = (strpos($text, 'class="multilang"') !== false);
1722 $filteredtext = $text;
1724 $filteredtextregex = '/<span(\s+lang="([a-zA-Z0-9_-]+)"|\s+class="multilang"){2}\s*>/';
1725 $filteredtext = preg_replace($filteredtextregex, '<span xxxlang="${2}">', $filteredtext);
1727 $filteredtext = (string)$purifier->purify($filteredtext);
1729 $filteredtext = preg_replace('/<span xxxlang="([a-zA-Z0-9_-]+)">/', '<span lang="${1}" class="multilang">', $filteredtext);
1732 if ($text === $filteredtext) {
1733 // No need to store the filtered text, next time we will just return unfiltered text
1734 // because it was not changed by purifying.
1735 $cache->set($key, true);
1737 $cache->set($key, $filteredtext);
1740 return $filteredtext;
1744 * Given plain text, makes it into HTML as nicely as possible.
1746 * May contain HTML tags already.
1748 * Do not abuse this function. It is intended as lower level formatting feature used
1749 * by {@link format_text()} to convert FORMAT_MOODLE to HTML. You are supposed
1750 * to call format_text() in most of cases.
1752 * @param string $text The string to convert.
1753 * @param boolean $smileyignored Was used to determine if smiley characters should convert to smiley images, ignored now
1754 * @param boolean $para If true then the returned string will be wrapped in div tags
1755 * @param boolean $newlines If true then lines newline breaks will be converted to HTML newline breaks.
1758 function text_to_html($text, $smileyignored = null, $para = true, $newlines = true) {
1759 // Remove any whitespace that may be between HTML tags.
1760 $text = preg_replace("~>([[:space:]]+)<~i", "><", $text);
1762 // Remove any returns that precede or follow HTML tags.
1763 $text = preg_replace("~([\n\r])<~i", " <", $text);
1764 $text = preg_replace("~>([\n\r])~i", "> ", $text);
1766 // Make returns into HTML newlines.
1768 $text = nl2br($text);
1771 // Wrap the whole thing in a div if required.
1773 // In 1.9 this was changed from a p => div.
1774 return '<div class="text_to_html">'.$text.'</div>';
1781 * Given Markdown formatted text, make it into XHTML using external function
1783 * @param string $text The markdown formatted text to be converted.
1784 * @return string Converted text
1786 function markdown_to_html($text) {
1789 if ($text === '' or $text === null) {
1793 require_once($CFG->libdir
.'/markdown/MarkdownInterface.php');
1794 require_once($CFG->libdir
.'/markdown/Markdown.php');
1795 require_once($CFG->libdir
.'/markdown/MarkdownExtra.php');
1797 return \Michelf\MarkdownExtra
::defaultTransform($text);
1801 * Given HTML text, make it into plain text using external function
1803 * @param string $html The text to be converted.
1804 * @param integer $width Width to wrap the text at. (optional, default 75 which
1805 * is a good value for email. 0 means do not limit line length.)
1806 * @param boolean $dolinks By default, any links in the HTML are collected, and
1807 * printed as a list at the end of the HTML. If you don't want that, set this
1808 * argument to false.
1809 * @return string plain text equivalent of the HTML.
1811 function html_to_text($html, $width = 75, $dolinks = true) {
1815 require_once($CFG->libdir
.'/html2text.php');
1817 $h2t = new html2text($html, false, $dolinks, $width);
1818 $result = $h2t->get_text();
1824 * This function will highlight search words in a given string
1826 * It cares about HTML and will not ruin links. It's best to use
1827 * this function after performing any conversions to HTML.
1829 * @param string $needle The search string. Syntax like "word1 +word2 -word3" is dealt with correctly.
1830 * @param string $haystack The string (HTML) within which to highlight the search terms.
1831 * @param boolean $matchcase whether to do case-sensitive. Default case-insensitive.
1832 * @param string $prefix the string to put before each search term found.
1833 * @param string $suffix the string to put after each search term found.
1834 * @return string The highlighted HTML.
1836 function highlight($needle, $haystack, $matchcase = false,
1837 $prefix = '<span class="highlight">', $suffix = '</span>') {
1839 // Quick bail-out in trivial cases.
1840 if (empty($needle) or empty($haystack)) {
1844 // Break up the search term into words, discard any -words and build a regexp.
1845 $words = preg_split('/ +/', trim($needle));
1846 foreach ($words as $index => $word) {
1847 if (strpos($word, '-') === 0) {
1848 unset($words[$index]);
1849 } else if (strpos($word, '+') === 0) {
1850 $words[$index] = '\b' . preg_quote(ltrim($word, '+'), '/') . '\b'; // Match only as a complete word.
1852 $words[$index] = preg_quote($word, '/');
1855 $regexp = '/(' . implode('|', $words) . ')/u'; // Char u is to do UTF-8 matching.
1860 // Another chance to bail-out if $search was only -words.
1861 if (empty($words)) {
1865 // Split the string into HTML tags and real content.
1866 $chunks = preg_split('/((?:<[^>]*>)+)/', $haystack, -1, PREG_SPLIT_DELIM_CAPTURE
);
1868 // We have an array of alternating blocks of text, then HTML tags, then text, ...
1869 // Loop through replacing search terms in the text, and leaving the HTML unchanged.
1870 $ishtmlchunk = false;
1872 foreach ($chunks as $chunk) {
1876 $result .= preg_replace($regexp, $prefix . '$1' . $suffix, $chunk);
1878 $ishtmlchunk = !$ishtmlchunk;
1885 * This function will highlight instances of $needle in $haystack
1887 * It's faster that the above function {@link highlight()} and doesn't care about
1890 * @param string $needle The string to search for
1891 * @param string $haystack The string to search for $needle in
1892 * @return string The highlighted HTML
1894 function highlightfast($needle, $haystack) {
1896 if (empty($needle) or empty($haystack)) {
1900 $parts = explode(core_text
::strtolower($needle), core_text
::strtolower($haystack));
1902 if (count($parts) === 1) {
1908 foreach ($parts as $key => $part) {
1909 $parts[$key] = substr($haystack, $pos, strlen($part));
1910 $pos +
= strlen($part);
1912 $parts[$key] .= '<span class="highlight">'.substr($haystack, $pos, strlen($needle)).'</span>';
1913 $pos +
= strlen($needle);
1916 return str_replace('<span class="highlight"></span>', '', join('', $parts));
1920 * Return a string containing 'lang', xml:lang and optionally 'dir' HTML attributes.
1922 * Internationalisation, for print_header and backup/restorelib.
1924 * @param bool $dir Default false
1925 * @return string Attributes
1927 function get_html_lang($dir = false) {
1930 if (right_to_left()) {
1931 $direction = ' dir="rtl"';
1933 $direction = ' dir="ltr"';
1936 // Accessibility: added the 'lang' attribute to $direction, used in theme <html> tag.
1937 $language = str_replace('_', '-', current_language());
1938 @header
('Content-Language: '.$language);
1939 return ($direction.' lang="'.$language.'" xml:lang="'.$language.'"');
1943 // STANDARD WEB PAGE PARTS.
1946 * Send the HTTP headers that Moodle requires.
1948 * There is a backwards compatibility hack for legacy code
1949 * that needs to add custom IE compatibility directive.
1953 * if (!isset($CFG->additionalhtmlhead)) {
1954 * $CFG->additionalhtmlhead = '';
1956 * $CFG->additionalhtmlhead .= '<meta http-equiv="X-UA-Compatible" content="IE=8" />';
1957 * header('X-UA-Compatible: IE=8');
1958 * echo $OUTPUT->header();
1961 * Please note the $CFG->additionalhtmlhead alone might not work,
1962 * you should send the IE compatibility header() too.
1964 * @param string $contenttype
1965 * @param bool $cacheable Can this page be cached on back?
1966 * @return void, sends HTTP headers
1968 function send_headers($contenttype, $cacheable = true) {
1971 @header
('Content-Type: ' . $contenttype);
1972 @header
('Content-Script-Type: text/javascript');
1973 @header
('Content-Style-Type: text/css');
1975 if (empty($CFG->additionalhtmlhead
) or stripos($CFG->additionalhtmlhead
, 'X-UA-Compatible') === false) {
1976 @header
('X-UA-Compatible: IE=edge');
1980 // Allow caching on "back" (but not on normal clicks).
1981 @header
('Cache-Control: private, pre-check=0, post-check=0, max-age=0, no-transform');
1982 @header
('Pragma: no-cache');
1983 @header
('Expires: ');
1985 // Do everything we can to always prevent clients and proxies caching.
1986 @header
('Cache-Control: no-store, no-cache, must-revalidate');
1987 @header
('Cache-Control: post-check=0, pre-check=0, no-transform', false);
1988 @header
('Pragma: no-cache');
1989 @header
('Expires: Mon, 20 Aug 1969 09:23:00 GMT');
1990 @header
('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
1992 @header
('Accept-Ranges: none');
1994 if (empty($CFG->allowframembedding
)) {
1995 @header
('X-Frame-Options: sameorigin');
2000 * Return the right arrow with text ('next'), and optionally embedded in a link.
2002 * @param string $text HTML/plain text label (set to blank only for breadcrumb separator cases).
2003 * @param string $url An optional link to use in a surrounding HTML anchor.
2004 * @param bool $accesshide True if text should be hidden (for screen readers only).
2005 * @param string $addclass Additional class names for the link, or the arrow character.
2006 * @return string HTML string.
2008 function link_arrow_right($text, $url='', $accesshide=false, $addclass='') {
2009 global $OUTPUT; // TODO: move to output renderer.
2010 $arrowclass = 'arrow ';
2012 $arrowclass .= $addclass;
2014 $arrow = '<span class="'.$arrowclass.'">'.$OUTPUT->rarrow().'</span>';
2017 $htmltext = '<span class="arrow_text">'.$text.'</span> ';
2019 $htmltext = get_accesshide($htmltext);
2023 $class = 'arrow_link';
2025 $class .= ' '.$addclass;
2027 return '<a class="'.$class.'" href="'.$url.'" title="'.preg_replace('/<.*?>/', '', $text).'">'.$htmltext.$arrow.'</a>';
2029 return $htmltext.$arrow;
2033 * Return the left arrow with text ('previous'), and optionally embedded in a link.
2035 * @param string $text HTML/plain text label (set to blank only for breadcrumb separator cases).
2036 * @param string $url An optional link to use in a surrounding HTML anchor.
2037 * @param bool $accesshide True if text should be hidden (for screen readers only).
2038 * @param string $addclass Additional class names for the link, or the arrow character.
2039 * @return string HTML string.
2041 function link_arrow_left($text, $url='', $accesshide=false, $addclass='') {
2042 global $OUTPUT; // TODO: move to utput renderer.
2043 $arrowclass = 'arrow ';
2045 $arrowclass .= $addclass;
2047 $arrow = '<span class="'.$arrowclass.'">'.$OUTPUT->larrow().'</span>';
2050 $htmltext = ' <span class="arrow_text">'.$text.'</span>';
2052 $htmltext = get_accesshide($htmltext);
2056 $class = 'arrow_link';
2058 $class .= ' '.$addclass;
2060 return '<a class="'.$class.'" href="'.$url.'" title="'.preg_replace('/<.*?>/', '', $text).'">'.$arrow.$htmltext.'</a>';
2062 return $arrow.$htmltext;
2066 * Return a HTML element with the class "accesshide", for accessibility.
2068 * Please use cautiously - where possible, text should be visible!
2070 * @param string $text Plain text.
2071 * @param string $elem Lowercase element name, default "span".
2072 * @param string $class Additional classes for the element.
2073 * @param string $attrs Additional attributes string in the form, "name='value' name2='value2'"
2074 * @return string HTML string.
2076 function get_accesshide($text, $elem='span', $class='', $attrs='') {
2077 return "<$elem class=\"accesshide $class\" $attrs>$text</$elem>";
2081 * Return the breadcrumb trail navigation separator.
2083 * @return string HTML string.
2085 function get_separator() {
2086 // Accessibility: the 'hidden' slash is preferred for screen readers.
2087 return ' '.link_arrow_right($text='/', $url='', $accesshide=true, 'sep').' ';
2091 * Print (or return) a collapsible region, that has a caption that can be clicked to expand or collapse the region.
2093 * If JavaScript is off, then the region will always be expanded.
2095 * @param string $contents the contents of the box.
2096 * @param string $classes class names added to the div that is output.
2097 * @param string $id id added to the div that is output. Must not be blank.
2098 * @param string $caption text displayed at the top. Clicking on this will cause the region to expand or contract.
2099 * @param string $userpref the name of the user preference that stores the user's preferred default state.
2100 * (May be blank if you do not wish the state to be persisted.
2101 * @param boolean $default Initial collapsed state to use if the user_preference it not set.
2102 * @param boolean $return if true, return the HTML as a string, rather than printing it.
2103 * @return string|void If $return is false, returns nothing, otherwise returns a string of HTML.
2105 function print_collapsible_region($contents, $classes, $id, $caption, $userpref = '', $default = false, $return = false) {
2106 $output = print_collapsible_region_start($classes, $id, $caption, $userpref, $default, true);
2107 $output .= $contents;
2108 $output .= print_collapsible_region_end(true);
2118 * Print (or return) the start of a collapsible region
2120 * The collapsibleregion has a caption that can be clicked to expand or collapse the region. If JavaScript is off, then the region
2121 * will always be expanded.
2123 * @param string $classes class names added to the div that is output.
2124 * @param string $id id added to the div that is output. Must not be blank.
2125 * @param string $caption text displayed at the top. Clicking on this will cause the region to expand or contract.
2126 * @param string $userpref the name of the user preference that stores the user's preferred default state.
2127 * (May be blank if you do not wish the state to be persisted.
2128 * @param boolean $default Initial collapsed state to use if the user_preference it not set.
2129 * @param boolean $return if true, return the HTML as a string, rather than printing it.
2130 * @return string|void if $return is false, returns nothing, otherwise returns a string of HTML.
2132 function print_collapsible_region_start($classes, $id, $caption, $userpref = '', $default = false, $return = false) {
2135 // Work out the initial state.
2136 if (!empty($userpref) and is_string($userpref)) {
2137 user_preference_allow_ajax_update($userpref, PARAM_BOOL
);
2138 $collapsed = get_user_preferences($userpref, $default);
2140 $collapsed = $default;
2145 $classes .= ' collapsed';
2149 $output .= '<div id="' . $id . '" class="collapsibleregion ' . $classes . '">';
2150 $output .= '<div id="' . $id . '_sizer">';
2151 $output .= '<div id="' . $id . '_caption" class="collapsibleregioncaption">';
2152 $output .= $caption . ' ';
2153 $output .= '</div><div id="' . $id . '_inner" class="collapsibleregioninner">';
2154 $PAGE->requires
->js_init_call('M.util.init_collapsible_region', array($id, $userpref, get_string('clicktohideshow')));
2164 * Close a region started with print_collapsible_region_start.
2166 * @param boolean $return if true, return the HTML as a string, rather than printing it.
2167 * @return string|void if $return is false, returns nothing, otherwise returns a string of HTML.
2169 function print_collapsible_region_end($return = false) {
2170 $output = '</div></div></div>';
2180 * Print a specified group's avatar.
2182 * @param array|stdClass $group A single {@link group} object OR array of groups.
2183 * @param int $courseid The course ID.
2184 * @param boolean $large Default small picture, or large.
2185 * @param boolean $return If false print picture, otherwise return the output as string
2186 * @param boolean $link Enclose image in a link to view specified course?
2187 * @return string|void Depending on the setting of $return
2189 function print_group_picture($group, $courseid, $large=false, $return=false, $link=true) {
2192 if (is_array($group)) {
2194 foreach ($group as $g) {
2195 $output .= print_group_picture($g, $courseid, $large, true, $link);
2205 $context = context_course
::instance($courseid);
2207 // If there is no picture, do nothing.
2208 if (!$group->picture
) {
2212 // If picture is hidden, only show to those with course:managegroups.
2213 if ($group->hidepicture
and !has_capability('moodle/course:managegroups', $context)) {
2217 if ($link or has_capability('moodle/site:accessallgroups', $context)) {
2218 $output = '<a href="'. $CFG->wwwroot
.'/user/index.php?id='. $courseid .'&group='. $group->id
.'">';
2228 $grouppictureurl = moodle_url
::make_pluginfile_url($context->id
, 'group', 'icon', $group->id
, '/', $file);
2229 $grouppictureurl->param('rev', $group->picture
);
2230 $output .= '<img class="grouppicture" src="'.$grouppictureurl.'"'.
2231 ' alt="'.s(get_string('group').' '.$group->name
).'" title="'.s($group->name
).'"/>';
2233 if ($link or has_capability('moodle/site:accessallgroups', $context)) {
2246 * Display a recent activity note
2248 * @staticvar string $strftimerecent
2249 * @param int $time A timestamp int.
2250 * @param stdClass $user A user object from the database.
2251 * @param string $text Text for display for the note
2252 * @param string $link The link to wrap around the text
2253 * @param bool $return If set to true the HTML is returned rather than echo'd
2254 * @param string $viewfullnames
2255 * @return string If $retrun was true returns HTML for a recent activity notice.
2257 function print_recent_activity_note($time, $user, $text, $link, $return=false, $viewfullnames=null) {
2258 static $strftimerecent = null;
2261 if (is_null($viewfullnames)) {
2262 $context = context_system
::instance();
2263 $viewfullnames = has_capability('moodle/site:viewfullnames', $context);
2266 if (is_null($strftimerecent)) {
2267 $strftimerecent = get_string('strftimerecent');
2270 $output .= '<div class="head">';
2271 $output .= '<div class="date">'.userdate($time, $strftimerecent).'</div>';
2272 $output .= '<div class="name">'.fullname($user, $viewfullnames).'</div>';
2273 $output .= '</div>';
2274 $output .= '<div class="info"><a href="'.$link.'">'.format_string($text, true).'</a></div>';
2284 * Returns a popup menu with course activity modules
2286 * Given a course this function returns a small popup menu with all the course activity modules in it, as a navigation menu
2287 * outputs a simple list structure in XHTML.
2288 * The data is taken from the serialised array stored in the course record.
2290 * @param course $course A {@link $COURSE} object.
2291 * @param array $sections
2292 * @param course_modinfo $modinfo
2293 * @param string $strsection
2294 * @param string $strjumpto
2296 * @param string $cmid
2297 * @return string The HTML block
2299 function navmenulist($course, $sections, $modinfo, $strsection, $strjumpto, $width=50, $cmid=0) {
2301 global $CFG, $OUTPUT;
2305 $doneheading = false;
2307 $courseformatoptions = course_get_format($course)->get_format_options();
2308 $coursecontext = context_course
::instance($course->id
);
2310 $menu[] = '<ul class="navmenulist"><li class="jumpto section"><span>'.$strjumpto.'</span><ul>';
2311 foreach ($modinfo->cms
as $mod) {
2312 if (!$mod->has_view()) {
2313 // Don't show modules which you can't link to!
2317 // For course formats using 'numsections' do not show extra sections.
2318 if (isset($courseformatoptions['numsections']) && $mod->sectionnum
> $courseformatoptions['numsections']) {
2322 if (!$mod->uservisible
) { // Do not icnlude empty sections at all.
2326 if ($mod->sectionnum
>= 0 and $section != $mod->sectionnum
) {
2327 $thissection = $sections[$mod->sectionnum
];
2329 if ($thissection->visible
or
2330 (isset($courseformatoptions['hiddensections']) and !$courseformatoptions['hiddensections']) or
2331 has_capability('moodle/course:viewhiddensections', $coursecontext)) {
2332 $thissection->summary
= strip_tags(format_string($thissection->summary
, true));
2333 if (!$doneheading) {
2334 $menu[] = '</ul></li>';
2336 if ($course->format
== 'weeks' or empty($thissection->summary
)) {
2337 $item = $strsection ." ". $mod->sectionnum
;
2339 if (core_text
::strlen($thissection->summary
) < ($width-3)) {
2340 $item = $thissection->summary
;
2342 $item = core_text
::substr($thissection->summary
, 0, $width).'...';
2345 $menu[] = '<li class="section"><span>'.$item.'</span>';
2347 $doneheading = true;
2349 $section = $mod->sectionnum
;
2351 // No activities from this hidden section shown.
2356 $url = $mod->modname
.'/view.php?id='. $mod->id
;
2357 $mod->name
= strip_tags(format_string($mod->name
,true));
2358 if (core_text
::strlen($mod->name
) > ($width+
5)) {
2359 $mod->name
= core_text
::substr($mod->name
, 0, $width).'...';
2361 if (!$mod->visible
) {
2362 $mod->name
= '('.$mod->name
.')';
2364 $class = 'activity '.$mod->modname
;
2365 $class .= ($cmid == $mod->id
) ?
' selected' : '';
2366 $menu[] = '<li class="'.$class.'">'.
2367 '<img src="'.$OUTPUT->pix_url('icon', $mod->modname
) . '" alt="" />'.
2368 '<a href="'.$CFG->wwwroot
.'/mod/'.$url.'">'.$mod->name
.'</a></li>';
2372 $menu[] = '</ul></li>';
2374 $menu[] = '</ul></li></ul>';
2376 return implode("\n", $menu);
2380 * Prints a grade menu (as part of an existing form) with help showing all possible numerical grades and scales.
2382 * @todo Finish documenting this function
2383 * @todo Deprecate: this is only used in a few contrib modules
2385 * @param int $courseid The course ID
2386 * @param string $name
2387 * @param string $current
2388 * @param boolean $includenograde Include those with no grades
2389 * @param boolean $return If set to true returns rather than echo's
2390 * @return string|bool Depending on value of $return
2392 function print_grade_menu($courseid, $name, $current, $includenograde=true, $return=false) {
2396 $strscale = get_string('scale');
2397 $strscales = get_string('scales');
2399 $scales = get_scales_menu($courseid);
2400 foreach ($scales as $i => $scalename) {
2401 $grades[-$i] = $strscale .': '. $scalename;
2403 if ($includenograde) {
2404 $grades[0] = get_string('nograde');
2406 for ($i=100; $i>=1; $i--) {
2409 $output .= html_writer
::select($grades, $name, $current, false);
2411 $helppix = $OUTPUT->pix_url('help');
2412 $linkobject = '<span class="helplink"><img class="iconhelp" alt="'.$strscales.'" src="'.$helppix.'" /></span>';
2413 $link = new moodle_url('/course/scales.php', array('id' => $courseid, 'list' => 1));
2414 $action = new popup_action('click', $link, 'ratingscales', array('height' => 400, 'width' => 500));
2415 $output .= $OUTPUT->action_link($link, $linkobject, $action, array('title' => $strscales));
2425 * Print an error to STDOUT and exit with a non-zero code. For commandline scripts.
2427 * Default errorcode is 1.
2429 * Very useful for perl-like error-handling:
2430 * do_somethting() or mdie("Something went wrong");
2432 * @param string $msg Error message
2433 * @param integer $errorcode Error code to emit
2435 function mdie($msg='', $errorcode=1) {
2436 trigger_error($msg);
2441 * Print a message and exit.
2443 * @param string $message The message to print in the notice
2444 * @param string $link The link to use for the continue button
2445 * @param object $course A course object. Unused.
2446 * @return void This function simply exits
2448 function notice ($message, $link='', $course=null) {
2449 global $PAGE, $OUTPUT;
2451 $message = clean_text($message); // In case nasties are in here.
2454 echo("!!$message!!\n");
2455 exit(1); // No success.
2458 if (!$PAGE->headerprinted
) {
2459 // Header not yet printed.
2460 $PAGE->set_title(get_string('notice'));
2461 echo $OUTPUT->header();
2463 echo $OUTPUT->container_end_all(false);
2466 echo $OUTPUT->box($message, 'generalbox', 'notice');
2467 echo $OUTPUT->continue_button($link);
2469 echo $OUTPUT->footer();
2470 exit(1); // General error code.
2474 * Redirects the user to another page, after printing a notice.
2476 * This function calls the OUTPUT redirect method, echo's the output and then dies to ensure nothing else happens.
2478 * <strong>Good practice:</strong> You should call this method before starting page
2479 * output by using any of the OUTPUT methods.
2481 * @param moodle_url|string $url A moodle_url to redirect to. Strings are not to be trusted!
2482 * @param string $message The message to display to the user
2483 * @param int $delay The delay before redirecting
2484 * @throws moodle_exception
2486 function redirect($url, $message='', $delay=-1) {
2487 global $OUTPUT, $PAGE, $CFG;
2489 if (CLI_SCRIPT
or AJAX_SCRIPT
) {
2490 // This is wrong - developers should not use redirect in these scripts but it should not be very likely.
2491 throw new moodle_exception('redirecterrordetected', 'error');
2494 // Prevent debug errors - make sure context is properly initialised.
2496 $PAGE->set_context(null);
2497 $PAGE->set_pagelayout('redirect'); // No header and footer needed.
2498 $PAGE->set_title(get_string('pageshouldredirect', 'moodle'));
2501 if ($url instanceof moodle_url
) {
2502 $url = $url->out(false);
2505 $debugdisableredirect = false;
2507 if (defined('DEBUGGING_PRINTED')) {
2508 // Some debugging already printed, no need to look more.
2509 $debugdisableredirect = true;
2513 if (core_useragent
::is_msword()) {
2514 // Clicking a URL from MS Word sends a request to the server without cookies. If that
2515 // causes a redirect Word will open a browser pointing the new URL. If not, the URL that
2516 // was clicked is opened. Because the request from Word is without cookies, it almost
2517 // always results in a redirect to the login page, even if the user is logged in in their
2518 // browser. This is not what we want, so prevent the redirect for requests from Word.
2519 $debugdisableredirect = true;
2523 if (empty($CFG->debugdisplay
) or empty($CFG->debug
)) {
2524 // No errors should be displayed.
2528 if (!function_exists('error_get_last') or !$lasterror = error_get_last()) {
2532 if (!($lasterror['type'] & $CFG->debug
)) {
2533 // Last error not interesting.
2537 // Watch out here, @hidden() errors are returned from error_get_last() too.
2538 if (headers_sent()) {
2539 // We already started printing something - that means errors likely printed.
2540 $debugdisableredirect = true;
2544 if (ob_get_level() and ob_get_contents()) {
2545 // There is something waiting to be printed, hopefully it is the errors,
2546 // but it might be some error hidden by @ too - such as the timezone mess from setup.php.
2547 $debugdisableredirect = true;
2552 // Technically, HTTP/1.1 requires Location: header to contain the absolute path.
2553 // (In practice browsers accept relative paths - but still, might as well do it properly.)
2554 // This code turns relative into absolute.
2555 if (!preg_match('|^[a-z]+:|', $url)) {
2556 // Get host name http://www.wherever.com.
2557 $hostpart = preg_replace('|^(.*?[^:/])/.*$|', '$1', $CFG->wwwroot
);
2558 if (preg_match('|^/|', $url)) {
2559 // URLs beginning with / are relative to web server root so we just add them in.
2560 $url = $hostpart.$url;
2562 // URLs not beginning with / are relative to path of current script, so add that on.
2563 $url = $hostpart.preg_replace('|\?.*$|', '', me()).'/../'.$url;
2567 $newurl = preg_replace('|/(?!\.\.)[^/]*/\.\./|', '/', $url);
2568 if ($newurl == $url) {
2575 // Sanitise url - we can not rely on moodle_url or our URL cleaning
2576 // because they do not support all valid external URLs.
2577 $url = preg_replace('/[\x00-\x1F\x7F]/', '', $url);
2578 $url = str_replace('"', '%22', $url);
2579 $encodedurl = preg_replace("/\&(?![a-zA-Z0-9#]{1,8};)/", "&", $url);
2580 $encodedurl = preg_replace('/^.*href="([^"]*)".*$/', "\\1", clean_text('<a href="'.$encodedurl.'" />', FORMAT_HTML
));
2581 $url = str_replace('&', '&', $encodedurl);
2583 if (!empty($message)) {
2584 if ($delay === -1 ||
!is_numeric($delay)) {
2587 $message = clean_text($message);
2589 $message = get_string('pageshouldredirect');
2593 // Make sure the session is closed properly, this prevents problems in IIS
2594 // and also some potential PHP shutdown issues.
2595 \core\session\manager
::write_close();
2597 if ($delay == 0 && !$debugdisableredirect && !headers_sent()) {
2598 // 302 might not work for POST requests, 303 is ignored by obsolete clients.
2599 @header
($_SERVER['SERVER_PROTOCOL'] . ' 303 See Other');
2600 @header
('Location: '.$url);
2601 echo bootstrap_renderer
::plain_redirect_message($encodedurl);
2605 // Include a redirect message, even with a HTTP redirect, because that is recommended practice.
2607 $CFG->docroot
= false; // To prevent the link to moodle docs from being displayed on redirect page.
2608 echo $OUTPUT->redirect_message($encodedurl, $message, $delay, $debugdisableredirect);
2611 echo bootstrap_renderer
::early_redirect_message($encodedurl, $message, $delay);
2617 * Given an email address, this function will return an obfuscated version of it.
2619 * @param string $email The email address to obfuscate
2620 * @return string The obfuscated email address
2622 function obfuscate_email($email) {
2624 $length = strlen($email);
2626 while ($i < $length) {
2627 if (rand(0, 2) && $email{$i}!='@') { // MDL-20619 some browsers have problems unobfuscating @.
2628 $obfuscated.='%'.dechex(ord($email{$i}));
2630 $obfuscated.=$email{$i};
2638 * This function takes some text and replaces about half of the characters
2639 * with HTML entity equivalents. Return string is obviously longer.
2641 * @param string $plaintext The text to be obfuscated
2642 * @return string The obfuscated text
2644 function obfuscate_text($plaintext) {
2646 $length = core_text
::strlen($plaintext);
2648 $prevobfuscated = false;
2649 while ($i < $length) {
2650 $char = core_text
::substr($plaintext, $i, 1);
2651 $ord = core_text
::utf8ord($char);
2652 $numerical = ($ord >= ord('0')) && ($ord <= ord('9'));
2653 if ($prevobfuscated and $numerical ) {
2654 $obfuscated.='&#'.$ord.';';
2655 } else if (rand(0, 2)) {
2656 $obfuscated.='&#'.$ord.';';
2657 $prevobfuscated = true;
2660 $prevobfuscated = false;
2668 * This function uses the {@link obfuscate_email()} and {@link obfuscate_text()}
2669 * to generate a fully obfuscated email link, ready to use.
2671 * @param string $email The email address to display
2672 * @param string $label The text to displayed as hyperlink to $email
2673 * @param boolean $dimmed If true then use css class 'dimmed' for hyperlink
2674 * @param string $subject The subject of the email in the mailto link
2675 * @param string $body The content of the email in the mailto link
2676 * @return string The obfuscated mailto link
2678 function obfuscate_mailto($email, $label='', $dimmed=false, $subject = '', $body = '') {
2680 if (empty($label)) {
2684 $label = obfuscate_text($label);
2685 $email = obfuscate_email($email);
2686 $mailto = obfuscate_text('mailto');
2687 $url = new moodle_url("mailto:$email");
2690 if (!empty($subject)) {
2691 $url->param('subject', format_string($subject));
2693 if (!empty($body)) {
2694 $url->param('body', format_string($body));
2697 // Use the obfuscated mailto.
2698 $url = preg_replace('/^mailto/', $mailto, $url->out());
2701 $attrs['title'] = get_string('emaildisable');
2702 $attrs['class'] = 'dimmed';
2705 return html_writer
::link($url, $label, $attrs);
2709 * This function is used to rebuild the <nolink> tag because some formats (PLAIN and WIKI)
2710 * will transform it to html entities
2712 * @param string $text Text to search for nolink tag in
2715 function rebuildnolinktag($text) {
2717 $text = preg_replace('/<(\/*nolink)>/i', '<$1>', $text);
2723 * Prints a maintenance message from $CFG->maintenance_message or default if empty.
2725 function print_maintenance_message() {
2726 global $CFG, $SITE, $PAGE, $OUTPUT;
2728 $PAGE->set_pagetype('maintenance-message');
2729 $PAGE->set_pagelayout('maintenance');
2730 $PAGE->set_title(strip_tags($SITE->fullname
));
2731 $PAGE->set_heading($SITE->fullname
);
2732 echo $OUTPUT->header();
2733 echo $OUTPUT->heading(get_string('sitemaintenance', 'admin'));
2734 if (isset($CFG->maintenance_message
) and !html_is_blank($CFG->maintenance_message
)) {
2735 echo $OUTPUT->box_start('maintenance_message generalbox boxwidthwide boxaligncenter');
2736 echo $CFG->maintenance_message
;
2737 echo $OUTPUT->box_end();
2739 echo $OUTPUT->footer();
2744 * Returns a string containing a nested list, suitable for formatting into tabs with CSS.
2746 * It is not recommended to use this function in Moodle 2.5 but it is left for backward
2749 * Example how to print a single line tabs:
2751 * new tabobject(...),
2752 * new tabobject(...)
2754 * echo $OUTPUT->tabtree($rows, $selectedid);
2756 * Multiple row tabs may not look good on some devices but if you want to use them
2757 * you can specify ->subtree for the active tabobject.
2759 * @param array $tabrows An array of rows where each row is an array of tab objects
2760 * @param string $selected The id of the selected tab (whatever row it's on)
2761 * @param array $inactive An array of ids of inactive tabs that are not selectable.
2762 * @param array $activated An array of ids of other tabs that are currently activated
2763 * @param bool $return If true output is returned rather then echo'd
2764 * @return string HTML output if $return was set to true.
2766 function print_tabs($tabrows, $selected = null, $inactive = null, $activated = null, $return = false) {
2769 $tabrows = array_reverse($tabrows);
2771 foreach ($tabrows as $row) {
2774 foreach ($row as $tab) {
2775 $tab->inactive
= is_array($inactive) && in_array((string)$tab->id
, $inactive);
2776 $tab->activated
= is_array($activated) && in_array((string)$tab->id
, $activated);
2777 $tab->selected
= (string)$tab->id
== $selected;
2779 if ($tab->activated ||
$tab->selected
) {
2780 $tab->subtree
= $subtree;
2786 $output = $OUTPUT->tabtree($subtree);
2791 return !empty($output);
2796 * Alter debugging level for the current request,
2797 * the change is not saved in database.
2799 * @param int $level one of the DEBUG_* constants
2800 * @param bool $debugdisplay
2802 function set_debugging($level, $debugdisplay = null) {
2805 $CFG->debug
= (int)$level;
2806 $CFG->debugdeveloper
= (($CFG->debug
& DEBUG_DEVELOPER
) === DEBUG_DEVELOPER
);
2808 if ($debugdisplay !== null) {
2809 $CFG->debugdisplay
= (bool)$debugdisplay;
2814 * Standard Debugging Function
2816 * Returns true if the current site debugging settings are equal or above specified level.
2817 * If passed a parameter it will emit a debugging notice similar to trigger_error(). The
2818 * routing of notices is controlled by $CFG->debugdisplay
2821 * 1) debugging('a normal debug notice');
2822 * 2) debugging('something really picky', DEBUG_ALL);
2823 * 3) debugging('annoying debug message only for developers', DEBUG_DEVELOPER);
2824 * 4) if (debugging()) { perform extra debugging operations (do not use print or echo) }
2826 * In code blocks controlled by debugging() (such as example 4)
2827 * any output should be routed via debugging() itself, or the lower-level
2828 * trigger_error() or error_log(). Using echo or print will break XHTML
2829 * JS and HTTP headers.
2831 * It is also possible to define NO_DEBUG_DISPLAY which redirects the message to error_log.
2833 * @param string $message a message to print
2834 * @param int $level the level at which this debugging statement should show
2835 * @param array $backtrace use different backtrace
2838 function debugging($message = '', $level = DEBUG_NORMAL
, $backtrace = null) {
2841 $forcedebug = false;
2842 if (!empty($CFG->debugusers
) && $USER) {
2843 $debugusers = explode(',', $CFG->debugusers
);
2844 $forcedebug = in_array($USER->id
, $debugusers);
2847 if (!$forcedebug and (empty($CFG->debug
) ||
($CFG->debug
!= -1 and $CFG->debug
< $level))) {
2851 if (!isset($CFG->debugdisplay
)) {
2852 $CFG->debugdisplay
= ini_get_bool('display_errors');
2857 $backtrace = debug_backtrace();
2859 $from = format_backtrace($backtrace, CLI_SCRIPT || NO_DEBUG_DISPLAY
);
2861 if (phpunit_util
::debugging_triggered($message, $level, $from)) {
2862 // We are inside test, the debug message was logged.
2867 if (NO_DEBUG_DISPLAY
) {
2868 // Script does not want any errors or debugging in output,
2869 // we send the info to error log instead.
2870 error_log('Debugging: ' . $message . ' in '. PHP_EOL
. $from);
2872 } else if ($forcedebug or $CFG->debugdisplay
) {
2873 if (!defined('DEBUGGING_PRINTED')) {
2874 define('DEBUGGING_PRINTED', 1); // Indicates we have printed something.
2877 echo "++ $message ++\n$from";
2879 echo '<div class="notifytiny debuggingmessage" data-rel="debugging">' , $message , $from , '</div>';
2883 trigger_error($message . $from, E_USER_NOTICE
);
2890 * Outputs a HTML comment to the browser.
2892 * This is used for those hard-to-debug pages that use bits from many different files in very confusing ways (e.g. blocks).
2894 * <code>print_location_comment(__FILE__, __LINE__);</code>
2896 * @param string $file
2897 * @param integer $line
2898 * @param boolean $return Whether to return or print the comment
2899 * @return string|void Void unless true given as third parameter
2901 function print_location_comment($file, $line, $return = false) {
2903 return "<!-- $file at line $line -->\n";
2905 echo "<!-- $file at line $line -->\n";
2911 * Returns true if the user is using a right-to-left language.
2913 * @return boolean true if the current language is right-to-left (Hebrew, Arabic etc)
2915 function right_to_left() {
2916 return (get_string('thisdirection', 'langconfig') === 'rtl');
2921 * Returns swapped left<=> right if in RTL environment.
2923 * Part of RTL Moodles support.
2925 * @param string $align align to check
2928 function fix_align_rtl($align) {
2929 if (!right_to_left()) {
2932 if ($align == 'left') {
2935 if ($align == 'right') {
2943 * Returns true if the page is displayed in a popup window.
2945 * Gets the information from the URL parameter inpopup.
2947 * @todo Use a central function to create the popup calls all over Moodle and
2948 * In the moment only works with resources and probably questions.
2952 function is_in_popup() {
2953 $inpopup = optional_param('inpopup', '', PARAM_BOOL
);
2959 * Progress bar class.
2961 * Manages the display of a progress bar.
2963 * To use this class.
2965 * - call create (or use the 3rd param to the constructor)
2966 * - call update or update_full() or update() repeatedly
2968 * @copyright 2008 jamiesensei
2969 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2972 class progress_bar
{
2973 /** @var string html id */
2975 /** @var int total width */
2977 /** @var int last percentage printed */
2978 private $percent = 0;
2979 /** @var int time when last printed */
2980 private $lastupdate = 0;
2981 /** @var int when did we start printing this */
2982 private $time_start = 0;
2987 * Prints JS code if $autostart true.
2989 * @param string $html_id
2991 * @param bool $autostart Default to false
2993 public function __construct($htmlid = '', $width = 500, $autostart = false) {
2994 if (!empty($htmlid)) {
2995 $this->html_id
= $htmlid;
2997 $this->html_id
= 'pbar_'.uniqid();
3000 $this->width
= $width;
3008 * Create a new progress bar, this function will output html.
3010 * @return void Echo's output
3012 public function create() {
3013 $this->time_start
= microtime(true);
3015 return; // Temporary solution for cli scripts.
3017 $widthplusborder = $this->width +
2;
3019 <div style="text-align:center;width:{$widthplusborder}px;clear:both;padding:0;margin:0 auto;">
3020 <h2 id="status_{$this->html_id}" style="text-align: center;margin:0 auto"></h2>
3021 <p id="time_{$this->html_id}"></p>
3022 <div id="bar_{$this->html_id}" style="border-style:solid;border-width:1px;width:{$this->width}px;height:50px;">
3023 <div id="progress_{$this->html_id}"
3024 style="text-align:center;background:#FFCC66;width:4px;border:1px
3025 solid gray;height:38px; padding-top:10px;"> <span id="pt_{$this->html_id}"></span>
3036 * Update the progress bar
3038 * @param int $percent from 1-100
3039 * @param string $msg
3040 * @return void Echo's output
3041 * @throws coding_exception
3043 private function _update($percent, $msg) {
3044 if (empty($this->time_start
)) {
3045 throw new coding_exception('You must call create() (or use the $autostart ' .
3046 'argument to the constructor) before you try updating the progress bar.');
3050 return; // Temporary solution for cli scripts.
3053 $es = $this->estimate($percent);
3056 // Always do the first and last updates.
3058 } else if ($es == 0) {
3059 // Always do the last updates.
3060 } else if ($this->lastupdate +
20 < time()) {
3061 // We must update otherwise browser would time out.
3062 } else if (round($this->percent
, 2) === round($percent, 2)) {
3063 // No significant change, no need to update anything.
3067 $this->percent
= $percent;
3068 $this->lastupdate
= microtime(true);
3070 $w = ($this->percent
/100) * $this->width
;
3071 echo html_writer
::script(js_writer
::function_call('update_progress_bar',
3072 array($this->html_id
, $w, $this->percent
, $msg, $es)));
3077 * Estimate how much time it is going to take.
3079 * @param int $pt from 1-100
3080 * @return mixed Null (unknown), or int
3082 private function estimate($pt) {
3083 if ($this->lastupdate
== 0) {
3086 if ($pt < 0.00001) {
3087 return null; // We do not know yet how long it will take.
3089 if ($pt > 99.99999) {
3090 return 0; // Nearly done, right?
3092 $consumed = microtime(true) - $this->time_start
;
3093 if ($consumed < 0.001) {
3097 return (100 - $pt) * ($consumed / $pt);
3101 * Update progress bar according percent
3103 * @param int $percent from 1-100
3104 * @param string $msg the message needed to be shown
3106 public function update_full($percent, $msg) {
3107 $percent = max(min($percent, 100), 0);
3108 $this->_update($percent, $msg);
3112 * Update progress bar according the number of tasks
3114 * @param int $cur current task number
3115 * @param int $total total task number
3116 * @param string $msg message
3118 public function update($cur, $total, $msg) {
3119 $percent = ($cur / $total) * 100;
3120 $this->update_full($percent, $msg);
3124 * Restart the progress bar.
3126 public function restart() {
3128 $this->lastupdate
= 0;
3129 $this->time_start
= 0;
3134 * Progress trace class.
3136 * Use this class from long operations where you want to output occasional information about
3137 * what is going on, but don't know if, or in what format, the output should be.
3139 * @copyright 2009 Tim Hunt
3140 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3143 abstract class progress_trace
{
3145 * Output an progress message in whatever format.
3147 * @param string $message the message to output.
3148 * @param integer $depth indent depth for this message.
3150 abstract public function output($message, $depth = 0);
3153 * Called when the processing is finished.
3155 public function finished() {
3160 * This subclass of progress_trace does not ouput anything.
3162 * @copyright 2009 Tim Hunt
3163 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3166 class null_progress_trace
extends progress_trace
{
3170 * @param string $message
3172 * @return void Does Nothing
3174 public function output($message, $depth = 0) {
3179 * This subclass of progress_trace outputs to plain text.
3181 * @copyright 2009 Tim Hunt
3182 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3185 class text_progress_trace
extends progress_trace
{
3187 * Output the trace message.
3189 * @param string $message
3191 * @return void Output is echo'd
3193 public function output($message, $depth = 0) {
3194 echo str_repeat(' ', $depth), $message, "\n";
3200 * This subclass of progress_trace outputs as HTML.
3202 * @copyright 2009 Tim Hunt
3203 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3206 class html_progress_trace
extends progress_trace
{
3208 * Output the trace message.
3210 * @param string $message
3212 * @return void Output is echo'd
3214 public function output($message, $depth = 0) {
3215 echo '<p>', str_repeat('  ', $depth), htmlspecialchars($message), "</p>\n";
3221 * HTML List Progress Tree
3223 * @copyright 2009 Tim Hunt
3224 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3227 class html_list_progress_trace
extends progress_trace
{
3229 protected $currentdepth = -1;
3234 * @param string $message The message to display
3236 * @return void Output is echoed
3238 public function output($message, $depth = 0) {
3240 while ($this->currentdepth
> $depth) {
3241 echo "</li>\n</ul>\n";
3242 $this->currentdepth
-= 1;
3243 if ($this->currentdepth
== $depth) {
3248 while ($this->currentdepth
< $depth) {
3250 $this->currentdepth +
= 1;
3256 echo htmlspecialchars($message);
3261 * Called when the processing is finished.
3263 public function finished() {
3264 while ($this->currentdepth
>= 0) {
3265 echo "</li>\n</ul>\n";
3266 $this->currentdepth
-= 1;
3272 * This subclass of progress_trace outputs to error log.
3274 * @copyright Petr Skoda {@link http://skodak.org}
3275 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3278 class error_log_progress_trace
extends progress_trace
{
3279 /** @var string log prefix */
3284 * @param string $prefix optional log prefix
3286 public function __construct($prefix = '') {
3287 $this->prefix
= $prefix;
3291 * Output the trace message.
3293 * @param string $message
3295 * @return void Output is sent to error log.
3297 public function output($message, $depth = 0) {
3298 error_log($this->prefix
. str_repeat(' ', $depth) . $message);
3303 * Special type of trace that can be used for catching of output of other traces.
3305 * @copyright Petr Skoda {@link http://skodak.org}
3306 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3309 class progress_trace_buffer
extends progress_trace
{
3310 /** @var progres_trace */
3312 /** @var bool do we pass output out */
3313 protected $passthrough;
3314 /** @var string output buffer */
3320 * @param progress_trace $trace
3321 * @param bool $passthrough true means output and buffer, false means just buffer and no output
3323 public function __construct(progress_trace
$trace, $passthrough = true) {
3324 $this->trace
= $trace;
3325 $this->passthrough
= $passthrough;
3330 * Output the trace message.
3332 * @param string $message the message to output.
3333 * @param int $depth indent depth for this message.
3334 * @return void output stored in buffer
3336 public function output($message, $depth = 0) {
3338 $this->trace
->output($message, $depth);
3339 $this->buffer
.= ob_get_contents();
3340 if ($this->passthrough
) {
3348 * Called when the processing is finished.
3350 public function finished() {
3352 $this->trace
->finished();
3353 $this->buffer
.= ob_get_contents();
3354 if ($this->passthrough
) {
3362 * Reset internal text buffer.
3364 public function reset_buffer() {
3369 * Return internal text buffer.
3370 * @return string buffered plain text
3372 public function get_buffer() {
3373 return $this->buffer
;
3378 * Special type of trace that can be used for redirecting to multiple other traces.
3380 * @copyright Petr Skoda {@link http://skodak.org}
3381 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3384 class combined_progress_trace
extends progress_trace
{
3387 * An array of traces.
3393 * Constructs a new instance.
3395 * @param array $traces multiple traces
3397 public function __construct(array $traces) {
3398 $this->traces
= $traces;
3402 * Output an progress message in whatever format.
3404 * @param string $message the message to output.
3405 * @param integer $depth indent depth for this message.
3407 public function output($message, $depth = 0) {
3408 foreach ($this->traces
as $trace) {
3409 $trace->output($message, $depth);
3414 * Called when the processing is finished.
3416 public function finished() {
3417 foreach ($this->traces
as $trace) {
3424 * Returns a localized sentence in the current language summarizing the current password policy
3426 * @todo this should be handled by a function/method in the language pack library once we have a support for it
3430 function print_password_policy() {
3434 if (!empty($CFG->passwordpolicy
)) {
3435 $messages = array();
3436 $messages[] = get_string('informminpasswordlength', 'auth', $CFG->minpasswordlength
);
3437 if (!empty($CFG->minpassworddigits
)) {
3438 $messages[] = get_string('informminpassworddigits', 'auth', $CFG->minpassworddigits
);
3440 if (!empty($CFG->minpasswordlower
)) {
3441 $messages[] = get_string('informminpasswordlower', 'auth', $CFG->minpasswordlower
);
3443 if (!empty($CFG->minpasswordupper
)) {
3444 $messages[] = get_string('informminpasswordupper', 'auth', $CFG->minpasswordupper
);
3446 if (!empty($CFG->minpasswordnonalphanum
)) {
3447 $messages[] = get_string('informminpasswordnonalphanum', 'auth', $CFG->minpasswordnonalphanum
);
3450 $messages = join(', ', $messages); // This is ugly but we do not have anything better yet...
3451 $message = get_string('informpasswordpolicy', 'auth', $messages);
3457 * Get the value of a help string fully prepared for display in the current language.
3459 * @param string $identifier The identifier of the string to search for.
3460 * @param string $component The module the string is associated with.
3461 * @param boolean $ajax Whether this help is called from an AJAX script.
3462 * This is used to influence text formatting and determines
3463 * which format to output the doclink in.
3464 * @return Object An object containing:
3465 * - heading: Any heading that there may be for this help string.
3466 * - text: The wiki-formatted help string.
3467 * - doclink: An object containing a link, the linktext, and any additional
3468 * CSS classes to apply to that link. Only present if $ajax = false.
3469 * - completedoclink: A text representation of the doclink. Only present if $ajax = true.
3471 function get_formatted_help_string($identifier, $component, $ajax = false) {
3472 global $CFG, $OUTPUT;
3473 $sm = get_string_manager();
3475 // Do not rebuild caches here!
3476 // Devs need to learn to purge all caches after any change or disable $CFG->langstringcache.
3478 $data = new stdClass();
3480 if ($sm->string_exists($identifier, $component)) {
3481 $data->heading
= format_string(get_string($identifier, $component));
3483 // Gracefully fall back to an empty string.
3484 $data->heading
= '';
3487 if ($sm->string_exists($identifier . '_help', $component)) {
3488 $options = new stdClass();
3489 $options->trusted
= false;
3490 $options->noclean
= false;
3491 $options->smiley
= false;
3492 $options->filter
= false;
3493 $options->para
= true;
3494 $options->newlines
= false;
3495 $options->overflowdiv
= !$ajax;
3497 // Should be simple wiki only MDL-21695.
3498 $data->text
= format_text(get_string($identifier.'_help', $component), FORMAT_MARKDOWN
, $options);
3500 $helplink = $identifier . '_link';
3501 if ($sm->string_exists($helplink, $component)) { // Link to further info in Moodle docs.
3502 $link = get_string($helplink, $component);
3503 $linktext = get_string('morehelp');
3505 $data->doclink
= new stdClass();
3506 $url = new moodle_url(get_docs_url($link));
3508 $data->doclink
->link
= $url->out();
3509 $data->doclink
->linktext
= $linktext;
3510 $data->doclink
->class = ($CFG->doctonewwindow
) ?
'helplinkpopup' : '';
3512 $data->completedoclink
= html_writer
::tag('div', $OUTPUT->doc_link($link, $linktext),
3513 array('class' => 'helpdoclink'));
3517 $data->text
= html_writer
::tag('p',
3518 html_writer
::tag('strong', 'TODO') . ": missing help string [{$identifier}_help, {$component}]");