Merge branch 'm35_MDL-60793_Mod_Chat_Reserved_Words_In_MySQL8p0p3_And_Above' of https...
[moodle.git] / lib / weblib.php
blobae480fdec6053f0f7ee6180bb96802e46bc2df42
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) {
95 if ($var === false) {
96 return '0';
99 return preg_replace('/&amp;#(\d+|x[0-9a-f]+);/i', '&#$1;',
100 htmlspecialchars($var, ENT_QUOTES | ENT_HTML401 | ENT_SUBSTITUTE));
104 * Add quotes to HTML characters.
106 * Prints $var with HTML characters (like "<", ">", etc.) properly quoted.
107 * This function simply calls & displays {@link s()}.
108 * @see s()
110 * @param string $var the string potentially containing HTML characters
111 * @return string
113 function p($var) {
114 echo s($var);
118 * Does proper javascript quoting.
120 * Do not use addslashes anymore, because it does not work when magic_quotes_sybase is enabled.
122 * @param mixed $var String, Array, or Object to add slashes to
123 * @return mixed quoted result
125 function addslashes_js($var) {
126 if (is_string($var)) {
127 $var = str_replace('\\', '\\\\', $var);
128 $var = str_replace(array('\'', '"', "\n", "\r", "\0"), array('\\\'', '\\"', '\\n', '\\r', '\\0'), $var);
129 $var = str_replace('</', '<\/', $var); // XHTML compliance.
130 } else if (is_array($var)) {
131 $var = array_map('addslashes_js', $var);
132 } else if (is_object($var)) {
133 $a = get_object_vars($var);
134 foreach ($a as $key => $value) {
135 $a[$key] = addslashes_js($value);
137 $var = (object)$a;
139 return $var;
143 * Remove query string from url.
145 * Takes in a URL and returns it without the querystring portion.
147 * @param string $url the url which may have a query string attached.
148 * @return string The remaining URL.
150 function strip_querystring($url) {
152 if ($commapos = strpos($url, '?')) {
153 return substr($url, 0, $commapos);
154 } else {
155 return $url;
160 * Returns the name of the current script, WITH the querystring portion.
162 * This function is necessary because PHP_SELF and REQUEST_URI and SCRIPT_NAME
163 * return different things depending on a lot of things like your OS, Web
164 * server, and the way PHP is compiled (ie. as a CGI, module, ISAPI, etc.)
165 * <b>NOTE:</b> This function returns false if the global variables needed are not set.
167 * @return mixed String or false if the global variables needed are not set.
169 function me() {
170 global $ME;
171 return $ME;
175 * Guesses the full URL of the current script.
177 * This function is using $PAGE->url, but may fall back to $FULLME which
178 * is constructed from PHP_SELF and REQUEST_URI or SCRIPT_NAME
180 * @return mixed full page URL string or false if unknown
182 function qualified_me() {
183 global $FULLME, $PAGE, $CFG;
185 if (isset($PAGE) and $PAGE->has_set_url()) {
186 // This is the only recommended way to find out current page.
187 return $PAGE->url->out(false);
189 } else {
190 if ($FULLME === null) {
191 // CLI script most probably.
192 return false;
194 if (!empty($CFG->sslproxy)) {
195 // Return only https links when using SSL proxy.
196 return preg_replace('/^http:/', 'https:', $FULLME, 1);
197 } else {
198 return $FULLME;
204 * Determines whether or not the Moodle site is being served over HTTPS.
206 * This is done simply by checking the value of $CFG->wwwroot, which seems
207 * to be the only reliable method.
209 * @return boolean True if site is served over HTTPS, false otherwise.
211 function is_https() {
212 global $CFG;
214 return (strpos($CFG->wwwroot, 'https://') === 0);
218 * Returns the cleaned local URL of the HTTP_REFERER less the URL query string parameters if required.
220 * @param bool $stripquery if true, also removes the query part of the url.
221 * @return string The resulting referer or empty string.
223 function get_local_referer($stripquery = true) {
224 if (isset($_SERVER['HTTP_REFERER'])) {
225 $referer = clean_param($_SERVER['HTTP_REFERER'], PARAM_LOCALURL);
226 if ($stripquery) {
227 return strip_querystring($referer);
228 } else {
229 return $referer;
231 } else {
232 return '';
237 * Class for creating and manipulating urls.
239 * It can be used in moodle pages where config.php has been included without any further includes.
241 * It is useful for manipulating urls with long lists of params.
242 * One situation where it will be useful is a page which links to itself to perform various actions
243 * and / or to process form data. A moodle_url object :
244 * can be created for a page to refer to itself with all the proper get params being passed from page call to
245 * page call and methods can be used to output a url including all the params, optionally adding and overriding
246 * params and can also be used to
247 * - output the url without any get params
248 * - and output the params as hidden fields to be output within a form
250 * @copyright 2007 jamiesensei
251 * @link http://docs.moodle.org/dev/lib/weblib.php_moodle_url See short write up here
252 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
253 * @package core
255 class moodle_url {
258 * Scheme, ex.: http, https
259 * @var string
261 protected $scheme = '';
264 * Hostname.
265 * @var string
267 protected $host = '';
270 * Port number, empty means default 80 or 443 in case of http.
271 * @var int
273 protected $port = '';
276 * Username for http auth.
277 * @var string
279 protected $user = '';
282 * Password for http auth.
283 * @var string
285 protected $pass = '';
288 * Script path.
289 * @var string
291 protected $path = '';
294 * Optional slash argument value.
295 * @var string
297 protected $slashargument = '';
300 * Anchor, may be also empty, null means none.
301 * @var string
303 protected $anchor = null;
306 * Url parameters as associative array.
307 * @var array
309 protected $params = array();
312 * Create new instance of moodle_url.
314 * @param moodle_url|string $url - moodle_url means make a copy of another
315 * moodle_url and change parameters, string means full url or shortened
316 * form (ex.: '/course/view.php'). It is strongly encouraged to not include
317 * query string because it may result in double encoded values. Use the
318 * $params instead. For admin URLs, just use /admin/script.php, this
319 * class takes care of the $CFG->admin issue.
320 * @param array $params these params override current params or add new
321 * @param string $anchor The anchor to use as part of the URL if there is one.
322 * @throws moodle_exception
324 public function __construct($url, array $params = null, $anchor = null) {
325 global $CFG;
327 if ($url instanceof moodle_url) {
328 $this->scheme = $url->scheme;
329 $this->host = $url->host;
330 $this->port = $url->port;
331 $this->user = $url->user;
332 $this->pass = $url->pass;
333 $this->path = $url->path;
334 $this->slashargument = $url->slashargument;
335 $this->params = $url->params;
336 $this->anchor = $url->anchor;
338 } else {
339 // Detect if anchor used.
340 $apos = strpos($url, '#');
341 if ($apos !== false) {
342 $anchor = substr($url, $apos);
343 $anchor = ltrim($anchor, '#');
344 $this->set_anchor($anchor);
345 $url = substr($url, 0, $apos);
348 // Normalise shortened form of our url ex.: '/course/view.php'.
349 if (strpos($url, '/') === 0) {
350 $url = $CFG->wwwroot.$url;
353 if ($CFG->admin !== 'admin') {
354 if (strpos($url, "$CFG->wwwroot/admin/") === 0) {
355 $url = str_replace("$CFG->wwwroot/admin/", "$CFG->wwwroot/$CFG->admin/", $url);
359 // Parse the $url.
360 $parts = parse_url($url);
361 if ($parts === false) {
362 throw new moodle_exception('invalidurl');
364 if (isset($parts['query'])) {
365 // Note: the values may not be correctly decoded, url parameters should be always passed as array.
366 parse_str(str_replace('&amp;', '&', $parts['query']), $this->params);
368 unset($parts['query']);
369 foreach ($parts as $key => $value) {
370 $this->$key = $value;
373 // Detect slashargument value from path - we do not support directory names ending with .php.
374 $pos = strpos($this->path, '.php/');
375 if ($pos !== false) {
376 $this->slashargument = substr($this->path, $pos + 4);
377 $this->path = substr($this->path, 0, $pos + 4);
381 $this->params($params);
382 if ($anchor !== null) {
383 $this->anchor = (string)$anchor;
388 * Add an array of params to the params for this url.
390 * The added params override existing ones if they have the same name.
392 * @param array $params Defaults to null. If null then returns all params.
393 * @return array Array of Params for url.
394 * @throws coding_exception
396 public function params(array $params = null) {
397 $params = (array)$params;
399 foreach ($params as $key => $value) {
400 if (is_int($key)) {
401 throw new coding_exception('Url parameters can not have numeric keys!');
403 if (!is_string($value)) {
404 if (is_array($value)) {
405 throw new coding_exception('Url parameters values can not be arrays!');
407 if (is_object($value) and !method_exists($value, '__toString')) {
408 throw new coding_exception('Url parameters values can not be objects, unless __toString() is defined!');
411 $this->params[$key] = (string)$value;
413 return $this->params;
417 * Remove all params if no arguments passed.
418 * Remove selected params if arguments are passed.
420 * Can be called as either remove_params('param1', 'param2')
421 * or remove_params(array('param1', 'param2')).
423 * @param string[]|string $params,... either an array of param names, or 1..n string params to remove as args.
424 * @return array url parameters
426 public function remove_params($params = null) {
427 if (!is_array($params)) {
428 $params = func_get_args();
430 foreach ($params as $param) {
431 unset($this->params[$param]);
433 return $this->params;
437 * Remove all url parameters.
439 * @todo remove the unused param.
440 * @param array $params Unused param
441 * @return void
443 public function remove_all_params($params = null) {
444 $this->params = array();
445 $this->slashargument = '';
449 * Add a param to the params for this url.
451 * The added param overrides existing one if they have the same name.
453 * @param string $paramname name
454 * @param string $newvalue Param value. If new value specified current value is overriden or parameter is added
455 * @return mixed string parameter value, null if parameter does not exist
457 public function param($paramname, $newvalue = '') {
458 if (func_num_args() > 1) {
459 // Set new value.
460 $this->params(array($paramname => $newvalue));
462 if (isset($this->params[$paramname])) {
463 return $this->params[$paramname];
464 } else {
465 return null;
470 * Merges parameters and validates them
472 * @param array $overrideparams
473 * @return array merged parameters
474 * @throws coding_exception
476 protected function merge_overrideparams(array $overrideparams = null) {
477 $overrideparams = (array)$overrideparams;
478 $params = $this->params;
479 foreach ($overrideparams as $key => $value) {
480 if (is_int($key)) {
481 throw new coding_exception('Overridden parameters can not have numeric keys!');
483 if (is_array($value)) {
484 throw new coding_exception('Overridden parameters values can not be arrays!');
486 if (is_object($value) and !method_exists($value, '__toString')) {
487 throw new coding_exception('Overridden parameters values can not be objects, unless __toString() is defined!');
489 $params[$key] = (string)$value;
491 return $params;
495 * Get the params as as a query string.
497 * This method should not be used outside of this method.
499 * @param bool $escaped Use &amp; as params separator instead of plain &
500 * @param array $overrideparams params to add to the output params, these
501 * override existing ones with the same name.
502 * @return string query string that can be added to a url.
504 public function get_query_string($escaped = true, array $overrideparams = null) {
505 $arr = array();
506 if ($overrideparams !== null) {
507 $params = $this->merge_overrideparams($overrideparams);
508 } else {
509 $params = $this->params;
511 foreach ($params as $key => $val) {
512 if (is_array($val)) {
513 foreach ($val as $index => $value) {
514 $arr[] = rawurlencode($key.'['.$index.']')."=".rawurlencode($value);
516 } else {
517 if (isset($val) && $val !== '') {
518 $arr[] = rawurlencode($key)."=".rawurlencode($val);
519 } else {
520 $arr[] = rawurlencode($key);
524 if ($escaped) {
525 return implode('&amp;', $arr);
526 } else {
527 return implode('&', $arr);
532 * Shortcut for printing of encoded URL.
534 * @return string
536 public function __toString() {
537 return $this->out(true);
541 * Output url.
543 * If you use the returned URL in HTML code, you want the escaped ampersands. If you use
544 * the returned URL in HTTP headers, you want $escaped=false.
546 * @param bool $escaped Use &amp; as params separator instead of plain &
547 * @param array $overrideparams params to add to the output url, these override existing ones with the same name.
548 * @return string Resulting URL
550 public function out($escaped = true, array $overrideparams = null) {
552 global $CFG;
554 if (!is_bool($escaped)) {
555 debugging('Escape parameter must be of type boolean, '.gettype($escaped).' given instead.');
558 $url = $this;
560 // Allow url's to be rewritten by a plugin.
561 if (isset($CFG->urlrewriteclass) && !isset($CFG->upgraderunning)) {
562 $class = $CFG->urlrewriteclass;
563 $pluginurl = $class::url_rewrite($url);
564 if ($pluginurl instanceof moodle_url) {
565 $url = $pluginurl;
569 return $url->raw_out($escaped, $overrideparams);
574 * Output url without any rewrites
576 * This is identical in signature and use to out() but doesn't call the rewrite handler.
578 * @param bool $escaped Use &amp; as params separator instead of plain &
579 * @param array $overrideparams params to add to the output url, these override existing ones with the same name.
580 * @return string Resulting URL
582 public function raw_out($escaped = true, array $overrideparams = null) {
583 if (!is_bool($escaped)) {
584 debugging('Escape parameter must be of type boolean, '.gettype($escaped).' given instead.');
587 $uri = $this->out_omit_querystring().$this->slashargument;
589 $querystring = $this->get_query_string($escaped, $overrideparams);
590 if ($querystring !== '') {
591 $uri .= '?' . $querystring;
593 if (!is_null($this->anchor)) {
594 $uri .= '#'.$this->anchor;
597 return $uri;
601 * Returns url without parameters, everything before '?'.
603 * @param bool $includeanchor if {@link self::anchor} is defined, should it be returned?
604 * @return string
606 public function out_omit_querystring($includeanchor = false) {
608 $uri = $this->scheme ? $this->scheme.':'.((strtolower($this->scheme) == 'mailto') ? '':'//'): '';
609 $uri .= $this->user ? $this->user.($this->pass? ':'.$this->pass:'').'@':'';
610 $uri .= $this->host ? $this->host : '';
611 $uri .= $this->port ? ':'.$this->port : '';
612 $uri .= $this->path ? $this->path : '';
613 if ($includeanchor and !is_null($this->anchor)) {
614 $uri .= '#' . $this->anchor;
617 return $uri;
621 * Compares this moodle_url with another.
623 * See documentation of constants for an explanation of the comparison flags.
625 * @param moodle_url $url The moodle_url object to compare
626 * @param int $matchtype The type of comparison (URL_MATCH_BASE, URL_MATCH_PARAMS, URL_MATCH_EXACT)
627 * @return bool
629 public function compare(moodle_url $url, $matchtype = URL_MATCH_EXACT) {
631 $baseself = $this->out_omit_querystring();
632 $baseother = $url->out_omit_querystring();
634 // Append index.php if there is no specific file.
635 if (substr($baseself, -1) == '/') {
636 $baseself .= 'index.php';
638 if (substr($baseother, -1) == '/') {
639 $baseother .= 'index.php';
642 // Compare the two base URLs.
643 if ($baseself != $baseother) {
644 return false;
647 if ($matchtype == URL_MATCH_BASE) {
648 return true;
651 $urlparams = $url->params();
652 foreach ($this->params() as $param => $value) {
653 if ($param == 'sesskey') {
654 continue;
656 if (!array_key_exists($param, $urlparams) || $urlparams[$param] != $value) {
657 return false;
661 if ($matchtype == URL_MATCH_PARAMS) {
662 return true;
665 foreach ($urlparams as $param => $value) {
666 if ($param == 'sesskey') {
667 continue;
669 if (!array_key_exists($param, $this->params()) || $this->param($param) != $value) {
670 return false;
674 if ($url->anchor !== $this->anchor) {
675 return false;
678 return true;
682 * Sets the anchor for the URI (the bit after the hash)
684 * @param string $anchor null means remove previous
686 public function set_anchor($anchor) {
687 if (is_null($anchor)) {
688 // Remove.
689 $this->anchor = null;
690 } else if ($anchor === '') {
691 // Special case, used as empty link.
692 $this->anchor = '';
693 } else if (preg_match('|[a-zA-Z\_\:][a-zA-Z0-9\_\-\.\:]*|', $anchor)) {
694 // Match the anchor against the NMTOKEN spec.
695 $this->anchor = $anchor;
696 } else {
697 // Bad luck, no valid anchor found.
698 $this->anchor = null;
703 * Sets the scheme for the URI (the bit before ://)
705 * @param string $scheme
707 public function set_scheme($scheme) {
708 // See http://www.ietf.org/rfc/rfc3986.txt part 3.1.
709 if (preg_match('/^[a-zA-Z][a-zA-Z0-9+.-]*$/', $scheme)) {
710 $this->scheme = $scheme;
711 } else {
712 throw new coding_exception('Bad URL scheme.');
717 * Sets the url slashargument value.
719 * @param string $path usually file path
720 * @param string $parameter name of page parameter if slasharguments not supported
721 * @param bool $supported usually null, then it depends on $CFG->slasharguments, use true or false for other servers
722 * @return void
724 public function set_slashargument($path, $parameter = 'file', $supported = null) {
725 global $CFG;
726 if (is_null($supported)) {
727 $supported = !empty($CFG->slasharguments);
730 if ($supported) {
731 $parts = explode('/', $path);
732 $parts = array_map('rawurlencode', $parts);
733 $path = implode('/', $parts);
734 $this->slashargument = $path;
735 unset($this->params[$parameter]);
737 } else {
738 $this->slashargument = '';
739 $this->params[$parameter] = $path;
743 // Static factory methods.
746 * General moodle file url.
748 * @param string $urlbase the script serving the file
749 * @param string $path
750 * @param bool $forcedownload
751 * @return moodle_url
753 public static function make_file_url($urlbase, $path, $forcedownload = false) {
754 $params = array();
755 if ($forcedownload) {
756 $params['forcedownload'] = 1;
758 $url = new moodle_url($urlbase, $params);
759 $url->set_slashargument($path);
760 return $url;
764 * Factory method for creation of url pointing to plugin file.
766 * Please note this method can be used only from the plugins to
767 * create urls of own files, it must not be used outside of plugins!
769 * @param int $contextid
770 * @param string $component
771 * @param string $area
772 * @param int $itemid
773 * @param string $pathname
774 * @param string $filename
775 * @param bool $forcedownload
776 * @return moodle_url
778 public static function make_pluginfile_url($contextid, $component, $area, $itemid, $pathname, $filename,
779 $forcedownload = false) {
780 global $CFG;
781 $urlbase = "$CFG->wwwroot/pluginfile.php";
782 if ($itemid === null) {
783 return self::make_file_url($urlbase, "/$contextid/$component/$area".$pathname.$filename, $forcedownload);
784 } else {
785 return self::make_file_url($urlbase, "/$contextid/$component/$area/$itemid".$pathname.$filename, $forcedownload);
790 * Factory method for creation of url pointing to plugin file.
791 * This method is the same that make_pluginfile_url but pointing to the webservice pluginfile.php script.
792 * It should be used only in external functions.
794 * @since 2.8
795 * @param int $contextid
796 * @param string $component
797 * @param string $area
798 * @param int $itemid
799 * @param string $pathname
800 * @param string $filename
801 * @param bool $forcedownload
802 * @return moodle_url
804 public static function make_webservice_pluginfile_url($contextid, $component, $area, $itemid, $pathname, $filename,
805 $forcedownload = false) {
806 global $CFG;
807 $urlbase = "$CFG->wwwroot/webservice/pluginfile.php";
808 if ($itemid === null) {
809 return self::make_file_url($urlbase, "/$contextid/$component/$area".$pathname.$filename, $forcedownload);
810 } else {
811 return self::make_file_url($urlbase, "/$contextid/$component/$area/$itemid".$pathname.$filename, $forcedownload);
816 * Factory method for creation of url pointing to draft file of current user.
818 * @param int $draftid draft item id
819 * @param string $pathname
820 * @param string $filename
821 * @param bool $forcedownload
822 * @return moodle_url
824 public static function make_draftfile_url($draftid, $pathname, $filename, $forcedownload = false) {
825 global $CFG, $USER;
826 $urlbase = "$CFG->wwwroot/draftfile.php";
827 $context = context_user::instance($USER->id);
829 return self::make_file_url($urlbase, "/$context->id/user/draft/$draftid".$pathname.$filename, $forcedownload);
833 * Factory method for creating of links to legacy course files.
835 * @param int $courseid
836 * @param string $filepath
837 * @param bool $forcedownload
838 * @return moodle_url
840 public static function make_legacyfile_url($courseid, $filepath, $forcedownload = false) {
841 global $CFG;
843 $urlbase = "$CFG->wwwroot/file.php";
844 return self::make_file_url($urlbase, '/'.$courseid.'/'.$filepath, $forcedownload);
848 * Returns URL a relative path from $CFG->wwwroot
850 * Can be used for passing around urls with the wwwroot stripped
852 * @param boolean $escaped Use &amp; as params separator instead of plain &
853 * @param array $overrideparams params to add to the output url, these override existing ones with the same name.
854 * @return string Resulting URL
855 * @throws coding_exception if called on a non-local url
857 public function out_as_local_url($escaped = true, array $overrideparams = null) {
858 global $CFG;
860 $url = $this->out($escaped, $overrideparams);
862 // Url should be equal to wwwroot. If not then throw exception.
863 if (($url === $CFG->wwwroot) || (strpos($url, $CFG->wwwroot.'/') === 0)) {
864 $localurl = substr($url, strlen($CFG->wwwroot));
865 return !empty($localurl) ? $localurl : '';
866 } else {
867 throw new coding_exception('out_as_local_url called on a non-local URL');
872 * Returns the 'path' portion of a URL. For example, if the URL is
873 * http://www.example.org:447/my/file/is/here.txt?really=1 then this will
874 * return '/my/file/is/here.txt'.
876 * By default the path includes slash-arguments (for example,
877 * '/myfile.php/extra/arguments') so it is what you would expect from a
878 * URL path. If you don't want this behaviour, you can opt to exclude the
879 * slash arguments. (Be careful: if the $CFG variable slasharguments is
880 * disabled, these URLs will have a different format and you may need to
881 * look at the 'file' parameter too.)
883 * @param bool $includeslashargument If true, includes slash arguments
884 * @return string Path of URL
886 public function get_path($includeslashargument = true) {
887 return $this->path . ($includeslashargument ? $this->slashargument : '');
891 * Returns a given parameter value from the URL.
893 * @param string $name Name of parameter
894 * @return string Value of parameter or null if not set
896 public function get_param($name) {
897 if (array_key_exists($name, $this->params)) {
898 return $this->params[$name];
899 } else {
900 return null;
905 * Returns the 'scheme' portion of a URL. For example, if the URL is
906 * http://www.example.org:447/my/file/is/here.txt?really=1 then this will
907 * return 'http' (without the colon).
909 * @return string Scheme of the URL.
911 public function get_scheme() {
912 return $this->scheme;
916 * Returns the 'host' portion of a URL. For example, if the URL is
917 * http://www.example.org:447/my/file/is/here.txt?really=1 then this will
918 * return 'www.example.org'.
920 * @return string Host of the URL.
922 public function get_host() {
923 return $this->host;
927 * Returns the 'port' portion of a URL. For example, if the URL is
928 * http://www.example.org:447/my/file/is/here.txt?really=1 then this will
929 * return '447'.
931 * @return string Port of the URL.
933 public function get_port() {
934 return $this->port;
939 * Determine if there is data waiting to be processed from a form
941 * Used on most forms in Moodle to check for data
942 * Returns the data as an object, if it's found.
943 * This object can be used in foreach loops without
944 * casting because it's cast to (array) automatically
946 * Checks that submitted POST data exists and returns it as object.
948 * @return mixed false or object
950 function data_submitted() {
952 if (empty($_POST)) {
953 return false;
954 } else {
955 return (object)fix_utf8($_POST);
960 * Given some normal text this function will break up any
961 * long words to a given size by inserting the given character
963 * It's multibyte savvy and doesn't change anything inside html tags.
965 * @param string $string the string to be modified
966 * @param int $maxsize maximum length of the string to be returned
967 * @param string $cutchar the string used to represent word breaks
968 * @return string
970 function break_up_long_words($string, $maxsize=20, $cutchar=' ') {
972 // First of all, save all the tags inside the text to skip them.
973 $tags = array();
974 filter_save_tags($string, $tags);
976 // Process the string adding the cut when necessary.
977 $output = '';
978 $length = core_text::strlen($string);
979 $wordlength = 0;
981 for ($i=0; $i<$length; $i++) {
982 $char = core_text::substr($string, $i, 1);
983 if ($char == ' ' or $char == "\t" or $char == "\n" or $char == "\r" or $char == "<" or $char == ">") {
984 $wordlength = 0;
985 } else {
986 $wordlength++;
987 if ($wordlength > $maxsize) {
988 $output .= $cutchar;
989 $wordlength = 0;
992 $output .= $char;
995 // Finally load the tags back again.
996 if (!empty($tags)) {
997 $output = str_replace(array_keys($tags), $tags, $output);
1000 return $output;
1004 * Try and close the current window using JavaScript, either immediately, or after a delay.
1006 * Echo's out the resulting XHTML & javascript
1008 * @param integer $delay a delay in seconds before closing the window. Default 0.
1009 * @param boolean $reloadopener if true, we will see if this window was a pop-up, and try
1010 * to reload the parent window before this one closes.
1012 function close_window($delay = 0, $reloadopener = false) {
1013 global $PAGE, $OUTPUT;
1015 if (!$PAGE->headerprinted) {
1016 $PAGE->set_title(get_string('closewindow'));
1017 echo $OUTPUT->header();
1018 } else {
1019 $OUTPUT->container_end_all(false);
1022 if ($reloadopener) {
1023 // Trigger the reload immediately, even if the reload is after a delay.
1024 $PAGE->requires->js_function_call('window.opener.location.reload', array(true));
1026 $OUTPUT->notification(get_string('windowclosing'), 'notifysuccess');
1028 $PAGE->requires->js_function_call('close_window', array(new stdClass()), false, $delay);
1030 echo $OUTPUT->footer();
1031 exit;
1035 * Returns a string containing a link to the user documentation for the current page.
1037 * Also contains an icon by default. Shown to teachers and admin only.
1039 * @param string $text The text to be displayed for the link
1040 * @return string The link to user documentation for this current page
1042 function page_doc_link($text='') {
1043 global $OUTPUT, $PAGE;
1044 $path = page_get_doc_link_path($PAGE);
1045 if (!$path) {
1046 return '';
1048 return $OUTPUT->doc_link($path, $text);
1052 * Returns the path to use when constructing a link to the docs.
1054 * @since Moodle 2.5.1 2.6
1055 * @param moodle_page $page
1056 * @return string
1058 function page_get_doc_link_path(moodle_page $page) {
1059 global $CFG;
1061 if (empty($CFG->docroot) || during_initial_install()) {
1062 return '';
1064 if (!has_capability('moodle/site:doclinks', $page->context)) {
1065 return '';
1068 $path = $page->docspath;
1069 if (!$path) {
1070 return '';
1072 return $path;
1077 * Validates an email to make sure it makes sense.
1079 * @param string $address The email address to validate.
1080 * @return boolean
1082 function validate_email($address) {
1084 return (bool)preg_match('#^[-!\#$%&\'*+\\/0-9=?A-Z^_`a-z{|}~]+'.
1085 '(\.[-!\#$%&\'*+\\/0-9=?A-Z^_`a-z{|}~]+)*'.
1086 '@'.
1087 '[-!\#$%&\'*+\\/0-9=?A-Z^_`a-z{|}~]+\.'.
1088 '[-!\#$%&\'*+\\./0-9=?A-Z^_`a-z{|}~]+$#',
1089 $address);
1093 * Extracts file argument either from file parameter or PATH_INFO
1095 * Note: $scriptname parameter is not needed anymore
1097 * @return string file path (only safe characters)
1099 function get_file_argument() {
1100 global $SCRIPT;
1102 $relativepath = false;
1103 $hasforcedslashargs = false;
1105 if (isset($_SERVER['REQUEST_URI']) && !empty($_SERVER['REQUEST_URI'])) {
1106 // Checks whether $_SERVER['REQUEST_URI'] contains '/pluginfile.php/'
1107 // instead of '/pluginfile.php?', when serving a file from e.g. mod_imscp or mod_scorm.
1108 if ((strpos($_SERVER['REQUEST_URI'], '/pluginfile.php/') !== false)
1109 && isset($_SERVER['PATH_INFO']) && !empty($_SERVER['PATH_INFO'])) {
1110 // Exclude edge cases like '/pluginfile.php/?file='.
1111 $args = explode('/', ltrim($_SERVER['PATH_INFO'], '/'));
1112 $hasforcedslashargs = (count($args) > 2); // Always at least: context, component and filearea.
1115 if (!$hasforcedslashargs) {
1116 $relativepath = optional_param('file', false, PARAM_PATH);
1119 if ($relativepath !== false and $relativepath !== '') {
1120 return $relativepath;
1122 $relativepath = false;
1124 // Then try extract file from the slasharguments.
1125 if (stripos($_SERVER['SERVER_SOFTWARE'], 'iis') !== false) {
1126 // NOTE: IIS tends to convert all file paths to single byte DOS encoding,
1127 // we can not use other methods because they break unicode chars,
1128 // the only ways are to use URL rewriting
1129 // OR
1130 // to properly set the 'FastCGIUtf8ServerVariables' registry key.
1131 if (isset($_SERVER['PATH_INFO']) and $_SERVER['PATH_INFO'] !== '') {
1132 // Check that PATH_INFO works == must not contain the script name.
1133 if (strpos($_SERVER['PATH_INFO'], $SCRIPT) === false) {
1134 $relativepath = clean_param(urldecode($_SERVER['PATH_INFO']), PARAM_PATH);
1137 } else {
1138 // All other apache-like servers depend on PATH_INFO.
1139 if (isset($_SERVER['PATH_INFO'])) {
1140 if (isset($_SERVER['SCRIPT_NAME']) and strpos($_SERVER['PATH_INFO'], $_SERVER['SCRIPT_NAME']) === 0) {
1141 $relativepath = substr($_SERVER['PATH_INFO'], strlen($_SERVER['SCRIPT_NAME']));
1142 } else {
1143 $relativepath = $_SERVER['PATH_INFO'];
1145 $relativepath = clean_param($relativepath, PARAM_PATH);
1149 return $relativepath;
1153 * Just returns an array of text formats suitable for a popup menu
1155 * @return array
1157 function format_text_menu() {
1158 return array (FORMAT_MOODLE => get_string('formattext'),
1159 FORMAT_HTML => get_string('formathtml'),
1160 FORMAT_PLAIN => get_string('formatplain'),
1161 FORMAT_MARKDOWN => get_string('formatmarkdown'));
1165 * Given text in a variety of format codings, this function returns the text as safe HTML.
1167 * This function should mainly be used for long strings like posts,
1168 * answers, glossary items etc. For short strings {@link format_string()}.
1170 * <pre>
1171 * Options:
1172 * trusted : If true the string won't be cleaned. Default false required noclean=true.
1173 * noclean : If true the string won't be cleaned. Default false required trusted=true.
1174 * nocache : If true the strign will not be cached and will be formatted every call. Default false.
1175 * filter : If true the string will be run through applicable filters as well. Default true.
1176 * para : If true then the returned string will be wrapped in div tags. Default true.
1177 * newlines : If true then lines newline breaks will be converted to HTML newline breaks. Default true.
1178 * context : The context that will be used for filtering.
1179 * overflowdiv : If set to true the formatted text will be encased in a div
1180 * with the class no-overflow before being returned. Default false.
1181 * allowid : If true then id attributes will not be removed, even when
1182 * using htmlpurifier. Default false.
1183 * blanktarget : If true all <a> tags will have target="_blank" added unless target is explicitly specified.
1184 * </pre>
1186 * @staticvar array $croncache
1187 * @param string $text The text to be formatted. This is raw text originally from user input.
1188 * @param int $format Identifier of the text format to be used
1189 * [FORMAT_MOODLE, FORMAT_HTML, FORMAT_PLAIN, FORMAT_MARKDOWN]
1190 * @param object/array $options text formatting options
1191 * @param int $courseiddonotuse deprecated course id, use context option instead
1192 * @return string
1194 function format_text($text, $format = FORMAT_MOODLE, $options = null, $courseiddonotuse = null) {
1195 global $CFG, $DB, $PAGE;
1197 if ($text === '' || is_null($text)) {
1198 // No need to do any filters and cleaning.
1199 return '';
1202 // Detach object, we can not modify it.
1203 $options = (array)$options;
1205 if (!isset($options['trusted'])) {
1206 $options['trusted'] = false;
1208 if (!isset($options['noclean'])) {
1209 if ($options['trusted'] and trusttext_active()) {
1210 // No cleaning if text trusted and noclean not specified.
1211 $options['noclean'] = true;
1212 } else {
1213 $options['noclean'] = false;
1216 if (!isset($options['nocache'])) {
1217 $options['nocache'] = false;
1219 if (!isset($options['filter'])) {
1220 $options['filter'] = true;
1222 if (!isset($options['para'])) {
1223 $options['para'] = true;
1225 if (!isset($options['newlines'])) {
1226 $options['newlines'] = true;
1228 if (!isset($options['overflowdiv'])) {
1229 $options['overflowdiv'] = false;
1231 $options['blanktarget'] = !empty($options['blanktarget']);
1233 // Calculate best context.
1234 if (empty($CFG->version) or $CFG->version < 2013051400 or during_initial_install()) {
1235 // Do not filter anything during installation or before upgrade completes.
1236 $context = null;
1238 } else if (isset($options['context'])) { // First by explicit passed context option.
1239 if (is_object($options['context'])) {
1240 $context = $options['context'];
1241 } else {
1242 $context = context::instance_by_id($options['context']);
1244 } else if ($courseiddonotuse) {
1245 // Legacy courseid.
1246 $context = context_course::instance($courseiddonotuse);
1247 } else {
1248 // Fallback to $PAGE->context this may be problematic in CLI and other non-standard pages :-(.
1249 $context = $PAGE->context;
1252 if (!$context) {
1253 // Either install/upgrade or something has gone really wrong because context does not exist (yet?).
1254 $options['nocache'] = true;
1255 $options['filter'] = false;
1258 if ($options['filter']) {
1259 $filtermanager = filter_manager::instance();
1260 $filtermanager->setup_page_for_filters($PAGE, $context); // Setup global stuff filters may have.
1261 $filteroptions = array(
1262 'originalformat' => $format,
1263 'noclean' => $options['noclean'],
1265 } else {
1266 $filtermanager = new null_filter_manager();
1267 $filteroptions = array();
1270 switch ($format) {
1271 case FORMAT_HTML:
1272 if (!$options['noclean']) {
1273 $text = clean_text($text, FORMAT_HTML, $options);
1275 $text = $filtermanager->filter_text($text, $context, $filteroptions);
1276 break;
1278 case FORMAT_PLAIN:
1279 $text = s($text); // Cleans dangerous JS.
1280 $text = rebuildnolinktag($text);
1281 $text = str_replace(' ', '&nbsp; ', $text);
1282 $text = nl2br($text);
1283 break;
1285 case FORMAT_WIKI:
1286 // This format is deprecated.
1287 $text = '<p>NOTICE: Wiki-like formatting has been removed from Moodle. You should not be seeing
1288 this message as all texts should have been converted to Markdown format instead.
1289 Please post a bug report to http://moodle.org/bugs with information about where you
1290 saw this message.</p>'.s($text);
1291 break;
1293 case FORMAT_MARKDOWN:
1294 $text = markdown_to_html($text);
1295 if (!$options['noclean']) {
1296 $text = clean_text($text, FORMAT_HTML, $options);
1298 $text = $filtermanager->filter_text($text, $context, $filteroptions);
1299 break;
1301 default: // FORMAT_MOODLE or anything else.
1302 $text = text_to_html($text, null, $options['para'], $options['newlines']);
1303 if (!$options['noclean']) {
1304 $text = clean_text($text, FORMAT_HTML, $options);
1306 $text = $filtermanager->filter_text($text, $context, $filteroptions);
1307 break;
1309 if ($options['filter']) {
1310 // At this point there should not be any draftfile links any more,
1311 // this happens when developers forget to post process the text.
1312 // The only potential problem is that somebody might try to format
1313 // the text before storing into database which would be itself big bug..
1314 $text = str_replace("\"$CFG->wwwroot/draftfile.php", "\"$CFG->wwwroot/brokenfile.php#", $text);
1316 if ($CFG->debugdeveloper) {
1317 if (strpos($text, '@@PLUGINFILE@@/') !== false) {
1318 debugging('Before calling format_text(), the content must be processed with file_rewrite_pluginfile_urls()',
1319 DEBUG_DEVELOPER);
1324 if (!empty($options['overflowdiv'])) {
1325 $text = html_writer::tag('div', $text, array('class' => 'no-overflow'));
1328 if ($options['blanktarget']) {
1329 $domdoc = new DOMDocument();
1330 libxml_use_internal_errors(true);
1331 $domdoc->loadHTML('<?xml version="1.0" encoding="UTF-8" ?>' . $text);
1332 libxml_clear_errors();
1333 foreach ($domdoc->getElementsByTagName('a') as $link) {
1334 if ($link->hasAttribute('target') && strpos($link->getAttribute('target'), '_blank') === false) {
1335 continue;
1337 $link->setAttribute('target', '_blank');
1338 if (strpos($link->getAttribute('rel'), 'noreferrer') === false) {
1339 $link->setAttribute('rel', trim($link->getAttribute('rel') . ' noreferrer'));
1343 // This regex is nasty and I don't like it. The correct way to solve this is by loading the HTML like so:
1344 // $domdoc->loadHTML($text, LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD); however it seems like the libxml
1345 // version that travis uses doesn't work properly and ends up leaving <html><body>, so I'm forced to use
1346 // this regex to remove those tags.
1347 $text = trim(preg_replace('~<(?:!DOCTYPE|/?(?:html|body))[^>]*>\s*~i', '', $domdoc->saveHTML($domdoc->documentElement)));
1350 return $text;
1354 * Resets some data related to filters, called during upgrade or when general filter settings change.
1356 * @param bool $phpunitreset true means called from our PHPUnit integration test reset
1357 * @return void
1359 function reset_text_filters_cache($phpunitreset = false) {
1360 global $CFG, $DB;
1362 if ($phpunitreset) {
1363 // HTMLPurifier does not change, DB is already reset to defaults,
1364 // nothing to do here, the dataroot was cleared too.
1365 return;
1368 // The purge_all_caches() deals with cachedir and localcachedir purging,
1369 // the individual filter caches are invalidated as necessary elsewhere.
1371 // Update $CFG->filterall cache flag.
1372 if (empty($CFG->stringfilters)) {
1373 set_config('filterall', 0);
1374 return;
1376 $installedfilters = core_component::get_plugin_list('filter');
1377 $filters = explode(',', $CFG->stringfilters);
1378 foreach ($filters as $filter) {
1379 if (isset($installedfilters[$filter])) {
1380 set_config('filterall', 1);
1381 return;
1384 set_config('filterall', 0);
1388 * Given a simple string, this function returns the string
1389 * processed by enabled string filters if $CFG->filterall is enabled
1391 * This function should be used to print short strings (non html) that
1392 * need filter processing e.g. activity titles, post subjects,
1393 * glossary concepts.
1395 * @staticvar bool $strcache
1396 * @param string $string The string to be filtered. Should be plain text, expect
1397 * possibly for multilang tags.
1398 * @param boolean $striplinks To strip any link in the result text. Moodle 1.8 default changed from false to true! MDL-8713
1399 * @param array $options options array/object or courseid
1400 * @return string
1402 function format_string($string, $striplinks = true, $options = null) {
1403 global $CFG, $PAGE;
1405 // We'll use a in-memory cache here to speed up repeated strings.
1406 static $strcache = false;
1408 if (empty($CFG->version) or $CFG->version < 2013051400 or during_initial_install()) {
1409 // Do not filter anything during installation or before upgrade completes.
1410 return $string = strip_tags($string);
1413 if ($strcache === false or count($strcache) > 2000) {
1414 // This number might need some tuning to limit memory usage in cron.
1415 $strcache = array();
1418 if (is_numeric($options)) {
1419 // Legacy courseid usage.
1420 $options = array('context' => context_course::instance($options));
1421 } else {
1422 // Detach object, we can not modify it.
1423 $options = (array)$options;
1426 if (empty($options['context'])) {
1427 // Fallback to $PAGE->context this may be problematic in CLI and other non-standard pages :-(.
1428 $options['context'] = $PAGE->context;
1429 } else if (is_numeric($options['context'])) {
1430 $options['context'] = context::instance_by_id($options['context']);
1432 if (!isset($options['filter'])) {
1433 $options['filter'] = true;
1436 $options['escape'] = !isset($options['escape']) || $options['escape'];
1438 if (!$options['context']) {
1439 // We did not find any context? weird.
1440 return $string = strip_tags($string);
1443 // Calculate md5.
1444 $md5 = md5($string.'<+>'.$striplinks.'<+>'.$options['context']->id.'<+>'.$options['escape'].'<+>'.current_language());
1446 // Fetch from cache if possible.
1447 if (isset($strcache[$md5])) {
1448 return $strcache[$md5];
1451 // First replace all ampersands not followed by html entity code
1452 // Regular expression moved to its own method for easier unit testing.
1453 $string = $options['escape'] ? replace_ampersands_not_followed_by_entity($string) : $string;
1455 if (!empty($CFG->filterall) && $options['filter']) {
1456 $filtermanager = filter_manager::instance();
1457 $filtermanager->setup_page_for_filters($PAGE, $options['context']); // Setup global stuff filters may have.
1458 $string = $filtermanager->filter_string($string, $options['context']);
1461 // If the site requires it, strip ALL tags from this string.
1462 if (!empty($CFG->formatstringstriptags)) {
1463 if ($options['escape']) {
1464 $string = str_replace(array('<', '>'), array('&lt;', '&gt;'), strip_tags($string));
1465 } else {
1466 $string = strip_tags($string);
1468 } else {
1469 // Otherwise strip just links if that is required (default).
1470 if ($striplinks) {
1471 // Strip links in string.
1472 $string = strip_links($string);
1474 $string = clean_text($string);
1477 // Store to cache.
1478 $strcache[$md5] = $string;
1480 return $string;
1484 * Given a string, performs a negative lookahead looking for any ampersand character
1485 * that is not followed by a proper HTML entity. If any is found, it is replaced
1486 * by &amp;. The string is then returned.
1488 * @param string $string
1489 * @return string
1491 function replace_ampersands_not_followed_by_entity($string) {
1492 return preg_replace("/\&(?![a-zA-Z0-9#]{1,8};)/", "&amp;", $string);
1496 * Given a string, replaces all <a>.*</a> by .* and returns the string.
1498 * @param string $string
1499 * @return string
1501 function strip_links($string) {
1502 return preg_replace('/(<a\s[^>]+?>)(.+?)(<\/a>)/is', '$2', $string);
1506 * This expression turns links into something nice in a text format. (Russell Jungwirth)
1508 * @param string $string
1509 * @return string
1511 function wikify_links($string) {
1512 return preg_replace('~(<a [^<]*href=["|\']?([^ "\']*)["|\']?[^>]*>([^<]*)</a>)~i', '$3 [ $2 ]', $string);
1516 * Given text in a variety of format codings, this function returns the text as plain text suitable for plain email.
1518 * @param string $text The text to be formatted. This is raw text originally from user input.
1519 * @param int $format Identifier of the text format to be used
1520 * [FORMAT_MOODLE, FORMAT_HTML, FORMAT_PLAIN, FORMAT_WIKI, FORMAT_MARKDOWN]
1521 * @return string
1523 function format_text_email($text, $format) {
1525 switch ($format) {
1527 case FORMAT_PLAIN:
1528 return $text;
1529 break;
1531 case FORMAT_WIKI:
1532 // There should not be any of these any more!
1533 $text = wikify_links($text);
1534 return core_text::entities_to_utf8(strip_tags($text), true);
1535 break;
1537 case FORMAT_HTML:
1538 return html_to_text($text);
1539 break;
1541 case FORMAT_MOODLE:
1542 case FORMAT_MARKDOWN:
1543 default:
1544 $text = wikify_links($text);
1545 return core_text::entities_to_utf8(strip_tags($text), true);
1546 break;
1551 * Formats activity intro text
1553 * @param string $module name of module
1554 * @param object $activity instance of activity
1555 * @param int $cmid course module id
1556 * @param bool $filter filter resulting html text
1557 * @return string
1559 function format_module_intro($module, $activity, $cmid, $filter=true) {
1560 global $CFG;
1561 require_once("$CFG->libdir/filelib.php");
1562 $context = context_module::instance($cmid);
1563 $options = array('noclean' => true, 'para' => false, 'filter' => $filter, 'context' => $context, 'overflowdiv' => true);
1564 $intro = file_rewrite_pluginfile_urls($activity->intro, 'pluginfile.php', $context->id, 'mod_'.$module, 'intro', null);
1565 return trim(format_text($intro, $activity->introformat, $options, null));
1569 * Removes the usage of Moodle files from a text.
1571 * In some rare cases we need to re-use a text that already has embedded links
1572 * to some files hosted within Moodle. But the new area in which we will push
1573 * this content does not support files... therefore we need to remove those files.
1575 * @param string $source The text
1576 * @return string The stripped text
1578 function strip_pluginfile_content($source) {
1579 $baseurl = '@@PLUGINFILE@@';
1580 // Looking for something like < .* "@@pluginfile@@.*" .* >
1581 $pattern = '$<[^<>]+["\']' . $baseurl . '[^"\']*["\'][^<>]*>$';
1582 $stripped = preg_replace($pattern, '', $source);
1583 // Use purify html to rebalence potentially mismatched tags and generally cleanup.
1584 return purify_html($stripped);
1588 * Legacy function, used for cleaning of old forum and glossary text only.
1590 * @param string $text text that may contain legacy TRUSTTEXT marker
1591 * @return string text without legacy TRUSTTEXT marker
1593 function trusttext_strip($text) {
1594 if (!is_string($text)) {
1595 // This avoids the potential for an endless loop below.
1596 throw new coding_exception('trusttext_strip parameter must be a string');
1598 while (true) { // Removing nested TRUSTTEXT.
1599 $orig = $text;
1600 $text = str_replace('#####TRUSTTEXT#####', '', $text);
1601 if (strcmp($orig, $text) === 0) {
1602 return $text;
1608 * Must be called before editing of all texts with trust flag. Removes all XSS nasties from texts stored in database if needed.
1610 * @param stdClass $object data object with xxx, xxxformat and xxxtrust fields
1611 * @param string $field name of text field
1612 * @param context $context active context
1613 * @return stdClass updated $object
1615 function trusttext_pre_edit($object, $field, $context) {
1616 $trustfield = $field.'trust';
1617 $formatfield = $field.'format';
1619 if (!$object->$trustfield or !trusttext_trusted($context)) {
1620 $object->$field = clean_text($object->$field, $object->$formatfield);
1623 return $object;
1627 * Is current user trusted to enter no dangerous XSS in this context?
1629 * Please note the user must be in fact trusted everywhere on this server!!
1631 * @param context $context
1632 * @return bool true if user trusted
1634 function trusttext_trusted($context) {
1635 return (trusttext_active() and has_capability('moodle/site:trustcontent', $context));
1639 * Is trusttext feature active?
1641 * @return bool
1643 function trusttext_active() {
1644 global $CFG;
1646 return !empty($CFG->enabletrusttext);
1650 * Cleans raw text removing nasties.
1652 * Given raw text (eg typed in by a user) this function cleans it up and removes any nasty tags that could mess up
1653 * Moodle pages through XSS attacks.
1655 * The result must be used as a HTML text fragment, this function can not cleanup random
1656 * parts of html tags such as url or src attributes.
1658 * NOTE: the format parameter was deprecated because we can safely clean only HTML.
1660 * @param string $text The text to be cleaned
1661 * @param int|string $format deprecated parameter, should always contain FORMAT_HTML or FORMAT_MOODLE
1662 * @param array $options Array of options; currently only option supported is 'allowid' (if true,
1663 * does not remove id attributes when cleaning)
1664 * @return string The cleaned up text
1666 function clean_text($text, $format = FORMAT_HTML, $options = array()) {
1667 $text = (string)$text;
1669 if ($format != FORMAT_HTML and $format != FORMAT_HTML) {
1670 // TODO: we need to standardise cleanup of text when loading it into editor first.
1671 // debugging('clean_text() is designed to work only with html');.
1674 if ($format == FORMAT_PLAIN) {
1675 return $text;
1678 if (is_purify_html_necessary($text)) {
1679 $text = purify_html($text, $options);
1682 // Originally we tried to neutralise some script events here, it was a wrong approach because
1683 // it was trivial to work around that (for example using style based XSS exploits).
1684 // We must not give false sense of security here - all developers MUST understand how to use
1685 // rawurlencode(), htmlentities(), htmlspecialchars(), p(), s(), moodle_url, html_writer and friends!!!
1687 return $text;
1691 * Is it necessary to use HTMLPurifier?
1693 * @private
1694 * @param string $text
1695 * @return bool false means html is safe and valid, true means use HTMLPurifier
1697 function is_purify_html_necessary($text) {
1698 if ($text === '') {
1699 return false;
1702 if ($text === (string)((int)$text)) {
1703 return false;
1706 if (strpos($text, '&') !== false or preg_match('|<[^pesb/]|', $text)) {
1707 // We need to normalise entities or other tags except p, em, strong and br present.
1708 return true;
1711 $altered = htmlspecialchars($text, ENT_NOQUOTES, 'UTF-8', true);
1712 if ($altered === $text) {
1713 // No < > or other special chars means this must be safe.
1714 return false;
1717 // Let's try to convert back some safe html tags.
1718 $altered = preg_replace('|&lt;p&gt;(.*?)&lt;/p&gt;|m', '<p>$1</p>', $altered);
1719 if ($altered === $text) {
1720 return false;
1722 $altered = preg_replace('|&lt;em&gt;([^<>]+?)&lt;/em&gt;|m', '<em>$1</em>', $altered);
1723 if ($altered === $text) {
1724 return false;
1726 $altered = preg_replace('|&lt;strong&gt;([^<>]+?)&lt;/strong&gt;|m', '<strong>$1</strong>', $altered);
1727 if ($altered === $text) {
1728 return false;
1730 $altered = str_replace('&lt;br /&gt;', '<br />', $altered);
1731 if ($altered === $text) {
1732 return false;
1735 return true;
1739 * KSES replacement cleaning function - uses HTML Purifier.
1741 * @param string $text The (X)HTML string to purify
1742 * @param array $options Array of options; currently only option supported is 'allowid' (if set,
1743 * does not remove id attributes when cleaning)
1744 * @return string
1746 function purify_html($text, $options = array()) {
1747 global $CFG;
1749 $text = (string)$text;
1751 static $purifiers = array();
1752 static $caches = array();
1754 // Purifier code can change only during major version upgrade.
1755 $version = empty($CFG->version) ? 0 : $CFG->version;
1756 $cachedir = "$CFG->localcachedir/htmlpurifier/$version";
1757 if (!file_exists($cachedir)) {
1758 // Purging of caches may remove the cache dir at any time,
1759 // luckily file_exists() results should be cached for all existing directories.
1760 $purifiers = array();
1761 $caches = array();
1762 gc_collect_cycles();
1764 make_localcache_directory('htmlpurifier', false);
1765 check_dir_exists($cachedir);
1768 $allowid = empty($options['allowid']) ? 0 : 1;
1769 $allowobjectembed = empty($CFG->allowobjectembed) ? 0 : 1;
1771 $type = 'type_'.$allowid.'_'.$allowobjectembed;
1773 if (!array_key_exists($type, $caches)) {
1774 $caches[$type] = cache::make('core', 'htmlpurifier', array('type' => $type));
1776 $cache = $caches[$type];
1778 // Add revision number and all options to the text key so that it is compatible with local cluster node caches.
1779 $key = "|$version|$allowobjectembed|$allowid|$text";
1780 $filteredtext = $cache->get($key);
1782 if ($filteredtext === true) {
1783 // The filtering did not change the text last time, no need to filter anything again.
1784 return $text;
1785 } else if ($filteredtext !== false) {
1786 return $filteredtext;
1789 if (empty($purifiers[$type])) {
1790 require_once $CFG->libdir.'/htmlpurifier/HTMLPurifier.safe-includes.php';
1791 require_once $CFG->libdir.'/htmlpurifier/locallib.php';
1792 $config = HTMLPurifier_Config::createDefault();
1794 $config->set('HTML.DefinitionID', 'moodlehtml');
1795 $config->set('HTML.DefinitionRev', 6);
1796 $config->set('Cache.SerializerPath', $cachedir);
1797 $config->set('Cache.SerializerPermissions', $CFG->directorypermissions);
1798 $config->set('Core.NormalizeNewlines', false);
1799 $config->set('Core.ConvertDocumentToFragment', true);
1800 $config->set('Core.Encoding', 'UTF-8');
1801 $config->set('HTML.Doctype', 'XHTML 1.0 Transitional');
1802 $config->set('URI.AllowedSchemes', array(
1803 'http' => true,
1804 'https' => true,
1805 'ftp' => true,
1806 'irc' => true,
1807 'nntp' => true,
1808 'news' => true,
1809 'rtsp' => true,
1810 'rtmp' => true,
1811 'teamspeak' => true,
1812 'gopher' => true,
1813 'mms' => true,
1814 'mailto' => true
1816 $config->set('Attr.AllowedFrameTargets', array('_blank'));
1818 if ($allowobjectembed) {
1819 $config->set('HTML.SafeObject', true);
1820 $config->set('Output.FlashCompat', true);
1821 $config->set('HTML.SafeEmbed', true);
1824 if ($allowid) {
1825 $config->set('Attr.EnableID', true);
1828 if ($def = $config->maybeGetRawHTMLDefinition()) {
1829 $def->addElement('nolink', 'Block', 'Flow', array()); // Skip our filters inside.
1830 $def->addElement('tex', 'Inline', 'Inline', array()); // Tex syntax, equivalent to $$xx$$.
1831 $def->addElement('algebra', 'Inline', 'Inline', array()); // Algebra syntax, equivalent to @@xx@@.
1832 $def->addElement('lang', 'Block', 'Flow', array(), array('lang'=>'CDATA')); // Original multilang style - only our hacked lang attribute.
1833 $def->addAttribute('span', 'xxxlang', 'CDATA'); // Current very problematic multilang.
1835 // Media elements.
1836 // https://html.spec.whatwg.org/#the-video-element
1837 $def->addElement('video', 'Block', 'Optional: #PCDATA | Flow | source | track', 'Common', [
1838 'src' => 'URI',
1839 'crossorigin' => 'Enum#anonymous,use-credentials',
1840 'poster' => 'URI',
1841 'preload' => 'Enum#auto,metadata,none',
1842 'autoplay' => 'Bool',
1843 'playsinline' => 'Bool',
1844 'loop' => 'Bool',
1845 'muted' => 'Bool',
1846 'controls' => 'Bool',
1847 'width' => 'Length',
1848 'height' => 'Length',
1850 // https://html.spec.whatwg.org/#the-audio-element
1851 $def->addElement('audio', 'Block', 'Optional: #PCDATA | Flow | source | track', 'Common', [
1852 'src' => 'URI',
1853 'crossorigin' => 'Enum#anonymous,use-credentials',
1854 'preload' => 'Enum#auto,metadata,none',
1855 'autoplay' => 'Bool',
1856 'loop' => 'Bool',
1857 'muted' => 'Bool',
1858 'controls' => 'Bool'
1860 // https://html.spec.whatwg.org/#the-source-element
1861 $def->addElement('source', false, 'Empty', null, [
1862 'src' => 'URI',
1863 'type' => 'Text'
1865 // https://html.spec.whatwg.org/#the-track-element
1866 $def->addElement('track', false, 'Empty', null, [
1867 'src' => 'URI',
1868 'kind' => 'Enum#subtitles,captions,descriptions,chapters,metadata',
1869 'srclang' => 'Text',
1870 'label' => 'Text',
1871 'default' => 'Bool',
1874 // Use the built-in Ruby module to add annotation support.
1875 $def->manager->addModule(new HTMLPurifier_HTMLModule_Ruby());
1878 $purifier = new HTMLPurifier($config);
1879 $purifiers[$type] = $purifier;
1880 } else {
1881 $purifier = $purifiers[$type];
1884 $multilang = (strpos($text, 'class="multilang"') !== false);
1886 $filteredtext = $text;
1887 if ($multilang) {
1888 $filteredtextregex = '/<span(\s+lang="([a-zA-Z0-9_-]+)"|\s+class="multilang"){2}\s*>/';
1889 $filteredtext = preg_replace($filteredtextregex, '<span xxxlang="${2}">', $filteredtext);
1891 $filteredtext = (string)$purifier->purify($filteredtext);
1892 if ($multilang) {
1893 $filteredtext = preg_replace('/<span xxxlang="([a-zA-Z0-9_-]+)">/', '<span lang="${1}" class="multilang">', $filteredtext);
1896 if ($text === $filteredtext) {
1897 // No need to store the filtered text, next time we will just return unfiltered text
1898 // because it was not changed by purifying.
1899 $cache->set($key, true);
1900 } else {
1901 $cache->set($key, $filteredtext);
1904 return $filteredtext;
1908 * Given plain text, makes it into HTML as nicely as possible.
1910 * May contain HTML tags already.
1912 * Do not abuse this function. It is intended as lower level formatting feature used
1913 * by {@link format_text()} to convert FORMAT_MOODLE to HTML. You are supposed
1914 * to call format_text() in most of cases.
1916 * @param string $text The string to convert.
1917 * @param boolean $smileyignored Was used to determine if smiley characters should convert to smiley images, ignored now
1918 * @param boolean $para If true then the returned string will be wrapped in div tags
1919 * @param boolean $newlines If true then lines newline breaks will be converted to HTML newline breaks.
1920 * @return string
1922 function text_to_html($text, $smileyignored = null, $para = true, $newlines = true) {
1923 // Remove any whitespace that may be between HTML tags.
1924 $text = preg_replace("~>([[:space:]]+)<~i", "><", $text);
1926 // Remove any returns that precede or follow HTML tags.
1927 $text = preg_replace("~([\n\r])<~i", " <", $text);
1928 $text = preg_replace("~>([\n\r])~i", "> ", $text);
1930 // Make returns into HTML newlines.
1931 if ($newlines) {
1932 $text = nl2br($text);
1935 // Wrap the whole thing in a div if required.
1936 if ($para) {
1937 // In 1.9 this was changed from a p => div.
1938 return '<div class="text_to_html">'.$text.'</div>';
1939 } else {
1940 return $text;
1945 * Given Markdown formatted text, make it into XHTML using external function
1947 * @param string $text The markdown formatted text to be converted.
1948 * @return string Converted text
1950 function markdown_to_html($text) {
1951 global $CFG;
1953 if ($text === '' or $text === null) {
1954 return $text;
1957 require_once($CFG->libdir .'/markdown/MarkdownInterface.php');
1958 require_once($CFG->libdir .'/markdown/Markdown.php');
1959 require_once($CFG->libdir .'/markdown/MarkdownExtra.php');
1961 return \Michelf\MarkdownExtra::defaultTransform($text);
1965 * Given HTML text, make it into plain text using external function
1967 * @param string $html The text to be converted.
1968 * @param integer $width Width to wrap the text at. (optional, default 75 which
1969 * is a good value for email. 0 means do not limit line length.)
1970 * @param boolean $dolinks By default, any links in the HTML are collected, and
1971 * printed as a list at the end of the HTML. If you don't want that, set this
1972 * argument to false.
1973 * @return string plain text equivalent of the HTML.
1975 function html_to_text($html, $width = 75, $dolinks = true) {
1976 global $CFG;
1978 require_once($CFG->libdir .'/html2text/lib.php');
1980 $options = array(
1981 'width' => $width,
1982 'do_links' => 'table',
1985 if (empty($dolinks)) {
1986 $options['do_links'] = 'none';
1988 $h2t = new core_html2text($html, $options);
1989 $result = $h2t->getText();
1991 return $result;
1995 * Converts texts or strings to plain text.
1997 * - When used to convert user input introduced in an editor the text format needs to be passed in $contentformat like we usually
1998 * do in format_text.
1999 * - When this function is used for strings that are usually passed through format_string before displaying them
2000 * we need to set $contentformat to false. This will execute html_to_text as these strings can contain multilang tags if
2001 * multilang filter is applied to headings.
2003 * @param string $content The text as entered by the user
2004 * @param int|false $contentformat False for strings or the text format: FORMAT_MOODLE/FORMAT_HTML/FORMAT_PLAIN/FORMAT_MARKDOWN
2005 * @return string Plain text.
2007 function content_to_text($content, $contentformat) {
2009 switch ($contentformat) {
2010 case FORMAT_PLAIN:
2011 // Nothing here.
2012 break;
2013 case FORMAT_MARKDOWN:
2014 $content = markdown_to_html($content);
2015 $content = html_to_text($content, 75, false);
2016 break;
2017 default:
2018 // FORMAT_HTML, FORMAT_MOODLE and $contentformat = false, the later one are strings usually formatted through
2019 // format_string, we need to convert them from html because they can contain HTML (multilang filter).
2020 $content = html_to_text($content, 75, false);
2023 return trim($content, "\r\n ");
2027 * This function will highlight search words in a given string
2029 * It cares about HTML and will not ruin links. It's best to use
2030 * this function after performing any conversions to HTML.
2032 * @param string $needle The search string. Syntax like "word1 +word2 -word3" is dealt with correctly.
2033 * @param string $haystack The string (HTML) within which to highlight the search terms.
2034 * @param boolean $matchcase whether to do case-sensitive. Default case-insensitive.
2035 * @param string $prefix the string to put before each search term found.
2036 * @param string $suffix the string to put after each search term found.
2037 * @return string The highlighted HTML.
2039 function highlight($needle, $haystack, $matchcase = false,
2040 $prefix = '<span class="highlight">', $suffix = '</span>') {
2042 // Quick bail-out in trivial cases.
2043 if (empty($needle) or empty($haystack)) {
2044 return $haystack;
2047 // Break up the search term into words, discard any -words and build a regexp.
2048 $words = preg_split('/ +/', trim($needle));
2049 foreach ($words as $index => $word) {
2050 if (strpos($word, '-') === 0) {
2051 unset($words[$index]);
2052 } else if (strpos($word, '+') === 0) {
2053 $words[$index] = '\b' . preg_quote(ltrim($word, '+'), '/') . '\b'; // Match only as a complete word.
2054 } else {
2055 $words[$index] = preg_quote($word, '/');
2058 $regexp = '/(' . implode('|', $words) . ')/u'; // Char u is to do UTF-8 matching.
2059 if (!$matchcase) {
2060 $regexp .= 'i';
2063 // Another chance to bail-out if $search was only -words.
2064 if (empty($words)) {
2065 return $haystack;
2068 // Split the string into HTML tags and real content.
2069 $chunks = preg_split('/((?:<[^>]*>)+)/', $haystack, -1, PREG_SPLIT_DELIM_CAPTURE);
2071 // We have an array of alternating blocks of text, then HTML tags, then text, ...
2072 // Loop through replacing search terms in the text, and leaving the HTML unchanged.
2073 $ishtmlchunk = false;
2074 $result = '';
2075 foreach ($chunks as $chunk) {
2076 if ($ishtmlchunk) {
2077 $result .= $chunk;
2078 } else {
2079 $result .= preg_replace($regexp, $prefix . '$1' . $suffix, $chunk);
2081 $ishtmlchunk = !$ishtmlchunk;
2084 return $result;
2088 * This function will highlight instances of $needle in $haystack
2090 * It's faster that the above function {@link highlight()} and doesn't care about
2091 * HTML or anything.
2093 * @param string $needle The string to search for
2094 * @param string $haystack The string to search for $needle in
2095 * @return string The highlighted HTML
2097 function highlightfast($needle, $haystack) {
2099 if (empty($needle) or empty($haystack)) {
2100 return $haystack;
2103 $parts = explode(core_text::strtolower($needle), core_text::strtolower($haystack));
2105 if (count($parts) === 1) {
2106 return $haystack;
2109 $pos = 0;
2111 foreach ($parts as $key => $part) {
2112 $parts[$key] = substr($haystack, $pos, strlen($part));
2113 $pos += strlen($part);
2115 $parts[$key] .= '<span class="highlight">'.substr($haystack, $pos, strlen($needle)).'</span>';
2116 $pos += strlen($needle);
2119 return str_replace('<span class="highlight"></span>', '', join('', $parts));
2123 * Return a string containing 'lang', xml:lang and optionally 'dir' HTML attributes.
2125 * Internationalisation, for print_header and backup/restorelib.
2127 * @param bool $dir Default false
2128 * @return string Attributes
2130 function get_html_lang($dir = false) {
2131 $direction = '';
2132 if ($dir) {
2133 if (right_to_left()) {
2134 $direction = ' dir="rtl"';
2135 } else {
2136 $direction = ' dir="ltr"';
2139 // Accessibility: added the 'lang' attribute to $direction, used in theme <html> tag.
2140 $language = str_replace('_', '-', current_language());
2141 @header('Content-Language: '.$language);
2142 return ($direction.' lang="'.$language.'" xml:lang="'.$language.'"');
2146 // STANDARD WEB PAGE PARTS.
2149 * Send the HTTP headers that Moodle requires.
2151 * There is a backwards compatibility hack for legacy code
2152 * that needs to add custom IE compatibility directive.
2154 * Example:
2155 * <code>
2156 * if (!isset($CFG->additionalhtmlhead)) {
2157 * $CFG->additionalhtmlhead = '';
2159 * $CFG->additionalhtmlhead .= '<meta http-equiv="X-UA-Compatible" content="IE=8" />';
2160 * header('X-UA-Compatible: IE=8');
2161 * echo $OUTPUT->header();
2162 * </code>
2164 * Please note the $CFG->additionalhtmlhead alone might not work,
2165 * you should send the IE compatibility header() too.
2167 * @param string $contenttype
2168 * @param bool $cacheable Can this page be cached on back?
2169 * @return void, sends HTTP headers
2171 function send_headers($contenttype, $cacheable = true) {
2172 global $CFG;
2174 @header('Content-Type: ' . $contenttype);
2175 @header('Content-Script-Type: text/javascript');
2176 @header('Content-Style-Type: text/css');
2178 if (empty($CFG->additionalhtmlhead) or stripos($CFG->additionalhtmlhead, 'X-UA-Compatible') === false) {
2179 @header('X-UA-Compatible: IE=edge');
2182 if ($cacheable) {
2183 // Allow caching on "back" (but not on normal clicks).
2184 @header('Cache-Control: private, pre-check=0, post-check=0, max-age=0, no-transform');
2185 @header('Pragma: no-cache');
2186 @header('Expires: ');
2187 } else {
2188 // Do everything we can to always prevent clients and proxies caching.
2189 @header('Cache-Control: no-store, no-cache, must-revalidate');
2190 @header('Cache-Control: post-check=0, pre-check=0, no-transform', false);
2191 @header('Pragma: no-cache');
2192 @header('Expires: Mon, 20 Aug 1969 09:23:00 GMT');
2193 @header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
2195 @header('Accept-Ranges: none');
2197 if (empty($CFG->allowframembedding)) {
2198 @header('X-Frame-Options: sameorigin');
2203 * Return the right arrow with text ('next'), and optionally embedded in a link.
2205 * @param string $text HTML/plain text label (set to blank only for breadcrumb separator cases).
2206 * @param string $url An optional link to use in a surrounding HTML anchor.
2207 * @param bool $accesshide True if text should be hidden (for screen readers only).
2208 * @param string $addclass Additional class names for the link, or the arrow character.
2209 * @return string HTML string.
2211 function link_arrow_right($text, $url='', $accesshide=false, $addclass='', $addparams = []) {
2212 global $OUTPUT; // TODO: move to output renderer.
2213 $arrowclass = 'arrow ';
2214 if (!$url) {
2215 $arrowclass .= $addclass;
2217 $arrow = '<span class="'.$arrowclass.'">'.$OUTPUT->rarrow().'</span>';
2218 $htmltext = '';
2219 if ($text) {
2220 $htmltext = '<span class="arrow_text">'.$text.'</span>&nbsp;';
2221 if ($accesshide) {
2222 $htmltext = get_accesshide($htmltext);
2225 if ($url) {
2226 $class = 'arrow_link';
2227 if ($addclass) {
2228 $class .= ' '.$addclass;
2231 $linkparams = [
2232 'class' => $class,
2233 'href' => $url,
2234 'title' => preg_replace('/<.*?>/', '', $text),
2237 $linkparams += $addparams;
2239 return html_writer::link($url, $htmltext . $arrow, $linkparams);
2241 return $htmltext.$arrow;
2245 * Return the left arrow with text ('previous'), and optionally embedded in a link.
2247 * @param string $text HTML/plain text label (set to blank only for breadcrumb separator cases).
2248 * @param string $url An optional link to use in a surrounding HTML anchor.
2249 * @param bool $accesshide True if text should be hidden (for screen readers only).
2250 * @param string $addclass Additional class names for the link, or the arrow character.
2251 * @return string HTML string.
2253 function link_arrow_left($text, $url='', $accesshide=false, $addclass='', $addparams = []) {
2254 global $OUTPUT; // TODO: move to utput renderer.
2255 $arrowclass = 'arrow ';
2256 if (! $url) {
2257 $arrowclass .= $addclass;
2259 $arrow = '<span class="'.$arrowclass.'">'.$OUTPUT->larrow().'</span>';
2260 $htmltext = '';
2261 if ($text) {
2262 $htmltext = '&nbsp;<span class="arrow_text">'.$text.'</span>';
2263 if ($accesshide) {
2264 $htmltext = get_accesshide($htmltext);
2267 if ($url) {
2268 $class = 'arrow_link';
2269 if ($addclass) {
2270 $class .= ' '.$addclass;
2273 $linkparams = [
2274 'class' => $class,
2275 'href' => $url,
2276 'title' => preg_replace('/<.*?>/', '', $text),
2279 $linkparams += $addparams;
2281 return html_writer::link($url, $arrow . $htmltext, $linkparams);
2283 return $arrow.$htmltext;
2287 * Return a HTML element with the class "accesshide", for accessibility.
2289 * Please use cautiously - where possible, text should be visible!
2291 * @param string $text Plain text.
2292 * @param string $elem Lowercase element name, default "span".
2293 * @param string $class Additional classes for the element.
2294 * @param string $attrs Additional attributes string in the form, "name='value' name2='value2'"
2295 * @return string HTML string.
2297 function get_accesshide($text, $elem='span', $class='', $attrs='') {
2298 return "<$elem class=\"accesshide $class\" $attrs>$text</$elem>";
2302 * Return the breadcrumb trail navigation separator.
2304 * @return string HTML string.
2306 function get_separator() {
2307 // Accessibility: the 'hidden' slash is preferred for screen readers.
2308 return ' '.link_arrow_right($text='/', $url='', $accesshide=true, 'sep').' ';
2312 * Print (or return) a collapsible region, that has a caption that can be clicked to expand or collapse the region.
2314 * If JavaScript is off, then the region will always be expanded.
2316 * @param string $contents the contents of the box.
2317 * @param string $classes class names added to the div that is output.
2318 * @param string $id id added to the div that is output. Must not be blank.
2319 * @param string $caption text displayed at the top. Clicking on this will cause the region to expand or contract.
2320 * @param string $userpref the name of the user preference that stores the user's preferred default state.
2321 * (May be blank if you do not wish the state to be persisted.
2322 * @param boolean $default Initial collapsed state to use if the user_preference it not set.
2323 * @param boolean $return if true, return the HTML as a string, rather than printing it.
2324 * @return string|void If $return is false, returns nothing, otherwise returns a string of HTML.
2326 function print_collapsible_region($contents, $classes, $id, $caption, $userpref = '', $default = false, $return = false) {
2327 $output = print_collapsible_region_start($classes, $id, $caption, $userpref, $default, true);
2328 $output .= $contents;
2329 $output .= print_collapsible_region_end(true);
2331 if ($return) {
2332 return $output;
2333 } else {
2334 echo $output;
2339 * Print (or return) the start of a collapsible region
2341 * The collapsibleregion has a caption that can be clicked to expand or collapse the region. If JavaScript is off, then the region
2342 * will always be expanded.
2344 * @param string $classes class names added to the div that is output.
2345 * @param string $id id added to the div that is output. Must not be blank.
2346 * @param string $caption text displayed at the top. Clicking on this will cause the region to expand or contract.
2347 * @param string $userpref the name of the user preference that stores the user's preferred default state.
2348 * (May be blank if you do not wish the state to be persisted.
2349 * @param boolean $default Initial collapsed state to use if the user_preference it not set.
2350 * @param boolean $return if true, return the HTML as a string, rather than printing it.
2351 * @return string|void if $return is false, returns nothing, otherwise returns a string of HTML.
2353 function print_collapsible_region_start($classes, $id, $caption, $userpref = '', $default = false, $return = false) {
2354 global $PAGE;
2356 // Work out the initial state.
2357 if (!empty($userpref) and is_string($userpref)) {
2358 user_preference_allow_ajax_update($userpref, PARAM_BOOL);
2359 $collapsed = get_user_preferences($userpref, $default);
2360 } else {
2361 $collapsed = $default;
2362 $userpref = false;
2365 if ($collapsed) {
2366 $classes .= ' collapsed';
2369 $output = '';
2370 $output .= '<div id="' . $id . '" class="collapsibleregion ' . $classes . '">';
2371 $output .= '<div id="' . $id . '_sizer">';
2372 $output .= '<div id="' . $id . '_caption" class="collapsibleregioncaption">';
2373 $output .= $caption . ' ';
2374 $output .= '</div><div id="' . $id . '_inner" class="collapsibleregioninner">';
2375 $PAGE->requires->js_init_call('M.util.init_collapsible_region', array($id, $userpref, get_string('clicktohideshow')));
2377 if ($return) {
2378 return $output;
2379 } else {
2380 echo $output;
2385 * Close a region started with print_collapsible_region_start.
2387 * @param boolean $return if true, return the HTML as a string, rather than printing it.
2388 * @return string|void if $return is false, returns nothing, otherwise returns a string of HTML.
2390 function print_collapsible_region_end($return = false) {
2391 $output = '</div></div></div>';
2393 if ($return) {
2394 return $output;
2395 } else {
2396 echo $output;
2401 * Print a specified group's avatar.
2403 * @param array|stdClass $group A single {@link group} object OR array of groups.
2404 * @param int $courseid The course ID.
2405 * @param boolean $large Default small picture, or large.
2406 * @param boolean $return If false print picture, otherwise return the output as string
2407 * @param boolean $link Enclose image in a link to view specified course?
2408 * @return string|void Depending on the setting of $return
2410 function print_group_picture($group, $courseid, $large=false, $return=false, $link=true) {
2411 global $CFG;
2413 if (is_array($group)) {
2414 $output = '';
2415 foreach ($group as $g) {
2416 $output .= print_group_picture($g, $courseid, $large, true, $link);
2418 if ($return) {
2419 return $output;
2420 } else {
2421 echo $output;
2422 return;
2426 $pictureurl = get_group_picture_url($group, $courseid, $large);
2428 // If there is no picture, do nothing.
2429 if (!isset($pictureurl)) {
2430 return;
2433 $context = context_course::instance($courseid);
2435 $groupname = s($group->name);
2436 $pictureimage = html_writer::img($pictureurl, $groupname, ['title' => $groupname]);
2438 $output = '';
2439 if ($link or has_capability('moodle/site:accessallgroups', $context)) {
2440 $linkurl = new moodle_url('/user/index.php', ['id' => $courseid, 'group' => $group->id]);
2441 $output .= html_writer::link($linkurl, $pictureimage);
2442 } else {
2443 $output .= $pictureimage;
2446 if ($return) {
2447 return $output;
2448 } else {
2449 echo $output;
2454 * Return the url to the group picture.
2456 * @param stdClass $group A group object.
2457 * @param int $courseid The course ID for the group.
2458 * @param bool $large A large or small group picture? Default is small.
2459 * @return moodle_url Returns the url for the group picture.
2461 function get_group_picture_url($group, $courseid, $large = false) {
2462 global $CFG;
2464 $context = context_course::instance($courseid);
2466 // If there is no picture, do nothing.
2467 if (!$group->picture) {
2468 return;
2471 // If picture is hidden, only show to those with course:managegroups.
2472 if ($group->hidepicture and !has_capability('moodle/course:managegroups', $context)) {
2473 return;
2476 if ($large) {
2477 $file = 'f1';
2478 } else {
2479 $file = 'f2';
2482 $grouppictureurl = moodle_url::make_pluginfile_url($context->id, 'group', 'icon', $group->id, '/', $file);
2483 $grouppictureurl->param('rev', $group->picture);
2484 return $grouppictureurl;
2489 * Display a recent activity note
2491 * @staticvar string $strftimerecent
2492 * @param int $time A timestamp int.
2493 * @param stdClass $user A user object from the database.
2494 * @param string $text Text for display for the note
2495 * @param string $link The link to wrap around the text
2496 * @param bool $return If set to true the HTML is returned rather than echo'd
2497 * @param string $viewfullnames
2498 * @return string If $retrun was true returns HTML for a recent activity notice.
2500 function print_recent_activity_note($time, $user, $text, $link, $return=false, $viewfullnames=null) {
2501 static $strftimerecent = null;
2502 $output = '';
2504 if (is_null($viewfullnames)) {
2505 $context = context_system::instance();
2506 $viewfullnames = has_capability('moodle/site:viewfullnames', $context);
2509 if (is_null($strftimerecent)) {
2510 $strftimerecent = get_string('strftimerecent');
2513 $output .= '<div class="head">';
2514 $output .= '<div class="date">'.userdate($time, $strftimerecent).'</div>';
2515 $output .= '<div class="name">'.fullname($user, $viewfullnames).'</div>';
2516 $output .= '</div>';
2517 $output .= '<div class="info"><a href="'.$link.'">'.format_string($text, true).'</a></div>';
2519 if ($return) {
2520 return $output;
2521 } else {
2522 echo $output;
2527 * Returns a popup menu with course activity modules
2529 * Given a course this function returns a small popup menu with all the course activity modules in it, as a navigation menu
2530 * outputs a simple list structure in XHTML.
2531 * The data is taken from the serialised array stored in the course record.
2533 * @param course $course A {@link $COURSE} object.
2534 * @param array $sections
2535 * @param course_modinfo $modinfo
2536 * @param string $strsection
2537 * @param string $strjumpto
2538 * @param int $width
2539 * @param string $cmid
2540 * @return string The HTML block
2542 function navmenulist($course, $sections, $modinfo, $strsection, $strjumpto, $width=50, $cmid=0) {
2544 global $CFG, $OUTPUT;
2546 $section = -1;
2547 $menu = array();
2548 $doneheading = false;
2550 $courseformatoptions = course_get_format($course)->get_format_options();
2551 $coursecontext = context_course::instance($course->id);
2553 $menu[] = '<ul class="navmenulist"><li class="jumpto section"><span>'.$strjumpto.'</span><ul>';
2554 foreach ($modinfo->cms as $mod) {
2555 if (!$mod->has_view()) {
2556 // Don't show modules which you can't link to!
2557 continue;
2560 // For course formats using 'numsections' do not show extra sections.
2561 if (isset($courseformatoptions['numsections']) && $mod->sectionnum > $courseformatoptions['numsections']) {
2562 break;
2565 if (!$mod->uservisible) { // Do not icnlude empty sections at all.
2566 continue;
2569 if ($mod->sectionnum >= 0 and $section != $mod->sectionnum) {
2570 $thissection = $sections[$mod->sectionnum];
2572 if ($thissection->visible or
2573 (isset($courseformatoptions['hiddensections']) and !$courseformatoptions['hiddensections']) or
2574 has_capability('moodle/course:viewhiddensections', $coursecontext)) {
2575 $thissection->summary = strip_tags(format_string($thissection->summary, true));
2576 if (!$doneheading) {
2577 $menu[] = '</ul></li>';
2579 if ($course->format == 'weeks' or empty($thissection->summary)) {
2580 $item = $strsection ." ". $mod->sectionnum;
2581 } else {
2582 if (core_text::strlen($thissection->summary) < ($width-3)) {
2583 $item = $thissection->summary;
2584 } else {
2585 $item = core_text::substr($thissection->summary, 0, $width).'...';
2588 $menu[] = '<li class="section"><span>'.$item.'</span>';
2589 $menu[] = '<ul>';
2590 $doneheading = true;
2592 $section = $mod->sectionnum;
2593 } else {
2594 // No activities from this hidden section shown.
2595 continue;
2599 $url = $mod->modname .'/view.php?id='. $mod->id;
2600 $mod->name = strip_tags(format_string($mod->name ,true));
2601 if (core_text::strlen($mod->name) > ($width+5)) {
2602 $mod->name = core_text::substr($mod->name, 0, $width).'...';
2604 if (!$mod->visible) {
2605 $mod->name = '('.$mod->name.')';
2607 $class = 'activity '.$mod->modname;
2608 $class .= ($cmid == $mod->id) ? ' selected' : '';
2609 $menu[] = '<li class="'.$class.'">'.
2610 $OUTPUT->image_icon('icon', '', $mod->modname).
2611 '<a href="'.$CFG->wwwroot.'/mod/'.$url.'">'.$mod->name.'</a></li>';
2614 if ($doneheading) {
2615 $menu[] = '</ul></li>';
2617 $menu[] = '</ul></li></ul>';
2619 return implode("\n", $menu);
2623 * Prints a grade menu (as part of an existing form) with help showing all possible numerical grades and scales.
2625 * @todo Finish documenting this function
2626 * @todo Deprecate: this is only used in a few contrib modules
2628 * @param int $courseid The course ID
2629 * @param string $name
2630 * @param string $current
2631 * @param boolean $includenograde Include those with no grades
2632 * @param boolean $return If set to true returns rather than echo's
2633 * @return string|bool Depending on value of $return
2635 function print_grade_menu($courseid, $name, $current, $includenograde=true, $return=false) {
2636 global $OUTPUT;
2638 $output = '';
2639 $strscale = get_string('scale');
2640 $strscales = get_string('scales');
2642 $scales = get_scales_menu($courseid);
2643 foreach ($scales as $i => $scalename) {
2644 $grades[-$i] = $strscale .': '. $scalename;
2646 if ($includenograde) {
2647 $grades[0] = get_string('nograde');
2649 for ($i=100; $i>=1; $i--) {
2650 $grades[$i] = $i;
2652 $output .= html_writer::select($grades, $name, $current, false);
2654 $linkobject = '<span class="helplink">' . $OUTPUT->pix_icon('help', $strscales) . '</span>';
2655 $link = new moodle_url('/course/scales.php', array('id' => $courseid, 'list' => 1));
2656 $action = new popup_action('click', $link, 'ratingscales', array('height' => 400, 'width' => 500));
2657 $output .= $OUTPUT->action_link($link, $linkobject, $action, array('title' => $strscales));
2659 if ($return) {
2660 return $output;
2661 } else {
2662 echo $output;
2667 * Print an error to STDOUT and exit with a non-zero code. For commandline scripts.
2669 * Default errorcode is 1.
2671 * Very useful for perl-like error-handling:
2672 * do_somethting() or mdie("Something went wrong");
2674 * @param string $msg Error message
2675 * @param integer $errorcode Error code to emit
2677 function mdie($msg='', $errorcode=1) {
2678 trigger_error($msg);
2679 exit($errorcode);
2683 * Print a message and exit.
2685 * @param string $message The message to print in the notice
2686 * @param moodle_url|string $link The link to use for the continue button
2687 * @param object $course A course object. Unused.
2688 * @return void This function simply exits
2690 function notice ($message, $link='', $course=null) {
2691 global $PAGE, $OUTPUT;
2693 $message = clean_text($message); // In case nasties are in here.
2695 if (CLI_SCRIPT) {
2696 echo("!!$message!!\n");
2697 exit(1); // No success.
2700 if (!$PAGE->headerprinted) {
2701 // Header not yet printed.
2702 $PAGE->set_title(get_string('notice'));
2703 echo $OUTPUT->header();
2704 } else {
2705 echo $OUTPUT->container_end_all(false);
2708 echo $OUTPUT->box($message, 'generalbox', 'notice');
2709 echo $OUTPUT->continue_button($link);
2711 echo $OUTPUT->footer();
2712 exit(1); // General error code.
2716 * Redirects the user to another page, after printing a notice.
2718 * This function calls the OUTPUT redirect method, echo's the output and then dies to ensure nothing else happens.
2720 * <strong>Good practice:</strong> You should call this method before starting page
2721 * output by using any of the OUTPUT methods.
2723 * @param moodle_url|string $url A moodle_url to redirect to. Strings are not to be trusted!
2724 * @param string $message The message to display to the user
2725 * @param int $delay The delay before redirecting
2726 * @param string $messagetype The type of notification to show the message in. See constants on \core\output\notification.
2727 * @throws moodle_exception
2729 function redirect($url, $message='', $delay=null, $messagetype = \core\output\notification::NOTIFY_INFO) {
2730 global $OUTPUT, $PAGE, $CFG;
2732 if (CLI_SCRIPT or AJAX_SCRIPT) {
2733 // This is wrong - developers should not use redirect in these scripts but it should not be very likely.
2734 throw new moodle_exception('redirecterrordetected', 'error');
2737 if ($delay === null) {
2738 $delay = -1;
2741 // Prevent debug errors - make sure context is properly initialised.
2742 if ($PAGE) {
2743 $PAGE->set_context(null);
2744 $PAGE->set_pagelayout('redirect'); // No header and footer needed.
2745 $PAGE->set_title(get_string('pageshouldredirect', 'moodle'));
2748 if ($url instanceof moodle_url) {
2749 $url = $url->out(false);
2752 $debugdisableredirect = false;
2753 do {
2754 if (defined('DEBUGGING_PRINTED')) {
2755 // Some debugging already printed, no need to look more.
2756 $debugdisableredirect = true;
2757 break;
2760 if (core_useragent::is_msword()) {
2761 // Clicking a URL from MS Word sends a request to the server without cookies. If that
2762 // causes a redirect Word will open a browser pointing the new URL. If not, the URL that
2763 // was clicked is opened. Because the request from Word is without cookies, it almost
2764 // always results in a redirect to the login page, even if the user is logged in in their
2765 // browser. This is not what we want, so prevent the redirect for requests from Word.
2766 $debugdisableredirect = true;
2767 break;
2770 if (empty($CFG->debugdisplay) or empty($CFG->debug)) {
2771 // No errors should be displayed.
2772 break;
2775 if (!function_exists('error_get_last') or !$lasterror = error_get_last()) {
2776 break;
2779 if (!($lasterror['type'] & $CFG->debug)) {
2780 // Last error not interesting.
2781 break;
2784 // Watch out here, @hidden() errors are returned from error_get_last() too.
2785 if (headers_sent()) {
2786 // We already started printing something - that means errors likely printed.
2787 $debugdisableredirect = true;
2788 break;
2791 if (ob_get_level() and ob_get_contents()) {
2792 // There is something waiting to be printed, hopefully it is the errors,
2793 // but it might be some error hidden by @ too - such as the timezone mess from setup.php.
2794 $debugdisableredirect = true;
2795 break;
2797 } while (false);
2799 // Technically, HTTP/1.1 requires Location: header to contain the absolute path.
2800 // (In practice browsers accept relative paths - but still, might as well do it properly.)
2801 // This code turns relative into absolute.
2802 if (!preg_match('|^[a-z]+:|i', $url)) {
2803 // Get host name http://www.wherever.com.
2804 $hostpart = preg_replace('|^(.*?[^:/])/.*$|', '$1', $CFG->wwwroot);
2805 if (preg_match('|^/|', $url)) {
2806 // URLs beginning with / are relative to web server root so we just add them in.
2807 $url = $hostpart.$url;
2808 } else {
2809 // URLs not beginning with / are relative to path of current script, so add that on.
2810 $url = $hostpart.preg_replace('|\?.*$|', '', me()).'/../'.$url;
2812 // Replace all ..s.
2813 while (true) {
2814 $newurl = preg_replace('|/(?!\.\.)[^/]*/\.\./|', '/', $url);
2815 if ($newurl == $url) {
2816 break;
2818 $url = $newurl;
2822 // Sanitise url - we can not rely on moodle_url or our URL cleaning
2823 // because they do not support all valid external URLs.
2824 $url = preg_replace('/[\x00-\x1F\x7F]/', '', $url);
2825 $url = str_replace('"', '%22', $url);
2826 $encodedurl = preg_replace("/\&(?![a-zA-Z0-9#]{1,8};)/", "&amp;", $url);
2827 $encodedurl = preg_replace('/^.*href="([^"]*)".*$/', "\\1", clean_text('<a href="'.$encodedurl.'" />', FORMAT_HTML));
2828 $url = str_replace('&amp;', '&', $encodedurl);
2830 if (!empty($message)) {
2831 if (!$debugdisableredirect && !headers_sent()) {
2832 // A message has been provided, and the headers have not yet been sent.
2833 // Display the message as a notification on the subsequent page.
2834 \core\notification::add($message, $messagetype);
2835 $message = null;
2836 $delay = 0;
2837 } else {
2838 if ($delay === -1 || !is_numeric($delay)) {
2839 $delay = 3;
2841 $message = clean_text($message);
2843 } else {
2844 $message = get_string('pageshouldredirect');
2845 $delay = 0;
2848 // Make sure the session is closed properly, this prevents problems in IIS
2849 // and also some potential PHP shutdown issues.
2850 \core\session\manager::write_close();
2852 if ($delay == 0 && !$debugdisableredirect && !headers_sent()) {
2853 // 302 might not work for POST requests, 303 is ignored by obsolete clients.
2854 @header($_SERVER['SERVER_PROTOCOL'] . ' 303 See Other');
2855 @header('Location: '.$url);
2856 echo bootstrap_renderer::plain_redirect_message($encodedurl);
2857 exit;
2860 // Include a redirect message, even with a HTTP redirect, because that is recommended practice.
2861 if ($PAGE) {
2862 $CFG->docroot = false; // To prevent the link to moodle docs from being displayed on redirect page.
2863 echo $OUTPUT->redirect_message($encodedurl, $message, $delay, $debugdisableredirect, $messagetype);
2864 exit;
2865 } else {
2866 echo bootstrap_renderer::early_redirect_message($encodedurl, $message, $delay);
2867 exit;
2872 * Given an email address, this function will return an obfuscated version of it.
2874 * @param string $email The email address to obfuscate
2875 * @return string The obfuscated email address
2877 function obfuscate_email($email) {
2878 $i = 0;
2879 $length = strlen($email);
2880 $obfuscated = '';
2881 while ($i < $length) {
2882 if (rand(0, 2) && $email{$i}!='@') { // MDL-20619 some browsers have problems unobfuscating @.
2883 $obfuscated.='%'.dechex(ord($email{$i}));
2884 } else {
2885 $obfuscated.=$email{$i};
2887 $i++;
2889 return $obfuscated;
2893 * This function takes some text and replaces about half of the characters
2894 * with HTML entity equivalents. Return string is obviously longer.
2896 * @param string $plaintext The text to be obfuscated
2897 * @return string The obfuscated text
2899 function obfuscate_text($plaintext) {
2900 $i=0;
2901 $length = core_text::strlen($plaintext);
2902 $obfuscated='';
2903 $prevobfuscated = false;
2904 while ($i < $length) {
2905 $char = core_text::substr($plaintext, $i, 1);
2906 $ord = core_text::utf8ord($char);
2907 $numerical = ($ord >= ord('0')) && ($ord <= ord('9'));
2908 if ($prevobfuscated and $numerical ) {
2909 $obfuscated.='&#'.$ord.';';
2910 } else if (rand(0, 2)) {
2911 $obfuscated.='&#'.$ord.';';
2912 $prevobfuscated = true;
2913 } else {
2914 $obfuscated.=$char;
2915 $prevobfuscated = false;
2917 $i++;
2919 return $obfuscated;
2923 * This function uses the {@link obfuscate_email()} and {@link obfuscate_text()}
2924 * to generate a fully obfuscated email link, ready to use.
2926 * @param string $email The email address to display
2927 * @param string $label The text to displayed as hyperlink to $email
2928 * @param boolean $dimmed If true then use css class 'dimmed' for hyperlink
2929 * @param string $subject The subject of the email in the mailto link
2930 * @param string $body The content of the email in the mailto link
2931 * @return string The obfuscated mailto link
2933 function obfuscate_mailto($email, $label='', $dimmed=false, $subject = '', $body = '') {
2935 if (empty($label)) {
2936 $label = $email;
2939 $label = obfuscate_text($label);
2940 $email = obfuscate_email($email);
2941 $mailto = obfuscate_text('mailto');
2942 $url = new moodle_url("mailto:$email");
2943 $attrs = array();
2945 if (!empty($subject)) {
2946 $url->param('subject', format_string($subject));
2948 if (!empty($body)) {
2949 $url->param('body', format_string($body));
2952 // Use the obfuscated mailto.
2953 $url = preg_replace('/^mailto/', $mailto, $url->out());
2955 if ($dimmed) {
2956 $attrs['title'] = get_string('emaildisable');
2957 $attrs['class'] = 'dimmed';
2960 return html_writer::link($url, $label, $attrs);
2964 * This function is used to rebuild the <nolink> tag because some formats (PLAIN and WIKI)
2965 * will transform it to html entities
2967 * @param string $text Text to search for nolink tag in
2968 * @return string
2970 function rebuildnolinktag($text) {
2972 $text = preg_replace('/&lt;(\/*nolink)&gt;/i', '<$1>', $text);
2974 return $text;
2978 * Prints a maintenance message from $CFG->maintenance_message or default if empty.
2980 function print_maintenance_message() {
2981 global $CFG, $SITE, $PAGE, $OUTPUT;
2983 header($_SERVER['SERVER_PROTOCOL'] . ' 503 Moodle under maintenance');
2984 header('Status: 503 Moodle under maintenance');
2985 header('Retry-After: 300');
2987 $PAGE->set_pagetype('maintenance-message');
2988 $PAGE->set_pagelayout('maintenance');
2989 $PAGE->set_title(strip_tags($SITE->fullname));
2990 $PAGE->set_heading($SITE->fullname);
2991 echo $OUTPUT->header();
2992 echo $OUTPUT->heading(get_string('sitemaintenance', 'admin'));
2993 if (isset($CFG->maintenance_message) and !html_is_blank($CFG->maintenance_message)) {
2994 echo $OUTPUT->box_start('maintenance_message generalbox boxwidthwide boxaligncenter');
2995 echo $CFG->maintenance_message;
2996 echo $OUTPUT->box_end();
2998 echo $OUTPUT->footer();
2999 die;
3003 * Returns a string containing a nested list, suitable for formatting into tabs with CSS.
3005 * It is not recommended to use this function in Moodle 2.5 but it is left for backward
3006 * compartibility.
3008 * Example how to print a single line tabs:
3009 * $rows = array(
3010 * new tabobject(...),
3011 * new tabobject(...)
3012 * );
3013 * echo $OUTPUT->tabtree($rows, $selectedid);
3015 * Multiple row tabs may not look good on some devices but if you want to use them
3016 * you can specify ->subtree for the active tabobject.
3018 * @param array $tabrows An array of rows where each row is an array of tab objects
3019 * @param string $selected The id of the selected tab (whatever row it's on)
3020 * @param array $inactive An array of ids of inactive tabs that are not selectable.
3021 * @param array $activated An array of ids of other tabs that are currently activated
3022 * @param bool $return If true output is returned rather then echo'd
3023 * @return string HTML output if $return was set to true.
3025 function print_tabs($tabrows, $selected = null, $inactive = null, $activated = null, $return = false) {
3026 global $OUTPUT;
3028 $tabrows = array_reverse($tabrows);
3029 $subtree = array();
3030 foreach ($tabrows as $row) {
3031 $tree = array();
3033 foreach ($row as $tab) {
3034 $tab->inactive = is_array($inactive) && in_array((string)$tab->id, $inactive);
3035 $tab->activated = is_array($activated) && in_array((string)$tab->id, $activated);
3036 $tab->selected = (string)$tab->id == $selected;
3038 if ($tab->activated || $tab->selected) {
3039 $tab->subtree = $subtree;
3041 $tree[] = $tab;
3043 $subtree = $tree;
3045 $output = $OUTPUT->tabtree($subtree);
3046 if ($return) {
3047 return $output;
3048 } else {
3049 print $output;
3050 return !empty($output);
3055 * Alter debugging level for the current request,
3056 * the change is not saved in database.
3058 * @param int $level one of the DEBUG_* constants
3059 * @param bool $debugdisplay
3061 function set_debugging($level, $debugdisplay = null) {
3062 global $CFG;
3064 $CFG->debug = (int)$level;
3065 $CFG->debugdeveloper = (($CFG->debug & DEBUG_DEVELOPER) === DEBUG_DEVELOPER);
3067 if ($debugdisplay !== null) {
3068 $CFG->debugdisplay = (bool)$debugdisplay;
3073 * Standard Debugging Function
3075 * Returns true if the current site debugging settings are equal or above specified level.
3076 * If passed a parameter it will emit a debugging notice similar to trigger_error(). The
3077 * routing of notices is controlled by $CFG->debugdisplay
3078 * eg use like this:
3080 * 1) debugging('a normal debug notice');
3081 * 2) debugging('something really picky', DEBUG_ALL);
3082 * 3) debugging('annoying debug message only for developers', DEBUG_DEVELOPER);
3083 * 4) if (debugging()) { perform extra debugging operations (do not use print or echo) }
3085 * In code blocks controlled by debugging() (such as example 4)
3086 * any output should be routed via debugging() itself, or the lower-level
3087 * trigger_error() or error_log(). Using echo or print will break XHTML
3088 * JS and HTTP headers.
3090 * It is also possible to define NO_DEBUG_DISPLAY which redirects the message to error_log.
3092 * @param string $message a message to print
3093 * @param int $level the level at which this debugging statement should show
3094 * @param array $backtrace use different backtrace
3095 * @return bool
3097 function debugging($message = '', $level = DEBUG_NORMAL, $backtrace = null) {
3098 global $CFG, $USER;
3100 $forcedebug = false;
3101 if (!empty($CFG->debugusers) && $USER) {
3102 $debugusers = explode(',', $CFG->debugusers);
3103 $forcedebug = in_array($USER->id, $debugusers);
3106 if (!$forcedebug and (empty($CFG->debug) || ($CFG->debug != -1 and $CFG->debug < $level))) {
3107 return false;
3110 if (!isset($CFG->debugdisplay)) {
3111 $CFG->debugdisplay = ini_get_bool('display_errors');
3114 if ($message) {
3115 if (!$backtrace) {
3116 $backtrace = debug_backtrace();
3118 $from = format_backtrace($backtrace, CLI_SCRIPT || NO_DEBUG_DISPLAY);
3119 if (PHPUNIT_TEST) {
3120 if (phpunit_util::debugging_triggered($message, $level, $from)) {
3121 // We are inside test, the debug message was logged.
3122 return true;
3126 if (NO_DEBUG_DISPLAY) {
3127 // Script does not want any errors or debugging in output,
3128 // we send the info to error log instead.
3129 error_log('Debugging: ' . $message . ' in '. PHP_EOL . $from);
3131 } else if ($forcedebug or $CFG->debugdisplay) {
3132 if (!defined('DEBUGGING_PRINTED')) {
3133 define('DEBUGGING_PRINTED', 1); // Indicates we have printed something.
3135 if (CLI_SCRIPT) {
3136 echo "++ $message ++\n$from";
3137 } else {
3138 echo '<div class="notifytiny debuggingmessage" data-rel="debugging">' , $message , $from , '</div>';
3141 } else {
3142 trigger_error($message . $from, E_USER_NOTICE);
3145 return true;
3149 * Outputs a HTML comment to the browser.
3151 * This is used for those hard-to-debug pages that use bits from many different files in very confusing ways (e.g. blocks).
3153 * <code>print_location_comment(__FILE__, __LINE__);</code>
3155 * @param string $file
3156 * @param integer $line
3157 * @param boolean $return Whether to return or print the comment
3158 * @return string|void Void unless true given as third parameter
3160 function print_location_comment($file, $line, $return = false) {
3161 if ($return) {
3162 return "<!-- $file at line $line -->\n";
3163 } else {
3164 echo "<!-- $file at line $line -->\n";
3170 * Returns true if the user is using a right-to-left language.
3172 * @return boolean true if the current language is right-to-left (Hebrew, Arabic etc)
3174 function right_to_left() {
3175 return (get_string('thisdirection', 'langconfig') === 'rtl');
3180 * Returns swapped left<=> right if in RTL environment.
3182 * Part of RTL Moodles support.
3184 * @param string $align align to check
3185 * @return string
3187 function fix_align_rtl($align) {
3188 if (!right_to_left()) {
3189 return $align;
3191 if ($align == 'left') {
3192 return 'right';
3194 if ($align == 'right') {
3195 return 'left';
3197 return $align;
3202 * Returns true if the page is displayed in a popup window.
3204 * Gets the information from the URL parameter inpopup.
3206 * @todo Use a central function to create the popup calls all over Moodle and
3207 * In the moment only works with resources and probably questions.
3209 * @return boolean
3211 function is_in_popup() {
3212 $inpopup = optional_param('inpopup', '', PARAM_BOOL);
3214 return ($inpopup);
3218 * Progress trace class.
3220 * Use this class from long operations where you want to output occasional information about
3221 * what is going on, but don't know if, or in what format, the output should be.
3223 * @copyright 2009 Tim Hunt
3224 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3225 * @package core
3227 abstract class progress_trace {
3229 * Output an progress message in whatever format.
3231 * @param string $message the message to output.
3232 * @param integer $depth indent depth for this message.
3234 abstract public function output($message, $depth = 0);
3237 * Called when the processing is finished.
3239 public function finished() {
3244 * This subclass of progress_trace does not ouput anything.
3246 * @copyright 2009 Tim Hunt
3247 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3248 * @package core
3250 class null_progress_trace extends progress_trace {
3252 * Does Nothing
3254 * @param string $message
3255 * @param int $depth
3256 * @return void Does Nothing
3258 public function output($message, $depth = 0) {
3263 * This subclass of progress_trace outputs to plain text.
3265 * @copyright 2009 Tim Hunt
3266 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3267 * @package core
3269 class text_progress_trace extends progress_trace {
3271 * Output the trace message.
3273 * @param string $message
3274 * @param int $depth
3275 * @return void Output is echo'd
3277 public function output($message, $depth = 0) {
3278 mtrace(str_repeat(' ', $depth) . $message);
3283 * This subclass of progress_trace outputs as HTML.
3285 * @copyright 2009 Tim Hunt
3286 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3287 * @package core
3289 class html_progress_trace extends progress_trace {
3291 * Output the trace message.
3293 * @param string $message
3294 * @param int $depth
3295 * @return void Output is echo'd
3297 public function output($message, $depth = 0) {
3298 echo '<p>', str_repeat('&#160;&#160;', $depth), htmlspecialchars($message), "</p>\n";
3299 flush();
3304 * HTML List Progress Tree
3306 * @copyright 2009 Tim Hunt
3307 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3308 * @package core
3310 class html_list_progress_trace extends progress_trace {
3311 /** @var int */
3312 protected $currentdepth = -1;
3315 * Echo out the list
3317 * @param string $message The message to display
3318 * @param int $depth
3319 * @return void Output is echoed
3321 public function output($message, $depth = 0) {
3322 $samedepth = true;
3323 while ($this->currentdepth > $depth) {
3324 echo "</li>\n</ul>\n";
3325 $this->currentdepth -= 1;
3326 if ($this->currentdepth == $depth) {
3327 echo '<li>';
3329 $samedepth = false;
3331 while ($this->currentdepth < $depth) {
3332 echo "<ul>\n<li>";
3333 $this->currentdepth += 1;
3334 $samedepth = false;
3336 if ($samedepth) {
3337 echo "</li>\n<li>";
3339 echo htmlspecialchars($message);
3340 flush();
3344 * Called when the processing is finished.
3346 public function finished() {
3347 while ($this->currentdepth >= 0) {
3348 echo "</li>\n</ul>\n";
3349 $this->currentdepth -= 1;
3355 * This subclass of progress_trace outputs to error log.
3357 * @copyright Petr Skoda {@link http://skodak.org}
3358 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3359 * @package core
3361 class error_log_progress_trace extends progress_trace {
3362 /** @var string log prefix */
3363 protected $prefix;
3366 * Constructor.
3367 * @param string $prefix optional log prefix
3369 public function __construct($prefix = '') {
3370 $this->prefix = $prefix;
3374 * Output the trace message.
3376 * @param string $message
3377 * @param int $depth
3378 * @return void Output is sent to error log.
3380 public function output($message, $depth = 0) {
3381 error_log($this->prefix . str_repeat(' ', $depth) . $message);
3386 * Special type of trace that can be used for catching of output of other traces.
3388 * @copyright Petr Skoda {@link http://skodak.org}
3389 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3390 * @package core
3392 class progress_trace_buffer extends progress_trace {
3393 /** @var progres_trace */
3394 protected $trace;
3395 /** @var bool do we pass output out */
3396 protected $passthrough;
3397 /** @var string output buffer */
3398 protected $buffer;
3401 * Constructor.
3403 * @param progress_trace $trace
3404 * @param bool $passthrough true means output and buffer, false means just buffer and no output
3406 public function __construct(progress_trace $trace, $passthrough = true) {
3407 $this->trace = $trace;
3408 $this->passthrough = $passthrough;
3409 $this->buffer = '';
3413 * Output the trace message.
3415 * @param string $message the message to output.
3416 * @param int $depth indent depth for this message.
3417 * @return void output stored in buffer
3419 public function output($message, $depth = 0) {
3420 ob_start();
3421 $this->trace->output($message, $depth);
3422 $this->buffer .= ob_get_contents();
3423 if ($this->passthrough) {
3424 ob_end_flush();
3425 } else {
3426 ob_end_clean();
3431 * Called when the processing is finished.
3433 public function finished() {
3434 ob_start();
3435 $this->trace->finished();
3436 $this->buffer .= ob_get_contents();
3437 if ($this->passthrough) {
3438 ob_end_flush();
3439 } else {
3440 ob_end_clean();
3445 * Reset internal text buffer.
3447 public function reset_buffer() {
3448 $this->buffer = '';
3452 * Return internal text buffer.
3453 * @return string buffered plain text
3455 public function get_buffer() {
3456 return $this->buffer;
3461 * Special type of trace that can be used for redirecting to multiple other traces.
3463 * @copyright Petr Skoda {@link http://skodak.org}
3464 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3465 * @package core
3467 class combined_progress_trace extends progress_trace {
3470 * An array of traces.
3471 * @var array
3473 protected $traces;
3476 * Constructs a new instance.
3478 * @param array $traces multiple traces
3480 public function __construct(array $traces) {
3481 $this->traces = $traces;
3485 * Output an progress message in whatever format.
3487 * @param string $message the message to output.
3488 * @param integer $depth indent depth for this message.
3490 public function output($message, $depth = 0) {
3491 foreach ($this->traces as $trace) {
3492 $trace->output($message, $depth);
3497 * Called when the processing is finished.
3499 public function finished() {
3500 foreach ($this->traces as $trace) {
3501 $trace->finished();
3507 * Returns a localized sentence in the current language summarizing the current password policy
3509 * @todo this should be handled by a function/method in the language pack library once we have a support for it
3510 * @uses $CFG
3511 * @return string
3513 function print_password_policy() {
3514 global $CFG;
3516 $message = '';
3517 if (!empty($CFG->passwordpolicy)) {
3518 $messages = array();
3519 $messages[] = get_string('informminpasswordlength', 'auth', $CFG->minpasswordlength);
3520 if (!empty($CFG->minpassworddigits)) {
3521 $messages[] = get_string('informminpassworddigits', 'auth', $CFG->minpassworddigits);
3523 if (!empty($CFG->minpasswordlower)) {
3524 $messages[] = get_string('informminpasswordlower', 'auth', $CFG->minpasswordlower);
3526 if (!empty($CFG->minpasswordupper)) {
3527 $messages[] = get_string('informminpasswordupper', 'auth', $CFG->minpasswordupper);
3529 if (!empty($CFG->minpasswordnonalphanum)) {
3530 $messages[] = get_string('informminpasswordnonalphanum', 'auth', $CFG->minpasswordnonalphanum);
3533 $messages = join(', ', $messages); // This is ugly but we do not have anything better yet...
3534 $message = get_string('informpasswordpolicy', 'auth', $messages);
3536 return $message;
3540 * Get the value of a help string fully prepared for display in the current language.
3542 * @param string $identifier The identifier of the string to search for.
3543 * @param string $component The module the string is associated with.
3544 * @param boolean $ajax Whether this help is called from an AJAX script.
3545 * This is used to influence text formatting and determines
3546 * which format to output the doclink in.
3547 * @param string|object|array $a An object, string or number that can be used
3548 * within translation strings
3549 * @return Object An object containing:
3550 * - heading: Any heading that there may be for this help string.
3551 * - text: The wiki-formatted help string.
3552 * - doclink: An object containing a link, the linktext, and any additional
3553 * CSS classes to apply to that link. Only present if $ajax = false.
3554 * - completedoclink: A text representation of the doclink. Only present if $ajax = true.
3556 function get_formatted_help_string($identifier, $component, $ajax = false, $a = null) {
3557 global $CFG, $OUTPUT;
3558 $sm = get_string_manager();
3560 // Do not rebuild caches here!
3561 // Devs need to learn to purge all caches after any change or disable $CFG->langstringcache.
3563 $data = new stdClass();
3565 if ($sm->string_exists($identifier, $component)) {
3566 $data->heading = format_string(get_string($identifier, $component));
3567 } else {
3568 // Gracefully fall back to an empty string.
3569 $data->heading = '';
3572 if ($sm->string_exists($identifier . '_help', $component)) {
3573 $options = new stdClass();
3574 $options->trusted = false;
3575 $options->noclean = false;
3576 $options->smiley = false;
3577 $options->filter = false;
3578 $options->para = true;
3579 $options->newlines = false;
3580 $options->overflowdiv = !$ajax;
3582 // Should be simple wiki only MDL-21695.
3583 $data->text = format_text(get_string($identifier.'_help', $component, $a), FORMAT_MARKDOWN, $options);
3585 $helplink = $identifier . '_link';
3586 if ($sm->string_exists($helplink, $component)) { // Link to further info in Moodle docs.
3587 $link = get_string($helplink, $component);
3588 $linktext = get_string('morehelp');
3590 $data->doclink = new stdClass();
3591 $url = new moodle_url(get_docs_url($link));
3592 if ($ajax) {
3593 $data->doclink->link = $url->out();
3594 $data->doclink->linktext = $linktext;
3595 $data->doclink->class = ($CFG->doctonewwindow) ? 'helplinkpopup' : '';
3596 } else {
3597 $data->completedoclink = html_writer::tag('div', $OUTPUT->doc_link($link, $linktext),
3598 array('class' => 'helpdoclink'));
3601 } else {
3602 $data->text = html_writer::tag('p',
3603 html_writer::tag('strong', 'TODO') . ": missing help string [{$identifier}_help, {$component}]");
3605 return $data;