Merge branch 'MDL-77433-master' of https://github.com/ferranrecio/moodle
[moodle.git] / lib / weblib.php
blobed22ae021388b00aac31d49a8a142edb0670f453
1 <?php
2 // This file is part of Moodle - http://moodle.org/
3 //
4 // Moodle is free software: you can redistribute it and/or modify
5 // it under the terms of the GNU General Public License as published by
6 // the Free Software Foundation, either version 3 of the License, or
7 // (at your option) any later version.
8 //
9 // Moodle is distributed in the hope that it will be useful,
10 // but WITHOUT ANY WARRANTY; without even the implied warranty of
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 // GNU General Public License for more details.
14 // You should have received a copy of the GNU General Public License
15 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
17 /**
18 * Library of functions for web output
20 * Library of all general-purpose Moodle PHP functions and constants
21 * that produce HTML output
23 * Other main libraries:
24 * - datalib.php - functions that access the database.
25 * - moodlelib.php - general-purpose Moodle functions.
27 * @package core
28 * @subpackage lib
29 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
30 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
33 defined('MOODLE_INTERNAL') || die();
35 // Constants.
37 // Define text formatting types ... eventually we can add Wiki, BBcode etc.
39 /**
40 * Does all sorts of transformations and filtering.
42 define('FORMAT_MOODLE', '0');
44 /**
45 * Plain HTML (with some tags stripped).
47 define('FORMAT_HTML', '1');
49 /**
50 * Plain text (even tags are printed in full).
52 define('FORMAT_PLAIN', '2');
54 /**
55 * Wiki-formatted text.
56 * Deprecated: left here just to note that '3' is not used (at the moment)
57 * and to catch any latent wiki-like text (which generates an error)
58 * @deprecated since 2005!
60 define('FORMAT_WIKI', '3');
62 /**
63 * Markdown-formatted text http://daringfireball.net/projects/markdown/
65 define('FORMAT_MARKDOWN', '4');
67 /**
68 * A moodle_url comparison using this flag will return true if the base URLs match, params are ignored.
70 define('URL_MATCH_BASE', 0);
72 /**
73 * A moodle_url comparison using this flag will return true if the base URLs match and the params of url1 are part of url2.
75 define('URL_MATCH_PARAMS', 1);
77 /**
78 * A moodle_url comparison using this flag will return true if the two URLs are identical, except for the order of the params.
80 define('URL_MATCH_EXACT', 2);
82 // Functions.
84 /**
85 * Add quotes to HTML characters.
87 * Returns $var with HTML characters (like "<", ">", etc.) properly quoted.
88 * Related function {@link p()} simply prints the output of this function.
90 * @param string $var the string potentially containing HTML characters
91 * @return string
93 function s($var) {
94 if ($var === false) {
95 return '0';
98 if ($var === null || $var === '') {
99 return '';
102 return preg_replace(
103 '/&amp;#(\d+|x[0-9a-f]+);/i', '&#$1;',
104 htmlspecialchars($var, ENT_QUOTES | ENT_HTML401 | ENT_SUBSTITUTE)
109 * Add quotes to HTML characters.
111 * Prints $var with HTML characters (like "<", ">", etc.) properly quoted.
112 * This function simply calls & displays {@link s()}.
113 * @see s()
115 * @param string $var the string potentially containing HTML characters
116 * @return string
118 function p($var) {
119 echo s($var);
123 * Does proper javascript quoting.
125 * Do not use addslashes anymore, because it does not work when magic_quotes_sybase is enabled.
127 * @param mixed $var String, Array, or Object to add slashes to
128 * @return mixed quoted result
130 function addslashes_js($var) {
131 if (is_string($var)) {
132 $var = str_replace('\\', '\\\\', $var);
133 $var = str_replace(array('\'', '"', "\n", "\r", "\0"), array('\\\'', '\\"', '\\n', '\\r', '\\0'), $var);
134 $var = str_replace('</', '<\/', $var); // XHTML compliance.
135 } else if (is_array($var)) {
136 $var = array_map('addslashes_js', $var);
137 } else if (is_object($var)) {
138 $a = get_object_vars($var);
139 foreach ($a as $key => $value) {
140 $a[$key] = addslashes_js($value);
142 $var = (object)$a;
144 return $var;
148 * Remove query string from url.
150 * Takes in a URL and returns it without the querystring portion.
152 * @param string $url the url which may have a query string attached.
153 * @return string The remaining URL.
155 function strip_querystring($url) {
156 if ($url === null || $url === '') {
157 return '';
160 if ($commapos = strpos($url, '?')) {
161 return substr($url, 0, $commapos);
162 } else {
163 return $url;
168 * Returns the name of the current script, WITH the querystring portion.
170 * This function is necessary because PHP_SELF and REQUEST_URI and SCRIPT_NAME
171 * return different things depending on a lot of things like your OS, Web
172 * server, and the way PHP is compiled (ie. as a CGI, module, ISAPI, etc.)
173 * <b>NOTE:</b> This function returns false if the global variables needed are not set.
175 * @return mixed String or false if the global variables needed are not set.
177 function me() {
178 global $ME;
179 return $ME;
183 * Guesses the full URL of the current script.
185 * This function is using $PAGE->url, but may fall back to $FULLME which
186 * is constructed from PHP_SELF and REQUEST_URI or SCRIPT_NAME
188 * @return mixed full page URL string or false if unknown
190 function qualified_me() {
191 global $FULLME, $PAGE, $CFG;
193 if (isset($PAGE) and $PAGE->has_set_url()) {
194 // This is the only recommended way to find out current page.
195 return $PAGE->url->out(false);
197 } else {
198 if ($FULLME === null) {
199 // CLI script most probably.
200 return false;
202 if (!empty($CFG->sslproxy)) {
203 // Return only https links when using SSL proxy.
204 return preg_replace('/^http:/', 'https:', $FULLME, 1);
205 } else {
206 return $FULLME;
212 * Determines whether or not the Moodle site is being served over HTTPS.
214 * This is done simply by checking the value of $CFG->wwwroot, which seems
215 * to be the only reliable method.
217 * @return boolean True if site is served over HTTPS, false otherwise.
219 function is_https() {
220 global $CFG;
222 return (strpos($CFG->wwwroot, 'https://') === 0);
226 * Returns the cleaned local URL of the HTTP_REFERER less the URL query string parameters if required.
228 * @param bool $stripquery if true, also removes the query part of the url.
229 * @return string The resulting referer or empty string.
231 function get_local_referer($stripquery = true) {
232 if (isset($_SERVER['HTTP_REFERER'])) {
233 $referer = clean_param($_SERVER['HTTP_REFERER'], PARAM_LOCALURL);
234 if ($stripquery) {
235 return strip_querystring($referer);
236 } else {
237 return $referer;
239 } else {
240 return '';
245 * Class for creating and manipulating urls.
247 * It can be used in moodle pages where config.php has been included without any further includes.
249 * It is useful for manipulating urls with long lists of params.
250 * One situation where it will be useful is a page which links to itself to perform various actions
251 * and / or to process form data. A moodle_url object :
252 * can be created for a page to refer to itself with all the proper get params being passed from page call to
253 * page call and methods can be used to output a url including all the params, optionally adding and overriding
254 * params and can also be used to
255 * - output the url without any get params
256 * - and output the params as hidden fields to be output within a form
258 * @copyright 2007 jamiesensei
259 * @link http://docs.moodle.org/dev/lib/weblib.php_moodle_url See short write up here
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 * Shortcut for printing of encoded URL.
543 * @return string
545 public function __toString() {
546 return $this->out(true);
550 * Output url.
552 * If you use the returned URL in HTML code, you want the escaped ampersands. If you use
553 * the returned URL in HTTP headers, you want $escaped=false.
555 * @param bool $escaped Use &amp; as params separator instead of plain &
556 * @param array $overrideparams params to add to the output url, these override existing ones with the same name.
557 * @return string Resulting URL
559 public function out($escaped = true, array $overrideparams = null) {
561 global $CFG;
563 if (!is_bool($escaped)) {
564 debugging('Escape parameter must be of type boolean, '.gettype($escaped).' given instead.');
567 $url = $this;
569 // Allow url's to be rewritten by a plugin.
570 if (isset($CFG->urlrewriteclass) && !isset($CFG->upgraderunning)) {
571 $class = $CFG->urlrewriteclass;
572 $pluginurl = $class::url_rewrite($url);
573 if ($pluginurl instanceof moodle_url) {
574 $url = $pluginurl;
578 return $url->raw_out($escaped, $overrideparams);
583 * Output url without any rewrites
585 * This is identical in signature and use to out() but doesn't call the rewrite handler.
587 * @param bool $escaped Use &amp; as params separator instead of plain &
588 * @param array $overrideparams params to add to the output url, these override existing ones with the same name.
589 * @return string Resulting URL
591 public function raw_out($escaped = true, array $overrideparams = null) {
592 if (!is_bool($escaped)) {
593 debugging('Escape parameter must be of type boolean, '.gettype($escaped).' given instead.');
596 $uri = $this->out_omit_querystring().$this->slashargument;
598 $querystring = $this->get_query_string($escaped, $overrideparams);
599 if ($querystring !== '') {
600 $uri .= '?' . $querystring;
602 if (!is_null($this->anchor)) {
603 $uri .= '#'.$this->anchor;
606 return $uri;
610 * Returns url without parameters, everything before '?'.
612 * @param bool $includeanchor if {@link self::anchor} is defined, should it be returned?
613 * @return string
615 public function out_omit_querystring($includeanchor = false) {
617 $uri = $this->scheme ? $this->scheme.':'.((strtolower($this->scheme) == 'mailto') ? '':'//'): '';
618 $uri .= $this->user ? $this->user.($this->pass? ':'.$this->pass:'').'@':'';
619 $uri .= $this->host ? $this->host : '';
620 $uri .= $this->port ? ':'.$this->port : '';
621 $uri .= $this->path ? $this->path : '';
622 if ($includeanchor and !is_null($this->anchor)) {
623 $uri .= '#' . $this->anchor;
626 return $uri;
630 * Compares this moodle_url with another.
632 * See documentation of constants for an explanation of the comparison flags.
634 * @param moodle_url $url The moodle_url object to compare
635 * @param int $matchtype The type of comparison (URL_MATCH_BASE, URL_MATCH_PARAMS, URL_MATCH_EXACT)
636 * @return bool
638 public function compare(moodle_url $url, $matchtype = URL_MATCH_EXACT) {
640 $baseself = $this->out_omit_querystring();
641 $baseother = $url->out_omit_querystring();
643 // Append index.php if there is no specific file.
644 if (substr($baseself, -1) == '/') {
645 $baseself .= 'index.php';
647 if (substr($baseother, -1) == '/') {
648 $baseother .= 'index.php';
651 // Compare the two base URLs.
652 if ($baseself != $baseother) {
653 return false;
656 if ($matchtype == URL_MATCH_BASE) {
657 return true;
660 $urlparams = $url->params();
661 foreach ($this->params() as $param => $value) {
662 if ($param == 'sesskey') {
663 continue;
665 if (!array_key_exists($param, $urlparams) || $urlparams[$param] != $value) {
666 return false;
670 if ($matchtype == URL_MATCH_PARAMS) {
671 return true;
674 foreach ($urlparams as $param => $value) {
675 if ($param == 'sesskey') {
676 continue;
678 if (!array_key_exists($param, $this->params()) || $this->param($param) != $value) {
679 return false;
683 if ($url->anchor !== $this->anchor) {
684 return false;
687 return true;
691 * Sets the anchor for the URI (the bit after the hash)
693 * @param string $anchor null means remove previous
695 public function set_anchor($anchor) {
696 if (is_null($anchor)) {
697 // Remove.
698 $this->anchor = null;
699 } else if ($anchor === '') {
700 // Special case, used as empty link.
701 $this->anchor = '';
702 } else if (preg_match('|[a-zA-Z\_\:][a-zA-Z0-9\_\-\.\:]*|', $anchor)) {
703 // Match the anchor against the NMTOKEN spec.
704 $this->anchor = $anchor;
705 } else {
706 // Bad luck, no valid anchor found.
707 $this->anchor = null;
712 * Sets the scheme for the URI (the bit before ://)
714 * @param string $scheme
716 public function set_scheme($scheme) {
717 // See http://www.ietf.org/rfc/rfc3986.txt part 3.1.
718 if (preg_match('/^[a-zA-Z][a-zA-Z0-9+.-]*$/', $scheme)) {
719 $this->scheme = $scheme;
720 } else {
721 throw new coding_exception('Bad URL scheme.');
726 * Sets the url slashargument value.
728 * @param string $path usually file path
729 * @param string $parameter name of page parameter if slasharguments not supported
730 * @param bool $supported usually null, then it depends on $CFG->slasharguments, use true or false for other servers
731 * @return void
733 public function set_slashargument($path, $parameter = 'file', $supported = null) {
734 global $CFG;
735 if (is_null($supported)) {
736 $supported = !empty($CFG->slasharguments);
739 if ($supported) {
740 $parts = explode('/', $path);
741 $parts = array_map('rawurlencode', $parts);
742 $path = implode('/', $parts);
743 $this->slashargument = $path;
744 unset($this->params[$parameter]);
746 } else {
747 $this->slashargument = '';
748 $this->params[$parameter] = $path;
752 // Static factory methods.
755 * General moodle file url.
757 * @param string $urlbase the script serving the file
758 * @param string $path
759 * @param bool $forcedownload
760 * @return moodle_url
762 public static function make_file_url($urlbase, $path, $forcedownload = false) {
763 $params = array();
764 if ($forcedownload) {
765 $params['forcedownload'] = 1;
767 $url = new moodle_url($urlbase, $params);
768 $url->set_slashargument($path);
769 return $url;
773 * Factory method for creation of url pointing to plugin file.
775 * Please note this method can be used only from the plugins to
776 * create urls of own files, it must not be used outside of plugins!
778 * @param int $contextid
779 * @param string $component
780 * @param string $area
781 * @param int $itemid
782 * @param string $pathname
783 * @param string $filename
784 * @param bool $forcedownload
785 * @param mixed $includetoken Whether to use a user token when displaying this group image.
786 * True indicates to generate a token for current user, and integer value indicates to generate a token for the
787 * user whose id is the value indicated.
788 * If the group picture is included in an e-mail or some other location where the audience is a specific
789 * user who will not be logged in when viewing, then we use a token to authenticate the user.
790 * @return moodle_url
792 public static function make_pluginfile_url($contextid, $component, $area, $itemid, $pathname, $filename,
793 $forcedownload = false, $includetoken = false) {
794 global $CFG, $USER;
796 $path = [];
798 if ($includetoken) {
799 $urlbase = "$CFG->wwwroot/tokenpluginfile.php";
800 $userid = $includetoken === true ? $USER->id : $includetoken;
801 $token = get_user_key('core_files', $userid);
802 if ($CFG->slasharguments) {
803 $path[] = $token;
805 } else {
806 $urlbase = "$CFG->wwwroot/pluginfile.php";
808 $path[] = $contextid;
809 $path[] = $component;
810 $path[] = $area;
812 if ($itemid !== null) {
813 $path[] = $itemid;
816 $path = "/" . implode('/', $path) . "{$pathname}{$filename}";
818 $url = self::make_file_url($urlbase, $path, $forcedownload, $includetoken);
819 if ($includetoken && empty($CFG->slasharguments)) {
820 $url->param('token', $token);
822 return $url;
826 * Factory method for creation of url pointing to plugin file.
827 * This method is the same that make_pluginfile_url but pointing to the webservice pluginfile.php script.
828 * It should be used only in external functions.
830 * @since 2.8
831 * @param int $contextid
832 * @param string $component
833 * @param string $area
834 * @param int $itemid
835 * @param string $pathname
836 * @param string $filename
837 * @param bool $forcedownload
838 * @return moodle_url
840 public static function make_webservice_pluginfile_url($contextid, $component, $area, $itemid, $pathname, $filename,
841 $forcedownload = false) {
842 global $CFG;
843 $urlbase = "$CFG->wwwroot/webservice/pluginfile.php";
844 if ($itemid === null) {
845 return self::make_file_url($urlbase, "/$contextid/$component/$area".$pathname.$filename, $forcedownload);
846 } else {
847 return self::make_file_url($urlbase, "/$contextid/$component/$area/$itemid".$pathname.$filename, $forcedownload);
852 * Factory method for creation of url pointing to draft file of current user.
854 * @param int $draftid draft item id
855 * @param string $pathname
856 * @param string $filename
857 * @param bool $forcedownload
858 * @return moodle_url
860 public static function make_draftfile_url($draftid, $pathname, $filename, $forcedownload = false) {
861 global $CFG, $USER;
862 $urlbase = "$CFG->wwwroot/draftfile.php";
863 $context = context_user::instance($USER->id);
865 return self::make_file_url($urlbase, "/$context->id/user/draft/$draftid".$pathname.$filename, $forcedownload);
869 * Factory method for creating of links to legacy course files.
871 * @param int $courseid
872 * @param string $filepath
873 * @param bool $forcedownload
874 * @return moodle_url
876 public static function make_legacyfile_url($courseid, $filepath, $forcedownload = false) {
877 global $CFG;
879 $urlbase = "$CFG->wwwroot/file.php";
880 return self::make_file_url($urlbase, '/'.$courseid.'/'.$filepath, $forcedownload);
884 * Checks if URL is relative to $CFG->wwwroot.
886 * @return bool True if URL is relative to $CFG->wwwroot; otherwise, false.
888 public function is_local_url() : bool {
889 global $CFG;
891 $url = $this->out();
892 // Does URL start with wwwroot? Otherwise, URL isn't relative to wwwroot.
893 return ( ($url === $CFG->wwwroot) || (strpos($url, $CFG->wwwroot.'/') === 0) );
897 * Returns URL as relative path from $CFG->wwwroot
899 * Can be used for passing around urls with the wwwroot stripped
901 * @param boolean $escaped Use &amp; as params separator instead of plain &
902 * @param array $overrideparams params to add to the output url, these override existing ones with the same name.
903 * @return string Resulting URL
904 * @throws coding_exception if called on a non-local url
906 public function out_as_local_url($escaped = true, array $overrideparams = null) {
907 global $CFG;
909 // URL should be relative to wwwroot. If not then throw exception.
910 if ($this->is_local_url()) {
911 $url = $this->out($escaped, $overrideparams);
912 $localurl = substr($url, strlen($CFG->wwwroot));
913 return !empty($localurl) ? $localurl : '';
914 } else {
915 throw new coding_exception('out_as_local_url called on a non-local URL');
920 * Returns the 'path' portion of a URL. For example, if the URL is
921 * http://www.example.org:447/my/file/is/here.txt?really=1 then this will
922 * return '/my/file/is/here.txt'.
924 * By default the path includes slash-arguments (for example,
925 * '/myfile.php/extra/arguments') so it is what you would expect from a
926 * URL path. If you don't want this behaviour, you can opt to exclude the
927 * slash arguments. (Be careful: if the $CFG variable slasharguments is
928 * disabled, these URLs will have a different format and you may need to
929 * look at the 'file' parameter too.)
931 * @param bool $includeslashargument If true, includes slash arguments
932 * @return string Path of URL
934 public function get_path($includeslashargument = true) {
935 return $this->path . ($includeslashargument ? $this->slashargument : '');
939 * Returns a given parameter value from the URL.
941 * @param string $name Name of parameter
942 * @return string Value of parameter or null if not set
944 public function get_param($name) {
945 if (array_key_exists($name, $this->params)) {
946 return $this->params[$name];
947 } else {
948 return null;
953 * Returns the 'scheme' portion of a URL. For example, if the URL is
954 * http://www.example.org:447/my/file/is/here.txt?really=1 then this will
955 * return 'http' (without the colon).
957 * @return string Scheme of the URL.
959 public function get_scheme() {
960 return $this->scheme;
964 * Returns the 'host' portion of a URL. For example, if the URL is
965 * http://www.example.org:447/my/file/is/here.txt?really=1 then this will
966 * return 'www.example.org'.
968 * @return string Host of the URL.
970 public function get_host() {
971 return $this->host;
975 * Returns the 'port' portion of a URL. For example, if the URL is
976 * http://www.example.org:447/my/file/is/here.txt?really=1 then this will
977 * return '447'.
979 * @return string Port of the URL.
981 public function get_port() {
982 return $this->port;
987 * Determine if there is data waiting to be processed from a form
989 * Used on most forms in Moodle to check for data
990 * Returns the data as an object, if it's found.
991 * This object can be used in foreach loops without
992 * casting because it's cast to (array) automatically
994 * Checks that submitted POST data exists and returns it as object.
996 * @return mixed false or object
998 function data_submitted() {
1000 if (empty($_POST)) {
1001 return false;
1002 } else {
1003 return (object)fix_utf8($_POST);
1008 * Given some normal text this function will break up any
1009 * long words to a given size by inserting the given character
1011 * It's multibyte savvy and doesn't change anything inside html tags.
1013 * @param string $string the string to be modified
1014 * @param int $maxsize maximum length of the string to be returned
1015 * @param string $cutchar the string used to represent word breaks
1016 * @return string
1018 function break_up_long_words($string, $maxsize=20, $cutchar=' ') {
1020 // First of all, save all the tags inside the text to skip them.
1021 $tags = array();
1022 filter_save_tags($string, $tags);
1024 // Process the string adding the cut when necessary.
1025 $output = '';
1026 $length = core_text::strlen($string);
1027 $wordlength = 0;
1029 for ($i=0; $i<$length; $i++) {
1030 $char = core_text::substr($string, $i, 1);
1031 if ($char == ' ' or $char == "\t" or $char == "\n" or $char == "\r" or $char == "<" or $char == ">") {
1032 $wordlength = 0;
1033 } else {
1034 $wordlength++;
1035 if ($wordlength > $maxsize) {
1036 $output .= $cutchar;
1037 $wordlength = 0;
1040 $output .= $char;
1043 // Finally load the tags back again.
1044 if (!empty($tags)) {
1045 $output = str_replace(array_keys($tags), $tags, $output);
1048 return $output;
1052 * Try and close the current window using JavaScript, either immediately, or after a delay.
1054 * Echo's out the resulting XHTML & javascript
1056 * @param integer $delay a delay in seconds before closing the window. Default 0.
1057 * @param boolean $reloadopener if true, we will see if this window was a pop-up, and try
1058 * to reload the parent window before this one closes.
1060 function close_window($delay = 0, $reloadopener = false) {
1061 global $PAGE, $OUTPUT;
1063 if (!$PAGE->headerprinted) {
1064 $PAGE->set_title(get_string('closewindow'));
1065 echo $OUTPUT->header();
1066 } else {
1067 $OUTPUT->container_end_all(false);
1070 if ($reloadopener) {
1071 // Trigger the reload immediately, even if the reload is after a delay.
1072 $PAGE->requires->js_function_call('window.opener.location.reload', array(true));
1074 $OUTPUT->notification(get_string('windowclosing'), 'notifysuccess');
1076 $PAGE->requires->js_function_call('close_window', array(new stdClass()), false, $delay);
1078 echo $OUTPUT->footer();
1079 exit;
1083 * Returns a string containing a link to the user documentation for the current page.
1085 * Also contains an icon by default. Shown to teachers and admin only.
1087 * @param string $text The text to be displayed for the link
1088 * @return string The link to user documentation for this current page
1090 function page_doc_link($text='') {
1091 global $OUTPUT, $PAGE;
1092 $path = page_get_doc_link_path($PAGE);
1093 if (!$path) {
1094 return '';
1096 return $OUTPUT->doc_link($path, $text);
1100 * Returns the path to use when constructing a link to the docs.
1102 * @since Moodle 2.5.1 2.6
1103 * @param moodle_page $page
1104 * @return string
1106 function page_get_doc_link_path(moodle_page $page) {
1107 global $CFG;
1109 if (empty($CFG->docroot) || during_initial_install()) {
1110 return '';
1112 if (!has_capability('moodle/site:doclinks', $page->context)) {
1113 return '';
1116 $path = $page->docspath;
1117 if (!$path) {
1118 return '';
1120 return $path;
1125 * Validates an email to make sure it makes sense.
1127 * @param string $address The email address to validate.
1128 * @return boolean
1130 function validate_email($address) {
1131 global $CFG;
1133 if ($address === null || $address === false || $address === '') {
1134 return false;
1137 require_once("{$CFG->libdir}/phpmailer/moodle_phpmailer.php");
1139 return moodle_phpmailer::validateAddress($address ?? '') && !preg_match('/[<>]/', $address);
1143 * Extracts file argument either from file parameter or PATH_INFO
1145 * Note: $scriptname parameter is not needed anymore
1147 * @return string file path (only safe characters)
1149 function get_file_argument() {
1150 global $SCRIPT;
1152 $relativepath = false;
1153 $hasforcedslashargs = false;
1155 if (isset($_SERVER['REQUEST_URI']) && !empty($_SERVER['REQUEST_URI'])) {
1156 // Checks whether $_SERVER['REQUEST_URI'] contains '/pluginfile.php/'
1157 // instead of '/pluginfile.php?', when serving a file from e.g. mod_imscp or mod_scorm.
1158 if ((strpos($_SERVER['REQUEST_URI'], '/pluginfile.php/') !== false)
1159 && isset($_SERVER['PATH_INFO']) && !empty($_SERVER['PATH_INFO'])) {
1160 // Exclude edge cases like '/pluginfile.php/?file='.
1161 $args = explode('/', ltrim($_SERVER['PATH_INFO'], '/'));
1162 $hasforcedslashargs = (count($args) > 2); // Always at least: context, component and filearea.
1165 if (!$hasforcedslashargs) {
1166 $relativepath = optional_param('file', false, PARAM_PATH);
1169 if ($relativepath !== false and $relativepath !== '') {
1170 return $relativepath;
1172 $relativepath = false;
1174 // Then try extract file from the slasharguments.
1175 if (stripos($_SERVER['SERVER_SOFTWARE'], 'iis') !== false) {
1176 // NOTE: IIS tends to convert all file paths to single byte DOS encoding,
1177 // we can not use other methods because they break unicode chars,
1178 // the only ways are to use URL rewriting
1179 // OR
1180 // to properly set the 'FastCGIUtf8ServerVariables' registry key.
1181 if (isset($_SERVER['PATH_INFO']) and $_SERVER['PATH_INFO'] !== '') {
1182 // Check that PATH_INFO works == must not contain the script name.
1183 if (strpos($_SERVER['PATH_INFO'], $SCRIPT) === false) {
1184 $relativepath = clean_param(urldecode($_SERVER['PATH_INFO']), PARAM_PATH);
1187 } else {
1188 // All other apache-like servers depend on PATH_INFO.
1189 if (isset($_SERVER['PATH_INFO'])) {
1190 if (isset($_SERVER['SCRIPT_NAME']) and strpos($_SERVER['PATH_INFO'], $_SERVER['SCRIPT_NAME']) === 0) {
1191 $relativepath = substr($_SERVER['PATH_INFO'], strlen($_SERVER['SCRIPT_NAME']));
1192 } else {
1193 $relativepath = $_SERVER['PATH_INFO'];
1195 $relativepath = clean_param($relativepath, PARAM_PATH);
1199 return $relativepath;
1203 * Just returns an array of text formats suitable for a popup menu
1205 * @return array
1207 function format_text_menu() {
1208 return array (FORMAT_MOODLE => get_string('formattext'),
1209 FORMAT_HTML => get_string('formathtml'),
1210 FORMAT_PLAIN => get_string('formatplain'),
1211 FORMAT_MARKDOWN => get_string('formatmarkdown'));
1215 * Given text in a variety of format codings, this function returns the text as safe HTML.
1217 * This function should mainly be used for long strings like posts,
1218 * answers, glossary items etc. For short strings {@link format_string()}.
1220 * <pre>
1221 * Options:
1222 * trusted : If true the string won't be cleaned. Default false required noclean=true.
1223 * noclean : If true the string won't be cleaned, unless $CFG->forceclean is set. Default false required trusted=true.
1224 * nocache : If true the strign will not be cached and will be formatted every call. Default false.
1225 * filter : If true the string will be run through applicable filters as well. Default true.
1226 * para : If true then the returned string will be wrapped in div tags. Default true.
1227 * newlines : If true then lines newline breaks will be converted to HTML newline breaks. Default true.
1228 * context : The context that will be used for filtering.
1229 * overflowdiv : If set to true the formatted text will be encased in a div
1230 * with the class no-overflow before being returned. Default false.
1231 * allowid : If true then id attributes will not be removed, even when
1232 * using htmlpurifier. Default false.
1233 * blanktarget : If true all <a> tags will have target="_blank" added unless target is explicitly specified.
1234 * </pre>
1236 * @staticvar array $croncache
1237 * @param string $text The text to be formatted. This is raw text originally from user input.
1238 * @param int $format Identifier of the text format to be used
1239 * [FORMAT_MOODLE, FORMAT_HTML, FORMAT_PLAIN, FORMAT_MARKDOWN]
1240 * @param object/array $options text formatting options
1241 * @param int $courseiddonotuse deprecated course id, use context option instead
1242 * @return string
1244 function format_text($text, $format = FORMAT_MOODLE, $options = null, $courseiddonotuse = null) {
1245 global $CFG, $DB, $PAGE;
1247 if ($text === '' || is_null($text)) {
1248 // No need to do any filters and cleaning.
1249 return '';
1252 // Detach object, we can not modify it.
1253 $options = (array)$options;
1255 if (!isset($options['trusted'])) {
1256 $options['trusted'] = false;
1258 if (!isset($options['noclean'])) {
1259 if ($options['trusted'] and trusttext_active()) {
1260 // No cleaning if text trusted and noclean not specified.
1261 $options['noclean'] = true;
1262 } else {
1263 $options['noclean'] = false;
1266 if (!empty($CFG->forceclean)) {
1267 // Whatever the caller claims, the admin wants all content cleaned anyway.
1268 $options['noclean'] = false;
1270 if (!isset($options['nocache'])) {
1271 $options['nocache'] = false;
1273 if (!isset($options['filter'])) {
1274 $options['filter'] = true;
1276 if (!isset($options['para'])) {
1277 $options['para'] = true;
1279 if (!isset($options['newlines'])) {
1280 $options['newlines'] = true;
1282 if (!isset($options['overflowdiv'])) {
1283 $options['overflowdiv'] = false;
1285 $options['blanktarget'] = !empty($options['blanktarget']);
1287 // Calculate best context.
1288 if (empty($CFG->version) or $CFG->version < 2013051400 or during_initial_install()) {
1289 // Do not filter anything during installation or before upgrade completes.
1290 $context = null;
1292 } else if (isset($options['context'])) { // First by explicit passed context option.
1293 if (is_object($options['context'])) {
1294 $context = $options['context'];
1295 } else {
1296 $context = context::instance_by_id($options['context']);
1298 } else if ($courseiddonotuse) {
1299 // Legacy courseid.
1300 $context = context_course::instance($courseiddonotuse);
1301 } else {
1302 // Fallback to $PAGE->context this may be problematic in CLI and other non-standard pages :-(.
1303 $context = $PAGE->context;
1306 if (!$context) {
1307 // Either install/upgrade or something has gone really wrong because context does not exist (yet?).
1308 $options['nocache'] = true;
1309 $options['filter'] = false;
1312 if ($options['filter']) {
1313 $filtermanager = filter_manager::instance();
1314 $filtermanager->setup_page_for_filters($PAGE, $context); // Setup global stuff filters may have.
1315 $filteroptions = array(
1316 'originalformat' => $format,
1317 'noclean' => $options['noclean'],
1319 } else {
1320 $filtermanager = new null_filter_manager();
1321 $filteroptions = array();
1324 switch ($format) {
1325 case FORMAT_HTML:
1326 if (!$options['noclean']) {
1327 $text = clean_text($text, FORMAT_HTML, $options);
1329 $text = $filtermanager->filter_text($text, $context, $filteroptions);
1330 break;
1332 case FORMAT_PLAIN:
1333 $text = s($text); // Cleans dangerous JS.
1334 $text = rebuildnolinktag($text);
1335 $text = str_replace(' ', '&nbsp; ', $text);
1336 $text = nl2br($text);
1337 break;
1339 case FORMAT_WIKI:
1340 // This format is deprecated.
1341 $text = '<p>NOTICE: Wiki-like formatting has been removed from Moodle. You should not be seeing
1342 this message as all texts should have been converted to Markdown format instead.
1343 Please post a bug report to http://moodle.org/bugs with information about where you
1344 saw this message.</p>'.s($text);
1345 break;
1347 case FORMAT_MARKDOWN:
1348 $text = markdown_to_html($text);
1349 // The markdown parser does not strip dangerous html so we need to clean it, even if noclean is set to true.
1350 $text = clean_text($text, FORMAT_HTML, $options);
1351 $text = $filtermanager->filter_text($text, $context, $filteroptions);
1352 break;
1354 default: // FORMAT_MOODLE or anything else.
1355 $text = text_to_html($text, null, $options['para'], $options['newlines']);
1356 if (!$options['noclean']) {
1357 $text = clean_text($text, FORMAT_HTML, $options);
1359 $text = $filtermanager->filter_text($text, $context, $filteroptions);
1360 break;
1362 if ($options['filter']) {
1363 // At this point there should not be any draftfile links any more,
1364 // this happens when developers forget to post process the text.
1365 // The only potential problem is that somebody might try to format
1366 // the text before storing into database which would be itself big bug..
1367 $text = str_replace("\"$CFG->wwwroot/draftfile.php", "\"$CFG->wwwroot/brokenfile.php#", $text);
1369 if ($CFG->debugdeveloper) {
1370 if (strpos($text, '@@PLUGINFILE@@/') !== false) {
1371 debugging('Before calling format_text(), the content must be processed with file_rewrite_pluginfile_urls()',
1372 DEBUG_DEVELOPER);
1377 if (!empty($options['overflowdiv'])) {
1378 $text = html_writer::tag('div', $text, array('class' => 'no-overflow'));
1381 if ($options['blanktarget']) {
1382 $domdoc = new DOMDocument();
1383 libxml_use_internal_errors(true);
1384 $domdoc->loadHTML('<?xml version="1.0" encoding="UTF-8" ?>' . $text);
1385 libxml_clear_errors();
1386 foreach ($domdoc->getElementsByTagName('a') as $link) {
1387 if ($link->hasAttribute('target') && strpos($link->getAttribute('target'), '_blank') === false) {
1388 continue;
1390 $link->setAttribute('target', '_blank');
1391 if (strpos($link->getAttribute('rel'), 'noreferrer') === false) {
1392 $link->setAttribute('rel', trim($link->getAttribute('rel') . ' noreferrer'));
1396 // This regex is nasty and I don't like it. The correct way to solve this is by loading the HTML like so:
1397 // $domdoc->loadHTML($text, LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD); however it seems like the libxml
1398 // version that travis uses doesn't work properly and ends up leaving <html><body>, so I'm forced to use
1399 // this regex to remove those tags.
1400 $text = trim(preg_replace('~<(?:!DOCTYPE|/?(?:html|body))[^>]*>\s*~i', '', $domdoc->saveHTML($domdoc->documentElement)));
1403 return $text;
1407 * Resets some data related to filters, called during upgrade or when general filter settings change.
1409 * @param bool $phpunitreset true means called from our PHPUnit integration test reset
1410 * @return void
1412 function reset_text_filters_cache($phpunitreset = false) {
1413 global $CFG, $DB;
1415 if ($phpunitreset) {
1416 // HTMLPurifier does not change, DB is already reset to defaults,
1417 // nothing to do here, the dataroot was cleared too.
1418 return;
1421 // The purge_all_caches() deals with cachedir and localcachedir purging,
1422 // the individual filter caches are invalidated as necessary elsewhere.
1424 // Update $CFG->filterall cache flag.
1425 if (empty($CFG->stringfilters)) {
1426 set_config('filterall', 0);
1427 return;
1429 $installedfilters = core_component::get_plugin_list('filter');
1430 $filters = explode(',', $CFG->stringfilters);
1431 foreach ($filters as $filter) {
1432 if (isset($installedfilters[$filter])) {
1433 set_config('filterall', 1);
1434 return;
1437 set_config('filterall', 0);
1441 * Given a simple string, this function returns the string
1442 * processed by enabled string filters if $CFG->filterall is enabled
1444 * This function should be used to print short strings (non html) that
1445 * need filter processing e.g. activity titles, post subjects,
1446 * glossary concepts.
1448 * @staticvar bool $strcache
1449 * @param string $string The string to be filtered. Should be plain text, expect
1450 * possibly for multilang tags.
1451 * @param boolean $striplinks To strip any link in the result text. Moodle 1.8 default changed from false to true! MDL-8713
1452 * @param array $options options array/object or courseid
1453 * @return string
1455 function format_string($string, $striplinks = true, $options = null) {
1456 global $CFG, $PAGE;
1458 if ($string === '' || is_null($string)) {
1459 // No need to do any filters and cleaning.
1460 return '';
1463 // We'll use a in-memory cache here to speed up repeated strings.
1464 static $strcache = false;
1466 if (empty($CFG->version) or $CFG->version < 2013051400 or during_initial_install()) {
1467 // Do not filter anything during installation or before upgrade completes.
1468 return $string = strip_tags($string);
1471 if ($strcache === false or count($strcache) > 2000) {
1472 // This number might need some tuning to limit memory usage in cron.
1473 $strcache = array();
1476 if (is_numeric($options)) {
1477 // Legacy courseid usage.
1478 $options = array('context' => context_course::instance($options));
1479 } else {
1480 // Detach object, we can not modify it.
1481 $options = (array)$options;
1484 if (empty($options['context'])) {
1485 // Fallback to $PAGE->context this may be problematic in CLI and other non-standard pages :-(.
1486 $options['context'] = $PAGE->context;
1487 } else if (is_numeric($options['context'])) {
1488 $options['context'] = context::instance_by_id($options['context']);
1490 if (!isset($options['filter'])) {
1491 $options['filter'] = true;
1494 $options['escape'] = !isset($options['escape']) || $options['escape'];
1496 if (!$options['context']) {
1497 // We did not find any context? weird.
1498 return $string = strip_tags($string);
1501 // Calculate md5.
1502 $cachekeys = array($string, $striplinks, $options['context']->id,
1503 $options['escape'], current_language(), $options['filter']);
1504 $md5 = md5(implode('<+>', $cachekeys));
1506 // Fetch from cache if possible.
1507 if (isset($strcache[$md5])) {
1508 return $strcache[$md5];
1511 // First replace all ampersands not followed by html entity code
1512 // Regular expression moved to its own method for easier unit testing.
1513 $string = $options['escape'] ? replace_ampersands_not_followed_by_entity($string) : $string;
1515 if (!empty($CFG->filterall) && $options['filter']) {
1516 $filtermanager = filter_manager::instance();
1517 $filtermanager->setup_page_for_filters($PAGE, $options['context']); // Setup global stuff filters may have.
1518 $string = $filtermanager->filter_string($string, $options['context']);
1521 // If the site requires it, strip ALL tags from this string.
1522 if (!empty($CFG->formatstringstriptags)) {
1523 if ($options['escape']) {
1524 $string = str_replace(array('<', '>'), array('&lt;', '&gt;'), strip_tags($string));
1525 } else {
1526 $string = strip_tags($string);
1528 } else {
1529 // Otherwise strip just links if that is required (default).
1530 if ($striplinks) {
1531 // Strip links in string.
1532 $string = strip_links($string);
1534 $string = clean_text($string);
1537 // Store to cache.
1538 $strcache[$md5] = $string;
1540 return $string;
1544 * Given a string, performs a negative lookahead looking for any ampersand character
1545 * that is not followed by a proper HTML entity. If any is found, it is replaced
1546 * by &amp;. The string is then returned.
1548 * @param string $string
1549 * @return string
1551 function replace_ampersands_not_followed_by_entity($string) {
1552 return preg_replace("/\&(?![a-zA-Z0-9#]{1,8};)/", "&amp;", $string ?? '');
1556 * Given a string, replaces all <a>.*</a> by .* and returns the string.
1558 * @param string $string
1559 * @return string
1561 function strip_links($string) {
1562 return preg_replace('/(<a\s[^>]+?>)(.+?)(<\/a>)/is', '$2', $string);
1566 * This expression turns links into something nice in a text format. (Russell Jungwirth)
1568 * @param string $string
1569 * @return string
1571 function wikify_links($string) {
1572 return preg_replace('~(<a [^<]*href=["|\']?([^ "\']*)["|\']?[^>]*>([^<]*)</a>)~i', '$3 [ $2 ]', $string);
1576 * Given text in a variety of format codings, this function returns the text as plain text suitable for plain email.
1578 * @param string $text The text to be formatted. This is raw text originally from user input.
1579 * @param int $format Identifier of the text format to be used
1580 * [FORMAT_MOODLE, FORMAT_HTML, FORMAT_PLAIN, FORMAT_WIKI, FORMAT_MARKDOWN]
1581 * @return string
1583 function format_text_email($text, $format) {
1585 switch ($format) {
1587 case FORMAT_PLAIN:
1588 return $text;
1589 break;
1591 case FORMAT_WIKI:
1592 // There should not be any of these any more!
1593 $text = wikify_links($text);
1594 return core_text::entities_to_utf8(strip_tags($text), true);
1595 break;
1597 case FORMAT_HTML:
1598 return html_to_text($text);
1599 break;
1601 case FORMAT_MOODLE:
1602 case FORMAT_MARKDOWN:
1603 default:
1604 $text = wikify_links($text);
1605 return core_text::entities_to_utf8(strip_tags($text), true);
1606 break;
1611 * Formats activity intro text
1613 * @param string $module name of module
1614 * @param object $activity instance of activity
1615 * @param int $cmid course module id
1616 * @param bool $filter filter resulting html text
1617 * @return string
1619 function format_module_intro($module, $activity, $cmid, $filter=true) {
1620 global $CFG;
1621 require_once("$CFG->libdir/filelib.php");
1622 $context = context_module::instance($cmid);
1623 $options = array('noclean' => true, 'para' => false, 'filter' => $filter, 'context' => $context, 'overflowdiv' => true);
1624 $intro = file_rewrite_pluginfile_urls($activity->intro, 'pluginfile.php', $context->id, 'mod_'.$module, 'intro', null);
1625 return trim(format_text($intro, $activity->introformat, $options, null));
1629 * Removes the usage of Moodle files from a text.
1631 * In some rare cases we need to re-use a text that already has embedded links
1632 * to some files hosted within Moodle. But the new area in which we will push
1633 * this content does not support files... therefore we need to remove those files.
1635 * @param string $source The text
1636 * @return string The stripped text
1638 function strip_pluginfile_content($source) {
1639 $baseurl = '@@PLUGINFILE@@';
1640 // Looking for something like < .* "@@pluginfile@@.*" .* >
1641 $pattern = '$<[^<>]+["\']' . $baseurl . '[^"\']*["\'][^<>]*>$';
1642 $stripped = preg_replace($pattern, '', $source);
1643 // Use purify html to rebalence potentially mismatched tags and generally cleanup.
1644 return purify_html($stripped);
1648 * Legacy function, used for cleaning of old forum and glossary text only.
1650 * @param string $text text that may contain legacy TRUSTTEXT marker
1651 * @return string text without legacy TRUSTTEXT marker
1653 function trusttext_strip($text) {
1654 if (!is_string($text)) {
1655 // This avoids the potential for an endless loop below.
1656 throw new coding_exception('trusttext_strip parameter must be a string');
1658 while (true) { // Removing nested TRUSTTEXT.
1659 $orig = $text;
1660 $text = str_replace('#####TRUSTTEXT#####', '', $text);
1661 if (strcmp($orig, $text) === 0) {
1662 return $text;
1668 * Must be called before editing of all texts with trust flag. Removes all XSS nasties from texts stored in database if needed.
1670 * @param stdClass $object data object with xxx, xxxformat and xxxtrust fields
1671 * @param string $field name of text field
1672 * @param context $context active context
1673 * @return stdClass updated $object
1675 function trusttext_pre_edit($object, $field, $context) {
1676 $trustfield = $field.'trust';
1677 $formatfield = $field.'format';
1679 if (!$object->$trustfield or !trusttext_trusted($context)) {
1680 $object->$field = clean_text($object->$field, $object->$formatfield);
1683 return $object;
1687 * Is current user trusted to enter no dangerous XSS in this context?
1689 * Please note the user must be in fact trusted everywhere on this server!!
1691 * @param context $context
1692 * @return bool true if user trusted
1694 function trusttext_trusted($context) {
1695 return (trusttext_active() and has_capability('moodle/site:trustcontent', $context));
1699 * Is trusttext feature active?
1701 * @return bool
1703 function trusttext_active() {
1704 global $CFG;
1706 return !empty($CFG->enabletrusttext);
1710 * Cleans raw text removing nasties.
1712 * Given raw text (eg typed in by a user) this function cleans it up and removes any nasty tags that could mess up
1713 * Moodle pages through XSS attacks.
1715 * The result must be used as a HTML text fragment, this function can not cleanup random
1716 * parts of html tags such as url or src attributes.
1718 * NOTE: the format parameter was deprecated because we can safely clean only HTML.
1720 * @param string $text The text to be cleaned
1721 * @param int|string $format deprecated parameter, should always contain FORMAT_HTML or FORMAT_MOODLE
1722 * @param array $options Array of options; currently only option supported is 'allowid' (if true,
1723 * does not remove id attributes when cleaning)
1724 * @return string The cleaned up text
1726 function clean_text($text, $format = FORMAT_HTML, $options = array()) {
1727 $text = (string)$text;
1729 if ($format != FORMAT_HTML and $format != FORMAT_HTML) {
1730 // TODO: we need to standardise cleanup of text when loading it into editor first.
1731 // debugging('clean_text() is designed to work only with html');.
1734 if ($format == FORMAT_PLAIN) {
1735 return $text;
1738 if (is_purify_html_necessary($text)) {
1739 $text = purify_html($text, $options);
1742 // Originally we tried to neutralise some script events here, it was a wrong approach because
1743 // it was trivial to work around that (for example using style based XSS exploits).
1744 // We must not give false sense of security here - all developers MUST understand how to use
1745 // rawurlencode(), htmlentities(), htmlspecialchars(), p(), s(), moodle_url, html_writer and friends!!!
1747 return $text;
1751 * Is it necessary to use HTMLPurifier?
1753 * @private
1754 * @param string $text
1755 * @return bool false means html is safe and valid, true means use HTMLPurifier
1757 function is_purify_html_necessary($text) {
1758 if ($text === '') {
1759 return false;
1762 if ($text === (string)((int)$text)) {
1763 return false;
1766 if (strpos($text, '&') !== false or preg_match('|<[^pesb/]|', $text)) {
1767 // We need to normalise entities or other tags except p, em, strong and br present.
1768 return true;
1771 $altered = htmlspecialchars($text, ENT_NOQUOTES, 'UTF-8', true);
1772 if ($altered === $text) {
1773 // No < > or other special chars means this must be safe.
1774 return false;
1777 // Let's try to convert back some safe html tags.
1778 $altered = preg_replace('|&lt;p&gt;(.*?)&lt;/p&gt;|m', '<p>$1</p>', $altered);
1779 if ($altered === $text) {
1780 return false;
1782 $altered = preg_replace('|&lt;em&gt;([^<>]+?)&lt;/em&gt;|m', '<em>$1</em>', $altered);
1783 if ($altered === $text) {
1784 return false;
1786 $altered = preg_replace('|&lt;strong&gt;([^<>]+?)&lt;/strong&gt;|m', '<strong>$1</strong>', $altered);
1787 if ($altered === $text) {
1788 return false;
1790 $altered = str_replace('&lt;br /&gt;', '<br />', $altered);
1791 if ($altered === $text) {
1792 return false;
1795 return true;
1799 * KSES replacement cleaning function - uses HTML Purifier.
1801 * @param string $text The (X)HTML string to purify
1802 * @param array $options Array of options; currently only option supported is 'allowid' (if set,
1803 * does not remove id attributes when cleaning)
1804 * @return string
1806 function purify_html($text, $options = array()) {
1807 global $CFG;
1809 $text = (string)$text;
1811 static $purifiers = array();
1812 static $caches = array();
1814 // Purifier code can change only during major version upgrade.
1815 $version = empty($CFG->version) ? 0 : $CFG->version;
1816 $cachedir = "$CFG->localcachedir/htmlpurifier/$version";
1817 if (!file_exists($cachedir)) {
1818 // Purging of caches may remove the cache dir at any time,
1819 // luckily file_exists() results should be cached for all existing directories.
1820 $purifiers = array();
1821 $caches = array();
1822 gc_collect_cycles();
1824 make_localcache_directory('htmlpurifier', false);
1825 check_dir_exists($cachedir);
1828 $allowid = empty($options['allowid']) ? 0 : 1;
1829 $allowobjectembed = empty($CFG->allowobjectembed) ? 0 : 1;
1831 $type = 'type_'.$allowid.'_'.$allowobjectembed;
1833 if (!array_key_exists($type, $caches)) {
1834 $caches[$type] = cache::make('core', 'htmlpurifier', array('type' => $type));
1836 $cache = $caches[$type];
1838 // Add revision number and all options to the text key so that it is compatible with local cluster node caches.
1839 $key = "|$version|$allowobjectembed|$allowid|$text";
1840 $filteredtext = $cache->get($key);
1842 if ($filteredtext === true) {
1843 // The filtering did not change the text last time, no need to filter anything again.
1844 return $text;
1845 } else if ($filteredtext !== false) {
1846 return $filteredtext;
1849 if (empty($purifiers[$type])) {
1850 require_once $CFG->libdir.'/htmlpurifier/HTMLPurifier.safe-includes.php';
1851 require_once $CFG->libdir.'/htmlpurifier/locallib.php';
1852 $config = HTMLPurifier_Config::createDefault();
1854 $config->set('HTML.DefinitionID', 'moodlehtml');
1855 $config->set('HTML.DefinitionRev', 6);
1856 $config->set('Cache.SerializerPath', $cachedir);
1857 $config->set('Cache.SerializerPermissions', $CFG->directorypermissions);
1858 $config->set('Core.NormalizeNewlines', false);
1859 $config->set('Core.ConvertDocumentToFragment', true);
1860 $config->set('Core.Encoding', 'UTF-8');
1861 $config->set('HTML.Doctype', 'XHTML 1.0 Transitional');
1862 $config->set('URI.AllowedSchemes', array(
1863 'http' => true,
1864 'https' => true,
1865 'ftp' => true,
1866 'irc' => true,
1867 'nntp' => true,
1868 'news' => true,
1869 'rtsp' => true,
1870 'rtmp' => true,
1871 'teamspeak' => true,
1872 'gopher' => true,
1873 'mms' => true,
1874 'mailto' => true
1876 $config->set('Attr.AllowedFrameTargets', array('_blank'));
1878 if ($allowobjectembed) {
1879 $config->set('HTML.SafeObject', true);
1880 $config->set('Output.FlashCompat', true);
1881 $config->set('HTML.SafeEmbed', true);
1884 if ($allowid) {
1885 $config->set('Attr.EnableID', true);
1888 if ($def = $config->maybeGetRawHTMLDefinition()) {
1889 $def->addElement('nolink', 'Inline', 'Flow', array()); // Skip our filters inside.
1890 $def->addElement('tex', 'Inline', 'Inline', array()); // Tex syntax, equivalent to $$xx$$.
1891 $def->addElement('algebra', 'Inline', 'Inline', array()); // Algebra syntax, equivalent to @@xx@@.
1892 $def->addElement('lang', 'Block', 'Flow', array(), array('lang'=>'CDATA')); // Original multilang style - only our hacked lang attribute.
1893 $def->addAttribute('span', 'xxxlang', 'CDATA'); // Current very problematic multilang.
1895 // Media elements.
1896 // https://html.spec.whatwg.org/#the-video-element
1897 $def->addElement('video', 'Block', 'Optional: #PCDATA | Flow | source | track', 'Common', [
1898 'src' => 'URI',
1899 'crossorigin' => 'Enum#anonymous,use-credentials',
1900 'poster' => 'URI',
1901 'preload' => 'Enum#auto,metadata,none',
1902 'autoplay' => 'Bool',
1903 'playsinline' => 'Bool',
1904 'loop' => 'Bool',
1905 'muted' => 'Bool',
1906 'controls' => 'Bool',
1907 'width' => 'Length',
1908 'height' => 'Length',
1910 // https://html.spec.whatwg.org/#the-audio-element
1911 $def->addElement('audio', 'Block', 'Optional: #PCDATA | Flow | source | track', 'Common', [
1912 'src' => 'URI',
1913 'crossorigin' => 'Enum#anonymous,use-credentials',
1914 'preload' => 'Enum#auto,metadata,none',
1915 'autoplay' => 'Bool',
1916 'loop' => 'Bool',
1917 'muted' => 'Bool',
1918 'controls' => 'Bool'
1920 // https://html.spec.whatwg.org/#the-source-element
1921 $def->addElement('source', false, 'Empty', null, [
1922 'src' => 'URI',
1923 'type' => 'Text'
1925 // https://html.spec.whatwg.org/#the-track-element
1926 $def->addElement('track', false, 'Empty', null, [
1927 'src' => 'URI',
1928 'kind' => 'Enum#subtitles,captions,descriptions,chapters,metadata',
1929 'srclang' => 'Text',
1930 'label' => 'Text',
1931 'default' => 'Bool',
1934 // Use the built-in Ruby module to add annotation support.
1935 $def->manager->addModule(new HTMLPurifier_HTMLModule_Ruby());
1938 $purifier = new HTMLPurifier($config);
1939 $purifiers[$type] = $purifier;
1940 } else {
1941 $purifier = $purifiers[$type];
1944 $multilang = (strpos($text, 'class="multilang"') !== false);
1946 $filteredtext = $text;
1947 if ($multilang) {
1948 $filteredtextregex = '/<span(\s+lang="([a-zA-Z0-9_-]+)"|\s+class="multilang"){2}\s*>/';
1949 $filteredtext = preg_replace($filteredtextregex, '<span xxxlang="${2}">', $filteredtext);
1951 $filteredtext = (string)$purifier->purify($filteredtext);
1952 if ($multilang) {
1953 $filteredtext = preg_replace('/<span xxxlang="([a-zA-Z0-9_-]+)">/', '<span lang="${1}" class="multilang">', $filteredtext);
1956 if ($text === $filteredtext) {
1957 // No need to store the filtered text, next time we will just return unfiltered text
1958 // because it was not changed by purifying.
1959 $cache->set($key, true);
1960 } else {
1961 $cache->set($key, $filteredtext);
1964 return $filteredtext;
1968 * Given plain text, makes it into HTML as nicely as possible.
1970 * May contain HTML tags already.
1972 * Do not abuse this function. It is intended as lower level formatting feature used
1973 * by {@link format_text()} to convert FORMAT_MOODLE to HTML. You are supposed
1974 * to call format_text() in most of cases.
1976 * @param string $text The string to convert.
1977 * @param boolean $smileyignored Was used to determine if smiley characters should convert to smiley images, ignored now
1978 * @param boolean $para If true then the returned string will be wrapped in div tags
1979 * @param boolean $newlines If true then lines newline breaks will be converted to HTML newline breaks.
1980 * @return string
1982 function text_to_html($text, $smileyignored = null, $para = true, $newlines = true) {
1983 // Remove any whitespace that may be between HTML tags.
1984 $text = preg_replace("~>([[:space:]]+)<~i", "><", $text);
1986 // Remove any returns that precede or follow HTML tags.
1987 $text = preg_replace("~([\n\r])<~i", " <", $text);
1988 $text = preg_replace("~>([\n\r])~i", "> ", $text);
1990 // Make returns into HTML newlines.
1991 if ($newlines) {
1992 $text = nl2br($text);
1995 // Wrap the whole thing in a div if required.
1996 if ($para) {
1997 // In 1.9 this was changed from a p => div.
1998 return '<div class="text_to_html">'.$text.'</div>';
1999 } else {
2000 return $text;
2005 * Given Markdown formatted text, make it into XHTML using external function
2007 * @param string $text The markdown formatted text to be converted.
2008 * @return string Converted text
2010 function markdown_to_html($text) {
2011 global $CFG;
2013 if ($text === '' or $text === null) {
2014 return $text;
2017 require_once($CFG->libdir .'/markdown/MarkdownInterface.php');
2018 require_once($CFG->libdir .'/markdown/Markdown.php');
2019 require_once($CFG->libdir .'/markdown/MarkdownExtra.php');
2021 return \Michelf\MarkdownExtra::defaultTransform($text);
2025 * Given HTML text, make it into plain text using external function
2027 * @param string $html The text to be converted.
2028 * @param integer $width Width to wrap the text at. (optional, default 75 which
2029 * is a good value for email. 0 means do not limit line length.)
2030 * @param boolean $dolinks By default, any links in the HTML are collected, and
2031 * printed as a list at the end of the HTML. If you don't want that, set this
2032 * argument to false.
2033 * @return string plain text equivalent of the HTML.
2035 function html_to_text($html, $width = 75, $dolinks = true) {
2036 global $CFG;
2038 require_once($CFG->libdir .'/html2text/lib.php');
2040 $options = array(
2041 'width' => $width,
2042 'do_links' => 'table',
2045 if (empty($dolinks)) {
2046 $options['do_links'] = 'none';
2048 $h2t = new core_html2text($html, $options);
2049 $result = $h2t->getText();
2051 return $result;
2055 * Converts texts or strings to plain text.
2057 * - When used to convert user input introduced in an editor the text format needs to be passed in $contentformat like we usually
2058 * do in format_text.
2059 * - When this function is used for strings that are usually passed through format_string before displaying them
2060 * we need to set $contentformat to false. This will execute html_to_text as these strings can contain multilang tags if
2061 * multilang filter is applied to headings.
2063 * @param string $content The text as entered by the user
2064 * @param int|false $contentformat False for strings or the text format: FORMAT_MOODLE/FORMAT_HTML/FORMAT_PLAIN/FORMAT_MARKDOWN
2065 * @return string Plain text.
2067 function content_to_text($content, $contentformat) {
2069 switch ($contentformat) {
2070 case FORMAT_PLAIN:
2071 // Nothing here.
2072 break;
2073 case FORMAT_MARKDOWN:
2074 $content = markdown_to_html($content);
2075 $content = html_to_text($content, 75, false);
2076 break;
2077 default:
2078 // FORMAT_HTML, FORMAT_MOODLE and $contentformat = false, the later one are strings usually formatted through
2079 // format_string, we need to convert them from html because they can contain HTML (multilang filter).
2080 $content = html_to_text($content, 75, false);
2083 return trim($content, "\r\n ");
2087 * Factory method for extracting draft file links from arbitrary text using regular expressions. Only text
2088 * is required; other file fields may be passed to filter.
2090 * @param string $text Some html content.
2091 * @param bool $forcehttps force https urls.
2092 * @param int $contextid This parameter and the next three identify the file area to save to.
2093 * @param string $component The component name.
2094 * @param string $filearea The filearea.
2095 * @param int $itemid The item id for the filearea.
2096 * @param string $filename The specific filename of the file.
2097 * @return array
2099 function extract_draft_file_urls_from_text($text, $forcehttps = false, $contextid = null, $component = null,
2100 $filearea = null, $itemid = null, $filename = null) {
2101 global $CFG;
2103 $wwwroot = $CFG->wwwroot;
2104 if ($forcehttps) {
2105 $wwwroot = str_replace('http://', 'https://', $wwwroot);
2107 $urlstring = '/' . preg_quote($wwwroot, '/');
2109 $urlbase = preg_quote('draftfile.php');
2110 $urlstring .= "\/(?<urlbase>{$urlbase})";
2112 if (is_null($contextid)) {
2113 $contextid = '[0-9]+';
2115 $urlstring .= "\/(?<contextid>{$contextid})";
2117 if (is_null($component)) {
2118 $component = '[a-z_]+';
2120 $urlstring .= "\/(?<component>{$component})";
2122 if (is_null($filearea)) {
2123 $filearea = '[a-z_]+';
2125 $urlstring .= "\/(?<filearea>{$filearea})";
2127 if (is_null($itemid)) {
2128 $itemid = '[0-9]+';
2130 $urlstring .= "\/(?<itemid>{$itemid})";
2132 // Filename matching magic based on file_rewrite_urls_to_pluginfile().
2133 if (is_null($filename)) {
2134 $filename = '[^\'\",&<>|`\s:\\\\]+';
2136 $urlstring .= "\/(?<filename>{$filename})/";
2138 // Regular expression which matches URLs and returns their components.
2139 preg_match_all($urlstring, $text, $urls, PREG_SET_ORDER);
2140 return $urls;
2144 * This function will highlight search words in a given string
2146 * It cares about HTML and will not ruin links. It's best to use
2147 * this function after performing any conversions to HTML.
2149 * @param string $needle The search string. Syntax like "word1 +word2 -word3" is dealt with correctly.
2150 * @param string $haystack The string (HTML) within which to highlight the search terms.
2151 * @param boolean $matchcase whether to do case-sensitive. Default case-insensitive.
2152 * @param string $prefix the string to put before each search term found.
2153 * @param string $suffix the string to put after each search term found.
2154 * @return string The highlighted HTML.
2156 function highlight($needle, $haystack, $matchcase = false,
2157 $prefix = '<span class="highlight">', $suffix = '</span>') {
2159 // Quick bail-out in trivial cases.
2160 if (empty($needle) or empty($haystack)) {
2161 return $haystack;
2164 // Break up the search term into words, discard any -words and build a regexp.
2165 $words = preg_split('/ +/', trim($needle));
2166 foreach ($words as $index => $word) {
2167 if (strpos($word, '-') === 0) {
2168 unset($words[$index]);
2169 } else if (strpos($word, '+') === 0) {
2170 $words[$index] = '\b' . preg_quote(ltrim($word, '+'), '/') . '\b'; // Match only as a complete word.
2171 } else {
2172 $words[$index] = preg_quote($word, '/');
2175 $regexp = '/(' . implode('|', $words) . ')/u'; // Char u is to do UTF-8 matching.
2176 if (!$matchcase) {
2177 $regexp .= 'i';
2180 // Another chance to bail-out if $search was only -words.
2181 if (empty($words)) {
2182 return $haystack;
2185 // Split the string into HTML tags and real content.
2186 $chunks = preg_split('/((?:<[^>]*>)+)/', $haystack, -1, PREG_SPLIT_DELIM_CAPTURE);
2188 // We have an array of alternating blocks of text, then HTML tags, then text, ...
2189 // Loop through replacing search terms in the text, and leaving the HTML unchanged.
2190 $ishtmlchunk = false;
2191 $result = '';
2192 foreach ($chunks as $chunk) {
2193 if ($ishtmlchunk) {
2194 $result .= $chunk;
2195 } else {
2196 $result .= preg_replace($regexp, $prefix . '$1' . $suffix, $chunk);
2198 $ishtmlchunk = !$ishtmlchunk;
2201 return $result;
2205 * This function will highlight instances of $needle in $haystack
2207 * It's faster that the above function {@link highlight()} and doesn't care about
2208 * HTML or anything.
2210 * @param string $needle The string to search for
2211 * @param string $haystack The string to search for $needle in
2212 * @return string The highlighted HTML
2214 function highlightfast($needle, $haystack) {
2216 if (empty($needle) or empty($haystack)) {
2217 return $haystack;
2220 $parts = explode(core_text::strtolower($needle), core_text::strtolower($haystack));
2222 if (count($parts) === 1) {
2223 return $haystack;
2226 $pos = 0;
2228 foreach ($parts as $key => $part) {
2229 $parts[$key] = substr($haystack, $pos, strlen($part));
2230 $pos += strlen($part);
2232 $parts[$key] .= '<span class="highlight">'.substr($haystack, $pos, strlen($needle)).'</span>';
2233 $pos += strlen($needle);
2236 return str_replace('<span class="highlight"></span>', '', join('', $parts));
2240 * Converts a language code to hyphen-separated format in accordance to the
2241 * {@link https://datatracker.ietf.org/doc/html/rfc5646#section-2.1 BCP47 syntax}.
2243 * For additional information, check out
2244 * {@link https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/lang MDN web docs - lang}.
2246 * @param string $langcode The language code to convert.
2247 * @return string
2249 function get_html_lang_attribute_value(string $langcode): string {
2250 if (empty(trim($langcode))) {
2251 // If the language code passed is an empty string, return 'unknown'.
2252 return 'unknown';
2254 return str_replace('_', '-', $langcode);
2258 * Return a string containing 'lang', xml:lang and optionally 'dir' HTML attributes.
2260 * Internationalisation, for print_header and backup/restorelib.
2262 * @param bool $dir Default false
2263 * @return string Attributes
2265 function get_html_lang($dir = false) {
2266 global $CFG;
2268 $currentlang = current_language();
2269 if ($currentlang !== $CFG->lang && !get_string_manager()->translation_exists($currentlang)) {
2270 // Use the default site language when the current language is not available.
2271 $currentlang = $CFG->lang;
2272 // Fix the current language.
2273 fix_current_language($currentlang);
2276 $direction = '';
2277 if ($dir) {
2278 if (right_to_left()) {
2279 $direction = ' dir="rtl"';
2280 } else {
2281 $direction = ' dir="ltr"';
2285 // Accessibility: added the 'lang' attribute to $direction, used in theme <html> tag.
2286 $language = get_html_lang_attribute_value($currentlang);
2287 @header('Content-Language: '.$language);
2288 return ($direction.' lang="'.$language.'" xml:lang="'.$language.'"');
2292 // STANDARD WEB PAGE PARTS.
2295 * Send the HTTP headers that Moodle requires.
2297 * There is a backwards compatibility hack for legacy code
2298 * that needs to add custom IE compatibility directive.
2300 * Example:
2301 * <code>
2302 * if (!isset($CFG->additionalhtmlhead)) {
2303 * $CFG->additionalhtmlhead = '';
2305 * $CFG->additionalhtmlhead .= '<meta http-equiv="X-UA-Compatible" content="IE=8" />';
2306 * header('X-UA-Compatible: IE=8');
2307 * echo $OUTPUT->header();
2308 * </code>
2310 * Please note the $CFG->additionalhtmlhead alone might not work,
2311 * you should send the IE compatibility header() too.
2313 * @param string $contenttype
2314 * @param bool $cacheable Can this page be cached on back?
2315 * @return void, sends HTTP headers
2317 function send_headers($contenttype, $cacheable = true) {
2318 global $CFG;
2320 @header('Content-Type: ' . $contenttype);
2321 @header('Content-Script-Type: text/javascript');
2322 @header('Content-Style-Type: text/css');
2324 if (empty($CFG->additionalhtmlhead) or stripos($CFG->additionalhtmlhead, 'X-UA-Compatible') === false) {
2325 @header('X-UA-Compatible: IE=edge');
2328 if ($cacheable) {
2329 // Allow caching on "back" (but not on normal clicks).
2330 @header('Cache-Control: private, pre-check=0, post-check=0, max-age=0, no-transform');
2331 @header('Pragma: no-cache');
2332 @header('Expires: ');
2333 } else {
2334 // Do everything we can to always prevent clients and proxies caching.
2335 @header('Cache-Control: no-store, no-cache, must-revalidate');
2336 @header('Cache-Control: post-check=0, pre-check=0, no-transform', false);
2337 @header('Pragma: no-cache');
2338 @header('Expires: Mon, 20 Aug 1969 09:23:00 GMT');
2339 @header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
2341 @header('Accept-Ranges: none');
2343 // The Moodle app must be allowed to embed content always.
2344 if (empty($CFG->allowframembedding) && !core_useragent::is_moodle_app()) {
2345 @header('X-Frame-Options: sameorigin');
2348 // If referrer policy is set, add a referrer header.
2349 if (!empty($CFG->referrerpolicy) && ($CFG->referrerpolicy !== 'default')) {
2350 @header('Referrer-Policy: ' . $CFG->referrerpolicy);
2355 * Return the right arrow with text ('next'), and optionally embedded in a link.
2357 * @param string $text HTML/plain text label (set to blank only for breadcrumb separator cases).
2358 * @param string $url An optional link to use in a surrounding HTML anchor.
2359 * @param bool $accesshide True if text should be hidden (for screen readers only).
2360 * @param string $addclass Additional class names for the link, or the arrow character.
2361 * @return string HTML string.
2363 function link_arrow_right($text, $url='', $accesshide=false, $addclass='', $addparams = []) {
2364 global $OUTPUT; // TODO: move to output renderer.
2365 $arrowclass = 'arrow ';
2366 if (!$url) {
2367 $arrowclass .= $addclass;
2369 $arrow = '<span class="'.$arrowclass.'">'.$OUTPUT->rarrow().'</span>';
2370 $htmltext = '';
2371 if ($text) {
2372 $htmltext = '<span class="arrow_text">'.$text.'</span>&nbsp;';
2373 if ($accesshide) {
2374 $htmltext = get_accesshide($htmltext);
2377 if ($url) {
2378 $class = 'arrow_link';
2379 if ($addclass) {
2380 $class .= ' '.$addclass;
2383 $linkparams = [
2384 'class' => $class,
2385 'href' => $url,
2386 'title' => preg_replace('/<.*?>/', '', $text),
2389 $linkparams += $addparams;
2391 return html_writer::link($url, $htmltext . $arrow, $linkparams);
2393 return $htmltext.$arrow;
2397 * Return the left arrow with text ('previous'), and optionally embedded in a link.
2399 * @param string $text HTML/plain text label (set to blank only for breadcrumb separator cases).
2400 * @param string $url An optional link to use in a surrounding HTML anchor.
2401 * @param bool $accesshide True if text should be hidden (for screen readers only).
2402 * @param string $addclass Additional class names for the link, or the arrow character.
2403 * @return string HTML string.
2405 function link_arrow_left($text, $url='', $accesshide=false, $addclass='', $addparams = []) {
2406 global $OUTPUT; // TODO: move to utput renderer.
2407 $arrowclass = 'arrow ';
2408 if (! $url) {
2409 $arrowclass .= $addclass;
2411 $arrow = '<span class="'.$arrowclass.'">'.$OUTPUT->larrow().'</span>';
2412 $htmltext = '';
2413 if ($text) {
2414 $htmltext = '&nbsp;<span class="arrow_text">'.$text.'</span>';
2415 if ($accesshide) {
2416 $htmltext = get_accesshide($htmltext);
2419 if ($url) {
2420 $class = 'arrow_link';
2421 if ($addclass) {
2422 $class .= ' '.$addclass;
2425 $linkparams = [
2426 'class' => $class,
2427 'href' => $url,
2428 'title' => preg_replace('/<.*?>/', '', $text),
2431 $linkparams += $addparams;
2433 return html_writer::link($url, $arrow . $htmltext, $linkparams);
2435 return $arrow.$htmltext;
2439 * Return a HTML element with the class "accesshide", for accessibility.
2441 * Please use cautiously - where possible, text should be visible!
2443 * @param string $text Plain text.
2444 * @param string $elem Lowercase element name, default "span".
2445 * @param string $class Additional classes for the element.
2446 * @param string $attrs Additional attributes string in the form, "name='value' name2='value2'"
2447 * @return string HTML string.
2449 function get_accesshide($text, $elem='span', $class='', $attrs='') {
2450 return "<$elem class=\"accesshide $class\" $attrs>$text</$elem>";
2454 * Return the breadcrumb trail navigation separator.
2456 * @return string HTML string.
2458 function get_separator() {
2459 // Accessibility: the 'hidden' slash is preferred for screen readers.
2460 return ' '.link_arrow_right($text='/', $url='', $accesshide=true, 'sep').' ';
2464 * Print (or return) a collapsible region, that has a caption that can be clicked to expand or collapse the region.
2466 * If JavaScript is off, then the region will always be expanded.
2468 * @param string $contents the contents of the box.
2469 * @param string $classes class names added to the div that is output.
2470 * @param string $id id added to the div that is output. Must not be blank.
2471 * @param string $caption text displayed at the top. Clicking on this will cause the region to expand or contract.
2472 * @param string $userpref the name of the user preference that stores the user's preferred default state.
2473 * (May be blank if you do not wish the state to be persisted.
2474 * @param boolean $default Initial collapsed state to use if the user_preference it not set.
2475 * @param boolean $return if true, return the HTML as a string, rather than printing it.
2476 * @return string|void If $return is false, returns nothing, otherwise returns a string of HTML.
2478 function print_collapsible_region($contents, $classes, $id, $caption, $userpref = '', $default = false, $return = false) {
2479 $output = print_collapsible_region_start($classes, $id, $caption, $userpref, $default, true);
2480 $output .= $contents;
2481 $output .= print_collapsible_region_end(true);
2483 if ($return) {
2484 return $output;
2485 } else {
2486 echo $output;
2491 * Print (or return) the start of a collapsible region
2493 * The collapsibleregion has a caption that can be clicked to expand or collapse the region. If JavaScript is off, then the region
2494 * will always be expanded.
2496 * @param string $classes class names added to the div that is output.
2497 * @param string $id id added to the div that is output. Must not be blank.
2498 * @param string $caption text displayed at the top. Clicking on this will cause the region to expand or contract.
2499 * @param string $userpref the name of the user preference that stores the user's preferred default state.
2500 * (May be blank if you do not wish the state to be persisted.
2501 * @param boolean $default Initial collapsed state to use if the user_preference it not set.
2502 * @param boolean $return if true, return the HTML as a string, rather than printing it.
2503 * @param string $extracontent the extra content will show next to caption, eg.Help icon.
2504 * @return string|void if $return is false, returns nothing, otherwise returns a string of HTML.
2506 function print_collapsible_region_start($classes, $id, $caption, $userpref = '', $default = false, $return = false,
2507 $extracontent = null) {
2508 global $PAGE;
2510 // Work out the initial state.
2511 if (!empty($userpref) and is_string($userpref)) {
2512 user_preference_allow_ajax_update($userpref, PARAM_BOOL);
2513 $collapsed = get_user_preferences($userpref, $default);
2514 } else {
2515 $collapsed = $default;
2516 $userpref = false;
2519 if ($collapsed) {
2520 $classes .= ' collapsed';
2523 $output = '';
2524 $output .= '<div id="' . $id . '" class="collapsibleregion ' . $classes . '">';
2525 $output .= '<div id="' . $id . '_sizer">';
2526 $output .= '<div id="' . $id . '_caption" class="collapsibleregioncaption">';
2527 $output .= $caption . ' </div>';
2528 if ($extracontent) {
2529 $output .= html_writer::div($extracontent, 'collapsibleregionextracontent');
2531 $output .= '<div id="' . $id . '_inner" class="collapsibleregioninner">';
2532 $PAGE->requires->js_init_call('M.util.init_collapsible_region', array($id, $userpref, get_string('clicktohideshow')));
2534 if ($return) {
2535 return $output;
2536 } else {
2537 echo $output;
2542 * Close a region started with print_collapsible_region_start.
2544 * @param boolean $return if true, return the HTML as a string, rather than printing it.
2545 * @return string|void if $return is false, returns nothing, otherwise returns a string of HTML.
2547 function print_collapsible_region_end($return = false) {
2548 $output = '</div></div></div>';
2550 if ($return) {
2551 return $output;
2552 } else {
2553 echo $output;
2558 * Print a specified group's avatar.
2560 * @param array|stdClass $group A single {@link group} object OR array of groups.
2561 * @param int $courseid The course ID.
2562 * @param boolean $large Default small picture, or large.
2563 * @param boolean $return If false print picture, otherwise return the output as string
2564 * @param boolean $link Enclose image in a link to view specified course?
2565 * @param boolean $includetoken Whether to use a user token when displaying this group image.
2566 * True indicates to generate a token for current user, and integer value indicates to generate a token for the
2567 * user whose id is the value indicated.
2568 * If the group picture is included in an e-mail or some other location where the audience is a specific
2569 * user who will not be logged in when viewing, then we use a token to authenticate the user.
2570 * @return string|void Depending on the setting of $return
2572 function print_group_picture($group, $courseid, $large = false, $return = false, $link = true, $includetoken = false) {
2573 global $CFG;
2575 if (is_array($group)) {
2576 $output = '';
2577 foreach ($group as $g) {
2578 $output .= print_group_picture($g, $courseid, $large, true, $link, $includetoken);
2580 if ($return) {
2581 return $output;
2582 } else {
2583 echo $output;
2584 return;
2588 $pictureurl = get_group_picture_url($group, $courseid, $large, $includetoken);
2590 // If there is no picture, do nothing.
2591 if (!isset($pictureurl)) {
2592 return;
2595 $context = context_course::instance($courseid);
2597 $groupname = s($group->name);
2598 $pictureimage = html_writer::img($pictureurl, $groupname, ['title' => $groupname]);
2600 $output = '';
2601 if ($link or has_capability('moodle/site:accessallgroups', $context)) {
2602 $linkurl = new moodle_url('/user/index.php', ['id' => $courseid, 'group' => $group->id]);
2603 $output .= html_writer::link($linkurl, $pictureimage);
2604 } else {
2605 $output .= $pictureimage;
2608 if ($return) {
2609 return $output;
2610 } else {
2611 echo $output;
2616 * Return the url to the group picture.
2618 * @param stdClass $group A group object.
2619 * @param int $courseid The course ID for the group.
2620 * @param bool $large A large or small group picture? Default is small.
2621 * @param boolean $includetoken Whether to use a user token when displaying this group image.
2622 * True indicates to generate a token for current user, and integer value indicates to generate a token for the
2623 * user whose id is the value indicated.
2624 * If the group picture is included in an e-mail or some other location where the audience is a specific
2625 * user who will not be logged in when viewing, then we use a token to authenticate the user.
2626 * @return moodle_url Returns the url for the group picture.
2628 function get_group_picture_url($group, $courseid, $large = false, $includetoken = false) {
2629 global $CFG;
2631 $context = context_course::instance($courseid);
2633 // If there is no picture, do nothing.
2634 if (!$group->picture) {
2635 return;
2638 if ($large) {
2639 $file = 'f1';
2640 } else {
2641 $file = 'f2';
2644 $grouppictureurl = moodle_url::make_pluginfile_url(
2645 $context->id, 'group', 'icon', $group->id, '/', $file, false, $includetoken);
2646 $grouppictureurl->param('rev', $group->picture);
2647 return $grouppictureurl;
2652 * Display a recent activity note
2654 * @staticvar string $strftimerecent
2655 * @param int $time A timestamp int.
2656 * @param stdClass $user A user object from the database.
2657 * @param string $text Text for display for the note
2658 * @param string $link The link to wrap around the text
2659 * @param bool $return If set to true the HTML is returned rather than echo'd
2660 * @param string $viewfullnames
2661 * @return string If $retrun was true returns HTML for a recent activity notice.
2663 function print_recent_activity_note($time, $user, $text, $link, $return=false, $viewfullnames=null) {
2664 static $strftimerecent = null;
2665 $output = '';
2667 if (is_null($viewfullnames)) {
2668 $context = context_system::instance();
2669 $viewfullnames = has_capability('moodle/site:viewfullnames', $context);
2672 if (is_null($strftimerecent)) {
2673 $strftimerecent = get_string('strftimerecent');
2676 $output .= '<div class="head">';
2677 $output .= '<div class="date">'.userdate($time, $strftimerecent).'</div>';
2678 $output .= '<div class="name">'.fullname($user, $viewfullnames).'</div>';
2679 $output .= '</div>';
2680 $output .= '<div class="info"><a href="'.$link.'">'.format_string($text, true).'</a></div>';
2682 if ($return) {
2683 return $output;
2684 } else {
2685 echo $output;
2690 * Returns a popup menu with course activity modules
2692 * Given a course this function returns a small popup menu with all the course activity modules in it, as a navigation menu
2693 * outputs a simple list structure in XHTML.
2694 * The data is taken from the serialised array stored in the course record.
2696 * @param course $course A {@link $COURSE} object.
2697 * @param array $sections
2698 * @param course_modinfo $modinfo
2699 * @param string $strsection
2700 * @param string $strjumpto
2701 * @param int $width
2702 * @param string $cmid
2703 * @return string The HTML block
2705 function navmenulist($course, $sections, $modinfo, $strsection, $strjumpto, $width=50, $cmid=0) {
2707 global $CFG, $OUTPUT;
2709 $section = -1;
2710 $menu = array();
2711 $doneheading = false;
2713 $courseformatoptions = course_get_format($course)->get_format_options();
2714 $coursecontext = context_course::instance($course->id);
2716 $menu[] = '<ul class="navmenulist"><li class="jumpto section"><span>'.$strjumpto.'</span><ul>';
2717 foreach ($modinfo->cms as $mod) {
2718 if (!$mod->has_view()) {
2719 // Don't show modules which you can't link to!
2720 continue;
2723 // For course formats using 'numsections' do not show extra sections.
2724 if (isset($courseformatoptions['numsections']) && $mod->sectionnum > $courseformatoptions['numsections']) {
2725 break;
2728 if (!$mod->uservisible) { // Do not icnlude empty sections at all.
2729 continue;
2732 if ($mod->sectionnum >= 0 and $section != $mod->sectionnum) {
2733 $thissection = $sections[$mod->sectionnum];
2735 if ($thissection->visible or
2736 (isset($courseformatoptions['hiddensections']) and !$courseformatoptions['hiddensections']) or
2737 has_capability('moodle/course:viewhiddensections', $coursecontext)) {
2738 $thissection->summary = strip_tags(format_string($thissection->summary, true));
2739 if (!$doneheading) {
2740 $menu[] = '</ul></li>';
2742 if ($course->format == 'weeks' or empty($thissection->summary)) {
2743 $item = $strsection ." ". $mod->sectionnum;
2744 } else {
2745 if (core_text::strlen($thissection->summary) < ($width-3)) {
2746 $item = $thissection->summary;
2747 } else {
2748 $item = core_text::substr($thissection->summary, 0, $width).'...';
2751 $menu[] = '<li class="section"><span>'.$item.'</span>';
2752 $menu[] = '<ul>';
2753 $doneheading = true;
2755 $section = $mod->sectionnum;
2756 } else {
2757 // No activities from this hidden section shown.
2758 continue;
2762 $url = $mod->modname .'/view.php?id='. $mod->id;
2763 $mod->name = strip_tags(format_string($mod->name ,true));
2764 if (core_text::strlen($mod->name) > ($width+5)) {
2765 $mod->name = core_text::substr($mod->name, 0, $width).'...';
2767 if (!$mod->visible) {
2768 $mod->name = '('.$mod->name.')';
2770 $class = 'activity '.$mod->modname;
2771 $class .= ($cmid == $mod->id) ? ' selected' : '';
2772 $menu[] = '<li class="'.$class.'">'.
2773 $OUTPUT->image_icon('monologo', '', $mod->modname).
2774 '<a href="'.$CFG->wwwroot.'/mod/'.$url.'">'.$mod->name.'</a></li>';
2777 if ($doneheading) {
2778 $menu[] = '</ul></li>';
2780 $menu[] = '</ul></li></ul>';
2782 return implode("\n", $menu);
2786 * Prints a grade menu (as part of an existing form) with help showing all possible numerical grades and scales.
2788 * @todo Finish documenting this function
2789 * @todo Deprecate: this is only used in a few contrib modules
2791 * @param int $courseid The course ID
2792 * @param string $name
2793 * @param string $current
2794 * @param boolean $includenograde Include those with no grades
2795 * @param boolean $return If set to true returns rather than echo's
2796 * @return string|bool Depending on value of $return
2798 function print_grade_menu($courseid, $name, $current, $includenograde=true, $return=false) {
2799 global $OUTPUT;
2801 $output = '';
2802 $strscale = get_string('scale');
2803 $strscales = get_string('scales');
2805 $scales = get_scales_menu($courseid);
2806 foreach ($scales as $i => $scalename) {
2807 $grades[-$i] = $strscale .': '. $scalename;
2809 if ($includenograde) {
2810 $grades[0] = get_string('nograde');
2812 for ($i=100; $i>=1; $i--) {
2813 $grades[$i] = $i;
2815 $output .= html_writer::select($grades, $name, $current, false);
2817 $linkobject = '<span class="helplink">' . $OUTPUT->pix_icon('help', $strscales) . '</span>';
2818 $link = new moodle_url('/course/scales.php', array('id' => $courseid, 'list' => 1));
2819 $action = new popup_action('click', $link, 'ratingscales', array('height' => 400, 'width' => 500));
2820 $output .= $OUTPUT->action_link($link, $linkobject, $action, array('title' => $strscales));
2822 if ($return) {
2823 return $output;
2824 } else {
2825 echo $output;
2830 * Print an error to STDOUT and exit with a non-zero code. For commandline scripts.
2832 * Default errorcode is 1.
2834 * Very useful for perl-like error-handling:
2835 * do_somethting() or mdie("Something went wrong");
2837 * @param string $msg Error message
2838 * @param integer $errorcode Error code to emit
2840 function mdie($msg='', $errorcode=1) {
2841 trigger_error($msg);
2842 exit($errorcode);
2846 * Print a message and exit.
2848 * @param string $message The message to print in the notice
2849 * @param moodle_url|string $link The link to use for the continue button
2850 * @param object $course A course object. Unused.
2851 * @return void This function simply exits
2853 function notice ($message, $link='', $course=null) {
2854 global $PAGE, $OUTPUT;
2856 $message = clean_text($message); // In case nasties are in here.
2858 if (CLI_SCRIPT) {
2859 echo("!!$message!!\n");
2860 exit(1); // No success.
2863 if (!$PAGE->headerprinted) {
2864 // Header not yet printed.
2865 $PAGE->set_title(get_string('notice'));
2866 echo $OUTPUT->header();
2867 } else {
2868 echo $OUTPUT->container_end_all(false);
2871 echo $OUTPUT->box($message, 'generalbox', 'notice');
2872 echo $OUTPUT->continue_button($link);
2874 echo $OUTPUT->footer();
2875 exit(1); // General error code.
2879 * Redirects the user to another page, after printing a notice.
2881 * This function calls the OUTPUT redirect method, echo's the output and then dies to ensure nothing else happens.
2883 * <strong>Good practice:</strong> You should call this method before starting page
2884 * output by using any of the OUTPUT methods.
2886 * @param moodle_url|string $url A moodle_url to redirect to. Strings are not to be trusted!
2887 * @param string $message The message to display to the user
2888 * @param int $delay The delay before redirecting
2889 * @param string $messagetype The type of notification to show the message in. See constants on \core\output\notification.
2890 * @throws moodle_exception
2892 function redirect($url, $message='', $delay=null, $messagetype = \core\output\notification::NOTIFY_INFO) {
2893 global $OUTPUT, $PAGE, $CFG;
2895 if (CLI_SCRIPT or AJAX_SCRIPT) {
2896 // This is wrong - developers should not use redirect in these scripts but it should not be very likely.
2897 throw new moodle_exception('redirecterrordetected', 'error');
2900 if ($delay === null) {
2901 $delay = -1;
2904 // Prevent debug errors - make sure context is properly initialised.
2905 if ($PAGE) {
2906 $PAGE->set_context(null);
2907 $PAGE->set_pagelayout('redirect'); // No header and footer needed.
2908 $PAGE->set_title(get_string('pageshouldredirect', 'moodle'));
2911 if ($url instanceof moodle_url) {
2912 $url = $url->out(false);
2915 $debugdisableredirect = false;
2916 do {
2917 if (defined('DEBUGGING_PRINTED')) {
2918 // Some debugging already printed, no need to look more.
2919 $debugdisableredirect = true;
2920 break;
2923 if (core_useragent::is_msword()) {
2924 // Clicking a URL from MS Word sends a request to the server without cookies. If that
2925 // causes a redirect Word will open a browser pointing the new URL. If not, the URL that
2926 // was clicked is opened. Because the request from Word is without cookies, it almost
2927 // always results in a redirect to the login page, even if the user is logged in in their
2928 // browser. This is not what we want, so prevent the redirect for requests from Word.
2929 $debugdisableredirect = true;
2930 break;
2933 if (empty($CFG->debugdisplay) or empty($CFG->debug)) {
2934 // No errors should be displayed.
2935 break;
2938 if (!function_exists('error_get_last') or !$lasterror = error_get_last()) {
2939 break;
2942 if (!($lasterror['type'] & $CFG->debug)) {
2943 // Last error not interesting.
2944 break;
2947 // Watch out here, @hidden() errors are returned from error_get_last() too.
2948 if (headers_sent()) {
2949 // We already started printing something - that means errors likely printed.
2950 $debugdisableredirect = true;
2951 break;
2954 if (ob_get_level() and ob_get_contents()) {
2955 // There is something waiting to be printed, hopefully it is the errors,
2956 // but it might be some error hidden by @ too - such as the timezone mess from setup.php.
2957 $debugdisableredirect = true;
2958 break;
2960 } while (false);
2962 // Technically, HTTP/1.1 requires Location: header to contain the absolute path.
2963 // (In practice browsers accept relative paths - but still, might as well do it properly.)
2964 // This code turns relative into absolute.
2965 if (!preg_match('|^[a-z]+:|i', $url)) {
2966 // Get host name http://www.wherever.com.
2967 $hostpart = preg_replace('|^(.*?[^:/])/.*$|', '$1', $CFG->wwwroot);
2968 if (preg_match('|^/|', $url)) {
2969 // URLs beginning with / are relative to web server root so we just add them in.
2970 $url = $hostpart.$url;
2971 } else {
2972 // URLs not beginning with / are relative to path of current script, so add that on.
2973 $url = $hostpart.preg_replace('|\?.*$|', '', me()).'/../'.$url;
2975 // Replace all ..s.
2976 while (true) {
2977 $newurl = preg_replace('|/(?!\.\.)[^/]*/\.\./|', '/', $url);
2978 if ($newurl == $url) {
2979 break;
2981 $url = $newurl;
2985 // Sanitise url - we can not rely on moodle_url or our URL cleaning
2986 // because they do not support all valid external URLs.
2987 $url = preg_replace('/[\x00-\x1F\x7F]/', '', $url);
2988 $url = str_replace('"', '%22', $url);
2989 $encodedurl = preg_replace("/\&(?![a-zA-Z0-9#]{1,8};)/", "&amp;", $url);
2990 $encodedurl = preg_replace('/^.*href="([^"]*)".*$/', "\\1", clean_text('<a href="'.$encodedurl.'" />', FORMAT_HTML));
2991 $url = str_replace('&amp;', '&', $encodedurl);
2993 if (!empty($message)) {
2994 if (!$debugdisableredirect && !headers_sent()) {
2995 // A message has been provided, and the headers have not yet been sent.
2996 // Display the message as a notification on the subsequent page.
2997 \core\notification::add($message, $messagetype);
2998 $message = null;
2999 $delay = 0;
3000 } else {
3001 if ($delay === -1 || !is_numeric($delay)) {
3002 $delay = 3;
3004 $message = clean_text($message);
3006 } else {
3007 $message = get_string('pageshouldredirect');
3008 $delay = 0;
3011 // Make sure the session is closed properly, this prevents problems in IIS
3012 // and also some potential PHP shutdown issues.
3013 \core\session\manager::write_close();
3015 if ($delay == 0 && !$debugdisableredirect && !headers_sent()) {
3017 // This helps when debugging redirect issues like loops and it is not clear
3018 // which layer in the stack sent the redirect header. If debugging is on
3019 // then the file and line is also shown.
3020 $redirectby = 'Moodle';
3021 if (debugging('', DEBUG_DEVELOPER)) {
3022 $origin = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 1)[0];
3023 $redirectby .= ' /' . str_replace($CFG->dirroot . '/', '', $origin['file']) . ':' . $origin['line'];
3025 @header("X-Redirect-By: $redirectby");
3027 // 302 might not work for POST requests, 303 is ignored by obsolete clients.
3028 @header($_SERVER['SERVER_PROTOCOL'] . ' 303 See Other');
3029 @header('Location: '.$url);
3030 echo bootstrap_renderer::plain_redirect_message($encodedurl);
3031 exit;
3034 // Include a redirect message, even with a HTTP redirect, because that is recommended practice.
3035 if ($PAGE) {
3036 $CFG->docroot = false; // To prevent the link to moodle docs from being displayed on redirect page.
3037 echo $OUTPUT->redirect_message($encodedurl, $message, $delay, $debugdisableredirect, $messagetype);
3038 exit;
3039 } else {
3040 echo bootstrap_renderer::early_redirect_message($encodedurl, $message, $delay);
3041 exit;
3046 * Given an email address, this function will return an obfuscated version of it.
3048 * @param string $email The email address to obfuscate
3049 * @return string The obfuscated email address
3051 function obfuscate_email($email) {
3052 $i = 0;
3053 $length = strlen($email);
3054 $obfuscated = '';
3055 while ($i < $length) {
3056 if (rand(0, 2) && $email[$i]!='@') { // MDL-20619 some browsers have problems unobfuscating @.
3057 $obfuscated.='%'.dechex(ord($email[$i]));
3058 } else {
3059 $obfuscated.=$email[$i];
3061 $i++;
3063 return $obfuscated;
3067 * This function takes some text and replaces about half of the characters
3068 * with HTML entity equivalents. Return string is obviously longer.
3070 * @param string $plaintext The text to be obfuscated
3071 * @return string The obfuscated text
3073 function obfuscate_text($plaintext) {
3074 $i=0;
3075 $length = core_text::strlen($plaintext);
3076 $obfuscated='';
3077 $prevobfuscated = false;
3078 while ($i < $length) {
3079 $char = core_text::substr($plaintext, $i, 1);
3080 $ord = core_text::utf8ord($char);
3081 $numerical = ($ord >= ord('0')) && ($ord <= ord('9'));
3082 if ($prevobfuscated and $numerical ) {
3083 $obfuscated.='&#'.$ord.';';
3084 } else if (rand(0, 2)) {
3085 $obfuscated.='&#'.$ord.';';
3086 $prevobfuscated = true;
3087 } else {
3088 $obfuscated.=$char;
3089 $prevobfuscated = false;
3091 $i++;
3093 return $obfuscated;
3097 * This function uses the {@link obfuscate_email()} and {@link obfuscate_text()}
3098 * to generate a fully obfuscated email link, ready to use.
3100 * @param string $email The email address to display
3101 * @param string $label The text to displayed as hyperlink to $email
3102 * @param boolean $dimmed If true then use css class 'dimmed' for hyperlink
3103 * @param string $subject The subject of the email in the mailto link
3104 * @param string $body The content of the email in the mailto link
3105 * @return string The obfuscated mailto link
3107 function obfuscate_mailto($email, $label='', $dimmed=false, $subject = '', $body = '') {
3109 if (empty($label)) {
3110 $label = $email;
3113 $label = obfuscate_text($label);
3114 $email = obfuscate_email($email);
3115 $mailto = obfuscate_text('mailto');
3116 $url = new moodle_url("mailto:$email");
3117 $attrs = array();
3119 if (!empty($subject)) {
3120 $url->param('subject', format_string($subject));
3122 if (!empty($body)) {
3123 $url->param('body', format_string($body));
3126 // Use the obfuscated mailto.
3127 $url = preg_replace('/^mailto/', $mailto, $url->out());
3129 if ($dimmed) {
3130 $attrs['title'] = get_string('emaildisable');
3131 $attrs['class'] = 'dimmed';
3134 return html_writer::link($url, $label, $attrs);
3138 * This function is used to rebuild the <nolink> tag because some formats (PLAIN and WIKI)
3139 * will transform it to html entities
3141 * @param string $text Text to search for nolink tag in
3142 * @return string
3144 function rebuildnolinktag($text) {
3146 $text = preg_replace('/&lt;(\/*nolink)&gt;/i', '<$1>', $text);
3148 return $text;
3152 * Prints a maintenance message from $CFG->maintenance_message or default if empty.
3154 function print_maintenance_message() {
3155 global $CFG, $SITE, $PAGE, $OUTPUT;
3157 header($_SERVER['SERVER_PROTOCOL'] . ' 503 Moodle under maintenance');
3158 header('Status: 503 Moodle under maintenance');
3159 header('Retry-After: 300');
3161 $PAGE->set_pagetype('maintenance-message');
3162 $PAGE->set_pagelayout('maintenance');
3163 $PAGE->set_title(strip_tags($SITE->fullname));
3164 $PAGE->set_heading($SITE->fullname);
3165 echo $OUTPUT->header();
3166 echo $OUTPUT->heading(get_string('sitemaintenance', 'admin'));
3167 if (isset($CFG->maintenance_message) and !html_is_blank($CFG->maintenance_message)) {
3168 echo $OUTPUT->box_start('maintenance_message generalbox boxwidthwide boxaligncenter');
3169 echo $CFG->maintenance_message;
3170 echo $OUTPUT->box_end();
3172 echo $OUTPUT->footer();
3173 die;
3177 * Returns a string containing a nested list, suitable for formatting into tabs with CSS.
3179 * It is not recommended to use this function in Moodle 2.5 but it is left for backward
3180 * compartibility.
3182 * Example how to print a single line tabs:
3183 * $rows = array(
3184 * new tabobject(...),
3185 * new tabobject(...)
3186 * );
3187 * echo $OUTPUT->tabtree($rows, $selectedid);
3189 * Multiple row tabs may not look good on some devices but if you want to use them
3190 * you can specify ->subtree for the active tabobject.
3192 * @param array $tabrows An array of rows where each row is an array of tab objects
3193 * @param string $selected The id of the selected tab (whatever row it's on)
3194 * @param array $inactive An array of ids of inactive tabs that are not selectable.
3195 * @param array $activated An array of ids of other tabs that are currently activated
3196 * @param bool $return If true output is returned rather then echo'd
3197 * @return string HTML output if $return was set to true.
3199 function print_tabs($tabrows, $selected = null, $inactive = null, $activated = null, $return = false) {
3200 global $OUTPUT;
3202 $tabrows = array_reverse($tabrows);
3203 $subtree = array();
3204 foreach ($tabrows as $row) {
3205 $tree = array();
3207 foreach ($row as $tab) {
3208 $tab->inactive = is_array($inactive) && in_array((string)$tab->id, $inactive);
3209 $tab->activated = is_array($activated) && in_array((string)$tab->id, $activated);
3210 $tab->selected = (string)$tab->id == $selected;
3212 if ($tab->activated || $tab->selected) {
3213 $tab->subtree = $subtree;
3215 $tree[] = $tab;
3217 $subtree = $tree;
3219 $output = $OUTPUT->tabtree($subtree);
3220 if ($return) {
3221 return $output;
3222 } else {
3223 print $output;
3224 return !empty($output);
3229 * Alter debugging level for the current request,
3230 * the change is not saved in database.
3232 * @param int $level one of the DEBUG_* constants
3233 * @param bool $debugdisplay
3235 function set_debugging($level, $debugdisplay = null) {
3236 global $CFG;
3238 $CFG->debug = (int)$level;
3239 $CFG->debugdeveloper = (($CFG->debug & DEBUG_DEVELOPER) === DEBUG_DEVELOPER);
3241 if ($debugdisplay !== null) {
3242 $CFG->debugdisplay = (bool)$debugdisplay;
3247 * Standard Debugging Function
3249 * Returns true if the current site debugging settings are equal or above specified level.
3250 * If passed a parameter it will emit a debugging notice similar to trigger_error(). The
3251 * routing of notices is controlled by $CFG->debugdisplay
3252 * eg use like this:
3254 * 1) debugging('a normal debug notice');
3255 * 2) debugging('something really picky', DEBUG_ALL);
3256 * 3) debugging('annoying debug message only for developers', DEBUG_DEVELOPER);
3257 * 4) if (debugging()) { perform extra debugging operations (do not use print or echo) }
3259 * In code blocks controlled by debugging() (such as example 4)
3260 * any output should be routed via debugging() itself, or the lower-level
3261 * trigger_error() or error_log(). Using echo or print will break XHTML
3262 * JS and HTTP headers.
3264 * It is also possible to define NO_DEBUG_DISPLAY which redirects the message to error_log.
3266 * @param string $message a message to print
3267 * @param int $level the level at which this debugging statement should show
3268 * @param array $backtrace use different backtrace
3269 * @return bool
3271 function debugging($message = '', $level = DEBUG_NORMAL, $backtrace = null) {
3272 global $CFG, $USER;
3274 $forcedebug = false;
3275 if (!empty($CFG->debugusers) && $USER) {
3276 $debugusers = explode(',', $CFG->debugusers);
3277 $forcedebug = in_array($USER->id, $debugusers);
3280 if (!$forcedebug and (empty($CFG->debug) || ($CFG->debug != -1 and $CFG->debug < $level))) {
3281 return false;
3284 if (!isset($CFG->debugdisplay)) {
3285 $CFG->debugdisplay = ini_get_bool('display_errors');
3288 if ($message) {
3289 if (!$backtrace) {
3290 $backtrace = debug_backtrace();
3292 $from = format_backtrace($backtrace, CLI_SCRIPT || NO_DEBUG_DISPLAY);
3293 if (PHPUNIT_TEST) {
3294 if (phpunit_util::debugging_triggered($message, $level, $from)) {
3295 // We are inside test, the debug message was logged.
3296 return true;
3300 if (NO_DEBUG_DISPLAY) {
3301 // Script does not want any errors or debugging in output,
3302 // we send the info to error log instead.
3303 error_log('Debugging: ' . $message . ' in '. PHP_EOL . $from);
3305 } else if ($forcedebug or $CFG->debugdisplay) {
3306 if (!defined('DEBUGGING_PRINTED')) {
3307 define('DEBUGGING_PRINTED', 1); // Indicates we have printed something.
3309 if (CLI_SCRIPT) {
3310 echo "++ $message ++\n$from";
3311 } else {
3312 echo '<div class="notifytiny debuggingmessage" data-rel="debugging">' , $message , $from , '</div>';
3315 } else {
3316 trigger_error($message . $from, E_USER_NOTICE);
3319 return true;
3323 * Outputs a HTML comment to the browser.
3325 * This is used for those hard-to-debug pages that use bits from many different files in very confusing ways (e.g. blocks).
3327 * <code>print_location_comment(__FILE__, __LINE__);</code>
3329 * @param string $file
3330 * @param integer $line
3331 * @param boolean $return Whether to return or print the comment
3332 * @return string|void Void unless true given as third parameter
3334 function print_location_comment($file, $line, $return = false) {
3335 if ($return) {
3336 return "<!-- $file at line $line -->\n";
3337 } else {
3338 echo "<!-- $file at line $line -->\n";
3344 * Returns true if the user is using a right-to-left language.
3346 * @return boolean true if the current language is right-to-left (Hebrew, Arabic etc)
3348 function right_to_left() {
3349 return (get_string('thisdirection', 'langconfig') === 'rtl');
3354 * Returns swapped left<=> right if in RTL environment.
3356 * Part of RTL Moodles support.
3358 * @param string $align align to check
3359 * @return string
3361 function fix_align_rtl($align) {
3362 if (!right_to_left()) {
3363 return $align;
3365 if ($align == 'left') {
3366 return 'right';
3368 if ($align == 'right') {
3369 return 'left';
3371 return $align;
3376 * Returns true if the page is displayed in a popup window.
3378 * Gets the information from the URL parameter inpopup.
3380 * @todo Use a central function to create the popup calls all over Moodle and
3381 * In the moment only works with resources and probably questions.
3383 * @return boolean
3385 function is_in_popup() {
3386 $inpopup = optional_param('inpopup', '', PARAM_BOOL);
3388 return ($inpopup);
3392 * Progress trace class.
3394 * Use this class from long operations where you want to output occasional information about
3395 * what is going on, but don't know if, or in what format, the output should be.
3397 * @copyright 2009 Tim Hunt
3398 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3399 * @package core
3401 abstract class progress_trace {
3403 * Output an progress message in whatever format.
3405 * @param string $message the message to output.
3406 * @param integer $depth indent depth for this message.
3408 abstract public function output($message, $depth = 0);
3411 * Called when the processing is finished.
3413 public function finished() {
3418 * This subclass of progress_trace does not ouput anything.
3420 * @copyright 2009 Tim Hunt
3421 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3422 * @package core
3424 class null_progress_trace extends progress_trace {
3426 * Does Nothing
3428 * @param string $message
3429 * @param int $depth
3430 * @return void Does Nothing
3432 public function output($message, $depth = 0) {
3437 * This subclass of progress_trace outputs to plain text.
3439 * @copyright 2009 Tim Hunt
3440 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3441 * @package core
3443 class text_progress_trace extends progress_trace {
3445 * Output the trace message.
3447 * @param string $message
3448 * @param int $depth
3449 * @return void Output is echo'd
3451 public function output($message, $depth = 0) {
3452 mtrace(str_repeat(' ', $depth) . $message);
3457 * This subclass of progress_trace outputs as HTML.
3459 * @copyright 2009 Tim Hunt
3460 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3461 * @package core
3463 class html_progress_trace extends progress_trace {
3465 * Output the trace message.
3467 * @param string $message
3468 * @param int $depth
3469 * @return void Output is echo'd
3471 public function output($message, $depth = 0) {
3472 echo '<p>', str_repeat('&#160;&#160;', $depth), htmlspecialchars($message, ENT_COMPAT), "</p>\n";
3473 flush();
3478 * HTML List Progress Tree
3480 * @copyright 2009 Tim Hunt
3481 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3482 * @package core
3484 class html_list_progress_trace extends progress_trace {
3485 /** @var int */
3486 protected $currentdepth = -1;
3489 * Echo out the list
3491 * @param string $message The message to display
3492 * @param int $depth
3493 * @return void Output is echoed
3495 public function output($message, $depth = 0) {
3496 $samedepth = true;
3497 while ($this->currentdepth > $depth) {
3498 echo "</li>\n</ul>\n";
3499 $this->currentdepth -= 1;
3500 if ($this->currentdepth == $depth) {
3501 echo '<li>';
3503 $samedepth = false;
3505 while ($this->currentdepth < $depth) {
3506 echo "<ul>\n<li>";
3507 $this->currentdepth += 1;
3508 $samedepth = false;
3510 if ($samedepth) {
3511 echo "</li>\n<li>";
3513 echo htmlspecialchars($message, ENT_COMPAT);
3514 flush();
3518 * Called when the processing is finished.
3520 public function finished() {
3521 while ($this->currentdepth >= 0) {
3522 echo "</li>\n</ul>\n";
3523 $this->currentdepth -= 1;
3529 * This subclass of progress_trace outputs to error log.
3531 * @copyright Petr Skoda {@link http://skodak.org}
3532 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3533 * @package core
3535 class error_log_progress_trace extends progress_trace {
3536 /** @var string log prefix */
3537 protected $prefix;
3540 * Constructor.
3541 * @param string $prefix optional log prefix
3543 public function __construct($prefix = '') {
3544 $this->prefix = $prefix;
3548 * Output the trace message.
3550 * @param string $message
3551 * @param int $depth
3552 * @return void Output is sent to error log.
3554 public function output($message, $depth = 0) {
3555 error_log($this->prefix . str_repeat(' ', $depth) . $message);
3560 * Special type of trace that can be used for catching of output of other traces.
3562 * @copyright Petr Skoda {@link http://skodak.org}
3563 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3564 * @package core
3566 class progress_trace_buffer extends progress_trace {
3567 /** @var progres_trace */
3568 protected $trace;
3569 /** @var bool do we pass output out */
3570 protected $passthrough;
3571 /** @var string output buffer */
3572 protected $buffer;
3575 * Constructor.
3577 * @param progress_trace $trace
3578 * @param bool $passthrough true means output and buffer, false means just buffer and no output
3580 public function __construct(progress_trace $trace, $passthrough = true) {
3581 $this->trace = $trace;
3582 $this->passthrough = $passthrough;
3583 $this->buffer = '';
3587 * Output the trace message.
3589 * @param string $message the message to output.
3590 * @param int $depth indent depth for this message.
3591 * @return void output stored in buffer
3593 public function output($message, $depth = 0) {
3594 ob_start();
3595 $this->trace->output($message, $depth);
3596 $this->buffer .= ob_get_contents();
3597 if ($this->passthrough) {
3598 ob_end_flush();
3599 } else {
3600 ob_end_clean();
3605 * Called when the processing is finished.
3607 public function finished() {
3608 ob_start();
3609 $this->trace->finished();
3610 $this->buffer .= ob_get_contents();
3611 if ($this->passthrough) {
3612 ob_end_flush();
3613 } else {
3614 ob_end_clean();
3619 * Reset internal text buffer.
3621 public function reset_buffer() {
3622 $this->buffer = '';
3626 * Return internal text buffer.
3627 * @return string buffered plain text
3629 public function get_buffer() {
3630 return $this->buffer;
3635 * Special type of trace that can be used for redirecting to multiple other traces.
3637 * @copyright Petr Skoda {@link http://skodak.org}
3638 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3639 * @package core
3641 class combined_progress_trace extends progress_trace {
3644 * An array of traces.
3645 * @var array
3647 protected $traces;
3650 * Constructs a new instance.
3652 * @param array $traces multiple traces
3654 public function __construct(array $traces) {
3655 $this->traces = $traces;
3659 * Output an progress message in whatever format.
3661 * @param string $message the message to output.
3662 * @param integer $depth indent depth for this message.
3664 public function output($message, $depth = 0) {
3665 foreach ($this->traces as $trace) {
3666 $trace->output($message, $depth);
3671 * Called when the processing is finished.
3673 public function finished() {
3674 foreach ($this->traces as $trace) {
3675 $trace->finished();
3681 * Returns a localized sentence in the current language summarizing the current password policy
3683 * @todo this should be handled by a function/method in the language pack library once we have a support for it
3684 * @uses $CFG
3685 * @return string
3687 function print_password_policy() {
3688 global $CFG;
3690 $message = '';
3691 if (!empty($CFG->passwordpolicy)) {
3692 $messages = array();
3693 if (!empty($CFG->minpasswordlength)) {
3694 $messages[] = get_string('informminpasswordlength', 'auth', $CFG->minpasswordlength);
3696 if (!empty($CFG->minpassworddigits)) {
3697 $messages[] = get_string('informminpassworddigits', 'auth', $CFG->minpassworddigits);
3699 if (!empty($CFG->minpasswordlower)) {
3700 $messages[] = get_string('informminpasswordlower', 'auth', $CFG->minpasswordlower);
3702 if (!empty($CFG->minpasswordupper)) {
3703 $messages[] = get_string('informminpasswordupper', 'auth', $CFG->minpasswordupper);
3705 if (!empty($CFG->minpasswordnonalphanum)) {
3706 $messages[] = get_string('informminpasswordnonalphanum', 'auth', $CFG->minpasswordnonalphanum);
3709 // Fire any additional password policy functions from plugins.
3710 // Callbacks must return an array of message strings.
3711 $pluginsfunction = get_plugins_with_function('print_password_policy');
3712 foreach ($pluginsfunction as $plugintype => $plugins) {
3713 foreach ($plugins as $pluginfunction) {
3714 $messages = array_merge($messages, $pluginfunction());
3718 $messages = join(', ', $messages); // This is ugly but we do not have anything better yet...
3719 // Check if messages is empty before outputting any text.
3720 if ($messages != '') {
3721 $message = get_string('informpasswordpolicy', 'auth', $messages);
3724 return $message;
3728 * Get the value of a help string fully prepared for display in the current language.
3730 * @param string $identifier The identifier of the string to search for.
3731 * @param string $component The module the string is associated with.
3732 * @param boolean $ajax Whether this help is called from an AJAX script.
3733 * This is used to influence text formatting and determines
3734 * which format to output the doclink in.
3735 * @param string|object|array $a An object, string or number that can be used
3736 * within translation strings
3737 * @return Object An object containing:
3738 * - heading: Any heading that there may be for this help string.
3739 * - text: The wiki-formatted help string.
3740 * - doclink: An object containing a link, the linktext, and any additional
3741 * CSS classes to apply to that link. Only present if $ajax = false.
3742 * - completedoclink: A text representation of the doclink. Only present if $ajax = true.
3744 function get_formatted_help_string($identifier, $component, $ajax = false, $a = null) {
3745 global $CFG, $OUTPUT;
3746 $sm = get_string_manager();
3748 // Do not rebuild caches here!
3749 // Devs need to learn to purge all caches after any change or disable $CFG->langstringcache.
3751 $data = new stdClass();
3753 if ($sm->string_exists($identifier, $component)) {
3754 $data->heading = format_string(get_string($identifier, $component));
3755 } else {
3756 // Gracefully fall back to an empty string.
3757 $data->heading = '';
3760 if ($sm->string_exists($identifier . '_help', $component)) {
3761 $options = new stdClass();
3762 $options->trusted = false;
3763 $options->noclean = false;
3764 $options->smiley = false;
3765 $options->filter = false;
3766 $options->para = true;
3767 $options->newlines = false;
3768 $options->overflowdiv = !$ajax;
3770 // Should be simple wiki only MDL-21695.
3771 $data->text = format_text(get_string($identifier.'_help', $component, $a), FORMAT_MARKDOWN, $options);
3773 $helplink = $identifier . '_link';
3774 if ($sm->string_exists($helplink, $component)) { // Link to further info in Moodle docs.
3775 $link = get_string($helplink, $component);
3776 $linktext = get_string('morehelp');
3778 $data->doclink = new stdClass();
3779 $url = new moodle_url(get_docs_url($link));
3780 if ($ajax) {
3781 $data->doclink->link = $url->out();
3782 $data->doclink->linktext = $linktext;
3783 $data->doclink->class = ($CFG->doctonewwindow) ? 'helplinkpopup' : '';
3784 } else {
3785 $data->completedoclink = html_writer::tag('div', $OUTPUT->doc_link($link, $linktext),
3786 array('class' => 'helpdoclink'));
3789 } else {
3790 $data->text = html_writer::tag('p',
3791 html_writer::tag('strong', 'TODO') . ": missing help string [{$identifier}_help, {$component}]");
3793 return $data;