NOBUG: Fixed SVG browser compatibility
[moodle.git] / lib / weblib.php
blobab4c9031653c900fab4c4fed58a6cad8c569bcce
1 <?php
2 // This file is part of Moodle - http://moodle.org/
3 //
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.
8 //
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/>.
17 /**
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.
27 * @package core
28 * @subpackage lib
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();
35 // Constants.
37 // Define text formatting types ... eventually we can add Wiki, BBcode etc.
39 /**
40 * Does all sorts of transformations and filtering.
42 define('FORMAT_MOODLE', '0');
44 /**
45 * Plain HTML (with some tags stripped).
47 define('FORMAT_HTML', '1');
49 /**
50 * Plain text (even tags are printed in full).
52 define('FORMAT_PLAIN', '2');
54 /**
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');
62 /**
63 * Markdown-formatted text http://daringfireball.net/projects/markdown/
65 define('FORMAT_MARKDOWN', '4');
67 /**
68 * A moodle_url comparison using this flag will return true if the base URLs match, params are ignored.
70 define('URL_MATCH_BASE', 0);
72 /**
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);
77 /**
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);
82 // Functions.
84 /**
85 * Add quotes to HTML characters.
87 * Returns $var with HTML characters (like "<", ">", etc.) properly quoted.
88 * Related function {@link p()} simply prints the output of this function.
90 * @param string $var the string potentially containing HTML characters
91 * @return string
93 function s($var) {
94 if ($var === false) {
95 return '0';
98 if ($var === null || $var === '') {
99 return '';
102 return preg_replace(
103 '/&amp;#(\d+|x[0-9a-f]+);/i', '&#$1;',
104 htmlspecialchars($var, ENT_QUOTES | ENT_HTML401 | ENT_SUBSTITUTE)
109 * Add quotes to HTML characters.
111 * Prints $var with HTML characters (like "<", ">", etc.) properly quoted.
112 * This function simply calls & displays {@link s()}.
113 * @see s()
115 * @param string $var the string potentially containing HTML characters
117 function p($var) {
118 echo s($var);
122 * Does proper javascript quoting.
124 * Do not use addslashes anymore, because it does not work when magic_quotes_sybase is enabled.
126 * @param mixed $var String, Array, or Object to add slashes to
127 * @return mixed quoted result
129 function addslashes_js($var) {
130 if (is_string($var)) {
131 $var = str_replace('\\', '\\\\', $var);
132 $var = str_replace(array('\'', '"', "\n", "\r", "\0"), array('\\\'', '\\"', '\\n', '\\r', '\\0'), $var);
133 $var = str_replace('</', '<\/', $var); // XHTML compliance.
134 } else if (is_array($var)) {
135 $var = array_map('addslashes_js', $var);
136 } else if (is_object($var)) {
137 $a = get_object_vars($var);
138 foreach ($a as $key => $value) {
139 $a[$key] = addslashes_js($value);
141 $var = (object)$a;
143 return $var;
147 * Remove query string from url.
149 * Takes in a URL and returns it without the querystring portion.
151 * @param string $url the url which may have a query string attached.
152 * @return string The remaining URL.
154 function strip_querystring($url) {
155 if ($url === null || $url === '') {
156 return '';
159 if ($commapos = strpos($url, '?')) {
160 return substr($url, 0, $commapos);
161 } else {
162 return $url;
167 * Returns the name of the current script, WITH the querystring portion.
169 * This function is necessary because PHP_SELF and REQUEST_URI and SCRIPT_NAME
170 * return different things depending on a lot of things like your OS, Web
171 * server, and the way PHP is compiled (ie. as a CGI, module, ISAPI, etc.)
172 * <b>NOTE:</b> This function returns false if the global variables needed are not set.
174 * @return mixed String or false if the global variables needed are not set.
176 function me() {
177 global $ME;
178 return $ME;
182 * Guesses the full URL of the current script.
184 * This function is using $PAGE->url, but may fall back to $FULLME which
185 * is constructed from PHP_SELF and REQUEST_URI or SCRIPT_NAME
187 * @return mixed full page URL string or false if unknown
189 function qualified_me() {
190 global $FULLME, $PAGE, $CFG;
192 if (isset($PAGE) and $PAGE->has_set_url()) {
193 // This is the only recommended way to find out current page.
194 return $PAGE->url->out(false);
196 } else {
197 if ($FULLME === null) {
198 // CLI script most probably.
199 return false;
201 if (!empty($CFG->sslproxy)) {
202 // Return only https links when using SSL proxy.
203 return preg_replace('/^http:/', 'https:', $FULLME, 1);
204 } else {
205 return $FULLME;
211 * Determines whether or not the Moodle site is being served over HTTPS.
213 * This is done simply by checking the value of $CFG->wwwroot, which seems
214 * to be the only reliable method.
216 * @return boolean True if site is served over HTTPS, false otherwise.
218 function is_https() {
219 global $CFG;
221 return (strpos($CFG->wwwroot, 'https://') === 0);
225 * Returns the cleaned local URL of the HTTP_REFERER less the URL query string parameters if required.
227 * @param bool $stripquery if true, also removes the query part of the url.
228 * @return string The resulting referer or empty string.
230 function get_local_referer($stripquery = true) {
231 if (isset($_SERVER['HTTP_REFERER'])) {
232 $referer = clean_param($_SERVER['HTTP_REFERER'], PARAM_LOCALURL);
233 if ($stripquery) {
234 return strip_querystring($referer);
235 } else {
236 return $referer;
238 } else {
239 return '';
244 * Class for creating and manipulating urls.
246 * It can be used in moodle pages where config.php has been included without any further includes.
248 * It is useful for manipulating urls with long lists of params.
249 * One situation where it will be useful is a page which links to itself to perform various actions
250 * and / or to process form data. A moodle_url object :
251 * can be created for a page to refer to itself with all the proper get params being passed from page call to
252 * page call and methods can be used to output a url including all the params, optionally adding and overriding
253 * params and can also be used to
254 * - output the url without any get params
255 * - and output the params as hidden fields to be output within a form
257 * @copyright 2007 jamiesensei
258 * @link http://docs.moodle.org/dev/lib/weblib.php_moodle_url See short write up here
259 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
260 * @package core
262 class moodle_url {
265 * Scheme, ex.: http, https
266 * @var string
268 protected $scheme = '';
271 * Hostname.
272 * @var string
274 protected $host = '';
277 * Port number, empty means default 80 or 443 in case of http.
278 * @var int
280 protected $port = '';
283 * Username for http auth.
284 * @var string
286 protected $user = '';
289 * Password for http auth.
290 * @var string
292 protected $pass = '';
295 * Script path.
296 * @var string
298 protected $path = '';
301 * Optional slash argument value.
302 * @var string
304 protected $slashargument = '';
307 * Anchor, may be also empty, null means none.
308 * @var string
310 protected $anchor = null;
313 * Url parameters as associative array.
314 * @var array
316 protected $params = array();
319 * Create new instance of moodle_url.
321 * @param moodle_url|string $url - moodle_url means make a copy of another
322 * moodle_url and change parameters, string means full url or shortened
323 * form (ex.: '/course/view.php'). It is strongly encouraged to not include
324 * query string because it may result in double encoded values. Use the
325 * $params instead. For admin URLs, just use /admin/script.php, this
326 * class takes care of the $CFG->admin issue.
327 * @param array $params these params override current params or add new
328 * @param string $anchor The anchor to use as part of the URL if there is one.
329 * @throws moodle_exception
331 public function __construct($url, array $params = null, $anchor = null) {
332 global $CFG;
334 if ($url instanceof moodle_url) {
335 $this->scheme = $url->scheme;
336 $this->host = $url->host;
337 $this->port = $url->port;
338 $this->user = $url->user;
339 $this->pass = $url->pass;
340 $this->path = $url->path;
341 $this->slashargument = $url->slashargument;
342 $this->params = $url->params;
343 $this->anchor = $url->anchor;
345 } else {
346 $url = $url ?? '';
347 // Detect if anchor used.
348 $apos = strpos($url, '#');
349 if ($apos !== false) {
350 $anchor = substr($url, $apos);
351 $anchor = ltrim($anchor, '#');
352 $this->set_anchor($anchor);
353 $url = substr($url, 0, $apos);
356 // Normalise shortened form of our url ex.: '/course/view.php'.
357 if (strpos($url, '/') === 0) {
358 $url = $CFG->wwwroot.$url;
361 if ($CFG->admin !== 'admin') {
362 if (strpos($url, "$CFG->wwwroot/admin/") === 0) {
363 $url = str_replace("$CFG->wwwroot/admin/", "$CFG->wwwroot/$CFG->admin/", $url);
367 // Parse the $url.
368 $parts = parse_url($url);
369 if ($parts === false) {
370 throw new moodle_exception('invalidurl');
372 if (isset($parts['query'])) {
373 // Note: the values may not be correctly decoded, url parameters should be always passed as array.
374 parse_str(str_replace('&amp;', '&', $parts['query']), $this->params);
376 unset($parts['query']);
377 foreach ($parts as $key => $value) {
378 $this->$key = $value;
381 // Detect slashargument value from path - we do not support directory names ending with .php.
382 $pos = strpos($this->path, '.php/');
383 if ($pos !== false) {
384 $this->slashargument = substr($this->path, $pos + 4);
385 $this->path = substr($this->path, 0, $pos + 4);
389 $this->params($params);
390 if ($anchor !== null) {
391 $this->anchor = (string)$anchor;
396 * Add an array of params to the params for this url.
398 * The added params override existing ones if they have the same name.
400 * @param array $params Defaults to null. If null then returns all params.
401 * @return array Array of Params for url.
402 * @throws coding_exception
404 public function params(array $params = null) {
405 $params = (array)$params;
407 foreach ($params as $key => $value) {
408 if (is_int($key)) {
409 throw new coding_exception('Url parameters can not have numeric keys!');
411 if (!is_string($value)) {
412 if (is_array($value)) {
413 throw new coding_exception('Url parameters values can not be arrays!');
415 if (is_object($value) and !method_exists($value, '__toString')) {
416 throw new coding_exception('Url parameters values can not be objects, unless __toString() is defined!');
419 $this->params[$key] = (string)$value;
421 return $this->params;
425 * Remove all params if no arguments passed.
426 * Remove selected params if arguments are passed.
428 * Can be called as either remove_params('param1', 'param2')
429 * or remove_params(array('param1', 'param2')).
431 * @param string[]|string $params,... either an array of param names, or 1..n string params to remove as args.
432 * @return array url parameters
434 public function remove_params($params = null) {
435 if (!is_array($params)) {
436 $params = func_get_args();
438 foreach ($params as $param) {
439 unset($this->params[$param]);
441 return $this->params;
445 * Remove all url parameters.
447 * @todo remove the unused param.
448 * @param array $params Unused param
449 * @return void
451 public function remove_all_params($params = null) {
452 $this->params = array();
453 $this->slashargument = '';
457 * Add a param to the params for this url.
459 * The added param overrides existing one if they have the same name.
461 * @param string $paramname name
462 * @param string $newvalue Param value. If new value specified current value is overriden or parameter is added
463 * @return mixed string parameter value, null if parameter does not exist
465 public function param($paramname, $newvalue = '') {
466 if (func_num_args() > 1) {
467 // Set new value.
468 $this->params(array($paramname => $newvalue));
470 if (isset($this->params[$paramname])) {
471 return $this->params[$paramname];
472 } else {
473 return null;
478 * Merges parameters and validates them
480 * @param array $overrideparams
481 * @return array merged parameters
482 * @throws coding_exception
484 protected function merge_overrideparams(array $overrideparams = null) {
485 $overrideparams = (array)$overrideparams;
486 $params = $this->params;
487 foreach ($overrideparams as $key => $value) {
488 if (is_int($key)) {
489 throw new coding_exception('Overridden parameters can not have numeric keys!');
491 if (is_array($value)) {
492 throw new coding_exception('Overridden parameters values can not be arrays!');
494 if (is_object($value) and !method_exists($value, '__toString')) {
495 throw new coding_exception('Overridden parameters values can not be objects, unless __toString() is defined!');
497 $params[$key] = (string)$value;
499 return $params;
503 * Get the params as as a query string.
505 * This method should not be used outside of this method.
507 * @param bool $escaped Use &amp; as params separator instead of plain &
508 * @param array $overrideparams params to add to the output params, these
509 * override existing ones with the same name.
510 * @return string query string that can be added to a url.
512 public function get_query_string($escaped = true, array $overrideparams = null) {
513 $arr = array();
514 if ($overrideparams !== null) {
515 $params = $this->merge_overrideparams($overrideparams);
516 } else {
517 $params = $this->params;
519 foreach ($params as $key => $val) {
520 if (is_array($val)) {
521 foreach ($val as $index => $value) {
522 $arr[] = rawurlencode($key.'['.$index.']')."=".rawurlencode($value);
524 } else {
525 if (isset($val) && $val !== '') {
526 $arr[] = rawurlencode($key)."=".rawurlencode($val);
527 } else {
528 $arr[] = rawurlencode($key);
532 if ($escaped) {
533 return implode('&amp;', $arr);
534 } else {
535 return implode('&', $arr);
540 * Get the url params as an array of key => value pairs.
542 * This helps in handling cases where url params contain arrays.
544 * @return array params array for templates.
546 public function export_params_for_template(): array {
547 $data = [];
548 foreach ($this->params as $key => $val) {
549 if (is_array($val)) {
550 foreach ($val as $index => $value) {
551 $data[] = ['name' => $key.'['.$index.']', 'value' => $value];
553 } else {
554 $data[] = ['name' => $key, 'value' => $val];
557 return $data;
561 * Shortcut for printing of encoded URL.
563 * @return string
565 public function __toString() {
566 return $this->out(true);
570 * Output url.
572 * If you use the returned URL in HTML code, you want the escaped ampersands. If you use
573 * the returned URL in HTTP headers, you want $escaped=false.
575 * @param bool $escaped Use &amp; as params separator instead of plain &
576 * @param array $overrideparams params to add to the output url, these override existing ones with the same name.
577 * @return string Resulting URL
579 public function out($escaped = true, array $overrideparams = null) {
581 global $CFG;
583 if (!is_bool($escaped)) {
584 debugging('Escape parameter must be of type boolean, '.gettype($escaped).' given instead.');
587 $url = $this;
589 // Allow url's to be rewritten by a plugin.
590 if (isset($CFG->urlrewriteclass) && !isset($CFG->upgraderunning)) {
591 $class = $CFG->urlrewriteclass;
592 $pluginurl = $class::url_rewrite($url);
593 if ($pluginurl instanceof moodle_url) {
594 $url = $pluginurl;
598 return $url->raw_out($escaped, $overrideparams);
603 * Output url without any rewrites
605 * This is identical in signature and use to out() but doesn't call the rewrite handler.
607 * @param bool $escaped Use &amp; as params separator instead of plain &
608 * @param array $overrideparams params to add to the output url, these override existing ones with the same name.
609 * @return string Resulting URL
611 public function raw_out($escaped = true, array $overrideparams = null) {
612 if (!is_bool($escaped)) {
613 debugging('Escape parameter must be of type boolean, '.gettype($escaped).' given instead.');
616 $uri = $this->out_omit_querystring().$this->slashargument;
618 $querystring = $this->get_query_string($escaped, $overrideparams);
619 if ($querystring !== '') {
620 $uri .= '?' . $querystring;
622 if (!is_null($this->anchor)) {
623 $uri .= '#'.$this->anchor;
626 return $uri;
630 * Returns url without parameters, everything before '?'.
632 * @param bool $includeanchor if {@link self::anchor} is defined, should it be returned?
633 * @return string
635 public function out_omit_querystring($includeanchor = false) {
637 $uri = $this->scheme ? $this->scheme.':'.((strtolower($this->scheme) == 'mailto') ? '':'//'): '';
638 $uri .= $this->user ? $this->user.($this->pass? ':'.$this->pass:'').'@':'';
639 $uri .= $this->host ? $this->host : '';
640 $uri .= $this->port ? ':'.$this->port : '';
641 $uri .= $this->path ? $this->path : '';
642 if ($includeanchor and !is_null($this->anchor)) {
643 $uri .= '#' . $this->anchor;
646 return $uri;
650 * Compares this moodle_url with another.
652 * See documentation of constants for an explanation of the comparison flags.
654 * @param moodle_url $url The moodle_url object to compare
655 * @param int $matchtype The type of comparison (URL_MATCH_BASE, URL_MATCH_PARAMS, URL_MATCH_EXACT)
656 * @return bool
658 public function compare(moodle_url $url, $matchtype = URL_MATCH_EXACT) {
660 $baseself = $this->out_omit_querystring();
661 $baseother = $url->out_omit_querystring();
663 // Append index.php if there is no specific file.
664 if (substr($baseself, -1) == '/') {
665 $baseself .= 'index.php';
667 if (substr($baseother, -1) == '/') {
668 $baseother .= 'index.php';
671 // Compare the two base URLs.
672 if ($baseself != $baseother) {
673 return false;
676 if ($matchtype == URL_MATCH_BASE) {
677 return true;
680 $urlparams = $url->params();
681 foreach ($this->params() as $param => $value) {
682 if ($param == 'sesskey') {
683 continue;
685 if (!array_key_exists($param, $urlparams) || $urlparams[$param] != $value) {
686 return false;
690 if ($matchtype == URL_MATCH_PARAMS) {
691 return true;
694 foreach ($urlparams as $param => $value) {
695 if ($param == 'sesskey') {
696 continue;
698 if (!array_key_exists($param, $this->params()) || $this->param($param) != $value) {
699 return false;
703 if ($url->anchor !== $this->anchor) {
704 return false;
707 return true;
711 * Sets the anchor for the URI (the bit after the hash)
713 * @param string $anchor null means remove previous
715 public function set_anchor($anchor) {
716 if (is_null($anchor)) {
717 // Remove.
718 $this->anchor = null;
719 } else if ($anchor === '') {
720 // Special case, used as empty link.
721 $this->anchor = '';
722 } else if (preg_match('|[a-zA-Z\_\:][a-zA-Z0-9\_\-\.\:]*|', $anchor)) {
723 // Match the anchor against the NMTOKEN spec.
724 $this->anchor = $anchor;
725 } else {
726 // Bad luck, no valid anchor found.
727 $this->anchor = null;
732 * Sets the scheme for the URI (the bit before ://)
734 * @param string $scheme
736 public function set_scheme($scheme) {
737 // See http://www.ietf.org/rfc/rfc3986.txt part 3.1.
738 if (preg_match('/^[a-zA-Z][a-zA-Z0-9+.-]*$/', $scheme)) {
739 $this->scheme = $scheme;
740 } else {
741 throw new coding_exception('Bad URL scheme.');
746 * Sets the url slashargument value.
748 * @param string $path usually file path
749 * @param string $parameter name of page parameter if slasharguments not supported
750 * @param bool $supported usually null, then it depends on $CFG->slasharguments, use true or false for other servers
751 * @return void
753 public function set_slashargument($path, $parameter = 'file', $supported = null) {
754 global $CFG;
755 if (is_null($supported)) {
756 $supported = !empty($CFG->slasharguments);
759 if ($supported) {
760 $parts = explode('/', $path);
761 $parts = array_map('rawurlencode', $parts);
762 $path = implode('/', $parts);
763 $this->slashargument = $path;
764 unset($this->params[$parameter]);
766 } else {
767 $this->slashargument = '';
768 $this->params[$parameter] = $path;
772 // Static factory methods.
775 * General moodle file url.
777 * @param string $urlbase the script serving the file
778 * @param string $path
779 * @param bool $forcedownload
780 * @return moodle_url
782 public static function make_file_url($urlbase, $path, $forcedownload = false) {
783 $params = array();
784 if ($forcedownload) {
785 $params['forcedownload'] = 1;
787 $url = new moodle_url($urlbase, $params);
788 $url->set_slashargument($path);
789 return $url;
793 * Factory method for creation of url pointing to plugin file.
795 * Please note this method can be used only from the plugins to
796 * create urls of own files, it must not be used outside of plugins!
798 * @param int $contextid
799 * @param string $component
800 * @param string $area
801 * @param int $itemid
802 * @param string $pathname
803 * @param string $filename
804 * @param bool $forcedownload
805 * @param mixed $includetoken Whether to use a user token when displaying this group image.
806 * True indicates to generate a token for current user, and integer value indicates to generate a token for the
807 * user whose id is the value indicated.
808 * If the group picture is included in an e-mail or some other location where the audience is a specific
809 * user who will not be logged in when viewing, then we use a token to authenticate the user.
810 * @return moodle_url
812 public static function make_pluginfile_url($contextid, $component, $area, $itemid, $pathname, $filename,
813 $forcedownload = false, $includetoken = false) {
814 global $CFG, $USER;
816 $path = [];
818 if ($includetoken) {
819 $urlbase = "$CFG->wwwroot/tokenpluginfile.php";
820 $userid = $includetoken === true ? $USER->id : $includetoken;
821 $token = get_user_key('core_files', $userid);
822 if ($CFG->slasharguments) {
823 $path[] = $token;
825 } else {
826 $urlbase = "$CFG->wwwroot/pluginfile.php";
828 $path[] = $contextid;
829 $path[] = $component;
830 $path[] = $area;
832 if ($itemid !== null) {
833 $path[] = $itemid;
836 $path = "/" . implode('/', $path) . "{$pathname}{$filename}";
838 $url = self::make_file_url($urlbase, $path, $forcedownload, $includetoken);
839 if ($includetoken && empty($CFG->slasharguments)) {
840 $url->param('token', $token);
842 return $url;
846 * Factory method for creation of url pointing to plugin file.
847 * This method is the same that make_pluginfile_url but pointing to the webservice pluginfile.php script.
848 * It should be used only in external functions.
850 * @since 2.8
851 * @param int $contextid
852 * @param string $component
853 * @param string $area
854 * @param int $itemid
855 * @param string $pathname
856 * @param string $filename
857 * @param bool $forcedownload
858 * @return moodle_url
860 public static function make_webservice_pluginfile_url($contextid, $component, $area, $itemid, $pathname, $filename,
861 $forcedownload = false) {
862 global $CFG;
863 $urlbase = "$CFG->wwwroot/webservice/pluginfile.php";
864 if ($itemid === null) {
865 return self::make_file_url($urlbase, "/$contextid/$component/$area".$pathname.$filename, $forcedownload);
866 } else {
867 return self::make_file_url($urlbase, "/$contextid/$component/$area/$itemid".$pathname.$filename, $forcedownload);
872 * Factory method for creation of url pointing to draft file of current user.
874 * @param int $draftid draft item id
875 * @param string $pathname
876 * @param string $filename
877 * @param bool $forcedownload
878 * @return moodle_url
880 public static function make_draftfile_url($draftid, $pathname, $filename, $forcedownload = false) {
881 global $CFG, $USER;
882 $urlbase = "$CFG->wwwroot/draftfile.php";
883 $context = context_user::instance($USER->id);
885 return self::make_file_url($urlbase, "/$context->id/user/draft/$draftid".$pathname.$filename, $forcedownload);
889 * Factory method for creating of links to legacy course files.
891 * @param int $courseid
892 * @param string $filepath
893 * @param bool $forcedownload
894 * @return moodle_url
896 public static function make_legacyfile_url($courseid, $filepath, $forcedownload = false) {
897 global $CFG;
899 $urlbase = "$CFG->wwwroot/file.php";
900 return self::make_file_url($urlbase, '/'.$courseid.'/'.$filepath, $forcedownload);
904 * Checks if URL is relative to $CFG->wwwroot.
906 * @return bool True if URL is relative to $CFG->wwwroot; otherwise, false.
908 public function is_local_url() : bool {
909 global $CFG;
911 $url = $this->out();
912 // Does URL start with wwwroot? Otherwise, URL isn't relative to wwwroot.
913 return ( ($url === $CFG->wwwroot) || (strpos($url, $CFG->wwwroot.'/') === 0) );
917 * Returns URL as relative path from $CFG->wwwroot
919 * Can be used for passing around urls with the wwwroot stripped
921 * @param boolean $escaped Use &amp; as params separator instead of plain &
922 * @param array $overrideparams params to add to the output url, these override existing ones with the same name.
923 * @return string Resulting URL
924 * @throws coding_exception if called on a non-local url
926 public function out_as_local_url($escaped = true, array $overrideparams = null) {
927 global $CFG;
929 // URL should be relative to wwwroot. If not then throw exception.
930 if ($this->is_local_url()) {
931 $url = $this->out($escaped, $overrideparams);
932 $localurl = substr($url, strlen($CFG->wwwroot));
933 return !empty($localurl) ? $localurl : '';
934 } else {
935 throw new coding_exception('out_as_local_url called on a non-local URL');
940 * Returns the 'path' portion of a URL. For example, if the URL is
941 * http://www.example.org:447/my/file/is/here.txt?really=1 then this will
942 * return '/my/file/is/here.txt'.
944 * By default the path includes slash-arguments (for example,
945 * '/myfile.php/extra/arguments') so it is what you would expect from a
946 * URL path. If you don't want this behaviour, you can opt to exclude the
947 * slash arguments. (Be careful: if the $CFG variable slasharguments is
948 * disabled, these URLs will have a different format and you may need to
949 * look at the 'file' parameter too.)
951 * @param bool $includeslashargument If true, includes slash arguments
952 * @return string Path of URL
954 public function get_path($includeslashargument = true) {
955 return $this->path . ($includeslashargument ? $this->slashargument : '');
959 * Returns a given parameter value from the URL.
961 * @param string $name Name of parameter
962 * @return string Value of parameter or null if not set
964 public function get_param($name) {
965 if (array_key_exists($name, $this->params)) {
966 return $this->params[$name];
967 } else {
968 return null;
973 * Returns the 'scheme' portion of a URL. For example, if the URL is
974 * http://www.example.org:447/my/file/is/here.txt?really=1 then this will
975 * return 'http' (without the colon).
977 * @return string Scheme of the URL.
979 public function get_scheme() {
980 return $this->scheme;
984 * Returns the 'host' portion of a URL. For example, if the URL is
985 * http://www.example.org:447/my/file/is/here.txt?really=1 then this will
986 * return 'www.example.org'.
988 * @return string Host of the URL.
990 public function get_host() {
991 return $this->host;
995 * Returns the 'port' portion of a URL. For example, if the URL is
996 * http://www.example.org:447/my/file/is/here.txt?really=1 then this will
997 * return '447'.
999 * @return string Port of the URL.
1001 public function get_port() {
1002 return $this->port;
1007 * Determine if there is data waiting to be processed from a form
1009 * Used on most forms in Moodle to check for data
1010 * Returns the data as an object, if it's found.
1011 * This object can be used in foreach loops without
1012 * casting because it's cast to (array) automatically
1014 * Checks that submitted POST data exists and returns it as object.
1016 * @return mixed false or object
1018 function data_submitted() {
1020 if (empty($_POST)) {
1021 return false;
1022 } else {
1023 return (object)fix_utf8($_POST);
1028 * Given some normal text this function will break up any
1029 * long words to a given size by inserting the given character
1031 * It's multibyte savvy and doesn't change anything inside html tags.
1033 * @param string $string the string to be modified
1034 * @param int $maxsize maximum length of the string to be returned
1035 * @param string $cutchar the string used to represent word breaks
1036 * @return string
1038 function break_up_long_words($string, $maxsize=20, $cutchar=' ') {
1040 // First of all, save all the tags inside the text to skip them.
1041 $tags = array();
1042 filter_save_tags($string, $tags);
1044 // Process the string adding the cut when necessary.
1045 $output = '';
1046 $length = core_text::strlen($string);
1047 $wordlength = 0;
1049 for ($i=0; $i<$length; $i++) {
1050 $char = core_text::substr($string, $i, 1);
1051 if ($char == ' ' or $char == "\t" or $char == "\n" or $char == "\r" or $char == "<" or $char == ">") {
1052 $wordlength = 0;
1053 } else {
1054 $wordlength++;
1055 if ($wordlength > $maxsize) {
1056 $output .= $cutchar;
1057 $wordlength = 0;
1060 $output .= $char;
1063 // Finally load the tags back again.
1064 if (!empty($tags)) {
1065 $output = str_replace(array_keys($tags), $tags, $output);
1068 return $output;
1072 * Try and close the current window using JavaScript, either immediately, or after a delay.
1074 * Echo's out the resulting XHTML & javascript
1076 * @param integer $delay a delay in seconds before closing the window. Default 0.
1077 * @param boolean $reloadopener if true, we will see if this window was a pop-up, and try
1078 * to reload the parent window before this one closes.
1080 function close_window($delay = 0, $reloadopener = false) {
1081 global $PAGE, $OUTPUT;
1083 if (!$PAGE->headerprinted) {
1084 $PAGE->set_title(get_string('closewindow'));
1085 echo $OUTPUT->header();
1086 } else {
1087 $OUTPUT->container_end_all(false);
1090 if ($reloadopener) {
1091 // Trigger the reload immediately, even if the reload is after a delay.
1092 $PAGE->requires->js_function_call('window.opener.location.reload', array(true));
1094 $OUTPUT->notification(get_string('windowclosing'), 'notifysuccess');
1096 $PAGE->requires->js_function_call('close_window', array(new stdClass()), false, $delay);
1098 echo $OUTPUT->footer();
1099 exit;
1103 * Returns a string containing a link to the user documentation for the current page.
1105 * Also contains an icon by default. Shown to teachers and admin only.
1107 * @param string $text The text to be displayed for the link
1108 * @return string The link to user documentation for this current page
1110 function page_doc_link($text='') {
1111 global $OUTPUT, $PAGE;
1112 $path = page_get_doc_link_path($PAGE);
1113 if (!$path) {
1114 return '';
1116 return $OUTPUT->doc_link($path, $text);
1120 * Returns the path to use when constructing a link to the docs.
1122 * @since Moodle 2.5.1 2.6
1123 * @param moodle_page $page
1124 * @return string
1126 function page_get_doc_link_path(moodle_page $page) {
1127 global $CFG;
1129 if (empty($CFG->docroot) || during_initial_install()) {
1130 return '';
1132 if (!has_capability('moodle/site:doclinks', $page->context)) {
1133 return '';
1136 $path = $page->docspath;
1137 if (!$path) {
1138 return '';
1140 return $path;
1145 * Validates an email to make sure it makes sense.
1147 * @param string $address The email address to validate.
1148 * @return boolean
1150 function validate_email($address) {
1151 global $CFG;
1153 if ($address === null || $address === false || $address === '') {
1154 return false;
1157 require_once("{$CFG->libdir}/phpmailer/moodle_phpmailer.php");
1159 return moodle_phpmailer::validateAddress($address ?? '') && !preg_match('/[<>]/', $address);
1163 * Extracts file argument either from file parameter or PATH_INFO
1165 * Note: $scriptname parameter is not needed anymore
1167 * @return string file path (only safe characters)
1169 function get_file_argument() {
1170 global $SCRIPT;
1172 $relativepath = false;
1173 $hasforcedslashargs = false;
1175 if (isset($_SERVER['REQUEST_URI']) && !empty($_SERVER['REQUEST_URI'])) {
1176 // Checks whether $_SERVER['REQUEST_URI'] contains '/pluginfile.php/'
1177 // instead of '/pluginfile.php?', when serving a file from e.g. mod_imscp or mod_scorm.
1178 if ((strpos($_SERVER['REQUEST_URI'], '/pluginfile.php/') !== false)
1179 && isset($_SERVER['PATH_INFO']) && !empty($_SERVER['PATH_INFO'])) {
1180 // Exclude edge cases like '/pluginfile.php/?file='.
1181 $args = explode('/', ltrim($_SERVER['PATH_INFO'], '/'));
1182 $hasforcedslashargs = (count($args) > 2); // Always at least: context, component and filearea.
1185 if (!$hasforcedslashargs) {
1186 $relativepath = optional_param('file', false, PARAM_PATH);
1189 if ($relativepath !== false and $relativepath !== '') {
1190 return $relativepath;
1192 $relativepath = false;
1194 // Then try extract file from the slasharguments.
1195 if (stripos($_SERVER['SERVER_SOFTWARE'], 'iis') !== false) {
1196 // NOTE: IIS tends to convert all file paths to single byte DOS encoding,
1197 // we can not use other methods because they break unicode chars,
1198 // the only ways are to use URL rewriting
1199 // OR
1200 // to properly set the 'FastCGIUtf8ServerVariables' registry key.
1201 if (isset($_SERVER['PATH_INFO']) and $_SERVER['PATH_INFO'] !== '') {
1202 // Check that PATH_INFO works == must not contain the script name.
1203 if (strpos($_SERVER['PATH_INFO'], $SCRIPT) === false) {
1204 $relativepath = clean_param(urldecode($_SERVER['PATH_INFO']), PARAM_PATH);
1207 } else {
1208 // All other apache-like servers depend on PATH_INFO.
1209 if (isset($_SERVER['PATH_INFO'])) {
1210 if (isset($_SERVER['SCRIPT_NAME']) and strpos($_SERVER['PATH_INFO'], $_SERVER['SCRIPT_NAME']) === 0) {
1211 $relativepath = substr($_SERVER['PATH_INFO'], strlen($_SERVER['SCRIPT_NAME']));
1212 } else {
1213 $relativepath = $_SERVER['PATH_INFO'];
1215 $relativepath = clean_param($relativepath, PARAM_PATH);
1219 return $relativepath;
1223 * Just returns an array of text formats suitable for a popup menu
1225 * @return array
1227 function format_text_menu() {
1228 return array (FORMAT_MOODLE => get_string('formattext'),
1229 FORMAT_HTML => get_string('formathtml'),
1230 FORMAT_PLAIN => get_string('formatplain'),
1231 FORMAT_MARKDOWN => get_string('formatmarkdown'));
1235 * Given text in a variety of format codings, this function returns the text as safe HTML.
1237 * This function should mainly be used for long strings like posts,
1238 * answers, glossary items etc. For short strings {@link format_string()}.
1240 * <pre>
1241 * Options:
1242 * trusted : If true the string won't be cleaned. Default false required noclean=true.
1243 * noclean : If true the string won't be cleaned, unless $CFG->forceclean is set. Default false required trusted=true.
1244 * nocache : If true the strign will not be cached and will be formatted every call. Default false.
1245 * filter : If true the string will be run through applicable filters as well. Default true.
1246 * para : If true then the returned string will be wrapped in div tags. Default true.
1247 * newlines : If true then lines newline breaks will be converted to HTML newline breaks. Default true.
1248 * context : The context that will be used for filtering.
1249 * overflowdiv : If set to true the formatted text will be encased in a div
1250 * with the class no-overflow before being returned. Default false.
1251 * allowid : If true then id attributes will not be removed, even when
1252 * using htmlpurifier. Default false.
1253 * blanktarget : If true all <a> tags will have target="_blank" added unless target is explicitly specified.
1254 * </pre>
1256 * @staticvar array $croncache
1257 * @param string $text The text to be formatted. This is raw text originally from user input.
1258 * @param int $format Identifier of the text format to be used
1259 * [FORMAT_MOODLE, FORMAT_HTML, FORMAT_PLAIN, FORMAT_MARKDOWN]
1260 * @param stdClass|array $options text formatting options
1261 * @param int $courseiddonotuse deprecated course id, use context option instead
1262 * @return string
1264 function format_text($text, $format = FORMAT_MOODLE, $options = null, $courseiddonotuse = null) {
1265 global $CFG, $DB, $PAGE;
1267 if ($text === '' || is_null($text)) {
1268 // No need to do any filters and cleaning.
1269 return '';
1272 // Detach object, we can not modify it.
1273 $options = (array)$options;
1275 if (!isset($options['trusted'])) {
1276 $options['trusted'] = false;
1278 if ($format == FORMAT_MARKDOWN) {
1279 // Markdown format cannot be trusted in trusttext areas,
1280 // because we do not know how to sanitise it before editing.
1281 $options['trusted'] = false;
1283 if (!isset($options['noclean'])) {
1284 if ($options['trusted'] and trusttext_active()) {
1285 // No cleaning if text trusted and noclean not specified.
1286 $options['noclean'] = true;
1287 } else {
1288 $options['noclean'] = false;
1291 if (!empty($CFG->forceclean)) {
1292 // Whatever the caller claims, the admin wants all content cleaned anyway.
1293 $options['noclean'] = false;
1295 if (!isset($options['nocache'])) {
1296 $options['nocache'] = false;
1298 if (!isset($options['filter'])) {
1299 $options['filter'] = true;
1301 if (!isset($options['para'])) {
1302 $options['para'] = true;
1304 if (!isset($options['newlines'])) {
1305 $options['newlines'] = true;
1307 if (!isset($options['overflowdiv'])) {
1308 $options['overflowdiv'] = false;
1310 $options['blanktarget'] = !empty($options['blanktarget']);
1312 // Calculate best context.
1313 if (empty($CFG->version) or $CFG->version < 2013051400 or during_initial_install()) {
1314 // Do not filter anything during installation or before upgrade completes.
1315 $context = null;
1317 } else if (isset($options['context'])) { // First by explicit passed context option.
1318 if (is_object($options['context'])) {
1319 $context = $options['context'];
1320 } else {
1321 $context = context::instance_by_id($options['context']);
1323 } else if ($courseiddonotuse) {
1324 // Legacy courseid.
1325 $context = context_course::instance($courseiddonotuse);
1326 } else {
1327 // Fallback to $PAGE->context this may be problematic in CLI and other non-standard pages :-(.
1328 $context = $PAGE->context;
1331 if (!$context) {
1332 // Either install/upgrade or something has gone really wrong because context does not exist (yet?).
1333 $options['nocache'] = true;
1334 $options['filter'] = false;
1337 if ($options['filter']) {
1338 $filtermanager = filter_manager::instance();
1339 $filtermanager->setup_page_for_filters($PAGE, $context); // Setup global stuff filters may have.
1340 $filteroptions = array(
1341 'originalformat' => $format,
1342 'noclean' => $options['noclean'],
1344 } else {
1345 $filtermanager = new null_filter_manager();
1346 $filteroptions = array();
1349 switch ($format) {
1350 case FORMAT_HTML:
1351 $filteroptions['stage'] = 'pre_format';
1352 $text = $filtermanager->filter_text($text, $context, $filteroptions);
1353 // Text is already in HTML format, so just continue to the next filtering stage.
1354 $filteroptions['stage'] = 'pre_clean';
1355 $text = $filtermanager->filter_text($text, $context, $filteroptions);
1356 if (!$options['noclean']) {
1357 $text = clean_text($text, FORMAT_HTML, $options);
1359 $filteroptions['stage'] = 'post_clean';
1360 $text = $filtermanager->filter_text($text, $context, $filteroptions);
1361 break;
1363 case FORMAT_PLAIN:
1364 $text = s($text); // Cleans dangerous JS.
1365 $text = rebuildnolinktag($text);
1366 $text = str_replace(' ', '&nbsp; ', $text);
1367 $text = nl2br($text);
1368 break;
1370 case FORMAT_WIKI:
1371 // This format is deprecated.
1372 $text = '<p>NOTICE: Wiki-like formatting has been removed from Moodle. You should not be seeing
1373 this message as all texts should have been converted to Markdown format instead.
1374 Please post a bug report to http://moodle.org/bugs with information about where you
1375 saw this message.</p>'.s($text);
1376 break;
1378 case FORMAT_MARKDOWN:
1379 $filteroptions['stage'] = 'pre_format';
1380 $text = $filtermanager->filter_text($text, $context, $filteroptions);
1381 $text = markdown_to_html($text);
1382 $filteroptions['stage'] = 'pre_clean';
1383 $text = $filtermanager->filter_text($text, $context, $filteroptions);
1384 if (!$options['noclean']) {
1385 $text = clean_text($text, FORMAT_HTML, $options);
1387 $filteroptions['stage'] = 'post_clean';
1388 $text = $filtermanager->filter_text($text, $context, $filteroptions);
1389 break;
1391 default: // FORMAT_MOODLE or anything else.
1392 $filteroptions['stage'] = 'pre_format';
1393 $text = $filtermanager->filter_text($text, $context, $filteroptions);
1394 $text = text_to_html($text, null, $options['para'], $options['newlines']);
1395 $filteroptions['stage'] = 'pre_clean';
1396 $text = $filtermanager->filter_text($text, $context, $filteroptions);
1397 if (!$options['noclean']) {
1398 $text = clean_text($text, FORMAT_HTML, $options);
1400 $filteroptions['stage'] = 'post_clean';
1401 $text = $filtermanager->filter_text($text, $context, $filteroptions);
1402 break;
1404 if ($options['filter']) {
1405 // At this point there should not be any draftfile links any more,
1406 // this happens when developers forget to post process the text.
1407 // The only potential problem is that somebody might try to format
1408 // the text before storing into database which would be itself big bug..
1409 $text = str_replace("\"$CFG->wwwroot/draftfile.php", "\"$CFG->wwwroot/brokenfile.php#", $text);
1411 if ($CFG->debugdeveloper) {
1412 if (strpos($text, '@@PLUGINFILE@@/') !== false) {
1413 debugging('Before calling format_text(), the content must be processed with file_rewrite_pluginfile_urls()',
1414 DEBUG_DEVELOPER);
1419 if (!empty($options['overflowdiv'])) {
1420 $text = html_writer::tag('div', $text, array('class' => 'no-overflow'));
1423 if ($options['blanktarget']) {
1424 $domdoc = new DOMDocument();
1425 libxml_use_internal_errors(true);
1426 $domdoc->loadHTML('<?xml version="1.0" encoding="UTF-8" ?>' . $text);
1427 libxml_clear_errors();
1428 foreach ($domdoc->getElementsByTagName('a') as $link) {
1429 if ($link->hasAttribute('target') && strpos($link->getAttribute('target'), '_blank') === false) {
1430 continue;
1432 $link->setAttribute('target', '_blank');
1433 if (strpos($link->getAttribute('rel'), 'noreferrer') === false) {
1434 $link->setAttribute('rel', trim($link->getAttribute('rel') . ' noreferrer'));
1438 // This regex is nasty and I don't like it. The correct way to solve this is by loading the HTML like so:
1439 // $domdoc->loadHTML($text, LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD); however it seems like some libxml
1440 // versions don't work properly and end up leaving <html><body>, so I'm forced to use
1441 // this regex to remove those tags as a preventive measure.
1442 $text = trim(preg_replace('~<(?:!DOCTYPE|/?(?:html|body))[^>]*>\s*~i', '', $domdoc->saveHTML($domdoc->documentElement)));
1445 return $text;
1449 * Resets some data related to filters, called during upgrade or when general filter settings change.
1451 * @param bool $phpunitreset true means called from our PHPUnit integration test reset
1452 * @return void
1454 function reset_text_filters_cache($phpunitreset = false) {
1455 global $CFG, $DB;
1457 if ($phpunitreset) {
1458 // HTMLPurifier does not change, DB is already reset to defaults,
1459 // nothing to do here, the dataroot was cleared too.
1460 return;
1463 // The purge_all_caches() deals with cachedir and localcachedir purging,
1464 // the individual filter caches are invalidated as necessary elsewhere.
1466 // Update $CFG->filterall cache flag.
1467 if (empty($CFG->stringfilters)) {
1468 set_config('filterall', 0);
1469 return;
1471 $installedfilters = core_component::get_plugin_list('filter');
1472 $filters = explode(',', $CFG->stringfilters);
1473 foreach ($filters as $filter) {
1474 if (isset($installedfilters[$filter])) {
1475 set_config('filterall', 1);
1476 return;
1479 set_config('filterall', 0);
1483 * Given a simple string, this function returns the string
1484 * processed by enabled string filters if $CFG->filterall is enabled
1486 * This function should be used to print short strings (non html) that
1487 * need filter processing e.g. activity titles, post subjects,
1488 * glossary concepts.
1490 * @staticvar bool $strcache
1491 * @param string $string The string to be filtered. Should be plain text, expect
1492 * possibly for multilang tags.
1493 * @param boolean $striplinks To strip any link in the result text. Moodle 1.8 default changed from false to true! MDL-8713
1494 * @param array $options options array/object or courseid
1495 * @return string
1497 function format_string($string, $striplinks = true, $options = null) {
1498 global $CFG, $PAGE;
1500 if ($string === '' || is_null($string)) {
1501 // No need to do any filters and cleaning.
1502 return '';
1505 // We'll use a in-memory cache here to speed up repeated strings.
1506 static $strcache = false;
1508 if (empty($CFG->version) or $CFG->version < 2013051400 or during_initial_install()) {
1509 // Do not filter anything during installation or before upgrade completes.
1510 return $string = strip_tags($string);
1513 if ($strcache === false or count($strcache) > 2000) {
1514 // This number might need some tuning to limit memory usage in cron.
1515 $strcache = array();
1518 if (is_numeric($options)) {
1519 // Legacy courseid usage.
1520 $options = array('context' => context_course::instance($options));
1521 } else {
1522 // Detach object, we can not modify it.
1523 $options = (array)$options;
1526 if (empty($options['context'])) {
1527 // Fallback to $PAGE->context this may be problematic in CLI and other non-standard pages :-(.
1528 $options['context'] = $PAGE->context;
1529 } else if (is_numeric($options['context'])) {
1530 $options['context'] = context::instance_by_id($options['context']);
1532 if (!isset($options['filter'])) {
1533 $options['filter'] = true;
1536 $options['escape'] = !isset($options['escape']) || $options['escape'];
1538 if (!$options['context']) {
1539 // We did not find any context? weird.
1540 return $string = strip_tags($string);
1543 // Calculate md5.
1544 $cachekeys = array($string, $striplinks, $options['context']->id,
1545 $options['escape'], current_language(), $options['filter']);
1546 $md5 = md5(implode('<+>', $cachekeys));
1548 // Fetch from cache if possible.
1549 if (isset($strcache[$md5])) {
1550 return $strcache[$md5];
1553 // First replace all ampersands not followed by html entity code
1554 // Regular expression moved to its own method for easier unit testing.
1555 $string = $options['escape'] ? replace_ampersands_not_followed_by_entity($string) : $string;
1557 if (!empty($CFG->filterall) && $options['filter']) {
1558 $filtermanager = filter_manager::instance();
1559 $filtermanager->setup_page_for_filters($PAGE, $options['context']); // Setup global stuff filters may have.
1560 $string = $filtermanager->filter_string($string, $options['context']);
1563 // If the site requires it, strip ALL tags from this string.
1564 if (!empty($CFG->formatstringstriptags)) {
1565 if ($options['escape']) {
1566 $string = str_replace(array('<', '>'), array('&lt;', '&gt;'), strip_tags($string));
1567 } else {
1568 $string = strip_tags($string);
1570 } else {
1571 // Otherwise strip just links if that is required (default).
1572 if ($striplinks) {
1573 // Strip links in string.
1574 $string = strip_links($string);
1576 $string = clean_text($string);
1579 // Store to cache.
1580 $strcache[$md5] = $string;
1582 return $string;
1586 * Given a string, performs a negative lookahead looking for any ampersand character
1587 * that is not followed by a proper HTML entity. If any is found, it is replaced
1588 * by &amp;. The string is then returned.
1590 * @param string $string
1591 * @return string
1593 function replace_ampersands_not_followed_by_entity($string) {
1594 return preg_replace("/\&(?![a-zA-Z0-9#]{1,8};)/", "&amp;", $string ?? '');
1598 * Given a string, replaces all <a>.*</a> by .* and returns the string.
1600 * @param string $string
1601 * @return string
1603 function strip_links($string) {
1604 return preg_replace('/(<a\s[^>]+?>)(.+?)(<\/a>)/is', '$2', $string);
1608 * This expression turns links into something nice in a text format. (Russell Jungwirth)
1610 * @param string $string
1611 * @return string
1613 function wikify_links($string) {
1614 return preg_replace('~(<a [^<]*href=["|\']?([^ "\']*)["|\']?[^>]*>([^<]*)</a>)~i', '$3 [ $2 ]', $string);
1618 * Given text in a variety of format codings, this function returns the text as plain text suitable for plain email.
1620 * @param string $text The text to be formatted. This is raw text originally from user input.
1621 * @param int $format Identifier of the text format to be used
1622 * [FORMAT_MOODLE, FORMAT_HTML, FORMAT_PLAIN, FORMAT_WIKI, FORMAT_MARKDOWN]
1623 * @return string
1625 function format_text_email($text, $format) {
1627 switch ($format) {
1629 case FORMAT_PLAIN:
1630 return $text;
1631 break;
1633 case FORMAT_WIKI:
1634 // There should not be any of these any more!
1635 $text = wikify_links($text);
1636 return core_text::entities_to_utf8(strip_tags($text), true);
1637 break;
1639 case FORMAT_HTML:
1640 return html_to_text($text);
1641 break;
1643 case FORMAT_MOODLE:
1644 case FORMAT_MARKDOWN:
1645 default:
1646 $text = wikify_links($text);
1647 return core_text::entities_to_utf8(strip_tags($text), true);
1648 break;
1653 * Formats activity intro text
1655 * @param string $module name of module
1656 * @param object $activity instance of activity
1657 * @param int $cmid course module id
1658 * @param bool $filter filter resulting html text
1659 * @return string
1661 function format_module_intro($module, $activity, $cmid, $filter=true) {
1662 global $CFG;
1663 require_once("$CFG->libdir/filelib.php");
1664 $context = context_module::instance($cmid);
1665 $options = array('noclean' => true, 'para' => false, 'filter' => $filter, 'context' => $context, 'overflowdiv' => true);
1666 $intro = file_rewrite_pluginfile_urls($activity->intro, 'pluginfile.php', $context->id, 'mod_'.$module, 'intro', null);
1667 return trim(format_text($intro, $activity->introformat, $options, null));
1671 * Removes the usage of Moodle files from a text.
1673 * In some rare cases we need to re-use a text that already has embedded links
1674 * to some files hosted within Moodle. But the new area in which we will push
1675 * this content does not support files... therefore we need to remove those files.
1677 * @param string $source The text
1678 * @return string The stripped text
1680 function strip_pluginfile_content($source) {
1681 $baseurl = '@@PLUGINFILE@@';
1682 // Looking for something like < .* "@@pluginfile@@.*" .* >
1683 $pattern = '$<[^<>]+["\']' . $baseurl . '[^"\']*["\'][^<>]*>$';
1684 $stripped = preg_replace($pattern, '', $source);
1685 // Use purify html to rebalence potentially mismatched tags and generally cleanup.
1686 return purify_html($stripped);
1690 * Legacy function, used for cleaning of old forum and glossary text only.
1692 * @param string $text text that may contain legacy TRUSTTEXT marker
1693 * @return string text without legacy TRUSTTEXT marker
1695 function trusttext_strip($text) {
1696 if (!is_string($text)) {
1697 // This avoids the potential for an endless loop below.
1698 throw new coding_exception('trusttext_strip parameter must be a string');
1700 while (true) { // Removing nested TRUSTTEXT.
1701 $orig = $text;
1702 $text = str_replace('#####TRUSTTEXT#####', '', $text);
1703 if (strcmp($orig, $text) === 0) {
1704 return $text;
1710 * Must be called before editing of all texts with trust flag. Removes all XSS nasties from texts stored in database if needed.
1712 * @param stdClass $object data object with xxx, xxxformat and xxxtrust fields
1713 * @param string $field name of text field
1714 * @param context $context active context
1715 * @return stdClass updated $object
1717 function trusttext_pre_edit($object, $field, $context) {
1718 $trustfield = $field.'trust';
1719 $formatfield = $field.'format';
1721 if ($object->$formatfield == FORMAT_MARKDOWN) {
1722 // We do not have a way to sanitise Markdown texts,
1723 // luckily editors for this format should not have XSS problems.
1724 return $object;
1727 if (!$object->$trustfield or !trusttext_trusted($context)) {
1728 $object->$field = clean_text($object->$field, $object->$formatfield);
1731 return $object;
1735 * Is current user trusted to enter no dangerous XSS in this context?
1737 * Please note the user must be in fact trusted everywhere on this server!!
1739 * @param context $context
1740 * @return bool true if user trusted
1742 function trusttext_trusted($context) {
1743 return (trusttext_active() and has_capability('moodle/site:trustcontent', $context));
1747 * Is trusttext feature active?
1749 * @return bool
1751 function trusttext_active() {
1752 global $CFG;
1754 return !empty($CFG->enabletrusttext);
1758 * Cleans raw text removing nasties.
1760 * Given raw text (eg typed in by a user) this function cleans it up and removes any nasty tags that could mess up
1761 * Moodle pages through XSS attacks.
1763 * The result must be used as a HTML text fragment, this function can not cleanup random
1764 * parts of html tags such as url or src attributes.
1766 * NOTE: the format parameter was deprecated because we can safely clean only HTML.
1768 * @param string $text The text to be cleaned
1769 * @param int|string $format deprecated parameter, should always contain FORMAT_HTML or FORMAT_MOODLE
1770 * @param array $options Array of options; currently only option supported is 'allowid' (if true,
1771 * does not remove id attributes when cleaning)
1772 * @return string The cleaned up text
1774 function clean_text($text, $format = FORMAT_HTML, $options = array()) {
1775 $text = (string)$text;
1777 if ($format != FORMAT_HTML and $format != FORMAT_HTML) {
1778 // TODO: we need to standardise cleanup of text when loading it into editor first.
1779 // debugging('clean_text() is designed to work only with html');.
1782 if ($format == FORMAT_PLAIN) {
1783 return $text;
1786 if (is_purify_html_necessary($text)) {
1787 $text = purify_html($text, $options);
1790 // Originally we tried to neutralise some script events here, it was a wrong approach because
1791 // it was trivial to work around that (for example using style based XSS exploits).
1792 // We must not give false sense of security here - all developers MUST understand how to use
1793 // rawurlencode(), htmlentities(), htmlspecialchars(), p(), s(), moodle_url, html_writer and friends!!!
1795 return $text;
1799 * Is it necessary to use HTMLPurifier?
1801 * @private
1802 * @param string $text
1803 * @return bool false means html is safe and valid, true means use HTMLPurifier
1805 function is_purify_html_necessary($text) {
1806 if ($text === '') {
1807 return false;
1810 if ($text === (string)((int)$text)) {
1811 return false;
1814 if (strpos($text, '&') !== false or preg_match('|<[^pesb/]|', $text)) {
1815 // We need to normalise entities or other tags except p, em, strong and br present.
1816 return true;
1819 $altered = htmlspecialchars($text, ENT_NOQUOTES, 'UTF-8', true);
1820 if ($altered === $text) {
1821 // No < > or other special chars means this must be safe.
1822 return false;
1825 // Let's try to convert back some safe html tags.
1826 $altered = preg_replace('|&lt;p&gt;(.*?)&lt;/p&gt;|m', '<p>$1</p>', $altered);
1827 if ($altered === $text) {
1828 return false;
1830 $altered = preg_replace('|&lt;em&gt;([^<>]+?)&lt;/em&gt;|m', '<em>$1</em>', $altered);
1831 if ($altered === $text) {
1832 return false;
1834 $altered = preg_replace('|&lt;strong&gt;([^<>]+?)&lt;/strong&gt;|m', '<strong>$1</strong>', $altered);
1835 if ($altered === $text) {
1836 return false;
1838 $altered = str_replace('&lt;br /&gt;', '<br />', $altered);
1839 if ($altered === $text) {
1840 return false;
1843 return true;
1847 * KSES replacement cleaning function - uses HTML Purifier.
1849 * @param string $text The (X)HTML string to purify
1850 * @param array $options Array of options; currently only option supported is 'allowid' (if set,
1851 * does not remove id attributes when cleaning)
1852 * @return string
1854 function purify_html($text, $options = array()) {
1855 global $CFG;
1857 $text = (string)$text;
1859 static $purifiers = array();
1860 static $caches = array();
1862 // Purifier code can change only during major version upgrade.
1863 $version = empty($CFG->version) ? 0 : $CFG->version;
1864 $cachedir = "$CFG->localcachedir/htmlpurifier/$version";
1865 if (!file_exists($cachedir)) {
1866 // Purging of caches may remove the cache dir at any time,
1867 // luckily file_exists() results should be cached for all existing directories.
1868 $purifiers = array();
1869 $caches = array();
1870 gc_collect_cycles();
1872 make_localcache_directory('htmlpurifier', false);
1873 check_dir_exists($cachedir);
1876 $allowid = empty($options['allowid']) ? 0 : 1;
1877 $allowobjectembed = empty($CFG->allowobjectembed) ? 0 : 1;
1879 $type = 'type_'.$allowid.'_'.$allowobjectembed;
1881 if (!array_key_exists($type, $caches)) {
1882 $caches[$type] = cache::make('core', 'htmlpurifier', array('type' => $type));
1884 $cache = $caches[$type];
1886 // Add revision number and all options to the text key so that it is compatible with local cluster node caches.
1887 $key = "|$version|$allowobjectembed|$allowid|$text";
1888 $filteredtext = $cache->get($key);
1890 if ($filteredtext === true) {
1891 // The filtering did not change the text last time, no need to filter anything again.
1892 return $text;
1893 } else if ($filteredtext !== false) {
1894 return $filteredtext;
1897 if (empty($purifiers[$type])) {
1898 require_once $CFG->libdir.'/htmlpurifier/HTMLPurifier.safe-includes.php';
1899 require_once $CFG->libdir.'/htmlpurifier/locallib.php';
1900 $config = HTMLPurifier_Config::createDefault();
1902 $config->set('HTML.DefinitionID', 'moodlehtml');
1903 $config->set('HTML.DefinitionRev', 7);
1904 $config->set('Cache.SerializerPath', $cachedir);
1905 $config->set('Cache.SerializerPermissions', $CFG->directorypermissions);
1906 $config->set('Core.NormalizeNewlines', false);
1907 $config->set('Core.ConvertDocumentToFragment', true);
1908 $config->set('Core.Encoding', 'UTF-8');
1909 $config->set('HTML.Doctype', 'XHTML 1.0 Transitional');
1910 $config->set('URI.AllowedSchemes', array(
1911 'http' => true,
1912 'https' => true,
1913 'ftp' => true,
1914 'irc' => true,
1915 'nntp' => true,
1916 'news' => true,
1917 'rtsp' => true,
1918 'rtmp' => true,
1919 'teamspeak' => true,
1920 'gopher' => true,
1921 'mms' => true,
1922 'mailto' => true
1924 $config->set('Attr.AllowedFrameTargets', array('_blank'));
1926 if ($allowobjectembed) {
1927 $config->set('HTML.SafeObject', true);
1928 $config->set('Output.FlashCompat', true);
1929 $config->set('HTML.SafeEmbed', true);
1932 if ($allowid) {
1933 $config->set('Attr.EnableID', true);
1936 if ($def = $config->maybeGetRawHTMLDefinition()) {
1937 $def->addElement('nolink', 'Inline', 'Flow', array()); // Skip our filters inside.
1938 $def->addElement('tex', 'Inline', 'Inline', array()); // Tex syntax, equivalent to $$xx$$.
1939 $def->addElement('algebra', 'Inline', 'Inline', array()); // Algebra syntax, equivalent to @@xx@@.
1940 $def->addElement('lang', 'Block', 'Flow', array(), array('lang'=>'CDATA')); // Original multilang style - only our hacked lang attribute.
1941 $def->addAttribute('span', 'xxxlang', 'CDATA'); // Current very problematic multilang.
1942 // Enable the bidirectional isolate element and its span equivalent.
1943 $def->addElement('bdi', 'Inline', 'Flow', 'Common');
1944 $def->addAttribute('span', 'dir', 'Enum#ltr,rtl,auto');
1946 // Media elements.
1947 // https://html.spec.whatwg.org/#the-video-element
1948 $def->addElement('video', 'Inline', 'Optional: #PCDATA | Flow | source | track', 'Common', [
1949 'src' => 'URI',
1950 'crossorigin' => 'Enum#anonymous,use-credentials',
1951 'poster' => 'URI',
1952 'preload' => 'Enum#auto,metadata,none',
1953 'autoplay' => 'Bool',
1954 'playsinline' => 'Bool',
1955 'loop' => 'Bool',
1956 'muted' => 'Bool',
1957 'controls' => 'Bool',
1958 'width' => 'Length',
1959 'height' => 'Length',
1961 // https://html.spec.whatwg.org/#the-audio-element
1962 $def->addElement('audio', 'Inline', 'Optional: #PCDATA | Flow | source | track', 'Common', [
1963 'src' => 'URI',
1964 'crossorigin' => 'Enum#anonymous,use-credentials',
1965 'preload' => 'Enum#auto,metadata,none',
1966 'autoplay' => 'Bool',
1967 'loop' => 'Bool',
1968 'muted' => 'Bool',
1969 'controls' => 'Bool'
1971 // https://html.spec.whatwg.org/#the-source-element
1972 $def->addElement('source', false, 'Empty', null, [
1973 'src' => 'URI',
1974 'type' => 'Text'
1976 // https://html.spec.whatwg.org/#the-track-element
1977 $def->addElement('track', false, 'Empty', null, [
1978 'src' => 'URI',
1979 'kind' => 'Enum#subtitles,captions,descriptions,chapters,metadata',
1980 'srclang' => 'Text',
1981 'label' => 'Text',
1982 'default' => 'Bool',
1985 // Use the built-in Ruby module to add annotation support.
1986 $def->manager->addModule(new HTMLPurifier_HTMLModule_Ruby());
1989 $purifier = new HTMLPurifier($config);
1990 $purifiers[$type] = $purifier;
1991 } else {
1992 $purifier = $purifiers[$type];
1995 $multilang = (strpos($text, 'class="multilang"') !== false);
1997 $filteredtext = $text;
1998 if ($multilang) {
1999 $filteredtextregex = '/<span(\s+lang="([a-zA-Z0-9_-]+)"|\s+class="multilang"){2}\s*>/';
2000 $filteredtext = preg_replace($filteredtextregex, '<span xxxlang="${2}">', $filteredtext);
2002 $filteredtext = (string)$purifier->purify($filteredtext);
2003 if ($multilang) {
2004 $filteredtext = preg_replace('/<span xxxlang="([a-zA-Z0-9_-]+)">/', '<span lang="${1}" class="multilang">', $filteredtext);
2007 if ($text === $filteredtext) {
2008 // No need to store the filtered text, next time we will just return unfiltered text
2009 // because it was not changed by purifying.
2010 $cache->set($key, true);
2011 } else {
2012 $cache->set($key, $filteredtext);
2015 return $filteredtext;
2019 * Given plain text, makes it into HTML as nicely as possible.
2021 * May contain HTML tags already.
2023 * Do not abuse this function. It is intended as lower level formatting feature used
2024 * by {@link format_text()} to convert FORMAT_MOODLE to HTML. You are supposed
2025 * to call format_text() in most of cases.
2027 * @param string $text The string to convert.
2028 * @param boolean $smileyignored Was used to determine if smiley characters should convert to smiley images, ignored now
2029 * @param boolean $para If true then the returned string will be wrapped in div tags
2030 * @param boolean $newlines If true then lines newline breaks will be converted to HTML newline breaks.
2031 * @return string
2033 function text_to_html($text, $smileyignored = null, $para = true, $newlines = true) {
2034 // Remove any whitespace that may be between HTML tags.
2035 $text = preg_replace("~>([[:space:]]+)<~i", "><", $text);
2037 // Remove any returns that precede or follow HTML tags.
2038 $text = preg_replace("~([\n\r])<~i", " <", $text);
2039 $text = preg_replace("~>([\n\r])~i", "> ", $text);
2041 // Make returns into HTML newlines.
2042 if ($newlines) {
2043 $text = nl2br($text);
2046 // Wrap the whole thing in a div if required.
2047 if ($para) {
2048 // In 1.9 this was changed from a p => div.
2049 return '<div class="text_to_html">'.$text.'</div>';
2050 } else {
2051 return $text;
2056 * Given Markdown formatted text, make it into XHTML using external function
2058 * @param string $text The markdown formatted text to be converted.
2059 * @return string Converted text
2061 function markdown_to_html($text) {
2062 global $CFG;
2064 if ($text === '' or $text === null) {
2065 return $text;
2068 require_once($CFG->libdir .'/markdown/MarkdownInterface.php');
2069 require_once($CFG->libdir .'/markdown/Markdown.php');
2070 require_once($CFG->libdir .'/markdown/MarkdownExtra.php');
2072 return \Michelf\MarkdownExtra::defaultTransform($text);
2076 * Given HTML text, make it into plain text using external function
2078 * @param string $html The text to be converted.
2079 * @param integer $width Width to wrap the text at. (optional, default 75 which
2080 * is a good value for email. 0 means do not limit line length.)
2081 * @param boolean $dolinks By default, any links in the HTML are collected, and
2082 * printed as a list at the end of the HTML. If you don't want that, set this
2083 * argument to false.
2084 * @return string plain text equivalent of the HTML.
2086 function html_to_text($html, $width = 75, $dolinks = true) {
2087 global $CFG;
2089 require_once($CFG->libdir .'/html2text/lib.php');
2091 $options = array(
2092 'width' => $width,
2093 'do_links' => 'table',
2096 if (empty($dolinks)) {
2097 $options['do_links'] = 'none';
2099 $h2t = new core_html2text($html, $options);
2100 $result = $h2t->getText();
2102 return $result;
2106 * Converts texts or strings to plain text.
2108 * - When used to convert user input introduced in an editor the text format needs to be passed in $contentformat like we usually
2109 * do in format_text.
2110 * - When this function is used for strings that are usually passed through format_string before displaying them
2111 * we need to set $contentformat to false. This will execute html_to_text as these strings can contain multilang tags if
2112 * multilang filter is applied to headings.
2114 * @param string $content The text as entered by the user
2115 * @param int|false $contentformat False for strings or the text format: FORMAT_MOODLE/FORMAT_HTML/FORMAT_PLAIN/FORMAT_MARKDOWN
2116 * @return string Plain text.
2118 function content_to_text($content, $contentformat) {
2120 switch ($contentformat) {
2121 case FORMAT_PLAIN:
2122 // Nothing here.
2123 break;
2124 case FORMAT_MARKDOWN:
2125 $content = markdown_to_html($content);
2126 $content = html_to_text($content, 75, false);
2127 break;
2128 default:
2129 // FORMAT_HTML, FORMAT_MOODLE and $contentformat = false, the later one are strings usually formatted through
2130 // format_string, we need to convert them from html because they can contain HTML (multilang filter).
2131 $content = html_to_text($content, 75, false);
2134 return trim($content, "\r\n ");
2138 * Factory method for extracting draft file links from arbitrary text using regular expressions. Only text
2139 * is required; other file fields may be passed to filter.
2141 * @param string $text Some html content.
2142 * @param bool $forcehttps force https urls.
2143 * @param int $contextid This parameter and the next three identify the file area to save to.
2144 * @param string $component The component name.
2145 * @param string $filearea The filearea.
2146 * @param int $itemid The item id for the filearea.
2147 * @param string $filename The specific filename of the file.
2148 * @return array
2150 function extract_draft_file_urls_from_text($text, $forcehttps = false, $contextid = null, $component = null,
2151 $filearea = null, $itemid = null, $filename = null) {
2152 global $CFG;
2154 $wwwroot = $CFG->wwwroot;
2155 if ($forcehttps) {
2156 $wwwroot = str_replace('http://', 'https://', $wwwroot);
2158 $urlstring = '/' . preg_quote($wwwroot, '/');
2160 $urlbase = preg_quote('draftfile.php');
2161 $urlstring .= "\/(?<urlbase>{$urlbase})";
2163 if (is_null($contextid)) {
2164 $contextid = '[0-9]+';
2166 $urlstring .= "\/(?<contextid>{$contextid})";
2168 if (is_null($component)) {
2169 $component = '[a-z_]+';
2171 $urlstring .= "\/(?<component>{$component})";
2173 if (is_null($filearea)) {
2174 $filearea = '[a-z_]+';
2176 $urlstring .= "\/(?<filearea>{$filearea})";
2178 if (is_null($itemid)) {
2179 $itemid = '[0-9]+';
2181 $urlstring .= "\/(?<itemid>{$itemid})";
2183 // Filename matching magic based on file_rewrite_urls_to_pluginfile().
2184 if (is_null($filename)) {
2185 $filename = '[^\'\",&<>|`\s:\\\\]+';
2187 $urlstring .= "\/(?<filename>{$filename})/";
2189 // Regular expression which matches URLs and returns their components.
2190 preg_match_all($urlstring, $text, $urls, PREG_SET_ORDER);
2191 return $urls;
2195 * This function will highlight search words in a given string
2197 * It cares about HTML and will not ruin links. It's best to use
2198 * this function after performing any conversions to HTML.
2200 * @param string $needle The search string. Syntax like "word1 +word2 -word3" is dealt with correctly.
2201 * @param string $haystack The string (HTML) within which to highlight the search terms.
2202 * @param boolean $matchcase whether to do case-sensitive. Default case-insensitive.
2203 * @param string $prefix the string to put before each search term found.
2204 * @param string $suffix the string to put after each search term found.
2205 * @return string The highlighted HTML.
2207 function highlight($needle, $haystack, $matchcase = false,
2208 $prefix = '<span class="highlight">', $suffix = '</span>') {
2210 // Quick bail-out in trivial cases.
2211 if (empty($needle) or empty($haystack)) {
2212 return $haystack;
2215 // Break up the search term into words, discard any -words and build a regexp.
2216 $words = preg_split('/ +/', trim($needle));
2217 foreach ($words as $index => $word) {
2218 if (strpos($word, '-') === 0) {
2219 unset($words[$index]);
2220 } else if (strpos($word, '+') === 0) {
2221 $words[$index] = '\b' . preg_quote(ltrim($word, '+'), '/') . '\b'; // Match only as a complete word.
2222 } else {
2223 $words[$index] = preg_quote($word, '/');
2226 $regexp = '/(' . implode('|', $words) . ')/u'; // Char u is to do UTF-8 matching.
2227 if (!$matchcase) {
2228 $regexp .= 'i';
2231 // Another chance to bail-out if $search was only -words.
2232 if (empty($words)) {
2233 return $haystack;
2236 // Split the string into HTML tags and real content.
2237 $chunks = preg_split('/((?:<[^>]*>)+)/', $haystack, -1, PREG_SPLIT_DELIM_CAPTURE);
2239 // We have an array of alternating blocks of text, then HTML tags, then text, ...
2240 // Loop through replacing search terms in the text, and leaving the HTML unchanged.
2241 $ishtmlchunk = false;
2242 $result = '';
2243 foreach ($chunks as $chunk) {
2244 if ($ishtmlchunk) {
2245 $result .= $chunk;
2246 } else {
2247 $result .= preg_replace($regexp, $prefix . '$1' . $suffix, $chunk);
2249 $ishtmlchunk = !$ishtmlchunk;
2252 return $result;
2256 * This function will highlight instances of $needle in $haystack
2258 * It's faster that the above function {@link highlight()} and doesn't care about
2259 * HTML or anything.
2261 * @param string $needle The string to search for
2262 * @param string $haystack The string to search for $needle in
2263 * @return string The highlighted HTML
2265 function highlightfast($needle, $haystack) {
2267 if (empty($needle) or empty($haystack)) {
2268 return $haystack;
2271 $parts = explode(core_text::strtolower($needle), core_text::strtolower($haystack));
2273 if (count($parts) === 1) {
2274 return $haystack;
2277 $pos = 0;
2279 foreach ($parts as $key => $part) {
2280 $parts[$key] = substr($haystack, $pos, strlen($part));
2281 $pos += strlen($part);
2283 $parts[$key] .= '<span class="highlight">'.substr($haystack, $pos, strlen($needle)).'</span>';
2284 $pos += strlen($needle);
2287 return str_replace('<span class="highlight"></span>', '', join('', $parts));
2291 * Converts a language code to hyphen-separated format in accordance to the
2292 * {@link https://datatracker.ietf.org/doc/html/rfc5646#section-2.1 BCP47 syntax}.
2294 * For additional information, check out
2295 * {@link https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/lang MDN web docs - lang}.
2297 * @param string $langcode The language code to convert.
2298 * @return string
2300 function get_html_lang_attribute_value(string $langcode): string {
2301 if (empty(trim($langcode))) {
2302 // If the language code passed is an empty string, return 'unknown'.
2303 return 'unknown';
2305 return str_replace('_', '-', $langcode);
2309 * Return a string containing 'lang', xml:lang and optionally 'dir' HTML attributes.
2311 * Internationalisation, for print_header and backup/restorelib.
2313 * @param bool $dir Default false
2314 * @return string Attributes
2316 function get_html_lang($dir = false) {
2317 global $CFG;
2319 $currentlang = current_language();
2320 if (isset($CFG->lang) && $currentlang !== $CFG->lang && !get_string_manager()->translation_exists($currentlang)) {
2321 // Use the default site language when the current language is not available.
2322 $currentlang = $CFG->lang;
2323 // Fix the current language.
2324 fix_current_language($currentlang);
2327 $direction = '';
2328 if ($dir) {
2329 if (right_to_left()) {
2330 $direction = ' dir="rtl"';
2331 } else {
2332 $direction = ' dir="ltr"';
2336 // Accessibility: added the 'lang' attribute to $direction, used in theme <html> tag.
2337 $language = get_html_lang_attribute_value($currentlang);
2338 @header('Content-Language: '.$language);
2339 return ($direction.' lang="'.$language.'" xml:lang="'.$language.'"');
2343 // STANDARD WEB PAGE PARTS.
2346 * Send the HTTP headers that Moodle requires.
2348 * There is a backwards compatibility hack for legacy code
2349 * that needs to add custom IE compatibility directive.
2351 * Example:
2352 * <code>
2353 * if (!isset($CFG->additionalhtmlhead)) {
2354 * $CFG->additionalhtmlhead = '';
2356 * $CFG->additionalhtmlhead .= '<meta http-equiv="X-UA-Compatible" content="IE=8" />';
2357 * header('X-UA-Compatible: IE=8');
2358 * echo $OUTPUT->header();
2359 * </code>
2361 * Please note the $CFG->additionalhtmlhead alone might not work,
2362 * you should send the IE compatibility header() too.
2364 * @param string $contenttype
2365 * @param bool $cacheable Can this page be cached on back?
2366 * @return void, sends HTTP headers
2368 function send_headers($contenttype, $cacheable = true) {
2369 global $CFG;
2371 @header('Content-Type: ' . $contenttype);
2372 @header('Content-Script-Type: text/javascript');
2373 @header('Content-Style-Type: text/css');
2375 if (empty($CFG->additionalhtmlhead) or stripos($CFG->additionalhtmlhead, 'X-UA-Compatible') === false) {
2376 @header('X-UA-Compatible: IE=edge');
2379 if ($cacheable) {
2380 // Allow caching on "back" (but not on normal clicks).
2381 @header('Cache-Control: private, pre-check=0, post-check=0, max-age=0, no-transform');
2382 @header('Pragma: no-cache');
2383 @header('Expires: ');
2384 } else {
2385 // Do everything we can to always prevent clients and proxies caching.
2386 @header('Cache-Control: no-store, no-cache, must-revalidate');
2387 @header('Cache-Control: post-check=0, pre-check=0, no-transform', false);
2388 @header('Pragma: no-cache');
2389 @header('Expires: Mon, 20 Aug 1969 09:23:00 GMT');
2390 @header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
2392 @header('Accept-Ranges: none');
2394 // The Moodle app must be allowed to embed content always.
2395 if (empty($CFG->allowframembedding) && !core_useragent::is_moodle_app()) {
2396 @header('X-Frame-Options: sameorigin');
2399 // If referrer policy is set, add a referrer header.
2400 if (!empty($CFG->referrerpolicy) && ($CFG->referrerpolicy !== 'default')) {
2401 @header('Referrer-Policy: ' . $CFG->referrerpolicy);
2406 * Return the right arrow with text ('next'), and optionally embedded in a link.
2408 * @param string $text HTML/plain text label (set to blank only for breadcrumb separator cases).
2409 * @param string $url An optional link to use in a surrounding HTML anchor.
2410 * @param bool $accesshide True if text should be hidden (for screen readers only).
2411 * @param string $addclass Additional class names for the link, or the arrow character.
2412 * @return string HTML string.
2414 function link_arrow_right($text, $url='', $accesshide=false, $addclass='', $addparams = []) {
2415 global $OUTPUT; // TODO: move to output renderer.
2416 $arrowclass = 'arrow ';
2417 if (!$url) {
2418 $arrowclass .= $addclass;
2420 $arrow = '<span class="'.$arrowclass.'">'.$OUTPUT->rarrow().'</span>';
2421 $htmltext = '';
2422 if ($text) {
2423 $htmltext = '<span class="arrow_text">'.$text.'</span>&nbsp;';
2424 if ($accesshide) {
2425 $htmltext = get_accesshide($htmltext);
2428 if ($url) {
2429 $class = 'arrow_link';
2430 if ($addclass) {
2431 $class .= ' '.$addclass;
2434 $linkparams = [
2435 'class' => $class,
2436 'href' => $url,
2437 'title' => preg_replace('/<.*?>/', '', $text),
2440 $linkparams += $addparams;
2442 return html_writer::link($url, $htmltext . $arrow, $linkparams);
2444 return $htmltext.$arrow;
2448 * Return the left arrow with text ('previous'), and optionally embedded in a link.
2450 * @param string $text HTML/plain text label (set to blank only for breadcrumb separator cases).
2451 * @param string $url An optional link to use in a surrounding HTML anchor.
2452 * @param bool $accesshide True if text should be hidden (for screen readers only).
2453 * @param string $addclass Additional class names for the link, or the arrow character.
2454 * @return string HTML string.
2456 function link_arrow_left($text, $url='', $accesshide=false, $addclass='', $addparams = []) {
2457 global $OUTPUT; // TODO: move to utput renderer.
2458 $arrowclass = 'arrow ';
2459 if (! $url) {
2460 $arrowclass .= $addclass;
2462 $arrow = '<span class="'.$arrowclass.'">'.$OUTPUT->larrow().'</span>';
2463 $htmltext = '';
2464 if ($text) {
2465 $htmltext = '&nbsp;<span class="arrow_text">'.$text.'</span>';
2466 if ($accesshide) {
2467 $htmltext = get_accesshide($htmltext);
2470 if ($url) {
2471 $class = 'arrow_link';
2472 if ($addclass) {
2473 $class .= ' '.$addclass;
2476 $linkparams = [
2477 'class' => $class,
2478 'href' => $url,
2479 'title' => preg_replace('/<.*?>/', '', $text),
2482 $linkparams += $addparams;
2484 return html_writer::link($url, $arrow . $htmltext, $linkparams);
2486 return $arrow.$htmltext;
2490 * Return a HTML element with the class "accesshide", for accessibility.
2492 * Please use cautiously - where possible, text should be visible!
2494 * @param string $text Plain text.
2495 * @param string $elem Lowercase element name, default "span".
2496 * @param string $class Additional classes for the element.
2497 * @param string $attrs Additional attributes string in the form, "name='value' name2='value2'"
2498 * @return string HTML string.
2500 function get_accesshide($text, $elem='span', $class='', $attrs='') {
2501 return "<$elem class=\"accesshide $class\" $attrs>$text</$elem>";
2505 * Return the breadcrumb trail navigation separator.
2507 * @return string HTML string.
2509 function get_separator() {
2510 // Accessibility: the 'hidden' slash is preferred for screen readers.
2511 return ' '.link_arrow_right($text='/', $url='', $accesshide=true, 'sep').' ';
2515 * Print (or return) a collapsible region, that has a caption that can be clicked to expand or collapse the region.
2517 * If JavaScript is off, then the region will always be expanded.
2519 * @param string $contents the contents of the box.
2520 * @param string $classes class names added to the div that is output.
2521 * @param string $id id added to the div that is output. Must not be blank.
2522 * @param string $caption text displayed at the top. Clicking on this will cause the region to expand or contract.
2523 * @param string $userpref the name of the user preference that stores the user's preferred default state.
2524 * (May be blank if you do not wish the state to be persisted.
2525 * @param boolean $default Initial collapsed state to use if the user_preference it not set.
2526 * @param boolean $return if true, return the HTML as a string, rather than printing it.
2527 * @return string|void If $return is false, returns nothing, otherwise returns a string of HTML.
2529 function print_collapsible_region($contents, $classes, $id, $caption, $userpref = '', $default = false, $return = false) {
2530 $output = print_collapsible_region_start($classes, $id, $caption, $userpref, $default, true);
2531 $output .= $contents;
2532 $output .= print_collapsible_region_end(true);
2534 if ($return) {
2535 return $output;
2536 } else {
2537 echo $output;
2542 * Print (or return) the start of a collapsible region
2544 * The collapsibleregion has a caption that can be clicked to expand or collapse the region. If JavaScript is off, then the region
2545 * will always be expanded.
2547 * @param string $classes class names added to the div that is output.
2548 * @param string $id id added to the div that is output. Must not be blank.
2549 * @param string $caption text displayed at the top. Clicking on this will cause the region to expand or contract.
2550 * @param string $userpref the name of the user preference that stores the user's preferred default state.
2551 * (May be blank if you do not wish the state to be persisted.
2552 * @param boolean $default Initial collapsed state to use if the user_preference it not set.
2553 * @param boolean $return if true, return the HTML as a string, rather than printing it.
2554 * @param string $extracontent the extra content will show next to caption, eg.Help icon.
2555 * @return string|void if $return is false, returns nothing, otherwise returns a string of HTML.
2557 function print_collapsible_region_start($classes, $id, $caption, $userpref = '', $default = false, $return = false,
2558 $extracontent = null) {
2559 global $PAGE;
2561 // Work out the initial state.
2562 if (!empty($userpref) and is_string($userpref)) {
2563 $collapsed = get_user_preferences($userpref, $default);
2564 } else {
2565 $collapsed = $default;
2566 $userpref = false;
2569 if ($collapsed) {
2570 $classes .= ' collapsed';
2573 $output = '';
2574 $output .= '<div id="' . $id . '" class="collapsibleregion ' . $classes . '">';
2575 $output .= '<div id="' . $id . '_sizer">';
2576 $output .= '<div id="' . $id . '_caption" class="collapsibleregioncaption">';
2577 $output .= $caption . ' </div>';
2578 if ($extracontent) {
2579 $output .= html_writer::div($extracontent, 'collapsibleregionextracontent');
2581 $output .= '<div id="' . $id . '_inner" class="collapsibleregioninner">';
2582 $PAGE->requires->js_init_call('M.util.init_collapsible_region', array($id, $userpref, get_string('clicktohideshow')));
2584 if ($return) {
2585 return $output;
2586 } else {
2587 echo $output;
2592 * Close a region started with print_collapsible_region_start.
2594 * @param boolean $return if true, return the HTML as a string, rather than printing it.
2595 * @return string|void if $return is false, returns nothing, otherwise returns a string of HTML.
2597 function print_collapsible_region_end($return = false) {
2598 $output = '</div></div></div>';
2600 if ($return) {
2601 return $output;
2602 } else {
2603 echo $output;
2608 * Print a specified group's avatar.
2610 * @param array|stdClass $group A single {@link group} object OR array of groups.
2611 * @param int $courseid The course ID.
2612 * @param boolean $large Default small picture, or large.
2613 * @param boolean $return If false print picture, otherwise return the output as string
2614 * @param boolean $link Enclose image in a link to view specified course?
2615 * @param boolean $includetoken Whether to use a user token when displaying this group image.
2616 * True indicates to generate a token for current user, and integer value indicates to generate a token for the
2617 * user whose id is the value indicated.
2618 * If the group picture is included in an e-mail or some other location where the audience is a specific
2619 * user who will not be logged in when viewing, then we use a token to authenticate the user.
2620 * @return string|void Depending on the setting of $return
2622 function print_group_picture($group, $courseid, $large = false, $return = false, $link = true, $includetoken = false) {
2623 global $CFG;
2625 if (is_array($group)) {
2626 $output = '';
2627 foreach ($group as $g) {
2628 $output .= print_group_picture($g, $courseid, $large, true, $link, $includetoken);
2630 if ($return) {
2631 return $output;
2632 } else {
2633 echo $output;
2634 return;
2638 $pictureurl = get_group_picture_url($group, $courseid, $large, $includetoken);
2640 // If there is no picture, do nothing.
2641 if (!isset($pictureurl)) {
2642 return;
2645 $context = context_course::instance($courseid);
2647 $groupname = s($group->name);
2648 $pictureimage = html_writer::img($pictureurl, $groupname, ['title' => $groupname]);
2650 $output = '';
2651 if ($link or has_capability('moodle/site:accessallgroups', $context)) {
2652 $linkurl = new moodle_url('/user/index.php', ['id' => $courseid, 'group' => $group->id]);
2653 $output .= html_writer::link($linkurl, $pictureimage);
2654 } else {
2655 $output .= $pictureimage;
2658 if ($return) {
2659 return $output;
2660 } else {
2661 echo $output;
2666 * Return the url to the group picture.
2668 * @param stdClass $group A group object.
2669 * @param int $courseid The course ID for the group.
2670 * @param bool $large A large or small group picture? Default is small.
2671 * @param boolean $includetoken Whether to use a user token when displaying this group image.
2672 * True indicates to generate a token for current user, and integer value indicates to generate a token for the
2673 * user whose id is the value indicated.
2674 * If the group picture is included in an e-mail or some other location where the audience is a specific
2675 * user who will not be logged in when viewing, then we use a token to authenticate the user.
2676 * @return moodle_url Returns the url for the group picture.
2678 function get_group_picture_url($group, $courseid, $large = false, $includetoken = false) {
2679 global $CFG;
2681 $context = context_course::instance($courseid);
2683 // If there is no picture, do nothing.
2684 if (!$group->picture) {
2685 return;
2688 if ($large) {
2689 $file = 'f1';
2690 } else {
2691 $file = 'f2';
2694 $grouppictureurl = moodle_url::make_pluginfile_url(
2695 $context->id, 'group', 'icon', $group->id, '/', $file, false, $includetoken);
2696 $grouppictureurl->param('rev', $group->picture);
2697 return $grouppictureurl;
2702 * Display a recent activity note
2704 * @staticvar string $strftimerecent
2705 * @param int $time A timestamp int.
2706 * @param stdClass $user A user object from the database.
2707 * @param string $text Text for display for the note
2708 * @param string $link The link to wrap around the text
2709 * @param bool $return If set to true the HTML is returned rather than echo'd
2710 * @param string $viewfullnames
2711 * @return string If $retrun was true returns HTML for a recent activity notice.
2713 function print_recent_activity_note($time, $user, $text, $link, $return=false, $viewfullnames=null) {
2714 static $strftimerecent = null;
2715 $output = '';
2717 if (is_null($viewfullnames)) {
2718 $context = context_system::instance();
2719 $viewfullnames = has_capability('moodle/site:viewfullnames', $context);
2722 if (is_null($strftimerecent)) {
2723 $strftimerecent = get_string('strftimerecent');
2726 $output .= '<div class="head">';
2727 $output .= '<div class="date">'.userdate($time, $strftimerecent).'</div>';
2728 $output .= '<div class="name">'.fullname($user, $viewfullnames).'</div>';
2729 $output .= '</div>';
2730 $output .= '<div class="info"><a href="'.$link.'">'.format_string($text, true).'</a></div>';
2732 if ($return) {
2733 return $output;
2734 } else {
2735 echo $output;
2740 * Returns a popup menu with course activity modules
2742 * Given a course this function returns a small popup menu with all the course activity modules in it, as a navigation menu
2743 * outputs a simple list structure in XHTML.
2744 * The data is taken from the serialised array stored in the course record.
2746 * @param stdClass $course A course object.
2747 * @param array $sections
2748 * @param course_modinfo $modinfo
2749 * @param string $strsection
2750 * @param string $strjumpto
2751 * @param int $width
2752 * @param string $cmid
2753 * @return string The HTML block
2755 function navmenulist($course, $sections, $modinfo, $strsection, $strjumpto, $width=50, $cmid=0) {
2757 global $CFG, $OUTPUT;
2759 $section = -1;
2760 $menu = array();
2761 $doneheading = false;
2763 $courseformatoptions = course_get_format($course)->get_format_options();
2764 $coursecontext = context_course::instance($course->id);
2766 $menu[] = '<ul class="navmenulist"><li class="jumpto section"><span>'.$strjumpto.'</span><ul>';
2767 foreach ($modinfo->cms as $mod) {
2768 if (!$mod->has_view()) {
2769 // Don't show modules which you can't link to!
2770 continue;
2773 // For course formats using 'numsections' do not show extra sections.
2774 if (isset($courseformatoptions['numsections']) && $mod->sectionnum > $courseformatoptions['numsections']) {
2775 break;
2778 if (!$mod->uservisible) { // Do not icnlude empty sections at all.
2779 continue;
2782 if ($mod->sectionnum >= 0 and $section != $mod->sectionnum) {
2783 $thissection = $sections[$mod->sectionnum];
2785 if ($thissection->visible or
2786 (isset($courseformatoptions['hiddensections']) and !$courseformatoptions['hiddensections']) or
2787 has_capability('moodle/course:viewhiddensections', $coursecontext)) {
2788 $thissection->summary = strip_tags(format_string($thissection->summary, true));
2789 if (!$doneheading) {
2790 $menu[] = '</ul></li>';
2792 if ($course->format == 'weeks' or empty($thissection->summary)) {
2793 $item = $strsection ." ". $mod->sectionnum;
2794 } else {
2795 if (core_text::strlen($thissection->summary) < ($width-3)) {
2796 $item = $thissection->summary;
2797 } else {
2798 $item = core_text::substr($thissection->summary, 0, $width).'...';
2801 $menu[] = '<li class="section"><span>'.$item.'</span>';
2802 $menu[] = '<ul>';
2803 $doneheading = true;
2805 $section = $mod->sectionnum;
2806 } else {
2807 // No activities from this hidden section shown.
2808 continue;
2812 $url = $mod->modname .'/view.php?id='. $mod->id;
2813 $mod->name = strip_tags(format_string($mod->name ,true));
2814 if (core_text::strlen($mod->name) > ($width+5)) {
2815 $mod->name = core_text::substr($mod->name, 0, $width).'...';
2817 if (!$mod->visible) {
2818 $mod->name = '('.$mod->name.')';
2820 $class = 'activity '.$mod->modname;
2821 $class .= ($cmid == $mod->id) ? ' selected' : '';
2822 $menu[] = '<li class="'.$class.'">'.
2823 $OUTPUT->image_icon('monologo', '', $mod->modname).
2824 '<a href="'.$CFG->wwwroot.'/mod/'.$url.'">'.$mod->name.'</a></li>';
2827 if ($doneheading) {
2828 $menu[] = '</ul></li>';
2830 $menu[] = '</ul></li></ul>';
2832 return implode("\n", $menu);
2836 * Prints a grade menu (as part of an existing form) with help showing all possible numerical grades and scales.
2838 * @todo Finish documenting this function
2839 * @todo Deprecate: this is only used in a few contrib modules
2841 * @param int $courseid The course ID
2842 * @param string $name
2843 * @param string $current
2844 * @param boolean $includenograde Include those with no grades
2845 * @param boolean $return If set to true returns rather than echo's
2846 * @return string|bool Depending on value of $return
2848 function print_grade_menu($courseid, $name, $current, $includenograde=true, $return=false) {
2849 global $OUTPUT;
2851 $output = '';
2852 $strscale = get_string('scale');
2853 $strscales = get_string('scales');
2855 $scales = get_scales_menu($courseid);
2856 foreach ($scales as $i => $scalename) {
2857 $grades[-$i] = $strscale .': '. $scalename;
2859 if ($includenograde) {
2860 $grades[0] = get_string('nograde');
2862 for ($i=100; $i>=1; $i--) {
2863 $grades[$i] = $i;
2865 $output .= html_writer::select($grades, $name, $current, false);
2867 $linkobject = '<span class="helplink">' . $OUTPUT->pix_icon('help', $strscales) . '</span>';
2868 $link = new moodle_url('/course/scales.php', array('id' => $courseid, 'list' => 1));
2869 $action = new popup_action('click', $link, 'ratingscales', array('height' => 400, 'width' => 500));
2870 $output .= $OUTPUT->action_link($link, $linkobject, $action, array('title' => $strscales));
2872 if ($return) {
2873 return $output;
2874 } else {
2875 echo $output;
2880 * Print an error to STDOUT and exit with a non-zero code. For commandline scripts.
2882 * Default errorcode is 1.
2884 * Very useful for perl-like error-handling:
2885 * do_somethting() or mdie("Something went wrong");
2887 * @param string $msg Error message
2888 * @param integer $errorcode Error code to emit
2890 function mdie($msg='', $errorcode=1) {
2891 trigger_error($msg);
2892 exit($errorcode);
2896 * Print a message and exit.
2898 * @param string $message The message to print in the notice
2899 * @param moodle_url|string $link The link to use for the continue button
2900 * @param object $course A course object. Unused.
2901 * @return void This function simply exits
2903 function notice ($message, $link='', $course=null) {
2904 global $PAGE, $OUTPUT;
2906 $message = clean_text($message); // In case nasties are in here.
2908 if (CLI_SCRIPT) {
2909 echo("!!$message!!\n");
2910 exit(1); // No success.
2913 if (!$PAGE->headerprinted) {
2914 // Header not yet printed.
2915 $PAGE->set_title(get_string('notice'));
2916 echo $OUTPUT->header();
2917 } else {
2918 echo $OUTPUT->container_end_all(false);
2921 echo $OUTPUT->box($message, 'generalbox', 'notice');
2922 echo $OUTPUT->continue_button($link);
2924 echo $OUTPUT->footer();
2925 exit(1); // General error code.
2929 * Redirects the user to another page, after printing a notice.
2931 * This function calls the OUTPUT redirect method, echo's the output and then dies to ensure nothing else happens.
2933 * <strong>Good practice:</strong> You should call this method before starting page
2934 * output by using any of the OUTPUT methods.
2936 * @param moodle_url|string $url A moodle_url to redirect to. Strings are not to be trusted!
2937 * @param string $message The message to display to the user
2938 * @param int $delay The delay before redirecting
2939 * @param string $messagetype The type of notification to show the message in. See constants on \core\output\notification.
2940 * @throws moodle_exception
2942 function redirect($url, $message='', $delay=null, $messagetype = \core\output\notification::NOTIFY_INFO) {
2943 global $OUTPUT, $PAGE, $CFG;
2945 if (CLI_SCRIPT or AJAX_SCRIPT) {
2946 // This is wrong - developers should not use redirect in these scripts but it should not be very likely.
2947 throw new moodle_exception('redirecterrordetected', 'error');
2950 if ($delay === null) {
2951 $delay = -1;
2954 // Prevent debug errors - make sure context is properly initialised.
2955 if ($PAGE) {
2956 $PAGE->set_context(null);
2957 $PAGE->set_pagelayout('redirect'); // No header and footer needed.
2958 $PAGE->set_title(get_string('pageshouldredirect', 'moodle'));
2961 if ($url instanceof moodle_url) {
2962 $url = $url->out(false);
2965 $debugdisableredirect = false;
2966 do {
2967 if (defined('DEBUGGING_PRINTED')) {
2968 // Some debugging already printed, no need to look more.
2969 $debugdisableredirect = true;
2970 break;
2973 if (core_useragent::is_msword()) {
2974 // Clicking a URL from MS Word sends a request to the server without cookies. If that
2975 // causes a redirect Word will open a browser pointing the new URL. If not, the URL that
2976 // was clicked is opened. Because the request from Word is without cookies, it almost
2977 // always results in a redirect to the login page, even if the user is logged in in their
2978 // browser. This is not what we want, so prevent the redirect for requests from Word.
2979 $debugdisableredirect = true;
2980 break;
2983 if (empty($CFG->debugdisplay) or empty($CFG->debug)) {
2984 // No errors should be displayed.
2985 break;
2988 if (!function_exists('error_get_last') or !$lasterror = error_get_last()) {
2989 break;
2992 if (!($lasterror['type'] & $CFG->debug)) {
2993 // Last error not interesting.
2994 break;
2997 // Watch out here, @hidden() errors are returned from error_get_last() too.
2998 if (headers_sent()) {
2999 // We already started printing something - that means errors likely printed.
3000 $debugdisableredirect = true;
3001 break;
3004 if (ob_get_level() and ob_get_contents()) {
3005 // There is something waiting to be printed, hopefully it is the errors,
3006 // but it might be some error hidden by @ too - such as the timezone mess from setup.php.
3007 $debugdisableredirect = true;
3008 break;
3010 } while (false);
3012 // Technically, HTTP/1.1 requires Location: header to contain the absolute path.
3013 // (In practice browsers accept relative paths - but still, might as well do it properly.)
3014 // This code turns relative into absolute.
3015 if (!preg_match('|^[a-z]+:|i', $url)) {
3016 // Get host name http://www.wherever.com.
3017 $hostpart = preg_replace('|^(.*?[^:/])/.*$|', '$1', $CFG->wwwroot);
3018 if (preg_match('|^/|', $url)) {
3019 // URLs beginning with / are relative to web server root so we just add them in.
3020 $url = $hostpart.$url;
3021 } else {
3022 // URLs not beginning with / are relative to path of current script, so add that on.
3023 $url = $hostpart.preg_replace('|\?.*$|', '', me()).'/../'.$url;
3025 // Replace all ..s.
3026 while (true) {
3027 $newurl = preg_replace('|/(?!\.\.)[^/]*/\.\./|', '/', $url);
3028 if ($newurl == $url) {
3029 break;
3031 $url = $newurl;
3035 // Sanitise url - we can not rely on moodle_url or our URL cleaning
3036 // because they do not support all valid external URLs.
3037 $url = preg_replace('/[\x00-\x1F\x7F]/', '', $url);
3038 $url = str_replace('"', '%22', $url);
3039 $encodedurl = preg_replace("/\&(?![a-zA-Z0-9#]{1,8};)/", "&amp;", $url);
3040 $encodedurl = preg_replace('/^.*href="([^"]*)".*$/', "\\1", clean_text('<a href="'.$encodedurl.'" />', FORMAT_HTML));
3041 $url = str_replace('&amp;', '&', $encodedurl);
3043 if (!empty($message)) {
3044 if (!$debugdisableredirect && !headers_sent()) {
3045 // A message has been provided, and the headers have not yet been sent.
3046 // Display the message as a notification on the subsequent page.
3047 \core\notification::add($message, $messagetype);
3048 $message = null;
3049 $delay = 0;
3050 } else {
3051 if ($delay === -1 || !is_numeric($delay)) {
3052 $delay = 3;
3054 $message = clean_text($message);
3056 } else {
3057 $message = get_string('pageshouldredirect');
3058 $delay = 0;
3061 // Make sure the session is closed properly, this prevents problems in IIS
3062 // and also some potential PHP shutdown issues.
3063 \core\session\manager::write_close();
3065 if ($delay == 0 && !$debugdisableredirect && !headers_sent()) {
3067 // This helps when debugging redirect issues like loops and it is not clear
3068 // which layer in the stack sent the redirect header. If debugging is on
3069 // then the file and line is also shown.
3070 $redirectby = 'Moodle';
3071 if (debugging('', DEBUG_DEVELOPER)) {
3072 $origin = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 1)[0];
3073 $redirectby .= ' /' . str_replace($CFG->dirroot . '/', '', $origin['file']) . ':' . $origin['line'];
3075 @header("X-Redirect-By: $redirectby");
3077 // 302 might not work for POST requests, 303 is ignored by obsolete clients.
3078 @header($_SERVER['SERVER_PROTOCOL'] . ' 303 See Other');
3079 @header('Location: '.$url);
3080 echo bootstrap_renderer::plain_redirect_message($encodedurl);
3081 exit;
3084 // Include a redirect message, even with a HTTP redirect, because that is recommended practice.
3085 if ($PAGE) {
3086 $CFG->docroot = false; // To prevent the link to moodle docs from being displayed on redirect page.
3087 echo $OUTPUT->redirect_message($encodedurl, $message, $delay, $debugdisableredirect, $messagetype);
3088 exit;
3089 } else {
3090 echo bootstrap_renderer::early_redirect_message($encodedurl, $message, $delay);
3091 exit;
3096 * Given an email address, this function will return an obfuscated version of it.
3098 * @param string $email The email address to obfuscate
3099 * @return string The obfuscated email address
3101 function obfuscate_email($email) {
3102 $i = 0;
3103 $length = strlen($email);
3104 $obfuscated = '';
3105 while ($i < $length) {
3106 if (rand(0, 2) && $email[$i]!='@') { // MDL-20619 some browsers have problems unobfuscating @.
3107 $obfuscated.='%'.dechex(ord($email[$i]));
3108 } else {
3109 $obfuscated.=$email[$i];
3111 $i++;
3113 return $obfuscated;
3117 * This function takes some text and replaces about half of the characters
3118 * with HTML entity equivalents. Return string is obviously longer.
3120 * @param string $plaintext The text to be obfuscated
3121 * @return string The obfuscated text
3123 function obfuscate_text($plaintext) {
3124 $i=0;
3125 $length = core_text::strlen($plaintext);
3126 $obfuscated='';
3127 $prevobfuscated = false;
3128 while ($i < $length) {
3129 $char = core_text::substr($plaintext, $i, 1);
3130 $ord = core_text::utf8ord($char);
3131 $numerical = ($ord >= ord('0')) && ($ord <= ord('9'));
3132 if ($prevobfuscated and $numerical ) {
3133 $obfuscated.='&#'.$ord.';';
3134 } else if (rand(0, 2)) {
3135 $obfuscated.='&#'.$ord.';';
3136 $prevobfuscated = true;
3137 } else {
3138 $obfuscated.=$char;
3139 $prevobfuscated = false;
3141 $i++;
3143 return $obfuscated;
3147 * This function uses the {@link obfuscate_email()} and {@link obfuscate_text()}
3148 * to generate a fully obfuscated email link, ready to use.
3150 * @param string $email The email address to display
3151 * @param string $label The text to displayed as hyperlink to $email
3152 * @param boolean $dimmed If true then use css class 'dimmed' for hyperlink
3153 * @param string $subject The subject of the email in the mailto link
3154 * @param string $body The content of the email in the mailto link
3155 * @return string The obfuscated mailto link
3157 function obfuscate_mailto($email, $label='', $dimmed=false, $subject = '', $body = '') {
3159 if (empty($label)) {
3160 $label = $email;
3163 $label = obfuscate_text($label);
3164 $email = obfuscate_email($email);
3165 $mailto = obfuscate_text('mailto');
3166 $url = new moodle_url("mailto:$email");
3167 $attrs = array();
3169 if (!empty($subject)) {
3170 $url->param('subject', format_string($subject));
3172 if (!empty($body)) {
3173 $url->param('body', format_string($body));
3176 // Use the obfuscated mailto.
3177 $url = preg_replace('/^mailto/', $mailto, $url->out());
3179 if ($dimmed) {
3180 $attrs['title'] = get_string('emaildisable');
3181 $attrs['class'] = 'dimmed';
3184 return html_writer::link($url, $label, $attrs);
3188 * This function is used to rebuild the <nolink> tag because some formats (PLAIN and WIKI)
3189 * will transform it to html entities
3191 * @param string $text Text to search for nolink tag in
3192 * @return string
3194 function rebuildnolinktag($text) {
3196 $text = preg_replace('/&lt;(\/*nolink)&gt;/i', '<$1>', $text);
3198 return $text;
3202 * Prints a maintenance message from $CFG->maintenance_message or default if empty.
3204 function print_maintenance_message() {
3205 global $CFG, $SITE, $PAGE, $OUTPUT;
3207 header($_SERVER['SERVER_PROTOCOL'] . ' 503 Moodle under maintenance');
3208 header('Status: 503 Moodle under maintenance');
3209 header('Retry-After: 300');
3211 $PAGE->set_pagetype('maintenance-message');
3212 $PAGE->set_pagelayout('maintenance');
3213 $PAGE->set_title(strip_tags($SITE->fullname));
3214 $PAGE->set_heading($SITE->fullname);
3215 echo $OUTPUT->header();
3216 echo $OUTPUT->heading(get_string('sitemaintenance', 'admin'));
3217 if (isset($CFG->maintenance_message) and !html_is_blank($CFG->maintenance_message)) {
3218 echo $OUTPUT->box_start('maintenance_message generalbox boxwidthwide boxaligncenter');
3219 echo $CFG->maintenance_message;
3220 echo $OUTPUT->box_end();
3222 echo $OUTPUT->footer();
3223 die;
3227 * Returns a string containing a nested list, suitable for formatting into tabs with CSS.
3229 * It is not recommended to use this function in Moodle 2.5 but it is left for backward
3230 * compartibility.
3232 * Example how to print a single line tabs:
3233 * $rows = array(
3234 * new tabobject(...),
3235 * new tabobject(...)
3236 * );
3237 * echo $OUTPUT->tabtree($rows, $selectedid);
3239 * Multiple row tabs may not look good on some devices but if you want to use them
3240 * you can specify ->subtree for the active tabobject.
3242 * @param array $tabrows An array of rows where each row is an array of tab objects
3243 * @param string $selected The id of the selected tab (whatever row it's on)
3244 * @param array $inactive An array of ids of inactive tabs that are not selectable.
3245 * @param array $activated An array of ids of other tabs that are currently activated
3246 * @param bool $return If true output is returned rather then echo'd
3247 * @return string HTML output if $return was set to true.
3249 function print_tabs($tabrows, $selected = null, $inactive = null, $activated = null, $return = false) {
3250 global $OUTPUT;
3252 $tabrows = array_reverse($tabrows);
3253 $subtree = array();
3254 foreach ($tabrows as $row) {
3255 $tree = array();
3257 foreach ($row as $tab) {
3258 $tab->inactive = is_array($inactive) && in_array((string)$tab->id, $inactive);
3259 $tab->activated = is_array($activated) && in_array((string)$tab->id, $activated);
3260 $tab->selected = (string)$tab->id == $selected;
3262 if ($tab->activated || $tab->selected) {
3263 $tab->subtree = $subtree;
3265 $tree[] = $tab;
3267 $subtree = $tree;
3269 $output = $OUTPUT->tabtree($subtree);
3270 if ($return) {
3271 return $output;
3272 } else {
3273 print $output;
3274 return !empty($output);
3279 * Alter debugging level for the current request,
3280 * the change is not saved in database.
3282 * @param int $level one of the DEBUG_* constants
3283 * @param bool $debugdisplay
3285 function set_debugging($level, $debugdisplay = null) {
3286 global $CFG;
3288 $CFG->debug = (int)$level;
3289 $CFG->debugdeveloper = (($CFG->debug & DEBUG_DEVELOPER) === DEBUG_DEVELOPER);
3291 if ($debugdisplay !== null) {
3292 $CFG->debugdisplay = (bool)$debugdisplay;
3297 * Standard Debugging Function
3299 * Returns true if the current site debugging settings are equal or above specified level.
3300 * If passed a parameter it will emit a debugging notice similar to trigger_error(). The
3301 * routing of notices is controlled by $CFG->debugdisplay
3302 * eg use like this:
3304 * 1) debugging('a normal debug notice');
3305 * 2) debugging('something really picky', DEBUG_ALL);
3306 * 3) debugging('annoying debug message only for developers', DEBUG_DEVELOPER);
3307 * 4) if (debugging()) { perform extra debugging operations (do not use print or echo) }
3309 * In code blocks controlled by debugging() (such as example 4)
3310 * any output should be routed via debugging() itself, or the lower-level
3311 * trigger_error() or error_log(). Using echo or print will break XHTML
3312 * JS and HTTP headers.
3314 * It is also possible to define NO_DEBUG_DISPLAY which redirects the message to error_log.
3316 * @param string $message a message to print
3317 * @param int $level the level at which this debugging statement should show
3318 * @param array $backtrace use different backtrace
3319 * @return bool
3321 function debugging($message = '', $level = DEBUG_NORMAL, $backtrace = null) {
3322 global $CFG, $USER;
3324 $forcedebug = false;
3325 if (!empty($CFG->debugusers) && $USER) {
3326 $debugusers = explode(',', $CFG->debugusers);
3327 $forcedebug = in_array($USER->id, $debugusers);
3330 if (!$forcedebug and (empty($CFG->debug) || ($CFG->debug != -1 and $CFG->debug < $level))) {
3331 return false;
3334 if (!isset($CFG->debugdisplay)) {
3335 $CFG->debugdisplay = ini_get_bool('display_errors');
3338 if ($message) {
3339 if (!$backtrace) {
3340 $backtrace = debug_backtrace();
3342 $from = format_backtrace($backtrace, CLI_SCRIPT || NO_DEBUG_DISPLAY);
3343 if (PHPUNIT_TEST) {
3344 if (phpunit_util::debugging_triggered($message, $level, $from)) {
3345 // We are inside test, the debug message was logged.
3346 return true;
3350 if (NO_DEBUG_DISPLAY) {
3351 // Script does not want any errors or debugging in output,
3352 // we send the info to error log instead.
3353 error_log('Debugging: ' . $message . ' in '. PHP_EOL . $from);
3355 } else if ($forcedebug or $CFG->debugdisplay) {
3356 if (!defined('DEBUGGING_PRINTED')) {
3357 define('DEBUGGING_PRINTED', 1); // Indicates we have printed something.
3359 if (CLI_SCRIPT) {
3360 echo "++ $message ++\n$from";
3361 } else {
3362 echo '<div class="notifytiny debuggingmessage" data-rel="debugging">' , $message , $from , '</div>';
3365 } else {
3366 trigger_error($message . $from, E_USER_NOTICE);
3369 return true;
3373 * Outputs a HTML comment to the browser.
3375 * This is used for those hard-to-debug pages that use bits from many different files in very confusing ways (e.g. blocks).
3377 * <code>print_location_comment(__FILE__, __LINE__);</code>
3379 * @param string $file
3380 * @param integer $line
3381 * @param boolean $return Whether to return or print the comment
3382 * @return string|void Void unless true given as third parameter
3384 function print_location_comment($file, $line, $return = false) {
3385 if ($return) {
3386 return "<!-- $file at line $line -->\n";
3387 } else {
3388 echo "<!-- $file at line $line -->\n";
3394 * Returns true if the user is using a right-to-left language.
3396 * @return boolean true if the current language is right-to-left (Hebrew, Arabic etc)
3398 function right_to_left() {
3399 return (get_string('thisdirection', 'langconfig') === 'rtl');
3404 * Returns swapped left<=> right if in RTL environment.
3406 * Part of RTL Moodles support.
3408 * @param string $align align to check
3409 * @return string
3411 function fix_align_rtl($align) {
3412 if (!right_to_left()) {
3413 return $align;
3415 if ($align == 'left') {
3416 return 'right';
3418 if ($align == 'right') {
3419 return 'left';
3421 return $align;
3426 * Returns true if the page is displayed in a popup window.
3428 * Gets the information from the URL parameter inpopup.
3430 * @todo Use a central function to create the popup calls all over Moodle and
3431 * In the moment only works with resources and probably questions.
3433 * @return boolean
3435 function is_in_popup() {
3436 $inpopup = optional_param('inpopup', '', PARAM_BOOL);
3438 return ($inpopup);
3442 * Progress trace class.
3444 * Use this class from long operations where you want to output occasional information about
3445 * what is going on, but don't know if, or in what format, the output should be.
3447 * @copyright 2009 Tim Hunt
3448 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3449 * @package core
3451 abstract class progress_trace {
3453 * Output an progress message in whatever format.
3455 * @param string $message the message to output.
3456 * @param integer $depth indent depth for this message.
3458 abstract public function output($message, $depth = 0);
3461 * Called when the processing is finished.
3463 public function finished() {
3468 * This subclass of progress_trace does not ouput anything.
3470 * @copyright 2009 Tim Hunt
3471 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3472 * @package core
3474 class null_progress_trace extends progress_trace {
3476 * Does Nothing
3478 * @param string $message
3479 * @param int $depth
3480 * @return void Does Nothing
3482 public function output($message, $depth = 0) {
3487 * This subclass of progress_trace outputs to plain text.
3489 * @copyright 2009 Tim Hunt
3490 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3491 * @package core
3493 class text_progress_trace extends progress_trace {
3495 * Output the trace message.
3497 * @param string $message
3498 * @param int $depth
3499 * @return void Output is echo'd
3501 public function output($message, $depth = 0) {
3502 mtrace(str_repeat(' ', $depth) . $message);
3507 * This subclass of progress_trace outputs as HTML.
3509 * @copyright 2009 Tim Hunt
3510 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3511 * @package core
3513 class html_progress_trace extends progress_trace {
3515 * Output the trace message.
3517 * @param string $message
3518 * @param int $depth
3519 * @return void Output is echo'd
3521 public function output($message, $depth = 0) {
3522 echo '<p>', str_repeat('&#160;&#160;', $depth), htmlspecialchars($message, ENT_COMPAT), "</p>\n";
3523 flush();
3528 * HTML List Progress Tree
3530 * @copyright 2009 Tim Hunt
3531 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3532 * @package core
3534 class html_list_progress_trace extends progress_trace {
3535 /** @var int */
3536 protected $currentdepth = -1;
3539 * Echo out the list
3541 * @param string $message The message to display
3542 * @param int $depth
3543 * @return void Output is echoed
3545 public function output($message, $depth = 0) {
3546 $samedepth = true;
3547 while ($this->currentdepth > $depth) {
3548 echo "</li>\n</ul>\n";
3549 $this->currentdepth -= 1;
3550 if ($this->currentdepth == $depth) {
3551 echo '<li>';
3553 $samedepth = false;
3555 while ($this->currentdepth < $depth) {
3556 echo "<ul>\n<li>";
3557 $this->currentdepth += 1;
3558 $samedepth = false;
3560 if ($samedepth) {
3561 echo "</li>\n<li>";
3563 echo htmlspecialchars($message, ENT_COMPAT);
3564 flush();
3568 * Called when the processing is finished.
3570 public function finished() {
3571 while ($this->currentdepth >= 0) {
3572 echo "</li>\n</ul>\n";
3573 $this->currentdepth -= 1;
3579 * This subclass of progress_trace outputs to error log.
3581 * @copyright Petr Skoda {@link http://skodak.org}
3582 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3583 * @package core
3585 class error_log_progress_trace extends progress_trace {
3586 /** @var string log prefix */
3587 protected $prefix;
3590 * Constructor.
3591 * @param string $prefix optional log prefix
3593 public function __construct($prefix = '') {
3594 $this->prefix = $prefix;
3598 * Output the trace message.
3600 * @param string $message
3601 * @param int $depth
3602 * @return void Output is sent to error log.
3604 public function output($message, $depth = 0) {
3605 error_log($this->prefix . str_repeat(' ', $depth) . $message);
3610 * Special type of trace that can be used for catching of output of other traces.
3612 * @copyright Petr Skoda {@link http://skodak.org}
3613 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3614 * @package core
3616 class progress_trace_buffer extends progress_trace {
3617 /** @var progress_trace */
3618 protected $trace;
3619 /** @var bool do we pass output out */
3620 protected $passthrough;
3621 /** @var string output buffer */
3622 protected $buffer;
3625 * Constructor.
3627 * @param progress_trace $trace
3628 * @param bool $passthrough true means output and buffer, false means just buffer and no output
3630 public function __construct(progress_trace $trace, $passthrough = true) {
3631 $this->trace = $trace;
3632 $this->passthrough = $passthrough;
3633 $this->buffer = '';
3637 * Output the trace message.
3639 * @param string $message the message to output.
3640 * @param int $depth indent depth for this message.
3641 * @return void output stored in buffer
3643 public function output($message, $depth = 0) {
3644 ob_start();
3645 $this->trace->output($message, $depth);
3646 $this->buffer .= ob_get_contents();
3647 if ($this->passthrough) {
3648 ob_end_flush();
3649 } else {
3650 ob_end_clean();
3655 * Called when the processing is finished.
3657 public function finished() {
3658 ob_start();
3659 $this->trace->finished();
3660 $this->buffer .= ob_get_contents();
3661 if ($this->passthrough) {
3662 ob_end_flush();
3663 } else {
3664 ob_end_clean();
3669 * Reset internal text buffer.
3671 public function reset_buffer() {
3672 $this->buffer = '';
3676 * Return internal text buffer.
3677 * @return string buffered plain text
3679 public function get_buffer() {
3680 return $this->buffer;
3685 * Special type of trace that can be used for redirecting to multiple other traces.
3687 * @copyright Petr Skoda {@link http://skodak.org}
3688 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3689 * @package core
3691 class combined_progress_trace extends progress_trace {
3694 * An array of traces.
3695 * @var array
3697 protected $traces;
3700 * Constructs a new instance.
3702 * @param array $traces multiple traces
3704 public function __construct(array $traces) {
3705 $this->traces = $traces;
3709 * Output an progress message in whatever format.
3711 * @param string $message the message to output.
3712 * @param integer $depth indent depth for this message.
3714 public function output($message, $depth = 0) {
3715 foreach ($this->traces as $trace) {
3716 $trace->output($message, $depth);
3721 * Called when the processing is finished.
3723 public function finished() {
3724 foreach ($this->traces as $trace) {
3725 $trace->finished();
3731 * Returns a localized sentence in the current language summarizing the current password policy
3733 * @todo this should be handled by a function/method in the language pack library once we have a support for it
3734 * @uses $CFG
3735 * @return string
3737 function print_password_policy() {
3738 global $CFG;
3740 $message = '';
3741 if (!empty($CFG->passwordpolicy)) {
3742 $messages = array();
3743 if (!empty($CFG->minpasswordlength)) {
3744 $messages[] = get_string('informminpasswordlength', 'auth', $CFG->minpasswordlength);
3746 if (!empty($CFG->minpassworddigits)) {
3747 $messages[] = get_string('informminpassworddigits', 'auth', $CFG->minpassworddigits);
3749 if (!empty($CFG->minpasswordlower)) {
3750 $messages[] = get_string('informminpasswordlower', 'auth', $CFG->minpasswordlower);
3752 if (!empty($CFG->minpasswordupper)) {
3753 $messages[] = get_string('informminpasswordupper', 'auth', $CFG->minpasswordupper);
3755 if (!empty($CFG->minpasswordnonalphanum)) {
3756 $messages[] = get_string('informminpasswordnonalphanum', 'auth', $CFG->minpasswordnonalphanum);
3759 // Fire any additional password policy functions from plugins.
3760 // Callbacks must return an array of message strings.
3761 $pluginsfunction = get_plugins_with_function('print_password_policy');
3762 foreach ($pluginsfunction as $plugintype => $plugins) {
3763 foreach ($plugins as $pluginfunction) {
3764 $messages = array_merge($messages, $pluginfunction());
3768 $messages = join(', ', $messages); // This is ugly but we do not have anything better yet...
3769 // Check if messages is empty before outputting any text.
3770 if ($messages != '') {
3771 $message = get_string('informpasswordpolicy', 'auth', $messages);
3774 return $message;
3778 * Get the value of a help string fully prepared for display in the current language.
3780 * @param string $identifier The identifier of the string to search for.
3781 * @param string $component The module the string is associated with.
3782 * @param boolean $ajax Whether this help is called from an AJAX script.
3783 * This is used to influence text formatting and determines
3784 * which format to output the doclink in.
3785 * @param string|object|array $a An object, string or number that can be used
3786 * within translation strings
3787 * @return stdClass An object containing:
3788 * - heading: Any heading that there may be for this help string.
3789 * - text: The wiki-formatted help string.
3790 * - doclink: An object containing a link, the linktext, and any additional
3791 * CSS classes to apply to that link. Only present if $ajax = false.
3792 * - completedoclink: A text representation of the doclink. Only present if $ajax = true.
3794 function get_formatted_help_string($identifier, $component, $ajax = false, $a = null) {
3795 global $CFG, $OUTPUT;
3796 $sm = get_string_manager();
3798 // Do not rebuild caches here!
3799 // Devs need to learn to purge all caches after any change or disable $CFG->langstringcache.
3801 $data = new stdClass();
3803 if ($sm->string_exists($identifier, $component)) {
3804 $data->heading = format_string(get_string($identifier, $component));
3805 } else {
3806 // Gracefully fall back to an empty string.
3807 $data->heading = '';
3810 if ($sm->string_exists($identifier . '_help', $component)) {
3811 $options = new stdClass();
3812 $options->trusted = false;
3813 $options->noclean = false;
3814 $options->smiley = false;
3815 $options->filter = false;
3816 $options->para = true;
3817 $options->newlines = false;
3818 $options->overflowdiv = !$ajax;
3820 // Should be simple wiki only MDL-21695.
3821 $data->text = format_text(get_string($identifier.'_help', $component, $a), FORMAT_MARKDOWN, $options);
3823 $helplink = $identifier . '_link';
3824 if ($sm->string_exists($helplink, $component)) { // Link to further info in Moodle docs.
3825 $link = get_string($helplink, $component);
3826 $linktext = get_string('morehelp');
3828 $data->doclink = new stdClass();
3829 $url = new moodle_url(get_docs_url($link));
3830 if ($ajax) {
3831 $data->doclink->link = $url->out();
3832 $data->doclink->linktext = $linktext;
3833 $data->doclink->class = ($CFG->doctonewwindow) ? 'helplinkpopup' : '';
3834 } else {
3835 $data->completedoclink = html_writer::tag('div', $OUTPUT->doc_link($link, $linktext),
3836 array('class' => 'helpdoclink'));
3839 } else {
3840 $data->text = html_writer::tag('p',
3841 html_writer::tag('strong', 'TODO') . ": missing help string [{$identifier}_help, {$component}]");
3843 return $data;