MDL-79674 behat: Use proper tags for testing WCAG 2.1 criteria
[moodle.git] / lib / weblib.php
blobc03273b66f81b226933251c910491f5dc38d4440
1 <?php
2 // This file is part of Moodle - http://moodle.org/
3 //
4 // Moodle is free software: you can redistribute it and/or modify
5 // it under the terms of the GNU General Public License as published by
6 // the Free Software Foundation, either version 3 of the License, or
7 // (at your option) any later version.
8 //
9 // Moodle is distributed in the hope that it will be useful,
10 // but WITHOUT ANY WARRANTY; without even the implied warranty of
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 // GNU General Public License for more details.
14 // You should have received a copy of the GNU General Public License
15 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
17 /**
18 * Library of functions for web output
20 * Library of all general-purpose Moodle PHP functions and constants
21 * that produce HTML output
23 * Other main libraries:
24 * - datalib.php - functions that access the database.
25 * - moodlelib.php - general-purpose Moodle functions.
27 * @package core
28 * @subpackage lib
29 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
30 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
33 defined('MOODLE_INTERNAL') || die();
35 // Constants.
37 // Define text formatting types ... eventually we can add Wiki, BBcode etc.
39 /**
40 * Does all sorts of transformations and filtering.
42 define('FORMAT_MOODLE', '0');
44 /**
45 * Plain HTML (with some tags stripped).
47 define('FORMAT_HTML', '1');
49 /**
50 * Plain text (even tags are printed in full).
52 define('FORMAT_PLAIN', '2');
54 /**
55 * Wiki-formatted text.
56 * Deprecated: left here just to note that '3' is not used (at the moment)
57 * and to catch any latent wiki-like text (which generates an error)
58 * @deprecated since 2005!
60 define('FORMAT_WIKI', '3');
62 /**
63 * Markdown-formatted text http://daringfireball.net/projects/markdown/
65 define('FORMAT_MARKDOWN', '4');
67 /**
68 * A moodle_url comparison using this flag will return true if the base URLs match, params are ignored.
70 define('URL_MATCH_BASE', 0);
72 /**
73 * A moodle_url comparison using this flag will return true if the base URLs match and the params of url1 are part of url2.
75 define('URL_MATCH_PARAMS', 1);
77 /**
78 * A moodle_url comparison using this flag will return true if the two URLs are identical, except for the order of the params.
80 define('URL_MATCH_EXACT', 2);
82 // Functions.
84 /**
85 * Add quotes to HTML characters.
87 * Returns $var with HTML characters (like "<", ">", etc.) properly quoted.
88 * Related function {@link p()} simply prints the output of this function.
90 * @param string $var the string potentially containing HTML characters
91 * @return string
93 function s($var) {
94 if ($var === false) {
95 return '0';
98 if ($var === null || $var === '') {
99 return '';
102 return preg_replace(
103 '/&amp;#(\d+|x[0-9a-f]+);/i', '&#$1;',
104 htmlspecialchars($var, ENT_QUOTES | ENT_HTML401 | ENT_SUBSTITUTE)
109 * Add quotes to HTML characters.
111 * Prints $var with HTML characters (like "<", ">", etc.) properly quoted.
112 * This function simply calls & displays {@link s()}.
113 * @see s()
115 * @param string $var the string potentially containing HTML characters
117 function p($var) {
118 echo s($var);
122 * Does proper javascript quoting.
124 * Do not use addslashes anymore, because it does not work when magic_quotes_sybase is enabled.
126 * @param mixed $var String, Array, or Object to add slashes to
127 * @return mixed quoted result
129 function addslashes_js($var) {
130 if (is_string($var)) {
131 $var = str_replace('\\', '\\\\', $var);
132 $var = str_replace(array('\'', '"', "\n", "\r", "\0"), array('\\\'', '\\"', '\\n', '\\r', '\\0'), $var);
133 $var = str_replace('</', '<\/', $var); // XHTML compliance.
134 } else if (is_array($var)) {
135 $var = array_map('addslashes_js', $var);
136 } else if (is_object($var)) {
137 $a = get_object_vars($var);
138 foreach ($a as $key => $value) {
139 $a[$key] = addslashes_js($value);
141 $var = (object)$a;
143 return $var;
147 * Remove query string from url.
149 * Takes in a URL and returns it without the querystring portion.
151 * @param string $url the url which may have a query string attached.
152 * @return string The remaining URL.
154 function strip_querystring($url) {
155 if ($url === null || $url === '') {
156 return '';
159 if ($commapos = strpos($url, '?')) {
160 return substr($url, 0, $commapos);
161 } else {
162 return $url;
167 * Returns the name of the current script, WITH the querystring portion.
169 * This function is necessary because PHP_SELF and REQUEST_URI and SCRIPT_NAME
170 * return different things depending on a lot of things like your OS, Web
171 * server, and the way PHP is compiled (ie. as a CGI, module, ISAPI, etc.)
172 * <b>NOTE:</b> This function returns false if the global variables needed are not set.
174 * @return mixed String or false if the global variables needed are not set.
176 function me() {
177 global $ME;
178 return $ME;
182 * Guesses the full URL of the current script.
184 * This function is using $PAGE->url, but may fall back to $FULLME which
185 * is constructed from PHP_SELF and REQUEST_URI or SCRIPT_NAME
187 * @return mixed full page URL string or false if unknown
189 function qualified_me() {
190 global $FULLME, $PAGE, $CFG;
192 if (isset($PAGE) and $PAGE->has_set_url()) {
193 // This is the only recommended way to find out current page.
194 return $PAGE->url->out(false);
196 } else {
197 if ($FULLME === null) {
198 // CLI script most probably.
199 return false;
201 if (!empty($CFG->sslproxy)) {
202 // Return only https links when using SSL proxy.
203 return preg_replace('/^http:/', 'https:', $FULLME, 1);
204 } else {
205 return $FULLME;
211 * Determines whether or not the Moodle site is being served over HTTPS.
213 * This is done simply by checking the value of $CFG->wwwroot, which seems
214 * to be the only reliable method.
216 * @return boolean True if site is served over HTTPS, false otherwise.
218 function is_https() {
219 global $CFG;
221 return (strpos($CFG->wwwroot, 'https://') === 0);
225 * Returns the cleaned local URL of the HTTP_REFERER less the URL query string parameters if required.
227 * @param bool $stripquery if true, also removes the query part of the url.
228 * @return string The resulting referer or empty string.
230 function get_local_referer($stripquery = true) {
231 if (isset($_SERVER['HTTP_REFERER'])) {
232 $referer = clean_param($_SERVER['HTTP_REFERER'], PARAM_LOCALURL);
233 if ($stripquery) {
234 return strip_querystring($referer);
235 } else {
236 return $referer;
238 } else {
239 return '';
244 * Class for creating and manipulating urls.
246 * It can be used in moodle pages where config.php has been included without any further includes.
248 * It is useful for manipulating urls with long lists of params.
249 * One situation where it will be useful is a page which links to itself to perform various actions
250 * and / or to process form data. A moodle_url object :
251 * can be created for a page to refer to itself with all the proper get params being passed from page call to
252 * page call and methods can be used to output a url including all the params, optionally adding and overriding
253 * params and can also be used to
254 * - output the url without any get params
255 * - and output the params as hidden fields to be output within a form
257 * @copyright 2007 jamiesensei
258 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
259 * @package core
261 class moodle_url {
264 * Scheme, ex.: http, https
265 * @var string
267 protected $scheme = '';
270 * Hostname.
271 * @var string
273 protected $host = '';
276 * Port number, empty means default 80 or 443 in case of http.
277 * @var int
279 protected $port = '';
282 * Username for http auth.
283 * @var string
285 protected $user = '';
288 * Password for http auth.
289 * @var string
291 protected $pass = '';
294 * Script path.
295 * @var string
297 protected $path = '';
300 * Optional slash argument value.
301 * @var string
303 protected $slashargument = '';
306 * Anchor, may be also empty, null means none.
307 * @var string
309 protected $anchor = null;
312 * Url parameters as associative array.
313 * @var array
315 protected $params = array();
318 * Create new instance of moodle_url.
320 * @param moodle_url|string $url - moodle_url means make a copy of another
321 * moodle_url and change parameters, string means full url or shortened
322 * form (ex.: '/course/view.php'). It is strongly encouraged to not include
323 * query string because it may result in double encoded values. Use the
324 * $params instead. For admin URLs, just use /admin/script.php, this
325 * class takes care of the $CFG->admin issue.
326 * @param array $params these params override current params or add new
327 * @param string $anchor The anchor to use as part of the URL if there is one.
328 * @throws moodle_exception
330 public function __construct($url, array $params = null, $anchor = null) {
331 global $CFG;
333 if ($url instanceof moodle_url) {
334 $this->scheme = $url->scheme;
335 $this->host = $url->host;
336 $this->port = $url->port;
337 $this->user = $url->user;
338 $this->pass = $url->pass;
339 $this->path = $url->path;
340 $this->slashargument = $url->slashargument;
341 $this->params = $url->params;
342 $this->anchor = $url->anchor;
344 } else {
345 $url = $url ?? '';
346 // Detect if anchor used.
347 $apos = strpos($url, '#');
348 if ($apos !== false) {
349 $anchor = substr($url, $apos);
350 $anchor = ltrim($anchor, '#');
351 $this->set_anchor($anchor);
352 $url = substr($url, 0, $apos);
355 // Normalise shortened form of our url ex.: '/course/view.php'.
356 if (strpos($url, '/') === 0) {
357 $url = $CFG->wwwroot.$url;
360 if ($CFG->admin !== 'admin') {
361 if (strpos($url, "$CFG->wwwroot/admin/") === 0) {
362 $url = str_replace("$CFG->wwwroot/admin/", "$CFG->wwwroot/$CFG->admin/", $url);
366 // Parse the $url.
367 $parts = parse_url($url);
368 if ($parts === false) {
369 throw new moodle_exception('invalidurl');
371 if (isset($parts['query'])) {
372 // Note: the values may not be correctly decoded, url parameters should be always passed as array.
373 parse_str(str_replace('&amp;', '&', $parts['query']), $this->params);
375 unset($parts['query']);
376 foreach ($parts as $key => $value) {
377 $this->$key = $value;
380 // Detect slashargument value from path - we do not support directory names ending with .php.
381 $pos = strpos($this->path, '.php/');
382 if ($pos !== false) {
383 $this->slashargument = substr($this->path, $pos + 4);
384 $this->path = substr($this->path, 0, $pos + 4);
388 $this->params($params);
389 if ($anchor !== null) {
390 $this->anchor = (string)$anchor;
395 * Add an array of params to the params for this url.
397 * The added params override existing ones if they have the same name.
399 * @param array $params Defaults to null. If null then returns all params.
400 * @return array Array of Params for url.
401 * @throws coding_exception
403 public function params(array $params = null) {
404 $params = (array)$params;
406 foreach ($params as $key => $value) {
407 if (is_int($key)) {
408 throw new coding_exception('Url parameters can not have numeric keys!');
410 if (!is_string($value)) {
411 if (is_array($value)) {
412 throw new coding_exception('Url parameters values can not be arrays!');
414 if (is_object($value) and !method_exists($value, '__toString')) {
415 throw new coding_exception('Url parameters values can not be objects, unless __toString() is defined!');
418 $this->params[$key] = (string)$value;
420 return $this->params;
424 * Remove all params if no arguments passed.
425 * Remove selected params if arguments are passed.
427 * Can be called as either remove_params('param1', 'param2')
428 * or remove_params(array('param1', 'param2')).
430 * @param string[]|string $params,... either an array of param names, or 1..n string params to remove as args.
431 * @return array url parameters
433 public function remove_params($params = null) {
434 if (!is_array($params)) {
435 $params = func_get_args();
437 foreach ($params as $param) {
438 unset($this->params[$param]);
440 return $this->params;
444 * Remove all url parameters.
446 * @todo remove the unused param.
447 * @param array $params Unused param
448 * @return void
450 public function remove_all_params($params = null) {
451 $this->params = array();
452 $this->slashargument = '';
456 * Add a param to the params for this url.
458 * The added param overrides existing one if they have the same name.
460 * @param string $paramname name
461 * @param string $newvalue Param value. If new value specified current value is overriden or parameter is added
462 * @return mixed string parameter value, null if parameter does not exist
464 public function param($paramname, $newvalue = '') {
465 if (func_num_args() > 1) {
466 // Set new value.
467 $this->params(array($paramname => $newvalue));
469 if (isset($this->params[$paramname])) {
470 return $this->params[$paramname];
471 } else {
472 return null;
477 * Merges parameters and validates them
479 * @param array $overrideparams
480 * @return array merged parameters
481 * @throws coding_exception
483 protected function merge_overrideparams(array $overrideparams = null) {
484 $overrideparams = (array)$overrideparams;
485 $params = $this->params;
486 foreach ($overrideparams as $key => $value) {
487 if (is_int($key)) {
488 throw new coding_exception('Overridden parameters can not have numeric keys!');
490 if (is_array($value)) {
491 throw new coding_exception('Overridden parameters values can not be arrays!');
493 if (is_object($value) and !method_exists($value, '__toString')) {
494 throw new coding_exception('Overridden parameters values can not be objects, unless __toString() is defined!');
496 $params[$key] = (string)$value;
498 return $params;
502 * Get the params as as a query string.
504 * This method should not be used outside of this method.
506 * @param bool $escaped Use &amp; as params separator instead of plain &
507 * @param array $overrideparams params to add to the output params, these
508 * override existing ones with the same name.
509 * @return string query string that can be added to a url.
511 public function get_query_string($escaped = true, array $overrideparams = null) {
512 $arr = array();
513 if ($overrideparams !== null) {
514 $params = $this->merge_overrideparams($overrideparams);
515 } else {
516 $params = $this->params;
518 foreach ($params as $key => $val) {
519 if (is_array($val)) {
520 foreach ($val as $index => $value) {
521 $arr[] = rawurlencode($key.'['.$index.']')."=".rawurlencode($value);
523 } else {
524 if (isset($val) && $val !== '') {
525 $arr[] = rawurlencode($key)."=".rawurlencode($val);
526 } else {
527 $arr[] = rawurlencode($key);
531 if ($escaped) {
532 return implode('&amp;', $arr);
533 } else {
534 return implode('&', $arr);
539 * Get the url params as an array of key => value pairs.
541 * This helps in handling cases where url params contain arrays.
543 * @return array params array for templates.
545 public function export_params_for_template(): array {
546 $data = [];
547 foreach ($this->params as $key => $val) {
548 if (is_array($val)) {
549 foreach ($val as $index => $value) {
550 $data[] = ['name' => $key.'['.$index.']', 'value' => $value];
552 } else {
553 $data[] = ['name' => $key, 'value' => $val];
556 return $data;
560 * Shortcut for printing of encoded URL.
562 * @return string
564 public function __toString() {
565 return $this->out(true);
569 * Output url.
571 * If you use the returned URL in HTML code, you want the escaped ampersands. If you use
572 * the returned URL in HTTP headers, you want $escaped=false.
574 * @param bool $escaped Use &amp; as params separator instead of plain &
575 * @param array $overrideparams params to add to the output url, these override existing ones with the same name.
576 * @return string Resulting URL
578 public function out($escaped = true, array $overrideparams = null) {
580 global $CFG;
582 if (!is_bool($escaped)) {
583 debugging('Escape parameter must be of type boolean, '.gettype($escaped).' given instead.');
586 $url = $this;
588 // Allow url's to be rewritten by a plugin.
589 if (isset($CFG->urlrewriteclass) && !isset($CFG->upgraderunning)) {
590 $class = $CFG->urlrewriteclass;
591 $pluginurl = $class::url_rewrite($url);
592 if ($pluginurl instanceof moodle_url) {
593 $url = $pluginurl;
597 return $url->raw_out($escaped, $overrideparams);
602 * Output url without any rewrites
604 * This is identical in signature and use to out() but doesn't call the rewrite handler.
606 * @param bool $escaped Use &amp; as params separator instead of plain &
607 * @param array $overrideparams params to add to the output url, these override existing ones with the same name.
608 * @return string Resulting URL
610 public function raw_out($escaped = true, array $overrideparams = null) {
611 if (!is_bool($escaped)) {
612 debugging('Escape parameter must be of type boolean, '.gettype($escaped).' given instead.');
615 $uri = $this->out_omit_querystring().$this->slashargument;
617 $querystring = $this->get_query_string($escaped, $overrideparams);
618 if ($querystring !== '') {
619 $uri .= '?' . $querystring;
621 if (!is_null($this->anchor)) {
622 $uri .= '#'.$this->anchor;
625 return $uri;
629 * Returns url without parameters, everything before '?'.
631 * @param bool $includeanchor if {@link self::anchor} is defined, should it be returned?
632 * @return string
634 public function out_omit_querystring($includeanchor = false) {
636 $uri = $this->scheme ? $this->scheme.':'.((strtolower($this->scheme) == 'mailto') ? '':'//'): '';
637 $uri .= $this->user ? $this->user.($this->pass? ':'.$this->pass:'').'@':'';
638 $uri .= $this->host ? $this->host : '';
639 $uri .= $this->port ? ':'.$this->port : '';
640 $uri .= $this->path ? $this->path : '';
641 if ($includeanchor and !is_null($this->anchor)) {
642 $uri .= '#' . $this->anchor;
645 return $uri;
649 * Compares this moodle_url with another.
651 * See documentation of constants for an explanation of the comparison flags.
653 * @param moodle_url $url The moodle_url object to compare
654 * @param int $matchtype The type of comparison (URL_MATCH_BASE, URL_MATCH_PARAMS, URL_MATCH_EXACT)
655 * @return bool
657 public function compare(moodle_url $url, $matchtype = URL_MATCH_EXACT) {
659 $baseself = $this->out_omit_querystring();
660 $baseother = $url->out_omit_querystring();
662 // Append index.php if there is no specific file.
663 if (substr($baseself, -1) == '/') {
664 $baseself .= 'index.php';
666 if (substr($baseother, -1) == '/') {
667 $baseother .= 'index.php';
670 // Compare the two base URLs.
671 if ($baseself != $baseother) {
672 return false;
675 if ($matchtype == URL_MATCH_BASE) {
676 return true;
679 $urlparams = $url->params();
680 foreach ($this->params() as $param => $value) {
681 if ($param == 'sesskey') {
682 continue;
684 if (!array_key_exists($param, $urlparams) || $urlparams[$param] != $value) {
685 return false;
689 if ($matchtype == URL_MATCH_PARAMS) {
690 return true;
693 foreach ($urlparams as $param => $value) {
694 if ($param == 'sesskey') {
695 continue;
697 if (!array_key_exists($param, $this->params()) || $this->param($param) != $value) {
698 return false;
702 if ($url->anchor !== $this->anchor) {
703 return false;
706 return true;
710 * Sets the anchor for the URI (the bit after the hash)
712 * @param string $anchor null means remove previous
714 public function set_anchor($anchor) {
715 if (is_null($anchor)) {
716 // Remove.
717 $this->anchor = null;
718 } else if ($anchor === '') {
719 // Special case, used as empty link.
720 $this->anchor = '';
721 } else if (preg_match('|[a-zA-Z\_\:][a-zA-Z0-9\_\-\.\:]*|', $anchor)) {
722 // Match the anchor against the NMTOKEN spec.
723 $this->anchor = $anchor;
724 } else {
725 // Bad luck, no valid anchor found.
726 $this->anchor = null;
731 * Sets the scheme for the URI (the bit before ://)
733 * @param string $scheme
735 public function set_scheme($scheme) {
736 // See http://www.ietf.org/rfc/rfc3986.txt part 3.1.
737 if (preg_match('/^[a-zA-Z][a-zA-Z0-9+.-]*$/', $scheme)) {
738 $this->scheme = $scheme;
739 } else {
740 throw new coding_exception('Bad URL scheme.');
745 * Sets the url slashargument value.
747 * @param string $path usually file path
748 * @param string $parameter name of page parameter if slasharguments not supported
749 * @param bool $supported usually null, then it depends on $CFG->slasharguments, use true or false for other servers
750 * @return void
752 public function set_slashargument($path, $parameter = 'file', $supported = null) {
753 global $CFG;
754 if (is_null($supported)) {
755 $supported = !empty($CFG->slasharguments);
758 if ($supported) {
759 $parts = explode('/', $path);
760 $parts = array_map('rawurlencode', $parts);
761 $path = implode('/', $parts);
762 $this->slashargument = $path;
763 unset($this->params[$parameter]);
765 } else {
766 $this->slashargument = '';
767 $this->params[$parameter] = $path;
771 // Static factory methods.
774 * General moodle file url.
776 * @param string $urlbase the script serving the file
777 * @param string $path
778 * @param bool $forcedownload
779 * @return moodle_url
781 public static function make_file_url($urlbase, $path, $forcedownload = false) {
782 $params = array();
783 if ($forcedownload) {
784 $params['forcedownload'] = 1;
786 $url = new moodle_url($urlbase, $params);
787 $url->set_slashargument($path);
788 return $url;
792 * Factory method for creation of url pointing to plugin file.
794 * Please note this method can be used only from the plugins to
795 * create urls of own files, it must not be used outside of plugins!
797 * @param int $contextid
798 * @param string $component
799 * @param string $area
800 * @param int $itemid
801 * @param string $pathname
802 * @param string $filename
803 * @param bool $forcedownload
804 * @param mixed $includetoken Whether to use a user token when displaying this group image.
805 * True indicates to generate a token for current user, and integer value indicates to generate a token for the
806 * user whose id is the value indicated.
807 * If the group picture is included in an e-mail or some other location where the audience is a specific
808 * user who will not be logged in when viewing, then we use a token to authenticate the user.
809 * @return moodle_url
811 public static function make_pluginfile_url($contextid, $component, $area, $itemid, $pathname, $filename,
812 $forcedownload = false, $includetoken = false) {
813 global $CFG, $USER;
815 $path = [];
817 if ($includetoken) {
818 $urlbase = "$CFG->wwwroot/tokenpluginfile.php";
819 $userid = $includetoken === true ? $USER->id : $includetoken;
820 $token = get_user_key('core_files', $userid);
821 if ($CFG->slasharguments) {
822 $path[] = $token;
824 } else {
825 $urlbase = "$CFG->wwwroot/pluginfile.php";
827 $path[] = $contextid;
828 $path[] = $component;
829 $path[] = $area;
831 if ($itemid !== null) {
832 $path[] = $itemid;
835 $path = "/" . implode('/', $path) . "{$pathname}{$filename}";
837 $url = self::make_file_url($urlbase, $path, $forcedownload, $includetoken);
838 if ($includetoken && empty($CFG->slasharguments)) {
839 $url->param('token', $token);
841 return $url;
845 * Factory method for creation of url pointing to plugin file.
846 * This method is the same that make_pluginfile_url but pointing to the webservice pluginfile.php script.
847 * It should be used only in external functions.
849 * @since 2.8
850 * @param int $contextid
851 * @param string $component
852 * @param string $area
853 * @param int $itemid
854 * @param string $pathname
855 * @param string $filename
856 * @param bool $forcedownload
857 * @return moodle_url
859 public static function make_webservice_pluginfile_url($contextid, $component, $area, $itemid, $pathname, $filename,
860 $forcedownload = false) {
861 global $CFG;
862 $urlbase = "$CFG->wwwroot/webservice/pluginfile.php";
863 if ($itemid === null) {
864 return self::make_file_url($urlbase, "/$contextid/$component/$area".$pathname.$filename, $forcedownload);
865 } else {
866 return self::make_file_url($urlbase, "/$contextid/$component/$area/$itemid".$pathname.$filename, $forcedownload);
871 * Factory method for creation of url pointing to draft file of current user.
873 * @param int $draftid draft item id
874 * @param string $pathname
875 * @param string $filename
876 * @param bool $forcedownload
877 * @return moodle_url
879 public static function make_draftfile_url($draftid, $pathname, $filename, $forcedownload = false) {
880 global $CFG, $USER;
881 $urlbase = "$CFG->wwwroot/draftfile.php";
882 $context = context_user::instance($USER->id);
884 return self::make_file_url($urlbase, "/$context->id/user/draft/$draftid".$pathname.$filename, $forcedownload);
888 * Factory method for creating of links to legacy course files.
890 * @param int $courseid
891 * @param string $filepath
892 * @param bool $forcedownload
893 * @return moodle_url
895 public static function make_legacyfile_url($courseid, $filepath, $forcedownload = false) {
896 global $CFG;
898 $urlbase = "$CFG->wwwroot/file.php";
899 return self::make_file_url($urlbase, '/'.$courseid.'/'.$filepath, $forcedownload);
903 * Checks if URL is relative to $CFG->wwwroot.
905 * @return bool True if URL is relative to $CFG->wwwroot; otherwise, false.
907 public function is_local_url() : bool {
908 global $CFG;
910 $url = $this->out();
911 // Does URL start with wwwroot? Otherwise, URL isn't relative to wwwroot.
912 return ( ($url === $CFG->wwwroot) || (strpos($url, $CFG->wwwroot.'/') === 0) );
916 * Returns URL as relative path from $CFG->wwwroot
918 * Can be used for passing around urls with the wwwroot stripped
920 * @param boolean $escaped Use &amp; as params separator instead of plain &
921 * @param array $overrideparams params to add to the output url, these override existing ones with the same name.
922 * @return string Resulting URL
923 * @throws coding_exception if called on a non-local url
925 public function out_as_local_url($escaped = true, array $overrideparams = null) {
926 global $CFG;
928 // URL should be relative to wwwroot. If not then throw exception.
929 if ($this->is_local_url()) {
930 $url = $this->out($escaped, $overrideparams);
931 $localurl = substr($url, strlen($CFG->wwwroot));
932 return !empty($localurl) ? $localurl : '';
933 } else {
934 throw new coding_exception('out_as_local_url called on a non-local URL');
939 * Returns the 'path' portion of a URL. For example, if the URL is
940 * http://www.example.org:447/my/file/is/here.txt?really=1 then this will
941 * return '/my/file/is/here.txt'.
943 * By default the path includes slash-arguments (for example,
944 * '/myfile.php/extra/arguments') so it is what you would expect from a
945 * URL path. If you don't want this behaviour, you can opt to exclude the
946 * slash arguments. (Be careful: if the $CFG variable slasharguments is
947 * disabled, these URLs will have a different format and you may need to
948 * look at the 'file' parameter too.)
950 * @param bool $includeslashargument If true, includes slash arguments
951 * @return string Path of URL
953 public function get_path($includeslashargument = true) {
954 return $this->path . ($includeslashargument ? $this->slashargument : '');
958 * Returns a given parameter value from the URL.
960 * @param string $name Name of parameter
961 * @return string Value of parameter or null if not set
963 public function get_param($name) {
964 if (array_key_exists($name, $this->params)) {
965 return $this->params[$name];
966 } else {
967 return null;
972 * Returns the 'scheme' portion of a URL. For example, if the URL is
973 * http://www.example.org:447/my/file/is/here.txt?really=1 then this will
974 * return 'http' (without the colon).
976 * @return string Scheme of the URL.
978 public function get_scheme() {
979 return $this->scheme;
983 * Returns the 'host' portion of a URL. For example, if the URL is
984 * http://www.example.org:447/my/file/is/here.txt?really=1 then this will
985 * return 'www.example.org'.
987 * @return string Host of the URL.
989 public function get_host() {
990 return $this->host;
994 * Returns the 'port' portion of a URL. For example, if the URL is
995 * http://www.example.org:447/my/file/is/here.txt?really=1 then this will
996 * return '447'.
998 * @return string Port of the URL.
1000 public function get_port() {
1001 return $this->port;
1006 * Determine if there is data waiting to be processed from a form
1008 * Used on most forms in Moodle to check for data
1009 * Returns the data as an object, if it's found.
1010 * This object can be used in foreach loops without
1011 * casting because it's cast to (array) automatically
1013 * Checks that submitted POST data exists and returns it as object.
1015 * @return mixed false or object
1017 function data_submitted() {
1019 if (empty($_POST)) {
1020 return false;
1021 } else {
1022 return (object)fix_utf8($_POST);
1027 * Given some normal text this function will break up any
1028 * long words to a given size by inserting the given character
1030 * It's multibyte savvy and doesn't change anything inside html tags.
1032 * @param string $string the string to be modified
1033 * @param int $maxsize maximum length of the string to be returned
1034 * @param string $cutchar the string used to represent word breaks
1035 * @return string
1037 function break_up_long_words($string, $maxsize=20, $cutchar=' ') {
1039 // First of all, save all the tags inside the text to skip them.
1040 $tags = array();
1041 filter_save_tags($string, $tags);
1043 // Process the string adding the cut when necessary.
1044 $output = '';
1045 $length = core_text::strlen($string);
1046 $wordlength = 0;
1048 for ($i=0; $i<$length; $i++) {
1049 $char = core_text::substr($string, $i, 1);
1050 if ($char == ' ' or $char == "\t" or $char == "\n" or $char == "\r" or $char == "<" or $char == ">") {
1051 $wordlength = 0;
1052 } else {
1053 $wordlength++;
1054 if ($wordlength > $maxsize) {
1055 $output .= $cutchar;
1056 $wordlength = 0;
1059 $output .= $char;
1062 // Finally load the tags back again.
1063 if (!empty($tags)) {
1064 $output = str_replace(array_keys($tags), $tags, $output);
1067 return $output;
1071 * Try and close the current window using JavaScript, either immediately, or after a delay.
1073 * Echo's out the resulting XHTML & javascript
1075 * @param integer $delay a delay in seconds before closing the window. Default 0.
1076 * @param boolean $reloadopener if true, we will see if this window was a pop-up, and try
1077 * to reload the parent window before this one closes.
1079 function close_window($delay = 0, $reloadopener = false) {
1080 global $PAGE, $OUTPUT;
1082 if (!$PAGE->headerprinted) {
1083 $PAGE->set_title(get_string('closewindow'));
1084 echo $OUTPUT->header();
1085 } else {
1086 $OUTPUT->container_end_all(false);
1089 if ($reloadopener) {
1090 // Trigger the reload immediately, even if the reload is after a delay.
1091 $PAGE->requires->js_function_call('window.opener.location.reload', array(true));
1093 $OUTPUT->notification(get_string('windowclosing'), 'notifysuccess');
1095 $PAGE->requires->js_function_call('close_window', array(new stdClass()), false, $delay);
1097 echo $OUTPUT->footer();
1098 exit;
1102 * Returns a string containing a link to the user documentation for the current page.
1104 * Also contains an icon by default. Shown to teachers and admin only.
1106 * @param string $text The text to be displayed for the link
1107 * @return string The link to user documentation for this current page
1109 function page_doc_link($text='') {
1110 global $OUTPUT, $PAGE;
1111 $path = page_get_doc_link_path($PAGE);
1112 if (!$path) {
1113 return '';
1115 return $OUTPUT->doc_link($path, $text);
1119 * Returns the path to use when constructing a link to the docs.
1121 * @since Moodle 2.5.1 2.6
1122 * @param moodle_page $page
1123 * @return string
1125 function page_get_doc_link_path(moodle_page $page) {
1126 global $CFG;
1128 if (empty($CFG->docroot) || during_initial_install()) {
1129 return '';
1131 if (!has_capability('moodle/site:doclinks', $page->context)) {
1132 return '';
1135 $path = $page->docspath;
1136 if (!$path) {
1137 return '';
1139 return $path;
1144 * Validates an email to make sure it makes sense.
1146 * @param string $address The email address to validate.
1147 * @return boolean
1149 function validate_email($address) {
1150 global $CFG;
1152 if ($address === null || $address === false || $address === '') {
1153 return false;
1156 require_once("{$CFG->libdir}/phpmailer/moodle_phpmailer.php");
1158 return moodle_phpmailer::validateAddress($address ?? '') && !preg_match('/[<>]/', $address);
1162 * Extracts file argument either from file parameter or PATH_INFO
1164 * Note: $scriptname parameter is not needed anymore
1166 * @return string file path (only safe characters)
1168 function get_file_argument() {
1169 global $SCRIPT;
1171 $relativepath = false;
1172 $hasforcedslashargs = false;
1174 if (isset($_SERVER['REQUEST_URI']) && !empty($_SERVER['REQUEST_URI'])) {
1175 // Checks whether $_SERVER['REQUEST_URI'] contains '/pluginfile.php/'
1176 // instead of '/pluginfile.php?', when serving a file from e.g. mod_imscp or mod_scorm.
1177 if ((strpos($_SERVER['REQUEST_URI'], '/pluginfile.php/') !== false)
1178 && isset($_SERVER['PATH_INFO']) && !empty($_SERVER['PATH_INFO'])) {
1179 // Exclude edge cases like '/pluginfile.php/?file='.
1180 $args = explode('/', ltrim($_SERVER['PATH_INFO'], '/'));
1181 $hasforcedslashargs = (count($args) > 2); // Always at least: context, component and filearea.
1184 if (!$hasforcedslashargs) {
1185 $relativepath = optional_param('file', false, PARAM_PATH);
1188 if ($relativepath !== false and $relativepath !== '') {
1189 return $relativepath;
1191 $relativepath = false;
1193 // Then try extract file from the slasharguments.
1194 if (stripos($_SERVER['SERVER_SOFTWARE'], 'iis') !== false) {
1195 // NOTE: IIS tends to convert all file paths to single byte DOS encoding,
1196 // we can not use other methods because they break unicode chars,
1197 // the only ways are to use URL rewriting
1198 // OR
1199 // to properly set the 'FastCGIUtf8ServerVariables' registry key.
1200 if (isset($_SERVER['PATH_INFO']) and $_SERVER['PATH_INFO'] !== '') {
1201 // Check that PATH_INFO works == must not contain the script name.
1202 if (strpos($_SERVER['PATH_INFO'], $SCRIPT) === false) {
1203 $relativepath = clean_param(urldecode($_SERVER['PATH_INFO']), PARAM_PATH);
1206 } else {
1207 // All other apache-like servers depend on PATH_INFO.
1208 if (isset($_SERVER['PATH_INFO'])) {
1209 if (isset($_SERVER['SCRIPT_NAME']) and strpos($_SERVER['PATH_INFO'], $_SERVER['SCRIPT_NAME']) === 0) {
1210 $relativepath = substr($_SERVER['PATH_INFO'], strlen($_SERVER['SCRIPT_NAME']));
1211 } else {
1212 $relativepath = $_SERVER['PATH_INFO'];
1214 $relativepath = clean_param($relativepath, PARAM_PATH);
1218 return $relativepath;
1222 * Just returns an array of text formats suitable for a popup menu
1224 * @return array
1226 function format_text_menu() {
1227 return array (FORMAT_MOODLE => get_string('formattext'),
1228 FORMAT_HTML => get_string('formathtml'),
1229 FORMAT_PLAIN => get_string('formatplain'),
1230 FORMAT_MARKDOWN => get_string('formatmarkdown'));
1234 * Given text in a variety of format codings, this function returns the text as safe HTML.
1236 * This function should mainly be used for long strings like posts,
1237 * answers, glossary items etc. For short strings {@link format_string()}.
1239 * <pre>
1240 * Options:
1241 * trusted : If true the string won't be cleaned. Default false required noclean=true.
1242 * noclean : If true the string won't be cleaned, unless $CFG->forceclean is set. Default false required trusted=true.
1243 * filter : If true the string will be run through applicable filters as well. Default true.
1244 * para : If true then the returned string will be wrapped in div tags. Default true.
1245 * newlines : If true then lines newline breaks will be converted to HTML newline breaks. Default true.
1246 * context : The context that will be used for filtering.
1247 * overflowdiv : If set to true the formatted text will be encased in a div
1248 * with the class no-overflow before being returned. Default false.
1249 * allowid : If true then id attributes will not be removed, even when
1250 * using htmlpurifier. Default false.
1251 * blanktarget : If true all <a> tags will have target="_blank" added unless target is explicitly specified.
1252 * </pre>
1254 * @param string $text The text to be formatted. This is raw text originally from user input.
1255 * @param int $format Identifier of the text format to be used
1256 * [FORMAT_MOODLE, FORMAT_HTML, FORMAT_PLAIN, FORMAT_MARKDOWN]
1257 * @param stdClass|array $options text formatting options
1258 * @param int $courseiddonotuse deprecated course id, use context option instead
1259 * @return string
1261 function format_text($text, $format = FORMAT_MOODLE, $options = null, $courseiddonotuse = null) {
1262 global $CFG;
1264 // Manually include the formatting class for now until after the release after 4.5 LTS.
1265 require_once("{$CFG->libdir}/classes/formatting.php");
1267 if ($format === FORMAT_WIKI) {
1268 // This format was deprecated in Moodle 1.5.
1269 throw new \coding_exception(
1270 'Wiki-like formatting is not supported.'
1274 if ($options instanceof \core\context) {
1275 // A common mistake has been to call this function with a context object.
1276 // This has never been expected, or nor supported.
1277 debugging(
1278 'The options argument should not be a context object directly. ' .
1279 ' Please pass an array with a context key instead.',
1280 DEBUG_DEVELOPER,
1282 $params['context'] = $options;
1283 $options = [];
1286 if ($options) {
1287 $options = (array) $options;
1290 if (empty($CFG->version) || $CFG->version < 2013051400 || during_initial_install()) {
1291 // Do not filter anything during installation or before upgrade completes.
1292 $params['context'] = null;
1293 } else if ($options && isset($options['context'])) { // First by explicit passed context option.
1294 if (is_numeric($options['context'])) {
1295 // A contextid was passed.
1296 $params['context'] = \core\context::instance_by_id($options['context']);
1297 } else if ($options['context'] instanceof \core\context) {
1298 $params['context'] = $options['context'];
1299 } else {
1300 debugging(
1301 'Unknown context passed to format_text(). Content will not be filtered.',
1302 DEBUG_DEVELOPER,
1306 // Unset the context from $options to prevent it overriding the configured value.
1307 unset($options['context']);
1308 } else if ($courseiddonotuse) {
1309 // Legacy courseid.
1310 $params['context'] = \core\context\course::instance($courseiddonotuse);
1311 debugging(
1312 "Passing a courseid to format_text() is deprecated, please pass a context instead.",
1313 DEBUG_DEVELOPER,
1317 $params['text'] = $text;
1319 if ($options) {
1320 // The smiley option was deprecated in Moodle 2.0.
1321 if (array_key_exists('smiley', $options)) {
1322 unset($options['smiley']);
1323 debugging(
1324 'The smiley option is deprecated and no longer used.',
1325 DEBUG_DEVELOPER,
1329 // The nocache option was deprecated in Moodle 2.3 in MDL-34347.
1330 if (array_key_exists('nocache', $options)) {
1331 unset($options['nocache']);
1332 debugging(
1333 'The nocache option is deprecated and no longer used.',
1334 DEBUG_DEVELOPER,
1338 $validoptions = [
1339 'text',
1340 'format',
1341 'context',
1342 'trusted',
1343 'clean',
1344 'filter',
1345 'para',
1346 'newlines',
1347 'overflowdiv',
1348 'blanktarget',
1349 'allowid',
1350 'noclean',
1353 $invalidoptions = array_diff(array_keys($options), $validoptions);
1354 if ($invalidoptions) {
1355 debugging(sprintf(
1356 'The following options are not valid: %s',
1357 implode(', ', $invalidoptions),
1358 ), DEBUG_DEVELOPER);
1359 foreach ($invalidoptions as $option) {
1360 unset($options[$option]);
1364 foreach ($options as $option => $value) {
1365 $params[$option] = $value;
1368 // The noclean option has been renamed to clean.
1369 if (array_key_exists('noclean', $params)) {
1370 $params['clean'] = !$params['noclean'];
1371 unset($params['noclean']);
1375 if ($format !== null) {
1376 $params['format'] = $format;
1379 return \core\di::get(\core\formatting::class)->format_text(...$params);
1383 * Resets some data related to filters, called during upgrade or when general filter settings change.
1385 * @param bool $phpunitreset true means called from our PHPUnit integration test reset
1386 * @return void
1388 function reset_text_filters_cache($phpunitreset = false) {
1389 global $CFG, $DB;
1391 if ($phpunitreset) {
1392 // HTMLPurifier does not change, DB is already reset to defaults,
1393 // nothing to do here, the dataroot was cleared too.
1394 return;
1397 // The purge_all_caches() deals with cachedir and localcachedir purging,
1398 // the individual filter caches are invalidated as necessary elsewhere.
1400 // Update $CFG->filterall cache flag.
1401 if (empty($CFG->stringfilters)) {
1402 set_config('filterall', 0);
1403 return;
1405 $installedfilters = core_component::get_plugin_list('filter');
1406 $filters = explode(',', $CFG->stringfilters);
1407 foreach ($filters as $filter) {
1408 if (isset($installedfilters[$filter])) {
1409 set_config('filterall', 1);
1410 return;
1413 set_config('filterall', 0);
1417 * Given a simple string, this function returns the string
1418 * processed by enabled string filters if $CFG->filterall is enabled
1420 * This function should be used to print short strings (non html) that
1421 * need filter processing e.g. activity titles, post subjects,
1422 * glossary concepts.
1424 * @staticvar bool $strcache
1425 * @param string $string The string to be filtered. Should be plain text, expect
1426 * possibly for multilang tags.
1427 * @param boolean $striplinks To strip any link in the result text. Moodle 1.8 default changed from false to true! MDL-8713
1428 * @param array $options options array/object or courseid
1429 * @return string
1431 function format_string($string, $striplinks = true, $options = null) {
1432 global $CFG;
1434 // Manually include the formatting class for now until after the release after 4.5 LTS.
1435 require_once("{$CFG->libdir}/classes/formatting.php");
1437 $params = [
1438 'string' => $string,
1439 'striplinks' => (bool) $striplinks,
1442 // This method only expects either:
1443 // - an array of options;
1444 // - a stdClass of options to be cast to an array; or
1445 // - an integer courseid.
1446 if ($options instanceof \core\context) {
1447 // A common mistake has been to call this function with a context object.
1448 // This has never been expected, or nor supported.
1449 debugging(
1450 'The options argument should not be a context object directly. ' .
1451 ' Please pass an array with a context key instead.',
1452 DEBUG_DEVELOPER,
1454 $params['context'] = $options;
1455 $options = [];
1456 } else if (is_numeric($options)) {
1457 // Legacy courseid usage.
1458 $params['context'] = \core\context\course::instance($options);
1459 $options = [];
1460 } else if (is_array($options) || is_a($options, \stdClass::class)) {
1461 $options = (array) $options;
1462 if (isset($options['context'])) {
1463 if (is_numeric($options['context'])) {
1464 // A contextid was passed usage.
1465 $params['context'] = \core\context::instance_by_id($options['context']);
1466 } else if ($options['context'] instanceof \core\context) {
1467 $params['context'] = $options['context'];
1468 } else {
1469 debugging(
1470 'An invalid value for context was provided.',
1471 DEBUG_DEVELOPER,
1475 } else if ($options !== null) {
1476 // Something else was passed, so we'll just use an empty array.
1477 debugging(sprintf(
1478 'The options argument should be an Array, or stdclass. %s passed.',
1479 gettype($options),
1480 ), DEBUG_DEVELOPER);
1482 // Attempt to cast to array since we always used to, but throw in some debugging.
1483 $options = array_filter(
1484 (array) $options,
1485 fn ($key) => !is_numeric($key),
1486 ARRAY_FILTER_USE_KEY,
1490 if (isset($options['filter'])) {
1491 $params['filter'] = (bool) $options['filter'];
1492 } else {
1493 $params['filter'] = true;
1496 if (isset($options['escape'])) {
1497 $params['escape'] = (bool) $options['escape'];
1498 } else {
1499 $params['escape'] = true;
1502 $validoptions = [
1503 'string',
1504 'striplinks',
1505 'context',
1506 'filter',
1507 'escape',
1510 if ($options) {
1511 $invalidoptions = array_diff(array_keys($options), $validoptions);
1512 if ($invalidoptions) {
1513 debugging(sprintf(
1514 'The following options are not valid: %s',
1515 implode(', ', $invalidoptions),
1516 ), DEBUG_DEVELOPER);
1520 return \core\di::get(\core\formatting::class)->format_string(
1521 ...$params,
1526 * Given a string, performs a negative lookahead looking for any ampersand character
1527 * that is not followed by a proper HTML entity. If any is found, it is replaced
1528 * by &amp;. The string is then returned.
1530 * @param string $string
1531 * @return string
1533 function replace_ampersands_not_followed_by_entity($string) {
1534 return preg_replace("/\&(?![a-zA-Z0-9#]{1,8};)/", "&amp;", $string ?? '');
1538 * Given a string, replaces all <a>.*</a> by .* and returns the string.
1540 * @param string $string
1541 * @return string
1543 function strip_links($string) {
1544 return preg_replace('/(<a\s[^>]+?>)(.+?)(<\/a>)/is', '$2', $string);
1548 * This expression turns links into something nice in a text format. (Russell Jungwirth)
1550 * @param string $string
1551 * @return string
1553 function wikify_links($string) {
1554 return preg_replace('~(<a [^<]*href=["|\']?([^ "\']*)["|\']?[^>]*>([^<]*)</a>)~i', '$3 [ $2 ]', $string);
1558 * Given text in a variety of format codings, this function returns the text as plain text suitable for plain email.
1560 * @param string $text The text to be formatted. This is raw text originally from user input.
1561 * @param int $format Identifier of the text format to be used
1562 * [FORMAT_MOODLE, FORMAT_HTML, FORMAT_PLAIN, FORMAT_WIKI, FORMAT_MARKDOWN]
1563 * @return string
1565 function format_text_email($text, $format) {
1567 switch ($format) {
1569 case FORMAT_PLAIN:
1570 return $text;
1571 break;
1573 case FORMAT_WIKI:
1574 // There should not be any of these any more!
1575 $text = wikify_links($text);
1576 return core_text::entities_to_utf8(strip_tags($text), true);
1577 break;
1579 case FORMAT_HTML:
1580 return html_to_text($text);
1581 break;
1583 case FORMAT_MOODLE:
1584 case FORMAT_MARKDOWN:
1585 default:
1586 $text = wikify_links($text);
1587 return core_text::entities_to_utf8(strip_tags($text), true);
1588 break;
1593 * Formats activity intro text
1595 * @param string $module name of module
1596 * @param object $activity instance of activity
1597 * @param int $cmid course module id
1598 * @param bool $filter filter resulting html text
1599 * @return string
1601 function format_module_intro($module, $activity, $cmid, $filter=true) {
1602 global $CFG;
1603 require_once("$CFG->libdir/filelib.php");
1604 $context = context_module::instance($cmid);
1605 $options = array('noclean' => true, 'para' => false, 'filter' => $filter, 'context' => $context, 'overflowdiv' => true);
1606 $intro = file_rewrite_pluginfile_urls($activity->intro, 'pluginfile.php', $context->id, 'mod_'.$module, 'intro', null);
1607 return trim(format_text($intro, $activity->introformat, $options, null));
1611 * Removes the usage of Moodle files from a text.
1613 * In some rare cases we need to re-use a text that already has embedded links
1614 * to some files hosted within Moodle. But the new area in which we will push
1615 * this content does not support files... therefore we need to remove those files.
1617 * @param string $source The text
1618 * @return string The stripped text
1620 function strip_pluginfile_content($source) {
1621 $baseurl = '@@PLUGINFILE@@';
1622 // Looking for something like < .* "@@pluginfile@@.*" .* >
1623 $pattern = '$<[^<>]+["\']' . $baseurl . '[^"\']*["\'][^<>]*>$';
1624 $stripped = preg_replace($pattern, '', $source);
1625 // Use purify html to rebalence potentially mismatched tags and generally cleanup.
1626 return purify_html($stripped);
1630 * Legacy function, used for cleaning of old forum and glossary text only.
1632 * @param string $text text that may contain legacy TRUSTTEXT marker
1633 * @return string text without legacy TRUSTTEXT marker
1635 function trusttext_strip($text) {
1636 if (!is_string($text)) {
1637 // This avoids the potential for an endless loop below.
1638 throw new coding_exception('trusttext_strip parameter must be a string');
1640 while (true) { // Removing nested TRUSTTEXT.
1641 $orig = $text;
1642 $text = str_replace('#####TRUSTTEXT#####', '', $text);
1643 if (strcmp($orig, $text) === 0) {
1644 return $text;
1650 * Must be called before editing of all texts with trust flag. Removes all XSS nasties from texts stored in database if needed.
1652 * @param stdClass $object data object with xxx, xxxformat and xxxtrust fields
1653 * @param string $field name of text field
1654 * @param context $context active context
1655 * @return stdClass updated $object
1657 function trusttext_pre_edit($object, $field, $context) {
1658 $trustfield = $field.'trust';
1659 $formatfield = $field.'format';
1661 if ($object->$formatfield == FORMAT_MARKDOWN) {
1662 // We do not have a way to sanitise Markdown texts,
1663 // luckily editors for this format should not have XSS problems.
1664 return $object;
1667 if (!$object->$trustfield or !trusttext_trusted($context)) {
1668 $object->$field = clean_text($object->$field, $object->$formatfield);
1671 return $object;
1675 * Is current user trusted to enter no dangerous XSS in this context?
1677 * Please note the user must be in fact trusted everywhere on this server!!
1679 * @param context $context
1680 * @return bool true if user trusted
1682 function trusttext_trusted($context) {
1683 return (trusttext_active() and has_capability('moodle/site:trustcontent', $context));
1687 * Is trusttext feature active?
1689 * @return bool
1691 function trusttext_active() {
1692 global $CFG;
1694 return !empty($CFG->enabletrusttext);
1698 * Cleans raw text removing nasties.
1700 * Given raw text (eg typed in by a user) this function cleans it up and removes any nasty tags that could mess up
1701 * Moodle pages through XSS attacks.
1703 * The result must be used as a HTML text fragment, this function can not cleanup random
1704 * parts of html tags such as url or src attributes.
1706 * NOTE: the format parameter was deprecated because we can safely clean only HTML.
1708 * @param string $text The text to be cleaned
1709 * @param int|string $format deprecated parameter, should always contain FORMAT_HTML or FORMAT_MOODLE
1710 * @param array $options Array of options; currently only option supported is 'allowid' (if true,
1711 * does not remove id attributes when cleaning)
1712 * @return string The cleaned up text
1714 function clean_text($text, $format = FORMAT_HTML, $options = array()) {
1715 $text = (string)$text;
1717 if ($format != FORMAT_HTML and $format != FORMAT_HTML) {
1718 // TODO: we need to standardise cleanup of text when loading it into editor first.
1719 // debugging('clean_text() is designed to work only with html');.
1722 if ($format == FORMAT_PLAIN) {
1723 return $text;
1726 if (is_purify_html_necessary($text)) {
1727 $text = purify_html($text, $options);
1730 // Originally we tried to neutralise some script events here, it was a wrong approach because
1731 // it was trivial to work around that (for example using style based XSS exploits).
1732 // We must not give false sense of security here - all developers MUST understand how to use
1733 // rawurlencode(), htmlentities(), htmlspecialchars(), p(), s(), moodle_url, html_writer and friends!!!
1735 return $text;
1739 * Is it necessary to use HTMLPurifier?
1741 * @private
1742 * @param string $text
1743 * @return bool false means html is safe and valid, true means use HTMLPurifier
1745 function is_purify_html_necessary($text) {
1746 if ($text === '') {
1747 return false;
1750 if ($text === (string)((int)$text)) {
1751 return false;
1754 if (strpos($text, '&') !== false or preg_match('|<[^pesb/]|', $text)) {
1755 // We need to normalise entities or other tags except p, em, strong and br present.
1756 return true;
1759 $altered = htmlspecialchars($text, ENT_NOQUOTES, 'UTF-8', true);
1760 if ($altered === $text) {
1761 // No < > or other special chars means this must be safe.
1762 return false;
1765 // Let's try to convert back some safe html tags.
1766 $altered = preg_replace('|&lt;p&gt;(.*?)&lt;/p&gt;|m', '<p>$1</p>', $altered);
1767 if ($altered === $text) {
1768 return false;
1770 $altered = preg_replace('|&lt;em&gt;([^<>]+?)&lt;/em&gt;|m', '<em>$1</em>', $altered);
1771 if ($altered === $text) {
1772 return false;
1774 $altered = preg_replace('|&lt;strong&gt;([^<>]+?)&lt;/strong&gt;|m', '<strong>$1</strong>', $altered);
1775 if ($altered === $text) {
1776 return false;
1778 $altered = str_replace('&lt;br /&gt;', '<br />', $altered);
1779 if ($altered === $text) {
1780 return false;
1783 return true;
1787 * KSES replacement cleaning function - uses HTML Purifier.
1789 * @param string $text The (X)HTML string to purify
1790 * @param array $options Array of options; currently only option supported is 'allowid' (if set,
1791 * does not remove id attributes when cleaning)
1792 * @return string
1794 function purify_html($text, $options = array()) {
1795 global $CFG;
1797 $text = (string)$text;
1799 static $purifiers = array();
1800 static $caches = array();
1802 // Purifier code can change only during major version upgrade.
1803 $version = empty($CFG->version) ? 0 : $CFG->version;
1804 $cachedir = "$CFG->localcachedir/htmlpurifier/$version";
1805 if (!file_exists($cachedir)) {
1806 // Purging of caches may remove the cache dir at any time,
1807 // luckily file_exists() results should be cached for all existing directories.
1808 $purifiers = array();
1809 $caches = array();
1810 gc_collect_cycles();
1812 make_localcache_directory('htmlpurifier', false);
1813 check_dir_exists($cachedir);
1816 $allowid = empty($options['allowid']) ? 0 : 1;
1817 $allowobjectembed = empty($CFG->allowobjectembed) ? 0 : 1;
1819 $type = 'type_'.$allowid.'_'.$allowobjectembed;
1821 if (!array_key_exists($type, $caches)) {
1822 $caches[$type] = cache::make('core', 'htmlpurifier', array('type' => $type));
1824 $cache = $caches[$type];
1826 // Add revision number and all options to the text key so that it is compatible with local cluster node caches.
1827 $key = "|$version|$allowobjectembed|$allowid|$text";
1828 $filteredtext = $cache->get($key);
1830 if ($filteredtext === true) {
1831 // The filtering did not change the text last time, no need to filter anything again.
1832 return $text;
1833 } else if ($filteredtext !== false) {
1834 return $filteredtext;
1837 if (empty($purifiers[$type])) {
1838 require_once $CFG->libdir.'/htmlpurifier/HTMLPurifier.safe-includes.php';
1839 require_once $CFG->libdir.'/htmlpurifier/locallib.php';
1840 $config = HTMLPurifier_Config::createDefault();
1842 $config->set('HTML.DefinitionID', 'moodlehtml');
1843 $config->set('HTML.DefinitionRev', 7);
1844 $config->set('Cache.SerializerPath', $cachedir);
1845 $config->set('Cache.SerializerPermissions', $CFG->directorypermissions);
1846 $config->set('Core.NormalizeNewlines', false);
1847 $config->set('Core.ConvertDocumentToFragment', true);
1848 $config->set('Core.Encoding', 'UTF-8');
1849 $config->set('HTML.Doctype', 'XHTML 1.0 Transitional');
1850 $config->set('URI.AllowedSchemes', array(
1851 'http' => true,
1852 'https' => true,
1853 'ftp' => true,
1854 'irc' => true,
1855 'nntp' => true,
1856 'news' => true,
1857 'rtsp' => true,
1858 'rtmp' => true,
1859 'teamspeak' => true,
1860 'gopher' => true,
1861 'mms' => true,
1862 'mailto' => true
1864 $config->set('Attr.AllowedFrameTargets', array('_blank'));
1866 if ($allowobjectembed) {
1867 $config->set('HTML.SafeObject', true);
1868 $config->set('Output.FlashCompat', true);
1869 $config->set('HTML.SafeEmbed', true);
1872 if ($allowid) {
1873 $config->set('Attr.EnableID', true);
1876 if ($def = $config->maybeGetRawHTMLDefinition()) {
1877 $def->addElement('nolink', 'Inline', 'Flow', array()); // Skip our filters inside.
1878 $def->addElement('tex', 'Inline', 'Inline', array()); // Tex syntax, equivalent to $$xx$$.
1879 $def->addElement('algebra', 'Inline', 'Inline', array()); // Algebra syntax, equivalent to @@xx@@.
1880 $def->addElement('lang', 'Block', 'Flow', array(), array('lang'=>'CDATA')); // Original multilang style - only our hacked lang attribute.
1881 $def->addAttribute('span', 'xxxlang', 'CDATA'); // Current very problematic multilang.
1882 // Enable the bidirectional isolate element and its span equivalent.
1883 $def->addElement('bdi', 'Inline', 'Flow', 'Common');
1884 $def->addAttribute('span', 'dir', 'Enum#ltr,rtl,auto');
1886 // Media elements.
1887 // https://html.spec.whatwg.org/#the-video-element
1888 $def->addElement('video', 'Inline', 'Optional: #PCDATA | Flow | source | track', 'Common', [
1889 'src' => 'URI',
1890 'crossorigin' => 'Enum#anonymous,use-credentials',
1891 'poster' => 'URI',
1892 'preload' => 'Enum#auto,metadata,none',
1893 'autoplay' => 'Bool',
1894 'playsinline' => 'Bool',
1895 'loop' => 'Bool',
1896 'muted' => 'Bool',
1897 'controls' => 'Bool',
1898 'width' => 'Length',
1899 'height' => 'Length',
1901 // https://html.spec.whatwg.org/#the-audio-element
1902 $def->addElement('audio', 'Inline', 'Optional: #PCDATA | Flow | source | track', 'Common', [
1903 'src' => 'URI',
1904 'crossorigin' => 'Enum#anonymous,use-credentials',
1905 'preload' => 'Enum#auto,metadata,none',
1906 'autoplay' => 'Bool',
1907 'loop' => 'Bool',
1908 'muted' => 'Bool',
1909 'controls' => 'Bool'
1911 // https://html.spec.whatwg.org/#the-source-element
1912 $def->addElement('source', false, 'Empty', null, [
1913 'src' => 'URI',
1914 'type' => 'Text'
1916 // https://html.spec.whatwg.org/#the-track-element
1917 $def->addElement('track', false, 'Empty', null, [
1918 'src' => 'URI',
1919 'kind' => 'Enum#subtitles,captions,descriptions,chapters,metadata',
1920 'srclang' => 'Text',
1921 'label' => 'Text',
1922 'default' => 'Bool',
1925 // Use the built-in Ruby module to add annotation support.
1926 $def->manager->addModule(new HTMLPurifier_HTMLModule_Ruby());
1929 $purifier = new HTMLPurifier($config);
1930 $purifiers[$type] = $purifier;
1931 } else {
1932 $purifier = $purifiers[$type];
1935 $multilang = (strpos($text, 'class="multilang"') !== false);
1937 $filteredtext = $text;
1938 if ($multilang) {
1939 $filteredtextregex = '/<span(\s+lang="([a-zA-Z0-9_-]+)"|\s+class="multilang"){2}\s*>/';
1940 $filteredtext = preg_replace($filteredtextregex, '<span xxxlang="${2}">', $filteredtext);
1942 $filteredtext = (string)$purifier->purify($filteredtext);
1943 if ($multilang) {
1944 $filteredtext = preg_replace('/<span xxxlang="([a-zA-Z0-9_-]+)">/', '<span lang="${1}" class="multilang">', $filteredtext);
1947 if ($text === $filteredtext) {
1948 // No need to store the filtered text, next time we will just return unfiltered text
1949 // because it was not changed by purifying.
1950 $cache->set($key, true);
1951 } else {
1952 $cache->set($key, $filteredtext);
1955 return $filteredtext;
1959 * Given plain text, makes it into HTML as nicely as possible.
1961 * May contain HTML tags already.
1963 * Do not abuse this function. It is intended as lower level formatting feature used
1964 * by {@link format_text()} to convert FORMAT_MOODLE to HTML. You are supposed
1965 * to call format_text() in most of cases.
1967 * @param string $text The string to convert.
1968 * @param boolean $smileyignored Was used to determine if smiley characters should convert to smiley images, ignored now
1969 * @param boolean $para If true then the returned string will be wrapped in div tags
1970 * @param boolean $newlines If true then lines newline breaks will be converted to HTML newline breaks.
1971 * @return string
1973 function text_to_html($text, $smileyignored = null, $para = true, $newlines = true) {
1974 // Remove any whitespace that may be between HTML tags.
1975 $text = preg_replace("~>([[:space:]]+)<~i", "><", $text);
1977 // Remove any returns that precede or follow HTML tags.
1978 $text = preg_replace("~([\n\r])<~i", " <", $text);
1979 $text = preg_replace("~>([\n\r])~i", "> ", $text);
1981 // Make returns into HTML newlines.
1982 if ($newlines) {
1983 $text = nl2br($text);
1986 // Wrap the whole thing in a div if required.
1987 if ($para) {
1988 // In 1.9 this was changed from a p => div.
1989 return '<div class="text_to_html">'.$text.'</div>';
1990 } else {
1991 return $text;
1996 * Given Markdown formatted text, make it into XHTML using external function
1998 * @param string $text The markdown formatted text to be converted.
1999 * @return string Converted text
2001 function markdown_to_html($text) {
2002 global $CFG;
2004 if ($text === '' or $text === null) {
2005 return $text;
2008 require_once($CFG->libdir .'/markdown/MarkdownInterface.php');
2009 require_once($CFG->libdir .'/markdown/Markdown.php');
2010 require_once($CFG->libdir .'/markdown/MarkdownExtra.php');
2012 return \Michelf\MarkdownExtra::defaultTransform($text);
2016 * Given HTML text, make it into plain text using external function
2018 * @param string $html The text to be converted.
2019 * @param integer $width Width to wrap the text at. (optional, default 75 which
2020 * is a good value for email. 0 means do not limit line length.)
2021 * @param boolean $dolinks By default, any links in the HTML are collected, and
2022 * printed as a list at the end of the HTML. If you don't want that, set this
2023 * argument to false.
2024 * @return string plain text equivalent of the HTML.
2026 function html_to_text($html, $width = 75, $dolinks = true) {
2027 global $CFG;
2029 require_once($CFG->libdir .'/html2text/lib.php');
2031 $options = array(
2032 'width' => $width,
2033 'do_links' => 'table',
2036 if (empty($dolinks)) {
2037 $options['do_links'] = 'none';
2039 $h2t = new core_html2text($html, $options);
2040 $result = $h2t->getText();
2042 return $result;
2046 * Converts texts or strings to plain text.
2048 * - When used to convert user input introduced in an editor the text format needs to be passed in $contentformat like we usually
2049 * do in format_text.
2050 * - When this function is used for strings that are usually passed through format_string before displaying them
2051 * we need to set $contentformat to false. This will execute html_to_text as these strings can contain multilang tags if
2052 * multilang filter is applied to headings.
2054 * @param string $content The text as entered by the user
2055 * @param int|false $contentformat False for strings or the text format: FORMAT_MOODLE/FORMAT_HTML/FORMAT_PLAIN/FORMAT_MARKDOWN
2056 * @return string Plain text.
2058 function content_to_text($content, $contentformat) {
2060 switch ($contentformat) {
2061 case FORMAT_PLAIN:
2062 // Nothing here.
2063 break;
2064 case FORMAT_MARKDOWN:
2065 $content = markdown_to_html($content);
2066 $content = html_to_text($content, 75, false);
2067 break;
2068 default:
2069 // FORMAT_HTML, FORMAT_MOODLE and $contentformat = false, the later one are strings usually formatted through
2070 // format_string, we need to convert them from html because they can contain HTML (multilang filter).
2071 $content = html_to_text($content, 75, false);
2074 return trim($content, "\r\n ");
2078 * Factory method for extracting draft file links from arbitrary text using regular expressions. Only text
2079 * is required; other file fields may be passed to filter.
2081 * @param string $text Some html content.
2082 * @param bool $forcehttps force https urls.
2083 * @param int $contextid This parameter and the next three identify the file area to save to.
2084 * @param string $component The component name.
2085 * @param string $filearea The filearea.
2086 * @param int $itemid The item id for the filearea.
2087 * @param string $filename The specific filename of the file.
2088 * @return array
2090 function extract_draft_file_urls_from_text($text, $forcehttps = false, $contextid = null, $component = null,
2091 $filearea = null, $itemid = null, $filename = null) {
2092 global $CFG;
2094 $wwwroot = $CFG->wwwroot;
2095 if ($forcehttps) {
2096 $wwwroot = str_replace('http://', 'https://', $wwwroot);
2098 $urlstring = '/' . preg_quote($wwwroot, '/');
2100 $urlbase = preg_quote('draftfile.php');
2101 $urlstring .= "\/(?<urlbase>{$urlbase})";
2103 if (is_null($contextid)) {
2104 $contextid = '[0-9]+';
2106 $urlstring .= "\/(?<contextid>{$contextid})";
2108 if (is_null($component)) {
2109 $component = '[a-z_]+';
2111 $urlstring .= "\/(?<component>{$component})";
2113 if (is_null($filearea)) {
2114 $filearea = '[a-z_]+';
2116 $urlstring .= "\/(?<filearea>{$filearea})";
2118 if (is_null($itemid)) {
2119 $itemid = '[0-9]+';
2121 $urlstring .= "\/(?<itemid>{$itemid})";
2123 // Filename matching magic based on file_rewrite_urls_to_pluginfile().
2124 if (is_null($filename)) {
2125 $filename = '[^\'\",&<>|`\s:\\\\]+';
2127 $urlstring .= "\/(?<filename>{$filename})/";
2129 // Regular expression which matches URLs and returns their components.
2130 preg_match_all($urlstring, $text, $urls, PREG_SET_ORDER);
2131 return $urls;
2135 * This function will highlight search words in a given string
2137 * It cares about HTML and will not ruin links. It's best to use
2138 * this function after performing any conversions to HTML.
2140 * @param string $needle The search string. Syntax like "word1 +word2 -word3" is dealt with correctly.
2141 * @param string $haystack The string (HTML) within which to highlight the search terms.
2142 * @param boolean $matchcase whether to do case-sensitive. Default case-insensitive.
2143 * @param string $prefix the string to put before each search term found.
2144 * @param string $suffix the string to put after each search term found.
2145 * @return string The highlighted HTML.
2147 function highlight($needle, $haystack, $matchcase = false,
2148 $prefix = '<span class="highlight">', $suffix = '</span>') {
2150 // Quick bail-out in trivial cases.
2151 if (empty($needle) or empty($haystack)) {
2152 return $haystack;
2155 // Break up the search term into words, discard any -words and build a regexp.
2156 $words = preg_split('/ +/', trim($needle));
2157 foreach ($words as $index => $word) {
2158 if (strpos($word, '-') === 0) {
2159 unset($words[$index]);
2160 } else if (strpos($word, '+') === 0) {
2161 $words[$index] = '\b' . preg_quote(ltrim($word, '+'), '/') . '\b'; // Match only as a complete word.
2162 } else {
2163 $words[$index] = preg_quote($word, '/');
2166 $regexp = '/(' . implode('|', $words) . ')/u'; // Char u is to do UTF-8 matching.
2167 if (!$matchcase) {
2168 $regexp .= 'i';
2171 // Another chance to bail-out if $search was only -words.
2172 if (empty($words)) {
2173 return $haystack;
2176 // Split the string into HTML tags and real content.
2177 $chunks = preg_split('/((?:<[^>]*>)+)/', $haystack, -1, PREG_SPLIT_DELIM_CAPTURE);
2179 // We have an array of alternating blocks of text, then HTML tags, then text, ...
2180 // Loop through replacing search terms in the text, and leaving the HTML unchanged.
2181 $ishtmlchunk = false;
2182 $result = '';
2183 foreach ($chunks as $chunk) {
2184 if ($ishtmlchunk) {
2185 $result .= $chunk;
2186 } else {
2187 $result .= preg_replace($regexp, $prefix . '$1' . $suffix, $chunk);
2189 $ishtmlchunk = !$ishtmlchunk;
2192 return $result;
2196 * This function will highlight instances of $needle in $haystack
2198 * It's faster that the above function {@link highlight()} and doesn't care about
2199 * HTML or anything.
2201 * @param string $needle The string to search for
2202 * @param string $haystack The string to search for $needle in
2203 * @return string The highlighted HTML
2205 function highlightfast($needle, $haystack) {
2207 if (empty($needle) or empty($haystack)) {
2208 return $haystack;
2211 $parts = explode(core_text::strtolower($needle), core_text::strtolower($haystack));
2213 if (count($parts) === 1) {
2214 return $haystack;
2217 $pos = 0;
2219 foreach ($parts as $key => $part) {
2220 $parts[$key] = substr($haystack, $pos, strlen($part));
2221 $pos += strlen($part);
2223 $parts[$key] .= '<span class="highlight">'.substr($haystack, $pos, strlen($needle)).'</span>';
2224 $pos += strlen($needle);
2227 return str_replace('<span class="highlight"></span>', '', join('', $parts));
2231 * Converts a language code to hyphen-separated format in accordance to the
2232 * {@link https://datatracker.ietf.org/doc/html/rfc5646#section-2.1 BCP47 syntax}.
2234 * For additional information, check out
2235 * {@link https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/lang MDN web docs - lang}.
2237 * @param string $langcode The language code to convert.
2238 * @return string
2240 function get_html_lang_attribute_value(string $langcode): string {
2241 $langcode = clean_param($langcode, PARAM_LANG);
2242 if ($langcode === '') {
2243 return 'en';
2246 // Grab language ISO code from lang config. If it differs from English, then it's been specified and we can return it.
2247 $langiso = (string) (new lang_string('iso6391', 'core_langconfig', null, $langcode));
2248 if ($langiso !== 'en') {
2249 return $langiso;
2252 // Where we cannot determine the value from lang config, use the first two characters from the lang code.
2253 return substr($langcode, 0, 2);
2257 * Return a string containing 'lang', xml:lang and optionally 'dir' HTML attributes.
2259 * Internationalisation, for print_header and backup/restorelib.
2261 * @param bool $dir Default false
2262 * @return string Attributes
2264 function get_html_lang($dir = false) {
2265 global $CFG;
2267 $currentlang = current_language();
2268 if (isset($CFG->lang) && $currentlang !== $CFG->lang && !get_string_manager()->translation_exists($currentlang)) {
2269 // Use the default site language when the current language is not available.
2270 $currentlang = $CFG->lang;
2271 // Fix the current language.
2272 fix_current_language($currentlang);
2275 $direction = '';
2276 if ($dir) {
2277 if (right_to_left()) {
2278 $direction = ' dir="rtl"';
2279 } else {
2280 $direction = ' dir="ltr"';
2284 // Accessibility: added the 'lang' attribute to $direction, used in theme <html> tag.
2285 $language = get_html_lang_attribute_value($currentlang);
2286 @header('Content-Language: '.$language);
2287 return ($direction.' lang="'.$language.'" xml:lang="'.$language.'"');
2291 // STANDARD WEB PAGE PARTS.
2294 * Send the HTTP headers that Moodle requires.
2296 * There is a backwards compatibility hack for legacy code
2297 * that needs to add custom IE compatibility directive.
2299 * Example:
2300 * <code>
2301 * if (!isset($CFG->additionalhtmlhead)) {
2302 * $CFG->additionalhtmlhead = '';
2304 * $CFG->additionalhtmlhead .= '<meta http-equiv="X-UA-Compatible" content="IE=8" />';
2305 * header('X-UA-Compatible: IE=8');
2306 * echo $OUTPUT->header();
2307 * </code>
2309 * Please note the $CFG->additionalhtmlhead alone might not work,
2310 * you should send the IE compatibility header() too.
2312 * @param string $contenttype
2313 * @param bool $cacheable Can this page be cached on back?
2314 * @return void, sends HTTP headers
2316 function send_headers($contenttype, $cacheable = true) {
2317 global $CFG;
2319 @header('Content-Type: ' . $contenttype);
2320 @header('Content-Script-Type: text/javascript');
2321 @header('Content-Style-Type: text/css');
2323 if (empty($CFG->additionalhtmlhead) or stripos($CFG->additionalhtmlhead, 'X-UA-Compatible') === false) {
2324 @header('X-UA-Compatible: IE=edge');
2327 if ($cacheable) {
2328 // Allow caching on "back" (but not on normal clicks).
2329 @header('Cache-Control: private, pre-check=0, post-check=0, max-age=0, no-transform');
2330 @header('Pragma: no-cache');
2331 @header('Expires: ');
2332 } else {
2333 // Do everything we can to always prevent clients and proxies caching.
2334 @header('Cache-Control: no-store, no-cache, must-revalidate');
2335 @header('Cache-Control: post-check=0, pre-check=0, no-transform', false);
2336 @header('Pragma: no-cache');
2337 @header('Expires: Mon, 20 Aug 1969 09:23:00 GMT');
2338 @header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
2340 @header('Accept-Ranges: none');
2342 // The Moodle app must be allowed to embed content always.
2343 if (empty($CFG->allowframembedding) && !core_useragent::is_moodle_app()) {
2344 @header('X-Frame-Options: sameorigin');
2347 // If referrer policy is set, add a referrer header.
2348 if (!empty($CFG->referrerpolicy) && ($CFG->referrerpolicy !== 'default')) {
2349 @header('Referrer-Policy: ' . $CFG->referrerpolicy);
2354 * Return the right arrow with text ('next'), and optionally embedded in a link.
2356 * @param string $text HTML/plain text label (set to blank only for breadcrumb separator cases).
2357 * @param string $url An optional link to use in a surrounding HTML anchor.
2358 * @param bool $accesshide True if text should be hidden (for screen readers only).
2359 * @param string $addclass Additional class names for the link, or the arrow character.
2360 * @return string HTML string.
2362 function link_arrow_right($text, $url='', $accesshide=false, $addclass='', $addparams = []) {
2363 global $OUTPUT; // TODO: move to output renderer.
2364 $arrowclass = 'arrow ';
2365 if (!$url) {
2366 $arrowclass .= $addclass;
2368 $arrow = '<span class="'.$arrowclass.'" aria-hidden="true">'.$OUTPUT->rarrow().'</span>';
2369 $htmltext = '';
2370 if ($text) {
2371 $htmltext = '<span class="arrow_text">'.$text.'</span>&nbsp;';
2372 if ($accesshide) {
2373 $htmltext = get_accesshide($htmltext);
2376 if ($url) {
2377 $class = 'arrow_link';
2378 if ($addclass) {
2379 $class .= ' '.$addclass;
2382 $linkparams = [
2383 'class' => $class,
2384 'href' => $url,
2385 'title' => preg_replace('/<.*?>/', '', $text),
2388 $linkparams += $addparams;
2390 return html_writer::link($url, $htmltext . $arrow, $linkparams);
2392 return $htmltext.$arrow;
2396 * Return the left arrow with text ('previous'), and optionally embedded in a link.
2398 * @param string $text HTML/plain text label (set to blank only for breadcrumb separator cases).
2399 * @param string $url An optional link to use in a surrounding HTML anchor.
2400 * @param bool $accesshide True if text should be hidden (for screen readers only).
2401 * @param string $addclass Additional class names for the link, or the arrow character.
2402 * @return string HTML string.
2404 function link_arrow_left($text, $url='', $accesshide=false, $addclass='', $addparams = []) {
2405 global $OUTPUT; // TODO: move to utput renderer.
2406 $arrowclass = 'arrow ';
2407 if (! $url) {
2408 $arrowclass .= $addclass;
2410 $arrow = '<span class="'.$arrowclass.'" aria-hidden="true">'.$OUTPUT->larrow().'</span>';
2411 $htmltext = '';
2412 if ($text) {
2413 $htmltext = '&nbsp;<span class="arrow_text">'.$text.'</span>';
2414 if ($accesshide) {
2415 $htmltext = get_accesshide($htmltext);
2418 if ($url) {
2419 $class = 'arrow_link';
2420 if ($addclass) {
2421 $class .= ' '.$addclass;
2424 $linkparams = [
2425 'class' => $class,
2426 'href' => $url,
2427 'title' => preg_replace('/<.*?>/', '', $text),
2430 $linkparams += $addparams;
2432 return html_writer::link($url, $arrow . $htmltext, $linkparams);
2434 return $arrow.$htmltext;
2438 * Return a HTML element with the class "accesshide", for accessibility.
2440 * Please use cautiously - where possible, text should be visible!
2442 * @param string $text Plain text.
2443 * @param string $elem Lowercase element name, default "span".
2444 * @param string $class Additional classes for the element.
2445 * @param string $attrs Additional attributes string in the form, "name='value' name2='value2'"
2446 * @return string HTML string.
2448 function get_accesshide($text, $elem='span', $class='', $attrs='') {
2449 return "<$elem class=\"accesshide $class\" $attrs>$text</$elem>";
2453 * Return the breadcrumb trail navigation separator.
2455 * @return string HTML string.
2457 function get_separator() {
2458 // Accessibility: the 'hidden' slash is preferred for screen readers.
2459 return ' '.link_arrow_right($text='/', $url='', $accesshide=true, 'sep').' ';
2463 * Print (or return) a collapsible region, that has a caption that can be clicked to expand or collapse the region.
2465 * If JavaScript is off, then the region will always be expanded.
2467 * @param string $contents the contents of the box.
2468 * @param string $classes class names added to the div that is output.
2469 * @param string $id id added to the div that is output. Must not be blank.
2470 * @param string $caption text displayed at the top. Clicking on this will cause the region to expand or contract.
2471 * @param string $userpref the name of the user preference that stores the user's preferred default state.
2472 * (May be blank if you do not wish the state to be persisted.
2473 * @param boolean $default Initial collapsed state to use if the user_preference it not set.
2474 * @param boolean $return if true, return the HTML as a string, rather than printing it.
2475 * @return string|void If $return is false, returns nothing, otherwise returns a string of HTML.
2477 function print_collapsible_region($contents, $classes, $id, $caption, $userpref = '', $default = false, $return = false) {
2478 $output = print_collapsible_region_start($classes, $id, $caption, $userpref, $default, true);
2479 $output .= $contents;
2480 $output .= print_collapsible_region_end(true);
2482 if ($return) {
2483 return $output;
2484 } else {
2485 echo $output;
2490 * Print (or return) the start of a collapsible region
2492 * The collapsibleregion has a caption that can be clicked to expand or collapse the region. If JavaScript is off, then the region
2493 * will always be expanded.
2495 * @param string $classes class names added to the div that is output.
2496 * @param string $id id added to the div that is output. Must not be blank.
2497 * @param string $caption text displayed at the top. Clicking on this will cause the region to expand or contract.
2498 * @param string $userpref the name of the user preference that stores the user's preferred default state.
2499 * (May be blank if you do not wish the state to be persisted.
2500 * @param boolean $default Initial collapsed state to use if the user_preference it not set.
2501 * @param boolean $return if true, return the HTML as a string, rather than printing it.
2502 * @param string $extracontent the extra content will show next to caption, eg.Help icon.
2503 * @return string|void if $return is false, returns nothing, otherwise returns a string of HTML.
2505 function print_collapsible_region_start($classes, $id, $caption, $userpref = '', $default = false, $return = false,
2506 $extracontent = null) {
2507 global $PAGE;
2509 // Work out the initial state.
2510 if (!empty($userpref) and is_string($userpref)) {
2511 $collapsed = get_user_preferences($userpref, $default);
2512 } else {
2513 $collapsed = $default;
2514 $userpref = false;
2517 if ($collapsed) {
2518 $classes .= ' collapsed';
2521 $output = '';
2522 $output .= '<div id="' . $id . '" class="collapsibleregion ' . $classes . '">';
2523 $output .= '<div id="' . $id . '_sizer">';
2524 $output .= '<div id="' . $id . '_caption" class="collapsibleregioncaption">';
2525 $output .= $caption . ' </div>';
2526 if ($extracontent) {
2527 $output .= html_writer::div($extracontent, 'collapsibleregionextracontent');
2529 $output .= '<div id="' . $id . '_inner" class="collapsibleregioninner">';
2530 $PAGE->requires->js_init_call('M.util.init_collapsible_region', array($id, $userpref, get_string('clicktohideshow')));
2532 if ($return) {
2533 return $output;
2534 } else {
2535 echo $output;
2540 * Close a region started with print_collapsible_region_start.
2542 * @param boolean $return if true, return the HTML as a string, rather than printing it.
2543 * @return string|void if $return is false, returns nothing, otherwise returns a string of HTML.
2545 function print_collapsible_region_end($return = false) {
2546 $output = '</div></div></div>';
2548 if ($return) {
2549 return $output;
2550 } else {
2551 echo $output;
2556 * Print a specified group's avatar.
2558 * @param array|stdClass $group A single {@link group} object OR array of groups.
2559 * @param int $courseid The course ID.
2560 * @param boolean $large Default small picture, or large.
2561 * @param boolean $return If false print picture, otherwise return the output as string
2562 * @param boolean $link Enclose image in a link to view specified course?
2563 * @param boolean $includetoken Whether to use a user token when displaying this group image.
2564 * True indicates to generate a token for current user, and integer value indicates to generate a token for the
2565 * user whose id is the value indicated.
2566 * If the group picture is included in an e-mail or some other location where the audience is a specific
2567 * user who will not be logged in when viewing, then we use a token to authenticate the user.
2568 * @return string|void Depending on the setting of $return
2570 function print_group_picture($group, $courseid, $large = false, $return = false, $link = true, $includetoken = false) {
2571 global $CFG;
2573 if (is_array($group)) {
2574 $output = '';
2575 foreach ($group as $g) {
2576 $output .= print_group_picture($g, $courseid, $large, true, $link, $includetoken);
2578 if ($return) {
2579 return $output;
2580 } else {
2581 echo $output;
2582 return;
2586 $pictureurl = get_group_picture_url($group, $courseid, $large, $includetoken);
2588 // If there is no picture, do nothing.
2589 if (!isset($pictureurl)) {
2590 return;
2593 $context = context_course::instance($courseid);
2595 $groupname = s($group->name);
2596 $pictureimage = html_writer::img($pictureurl, $groupname, ['title' => $groupname]);
2598 $output = '';
2599 if ($link or has_capability('moodle/site:accessallgroups', $context)) {
2600 $linkurl = new moodle_url('/user/index.php', ['id' => $courseid, 'group' => $group->id]);
2601 $output .= html_writer::link($linkurl, $pictureimage);
2602 } else {
2603 $output .= $pictureimage;
2606 if ($return) {
2607 return $output;
2608 } else {
2609 echo $output;
2614 * Return the url to the group picture.
2616 * @param stdClass $group A group object.
2617 * @param int $courseid The course ID for the group.
2618 * @param bool $large A large or small group picture? Default is small.
2619 * @param boolean $includetoken Whether to use a user token when displaying this group image.
2620 * True indicates to generate a token for current user, and integer value indicates to generate a token for the
2621 * user whose id is the value indicated.
2622 * If the group picture is included in an e-mail or some other location where the audience is a specific
2623 * user who will not be logged in when viewing, then we use a token to authenticate the user.
2624 * @return moodle_url Returns the url for the group picture.
2626 function get_group_picture_url($group, $courseid, $large = false, $includetoken = false) {
2627 global $CFG;
2629 $context = context_course::instance($courseid);
2631 // If there is no picture, do nothing.
2632 if (!$group->picture) {
2633 return;
2636 if ($large) {
2637 $file = 'f1';
2638 } else {
2639 $file = 'f2';
2642 $grouppictureurl = moodle_url::make_pluginfile_url(
2643 $context->id, 'group', 'icon', $group->id, '/', $file, false, $includetoken);
2644 $grouppictureurl->param('rev', $group->picture);
2645 return $grouppictureurl;
2650 * Display a recent activity note
2652 * @staticvar string $strftimerecent
2653 * @param int $time A timestamp int.
2654 * @param stdClass $user A user object from the database.
2655 * @param string $text Text for display for the note
2656 * @param string $link The link to wrap around the text
2657 * @param bool $return If set to true the HTML is returned rather than echo'd
2658 * @param string $viewfullnames
2659 * @return string If $retrun was true returns HTML for a recent activity notice.
2661 function print_recent_activity_note($time, $user, $text, $link, $return=false, $viewfullnames=null) {
2662 static $strftimerecent = null;
2663 $output = '';
2665 if (is_null($viewfullnames)) {
2666 $context = context_system::instance();
2667 $viewfullnames = has_capability('moodle/site:viewfullnames', $context);
2670 if (is_null($strftimerecent)) {
2671 $strftimerecent = get_string('strftimerecent');
2674 $output .= '<div class="head">';
2675 $output .= '<div class="date">'.userdate($time, $strftimerecent).'</div>';
2676 $output .= '<div class="name">'.fullname($user, $viewfullnames).'</div>';
2677 $output .= '</div>';
2678 $output .= '<div class="info"><a href="'.$link.'">'.format_string($text, true).'</a></div>';
2680 if ($return) {
2681 return $output;
2682 } else {
2683 echo $output;
2688 * Returns a popup menu with course activity modules
2690 * Given a course this function returns a small popup menu with all the course activity modules in it, as a navigation menu
2691 * outputs a simple list structure in XHTML.
2692 * The data is taken from the serialised array stored in the course record.
2694 * @param stdClass $course A course object.
2695 * @param array $sections
2696 * @param course_modinfo $modinfo
2697 * @param string $strsection
2698 * @param string $strjumpto
2699 * @param int $width
2700 * @param string $cmid
2701 * @return string The HTML block
2703 function navmenulist($course, $sections, $modinfo, $strsection, $strjumpto, $width=50, $cmid=0) {
2705 global $CFG, $OUTPUT;
2707 $section = -1;
2708 $menu = array();
2709 $doneheading = false;
2711 $courseformatoptions = course_get_format($course)->get_format_options();
2712 $coursecontext = context_course::instance($course->id);
2714 $menu[] = '<ul class="navmenulist"><li class="jumpto section"><span>'.$strjumpto.'</span><ul>';
2715 foreach ($modinfo->cms as $mod) {
2716 if (!$mod->has_view()) {
2717 // Don't show modules which you can't link to!
2718 continue;
2721 // For course formats using 'numsections' do not show extra sections.
2722 if (isset($courseformatoptions['numsections']) && $mod->sectionnum > $courseformatoptions['numsections']) {
2723 break;
2726 if (!$mod->uservisible) { // Do not icnlude empty sections at all.
2727 continue;
2730 if ($mod->sectionnum >= 0 and $section != $mod->sectionnum) {
2731 $thissection = $sections[$mod->sectionnum];
2733 if ($thissection->visible or
2734 (isset($courseformatoptions['hiddensections']) and !$courseformatoptions['hiddensections']) or
2735 has_capability('moodle/course:viewhiddensections', $coursecontext)) {
2736 $thissection->summary = strip_tags(format_string($thissection->summary, true));
2737 if (!$doneheading) {
2738 $menu[] = '</ul></li>';
2740 if ($course->format == 'weeks' or empty($thissection->summary)) {
2741 $item = $strsection ." ". $mod->sectionnum;
2742 } else {
2743 if (core_text::strlen($thissection->summary) < ($width-3)) {
2744 $item = $thissection->summary;
2745 } else {
2746 $item = core_text::substr($thissection->summary, 0, $width).'...';
2749 $menu[] = '<li class="section"><span>'.$item.'</span>';
2750 $menu[] = '<ul>';
2751 $doneheading = true;
2753 $section = $mod->sectionnum;
2754 } else {
2755 // No activities from this hidden section shown.
2756 continue;
2760 $url = $mod->modname .'/view.php?id='. $mod->id;
2761 $mod->name = strip_tags(format_string($mod->name ,true));
2762 if (core_text::strlen($mod->name) > ($width+5)) {
2763 $mod->name = core_text::substr($mod->name, 0, $width).'...';
2765 if (!$mod->visible) {
2766 $mod->name = '('.$mod->name.')';
2768 $class = 'activity '.$mod->modname;
2769 $class .= ($cmid == $mod->id) ? ' selected' : '';
2770 $menu[] = '<li class="'.$class.'">'.
2771 $OUTPUT->image_icon('monologo', '', $mod->modname).
2772 '<a href="'.$CFG->wwwroot.'/mod/'.$url.'">'.$mod->name.'</a></li>';
2775 if ($doneheading) {
2776 $menu[] = '</ul></li>';
2778 $menu[] = '</ul></li></ul>';
2780 return implode("\n", $menu);
2784 * Prints a grade menu (as part of an existing form) with help showing all possible numerical grades and scales.
2786 * @todo Finish documenting this function
2787 * @todo Deprecate: this is only used in a few contrib modules
2789 * @param int $courseid The course ID
2790 * @param string $name
2791 * @param string $current
2792 * @param boolean $includenograde Include those with no grades
2793 * @param boolean $return If set to true returns rather than echo's
2794 * @return string|bool Depending on value of $return
2796 function print_grade_menu($courseid, $name, $current, $includenograde=true, $return=false) {
2797 global $OUTPUT;
2799 $output = '';
2800 $strscale = get_string('scale');
2801 $strscales = get_string('scales');
2803 $scales = get_scales_menu($courseid);
2804 foreach ($scales as $i => $scalename) {
2805 $grades[-$i] = $strscale .': '. $scalename;
2807 if ($includenograde) {
2808 $grades[0] = get_string('nograde');
2810 for ($i=100; $i>=1; $i--) {
2811 $grades[$i] = $i;
2813 $output .= html_writer::select($grades, $name, $current, false);
2815 $linkobject = '<span class="helplink">' . $OUTPUT->pix_icon('help', $strscales) . '</span>';
2816 $link = new moodle_url('/course/scales.php', array('id' => $courseid, 'list' => 1));
2817 $action = new popup_action('click', $link, 'ratingscales', array('height' => 400, 'width' => 500));
2818 $output .= $OUTPUT->action_link($link, $linkobject, $action, array('title' => $strscales));
2820 if ($return) {
2821 return $output;
2822 } else {
2823 echo $output;
2828 * Print an error to STDOUT and exit with a non-zero code. For commandline scripts.
2830 * Default errorcode is 1.
2832 * Very useful for perl-like error-handling:
2833 * do_somethting() or mdie("Something went wrong");
2835 * @param string $msg Error message
2836 * @param integer $errorcode Error code to emit
2838 function mdie($msg='', $errorcode=1) {
2839 trigger_error($msg);
2840 exit($errorcode);
2844 * Print a message and exit.
2846 * @param string $message The message to print in the notice
2847 * @param moodle_url|string $link The link to use for the continue button
2848 * @param object $course A course object. Unused.
2849 * @return void This function simply exits
2851 function notice ($message, $link='', $course=null) {
2852 global $PAGE, $OUTPUT;
2854 $message = clean_text($message); // In case nasties are in here.
2856 if (CLI_SCRIPT) {
2857 echo("!!$message!!\n");
2858 exit(1); // No success.
2861 if (!$PAGE->headerprinted) {
2862 // Header not yet printed.
2863 $PAGE->set_title(get_string('notice'));
2864 echo $OUTPUT->header();
2865 } else {
2866 echo $OUTPUT->container_end_all(false);
2869 echo $OUTPUT->box($message, 'generalbox', 'notice');
2870 echo $OUTPUT->continue_button($link);
2872 echo $OUTPUT->footer();
2873 exit(1); // General error code.
2877 * Redirects the user to another page, after printing a notice.
2879 * This function calls the OUTPUT redirect method, echo's the output and then dies to ensure nothing else happens.
2881 * <strong>Good practice:</strong> You should call this method before starting page
2882 * output by using any of the OUTPUT methods.
2884 * @param moodle_url|string $url A moodle_url to redirect to. Strings are not to be trusted!
2885 * @param string $message The message to display to the user
2886 * @param int $delay The delay before redirecting
2887 * @param string $messagetype The type of notification to show the message in. See constants on \core\output\notification.
2888 * @throws moodle_exception
2890 function redirect($url, $message='', $delay=null, $messagetype = \core\output\notification::NOTIFY_INFO) {
2891 global $OUTPUT, $PAGE, $CFG;
2893 if (CLI_SCRIPT or AJAX_SCRIPT) {
2894 // This is wrong - developers should not use redirect in these scripts but it should not be very likely.
2895 throw new moodle_exception('redirecterrordetected', 'error');
2898 if ($delay === null) {
2899 $delay = -1;
2902 // Prevent debug errors - make sure context is properly initialised.
2903 if ($PAGE) {
2904 $PAGE->set_context(null);
2905 $PAGE->set_pagelayout('redirect'); // No header and footer needed.
2906 $PAGE->set_title(get_string('pageshouldredirect', 'moodle'));
2909 if ($url instanceof moodle_url) {
2910 $url = $url->out(false);
2913 $debugdisableredirect = false;
2914 do {
2915 if (defined('DEBUGGING_PRINTED')) {
2916 // Some debugging already printed, no need to look more.
2917 $debugdisableredirect = true;
2918 break;
2921 if (core_useragent::is_msword()) {
2922 // Clicking a URL from MS Word sends a request to the server without cookies. If that
2923 // causes a redirect Word will open a browser pointing the new URL. If not, the URL that
2924 // was clicked is opened. Because the request from Word is without cookies, it almost
2925 // always results in a redirect to the login page, even if the user is logged in in their
2926 // browser. This is not what we want, so prevent the redirect for requests from Word.
2927 $debugdisableredirect = true;
2928 break;
2931 if (empty($CFG->debugdisplay) or empty($CFG->debug)) {
2932 // No errors should be displayed.
2933 break;
2936 if (!function_exists('error_get_last') or !$lasterror = error_get_last()) {
2937 break;
2940 if (!($lasterror['type'] & $CFG->debug)) {
2941 // Last error not interesting.
2942 break;
2945 // Watch out here, @hidden() errors are returned from error_get_last() too.
2946 if (headers_sent()) {
2947 // We already started printing something - that means errors likely printed.
2948 $debugdisableredirect = true;
2949 break;
2952 if (ob_get_level() and ob_get_contents()) {
2953 // There is something waiting to be printed, hopefully it is the errors,
2954 // but it might be some error hidden by @ too - such as the timezone mess from setup.php.
2955 $debugdisableredirect = true;
2956 break;
2958 } while (false);
2960 // Technically, HTTP/1.1 requires Location: header to contain the absolute path.
2961 // (In practice browsers accept relative paths - but still, might as well do it properly.)
2962 // This code turns relative into absolute.
2963 if (!preg_match('|^[a-z]+:|i', $url)) {
2964 // Get host name http://www.wherever.com.
2965 $hostpart = preg_replace('|^(.*?[^:/])/.*$|', '$1', $CFG->wwwroot);
2966 if (preg_match('|^/|', $url)) {
2967 // URLs beginning with / are relative to web server root so we just add them in.
2968 $url = $hostpart.$url;
2969 } else {
2970 // URLs not beginning with / are relative to path of current script, so add that on.
2971 $url = $hostpart.preg_replace('|\?.*$|', '', me()).'/../'.$url;
2973 // Replace all ..s.
2974 while (true) {
2975 $newurl = preg_replace('|/(?!\.\.)[^/]*/\.\./|', '/', $url);
2976 if ($newurl == $url) {
2977 break;
2979 $url = $newurl;
2983 // Sanitise url - we can not rely on moodle_url or our URL cleaning
2984 // because they do not support all valid external URLs.
2985 $url = preg_replace('/[\x00-\x1F\x7F]/', '', $url);
2986 $url = str_replace('"', '%22', $url);
2987 $encodedurl = preg_replace("/\&(?![a-zA-Z0-9#]{1,8};)/", "&amp;", $url);
2988 $encodedurl = preg_replace('/^.*href="([^"]*)".*$/', "\\1", clean_text('<a href="'.$encodedurl.'" />', FORMAT_HTML));
2989 $url = str_replace('&amp;', '&', $encodedurl);
2991 if (!empty($message)) {
2992 if (!$debugdisableredirect && !headers_sent()) {
2993 // A message has been provided, and the headers have not yet been sent.
2994 // Display the message as a notification on the subsequent page.
2995 \core\notification::add($message, $messagetype);
2996 $message = null;
2997 $delay = 0;
2998 } else {
2999 if ($delay === -1 || !is_numeric($delay)) {
3000 $delay = 3;
3002 $message = clean_text($message);
3004 } else {
3005 $message = get_string('pageshouldredirect');
3006 $delay = 0;
3009 // Make sure the session is closed properly, this prevents problems in IIS
3010 // and also some potential PHP shutdown issues.
3011 \core\session\manager::write_close();
3013 if ($delay == 0 && !$debugdisableredirect && !headers_sent()) {
3015 // This helps when debugging redirect issues like loops and it is not clear
3016 // which layer in the stack sent the redirect header. If debugging is on
3017 // then the file and line is also shown.
3018 $redirectby = 'Moodle';
3019 if (debugging('', DEBUG_DEVELOPER)) {
3020 $origin = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 1)[0];
3021 $redirectby .= ' /' . str_replace($CFG->dirroot . '/', '', $origin['file']) . ':' . $origin['line'];
3023 @header("X-Redirect-By: $redirectby");
3025 // 302 might not work for POST requests, 303 is ignored by obsolete clients.
3026 @header($_SERVER['SERVER_PROTOCOL'] . ' 303 See Other');
3027 @header('Location: '.$url);
3028 echo bootstrap_renderer::plain_redirect_message($encodedurl);
3029 exit;
3032 // Include a redirect message, even with a HTTP redirect, because that is recommended practice.
3033 if ($PAGE) {
3034 $CFG->docroot = false; // To prevent the link to moodle docs from being displayed on redirect page.
3035 echo $OUTPUT->redirect_message($encodedurl, $message, $delay, $debugdisableredirect, $messagetype);
3036 exit;
3037 } else {
3038 echo bootstrap_renderer::early_redirect_message($encodedurl, $message, $delay);
3039 exit;
3044 * Given an email address, this function will return an obfuscated version of it.
3046 * @param string $email The email address to obfuscate
3047 * @return string The obfuscated email address
3049 function obfuscate_email($email) {
3050 $i = 0;
3051 $length = strlen($email);
3052 $obfuscated = '';
3053 while ($i < $length) {
3054 if (rand(0, 2) && $email[$i]!='@') { // MDL-20619 some browsers have problems unobfuscating @.
3055 $obfuscated.='%'.dechex(ord($email[$i]));
3056 } else {
3057 $obfuscated.=$email[$i];
3059 $i++;
3061 return $obfuscated;
3065 * This function takes some text and replaces about half of the characters
3066 * with HTML entity equivalents. Return string is obviously longer.
3068 * @param string $plaintext The text to be obfuscated
3069 * @return string The obfuscated text
3071 function obfuscate_text($plaintext) {
3072 $i=0;
3073 $length = core_text::strlen($plaintext);
3074 $obfuscated='';
3075 $prevobfuscated = false;
3076 while ($i < $length) {
3077 $char = core_text::substr($plaintext, $i, 1);
3078 $ord = core_text::utf8ord($char);
3079 $numerical = ($ord >= ord('0')) && ($ord <= ord('9'));
3080 if ($prevobfuscated and $numerical ) {
3081 $obfuscated.='&#'.$ord.';';
3082 } else if (rand(0, 2)) {
3083 $obfuscated.='&#'.$ord.';';
3084 $prevobfuscated = true;
3085 } else {
3086 $obfuscated.=$char;
3087 $prevobfuscated = false;
3089 $i++;
3091 return $obfuscated;
3095 * This function uses the {@link obfuscate_email()} and {@link obfuscate_text()}
3096 * to generate a fully obfuscated email link, ready to use.
3098 * @param string $email The email address to display
3099 * @param string $label The text to displayed as hyperlink to $email
3100 * @param boolean $dimmed If true then use css class 'dimmed' for hyperlink
3101 * @param string $subject The subject of the email in the mailto link
3102 * @param string $body The content of the email in the mailto link
3103 * @return string The obfuscated mailto link
3105 function obfuscate_mailto($email, $label='', $dimmed=false, $subject = '', $body = '') {
3107 if (empty($label)) {
3108 $label = $email;
3111 $label = obfuscate_text($label);
3112 $email = obfuscate_email($email);
3113 $mailto = obfuscate_text('mailto');
3114 $url = new moodle_url("mailto:$email");
3115 $attrs = array();
3117 if (!empty($subject)) {
3118 $url->param('subject', format_string($subject));
3120 if (!empty($body)) {
3121 $url->param('body', format_string($body));
3124 // Use the obfuscated mailto.
3125 $url = preg_replace('/^mailto/', $mailto, $url->out());
3127 if ($dimmed) {
3128 $attrs['title'] = get_string('emaildisable');
3129 $attrs['class'] = 'dimmed';
3132 return html_writer::link($url, $label, $attrs);
3136 * This function is used to rebuild the <nolink> tag because some formats (PLAIN and WIKI)
3137 * will transform it to html entities
3139 * @param string $text Text to search for nolink tag in
3140 * @return string
3142 function rebuildnolinktag($text) {
3144 $text = preg_replace('/&lt;(\/*nolink)&gt;/i', '<$1>', $text);
3146 return $text;
3150 * Prints a maintenance message from $CFG->maintenance_message or default if empty.
3152 function print_maintenance_message() {
3153 global $CFG, $SITE, $PAGE, $OUTPUT;
3155 header($_SERVER['SERVER_PROTOCOL'] . ' 503 Moodle under maintenance');
3156 header('Status: 503 Moodle under maintenance');
3157 header('Retry-After: 300');
3159 $PAGE->set_pagetype('maintenance-message');
3160 $PAGE->set_pagelayout('maintenance');
3161 $PAGE->set_heading($SITE->fullname);
3162 echo $OUTPUT->header();
3163 echo $OUTPUT->heading(get_string('sitemaintenance', 'admin'));
3164 if (isset($CFG->maintenance_message) and !html_is_blank($CFG->maintenance_message)) {
3165 echo $OUTPUT->box_start('maintenance_message generalbox boxwidthwide boxaligncenter');
3166 echo $CFG->maintenance_message;
3167 echo $OUTPUT->box_end();
3169 echo $OUTPUT->footer();
3170 die;
3174 * Returns a string containing a nested list, suitable for formatting into tabs with CSS.
3176 * It is not recommended to use this function in Moodle 2.5 but it is left for backward
3177 * compartibility.
3179 * Example how to print a single line tabs:
3180 * $rows = array(
3181 * new tabobject(...),
3182 * new tabobject(...)
3183 * );
3184 * echo $OUTPUT->tabtree($rows, $selectedid);
3186 * Multiple row tabs may not look good on some devices but if you want to use them
3187 * you can specify ->subtree for the active tabobject.
3189 * @param array $tabrows An array of rows where each row is an array of tab objects
3190 * @param string $selected The id of the selected tab (whatever row it's on)
3191 * @param array $inactive An array of ids of inactive tabs that are not selectable.
3192 * @param array $activated An array of ids of other tabs that are currently activated
3193 * @param bool $return If true output is returned rather then echo'd
3194 * @return string HTML output if $return was set to true.
3196 function print_tabs($tabrows, $selected = null, $inactive = null, $activated = null, $return = false) {
3197 global $OUTPUT;
3199 $tabrows = array_reverse($tabrows);
3200 $subtree = array();
3201 foreach ($tabrows as $row) {
3202 $tree = array();
3204 foreach ($row as $tab) {
3205 $tab->inactive = is_array($inactive) && in_array((string)$tab->id, $inactive);
3206 $tab->activated = is_array($activated) && in_array((string)$tab->id, $activated);
3207 $tab->selected = (string)$tab->id == $selected;
3209 if ($tab->activated || $tab->selected) {
3210 $tab->subtree = $subtree;
3212 $tree[] = $tab;
3214 $subtree = $tree;
3216 $output = $OUTPUT->tabtree($subtree);
3217 if ($return) {
3218 return $output;
3219 } else {
3220 print $output;
3221 return !empty($output);
3226 * Alter debugging level for the current request,
3227 * the change is not saved in database.
3229 * @param int $level one of the DEBUG_* constants
3230 * @param bool $debugdisplay
3232 function set_debugging($level, $debugdisplay = null) {
3233 global $CFG;
3235 $CFG->debug = (int)$level;
3236 $CFG->debugdeveloper = (($CFG->debug & DEBUG_DEVELOPER) === DEBUG_DEVELOPER);
3238 if ($debugdisplay !== null) {
3239 $CFG->debugdisplay = (bool)$debugdisplay;
3244 * Standard Debugging Function
3246 * Returns true if the current site debugging settings are equal or above specified level.
3247 * If passed a parameter it will emit a debugging notice similar to trigger_error(). The
3248 * routing of notices is controlled by $CFG->debugdisplay
3249 * eg use like this:
3251 * 1) debugging('a normal debug notice');
3252 * 2) debugging('something really picky', DEBUG_ALL);
3253 * 3) debugging('annoying debug message only for developers', DEBUG_DEVELOPER);
3254 * 4) if (debugging()) { perform extra debugging operations (do not use print or echo) }
3256 * In code blocks controlled by debugging() (such as example 4)
3257 * any output should be routed via debugging() itself, or the lower-level
3258 * trigger_error() or error_log(). Using echo or print will break XHTML
3259 * JS and HTTP headers.
3261 * It is also possible to define NO_DEBUG_DISPLAY which redirects the message to error_log.
3263 * @param string $message a message to print
3264 * @param int $level the level at which this debugging statement should show
3265 * @param array $backtrace use different backtrace
3266 * @return bool
3268 function debugging($message = '', $level = DEBUG_NORMAL, $backtrace = null) {
3269 global $CFG, $USER;
3271 $forcedebug = false;
3272 if (!empty($CFG->debugusers) && $USER) {
3273 $debugusers = explode(',', $CFG->debugusers);
3274 $forcedebug = in_array($USER->id, $debugusers);
3277 if (!$forcedebug and (empty($CFG->debug) || ($CFG->debug != -1 and $CFG->debug < $level))) {
3278 return false;
3281 if (!isset($CFG->debugdisplay)) {
3282 $CFG->debugdisplay = ini_get_bool('display_errors');
3285 if ($message) {
3286 if (!$backtrace) {
3287 $backtrace = debug_backtrace();
3289 $from = format_backtrace($backtrace, CLI_SCRIPT || NO_DEBUG_DISPLAY);
3290 if (PHPUNIT_TEST) {
3291 if (phpunit_util::debugging_triggered($message, $level, $from)) {
3292 // We are inside test, the debug message was logged.
3293 return true;
3297 if (NO_DEBUG_DISPLAY) {
3298 // Script does not want any errors or debugging in output,
3299 // we send the info to error log instead.
3300 error_log('Debugging: ' . $message . ' in '. PHP_EOL . $from);
3302 } else if ($forcedebug or $CFG->debugdisplay) {
3303 if (!defined('DEBUGGING_PRINTED')) {
3304 define('DEBUGGING_PRINTED', 1); // Indicates we have printed something.
3306 if (CLI_SCRIPT) {
3307 echo "++ $message ++\n$from";
3308 } else {
3309 echo '<div class="notifytiny debuggingmessage" data-rel="debugging">' , $message , $from , '</div>';
3312 } else {
3313 trigger_error($message . $from, E_USER_NOTICE);
3316 return true;
3320 * Outputs a HTML comment to the browser.
3322 * This is used for those hard-to-debug pages that use bits from many different files in very confusing ways (e.g. blocks).
3324 * <code>print_location_comment(__FILE__, __LINE__);</code>
3326 * @param string $file
3327 * @param integer $line
3328 * @param boolean $return Whether to return or print the comment
3329 * @return string|void Void unless true given as third parameter
3331 function print_location_comment($file, $line, $return = false) {
3332 if ($return) {
3333 return "<!-- $file at line $line -->\n";
3334 } else {
3335 echo "<!-- $file at line $line -->\n";
3341 * Returns true if the user is using a right-to-left language.
3343 * @return boolean true if the current language is right-to-left (Hebrew, Arabic etc)
3345 function right_to_left() {
3346 return (get_string('thisdirection', 'langconfig') === 'rtl');
3351 * Returns swapped left<=> right if in RTL environment.
3353 * Part of RTL Moodles support.
3355 * @param string $align align to check
3356 * @return string
3358 function fix_align_rtl($align) {
3359 if (!right_to_left()) {
3360 return $align;
3362 if ($align == 'left') {
3363 return 'right';
3365 if ($align == 'right') {
3366 return 'left';
3368 return $align;
3373 * Returns true if the page is displayed in a popup window.
3375 * Gets the information from the URL parameter inpopup.
3377 * @todo Use a central function to create the popup calls all over Moodle and
3378 * In the moment only works with resources and probably questions.
3380 * @return boolean
3382 function is_in_popup() {
3383 $inpopup = optional_param('inpopup', '', PARAM_BOOL);
3385 return ($inpopup);
3389 * Progress trace class.
3391 * Use this class from long operations where you want to output occasional information about
3392 * what is going on, but don't know if, or in what format, the output should be.
3394 * @copyright 2009 Tim Hunt
3395 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3396 * @package core
3398 abstract class progress_trace {
3400 * Output an progress message in whatever format.
3402 * @param string $message the message to output.
3403 * @param integer $depth indent depth for this message.
3405 abstract public function output($message, $depth = 0);
3408 * Called when the processing is finished.
3410 public function finished() {
3415 * This subclass of progress_trace does not ouput anything.
3417 * @copyright 2009 Tim Hunt
3418 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3419 * @package core
3421 class null_progress_trace extends progress_trace {
3423 * Does Nothing
3425 * @param string $message
3426 * @param int $depth
3427 * @return void Does Nothing
3429 public function output($message, $depth = 0) {
3434 * This subclass of progress_trace outputs to plain text.
3436 * @copyright 2009 Tim Hunt
3437 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3438 * @package core
3440 class text_progress_trace extends progress_trace {
3442 * Output the trace message.
3444 * @param string $message
3445 * @param int $depth
3446 * @return void Output is echo'd
3448 public function output($message, $depth = 0) {
3449 mtrace(str_repeat(' ', $depth) . $message);
3454 * This subclass of progress_trace outputs as HTML.
3456 * @copyright 2009 Tim Hunt
3457 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3458 * @package core
3460 class html_progress_trace extends progress_trace {
3462 * Output the trace message.
3464 * @param string $message
3465 * @param int $depth
3466 * @return void Output is echo'd
3468 public function output($message, $depth = 0) {
3469 echo '<p>', str_repeat('&#160;&#160;', $depth), htmlspecialchars($message, ENT_COMPAT), "</p>\n";
3470 flush();
3475 * HTML List Progress Tree
3477 * @copyright 2009 Tim Hunt
3478 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3479 * @package core
3481 class html_list_progress_trace extends progress_trace {
3482 /** @var int */
3483 protected $currentdepth = -1;
3486 * Echo out the list
3488 * @param string $message The message to display
3489 * @param int $depth
3490 * @return void Output is echoed
3492 public function output($message, $depth = 0) {
3493 $samedepth = true;
3494 while ($this->currentdepth > $depth) {
3495 echo "</li>\n</ul>\n";
3496 $this->currentdepth -= 1;
3497 if ($this->currentdepth == $depth) {
3498 echo '<li>';
3500 $samedepth = false;
3502 while ($this->currentdepth < $depth) {
3503 echo "<ul>\n<li>";
3504 $this->currentdepth += 1;
3505 $samedepth = false;
3507 if ($samedepth) {
3508 echo "</li>\n<li>";
3510 echo htmlspecialchars($message, ENT_COMPAT);
3511 flush();
3515 * Called when the processing is finished.
3517 public function finished() {
3518 while ($this->currentdepth >= 0) {
3519 echo "</li>\n</ul>\n";
3520 $this->currentdepth -= 1;
3526 * This subclass of progress_trace outputs to error log.
3528 * @copyright Petr Skoda {@link http://skodak.org}
3529 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3530 * @package core
3532 class error_log_progress_trace extends progress_trace {
3533 /** @var string log prefix */
3534 protected $prefix;
3537 * Constructor.
3538 * @param string $prefix optional log prefix
3540 public function __construct($prefix = '') {
3541 $this->prefix = $prefix;
3545 * Output the trace message.
3547 * @param string $message
3548 * @param int $depth
3549 * @return void Output is sent to error log.
3551 public function output($message, $depth = 0) {
3552 error_log($this->prefix . str_repeat(' ', $depth) . $message);
3557 * Special type of trace that can be used for catching of output of other traces.
3559 * @copyright Petr Skoda {@link http://skodak.org}
3560 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3561 * @package core
3563 class progress_trace_buffer extends progress_trace {
3564 /** @var progress_trace */
3565 protected $trace;
3566 /** @var bool do we pass output out */
3567 protected $passthrough;
3568 /** @var string output buffer */
3569 protected $buffer;
3572 * Constructor.
3574 * @param progress_trace $trace
3575 * @param bool $passthrough true means output and buffer, false means just buffer and no output
3577 public function __construct(progress_trace $trace, $passthrough = true) {
3578 $this->trace = $trace;
3579 $this->passthrough = $passthrough;
3580 $this->buffer = '';
3584 * Output the trace message.
3586 * @param string $message the message to output.
3587 * @param int $depth indent depth for this message.
3588 * @return void output stored in buffer
3590 public function output($message, $depth = 0) {
3591 ob_start();
3592 $this->trace->output($message, $depth);
3593 $this->buffer .= ob_get_contents();
3594 if ($this->passthrough) {
3595 ob_end_flush();
3596 } else {
3597 ob_end_clean();
3602 * Called when the processing is finished.
3604 public function finished() {
3605 ob_start();
3606 $this->trace->finished();
3607 $this->buffer .= ob_get_contents();
3608 if ($this->passthrough) {
3609 ob_end_flush();
3610 } else {
3611 ob_end_clean();
3616 * Reset internal text buffer.
3618 public function reset_buffer() {
3619 $this->buffer = '';
3623 * Return internal text buffer.
3624 * @return string buffered plain text
3626 public function get_buffer() {
3627 return $this->buffer;
3632 * Special type of trace that can be used for redirecting to multiple other traces.
3634 * @copyright Petr Skoda {@link http://skodak.org}
3635 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3636 * @package core
3638 class combined_progress_trace extends progress_trace {
3641 * An array of traces.
3642 * @var array
3644 protected $traces;
3647 * Constructs a new instance.
3649 * @param array $traces multiple traces
3651 public function __construct(array $traces) {
3652 $this->traces = $traces;
3656 * Output an progress message in whatever format.
3658 * @param string $message the message to output.
3659 * @param integer $depth indent depth for this message.
3661 public function output($message, $depth = 0) {
3662 foreach ($this->traces as $trace) {
3663 $trace->output($message, $depth);
3668 * Called when the processing is finished.
3670 public function finished() {
3671 foreach ($this->traces as $trace) {
3672 $trace->finished();
3678 * Returns a localized sentence in the current language summarizing the current password policy
3680 * @todo this should be handled by a function/method in the language pack library once we have a support for it
3681 * @uses $CFG
3682 * @return string
3684 function print_password_policy() {
3685 global $CFG;
3687 $message = '';
3688 if (!empty($CFG->passwordpolicy)) {
3689 $messages = array();
3690 if (!empty($CFG->minpasswordlength)) {
3691 $messages[] = get_string('informminpasswordlength', 'auth', $CFG->minpasswordlength);
3693 if (!empty($CFG->minpassworddigits)) {
3694 $messages[] = get_string('informminpassworddigits', 'auth', $CFG->minpassworddigits);
3696 if (!empty($CFG->minpasswordlower)) {
3697 $messages[] = get_string('informminpasswordlower', 'auth', $CFG->minpasswordlower);
3699 if (!empty($CFG->minpasswordupper)) {
3700 $messages[] = get_string('informminpasswordupper', 'auth', $CFG->minpasswordupper);
3702 if (!empty($CFG->minpasswordnonalphanum)) {
3703 $messages[] = get_string('informminpasswordnonalphanum', 'auth', $CFG->minpasswordnonalphanum);
3706 // Fire any additional password policy functions from plugins.
3707 // Callbacks must return an array of message strings.
3708 $pluginsfunction = get_plugins_with_function('print_password_policy');
3709 foreach ($pluginsfunction as $plugintype => $plugins) {
3710 foreach ($plugins as $pluginfunction) {
3711 $messages = array_merge($messages, $pluginfunction());
3715 $messages = join(', ', $messages); // This is ugly but we do not have anything better yet...
3716 // Check if messages is empty before outputting any text.
3717 if ($messages != '') {
3718 $message = get_string('informpasswordpolicy', 'auth', $messages);
3721 return $message;
3725 * Get the value of a help string fully prepared for display in the current language.
3727 * @param string $identifier The identifier of the string to search for.
3728 * @param string $component The module the string is associated with.
3729 * @param boolean $ajax Whether this help is called from an AJAX script.
3730 * This is used to influence text formatting and determines
3731 * which format to output the doclink in.
3732 * @param string|object|array $a An object, string or number that can be used
3733 * within translation strings
3734 * @return stdClass An object containing:
3735 * - heading: Any heading that there may be for this help string.
3736 * - text: The wiki-formatted help string.
3737 * - doclink: An object containing a link, the linktext, and any additional
3738 * CSS classes to apply to that link. Only present if $ajax = false.
3739 * - completedoclink: A text representation of the doclink. Only present if $ajax = true.
3741 function get_formatted_help_string($identifier, $component, $ajax = false, $a = null) {
3742 global $CFG, $OUTPUT;
3743 $sm = get_string_manager();
3745 // Do not rebuild caches here!
3746 // Devs need to learn to purge all caches after any change or disable $CFG->langstringcache.
3748 $data = new stdClass();
3750 if ($sm->string_exists($identifier, $component)) {
3751 $data->heading = format_string(get_string($identifier, $component));
3752 } else {
3753 // Gracefully fall back to an empty string.
3754 $data->heading = '';
3757 if ($sm->string_exists($identifier . '_help', $component)) {
3758 $options = new stdClass();
3759 $options->trusted = false;
3760 $options->noclean = false;
3761 $options->filter = false;
3762 $options->para = true;
3763 $options->newlines = false;
3764 $options->overflowdiv = !$ajax;
3766 // Should be simple wiki only MDL-21695.
3767 $data->text = format_text(get_string($identifier.'_help', $component, $a), FORMAT_MARKDOWN, $options);
3769 $helplink = $identifier . '_link';
3770 if ($sm->string_exists($helplink, $component)) { // Link to further info in Moodle docs.
3771 $link = get_string($helplink, $component);
3772 $linktext = get_string('morehelp');
3774 $data->doclink = new stdClass();
3775 $url = new moodle_url(get_docs_url($link));
3776 if ($ajax) {
3777 $data->doclink->link = $url->out();
3778 $data->doclink->linktext = $linktext;
3779 $data->doclink->class = ($CFG->doctonewwindow) ? 'helplinkpopup' : '';
3780 } else {
3781 $data->completedoclink = html_writer::tag('div', $OUTPUT->doc_link($link, $linktext),
3782 array('class' => 'helpdoclink'));
3785 } else {
3786 $data->text = html_writer::tag('p',
3787 html_writer::tag('strong', 'TODO') . ": missing help string [{$identifier}_help, {$component}]");
3789 return $data;