2 // This file is part of Moodle - http://moodle.org/
4 // Moodle is free software: you can redistribute it and/or modify
5 // it under the terms of the GNU General Public License as published by
6 // the Free Software Foundation, either version 3 of the License, or
7 // (at your option) any later version.
9 // Moodle is distributed in the hope that it will be useful,
10 // but WITHOUT ANY WARRANTY; without even the implied warranty of
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 // GNU General Public License for more details.
14 // You should have received a copy of the GNU General Public License
15 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
18 * Library of functions for web output
20 * Library of all general-purpose Moodle PHP functions and constants
21 * that produce HTML output
23 * Other main libraries:
24 * - datalib.php - functions that access the database.
25 * - moodlelib.php - general-purpose Moodle functions.
29 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
30 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
33 use Psr\Http\Message\UriInterface
;
35 defined('MOODLE_INTERNAL') ||
die();
39 // Define text formatting types ... eventually we can add Wiki, BBcode etc.
42 * Does all sorts of transformations and filtering.
44 define('FORMAT_MOODLE', '0');
47 * Plain HTML (with some tags stripped).
49 define('FORMAT_HTML', '1');
52 * Plain text (even tags are printed in full).
54 define('FORMAT_PLAIN', '2');
57 * Wiki-formatted text.
58 * Deprecated: left here just to note that '3' is not used (at the moment)
59 * and to catch any latent wiki-like text (which generates an error)
60 * @deprecated since 2005!
62 define('FORMAT_WIKI', '3');
65 * Markdown-formatted text http://daringfireball.net/projects/markdown/
67 define('FORMAT_MARKDOWN', '4');
70 * A moodle_url comparison using this flag will return true if the base URLs match, params are ignored.
72 define('URL_MATCH_BASE', 0);
75 * A moodle_url comparison using this flag will return true if the base URLs match and the params of url1 are part of url2.
77 define('URL_MATCH_PARAMS', 1);
80 * A moodle_url comparison using this flag will return true if the two URLs are identical, except for the order of the params.
82 define('URL_MATCH_EXACT', 2);
87 * Add quotes to HTML characters.
89 * Returns $var with HTML characters (like "<", ">", etc.) properly quoted.
90 * Related function {@link p()} simply prints the output of this function.
92 * @param string $var the string potentially containing HTML characters
100 if ($var === null ||
$var === '') {
105 '/&#(\d+|x[0-9a-f]+);/i', '&#$1;',
106 htmlspecialchars($var, ENT_QUOTES | ENT_HTML401 | ENT_SUBSTITUTE
)
111 * Add quotes to HTML characters.
113 * Prints $var with HTML characters (like "<", ">", etc.) properly quoted.
114 * This function simply calls & displays {@link s()}.
117 * @param string $var the string potentially containing HTML characters
124 * Does proper javascript quoting.
126 * Do not use addslashes anymore, because it does not work when magic_quotes_sybase is enabled.
128 * @param mixed $var String, Array, or Object to add slashes to
129 * @return mixed quoted result
131 function addslashes_js($var) {
132 if (is_string($var)) {
133 $var = str_replace('\\', '\\\\', $var);
134 $var = str_replace(array('\'', '"', "\n", "\r", "\0"), array('\\\'', '\\"', '\\n', '\\r', '\\0'), $var);
135 $var = str_replace('</', '<\/', $var); // XHTML compliance.
136 } else if (is_array($var)) {
137 $var = array_map('addslashes_js', $var);
138 } else if (is_object($var)) {
139 $a = get_object_vars($var);
140 foreach ($a as $key => $value) {
141 $a[$key] = addslashes_js($value);
149 * Remove query string from url.
151 * Takes in a URL and returns it without the querystring portion.
153 * @param string $url the url which may have a query string attached.
154 * @return string The remaining URL.
156 function strip_querystring($url) {
157 if ($url === null ||
$url === '') {
161 if ($commapos = strpos($url, '?')) {
162 return substr($url, 0, $commapos);
169 * Returns the name of the current script, WITH the querystring portion.
171 * This function is necessary because PHP_SELF and REQUEST_URI and SCRIPT_NAME
172 * return different things depending on a lot of things like your OS, Web
173 * server, and the way PHP is compiled (ie. as a CGI, module, ISAPI, etc.)
174 * <b>NOTE:</b> This function returns false if the global variables needed are not set.
176 * @return mixed String or false if the global variables needed are not set.
184 * Guesses the full URL of the current script.
186 * This function is using $PAGE->url, but may fall back to $FULLME which
187 * is constructed from PHP_SELF and REQUEST_URI or SCRIPT_NAME
189 * @return mixed full page URL string or false if unknown
191 function qualified_me() {
192 global $FULLME, $PAGE, $CFG;
194 if (isset($PAGE) and $PAGE->has_set_url()) {
195 // This is the only recommended way to find out current page.
196 return $PAGE->url
->out(false);
199 if ($FULLME === null) {
200 // CLI script most probably.
203 if (!empty($CFG->sslproxy
)) {
204 // Return only https links when using SSL proxy.
205 return preg_replace('/^http:/', 'https:', $FULLME, 1);
213 * Determines whether or not the Moodle site is being served over HTTPS.
215 * This is done simply by checking the value of $CFG->wwwroot, which seems
216 * to be the only reliable method.
218 * @return boolean True if site is served over HTTPS, false otherwise.
220 function is_https() {
223 return (strpos($CFG->wwwroot
, 'https://') === 0);
227 * Returns the cleaned local URL of the HTTP_REFERER less the URL query string parameters if required.
229 * @param bool $stripquery if true, also removes the query part of the url.
230 * @return string The resulting referer or empty string.
232 function get_local_referer($stripquery = true) {
233 if (isset($_SERVER['HTTP_REFERER'])) {
234 $referer = clean_param($_SERVER['HTTP_REFERER'], PARAM_LOCALURL
);
236 return strip_querystring($referer);
246 * Class for creating and manipulating urls.
248 * It can be used in moodle pages where config.php has been included without any further includes.
250 * It is useful for manipulating urls with long lists of params.
251 * One situation where it will be useful is a page which links to itself to perform various actions
252 * and / or to process form data. A moodle_url object :
253 * can be created for a page to refer to itself with all the proper get params being passed from page call to
254 * page call and methods can be used to output a url including all the params, optionally adding and overriding
255 * params and can also be used to
256 * - output the url without any get params
257 * - and output the params as hidden fields to be output within a form
259 * @copyright 2007 jamiesensei
260 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
266 * Scheme, ex.: http, https
269 protected $scheme = '';
275 protected $host = '';
278 * Port number, empty means default 80 or 443 in case of http.
281 protected $port = '';
284 * Username for http auth.
287 protected $user = '';
290 * Password for http auth.
293 protected $pass = '';
299 protected $path = '';
302 * Optional slash argument value.
305 protected $slashargument = '';
308 * Anchor, may be also empty, null means none.
311 protected $anchor = null;
314 * Url parameters as associative array.
317 protected $params = array();
320 * Create new instance of moodle_url.
322 * @param moodle_url|string $url - moodle_url means make a copy of another
323 * moodle_url and change parameters, string means full url or shortened
324 * form (ex.: '/course/view.php'). It is strongly encouraged to not include
325 * query string because it may result in double encoded values. Use the
326 * $params instead. For admin URLs, just use /admin/script.php, this
327 * class takes care of the $CFG->admin issue.
328 * @param array $params these params override current params or add new
329 * @param string $anchor The anchor to use as part of the URL if there is one.
330 * @throws moodle_exception
332 public function __construct($url, array $params = null, $anchor = null) {
335 if ($url instanceof moodle_url
) {
336 $this->scheme
= $url->scheme
;
337 $this->host
= $url->host
;
338 $this->port
= $url->port
;
339 $this->user
= $url->user
;
340 $this->pass
= $url->pass
;
341 $this->path
= $url->path
;
342 $this->slashargument
= $url->slashargument
;
343 $this->params
= $url->params
;
344 $this->anchor
= $url->anchor
;
348 // Detect if anchor used.
349 $apos = strpos($url, '#');
350 if ($apos !== false) {
351 $anchor = substr($url, $apos);
352 $anchor = ltrim($anchor, '#');
353 $this->set_anchor($anchor);
354 $url = substr($url, 0, $apos);
357 // Normalise shortened form of our url ex.: '/course/view.php'.
358 if (strpos($url, '/') === 0) {
359 $url = $CFG->wwwroot
.$url;
362 if ($CFG->admin
!== 'admin') {
363 if (strpos($url, "$CFG->wwwroot/admin/") === 0) {
364 $url = str_replace("$CFG->wwwroot/admin/", "$CFG->wwwroot/$CFG->admin/", $url);
369 $parts = parse_url($url);
370 if ($parts === false) {
371 throw new moodle_exception('invalidurl');
373 if (isset($parts['query'])) {
374 // Note: the values may not be correctly decoded, url parameters should be always passed as array.
375 parse_str(str_replace('&', '&', $parts['query']), $this->params
);
377 unset($parts['query']);
378 foreach ($parts as $key => $value) {
379 $this->$key = $value;
382 // Detect slashargument value from path - we do not support directory names ending with .php.
383 $pos = strpos($this->path
, '.php/');
384 if ($pos !== false) {
385 $this->slashargument
= substr($this->path
, $pos +
4);
386 $this->path
= substr($this->path
, 0, $pos +
4);
390 $this->params($params);
391 if ($anchor !== null) {
392 $this->anchor
= (string)$anchor;
397 * Add an array of params to the params for this url.
399 * The added params override existing ones if they have the same name.
401 * @param array $params Defaults to null. If null then returns all params.
402 * @return array Array of Params for url.
403 * @throws coding_exception
405 public function params(array $params = null) {
406 $params = (array)$params;
408 foreach ($params as $key => $value) {
410 throw new coding_exception('Url parameters can not have numeric keys!');
412 if (!is_string($value)) {
413 if (is_array($value)) {
414 throw new coding_exception('Url parameters values can not be arrays!');
416 if (is_object($value) and !method_exists($value, '__toString')) {
417 throw new coding_exception('Url parameters values can not be objects, unless __toString() is defined!');
420 $this->params
[$key] = (string)$value;
422 return $this->params
;
426 * Remove all params if no arguments passed.
427 * Remove selected params if arguments are passed.
429 * Can be called as either remove_params('param1', 'param2')
430 * or remove_params(array('param1', 'param2')).
432 * @param string[]|string $params,... either an array of param names, or 1..n string params to remove as args.
433 * @return array url parameters
435 public function remove_params($params = null) {
436 if (!is_array($params)) {
437 $params = func_get_args();
439 foreach ($params as $param) {
440 unset($this->params
[$param]);
442 return $this->params
;
446 * Remove all url parameters.
448 * @todo remove the unused param.
449 * @param array $params Unused param
452 public function remove_all_params($params = null) {
453 $this->params
= array();
454 $this->slashargument
= '';
458 * Add a param to the params for this url.
460 * The added param overrides existing one if they have the same name.
462 * @param string $paramname name
463 * @param string $newvalue Param value. If new value specified current value is overriden or parameter is added
464 * @return mixed string parameter value, null if parameter does not exist
466 public function param($paramname, $newvalue = '') {
467 if (func_num_args() > 1) {
469 $this->params(array($paramname => $newvalue));
471 if (isset($this->params
[$paramname])) {
472 return $this->params
[$paramname];
479 * Merges parameters and validates them
481 * @param array $overrideparams
482 * @return array merged parameters
483 * @throws coding_exception
485 protected function merge_overrideparams(array $overrideparams = null) {
486 $overrideparams = (array)$overrideparams;
487 $params = $this->params
;
488 foreach ($overrideparams as $key => $value) {
490 throw new coding_exception('Overridden parameters can not have numeric keys!');
492 if (is_array($value)) {
493 throw new coding_exception('Overridden parameters values can not be arrays!');
495 if (is_object($value) and !method_exists($value, '__toString')) {
496 throw new coding_exception('Overridden parameters values can not be objects, unless __toString() is defined!');
498 $params[$key] = (string)$value;
504 * Get the params as as a query string.
506 * This method should not be used outside of this method.
508 * @param bool $escaped Use & as params separator instead of plain &
509 * @param array $overrideparams params to add to the output params, these
510 * override existing ones with the same name.
511 * @return string query string that can be added to a url.
513 public function get_query_string($escaped = true, array $overrideparams = null) {
515 if ($overrideparams !== null) {
516 $params = $this->merge_overrideparams($overrideparams);
518 $params = $this->params
;
520 foreach ($params as $key => $val) {
521 if (is_array($val)) {
522 foreach ($val as $index => $value) {
523 $arr[] = rawurlencode($key.'['.$index.']')."=".rawurlencode($value);
526 if (isset($val) && $val !== '') {
527 $arr[] = rawurlencode($key)."=".rawurlencode($val);
529 $arr[] = rawurlencode($key);
534 return implode('&', $arr);
536 return implode('&', $arr);
541 * Get the url params as an array of key => value pairs.
543 * This helps in handling cases where url params contain arrays.
545 * @return array params array for templates.
547 public function export_params_for_template(): array {
549 foreach ($this->params
as $key => $val) {
550 if (is_array($val)) {
551 foreach ($val as $index => $value) {
552 $data[] = ['name' => $key.'['.$index.']', 'value' => $value];
555 $data[] = ['name' => $key, 'value' => $val];
562 * Shortcut for printing of encoded URL.
566 public function __toString() {
567 return $this->out(true);
573 * If you use the returned URL in HTML code, you want the escaped ampersands. If you use
574 * the returned URL in HTTP headers, you want $escaped=false.
576 * @param bool $escaped Use & as params separator instead of plain &
577 * @param array $overrideparams params to add to the output url, these override existing ones with the same name.
578 * @return string Resulting URL
580 public function out($escaped = true, array $overrideparams = null) {
584 if (!is_bool($escaped)) {
585 debugging('Escape parameter must be of type boolean, '.gettype($escaped).' given instead.');
590 // Allow url's to be rewritten by a plugin.
591 if (isset($CFG->urlrewriteclass
) && !isset($CFG->upgraderunning
)) {
592 $class = $CFG->urlrewriteclass
;
593 $pluginurl = $class::url_rewrite($url);
594 if ($pluginurl instanceof moodle_url
) {
599 return $url->raw_out($escaped, $overrideparams);
604 * Output url without any rewrites
606 * This is identical in signature and use to out() but doesn't call the rewrite handler.
608 * @param bool $escaped Use & as params separator instead of plain &
609 * @param array $overrideparams params to add to the output url, these override existing ones with the same name.
610 * @return string Resulting URL
612 public function raw_out($escaped = true, array $overrideparams = null) {
613 if (!is_bool($escaped)) {
614 debugging('Escape parameter must be of type boolean, '.gettype($escaped).' given instead.');
617 $uri = $this->out_omit_querystring().$this->slashargument
;
619 $querystring = $this->get_query_string($escaped, $overrideparams);
620 if ($querystring !== '') {
621 $uri .= '?' . $querystring;
624 $uri .= $this->get_encoded_anchor();
630 * Encode the anchor according to RFC 3986.
632 * @return string The encoded anchor
634 public function get_encoded_anchor(): string {
635 if (is_null($this->anchor
)) {
639 // RFC 3986 allows the following characters in a fragment without them being encoded:
640 // pct-encoded: "%" HEXDIG HEXDIG
641 // unreserved: ALPHA / DIGIT / "-" / "." / "_" / "~" /
642 // sub-delims: "!" / "$" / "&" / "'" / "(" / ")" / "*" / "+" / "," / ";" / "=" / ":" / "@"
643 // fragment: "/" / "?"
645 // All other characters should be encoded.
646 // These should not be encoded in the fragment unless they were already encoded.
648 // The following characters are allowed in the fragment without encoding.
649 // In addition to this list is pct-encoded, but we can't easily handle this with a regular expression.
650 $allowed = 'a-zA-Z0-9\\-._~!$&\'()*+,;=:@\/?';
653 $remainder = $this->anchor
;
655 // Split the string on any %.
656 $parts = explode('%', $remainder, 2);
657 $anchorparts = array_shift($parts);
659 // The first part can go through our preg_replace_callback to quote any relevant characters.
660 $anchor .= preg_replace_callback(
661 '/[^' . $allowed . ']/',
662 fn ($matches) => rawurlencode($matches[0]),
666 // The second part _might_ be a valid pct-encoded character.
667 if (count($parts) === 0) {
671 // If the second part is a valid pct-encoded character, append it to the anchor.
672 $remainder = array_shift($parts);
673 if (preg_match('/^[a-fA-F0-9]{2}/', $remainder, $matches)) {
674 $anchor .= "%{$matches[0]}";
675 $remainder = substr($remainder, 2);
677 // This was not a valid pct-encoded character. Encode the % and continue with the next part.
678 $anchor .= rawurlencode('%');
680 } while (strlen($remainder) > 0);
686 * Returns url without parameters, everything before '?'.
688 * @param bool $includeanchor if {@link self::anchor} is defined, should it be returned?
691 public function out_omit_querystring($includeanchor = false) {
693 $uri = $this->scheme ?
$this->scheme
.':'.((strtolower($this->scheme
) == 'mailto') ?
'':'//'): '';
694 $uri .= $this->user ?
$this->user
.($this->pass?
':'.$this->pass
:'').'@':'';
695 $uri .= $this->host ?
$this->host
: '';
696 $uri .= $this->port ?
':'.$this->port
: '';
697 $uri .= $this->path ?
$this->path
: '';
698 if ($includeanchor) {
699 $uri .= $this->get_encoded_anchor();
706 * Compares this moodle_url with another.
708 * See documentation of constants for an explanation of the comparison flags.
710 * @param moodle_url $url The moodle_url object to compare
711 * @param int $matchtype The type of comparison (URL_MATCH_BASE, URL_MATCH_PARAMS, URL_MATCH_EXACT)
714 public function compare(moodle_url
$url, $matchtype = URL_MATCH_EXACT
) {
716 $baseself = $this->out_omit_querystring();
717 $baseother = $url->out_omit_querystring();
719 // Append index.php if there is no specific file.
720 if (substr($baseself, -1) == '/') {
721 $baseself .= 'index.php';
723 if (substr($baseother, -1) == '/') {
724 $baseother .= 'index.php';
727 // Compare the two base URLs.
728 if ($baseself != $baseother) {
732 if ($matchtype == URL_MATCH_BASE
) {
736 $urlparams = $url->params();
737 foreach ($this->params() as $param => $value) {
738 if ($param == 'sesskey') {
741 if (!array_key_exists($param, $urlparams) ||
$urlparams[$param] != $value) {
746 if ($matchtype == URL_MATCH_PARAMS
) {
750 foreach ($urlparams as $param => $value) {
751 if ($param == 'sesskey') {
754 if (!array_key_exists($param, $this->params()) ||
$this->param($param) != $value) {
759 if ($url->anchor
!== $this->anchor
) {
767 * Sets the anchor for the URI (the bit after the hash)
769 * @param string $anchor null means remove previous
771 public function set_anchor($anchor) {
772 if (is_null($anchor)) {
774 $this->anchor
= null;
776 $this->anchor
= $anchor;
781 * Sets the scheme for the URI (the bit before ://)
783 * @param string $scheme
785 public function set_scheme($scheme) {
786 // See http://www.ietf.org/rfc/rfc3986.txt part 3.1.
787 if (preg_match('/^[a-zA-Z][a-zA-Z0-9+.-]*$/', $scheme)) {
788 $this->scheme
= $scheme;
790 throw new coding_exception('Bad URL scheme.');
795 * Sets the url slashargument value.
797 * @param string $path usually file path
798 * @param string $parameter name of page parameter if slasharguments not supported
799 * @param bool $supported usually null, then it depends on $CFG->slasharguments, use true or false for other servers
802 public function set_slashargument($path, $parameter = 'file', $supported = null) {
804 if (is_null($supported)) {
805 $supported = !empty($CFG->slasharguments
);
809 $parts = explode('/', $path);
810 $parts = array_map('rawurlencode', $parts);
811 $path = implode('/', $parts);
812 $this->slashargument
= $path;
813 unset($this->params
[$parameter]);
816 $this->slashargument
= '';
817 $this->params
[$parameter] = $path;
821 // Static factory methods.
824 * Create a new moodle_url instance from a UriInterface.
826 * @param UriInterface $uri
829 public static function from_uri(UriInterface
$uri): self
{
831 url
: $uri->getScheme() . '://' . $uri->getAuthority() . $uri->getPath(),
832 anchor
: $uri->getFragment() ?
: null,
835 $params = $uri->getQuery();
836 foreach (explode('&', $params) as $param) {
837 $url->param(...explode('=', $param, 2));
844 * General moodle file url.
846 * @param string $urlbase the script serving the file
847 * @param string $path
848 * @param bool $forcedownload
851 public static function make_file_url($urlbase, $path, $forcedownload = false) {
853 if ($forcedownload) {
854 $params['forcedownload'] = 1;
856 $url = new moodle_url($urlbase, $params);
857 $url->set_slashargument($path);
862 * Factory method for creation of url pointing to plugin file.
864 * Please note this method can be used only from the plugins to
865 * create urls of own files, it must not be used outside of plugins!
867 * @param int $contextid
868 * @param string $component
869 * @param string $area
870 * @param ?int $itemid
871 * @param string $pathname
872 * @param string $filename
873 * @param bool $forcedownload
874 * @param mixed $includetoken Whether to use a user token when displaying this group image.
875 * True indicates to generate a token for current user, and integer value indicates to generate a token for the
876 * user whose id is the value indicated.
877 * If the group picture is included in an e-mail or some other location where the audience is a specific
878 * user who will not be logged in when viewing, then we use a token to authenticate the user.
881 public static function make_pluginfile_url($contextid, $component, $area, $itemid, $pathname, $filename,
882 $forcedownload = false, $includetoken = false) {
888 $urlbase = "$CFG->wwwroot/tokenpluginfile.php";
889 $userid = $includetoken === true ?
$USER->id
: $includetoken;
890 $token = get_user_key('core_files', $userid);
891 if ($CFG->slasharguments
) {
895 $urlbase = "$CFG->wwwroot/pluginfile.php";
897 $path[] = $contextid;
898 $path[] = $component;
901 if ($itemid !== null) {
905 $path = "/" . implode('/', $path) . "{$pathname}{$filename}";
907 $url = self
::make_file_url($urlbase, $path, $forcedownload, $includetoken);
908 if ($includetoken && empty($CFG->slasharguments
)) {
909 $url->param('token', $token);
915 * Factory method for creation of url pointing to plugin file.
916 * This method is the same that make_pluginfile_url but pointing to the webservice pluginfile.php script.
917 * It should be used only in external functions.
920 * @param int $contextid
921 * @param string $component
922 * @param string $area
924 * @param string $pathname
925 * @param string $filename
926 * @param bool $forcedownload
929 public static function make_webservice_pluginfile_url($contextid, $component, $area, $itemid, $pathname, $filename,
930 $forcedownload = false) {
932 $urlbase = "$CFG->wwwroot/webservice/pluginfile.php";
933 if ($itemid === null) {
934 return self
::make_file_url($urlbase, "/$contextid/$component/$area".$pathname.$filename, $forcedownload);
936 return self
::make_file_url($urlbase, "/$contextid/$component/$area/$itemid".$pathname.$filename, $forcedownload);
941 * Factory method for creation of url pointing to draft file of current user.
943 * @param int $draftid draft item id
944 * @param string $pathname
945 * @param string $filename
946 * @param bool $forcedownload
949 public static function make_draftfile_url($draftid, $pathname, $filename, $forcedownload = false) {
951 $urlbase = "$CFG->wwwroot/draftfile.php";
952 $context = context_user
::instance($USER->id
);
954 return self
::make_file_url($urlbase, "/$context->id/user/draft/$draftid".$pathname.$filename, $forcedownload);
958 * Factory method for creating of links to legacy course files.
960 * @param int $courseid
961 * @param string $filepath
962 * @param bool $forcedownload
965 public static function make_legacyfile_url($courseid, $filepath, $forcedownload = false) {
968 $urlbase = "$CFG->wwwroot/file.php";
969 return self
::make_file_url($urlbase, '/'.$courseid.'/'.$filepath, $forcedownload);
973 * Checks if URL is relative to $CFG->wwwroot.
975 * @return bool True if URL is relative to $CFG->wwwroot; otherwise, false.
977 public function is_local_url(): bool {
981 // Does URL start with wwwroot? Otherwise, URL isn't relative to wwwroot.
982 return ( ($url === $CFG->wwwroot
) ||
(strpos($url, $CFG->wwwroot
.'/') === 0) );
986 * Returns URL as relative path from $CFG->wwwroot
988 * Can be used for passing around urls with the wwwroot stripped
990 * @param boolean $escaped Use & as params separator instead of plain &
991 * @param array $overrideparams params to add to the output url, these override existing ones with the same name.
992 * @return string Resulting URL
993 * @throws coding_exception if called on a non-local url
995 public function out_as_local_url($escaped = true, array $overrideparams = null) {
998 // URL should be relative to wwwroot. If not then throw exception.
999 if ($this->is_local_url()) {
1000 $url = $this->out($escaped, $overrideparams);
1001 $localurl = substr($url, strlen($CFG->wwwroot
));
1002 return !empty($localurl) ?
$localurl : '';
1004 throw new coding_exception('out_as_local_url called on a non-local URL');
1009 * Returns the 'path' portion of a URL. For example, if the URL is
1010 * http://www.example.org:447/my/file/is/here.txt?really=1 then this will
1011 * return '/my/file/is/here.txt'.
1013 * By default the path includes slash-arguments (for example,
1014 * '/myfile.php/extra/arguments') so it is what you would expect from a
1015 * URL path. If you don't want this behaviour, you can opt to exclude the
1016 * slash arguments. (Be careful: if the $CFG variable slasharguments is
1017 * disabled, these URLs will have a different format and you may need to
1018 * look at the 'file' parameter too.)
1020 * @param bool $includeslashargument If true, includes slash arguments
1021 * @return string Path of URL
1023 public function get_path($includeslashargument = true) {
1024 return $this->path
. ($includeslashargument ?
$this->slashargument
: '');
1028 * Returns a given parameter value from the URL.
1030 * @param string $name Name of parameter
1031 * @return string Value of parameter or null if not set
1033 public function get_param($name) {
1034 if (array_key_exists($name, $this->params
)) {
1035 return $this->params
[$name];
1042 * Returns the 'scheme' portion of a URL. For example, if the URL is
1043 * http://www.example.org:447/my/file/is/here.txt?really=1 then this will
1044 * return 'http' (without the colon).
1046 * @return string Scheme of the URL.
1048 public function get_scheme() {
1049 return $this->scheme
;
1053 * Returns the 'host' portion of a URL. For example, if the URL is
1054 * http://www.example.org:447/my/file/is/here.txt?really=1 then this will
1055 * return 'www.example.org'.
1057 * @return string Host of the URL.
1059 public function get_host() {
1064 * Returns the 'port' portion of a URL. For example, if the URL is
1065 * http://www.example.org:447/my/file/is/here.txt?really=1 then this will
1068 * @return string Port of the URL.
1070 public function get_port() {
1076 * Determine if there is data waiting to be processed from a form
1078 * Used on most forms in Moodle to check for data
1079 * Returns the data as an object, if it's found.
1080 * This object can be used in foreach loops without
1081 * casting because it's cast to (array) automatically
1083 * Checks that submitted POST data exists and returns it as object.
1085 * @return mixed false or object
1087 function data_submitted() {
1089 if (empty($_POST)) {
1092 return (object)fix_utf8($_POST);
1097 * Given some normal text this function will break up any
1098 * long words to a given size by inserting the given character
1100 * It's multibyte savvy and doesn't change anything inside html tags.
1102 * @param string $string the string to be modified
1103 * @param int $maxsize maximum length of the string to be returned
1104 * @param string $cutchar the string used to represent word breaks
1107 function break_up_long_words($string, $maxsize=20, $cutchar=' ') {
1109 // First of all, save all the tags inside the text to skip them.
1111 filter_save_tags($string, $tags);
1113 // Process the string adding the cut when necessary.
1115 $length = core_text
::strlen($string);
1118 for ($i=0; $i<$length; $i++
) {
1119 $char = core_text
::substr($string, $i, 1);
1120 if ($char == ' ' or $char == "\t" or $char == "\n" or $char == "\r" or $char == "<" or $char == ">") {
1124 if ($wordlength > $maxsize) {
1125 $output .= $cutchar;
1132 // Finally load the tags back again.
1133 if (!empty($tags)) {
1134 $output = str_replace(array_keys($tags), $tags, $output);
1141 * Try and close the current window using JavaScript, either immediately, or after a delay.
1143 * Echo's out the resulting XHTML & javascript
1145 * @param integer $delay a delay in seconds before closing the window. Default 0.
1146 * @param boolean $reloadopener if true, we will see if this window was a pop-up, and try
1147 * to reload the parent window before this one closes.
1149 function close_window($delay = 0, $reloadopener = false) {
1150 global $PAGE, $OUTPUT;
1152 if (!$PAGE->headerprinted
) {
1153 $PAGE->set_title(get_string('closewindow'));
1154 echo $OUTPUT->header();
1156 $OUTPUT->container_end_all(false);
1159 if ($reloadopener) {
1160 // Trigger the reload immediately, even if the reload is after a delay.
1161 $PAGE->requires
->js_function_call('window.opener.location.reload', array(true));
1163 $OUTPUT->notification(get_string('windowclosing'), 'notifysuccess');
1165 $PAGE->requires
->js_function_call('close_window', array(new stdClass()), false, $delay);
1167 echo $OUTPUT->footer();
1172 * Returns a string containing a link to the user documentation for the current page.
1174 * Also contains an icon by default. Shown to teachers and admin only.
1176 * @param string $text The text to be displayed for the link
1177 * @return string The link to user documentation for this current page
1179 function page_doc_link($text='') {
1180 global $OUTPUT, $PAGE;
1181 $path = page_get_doc_link_path($PAGE);
1185 return $OUTPUT->doc_link($path, $text);
1189 * Returns the path to use when constructing a link to the docs.
1191 * @since Moodle 2.5.1 2.6
1192 * @param moodle_page $page
1195 function page_get_doc_link_path(moodle_page
$page) {
1198 if (empty($CFG->docroot
) ||
during_initial_install()) {
1201 if (!has_capability('moodle/site:doclinks', $page->context
)) {
1205 $path = $page->docspath
;
1214 * Validates an email to make sure it makes sense.
1216 * @param string $address The email address to validate.
1219 function validate_email($address) {
1222 if ($address === null ||
$address === false ||
$address === '') {
1226 require_once("{$CFG->libdir}/phpmailer/moodle_phpmailer.php");
1228 return moodle_phpmailer
::validateAddress($address ??
'') && !preg_match('/[<>]/', $address);
1232 * Extracts file argument either from file parameter or PATH_INFO
1234 * Note: $scriptname parameter is not needed anymore
1236 * @return string file path (only safe characters)
1238 function get_file_argument() {
1241 $relativepath = false;
1242 $hasforcedslashargs = false;
1244 if (isset($_SERVER['REQUEST_URI']) && !empty($_SERVER['REQUEST_URI'])) {
1245 // Checks whether $_SERVER['REQUEST_URI'] contains '/pluginfile.php/'
1246 // instead of '/pluginfile.php?', when serving a file from e.g. mod_imscp or mod_scorm.
1247 if ((strpos($_SERVER['REQUEST_URI'], '/pluginfile.php/') !== false)
1248 && isset($_SERVER['PATH_INFO']) && !empty($_SERVER['PATH_INFO'])) {
1249 // Exclude edge cases like '/pluginfile.php/?file='.
1250 $args = explode('/', ltrim($_SERVER['PATH_INFO'], '/'));
1251 $hasforcedslashargs = (count($args) > 2); // Always at least: context, component and filearea.
1254 if (!$hasforcedslashargs) {
1255 $relativepath = optional_param('file', false, PARAM_PATH
);
1258 if ($relativepath !== false and $relativepath !== '') {
1259 return $relativepath;
1261 $relativepath = false;
1263 // Then try extract file from the slasharguments.
1264 if (stripos($_SERVER['SERVER_SOFTWARE'], 'iis') !== false) {
1265 // NOTE: IIS tends to convert all file paths to single byte DOS encoding,
1266 // we can not use other methods because they break unicode chars,
1267 // the only ways are to use URL rewriting
1269 // to properly set the 'FastCGIUtf8ServerVariables' registry key.
1270 if (isset($_SERVER['PATH_INFO']) and $_SERVER['PATH_INFO'] !== '') {
1271 // Check that PATH_INFO works == must not contain the script name.
1272 if (strpos($_SERVER['PATH_INFO'], $SCRIPT) === false) {
1273 $relativepath = clean_param(urldecode($_SERVER['PATH_INFO']), PARAM_PATH
);
1277 // All other apache-like servers depend on PATH_INFO.
1278 if (isset($_SERVER['PATH_INFO'])) {
1279 if (isset($_SERVER['SCRIPT_NAME']) and strpos($_SERVER['PATH_INFO'], $_SERVER['SCRIPT_NAME']) === 0) {
1280 $relativepath = substr($_SERVER['PATH_INFO'], strlen($_SERVER['SCRIPT_NAME']));
1282 $relativepath = $_SERVER['PATH_INFO'];
1284 $relativepath = clean_param($relativepath, PARAM_PATH
);
1288 return $relativepath;
1292 * Just returns an array of text formats suitable for a popup menu
1296 function format_text_menu() {
1297 return array (FORMAT_MOODLE
=> get_string('formattext'),
1298 FORMAT_HTML
=> get_string('formathtml'),
1299 FORMAT_PLAIN
=> get_string('formatplain'),
1300 FORMAT_MARKDOWN
=> get_string('formatmarkdown'));
1304 * Given text in a variety of format codings, this function returns the text as safe HTML.
1306 * This function should mainly be used for long strings like posts,
1307 * answers, glossary items etc. For short strings {@link format_string()}.
1311 * trusted : If true the string won't be cleaned. Default false required noclean=true.
1312 * noclean : If true the string won't be cleaned, unless $CFG->forceclean is set. Default false required trusted=true.
1313 * filter : If true the string will be run through applicable filters as well. Default true.
1314 * para : If true then the returned string will be wrapped in div tags. Default true.
1315 * newlines : If true then lines newline breaks will be converted to HTML newline breaks. Default true.
1316 * context : The context that will be used for filtering.
1317 * overflowdiv : If set to true the formatted text will be encased in a div
1318 * with the class no-overflow before being returned. Default false.
1319 * allowid : If true then id attributes will not be removed, even when
1320 * using htmlpurifier. Default false.
1321 * blanktarget : If true all <a> tags will have target="_blank" added unless target is explicitly specified.
1324 * @param string $text The text to be formatted. This is raw text originally from user input.
1325 * @param int $format Identifier of the text format to be used
1326 * [FORMAT_MOODLE, FORMAT_HTML, FORMAT_PLAIN, FORMAT_MARKDOWN]
1327 * @param stdClass|array $options text formatting options
1328 * @param int $courseiddonotuse deprecated course id, use context option instead
1331 function format_text($text, $format = FORMAT_MOODLE
, $options = null, $courseiddonotuse = null) {
1334 // Manually include the formatting class for now until after the release after 4.5 LTS.
1335 require_once("{$CFG->libdir}/classes/formatting.php");
1337 if ($format === FORMAT_WIKI
) {
1338 // This format was deprecated in Moodle 1.5.
1339 throw new \
coding_exception(
1340 'Wiki-like formatting is not supported.'
1344 if ($options instanceof \core\context
) {
1345 // A common mistake has been to call this function with a context object.
1346 // This has never been expected, or nor supported.
1348 'The options argument should not be a context object directly. ' .
1349 ' Please pass an array with a context key instead.',
1352 $params['context'] = $options;
1357 $options = (array) $options;
1360 if (empty($CFG->version
) ||
$CFG->version
< 2013051400 ||
during_initial_install()) {
1361 // Do not filter anything during installation or before upgrade completes.
1362 $params['context'] = null;
1363 } else if ($options && isset($options['context'])) { // First by explicit passed context option.
1364 if (is_numeric($options['context'])) {
1365 // A contextid was passed.
1366 $params['context'] = \core\context
::instance_by_id($options['context']);
1367 } else if ($options['context'] instanceof \core\context
) {
1368 $params['context'] = $options['context'];
1371 'Unknown context passed to format_text(). Content will not be filtered.',
1376 // Unset the context from $options to prevent it overriding the configured value.
1377 unset($options['context']);
1378 } else if ($courseiddonotuse) {
1380 $params['context'] = \core\context\course
::instance($courseiddonotuse);
1382 "Passing a courseid to format_text() is deprecated, please pass a context instead.",
1387 $params['text'] = $text;
1390 // The smiley option was deprecated in Moodle 2.0.
1391 if (array_key_exists('smiley', $options)) {
1392 unset($options['smiley']);
1394 'The smiley option is deprecated and no longer used.',
1399 // The nocache option was deprecated in Moodle 2.3 in MDL-34347.
1400 if (array_key_exists('nocache', $options)) {
1401 unset($options['nocache']);
1403 'The nocache option is deprecated and no longer used.',
1423 $invalidoptions = array_diff(array_keys($options), $validoptions);
1424 if ($invalidoptions) {
1426 'The following options are not valid: %s',
1427 implode(', ', $invalidoptions),
1428 ), DEBUG_DEVELOPER
);
1429 foreach ($invalidoptions as $option) {
1430 unset($options[$option]);
1434 foreach ($options as $option => $value) {
1435 $params[$option] = $value;
1438 // The noclean option has been renamed to clean.
1439 if (array_key_exists('noclean', $params)) {
1440 $params['clean'] = !$params['noclean'];
1441 unset($params['noclean']);
1445 if ($format !== null) {
1446 $params['format'] = $format;
1449 return \core\di
::get(\core\formatting
::class)->format_text(...$params);
1453 * Resets some data related to filters, called during upgrade or when general filter settings change.
1455 * @param bool $phpunitreset true means called from our PHPUnit integration test reset
1458 function reset_text_filters_cache($phpunitreset = false) {
1461 if ($phpunitreset) {
1462 // HTMLPurifier does not change, DB is already reset to defaults,
1463 // nothing to do here, the dataroot was cleared too.
1467 // The purge_all_caches() deals with cachedir and localcachedir purging,
1468 // the individual filter caches are invalidated as necessary elsewhere.
1470 // Update $CFG->filterall cache flag.
1471 if (empty($CFG->stringfilters
)) {
1472 set_config('filterall', 0);
1475 $installedfilters = core_component
::get_plugin_list('filter');
1476 $filters = explode(',', $CFG->stringfilters
);
1477 foreach ($filters as $filter) {
1478 if (isset($installedfilters[$filter])) {
1479 set_config('filterall', 1);
1483 set_config('filterall', 0);
1487 * Given a simple string, this function returns the string
1488 * processed by enabled string filters if $CFG->filterall is enabled
1490 * This function should be used to print short strings (non html) that
1491 * need filter processing e.g. activity titles, post subjects,
1492 * glossary concepts.
1494 * @staticvar bool $strcache
1495 * @param string $string The string to be filtered. Should be plain text, expect
1496 * possibly for multilang tags.
1497 * @param ?bool $striplinks To strip any link in the result text. Moodle 1.8 default changed from false to true! MDL-8713
1498 * @param array $options options array/object or courseid
1501 function format_string($string, $striplinks = true, $options = null) {
1504 // Manually include the formatting class for now until after the release after 4.5 LTS.
1505 require_once("{$CFG->libdir}/classes/formatting.php");
1508 'string' => $string,
1509 'striplinks' => (bool) $striplinks,
1512 // This method only expects either:
1513 // - an array of options;
1514 // - a stdClass of options to be cast to an array; or
1515 // - an integer courseid.
1516 if ($options instanceof \core\context
) {
1517 // A common mistake has been to call this function with a context object.
1518 // This has never been expected, or nor supported.
1520 'The options argument should not be a context object directly. ' .
1521 ' Please pass an array with a context key instead.',
1524 $params['context'] = $options;
1526 } else if (is_numeric($options)) {
1527 // Legacy courseid usage.
1528 $params['context'] = \core\context\course
::instance($options);
1530 } else if (is_array($options) ||
is_a($options, \stdClass
::class)) {
1531 $options = (array) $options;
1532 if (isset($options['context'])) {
1533 if (is_numeric($options['context'])) {
1534 // A contextid was passed usage.
1535 $params['context'] = \core\context
::instance_by_id($options['context']);
1536 } else if ($options['context'] instanceof \core\context
) {
1537 $params['context'] = $options['context'];
1540 'An invalid value for context was provided.',
1545 } else if ($options !== null) {
1546 // Something else was passed, so we'll just use an empty array.
1548 'The options argument should be an Array, or stdclass. %s passed.',
1550 ), DEBUG_DEVELOPER
);
1552 // Attempt to cast to array since we always used to, but throw in some debugging.
1553 $options = array_filter(
1555 fn ($key) => !is_numeric($key),
1556 ARRAY_FILTER_USE_KEY
,
1560 if (isset($options['filter'])) {
1561 $params['filter'] = (bool) $options['filter'];
1563 $params['filter'] = true;
1566 if (isset($options['escape'])) {
1567 $params['escape'] = (bool) $options['escape'];
1569 $params['escape'] = true;
1581 $invalidoptions = array_diff(array_keys($options), $validoptions);
1582 if ($invalidoptions) {
1584 'The following options are not valid: %s',
1585 implode(', ', $invalidoptions),
1586 ), DEBUG_DEVELOPER
);
1590 return \core\di
::get(\core\formatting
::class)->format_string(
1596 * Given a string, performs a negative lookahead looking for any ampersand character
1597 * that is not followed by a proper HTML entity. If any is found, it is replaced
1598 * by &. The string is then returned.
1600 * @param string $string
1603 function replace_ampersands_not_followed_by_entity($string) {
1604 return preg_replace("/\&(?![a-zA-Z0-9#]{1,8};)/", "&", $string ??
'');
1608 * Given a string, replaces all <a>.*</a> by .* and returns the string.
1610 * @param string $string
1613 function strip_links($string) {
1614 return preg_replace('/(<a\s[^>]+?>)(.+?)(<\/a>)/is', '$2', $string);
1618 * This expression turns links into something nice in a text format. (Russell Jungwirth)
1620 * @param string $string
1623 function wikify_links($string) {
1624 return preg_replace('~(<a [^<]*href=["|\']?([^ "\']*)["|\']?[^>]*>([^<]*)</a>)~i', '$3 [ $2 ]', $string);
1628 * Given text in a variety of format codings, this function returns the text as plain text suitable for plain email.
1630 * @param string $text The text to be formatted. This is raw text originally from user input.
1631 * @param int $format Identifier of the text format to be used
1632 * [FORMAT_MOODLE, FORMAT_HTML, FORMAT_PLAIN, FORMAT_WIKI, FORMAT_MARKDOWN]
1635 function format_text_email($text, $format) {
1644 // There should not be any of these any more!
1645 $text = wikify_links($text);
1646 return core_text
::entities_to_utf8(strip_tags($text), true);
1650 return html_to_text($text);
1654 case FORMAT_MARKDOWN
:
1656 $text = wikify_links($text);
1657 return core_text
::entities_to_utf8(strip_tags($text), true);
1663 * Formats activity intro text
1665 * @param string $module name of module
1666 * @param object $activity instance of activity
1667 * @param int $cmid course module id
1668 * @param bool $filter filter resulting html text
1671 function format_module_intro($module, $activity, $cmid, $filter=true) {
1673 require_once("$CFG->libdir/filelib.php");
1674 $context = context_module
::instance($cmid);
1675 $options = array('noclean' => true, 'para' => false, 'filter' => $filter, 'context' => $context, 'overflowdiv' => true);
1676 $intro = file_rewrite_pluginfile_urls($activity->intro
, 'pluginfile.php', $context->id
, 'mod_'.$module, 'intro', null);
1677 return trim(format_text($intro, $activity->introformat
, $options, null));
1681 * Removes the usage of Moodle files from a text.
1683 * In some rare cases we need to re-use a text that already has embedded links
1684 * to some files hosted within Moodle. But the new area in which we will push
1685 * this content does not support files... therefore we need to remove those files.
1687 * @param string $source The text
1688 * @return string The stripped text
1690 function strip_pluginfile_content($source) {
1691 $baseurl = '@@PLUGINFILE@@';
1692 // Looking for something like < .* "@@pluginfile@@.*" .* >
1693 $pattern = '$<[^<>]+["\']' . $baseurl . '[^"\']*["\'][^<>]*>$';
1694 $stripped = preg_replace($pattern, '', $source);
1695 // Use purify html to rebalence potentially mismatched tags and generally cleanup.
1696 return purify_html($stripped);
1700 * Legacy function, used for cleaning of old forum and glossary text only.
1702 * @param string $text text that may contain legacy TRUSTTEXT marker
1703 * @return string text without legacy TRUSTTEXT marker
1705 function trusttext_strip($text) {
1706 if (!is_string($text)) {
1707 // This avoids the potential for an endless loop below.
1708 throw new coding_exception('trusttext_strip parameter must be a string');
1710 while (true) { // Removing nested TRUSTTEXT.
1712 $text = str_replace('#####TRUSTTEXT#####', '', $text);
1713 if (strcmp($orig, $text) === 0) {
1720 * Must be called before editing of all texts with trust flag. Removes all XSS nasties from texts stored in database if needed.
1722 * @param stdClass $object data object with xxx, xxxformat and xxxtrust fields
1723 * @param string $field name of text field
1724 * @param context $context active context
1725 * @return stdClass updated $object
1727 function trusttext_pre_edit($object, $field, $context) {
1728 $trustfield = $field.'trust';
1729 $formatfield = $field.'format';
1731 if ($object->$formatfield == FORMAT_MARKDOWN
) {
1732 // We do not have a way to sanitise Markdown texts,
1733 // luckily editors for this format should not have XSS problems.
1737 if (!$object->$trustfield or !trusttext_trusted($context)) {
1738 $object->$field = clean_text($object->$field, $object->$formatfield);
1745 * Is current user trusted to enter no dangerous XSS in this context?
1747 * Please note the user must be in fact trusted everywhere on this server!!
1749 * @param context $context
1750 * @return bool true if user trusted
1752 function trusttext_trusted($context) {
1753 return (trusttext_active() and has_capability('moodle/site:trustcontent', $context));
1757 * Is trusttext feature active?
1761 function trusttext_active() {
1764 return !empty($CFG->enabletrusttext
);
1768 * Cleans raw text removing nasties.
1770 * Given raw text (eg typed in by a user) this function cleans it up and removes any nasty tags that could mess up
1771 * Moodle pages through XSS attacks.
1773 * The result must be used as a HTML text fragment, this function can not cleanup random
1774 * parts of html tags such as url or src attributes.
1776 * NOTE: the format parameter was deprecated because we can safely clean only HTML.
1778 * @param string $text The text to be cleaned
1779 * @param int|string $format deprecated parameter, should always contain FORMAT_HTML or FORMAT_MOODLE
1780 * @param array $options Array of options; currently only option supported is 'allowid' (if true,
1781 * does not remove id attributes when cleaning)
1782 * @return string The cleaned up text
1784 function clean_text($text, $format = FORMAT_HTML
, $options = array()) {
1785 $text = (string)$text;
1787 if ($format != FORMAT_HTML
and $format != FORMAT_HTML
) {
1788 // TODO: we need to standardise cleanup of text when loading it into editor first.
1789 // debugging('clean_text() is designed to work only with html');.
1792 if ($format == FORMAT_PLAIN
) {
1796 if (is_purify_html_necessary($text)) {
1797 $text = purify_html($text, $options);
1800 // Originally we tried to neutralise some script events here, it was a wrong approach because
1801 // it was trivial to work around that (for example using style based XSS exploits).
1802 // We must not give false sense of security here - all developers MUST understand how to use
1803 // rawurlencode(), htmlentities(), htmlspecialchars(), p(), s(), moodle_url, html_writer and friends!!!
1809 * Is it necessary to use HTMLPurifier?
1812 * @param string $text
1813 * @return bool false means html is safe and valid, true means use HTMLPurifier
1815 function is_purify_html_necessary($text) {
1820 if ($text === (string)((int)$text)) {
1824 if (strpos($text, '&') !== false or preg_match('|<[^pesb/]|', $text)) {
1825 // We need to normalise entities or other tags except p, em, strong and br present.
1829 $altered = htmlspecialchars($text, ENT_NOQUOTES
, 'UTF-8', true);
1830 if ($altered === $text) {
1831 // No < > or other special chars means this must be safe.
1835 // Let's try to convert back some safe html tags.
1836 $altered = preg_replace('|<p>(.*?)</p>|m', '<p>$1</p>', $altered);
1837 if ($altered === $text) {
1840 $altered = preg_replace('|<em>([^<>]+?)</em>|m', '<em>$1</em>', $altered);
1841 if ($altered === $text) {
1844 $altered = preg_replace('|<strong>([^<>]+?)</strong>|m', '<strong>$1</strong>', $altered);
1845 if ($altered === $text) {
1848 $altered = str_replace('<br />', '<br />', $altered);
1849 if ($altered === $text) {
1857 * KSES replacement cleaning function - uses HTML Purifier.
1859 * @param string $text The (X)HTML string to purify
1860 * @param array $options Array of options; currently only option supported is 'allowid' (if set,
1861 * does not remove id attributes when cleaning)
1864 function purify_html($text, $options = array()) {
1867 $text = (string)$text;
1869 static $purifiers = array();
1870 static $caches = array();
1872 // Purifier code can change only during major version upgrade.
1873 $version = empty($CFG->version
) ?
0 : $CFG->version
;
1874 $cachedir = "$CFG->localcachedir/htmlpurifier/$version";
1875 if (!file_exists($cachedir)) {
1876 // Purging of caches may remove the cache dir at any time,
1877 // luckily file_exists() results should be cached for all existing directories.
1878 $purifiers = array();
1880 gc_collect_cycles();
1882 make_localcache_directory('htmlpurifier', false);
1883 check_dir_exists($cachedir);
1886 $allowid = empty($options['allowid']) ?
0 : 1;
1887 $allowobjectembed = empty($CFG->allowobjectembed
) ?
0 : 1;
1889 $type = 'type_'.$allowid.'_'.$allowobjectembed;
1891 if (!array_key_exists($type, $caches)) {
1892 $caches[$type] = cache
::make('core', 'htmlpurifier', array('type' => $type));
1894 $cache = $caches[$type];
1896 // Add revision number and all options to the text key so that it is compatible with local cluster node caches.
1897 $key = "|$version|$allowobjectembed|$allowid|$text";
1898 $filteredtext = $cache->get($key);
1900 if ($filteredtext === true) {
1901 // The filtering did not change the text last time, no need to filter anything again.
1903 } else if ($filteredtext !== false) {
1904 return $filteredtext;
1907 if (empty($purifiers[$type])) {
1908 require_once $CFG->libdir
.'/htmlpurifier/HTMLPurifier.safe-includes.php';
1909 require_once $CFG->libdir
.'/htmlpurifier/locallib.php';
1910 $config = HTMLPurifier_Config
::createDefault();
1912 $config->set('HTML.DefinitionID', 'moodlehtml');
1913 $config->set('HTML.DefinitionRev', 7);
1914 $config->set('Cache.SerializerPath', $cachedir);
1915 $config->set('Cache.SerializerPermissions', $CFG->directorypermissions
);
1916 $config->set('Core.NormalizeNewlines', false);
1917 $config->set('Core.ConvertDocumentToFragment', true);
1918 $config->set('Core.Encoding', 'UTF-8');
1919 $config->set('HTML.Doctype', 'XHTML 1.0 Transitional');
1920 $config->set('URI.AllowedSchemes', array(
1929 'teamspeak' => true,
1934 $config->set('Attr.AllowedFrameTargets', array('_blank'));
1936 if ($allowobjectembed) {
1937 $config->set('HTML.SafeObject', true);
1938 $config->set('Output.FlashCompat', true);
1939 $config->set('HTML.SafeEmbed', true);
1943 $config->set('Attr.EnableID', true);
1946 if ($def = $config->maybeGetRawHTMLDefinition()) {
1947 $def->addElement('nolink', 'Inline', 'Flow', array()); // Skip our filters inside.
1948 $def->addElement('tex', 'Inline', 'Inline', array()); // Tex syntax, equivalent to $$xx$$.
1949 $def->addElement('algebra', 'Inline', 'Inline', array()); // Algebra syntax, equivalent to @@xx@@.
1950 $def->addElement('lang', 'Block', 'Flow', array(), array('lang'=>'CDATA')); // Original multilang style - only our hacked lang attribute.
1951 $def->addAttribute('span', 'xxxlang', 'CDATA'); // Current very problematic multilang.
1952 // Enable the bidirectional isolate element and its span equivalent.
1953 $def->addElement('bdi', 'Inline', 'Flow', 'Common');
1954 $def->addAttribute('span', 'dir', 'Enum#ltr,rtl,auto');
1957 // https://html.spec.whatwg.org/#the-video-element
1958 $def->addElement('video', 'Inline', 'Optional: #PCDATA | Flow | source | track', 'Common', [
1960 'crossorigin' => 'Enum#anonymous,use-credentials',
1962 'preload' => 'Enum#auto,metadata,none',
1963 'autoplay' => 'Bool',
1964 'playsinline' => 'Bool',
1967 'controls' => 'Bool',
1968 'width' => 'Length',
1969 'height' => 'Length',
1971 // https://html.spec.whatwg.org/#the-audio-element
1972 $def->addElement('audio', 'Inline', 'Optional: #PCDATA | Flow | source | track', 'Common', [
1974 'crossorigin' => 'Enum#anonymous,use-credentials',
1975 'preload' => 'Enum#auto,metadata,none',
1976 'autoplay' => 'Bool',
1979 'controls' => 'Bool'
1981 // https://html.spec.whatwg.org/#the-source-element
1982 $def->addElement('source', false, 'Empty', null, [
1986 // https://html.spec.whatwg.org/#the-track-element
1987 $def->addElement('track', false, 'Empty', null, [
1989 'kind' => 'Enum#subtitles,captions,descriptions,chapters,metadata',
1990 'srclang' => 'Text',
1992 'default' => 'Bool',
1995 // Use the built-in Ruby module to add annotation support.
1996 $def->manager
->addModule(new HTMLPurifier_HTMLModule_Ruby());
1999 $purifier = new HTMLPurifier($config);
2000 $purifiers[$type] = $purifier;
2002 $purifier = $purifiers[$type];
2005 $multilang = (strpos($text, 'class="multilang"') !== false);
2007 $filteredtext = $text;
2009 $filteredtextregex = '/<span(\s+lang="([a-zA-Z0-9_-]+)"|\s+class="multilang"){2}\s*>/';
2010 $filteredtext = preg_replace($filteredtextregex, '<span xxxlang="${2}">', $filteredtext);
2012 $filteredtext = (string)$purifier->purify($filteredtext);
2014 $filteredtext = preg_replace('/<span xxxlang="([a-zA-Z0-9_-]+)">/', '<span lang="${1}" class="multilang">', $filteredtext);
2017 if ($text === $filteredtext) {
2018 // No need to store the filtered text, next time we will just return unfiltered text
2019 // because it was not changed by purifying.
2020 $cache->set($key, true);
2022 $cache->set($key, $filteredtext);
2025 return $filteredtext;
2029 * Given plain text, makes it into HTML as nicely as possible.
2031 * May contain HTML tags already.
2033 * Do not abuse this function. It is intended as lower level formatting feature used
2034 * by {@link format_text()} to convert FORMAT_MOODLE to HTML. You are supposed
2035 * to call format_text() in most of cases.
2037 * @param string $text The string to convert.
2038 * @param boolean $smileyignored Was used to determine if smiley characters should convert to smiley images, ignored now
2039 * @param boolean $para If true then the returned string will be wrapped in div tags
2040 * @param boolean $newlines If true then lines newline breaks will be converted to HTML newline breaks.
2043 function text_to_html($text, $smileyignored = null, $para = true, $newlines = true) {
2044 // Remove any whitespace that may be between HTML tags.
2045 $text = preg_replace("~>([[:space:]]+)<~i", "><", $text);
2047 // Remove any returns that precede or follow HTML tags.
2048 $text = preg_replace("~([\n\r])<~i", " <", $text);
2049 $text = preg_replace("~>([\n\r])~i", "> ", $text);
2051 // Make returns into HTML newlines.
2053 $text = nl2br($text);
2056 // Wrap the whole thing in a div if required.
2058 // In 1.9 this was changed from a p => div.
2059 return '<div class="text_to_html">'.$text.'</div>';
2066 * Given Markdown formatted text, make it into XHTML using external function
2068 * @param string $text The markdown formatted text to be converted.
2069 * @return string Converted text
2071 function markdown_to_html($text) {
2074 if ($text === '' or $text === null) {
2078 require_once($CFG->libdir
.'/markdown/MarkdownInterface.php');
2079 require_once($CFG->libdir
.'/markdown/Markdown.php');
2080 require_once($CFG->libdir
.'/markdown/MarkdownExtra.php');
2082 return \Michelf\MarkdownExtra
::defaultTransform($text);
2086 * Given HTML text, make it into plain text using external function
2088 * @param string $html The text to be converted.
2089 * @param integer $width Width to wrap the text at. (optional, default 75 which
2090 * is a good value for email. 0 means do not limit line length.)
2091 * @param boolean $dolinks By default, any links in the HTML are collected, and
2092 * printed as a list at the end of the HTML. If you don't want that, set this
2093 * argument to false.
2094 * @return string plain text equivalent of the HTML.
2096 function html_to_text($html, $width = 75, $dolinks = true) {
2099 require_once($CFG->libdir
.'/html2text/lib.php');
2103 'do_links' => 'table',
2106 if (empty($dolinks)) {
2107 $options['do_links'] = 'none';
2109 $h2t = new core_html2text($html, $options);
2110 $result = $h2t->getText();
2116 * Converts texts or strings to plain text.
2118 * - When used to convert user input introduced in an editor the text format needs to be passed in $contentformat like we usually
2119 * do in format_text.
2120 * - When this function is used for strings that are usually passed through format_string before displaying them
2121 * we need to set $contentformat to false. This will execute html_to_text as these strings can contain multilang tags if
2122 * multilang filter is applied to headings.
2124 * @param string $content The text as entered by the user
2125 * @param int|false $contentformat False for strings or the text format: FORMAT_MOODLE/FORMAT_HTML/FORMAT_PLAIN/FORMAT_MARKDOWN
2126 * @return string Plain text.
2128 function content_to_text($content, $contentformat) {
2130 switch ($contentformat) {
2134 case FORMAT_MARKDOWN
:
2135 $content = markdown_to_html($content);
2136 $content = html_to_text($content, 75, false);
2139 // FORMAT_HTML, FORMAT_MOODLE and $contentformat = false, the later one are strings usually formatted through
2140 // format_string, we need to convert them from html because they can contain HTML (multilang filter).
2141 $content = html_to_text($content, 75, false);
2144 return trim($content, "\r\n ");
2148 * Factory method for extracting draft file links from arbitrary text using regular expressions. Only text
2149 * is required; other file fields may be passed to filter.
2151 * @param string $text Some html content.
2152 * @param bool $forcehttps force https urls.
2153 * @param int $contextid This parameter and the next three identify the file area to save to.
2154 * @param string $component The component name.
2155 * @param string $filearea The filearea.
2156 * @param int $itemid The item id for the filearea.
2157 * @param string $filename The specific filename of the file.
2160 function extract_draft_file_urls_from_text($text, $forcehttps = false, $contextid = null, $component = null,
2161 $filearea = null, $itemid = null, $filename = null) {
2164 $wwwroot = $CFG->wwwroot
;
2166 $wwwroot = str_replace('http://', 'https://', $wwwroot);
2168 $urlstring = '/' . preg_quote($wwwroot, '/');
2170 $urlbase = preg_quote('draftfile.php');
2171 $urlstring .= "\/(?<urlbase>{$urlbase})";
2173 if (is_null($contextid)) {
2174 $contextid = '[0-9]+';
2176 $urlstring .= "\/(?<contextid>{$contextid})";
2178 if (is_null($component)) {
2179 $component = '[a-z_]+';
2181 $urlstring .= "\/(?<component>{$component})";
2183 if (is_null($filearea)) {
2184 $filearea = '[a-z_]+';
2186 $urlstring .= "\/(?<filearea>{$filearea})";
2188 if (is_null($itemid)) {
2191 $urlstring .= "\/(?<itemid>{$itemid})";
2193 // Filename matching magic based on file_rewrite_urls_to_pluginfile().
2194 if (is_null($filename)) {
2195 $filename = '[^\'\",&<>|`\s:\\\\]+';
2197 $urlstring .= "\/(?<filename>{$filename})/";
2199 // Regular expression which matches URLs and returns their components.
2200 preg_match_all($urlstring, $text, $urls, PREG_SET_ORDER
);
2205 * This function will highlight search words in a given string
2207 * It cares about HTML and will not ruin links. It's best to use
2208 * this function after performing any conversions to HTML.
2210 * @param string $needle The search string. Syntax like "word1 +word2 -word3" is dealt with correctly.
2211 * @param string $haystack The string (HTML) within which to highlight the search terms.
2212 * @param boolean $matchcase whether to do case-sensitive. Default case-insensitive.
2213 * @param string $prefix the string to put before each search term found.
2214 * @param string $suffix the string to put after each search term found.
2215 * @return string The highlighted HTML.
2217 function highlight($needle, $haystack, $matchcase = false,
2218 $prefix = '<span class="highlight">', $suffix = '</span>') {
2220 // Quick bail-out in trivial cases.
2221 if (empty($needle) or empty($haystack)) {
2225 // Break up the search term into words, discard any -words and build a regexp.
2226 $words = preg_split('/ +/', trim($needle));
2227 foreach ($words as $index => $word) {
2228 if (strpos($word, '-') === 0) {
2229 unset($words[$index]);
2230 } else if (strpos($word, '+') === 0) {
2231 $words[$index] = '\b' . preg_quote(ltrim($word, '+'), '/') . '\b'; // Match only as a complete word.
2233 $words[$index] = preg_quote($word, '/');
2236 $regexp = '/(' . implode('|', $words) . ')/u'; // Char u is to do UTF-8 matching.
2241 // Another chance to bail-out if $search was only -words.
2242 if (empty($words)) {
2246 // Split the string into HTML tags and real content.
2247 $chunks = preg_split('/((?:<[^>]*>)+)/', $haystack, -1, PREG_SPLIT_DELIM_CAPTURE
);
2249 // We have an array of alternating blocks of text, then HTML tags, then text, ...
2250 // Loop through replacing search terms in the text, and leaving the HTML unchanged.
2251 $ishtmlchunk = false;
2253 foreach ($chunks as $chunk) {
2257 $result .= preg_replace($regexp, $prefix . '$1' . $suffix, $chunk);
2259 $ishtmlchunk = !$ishtmlchunk;
2266 * This function will highlight instances of $needle in $haystack
2268 * It's faster that the above function {@link highlight()} and doesn't care about
2271 * @param string $needle The string to search for
2272 * @param string $haystack The string to search for $needle in
2273 * @return string The highlighted HTML
2275 function highlightfast($needle, $haystack) {
2277 if (empty($needle) or empty($haystack)) {
2281 $parts = explode(core_text
::strtolower($needle), core_text
::strtolower($haystack));
2283 if (count($parts) === 1) {
2289 foreach ($parts as $key => $part) {
2290 $parts[$key] = substr($haystack, $pos, strlen($part));
2291 $pos +
= strlen($part);
2293 $parts[$key] .= '<span class="highlight">'.substr($haystack, $pos, strlen($needle)).'</span>';
2294 $pos +
= strlen($needle);
2297 return str_replace('<span class="highlight"></span>', '', join('', $parts));
2301 * Converts a language code to hyphen-separated format in accordance to the
2302 * {@link https://datatracker.ietf.org/doc/html/rfc5646#section-2.1 BCP47 syntax}.
2304 * For additional information, check out
2305 * {@link https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/lang MDN web docs - lang}.
2307 * @param string $langcode The language code to convert.
2310 function get_html_lang_attribute_value(string $langcode): string {
2311 $langcode = clean_param($langcode, PARAM_LANG
);
2312 if ($langcode === '') {
2316 // Grab language ISO code from lang config. If it differs from English, then it's been specified and we can return it.
2317 $langiso = (string) (new lang_string('iso6391', 'core_langconfig', null, $langcode));
2318 if ($langiso !== 'en') {
2322 // Where we cannot determine the value from lang config, use the first two characters from the lang code.
2323 return substr($langcode, 0, 2);
2327 * Return a string containing 'lang', xml:lang and optionally 'dir' HTML attributes.
2329 * Internationalisation, for print_header and backup/restorelib.
2331 * @param bool $dir Default false
2332 * @return string Attributes
2334 function get_html_lang($dir = false) {
2337 $currentlang = current_language();
2338 if (isset($CFG->lang
) && $currentlang !== $CFG->lang
&& !get_string_manager()->translation_exists($currentlang)) {
2339 // Use the default site language when the current language is not available.
2340 $currentlang = $CFG->lang
;
2341 // Fix the current language.
2342 fix_current_language($currentlang);
2347 if (right_to_left()) {
2348 $direction = ' dir="rtl"';
2350 $direction = ' dir="ltr"';
2354 // Accessibility: added the 'lang' attribute to $direction, used in theme <html> tag.
2355 $language = get_html_lang_attribute_value($currentlang);
2356 @header
('Content-Language: '.$language);
2357 return ($direction.' lang="'.$language.'" xml:lang="'.$language.'"');
2361 // STANDARD WEB PAGE PARTS.
2364 * Send the HTTP headers that Moodle requires.
2366 * There is a backwards compatibility hack for legacy code
2367 * that needs to add custom IE compatibility directive.
2371 * if (!isset($CFG->additionalhtmlhead)) {
2372 * $CFG->additionalhtmlhead = '';
2374 * $CFG->additionalhtmlhead .= '<meta http-equiv="X-UA-Compatible" content="IE=8" />';
2375 * header('X-UA-Compatible: IE=8');
2376 * echo $OUTPUT->header();
2379 * Please note the $CFG->additionalhtmlhead alone might not work,
2380 * you should send the IE compatibility header() too.
2382 * @param string $contenttype
2383 * @param bool $cacheable Can this page be cached on back?
2384 * @return void, sends HTTP headers
2386 function send_headers($contenttype, $cacheable = true) {
2389 @header
('Content-Type: ' . $contenttype);
2390 @header
('Content-Script-Type: text/javascript');
2391 @header
('Content-Style-Type: text/css');
2393 if (empty($CFG->additionalhtmlhead
) or stripos($CFG->additionalhtmlhead
, 'X-UA-Compatible') === false) {
2394 @header
('X-UA-Compatible: IE=edge');
2398 // Allow caching on "back" (but not on normal clicks).
2399 @header
('Cache-Control: private, pre-check=0, post-check=0, max-age=0, no-transform');
2400 @header
('Pragma: no-cache');
2401 @header
('Expires: ');
2403 // Do everything we can to always prevent clients and proxies caching.
2404 @header
('Cache-Control: no-store, no-cache, must-revalidate');
2405 @header
('Cache-Control: post-check=0, pre-check=0, no-transform', false);
2406 @header
('Pragma: no-cache');
2407 @header
('Expires: Mon, 20 Aug 1969 09:23:00 GMT');
2408 @header
('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
2410 @header
('Accept-Ranges: none');
2412 // The Moodle app must be allowed to embed content always.
2413 if (empty($CFG->allowframembedding
) && !core_useragent
::is_moodle_app()) {
2414 @header
('X-Frame-Options: sameorigin');
2417 // If referrer policy is set, add a referrer header.
2418 if (!empty($CFG->referrerpolicy
) && ($CFG->referrerpolicy
!== 'default')) {
2419 @header
('Referrer-Policy: ' . $CFG->referrerpolicy
);
2424 * Return the right arrow with text ('next'), and optionally embedded in a link.
2426 * @param string $text HTML/plain text label (set to blank only for breadcrumb separator cases).
2427 * @param string $url An optional link to use in a surrounding HTML anchor.
2428 * @param bool $accesshide True if text should be hidden (for screen readers only).
2429 * @param string $addclass Additional class names for the link, or the arrow character.
2430 * @return string HTML string.
2432 function link_arrow_right($text, $url='', $accesshide=false, $addclass='', $addparams = []) {
2433 global $OUTPUT; // TODO: move to output renderer.
2434 $arrowclass = 'arrow ';
2436 $arrowclass .= $addclass;
2438 $arrow = '<span class="'.$arrowclass.'" aria-hidden="true">'.$OUTPUT->rarrow().'</span>';
2441 $htmltext = '<span class="arrow_text">'.$text.'</span> ';
2443 $htmltext = get_accesshide($htmltext);
2447 $class = 'arrow_link';
2449 $class .= ' '.$addclass;
2455 'title' => preg_replace('/<.*?>/', '', $text),
2458 $linkparams +
= $addparams;
2460 return html_writer
::link($url, $htmltext . $arrow, $linkparams);
2462 return $htmltext.$arrow;
2466 * Return the left arrow with text ('previous'), and optionally embedded in a link.
2468 * @param string $text HTML/plain text label (set to blank only for breadcrumb separator cases).
2469 * @param string $url An optional link to use in a surrounding HTML anchor.
2470 * @param bool $accesshide True if text should be hidden (for screen readers only).
2471 * @param string $addclass Additional class names for the link, or the arrow character.
2472 * @return string HTML string.
2474 function link_arrow_left($text, $url='', $accesshide=false, $addclass='', $addparams = []) {
2475 global $OUTPUT; // TODO: move to utput renderer.
2476 $arrowclass = 'arrow ';
2478 $arrowclass .= $addclass;
2480 $arrow = '<span class="'.$arrowclass.'" aria-hidden="true">'.$OUTPUT->larrow().'</span>';
2483 $htmltext = ' <span class="arrow_text">'.$text.'</span>';
2485 $htmltext = get_accesshide($htmltext);
2489 $class = 'arrow_link';
2491 $class .= ' '.$addclass;
2497 'title' => preg_replace('/<.*?>/', '', $text),
2500 $linkparams +
= $addparams;
2502 return html_writer
::link($url, $arrow . $htmltext, $linkparams);
2504 return $arrow.$htmltext;
2508 * Return a HTML element with the class "accesshide", for accessibility.
2510 * Please use cautiously - where possible, text should be visible!
2512 * @param string $text Plain text.
2513 * @param string $elem Lowercase element name, default "span".
2514 * @param string $class Additional classes for the element.
2515 * @param string $attrs Additional attributes string in the form, "name='value' name2='value2'"
2516 * @return string HTML string.
2518 function get_accesshide($text, $elem='span', $class='', $attrs='') {
2519 return "<$elem class=\"accesshide $class\" $attrs>$text</$elem>";
2523 * Return the breadcrumb trail navigation separator.
2525 * @return string HTML string.
2527 function get_separator() {
2528 // Accessibility: the 'hidden' slash is preferred for screen readers.
2529 return ' '.link_arrow_right($text='/', $url='', $accesshide=true, 'sep').' ';
2533 * Print (or return) a collapsible region, that has a caption that can be clicked to expand or collapse the region.
2535 * If JavaScript is off, then the region will always be expanded.
2537 * @param string $contents the contents of the box.
2538 * @param string $classes class names added to the div that is output.
2539 * @param string $id id added to the div that is output. Must not be blank.
2540 * @param string $caption text displayed at the top. Clicking on this will cause the region to expand or contract.
2541 * @param string $userpref the name of the user preference that stores the user's preferred default state.
2542 * (May be blank if you do not wish the state to be persisted.
2543 * @param boolean $default Initial collapsed state to use if the user_preference it not set.
2544 * @param boolean $return if true, return the HTML as a string, rather than printing it.
2545 * @return string|void If $return is false, returns nothing, otherwise returns a string of HTML.
2547 function print_collapsible_region($contents, $classes, $id, $caption, $userpref = '', $default = false, $return = false) {
2548 $output = print_collapsible_region_start($classes, $id, $caption, $userpref, $default, true);
2549 $output .= $contents;
2550 $output .= print_collapsible_region_end(true);
2560 * Print (or return) the start of a collapsible region
2562 * The collapsibleregion has a caption that can be clicked to expand or collapse the region. If JavaScript is off, then the region
2563 * will always be expanded.
2565 * @param string $classes class names added to the div that is output.
2566 * @param string $id id added to the div that is output. Must not be blank.
2567 * @param string $caption text displayed at the top. Clicking on this will cause the region to expand or contract.
2568 * @param string $userpref the name of the user preference that stores the user's preferred default state.
2569 * (May be blank if you do not wish the state to be persisted.
2570 * @param boolean $default Initial collapsed state to use if the user_preference it not set.
2571 * @param boolean $return if true, return the HTML as a string, rather than printing it.
2572 * @param string $extracontent the extra content will show next to caption, eg.Help icon.
2573 * @return string|void if $return is false, returns nothing, otherwise returns a string of HTML.
2575 function print_collapsible_region_start($classes, $id, $caption, $userpref = '', $default = false, $return = false,
2576 $extracontent = null) {
2579 // Work out the initial state.
2580 if (!empty($userpref) and is_string($userpref)) {
2581 $collapsed = get_user_preferences($userpref, $default);
2583 $collapsed = $default;
2588 $classes .= ' collapsed';
2592 $output .= '<div id="' . $id . '" class="collapsibleregion ' . $classes . '">';
2593 $output .= '<div id="' . $id . '_sizer">';
2594 $output .= '<div id="' . $id . '_caption" class="collapsibleregioncaption">';
2595 $output .= $caption . ' </div>';
2596 if ($extracontent) {
2597 $output .= html_writer
::div($extracontent, 'collapsibleregionextracontent');
2599 $output .= '<div id="' . $id . '_inner" class="collapsibleregioninner">';
2600 $PAGE->requires
->js_init_call('M.util.init_collapsible_region', array($id, $userpref, get_string('clicktohideshow')));
2610 * Close a region started with print_collapsible_region_start.
2612 * @param boolean $return if true, return the HTML as a string, rather than printing it.
2613 * @return string|void if $return is false, returns nothing, otherwise returns a string of HTML.
2615 function print_collapsible_region_end($return = false) {
2616 $output = '</div></div></div>';
2626 * Print a specified group's avatar.
2628 * @param array|stdClass $group A single {@link group} object OR array of groups.
2629 * @param int $courseid The course ID.
2630 * @param boolean $large Default small picture, or large.
2631 * @param boolean $return If false print picture, otherwise return the output as string
2632 * @param boolean $link Enclose image in a link to view specified course?
2633 * @param boolean $includetoken Whether to use a user token when displaying this group image.
2634 * True indicates to generate a token for current user, and integer value indicates to generate a token for the
2635 * user whose id is the value indicated.
2636 * If the group picture is included in an e-mail or some other location where the audience is a specific
2637 * user who will not be logged in when viewing, then we use a token to authenticate the user.
2638 * @return string|void Depending on the setting of $return
2640 function print_group_picture($group, $courseid, $large = false, $return = false, $link = true, $includetoken = false) {
2643 if (is_array($group)) {
2645 foreach ($group as $g) {
2646 $output .= print_group_picture($g, $courseid, $large, true, $link, $includetoken);
2656 $pictureurl = get_group_picture_url($group, $courseid, $large, $includetoken);
2658 // If there is no picture, do nothing.
2659 if (!isset($pictureurl)) {
2663 $context = context_course
::instance($courseid);
2665 $groupname = s($group->name
);
2666 $pictureimage = html_writer
::img($pictureurl, $groupname, ['title' => $groupname]);
2669 if ($link or has_capability('moodle/site:accessallgroups', $context)) {
2670 $linkurl = new moodle_url('/user/index.php', ['id' => $courseid, 'group' => $group->id
]);
2671 $output .= html_writer
::link($linkurl, $pictureimage);
2673 $output .= $pictureimage;
2684 * Return the url to the group picture.
2686 * @param stdClass $group A group object.
2687 * @param int $courseid The course ID for the group.
2688 * @param bool $large A large or small group picture? Default is small.
2689 * @param boolean $includetoken Whether to use a user token when displaying this group image.
2690 * True indicates to generate a token for current user, and integer value indicates to generate a token for the
2691 * user whose id is the value indicated.
2692 * If the group picture is included in an e-mail or some other location where the audience is a specific
2693 * user who will not be logged in when viewing, then we use a token to authenticate the user.
2694 * @return ?moodle_url Returns the url for the group picture.
2696 function get_group_picture_url($group, $courseid, $large = false, $includetoken = false) {
2699 $context = context_course
::instance($courseid);
2701 // If there is no picture, do nothing.
2702 if (!$group->picture
) {
2712 $grouppictureurl = moodle_url
::make_pluginfile_url(
2713 $context->id
, 'group', 'icon', $group->id
, '/', $file, false, $includetoken);
2714 $grouppictureurl->param('rev', $group->picture
);
2715 return $grouppictureurl;
2720 * Display a recent activity note
2722 * @staticvar string $strftimerecent
2723 * @param int $time A timestamp int.
2724 * @param stdClass $user A user object from the database.
2725 * @param string $text Text for display for the note
2726 * @param string $link The link to wrap around the text
2727 * @param bool $return If set to true the HTML is returned rather than echo'd
2728 * @param string $viewfullnames
2729 * @return ?string If $retrun was true returns HTML for a recent activity notice.
2731 function print_recent_activity_note($time, $user, $text, $link, $return=false, $viewfullnames=null) {
2732 static $strftimerecent = null;
2735 if (is_null($viewfullnames)) {
2736 $context = context_system
::instance();
2737 $viewfullnames = has_capability('moodle/site:viewfullnames', $context);
2740 if (is_null($strftimerecent)) {
2741 $strftimerecent = get_string('strftimerecent');
2744 $output .= '<div class="head">';
2745 $output .= '<div class="date">'.userdate($time, $strftimerecent).'</div>';
2746 $output .= '<div class="name">'.fullname($user, $viewfullnames).'</div>';
2747 $output .= '</div>';
2748 $output .= '<div class="info"><a href="'.$link.'">'.format_string($text, true).'</a></div>';
2758 * Returns a popup menu with course activity modules
2760 * Given a course this function returns a small popup menu with all the course activity modules in it, as a navigation menu
2761 * outputs a simple list structure in XHTML.
2762 * The data is taken from the serialised array stored in the course record.
2764 * @param stdClass $course A course object.
2765 * @param array $sections
2766 * @param course_modinfo $modinfo
2767 * @param string $strsection
2768 * @param string $strjumpto
2770 * @param string $cmid
2771 * @return string The HTML block
2773 function navmenulist($course, $sections, $modinfo, $strsection, $strjumpto, $width=50, $cmid=0) {
2775 global $CFG, $OUTPUT;
2779 $doneheading = false;
2781 $courseformatoptions = course_get_format($course)->get_format_options();
2782 $coursecontext = context_course
::instance($course->id
);
2784 $menu[] = '<ul class="navmenulist"><li class="jumpto section"><span>'.$strjumpto.'</span><ul>';
2785 foreach ($modinfo->cms
as $mod) {
2786 if (!$mod->has_view()) {
2787 // Don't show modules which you can't link to!
2791 // For course formats using 'numsections' do not show extra sections.
2792 if (isset($courseformatoptions['numsections']) && $mod->sectionnum
> $courseformatoptions['numsections']) {
2796 if (!$mod->uservisible
) { // Do not icnlude empty sections at all.
2800 if ($mod->sectionnum
>= 0 and $section != $mod->sectionnum
) {
2801 $thissection = $sections[$mod->sectionnum
];
2803 if ($thissection->visible
or
2804 (isset($courseformatoptions['hiddensections']) and !$courseformatoptions['hiddensections']) or
2805 has_capability('moodle/course:viewhiddensections', $coursecontext)) {
2806 $thissection->summary
= strip_tags(format_string($thissection->summary
, true));
2807 if (!$doneheading) {
2808 $menu[] = '</ul></li>';
2810 if ($course->format
== 'weeks' or empty($thissection->summary
)) {
2811 $item = $strsection ." ". $mod->sectionnum
;
2813 if (core_text
::strlen($thissection->summary
) < ($width-3)) {
2814 $item = $thissection->summary
;
2816 $item = core_text
::substr($thissection->summary
, 0, $width).'...';
2819 $menu[] = '<li class="section"><span>'.$item.'</span>';
2821 $doneheading = true;
2823 $section = $mod->sectionnum
;
2825 // No activities from this hidden section shown.
2830 $url = $mod->modname
.'/view.php?id='. $mod->id
;
2831 $mod->name
= strip_tags(format_string($mod->name
,true));
2832 if (core_text
::strlen($mod->name
) > ($width+
5)) {
2833 $mod->name
= core_text
::substr($mod->name
, 0, $width).'...';
2835 if (!$mod->visible
) {
2836 $mod->name
= '('.$mod->name
.')';
2838 $class = 'activity '.$mod->modname
;
2839 $class .= ($cmid == $mod->id
) ?
' selected' : '';
2840 $menu[] = '<li class="'.$class.'">'.
2841 $OUTPUT->image_icon('monologo', '', $mod->modname
).
2842 '<a href="'.$CFG->wwwroot
.'/mod/'.$url.'">'.$mod->name
.'</a></li>';
2846 $menu[] = '</ul></li>';
2848 $menu[] = '</ul></li></ul>';
2850 return implode("\n", $menu);
2854 * Prints a grade menu (as part of an existing form) with help showing all possible numerical grades and scales.
2856 * @todo Finish documenting this function
2857 * @todo Deprecate: this is only used in a few contrib modules
2859 * @param int $courseid The course ID
2860 * @param string $name
2861 * @param string $current
2862 * @param boolean $includenograde Include those with no grades
2863 * @param boolean $return If set to true returns rather than echo's
2864 * @return string|bool|null Depending on value of $return
2866 function print_grade_menu($courseid, $name, $current, $includenograde=true, $return=false) {
2870 $strscale = get_string('scale');
2871 $strscales = get_string('scales');
2873 $scales = get_scales_menu($courseid);
2874 foreach ($scales as $i => $scalename) {
2875 $grades[-$i] = $strscale .': '. $scalename;
2877 if ($includenograde) {
2878 $grades[0] = get_string('nograde');
2880 for ($i=100; $i>=1; $i--) {
2883 $output .= html_writer
::select($grades, $name, $current, false);
2885 $linkobject = '<span class="helplink">' . $OUTPUT->pix_icon('help', $strscales) . '</span>';
2886 $link = new moodle_url('/course/scales.php', array('id' => $courseid, 'list' => 1));
2887 $action = new popup_action('click', $link, 'ratingscales', array('height' => 400, 'width' => 500));
2888 $output .= $OUTPUT->action_link($link, $linkobject, $action, array('title' => $strscales));
2898 * Print an error to STDOUT and exit with a non-zero code. For commandline scripts.
2900 * Default errorcode is 1.
2902 * Very useful for perl-like error-handling:
2903 * do_somethting() or mdie("Something went wrong");
2905 * @param string $msg Error message
2906 * @param integer $errorcode Error code to emit
2908 function mdie($msg='', $errorcode=1) {
2909 trigger_error($msg);
2914 * Print a message and exit.
2916 * @param string $message The message to print in the notice
2917 * @param moodle_url|string $link The link to use for the continue button
2918 * @param object $course A course object. Unused.
2919 * @return void This function simply exits
2921 function notice ($message, $link='', $course=null) {
2922 global $PAGE, $OUTPUT;
2924 $message = clean_text($message); // In case nasties are in here.
2927 echo("!!$message!!\n");
2928 exit(1); // No success.
2931 if (!$PAGE->headerprinted
) {
2932 // Header not yet printed.
2933 $PAGE->set_title(get_string('notice'));
2934 echo $OUTPUT->header();
2936 echo $OUTPUT->container_end_all(false);
2939 echo $OUTPUT->box($message, 'generalbox', 'notice');
2940 echo $OUTPUT->continue_button($link);
2942 echo $OUTPUT->footer();
2943 exit(1); // General error code.
2947 * Redirects the user to another page, after printing a notice.
2949 * This function calls the OUTPUT redirect method, echo's the output and then dies to ensure nothing else happens.
2951 * <strong>Good practice:</strong> You should call this method before starting page
2952 * output by using any of the OUTPUT methods.
2954 * @param moodle_url|string $url A moodle_url to redirect to. Strings are not to be trusted!
2955 * @param string $message The message to display to the user
2956 * @param int $delay The delay before redirecting
2957 * @param string $messagetype The type of notification to show the message in. See constants on \core\output\notification.
2958 * @throws moodle_exception
2960 function redirect($url, $message='', $delay=null, $messagetype = \core\output\notification
::NOTIFY_INFO
) {
2961 global $OUTPUT, $PAGE, $CFG;
2963 if (CLI_SCRIPT
or AJAX_SCRIPT
) {
2964 // This is wrong - developers should not use redirect in these scripts but it should not be very likely.
2965 throw new moodle_exception('redirecterrordetected', 'error');
2968 if ($delay === null) {
2972 // Prevent debug errors - make sure context is properly initialised.
2974 $PAGE->set_context(null);
2975 $PAGE->set_pagelayout('redirect'); // No header and footer needed.
2976 $PAGE->set_title(get_string('pageshouldredirect', 'moodle'));
2979 if ($url instanceof moodle_url
) {
2980 $url = $url->out(false);
2983 $debugdisableredirect = false;
2985 if (defined('DEBUGGING_PRINTED')) {
2986 // Some debugging already printed, no need to look more.
2987 $debugdisableredirect = true;
2991 if (core_useragent
::is_msword()) {
2992 // Clicking a URL from MS Word sends a request to the server without cookies. If that
2993 // causes a redirect Word will open a browser pointing the new URL. If not, the URL that
2994 // was clicked is opened. Because the request from Word is without cookies, it almost
2995 // always results in a redirect to the login page, even if the user is logged in in their
2996 // browser. This is not what we want, so prevent the redirect for requests from Word.
2997 $debugdisableredirect = true;
3001 if (empty($CFG->debugdisplay
) or empty($CFG->debug
)) {
3002 // No errors should be displayed.
3006 if (!function_exists('error_get_last') or !$lasterror = error_get_last()) {
3010 if (!($lasterror['type'] & $CFG->debug
)) {
3011 // Last error not interesting.
3015 // Watch out here, @hidden() errors are returned from error_get_last() too.
3016 if (headers_sent()) {
3017 // We already started printing something - that means errors likely printed.
3018 $debugdisableredirect = true;
3022 if (ob_get_level() and ob_get_contents()) {
3023 // There is something waiting to be printed, hopefully it is the errors,
3024 // but it might be some error hidden by @ too - such as the timezone mess from setup.php.
3025 $debugdisableredirect = true;
3030 // Technically, HTTP/1.1 requires Location: header to contain the absolute path.
3031 // (In practice browsers accept relative paths - but still, might as well do it properly.)
3032 // This code turns relative into absolute.
3033 if (!preg_match('|^[a-z]+:|i', $url)) {
3034 // Get host name http://www.wherever.com.
3035 $hostpart = preg_replace('|^(.*?[^:/])/.*$|', '$1', $CFG->wwwroot
);
3036 if (preg_match('|^/|', $url)) {
3037 // URLs beginning with / are relative to web server root so we just add them in.
3038 $url = $hostpart.$url;
3040 // URLs not beginning with / are relative to path of current script, so add that on.
3041 $url = $hostpart.preg_replace('|\?.*$|', '', me()).'/../'.$url;
3045 $newurl = preg_replace('|/(?!\.\.)[^/]*/\.\./|', '/', $url);
3046 if ($newurl == $url) {
3053 // Sanitise url - we can not rely on moodle_url or our URL cleaning
3054 // because they do not support all valid external URLs.
3055 $url = preg_replace('/[\x00-\x1F\x7F]/', '', $url);
3056 $url = str_replace('"', '%22', $url);
3057 $encodedurl = preg_replace("/\&(?![a-zA-Z0-9#]{1,8};)/", "&", $url);
3058 $encodedurl = preg_replace('/^.*href="([^"]*)".*$/', "\\1", clean_text('<a href="'.$encodedurl.'" />', FORMAT_HTML
));
3059 $url = str_replace('&', '&', $encodedurl);
3061 if (!empty($message)) {
3062 if (!$debugdisableredirect && !headers_sent()) {
3063 // A message has been provided, and the headers have not yet been sent.
3064 // Display the message as a notification on the subsequent page.
3065 \core\notification
::add($message, $messagetype);
3069 if ($delay === -1 ||
!is_numeric($delay)) {
3072 $message = clean_text($message);
3075 $message = get_string('pageshouldredirect');
3079 // Make sure the session is closed properly, this prevents problems in IIS
3080 // and also some potential PHP shutdown issues.
3081 \core\session\manager
::write_close();
3083 if ($delay == 0 && !$debugdisableredirect && !headers_sent()) {
3085 // This helps when debugging redirect issues like loops and it is not clear
3086 // which layer in the stack sent the redirect header. If debugging is on
3087 // then the file and line is also shown.
3088 $redirectby = 'Moodle';
3089 if (debugging('', DEBUG_DEVELOPER
)) {
3090 $origin = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS
, 1)[0];
3091 $redirectby .= ' /' . str_replace($CFG->dirroot
. '/', '', $origin['file']) . ':' . $origin['line'];
3093 @header
("X-Redirect-By: $redirectby");
3095 // 302 might not work for POST requests, 303 is ignored by obsolete clients.
3096 @header
($_SERVER['SERVER_PROTOCOL'] . ' 303 See Other');
3097 @header
('Location: '.$url);
3098 echo bootstrap_renderer
::plain_redirect_message($encodedurl);
3102 // Include a redirect message, even with a HTTP redirect, because that is recommended practice.
3104 $CFG->docroot
= false; // To prevent the link to moodle docs from being displayed on redirect page.
3105 echo $OUTPUT->redirect_message($encodedurl, $message, $delay, $debugdisableredirect, $messagetype);
3108 echo bootstrap_renderer
::early_redirect_message($encodedurl, $message, $delay);
3114 * Given an email address, this function will return an obfuscated version of it.
3116 * @param string $email The email address to obfuscate
3117 * @return string The obfuscated email address
3119 function obfuscate_email($email) {
3121 $length = strlen($email);
3123 while ($i < $length) {
3124 if (rand(0, 2) && $email[$i]!='@') { // MDL-20619 some browsers have problems unobfuscating @.
3125 $obfuscated.='%'.dechex(ord($email[$i]));
3127 $obfuscated.=$email[$i];
3135 * This function takes some text and replaces about half of the characters
3136 * with HTML entity equivalents. Return string is obviously longer.
3138 * @param string $plaintext The text to be obfuscated
3139 * @return string The obfuscated text
3141 function obfuscate_text($plaintext) {
3143 $length = core_text
::strlen($plaintext);
3145 $prevobfuscated = false;
3146 while ($i < $length) {
3147 $char = core_text
::substr($plaintext, $i, 1);
3148 $ord = core_text
::utf8ord($char);
3149 $numerical = ($ord >= ord('0')) && ($ord <= ord('9'));
3150 if ($prevobfuscated and $numerical ) {
3151 $obfuscated.='&#'.$ord.';';
3152 } else if (rand(0, 2)) {
3153 $obfuscated.='&#'.$ord.';';
3154 $prevobfuscated = true;
3157 $prevobfuscated = false;
3165 * This function uses the {@link obfuscate_email()} and {@link obfuscate_text()}
3166 * to generate a fully obfuscated email link, ready to use.
3168 * @param string $email The email address to display
3169 * @param string $label The text to displayed as hyperlink to $email
3170 * @param boolean $dimmed If true then use css class 'dimmed' for hyperlink
3171 * @param string $subject The subject of the email in the mailto link
3172 * @param string $body The content of the email in the mailto link
3173 * @return string The obfuscated mailto link
3175 function obfuscate_mailto($email, $label='', $dimmed=false, $subject = '', $body = '') {
3177 if (empty($label)) {
3181 $label = obfuscate_text($label);
3182 $email = obfuscate_email($email);
3183 $mailto = obfuscate_text('mailto');
3184 $url = new moodle_url("mailto:$email");
3187 if (!empty($subject)) {
3188 $url->param('subject', format_string($subject));
3190 if (!empty($body)) {
3191 $url->param('body', format_string($body));
3194 // Use the obfuscated mailto.
3195 $url = preg_replace('/^mailto/', $mailto, $url->out());
3198 $attrs['title'] = get_string('emaildisable');
3199 $attrs['class'] = 'dimmed';
3202 return html_writer
::link($url, $label, $attrs);
3206 * This function is used to rebuild the <nolink> tag because some formats (PLAIN and WIKI)
3207 * will transform it to html entities
3209 * @param string $text Text to search for nolink tag in
3212 function rebuildnolinktag($text) {
3214 $text = preg_replace('/<(\/*nolink)>/i', '<$1>', $text);
3220 * Prints a maintenance message from $CFG->maintenance_message or default if empty.
3222 function print_maintenance_message() {
3223 global $CFG, $SITE, $PAGE, $OUTPUT;
3225 header($_SERVER['SERVER_PROTOCOL'] . ' 503 Moodle under maintenance');
3226 header('Status: 503 Moodle under maintenance');
3227 header('Retry-After: 300');
3229 $PAGE->set_pagetype('maintenance-message');
3230 $PAGE->set_pagelayout('maintenance');
3231 $PAGE->set_heading($SITE->fullname
);
3232 echo $OUTPUT->header();
3233 echo $OUTPUT->heading(get_string('sitemaintenance', 'admin'));
3234 if (isset($CFG->maintenance_message
) and !html_is_blank($CFG->maintenance_message
)) {
3235 echo $OUTPUT->box_start('maintenance_message generalbox boxwidthwide boxaligncenter');
3236 echo $CFG->maintenance_message
;
3237 echo $OUTPUT->box_end();
3239 echo $OUTPUT->footer();
3244 * Returns a string containing a nested list, suitable for formatting into tabs with CSS.
3246 * It is not recommended to use this function in Moodle 2.5 but it is left for backward
3249 * Example how to print a single line tabs:
3251 * new tabobject(...),
3252 * new tabobject(...)
3254 * echo $OUTPUT->tabtree($rows, $selectedid);
3256 * Multiple row tabs may not look good on some devices but if you want to use them
3257 * you can specify ->subtree for the active tabobject.
3259 * @param array $tabrows An array of rows where each row is an array of tab objects
3260 * @param string $selected The id of the selected tab (whatever row it's on)
3261 * @param array $inactive An array of ids of inactive tabs that are not selectable.
3262 * @param array $activated An array of ids of other tabs that are currently activated
3263 * @param bool $return If true output is returned rather then echo'd
3264 * @return string HTML output if $return was set to true.
3266 function print_tabs($tabrows, $selected = null, $inactive = null, $activated = null, $return = false) {
3269 $tabrows = array_reverse($tabrows);
3271 foreach ($tabrows as $row) {
3274 foreach ($row as $tab) {
3275 $tab->inactive
= is_array($inactive) && in_array((string)$tab->id
, $inactive);
3276 $tab->activated
= is_array($activated) && in_array((string)$tab->id
, $activated);
3277 $tab->selected
= (string)$tab->id
== $selected;
3279 if ($tab->activated ||
$tab->selected
) {
3280 $tab->subtree
= $subtree;
3286 $output = $OUTPUT->tabtree($subtree);
3291 return !empty($output);
3296 * Alter debugging level for the current request,
3297 * the change is not saved in database.
3299 * @param int $level one of the DEBUG_* constants
3300 * @param bool $debugdisplay
3302 function set_debugging($level, $debugdisplay = null) {
3305 $CFG->debug
= (int)$level;
3306 $CFG->debugdeveloper
= (($CFG->debug
& DEBUG_DEVELOPER
) === DEBUG_DEVELOPER
);
3308 if ($debugdisplay !== null) {
3309 $CFG->debugdisplay
= (bool)$debugdisplay;
3314 * Standard Debugging Function
3316 * Returns true if the current site debugging settings are equal or above specified level.
3317 * If passed a parameter it will emit a debugging notice similar to trigger_error(). The
3318 * routing of notices is controlled by $CFG->debugdisplay
3321 * 1) debugging('a normal debug notice');
3322 * 2) debugging('something really picky', DEBUG_ALL);
3323 * 3) debugging('annoying debug message only for developers', DEBUG_DEVELOPER);
3324 * 4) if (debugging()) { perform extra debugging operations (do not use print or echo) }
3326 * In code blocks controlled by debugging() (such as example 4)
3327 * any output should be routed via debugging() itself, or the lower-level
3328 * trigger_error() or error_log(). Using echo or print will break XHTML
3329 * JS and HTTP headers.
3331 * It is also possible to define NO_DEBUG_DISPLAY which redirects the message to error_log.
3333 * @param string $message a message to print
3334 * @param int $level the level at which this debugging statement should show
3335 * @param array $backtrace use different backtrace
3338 function debugging($message = '', $level = DEBUG_NORMAL
, $backtrace = null) {
3341 $forcedebug = false;
3342 if (!empty($CFG->debugusers
) && $USER) {
3343 $debugusers = explode(',', $CFG->debugusers
);
3344 $forcedebug = in_array($USER->id
, $debugusers);
3347 if (!$forcedebug and (empty($CFG->debug
) ||
($CFG->debug
!= -1 and $CFG->debug
< $level))) {
3351 if (!isset($CFG->debugdisplay
)) {
3352 $CFG->debugdisplay
= ini_get_bool('display_errors');
3357 $backtrace = debug_backtrace();
3359 $from = format_backtrace($backtrace, CLI_SCRIPT || NO_DEBUG_DISPLAY
);
3361 if (phpunit_util
::debugging_triggered($message, $level, $from)) {
3362 // We are inside test, the debug message was logged.
3367 if (NO_DEBUG_DISPLAY
) {
3368 // Script does not want any errors or debugging in output,
3369 // we send the info to error log instead.
3370 error_log('Debugging: ' . $message . ' in '. PHP_EOL
. $from);
3371 } else if ($forcedebug or $CFG->debugdisplay
) {
3372 if (!defined('DEBUGGING_PRINTED')) {
3373 define('DEBUGGING_PRINTED', 1); // Indicates we have printed something.
3377 echo "++ $message ++\n$from";
3379 if (property_exists($CFG, 'debug_developer_debugging_as_error')) {
3380 $showaserror = $CFG->debug_developer_debugging_as_error
;
3382 $showaserror = (bool) get_whoops();
3386 trigger_error($message, E_USER_NOTICE
);
3388 echo '<div class="notifytiny debuggingmessage" data-rel="debugging">', $message, $from, '</div>';
3392 trigger_error($message . $from, E_USER_NOTICE
);
3399 * Outputs a HTML comment to the browser.
3401 * This is used for those hard-to-debug pages that use bits from many different files in very confusing ways (e.g. blocks).
3403 * <code>print_location_comment(__FILE__, __LINE__);</code>
3405 * @param string $file
3406 * @param integer $line
3407 * @param boolean $return Whether to return or print the comment
3408 * @return string|void Void unless true given as third parameter
3410 function print_location_comment($file, $line, $return = false) {
3412 return "<!-- $file at line $line -->\n";
3414 echo "<!-- $file at line $line -->\n";
3420 * Returns true if the user is using a right-to-left language.
3422 * @return boolean true if the current language is right-to-left (Hebrew, Arabic etc)
3424 function right_to_left() {
3425 return (get_string('thisdirection', 'langconfig') === 'rtl');
3430 * Returns swapped left<=> right if in RTL environment.
3432 * Part of RTL Moodles support.
3434 * @param string $align align to check
3437 function fix_align_rtl($align) {
3438 if (!right_to_left()) {
3441 if ($align == 'left') {
3444 if ($align == 'right') {
3452 * Returns true if the page is displayed in a popup window.
3454 * Gets the information from the URL parameter inpopup.
3456 * @todo Use a central function to create the popup calls all over Moodle and
3457 * In the moment only works with resources and probably questions.
3461 function is_in_popup() {
3462 $inpopup = optional_param('inpopup', '', PARAM_BOOL
);
3468 * Progress trace class.
3470 * Use this class from long operations where you want to output occasional information about
3471 * what is going on, but don't know if, or in what format, the output should be.
3473 * @copyright 2009 Tim Hunt
3474 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3477 abstract class progress_trace
{
3479 * Output an progress message in whatever format.
3481 * @param string $message the message to output.
3482 * @param integer $depth indent depth for this message.
3484 abstract public function output($message, $depth = 0);
3487 * Called when the processing is finished.
3489 public function finished() {
3494 * This subclass of progress_trace does not ouput anything.
3496 * @copyright 2009 Tim Hunt
3497 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3500 class null_progress_trace
extends progress_trace
{
3504 * @param string $message
3506 * @return void Does Nothing
3508 public function output($message, $depth = 0) {
3513 * This subclass of progress_trace outputs to plain text.
3515 * @copyright 2009 Tim Hunt
3516 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3519 class text_progress_trace
extends progress_trace
{
3521 * Output the trace message.
3523 * @param string $message
3525 * @return void Output is echo'd
3527 public function output($message, $depth = 0) {
3528 mtrace(str_repeat(' ', $depth) . $message);
3533 * This subclass of progress_trace outputs as HTML.
3535 * @copyright 2009 Tim Hunt
3536 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3539 class html_progress_trace
extends progress_trace
{
3541 * Output the trace message.
3543 * @param string $message
3545 * @return void Output is echo'd
3547 public function output($message, $depth = 0) {
3548 echo '<p>', str_repeat('  ', $depth), htmlspecialchars($message, ENT_COMPAT
), "</p>\n";
3554 * HTML List Progress Tree
3556 * @copyright 2009 Tim Hunt
3557 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3560 class html_list_progress_trace
extends progress_trace
{
3562 protected $currentdepth = -1;
3567 * @param string $message The message to display
3569 * @return void Output is echoed
3571 public function output($message, $depth = 0) {
3573 while ($this->currentdepth
> $depth) {
3574 echo "</li>\n</ul>\n";
3575 $this->currentdepth
-= 1;
3576 if ($this->currentdepth
== $depth) {
3581 while ($this->currentdepth
< $depth) {
3583 $this->currentdepth +
= 1;
3589 echo htmlspecialchars($message, ENT_COMPAT
);
3594 * Called when the processing is finished.
3596 public function finished() {
3597 while ($this->currentdepth
>= 0) {
3598 echo "</li>\n</ul>\n";
3599 $this->currentdepth
-= 1;
3605 * This subclass of progress_trace outputs to error log.
3607 * @copyright Petr Skoda {@link http://skodak.org}
3608 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3611 class error_log_progress_trace
extends progress_trace
{
3612 /** @var string log prefix */
3617 * @param string $prefix optional log prefix
3619 public function __construct($prefix = '') {
3620 $this->prefix
= $prefix;
3624 * Output the trace message.
3626 * @param string $message
3628 * @return void Output is sent to error log.
3630 public function output($message, $depth = 0) {
3631 error_log($this->prefix
. str_repeat(' ', $depth) . $message);
3636 * Special type of trace that can be used for catching of output of other traces.
3638 * @copyright Petr Skoda {@link http://skodak.org}
3639 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3642 class progress_trace_buffer
extends progress_trace
{
3643 /** @var progress_trace */
3645 /** @var bool do we pass output out */
3646 protected $passthrough;
3647 /** @var string output buffer */
3653 * @param progress_trace $trace
3654 * @param bool $passthrough true means output and buffer, false means just buffer and no output
3656 public function __construct(progress_trace
$trace, $passthrough = true) {
3657 $this->trace
= $trace;
3658 $this->passthrough
= $passthrough;
3663 * Output the trace message.
3665 * @param string $message the message to output.
3666 * @param int $depth indent depth for this message.
3667 * @return void output stored in buffer
3669 public function output($message, $depth = 0) {
3671 $this->trace
->output($message, $depth);
3672 $this->buffer
.= ob_get_contents();
3673 if ($this->passthrough
) {
3681 * Called when the processing is finished.
3683 public function finished() {
3685 $this->trace
->finished();
3686 $this->buffer
.= ob_get_contents();
3687 if ($this->passthrough
) {
3695 * Reset internal text buffer.
3697 public function reset_buffer() {
3702 * Return internal text buffer.
3703 * @return string buffered plain text
3705 public function get_buffer() {
3706 return $this->buffer
;
3711 * Special type of trace that can be used for redirecting to multiple other traces.
3713 * @copyright Petr Skoda {@link http://skodak.org}
3714 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3717 class combined_progress_trace
extends progress_trace
{
3720 * An array of traces.
3726 * Constructs a new instance.
3728 * @param array $traces multiple traces
3730 public function __construct(array $traces) {
3731 $this->traces
= $traces;
3735 * Output an progress message in whatever format.
3737 * @param string $message the message to output.
3738 * @param integer $depth indent depth for this message.
3740 public function output($message, $depth = 0) {
3741 foreach ($this->traces
as $trace) {
3742 $trace->output($message, $depth);
3747 * Called when the processing is finished.
3749 public function finished() {
3750 foreach ($this->traces
as $trace) {
3757 * Returns a localized sentence in the current language summarizing the current password policy
3759 * @todo this should be handled by a function/method in the language pack library once we have a support for it
3763 function print_password_policy() {
3767 if (!empty($CFG->passwordpolicy
)) {
3768 $messages = array();
3769 if (!empty($CFG->minpasswordlength
)) {
3770 $messages[] = get_string('informminpasswordlength', 'auth', $CFG->minpasswordlength
);
3772 if (!empty($CFG->minpassworddigits
)) {
3773 $messages[] = get_string('informminpassworddigits', 'auth', $CFG->minpassworddigits
);
3775 if (!empty($CFG->minpasswordlower
)) {
3776 $messages[] = get_string('informminpasswordlower', 'auth', $CFG->minpasswordlower
);
3778 if (!empty($CFG->minpasswordupper
)) {
3779 $messages[] = get_string('informminpasswordupper', 'auth', $CFG->minpasswordupper
);
3781 if (!empty($CFG->minpasswordnonalphanum
)) {
3782 $messages[] = get_string('informminpasswordnonalphanum', 'auth', $CFG->minpasswordnonalphanum
);
3785 // Fire any additional password policy functions from plugins.
3786 // Callbacks must return an array of message strings.
3787 $pluginsfunction = get_plugins_with_function('print_password_policy');
3788 foreach ($pluginsfunction as $plugintype => $plugins) {
3789 foreach ($plugins as $pluginfunction) {
3790 $messages = array_merge($messages, $pluginfunction());
3794 $messages = join(', ', $messages); // This is ugly but we do not have anything better yet...
3795 // Check if messages is empty before outputting any text.
3796 if ($messages != '') {
3797 $message = get_string('informpasswordpolicy', 'auth', $messages);
3804 * Get the value of a help string fully prepared for display in the current language.
3806 * @param string $identifier The identifier of the string to search for.
3807 * @param string $component The module the string is associated with.
3808 * @param boolean $ajax Whether this help is called from an AJAX script.
3809 * This is used to influence text formatting and determines
3810 * which format to output the doclink in.
3811 * @param string|object|array $a An object, string or number that can be used
3812 * within translation strings
3813 * @return stdClass An object containing:
3814 * - heading: Any heading that there may be for this help string.
3815 * - text: The wiki-formatted help string.
3816 * - doclink: An object containing a link, the linktext, and any additional
3817 * CSS classes to apply to that link. Only present if $ajax = false.
3818 * - completedoclink: A text representation of the doclink. Only present if $ajax = true.
3820 function get_formatted_help_string($identifier, $component, $ajax = false, $a = null) {
3821 global $CFG, $OUTPUT;
3822 $sm = get_string_manager();
3824 // Do not rebuild caches here!
3825 // Devs need to learn to purge all caches after any change or disable $CFG->langstringcache.
3827 $data = new stdClass();
3829 if ($sm->string_exists($identifier, $component)) {
3830 $data->heading
= format_string(get_string($identifier, $component));
3832 // Gracefully fall back to an empty string.
3833 $data->heading
= '';
3836 if ($sm->string_exists($identifier . '_help', $component)) {
3837 $options = new stdClass();
3838 $options->trusted
= false;
3839 $options->noclean
= false;
3840 $options->filter
= false;
3841 $options->para
= true;
3842 $options->newlines
= false;
3843 $options->overflowdiv
= !$ajax;
3845 // Should be simple wiki only MDL-21695.
3846 $data->text
= format_text(get_string($identifier.'_help', $component, $a), FORMAT_MARKDOWN
, $options);
3848 $helplink = $identifier . '_link';
3849 if ($sm->string_exists($helplink, $component)) { // Link to further info in Moodle docs.
3850 $link = get_string($helplink, $component);
3851 $linktext = get_string('morehelp');
3853 $data->doclink
= new stdClass();
3854 $url = new moodle_url(get_docs_url($link));
3856 $data->doclink
->link
= $url->out();
3857 $data->doclink
->linktext
= $linktext;
3858 $data->doclink
->class = ($CFG->doctonewwindow
) ?
'helplinkpopup' : '';
3860 $data->completedoclink
= html_writer
::tag('div', $OUTPUT->doc_link($link, $linktext),
3861 array('class' => 'helpdoclink'));
3865 $data->text
= html_writer
::tag('p',
3866 html_writer
::tag('strong', 'TODO') . ": missing help string [{$identifier}_help, {$component}]");