Merge branch 'MDL-81419-main' of https://github.com/andrewnicols/moodle
[moodle.git] / lib / weblib.php
blobcbaaeca17f7e50cf4304b657411d6eeca6631ba6
1 <?php
2 // This file is part of Moodle - http://moodle.org/
3 //
4 // Moodle is free software: you can redistribute it and/or modify
5 // it under the terms of the GNU General Public License as published by
6 // the Free Software Foundation, either version 3 of the License, or
7 // (at your option) any later version.
8 //
9 // Moodle is distributed in the hope that it will be useful,
10 // but WITHOUT ANY WARRANTY; without even the implied warranty of
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 // GNU General Public License for more details.
14 // You should have received a copy of the GNU General Public License
15 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
17 /**
18 * Library of functions for web output
20 * Library of all general-purpose Moodle PHP functions and constants
21 * that produce HTML output
23 * Other main libraries:
24 * - datalib.php - functions that access the database.
25 * - moodlelib.php - general-purpose Moodle functions.
27 * @package core
28 * @subpackage lib
29 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
30 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
33 use Psr\Http\Message\UriInterface;
35 defined('MOODLE_INTERNAL') || die();
37 // Constants.
39 // Define text formatting types ... eventually we can add Wiki, BBcode etc.
41 /**
42 * Does all sorts of transformations and filtering.
44 define('FORMAT_MOODLE', '0');
46 /**
47 * Plain HTML (with some tags stripped).
49 define('FORMAT_HTML', '1');
51 /**
52 * Plain text (even tags are printed in full).
54 define('FORMAT_PLAIN', '2');
56 /**
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');
64 /**
65 * Markdown-formatted text http://daringfireball.net/projects/markdown/
67 define('FORMAT_MARKDOWN', '4');
69 /**
70 * A moodle_url comparison using this flag will return true if the base URLs match, params are ignored.
72 define('URL_MATCH_BASE', 0);
74 /**
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);
79 /**
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);
84 // Functions.
86 /**
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
93 * @return string
95 function s($var) {
96 if ($var === false) {
97 return '0';
100 if ($var === null || $var === '') {
101 return '';
104 return preg_replace(
105 '/&amp;#(\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()}.
115 * @see s()
117 * @param string $var the string potentially containing HTML characters
119 function p($var) {
120 echo s($var);
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);
143 $var = (object)$a;
145 return $var;
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 === '') {
158 return '';
161 if ($commapos = strpos($url, '?')) {
162 return substr($url, 0, $commapos);
163 } else {
164 return $url;
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.
178 function me() {
179 global $ME;
180 return $ME;
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);
198 } else {
199 if ($FULLME === null) {
200 // CLI script most probably.
201 return false;
203 if (!empty($CFG->sslproxy)) {
204 // Return only https links when using SSL proxy.
205 return preg_replace('/^http:/', 'https:', $FULLME, 1);
206 } else {
207 return $FULLME;
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() {
221 global $CFG;
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);
235 if ($stripquery) {
236 return strip_querystring($referer);
237 } else {
238 return $referer;
240 } else {
241 return '';
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
261 * @package core
263 class moodle_url {
266 * Scheme, ex.: http, https
267 * @var string
269 protected $scheme = '';
272 * Hostname.
273 * @var string
275 protected $host = '';
278 * Port number, empty means default 80 or 443 in case of http.
279 * @var int
281 protected $port = '';
284 * Username for http auth.
285 * @var string
287 protected $user = '';
290 * Password for http auth.
291 * @var string
293 protected $pass = '';
296 * Script path.
297 * @var string
299 protected $path = '';
302 * Optional slash argument value.
303 * @var string
305 protected $slashargument = '';
308 * Anchor, may be also empty, null means none.
309 * @var string
311 protected $anchor = null;
314 * Url parameters as associative array.
315 * @var 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) {
333 global $CFG;
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;
346 } else {
347 $url = $url ?? '';
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);
368 // Parse the $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('&amp;', '&', $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) {
409 if (is_int($key)) {
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
450 * @return void
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) {
468 // Set new value.
469 $this->params(array($paramname => $newvalue));
471 if (isset($this->params[$paramname])) {
472 return $this->params[$paramname];
473 } else {
474 return null;
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) {
489 if (is_int($key)) {
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;
500 return $params;
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 &amp; 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) {
514 $arr = array();
515 if ($overrideparams !== null) {
516 $params = $this->merge_overrideparams($overrideparams);
517 } else {
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);
525 } else {
526 if (isset($val) && $val !== '') {
527 $arr[] = rawurlencode($key)."=".rawurlencode($val);
528 } else {
529 $arr[] = rawurlencode($key);
533 if ($escaped) {
534 return implode('&amp;', $arr);
535 } else {
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 {
548 $data = [];
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];
554 } else {
555 $data[] = ['name' => $key, 'value' => $val];
558 return $data;
562 * Shortcut for printing of encoded URL.
564 * @return string
566 public function __toString() {
567 return $this->out(true);
571 * Output url.
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 &amp; 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) {
582 global $CFG;
584 if (!is_bool($escaped)) {
585 debugging('Escape parameter must be of type boolean, '.gettype($escaped).' given instead.');
588 $url = $this;
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) {
595 $url = $pluginurl;
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 &amp; 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;
623 if (!is_null($this->anchor)) {
624 $uri .= '#'.$this->anchor;
627 return $uri;
631 * Returns url without parameters, everything before '?'.
633 * @param bool $includeanchor if {@link self::anchor} is defined, should it be returned?
634 * @return string
636 public function out_omit_querystring($includeanchor = false) {
638 $uri = $this->scheme ? $this->scheme.':'.((strtolower($this->scheme) == 'mailto') ? '':'//'): '';
639 $uri .= $this->user ? $this->user.($this->pass? ':'.$this->pass:'').'@':'';
640 $uri .= $this->host ? $this->host : '';
641 $uri .= $this->port ? ':'.$this->port : '';
642 $uri .= $this->path ? $this->path : '';
643 if ($includeanchor and !is_null($this->anchor)) {
644 $uri .= '#' . $this->anchor;
647 return $uri;
651 * Compares this moodle_url with another.
653 * See documentation of constants for an explanation of the comparison flags.
655 * @param moodle_url $url The moodle_url object to compare
656 * @param int $matchtype The type of comparison (URL_MATCH_BASE, URL_MATCH_PARAMS, URL_MATCH_EXACT)
657 * @return bool
659 public function compare(moodle_url $url, $matchtype = URL_MATCH_EXACT) {
661 $baseself = $this->out_omit_querystring();
662 $baseother = $url->out_omit_querystring();
664 // Append index.php if there is no specific file.
665 if (substr($baseself, -1) == '/') {
666 $baseself .= 'index.php';
668 if (substr($baseother, -1) == '/') {
669 $baseother .= 'index.php';
672 // Compare the two base URLs.
673 if ($baseself != $baseother) {
674 return false;
677 if ($matchtype == URL_MATCH_BASE) {
678 return true;
681 $urlparams = $url->params();
682 foreach ($this->params() as $param => $value) {
683 if ($param == 'sesskey') {
684 continue;
686 if (!array_key_exists($param, $urlparams) || $urlparams[$param] != $value) {
687 return false;
691 if ($matchtype == URL_MATCH_PARAMS) {
692 return true;
695 foreach ($urlparams as $param => $value) {
696 if ($param == 'sesskey') {
697 continue;
699 if (!array_key_exists($param, $this->params()) || $this->param($param) != $value) {
700 return false;
704 if ($url->anchor !== $this->anchor) {
705 return false;
708 return true;
712 * Sets the anchor for the URI (the bit after the hash)
714 * @param string $anchor null means remove previous
716 public function set_anchor($anchor) {
717 if (is_null($anchor)) {
718 // Remove.
719 $this->anchor = null;
720 } else if ($anchor === '') {
721 // Special case, used as empty link.
722 $this->anchor = '';
723 } else if (preg_match('|[a-zA-Z\_\:][a-zA-Z0-9\_\-\.\:]*|', $anchor)) {
724 // Match the anchor against the NMTOKEN spec.
725 $this->anchor = $anchor;
726 } else {
727 // Bad luck, no valid anchor found.
728 $this->anchor = null;
733 * Sets the scheme for the URI (the bit before ://)
735 * @param string $scheme
737 public function set_scheme($scheme) {
738 // See http://www.ietf.org/rfc/rfc3986.txt part 3.1.
739 if (preg_match('/^[a-zA-Z][a-zA-Z0-9+.-]*$/', $scheme)) {
740 $this->scheme = $scheme;
741 } else {
742 throw new coding_exception('Bad URL scheme.');
747 * Sets the url slashargument value.
749 * @param string $path usually file path
750 * @param string $parameter name of page parameter if slasharguments not supported
751 * @param bool $supported usually null, then it depends on $CFG->slasharguments, use true or false for other servers
752 * @return void
754 public function set_slashargument($path, $parameter = 'file', $supported = null) {
755 global $CFG;
756 if (is_null($supported)) {
757 $supported = !empty($CFG->slasharguments);
760 if ($supported) {
761 $parts = explode('/', $path);
762 $parts = array_map('rawurlencode', $parts);
763 $path = implode('/', $parts);
764 $this->slashargument = $path;
765 unset($this->params[$parameter]);
767 } else {
768 $this->slashargument = '';
769 $this->params[$parameter] = $path;
773 // Static factory methods.
776 * Create a new moodle_url instance from a UriInterface.
778 * @param UriInterface $uri
779 * @return self
781 public static function from_uri(UriInterface $uri): self {
782 $url = new self(
783 url: $uri->getScheme() . '://' . $uri->getAuthority() . $uri->getPath(),
784 anchor: $uri->getFragment() ?: null,
787 $params = $uri->getQuery();
788 foreach (explode('&', $params) as $param) {
789 $url->param(...explode('=', $param, 2));
792 return $url;
796 * General moodle file url.
798 * @param string $urlbase the script serving the file
799 * @param string $path
800 * @param bool $forcedownload
801 * @return moodle_url
803 public static function make_file_url($urlbase, $path, $forcedownload = false) {
804 $params = array();
805 if ($forcedownload) {
806 $params['forcedownload'] = 1;
808 $url = new moodle_url($urlbase, $params);
809 $url->set_slashargument($path);
810 return $url;
814 * Factory method for creation of url pointing to plugin file.
816 * Please note this method can be used only from the plugins to
817 * create urls of own files, it must not be used outside of plugins!
819 * @param int $contextid
820 * @param string $component
821 * @param string $area
822 * @param int $itemid
823 * @param string $pathname
824 * @param string $filename
825 * @param bool $forcedownload
826 * @param mixed $includetoken Whether to use a user token when displaying this group image.
827 * True indicates to generate a token for current user, and integer value indicates to generate a token for the
828 * user whose id is the value indicated.
829 * If the group picture is included in an e-mail or some other location where the audience is a specific
830 * user who will not be logged in when viewing, then we use a token to authenticate the user.
831 * @return moodle_url
833 public static function make_pluginfile_url($contextid, $component, $area, $itemid, $pathname, $filename,
834 $forcedownload = false, $includetoken = false) {
835 global $CFG, $USER;
837 $path = [];
839 if ($includetoken) {
840 $urlbase = "$CFG->wwwroot/tokenpluginfile.php";
841 $userid = $includetoken === true ? $USER->id : $includetoken;
842 $token = get_user_key('core_files', $userid);
843 if ($CFG->slasharguments) {
844 $path[] = $token;
846 } else {
847 $urlbase = "$CFG->wwwroot/pluginfile.php";
849 $path[] = $contextid;
850 $path[] = $component;
851 $path[] = $area;
853 if ($itemid !== null) {
854 $path[] = $itemid;
857 $path = "/" . implode('/', $path) . "{$pathname}{$filename}";
859 $url = self::make_file_url($urlbase, $path, $forcedownload, $includetoken);
860 if ($includetoken && empty($CFG->slasharguments)) {
861 $url->param('token', $token);
863 return $url;
867 * Factory method for creation of url pointing to plugin file.
868 * This method is the same that make_pluginfile_url but pointing to the webservice pluginfile.php script.
869 * It should be used only in external functions.
871 * @since 2.8
872 * @param int $contextid
873 * @param string $component
874 * @param string $area
875 * @param int $itemid
876 * @param string $pathname
877 * @param string $filename
878 * @param bool $forcedownload
879 * @return moodle_url
881 public static function make_webservice_pluginfile_url($contextid, $component, $area, $itemid, $pathname, $filename,
882 $forcedownload = false) {
883 global $CFG;
884 $urlbase = "$CFG->wwwroot/webservice/pluginfile.php";
885 if ($itemid === null) {
886 return self::make_file_url($urlbase, "/$contextid/$component/$area".$pathname.$filename, $forcedownload);
887 } else {
888 return self::make_file_url($urlbase, "/$contextid/$component/$area/$itemid".$pathname.$filename, $forcedownload);
893 * Factory method for creation of url pointing to draft file of current user.
895 * @param int $draftid draft item id
896 * @param string $pathname
897 * @param string $filename
898 * @param bool $forcedownload
899 * @return moodle_url
901 public static function make_draftfile_url($draftid, $pathname, $filename, $forcedownload = false) {
902 global $CFG, $USER;
903 $urlbase = "$CFG->wwwroot/draftfile.php";
904 $context = context_user::instance($USER->id);
906 return self::make_file_url($urlbase, "/$context->id/user/draft/$draftid".$pathname.$filename, $forcedownload);
910 * Factory method for creating of links to legacy course files.
912 * @param int $courseid
913 * @param string $filepath
914 * @param bool $forcedownload
915 * @return moodle_url
917 public static function make_legacyfile_url($courseid, $filepath, $forcedownload = false) {
918 global $CFG;
920 $urlbase = "$CFG->wwwroot/file.php";
921 return self::make_file_url($urlbase, '/'.$courseid.'/'.$filepath, $forcedownload);
925 * Checks if URL is relative to $CFG->wwwroot.
927 * @return bool True if URL is relative to $CFG->wwwroot; otherwise, false.
929 public function is_local_url(): bool {
930 global $CFG;
932 $url = $this->out();
933 // Does URL start with wwwroot? Otherwise, URL isn't relative to wwwroot.
934 return ( ($url === $CFG->wwwroot) || (strpos($url, $CFG->wwwroot.'/') === 0) );
938 * Returns URL as relative path from $CFG->wwwroot
940 * Can be used for passing around urls with the wwwroot stripped
942 * @param boolean $escaped Use &amp; as params separator instead of plain &
943 * @param array $overrideparams params to add to the output url, these override existing ones with the same name.
944 * @return string Resulting URL
945 * @throws coding_exception if called on a non-local url
947 public function out_as_local_url($escaped = true, array $overrideparams = null) {
948 global $CFG;
950 // URL should be relative to wwwroot. If not then throw exception.
951 if ($this->is_local_url()) {
952 $url = $this->out($escaped, $overrideparams);
953 $localurl = substr($url, strlen($CFG->wwwroot));
954 return !empty($localurl) ? $localurl : '';
955 } else {
956 throw new coding_exception('out_as_local_url called on a non-local URL');
961 * Returns the 'path' portion of a URL. For example, if the URL is
962 * http://www.example.org:447/my/file/is/here.txt?really=1 then this will
963 * return '/my/file/is/here.txt'.
965 * By default the path includes slash-arguments (for example,
966 * '/myfile.php/extra/arguments') so it is what you would expect from a
967 * URL path. If you don't want this behaviour, you can opt to exclude the
968 * slash arguments. (Be careful: if the $CFG variable slasharguments is
969 * disabled, these URLs will have a different format and you may need to
970 * look at the 'file' parameter too.)
972 * @param bool $includeslashargument If true, includes slash arguments
973 * @return string Path of URL
975 public function get_path($includeslashargument = true) {
976 return $this->path . ($includeslashargument ? $this->slashargument : '');
980 * Returns a given parameter value from the URL.
982 * @param string $name Name of parameter
983 * @return string Value of parameter or null if not set
985 public function get_param($name) {
986 if (array_key_exists($name, $this->params)) {
987 return $this->params[$name];
988 } else {
989 return null;
994 * Returns the 'scheme' portion of a URL. For example, if the URL is
995 * http://www.example.org:447/my/file/is/here.txt?really=1 then this will
996 * return 'http' (without the colon).
998 * @return string Scheme of the URL.
1000 public function get_scheme() {
1001 return $this->scheme;
1005 * Returns the 'host' portion of a URL. For example, if the URL is
1006 * http://www.example.org:447/my/file/is/here.txt?really=1 then this will
1007 * return 'www.example.org'.
1009 * @return string Host of the URL.
1011 public function get_host() {
1012 return $this->host;
1016 * Returns the 'port' portion of a URL. For example, if the URL is
1017 * http://www.example.org:447/my/file/is/here.txt?really=1 then this will
1018 * return '447'.
1020 * @return string Port of the URL.
1022 public function get_port() {
1023 return $this->port;
1028 * Determine if there is data waiting to be processed from a form
1030 * Used on most forms in Moodle to check for data
1031 * Returns the data as an object, if it's found.
1032 * This object can be used in foreach loops without
1033 * casting because it's cast to (array) automatically
1035 * Checks that submitted POST data exists and returns it as object.
1037 * @return mixed false or object
1039 function data_submitted() {
1041 if (empty($_POST)) {
1042 return false;
1043 } else {
1044 return (object)fix_utf8($_POST);
1049 * Given some normal text this function will break up any
1050 * long words to a given size by inserting the given character
1052 * It's multibyte savvy and doesn't change anything inside html tags.
1054 * @param string $string the string to be modified
1055 * @param int $maxsize maximum length of the string to be returned
1056 * @param string $cutchar the string used to represent word breaks
1057 * @return string
1059 function break_up_long_words($string, $maxsize=20, $cutchar=' ') {
1061 // First of all, save all the tags inside the text to skip them.
1062 $tags = array();
1063 filter_save_tags($string, $tags);
1065 // Process the string adding the cut when necessary.
1066 $output = '';
1067 $length = core_text::strlen($string);
1068 $wordlength = 0;
1070 for ($i=0; $i<$length; $i++) {
1071 $char = core_text::substr($string, $i, 1);
1072 if ($char == ' ' or $char == "\t" or $char == "\n" or $char == "\r" or $char == "<" or $char == ">") {
1073 $wordlength = 0;
1074 } else {
1075 $wordlength++;
1076 if ($wordlength > $maxsize) {
1077 $output .= $cutchar;
1078 $wordlength = 0;
1081 $output .= $char;
1084 // Finally load the tags back again.
1085 if (!empty($tags)) {
1086 $output = str_replace(array_keys($tags), $tags, $output);
1089 return $output;
1093 * Try and close the current window using JavaScript, either immediately, or after a delay.
1095 * Echo's out the resulting XHTML & javascript
1097 * @param integer $delay a delay in seconds before closing the window. Default 0.
1098 * @param boolean $reloadopener if true, we will see if this window was a pop-up, and try
1099 * to reload the parent window before this one closes.
1101 function close_window($delay = 0, $reloadopener = false) {
1102 global $PAGE, $OUTPUT;
1104 if (!$PAGE->headerprinted) {
1105 $PAGE->set_title(get_string('closewindow'));
1106 echo $OUTPUT->header();
1107 } else {
1108 $OUTPUT->container_end_all(false);
1111 if ($reloadopener) {
1112 // Trigger the reload immediately, even if the reload is after a delay.
1113 $PAGE->requires->js_function_call('window.opener.location.reload', array(true));
1115 $OUTPUT->notification(get_string('windowclosing'), 'notifysuccess');
1117 $PAGE->requires->js_function_call('close_window', array(new stdClass()), false, $delay);
1119 echo $OUTPUT->footer();
1120 exit;
1124 * Returns a string containing a link to the user documentation for the current page.
1126 * Also contains an icon by default. Shown to teachers and admin only.
1128 * @param string $text The text to be displayed for the link
1129 * @return string The link to user documentation for this current page
1131 function page_doc_link($text='') {
1132 global $OUTPUT, $PAGE;
1133 $path = page_get_doc_link_path($PAGE);
1134 if (!$path) {
1135 return '';
1137 return $OUTPUT->doc_link($path, $text);
1141 * Returns the path to use when constructing a link to the docs.
1143 * @since Moodle 2.5.1 2.6
1144 * @param moodle_page $page
1145 * @return string
1147 function page_get_doc_link_path(moodle_page $page) {
1148 global $CFG;
1150 if (empty($CFG->docroot) || during_initial_install()) {
1151 return '';
1153 if (!has_capability('moodle/site:doclinks', $page->context)) {
1154 return '';
1157 $path = $page->docspath;
1158 if (!$path) {
1159 return '';
1161 return $path;
1166 * Validates an email to make sure it makes sense.
1168 * @param string $address The email address to validate.
1169 * @return boolean
1171 function validate_email($address) {
1172 global $CFG;
1174 if ($address === null || $address === false || $address === '') {
1175 return false;
1178 require_once("{$CFG->libdir}/phpmailer/moodle_phpmailer.php");
1180 return moodle_phpmailer::validateAddress($address ?? '') && !preg_match('/[<>]/', $address);
1184 * Extracts file argument either from file parameter or PATH_INFO
1186 * Note: $scriptname parameter is not needed anymore
1188 * @return string file path (only safe characters)
1190 function get_file_argument() {
1191 global $SCRIPT;
1193 $relativepath = false;
1194 $hasforcedslashargs = false;
1196 if (isset($_SERVER['REQUEST_URI']) && !empty($_SERVER['REQUEST_URI'])) {
1197 // Checks whether $_SERVER['REQUEST_URI'] contains '/pluginfile.php/'
1198 // instead of '/pluginfile.php?', when serving a file from e.g. mod_imscp or mod_scorm.
1199 if ((strpos($_SERVER['REQUEST_URI'], '/pluginfile.php/') !== false)
1200 && isset($_SERVER['PATH_INFO']) && !empty($_SERVER['PATH_INFO'])) {
1201 // Exclude edge cases like '/pluginfile.php/?file='.
1202 $args = explode('/', ltrim($_SERVER['PATH_INFO'], '/'));
1203 $hasforcedslashargs = (count($args) > 2); // Always at least: context, component and filearea.
1206 if (!$hasforcedslashargs) {
1207 $relativepath = optional_param('file', false, PARAM_PATH);
1210 if ($relativepath !== false and $relativepath !== '') {
1211 return $relativepath;
1213 $relativepath = false;
1215 // Then try extract file from the slasharguments.
1216 if (stripos($_SERVER['SERVER_SOFTWARE'], 'iis') !== false) {
1217 // NOTE: IIS tends to convert all file paths to single byte DOS encoding,
1218 // we can not use other methods because they break unicode chars,
1219 // the only ways are to use URL rewriting
1220 // OR
1221 // to properly set the 'FastCGIUtf8ServerVariables' registry key.
1222 if (isset($_SERVER['PATH_INFO']) and $_SERVER['PATH_INFO'] !== '') {
1223 // Check that PATH_INFO works == must not contain the script name.
1224 if (strpos($_SERVER['PATH_INFO'], $SCRIPT) === false) {
1225 $relativepath = clean_param(urldecode($_SERVER['PATH_INFO']), PARAM_PATH);
1228 } else {
1229 // All other apache-like servers depend on PATH_INFO.
1230 if (isset($_SERVER['PATH_INFO'])) {
1231 if (isset($_SERVER['SCRIPT_NAME']) and strpos($_SERVER['PATH_INFO'], $_SERVER['SCRIPT_NAME']) === 0) {
1232 $relativepath = substr($_SERVER['PATH_INFO'], strlen($_SERVER['SCRIPT_NAME']));
1233 } else {
1234 $relativepath = $_SERVER['PATH_INFO'];
1236 $relativepath = clean_param($relativepath, PARAM_PATH);
1240 return $relativepath;
1244 * Just returns an array of text formats suitable for a popup menu
1246 * @return array
1248 function format_text_menu() {
1249 return array (FORMAT_MOODLE => get_string('formattext'),
1250 FORMAT_HTML => get_string('formathtml'),
1251 FORMAT_PLAIN => get_string('formatplain'),
1252 FORMAT_MARKDOWN => get_string('formatmarkdown'));
1256 * Given text in a variety of format codings, this function returns the text as safe HTML.
1258 * This function should mainly be used for long strings like posts,
1259 * answers, glossary items etc. For short strings {@link format_string()}.
1261 * <pre>
1262 * Options:
1263 * trusted : If true the string won't be cleaned. Default false required noclean=true.
1264 * noclean : If true the string won't be cleaned, unless $CFG->forceclean is set. Default false required trusted=true.
1265 * filter : If true the string will be run through applicable filters as well. Default true.
1266 * para : If true then the returned string will be wrapped in div tags. Default true.
1267 * newlines : If true then lines newline breaks will be converted to HTML newline breaks. Default true.
1268 * context : The context that will be used for filtering.
1269 * overflowdiv : If set to true the formatted text will be encased in a div
1270 * with the class no-overflow before being returned. Default false.
1271 * allowid : If true then id attributes will not be removed, even when
1272 * using htmlpurifier. Default false.
1273 * blanktarget : If true all <a> tags will have target="_blank" added unless target is explicitly specified.
1274 * </pre>
1276 * @param string $text The text to be formatted. This is raw text originally from user input.
1277 * @param int $format Identifier of the text format to be used
1278 * [FORMAT_MOODLE, FORMAT_HTML, FORMAT_PLAIN, FORMAT_MARKDOWN]
1279 * @param stdClass|array $options text formatting options
1280 * @param int $courseiddonotuse deprecated course id, use context option instead
1281 * @return string
1283 function format_text($text, $format = FORMAT_MOODLE, $options = null, $courseiddonotuse = null) {
1284 global $CFG;
1286 // Manually include the formatting class for now until after the release after 4.5 LTS.
1287 require_once("{$CFG->libdir}/classes/formatting.php");
1289 if ($format === FORMAT_WIKI) {
1290 // This format was deprecated in Moodle 1.5.
1291 throw new \coding_exception(
1292 'Wiki-like formatting is not supported.'
1296 if ($options instanceof \core\context) {
1297 // A common mistake has been to call this function with a context object.
1298 // This has never been expected, or nor supported.
1299 debugging(
1300 'The options argument should not be a context object directly. ' .
1301 ' Please pass an array with a context key instead.',
1302 DEBUG_DEVELOPER,
1304 $params['context'] = $options;
1305 $options = [];
1308 if ($options) {
1309 $options = (array) $options;
1312 if (empty($CFG->version) || $CFG->version < 2013051400 || during_initial_install()) {
1313 // Do not filter anything during installation or before upgrade completes.
1314 $params['context'] = null;
1315 } else if ($options && isset($options['context'])) { // First by explicit passed context option.
1316 if (is_numeric($options['context'])) {
1317 // A contextid was passed.
1318 $params['context'] = \core\context::instance_by_id($options['context']);
1319 } else if ($options['context'] instanceof \core\context) {
1320 $params['context'] = $options['context'];
1321 } else {
1322 debugging(
1323 'Unknown context passed to format_text(). Content will not be filtered.',
1324 DEBUG_DEVELOPER,
1328 // Unset the context from $options to prevent it overriding the configured value.
1329 unset($options['context']);
1330 } else if ($courseiddonotuse) {
1331 // Legacy courseid.
1332 $params['context'] = \core\context\course::instance($courseiddonotuse);
1333 debugging(
1334 "Passing a courseid to format_text() is deprecated, please pass a context instead.",
1335 DEBUG_DEVELOPER,
1339 $params['text'] = $text;
1341 if ($options) {
1342 // The smiley option was deprecated in Moodle 2.0.
1343 if (array_key_exists('smiley', $options)) {
1344 unset($options['smiley']);
1345 debugging(
1346 'The smiley option is deprecated and no longer used.',
1347 DEBUG_DEVELOPER,
1351 // The nocache option was deprecated in Moodle 2.3 in MDL-34347.
1352 if (array_key_exists('nocache', $options)) {
1353 unset($options['nocache']);
1354 debugging(
1355 'The nocache option is deprecated and no longer used.',
1356 DEBUG_DEVELOPER,
1360 $validoptions = [
1361 'text',
1362 'format',
1363 'context',
1364 'trusted',
1365 'clean',
1366 'filter',
1367 'para',
1368 'newlines',
1369 'overflowdiv',
1370 'blanktarget',
1371 'allowid',
1372 'noclean',
1375 $invalidoptions = array_diff(array_keys($options), $validoptions);
1376 if ($invalidoptions) {
1377 debugging(sprintf(
1378 'The following options are not valid: %s',
1379 implode(', ', $invalidoptions),
1380 ), DEBUG_DEVELOPER);
1381 foreach ($invalidoptions as $option) {
1382 unset($options[$option]);
1386 foreach ($options as $option => $value) {
1387 $params[$option] = $value;
1390 // The noclean option has been renamed to clean.
1391 if (array_key_exists('noclean', $params)) {
1392 $params['clean'] = !$params['noclean'];
1393 unset($params['noclean']);
1397 if ($format !== null) {
1398 $params['format'] = $format;
1401 return \core\di::get(\core\formatting::class)->format_text(...$params);
1405 * Resets some data related to filters, called during upgrade or when general filter settings change.
1407 * @param bool $phpunitreset true means called from our PHPUnit integration test reset
1408 * @return void
1410 function reset_text_filters_cache($phpunitreset = false) {
1411 global $CFG, $DB;
1413 if ($phpunitreset) {
1414 // HTMLPurifier does not change, DB is already reset to defaults,
1415 // nothing to do here, the dataroot was cleared too.
1416 return;
1419 // The purge_all_caches() deals with cachedir and localcachedir purging,
1420 // the individual filter caches are invalidated as necessary elsewhere.
1422 // Update $CFG->filterall cache flag.
1423 if (empty($CFG->stringfilters)) {
1424 set_config('filterall', 0);
1425 return;
1427 $installedfilters = core_component::get_plugin_list('filter');
1428 $filters = explode(',', $CFG->stringfilters);
1429 foreach ($filters as $filter) {
1430 if (isset($installedfilters[$filter])) {
1431 set_config('filterall', 1);
1432 return;
1435 set_config('filterall', 0);
1439 * Given a simple string, this function returns the string
1440 * processed by enabled string filters if $CFG->filterall is enabled
1442 * This function should be used to print short strings (non html) that
1443 * need filter processing e.g. activity titles, post subjects,
1444 * glossary concepts.
1446 * @staticvar bool $strcache
1447 * @param string $string The string to be filtered. Should be plain text, expect
1448 * possibly for multilang tags.
1449 * @param boolean $striplinks To strip any link in the result text. Moodle 1.8 default changed from false to true! MDL-8713
1450 * @param array $options options array/object or courseid
1451 * @return string
1453 function format_string($string, $striplinks = true, $options = null) {
1454 global $CFG;
1456 // Manually include the formatting class for now until after the release after 4.5 LTS.
1457 require_once("{$CFG->libdir}/classes/formatting.php");
1459 $params = [
1460 'string' => $string,
1461 'striplinks' => (bool) $striplinks,
1464 // This method only expects either:
1465 // - an array of options;
1466 // - a stdClass of options to be cast to an array; or
1467 // - an integer courseid.
1468 if ($options instanceof \core\context) {
1469 // A common mistake has been to call this function with a context object.
1470 // This has never been expected, or nor supported.
1471 debugging(
1472 'The options argument should not be a context object directly. ' .
1473 ' Please pass an array with a context key instead.',
1474 DEBUG_DEVELOPER,
1476 $params['context'] = $options;
1477 $options = [];
1478 } else if (is_numeric($options)) {
1479 // Legacy courseid usage.
1480 $params['context'] = \core\context\course::instance($options);
1481 $options = [];
1482 } else if (is_array($options) || is_a($options, \stdClass::class)) {
1483 $options = (array) $options;
1484 if (isset($options['context'])) {
1485 if (is_numeric($options['context'])) {
1486 // A contextid was passed usage.
1487 $params['context'] = \core\context::instance_by_id($options['context']);
1488 } else if ($options['context'] instanceof \core\context) {
1489 $params['context'] = $options['context'];
1490 } else {
1491 debugging(
1492 'An invalid value for context was provided.',
1493 DEBUG_DEVELOPER,
1497 } else if ($options !== null) {
1498 // Something else was passed, so we'll just use an empty array.
1499 debugging(sprintf(
1500 'The options argument should be an Array, or stdclass. %s passed.',
1501 gettype($options),
1502 ), DEBUG_DEVELOPER);
1504 // Attempt to cast to array since we always used to, but throw in some debugging.
1505 $options = array_filter(
1506 (array) $options,
1507 fn ($key) => !is_numeric($key),
1508 ARRAY_FILTER_USE_KEY,
1512 if (isset($options['filter'])) {
1513 $params['filter'] = (bool) $options['filter'];
1514 } else {
1515 $params['filter'] = true;
1518 if (isset($options['escape'])) {
1519 $params['escape'] = (bool) $options['escape'];
1520 } else {
1521 $params['escape'] = true;
1524 $validoptions = [
1525 'string',
1526 'striplinks',
1527 'context',
1528 'filter',
1529 'escape',
1532 if ($options) {
1533 $invalidoptions = array_diff(array_keys($options), $validoptions);
1534 if ($invalidoptions) {
1535 debugging(sprintf(
1536 'The following options are not valid: %s',
1537 implode(', ', $invalidoptions),
1538 ), DEBUG_DEVELOPER);
1542 return \core\di::get(\core\formatting::class)->format_string(
1543 ...$params,
1548 * Given a string, performs a negative lookahead looking for any ampersand character
1549 * that is not followed by a proper HTML entity. If any is found, it is replaced
1550 * by &amp;. The string is then returned.
1552 * @param string $string
1553 * @return string
1555 function replace_ampersands_not_followed_by_entity($string) {
1556 return preg_replace("/\&(?![a-zA-Z0-9#]{1,8};)/", "&amp;", $string ?? '');
1560 * Given a string, replaces all <a>.*</a> by .* and returns the string.
1562 * @param string $string
1563 * @return string
1565 function strip_links($string) {
1566 return preg_replace('/(<a\s[^>]+?>)(.+?)(<\/a>)/is', '$2', $string);
1570 * This expression turns links into something nice in a text format. (Russell Jungwirth)
1572 * @param string $string
1573 * @return string
1575 function wikify_links($string) {
1576 return preg_replace('~(<a [^<]*href=["|\']?([^ "\']*)["|\']?[^>]*>([^<]*)</a>)~i', '$3 [ $2 ]', $string);
1580 * Given text in a variety of format codings, this function returns the text as plain text suitable for plain email.
1582 * @param string $text The text to be formatted. This is raw text originally from user input.
1583 * @param int $format Identifier of the text format to be used
1584 * [FORMAT_MOODLE, FORMAT_HTML, FORMAT_PLAIN, FORMAT_WIKI, FORMAT_MARKDOWN]
1585 * @return string
1587 function format_text_email($text, $format) {
1589 switch ($format) {
1591 case FORMAT_PLAIN:
1592 return $text;
1593 break;
1595 case FORMAT_WIKI:
1596 // There should not be any of these any more!
1597 $text = wikify_links($text);
1598 return core_text::entities_to_utf8(strip_tags($text), true);
1599 break;
1601 case FORMAT_HTML:
1602 return html_to_text($text);
1603 break;
1605 case FORMAT_MOODLE:
1606 case FORMAT_MARKDOWN:
1607 default:
1608 $text = wikify_links($text);
1609 return core_text::entities_to_utf8(strip_tags($text), true);
1610 break;
1615 * Formats activity intro text
1617 * @param string $module name of module
1618 * @param object $activity instance of activity
1619 * @param int $cmid course module id
1620 * @param bool $filter filter resulting html text
1621 * @return string
1623 function format_module_intro($module, $activity, $cmid, $filter=true) {
1624 global $CFG;
1625 require_once("$CFG->libdir/filelib.php");
1626 $context = context_module::instance($cmid);
1627 $options = array('noclean' => true, 'para' => false, 'filter' => $filter, 'context' => $context, 'overflowdiv' => true);
1628 $intro = file_rewrite_pluginfile_urls($activity->intro, 'pluginfile.php', $context->id, 'mod_'.$module, 'intro', null);
1629 return trim(format_text($intro, $activity->introformat, $options, null));
1633 * Removes the usage of Moodle files from a text.
1635 * In some rare cases we need to re-use a text that already has embedded links
1636 * to some files hosted within Moodle. But the new area in which we will push
1637 * this content does not support files... therefore we need to remove those files.
1639 * @param string $source The text
1640 * @return string The stripped text
1642 function strip_pluginfile_content($source) {
1643 $baseurl = '@@PLUGINFILE@@';
1644 // Looking for something like < .* "@@pluginfile@@.*" .* >
1645 $pattern = '$<[^<>]+["\']' . $baseurl . '[^"\']*["\'][^<>]*>$';
1646 $stripped = preg_replace($pattern, '', $source);
1647 // Use purify html to rebalence potentially mismatched tags and generally cleanup.
1648 return purify_html($stripped);
1652 * Legacy function, used for cleaning of old forum and glossary text only.
1654 * @param string $text text that may contain legacy TRUSTTEXT marker
1655 * @return string text without legacy TRUSTTEXT marker
1657 function trusttext_strip($text) {
1658 if (!is_string($text)) {
1659 // This avoids the potential for an endless loop below.
1660 throw new coding_exception('trusttext_strip parameter must be a string');
1662 while (true) { // Removing nested TRUSTTEXT.
1663 $orig = $text;
1664 $text = str_replace('#####TRUSTTEXT#####', '', $text);
1665 if (strcmp($orig, $text) === 0) {
1666 return $text;
1672 * Must be called before editing of all texts with trust flag. Removes all XSS nasties from texts stored in database if needed.
1674 * @param stdClass $object data object with xxx, xxxformat and xxxtrust fields
1675 * @param string $field name of text field
1676 * @param context $context active context
1677 * @return stdClass updated $object
1679 function trusttext_pre_edit($object, $field, $context) {
1680 $trustfield = $field.'trust';
1681 $formatfield = $field.'format';
1683 if ($object->$formatfield == FORMAT_MARKDOWN) {
1684 // We do not have a way to sanitise Markdown texts,
1685 // luckily editors for this format should not have XSS problems.
1686 return $object;
1689 if (!$object->$trustfield or !trusttext_trusted($context)) {
1690 $object->$field = clean_text($object->$field, $object->$formatfield);
1693 return $object;
1697 * Is current user trusted to enter no dangerous XSS in this context?
1699 * Please note the user must be in fact trusted everywhere on this server!!
1701 * @param context $context
1702 * @return bool true if user trusted
1704 function trusttext_trusted($context) {
1705 return (trusttext_active() and has_capability('moodle/site:trustcontent', $context));
1709 * Is trusttext feature active?
1711 * @return bool
1713 function trusttext_active() {
1714 global $CFG;
1716 return !empty($CFG->enabletrusttext);
1720 * Cleans raw text removing nasties.
1722 * Given raw text (eg typed in by a user) this function cleans it up and removes any nasty tags that could mess up
1723 * Moodle pages through XSS attacks.
1725 * The result must be used as a HTML text fragment, this function can not cleanup random
1726 * parts of html tags such as url or src attributes.
1728 * NOTE: the format parameter was deprecated because we can safely clean only HTML.
1730 * @param string $text The text to be cleaned
1731 * @param int|string $format deprecated parameter, should always contain FORMAT_HTML or FORMAT_MOODLE
1732 * @param array $options Array of options; currently only option supported is 'allowid' (if true,
1733 * does not remove id attributes when cleaning)
1734 * @return string The cleaned up text
1736 function clean_text($text, $format = FORMAT_HTML, $options = array()) {
1737 $text = (string)$text;
1739 if ($format != FORMAT_HTML and $format != FORMAT_HTML) {
1740 // TODO: we need to standardise cleanup of text when loading it into editor first.
1741 // debugging('clean_text() is designed to work only with html');.
1744 if ($format == FORMAT_PLAIN) {
1745 return $text;
1748 if (is_purify_html_necessary($text)) {
1749 $text = purify_html($text, $options);
1752 // Originally we tried to neutralise some script events here, it was a wrong approach because
1753 // it was trivial to work around that (for example using style based XSS exploits).
1754 // We must not give false sense of security here - all developers MUST understand how to use
1755 // rawurlencode(), htmlentities(), htmlspecialchars(), p(), s(), moodle_url, html_writer and friends!!!
1757 return $text;
1761 * Is it necessary to use HTMLPurifier?
1763 * @private
1764 * @param string $text
1765 * @return bool false means html is safe and valid, true means use HTMLPurifier
1767 function is_purify_html_necessary($text) {
1768 if ($text === '') {
1769 return false;
1772 if ($text === (string)((int)$text)) {
1773 return false;
1776 if (strpos($text, '&') !== false or preg_match('|<[^pesb/]|', $text)) {
1777 // We need to normalise entities or other tags except p, em, strong and br present.
1778 return true;
1781 $altered = htmlspecialchars($text, ENT_NOQUOTES, 'UTF-8', true);
1782 if ($altered === $text) {
1783 // No < > or other special chars means this must be safe.
1784 return false;
1787 // Let's try to convert back some safe html tags.
1788 $altered = preg_replace('|&lt;p&gt;(.*?)&lt;/p&gt;|m', '<p>$1</p>', $altered);
1789 if ($altered === $text) {
1790 return false;
1792 $altered = preg_replace('|&lt;em&gt;([^<>]+?)&lt;/em&gt;|m', '<em>$1</em>', $altered);
1793 if ($altered === $text) {
1794 return false;
1796 $altered = preg_replace('|&lt;strong&gt;([^<>]+?)&lt;/strong&gt;|m', '<strong>$1</strong>', $altered);
1797 if ($altered === $text) {
1798 return false;
1800 $altered = str_replace('&lt;br /&gt;', '<br />', $altered);
1801 if ($altered === $text) {
1802 return false;
1805 return true;
1809 * KSES replacement cleaning function - uses HTML Purifier.
1811 * @param string $text The (X)HTML string to purify
1812 * @param array $options Array of options; currently only option supported is 'allowid' (if set,
1813 * does not remove id attributes when cleaning)
1814 * @return string
1816 function purify_html($text, $options = array()) {
1817 global $CFG;
1819 $text = (string)$text;
1821 static $purifiers = array();
1822 static $caches = array();
1824 // Purifier code can change only during major version upgrade.
1825 $version = empty($CFG->version) ? 0 : $CFG->version;
1826 $cachedir = "$CFG->localcachedir/htmlpurifier/$version";
1827 if (!file_exists($cachedir)) {
1828 // Purging of caches may remove the cache dir at any time,
1829 // luckily file_exists() results should be cached for all existing directories.
1830 $purifiers = array();
1831 $caches = array();
1832 gc_collect_cycles();
1834 make_localcache_directory('htmlpurifier', false);
1835 check_dir_exists($cachedir);
1838 $allowid = empty($options['allowid']) ? 0 : 1;
1839 $allowobjectembed = empty($CFG->allowobjectembed) ? 0 : 1;
1841 $type = 'type_'.$allowid.'_'.$allowobjectembed;
1843 if (!array_key_exists($type, $caches)) {
1844 $caches[$type] = cache::make('core', 'htmlpurifier', array('type' => $type));
1846 $cache = $caches[$type];
1848 // Add revision number and all options to the text key so that it is compatible with local cluster node caches.
1849 $key = "|$version|$allowobjectembed|$allowid|$text";
1850 $filteredtext = $cache->get($key);
1852 if ($filteredtext === true) {
1853 // The filtering did not change the text last time, no need to filter anything again.
1854 return $text;
1855 } else if ($filteredtext !== false) {
1856 return $filteredtext;
1859 if (empty($purifiers[$type])) {
1860 require_once $CFG->libdir.'/htmlpurifier/HTMLPurifier.safe-includes.php';
1861 require_once $CFG->libdir.'/htmlpurifier/locallib.php';
1862 $config = HTMLPurifier_Config::createDefault();
1864 $config->set('HTML.DefinitionID', 'moodlehtml');
1865 $config->set('HTML.DefinitionRev', 7);
1866 $config->set('Cache.SerializerPath', $cachedir);
1867 $config->set('Cache.SerializerPermissions', $CFG->directorypermissions);
1868 $config->set('Core.NormalizeNewlines', false);
1869 $config->set('Core.ConvertDocumentToFragment', true);
1870 $config->set('Core.Encoding', 'UTF-8');
1871 $config->set('HTML.Doctype', 'XHTML 1.0 Transitional');
1872 $config->set('URI.AllowedSchemes', array(
1873 'http' => true,
1874 'https' => true,
1875 'ftp' => true,
1876 'irc' => true,
1877 'nntp' => true,
1878 'news' => true,
1879 'rtsp' => true,
1880 'rtmp' => true,
1881 'teamspeak' => true,
1882 'gopher' => true,
1883 'mms' => true,
1884 'mailto' => true
1886 $config->set('Attr.AllowedFrameTargets', array('_blank'));
1888 if ($allowobjectembed) {
1889 $config->set('HTML.SafeObject', true);
1890 $config->set('Output.FlashCompat', true);
1891 $config->set('HTML.SafeEmbed', true);
1894 if ($allowid) {
1895 $config->set('Attr.EnableID', true);
1898 if ($def = $config->maybeGetRawHTMLDefinition()) {
1899 $def->addElement('nolink', 'Inline', 'Flow', array()); // Skip our filters inside.
1900 $def->addElement('tex', 'Inline', 'Inline', array()); // Tex syntax, equivalent to $$xx$$.
1901 $def->addElement('algebra', 'Inline', 'Inline', array()); // Algebra syntax, equivalent to @@xx@@.
1902 $def->addElement('lang', 'Block', 'Flow', array(), array('lang'=>'CDATA')); // Original multilang style - only our hacked lang attribute.
1903 $def->addAttribute('span', 'xxxlang', 'CDATA'); // Current very problematic multilang.
1904 // Enable the bidirectional isolate element and its span equivalent.
1905 $def->addElement('bdi', 'Inline', 'Flow', 'Common');
1906 $def->addAttribute('span', 'dir', 'Enum#ltr,rtl,auto');
1908 // Media elements.
1909 // https://html.spec.whatwg.org/#the-video-element
1910 $def->addElement('video', 'Inline', 'Optional: #PCDATA | Flow | source | track', 'Common', [
1911 'src' => 'URI',
1912 'crossorigin' => 'Enum#anonymous,use-credentials',
1913 'poster' => 'URI',
1914 'preload' => 'Enum#auto,metadata,none',
1915 'autoplay' => 'Bool',
1916 'playsinline' => 'Bool',
1917 'loop' => 'Bool',
1918 'muted' => 'Bool',
1919 'controls' => 'Bool',
1920 'width' => 'Length',
1921 'height' => 'Length',
1923 // https://html.spec.whatwg.org/#the-audio-element
1924 $def->addElement('audio', 'Inline', 'Optional: #PCDATA | Flow | source | track', 'Common', [
1925 'src' => 'URI',
1926 'crossorigin' => 'Enum#anonymous,use-credentials',
1927 'preload' => 'Enum#auto,metadata,none',
1928 'autoplay' => 'Bool',
1929 'loop' => 'Bool',
1930 'muted' => 'Bool',
1931 'controls' => 'Bool'
1933 // https://html.spec.whatwg.org/#the-source-element
1934 $def->addElement('source', false, 'Empty', null, [
1935 'src' => 'URI',
1936 'type' => 'Text'
1938 // https://html.spec.whatwg.org/#the-track-element
1939 $def->addElement('track', false, 'Empty', null, [
1940 'src' => 'URI',
1941 'kind' => 'Enum#subtitles,captions,descriptions,chapters,metadata',
1942 'srclang' => 'Text',
1943 'label' => 'Text',
1944 'default' => 'Bool',
1947 // Use the built-in Ruby module to add annotation support.
1948 $def->manager->addModule(new HTMLPurifier_HTMLModule_Ruby());
1951 $purifier = new HTMLPurifier($config);
1952 $purifiers[$type] = $purifier;
1953 } else {
1954 $purifier = $purifiers[$type];
1957 $multilang = (strpos($text, 'class="multilang"') !== false);
1959 $filteredtext = $text;
1960 if ($multilang) {
1961 $filteredtextregex = '/<span(\s+lang="([a-zA-Z0-9_-]+)"|\s+class="multilang"){2}\s*>/';
1962 $filteredtext = preg_replace($filteredtextregex, '<span xxxlang="${2}">', $filteredtext);
1964 $filteredtext = (string)$purifier->purify($filteredtext);
1965 if ($multilang) {
1966 $filteredtext = preg_replace('/<span xxxlang="([a-zA-Z0-9_-]+)">/', '<span lang="${1}" class="multilang">', $filteredtext);
1969 if ($text === $filteredtext) {
1970 // No need to store the filtered text, next time we will just return unfiltered text
1971 // because it was not changed by purifying.
1972 $cache->set($key, true);
1973 } else {
1974 $cache->set($key, $filteredtext);
1977 return $filteredtext;
1981 * Given plain text, makes it into HTML as nicely as possible.
1983 * May contain HTML tags already.
1985 * Do not abuse this function. It is intended as lower level formatting feature used
1986 * by {@link format_text()} to convert FORMAT_MOODLE to HTML. You are supposed
1987 * to call format_text() in most of cases.
1989 * @param string $text The string to convert.
1990 * @param boolean $smileyignored Was used to determine if smiley characters should convert to smiley images, ignored now
1991 * @param boolean $para If true then the returned string will be wrapped in div tags
1992 * @param boolean $newlines If true then lines newline breaks will be converted to HTML newline breaks.
1993 * @return string
1995 function text_to_html($text, $smileyignored = null, $para = true, $newlines = true) {
1996 // Remove any whitespace that may be between HTML tags.
1997 $text = preg_replace("~>([[:space:]]+)<~i", "><", $text);
1999 // Remove any returns that precede or follow HTML tags.
2000 $text = preg_replace("~([\n\r])<~i", " <", $text);
2001 $text = preg_replace("~>([\n\r])~i", "> ", $text);
2003 // Make returns into HTML newlines.
2004 if ($newlines) {
2005 $text = nl2br($text);
2008 // Wrap the whole thing in a div if required.
2009 if ($para) {
2010 // In 1.9 this was changed from a p => div.
2011 return '<div class="text_to_html">'.$text.'</div>';
2012 } else {
2013 return $text;
2018 * Given Markdown formatted text, make it into XHTML using external function
2020 * @param string $text The markdown formatted text to be converted.
2021 * @return string Converted text
2023 function markdown_to_html($text) {
2024 global $CFG;
2026 if ($text === '' or $text === null) {
2027 return $text;
2030 require_once($CFG->libdir .'/markdown/MarkdownInterface.php');
2031 require_once($CFG->libdir .'/markdown/Markdown.php');
2032 require_once($CFG->libdir .'/markdown/MarkdownExtra.php');
2034 return \Michelf\MarkdownExtra::defaultTransform($text);
2038 * Given HTML text, make it into plain text using external function
2040 * @param string $html The text to be converted.
2041 * @param integer $width Width to wrap the text at. (optional, default 75 which
2042 * is a good value for email. 0 means do not limit line length.)
2043 * @param boolean $dolinks By default, any links in the HTML are collected, and
2044 * printed as a list at the end of the HTML. If you don't want that, set this
2045 * argument to false.
2046 * @return string plain text equivalent of the HTML.
2048 function html_to_text($html, $width = 75, $dolinks = true) {
2049 global $CFG;
2051 require_once($CFG->libdir .'/html2text/lib.php');
2053 $options = array(
2054 'width' => $width,
2055 'do_links' => 'table',
2058 if (empty($dolinks)) {
2059 $options['do_links'] = 'none';
2061 $h2t = new core_html2text($html, $options);
2062 $result = $h2t->getText();
2064 return $result;
2068 * Converts texts or strings to plain text.
2070 * - When used to convert user input introduced in an editor the text format needs to be passed in $contentformat like we usually
2071 * do in format_text.
2072 * - When this function is used for strings that are usually passed through format_string before displaying them
2073 * we need to set $contentformat to false. This will execute html_to_text as these strings can contain multilang tags if
2074 * multilang filter is applied to headings.
2076 * @param string $content The text as entered by the user
2077 * @param int|false $contentformat False for strings or the text format: FORMAT_MOODLE/FORMAT_HTML/FORMAT_PLAIN/FORMAT_MARKDOWN
2078 * @return string Plain text.
2080 function content_to_text($content, $contentformat) {
2082 switch ($contentformat) {
2083 case FORMAT_PLAIN:
2084 // Nothing here.
2085 break;
2086 case FORMAT_MARKDOWN:
2087 $content = markdown_to_html($content);
2088 $content = html_to_text($content, 75, false);
2089 break;
2090 default:
2091 // FORMAT_HTML, FORMAT_MOODLE and $contentformat = false, the later one are strings usually formatted through
2092 // format_string, we need to convert them from html because they can contain HTML (multilang filter).
2093 $content = html_to_text($content, 75, false);
2096 return trim($content, "\r\n ");
2100 * Factory method for extracting draft file links from arbitrary text using regular expressions. Only text
2101 * is required; other file fields may be passed to filter.
2103 * @param string $text Some html content.
2104 * @param bool $forcehttps force https urls.
2105 * @param int $contextid This parameter and the next three identify the file area to save to.
2106 * @param string $component The component name.
2107 * @param string $filearea The filearea.
2108 * @param int $itemid The item id for the filearea.
2109 * @param string $filename The specific filename of the file.
2110 * @return array
2112 function extract_draft_file_urls_from_text($text, $forcehttps = false, $contextid = null, $component = null,
2113 $filearea = null, $itemid = null, $filename = null) {
2114 global $CFG;
2116 $wwwroot = $CFG->wwwroot;
2117 if ($forcehttps) {
2118 $wwwroot = str_replace('http://', 'https://', $wwwroot);
2120 $urlstring = '/' . preg_quote($wwwroot, '/');
2122 $urlbase = preg_quote('draftfile.php');
2123 $urlstring .= "\/(?<urlbase>{$urlbase})";
2125 if (is_null($contextid)) {
2126 $contextid = '[0-9]+';
2128 $urlstring .= "\/(?<contextid>{$contextid})";
2130 if (is_null($component)) {
2131 $component = '[a-z_]+';
2133 $urlstring .= "\/(?<component>{$component})";
2135 if (is_null($filearea)) {
2136 $filearea = '[a-z_]+';
2138 $urlstring .= "\/(?<filearea>{$filearea})";
2140 if (is_null($itemid)) {
2141 $itemid = '[0-9]+';
2143 $urlstring .= "\/(?<itemid>{$itemid})";
2145 // Filename matching magic based on file_rewrite_urls_to_pluginfile().
2146 if (is_null($filename)) {
2147 $filename = '[^\'\",&<>|`\s:\\\\]+';
2149 $urlstring .= "\/(?<filename>{$filename})/";
2151 // Regular expression which matches URLs and returns their components.
2152 preg_match_all($urlstring, $text, $urls, PREG_SET_ORDER);
2153 return $urls;
2157 * This function will highlight search words in a given string
2159 * It cares about HTML and will not ruin links. It's best to use
2160 * this function after performing any conversions to HTML.
2162 * @param string $needle The search string. Syntax like "word1 +word2 -word3" is dealt with correctly.
2163 * @param string $haystack The string (HTML) within which to highlight the search terms.
2164 * @param boolean $matchcase whether to do case-sensitive. Default case-insensitive.
2165 * @param string $prefix the string to put before each search term found.
2166 * @param string $suffix the string to put after each search term found.
2167 * @return string The highlighted HTML.
2169 function highlight($needle, $haystack, $matchcase = false,
2170 $prefix = '<span class="highlight">', $suffix = '</span>') {
2172 // Quick bail-out in trivial cases.
2173 if (empty($needle) or empty($haystack)) {
2174 return $haystack;
2177 // Break up the search term into words, discard any -words and build a regexp.
2178 $words = preg_split('/ +/', trim($needle));
2179 foreach ($words as $index => $word) {
2180 if (strpos($word, '-') === 0) {
2181 unset($words[$index]);
2182 } else if (strpos($word, '+') === 0) {
2183 $words[$index] = '\b' . preg_quote(ltrim($word, '+'), '/') . '\b'; // Match only as a complete word.
2184 } else {
2185 $words[$index] = preg_quote($word, '/');
2188 $regexp = '/(' . implode('|', $words) . ')/u'; // Char u is to do UTF-8 matching.
2189 if (!$matchcase) {
2190 $regexp .= 'i';
2193 // Another chance to bail-out if $search was only -words.
2194 if (empty($words)) {
2195 return $haystack;
2198 // Split the string into HTML tags and real content.
2199 $chunks = preg_split('/((?:<[^>]*>)+)/', $haystack, -1, PREG_SPLIT_DELIM_CAPTURE);
2201 // We have an array of alternating blocks of text, then HTML tags, then text, ...
2202 // Loop through replacing search terms in the text, and leaving the HTML unchanged.
2203 $ishtmlchunk = false;
2204 $result = '';
2205 foreach ($chunks as $chunk) {
2206 if ($ishtmlchunk) {
2207 $result .= $chunk;
2208 } else {
2209 $result .= preg_replace($regexp, $prefix . '$1' . $suffix, $chunk);
2211 $ishtmlchunk = !$ishtmlchunk;
2214 return $result;
2218 * This function will highlight instances of $needle in $haystack
2220 * It's faster that the above function {@link highlight()} and doesn't care about
2221 * HTML or anything.
2223 * @param string $needle The string to search for
2224 * @param string $haystack The string to search for $needle in
2225 * @return string The highlighted HTML
2227 function highlightfast($needle, $haystack) {
2229 if (empty($needle) or empty($haystack)) {
2230 return $haystack;
2233 $parts = explode(core_text::strtolower($needle), core_text::strtolower($haystack));
2235 if (count($parts) === 1) {
2236 return $haystack;
2239 $pos = 0;
2241 foreach ($parts as $key => $part) {
2242 $parts[$key] = substr($haystack, $pos, strlen($part));
2243 $pos += strlen($part);
2245 $parts[$key] .= '<span class="highlight">'.substr($haystack, $pos, strlen($needle)).'</span>';
2246 $pos += strlen($needle);
2249 return str_replace('<span class="highlight"></span>', '', join('', $parts));
2253 * Converts a language code to hyphen-separated format in accordance to the
2254 * {@link https://datatracker.ietf.org/doc/html/rfc5646#section-2.1 BCP47 syntax}.
2256 * For additional information, check out
2257 * {@link https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/lang MDN web docs - lang}.
2259 * @param string $langcode The language code to convert.
2260 * @return string
2262 function get_html_lang_attribute_value(string $langcode): string {
2263 $langcode = clean_param($langcode, PARAM_LANG);
2264 if ($langcode === '') {
2265 return 'en';
2268 // Grab language ISO code from lang config. If it differs from English, then it's been specified and we can return it.
2269 $langiso = (string) (new lang_string('iso6391', 'core_langconfig', null, $langcode));
2270 if ($langiso !== 'en') {
2271 return $langiso;
2274 // Where we cannot determine the value from lang config, use the first two characters from the lang code.
2275 return substr($langcode, 0, 2);
2279 * Return a string containing 'lang', xml:lang and optionally 'dir' HTML attributes.
2281 * Internationalisation, for print_header and backup/restorelib.
2283 * @param bool $dir Default false
2284 * @return string Attributes
2286 function get_html_lang($dir = false) {
2287 global $CFG;
2289 $currentlang = current_language();
2290 if (isset($CFG->lang) && $currentlang !== $CFG->lang && !get_string_manager()->translation_exists($currentlang)) {
2291 // Use the default site language when the current language is not available.
2292 $currentlang = $CFG->lang;
2293 // Fix the current language.
2294 fix_current_language($currentlang);
2297 $direction = '';
2298 if ($dir) {
2299 if (right_to_left()) {
2300 $direction = ' dir="rtl"';
2301 } else {
2302 $direction = ' dir="ltr"';
2306 // Accessibility: added the 'lang' attribute to $direction, used in theme <html> tag.
2307 $language = get_html_lang_attribute_value($currentlang);
2308 @header('Content-Language: '.$language);
2309 return ($direction.' lang="'.$language.'" xml:lang="'.$language.'"');
2313 // STANDARD WEB PAGE PARTS.
2316 * Send the HTTP headers that Moodle requires.
2318 * There is a backwards compatibility hack for legacy code
2319 * that needs to add custom IE compatibility directive.
2321 * Example:
2322 * <code>
2323 * if (!isset($CFG->additionalhtmlhead)) {
2324 * $CFG->additionalhtmlhead = '';
2326 * $CFG->additionalhtmlhead .= '<meta http-equiv="X-UA-Compatible" content="IE=8" />';
2327 * header('X-UA-Compatible: IE=8');
2328 * echo $OUTPUT->header();
2329 * </code>
2331 * Please note the $CFG->additionalhtmlhead alone might not work,
2332 * you should send the IE compatibility header() too.
2334 * @param string $contenttype
2335 * @param bool $cacheable Can this page be cached on back?
2336 * @return void, sends HTTP headers
2338 function send_headers($contenttype, $cacheable = true) {
2339 global $CFG;
2341 @header('Content-Type: ' . $contenttype);
2342 @header('Content-Script-Type: text/javascript');
2343 @header('Content-Style-Type: text/css');
2345 if (empty($CFG->additionalhtmlhead) or stripos($CFG->additionalhtmlhead, 'X-UA-Compatible') === false) {
2346 @header('X-UA-Compatible: IE=edge');
2349 if ($cacheable) {
2350 // Allow caching on "back" (but not on normal clicks).
2351 @header('Cache-Control: private, pre-check=0, post-check=0, max-age=0, no-transform');
2352 @header('Pragma: no-cache');
2353 @header('Expires: ');
2354 } else {
2355 // Do everything we can to always prevent clients and proxies caching.
2356 @header('Cache-Control: no-store, no-cache, must-revalidate');
2357 @header('Cache-Control: post-check=0, pre-check=0, no-transform', false);
2358 @header('Pragma: no-cache');
2359 @header('Expires: Mon, 20 Aug 1969 09:23:00 GMT');
2360 @header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
2362 @header('Accept-Ranges: none');
2364 // The Moodle app must be allowed to embed content always.
2365 if (empty($CFG->allowframembedding) && !core_useragent::is_moodle_app()) {
2366 @header('X-Frame-Options: sameorigin');
2369 // If referrer policy is set, add a referrer header.
2370 if (!empty($CFG->referrerpolicy) && ($CFG->referrerpolicy !== 'default')) {
2371 @header('Referrer-Policy: ' . $CFG->referrerpolicy);
2376 * Return the right arrow with text ('next'), and optionally embedded in a link.
2378 * @param string $text HTML/plain text label (set to blank only for breadcrumb separator cases).
2379 * @param string $url An optional link to use in a surrounding HTML anchor.
2380 * @param bool $accesshide True if text should be hidden (for screen readers only).
2381 * @param string $addclass Additional class names for the link, or the arrow character.
2382 * @return string HTML string.
2384 function link_arrow_right($text, $url='', $accesshide=false, $addclass='', $addparams = []) {
2385 global $OUTPUT; // TODO: move to output renderer.
2386 $arrowclass = 'arrow ';
2387 if (!$url) {
2388 $arrowclass .= $addclass;
2390 $arrow = '<span class="'.$arrowclass.'" aria-hidden="true">'.$OUTPUT->rarrow().'</span>';
2391 $htmltext = '';
2392 if ($text) {
2393 $htmltext = '<span class="arrow_text">'.$text.'</span>&nbsp;';
2394 if ($accesshide) {
2395 $htmltext = get_accesshide($htmltext);
2398 if ($url) {
2399 $class = 'arrow_link';
2400 if ($addclass) {
2401 $class .= ' '.$addclass;
2404 $linkparams = [
2405 'class' => $class,
2406 'href' => $url,
2407 'title' => preg_replace('/<.*?>/', '', $text),
2410 $linkparams += $addparams;
2412 return html_writer::link($url, $htmltext . $arrow, $linkparams);
2414 return $htmltext.$arrow;
2418 * Return the left arrow with text ('previous'), and optionally embedded in a link.
2420 * @param string $text HTML/plain text label (set to blank only for breadcrumb separator cases).
2421 * @param string $url An optional link to use in a surrounding HTML anchor.
2422 * @param bool $accesshide True if text should be hidden (for screen readers only).
2423 * @param string $addclass Additional class names for the link, or the arrow character.
2424 * @return string HTML string.
2426 function link_arrow_left($text, $url='', $accesshide=false, $addclass='', $addparams = []) {
2427 global $OUTPUT; // TODO: move to utput renderer.
2428 $arrowclass = 'arrow ';
2429 if (! $url) {
2430 $arrowclass .= $addclass;
2432 $arrow = '<span class="'.$arrowclass.'" aria-hidden="true">'.$OUTPUT->larrow().'</span>';
2433 $htmltext = '';
2434 if ($text) {
2435 $htmltext = '&nbsp;<span class="arrow_text">'.$text.'</span>';
2436 if ($accesshide) {
2437 $htmltext = get_accesshide($htmltext);
2440 if ($url) {
2441 $class = 'arrow_link';
2442 if ($addclass) {
2443 $class .= ' '.$addclass;
2446 $linkparams = [
2447 'class' => $class,
2448 'href' => $url,
2449 'title' => preg_replace('/<.*?>/', '', $text),
2452 $linkparams += $addparams;
2454 return html_writer::link($url, $arrow . $htmltext, $linkparams);
2456 return $arrow.$htmltext;
2460 * Return a HTML element with the class "accesshide", for accessibility.
2462 * Please use cautiously - where possible, text should be visible!
2464 * @param string $text Plain text.
2465 * @param string $elem Lowercase element name, default "span".
2466 * @param string $class Additional classes for the element.
2467 * @param string $attrs Additional attributes string in the form, "name='value' name2='value2'"
2468 * @return string HTML string.
2470 function get_accesshide($text, $elem='span', $class='', $attrs='') {
2471 return "<$elem class=\"accesshide $class\" $attrs>$text</$elem>";
2475 * Return the breadcrumb trail navigation separator.
2477 * @return string HTML string.
2479 function get_separator() {
2480 // Accessibility: the 'hidden' slash is preferred for screen readers.
2481 return ' '.link_arrow_right($text='/', $url='', $accesshide=true, 'sep').' ';
2485 * Print (or return) a collapsible region, that has a caption that can be clicked to expand or collapse the region.
2487 * If JavaScript is off, then the region will always be expanded.
2489 * @param string $contents the contents of the box.
2490 * @param string $classes class names added to the div that is output.
2491 * @param string $id id added to the div that is output. Must not be blank.
2492 * @param string $caption text displayed at the top. Clicking on this will cause the region to expand or contract.
2493 * @param string $userpref the name of the user preference that stores the user's preferred default state.
2494 * (May be blank if you do not wish the state to be persisted.
2495 * @param boolean $default Initial collapsed state to use if the user_preference it not set.
2496 * @param boolean $return if true, return the HTML as a string, rather than printing it.
2497 * @return string|void If $return is false, returns nothing, otherwise returns a string of HTML.
2499 function print_collapsible_region($contents, $classes, $id, $caption, $userpref = '', $default = false, $return = false) {
2500 $output = print_collapsible_region_start($classes, $id, $caption, $userpref, $default, true);
2501 $output .= $contents;
2502 $output .= print_collapsible_region_end(true);
2504 if ($return) {
2505 return $output;
2506 } else {
2507 echo $output;
2512 * Print (or return) the start of a collapsible region
2514 * The collapsibleregion has a caption that can be clicked to expand or collapse the region. If JavaScript is off, then the region
2515 * will always be expanded.
2517 * @param string $classes class names added to the div that is output.
2518 * @param string $id id added to the div that is output. Must not be blank.
2519 * @param string $caption text displayed at the top. Clicking on this will cause the region to expand or contract.
2520 * @param string $userpref the name of the user preference that stores the user's preferred default state.
2521 * (May be blank if you do not wish the state to be persisted.
2522 * @param boolean $default Initial collapsed state to use if the user_preference it not set.
2523 * @param boolean $return if true, return the HTML as a string, rather than printing it.
2524 * @param string $extracontent the extra content will show next to caption, eg.Help icon.
2525 * @return string|void if $return is false, returns nothing, otherwise returns a string of HTML.
2527 function print_collapsible_region_start($classes, $id, $caption, $userpref = '', $default = false, $return = false,
2528 $extracontent = null) {
2529 global $PAGE;
2531 // Work out the initial state.
2532 if (!empty($userpref) and is_string($userpref)) {
2533 $collapsed = get_user_preferences($userpref, $default);
2534 } else {
2535 $collapsed = $default;
2536 $userpref = false;
2539 if ($collapsed) {
2540 $classes .= ' collapsed';
2543 $output = '';
2544 $output .= '<div id="' . $id . '" class="collapsibleregion ' . $classes . '">';
2545 $output .= '<div id="' . $id . '_sizer">';
2546 $output .= '<div id="' . $id . '_caption" class="collapsibleregioncaption">';
2547 $output .= $caption . ' </div>';
2548 if ($extracontent) {
2549 $output .= html_writer::div($extracontent, 'collapsibleregionextracontent');
2551 $output .= '<div id="' . $id . '_inner" class="collapsibleregioninner">';
2552 $PAGE->requires->js_init_call('M.util.init_collapsible_region', array($id, $userpref, get_string('clicktohideshow')));
2554 if ($return) {
2555 return $output;
2556 } else {
2557 echo $output;
2562 * Close a region started with print_collapsible_region_start.
2564 * @param boolean $return if true, return the HTML as a string, rather than printing it.
2565 * @return string|void if $return is false, returns nothing, otherwise returns a string of HTML.
2567 function print_collapsible_region_end($return = false) {
2568 $output = '</div></div></div>';
2570 if ($return) {
2571 return $output;
2572 } else {
2573 echo $output;
2578 * Print a specified group's avatar.
2580 * @param array|stdClass $group A single {@link group} object OR array of groups.
2581 * @param int $courseid The course ID.
2582 * @param boolean $large Default small picture, or large.
2583 * @param boolean $return If false print picture, otherwise return the output as string
2584 * @param boolean $link Enclose image in a link to view specified course?
2585 * @param boolean $includetoken Whether to use a user token when displaying this group image.
2586 * True indicates to generate a token for current user, and integer value indicates to generate a token for the
2587 * user whose id is the value indicated.
2588 * If the group picture is included in an e-mail or some other location where the audience is a specific
2589 * user who will not be logged in when viewing, then we use a token to authenticate the user.
2590 * @return string|void Depending on the setting of $return
2592 function print_group_picture($group, $courseid, $large = false, $return = false, $link = true, $includetoken = false) {
2593 global $CFG;
2595 if (is_array($group)) {
2596 $output = '';
2597 foreach ($group as $g) {
2598 $output .= print_group_picture($g, $courseid, $large, true, $link, $includetoken);
2600 if ($return) {
2601 return $output;
2602 } else {
2603 echo $output;
2604 return;
2608 $pictureurl = get_group_picture_url($group, $courseid, $large, $includetoken);
2610 // If there is no picture, do nothing.
2611 if (!isset($pictureurl)) {
2612 return;
2615 $context = context_course::instance($courseid);
2617 $groupname = s($group->name);
2618 $pictureimage = html_writer::img($pictureurl, $groupname, ['title' => $groupname]);
2620 $output = '';
2621 if ($link or has_capability('moodle/site:accessallgroups', $context)) {
2622 $linkurl = new moodle_url('/user/index.php', ['id' => $courseid, 'group' => $group->id]);
2623 $output .= html_writer::link($linkurl, $pictureimage);
2624 } else {
2625 $output .= $pictureimage;
2628 if ($return) {
2629 return $output;
2630 } else {
2631 echo $output;
2636 * Return the url to the group picture.
2638 * @param stdClass $group A group object.
2639 * @param int $courseid The course ID for the group.
2640 * @param bool $large A large or small group picture? Default is small.
2641 * @param boolean $includetoken Whether to use a user token when displaying this group image.
2642 * True indicates to generate a token for current user, and integer value indicates to generate a token for the
2643 * user whose id is the value indicated.
2644 * If the group picture is included in an e-mail or some other location where the audience is a specific
2645 * user who will not be logged in when viewing, then we use a token to authenticate the user.
2646 * @return moodle_url Returns the url for the group picture.
2648 function get_group_picture_url($group, $courseid, $large = false, $includetoken = false) {
2649 global $CFG;
2651 $context = context_course::instance($courseid);
2653 // If there is no picture, do nothing.
2654 if (!$group->picture) {
2655 return;
2658 if ($large) {
2659 $file = 'f1';
2660 } else {
2661 $file = 'f2';
2664 $grouppictureurl = moodle_url::make_pluginfile_url(
2665 $context->id, 'group', 'icon', $group->id, '/', $file, false, $includetoken);
2666 $grouppictureurl->param('rev', $group->picture);
2667 return $grouppictureurl;
2672 * Display a recent activity note
2674 * @staticvar string $strftimerecent
2675 * @param int $time A timestamp int.
2676 * @param stdClass $user A user object from the database.
2677 * @param string $text Text for display for the note
2678 * @param string $link The link to wrap around the text
2679 * @param bool $return If set to true the HTML is returned rather than echo'd
2680 * @param string $viewfullnames
2681 * @return string If $retrun was true returns HTML for a recent activity notice.
2683 function print_recent_activity_note($time, $user, $text, $link, $return=false, $viewfullnames=null) {
2684 static $strftimerecent = null;
2685 $output = '';
2687 if (is_null($viewfullnames)) {
2688 $context = context_system::instance();
2689 $viewfullnames = has_capability('moodle/site:viewfullnames', $context);
2692 if (is_null($strftimerecent)) {
2693 $strftimerecent = get_string('strftimerecent');
2696 $output .= '<div class="head">';
2697 $output .= '<div class="date">'.userdate($time, $strftimerecent).'</div>';
2698 $output .= '<div class="name">'.fullname($user, $viewfullnames).'</div>';
2699 $output .= '</div>';
2700 $output .= '<div class="info"><a href="'.$link.'">'.format_string($text, true).'</a></div>';
2702 if ($return) {
2703 return $output;
2704 } else {
2705 echo $output;
2710 * Returns a popup menu with course activity modules
2712 * Given a course this function returns a small popup menu with all the course activity modules in it, as a navigation menu
2713 * outputs a simple list structure in XHTML.
2714 * The data is taken from the serialised array stored in the course record.
2716 * @param stdClass $course A course object.
2717 * @param array $sections
2718 * @param course_modinfo $modinfo
2719 * @param string $strsection
2720 * @param string $strjumpto
2721 * @param int $width
2722 * @param string $cmid
2723 * @return string The HTML block
2725 function navmenulist($course, $sections, $modinfo, $strsection, $strjumpto, $width=50, $cmid=0) {
2727 global $CFG, $OUTPUT;
2729 $section = -1;
2730 $menu = array();
2731 $doneheading = false;
2733 $courseformatoptions = course_get_format($course)->get_format_options();
2734 $coursecontext = context_course::instance($course->id);
2736 $menu[] = '<ul class="navmenulist"><li class="jumpto section"><span>'.$strjumpto.'</span><ul>';
2737 foreach ($modinfo->cms as $mod) {
2738 if (!$mod->has_view()) {
2739 // Don't show modules which you can't link to!
2740 continue;
2743 // For course formats using 'numsections' do not show extra sections.
2744 if (isset($courseformatoptions['numsections']) && $mod->sectionnum > $courseformatoptions['numsections']) {
2745 break;
2748 if (!$mod->uservisible) { // Do not icnlude empty sections at all.
2749 continue;
2752 if ($mod->sectionnum >= 0 and $section != $mod->sectionnum) {
2753 $thissection = $sections[$mod->sectionnum];
2755 if ($thissection->visible or
2756 (isset($courseformatoptions['hiddensections']) and !$courseformatoptions['hiddensections']) or
2757 has_capability('moodle/course:viewhiddensections', $coursecontext)) {
2758 $thissection->summary = strip_tags(format_string($thissection->summary, true));
2759 if (!$doneheading) {
2760 $menu[] = '</ul></li>';
2762 if ($course->format == 'weeks' or empty($thissection->summary)) {
2763 $item = $strsection ." ". $mod->sectionnum;
2764 } else {
2765 if (core_text::strlen($thissection->summary) < ($width-3)) {
2766 $item = $thissection->summary;
2767 } else {
2768 $item = core_text::substr($thissection->summary, 0, $width).'...';
2771 $menu[] = '<li class="section"><span>'.$item.'</span>';
2772 $menu[] = '<ul>';
2773 $doneheading = true;
2775 $section = $mod->sectionnum;
2776 } else {
2777 // No activities from this hidden section shown.
2778 continue;
2782 $url = $mod->modname .'/view.php?id='. $mod->id;
2783 $mod->name = strip_tags(format_string($mod->name ,true));
2784 if (core_text::strlen($mod->name) > ($width+5)) {
2785 $mod->name = core_text::substr($mod->name, 0, $width).'...';
2787 if (!$mod->visible) {
2788 $mod->name = '('.$mod->name.')';
2790 $class = 'activity '.$mod->modname;
2791 $class .= ($cmid == $mod->id) ? ' selected' : '';
2792 $menu[] = '<li class="'.$class.'">'.
2793 $OUTPUT->image_icon('monologo', '', $mod->modname).
2794 '<a href="'.$CFG->wwwroot.'/mod/'.$url.'">'.$mod->name.'</a></li>';
2797 if ($doneheading) {
2798 $menu[] = '</ul></li>';
2800 $menu[] = '</ul></li></ul>';
2802 return implode("\n", $menu);
2806 * Prints a grade menu (as part of an existing form) with help showing all possible numerical grades and scales.
2808 * @todo Finish documenting this function
2809 * @todo Deprecate: this is only used in a few contrib modules
2811 * @param int $courseid The course ID
2812 * @param string $name
2813 * @param string $current
2814 * @param boolean $includenograde Include those with no grades
2815 * @param boolean $return If set to true returns rather than echo's
2816 * @return string|bool Depending on value of $return
2818 function print_grade_menu($courseid, $name, $current, $includenograde=true, $return=false) {
2819 global $OUTPUT;
2821 $output = '';
2822 $strscale = get_string('scale');
2823 $strscales = get_string('scales');
2825 $scales = get_scales_menu($courseid);
2826 foreach ($scales as $i => $scalename) {
2827 $grades[-$i] = $strscale .': '. $scalename;
2829 if ($includenograde) {
2830 $grades[0] = get_string('nograde');
2832 for ($i=100; $i>=1; $i--) {
2833 $grades[$i] = $i;
2835 $output .= html_writer::select($grades, $name, $current, false);
2837 $linkobject = '<span class="helplink">' . $OUTPUT->pix_icon('help', $strscales) . '</span>';
2838 $link = new moodle_url('/course/scales.php', array('id' => $courseid, 'list' => 1));
2839 $action = new popup_action('click', $link, 'ratingscales', array('height' => 400, 'width' => 500));
2840 $output .= $OUTPUT->action_link($link, $linkobject, $action, array('title' => $strscales));
2842 if ($return) {
2843 return $output;
2844 } else {
2845 echo $output;
2850 * Print an error to STDOUT and exit with a non-zero code. For commandline scripts.
2852 * Default errorcode is 1.
2854 * Very useful for perl-like error-handling:
2855 * do_somethting() or mdie("Something went wrong");
2857 * @param string $msg Error message
2858 * @param integer $errorcode Error code to emit
2860 function mdie($msg='', $errorcode=1) {
2861 trigger_error($msg);
2862 exit($errorcode);
2866 * Print a message and exit.
2868 * @param string $message The message to print in the notice
2869 * @param moodle_url|string $link The link to use for the continue button
2870 * @param object $course A course object. Unused.
2871 * @return void This function simply exits
2873 function notice ($message, $link='', $course=null) {
2874 global $PAGE, $OUTPUT;
2876 $message = clean_text($message); // In case nasties are in here.
2878 if (CLI_SCRIPT) {
2879 echo("!!$message!!\n");
2880 exit(1); // No success.
2883 if (!$PAGE->headerprinted) {
2884 // Header not yet printed.
2885 $PAGE->set_title(get_string('notice'));
2886 echo $OUTPUT->header();
2887 } else {
2888 echo $OUTPUT->container_end_all(false);
2891 echo $OUTPUT->box($message, 'generalbox', 'notice');
2892 echo $OUTPUT->continue_button($link);
2894 echo $OUTPUT->footer();
2895 exit(1); // General error code.
2899 * Redirects the user to another page, after printing a notice.
2901 * This function calls the OUTPUT redirect method, echo's the output and then dies to ensure nothing else happens.
2903 * <strong>Good practice:</strong> You should call this method before starting page
2904 * output by using any of the OUTPUT methods.
2906 * @param moodle_url|string $url A moodle_url to redirect to. Strings are not to be trusted!
2907 * @param string $message The message to display to the user
2908 * @param int $delay The delay before redirecting
2909 * @param string $messagetype The type of notification to show the message in. See constants on \core\output\notification.
2910 * @throws moodle_exception
2912 function redirect($url, $message='', $delay=null, $messagetype = \core\output\notification::NOTIFY_INFO) {
2913 global $OUTPUT, $PAGE, $CFG;
2915 if (CLI_SCRIPT or AJAX_SCRIPT) {
2916 // This is wrong - developers should not use redirect in these scripts but it should not be very likely.
2917 throw new moodle_exception('redirecterrordetected', 'error');
2920 if ($delay === null) {
2921 $delay = -1;
2924 // Prevent debug errors - make sure context is properly initialised.
2925 if ($PAGE) {
2926 $PAGE->set_context(null);
2927 $PAGE->set_pagelayout('redirect'); // No header and footer needed.
2928 $PAGE->set_title(get_string('pageshouldredirect', 'moodle'));
2931 if ($url instanceof moodle_url) {
2932 $url = $url->out(false);
2935 $debugdisableredirect = false;
2936 do {
2937 if (defined('DEBUGGING_PRINTED')) {
2938 // Some debugging already printed, no need to look more.
2939 $debugdisableredirect = true;
2940 break;
2943 if (core_useragent::is_msword()) {
2944 // Clicking a URL from MS Word sends a request to the server without cookies. If that
2945 // causes a redirect Word will open a browser pointing the new URL. If not, the URL that
2946 // was clicked is opened. Because the request from Word is without cookies, it almost
2947 // always results in a redirect to the login page, even if the user is logged in in their
2948 // browser. This is not what we want, so prevent the redirect for requests from Word.
2949 $debugdisableredirect = true;
2950 break;
2953 if (empty($CFG->debugdisplay) or empty($CFG->debug)) {
2954 // No errors should be displayed.
2955 break;
2958 if (!function_exists('error_get_last') or !$lasterror = error_get_last()) {
2959 break;
2962 if (!($lasterror['type'] & $CFG->debug)) {
2963 // Last error not interesting.
2964 break;
2967 // Watch out here, @hidden() errors are returned from error_get_last() too.
2968 if (headers_sent()) {
2969 // We already started printing something - that means errors likely printed.
2970 $debugdisableredirect = true;
2971 break;
2974 if (ob_get_level() and ob_get_contents()) {
2975 // There is something waiting to be printed, hopefully it is the errors,
2976 // but it might be some error hidden by @ too - such as the timezone mess from setup.php.
2977 $debugdisableredirect = true;
2978 break;
2980 } while (false);
2982 // Technically, HTTP/1.1 requires Location: header to contain the absolute path.
2983 // (In practice browsers accept relative paths - but still, might as well do it properly.)
2984 // This code turns relative into absolute.
2985 if (!preg_match('|^[a-z]+:|i', $url)) {
2986 // Get host name http://www.wherever.com.
2987 $hostpart = preg_replace('|^(.*?[^:/])/.*$|', '$1', $CFG->wwwroot);
2988 if (preg_match('|^/|', $url)) {
2989 // URLs beginning with / are relative to web server root so we just add them in.
2990 $url = $hostpart.$url;
2991 } else {
2992 // URLs not beginning with / are relative to path of current script, so add that on.
2993 $url = $hostpart.preg_replace('|\?.*$|', '', me()).'/../'.$url;
2995 // Replace all ..s.
2996 while (true) {
2997 $newurl = preg_replace('|/(?!\.\.)[^/]*/\.\./|', '/', $url);
2998 if ($newurl == $url) {
2999 break;
3001 $url = $newurl;
3005 // Sanitise url - we can not rely on moodle_url or our URL cleaning
3006 // because they do not support all valid external URLs.
3007 $url = preg_replace('/[\x00-\x1F\x7F]/', '', $url);
3008 $url = str_replace('"', '%22', $url);
3009 $encodedurl = preg_replace("/\&(?![a-zA-Z0-9#]{1,8};)/", "&amp;", $url);
3010 $encodedurl = preg_replace('/^.*href="([^"]*)".*$/', "\\1", clean_text('<a href="'.$encodedurl.'" />', FORMAT_HTML));
3011 $url = str_replace('&amp;', '&', $encodedurl);
3013 if (!empty($message)) {
3014 if (!$debugdisableredirect && !headers_sent()) {
3015 // A message has been provided, and the headers have not yet been sent.
3016 // Display the message as a notification on the subsequent page.
3017 \core\notification::add($message, $messagetype);
3018 $message = null;
3019 $delay = 0;
3020 } else {
3021 if ($delay === -1 || !is_numeric($delay)) {
3022 $delay = 3;
3024 $message = clean_text($message);
3026 } else {
3027 $message = get_string('pageshouldredirect');
3028 $delay = 0;
3031 // Make sure the session is closed properly, this prevents problems in IIS
3032 // and also some potential PHP shutdown issues.
3033 \core\session\manager::write_close();
3035 if ($delay == 0 && !$debugdisableredirect && !headers_sent()) {
3037 // This helps when debugging redirect issues like loops and it is not clear
3038 // which layer in the stack sent the redirect header. If debugging is on
3039 // then the file and line is also shown.
3040 $redirectby = 'Moodle';
3041 if (debugging('', DEBUG_DEVELOPER)) {
3042 $origin = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 1)[0];
3043 $redirectby .= ' /' . str_replace($CFG->dirroot . '/', '', $origin['file']) . ':' . $origin['line'];
3045 @header("X-Redirect-By: $redirectby");
3047 // 302 might not work for POST requests, 303 is ignored by obsolete clients.
3048 @header($_SERVER['SERVER_PROTOCOL'] . ' 303 See Other');
3049 @header('Location: '.$url);
3050 echo bootstrap_renderer::plain_redirect_message($encodedurl);
3051 exit;
3054 // Include a redirect message, even with a HTTP redirect, because that is recommended practice.
3055 if ($PAGE) {
3056 $CFG->docroot = false; // To prevent the link to moodle docs from being displayed on redirect page.
3057 echo $OUTPUT->redirect_message($encodedurl, $message, $delay, $debugdisableredirect, $messagetype);
3058 exit;
3059 } else {
3060 echo bootstrap_renderer::early_redirect_message($encodedurl, $message, $delay);
3061 exit;
3066 * Given an email address, this function will return an obfuscated version of it.
3068 * @param string $email The email address to obfuscate
3069 * @return string The obfuscated email address
3071 function obfuscate_email($email) {
3072 $i = 0;
3073 $length = strlen($email);
3074 $obfuscated = '';
3075 while ($i < $length) {
3076 if (rand(0, 2) && $email[$i]!='@') { // MDL-20619 some browsers have problems unobfuscating @.
3077 $obfuscated.='%'.dechex(ord($email[$i]));
3078 } else {
3079 $obfuscated.=$email[$i];
3081 $i++;
3083 return $obfuscated;
3087 * This function takes some text and replaces about half of the characters
3088 * with HTML entity equivalents. Return string is obviously longer.
3090 * @param string $plaintext The text to be obfuscated
3091 * @return string The obfuscated text
3093 function obfuscate_text($plaintext) {
3094 $i=0;
3095 $length = core_text::strlen($plaintext);
3096 $obfuscated='';
3097 $prevobfuscated = false;
3098 while ($i < $length) {
3099 $char = core_text::substr($plaintext, $i, 1);
3100 $ord = core_text::utf8ord($char);
3101 $numerical = ($ord >= ord('0')) && ($ord <= ord('9'));
3102 if ($prevobfuscated and $numerical ) {
3103 $obfuscated.='&#'.$ord.';';
3104 } else if (rand(0, 2)) {
3105 $obfuscated.='&#'.$ord.';';
3106 $prevobfuscated = true;
3107 } else {
3108 $obfuscated.=$char;
3109 $prevobfuscated = false;
3111 $i++;
3113 return $obfuscated;
3117 * This function uses the {@link obfuscate_email()} and {@link obfuscate_text()}
3118 * to generate a fully obfuscated email link, ready to use.
3120 * @param string $email The email address to display
3121 * @param string $label The text to displayed as hyperlink to $email
3122 * @param boolean $dimmed If true then use css class 'dimmed' for hyperlink
3123 * @param string $subject The subject of the email in the mailto link
3124 * @param string $body The content of the email in the mailto link
3125 * @return string The obfuscated mailto link
3127 function obfuscate_mailto($email, $label='', $dimmed=false, $subject = '', $body = '') {
3129 if (empty($label)) {
3130 $label = $email;
3133 $label = obfuscate_text($label);
3134 $email = obfuscate_email($email);
3135 $mailto = obfuscate_text('mailto');
3136 $url = new moodle_url("mailto:$email");
3137 $attrs = array();
3139 if (!empty($subject)) {
3140 $url->param('subject', format_string($subject));
3142 if (!empty($body)) {
3143 $url->param('body', format_string($body));
3146 // Use the obfuscated mailto.
3147 $url = preg_replace('/^mailto/', $mailto, $url->out());
3149 if ($dimmed) {
3150 $attrs['title'] = get_string('emaildisable');
3151 $attrs['class'] = 'dimmed';
3154 return html_writer::link($url, $label, $attrs);
3158 * This function is used to rebuild the <nolink> tag because some formats (PLAIN and WIKI)
3159 * will transform it to html entities
3161 * @param string $text Text to search for nolink tag in
3162 * @return string
3164 function rebuildnolinktag($text) {
3166 $text = preg_replace('/&lt;(\/*nolink)&gt;/i', '<$1>', $text);
3168 return $text;
3172 * Prints a maintenance message from $CFG->maintenance_message or default if empty.
3174 function print_maintenance_message() {
3175 global $CFG, $SITE, $PAGE, $OUTPUT;
3177 header($_SERVER['SERVER_PROTOCOL'] . ' 503 Moodle under maintenance');
3178 header('Status: 503 Moodle under maintenance');
3179 header('Retry-After: 300');
3181 $PAGE->set_pagetype('maintenance-message');
3182 $PAGE->set_pagelayout('maintenance');
3183 $PAGE->set_heading($SITE->fullname);
3184 echo $OUTPUT->header();
3185 echo $OUTPUT->heading(get_string('sitemaintenance', 'admin'));
3186 if (isset($CFG->maintenance_message) and !html_is_blank($CFG->maintenance_message)) {
3187 echo $OUTPUT->box_start('maintenance_message generalbox boxwidthwide boxaligncenter');
3188 echo $CFG->maintenance_message;
3189 echo $OUTPUT->box_end();
3191 echo $OUTPUT->footer();
3192 die;
3196 * Returns a string containing a nested list, suitable for formatting into tabs with CSS.
3198 * It is not recommended to use this function in Moodle 2.5 but it is left for backward
3199 * compartibility.
3201 * Example how to print a single line tabs:
3202 * $rows = array(
3203 * new tabobject(...),
3204 * new tabobject(...)
3205 * );
3206 * echo $OUTPUT->tabtree($rows, $selectedid);
3208 * Multiple row tabs may not look good on some devices but if you want to use them
3209 * you can specify ->subtree for the active tabobject.
3211 * @param array $tabrows An array of rows where each row is an array of tab objects
3212 * @param string $selected The id of the selected tab (whatever row it's on)
3213 * @param array $inactive An array of ids of inactive tabs that are not selectable.
3214 * @param array $activated An array of ids of other tabs that are currently activated
3215 * @param bool $return If true output is returned rather then echo'd
3216 * @return string HTML output if $return was set to true.
3218 function print_tabs($tabrows, $selected = null, $inactive = null, $activated = null, $return = false) {
3219 global $OUTPUT;
3221 $tabrows = array_reverse($tabrows);
3222 $subtree = array();
3223 foreach ($tabrows as $row) {
3224 $tree = array();
3226 foreach ($row as $tab) {
3227 $tab->inactive = is_array($inactive) && in_array((string)$tab->id, $inactive);
3228 $tab->activated = is_array($activated) && in_array((string)$tab->id, $activated);
3229 $tab->selected = (string)$tab->id == $selected;
3231 if ($tab->activated || $tab->selected) {
3232 $tab->subtree = $subtree;
3234 $tree[] = $tab;
3236 $subtree = $tree;
3238 $output = $OUTPUT->tabtree($subtree);
3239 if ($return) {
3240 return $output;
3241 } else {
3242 print $output;
3243 return !empty($output);
3248 * Alter debugging level for the current request,
3249 * the change is not saved in database.
3251 * @param int $level one of the DEBUG_* constants
3252 * @param bool $debugdisplay
3254 function set_debugging($level, $debugdisplay = null) {
3255 global $CFG;
3257 $CFG->debug = (int)$level;
3258 $CFG->debugdeveloper = (($CFG->debug & DEBUG_DEVELOPER) === DEBUG_DEVELOPER);
3260 if ($debugdisplay !== null) {
3261 $CFG->debugdisplay = (bool)$debugdisplay;
3266 * Standard Debugging Function
3268 * Returns true if the current site debugging settings are equal or above specified level.
3269 * If passed a parameter it will emit a debugging notice similar to trigger_error(). The
3270 * routing of notices is controlled by $CFG->debugdisplay
3271 * eg use like this:
3273 * 1) debugging('a normal debug notice');
3274 * 2) debugging('something really picky', DEBUG_ALL);
3275 * 3) debugging('annoying debug message only for developers', DEBUG_DEVELOPER);
3276 * 4) if (debugging()) { perform extra debugging operations (do not use print or echo) }
3278 * In code blocks controlled by debugging() (such as example 4)
3279 * any output should be routed via debugging() itself, or the lower-level
3280 * trigger_error() or error_log(). Using echo or print will break XHTML
3281 * JS and HTTP headers.
3283 * It is also possible to define NO_DEBUG_DISPLAY which redirects the message to error_log.
3285 * @param string $message a message to print
3286 * @param int $level the level at which this debugging statement should show
3287 * @param array $backtrace use different backtrace
3288 * @return bool
3290 function debugging($message = '', $level = DEBUG_NORMAL, $backtrace = null) {
3291 global $CFG, $USER;
3293 $forcedebug = false;
3294 if (!empty($CFG->debugusers) && $USER) {
3295 $debugusers = explode(',', $CFG->debugusers);
3296 $forcedebug = in_array($USER->id, $debugusers);
3299 if (!$forcedebug and (empty($CFG->debug) || ($CFG->debug != -1 and $CFG->debug < $level))) {
3300 return false;
3303 if (!isset($CFG->debugdisplay)) {
3304 $CFG->debugdisplay = ini_get_bool('display_errors');
3307 if ($message) {
3308 if (!$backtrace) {
3309 $backtrace = debug_backtrace();
3311 $from = format_backtrace($backtrace, CLI_SCRIPT || NO_DEBUG_DISPLAY);
3312 if (PHPUNIT_TEST) {
3313 if (phpunit_util::debugging_triggered($message, $level, $from)) {
3314 // We are inside test, the debug message was logged.
3315 return true;
3319 if (NO_DEBUG_DISPLAY) {
3320 // Script does not want any errors or debugging in output,
3321 // we send the info to error log instead.
3322 error_log('Debugging: ' . $message . ' in '. PHP_EOL . $from);
3323 } else if ($forcedebug or $CFG->debugdisplay) {
3324 if (!defined('DEBUGGING_PRINTED')) {
3325 define('DEBUGGING_PRINTED', 1); // Indicates we have printed something.
3328 if (CLI_SCRIPT) {
3329 echo "++ $message ++\n$from";
3330 } else {
3331 if (property_exists($CFG, 'debug_developer_debugging_as_error')) {
3332 $showaserror = $CFG->debug_developer_debugging_as_error;
3333 } else {
3334 $showaserror = (bool) get_whoops();
3337 if ($showaserror) {
3338 trigger_error($message, E_USER_NOTICE);
3339 } else {
3340 echo '<div class="notifytiny debuggingmessage" data-rel="debugging">', $message, $from, '</div>';
3343 } else {
3344 trigger_error($message . $from, E_USER_NOTICE);
3347 return true;
3351 * Outputs a HTML comment to the browser.
3353 * This is used for those hard-to-debug pages that use bits from many different files in very confusing ways (e.g. blocks).
3355 * <code>print_location_comment(__FILE__, __LINE__);</code>
3357 * @param string $file
3358 * @param integer $line
3359 * @param boolean $return Whether to return or print the comment
3360 * @return string|void Void unless true given as third parameter
3362 function print_location_comment($file, $line, $return = false) {
3363 if ($return) {
3364 return "<!-- $file at line $line -->\n";
3365 } else {
3366 echo "<!-- $file at line $line -->\n";
3372 * Returns true if the user is using a right-to-left language.
3374 * @return boolean true if the current language is right-to-left (Hebrew, Arabic etc)
3376 function right_to_left() {
3377 return (get_string('thisdirection', 'langconfig') === 'rtl');
3382 * Returns swapped left<=> right if in RTL environment.
3384 * Part of RTL Moodles support.
3386 * @param string $align align to check
3387 * @return string
3389 function fix_align_rtl($align) {
3390 if (!right_to_left()) {
3391 return $align;
3393 if ($align == 'left') {
3394 return 'right';
3396 if ($align == 'right') {
3397 return 'left';
3399 return $align;
3404 * Returns true if the page is displayed in a popup window.
3406 * Gets the information from the URL parameter inpopup.
3408 * @todo Use a central function to create the popup calls all over Moodle and
3409 * In the moment only works with resources and probably questions.
3411 * @return boolean
3413 function is_in_popup() {
3414 $inpopup = optional_param('inpopup', '', PARAM_BOOL);
3416 return ($inpopup);
3420 * Progress trace class.
3422 * Use this class from long operations where you want to output occasional information about
3423 * what is going on, but don't know if, or in what format, the output should be.
3425 * @copyright 2009 Tim Hunt
3426 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3427 * @package core
3429 abstract class progress_trace {
3431 * Output an progress message in whatever format.
3433 * @param string $message the message to output.
3434 * @param integer $depth indent depth for this message.
3436 abstract public function output($message, $depth = 0);
3439 * Called when the processing is finished.
3441 public function finished() {
3446 * This subclass of progress_trace does not ouput anything.
3448 * @copyright 2009 Tim Hunt
3449 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3450 * @package core
3452 class null_progress_trace extends progress_trace {
3454 * Does Nothing
3456 * @param string $message
3457 * @param int $depth
3458 * @return void Does Nothing
3460 public function output($message, $depth = 0) {
3465 * This subclass of progress_trace outputs to plain text.
3467 * @copyright 2009 Tim Hunt
3468 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3469 * @package core
3471 class text_progress_trace extends progress_trace {
3473 * Output the trace message.
3475 * @param string $message
3476 * @param int $depth
3477 * @return void Output is echo'd
3479 public function output($message, $depth = 0) {
3480 mtrace(str_repeat(' ', $depth) . $message);
3485 * This subclass of progress_trace outputs as HTML.
3487 * @copyright 2009 Tim Hunt
3488 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3489 * @package core
3491 class html_progress_trace extends progress_trace {
3493 * Output the trace message.
3495 * @param string $message
3496 * @param int $depth
3497 * @return void Output is echo'd
3499 public function output($message, $depth = 0) {
3500 echo '<p>', str_repeat('&#160;&#160;', $depth), htmlspecialchars($message, ENT_COMPAT), "</p>\n";
3501 flush();
3506 * HTML List Progress Tree
3508 * @copyright 2009 Tim Hunt
3509 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3510 * @package core
3512 class html_list_progress_trace extends progress_trace {
3513 /** @var int */
3514 protected $currentdepth = -1;
3517 * Echo out the list
3519 * @param string $message The message to display
3520 * @param int $depth
3521 * @return void Output is echoed
3523 public function output($message, $depth = 0) {
3524 $samedepth = true;
3525 while ($this->currentdepth > $depth) {
3526 echo "</li>\n</ul>\n";
3527 $this->currentdepth -= 1;
3528 if ($this->currentdepth == $depth) {
3529 echo '<li>';
3531 $samedepth = false;
3533 while ($this->currentdepth < $depth) {
3534 echo "<ul>\n<li>";
3535 $this->currentdepth += 1;
3536 $samedepth = false;
3538 if ($samedepth) {
3539 echo "</li>\n<li>";
3541 echo htmlspecialchars($message, ENT_COMPAT);
3542 flush();
3546 * Called when the processing is finished.
3548 public function finished() {
3549 while ($this->currentdepth >= 0) {
3550 echo "</li>\n</ul>\n";
3551 $this->currentdepth -= 1;
3557 * This subclass of progress_trace outputs to error log.
3559 * @copyright Petr Skoda {@link http://skodak.org}
3560 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3561 * @package core
3563 class error_log_progress_trace extends progress_trace {
3564 /** @var string log prefix */
3565 protected $prefix;
3568 * Constructor.
3569 * @param string $prefix optional log prefix
3571 public function __construct($prefix = '') {
3572 $this->prefix = $prefix;
3576 * Output the trace message.
3578 * @param string $message
3579 * @param int $depth
3580 * @return void Output is sent to error log.
3582 public function output($message, $depth = 0) {
3583 error_log($this->prefix . str_repeat(' ', $depth) . $message);
3588 * Special type of trace that can be used for catching of output of other traces.
3590 * @copyright Petr Skoda {@link http://skodak.org}
3591 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3592 * @package core
3594 class progress_trace_buffer extends progress_trace {
3595 /** @var progress_trace */
3596 protected $trace;
3597 /** @var bool do we pass output out */
3598 protected $passthrough;
3599 /** @var string output buffer */
3600 protected $buffer;
3603 * Constructor.
3605 * @param progress_trace $trace
3606 * @param bool $passthrough true means output and buffer, false means just buffer and no output
3608 public function __construct(progress_trace $trace, $passthrough = true) {
3609 $this->trace = $trace;
3610 $this->passthrough = $passthrough;
3611 $this->buffer = '';
3615 * Output the trace message.
3617 * @param string $message the message to output.
3618 * @param int $depth indent depth for this message.
3619 * @return void output stored in buffer
3621 public function output($message, $depth = 0) {
3622 ob_start();
3623 $this->trace->output($message, $depth);
3624 $this->buffer .= ob_get_contents();
3625 if ($this->passthrough) {
3626 ob_end_flush();
3627 } else {
3628 ob_end_clean();
3633 * Called when the processing is finished.
3635 public function finished() {
3636 ob_start();
3637 $this->trace->finished();
3638 $this->buffer .= ob_get_contents();
3639 if ($this->passthrough) {
3640 ob_end_flush();
3641 } else {
3642 ob_end_clean();
3647 * Reset internal text buffer.
3649 public function reset_buffer() {
3650 $this->buffer = '';
3654 * Return internal text buffer.
3655 * @return string buffered plain text
3657 public function get_buffer() {
3658 return $this->buffer;
3663 * Special type of trace that can be used for redirecting to multiple other traces.
3665 * @copyright Petr Skoda {@link http://skodak.org}
3666 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3667 * @package core
3669 class combined_progress_trace extends progress_trace {
3672 * An array of traces.
3673 * @var array
3675 protected $traces;
3678 * Constructs a new instance.
3680 * @param array $traces multiple traces
3682 public function __construct(array $traces) {
3683 $this->traces = $traces;
3687 * Output an progress message in whatever format.
3689 * @param string $message the message to output.
3690 * @param integer $depth indent depth for this message.
3692 public function output($message, $depth = 0) {
3693 foreach ($this->traces as $trace) {
3694 $trace->output($message, $depth);
3699 * Called when the processing is finished.
3701 public function finished() {
3702 foreach ($this->traces as $trace) {
3703 $trace->finished();
3709 * Returns a localized sentence in the current language summarizing the current password policy
3711 * @todo this should be handled by a function/method in the language pack library once we have a support for it
3712 * @uses $CFG
3713 * @return string
3715 function print_password_policy() {
3716 global $CFG;
3718 $message = '';
3719 if (!empty($CFG->passwordpolicy)) {
3720 $messages = array();
3721 if (!empty($CFG->minpasswordlength)) {
3722 $messages[] = get_string('informminpasswordlength', 'auth', $CFG->minpasswordlength);
3724 if (!empty($CFG->minpassworddigits)) {
3725 $messages[] = get_string('informminpassworddigits', 'auth', $CFG->minpassworddigits);
3727 if (!empty($CFG->minpasswordlower)) {
3728 $messages[] = get_string('informminpasswordlower', 'auth', $CFG->minpasswordlower);
3730 if (!empty($CFG->minpasswordupper)) {
3731 $messages[] = get_string('informminpasswordupper', 'auth', $CFG->minpasswordupper);
3733 if (!empty($CFG->minpasswordnonalphanum)) {
3734 $messages[] = get_string('informminpasswordnonalphanum', 'auth', $CFG->minpasswordnonalphanum);
3737 // Fire any additional password policy functions from plugins.
3738 // Callbacks must return an array of message strings.
3739 $pluginsfunction = get_plugins_with_function('print_password_policy');
3740 foreach ($pluginsfunction as $plugintype => $plugins) {
3741 foreach ($plugins as $pluginfunction) {
3742 $messages = array_merge($messages, $pluginfunction());
3746 $messages = join(', ', $messages); // This is ugly but we do not have anything better yet...
3747 // Check if messages is empty before outputting any text.
3748 if ($messages != '') {
3749 $message = get_string('informpasswordpolicy', 'auth', $messages);
3752 return $message;
3756 * Get the value of a help string fully prepared for display in the current language.
3758 * @param string $identifier The identifier of the string to search for.
3759 * @param string $component The module the string is associated with.
3760 * @param boolean $ajax Whether this help is called from an AJAX script.
3761 * This is used to influence text formatting and determines
3762 * which format to output the doclink in.
3763 * @param string|object|array $a An object, string or number that can be used
3764 * within translation strings
3765 * @return stdClass An object containing:
3766 * - heading: Any heading that there may be for this help string.
3767 * - text: The wiki-formatted help string.
3768 * - doclink: An object containing a link, the linktext, and any additional
3769 * CSS classes to apply to that link. Only present if $ajax = false.
3770 * - completedoclink: A text representation of the doclink. Only present if $ajax = true.
3772 function get_formatted_help_string($identifier, $component, $ajax = false, $a = null) {
3773 global $CFG, $OUTPUT;
3774 $sm = get_string_manager();
3776 // Do not rebuild caches here!
3777 // Devs need to learn to purge all caches after any change or disable $CFG->langstringcache.
3779 $data = new stdClass();
3781 if ($sm->string_exists($identifier, $component)) {
3782 $data->heading = format_string(get_string($identifier, $component));
3783 } else {
3784 // Gracefully fall back to an empty string.
3785 $data->heading = '';
3788 if ($sm->string_exists($identifier . '_help', $component)) {
3789 $options = new stdClass();
3790 $options->trusted = false;
3791 $options->noclean = false;
3792 $options->filter = false;
3793 $options->para = true;
3794 $options->newlines = false;
3795 $options->overflowdiv = !$ajax;
3797 // Should be simple wiki only MDL-21695.
3798 $data->text = format_text(get_string($identifier.'_help', $component, $a), FORMAT_MARKDOWN, $options);
3800 $helplink = $identifier . '_link';
3801 if ($sm->string_exists($helplink, $component)) { // Link to further info in Moodle docs.
3802 $link = get_string($helplink, $component);
3803 $linktext = get_string('morehelp');
3805 $data->doclink = new stdClass();
3806 $url = new moodle_url(get_docs_url($link));
3807 if ($ajax) {
3808 $data->doclink->link = $url->out();
3809 $data->doclink->linktext = $linktext;
3810 $data->doclink->class = ($CFG->doctonewwindow) ? 'helplinkpopup' : '';
3811 } else {
3812 $data->completedoclink = html_writer::tag('div', $OUTPUT->doc_link($link, $linktext),
3813 array('class' => 'helpdoclink'));
3816 } else {
3817 $data->text = html_writer::tag('p',
3818 html_writer::tag('strong', 'TODO') . ": missing help string [{$identifier}_help, {$component}]");
3820 return $data;