MDL-61502 questions: add filter tests to gapselect question type.
[moodle.git] / lib / weblib.php
blob5cd97338763ff099c0247b81f9f111bcab41b680
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->httpswwwroot, 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->httpswwwroot, '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 // We must not use httpswwwroot here, because it might be url of other page,
351 // devs have to use httpswwwroot explicitly when creating new moodle_url.
352 $url = $CFG->wwwroot.$url;
355 // Now fix the admin links if needed, no need to mess with httpswwwroot.
356 if ($CFG->admin !== 'admin') {
357 if (strpos($url, "$CFG->wwwroot/admin/") === 0) {
358 $url = str_replace("$CFG->wwwroot/admin/", "$CFG->wwwroot/$CFG->admin/", $url);
362 // Parse the $url.
363 $parts = parse_url($url);
364 if ($parts === false) {
365 throw new moodle_exception('invalidurl');
367 if (isset($parts['query'])) {
368 // Note: the values may not be correctly decoded, url parameters should be always passed as array.
369 parse_str(str_replace('&amp;', '&', $parts['query']), $this->params);
371 unset($parts['query']);
372 foreach ($parts as $key => $value) {
373 $this->$key = $value;
376 // Detect slashargument value from path - we do not support directory names ending with .php.
377 $pos = strpos($this->path, '.php/');
378 if ($pos !== false) {
379 $this->slashargument = substr($this->path, $pos + 4);
380 $this->path = substr($this->path, 0, $pos + 4);
384 $this->params($params);
385 if ($anchor !== null) {
386 $this->anchor = (string)$anchor;
391 * Add an array of params to the params for this url.
393 * The added params override existing ones if they have the same name.
395 * @param array $params Defaults to null. If null then returns all params.
396 * @return array Array of Params for url.
397 * @throws coding_exception
399 public function params(array $params = null) {
400 $params = (array)$params;
402 foreach ($params as $key => $value) {
403 if (is_int($key)) {
404 throw new coding_exception('Url parameters can not have numeric keys!');
406 if (!is_string($value)) {
407 if (is_array($value)) {
408 throw new coding_exception('Url parameters values can not be arrays!');
410 if (is_object($value) and !method_exists($value, '__toString')) {
411 throw new coding_exception('Url parameters values can not be objects, unless __toString() is defined!');
414 $this->params[$key] = (string)$value;
416 return $this->params;
420 * Remove all params if no arguments passed.
421 * Remove selected params if arguments are passed.
423 * Can be called as either remove_params('param1', 'param2')
424 * or remove_params(array('param1', 'param2')).
426 * @param string[]|string $params,... either an array of param names, or 1..n string params to remove as args.
427 * @return array url parameters
429 public function remove_params($params = null) {
430 if (!is_array($params)) {
431 $params = func_get_args();
433 foreach ($params as $param) {
434 unset($this->params[$param]);
436 return $this->params;
440 * Remove all url parameters.
442 * @todo remove the unused param.
443 * @param array $params Unused param
444 * @return void
446 public function remove_all_params($params = null) {
447 $this->params = array();
448 $this->slashargument = '';
452 * Add a param to the params for this url.
454 * The added param overrides existing one if they have the same name.
456 * @param string $paramname name
457 * @param string $newvalue Param value. If new value specified current value is overriden or parameter is added
458 * @return mixed string parameter value, null if parameter does not exist
460 public function param($paramname, $newvalue = '') {
461 if (func_num_args() > 1) {
462 // Set new value.
463 $this->params(array($paramname => $newvalue));
465 if (isset($this->params[$paramname])) {
466 return $this->params[$paramname];
467 } else {
468 return null;
473 * Merges parameters and validates them
475 * @param array $overrideparams
476 * @return array merged parameters
477 * @throws coding_exception
479 protected function merge_overrideparams(array $overrideparams = null) {
480 $overrideparams = (array)$overrideparams;
481 $params = $this->params;
482 foreach ($overrideparams as $key => $value) {
483 if (is_int($key)) {
484 throw new coding_exception('Overridden parameters can not have numeric keys!');
486 if (is_array($value)) {
487 throw new coding_exception('Overridden parameters values can not be arrays!');
489 if (is_object($value) and !method_exists($value, '__toString')) {
490 throw new coding_exception('Overridden parameters values can not be objects, unless __toString() is defined!');
492 $params[$key] = (string)$value;
494 return $params;
498 * Get the params as as a query string.
500 * This method should not be used outside of this method.
502 * @param bool $escaped Use &amp; as params separator instead of plain &
503 * @param array $overrideparams params to add to the output params, these
504 * override existing ones with the same name.
505 * @return string query string that can be added to a url.
507 public function get_query_string($escaped = true, array $overrideparams = null) {
508 $arr = array();
509 if ($overrideparams !== null) {
510 $params = $this->merge_overrideparams($overrideparams);
511 } else {
512 $params = $this->params;
514 foreach ($params as $key => $val) {
515 if (is_array($val)) {
516 foreach ($val as $index => $value) {
517 $arr[] = rawurlencode($key.'['.$index.']')."=".rawurlencode($value);
519 } else {
520 if (isset($val) && $val !== '') {
521 $arr[] = rawurlencode($key)."=".rawurlencode($val);
522 } else {
523 $arr[] = rawurlencode($key);
527 if ($escaped) {
528 return implode('&amp;', $arr);
529 } else {
530 return implode('&', $arr);
535 * Shortcut for printing of encoded URL.
537 * @return string
539 public function __toString() {
540 return $this->out(true);
544 * Output url.
546 * If you use the returned URL in HTML code, you want the escaped ampersands. If you use
547 * the returned URL in HTTP headers, you want $escaped=false.
549 * @param bool $escaped Use &amp; as params separator instead of plain &
550 * @param array $overrideparams params to add to the output url, these override existing ones with the same name.
551 * @return string Resulting URL
553 public function out($escaped = true, array $overrideparams = null) {
555 global $CFG;
557 if (!is_bool($escaped)) {
558 debugging('Escape parameter must be of type boolean, '.gettype($escaped).' given instead.');
561 $url = $this;
563 // Allow url's to be rewritten by a plugin.
564 if (isset($CFG->urlrewriteclass) && !isset($CFG->upgraderunning)) {
565 $class = $CFG->urlrewriteclass;
566 $pluginurl = $class::url_rewrite($url);
567 if ($pluginurl instanceof moodle_url) {
568 $url = $pluginurl;
572 return $url->raw_out($escaped, $overrideparams);
577 * Output url without any rewrites
579 * This is identical in signature and use to out() but doesn't call the rewrite handler.
581 * @param bool $escaped Use &amp; as params separator instead of plain &
582 * @param array $overrideparams params to add to the output url, these override existing ones with the same name.
583 * @return string Resulting URL
585 public function raw_out($escaped = true, array $overrideparams = null) {
586 if (!is_bool($escaped)) {
587 debugging('Escape parameter must be of type boolean, '.gettype($escaped).' given instead.');
590 $uri = $this->out_omit_querystring().$this->slashargument;
592 $querystring = $this->get_query_string($escaped, $overrideparams);
593 if ($querystring !== '') {
594 $uri .= '?' . $querystring;
596 if (!is_null($this->anchor)) {
597 $uri .= '#'.$this->anchor;
600 return $uri;
604 * Returns url without parameters, everything before '?'.
606 * @param bool $includeanchor if {@link self::anchor} is defined, should it be returned?
607 * @return string
609 public function out_omit_querystring($includeanchor = false) {
611 $uri = $this->scheme ? $this->scheme.':'.((strtolower($this->scheme) == 'mailto') ? '':'//'): '';
612 $uri .= $this->user ? $this->user.($this->pass? ':'.$this->pass:'').'@':'';
613 $uri .= $this->host ? $this->host : '';
614 $uri .= $this->port ? ':'.$this->port : '';
615 $uri .= $this->path ? $this->path : '';
616 if ($includeanchor and !is_null($this->anchor)) {
617 $uri .= '#' . $this->anchor;
620 return $uri;
624 * Compares this moodle_url with another.
626 * See documentation of constants for an explanation of the comparison flags.
628 * @param moodle_url $url The moodle_url object to compare
629 * @param int $matchtype The type of comparison (URL_MATCH_BASE, URL_MATCH_PARAMS, URL_MATCH_EXACT)
630 * @return bool
632 public function compare(moodle_url $url, $matchtype = URL_MATCH_EXACT) {
634 $baseself = $this->out_omit_querystring();
635 $baseother = $url->out_omit_querystring();
637 // Append index.php if there is no specific file.
638 if (substr($baseself, -1) == '/') {
639 $baseself .= 'index.php';
641 if (substr($baseother, -1) == '/') {
642 $baseother .= 'index.php';
645 // Compare the two base URLs.
646 if ($baseself != $baseother) {
647 return false;
650 if ($matchtype == URL_MATCH_BASE) {
651 return true;
654 $urlparams = $url->params();
655 foreach ($this->params() as $param => $value) {
656 if ($param == 'sesskey') {
657 continue;
659 if (!array_key_exists($param, $urlparams) || $urlparams[$param] != $value) {
660 return false;
664 if ($matchtype == URL_MATCH_PARAMS) {
665 return true;
668 foreach ($urlparams as $param => $value) {
669 if ($param == 'sesskey') {
670 continue;
672 if (!array_key_exists($param, $this->params()) || $this->param($param) != $value) {
673 return false;
677 if ($url->anchor !== $this->anchor) {
678 return false;
681 return true;
685 * Sets the anchor for the URI (the bit after the hash)
687 * @param string $anchor null means remove previous
689 public function set_anchor($anchor) {
690 if (is_null($anchor)) {
691 // Remove.
692 $this->anchor = null;
693 } else if ($anchor === '') {
694 // Special case, used as empty link.
695 $this->anchor = '';
696 } else if (preg_match('|[a-zA-Z\_\:][a-zA-Z0-9\_\-\.\:]*|', $anchor)) {
697 // Match the anchor against the NMTOKEN spec.
698 $this->anchor = $anchor;
699 } else {
700 // Bad luck, no valid anchor found.
701 $this->anchor = null;
706 * Sets the scheme for the URI (the bit before ://)
708 * @param string $scheme
710 public function set_scheme($scheme) {
711 // See http://www.ietf.org/rfc/rfc3986.txt part 3.1.
712 if (preg_match('/^[a-zA-Z][a-zA-Z0-9+.-]*$/', $scheme)) {
713 $this->scheme = $scheme;
714 } else {
715 throw new coding_exception('Bad URL scheme.');
720 * Sets the url slashargument value.
722 * @param string $path usually file path
723 * @param string $parameter name of page parameter if slasharguments not supported
724 * @param bool $supported usually null, then it depends on $CFG->slasharguments, use true or false for other servers
725 * @return void
727 public function set_slashargument($path, $parameter = 'file', $supported = null) {
728 global $CFG;
729 if (is_null($supported)) {
730 $supported = !empty($CFG->slasharguments);
733 if ($supported) {
734 $parts = explode('/', $path);
735 $parts = array_map('rawurlencode', $parts);
736 $path = implode('/', $parts);
737 $this->slashargument = $path;
738 unset($this->params[$parameter]);
740 } else {
741 $this->slashargument = '';
742 $this->params[$parameter] = $path;
746 // Static factory methods.
749 * General moodle file url.
751 * @param string $urlbase the script serving the file
752 * @param string $path
753 * @param bool $forcedownload
754 * @return moodle_url
756 public static function make_file_url($urlbase, $path, $forcedownload = false) {
757 $params = array();
758 if ($forcedownload) {
759 $params['forcedownload'] = 1;
761 $url = new moodle_url($urlbase, $params);
762 $url->set_slashargument($path);
763 return $url;
767 * Factory method for creation of url pointing to plugin file.
769 * Please note this method can be used only from the plugins to
770 * create urls of own files, it must not be used outside of plugins!
772 * @param int $contextid
773 * @param string $component
774 * @param string $area
775 * @param int $itemid
776 * @param string $pathname
777 * @param string $filename
778 * @param bool $forcedownload
779 * @return moodle_url
781 public static function make_pluginfile_url($contextid, $component, $area, $itemid, $pathname, $filename,
782 $forcedownload = false) {
783 global $CFG;
784 $urlbase = "$CFG->httpswwwroot/pluginfile.php";
785 if ($itemid === null) {
786 return self::make_file_url($urlbase, "/$contextid/$component/$area".$pathname.$filename, $forcedownload);
787 } else {
788 return self::make_file_url($urlbase, "/$contextid/$component/$area/$itemid".$pathname.$filename, $forcedownload);
793 * Factory method for creation of url pointing to plugin file.
794 * This method is the same that make_pluginfile_url but pointing to the webservice pluginfile.php script.
795 * It should be used only in external functions.
797 * @since 2.8
798 * @param int $contextid
799 * @param string $component
800 * @param string $area
801 * @param int $itemid
802 * @param string $pathname
803 * @param string $filename
804 * @param bool $forcedownload
805 * @return moodle_url
807 public static function make_webservice_pluginfile_url($contextid, $component, $area, $itemid, $pathname, $filename,
808 $forcedownload = false) {
809 global $CFG;
810 $urlbase = "$CFG->httpswwwroot/webservice/pluginfile.php";
811 if ($itemid === null) {
812 return self::make_file_url($urlbase, "/$contextid/$component/$area".$pathname.$filename, $forcedownload);
813 } else {
814 return self::make_file_url($urlbase, "/$contextid/$component/$area/$itemid".$pathname.$filename, $forcedownload);
819 * Factory method for creation of url pointing to draft file of current user.
821 * @param int $draftid draft item id
822 * @param string $pathname
823 * @param string $filename
824 * @param bool $forcedownload
825 * @return moodle_url
827 public static function make_draftfile_url($draftid, $pathname, $filename, $forcedownload = false) {
828 global $CFG, $USER;
829 $urlbase = "$CFG->httpswwwroot/draftfile.php";
830 $context = context_user::instance($USER->id);
832 return self::make_file_url($urlbase, "/$context->id/user/draft/$draftid".$pathname.$filename, $forcedownload);
836 * Factory method for creating of links to legacy course files.
838 * @param int $courseid
839 * @param string $filepath
840 * @param bool $forcedownload
841 * @return moodle_url
843 public static function make_legacyfile_url($courseid, $filepath, $forcedownload = false) {
844 global $CFG;
846 $urlbase = "$CFG->wwwroot/file.php";
847 return self::make_file_url($urlbase, '/'.$courseid.'/'.$filepath, $forcedownload);
851 * Returns URL a relative path from $CFG->wwwroot
853 * Can be used for passing around urls with the wwwroot stripped
855 * @param boolean $escaped Use &amp; as params separator instead of plain &
856 * @param array $overrideparams params to add to the output url, these override existing ones with the same name.
857 * @return string Resulting URL
858 * @throws coding_exception if called on a non-local url
860 public function out_as_local_url($escaped = true, array $overrideparams = null) {
861 global $CFG;
863 $url = $this->out($escaped, $overrideparams);
864 $httpswwwroot = str_replace("http://", "https://", $CFG->wwwroot);
866 // Url should be equal to wwwroot or httpswwwroot. If not then throw exception.
867 if (($url === $CFG->wwwroot) || (strpos($url, $CFG->wwwroot.'/') === 0)) {
868 $localurl = substr($url, strlen($CFG->wwwroot));
869 return !empty($localurl) ? $localurl : '';
870 } else if (($url === $httpswwwroot) || (strpos($url, $httpswwwroot.'/') === 0)) {
871 $localurl = substr($url, strlen($httpswwwroot));
872 return !empty($localurl) ? $localurl : '';
873 } else {
874 throw new coding_exception('out_as_local_url called on a non-local URL');
879 * Returns the 'path' portion of a URL. For example, if the URL is
880 * http://www.example.org:447/my/file/is/here.txt?really=1 then this will
881 * return '/my/file/is/here.txt'.
883 * By default the path includes slash-arguments (for example,
884 * '/myfile.php/extra/arguments') so it is what you would expect from a
885 * URL path. If you don't want this behaviour, you can opt to exclude the
886 * slash arguments. (Be careful: if the $CFG variable slasharguments is
887 * disabled, these URLs will have a different format and you may need to
888 * look at the 'file' parameter too.)
890 * @param bool $includeslashargument If true, includes slash arguments
891 * @return string Path of URL
893 public function get_path($includeslashargument = true) {
894 return $this->path . ($includeslashargument ? $this->slashargument : '');
898 * Returns a given parameter value from the URL.
900 * @param string $name Name of parameter
901 * @return string Value of parameter or null if not set
903 public function get_param($name) {
904 if (array_key_exists($name, $this->params)) {
905 return $this->params[$name];
906 } else {
907 return null;
912 * Returns the 'scheme' portion of a URL. For example, if the URL is
913 * http://www.example.org:447/my/file/is/here.txt?really=1 then this will
914 * return 'http' (without the colon).
916 * @return string Scheme of the URL.
918 public function get_scheme() {
919 return $this->scheme;
923 * Returns the 'host' portion of a URL. For example, if the URL is
924 * http://www.example.org:447/my/file/is/here.txt?really=1 then this will
925 * return 'www.example.org'.
927 * @return string Host of the URL.
929 public function get_host() {
930 return $this->host;
934 * Returns the 'port' portion of a URL. For example, if the URL is
935 * http://www.example.org:447/my/file/is/here.txt?really=1 then this will
936 * return '447'.
938 * @return string Port of the URL.
940 public function get_port() {
941 return $this->port;
946 * Determine if there is data waiting to be processed from a form
948 * Used on most forms in Moodle to check for data
949 * Returns the data as an object, if it's found.
950 * This object can be used in foreach loops without
951 * casting because it's cast to (array) automatically
953 * Checks that submitted POST data exists and returns it as object.
955 * @return mixed false or object
957 function data_submitted() {
959 if (empty($_POST)) {
960 return false;
961 } else {
962 return (object)fix_utf8($_POST);
967 * Given some normal text this function will break up any
968 * long words to a given size by inserting the given character
970 * It's multibyte savvy and doesn't change anything inside html tags.
972 * @param string $string the string to be modified
973 * @param int $maxsize maximum length of the string to be returned
974 * @param string $cutchar the string used to represent word breaks
975 * @return string
977 function break_up_long_words($string, $maxsize=20, $cutchar=' ') {
979 // First of all, save all the tags inside the text to skip them.
980 $tags = array();
981 filter_save_tags($string, $tags);
983 // Process the string adding the cut when necessary.
984 $output = '';
985 $length = core_text::strlen($string);
986 $wordlength = 0;
988 for ($i=0; $i<$length; $i++) {
989 $char = core_text::substr($string, $i, 1);
990 if ($char == ' ' or $char == "\t" or $char == "\n" or $char == "\r" or $char == "<" or $char == ">") {
991 $wordlength = 0;
992 } else {
993 $wordlength++;
994 if ($wordlength > $maxsize) {
995 $output .= $cutchar;
996 $wordlength = 0;
999 $output .= $char;
1002 // Finally load the tags back again.
1003 if (!empty($tags)) {
1004 $output = str_replace(array_keys($tags), $tags, $output);
1007 return $output;
1011 * Try and close the current window using JavaScript, either immediately, or after a delay.
1013 * Echo's out the resulting XHTML & javascript
1015 * @param integer $delay a delay in seconds before closing the window. Default 0.
1016 * @param boolean $reloadopener if true, we will see if this window was a pop-up, and try
1017 * to reload the parent window before this one closes.
1019 function close_window($delay = 0, $reloadopener = false) {
1020 global $PAGE, $OUTPUT;
1022 if (!$PAGE->headerprinted) {
1023 $PAGE->set_title(get_string('closewindow'));
1024 echo $OUTPUT->header();
1025 } else {
1026 $OUTPUT->container_end_all(false);
1029 if ($reloadopener) {
1030 // Trigger the reload immediately, even if the reload is after a delay.
1031 $PAGE->requires->js_function_call('window.opener.location.reload', array(true));
1033 $OUTPUT->notification(get_string('windowclosing'), 'notifysuccess');
1035 $PAGE->requires->js_function_call('close_window', array(new stdClass()), false, $delay);
1037 echo $OUTPUT->footer();
1038 exit;
1042 * Returns a string containing a link to the user documentation for the current page.
1044 * Also contains an icon by default. Shown to teachers and admin only.
1046 * @param string $text The text to be displayed for the link
1047 * @return string The link to user documentation for this current page
1049 function page_doc_link($text='') {
1050 global $OUTPUT, $PAGE;
1051 $path = page_get_doc_link_path($PAGE);
1052 if (!$path) {
1053 return '';
1055 return $OUTPUT->doc_link($path, $text);
1059 * Returns the path to use when constructing a link to the docs.
1061 * @since Moodle 2.5.1 2.6
1062 * @param moodle_page $page
1063 * @return string
1065 function page_get_doc_link_path(moodle_page $page) {
1066 global $CFG;
1068 if (empty($CFG->docroot) || during_initial_install()) {
1069 return '';
1071 if (!has_capability('moodle/site:doclinks', $page->context)) {
1072 return '';
1075 $path = $page->docspath;
1076 if (!$path) {
1077 return '';
1079 return $path;
1084 * Validates an email to make sure it makes sense.
1086 * @param string $address The email address to validate.
1087 * @return boolean
1089 function validate_email($address) {
1091 return (bool)preg_match('#^[-!\#$%&\'*+\\/0-9=?A-Z^_`a-z{|}~]+'.
1092 '(\.[-!\#$%&\'*+\\/0-9=?A-Z^_`a-z{|}~]+)*'.
1093 '@'.
1094 '[-!\#$%&\'*+\\/0-9=?A-Z^_`a-z{|}~]+\.'.
1095 '[-!\#$%&\'*+\\./0-9=?A-Z^_`a-z{|}~]+$#',
1096 $address);
1100 * Extracts file argument either from file parameter or PATH_INFO
1102 * Note: $scriptname parameter is not needed anymore
1104 * @return string file path (only safe characters)
1106 function get_file_argument() {
1107 global $SCRIPT;
1109 $relativepath = false;
1110 $hasforcedslashargs = false;
1112 if (isset($_SERVER['REQUEST_URI']) && !empty($_SERVER['REQUEST_URI'])) {
1113 // Checks whether $_SERVER['REQUEST_URI'] contains '/pluginfile.php/'
1114 // instead of '/pluginfile.php?', when serving a file from e.g. mod_imscp or mod_scorm.
1115 if ((strpos($_SERVER['REQUEST_URI'], '/pluginfile.php/') !== false)
1116 && isset($_SERVER['PATH_INFO']) && !empty($_SERVER['PATH_INFO'])) {
1117 // Exclude edge cases like '/pluginfile.php/?file='.
1118 $args = explode('/', ltrim($_SERVER['PATH_INFO'], '/'));
1119 $hasforcedslashargs = (count($args) > 2); // Always at least: context, component and filearea.
1122 if (!$hasforcedslashargs) {
1123 $relativepath = optional_param('file', false, PARAM_PATH);
1126 if ($relativepath !== false and $relativepath !== '') {
1127 return $relativepath;
1129 $relativepath = false;
1131 // Then try extract file from the slasharguments.
1132 if (stripos($_SERVER['SERVER_SOFTWARE'], 'iis') !== false) {
1133 // NOTE: IIS tends to convert all file paths to single byte DOS encoding,
1134 // we can not use other methods because they break unicode chars,
1135 // the only ways are to use URL rewriting
1136 // OR
1137 // to properly set the 'FastCGIUtf8ServerVariables' registry key.
1138 if (isset($_SERVER['PATH_INFO']) and $_SERVER['PATH_INFO'] !== '') {
1139 // Check that PATH_INFO works == must not contain the script name.
1140 if (strpos($_SERVER['PATH_INFO'], $SCRIPT) === false) {
1141 $relativepath = clean_param(urldecode($_SERVER['PATH_INFO']), PARAM_PATH);
1144 } else {
1145 // All other apache-like servers depend on PATH_INFO.
1146 if (isset($_SERVER['PATH_INFO'])) {
1147 if (isset($_SERVER['SCRIPT_NAME']) and strpos($_SERVER['PATH_INFO'], $_SERVER['SCRIPT_NAME']) === 0) {
1148 $relativepath = substr($_SERVER['PATH_INFO'], strlen($_SERVER['SCRIPT_NAME']));
1149 } else {
1150 $relativepath = $_SERVER['PATH_INFO'];
1152 $relativepath = clean_param($relativepath, PARAM_PATH);
1156 return $relativepath;
1160 * Just returns an array of text formats suitable for a popup menu
1162 * @return array
1164 function format_text_menu() {
1165 return array (FORMAT_MOODLE => get_string('formattext'),
1166 FORMAT_HTML => get_string('formathtml'),
1167 FORMAT_PLAIN => get_string('formatplain'),
1168 FORMAT_MARKDOWN => get_string('formatmarkdown'));
1172 * Given text in a variety of format codings, this function returns the text as safe HTML.
1174 * This function should mainly be used for long strings like posts,
1175 * answers, glossary items etc. For short strings {@link format_string()}.
1177 * <pre>
1178 * Options:
1179 * trusted : If true the string won't be cleaned. Default false required noclean=true.
1180 * noclean : If true the string won't be cleaned. Default false required trusted=true.
1181 * nocache : If true the strign will not be cached and will be formatted every call. Default false.
1182 * filter : If true the string will be run through applicable filters as well. Default true.
1183 * para : If true then the returned string will be wrapped in div tags. Default true.
1184 * newlines : If true then lines newline breaks will be converted to HTML newline breaks. Default true.
1185 * context : The context that will be used for filtering.
1186 * overflowdiv : If set to true the formatted text will be encased in a div
1187 * with the class no-overflow before being returned. Default false.
1188 * allowid : If true then id attributes will not be removed, even when
1189 * using htmlpurifier. Default false.
1190 * blanktarget : If true all <a> tags will have target="_blank" added unless target is explicitly specified.
1191 * </pre>
1193 * @staticvar array $croncache
1194 * @param string $text The text to be formatted. This is raw text originally from user input.
1195 * @param int $format Identifier of the text format to be used
1196 * [FORMAT_MOODLE, FORMAT_HTML, FORMAT_PLAIN, FORMAT_MARKDOWN]
1197 * @param object/array $options text formatting options
1198 * @param int $courseiddonotuse deprecated course id, use context option instead
1199 * @return string
1201 function format_text($text, $format = FORMAT_MOODLE, $options = null, $courseiddonotuse = null) {
1202 global $CFG, $DB, $PAGE;
1204 if ($text === '' || is_null($text)) {
1205 // No need to do any filters and cleaning.
1206 return '';
1209 // Detach object, we can not modify it.
1210 $options = (array)$options;
1212 if (!isset($options['trusted'])) {
1213 $options['trusted'] = false;
1215 if (!isset($options['noclean'])) {
1216 if ($options['trusted'] and trusttext_active()) {
1217 // No cleaning if text trusted and noclean not specified.
1218 $options['noclean'] = true;
1219 } else {
1220 $options['noclean'] = false;
1223 if (!isset($options['nocache'])) {
1224 $options['nocache'] = false;
1226 if (!isset($options['filter'])) {
1227 $options['filter'] = true;
1229 if (!isset($options['para'])) {
1230 $options['para'] = true;
1232 if (!isset($options['newlines'])) {
1233 $options['newlines'] = true;
1235 if (!isset($options['overflowdiv'])) {
1236 $options['overflowdiv'] = false;
1238 $options['blanktarget'] = !empty($options['blanktarget']);
1240 // Calculate best context.
1241 if (empty($CFG->version) or $CFG->version < 2013051400 or during_initial_install()) {
1242 // Do not filter anything during installation or before upgrade completes.
1243 $context = null;
1245 } else if (isset($options['context'])) { // First by explicit passed context option.
1246 if (is_object($options['context'])) {
1247 $context = $options['context'];
1248 } else {
1249 $context = context::instance_by_id($options['context']);
1251 } else if ($courseiddonotuse) {
1252 // Legacy courseid.
1253 $context = context_course::instance($courseiddonotuse);
1254 } else {
1255 // Fallback to $PAGE->context this may be problematic in CLI and other non-standard pages :-(.
1256 $context = $PAGE->context;
1259 if (!$context) {
1260 // Either install/upgrade or something has gone really wrong because context does not exist (yet?).
1261 $options['nocache'] = true;
1262 $options['filter'] = false;
1265 if ($options['filter']) {
1266 $filtermanager = filter_manager::instance();
1267 $filtermanager->setup_page_for_filters($PAGE, $context); // Setup global stuff filters may have.
1268 $filteroptions = array(
1269 'originalformat' => $format,
1270 'noclean' => $options['noclean'],
1272 } else {
1273 $filtermanager = new null_filter_manager();
1274 $filteroptions = array();
1277 switch ($format) {
1278 case FORMAT_HTML:
1279 if (!$options['noclean']) {
1280 $text = clean_text($text, FORMAT_HTML, $options);
1282 $text = $filtermanager->filter_text($text, $context, $filteroptions);
1283 break;
1285 case FORMAT_PLAIN:
1286 $text = s($text); // Cleans dangerous JS.
1287 $text = rebuildnolinktag($text);
1288 $text = str_replace(' ', '&nbsp; ', $text);
1289 $text = nl2br($text);
1290 break;
1292 case FORMAT_WIKI:
1293 // This format is deprecated.
1294 $text = '<p>NOTICE: Wiki-like formatting has been removed from Moodle. You should not be seeing
1295 this message as all texts should have been converted to Markdown format instead.
1296 Please post a bug report to http://moodle.org/bugs with information about where you
1297 saw this message.</p>'.s($text);
1298 break;
1300 case FORMAT_MARKDOWN:
1301 $text = markdown_to_html($text);
1302 if (!$options['noclean']) {
1303 $text = clean_text($text, FORMAT_HTML, $options);
1305 $text = $filtermanager->filter_text($text, $context, $filteroptions);
1306 break;
1308 default: // FORMAT_MOODLE or anything else.
1309 $text = text_to_html($text, null, $options['para'], $options['newlines']);
1310 if (!$options['noclean']) {
1311 $text = clean_text($text, FORMAT_HTML, $options);
1313 $text = $filtermanager->filter_text($text, $context, $filteroptions);
1314 break;
1316 if ($options['filter']) {
1317 // At this point there should not be any draftfile links any more,
1318 // this happens when developers forget to post process the text.
1319 // The only potential problem is that somebody might try to format
1320 // the text before storing into database which would be itself big bug..
1321 $text = str_replace("\"$CFG->httpswwwroot/draftfile.php", "\"$CFG->httpswwwroot/brokenfile.php#", $text);
1323 if ($CFG->debugdeveloper) {
1324 if (strpos($text, '@@PLUGINFILE@@/') !== false) {
1325 debugging('Before calling format_text(), the content must be processed with file_rewrite_pluginfile_urls()',
1326 DEBUG_DEVELOPER);
1331 if (!empty($options['overflowdiv'])) {
1332 $text = html_writer::tag('div', $text, array('class' => 'no-overflow'));
1335 if ($options['blanktarget']) {
1336 $domdoc = new DOMDocument();
1337 libxml_use_internal_errors(true);
1338 $domdoc->loadHTML('<?xml version="1.0" encoding="UTF-8" ?>' . $text);
1339 libxml_clear_errors();
1340 foreach ($domdoc->getElementsByTagName('a') as $link) {
1341 if ($link->hasAttribute('target') && strpos($link->getAttribute('target'), '_blank') === false) {
1342 continue;
1344 $link->setAttribute('target', '_blank');
1345 if (strpos($link->getAttribute('rel'), 'noreferrer') === false) {
1346 $link->setAttribute('rel', trim($link->getAttribute('rel') . ' noreferrer'));
1350 // This regex is nasty and I don't like it. The correct way to solve this is by loading the HTML like so:
1351 // $domdoc->loadHTML($text, LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD); however it seems like the libxml
1352 // version that travis uses doesn't work properly and ends up leaving <html><body>, so I'm forced to use
1353 // this regex to remove those tags.
1354 $text = trim(preg_replace('~<(?:!DOCTYPE|/?(?:html|body))[^>]*>\s*~i', '', $domdoc->saveHTML($domdoc->documentElement)));
1357 return $text;
1361 * Resets some data related to filters, called during upgrade or when general filter settings change.
1363 * @param bool $phpunitreset true means called from our PHPUnit integration test reset
1364 * @return void
1366 function reset_text_filters_cache($phpunitreset = false) {
1367 global $CFG, $DB;
1369 if ($phpunitreset) {
1370 // HTMLPurifier does not change, DB is already reset to defaults,
1371 // nothing to do here, the dataroot was cleared too.
1372 return;
1375 // The purge_all_caches() deals with cachedir and localcachedir purging,
1376 // the individual filter caches are invalidated as necessary elsewhere.
1378 // Update $CFG->filterall cache flag.
1379 if (empty($CFG->stringfilters)) {
1380 set_config('filterall', 0);
1381 return;
1383 $installedfilters = core_component::get_plugin_list('filter');
1384 $filters = explode(',', $CFG->stringfilters);
1385 foreach ($filters as $filter) {
1386 if (isset($installedfilters[$filter])) {
1387 set_config('filterall', 1);
1388 return;
1391 set_config('filterall', 0);
1395 * Given a simple string, this function returns the string
1396 * processed by enabled string filters if $CFG->filterall is enabled
1398 * This function should be used to print short strings (non html) that
1399 * need filter processing e.g. activity titles, post subjects,
1400 * glossary concepts.
1402 * @staticvar bool $strcache
1403 * @param string $string The string to be filtered. Should be plain text, expect
1404 * possibly for multilang tags.
1405 * @param boolean $striplinks To strip any link in the result text. Moodle 1.8 default changed from false to true! MDL-8713
1406 * @param array $options options array/object or courseid
1407 * @return string
1409 function format_string($string, $striplinks = true, $options = null) {
1410 global $CFG, $PAGE;
1412 // We'll use a in-memory cache here to speed up repeated strings.
1413 static $strcache = false;
1415 if (empty($CFG->version) or $CFG->version < 2013051400 or during_initial_install()) {
1416 // Do not filter anything during installation or before upgrade completes.
1417 return $string = strip_tags($string);
1420 if ($strcache === false or count($strcache) > 2000) {
1421 // This number might need some tuning to limit memory usage in cron.
1422 $strcache = array();
1425 if (is_numeric($options)) {
1426 // Legacy courseid usage.
1427 $options = array('context' => context_course::instance($options));
1428 } else {
1429 // Detach object, we can not modify it.
1430 $options = (array)$options;
1433 if (empty($options['context'])) {
1434 // Fallback to $PAGE->context this may be problematic in CLI and other non-standard pages :-(.
1435 $options['context'] = $PAGE->context;
1436 } else if (is_numeric($options['context'])) {
1437 $options['context'] = context::instance_by_id($options['context']);
1439 if (!isset($options['filter'])) {
1440 $options['filter'] = true;
1443 $options['escape'] = !isset($options['escape']) || $options['escape'];
1445 if (!$options['context']) {
1446 // We did not find any context? weird.
1447 return $string = strip_tags($string);
1450 // Calculate md5.
1451 $cachekeys = array($string, $striplinks, $options['context']->id,
1452 $options['escape'], current_language(), $options['filter']);
1453 $md5 = md5(implode('<+>', $cachekeys));
1455 // Fetch from cache if possible.
1456 if (isset($strcache[$md5])) {
1457 return $strcache[$md5];
1460 // First replace all ampersands not followed by html entity code
1461 // Regular expression moved to its own method for easier unit testing.
1462 $string = $options['escape'] ? replace_ampersands_not_followed_by_entity($string) : $string;
1464 if (!empty($CFG->filterall) && $options['filter']) {
1465 $filtermanager = filter_manager::instance();
1466 $filtermanager->setup_page_for_filters($PAGE, $options['context']); // Setup global stuff filters may have.
1467 $string = $filtermanager->filter_string($string, $options['context']);
1470 // If the site requires it, strip ALL tags from this string.
1471 if (!empty($CFG->formatstringstriptags)) {
1472 if ($options['escape']) {
1473 $string = str_replace(array('<', '>'), array('&lt;', '&gt;'), strip_tags($string));
1474 } else {
1475 $string = strip_tags($string);
1477 } else {
1478 // Otherwise strip just links if that is required (default).
1479 if ($striplinks) {
1480 // Strip links in string.
1481 $string = strip_links($string);
1483 $string = clean_text($string);
1486 // Store to cache.
1487 $strcache[$md5] = $string;
1489 return $string;
1493 * Given a string, performs a negative lookahead looking for any ampersand character
1494 * that is not followed by a proper HTML entity. If any is found, it is replaced
1495 * by &amp;. The string is then returned.
1497 * @param string $string
1498 * @return string
1500 function replace_ampersands_not_followed_by_entity($string) {
1501 return preg_replace("/\&(?![a-zA-Z0-9#]{1,8};)/", "&amp;", $string);
1505 * Given a string, replaces all <a>.*</a> by .* and returns the string.
1507 * @param string $string
1508 * @return string
1510 function strip_links($string) {
1511 return preg_replace('/(<a\s[^>]+?>)(.+?)(<\/a>)/is', '$2', $string);
1515 * This expression turns links into something nice in a text format. (Russell Jungwirth)
1517 * @param string $string
1518 * @return string
1520 function wikify_links($string) {
1521 return preg_replace('~(<a [^<]*href=["|\']?([^ "\']*)["|\']?[^>]*>([^<]*)</a>)~i', '$3 [ $2 ]', $string);
1525 * Given text in a variety of format codings, this function returns the text as plain text suitable for plain email.
1527 * @param string $text The text to be formatted. This is raw text originally from user input.
1528 * @param int $format Identifier of the text format to be used
1529 * [FORMAT_MOODLE, FORMAT_HTML, FORMAT_PLAIN, FORMAT_WIKI, FORMAT_MARKDOWN]
1530 * @return string
1532 function format_text_email($text, $format) {
1534 switch ($format) {
1536 case FORMAT_PLAIN:
1537 return $text;
1538 break;
1540 case FORMAT_WIKI:
1541 // There should not be any of these any more!
1542 $text = wikify_links($text);
1543 return core_text::entities_to_utf8(strip_tags($text), true);
1544 break;
1546 case FORMAT_HTML:
1547 return html_to_text($text);
1548 break;
1550 case FORMAT_MOODLE:
1551 case FORMAT_MARKDOWN:
1552 default:
1553 $text = wikify_links($text);
1554 return core_text::entities_to_utf8(strip_tags($text), true);
1555 break;
1560 * Formats activity intro text
1562 * @param string $module name of module
1563 * @param object $activity instance of activity
1564 * @param int $cmid course module id
1565 * @param bool $filter filter resulting html text
1566 * @return string
1568 function format_module_intro($module, $activity, $cmid, $filter=true) {
1569 global $CFG;
1570 require_once("$CFG->libdir/filelib.php");
1571 $context = context_module::instance($cmid);
1572 $options = array('noclean' => true, 'para' => false, 'filter' => $filter, 'context' => $context, 'overflowdiv' => true);
1573 $intro = file_rewrite_pluginfile_urls($activity->intro, 'pluginfile.php', $context->id, 'mod_'.$module, 'intro', null);
1574 return trim(format_text($intro, $activity->introformat, $options, null));
1578 * Removes the usage of Moodle files from a text.
1580 * In some rare cases we need to re-use a text that already has embedded links
1581 * to some files hosted within Moodle. But the new area in which we will push
1582 * this content does not support files... therefore we need to remove those files.
1584 * @param string $source The text
1585 * @return string The stripped text
1587 function strip_pluginfile_content($source) {
1588 $baseurl = '@@PLUGINFILE@@';
1589 // Looking for something like < .* "@@pluginfile@@.*" .* >
1590 $pattern = '$<[^<>]+["\']' . $baseurl . '[^"\']*["\'][^<>]*>$';
1591 $stripped = preg_replace($pattern, '', $source);
1592 // Use purify html to rebalence potentially mismatched tags and generally cleanup.
1593 return purify_html($stripped);
1597 * Legacy function, used for cleaning of old forum and glossary text only.
1599 * @param string $text text that may contain legacy TRUSTTEXT marker
1600 * @return string text without legacy TRUSTTEXT marker
1602 function trusttext_strip($text) {
1603 if (!is_string($text)) {
1604 // This avoids the potential for an endless loop below.
1605 throw new coding_exception('trusttext_strip parameter must be a string');
1607 while (true) { // Removing nested TRUSTTEXT.
1608 $orig = $text;
1609 $text = str_replace('#####TRUSTTEXT#####', '', $text);
1610 if (strcmp($orig, $text) === 0) {
1611 return $text;
1617 * Must be called before editing of all texts with trust flag. Removes all XSS nasties from texts stored in database if needed.
1619 * @param stdClass $object data object with xxx, xxxformat and xxxtrust fields
1620 * @param string $field name of text field
1621 * @param context $context active context
1622 * @return stdClass updated $object
1624 function trusttext_pre_edit($object, $field, $context) {
1625 $trustfield = $field.'trust';
1626 $formatfield = $field.'format';
1628 if (!$object->$trustfield or !trusttext_trusted($context)) {
1629 $object->$field = clean_text($object->$field, $object->$formatfield);
1632 return $object;
1636 * Is current user trusted to enter no dangerous XSS in this context?
1638 * Please note the user must be in fact trusted everywhere on this server!!
1640 * @param context $context
1641 * @return bool true if user trusted
1643 function trusttext_trusted($context) {
1644 return (trusttext_active() and has_capability('moodle/site:trustcontent', $context));
1648 * Is trusttext feature active?
1650 * @return bool
1652 function trusttext_active() {
1653 global $CFG;
1655 return !empty($CFG->enabletrusttext);
1659 * Cleans raw text removing nasties.
1661 * Given raw text (eg typed in by a user) this function cleans it up and removes any nasty tags that could mess up
1662 * Moodle pages through XSS attacks.
1664 * The result must be used as a HTML text fragment, this function can not cleanup random
1665 * parts of html tags such as url or src attributes.
1667 * NOTE: the format parameter was deprecated because we can safely clean only HTML.
1669 * @param string $text The text to be cleaned
1670 * @param int|string $format deprecated parameter, should always contain FORMAT_HTML or FORMAT_MOODLE
1671 * @param array $options Array of options; currently only option supported is 'allowid' (if true,
1672 * does not remove id attributes when cleaning)
1673 * @return string The cleaned up text
1675 function clean_text($text, $format = FORMAT_HTML, $options = array()) {
1676 $text = (string)$text;
1678 if ($format != FORMAT_HTML and $format != FORMAT_HTML) {
1679 // TODO: we need to standardise cleanup of text when loading it into editor first.
1680 // debugging('clean_text() is designed to work only with html');.
1683 if ($format == FORMAT_PLAIN) {
1684 return $text;
1687 if (is_purify_html_necessary($text)) {
1688 $text = purify_html($text, $options);
1691 // Originally we tried to neutralise some script events here, it was a wrong approach because
1692 // it was trivial to work around that (for example using style based XSS exploits).
1693 // We must not give false sense of security here - all developers MUST understand how to use
1694 // rawurlencode(), htmlentities(), htmlspecialchars(), p(), s(), moodle_url, html_writer and friends!!!
1696 return $text;
1700 * Is it necessary to use HTMLPurifier?
1702 * @private
1703 * @param string $text
1704 * @return bool false means html is safe and valid, true means use HTMLPurifier
1706 function is_purify_html_necessary($text) {
1707 if ($text === '') {
1708 return false;
1711 if ($text === (string)((int)$text)) {
1712 return false;
1715 if (strpos($text, '&') !== false or preg_match('|<[^pesb/]|', $text)) {
1716 // We need to normalise entities or other tags except p, em, strong and br present.
1717 return true;
1720 $altered = htmlspecialchars($text, ENT_NOQUOTES, 'UTF-8', true);
1721 if ($altered === $text) {
1722 // No < > or other special chars means this must be safe.
1723 return false;
1726 // Let's try to convert back some safe html tags.
1727 $altered = preg_replace('|&lt;p&gt;(.*?)&lt;/p&gt;|m', '<p>$1</p>', $altered);
1728 if ($altered === $text) {
1729 return false;
1731 $altered = preg_replace('|&lt;em&gt;([^<>]+?)&lt;/em&gt;|m', '<em>$1</em>', $altered);
1732 if ($altered === $text) {
1733 return false;
1735 $altered = preg_replace('|&lt;strong&gt;([^<>]+?)&lt;/strong&gt;|m', '<strong>$1</strong>', $altered);
1736 if ($altered === $text) {
1737 return false;
1739 $altered = str_replace('&lt;br /&gt;', '<br />', $altered);
1740 if ($altered === $text) {
1741 return false;
1744 return true;
1748 * KSES replacement cleaning function - uses HTML Purifier.
1750 * @param string $text The (X)HTML string to purify
1751 * @param array $options Array of options; currently only option supported is 'allowid' (if set,
1752 * does not remove id attributes when cleaning)
1753 * @return string
1755 function purify_html($text, $options = array()) {
1756 global $CFG;
1758 $text = (string)$text;
1760 static $purifiers = array();
1761 static $caches = array();
1763 // Purifier code can change only during major version upgrade.
1764 $version = empty($CFG->version) ? 0 : $CFG->version;
1765 $cachedir = "$CFG->localcachedir/htmlpurifier/$version";
1766 if (!file_exists($cachedir)) {
1767 // Purging of caches may remove the cache dir at any time,
1768 // luckily file_exists() results should be cached for all existing directories.
1769 $purifiers = array();
1770 $caches = array();
1771 gc_collect_cycles();
1773 make_localcache_directory('htmlpurifier', false);
1774 check_dir_exists($cachedir);
1777 $allowid = empty($options['allowid']) ? 0 : 1;
1778 $allowobjectembed = empty($CFG->allowobjectembed) ? 0 : 1;
1780 $type = 'type_'.$allowid.'_'.$allowobjectembed;
1782 if (!array_key_exists($type, $caches)) {
1783 $caches[$type] = cache::make('core', 'htmlpurifier', array('type' => $type));
1785 $cache = $caches[$type];
1787 // Add revision number and all options to the text key so that it is compatible with local cluster node caches.
1788 $key = "|$version|$allowobjectembed|$allowid|$text";
1789 $filteredtext = $cache->get($key);
1791 if ($filteredtext === true) {
1792 // The filtering did not change the text last time, no need to filter anything again.
1793 return $text;
1794 } else if ($filteredtext !== false) {
1795 return $filteredtext;
1798 if (empty($purifiers[$type])) {
1799 require_once $CFG->libdir.'/htmlpurifier/HTMLPurifier.safe-includes.php';
1800 require_once $CFG->libdir.'/htmlpurifier/locallib.php';
1801 $config = HTMLPurifier_Config::createDefault();
1803 $config->set('HTML.DefinitionID', 'moodlehtml');
1804 $config->set('HTML.DefinitionRev', 6);
1805 $config->set('Cache.SerializerPath', $cachedir);
1806 $config->set('Cache.SerializerPermissions', $CFG->directorypermissions);
1807 $config->set('Core.NormalizeNewlines', false);
1808 $config->set('Core.ConvertDocumentToFragment', true);
1809 $config->set('Core.Encoding', 'UTF-8');
1810 $config->set('HTML.Doctype', 'XHTML 1.0 Transitional');
1811 $config->set('URI.AllowedSchemes', array(
1812 'http' => true,
1813 'https' => true,
1814 'ftp' => true,
1815 'irc' => true,
1816 'nntp' => true,
1817 'news' => true,
1818 'rtsp' => true,
1819 'rtmp' => true,
1820 'teamspeak' => true,
1821 'gopher' => true,
1822 'mms' => true,
1823 'mailto' => true
1825 $config->set('Attr.AllowedFrameTargets', array('_blank'));
1827 if ($allowobjectembed) {
1828 $config->set('HTML.SafeObject', true);
1829 $config->set('Output.FlashCompat', true);
1830 $config->set('HTML.SafeEmbed', true);
1833 if ($allowid) {
1834 $config->set('Attr.EnableID', true);
1837 if ($def = $config->maybeGetRawHTMLDefinition()) {
1838 $def->addElement('nolink', 'Block', 'Flow', array()); // Skip our filters inside.
1839 $def->addElement('tex', 'Inline', 'Inline', array()); // Tex syntax, equivalent to $$xx$$.
1840 $def->addElement('algebra', 'Inline', 'Inline', array()); // Algebra syntax, equivalent to @@xx@@.
1841 $def->addElement('lang', 'Block', 'Flow', array(), array('lang'=>'CDATA')); // Original multilang style - only our hacked lang attribute.
1842 $def->addAttribute('span', 'xxxlang', 'CDATA'); // Current very problematic multilang.
1844 // Media elements.
1845 // https://html.spec.whatwg.org/#the-video-element
1846 $def->addElement('video', 'Block', 'Optional: #PCDATA | Flow | source | track', 'Common', [
1847 'src' => 'URI',
1848 'crossorigin' => 'Enum#anonymous,use-credentials',
1849 'poster' => 'URI',
1850 'preload' => 'Enum#auto,metadata,none',
1851 'autoplay' => 'Bool',
1852 'playsinline' => 'Bool',
1853 'loop' => 'Bool',
1854 'muted' => 'Bool',
1855 'controls' => 'Bool',
1856 'width' => 'Length',
1857 'height' => 'Length',
1859 // https://html.spec.whatwg.org/#the-audio-element
1860 $def->addElement('audio', 'Block', 'Optional: #PCDATA | Flow | source | track', 'Common', [
1861 'src' => 'URI',
1862 'crossorigin' => 'Enum#anonymous,use-credentials',
1863 'preload' => 'Enum#auto,metadata,none',
1864 'autoplay' => 'Bool',
1865 'loop' => 'Bool',
1866 'muted' => 'Bool',
1867 'controls' => 'Bool'
1869 // https://html.spec.whatwg.org/#the-source-element
1870 $def->addElement('source', false, 'Empty', null, [
1871 'src' => 'URI',
1872 'type' => 'Text'
1874 // https://html.spec.whatwg.org/#the-track-element
1875 $def->addElement('track', false, 'Empty', null, [
1876 'src' => 'URI',
1877 'kind' => 'Enum#subtitles,captions,descriptions,chapters,metadata',
1878 'srclang' => 'Text',
1879 'label' => 'Text',
1880 'default' => 'Bool',
1883 // Use the built-in Ruby module to add annotation support.
1884 $def->manager->addModule(new HTMLPurifier_HTMLModule_Ruby());
1887 $purifier = new HTMLPurifier($config);
1888 $purifiers[$type] = $purifier;
1889 } else {
1890 $purifier = $purifiers[$type];
1893 $multilang = (strpos($text, 'class="multilang"') !== false);
1895 $filteredtext = $text;
1896 if ($multilang) {
1897 $filteredtextregex = '/<span(\s+lang="([a-zA-Z0-9_-]+)"|\s+class="multilang"){2}\s*>/';
1898 $filteredtext = preg_replace($filteredtextregex, '<span xxxlang="${2}">', $filteredtext);
1900 $filteredtext = (string)$purifier->purify($filteredtext);
1901 if ($multilang) {
1902 $filteredtext = preg_replace('/<span xxxlang="([a-zA-Z0-9_-]+)">/', '<span lang="${1}" class="multilang">', $filteredtext);
1905 if ($text === $filteredtext) {
1906 // No need to store the filtered text, next time we will just return unfiltered text
1907 // because it was not changed by purifying.
1908 $cache->set($key, true);
1909 } else {
1910 $cache->set($key, $filteredtext);
1913 return $filteredtext;
1917 * Given plain text, makes it into HTML as nicely as possible.
1919 * May contain HTML tags already.
1921 * Do not abuse this function. It is intended as lower level formatting feature used
1922 * by {@link format_text()} to convert FORMAT_MOODLE to HTML. You are supposed
1923 * to call format_text() in most of cases.
1925 * @param string $text The string to convert.
1926 * @param boolean $smileyignored Was used to determine if smiley characters should convert to smiley images, ignored now
1927 * @param boolean $para If true then the returned string will be wrapped in div tags
1928 * @param boolean $newlines If true then lines newline breaks will be converted to HTML newline breaks.
1929 * @return string
1931 function text_to_html($text, $smileyignored = null, $para = true, $newlines = true) {
1932 // Remove any whitespace that may be between HTML tags.
1933 $text = preg_replace("~>([[:space:]]+)<~i", "><", $text);
1935 // Remove any returns that precede or follow HTML tags.
1936 $text = preg_replace("~([\n\r])<~i", " <", $text);
1937 $text = preg_replace("~>([\n\r])~i", "> ", $text);
1939 // Make returns into HTML newlines.
1940 if ($newlines) {
1941 $text = nl2br($text);
1944 // Wrap the whole thing in a div if required.
1945 if ($para) {
1946 // In 1.9 this was changed from a p => div.
1947 return '<div class="text_to_html">'.$text.'</div>';
1948 } else {
1949 return $text;
1954 * Given Markdown formatted text, make it into XHTML using external function
1956 * @param string $text The markdown formatted text to be converted.
1957 * @return string Converted text
1959 function markdown_to_html($text) {
1960 global $CFG;
1962 if ($text === '' or $text === null) {
1963 return $text;
1966 require_once($CFG->libdir .'/markdown/MarkdownInterface.php');
1967 require_once($CFG->libdir .'/markdown/Markdown.php');
1968 require_once($CFG->libdir .'/markdown/MarkdownExtra.php');
1970 return \Michelf\MarkdownExtra::defaultTransform($text);
1974 * Given HTML text, make it into plain text using external function
1976 * @param string $html The text to be converted.
1977 * @param integer $width Width to wrap the text at. (optional, default 75 which
1978 * is a good value for email. 0 means do not limit line length.)
1979 * @param boolean $dolinks By default, any links in the HTML are collected, and
1980 * printed as a list at the end of the HTML. If you don't want that, set this
1981 * argument to false.
1982 * @return string plain text equivalent of the HTML.
1984 function html_to_text($html, $width = 75, $dolinks = true) {
1985 global $CFG;
1987 require_once($CFG->libdir .'/html2text/lib.php');
1989 $options = array(
1990 'width' => $width,
1991 'do_links' => 'table',
1994 if (empty($dolinks)) {
1995 $options['do_links'] = 'none';
1997 $h2t = new core_html2text($html, $options);
1998 $result = $h2t->getText();
2000 return $result;
2004 * Converts texts or strings to plain text.
2006 * - When used to convert user input introduced in an editor the text format needs to be passed in $contentformat like we usually
2007 * do in format_text.
2008 * - When this function is used for strings that are usually passed through format_string before displaying them
2009 * we need to set $contentformat to false. This will execute html_to_text as these strings can contain multilang tags if
2010 * multilang filter is applied to headings.
2012 * @param string $content The text as entered by the user
2013 * @param int|false $contentformat False for strings or the text format: FORMAT_MOODLE/FORMAT_HTML/FORMAT_PLAIN/FORMAT_MARKDOWN
2014 * @return string Plain text.
2016 function content_to_text($content, $contentformat) {
2018 switch ($contentformat) {
2019 case FORMAT_PLAIN:
2020 // Nothing here.
2021 break;
2022 case FORMAT_MARKDOWN:
2023 $content = markdown_to_html($content);
2024 $content = html_to_text($content, 75, false);
2025 break;
2026 default:
2027 // FORMAT_HTML, FORMAT_MOODLE and $contentformat = false, the later one are strings usually formatted through
2028 // format_string, we need to convert them from html because they can contain HTML (multilang filter).
2029 $content = html_to_text($content, 75, false);
2032 return trim($content, "\r\n ");
2036 * This function will highlight search words in a given string
2038 * It cares about HTML and will not ruin links. It's best to use
2039 * this function after performing any conversions to HTML.
2041 * @param string $needle The search string. Syntax like "word1 +word2 -word3" is dealt with correctly.
2042 * @param string $haystack The string (HTML) within which to highlight the search terms.
2043 * @param boolean $matchcase whether to do case-sensitive. Default case-insensitive.
2044 * @param string $prefix the string to put before each search term found.
2045 * @param string $suffix the string to put after each search term found.
2046 * @return string The highlighted HTML.
2048 function highlight($needle, $haystack, $matchcase = false,
2049 $prefix = '<span class="highlight">', $suffix = '</span>') {
2051 // Quick bail-out in trivial cases.
2052 if (empty($needle) or empty($haystack)) {
2053 return $haystack;
2056 // Break up the search term into words, discard any -words and build a regexp.
2057 $words = preg_split('/ +/', trim($needle));
2058 foreach ($words as $index => $word) {
2059 if (strpos($word, '-') === 0) {
2060 unset($words[$index]);
2061 } else if (strpos($word, '+') === 0) {
2062 $words[$index] = '\b' . preg_quote(ltrim($word, '+'), '/') . '\b'; // Match only as a complete word.
2063 } else {
2064 $words[$index] = preg_quote($word, '/');
2067 $regexp = '/(' . implode('|', $words) . ')/u'; // Char u is to do UTF-8 matching.
2068 if (!$matchcase) {
2069 $regexp .= 'i';
2072 // Another chance to bail-out if $search was only -words.
2073 if (empty($words)) {
2074 return $haystack;
2077 // Split the string into HTML tags and real content.
2078 $chunks = preg_split('/((?:<[^>]*>)+)/', $haystack, -1, PREG_SPLIT_DELIM_CAPTURE);
2080 // We have an array of alternating blocks of text, then HTML tags, then text, ...
2081 // Loop through replacing search terms in the text, and leaving the HTML unchanged.
2082 $ishtmlchunk = false;
2083 $result = '';
2084 foreach ($chunks as $chunk) {
2085 if ($ishtmlchunk) {
2086 $result .= $chunk;
2087 } else {
2088 $result .= preg_replace($regexp, $prefix . '$1' . $suffix, $chunk);
2090 $ishtmlchunk = !$ishtmlchunk;
2093 return $result;
2097 * This function will highlight instances of $needle in $haystack
2099 * It's faster that the above function {@link highlight()} and doesn't care about
2100 * HTML or anything.
2102 * @param string $needle The string to search for
2103 * @param string $haystack The string to search for $needle in
2104 * @return string The highlighted HTML
2106 function highlightfast($needle, $haystack) {
2108 if (empty($needle) or empty($haystack)) {
2109 return $haystack;
2112 $parts = explode(core_text::strtolower($needle), core_text::strtolower($haystack));
2114 if (count($parts) === 1) {
2115 return $haystack;
2118 $pos = 0;
2120 foreach ($parts as $key => $part) {
2121 $parts[$key] = substr($haystack, $pos, strlen($part));
2122 $pos += strlen($part);
2124 $parts[$key] .= '<span class="highlight">'.substr($haystack, $pos, strlen($needle)).'</span>';
2125 $pos += strlen($needle);
2128 return str_replace('<span class="highlight"></span>', '', join('', $parts));
2132 * Return a string containing 'lang', xml:lang and optionally 'dir' HTML attributes.
2134 * Internationalisation, for print_header and backup/restorelib.
2136 * @param bool $dir Default false
2137 * @return string Attributes
2139 function get_html_lang($dir = false) {
2140 $direction = '';
2141 if ($dir) {
2142 if (right_to_left()) {
2143 $direction = ' dir="rtl"';
2144 } else {
2145 $direction = ' dir="ltr"';
2148 // Accessibility: added the 'lang' attribute to $direction, used in theme <html> tag.
2149 $language = str_replace('_', '-', current_language());
2150 @header('Content-Language: '.$language);
2151 return ($direction.' lang="'.$language.'" xml:lang="'.$language.'"');
2155 // STANDARD WEB PAGE PARTS.
2158 * Send the HTTP headers that Moodle requires.
2160 * There is a backwards compatibility hack for legacy code
2161 * that needs to add custom IE compatibility directive.
2163 * Example:
2164 * <code>
2165 * if (!isset($CFG->additionalhtmlhead)) {
2166 * $CFG->additionalhtmlhead = '';
2168 * $CFG->additionalhtmlhead .= '<meta http-equiv="X-UA-Compatible" content="IE=8" />';
2169 * header('X-UA-Compatible: IE=8');
2170 * echo $OUTPUT->header();
2171 * </code>
2173 * Please note the $CFG->additionalhtmlhead alone might not work,
2174 * you should send the IE compatibility header() too.
2176 * @param string $contenttype
2177 * @param bool $cacheable Can this page be cached on back?
2178 * @return void, sends HTTP headers
2180 function send_headers($contenttype, $cacheable = true) {
2181 global $CFG;
2183 @header('Content-Type: ' . $contenttype);
2184 @header('Content-Script-Type: text/javascript');
2185 @header('Content-Style-Type: text/css');
2187 if (empty($CFG->additionalhtmlhead) or stripos($CFG->additionalhtmlhead, 'X-UA-Compatible') === false) {
2188 @header('X-UA-Compatible: IE=edge');
2191 if ($cacheable) {
2192 // Allow caching on "back" (but not on normal clicks).
2193 @header('Cache-Control: private, pre-check=0, post-check=0, max-age=0, no-transform');
2194 @header('Pragma: no-cache');
2195 @header('Expires: ');
2196 } else {
2197 // Do everything we can to always prevent clients and proxies caching.
2198 @header('Cache-Control: no-store, no-cache, must-revalidate');
2199 @header('Cache-Control: post-check=0, pre-check=0, no-transform', false);
2200 @header('Pragma: no-cache');
2201 @header('Expires: Mon, 20 Aug 1969 09:23:00 GMT');
2202 @header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
2204 @header('Accept-Ranges: none');
2206 if (empty($CFG->allowframembedding)) {
2207 @header('X-Frame-Options: sameorigin');
2212 * Return the right arrow with text ('next'), and optionally embedded in a link.
2214 * @param string $text HTML/plain text label (set to blank only for breadcrumb separator cases).
2215 * @param string $url An optional link to use in a surrounding HTML anchor.
2216 * @param bool $accesshide True if text should be hidden (for screen readers only).
2217 * @param string $addclass Additional class names for the link, or the arrow character.
2218 * @return string HTML string.
2220 function link_arrow_right($text, $url='', $accesshide=false, $addclass='') {
2221 global $OUTPUT; // TODO: move to output renderer.
2222 $arrowclass = 'arrow ';
2223 if (!$url) {
2224 $arrowclass .= $addclass;
2226 $arrow = '<span class="'.$arrowclass.'">'.$OUTPUT->rarrow().'</span>';
2227 $htmltext = '';
2228 if ($text) {
2229 $htmltext = '<span class="arrow_text">'.$text.'</span>&nbsp;';
2230 if ($accesshide) {
2231 $htmltext = get_accesshide($htmltext);
2234 if ($url) {
2235 $class = 'arrow_link';
2236 if ($addclass) {
2237 $class .= ' '.$addclass;
2239 return '<a class="'.$class.'" href="'.$url.'" title="'.preg_replace('/<.*?>/', '', $text).'">'.$htmltext.$arrow.'</a>';
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='') {
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;
2272 return '<a class="'.$class.'" href="'.$url.'" title="'.preg_replace('/<.*?>/', '', $text).'">'.$arrow.$htmltext.'</a>';
2274 return $arrow.$htmltext;
2278 * Return a HTML element with the class "accesshide", for accessibility.
2280 * Please use cautiously - where possible, text should be visible!
2282 * @param string $text Plain text.
2283 * @param string $elem Lowercase element name, default "span".
2284 * @param string $class Additional classes for the element.
2285 * @param string $attrs Additional attributes string in the form, "name='value' name2='value2'"
2286 * @return string HTML string.
2288 function get_accesshide($text, $elem='span', $class='', $attrs='') {
2289 return "<$elem class=\"accesshide $class\" $attrs>$text</$elem>";
2293 * Return the breadcrumb trail navigation separator.
2295 * @return string HTML string.
2297 function get_separator() {
2298 // Accessibility: the 'hidden' slash is preferred for screen readers.
2299 return ' '.link_arrow_right($text='/', $url='', $accesshide=true, 'sep').' ';
2303 * Print (or return) a collapsible region, that has a caption that can be clicked to expand or collapse the region.
2305 * If JavaScript is off, then the region will always be expanded.
2307 * @param string $contents the contents of the box.
2308 * @param string $classes class names added to the div that is output.
2309 * @param string $id id added to the div that is output. Must not be blank.
2310 * @param string $caption text displayed at the top. Clicking on this will cause the region to expand or contract.
2311 * @param string $userpref the name of the user preference that stores the user's preferred default state.
2312 * (May be blank if you do not wish the state to be persisted.
2313 * @param boolean $default Initial collapsed state to use if the user_preference it not set.
2314 * @param boolean $return if true, return the HTML as a string, rather than printing it.
2315 * @return string|void If $return is false, returns nothing, otherwise returns a string of HTML.
2317 function print_collapsible_region($contents, $classes, $id, $caption, $userpref = '', $default = false, $return = false) {
2318 $output = print_collapsible_region_start($classes, $id, $caption, $userpref, $default, true);
2319 $output .= $contents;
2320 $output .= print_collapsible_region_end(true);
2322 if ($return) {
2323 return $output;
2324 } else {
2325 echo $output;
2330 * Print (or return) the start of a collapsible region
2332 * The collapsibleregion has a caption that can be clicked to expand or collapse the region. If JavaScript is off, then the region
2333 * will always be expanded.
2335 * @param string $classes class names added to the div that is output.
2336 * @param string $id id added to the div that is output. Must not be blank.
2337 * @param string $caption text displayed at the top. Clicking on this will cause the region to expand or contract.
2338 * @param string $userpref the name of the user preference that stores the user's preferred default state.
2339 * (May be blank if you do not wish the state to be persisted.
2340 * @param boolean $default Initial collapsed state to use if the user_preference it not set.
2341 * @param boolean $return if true, return the HTML as a string, rather than printing it.
2342 * @return string|void if $return is false, returns nothing, otherwise returns a string of HTML.
2344 function print_collapsible_region_start($classes, $id, $caption, $userpref = '', $default = false, $return = false) {
2345 global $PAGE;
2347 // Work out the initial state.
2348 if (!empty($userpref) and is_string($userpref)) {
2349 user_preference_allow_ajax_update($userpref, PARAM_BOOL);
2350 $collapsed = get_user_preferences($userpref, $default);
2351 } else {
2352 $collapsed = $default;
2353 $userpref = false;
2356 if ($collapsed) {
2357 $classes .= ' collapsed';
2360 $output = '';
2361 $output .= '<div id="' . $id . '" class="collapsibleregion ' . $classes . '">';
2362 $output .= '<div id="' . $id . '_sizer">';
2363 $output .= '<div id="' . $id . '_caption" class="collapsibleregioncaption">';
2364 $output .= $caption . ' ';
2365 $output .= '</div><div id="' . $id . '_inner" class="collapsibleregioninner">';
2366 $PAGE->requires->js_init_call('M.util.init_collapsible_region', array($id, $userpref, get_string('clicktohideshow')));
2368 if ($return) {
2369 return $output;
2370 } else {
2371 echo $output;
2376 * Close a region started with print_collapsible_region_start.
2378 * @param boolean $return if true, return the HTML as a string, rather than printing it.
2379 * @return string|void if $return is false, returns nothing, otherwise returns a string of HTML.
2381 function print_collapsible_region_end($return = false) {
2382 $output = '</div></div></div>';
2384 if ($return) {
2385 return $output;
2386 } else {
2387 echo $output;
2392 * Print a specified group's avatar.
2394 * @param array|stdClass $group A single {@link group} object OR array of groups.
2395 * @param int $courseid The course ID.
2396 * @param boolean $large Default small picture, or large.
2397 * @param boolean $return If false print picture, otherwise return the output as string
2398 * @param boolean $link Enclose image in a link to view specified course?
2399 * @return string|void Depending on the setting of $return
2401 function print_group_picture($group, $courseid, $large=false, $return=false, $link=true) {
2402 global $CFG;
2404 if (is_array($group)) {
2405 $output = '';
2406 foreach ($group as $g) {
2407 $output .= print_group_picture($g, $courseid, $large, true, $link);
2409 if ($return) {
2410 return $output;
2411 } else {
2412 echo $output;
2413 return;
2417 $context = context_course::instance($courseid);
2419 // If there is no picture, do nothing.
2420 if (!$group->picture) {
2421 return '';
2424 // If picture is hidden, only show to those with course:managegroups.
2425 if ($group->hidepicture and !has_capability('moodle/course:managegroups', $context)) {
2426 return '';
2429 if ($link or has_capability('moodle/site:accessallgroups', $context)) {
2430 $output = '<a href="'. $CFG->wwwroot .'/user/index.php?id='. $courseid .'&amp;group='. $group->id .'">';
2431 } else {
2432 $output = '';
2434 if ($large) {
2435 $file = 'f1';
2436 } else {
2437 $file = 'f2';
2440 $grouppictureurl = moodle_url::make_pluginfile_url($context->id, 'group', 'icon', $group->id, '/', $file);
2441 $grouppictureurl->param('rev', $group->picture);
2442 $output .= '<img class="grouppicture" src="'.$grouppictureurl.'"'.
2443 ' alt="'.s(get_string('group').' '.$group->name).'" title="'.s($group->name).'"/>';
2445 if ($link or has_capability('moodle/site:accessallgroups', $context)) {
2446 $output .= '</a>';
2449 if ($return) {
2450 return $output;
2451 } else {
2452 echo $output;
2458 * Display a recent activity note
2460 * @staticvar string $strftimerecent
2461 * @param int $time A timestamp int.
2462 * @param stdClass $user A user object from the database.
2463 * @param string $text Text for display for the note
2464 * @param string $link The link to wrap around the text
2465 * @param bool $return If set to true the HTML is returned rather than echo'd
2466 * @param string $viewfullnames
2467 * @return string If $retrun was true returns HTML for a recent activity notice.
2469 function print_recent_activity_note($time, $user, $text, $link, $return=false, $viewfullnames=null) {
2470 static $strftimerecent = null;
2471 $output = '';
2473 if (is_null($viewfullnames)) {
2474 $context = context_system::instance();
2475 $viewfullnames = has_capability('moodle/site:viewfullnames', $context);
2478 if (is_null($strftimerecent)) {
2479 $strftimerecent = get_string('strftimerecent');
2482 $output .= '<div class="head">';
2483 $output .= '<div class="date">'.userdate($time, $strftimerecent).'</div>';
2484 $output .= '<div class="name">'.fullname($user, $viewfullnames).'</div>';
2485 $output .= '</div>';
2486 $output .= '<div class="info"><a href="'.$link.'">'.format_string($text, true).'</a></div>';
2488 if ($return) {
2489 return $output;
2490 } else {
2491 echo $output;
2496 * Returns a popup menu with course activity modules
2498 * Given a course this function returns a small popup menu with all the course activity modules in it, as a navigation menu
2499 * outputs a simple list structure in XHTML.
2500 * The data is taken from the serialised array stored in the course record.
2502 * @param course $course A {@link $COURSE} object.
2503 * @param array $sections
2504 * @param course_modinfo $modinfo
2505 * @param string $strsection
2506 * @param string $strjumpto
2507 * @param int $width
2508 * @param string $cmid
2509 * @return string The HTML block
2511 function navmenulist($course, $sections, $modinfo, $strsection, $strjumpto, $width=50, $cmid=0) {
2513 global $CFG, $OUTPUT;
2515 $section = -1;
2516 $menu = array();
2517 $doneheading = false;
2519 $courseformatoptions = course_get_format($course)->get_format_options();
2520 $coursecontext = context_course::instance($course->id);
2522 $menu[] = '<ul class="navmenulist"><li class="jumpto section"><span>'.$strjumpto.'</span><ul>';
2523 foreach ($modinfo->cms as $mod) {
2524 if (!$mod->has_view()) {
2525 // Don't show modules which you can't link to!
2526 continue;
2529 // For course formats using 'numsections' do not show extra sections.
2530 if (isset($courseformatoptions['numsections']) && $mod->sectionnum > $courseformatoptions['numsections']) {
2531 break;
2534 if (!$mod->uservisible) { // Do not icnlude empty sections at all.
2535 continue;
2538 if ($mod->sectionnum >= 0 and $section != $mod->sectionnum) {
2539 $thissection = $sections[$mod->sectionnum];
2541 if ($thissection->visible or
2542 (isset($courseformatoptions['hiddensections']) and !$courseformatoptions['hiddensections']) or
2543 has_capability('moodle/course:viewhiddensections', $coursecontext)) {
2544 $thissection->summary = strip_tags(format_string($thissection->summary, true));
2545 if (!$doneheading) {
2546 $menu[] = '</ul></li>';
2548 if ($course->format == 'weeks' or empty($thissection->summary)) {
2549 $item = $strsection ." ". $mod->sectionnum;
2550 } else {
2551 if (core_text::strlen($thissection->summary) < ($width-3)) {
2552 $item = $thissection->summary;
2553 } else {
2554 $item = core_text::substr($thissection->summary, 0, $width).'...';
2557 $menu[] = '<li class="section"><span>'.$item.'</span>';
2558 $menu[] = '<ul>';
2559 $doneheading = true;
2561 $section = $mod->sectionnum;
2562 } else {
2563 // No activities from this hidden section shown.
2564 continue;
2568 $url = $mod->modname .'/view.php?id='. $mod->id;
2569 $mod->name = strip_tags(format_string($mod->name ,true));
2570 if (core_text::strlen($mod->name) > ($width+5)) {
2571 $mod->name = core_text::substr($mod->name, 0, $width).'...';
2573 if (!$mod->visible) {
2574 $mod->name = '('.$mod->name.')';
2576 $class = 'activity '.$mod->modname;
2577 $class .= ($cmid == $mod->id) ? ' selected' : '';
2578 $menu[] = '<li class="'.$class.'">'.
2579 $OUTPUT->image_icon('icon', '', $mod->modname).
2580 '<a href="'.$CFG->wwwroot.'/mod/'.$url.'">'.$mod->name.'</a></li>';
2583 if ($doneheading) {
2584 $menu[] = '</ul></li>';
2586 $menu[] = '</ul></li></ul>';
2588 return implode("\n", $menu);
2592 * Prints a grade menu (as part of an existing form) with help showing all possible numerical grades and scales.
2594 * @todo Finish documenting this function
2595 * @todo Deprecate: this is only used in a few contrib modules
2597 * @param int $courseid The course ID
2598 * @param string $name
2599 * @param string $current
2600 * @param boolean $includenograde Include those with no grades
2601 * @param boolean $return If set to true returns rather than echo's
2602 * @return string|bool Depending on value of $return
2604 function print_grade_menu($courseid, $name, $current, $includenograde=true, $return=false) {
2605 global $OUTPUT;
2607 $output = '';
2608 $strscale = get_string('scale');
2609 $strscales = get_string('scales');
2611 $scales = get_scales_menu($courseid);
2612 foreach ($scales as $i => $scalename) {
2613 $grades[-$i] = $strscale .': '. $scalename;
2615 if ($includenograde) {
2616 $grades[0] = get_string('nograde');
2618 for ($i=100; $i>=1; $i--) {
2619 $grades[$i] = $i;
2621 $output .= html_writer::select($grades, $name, $current, false);
2623 $linkobject = '<span class="helplink">' . $OUTPUT->pix_icon('help', $strscales) . '</span>';
2624 $link = new moodle_url('/course/scales.php', array('id' => $courseid, 'list' => 1));
2625 $action = new popup_action('click', $link, 'ratingscales', array('height' => 400, 'width' => 500));
2626 $output .= $OUTPUT->action_link($link, $linkobject, $action, array('title' => $strscales));
2628 if ($return) {
2629 return $output;
2630 } else {
2631 echo $output;
2636 * Print an error to STDOUT and exit with a non-zero code. For commandline scripts.
2638 * Default errorcode is 1.
2640 * Very useful for perl-like error-handling:
2641 * do_somethting() or mdie("Something went wrong");
2643 * @param string $msg Error message
2644 * @param integer $errorcode Error code to emit
2646 function mdie($msg='', $errorcode=1) {
2647 trigger_error($msg);
2648 exit($errorcode);
2652 * Print a message and exit.
2654 * @param string $message The message to print in the notice
2655 * @param moodle_url|string $link The link to use for the continue button
2656 * @param object $course A course object. Unused.
2657 * @return void This function simply exits
2659 function notice ($message, $link='', $course=null) {
2660 global $PAGE, $OUTPUT;
2662 $message = clean_text($message); // In case nasties are in here.
2664 if (CLI_SCRIPT) {
2665 echo("!!$message!!\n");
2666 exit(1); // No success.
2669 if (!$PAGE->headerprinted) {
2670 // Header not yet printed.
2671 $PAGE->set_title(get_string('notice'));
2672 echo $OUTPUT->header();
2673 } else {
2674 echo $OUTPUT->container_end_all(false);
2677 echo $OUTPUT->box($message, 'generalbox', 'notice');
2678 echo $OUTPUT->continue_button($link);
2680 echo $OUTPUT->footer();
2681 exit(1); // General error code.
2685 * Redirects the user to another page, after printing a notice.
2687 * This function calls the OUTPUT redirect method, echo's the output and then dies to ensure nothing else happens.
2689 * <strong>Good practice:</strong> You should call this method before starting page
2690 * output by using any of the OUTPUT methods.
2692 * @param moodle_url|string $url A moodle_url to redirect to. Strings are not to be trusted!
2693 * @param string $message The message to display to the user
2694 * @param int $delay The delay before redirecting
2695 * @param string $messagetype The type of notification to show the message in. See constants on \core\output\notification.
2696 * @throws moodle_exception
2698 function redirect($url, $message='', $delay=null, $messagetype = \core\output\notification::NOTIFY_INFO) {
2699 global $OUTPUT, $PAGE, $CFG;
2701 if (CLI_SCRIPT or AJAX_SCRIPT) {
2702 // This is wrong - developers should not use redirect in these scripts but it should not be very likely.
2703 throw new moodle_exception('redirecterrordetected', 'error');
2706 if ($delay === null) {
2707 $delay = -1;
2710 // Prevent debug errors - make sure context is properly initialised.
2711 if ($PAGE) {
2712 $PAGE->set_context(null);
2713 $PAGE->set_pagelayout('redirect'); // No header and footer needed.
2714 $PAGE->set_title(get_string('pageshouldredirect', 'moodle'));
2717 if ($url instanceof moodle_url) {
2718 $url = $url->out(false);
2721 $debugdisableredirect = false;
2722 do {
2723 if (defined('DEBUGGING_PRINTED')) {
2724 // Some debugging already printed, no need to look more.
2725 $debugdisableredirect = true;
2726 break;
2729 if (core_useragent::is_msword()) {
2730 // Clicking a URL from MS Word sends a request to the server without cookies. If that
2731 // causes a redirect Word will open a browser pointing the new URL. If not, the URL that
2732 // was clicked is opened. Because the request from Word is without cookies, it almost
2733 // always results in a redirect to the login page, even if the user is logged in in their
2734 // browser. This is not what we want, so prevent the redirect for requests from Word.
2735 $debugdisableredirect = true;
2736 break;
2739 if (empty($CFG->debugdisplay) or empty($CFG->debug)) {
2740 // No errors should be displayed.
2741 break;
2744 if (!function_exists('error_get_last') or !$lasterror = error_get_last()) {
2745 break;
2748 if (!($lasterror['type'] & $CFG->debug)) {
2749 // Last error not interesting.
2750 break;
2753 // Watch out here, @hidden() errors are returned from error_get_last() too.
2754 if (headers_sent()) {
2755 // We already started printing something - that means errors likely printed.
2756 $debugdisableredirect = true;
2757 break;
2760 if (ob_get_level() and ob_get_contents()) {
2761 // There is something waiting to be printed, hopefully it is the errors,
2762 // but it might be some error hidden by @ too - such as the timezone mess from setup.php.
2763 $debugdisableredirect = true;
2764 break;
2766 } while (false);
2768 // Technically, HTTP/1.1 requires Location: header to contain the absolute path.
2769 // (In practice browsers accept relative paths - but still, might as well do it properly.)
2770 // This code turns relative into absolute.
2771 if (!preg_match('|^[a-z]+:|i', $url)) {
2772 // Get host name http://www.wherever.com.
2773 $hostpart = preg_replace('|^(.*?[^:/])/.*$|', '$1', $CFG->wwwroot);
2774 if (preg_match('|^/|', $url)) {
2775 // URLs beginning with / are relative to web server root so we just add them in.
2776 $url = $hostpart.$url;
2777 } else {
2778 // URLs not beginning with / are relative to path of current script, so add that on.
2779 $url = $hostpart.preg_replace('|\?.*$|', '', me()).'/../'.$url;
2781 // Replace all ..s.
2782 while (true) {
2783 $newurl = preg_replace('|/(?!\.\.)[^/]*/\.\./|', '/', $url);
2784 if ($newurl == $url) {
2785 break;
2787 $url = $newurl;
2791 // Sanitise url - we can not rely on moodle_url or our URL cleaning
2792 // because they do not support all valid external URLs.
2793 $url = preg_replace('/[\x00-\x1F\x7F]/', '', $url);
2794 $url = str_replace('"', '%22', $url);
2795 $encodedurl = preg_replace("/\&(?![a-zA-Z0-9#]{1,8};)/", "&amp;", $url);
2796 $encodedurl = preg_replace('/^.*href="([^"]*)".*$/', "\\1", clean_text('<a href="'.$encodedurl.'" />', FORMAT_HTML));
2797 $url = str_replace('&amp;', '&', $encodedurl);
2799 if (!empty($message)) {
2800 if (!$debugdisableredirect && !headers_sent()) {
2801 // A message has been provided, and the headers have not yet been sent.
2802 // Display the message as a notification on the subsequent page.
2803 \core\notification::add($message, $messagetype);
2804 $message = null;
2805 $delay = 0;
2806 } else {
2807 if ($delay === -1 || !is_numeric($delay)) {
2808 $delay = 3;
2810 $message = clean_text($message);
2812 } else {
2813 $message = get_string('pageshouldredirect');
2814 $delay = 0;
2817 // Make sure the session is closed properly, this prevents problems in IIS
2818 // and also some potential PHP shutdown issues.
2819 \core\session\manager::write_close();
2821 if ($delay == 0 && !$debugdisableredirect && !headers_sent()) {
2822 // 302 might not work for POST requests, 303 is ignored by obsolete clients.
2823 @header($_SERVER['SERVER_PROTOCOL'] . ' 303 See Other');
2824 @header('Location: '.$url);
2825 echo bootstrap_renderer::plain_redirect_message($encodedurl);
2826 exit;
2829 // Include a redirect message, even with a HTTP redirect, because that is recommended practice.
2830 if ($PAGE) {
2831 $CFG->docroot = false; // To prevent the link to moodle docs from being displayed on redirect page.
2832 echo $OUTPUT->redirect_message($encodedurl, $message, $delay, $debugdisableredirect, $messagetype);
2833 exit;
2834 } else {
2835 echo bootstrap_renderer::early_redirect_message($encodedurl, $message, $delay);
2836 exit;
2841 * Given an email address, this function will return an obfuscated version of it.
2843 * @param string $email The email address to obfuscate
2844 * @return string The obfuscated email address
2846 function obfuscate_email($email) {
2847 $i = 0;
2848 $length = strlen($email);
2849 $obfuscated = '';
2850 while ($i < $length) {
2851 if (rand(0, 2) && $email{$i}!='@') { // MDL-20619 some browsers have problems unobfuscating @.
2852 $obfuscated.='%'.dechex(ord($email{$i}));
2853 } else {
2854 $obfuscated.=$email{$i};
2856 $i++;
2858 return $obfuscated;
2862 * This function takes some text and replaces about half of the characters
2863 * with HTML entity equivalents. Return string is obviously longer.
2865 * @param string $plaintext The text to be obfuscated
2866 * @return string The obfuscated text
2868 function obfuscate_text($plaintext) {
2869 $i=0;
2870 $length = core_text::strlen($plaintext);
2871 $obfuscated='';
2872 $prevobfuscated = false;
2873 while ($i < $length) {
2874 $char = core_text::substr($plaintext, $i, 1);
2875 $ord = core_text::utf8ord($char);
2876 $numerical = ($ord >= ord('0')) && ($ord <= ord('9'));
2877 if ($prevobfuscated and $numerical ) {
2878 $obfuscated.='&#'.$ord.';';
2879 } else if (rand(0, 2)) {
2880 $obfuscated.='&#'.$ord.';';
2881 $prevobfuscated = true;
2882 } else {
2883 $obfuscated.=$char;
2884 $prevobfuscated = false;
2886 $i++;
2888 return $obfuscated;
2892 * This function uses the {@link obfuscate_email()} and {@link obfuscate_text()}
2893 * to generate a fully obfuscated email link, ready to use.
2895 * @param string $email The email address to display
2896 * @param string $label The text to displayed as hyperlink to $email
2897 * @param boolean $dimmed If true then use css class 'dimmed' for hyperlink
2898 * @param string $subject The subject of the email in the mailto link
2899 * @param string $body The content of the email in the mailto link
2900 * @return string The obfuscated mailto link
2902 function obfuscate_mailto($email, $label='', $dimmed=false, $subject = '', $body = '') {
2904 if (empty($label)) {
2905 $label = $email;
2908 $label = obfuscate_text($label);
2909 $email = obfuscate_email($email);
2910 $mailto = obfuscate_text('mailto');
2911 $url = new moodle_url("mailto:$email");
2912 $attrs = array();
2914 if (!empty($subject)) {
2915 $url->param('subject', format_string($subject));
2917 if (!empty($body)) {
2918 $url->param('body', format_string($body));
2921 // Use the obfuscated mailto.
2922 $url = preg_replace('/^mailto/', $mailto, $url->out());
2924 if ($dimmed) {
2925 $attrs['title'] = get_string('emaildisable');
2926 $attrs['class'] = 'dimmed';
2929 return html_writer::link($url, $label, $attrs);
2933 * This function is used to rebuild the <nolink> tag because some formats (PLAIN and WIKI)
2934 * will transform it to html entities
2936 * @param string $text Text to search for nolink tag in
2937 * @return string
2939 function rebuildnolinktag($text) {
2941 $text = preg_replace('/&lt;(\/*nolink)&gt;/i', '<$1>', $text);
2943 return $text;
2947 * Prints a maintenance message from $CFG->maintenance_message or default if empty.
2949 function print_maintenance_message() {
2950 global $CFG, $SITE, $PAGE, $OUTPUT;
2952 header($_SERVER['SERVER_PROTOCOL'] . ' 503 Moodle under maintenance');
2953 header('Status: 503 Moodle under maintenance');
2954 header('Retry-After: 300');
2956 $PAGE->set_pagetype('maintenance-message');
2957 $PAGE->set_pagelayout('maintenance');
2958 $PAGE->set_title(strip_tags($SITE->fullname));
2959 $PAGE->set_heading($SITE->fullname);
2960 echo $OUTPUT->header();
2961 echo $OUTPUT->heading(get_string('sitemaintenance', 'admin'));
2962 if (isset($CFG->maintenance_message) and !html_is_blank($CFG->maintenance_message)) {
2963 echo $OUTPUT->box_start('maintenance_message generalbox boxwidthwide boxaligncenter');
2964 echo $CFG->maintenance_message;
2965 echo $OUTPUT->box_end();
2967 echo $OUTPUT->footer();
2968 die;
2972 * Returns a string containing a nested list, suitable for formatting into tabs with CSS.
2974 * It is not recommended to use this function in Moodle 2.5 but it is left for backward
2975 * compartibility.
2977 * Example how to print a single line tabs:
2978 * $rows = array(
2979 * new tabobject(...),
2980 * new tabobject(...)
2981 * );
2982 * echo $OUTPUT->tabtree($rows, $selectedid);
2984 * Multiple row tabs may not look good on some devices but if you want to use them
2985 * you can specify ->subtree for the active tabobject.
2987 * @param array $tabrows An array of rows where each row is an array of tab objects
2988 * @param string $selected The id of the selected tab (whatever row it's on)
2989 * @param array $inactive An array of ids of inactive tabs that are not selectable.
2990 * @param array $activated An array of ids of other tabs that are currently activated
2991 * @param bool $return If true output is returned rather then echo'd
2992 * @return string HTML output if $return was set to true.
2994 function print_tabs($tabrows, $selected = null, $inactive = null, $activated = null, $return = false) {
2995 global $OUTPUT;
2997 $tabrows = array_reverse($tabrows);
2998 $subtree = array();
2999 foreach ($tabrows as $row) {
3000 $tree = array();
3002 foreach ($row as $tab) {
3003 $tab->inactive = is_array($inactive) && in_array((string)$tab->id, $inactive);
3004 $tab->activated = is_array($activated) && in_array((string)$tab->id, $activated);
3005 $tab->selected = (string)$tab->id == $selected;
3007 if ($tab->activated || $tab->selected) {
3008 $tab->subtree = $subtree;
3010 $tree[] = $tab;
3012 $subtree = $tree;
3014 $output = $OUTPUT->tabtree($subtree);
3015 if ($return) {
3016 return $output;
3017 } else {
3018 print $output;
3019 return !empty($output);
3024 * Alter debugging level for the current request,
3025 * the change is not saved in database.
3027 * @param int $level one of the DEBUG_* constants
3028 * @param bool $debugdisplay
3030 function set_debugging($level, $debugdisplay = null) {
3031 global $CFG;
3033 $CFG->debug = (int)$level;
3034 $CFG->debugdeveloper = (($CFG->debug & DEBUG_DEVELOPER) === DEBUG_DEVELOPER);
3036 if ($debugdisplay !== null) {
3037 $CFG->debugdisplay = (bool)$debugdisplay;
3042 * Standard Debugging Function
3044 * Returns true if the current site debugging settings are equal or above specified level.
3045 * If passed a parameter it will emit a debugging notice similar to trigger_error(). The
3046 * routing of notices is controlled by $CFG->debugdisplay
3047 * eg use like this:
3049 * 1) debugging('a normal debug notice');
3050 * 2) debugging('something really picky', DEBUG_ALL);
3051 * 3) debugging('annoying debug message only for developers', DEBUG_DEVELOPER);
3052 * 4) if (debugging()) { perform extra debugging operations (do not use print or echo) }
3054 * In code blocks controlled by debugging() (such as example 4)
3055 * any output should be routed via debugging() itself, or the lower-level
3056 * trigger_error() or error_log(). Using echo or print will break XHTML
3057 * JS and HTTP headers.
3059 * It is also possible to define NO_DEBUG_DISPLAY which redirects the message to error_log.
3061 * @param string $message a message to print
3062 * @param int $level the level at which this debugging statement should show
3063 * @param array $backtrace use different backtrace
3064 * @return bool
3066 function debugging($message = '', $level = DEBUG_NORMAL, $backtrace = null) {
3067 global $CFG, $USER;
3069 $forcedebug = false;
3070 if (!empty($CFG->debugusers) && $USER) {
3071 $debugusers = explode(',', $CFG->debugusers);
3072 $forcedebug = in_array($USER->id, $debugusers);
3075 if (!$forcedebug and (empty($CFG->debug) || ($CFG->debug != -1 and $CFG->debug < $level))) {
3076 return false;
3079 if (!isset($CFG->debugdisplay)) {
3080 $CFG->debugdisplay = ini_get_bool('display_errors');
3083 if ($message) {
3084 if (!$backtrace) {
3085 $backtrace = debug_backtrace();
3087 $from = format_backtrace($backtrace, CLI_SCRIPT || NO_DEBUG_DISPLAY);
3088 if (PHPUNIT_TEST) {
3089 if (phpunit_util::debugging_triggered($message, $level, $from)) {
3090 // We are inside test, the debug message was logged.
3091 return true;
3095 if (NO_DEBUG_DISPLAY) {
3096 // Script does not want any errors or debugging in output,
3097 // we send the info to error log instead.
3098 error_log('Debugging: ' . $message . ' in '. PHP_EOL . $from);
3100 } else if ($forcedebug or $CFG->debugdisplay) {
3101 if (!defined('DEBUGGING_PRINTED')) {
3102 define('DEBUGGING_PRINTED', 1); // Indicates we have printed something.
3104 if (CLI_SCRIPT) {
3105 echo "++ $message ++\n$from";
3106 } else {
3107 echo '<div class="notifytiny debuggingmessage" data-rel="debugging">' , $message , $from , '</div>';
3110 } else {
3111 trigger_error($message . $from, E_USER_NOTICE);
3114 return true;
3118 * Outputs a HTML comment to the browser.
3120 * This is used for those hard-to-debug pages that use bits from many different files in very confusing ways (e.g. blocks).
3122 * <code>print_location_comment(__FILE__, __LINE__);</code>
3124 * @param string $file
3125 * @param integer $line
3126 * @param boolean $return Whether to return or print the comment
3127 * @return string|void Void unless true given as third parameter
3129 function print_location_comment($file, $line, $return = false) {
3130 if ($return) {
3131 return "<!-- $file at line $line -->\n";
3132 } else {
3133 echo "<!-- $file at line $line -->\n";
3139 * Returns true if the user is using a right-to-left language.
3141 * @return boolean true if the current language is right-to-left (Hebrew, Arabic etc)
3143 function right_to_left() {
3144 return (get_string('thisdirection', 'langconfig') === 'rtl');
3149 * Returns swapped left<=> right if in RTL environment.
3151 * Part of RTL Moodles support.
3153 * @param string $align align to check
3154 * @return string
3156 function fix_align_rtl($align) {
3157 if (!right_to_left()) {
3158 return $align;
3160 if ($align == 'left') {
3161 return 'right';
3163 if ($align == 'right') {
3164 return 'left';
3166 return $align;
3171 * Returns true if the page is displayed in a popup window.
3173 * Gets the information from the URL parameter inpopup.
3175 * @todo Use a central function to create the popup calls all over Moodle and
3176 * In the moment only works with resources and probably questions.
3178 * @return boolean
3180 function is_in_popup() {
3181 $inpopup = optional_param('inpopup', '', PARAM_BOOL);
3183 return ($inpopup);
3187 * Progress trace class.
3189 * Use this class from long operations where you want to output occasional information about
3190 * what is going on, but don't know if, or in what format, the output should be.
3192 * @copyright 2009 Tim Hunt
3193 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3194 * @package core
3196 abstract class progress_trace {
3198 * Output an progress message in whatever format.
3200 * @param string $message the message to output.
3201 * @param integer $depth indent depth for this message.
3203 abstract public function output($message, $depth = 0);
3206 * Called when the processing is finished.
3208 public function finished() {
3213 * This subclass of progress_trace does not ouput anything.
3215 * @copyright 2009 Tim Hunt
3216 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3217 * @package core
3219 class null_progress_trace extends progress_trace {
3221 * Does Nothing
3223 * @param string $message
3224 * @param int $depth
3225 * @return void Does Nothing
3227 public function output($message, $depth = 0) {
3232 * This subclass of progress_trace outputs to plain text.
3234 * @copyright 2009 Tim Hunt
3235 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3236 * @package core
3238 class text_progress_trace extends progress_trace {
3240 * Output the trace message.
3242 * @param string $message
3243 * @param int $depth
3244 * @return void Output is echo'd
3246 public function output($message, $depth = 0) {
3247 mtrace(str_repeat(' ', $depth) . $message);
3252 * This subclass of progress_trace outputs as HTML.
3254 * @copyright 2009 Tim Hunt
3255 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3256 * @package core
3258 class html_progress_trace extends progress_trace {
3260 * Output the trace message.
3262 * @param string $message
3263 * @param int $depth
3264 * @return void Output is echo'd
3266 public function output($message, $depth = 0) {
3267 echo '<p>', str_repeat('&#160;&#160;', $depth), htmlspecialchars($message), "</p>\n";
3268 flush();
3273 * HTML List Progress Tree
3275 * @copyright 2009 Tim Hunt
3276 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3277 * @package core
3279 class html_list_progress_trace extends progress_trace {
3280 /** @var int */
3281 protected $currentdepth = -1;
3284 * Echo out the list
3286 * @param string $message The message to display
3287 * @param int $depth
3288 * @return void Output is echoed
3290 public function output($message, $depth = 0) {
3291 $samedepth = true;
3292 while ($this->currentdepth > $depth) {
3293 echo "</li>\n</ul>\n";
3294 $this->currentdepth -= 1;
3295 if ($this->currentdepth == $depth) {
3296 echo '<li>';
3298 $samedepth = false;
3300 while ($this->currentdepth < $depth) {
3301 echo "<ul>\n<li>";
3302 $this->currentdepth += 1;
3303 $samedepth = false;
3305 if ($samedepth) {
3306 echo "</li>\n<li>";
3308 echo htmlspecialchars($message);
3309 flush();
3313 * Called when the processing is finished.
3315 public function finished() {
3316 while ($this->currentdepth >= 0) {
3317 echo "</li>\n</ul>\n";
3318 $this->currentdepth -= 1;
3324 * This subclass of progress_trace outputs to error log.
3326 * @copyright Petr Skoda {@link http://skodak.org}
3327 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3328 * @package core
3330 class error_log_progress_trace extends progress_trace {
3331 /** @var string log prefix */
3332 protected $prefix;
3335 * Constructor.
3336 * @param string $prefix optional log prefix
3338 public function __construct($prefix = '') {
3339 $this->prefix = $prefix;
3343 * Output the trace message.
3345 * @param string $message
3346 * @param int $depth
3347 * @return void Output is sent to error log.
3349 public function output($message, $depth = 0) {
3350 error_log($this->prefix . str_repeat(' ', $depth) . $message);
3355 * Special type of trace that can be used for catching of output of other traces.
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 progress_trace_buffer extends progress_trace {
3362 /** @var progres_trace */
3363 protected $trace;
3364 /** @var bool do we pass output out */
3365 protected $passthrough;
3366 /** @var string output buffer */
3367 protected $buffer;
3370 * Constructor.
3372 * @param progress_trace $trace
3373 * @param bool $passthrough true means output and buffer, false means just buffer and no output
3375 public function __construct(progress_trace $trace, $passthrough = true) {
3376 $this->trace = $trace;
3377 $this->passthrough = $passthrough;
3378 $this->buffer = '';
3382 * Output the trace message.
3384 * @param string $message the message to output.
3385 * @param int $depth indent depth for this message.
3386 * @return void output stored in buffer
3388 public function output($message, $depth = 0) {
3389 ob_start();
3390 $this->trace->output($message, $depth);
3391 $this->buffer .= ob_get_contents();
3392 if ($this->passthrough) {
3393 ob_end_flush();
3394 } else {
3395 ob_end_clean();
3400 * Called when the processing is finished.
3402 public function finished() {
3403 ob_start();
3404 $this->trace->finished();
3405 $this->buffer .= ob_get_contents();
3406 if ($this->passthrough) {
3407 ob_end_flush();
3408 } else {
3409 ob_end_clean();
3414 * Reset internal text buffer.
3416 public function reset_buffer() {
3417 $this->buffer = '';
3421 * Return internal text buffer.
3422 * @return string buffered plain text
3424 public function get_buffer() {
3425 return $this->buffer;
3430 * Special type of trace that can be used for redirecting to multiple other traces.
3432 * @copyright Petr Skoda {@link http://skodak.org}
3433 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3434 * @package core
3436 class combined_progress_trace extends progress_trace {
3439 * An array of traces.
3440 * @var array
3442 protected $traces;
3445 * Constructs a new instance.
3447 * @param array $traces multiple traces
3449 public function __construct(array $traces) {
3450 $this->traces = $traces;
3454 * Output an progress message in whatever format.
3456 * @param string $message the message to output.
3457 * @param integer $depth indent depth for this message.
3459 public function output($message, $depth = 0) {
3460 foreach ($this->traces as $trace) {
3461 $trace->output($message, $depth);
3466 * Called when the processing is finished.
3468 public function finished() {
3469 foreach ($this->traces as $trace) {
3470 $trace->finished();
3476 * Returns a localized sentence in the current language summarizing the current password policy
3478 * @todo this should be handled by a function/method in the language pack library once we have a support for it
3479 * @uses $CFG
3480 * @return string
3482 function print_password_policy() {
3483 global $CFG;
3485 $message = '';
3486 if (!empty($CFG->passwordpolicy)) {
3487 $messages = array();
3488 $messages[] = get_string('informminpasswordlength', 'auth', $CFG->minpasswordlength);
3489 if (!empty($CFG->minpassworddigits)) {
3490 $messages[] = get_string('informminpassworddigits', 'auth', $CFG->minpassworddigits);
3492 if (!empty($CFG->minpasswordlower)) {
3493 $messages[] = get_string('informminpasswordlower', 'auth', $CFG->minpasswordlower);
3495 if (!empty($CFG->minpasswordupper)) {
3496 $messages[] = get_string('informminpasswordupper', 'auth', $CFG->minpasswordupper);
3498 if (!empty($CFG->minpasswordnonalphanum)) {
3499 $messages[] = get_string('informminpasswordnonalphanum', 'auth', $CFG->minpasswordnonalphanum);
3502 $messages = join(', ', $messages); // This is ugly but we do not have anything better yet...
3503 $message = get_string('informpasswordpolicy', 'auth', $messages);
3505 return $message;
3509 * Get the value of a help string fully prepared for display in the current language.
3511 * @param string $identifier The identifier of the string to search for.
3512 * @param string $component The module the string is associated with.
3513 * @param boolean $ajax Whether this help is called from an AJAX script.
3514 * This is used to influence text formatting and determines
3515 * which format to output the doclink in.
3516 * @param string|object|array $a An object, string or number that can be used
3517 * within translation strings
3518 * @return Object An object containing:
3519 * - heading: Any heading that there may be for this help string.
3520 * - text: The wiki-formatted help string.
3521 * - doclink: An object containing a link, the linktext, and any additional
3522 * CSS classes to apply to that link. Only present if $ajax = false.
3523 * - completedoclink: A text representation of the doclink. Only present if $ajax = true.
3525 function get_formatted_help_string($identifier, $component, $ajax = false, $a = null) {
3526 global $CFG, $OUTPUT;
3527 $sm = get_string_manager();
3529 // Do not rebuild caches here!
3530 // Devs need to learn to purge all caches after any change or disable $CFG->langstringcache.
3532 $data = new stdClass();
3534 if ($sm->string_exists($identifier, $component)) {
3535 $data->heading = format_string(get_string($identifier, $component));
3536 } else {
3537 // Gracefully fall back to an empty string.
3538 $data->heading = '';
3541 if ($sm->string_exists($identifier . '_help', $component)) {
3542 $options = new stdClass();
3543 $options->trusted = false;
3544 $options->noclean = false;
3545 $options->smiley = false;
3546 $options->filter = false;
3547 $options->para = true;
3548 $options->newlines = false;
3549 $options->overflowdiv = !$ajax;
3551 // Should be simple wiki only MDL-21695.
3552 $data->text = format_text(get_string($identifier.'_help', $component, $a), FORMAT_MARKDOWN, $options);
3554 $helplink = $identifier . '_link';
3555 if ($sm->string_exists($helplink, $component)) { // Link to further info in Moodle docs.
3556 $link = get_string($helplink, $component);
3557 $linktext = get_string('morehelp');
3559 $data->doclink = new stdClass();
3560 $url = new moodle_url(get_docs_url($link));
3561 if ($ajax) {
3562 $data->doclink->link = $url->out();
3563 $data->doclink->linktext = $linktext;
3564 $data->doclink->class = ($CFG->doctonewwindow) ? 'helplinkpopup' : '';
3565 } else {
3566 $data->completedoclink = html_writer::tag('div', $OUTPUT->doc_link($link, $linktext),
3567 array('class' => 'helpdoclink'));
3570 } else {
3571 $data->text = html_writer::tag('p',
3572 html_writer::tag('strong', 'TODO') . ": missing help string [{$identifier}_help, {$component}]");
3574 return $data;