Merge branch 'MDL-79681' of https://github.com/paulholden/moodle
[moodle.git] / lib / weblib.php
blob8415fe0a90b982c346cc130fdc7f6e6ceab2cfce
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 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
259 * @package core
261 class moodle_url {
264 * Scheme, ex.: http, https
265 * @var string
267 protected $scheme = '';
270 * Hostname.
271 * @var string
273 protected $host = '';
276 * Port number, empty means default 80 or 443 in case of http.
277 * @var int
279 protected $port = '';
282 * Username for http auth.
283 * @var string
285 protected $user = '';
288 * Password for http auth.
289 * @var string
291 protected $pass = '';
294 * Script path.
295 * @var string
297 protected $path = '';
300 * Optional slash argument value.
301 * @var string
303 protected $slashargument = '';
306 * Anchor, may be also empty, null means none.
307 * @var string
309 protected $anchor = null;
312 * Url parameters as associative array.
313 * @var array
315 protected $params = array();
318 * Create new instance of moodle_url.
320 * @param moodle_url|string $url - moodle_url means make a copy of another
321 * moodle_url and change parameters, string means full url or shortened
322 * form (ex.: '/course/view.php'). It is strongly encouraged to not include
323 * query string because it may result in double encoded values. Use the
324 * $params instead. For admin URLs, just use /admin/script.php, this
325 * class takes care of the $CFG->admin issue.
326 * @param array $params these params override current params or add new
327 * @param string $anchor The anchor to use as part of the URL if there is one.
328 * @throws moodle_exception
330 public function __construct($url, array $params = null, $anchor = null) {
331 global $CFG;
333 if ($url instanceof moodle_url) {
334 $this->scheme = $url->scheme;
335 $this->host = $url->host;
336 $this->port = $url->port;
337 $this->user = $url->user;
338 $this->pass = $url->pass;
339 $this->path = $url->path;
340 $this->slashargument = $url->slashargument;
341 $this->params = $url->params;
342 $this->anchor = $url->anchor;
344 } else {
345 $url = $url ?? '';
346 // Detect if anchor used.
347 $apos = strpos($url, '#');
348 if ($apos !== false) {
349 $anchor = substr($url, $apos);
350 $anchor = ltrim($anchor, '#');
351 $this->set_anchor($anchor);
352 $url = substr($url, 0, $apos);
355 // Normalise shortened form of our url ex.: '/course/view.php'.
356 if (strpos($url, '/') === 0) {
357 $url = $CFG->wwwroot.$url;
360 if ($CFG->admin !== 'admin') {
361 if (strpos($url, "$CFG->wwwroot/admin/") === 0) {
362 $url = str_replace("$CFG->wwwroot/admin/", "$CFG->wwwroot/$CFG->admin/", $url);
366 // Parse the $url.
367 $parts = parse_url($url);
368 if ($parts === false) {
369 throw new moodle_exception('invalidurl');
371 if (isset($parts['query'])) {
372 // Note: the values may not be correctly decoded, url parameters should be always passed as array.
373 parse_str(str_replace('&amp;', '&', $parts['query']), $this->params);
375 unset($parts['query']);
376 foreach ($parts as $key => $value) {
377 $this->$key = $value;
380 // Detect slashargument value from path - we do not support directory names ending with .php.
381 $pos = strpos($this->path, '.php/');
382 if ($pos !== false) {
383 $this->slashargument = substr($this->path, $pos + 4);
384 $this->path = substr($this->path, 0, $pos + 4);
388 $this->params($params);
389 if ($anchor !== null) {
390 $this->anchor = (string)$anchor;
395 * Add an array of params to the params for this url.
397 * The added params override existing ones if they have the same name.
399 * @param array $params Defaults to null. If null then returns all params.
400 * @return array Array of Params for url.
401 * @throws coding_exception
403 public function params(array $params = null) {
404 $params = (array)$params;
406 foreach ($params as $key => $value) {
407 if (is_int($key)) {
408 throw new coding_exception('Url parameters can not have numeric keys!');
410 if (!is_string($value)) {
411 if (is_array($value)) {
412 throw new coding_exception('Url parameters values can not be arrays!');
414 if (is_object($value) and !method_exists($value, '__toString')) {
415 throw new coding_exception('Url parameters values can not be objects, unless __toString() is defined!');
418 $this->params[$key] = (string)$value;
420 return $this->params;
424 * Remove all params if no arguments passed.
425 * Remove selected params if arguments are passed.
427 * Can be called as either remove_params('param1', 'param2')
428 * or remove_params(array('param1', 'param2')).
430 * @param string[]|string $params,... either an array of param names, or 1..n string params to remove as args.
431 * @return array url parameters
433 public function remove_params($params = null) {
434 if (!is_array($params)) {
435 $params = func_get_args();
437 foreach ($params as $param) {
438 unset($this->params[$param]);
440 return $this->params;
444 * Remove all url parameters.
446 * @todo remove the unused param.
447 * @param array $params Unused param
448 * @return void
450 public function remove_all_params($params = null) {
451 $this->params = array();
452 $this->slashargument = '';
456 * Add a param to the params for this url.
458 * The added param overrides existing one if they have the same name.
460 * @param string $paramname name
461 * @param string $newvalue Param value. If new value specified current value is overriden or parameter is added
462 * @return mixed string parameter value, null if parameter does not exist
464 public function param($paramname, $newvalue = '') {
465 if (func_num_args() > 1) {
466 // Set new value.
467 $this->params(array($paramname => $newvalue));
469 if (isset($this->params[$paramname])) {
470 return $this->params[$paramname];
471 } else {
472 return null;
477 * Merges parameters and validates them
479 * @param array $overrideparams
480 * @return array merged parameters
481 * @throws coding_exception
483 protected function merge_overrideparams(array $overrideparams = null) {
484 $overrideparams = (array)$overrideparams;
485 $params = $this->params;
486 foreach ($overrideparams as $key => $value) {
487 if (is_int($key)) {
488 throw new coding_exception('Overridden parameters can not have numeric keys!');
490 if (is_array($value)) {
491 throw new coding_exception('Overridden parameters values can not be arrays!');
493 if (is_object($value) and !method_exists($value, '__toString')) {
494 throw new coding_exception('Overridden parameters values can not be objects, unless __toString() is defined!');
496 $params[$key] = (string)$value;
498 return $params;
502 * Get the params as as a query string.
504 * This method should not be used outside of this method.
506 * @param bool $escaped Use &amp; as params separator instead of plain &
507 * @param array $overrideparams params to add to the output params, these
508 * override existing ones with the same name.
509 * @return string query string that can be added to a url.
511 public function get_query_string($escaped = true, array $overrideparams = null) {
512 $arr = array();
513 if ($overrideparams !== null) {
514 $params = $this->merge_overrideparams($overrideparams);
515 } else {
516 $params = $this->params;
518 foreach ($params as $key => $val) {
519 if (is_array($val)) {
520 foreach ($val as $index => $value) {
521 $arr[] = rawurlencode($key.'['.$index.']')."=".rawurlencode($value);
523 } else {
524 if (isset($val) && $val !== '') {
525 $arr[] = rawurlencode($key)."=".rawurlencode($val);
526 } else {
527 $arr[] = rawurlencode($key);
531 if ($escaped) {
532 return implode('&amp;', $arr);
533 } else {
534 return implode('&', $arr);
539 * Get the url params as an array of key => value pairs.
541 * This helps in handling cases where url params contain arrays.
543 * @return array params array for templates.
545 public function export_params_for_template(): array {
546 $data = [];
547 foreach ($this->params as $key => $val) {
548 if (is_array($val)) {
549 foreach ($val as $index => $value) {
550 $data[] = ['name' => $key.'['.$index.']', 'value' => $value];
552 } else {
553 $data[] = ['name' => $key, 'value' => $val];
556 return $data;
560 * Shortcut for printing of encoded URL.
562 * @return string
564 public function __toString() {
565 return $this->out(true);
569 * Output url.
571 * If you use the returned URL in HTML code, you want the escaped ampersands. If you use
572 * the returned URL in HTTP headers, you want $escaped=false.
574 * @param bool $escaped Use &amp; as params separator instead of plain &
575 * @param array $overrideparams params to add to the output url, these override existing ones with the same name.
576 * @return string Resulting URL
578 public function out($escaped = true, array $overrideparams = null) {
580 global $CFG;
582 if (!is_bool($escaped)) {
583 debugging('Escape parameter must be of type boolean, '.gettype($escaped).' given instead.');
586 $url = $this;
588 // Allow url's to be rewritten by a plugin.
589 if (isset($CFG->urlrewriteclass) && !isset($CFG->upgraderunning)) {
590 $class = $CFG->urlrewriteclass;
591 $pluginurl = $class::url_rewrite($url);
592 if ($pluginurl instanceof moodle_url) {
593 $url = $pluginurl;
597 return $url->raw_out($escaped, $overrideparams);
602 * Output url without any rewrites
604 * This is identical in signature and use to out() but doesn't call the rewrite handler.
606 * @param bool $escaped Use &amp; as params separator instead of plain &
607 * @param array $overrideparams params to add to the output url, these override existing ones with the same name.
608 * @return string Resulting URL
610 public function raw_out($escaped = true, array $overrideparams = null) {
611 if (!is_bool($escaped)) {
612 debugging('Escape parameter must be of type boolean, '.gettype($escaped).' given instead.');
615 $uri = $this->out_omit_querystring().$this->slashargument;
617 $querystring = $this->get_query_string($escaped, $overrideparams);
618 if ($querystring !== '') {
619 $uri .= '?' . $querystring;
621 if (!is_null($this->anchor)) {
622 $uri .= '#'.$this->anchor;
625 return $uri;
629 * Returns url without parameters, everything before '?'.
631 * @param bool $includeanchor if {@link self::anchor} is defined, should it be returned?
632 * @return string
634 public function out_omit_querystring($includeanchor = false) {
636 $uri = $this->scheme ? $this->scheme.':'.((strtolower($this->scheme) == 'mailto') ? '':'//'): '';
637 $uri .= $this->user ? $this->user.($this->pass? ':'.$this->pass:'').'@':'';
638 $uri .= $this->host ? $this->host : '';
639 $uri .= $this->port ? ':'.$this->port : '';
640 $uri .= $this->path ? $this->path : '';
641 if ($includeanchor and !is_null($this->anchor)) {
642 $uri .= '#' . $this->anchor;
645 return $uri;
649 * Compares this moodle_url with another.
651 * See documentation of constants for an explanation of the comparison flags.
653 * @param moodle_url $url The moodle_url object to compare
654 * @param int $matchtype The type of comparison (URL_MATCH_BASE, URL_MATCH_PARAMS, URL_MATCH_EXACT)
655 * @return bool
657 public function compare(moodle_url $url, $matchtype = URL_MATCH_EXACT) {
659 $baseself = $this->out_omit_querystring();
660 $baseother = $url->out_omit_querystring();
662 // Append index.php if there is no specific file.
663 if (substr($baseself, -1) == '/') {
664 $baseself .= 'index.php';
666 if (substr($baseother, -1) == '/') {
667 $baseother .= 'index.php';
670 // Compare the two base URLs.
671 if ($baseself != $baseother) {
672 return false;
675 if ($matchtype == URL_MATCH_BASE) {
676 return true;
679 $urlparams = $url->params();
680 foreach ($this->params() as $param => $value) {
681 if ($param == 'sesskey') {
682 continue;
684 if (!array_key_exists($param, $urlparams) || $urlparams[$param] != $value) {
685 return false;
689 if ($matchtype == URL_MATCH_PARAMS) {
690 return true;
693 foreach ($urlparams as $param => $value) {
694 if ($param == 'sesskey') {
695 continue;
697 if (!array_key_exists($param, $this->params()) || $this->param($param) != $value) {
698 return false;
702 if ($url->anchor !== $this->anchor) {
703 return false;
706 return true;
710 * Sets the anchor for the URI (the bit after the hash)
712 * @param string $anchor null means remove previous
714 public function set_anchor($anchor) {
715 if (is_null($anchor)) {
716 // Remove.
717 $this->anchor = null;
718 } else if ($anchor === '') {
719 // Special case, used as empty link.
720 $this->anchor = '';
721 } else if (preg_match('|[a-zA-Z\_\:][a-zA-Z0-9\_\-\.\:]*|', $anchor)) {
722 // Match the anchor against the NMTOKEN spec.
723 $this->anchor = $anchor;
724 } else {
725 // Bad luck, no valid anchor found.
726 $this->anchor = null;
731 * Sets the scheme for the URI (the bit before ://)
733 * @param string $scheme
735 public function set_scheme($scheme) {
736 // See http://www.ietf.org/rfc/rfc3986.txt part 3.1.
737 if (preg_match('/^[a-zA-Z][a-zA-Z0-9+.-]*$/', $scheme)) {
738 $this->scheme = $scheme;
739 } else {
740 throw new coding_exception('Bad URL scheme.');
745 * Sets the url slashargument value.
747 * @param string $path usually file path
748 * @param string $parameter name of page parameter if slasharguments not supported
749 * @param bool $supported usually null, then it depends on $CFG->slasharguments, use true or false for other servers
750 * @return void
752 public function set_slashargument($path, $parameter = 'file', $supported = null) {
753 global $CFG;
754 if (is_null($supported)) {
755 $supported = !empty($CFG->slasharguments);
758 if ($supported) {
759 $parts = explode('/', $path);
760 $parts = array_map('rawurlencode', $parts);
761 $path = implode('/', $parts);
762 $this->slashargument = $path;
763 unset($this->params[$parameter]);
765 } else {
766 $this->slashargument = '';
767 $this->params[$parameter] = $path;
771 // Static factory methods.
774 * General moodle file url.
776 * @param string $urlbase the script serving the file
777 * @param string $path
778 * @param bool $forcedownload
779 * @return moodle_url
781 public static function make_file_url($urlbase, $path, $forcedownload = false) {
782 $params = array();
783 if ($forcedownload) {
784 $params['forcedownload'] = 1;
786 $url = new moodle_url($urlbase, $params);
787 $url->set_slashargument($path);
788 return $url;
792 * Factory method for creation of url pointing to plugin file.
794 * Please note this method can be used only from the plugins to
795 * create urls of own files, it must not be used outside of plugins!
797 * @param int $contextid
798 * @param string $component
799 * @param string $area
800 * @param int $itemid
801 * @param string $pathname
802 * @param string $filename
803 * @param bool $forcedownload
804 * @param mixed $includetoken Whether to use a user token when displaying this group image.
805 * True indicates to generate a token for current user, and integer value indicates to generate a token for the
806 * user whose id is the value indicated.
807 * If the group picture is included in an e-mail or some other location where the audience is a specific
808 * user who will not be logged in when viewing, then we use a token to authenticate the user.
809 * @return moodle_url
811 public static function make_pluginfile_url($contextid, $component, $area, $itemid, $pathname, $filename,
812 $forcedownload = false, $includetoken = false) {
813 global $CFG, $USER;
815 $path = [];
817 if ($includetoken) {
818 $urlbase = "$CFG->wwwroot/tokenpluginfile.php";
819 $userid = $includetoken === true ? $USER->id : $includetoken;
820 $token = get_user_key('core_files', $userid);
821 if ($CFG->slasharguments) {
822 $path[] = $token;
824 } else {
825 $urlbase = "$CFG->wwwroot/pluginfile.php";
827 $path[] = $contextid;
828 $path[] = $component;
829 $path[] = $area;
831 if ($itemid !== null) {
832 $path[] = $itemid;
835 $path = "/" . implode('/', $path) . "{$pathname}{$filename}";
837 $url = self::make_file_url($urlbase, $path, $forcedownload, $includetoken);
838 if ($includetoken && empty($CFG->slasharguments)) {
839 $url->param('token', $token);
841 return $url;
845 * Factory method for creation of url pointing to plugin file.
846 * This method is the same that make_pluginfile_url but pointing to the webservice pluginfile.php script.
847 * It should be used only in external functions.
849 * @since 2.8
850 * @param int $contextid
851 * @param string $component
852 * @param string $area
853 * @param int $itemid
854 * @param string $pathname
855 * @param string $filename
856 * @param bool $forcedownload
857 * @return moodle_url
859 public static function make_webservice_pluginfile_url($contextid, $component, $area, $itemid, $pathname, $filename,
860 $forcedownload = false) {
861 global $CFG;
862 $urlbase = "$CFG->wwwroot/webservice/pluginfile.php";
863 if ($itemid === null) {
864 return self::make_file_url($urlbase, "/$contextid/$component/$area".$pathname.$filename, $forcedownload);
865 } else {
866 return self::make_file_url($urlbase, "/$contextid/$component/$area/$itemid".$pathname.$filename, $forcedownload);
871 * Factory method for creation of url pointing to draft file of current user.
873 * @param int $draftid draft item id
874 * @param string $pathname
875 * @param string $filename
876 * @param bool $forcedownload
877 * @return moodle_url
879 public static function make_draftfile_url($draftid, $pathname, $filename, $forcedownload = false) {
880 global $CFG, $USER;
881 $urlbase = "$CFG->wwwroot/draftfile.php";
882 $context = context_user::instance($USER->id);
884 return self::make_file_url($urlbase, "/$context->id/user/draft/$draftid".$pathname.$filename, $forcedownload);
888 * Factory method for creating of links to legacy course files.
890 * @param int $courseid
891 * @param string $filepath
892 * @param bool $forcedownload
893 * @return moodle_url
895 public static function make_legacyfile_url($courseid, $filepath, $forcedownload = false) {
896 global $CFG;
898 $urlbase = "$CFG->wwwroot/file.php";
899 return self::make_file_url($urlbase, '/'.$courseid.'/'.$filepath, $forcedownload);
903 * Checks if URL is relative to $CFG->wwwroot.
905 * @return bool True if URL is relative to $CFG->wwwroot; otherwise, false.
907 public function is_local_url() : bool {
908 global $CFG;
910 $url = $this->out();
911 // Does URL start with wwwroot? Otherwise, URL isn't relative to wwwroot.
912 return ( ($url === $CFG->wwwroot) || (strpos($url, $CFG->wwwroot.'/') === 0) );
916 * Returns URL as relative path from $CFG->wwwroot
918 * Can be used for passing around urls with the wwwroot stripped
920 * @param boolean $escaped Use &amp; as params separator instead of plain &
921 * @param array $overrideparams params to add to the output url, these override existing ones with the same name.
922 * @return string Resulting URL
923 * @throws coding_exception if called on a non-local url
925 public function out_as_local_url($escaped = true, array $overrideparams = null) {
926 global $CFG;
928 // URL should be relative to wwwroot. If not then throw exception.
929 if ($this->is_local_url()) {
930 $url = $this->out($escaped, $overrideparams);
931 $localurl = substr($url, strlen($CFG->wwwroot));
932 return !empty($localurl) ? $localurl : '';
933 } else {
934 throw new coding_exception('out_as_local_url called on a non-local URL');
939 * Returns the 'path' portion of a URL. For example, if the URL is
940 * http://www.example.org:447/my/file/is/here.txt?really=1 then this will
941 * return '/my/file/is/here.txt'.
943 * By default the path includes slash-arguments (for example,
944 * '/myfile.php/extra/arguments') so it is what you would expect from a
945 * URL path. If you don't want this behaviour, you can opt to exclude the
946 * slash arguments. (Be careful: if the $CFG variable slasharguments is
947 * disabled, these URLs will have a different format and you may need to
948 * look at the 'file' parameter too.)
950 * @param bool $includeslashargument If true, includes slash arguments
951 * @return string Path of URL
953 public function get_path($includeslashargument = true) {
954 return $this->path . ($includeslashargument ? $this->slashargument : '');
958 * Returns a given parameter value from the URL.
960 * @param string $name Name of parameter
961 * @return string Value of parameter or null if not set
963 public function get_param($name) {
964 if (array_key_exists($name, $this->params)) {
965 return $this->params[$name];
966 } else {
967 return null;
972 * Returns the 'scheme' portion of a URL. For example, if the URL is
973 * http://www.example.org:447/my/file/is/here.txt?really=1 then this will
974 * return 'http' (without the colon).
976 * @return string Scheme of the URL.
978 public function get_scheme() {
979 return $this->scheme;
983 * Returns the 'host' portion of a URL. For example, if the URL is
984 * http://www.example.org:447/my/file/is/here.txt?really=1 then this will
985 * return 'www.example.org'.
987 * @return string Host of the URL.
989 public function get_host() {
990 return $this->host;
994 * Returns the 'port' portion of a URL. For example, if the URL is
995 * http://www.example.org:447/my/file/is/here.txt?really=1 then this will
996 * return '447'.
998 * @return string Port of the URL.
1000 public function get_port() {
1001 return $this->port;
1006 * Determine if there is data waiting to be processed from a form
1008 * Used on most forms in Moodle to check for data
1009 * Returns the data as an object, if it's found.
1010 * This object can be used in foreach loops without
1011 * casting because it's cast to (array) automatically
1013 * Checks that submitted POST data exists and returns it as object.
1015 * @return mixed false or object
1017 function data_submitted() {
1019 if (empty($_POST)) {
1020 return false;
1021 } else {
1022 return (object)fix_utf8($_POST);
1027 * Given some normal text this function will break up any
1028 * long words to a given size by inserting the given character
1030 * It's multibyte savvy and doesn't change anything inside html tags.
1032 * @param string $string the string to be modified
1033 * @param int $maxsize maximum length of the string to be returned
1034 * @param string $cutchar the string used to represent word breaks
1035 * @return string
1037 function break_up_long_words($string, $maxsize=20, $cutchar=' ') {
1039 // First of all, save all the tags inside the text to skip them.
1040 $tags = array();
1041 filter_save_tags($string, $tags);
1043 // Process the string adding the cut when necessary.
1044 $output = '';
1045 $length = core_text::strlen($string);
1046 $wordlength = 0;
1048 for ($i=0; $i<$length; $i++) {
1049 $char = core_text::substr($string, $i, 1);
1050 if ($char == ' ' or $char == "\t" or $char == "\n" or $char == "\r" or $char == "<" or $char == ">") {
1051 $wordlength = 0;
1052 } else {
1053 $wordlength++;
1054 if ($wordlength > $maxsize) {
1055 $output .= $cutchar;
1056 $wordlength = 0;
1059 $output .= $char;
1062 // Finally load the tags back again.
1063 if (!empty($tags)) {
1064 $output = str_replace(array_keys($tags), $tags, $output);
1067 return $output;
1071 * Try and close the current window using JavaScript, either immediately, or after a delay.
1073 * Echo's out the resulting XHTML & javascript
1075 * @param integer $delay a delay in seconds before closing the window. Default 0.
1076 * @param boolean $reloadopener if true, we will see if this window was a pop-up, and try
1077 * to reload the parent window before this one closes.
1079 function close_window($delay = 0, $reloadopener = false) {
1080 global $PAGE, $OUTPUT;
1082 if (!$PAGE->headerprinted) {
1083 $PAGE->set_title(get_string('closewindow'));
1084 echo $OUTPUT->header();
1085 } else {
1086 $OUTPUT->container_end_all(false);
1089 if ($reloadopener) {
1090 // Trigger the reload immediately, even if the reload is after a delay.
1091 $PAGE->requires->js_function_call('window.opener.location.reload', array(true));
1093 $OUTPUT->notification(get_string('windowclosing'), 'notifysuccess');
1095 $PAGE->requires->js_function_call('close_window', array(new stdClass()), false, $delay);
1097 echo $OUTPUT->footer();
1098 exit;
1102 * Returns a string containing a link to the user documentation for the current page.
1104 * Also contains an icon by default. Shown to teachers and admin only.
1106 * @param string $text The text to be displayed for the link
1107 * @return string The link to user documentation for this current page
1109 function page_doc_link($text='') {
1110 global $OUTPUT, $PAGE;
1111 $path = page_get_doc_link_path($PAGE);
1112 if (!$path) {
1113 return '';
1115 return $OUTPUT->doc_link($path, $text);
1119 * Returns the path to use when constructing a link to the docs.
1121 * @since Moodle 2.5.1 2.6
1122 * @param moodle_page $page
1123 * @return string
1125 function page_get_doc_link_path(moodle_page $page) {
1126 global $CFG;
1128 if (empty($CFG->docroot) || during_initial_install()) {
1129 return '';
1131 if (!has_capability('moodle/site:doclinks', $page->context)) {
1132 return '';
1135 $path = $page->docspath;
1136 if (!$path) {
1137 return '';
1139 return $path;
1144 * Validates an email to make sure it makes sense.
1146 * @param string $address The email address to validate.
1147 * @return boolean
1149 function validate_email($address) {
1150 global $CFG;
1152 if ($address === null || $address === false || $address === '') {
1153 return false;
1156 require_once("{$CFG->libdir}/phpmailer/moodle_phpmailer.php");
1158 return moodle_phpmailer::validateAddress($address ?? '') && !preg_match('/[<>]/', $address);
1162 * Extracts file argument either from file parameter or PATH_INFO
1164 * Note: $scriptname parameter is not needed anymore
1166 * @return string file path (only safe characters)
1168 function get_file_argument() {
1169 global $SCRIPT;
1171 $relativepath = false;
1172 $hasforcedslashargs = false;
1174 if (isset($_SERVER['REQUEST_URI']) && !empty($_SERVER['REQUEST_URI'])) {
1175 // Checks whether $_SERVER['REQUEST_URI'] contains '/pluginfile.php/'
1176 // instead of '/pluginfile.php?', when serving a file from e.g. mod_imscp or mod_scorm.
1177 if ((strpos($_SERVER['REQUEST_URI'], '/pluginfile.php/') !== false)
1178 && isset($_SERVER['PATH_INFO']) && !empty($_SERVER['PATH_INFO'])) {
1179 // Exclude edge cases like '/pluginfile.php/?file='.
1180 $args = explode('/', ltrim($_SERVER['PATH_INFO'], '/'));
1181 $hasforcedslashargs = (count($args) > 2); // Always at least: context, component and filearea.
1184 if (!$hasforcedslashargs) {
1185 $relativepath = optional_param('file', false, PARAM_PATH);
1188 if ($relativepath !== false and $relativepath !== '') {
1189 return $relativepath;
1191 $relativepath = false;
1193 // Then try extract file from the slasharguments.
1194 if (stripos($_SERVER['SERVER_SOFTWARE'], 'iis') !== false) {
1195 // NOTE: IIS tends to convert all file paths to single byte DOS encoding,
1196 // we can not use other methods because they break unicode chars,
1197 // the only ways are to use URL rewriting
1198 // OR
1199 // to properly set the 'FastCGIUtf8ServerVariables' registry key.
1200 if (isset($_SERVER['PATH_INFO']) and $_SERVER['PATH_INFO'] !== '') {
1201 // Check that PATH_INFO works == must not contain the script name.
1202 if (strpos($_SERVER['PATH_INFO'], $SCRIPT) === false) {
1203 $relativepath = clean_param(urldecode($_SERVER['PATH_INFO']), PARAM_PATH);
1206 } else {
1207 // All other apache-like servers depend on PATH_INFO.
1208 if (isset($_SERVER['PATH_INFO'])) {
1209 if (isset($_SERVER['SCRIPT_NAME']) and strpos($_SERVER['PATH_INFO'], $_SERVER['SCRIPT_NAME']) === 0) {
1210 $relativepath = substr($_SERVER['PATH_INFO'], strlen($_SERVER['SCRIPT_NAME']));
1211 } else {
1212 $relativepath = $_SERVER['PATH_INFO'];
1214 $relativepath = clean_param($relativepath, PARAM_PATH);
1218 return $relativepath;
1222 * Just returns an array of text formats suitable for a popup menu
1224 * @return array
1226 function format_text_menu() {
1227 return array (FORMAT_MOODLE => get_string('formattext'),
1228 FORMAT_HTML => get_string('formathtml'),
1229 FORMAT_PLAIN => get_string('formatplain'),
1230 FORMAT_MARKDOWN => get_string('formatmarkdown'));
1234 * Given text in a variety of format codings, this function returns the text as safe HTML.
1236 * This function should mainly be used for long strings like posts,
1237 * answers, glossary items etc. For short strings {@link format_string()}.
1239 * <pre>
1240 * Options:
1241 * trusted : If true the string won't be cleaned. Default false required noclean=true.
1242 * noclean : If true the string won't be cleaned, unless $CFG->forceclean is set. Default false required trusted=true.
1243 * nocache : If true the strign will not be cached and will be formatted every call. Default false.
1244 * filter : If true the string will be run through applicable filters as well. Default true.
1245 * para : If true then the returned string will be wrapped in div tags. Default true.
1246 * newlines : If true then lines newline breaks will be converted to HTML newline breaks. Default true.
1247 * context : The context that will be used for filtering.
1248 * overflowdiv : If set to true the formatted text will be encased in a div
1249 * with the class no-overflow before being returned. Default false.
1250 * allowid : If true then id attributes will not be removed, even when
1251 * using htmlpurifier. Default false.
1252 * blanktarget : If true all <a> tags will have target="_blank" added unless target is explicitly specified.
1253 * </pre>
1255 * @staticvar array $croncache
1256 * @param string $text The text to be formatted. This is raw text originally from user input.
1257 * @param int $format Identifier of the text format to be used
1258 * [FORMAT_MOODLE, FORMAT_HTML, FORMAT_PLAIN, FORMAT_MARKDOWN]
1259 * @param stdClass|array $options text formatting options
1260 * @param int $courseiddonotuse deprecated course id, use context option instead
1261 * @return string
1263 function format_text($text, $format = FORMAT_MOODLE, $options = null, $courseiddonotuse = null) {
1264 global $CFG, $DB, $PAGE;
1266 if ($text === '' || is_null($text)) {
1267 // No need to do any filters and cleaning.
1268 return '';
1271 if ($options instanceof \core\context) {
1272 // A common mistake has been to call this function with a context object.
1273 // This has never been expected, nor supported.
1274 debugging(
1275 'The options argument should not be a context object directly. ' .
1276 ' Please pass an array with a context key instead.',
1277 DEBUG_DEVELOPER,
1279 $options = ['context' => $options];
1282 // Detach object, we can not modify it.
1283 $options = (array)$options;
1285 if (!isset($options['trusted'])) {
1286 $options['trusted'] = false;
1288 if ($format == FORMAT_MARKDOWN) {
1289 // Markdown format cannot be trusted in trusttext areas,
1290 // because we do not know how to sanitise it before editing.
1291 $options['trusted'] = false;
1293 if (!isset($options['noclean'])) {
1294 if ($options['trusted'] and trusttext_active()) {
1295 // No cleaning if text trusted and noclean not specified.
1296 $options['noclean'] = true;
1297 } else {
1298 $options['noclean'] = false;
1301 if (!empty($CFG->forceclean)) {
1302 // Whatever the caller claims, the admin wants all content cleaned anyway.
1303 $options['noclean'] = false;
1305 if (!isset($options['nocache'])) {
1306 $options['nocache'] = false;
1308 if (!isset($options['filter'])) {
1309 $options['filter'] = true;
1311 if (!isset($options['para'])) {
1312 $options['para'] = true;
1314 if (!isset($options['newlines'])) {
1315 $options['newlines'] = true;
1317 if (!isset($options['overflowdiv'])) {
1318 $options['overflowdiv'] = false;
1320 $options['blanktarget'] = !empty($options['blanktarget']);
1322 // Calculate best context.
1323 if (empty($CFG->version) or $CFG->version < 2013051400 or during_initial_install()) {
1324 // Do not filter anything during installation or before upgrade completes.
1325 $context = null;
1327 } else if (isset($options['context'])) { // First by explicit passed context option.
1328 if (is_object($options['context'])) {
1329 $context = $options['context'];
1330 } else {
1331 $context = context::instance_by_id($options['context']);
1333 } else if ($courseiddonotuse) {
1334 // Legacy courseid.
1335 $context = context_course::instance($courseiddonotuse);
1336 } else {
1337 // Fallback to $PAGE->context this may be problematic in CLI and other non-standard pages :-(.
1338 $context = $PAGE->context;
1341 if (!$context) {
1342 // Either install/upgrade or something has gone really wrong because context does not exist (yet?).
1343 $options['nocache'] = true;
1344 $options['filter'] = false;
1347 if ($options['filter']) {
1348 $filtermanager = filter_manager::instance();
1349 $filtermanager->setup_page_for_filters($PAGE, $context); // Setup global stuff filters may have.
1350 $filteroptions = array(
1351 'originalformat' => $format,
1352 'noclean' => $options['noclean'],
1354 } else {
1355 $filtermanager = new null_filter_manager();
1356 $filteroptions = array();
1359 switch ($format) {
1360 case FORMAT_HTML:
1361 $filteroptions['stage'] = 'pre_format';
1362 $text = $filtermanager->filter_text($text, $context, $filteroptions);
1363 // Text is already in HTML format, so just continue to the next filtering stage.
1364 $filteroptions['stage'] = 'pre_clean';
1365 $text = $filtermanager->filter_text($text, $context, $filteroptions);
1366 if (!$options['noclean']) {
1367 $text = clean_text($text, FORMAT_HTML, $options);
1369 $filteroptions['stage'] = 'post_clean';
1370 $text = $filtermanager->filter_text($text, $context, $filteroptions);
1371 break;
1373 case FORMAT_PLAIN:
1374 $text = s($text); // Cleans dangerous JS.
1375 $text = rebuildnolinktag($text);
1376 $text = str_replace(' ', '&nbsp; ', $text);
1377 $text = nl2br($text);
1378 break;
1380 case FORMAT_WIKI:
1381 // This format is deprecated.
1382 $text = '<p>NOTICE: Wiki-like formatting has been removed from Moodle. You should not be seeing
1383 this message as all texts should have been converted to Markdown format instead.
1384 Please post a bug report to http://moodle.org/bugs with information about where you
1385 saw this message.</p>'.s($text);
1386 break;
1388 case FORMAT_MARKDOWN:
1389 $filteroptions['stage'] = 'pre_format';
1390 $text = $filtermanager->filter_text($text, $context, $filteroptions);
1391 $text = markdown_to_html($text);
1392 $filteroptions['stage'] = 'pre_clean';
1393 $text = $filtermanager->filter_text($text, $context, $filteroptions);
1394 if (!$options['noclean']) {
1395 $text = clean_text($text, FORMAT_HTML, $options);
1397 $filteroptions['stage'] = 'post_clean';
1398 $text = $filtermanager->filter_text($text, $context, $filteroptions);
1399 break;
1401 default: // FORMAT_MOODLE or anything else.
1402 $filteroptions['stage'] = 'pre_format';
1403 $text = $filtermanager->filter_text($text, $context, $filteroptions);
1404 $text = text_to_html($text, null, $options['para'], $options['newlines']);
1405 $filteroptions['stage'] = 'pre_clean';
1406 $text = $filtermanager->filter_text($text, $context, $filteroptions);
1407 if (!$options['noclean']) {
1408 $text = clean_text($text, FORMAT_HTML, $options);
1410 $filteroptions['stage'] = 'post_clean';
1411 $text = $filtermanager->filter_text($text, $context, $filteroptions);
1412 break;
1414 if ($options['filter']) {
1415 // At this point there should not be any draftfile links any more,
1416 // this happens when developers forget to post process the text.
1417 // The only potential problem is that somebody might try to format
1418 // the text before storing into database which would be itself big bug..
1419 $text = str_replace("\"$CFG->wwwroot/draftfile.php", "\"$CFG->wwwroot/brokenfile.php#", $text);
1421 if ($CFG->debugdeveloper) {
1422 if (strpos($text, '@@PLUGINFILE@@/') !== false) {
1423 debugging('Before calling format_text(), the content must be processed with file_rewrite_pluginfile_urls()',
1424 DEBUG_DEVELOPER);
1429 if (!empty($options['overflowdiv'])) {
1430 $text = html_writer::tag('div', $text, array('class' => 'no-overflow'));
1433 if ($options['blanktarget']) {
1434 $domdoc = new DOMDocument();
1435 libxml_use_internal_errors(true);
1436 $domdoc->loadHTML('<?xml version="1.0" encoding="UTF-8" ?>' . $text);
1437 libxml_clear_errors();
1438 foreach ($domdoc->getElementsByTagName('a') as $link) {
1439 if ($link->hasAttribute('target') && strpos($link->getAttribute('target'), '_blank') === false) {
1440 continue;
1442 $link->setAttribute('target', '_blank');
1443 if (strpos($link->getAttribute('rel'), 'noreferrer') === false) {
1444 $link->setAttribute('rel', trim($link->getAttribute('rel') . ' noreferrer'));
1448 // This regex is nasty and I don't like it. The correct way to solve this is by loading the HTML like so:
1449 // $domdoc->loadHTML($text, LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD); however it seems like some libxml
1450 // versions don't work properly and end up leaving <html><body>, so I'm forced to use
1451 // this regex to remove those tags as a preventive measure.
1452 $text = trim(preg_replace('~<(?:!DOCTYPE|/?(?:html|body))[^>]*>\s*~i', '', $domdoc->saveHTML($domdoc->documentElement)));
1455 return $text;
1459 * Resets some data related to filters, called during upgrade or when general filter settings change.
1461 * @param bool $phpunitreset true means called from our PHPUnit integration test reset
1462 * @return void
1464 function reset_text_filters_cache($phpunitreset = false) {
1465 global $CFG, $DB;
1467 if ($phpunitreset) {
1468 // HTMLPurifier does not change, DB is already reset to defaults,
1469 // nothing to do here, the dataroot was cleared too.
1470 return;
1473 // The purge_all_caches() deals with cachedir and localcachedir purging,
1474 // the individual filter caches are invalidated as necessary elsewhere.
1476 // Update $CFG->filterall cache flag.
1477 if (empty($CFG->stringfilters)) {
1478 set_config('filterall', 0);
1479 return;
1481 $installedfilters = core_component::get_plugin_list('filter');
1482 $filters = explode(',', $CFG->stringfilters);
1483 foreach ($filters as $filter) {
1484 if (isset($installedfilters[$filter])) {
1485 set_config('filterall', 1);
1486 return;
1489 set_config('filterall', 0);
1493 * Given a simple string, this function returns the string
1494 * processed by enabled string filters if $CFG->filterall is enabled
1496 * This function should be used to print short strings (non html) that
1497 * need filter processing e.g. activity titles, post subjects,
1498 * glossary concepts.
1500 * @staticvar bool $strcache
1501 * @param string $string The string to be filtered. Should be plain text, expect
1502 * possibly for multilang tags.
1503 * @param boolean $striplinks To strip any link in the result text. Moodle 1.8 default changed from false to true! MDL-8713
1504 * @param array $options options array/object or courseid
1505 * @return string
1507 function format_string($string, $striplinks = true, $options = null) {
1508 global $CFG, $PAGE;
1510 if ($string === '' || is_null($string)) {
1511 // No need to do any filters and cleaning.
1512 return '';
1515 // We'll use a in-memory cache here to speed up repeated strings.
1516 static $strcache = false;
1518 if (empty($CFG->version) or $CFG->version < 2013051400 or during_initial_install()) {
1519 // Do not filter anything during installation or before upgrade completes.
1520 return $string = strip_tags($string);
1523 if ($strcache === false or count($strcache) > 2000) {
1524 // This number might need some tuning to limit memory usage in cron.
1525 $strcache = array();
1528 // This method only expects either:
1529 // - an array of options;
1530 // - a stdClass of options to be cast to an array; or
1531 // - an integer courseid.
1532 if ($options === null) {
1533 $options = [];
1534 } else if (is_numeric($options)) {
1535 // Legacy courseid usage.
1536 $options = ['context' => \core\context\course::instance($options)];
1537 } else if ($options instanceof \core\context) {
1538 // A common mistake has been to call this function with a context object.
1539 // This has never been expected, or nor supported.
1540 debugging(
1541 'The options argument should not be a context object directly. ' .
1542 ' Please pass an array with a context key instead.',
1543 DEBUG_DEVELOPER,
1545 $options = ['context' => $options];
1546 } else if (is_array($options) || is_a($options, \stdClass::class)) {
1547 // Re-cast to array to prevent modifications to the original object.
1548 $options = (array) $options;
1549 } else {
1550 // Something else was passed, so we'll just use an empty array.
1551 // Attempt to cast to array since we always used to, but throw in some debugging.
1552 debugging(sprintf(
1553 'The options argument should be an Array, or stdclass. %s passed.',
1554 gettype($options),
1555 ), DEBUG_DEVELOPER);
1556 $options = (array) $options;
1559 if (empty($options['context'])) {
1560 // Fallback to $PAGE->context this may be problematic in CLI and other non-standard pages :-(.
1561 $options['context'] = $PAGE->context;
1562 } else if (is_numeric($options['context'])) {
1563 $options['context'] = context::instance_by_id($options['context']);
1565 if (!isset($options['filter'])) {
1566 $options['filter'] = true;
1569 $options['escape'] = !isset($options['escape']) || $options['escape'];
1571 if (!$options['context']) {
1572 // We did not find any context? weird.
1573 return $string = strip_tags($string);
1576 // Calculate md5.
1577 $cachekeys = array($string, $striplinks, $options['context']->id,
1578 $options['escape'], current_language(), $options['filter']);
1579 $md5 = md5(implode('<+>', $cachekeys));
1581 // Fetch from cache if possible.
1582 if (isset($strcache[$md5])) {
1583 return $strcache[$md5];
1586 // First replace all ampersands not followed by html entity code
1587 // Regular expression moved to its own method for easier unit testing.
1588 $string = $options['escape'] ? replace_ampersands_not_followed_by_entity($string) : $string;
1590 if (!empty($CFG->filterall) && $options['filter']) {
1591 $filtermanager = filter_manager::instance();
1592 $filtermanager->setup_page_for_filters($PAGE, $options['context']); // Setup global stuff filters may have.
1593 $string = $filtermanager->filter_string($string, $options['context']);
1596 // If the site requires it, strip ALL tags from this string.
1597 if (!empty($CFG->formatstringstriptags)) {
1598 if ($options['escape']) {
1599 $string = str_replace(array('<', '>'), array('&lt;', '&gt;'), strip_tags($string));
1600 } else {
1601 $string = strip_tags($string);
1603 } else {
1604 // Otherwise strip just links if that is required (default).
1605 if ($striplinks) {
1606 // Strip links in string.
1607 $string = strip_links($string);
1609 $string = clean_text($string);
1612 // Store to cache.
1613 $strcache[$md5] = $string;
1615 return $string;
1619 * Given a string, performs a negative lookahead looking for any ampersand character
1620 * that is not followed by a proper HTML entity. If any is found, it is replaced
1621 * by &amp;. The string is then returned.
1623 * @param string $string
1624 * @return string
1626 function replace_ampersands_not_followed_by_entity($string) {
1627 return preg_replace("/\&(?![a-zA-Z0-9#]{1,8};)/", "&amp;", $string ?? '');
1631 * Given a string, replaces all <a>.*</a> by .* and returns the string.
1633 * @param string $string
1634 * @return string
1636 function strip_links($string) {
1637 return preg_replace('/(<a\s[^>]+?>)(.+?)(<\/a>)/is', '$2', $string);
1641 * This expression turns links into something nice in a text format. (Russell Jungwirth)
1643 * @param string $string
1644 * @return string
1646 function wikify_links($string) {
1647 return preg_replace('~(<a [^<]*href=["|\']?([^ "\']*)["|\']?[^>]*>([^<]*)</a>)~i', '$3 [ $2 ]', $string);
1651 * Given text in a variety of format codings, this function returns the text as plain text suitable for plain email.
1653 * @param string $text The text to be formatted. This is raw text originally from user input.
1654 * @param int $format Identifier of the text format to be used
1655 * [FORMAT_MOODLE, FORMAT_HTML, FORMAT_PLAIN, FORMAT_WIKI, FORMAT_MARKDOWN]
1656 * @return string
1658 function format_text_email($text, $format) {
1660 switch ($format) {
1662 case FORMAT_PLAIN:
1663 return $text;
1664 break;
1666 case FORMAT_WIKI:
1667 // There should not be any of these any more!
1668 $text = wikify_links($text);
1669 return core_text::entities_to_utf8(strip_tags($text), true);
1670 break;
1672 case FORMAT_HTML:
1673 return html_to_text($text);
1674 break;
1676 case FORMAT_MOODLE:
1677 case FORMAT_MARKDOWN:
1678 default:
1679 $text = wikify_links($text);
1680 return core_text::entities_to_utf8(strip_tags($text), true);
1681 break;
1686 * Formats activity intro text
1688 * @param string $module name of module
1689 * @param object $activity instance of activity
1690 * @param int $cmid course module id
1691 * @param bool $filter filter resulting html text
1692 * @return string
1694 function format_module_intro($module, $activity, $cmid, $filter=true) {
1695 global $CFG;
1696 require_once("$CFG->libdir/filelib.php");
1697 $context = context_module::instance($cmid);
1698 $options = array('noclean' => true, 'para' => false, 'filter' => $filter, 'context' => $context, 'overflowdiv' => true);
1699 $intro = file_rewrite_pluginfile_urls($activity->intro, 'pluginfile.php', $context->id, 'mod_'.$module, 'intro', null);
1700 return trim(format_text($intro, $activity->introformat, $options, null));
1704 * Removes the usage of Moodle files from a text.
1706 * In some rare cases we need to re-use a text that already has embedded links
1707 * to some files hosted within Moodle. But the new area in which we will push
1708 * this content does not support files... therefore we need to remove those files.
1710 * @param string $source The text
1711 * @return string The stripped text
1713 function strip_pluginfile_content($source) {
1714 $baseurl = '@@PLUGINFILE@@';
1715 // Looking for something like < .* "@@pluginfile@@.*" .* >
1716 $pattern = '$<[^<>]+["\']' . $baseurl . '[^"\']*["\'][^<>]*>$';
1717 $stripped = preg_replace($pattern, '', $source);
1718 // Use purify html to rebalence potentially mismatched tags and generally cleanup.
1719 return purify_html($stripped);
1723 * Legacy function, used for cleaning of old forum and glossary text only.
1725 * @param string $text text that may contain legacy TRUSTTEXT marker
1726 * @return string text without legacy TRUSTTEXT marker
1728 function trusttext_strip($text) {
1729 if (!is_string($text)) {
1730 // This avoids the potential for an endless loop below.
1731 throw new coding_exception('trusttext_strip parameter must be a string');
1733 while (true) { // Removing nested TRUSTTEXT.
1734 $orig = $text;
1735 $text = str_replace('#####TRUSTTEXT#####', '', $text);
1736 if (strcmp($orig, $text) === 0) {
1737 return $text;
1743 * Must be called before editing of all texts with trust flag. Removes all XSS nasties from texts stored in database if needed.
1745 * @param stdClass $object data object with xxx, xxxformat and xxxtrust fields
1746 * @param string $field name of text field
1747 * @param context $context active context
1748 * @return stdClass updated $object
1750 function trusttext_pre_edit($object, $field, $context) {
1751 $trustfield = $field.'trust';
1752 $formatfield = $field.'format';
1754 if ($object->$formatfield == FORMAT_MARKDOWN) {
1755 // We do not have a way to sanitise Markdown texts,
1756 // luckily editors for this format should not have XSS problems.
1757 return $object;
1760 if (!$object->$trustfield or !trusttext_trusted($context)) {
1761 $object->$field = clean_text($object->$field, $object->$formatfield);
1764 return $object;
1768 * Is current user trusted to enter no dangerous XSS in this context?
1770 * Please note the user must be in fact trusted everywhere on this server!!
1772 * @param context $context
1773 * @return bool true if user trusted
1775 function trusttext_trusted($context) {
1776 return (trusttext_active() and has_capability('moodle/site:trustcontent', $context));
1780 * Is trusttext feature active?
1782 * @return bool
1784 function trusttext_active() {
1785 global $CFG;
1787 return !empty($CFG->enabletrusttext);
1791 * Cleans raw text removing nasties.
1793 * Given raw text (eg typed in by a user) this function cleans it up and removes any nasty tags that could mess up
1794 * Moodle pages through XSS attacks.
1796 * The result must be used as a HTML text fragment, this function can not cleanup random
1797 * parts of html tags such as url or src attributes.
1799 * NOTE: the format parameter was deprecated because we can safely clean only HTML.
1801 * @param string $text The text to be cleaned
1802 * @param int|string $format deprecated parameter, should always contain FORMAT_HTML or FORMAT_MOODLE
1803 * @param array $options Array of options; currently only option supported is 'allowid' (if true,
1804 * does not remove id attributes when cleaning)
1805 * @return string The cleaned up text
1807 function clean_text($text, $format = FORMAT_HTML, $options = array()) {
1808 $text = (string)$text;
1810 if ($format != FORMAT_HTML and $format != FORMAT_HTML) {
1811 // TODO: we need to standardise cleanup of text when loading it into editor first.
1812 // debugging('clean_text() is designed to work only with html');.
1815 if ($format == FORMAT_PLAIN) {
1816 return $text;
1819 if (is_purify_html_necessary($text)) {
1820 $text = purify_html($text, $options);
1823 // Originally we tried to neutralise some script events here, it was a wrong approach because
1824 // it was trivial to work around that (for example using style based XSS exploits).
1825 // We must not give false sense of security here - all developers MUST understand how to use
1826 // rawurlencode(), htmlentities(), htmlspecialchars(), p(), s(), moodle_url, html_writer and friends!!!
1828 return $text;
1832 * Is it necessary to use HTMLPurifier?
1834 * @private
1835 * @param string $text
1836 * @return bool false means html is safe and valid, true means use HTMLPurifier
1838 function is_purify_html_necessary($text) {
1839 if ($text === '') {
1840 return false;
1843 if ($text === (string)((int)$text)) {
1844 return false;
1847 if (strpos($text, '&') !== false or preg_match('|<[^pesb/]|', $text)) {
1848 // We need to normalise entities or other tags except p, em, strong and br present.
1849 return true;
1852 $altered = htmlspecialchars($text, ENT_NOQUOTES, 'UTF-8', true);
1853 if ($altered === $text) {
1854 // No < > or other special chars means this must be safe.
1855 return false;
1858 // Let's try to convert back some safe html tags.
1859 $altered = preg_replace('|&lt;p&gt;(.*?)&lt;/p&gt;|m', '<p>$1</p>', $altered);
1860 if ($altered === $text) {
1861 return false;
1863 $altered = preg_replace('|&lt;em&gt;([^<>]+?)&lt;/em&gt;|m', '<em>$1</em>', $altered);
1864 if ($altered === $text) {
1865 return false;
1867 $altered = preg_replace('|&lt;strong&gt;([^<>]+?)&lt;/strong&gt;|m', '<strong>$1</strong>', $altered);
1868 if ($altered === $text) {
1869 return false;
1871 $altered = str_replace('&lt;br /&gt;', '<br />', $altered);
1872 if ($altered === $text) {
1873 return false;
1876 return true;
1880 * KSES replacement cleaning function - uses HTML Purifier.
1882 * @param string $text The (X)HTML string to purify
1883 * @param array $options Array of options; currently only option supported is 'allowid' (if set,
1884 * does not remove id attributes when cleaning)
1885 * @return string
1887 function purify_html($text, $options = array()) {
1888 global $CFG;
1890 $text = (string)$text;
1892 static $purifiers = array();
1893 static $caches = array();
1895 // Purifier code can change only during major version upgrade.
1896 $version = empty($CFG->version) ? 0 : $CFG->version;
1897 $cachedir = "$CFG->localcachedir/htmlpurifier/$version";
1898 if (!file_exists($cachedir)) {
1899 // Purging of caches may remove the cache dir at any time,
1900 // luckily file_exists() results should be cached for all existing directories.
1901 $purifiers = array();
1902 $caches = array();
1903 gc_collect_cycles();
1905 make_localcache_directory('htmlpurifier', false);
1906 check_dir_exists($cachedir);
1909 $allowid = empty($options['allowid']) ? 0 : 1;
1910 $allowobjectembed = empty($CFG->allowobjectembed) ? 0 : 1;
1912 $type = 'type_'.$allowid.'_'.$allowobjectembed;
1914 if (!array_key_exists($type, $caches)) {
1915 $caches[$type] = cache::make('core', 'htmlpurifier', array('type' => $type));
1917 $cache = $caches[$type];
1919 // Add revision number and all options to the text key so that it is compatible with local cluster node caches.
1920 $key = "|$version|$allowobjectembed|$allowid|$text";
1921 $filteredtext = $cache->get($key);
1923 if ($filteredtext === true) {
1924 // The filtering did not change the text last time, no need to filter anything again.
1925 return $text;
1926 } else if ($filteredtext !== false) {
1927 return $filteredtext;
1930 if (empty($purifiers[$type])) {
1931 require_once $CFG->libdir.'/htmlpurifier/HTMLPurifier.safe-includes.php';
1932 require_once $CFG->libdir.'/htmlpurifier/locallib.php';
1933 $config = HTMLPurifier_Config::createDefault();
1935 $config->set('HTML.DefinitionID', 'moodlehtml');
1936 $config->set('HTML.DefinitionRev', 7);
1937 $config->set('Cache.SerializerPath', $cachedir);
1938 $config->set('Cache.SerializerPermissions', $CFG->directorypermissions);
1939 $config->set('Core.NormalizeNewlines', false);
1940 $config->set('Core.ConvertDocumentToFragment', true);
1941 $config->set('Core.Encoding', 'UTF-8');
1942 $config->set('HTML.Doctype', 'XHTML 1.0 Transitional');
1943 $config->set('URI.AllowedSchemes', array(
1944 'http' => true,
1945 'https' => true,
1946 'ftp' => true,
1947 'irc' => true,
1948 'nntp' => true,
1949 'news' => true,
1950 'rtsp' => true,
1951 'rtmp' => true,
1952 'teamspeak' => true,
1953 'gopher' => true,
1954 'mms' => true,
1955 'mailto' => true
1957 $config->set('Attr.AllowedFrameTargets', array('_blank'));
1959 if ($allowobjectembed) {
1960 $config->set('HTML.SafeObject', true);
1961 $config->set('Output.FlashCompat', true);
1962 $config->set('HTML.SafeEmbed', true);
1965 if ($allowid) {
1966 $config->set('Attr.EnableID', true);
1969 if ($def = $config->maybeGetRawHTMLDefinition()) {
1970 $def->addElement('nolink', 'Inline', 'Flow', array()); // Skip our filters inside.
1971 $def->addElement('tex', 'Inline', 'Inline', array()); // Tex syntax, equivalent to $$xx$$.
1972 $def->addElement('algebra', 'Inline', 'Inline', array()); // Algebra syntax, equivalent to @@xx@@.
1973 $def->addElement('lang', 'Block', 'Flow', array(), array('lang'=>'CDATA')); // Original multilang style - only our hacked lang attribute.
1974 $def->addAttribute('span', 'xxxlang', 'CDATA'); // Current very problematic multilang.
1975 // Enable the bidirectional isolate element and its span equivalent.
1976 $def->addElement('bdi', 'Inline', 'Flow', 'Common');
1977 $def->addAttribute('span', 'dir', 'Enum#ltr,rtl,auto');
1979 // Media elements.
1980 // https://html.spec.whatwg.org/#the-video-element
1981 $def->addElement('video', 'Inline', 'Optional: #PCDATA | Flow | source | track', 'Common', [
1982 'src' => 'URI',
1983 'crossorigin' => 'Enum#anonymous,use-credentials',
1984 'poster' => 'URI',
1985 'preload' => 'Enum#auto,metadata,none',
1986 'autoplay' => 'Bool',
1987 'playsinline' => 'Bool',
1988 'loop' => 'Bool',
1989 'muted' => 'Bool',
1990 'controls' => 'Bool',
1991 'width' => 'Length',
1992 'height' => 'Length',
1994 // https://html.spec.whatwg.org/#the-audio-element
1995 $def->addElement('audio', 'Inline', 'Optional: #PCDATA | Flow | source | track', 'Common', [
1996 'src' => 'URI',
1997 'crossorigin' => 'Enum#anonymous,use-credentials',
1998 'preload' => 'Enum#auto,metadata,none',
1999 'autoplay' => 'Bool',
2000 'loop' => 'Bool',
2001 'muted' => 'Bool',
2002 'controls' => 'Bool'
2004 // https://html.spec.whatwg.org/#the-source-element
2005 $def->addElement('source', false, 'Empty', null, [
2006 'src' => 'URI',
2007 'type' => 'Text'
2009 // https://html.spec.whatwg.org/#the-track-element
2010 $def->addElement('track', false, 'Empty', null, [
2011 'src' => 'URI',
2012 'kind' => 'Enum#subtitles,captions,descriptions,chapters,metadata',
2013 'srclang' => 'Text',
2014 'label' => 'Text',
2015 'default' => 'Bool',
2018 // Use the built-in Ruby module to add annotation support.
2019 $def->manager->addModule(new HTMLPurifier_HTMLModule_Ruby());
2022 $purifier = new HTMLPurifier($config);
2023 $purifiers[$type] = $purifier;
2024 } else {
2025 $purifier = $purifiers[$type];
2028 $multilang = (strpos($text, 'class="multilang"') !== false);
2030 $filteredtext = $text;
2031 if ($multilang) {
2032 $filteredtextregex = '/<span(\s+lang="([a-zA-Z0-9_-]+)"|\s+class="multilang"){2}\s*>/';
2033 $filteredtext = preg_replace($filteredtextregex, '<span xxxlang="${2}">', $filteredtext);
2035 $filteredtext = (string)$purifier->purify($filteredtext);
2036 if ($multilang) {
2037 $filteredtext = preg_replace('/<span xxxlang="([a-zA-Z0-9_-]+)">/', '<span lang="${1}" class="multilang">', $filteredtext);
2040 if ($text === $filteredtext) {
2041 // No need to store the filtered text, next time we will just return unfiltered text
2042 // because it was not changed by purifying.
2043 $cache->set($key, true);
2044 } else {
2045 $cache->set($key, $filteredtext);
2048 return $filteredtext;
2052 * Given plain text, makes it into HTML as nicely as possible.
2054 * May contain HTML tags already.
2056 * Do not abuse this function. It is intended as lower level formatting feature used
2057 * by {@link format_text()} to convert FORMAT_MOODLE to HTML. You are supposed
2058 * to call format_text() in most of cases.
2060 * @param string $text The string to convert.
2061 * @param boolean $smileyignored Was used to determine if smiley characters should convert to smiley images, ignored now
2062 * @param boolean $para If true then the returned string will be wrapped in div tags
2063 * @param boolean $newlines If true then lines newline breaks will be converted to HTML newline breaks.
2064 * @return string
2066 function text_to_html($text, $smileyignored = null, $para = true, $newlines = true) {
2067 // Remove any whitespace that may be between HTML tags.
2068 $text = preg_replace("~>([[:space:]]+)<~i", "><", $text);
2070 // Remove any returns that precede or follow HTML tags.
2071 $text = preg_replace("~([\n\r])<~i", " <", $text);
2072 $text = preg_replace("~>([\n\r])~i", "> ", $text);
2074 // Make returns into HTML newlines.
2075 if ($newlines) {
2076 $text = nl2br($text);
2079 // Wrap the whole thing in a div if required.
2080 if ($para) {
2081 // In 1.9 this was changed from a p => div.
2082 return '<div class="text_to_html">'.$text.'</div>';
2083 } else {
2084 return $text;
2089 * Given Markdown formatted text, make it into XHTML using external function
2091 * @param string $text The markdown formatted text to be converted.
2092 * @return string Converted text
2094 function markdown_to_html($text) {
2095 global $CFG;
2097 if ($text === '' or $text === null) {
2098 return $text;
2101 require_once($CFG->libdir .'/markdown/MarkdownInterface.php');
2102 require_once($CFG->libdir .'/markdown/Markdown.php');
2103 require_once($CFG->libdir .'/markdown/MarkdownExtra.php');
2105 return \Michelf\MarkdownExtra::defaultTransform($text);
2109 * Given HTML text, make it into plain text using external function
2111 * @param string $html The text to be converted.
2112 * @param integer $width Width to wrap the text at. (optional, default 75 which
2113 * is a good value for email. 0 means do not limit line length.)
2114 * @param boolean $dolinks By default, any links in the HTML are collected, and
2115 * printed as a list at the end of the HTML. If you don't want that, set this
2116 * argument to false.
2117 * @return string plain text equivalent of the HTML.
2119 function html_to_text($html, $width = 75, $dolinks = true) {
2120 global $CFG;
2122 require_once($CFG->libdir .'/html2text/lib.php');
2124 $options = array(
2125 'width' => $width,
2126 'do_links' => 'table',
2129 if (empty($dolinks)) {
2130 $options['do_links'] = 'none';
2132 $h2t = new core_html2text($html, $options);
2133 $result = $h2t->getText();
2135 return $result;
2139 * Converts texts or strings to plain text.
2141 * - When used to convert user input introduced in an editor the text format needs to be passed in $contentformat like we usually
2142 * do in format_text.
2143 * - When this function is used for strings that are usually passed through format_string before displaying them
2144 * we need to set $contentformat to false. This will execute html_to_text as these strings can contain multilang tags if
2145 * multilang filter is applied to headings.
2147 * @param string $content The text as entered by the user
2148 * @param int|false $contentformat False for strings or the text format: FORMAT_MOODLE/FORMAT_HTML/FORMAT_PLAIN/FORMAT_MARKDOWN
2149 * @return string Plain text.
2151 function content_to_text($content, $contentformat) {
2153 switch ($contentformat) {
2154 case FORMAT_PLAIN:
2155 // Nothing here.
2156 break;
2157 case FORMAT_MARKDOWN:
2158 $content = markdown_to_html($content);
2159 $content = html_to_text($content, 75, false);
2160 break;
2161 default:
2162 // FORMAT_HTML, FORMAT_MOODLE and $contentformat = false, the later one are strings usually formatted through
2163 // format_string, we need to convert them from html because they can contain HTML (multilang filter).
2164 $content = html_to_text($content, 75, false);
2167 return trim($content, "\r\n ");
2171 * Factory method for extracting draft file links from arbitrary text using regular expressions. Only text
2172 * is required; other file fields may be passed to filter.
2174 * @param string $text Some html content.
2175 * @param bool $forcehttps force https urls.
2176 * @param int $contextid This parameter and the next three identify the file area to save to.
2177 * @param string $component The component name.
2178 * @param string $filearea The filearea.
2179 * @param int $itemid The item id for the filearea.
2180 * @param string $filename The specific filename of the file.
2181 * @return array
2183 function extract_draft_file_urls_from_text($text, $forcehttps = false, $contextid = null, $component = null,
2184 $filearea = null, $itemid = null, $filename = null) {
2185 global $CFG;
2187 $wwwroot = $CFG->wwwroot;
2188 if ($forcehttps) {
2189 $wwwroot = str_replace('http://', 'https://', $wwwroot);
2191 $urlstring = '/' . preg_quote($wwwroot, '/');
2193 $urlbase = preg_quote('draftfile.php');
2194 $urlstring .= "\/(?<urlbase>{$urlbase})";
2196 if (is_null($contextid)) {
2197 $contextid = '[0-9]+';
2199 $urlstring .= "\/(?<contextid>{$contextid})";
2201 if (is_null($component)) {
2202 $component = '[a-z_]+';
2204 $urlstring .= "\/(?<component>{$component})";
2206 if (is_null($filearea)) {
2207 $filearea = '[a-z_]+';
2209 $urlstring .= "\/(?<filearea>{$filearea})";
2211 if (is_null($itemid)) {
2212 $itemid = '[0-9]+';
2214 $urlstring .= "\/(?<itemid>{$itemid})";
2216 // Filename matching magic based on file_rewrite_urls_to_pluginfile().
2217 if (is_null($filename)) {
2218 $filename = '[^\'\",&<>|`\s:\\\\]+';
2220 $urlstring .= "\/(?<filename>{$filename})/";
2222 // Regular expression which matches URLs and returns their components.
2223 preg_match_all($urlstring, $text, $urls, PREG_SET_ORDER);
2224 return $urls;
2228 * This function will highlight search words in a given string
2230 * It cares about HTML and will not ruin links. It's best to use
2231 * this function after performing any conversions to HTML.
2233 * @param string $needle The search string. Syntax like "word1 +word2 -word3" is dealt with correctly.
2234 * @param string $haystack The string (HTML) within which to highlight the search terms.
2235 * @param boolean $matchcase whether to do case-sensitive. Default case-insensitive.
2236 * @param string $prefix the string to put before each search term found.
2237 * @param string $suffix the string to put after each search term found.
2238 * @return string The highlighted HTML.
2240 function highlight($needle, $haystack, $matchcase = false,
2241 $prefix = '<span class="highlight">', $suffix = '</span>') {
2243 // Quick bail-out in trivial cases.
2244 if (empty($needle) or empty($haystack)) {
2245 return $haystack;
2248 // Break up the search term into words, discard any -words and build a regexp.
2249 $words = preg_split('/ +/', trim($needle));
2250 foreach ($words as $index => $word) {
2251 if (strpos($word, '-') === 0) {
2252 unset($words[$index]);
2253 } else if (strpos($word, '+') === 0) {
2254 $words[$index] = '\b' . preg_quote(ltrim($word, '+'), '/') . '\b'; // Match only as a complete word.
2255 } else {
2256 $words[$index] = preg_quote($word, '/');
2259 $regexp = '/(' . implode('|', $words) . ')/u'; // Char u is to do UTF-8 matching.
2260 if (!$matchcase) {
2261 $regexp .= 'i';
2264 // Another chance to bail-out if $search was only -words.
2265 if (empty($words)) {
2266 return $haystack;
2269 // Split the string into HTML tags and real content.
2270 $chunks = preg_split('/((?:<[^>]*>)+)/', $haystack, -1, PREG_SPLIT_DELIM_CAPTURE);
2272 // We have an array of alternating blocks of text, then HTML tags, then text, ...
2273 // Loop through replacing search terms in the text, and leaving the HTML unchanged.
2274 $ishtmlchunk = false;
2275 $result = '';
2276 foreach ($chunks as $chunk) {
2277 if ($ishtmlchunk) {
2278 $result .= $chunk;
2279 } else {
2280 $result .= preg_replace($regexp, $prefix . '$1' . $suffix, $chunk);
2282 $ishtmlchunk = !$ishtmlchunk;
2285 return $result;
2289 * This function will highlight instances of $needle in $haystack
2291 * It's faster that the above function {@link highlight()} and doesn't care about
2292 * HTML or anything.
2294 * @param string $needle The string to search for
2295 * @param string $haystack The string to search for $needle in
2296 * @return string The highlighted HTML
2298 function highlightfast($needle, $haystack) {
2300 if (empty($needle) or empty($haystack)) {
2301 return $haystack;
2304 $parts = explode(core_text::strtolower($needle), core_text::strtolower($haystack));
2306 if (count($parts) === 1) {
2307 return $haystack;
2310 $pos = 0;
2312 foreach ($parts as $key => $part) {
2313 $parts[$key] = substr($haystack, $pos, strlen($part));
2314 $pos += strlen($part);
2316 $parts[$key] .= '<span class="highlight">'.substr($haystack, $pos, strlen($needle)).'</span>';
2317 $pos += strlen($needle);
2320 return str_replace('<span class="highlight"></span>', '', join('', $parts));
2324 * Converts a language code to hyphen-separated format in accordance to the
2325 * {@link https://datatracker.ietf.org/doc/html/rfc5646#section-2.1 BCP47 syntax}.
2327 * For additional information, check out
2328 * {@link https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/lang MDN web docs - lang}.
2330 * @param string $langcode The language code to convert.
2331 * @return string
2333 function get_html_lang_attribute_value(string $langcode): string {
2334 $langcode = clean_param($langcode, PARAM_LANG);
2335 if ($langcode === '') {
2336 return 'en';
2339 // Grab language ISO code from lang config. If it differs from English, then it's been specified and we can return it.
2340 $langiso = (string) (new lang_string('iso6391', 'core_langconfig', null, $langcode));
2341 if ($langiso !== 'en') {
2342 return $langiso;
2345 // Where we cannot determine the value from lang config, use the first two characters from the lang code.
2346 return substr($langcode, 0, 2);
2350 * Return a string containing 'lang', xml:lang and optionally 'dir' HTML attributes.
2352 * Internationalisation, for print_header and backup/restorelib.
2354 * @param bool $dir Default false
2355 * @return string Attributes
2357 function get_html_lang($dir = false) {
2358 global $CFG;
2360 $currentlang = current_language();
2361 if (isset($CFG->lang) && $currentlang !== $CFG->lang && !get_string_manager()->translation_exists($currentlang)) {
2362 // Use the default site language when the current language is not available.
2363 $currentlang = $CFG->lang;
2364 // Fix the current language.
2365 fix_current_language($currentlang);
2368 $direction = '';
2369 if ($dir) {
2370 if (right_to_left()) {
2371 $direction = ' dir="rtl"';
2372 } else {
2373 $direction = ' dir="ltr"';
2377 // Accessibility: added the 'lang' attribute to $direction, used in theme <html> tag.
2378 $language = get_html_lang_attribute_value($currentlang);
2379 @header('Content-Language: '.$language);
2380 return ($direction.' lang="'.$language.'" xml:lang="'.$language.'"');
2384 // STANDARD WEB PAGE PARTS.
2387 * Send the HTTP headers that Moodle requires.
2389 * There is a backwards compatibility hack for legacy code
2390 * that needs to add custom IE compatibility directive.
2392 * Example:
2393 * <code>
2394 * if (!isset($CFG->additionalhtmlhead)) {
2395 * $CFG->additionalhtmlhead = '';
2397 * $CFG->additionalhtmlhead .= '<meta http-equiv="X-UA-Compatible" content="IE=8" />';
2398 * header('X-UA-Compatible: IE=8');
2399 * echo $OUTPUT->header();
2400 * </code>
2402 * Please note the $CFG->additionalhtmlhead alone might not work,
2403 * you should send the IE compatibility header() too.
2405 * @param string $contenttype
2406 * @param bool $cacheable Can this page be cached on back?
2407 * @return void, sends HTTP headers
2409 function send_headers($contenttype, $cacheable = true) {
2410 global $CFG;
2412 @header('Content-Type: ' . $contenttype);
2413 @header('Content-Script-Type: text/javascript');
2414 @header('Content-Style-Type: text/css');
2416 if (empty($CFG->additionalhtmlhead) or stripos($CFG->additionalhtmlhead, 'X-UA-Compatible') === false) {
2417 @header('X-UA-Compatible: IE=edge');
2420 if ($cacheable) {
2421 // Allow caching on "back" (but not on normal clicks).
2422 @header('Cache-Control: private, pre-check=0, post-check=0, max-age=0, no-transform');
2423 @header('Pragma: no-cache');
2424 @header('Expires: ');
2425 } else {
2426 // Do everything we can to always prevent clients and proxies caching.
2427 @header('Cache-Control: no-store, no-cache, must-revalidate');
2428 @header('Cache-Control: post-check=0, pre-check=0, no-transform', false);
2429 @header('Pragma: no-cache');
2430 @header('Expires: Mon, 20 Aug 1969 09:23:00 GMT');
2431 @header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
2433 @header('Accept-Ranges: none');
2435 // The Moodle app must be allowed to embed content always.
2436 if (empty($CFG->allowframembedding) && !core_useragent::is_moodle_app()) {
2437 @header('X-Frame-Options: sameorigin');
2440 // If referrer policy is set, add a referrer header.
2441 if (!empty($CFG->referrerpolicy) && ($CFG->referrerpolicy !== 'default')) {
2442 @header('Referrer-Policy: ' . $CFG->referrerpolicy);
2447 * Return the right arrow with text ('next'), and optionally embedded in a link.
2449 * @param string $text HTML/plain text label (set to blank only for breadcrumb separator cases).
2450 * @param string $url An optional link to use in a surrounding HTML anchor.
2451 * @param bool $accesshide True if text should be hidden (for screen readers only).
2452 * @param string $addclass Additional class names for the link, or the arrow character.
2453 * @return string HTML string.
2455 function link_arrow_right($text, $url='', $accesshide=false, $addclass='', $addparams = []) {
2456 global $OUTPUT; // TODO: move to output renderer.
2457 $arrowclass = 'arrow ';
2458 if (!$url) {
2459 $arrowclass .= $addclass;
2461 $arrow = '<span class="'.$arrowclass.'" aria-hidden="true">'.$OUTPUT->rarrow().'</span>';
2462 $htmltext = '';
2463 if ($text) {
2464 $htmltext = '<span class="arrow_text">'.$text.'</span>&nbsp;';
2465 if ($accesshide) {
2466 $htmltext = get_accesshide($htmltext);
2469 if ($url) {
2470 $class = 'arrow_link';
2471 if ($addclass) {
2472 $class .= ' '.$addclass;
2475 $linkparams = [
2476 'class' => $class,
2477 'href' => $url,
2478 'title' => preg_replace('/<.*?>/', '', $text),
2481 $linkparams += $addparams;
2483 return html_writer::link($url, $htmltext . $arrow, $linkparams);
2485 return $htmltext.$arrow;
2489 * Return the left arrow with text ('previous'), and optionally embedded in a link.
2491 * @param string $text HTML/plain text label (set to blank only for breadcrumb separator cases).
2492 * @param string $url An optional link to use in a surrounding HTML anchor.
2493 * @param bool $accesshide True if text should be hidden (for screen readers only).
2494 * @param string $addclass Additional class names for the link, or the arrow character.
2495 * @return string HTML string.
2497 function link_arrow_left($text, $url='', $accesshide=false, $addclass='', $addparams = []) {
2498 global $OUTPUT; // TODO: move to utput renderer.
2499 $arrowclass = 'arrow ';
2500 if (! $url) {
2501 $arrowclass .= $addclass;
2503 $arrow = '<span class="'.$arrowclass.'" aria-hidden="true">'.$OUTPUT->larrow().'</span>';
2504 $htmltext = '';
2505 if ($text) {
2506 $htmltext = '&nbsp;<span class="arrow_text">'.$text.'</span>';
2507 if ($accesshide) {
2508 $htmltext = get_accesshide($htmltext);
2511 if ($url) {
2512 $class = 'arrow_link';
2513 if ($addclass) {
2514 $class .= ' '.$addclass;
2517 $linkparams = [
2518 'class' => $class,
2519 'href' => $url,
2520 'title' => preg_replace('/<.*?>/', '', $text),
2523 $linkparams += $addparams;
2525 return html_writer::link($url, $arrow . $htmltext, $linkparams);
2527 return $arrow.$htmltext;
2531 * Return a HTML element with the class "accesshide", for accessibility.
2533 * Please use cautiously - where possible, text should be visible!
2535 * @param string $text Plain text.
2536 * @param string $elem Lowercase element name, default "span".
2537 * @param string $class Additional classes for the element.
2538 * @param string $attrs Additional attributes string in the form, "name='value' name2='value2'"
2539 * @return string HTML string.
2541 function get_accesshide($text, $elem='span', $class='', $attrs='') {
2542 return "<$elem class=\"accesshide $class\" $attrs>$text</$elem>";
2546 * Return the breadcrumb trail navigation separator.
2548 * @return string HTML string.
2550 function get_separator() {
2551 // Accessibility: the 'hidden' slash is preferred for screen readers.
2552 return ' '.link_arrow_right($text='/', $url='', $accesshide=true, 'sep').' ';
2556 * Print (or return) a collapsible region, that has a caption that can be clicked to expand or collapse the region.
2558 * If JavaScript is off, then the region will always be expanded.
2560 * @param string $contents the contents of the box.
2561 * @param string $classes class names added to the div that is output.
2562 * @param string $id id added to the div that is output. Must not be blank.
2563 * @param string $caption text displayed at the top. Clicking on this will cause the region to expand or contract.
2564 * @param string $userpref the name of the user preference that stores the user's preferred default state.
2565 * (May be blank if you do not wish the state to be persisted.
2566 * @param boolean $default Initial collapsed state to use if the user_preference it not set.
2567 * @param boolean $return if true, return the HTML as a string, rather than printing it.
2568 * @return string|void If $return is false, returns nothing, otherwise returns a string of HTML.
2570 function print_collapsible_region($contents, $classes, $id, $caption, $userpref = '', $default = false, $return = false) {
2571 $output = print_collapsible_region_start($classes, $id, $caption, $userpref, $default, true);
2572 $output .= $contents;
2573 $output .= print_collapsible_region_end(true);
2575 if ($return) {
2576 return $output;
2577 } else {
2578 echo $output;
2583 * Print (or return) the start of a collapsible region
2585 * The collapsibleregion has a caption that can be clicked to expand or collapse the region. If JavaScript is off, then the region
2586 * will always be expanded.
2588 * @param string $classes class names added to the div that is output.
2589 * @param string $id id added to the div that is output. Must not be blank.
2590 * @param string $caption text displayed at the top. Clicking on this will cause the region to expand or contract.
2591 * @param string $userpref the name of the user preference that stores the user's preferred default state.
2592 * (May be blank if you do not wish the state to be persisted.
2593 * @param boolean $default Initial collapsed state to use if the user_preference it not set.
2594 * @param boolean $return if true, return the HTML as a string, rather than printing it.
2595 * @param string $extracontent the extra content will show next to caption, eg.Help icon.
2596 * @return string|void if $return is false, returns nothing, otherwise returns a string of HTML.
2598 function print_collapsible_region_start($classes, $id, $caption, $userpref = '', $default = false, $return = false,
2599 $extracontent = null) {
2600 global $PAGE;
2602 // Work out the initial state.
2603 if (!empty($userpref) and is_string($userpref)) {
2604 $collapsed = get_user_preferences($userpref, $default);
2605 } else {
2606 $collapsed = $default;
2607 $userpref = false;
2610 if ($collapsed) {
2611 $classes .= ' collapsed';
2614 $output = '';
2615 $output .= '<div id="' . $id . '" class="collapsibleregion ' . $classes . '">';
2616 $output .= '<div id="' . $id . '_sizer">';
2617 $output .= '<div id="' . $id . '_caption" class="collapsibleregioncaption">';
2618 $output .= $caption . ' </div>';
2619 if ($extracontent) {
2620 $output .= html_writer::div($extracontent, 'collapsibleregionextracontent');
2622 $output .= '<div id="' . $id . '_inner" class="collapsibleregioninner">';
2623 $PAGE->requires->js_init_call('M.util.init_collapsible_region', array($id, $userpref, get_string('clicktohideshow')));
2625 if ($return) {
2626 return $output;
2627 } else {
2628 echo $output;
2633 * Close a region started with print_collapsible_region_start.
2635 * @param boolean $return if true, return the HTML as a string, rather than printing it.
2636 * @return string|void if $return is false, returns nothing, otherwise returns a string of HTML.
2638 function print_collapsible_region_end($return = false) {
2639 $output = '</div></div></div>';
2641 if ($return) {
2642 return $output;
2643 } else {
2644 echo $output;
2649 * Print a specified group's avatar.
2651 * @param array|stdClass $group A single {@link group} object OR array of groups.
2652 * @param int $courseid The course ID.
2653 * @param boolean $large Default small picture, or large.
2654 * @param boolean $return If false print picture, otherwise return the output as string
2655 * @param boolean $link Enclose image in a link to view specified course?
2656 * @param boolean $includetoken Whether to use a user token when displaying this group image.
2657 * True indicates to generate a token for current user, and integer value indicates to generate a token for the
2658 * user whose id is the value indicated.
2659 * If the group picture is included in an e-mail or some other location where the audience is a specific
2660 * user who will not be logged in when viewing, then we use a token to authenticate the user.
2661 * @return string|void Depending on the setting of $return
2663 function print_group_picture($group, $courseid, $large = false, $return = false, $link = true, $includetoken = false) {
2664 global $CFG;
2666 if (is_array($group)) {
2667 $output = '';
2668 foreach ($group as $g) {
2669 $output .= print_group_picture($g, $courseid, $large, true, $link, $includetoken);
2671 if ($return) {
2672 return $output;
2673 } else {
2674 echo $output;
2675 return;
2679 $pictureurl = get_group_picture_url($group, $courseid, $large, $includetoken);
2681 // If there is no picture, do nothing.
2682 if (!isset($pictureurl)) {
2683 return;
2686 $context = context_course::instance($courseid);
2688 $groupname = s($group->name);
2689 $pictureimage = html_writer::img($pictureurl, $groupname, ['title' => $groupname]);
2691 $output = '';
2692 if ($link or has_capability('moodle/site:accessallgroups', $context)) {
2693 $linkurl = new moodle_url('/user/index.php', ['id' => $courseid, 'group' => $group->id]);
2694 $output .= html_writer::link($linkurl, $pictureimage);
2695 } else {
2696 $output .= $pictureimage;
2699 if ($return) {
2700 return $output;
2701 } else {
2702 echo $output;
2707 * Return the url to the group picture.
2709 * @param stdClass $group A group object.
2710 * @param int $courseid The course ID for the group.
2711 * @param bool $large A large or small group picture? Default is small.
2712 * @param boolean $includetoken Whether to use a user token when displaying this group image.
2713 * True indicates to generate a token for current user, and integer value indicates to generate a token for the
2714 * user whose id is the value indicated.
2715 * If the group picture is included in an e-mail or some other location where the audience is a specific
2716 * user who will not be logged in when viewing, then we use a token to authenticate the user.
2717 * @return moodle_url Returns the url for the group picture.
2719 function get_group_picture_url($group, $courseid, $large = false, $includetoken = false) {
2720 global $CFG;
2722 $context = context_course::instance($courseid);
2724 // If there is no picture, do nothing.
2725 if (!$group->picture) {
2726 return;
2729 if ($large) {
2730 $file = 'f1';
2731 } else {
2732 $file = 'f2';
2735 $grouppictureurl = moodle_url::make_pluginfile_url(
2736 $context->id, 'group', 'icon', $group->id, '/', $file, false, $includetoken);
2737 $grouppictureurl->param('rev', $group->picture);
2738 return $grouppictureurl;
2743 * Display a recent activity note
2745 * @staticvar string $strftimerecent
2746 * @param int $time A timestamp int.
2747 * @param stdClass $user A user object from the database.
2748 * @param string $text Text for display for the note
2749 * @param string $link The link to wrap around the text
2750 * @param bool $return If set to true the HTML is returned rather than echo'd
2751 * @param string $viewfullnames
2752 * @return string If $retrun was true returns HTML for a recent activity notice.
2754 function print_recent_activity_note($time, $user, $text, $link, $return=false, $viewfullnames=null) {
2755 static $strftimerecent = null;
2756 $output = '';
2758 if (is_null($viewfullnames)) {
2759 $context = context_system::instance();
2760 $viewfullnames = has_capability('moodle/site:viewfullnames', $context);
2763 if (is_null($strftimerecent)) {
2764 $strftimerecent = get_string('strftimerecent');
2767 $output .= '<div class="head">';
2768 $output .= '<div class="date">'.userdate($time, $strftimerecent).'</div>';
2769 $output .= '<div class="name">'.fullname($user, $viewfullnames).'</div>';
2770 $output .= '</div>';
2771 $output .= '<div class="info"><a href="'.$link.'">'.format_string($text, true).'</a></div>';
2773 if ($return) {
2774 return $output;
2775 } else {
2776 echo $output;
2781 * Returns a popup menu with course activity modules
2783 * Given a course this function returns a small popup menu with all the course activity modules in it, as a navigation menu
2784 * outputs a simple list structure in XHTML.
2785 * The data is taken from the serialised array stored in the course record.
2787 * @param stdClass $course A course object.
2788 * @param array $sections
2789 * @param course_modinfo $modinfo
2790 * @param string $strsection
2791 * @param string $strjumpto
2792 * @param int $width
2793 * @param string $cmid
2794 * @return string The HTML block
2796 function navmenulist($course, $sections, $modinfo, $strsection, $strjumpto, $width=50, $cmid=0) {
2798 global $CFG, $OUTPUT;
2800 $section = -1;
2801 $menu = array();
2802 $doneheading = false;
2804 $courseformatoptions = course_get_format($course)->get_format_options();
2805 $coursecontext = context_course::instance($course->id);
2807 $menu[] = '<ul class="navmenulist"><li class="jumpto section"><span>'.$strjumpto.'</span><ul>';
2808 foreach ($modinfo->cms as $mod) {
2809 if (!$mod->has_view()) {
2810 // Don't show modules which you can't link to!
2811 continue;
2814 // For course formats using 'numsections' do not show extra sections.
2815 if (isset($courseformatoptions['numsections']) && $mod->sectionnum > $courseformatoptions['numsections']) {
2816 break;
2819 if (!$mod->uservisible) { // Do not icnlude empty sections at all.
2820 continue;
2823 if ($mod->sectionnum >= 0 and $section != $mod->sectionnum) {
2824 $thissection = $sections[$mod->sectionnum];
2826 if ($thissection->visible or
2827 (isset($courseformatoptions['hiddensections']) and !$courseformatoptions['hiddensections']) or
2828 has_capability('moodle/course:viewhiddensections', $coursecontext)) {
2829 $thissection->summary = strip_tags(format_string($thissection->summary, true));
2830 if (!$doneheading) {
2831 $menu[] = '</ul></li>';
2833 if ($course->format == 'weeks' or empty($thissection->summary)) {
2834 $item = $strsection ." ". $mod->sectionnum;
2835 } else {
2836 if (core_text::strlen($thissection->summary) < ($width-3)) {
2837 $item = $thissection->summary;
2838 } else {
2839 $item = core_text::substr($thissection->summary, 0, $width).'...';
2842 $menu[] = '<li class="section"><span>'.$item.'</span>';
2843 $menu[] = '<ul>';
2844 $doneheading = true;
2846 $section = $mod->sectionnum;
2847 } else {
2848 // No activities from this hidden section shown.
2849 continue;
2853 $url = $mod->modname .'/view.php?id='. $mod->id;
2854 $mod->name = strip_tags(format_string($mod->name ,true));
2855 if (core_text::strlen($mod->name) > ($width+5)) {
2856 $mod->name = core_text::substr($mod->name, 0, $width).'...';
2858 if (!$mod->visible) {
2859 $mod->name = '('.$mod->name.')';
2861 $class = 'activity '.$mod->modname;
2862 $class .= ($cmid == $mod->id) ? ' selected' : '';
2863 $menu[] = '<li class="'.$class.'">'.
2864 $OUTPUT->image_icon('monologo', '', $mod->modname).
2865 '<a href="'.$CFG->wwwroot.'/mod/'.$url.'">'.$mod->name.'</a></li>';
2868 if ($doneheading) {
2869 $menu[] = '</ul></li>';
2871 $menu[] = '</ul></li></ul>';
2873 return implode("\n", $menu);
2877 * Prints a grade menu (as part of an existing form) with help showing all possible numerical grades and scales.
2879 * @todo Finish documenting this function
2880 * @todo Deprecate: this is only used in a few contrib modules
2882 * @param int $courseid The course ID
2883 * @param string $name
2884 * @param string $current
2885 * @param boolean $includenograde Include those with no grades
2886 * @param boolean $return If set to true returns rather than echo's
2887 * @return string|bool Depending on value of $return
2889 function print_grade_menu($courseid, $name, $current, $includenograde=true, $return=false) {
2890 global $OUTPUT;
2892 $output = '';
2893 $strscale = get_string('scale');
2894 $strscales = get_string('scales');
2896 $scales = get_scales_menu($courseid);
2897 foreach ($scales as $i => $scalename) {
2898 $grades[-$i] = $strscale .': '. $scalename;
2900 if ($includenograde) {
2901 $grades[0] = get_string('nograde');
2903 for ($i=100; $i>=1; $i--) {
2904 $grades[$i] = $i;
2906 $output .= html_writer::select($grades, $name, $current, false);
2908 $linkobject = '<span class="helplink">' . $OUTPUT->pix_icon('help', $strscales) . '</span>';
2909 $link = new moodle_url('/course/scales.php', array('id' => $courseid, 'list' => 1));
2910 $action = new popup_action('click', $link, 'ratingscales', array('height' => 400, 'width' => 500));
2911 $output .= $OUTPUT->action_link($link, $linkobject, $action, array('title' => $strscales));
2913 if ($return) {
2914 return $output;
2915 } else {
2916 echo $output;
2921 * Print an error to STDOUT and exit with a non-zero code. For commandline scripts.
2923 * Default errorcode is 1.
2925 * Very useful for perl-like error-handling:
2926 * do_somethting() or mdie("Something went wrong");
2928 * @param string $msg Error message
2929 * @param integer $errorcode Error code to emit
2931 function mdie($msg='', $errorcode=1) {
2932 trigger_error($msg);
2933 exit($errorcode);
2937 * Print a message and exit.
2939 * @param string $message The message to print in the notice
2940 * @param moodle_url|string $link The link to use for the continue button
2941 * @param object $course A course object. Unused.
2942 * @return void This function simply exits
2944 function notice ($message, $link='', $course=null) {
2945 global $PAGE, $OUTPUT;
2947 $message = clean_text($message); // In case nasties are in here.
2949 if (CLI_SCRIPT) {
2950 echo("!!$message!!\n");
2951 exit(1); // No success.
2954 if (!$PAGE->headerprinted) {
2955 // Header not yet printed.
2956 $PAGE->set_title(get_string('notice'));
2957 echo $OUTPUT->header();
2958 } else {
2959 echo $OUTPUT->container_end_all(false);
2962 echo $OUTPUT->box($message, 'generalbox', 'notice');
2963 echo $OUTPUT->continue_button($link);
2965 echo $OUTPUT->footer();
2966 exit(1); // General error code.
2970 * Redirects the user to another page, after printing a notice.
2972 * This function calls the OUTPUT redirect method, echo's the output and then dies to ensure nothing else happens.
2974 * <strong>Good practice:</strong> You should call this method before starting page
2975 * output by using any of the OUTPUT methods.
2977 * @param moodle_url|string $url A moodle_url to redirect to. Strings are not to be trusted!
2978 * @param string $message The message to display to the user
2979 * @param int $delay The delay before redirecting
2980 * @param string $messagetype The type of notification to show the message in. See constants on \core\output\notification.
2981 * @throws moodle_exception
2983 function redirect($url, $message='', $delay=null, $messagetype = \core\output\notification::NOTIFY_INFO) {
2984 global $OUTPUT, $PAGE, $CFG;
2986 if (CLI_SCRIPT or AJAX_SCRIPT) {
2987 // This is wrong - developers should not use redirect in these scripts but it should not be very likely.
2988 throw new moodle_exception('redirecterrordetected', 'error');
2991 if ($delay === null) {
2992 $delay = -1;
2995 // Prevent debug errors - make sure context is properly initialised.
2996 if ($PAGE) {
2997 $PAGE->set_context(null);
2998 $PAGE->set_pagelayout('redirect'); // No header and footer needed.
2999 $PAGE->set_title(get_string('pageshouldredirect', 'moodle'));
3002 if ($url instanceof moodle_url) {
3003 $url = $url->out(false);
3006 $debugdisableredirect = false;
3007 do {
3008 if (defined('DEBUGGING_PRINTED')) {
3009 // Some debugging already printed, no need to look more.
3010 $debugdisableredirect = true;
3011 break;
3014 if (core_useragent::is_msword()) {
3015 // Clicking a URL from MS Word sends a request to the server without cookies. If that
3016 // causes a redirect Word will open a browser pointing the new URL. If not, the URL that
3017 // was clicked is opened. Because the request from Word is without cookies, it almost
3018 // always results in a redirect to the login page, even if the user is logged in in their
3019 // browser. This is not what we want, so prevent the redirect for requests from Word.
3020 $debugdisableredirect = true;
3021 break;
3024 if (empty($CFG->debugdisplay) or empty($CFG->debug)) {
3025 // No errors should be displayed.
3026 break;
3029 if (!function_exists('error_get_last') or !$lasterror = error_get_last()) {
3030 break;
3033 if (!($lasterror['type'] & $CFG->debug)) {
3034 // Last error not interesting.
3035 break;
3038 // Watch out here, @hidden() errors are returned from error_get_last() too.
3039 if (headers_sent()) {
3040 // We already started printing something - that means errors likely printed.
3041 $debugdisableredirect = true;
3042 break;
3045 if (ob_get_level() and ob_get_contents()) {
3046 // There is something waiting to be printed, hopefully it is the errors,
3047 // but it might be some error hidden by @ too - such as the timezone mess from setup.php.
3048 $debugdisableredirect = true;
3049 break;
3051 } while (false);
3053 // Technically, HTTP/1.1 requires Location: header to contain the absolute path.
3054 // (In practice browsers accept relative paths - but still, might as well do it properly.)
3055 // This code turns relative into absolute.
3056 if (!preg_match('|^[a-z]+:|i', $url)) {
3057 // Get host name http://www.wherever.com.
3058 $hostpart = preg_replace('|^(.*?[^:/])/.*$|', '$1', $CFG->wwwroot);
3059 if (preg_match('|^/|', $url)) {
3060 // URLs beginning with / are relative to web server root so we just add them in.
3061 $url = $hostpart.$url;
3062 } else {
3063 // URLs not beginning with / are relative to path of current script, so add that on.
3064 $url = $hostpart.preg_replace('|\?.*$|', '', me()).'/../'.$url;
3066 // Replace all ..s.
3067 while (true) {
3068 $newurl = preg_replace('|/(?!\.\.)[^/]*/\.\./|', '/', $url);
3069 if ($newurl == $url) {
3070 break;
3072 $url = $newurl;
3076 // Sanitise url - we can not rely on moodle_url or our URL cleaning
3077 // because they do not support all valid external URLs.
3078 $url = preg_replace('/[\x00-\x1F\x7F]/', '', $url);
3079 $url = str_replace('"', '%22', $url);
3080 $encodedurl = preg_replace("/\&(?![a-zA-Z0-9#]{1,8};)/", "&amp;", $url);
3081 $encodedurl = preg_replace('/^.*href="([^"]*)".*$/', "\\1", clean_text('<a href="'.$encodedurl.'" />', FORMAT_HTML));
3082 $url = str_replace('&amp;', '&', $encodedurl);
3084 if (!empty($message)) {
3085 if (!$debugdisableredirect && !headers_sent()) {
3086 // A message has been provided, and the headers have not yet been sent.
3087 // Display the message as a notification on the subsequent page.
3088 \core\notification::add($message, $messagetype);
3089 $message = null;
3090 $delay = 0;
3091 } else {
3092 if ($delay === -1 || !is_numeric($delay)) {
3093 $delay = 3;
3095 $message = clean_text($message);
3097 } else {
3098 $message = get_string('pageshouldredirect');
3099 $delay = 0;
3102 // Make sure the session is closed properly, this prevents problems in IIS
3103 // and also some potential PHP shutdown issues.
3104 \core\session\manager::write_close();
3106 if ($delay == 0 && !$debugdisableredirect && !headers_sent()) {
3108 // This helps when debugging redirect issues like loops and it is not clear
3109 // which layer in the stack sent the redirect header. If debugging is on
3110 // then the file and line is also shown.
3111 $redirectby = 'Moodle';
3112 if (debugging('', DEBUG_DEVELOPER)) {
3113 $origin = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 1)[0];
3114 $redirectby .= ' /' . str_replace($CFG->dirroot . '/', '', $origin['file']) . ':' . $origin['line'];
3116 @header("X-Redirect-By: $redirectby");
3118 // 302 might not work for POST requests, 303 is ignored by obsolete clients.
3119 @header($_SERVER['SERVER_PROTOCOL'] . ' 303 See Other');
3120 @header('Location: '.$url);
3121 echo bootstrap_renderer::plain_redirect_message($encodedurl);
3122 exit;
3125 // Include a redirect message, even with a HTTP redirect, because that is recommended practice.
3126 if ($PAGE) {
3127 $CFG->docroot = false; // To prevent the link to moodle docs from being displayed on redirect page.
3128 echo $OUTPUT->redirect_message($encodedurl, $message, $delay, $debugdisableredirect, $messagetype);
3129 exit;
3130 } else {
3131 echo bootstrap_renderer::early_redirect_message($encodedurl, $message, $delay);
3132 exit;
3137 * Given an email address, this function will return an obfuscated version of it.
3139 * @param string $email The email address to obfuscate
3140 * @return string The obfuscated email address
3142 function obfuscate_email($email) {
3143 $i = 0;
3144 $length = strlen($email);
3145 $obfuscated = '';
3146 while ($i < $length) {
3147 if (rand(0, 2) && $email[$i]!='@') { // MDL-20619 some browsers have problems unobfuscating @.
3148 $obfuscated.='%'.dechex(ord($email[$i]));
3149 } else {
3150 $obfuscated.=$email[$i];
3152 $i++;
3154 return $obfuscated;
3158 * This function takes some text and replaces about half of the characters
3159 * with HTML entity equivalents. Return string is obviously longer.
3161 * @param string $plaintext The text to be obfuscated
3162 * @return string The obfuscated text
3164 function obfuscate_text($plaintext) {
3165 $i=0;
3166 $length = core_text::strlen($plaintext);
3167 $obfuscated='';
3168 $prevobfuscated = false;
3169 while ($i < $length) {
3170 $char = core_text::substr($plaintext, $i, 1);
3171 $ord = core_text::utf8ord($char);
3172 $numerical = ($ord >= ord('0')) && ($ord <= ord('9'));
3173 if ($prevobfuscated and $numerical ) {
3174 $obfuscated.='&#'.$ord.';';
3175 } else if (rand(0, 2)) {
3176 $obfuscated.='&#'.$ord.';';
3177 $prevobfuscated = true;
3178 } else {
3179 $obfuscated.=$char;
3180 $prevobfuscated = false;
3182 $i++;
3184 return $obfuscated;
3188 * This function uses the {@link obfuscate_email()} and {@link obfuscate_text()}
3189 * to generate a fully obfuscated email link, ready to use.
3191 * @param string $email The email address to display
3192 * @param string $label The text to displayed as hyperlink to $email
3193 * @param boolean $dimmed If true then use css class 'dimmed' for hyperlink
3194 * @param string $subject The subject of the email in the mailto link
3195 * @param string $body The content of the email in the mailto link
3196 * @return string The obfuscated mailto link
3198 function obfuscate_mailto($email, $label='', $dimmed=false, $subject = '', $body = '') {
3200 if (empty($label)) {
3201 $label = $email;
3204 $label = obfuscate_text($label);
3205 $email = obfuscate_email($email);
3206 $mailto = obfuscate_text('mailto');
3207 $url = new moodle_url("mailto:$email");
3208 $attrs = array();
3210 if (!empty($subject)) {
3211 $url->param('subject', format_string($subject));
3213 if (!empty($body)) {
3214 $url->param('body', format_string($body));
3217 // Use the obfuscated mailto.
3218 $url = preg_replace('/^mailto/', $mailto, $url->out());
3220 if ($dimmed) {
3221 $attrs['title'] = get_string('emaildisable');
3222 $attrs['class'] = 'dimmed';
3225 return html_writer::link($url, $label, $attrs);
3229 * This function is used to rebuild the <nolink> tag because some formats (PLAIN and WIKI)
3230 * will transform it to html entities
3232 * @param string $text Text to search for nolink tag in
3233 * @return string
3235 function rebuildnolinktag($text) {
3237 $text = preg_replace('/&lt;(\/*nolink)&gt;/i', '<$1>', $text);
3239 return $text;
3243 * Prints a maintenance message from $CFG->maintenance_message or default if empty.
3245 function print_maintenance_message() {
3246 global $CFG, $SITE, $PAGE, $OUTPUT;
3248 header($_SERVER['SERVER_PROTOCOL'] . ' 503 Moodle under maintenance');
3249 header('Status: 503 Moodle under maintenance');
3250 header('Retry-After: 300');
3252 $PAGE->set_pagetype('maintenance-message');
3253 $PAGE->set_pagelayout('maintenance');
3254 $PAGE->set_heading($SITE->fullname);
3255 echo $OUTPUT->header();
3256 echo $OUTPUT->heading(get_string('sitemaintenance', 'admin'));
3257 if (isset($CFG->maintenance_message) and !html_is_blank($CFG->maintenance_message)) {
3258 echo $OUTPUT->box_start('maintenance_message generalbox boxwidthwide boxaligncenter');
3259 echo $CFG->maintenance_message;
3260 echo $OUTPUT->box_end();
3262 echo $OUTPUT->footer();
3263 die;
3267 * Returns a string containing a nested list, suitable for formatting into tabs with CSS.
3269 * It is not recommended to use this function in Moodle 2.5 but it is left for backward
3270 * compartibility.
3272 * Example how to print a single line tabs:
3273 * $rows = array(
3274 * new tabobject(...),
3275 * new tabobject(...)
3276 * );
3277 * echo $OUTPUT->tabtree($rows, $selectedid);
3279 * Multiple row tabs may not look good on some devices but if you want to use them
3280 * you can specify ->subtree for the active tabobject.
3282 * @param array $tabrows An array of rows where each row is an array of tab objects
3283 * @param string $selected The id of the selected tab (whatever row it's on)
3284 * @param array $inactive An array of ids of inactive tabs that are not selectable.
3285 * @param array $activated An array of ids of other tabs that are currently activated
3286 * @param bool $return If true output is returned rather then echo'd
3287 * @return string HTML output if $return was set to true.
3289 function print_tabs($tabrows, $selected = null, $inactive = null, $activated = null, $return = false) {
3290 global $OUTPUT;
3292 $tabrows = array_reverse($tabrows);
3293 $subtree = array();
3294 foreach ($tabrows as $row) {
3295 $tree = array();
3297 foreach ($row as $tab) {
3298 $tab->inactive = is_array($inactive) && in_array((string)$tab->id, $inactive);
3299 $tab->activated = is_array($activated) && in_array((string)$tab->id, $activated);
3300 $tab->selected = (string)$tab->id == $selected;
3302 if ($tab->activated || $tab->selected) {
3303 $tab->subtree = $subtree;
3305 $tree[] = $tab;
3307 $subtree = $tree;
3309 $output = $OUTPUT->tabtree($subtree);
3310 if ($return) {
3311 return $output;
3312 } else {
3313 print $output;
3314 return !empty($output);
3319 * Alter debugging level for the current request,
3320 * the change is not saved in database.
3322 * @param int $level one of the DEBUG_* constants
3323 * @param bool $debugdisplay
3325 function set_debugging($level, $debugdisplay = null) {
3326 global $CFG;
3328 $CFG->debug = (int)$level;
3329 $CFG->debugdeveloper = (($CFG->debug & DEBUG_DEVELOPER) === DEBUG_DEVELOPER);
3331 if ($debugdisplay !== null) {
3332 $CFG->debugdisplay = (bool)$debugdisplay;
3337 * Standard Debugging Function
3339 * Returns true if the current site debugging settings are equal or above specified level.
3340 * If passed a parameter it will emit a debugging notice similar to trigger_error(). The
3341 * routing of notices is controlled by $CFG->debugdisplay
3342 * eg use like this:
3344 * 1) debugging('a normal debug notice');
3345 * 2) debugging('something really picky', DEBUG_ALL);
3346 * 3) debugging('annoying debug message only for developers', DEBUG_DEVELOPER);
3347 * 4) if (debugging()) { perform extra debugging operations (do not use print or echo) }
3349 * In code blocks controlled by debugging() (such as example 4)
3350 * any output should be routed via debugging() itself, or the lower-level
3351 * trigger_error() or error_log(). Using echo or print will break XHTML
3352 * JS and HTTP headers.
3354 * It is also possible to define NO_DEBUG_DISPLAY which redirects the message to error_log.
3356 * @param string $message a message to print
3357 * @param int $level the level at which this debugging statement should show
3358 * @param array $backtrace use different backtrace
3359 * @return bool
3361 function debugging($message = '', $level = DEBUG_NORMAL, $backtrace = null) {
3362 global $CFG, $USER;
3364 $forcedebug = false;
3365 if (!empty($CFG->debugusers) && $USER) {
3366 $debugusers = explode(',', $CFG->debugusers);
3367 $forcedebug = in_array($USER->id, $debugusers);
3370 if (!$forcedebug and (empty($CFG->debug) || ($CFG->debug != -1 and $CFG->debug < $level))) {
3371 return false;
3374 if (!isset($CFG->debugdisplay)) {
3375 $CFG->debugdisplay = ini_get_bool('display_errors');
3378 if ($message) {
3379 if (!$backtrace) {
3380 $backtrace = debug_backtrace();
3382 $from = format_backtrace($backtrace, CLI_SCRIPT || NO_DEBUG_DISPLAY);
3383 if (PHPUNIT_TEST) {
3384 if (phpunit_util::debugging_triggered($message, $level, $from)) {
3385 // We are inside test, the debug message was logged.
3386 return true;
3390 if (NO_DEBUG_DISPLAY) {
3391 // Script does not want any errors or debugging in output,
3392 // we send the info to error log instead.
3393 error_log('Debugging: ' . $message . ' in '. PHP_EOL . $from);
3395 } else if ($forcedebug or $CFG->debugdisplay) {
3396 if (!defined('DEBUGGING_PRINTED')) {
3397 define('DEBUGGING_PRINTED', 1); // Indicates we have printed something.
3399 if (CLI_SCRIPT) {
3400 echo "++ $message ++\n$from";
3401 } else {
3402 echo '<div class="notifytiny debuggingmessage" data-rel="debugging">' , $message , $from , '</div>';
3405 } else {
3406 trigger_error($message . $from, E_USER_NOTICE);
3409 return true;
3413 * Outputs a HTML comment to the browser.
3415 * This is used for those hard-to-debug pages that use bits from many different files in very confusing ways (e.g. blocks).
3417 * <code>print_location_comment(__FILE__, __LINE__);</code>
3419 * @param string $file
3420 * @param integer $line
3421 * @param boolean $return Whether to return or print the comment
3422 * @return string|void Void unless true given as third parameter
3424 function print_location_comment($file, $line, $return = false) {
3425 if ($return) {
3426 return "<!-- $file at line $line -->\n";
3427 } else {
3428 echo "<!-- $file at line $line -->\n";
3434 * Returns true if the user is using a right-to-left language.
3436 * @return boolean true if the current language is right-to-left (Hebrew, Arabic etc)
3438 function right_to_left() {
3439 return (get_string('thisdirection', 'langconfig') === 'rtl');
3444 * Returns swapped left<=> right if in RTL environment.
3446 * Part of RTL Moodles support.
3448 * @param string $align align to check
3449 * @return string
3451 function fix_align_rtl($align) {
3452 if (!right_to_left()) {
3453 return $align;
3455 if ($align == 'left') {
3456 return 'right';
3458 if ($align == 'right') {
3459 return 'left';
3461 return $align;
3466 * Returns true if the page is displayed in a popup window.
3468 * Gets the information from the URL parameter inpopup.
3470 * @todo Use a central function to create the popup calls all over Moodle and
3471 * In the moment only works with resources and probably questions.
3473 * @return boolean
3475 function is_in_popup() {
3476 $inpopup = optional_param('inpopup', '', PARAM_BOOL);
3478 return ($inpopup);
3482 * Progress trace class.
3484 * Use this class from long operations where you want to output occasional information about
3485 * what is going on, but don't know if, or in what format, the output should be.
3487 * @copyright 2009 Tim Hunt
3488 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3489 * @package core
3491 abstract class progress_trace {
3493 * Output an progress message in whatever format.
3495 * @param string $message the message to output.
3496 * @param integer $depth indent depth for this message.
3498 abstract public function output($message, $depth = 0);
3501 * Called when the processing is finished.
3503 public function finished() {
3508 * This subclass of progress_trace does not ouput anything.
3510 * @copyright 2009 Tim Hunt
3511 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3512 * @package core
3514 class null_progress_trace extends progress_trace {
3516 * Does Nothing
3518 * @param string $message
3519 * @param int $depth
3520 * @return void Does Nothing
3522 public function output($message, $depth = 0) {
3527 * This subclass of progress_trace outputs to plain text.
3529 * @copyright 2009 Tim Hunt
3530 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3531 * @package core
3533 class text_progress_trace extends progress_trace {
3535 * Output the trace message.
3537 * @param string $message
3538 * @param int $depth
3539 * @return void Output is echo'd
3541 public function output($message, $depth = 0) {
3542 mtrace(str_repeat(' ', $depth) . $message);
3547 * This subclass of progress_trace outputs as HTML.
3549 * @copyright 2009 Tim Hunt
3550 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3551 * @package core
3553 class html_progress_trace extends progress_trace {
3555 * Output the trace message.
3557 * @param string $message
3558 * @param int $depth
3559 * @return void Output is echo'd
3561 public function output($message, $depth = 0) {
3562 echo '<p>', str_repeat('&#160;&#160;', $depth), htmlspecialchars($message, ENT_COMPAT), "</p>\n";
3563 flush();
3568 * HTML List Progress Tree
3570 * @copyright 2009 Tim Hunt
3571 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3572 * @package core
3574 class html_list_progress_trace extends progress_trace {
3575 /** @var int */
3576 protected $currentdepth = -1;
3579 * Echo out the list
3581 * @param string $message The message to display
3582 * @param int $depth
3583 * @return void Output is echoed
3585 public function output($message, $depth = 0) {
3586 $samedepth = true;
3587 while ($this->currentdepth > $depth) {
3588 echo "</li>\n</ul>\n";
3589 $this->currentdepth -= 1;
3590 if ($this->currentdepth == $depth) {
3591 echo '<li>';
3593 $samedepth = false;
3595 while ($this->currentdepth < $depth) {
3596 echo "<ul>\n<li>";
3597 $this->currentdepth += 1;
3598 $samedepth = false;
3600 if ($samedepth) {
3601 echo "</li>\n<li>";
3603 echo htmlspecialchars($message, ENT_COMPAT);
3604 flush();
3608 * Called when the processing is finished.
3610 public function finished() {
3611 while ($this->currentdepth >= 0) {
3612 echo "</li>\n</ul>\n";
3613 $this->currentdepth -= 1;
3619 * This subclass of progress_trace outputs to error log.
3621 * @copyright Petr Skoda {@link http://skodak.org}
3622 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3623 * @package core
3625 class error_log_progress_trace extends progress_trace {
3626 /** @var string log prefix */
3627 protected $prefix;
3630 * Constructor.
3631 * @param string $prefix optional log prefix
3633 public function __construct($prefix = '') {
3634 $this->prefix = $prefix;
3638 * Output the trace message.
3640 * @param string $message
3641 * @param int $depth
3642 * @return void Output is sent to error log.
3644 public function output($message, $depth = 0) {
3645 error_log($this->prefix . str_repeat(' ', $depth) . $message);
3650 * Special type of trace that can be used for catching of output of other traces.
3652 * @copyright Petr Skoda {@link http://skodak.org}
3653 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3654 * @package core
3656 class progress_trace_buffer extends progress_trace {
3657 /** @var progress_trace */
3658 protected $trace;
3659 /** @var bool do we pass output out */
3660 protected $passthrough;
3661 /** @var string output buffer */
3662 protected $buffer;
3665 * Constructor.
3667 * @param progress_trace $trace
3668 * @param bool $passthrough true means output and buffer, false means just buffer and no output
3670 public function __construct(progress_trace $trace, $passthrough = true) {
3671 $this->trace = $trace;
3672 $this->passthrough = $passthrough;
3673 $this->buffer = '';
3677 * Output the trace message.
3679 * @param string $message the message to output.
3680 * @param int $depth indent depth for this message.
3681 * @return void output stored in buffer
3683 public function output($message, $depth = 0) {
3684 ob_start();
3685 $this->trace->output($message, $depth);
3686 $this->buffer .= ob_get_contents();
3687 if ($this->passthrough) {
3688 ob_end_flush();
3689 } else {
3690 ob_end_clean();
3695 * Called when the processing is finished.
3697 public function finished() {
3698 ob_start();
3699 $this->trace->finished();
3700 $this->buffer .= ob_get_contents();
3701 if ($this->passthrough) {
3702 ob_end_flush();
3703 } else {
3704 ob_end_clean();
3709 * Reset internal text buffer.
3711 public function reset_buffer() {
3712 $this->buffer = '';
3716 * Return internal text buffer.
3717 * @return string buffered plain text
3719 public function get_buffer() {
3720 return $this->buffer;
3725 * Special type of trace that can be used for redirecting to multiple other traces.
3727 * @copyright Petr Skoda {@link http://skodak.org}
3728 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3729 * @package core
3731 class combined_progress_trace extends progress_trace {
3734 * An array of traces.
3735 * @var array
3737 protected $traces;
3740 * Constructs a new instance.
3742 * @param array $traces multiple traces
3744 public function __construct(array $traces) {
3745 $this->traces = $traces;
3749 * Output an progress message in whatever format.
3751 * @param string $message the message to output.
3752 * @param integer $depth indent depth for this message.
3754 public function output($message, $depth = 0) {
3755 foreach ($this->traces as $trace) {
3756 $trace->output($message, $depth);
3761 * Called when the processing is finished.
3763 public function finished() {
3764 foreach ($this->traces as $trace) {
3765 $trace->finished();
3771 * Returns a localized sentence in the current language summarizing the current password policy
3773 * @todo this should be handled by a function/method in the language pack library once we have a support for it
3774 * @uses $CFG
3775 * @return string
3777 function print_password_policy() {
3778 global $CFG;
3780 $message = '';
3781 if (!empty($CFG->passwordpolicy)) {
3782 $messages = array();
3783 if (!empty($CFG->minpasswordlength)) {
3784 $messages[] = get_string('informminpasswordlength', 'auth', $CFG->minpasswordlength);
3786 if (!empty($CFG->minpassworddigits)) {
3787 $messages[] = get_string('informminpassworddigits', 'auth', $CFG->minpassworddigits);
3789 if (!empty($CFG->minpasswordlower)) {
3790 $messages[] = get_string('informminpasswordlower', 'auth', $CFG->minpasswordlower);
3792 if (!empty($CFG->minpasswordupper)) {
3793 $messages[] = get_string('informminpasswordupper', 'auth', $CFG->minpasswordupper);
3795 if (!empty($CFG->minpasswordnonalphanum)) {
3796 $messages[] = get_string('informminpasswordnonalphanum', 'auth', $CFG->minpasswordnonalphanum);
3799 // Fire any additional password policy functions from plugins.
3800 // Callbacks must return an array of message strings.
3801 $pluginsfunction = get_plugins_with_function('print_password_policy');
3802 foreach ($pluginsfunction as $plugintype => $plugins) {
3803 foreach ($plugins as $pluginfunction) {
3804 $messages = array_merge($messages, $pluginfunction());
3808 $messages = join(', ', $messages); // This is ugly but we do not have anything better yet...
3809 // Check if messages is empty before outputting any text.
3810 if ($messages != '') {
3811 $message = get_string('informpasswordpolicy', 'auth', $messages);
3814 return $message;
3818 * Get the value of a help string fully prepared for display in the current language.
3820 * @param string $identifier The identifier of the string to search for.
3821 * @param string $component The module the string is associated with.
3822 * @param boolean $ajax Whether this help is called from an AJAX script.
3823 * This is used to influence text formatting and determines
3824 * which format to output the doclink in.
3825 * @param string|object|array $a An object, string or number that can be used
3826 * within translation strings
3827 * @return stdClass An object containing:
3828 * - heading: Any heading that there may be for this help string.
3829 * - text: The wiki-formatted help string.
3830 * - doclink: An object containing a link, the linktext, and any additional
3831 * CSS classes to apply to that link. Only present if $ajax = false.
3832 * - completedoclink: A text representation of the doclink. Only present if $ajax = true.
3834 function get_formatted_help_string($identifier, $component, $ajax = false, $a = null) {
3835 global $CFG, $OUTPUT;
3836 $sm = get_string_manager();
3838 // Do not rebuild caches here!
3839 // Devs need to learn to purge all caches after any change or disable $CFG->langstringcache.
3841 $data = new stdClass();
3843 if ($sm->string_exists($identifier, $component)) {
3844 $data->heading = format_string(get_string($identifier, $component));
3845 } else {
3846 // Gracefully fall back to an empty string.
3847 $data->heading = '';
3850 if ($sm->string_exists($identifier . '_help', $component)) {
3851 $options = new stdClass();
3852 $options->trusted = false;
3853 $options->noclean = false;
3854 $options->smiley = false;
3855 $options->filter = false;
3856 $options->para = true;
3857 $options->newlines = false;
3858 $options->overflowdiv = !$ajax;
3860 // Should be simple wiki only MDL-21695.
3861 $data->text = format_text(get_string($identifier.'_help', $component, $a), FORMAT_MARKDOWN, $options);
3863 $helplink = $identifier . '_link';
3864 if ($sm->string_exists($helplink, $component)) { // Link to further info in Moodle docs.
3865 $link = get_string($helplink, $component);
3866 $linktext = get_string('morehelp');
3868 $data->doclink = new stdClass();
3869 $url = new moodle_url(get_docs_url($link));
3870 if ($ajax) {
3871 $data->doclink->link = $url->out();
3872 $data->doclink->linktext = $linktext;
3873 $data->doclink->class = ($CFG->doctonewwindow) ? 'helplinkpopup' : '';
3874 } else {
3875 $data->completedoclink = html_writer::tag('div', $OUTPUT->doc_link($link, $linktext),
3876 array('class' => 'helpdoclink'));
3879 } else {
3880 $data->text = html_writer::tag('p',
3881 html_writer::tag('strong', 'TODO') . ": missing help string [{$identifier}_help, {$component}]");
3883 return $data;