MDL-53356 admin: Fixed erroneous sectionerror when upgrade is needed
[moodle.git] / lib / weblib.php
blobb2e7eeb81d04f4a4db6a9d362aa18e758265db27
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 // When we move to PHP 5.4 as a minimum version, change ENT_QUOTES on the
100 // next line to ENT_QUOTES | ENT_HTML5 | ENT_SUBSTITUTE, and remove the
101 // 'UTF-8' argument. Both bring a speed-increase.
102 return preg_replace('/&amp;#(\d+|x[0-9a-f]+);/i', '&#$1;', htmlspecialchars($var, ENT_QUOTES, 'UTF-8'));
106 * Add quotes to HTML characters.
108 * Prints $var with HTML characters (like "<", ">", etc.) properly quoted.
109 * This function simply calls & displays {@link s()}.
110 * @see s()
112 * @param string $var the string potentially containing HTML characters
113 * @return string
115 function p($var) {
116 echo s($var);
120 * Does proper javascript quoting.
122 * Do not use addslashes anymore, because it does not work when magic_quotes_sybase is enabled.
124 * @param mixed $var String, Array, or Object to add slashes to
125 * @return mixed quoted result
127 function addslashes_js($var) {
128 if (is_string($var)) {
129 $var = str_replace('\\', '\\\\', $var);
130 $var = str_replace(array('\'', '"', "\n", "\r", "\0"), array('\\\'', '\\"', '\\n', '\\r', '\\0'), $var);
131 $var = str_replace('</', '<\/', $var); // XHTML compliance.
132 } else if (is_array($var)) {
133 $var = array_map('addslashes_js', $var);
134 } else if (is_object($var)) {
135 $a = get_object_vars($var);
136 foreach ($a as $key => $value) {
137 $a[$key] = addslashes_js($value);
139 $var = (object)$a;
141 return $var;
145 * Remove query string from url.
147 * Takes in a URL and returns it without the querystring portion.
149 * @param string $url the url which may have a query string attached.
150 * @return string The remaining URL.
152 function strip_querystring($url) {
154 if ($commapos = strpos($url, '?')) {
155 return substr($url, 0, $commapos);
156 } else {
157 return $url;
162 * Returns the name of the current script, WITH the querystring portion.
164 * This function is necessary because PHP_SELF and REQUEST_URI and SCRIPT_NAME
165 * return different things depending on a lot of things like your OS, Web
166 * server, and the way PHP is compiled (ie. as a CGI, module, ISAPI, etc.)
167 * <b>NOTE:</b> This function returns false if the global variables needed are not set.
169 * @return mixed String or false if the global variables needed are not set.
171 function me() {
172 global $ME;
173 return $ME;
177 * Guesses the full URL of the current script.
179 * This function is using $PAGE->url, but may fall back to $FULLME which
180 * is constructed from PHP_SELF and REQUEST_URI or SCRIPT_NAME
182 * @return mixed full page URL string or false if unknown
184 function qualified_me() {
185 global $FULLME, $PAGE, $CFG;
187 if (isset($PAGE) and $PAGE->has_set_url()) {
188 // This is the only recommended way to find out current page.
189 return $PAGE->url->out(false);
191 } else {
192 if ($FULLME === null) {
193 // CLI script most probably.
194 return false;
196 if (!empty($CFG->sslproxy)) {
197 // Return only https links when using SSL proxy.
198 return preg_replace('/^http:/', 'https:', $FULLME, 1);
199 } else {
200 return $FULLME;
206 * Determines whether or not the Moodle site is being served over HTTPS.
208 * This is done simply by checking the value of $CFG->httpswwwroot, which seems
209 * to be the only reliable method.
211 * @return boolean True if site is served over HTTPS, false otherwise.
213 function is_https() {
214 global $CFG;
216 return (strpos($CFG->httpswwwroot, 'https://') === 0);
220 * Returns the cleaned local URL of the HTTP_REFERER less the URL query string parameters if required.
222 * @param bool $stripquery if true, also removes the query part of the url.
223 * @return string The resulting referer or empty string.
225 function get_local_referer($stripquery = true) {
226 if (isset($_SERVER['HTTP_REFERER'])) {
227 $referer = clean_param($_SERVER['HTTP_REFERER'], PARAM_LOCALURL);
228 if ($stripquery) {
229 return strip_querystring($referer);
230 } else {
231 return $referer;
233 } else {
234 return '';
239 * Class for creating and manipulating urls.
241 * It can be used in moodle pages where config.php has been included without any further includes.
243 * It is useful for manipulating urls with long lists of params.
244 * One situation where it will be useful is a page which links to itself to perform various actions
245 * and / or to process form data. A moodle_url object :
246 * can be created for a page to refer to itself with all the proper get params being passed from page call to
247 * page call and methods can be used to output a url including all the params, optionally adding and overriding
248 * params and can also be used to
249 * - output the url without any get params
250 * - and output the params as hidden fields to be output within a form
252 * @copyright 2007 jamiesensei
253 * @link http://docs.moodle.org/dev/lib/weblib.php_moodle_url See short write up here
254 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
255 * @package core
257 class moodle_url {
260 * Scheme, ex.: http, https
261 * @var string
263 protected $scheme = '';
266 * Hostname.
267 * @var string
269 protected $host = '';
272 * Port number, empty means default 80 or 443 in case of http.
273 * @var int
275 protected $port = '';
278 * Username for http auth.
279 * @var string
281 protected $user = '';
284 * Password for http auth.
285 * @var string
287 protected $pass = '';
290 * Script path.
291 * @var string
293 protected $path = '';
296 * Optional slash argument value.
297 * @var string
299 protected $slashargument = '';
302 * Anchor, may be also empty, null means none.
303 * @var string
305 protected $anchor = null;
308 * Url parameters as associative array.
309 * @var array
311 protected $params = array();
314 * Create new instance of moodle_url.
316 * @param moodle_url|string $url - moodle_url means make a copy of another
317 * moodle_url and change parameters, string means full url or shortened
318 * form (ex.: '/course/view.php'). It is strongly encouraged to not include
319 * query string because it may result in double encoded values. Use the
320 * $params instead. For admin URLs, just use /admin/script.php, this
321 * class takes care of the $CFG->admin issue.
322 * @param array $params these params override current params or add new
323 * @param string $anchor The anchor to use as part of the URL if there is one.
324 * @throws moodle_exception
326 public function __construct($url, array $params = null, $anchor = null) {
327 global $CFG;
329 if ($url instanceof moodle_url) {
330 $this->scheme = $url->scheme;
331 $this->host = $url->host;
332 $this->port = $url->port;
333 $this->user = $url->user;
334 $this->pass = $url->pass;
335 $this->path = $url->path;
336 $this->slashargument = $url->slashargument;
337 $this->params = $url->params;
338 $this->anchor = $url->anchor;
340 } else {
341 // Detect if anchor used.
342 $apos = strpos($url, '#');
343 if ($apos !== false) {
344 $anchor = substr($url, $apos);
345 $anchor = ltrim($anchor, '#');
346 $this->set_anchor($anchor);
347 $url = substr($url, 0, $apos);
350 // Normalise shortened form of our url ex.: '/course/view.php'.
351 if (strpos($url, '/') === 0) {
352 // We must not use httpswwwroot here, because it might be url of other page,
353 // devs have to use httpswwwroot explicitly when creating new moodle_url.
354 $url = $CFG->wwwroot.$url;
357 // Now fix the admin links if needed, no need to mess with httpswwwroot.
358 if ($CFG->admin !== 'admin') {
359 if (strpos($url, "$CFG->wwwroot/admin/") === 0) {
360 $url = str_replace("$CFG->wwwroot/admin/", "$CFG->wwwroot/$CFG->admin/", $url);
364 // Parse the $url.
365 $parts = parse_url($url);
366 if ($parts === false) {
367 throw new moodle_exception('invalidurl');
369 if (isset($parts['query'])) {
370 // Note: the values may not be correctly decoded, url parameters should be always passed as array.
371 parse_str(str_replace('&amp;', '&', $parts['query']), $this->params);
373 unset($parts['query']);
374 foreach ($parts as $key => $value) {
375 $this->$key = $value;
378 // Detect slashargument value from path - we do not support directory names ending with .php.
379 $pos = strpos($this->path, '.php/');
380 if ($pos !== false) {
381 $this->slashargument = substr($this->path, $pos + 4);
382 $this->path = substr($this->path, 0, $pos + 4);
386 $this->params($params);
387 if ($anchor !== null) {
388 $this->anchor = (string)$anchor;
393 * Add an array of params to the params for this url.
395 * The added params override existing ones if they have the same name.
397 * @param array $params Defaults to null. If null then returns all params.
398 * @return array Array of Params for url.
399 * @throws coding_exception
401 public function params(array $params = null) {
402 $params = (array)$params;
404 foreach ($params as $key => $value) {
405 if (is_int($key)) {
406 throw new coding_exception('Url parameters can not have numeric keys!');
408 if (!is_string($value)) {
409 if (is_array($value)) {
410 throw new coding_exception('Url parameters values can not be arrays!');
412 if (is_object($value) and !method_exists($value, '__toString')) {
413 throw new coding_exception('Url parameters values can not be objects, unless __toString() is defined!');
416 $this->params[$key] = (string)$value;
418 return $this->params;
422 * Remove all params if no arguments passed.
423 * Remove selected params if arguments are passed.
425 * Can be called as either remove_params('param1', 'param2')
426 * or remove_params(array('param1', 'param2')).
428 * @param string[]|string $params,... either an array of param names, or 1..n string params to remove as args.
429 * @return array url parameters
431 public function remove_params($params = null) {
432 if (!is_array($params)) {
433 $params = func_get_args();
435 foreach ($params as $param) {
436 unset($this->params[$param]);
438 return $this->params;
442 * Remove all url parameters.
444 * @todo remove the unused param.
445 * @param array $params Unused param
446 * @return void
448 public function remove_all_params($params = null) {
449 $this->params = array();
450 $this->slashargument = '';
454 * Add a param to the params for this url.
456 * The added param overrides existing one if they have the same name.
458 * @param string $paramname name
459 * @param string $newvalue Param value. If new value specified current value is overriden or parameter is added
460 * @return mixed string parameter value, null if parameter does not exist
462 public function param($paramname, $newvalue = '') {
463 if (func_num_args() > 1) {
464 // Set new value.
465 $this->params(array($paramname => $newvalue));
467 if (isset($this->params[$paramname])) {
468 return $this->params[$paramname];
469 } else {
470 return null;
475 * Merges parameters and validates them
477 * @param array $overrideparams
478 * @return array merged parameters
479 * @throws coding_exception
481 protected function merge_overrideparams(array $overrideparams = null) {
482 $overrideparams = (array)$overrideparams;
483 $params = $this->params;
484 foreach ($overrideparams as $key => $value) {
485 if (is_int($key)) {
486 throw new coding_exception('Overridden parameters can not have numeric keys!');
488 if (is_array($value)) {
489 throw new coding_exception('Overridden parameters values can not be arrays!');
491 if (is_object($value) and !method_exists($value, '__toString')) {
492 throw new coding_exception('Overridden parameters values can not be objects, unless __toString() is defined!');
494 $params[$key] = (string)$value;
496 return $params;
500 * Get the params as as a query string.
502 * This method should not be used outside of this method.
504 * @param bool $escaped Use &amp; as params separator instead of plain &
505 * @param array $overrideparams params to add to the output params, these
506 * override existing ones with the same name.
507 * @return string query string that can be added to a url.
509 public function get_query_string($escaped = true, array $overrideparams = null) {
510 $arr = array();
511 if ($overrideparams !== null) {
512 $params = $this->merge_overrideparams($overrideparams);
513 } else {
514 $params = $this->params;
516 foreach ($params as $key => $val) {
517 if (is_array($val)) {
518 foreach ($val as $index => $value) {
519 $arr[] = rawurlencode($key.'['.$index.']')."=".rawurlencode($value);
521 } else {
522 if (isset($val) && $val !== '') {
523 $arr[] = rawurlencode($key)."=".rawurlencode($val);
524 } else {
525 $arr[] = rawurlencode($key);
529 if ($escaped) {
530 return implode('&amp;', $arr);
531 } else {
532 return implode('&', $arr);
537 * Shortcut for printing of encoded URL.
539 * @return string
541 public function __toString() {
542 return $this->out(true);
546 * Output url.
548 * If you use the returned URL in HTML code, you want the escaped ampersands. If you use
549 * the returned URL in HTTP headers, you want $escaped=false.
551 * @param bool $escaped Use &amp; as params separator instead of plain &
552 * @param array $overrideparams params to add to the output url, these override existing ones with the same name.
553 * @return string Resulting URL
555 public function out($escaped = true, array $overrideparams = null) {
557 global $CFG;
559 if (!is_bool($escaped)) {
560 debugging('Escape parameter must be of type boolean, '.gettype($escaped).' given instead.');
563 $url = $this;
565 // Allow url's to be rewritten by a plugin.
566 if (isset($CFG->urlrewriteclass) && !isset($CFG->upgraderunning)) {
567 $class = $CFG->urlrewriteclass;
568 $pluginurl = $class::url_rewrite($url);
569 if ($pluginurl instanceof moodle_url) {
570 $url = $pluginurl;
574 return $url->raw_out($escaped, $overrideparams);
579 * Output url without any rewrites
581 * This is identical in signature and use to out() but doesn't call the rewrite handler.
583 * @param bool $escaped Use &amp; as params separator instead of plain &
584 * @param array $overrideparams params to add to the output url, these override existing ones with the same name.
585 * @return string Resulting URL
587 public function raw_out($escaped = true, array $overrideparams = null) {
588 if (!is_bool($escaped)) {
589 debugging('Escape parameter must be of type boolean, '.gettype($escaped).' given instead.');
592 $uri = $this->out_omit_querystring().$this->slashargument;
594 $querystring = $this->get_query_string($escaped, $overrideparams);
595 if ($querystring !== '') {
596 $uri .= '?' . $querystring;
598 if (!is_null($this->anchor)) {
599 $uri .= '#'.$this->anchor;
602 return $uri;
606 * Returns url without parameters, everything before '?'.
608 * @param bool $includeanchor if {@link self::anchor} is defined, should it be returned?
609 * @return string
611 public function out_omit_querystring($includeanchor = false) {
613 $uri = $this->scheme ? $this->scheme.':'.((strtolower($this->scheme) == 'mailto') ? '':'//'): '';
614 $uri .= $this->user ? $this->user.($this->pass? ':'.$this->pass:'').'@':'';
615 $uri .= $this->host ? $this->host : '';
616 $uri .= $this->port ? ':'.$this->port : '';
617 $uri .= $this->path ? $this->path : '';
618 if ($includeanchor and !is_null($this->anchor)) {
619 $uri .= '#' . $this->anchor;
622 return $uri;
626 * Compares this moodle_url with another.
628 * See documentation of constants for an explanation of the comparison flags.
630 * @param moodle_url $url The moodle_url object to compare
631 * @param int $matchtype The type of comparison (URL_MATCH_BASE, URL_MATCH_PARAMS, URL_MATCH_EXACT)
632 * @return bool
634 public function compare(moodle_url $url, $matchtype = URL_MATCH_EXACT) {
636 $baseself = $this->out_omit_querystring();
637 $baseother = $url->out_omit_querystring();
639 // Append index.php if there is no specific file.
640 if (substr($baseself, -1) == '/') {
641 $baseself .= 'index.php';
643 if (substr($baseother, -1) == '/') {
644 $baseother .= 'index.php';
647 // Compare the two base URLs.
648 if ($baseself != $baseother) {
649 return false;
652 if ($matchtype == URL_MATCH_BASE) {
653 return true;
656 $urlparams = $url->params();
657 foreach ($this->params() as $param => $value) {
658 if ($param == 'sesskey') {
659 continue;
661 if (!array_key_exists($param, $urlparams) || $urlparams[$param] != $value) {
662 return false;
666 if ($matchtype == URL_MATCH_PARAMS) {
667 return true;
670 foreach ($urlparams as $param => $value) {
671 if ($param == 'sesskey') {
672 continue;
674 if (!array_key_exists($param, $this->params()) || $this->param($param) != $value) {
675 return false;
679 if ($url->anchor !== $this->anchor) {
680 return false;
683 return true;
687 * Sets the anchor for the URI (the bit after the hash)
689 * @param string $anchor null means remove previous
691 public function set_anchor($anchor) {
692 if (is_null($anchor)) {
693 // Remove.
694 $this->anchor = null;
695 } else if ($anchor === '') {
696 // Special case, used as empty link.
697 $this->anchor = '';
698 } else if (preg_match('|[a-zA-Z\_\:][a-zA-Z0-9\_\-\.\:]*|', $anchor)) {
699 // Match the anchor against the NMTOKEN spec.
700 $this->anchor = $anchor;
701 } else {
702 // Bad luck, no valid anchor found.
703 $this->anchor = null;
708 * Sets the scheme for the URI (the bit before ://)
710 * @param string $scheme
712 public function set_scheme($scheme) {
713 // See http://www.ietf.org/rfc/rfc3986.txt part 3.1.
714 if (preg_match('/^[a-zA-Z][a-zA-Z0-9+.-]*$/', $scheme)) {
715 $this->scheme = $scheme;
716 } else {
717 throw new coding_exception('Bad URL scheme.');
722 * Sets the url slashargument value.
724 * @param string $path usually file path
725 * @param string $parameter name of page parameter if slasharguments not supported
726 * @param bool $supported usually null, then it depends on $CFG->slasharguments, use true or false for other servers
727 * @return void
729 public function set_slashargument($path, $parameter = 'file', $supported = null) {
730 global $CFG;
731 if (is_null($supported)) {
732 $supported = !empty($CFG->slasharguments);
735 if ($supported) {
736 $parts = explode('/', $path);
737 $parts = array_map('rawurlencode', $parts);
738 $path = implode('/', $parts);
739 $this->slashargument = $path;
740 unset($this->params[$parameter]);
742 } else {
743 $this->slashargument = '';
744 $this->params[$parameter] = $path;
748 // Static factory methods.
751 * General moodle file url.
753 * @param string $urlbase the script serving the file
754 * @param string $path
755 * @param bool $forcedownload
756 * @return moodle_url
758 public static function make_file_url($urlbase, $path, $forcedownload = false) {
759 $params = array();
760 if ($forcedownload) {
761 $params['forcedownload'] = 1;
763 $path = rtrim($path, '/');
764 $url = new moodle_url($urlbase, $params);
765 $url->set_slashargument($path);
766 return $url;
770 * Factory method for creation of url pointing to plugin file.
772 * Please note this method can be used only from the plugins to
773 * create urls of own files, it must not be used outside of plugins!
775 * @param int $contextid
776 * @param string $component
777 * @param string $area
778 * @param int $itemid
779 * @param string $pathname
780 * @param string $filename
781 * @param bool $forcedownload
782 * @return moodle_url
784 public static function make_pluginfile_url($contextid, $component, $area, $itemid, $pathname, $filename,
785 $forcedownload = false) {
786 global $CFG;
787 $urlbase = "$CFG->httpswwwroot/pluginfile.php";
788 if ($itemid === null) {
789 return self::make_file_url($urlbase, "/$contextid/$component/$area".$pathname.$filename, $forcedownload);
790 } else {
791 return self::make_file_url($urlbase, "/$contextid/$component/$area/$itemid".$pathname.$filename, $forcedownload);
796 * Factory method for creation of url pointing to plugin file.
797 * This method is the same that make_pluginfile_url but pointing to the webservice pluginfile.php script.
798 * It should be used only in external functions.
800 * @since 2.8
801 * @param int $contextid
802 * @param string $component
803 * @param string $area
804 * @param int $itemid
805 * @param string $pathname
806 * @param string $filename
807 * @param bool $forcedownload
808 * @return moodle_url
810 public static function make_webservice_pluginfile_url($contextid, $component, $area, $itemid, $pathname, $filename,
811 $forcedownload = false) {
812 global $CFG;
813 $urlbase = "$CFG->httpswwwroot/webservice/pluginfile.php";
814 if ($itemid === null) {
815 return self::make_file_url($urlbase, "/$contextid/$component/$area".$pathname.$filename, $forcedownload);
816 } else {
817 return self::make_file_url($urlbase, "/$contextid/$component/$area/$itemid".$pathname.$filename, $forcedownload);
822 * Factory method for creation of url pointing to draft file of current user.
824 * @param int $draftid draft item id
825 * @param string $pathname
826 * @param string $filename
827 * @param bool $forcedownload
828 * @return moodle_url
830 public static function make_draftfile_url($draftid, $pathname, $filename, $forcedownload = false) {
831 global $CFG, $USER;
832 $urlbase = "$CFG->httpswwwroot/draftfile.php";
833 $context = context_user::instance($USER->id);
835 return self::make_file_url($urlbase, "/$context->id/user/draft/$draftid".$pathname.$filename, $forcedownload);
839 * Factory method for creating of links to legacy course files.
841 * @param int $courseid
842 * @param string $filepath
843 * @param bool $forcedownload
844 * @return moodle_url
846 public static function make_legacyfile_url($courseid, $filepath, $forcedownload = false) {
847 global $CFG;
849 $urlbase = "$CFG->wwwroot/file.php";
850 return self::make_file_url($urlbase, '/'.$courseid.'/'.$filepath, $forcedownload);
854 * Returns URL a relative path from $CFG->wwwroot
856 * Can be used for passing around urls with the wwwroot stripped
858 * @param boolean $escaped Use &amp; as params separator instead of plain &
859 * @param array $overrideparams params to add to the output url, these override existing ones with the same name.
860 * @return string Resulting URL
861 * @throws coding_exception if called on a non-local url
863 public function out_as_local_url($escaped = true, array $overrideparams = null) {
864 global $CFG;
866 $url = $this->out($escaped, $overrideparams);
867 $httpswwwroot = str_replace("http://", "https://", $CFG->wwwroot);
869 // Url should be equal to wwwroot or httpswwwroot. If not then throw exception.
870 if (($url === $CFG->wwwroot) || (strpos($url, $CFG->wwwroot.'/') === 0)) {
871 $localurl = substr($url, strlen($CFG->wwwroot));
872 return !empty($localurl) ? $localurl : '';
873 } else if (($url === $httpswwwroot) || (strpos($url, $httpswwwroot.'/') === 0)) {
874 $localurl = substr($url, strlen($httpswwwroot));
875 return !empty($localurl) ? $localurl : '';
876 } else {
877 throw new coding_exception('out_as_local_url called on a non-local URL');
882 * Returns the 'path' portion of a URL. For example, if the URL is
883 * http://www.example.org:447/my/file/is/here.txt?really=1 then this will
884 * return '/my/file/is/here.txt'.
886 * By default the path includes slash-arguments (for example,
887 * '/myfile.php/extra/arguments') so it is what you would expect from a
888 * URL path. If you don't want this behaviour, you can opt to exclude the
889 * slash arguments. (Be careful: if the $CFG variable slasharguments is
890 * disabled, these URLs will have a different format and you may need to
891 * look at the 'file' parameter too.)
893 * @param bool $includeslashargument If true, includes slash arguments
894 * @return string Path of URL
896 public function get_path($includeslashargument = true) {
897 return $this->path . ($includeslashargument ? $this->slashargument : '');
901 * Returns a given parameter value from the URL.
903 * @param string $name Name of parameter
904 * @return string Value of parameter or null if not set
906 public function get_param($name) {
907 if (array_key_exists($name, $this->params)) {
908 return $this->params[$name];
909 } else {
910 return null;
915 * Returns the 'scheme' portion of a URL. For example, if the URL is
916 * http://www.example.org:447/my/file/is/here.txt?really=1 then this will
917 * return 'http' (without the colon).
919 * @return string Scheme of the URL.
921 public function get_scheme() {
922 return $this->scheme;
926 * Returns the 'host' portion of a URL. For example, if the URL is
927 * http://www.example.org:447/my/file/is/here.txt?really=1 then this will
928 * return 'www.example.org'.
930 * @return string Host of the URL.
932 public function get_host() {
933 return $this->host;
937 * Returns the 'port' portion of a URL. For example, if the URL is
938 * http://www.example.org:447/my/file/is/here.txt?really=1 then this will
939 * return '447'.
941 * @return string Port of the URL.
943 public function get_port() {
944 return $this->port;
949 * Determine if there is data waiting to be processed from a form
951 * Used on most forms in Moodle to check for data
952 * Returns the data as an object, if it's found.
953 * This object can be used in foreach loops without
954 * casting because it's cast to (array) automatically
956 * Checks that submitted POST data exists and returns it as object.
958 * @return mixed false or object
960 function data_submitted() {
962 if (empty($_POST)) {
963 return false;
964 } else {
965 return (object)fix_utf8($_POST);
970 * Given some normal text this function will break up any
971 * long words to a given size by inserting the given character
973 * It's multibyte savvy and doesn't change anything inside html tags.
975 * @param string $string the string to be modified
976 * @param int $maxsize maximum length of the string to be returned
977 * @param string $cutchar the string used to represent word breaks
978 * @return string
980 function break_up_long_words($string, $maxsize=20, $cutchar=' ') {
982 // First of all, save all the tags inside the text to skip them.
983 $tags = array();
984 filter_save_tags($string, $tags);
986 // Process the string adding the cut when necessary.
987 $output = '';
988 $length = core_text::strlen($string);
989 $wordlength = 0;
991 for ($i=0; $i<$length; $i++) {
992 $char = core_text::substr($string, $i, 1);
993 if ($char == ' ' or $char == "\t" or $char == "\n" or $char == "\r" or $char == "<" or $char == ">") {
994 $wordlength = 0;
995 } else {
996 $wordlength++;
997 if ($wordlength > $maxsize) {
998 $output .= $cutchar;
999 $wordlength = 0;
1002 $output .= $char;
1005 // Finally load the tags back again.
1006 if (!empty($tags)) {
1007 $output = str_replace(array_keys($tags), $tags, $output);
1010 return $output;
1014 * Try and close the current window using JavaScript, either immediately, or after a delay.
1016 * Echo's out the resulting XHTML & javascript
1018 * @param integer $delay a delay in seconds before closing the window. Default 0.
1019 * @param boolean $reloadopener if true, we will see if this window was a pop-up, and try
1020 * to reload the parent window before this one closes.
1022 function close_window($delay = 0, $reloadopener = false) {
1023 global $PAGE, $OUTPUT;
1025 if (!$PAGE->headerprinted) {
1026 $PAGE->set_title(get_string('closewindow'));
1027 echo $OUTPUT->header();
1028 } else {
1029 $OUTPUT->container_end_all(false);
1032 if ($reloadopener) {
1033 // Trigger the reload immediately, even if the reload is after a delay.
1034 $PAGE->requires->js_function_call('window.opener.location.reload', array(true));
1036 $OUTPUT->notification(get_string('windowclosing'), 'notifysuccess');
1038 $PAGE->requires->js_function_call('close_window', array(new stdClass()), false, $delay);
1040 echo $OUTPUT->footer();
1041 exit;
1045 * Returns a string containing a link to the user documentation for the current page.
1047 * Also contains an icon by default. Shown to teachers and admin only.
1049 * @param string $text The text to be displayed for the link
1050 * @return string The link to user documentation for this current page
1052 function page_doc_link($text='') {
1053 global $OUTPUT, $PAGE;
1054 $path = page_get_doc_link_path($PAGE);
1055 if (!$path) {
1056 return '';
1058 return $OUTPUT->doc_link($path, $text);
1062 * Returns the path to use when constructing a link to the docs.
1064 * @since Moodle 2.5.1 2.6
1065 * @param moodle_page $page
1066 * @return string
1068 function page_get_doc_link_path(moodle_page $page) {
1069 global $CFG;
1071 if (empty($CFG->docroot) || during_initial_install()) {
1072 return '';
1074 if (!has_capability('moodle/site:doclinks', $page->context)) {
1075 return '';
1078 $path = $page->docspath;
1079 if (!$path) {
1080 return '';
1082 return $path;
1087 * Validates an email to make sure it makes sense.
1089 * @param string $address The email address to validate.
1090 * @return boolean
1092 function validate_email($address) {
1094 return (preg_match('#^[-!\#$%&\'*+\\/0-9=?A-Z^_`a-z{|}~]+'.
1095 '(\.[-!\#$%&\'*+\\/0-9=?A-Z^_`a-z{|}~]+)*'.
1096 '@'.
1097 '[-!\#$%&\'*+\\/0-9=?A-Z^_`a-z{|}~]+\.'.
1098 '[-!\#$%&\'*+\\./0-9=?A-Z^_`a-z{|}~]+$#',
1099 $address));
1103 * Extracts file argument either from file parameter or PATH_INFO
1105 * Note: $scriptname parameter is not needed anymore
1107 * @return string file path (only safe characters)
1109 function get_file_argument() {
1110 global $SCRIPT;
1112 $relativepath = optional_param('file', false, PARAM_PATH);
1114 if ($relativepath !== false and $relativepath !== '') {
1115 return $relativepath;
1117 $relativepath = false;
1119 // Then try extract file from the slasharguments.
1120 if (stripos($_SERVER['SERVER_SOFTWARE'], 'iis') !== false) {
1121 // NOTE: IIS tends to convert all file paths to single byte DOS encoding,
1122 // we can not use other methods because they break unicode chars,
1123 // the only ways are to use URL rewriting
1124 // OR
1125 // to properly set the 'FastCGIUtf8ServerVariables' registry key.
1126 if (isset($_SERVER['PATH_INFO']) and $_SERVER['PATH_INFO'] !== '') {
1127 // Check that PATH_INFO works == must not contain the script name.
1128 if (strpos($_SERVER['PATH_INFO'], $SCRIPT) === false) {
1129 $relativepath = clean_param(urldecode($_SERVER['PATH_INFO']), PARAM_PATH);
1132 } else {
1133 // All other apache-like servers depend on PATH_INFO.
1134 if (isset($_SERVER['PATH_INFO'])) {
1135 if (isset($_SERVER['SCRIPT_NAME']) and strpos($_SERVER['PATH_INFO'], $_SERVER['SCRIPT_NAME']) === 0) {
1136 $relativepath = substr($_SERVER['PATH_INFO'], strlen($_SERVER['SCRIPT_NAME']));
1137 } else {
1138 $relativepath = $_SERVER['PATH_INFO'];
1140 $relativepath = clean_param($relativepath, PARAM_PATH);
1144 return $relativepath;
1148 * Just returns an array of text formats suitable for a popup menu
1150 * @return array
1152 function format_text_menu() {
1153 return array (FORMAT_MOODLE => get_string('formattext'),
1154 FORMAT_HTML => get_string('formathtml'),
1155 FORMAT_PLAIN => get_string('formatplain'),
1156 FORMAT_MARKDOWN => get_string('formatmarkdown'));
1160 * Given text in a variety of format codings, this function returns the text as safe HTML.
1162 * This function should mainly be used for long strings like posts,
1163 * answers, glossary items etc. For short strings {@link format_string()}.
1165 * <pre>
1166 * Options:
1167 * trusted : If true the string won't be cleaned. Default false required noclean=true.
1168 * noclean : If true the string won't be cleaned. Default false required trusted=true.
1169 * nocache : If true the strign will not be cached and will be formatted every call. Default false.
1170 * filter : If true the string will be run through applicable filters as well. Default true.
1171 * para : If true then the returned string will be wrapped in div tags. Default true.
1172 * newlines : If true then lines newline breaks will be converted to HTML newline breaks. Default true.
1173 * context : The context that will be used for filtering.
1174 * overflowdiv : If set to true the formatted text will be encased in a div
1175 * with the class no-overflow before being returned. Default false.
1176 * allowid : If true then id attributes will not be removed, even when
1177 * using htmlpurifier. Default false.
1178 * </pre>
1180 * @staticvar array $croncache
1181 * @param string $text The text to be formatted. This is raw text originally from user input.
1182 * @param int $format Identifier of the text format to be used
1183 * [FORMAT_MOODLE, FORMAT_HTML, FORMAT_PLAIN, FORMAT_MARKDOWN]
1184 * @param object/array $options text formatting options
1185 * @param int $courseiddonotuse deprecated course id, use context option instead
1186 * @return string
1188 function format_text($text, $format = FORMAT_MOODLE, $options = null, $courseiddonotuse = null) {
1189 global $CFG, $DB, $PAGE;
1191 if ($text === '' || is_null($text)) {
1192 // No need to do any filters and cleaning.
1193 return '';
1196 // Detach object, we can not modify it.
1197 $options = (array)$options;
1199 if (!isset($options['trusted'])) {
1200 $options['trusted'] = false;
1202 if (!isset($options['noclean'])) {
1203 if ($options['trusted'] and trusttext_active()) {
1204 // No cleaning if text trusted and noclean not specified.
1205 $options['noclean'] = true;
1206 } else {
1207 $options['noclean'] = false;
1210 if (!isset($options['nocache'])) {
1211 $options['nocache'] = false;
1213 if (!isset($options['filter'])) {
1214 $options['filter'] = true;
1216 if (!isset($options['para'])) {
1217 $options['para'] = true;
1219 if (!isset($options['newlines'])) {
1220 $options['newlines'] = true;
1222 if (!isset($options['overflowdiv'])) {
1223 $options['overflowdiv'] = false;
1226 // Calculate best context.
1227 if (empty($CFG->version) or $CFG->version < 2013051400 or during_initial_install()) {
1228 // Do not filter anything during installation or before upgrade completes.
1229 $context = null;
1231 } else if (isset($options['context'])) { // First by explicit passed context option.
1232 if (is_object($options['context'])) {
1233 $context = $options['context'];
1234 } else {
1235 $context = context::instance_by_id($options['context']);
1237 } else if ($courseiddonotuse) {
1238 // Legacy courseid.
1239 $context = context_course::instance($courseiddonotuse);
1240 } else {
1241 // Fallback to $PAGE->context this may be problematic in CLI and other non-standard pages :-(.
1242 $context = $PAGE->context;
1245 if (!$context) {
1246 // Either install/upgrade or something has gone really wrong because context does not exist (yet?).
1247 $options['nocache'] = true;
1248 $options['filter'] = false;
1251 if ($options['filter']) {
1252 $filtermanager = filter_manager::instance();
1253 $filtermanager->setup_page_for_filters($PAGE, $context); // Setup global stuff filters may have.
1254 $filteroptions = array(
1255 'originalformat' => $format,
1256 'noclean' => $options['noclean'],
1258 } else {
1259 $filtermanager = new null_filter_manager();
1260 $filteroptions = array();
1263 switch ($format) {
1264 case FORMAT_HTML:
1265 if (!$options['noclean']) {
1266 $text = clean_text($text, FORMAT_HTML, $options);
1268 $text = $filtermanager->filter_text($text, $context, $filteroptions);
1269 break;
1271 case FORMAT_PLAIN:
1272 $text = s($text); // Cleans dangerous JS.
1273 $text = rebuildnolinktag($text);
1274 $text = str_replace(' ', '&nbsp; ', $text);
1275 $text = nl2br($text);
1276 break;
1278 case FORMAT_WIKI:
1279 // This format is deprecated.
1280 $text = '<p>NOTICE: Wiki-like formatting has been removed from Moodle. You should not be seeing
1281 this message as all texts should have been converted to Markdown format instead.
1282 Please post a bug report to http://moodle.org/bugs with information about where you
1283 saw this message.</p>'.s($text);
1284 break;
1286 case FORMAT_MARKDOWN:
1287 $text = markdown_to_html($text);
1288 if (!$options['noclean']) {
1289 $text = clean_text($text, FORMAT_HTML, $options);
1291 $text = $filtermanager->filter_text($text, $context, $filteroptions);
1292 break;
1294 default: // FORMAT_MOODLE or anything else.
1295 $text = text_to_html($text, null, $options['para'], $options['newlines']);
1296 if (!$options['noclean']) {
1297 $text = clean_text($text, FORMAT_HTML, $options);
1299 $text = $filtermanager->filter_text($text, $context, $filteroptions);
1300 break;
1302 if ($options['filter']) {
1303 // At this point there should not be any draftfile links any more,
1304 // this happens when developers forget to post process the text.
1305 // The only potential problem is that somebody might try to format
1306 // the text before storing into database which would be itself big bug..
1307 $text = str_replace("\"$CFG->httpswwwroot/draftfile.php", "\"$CFG->httpswwwroot/brokenfile.php#", $text);
1309 if ($CFG->debugdeveloper) {
1310 if (strpos($text, '@@PLUGINFILE@@/') !== false) {
1311 debugging('Before calling format_text(), the content must be processed with file_rewrite_pluginfile_urls()',
1312 DEBUG_DEVELOPER);
1317 if (!empty($options['overflowdiv'])) {
1318 $text = html_writer::tag('div', $text, array('class' => 'no-overflow'));
1321 return $text;
1325 * Resets some data related to filters, called during upgrade or when general filter settings change.
1327 * @param bool $phpunitreset true means called from our PHPUnit integration test reset
1328 * @return void
1330 function reset_text_filters_cache($phpunitreset = false) {
1331 global $CFG, $DB;
1333 if ($phpunitreset) {
1334 // HTMLPurifier does not change, DB is already reset to defaults,
1335 // nothing to do here, the dataroot was cleared too.
1336 return;
1339 // The purge_all_caches() deals with cachedir and localcachedir purging,
1340 // the individual filter caches are invalidated as necessary elsewhere.
1342 // Update $CFG->filterall cache flag.
1343 if (empty($CFG->stringfilters)) {
1344 set_config('filterall', 0);
1345 return;
1347 $installedfilters = core_component::get_plugin_list('filter');
1348 $filters = explode(',', $CFG->stringfilters);
1349 foreach ($filters as $filter) {
1350 if (isset($installedfilters[$filter])) {
1351 set_config('filterall', 1);
1352 return;
1355 set_config('filterall', 0);
1359 * Given a simple string, this function returns the string
1360 * processed by enabled string filters if $CFG->filterall is enabled
1362 * This function should be used to print short strings (non html) that
1363 * need filter processing e.g. activity titles, post subjects,
1364 * glossary concepts.
1366 * @staticvar bool $strcache
1367 * @param string $string The string to be filtered. Should be plain text, expect
1368 * possibly for multilang tags.
1369 * @param boolean $striplinks To strip any link in the result text. Moodle 1.8 default changed from false to true! MDL-8713
1370 * @param array $options options array/object or courseid
1371 * @return string
1373 function format_string($string, $striplinks = true, $options = null) {
1374 global $CFG, $PAGE;
1376 // We'll use a in-memory cache here to speed up repeated strings.
1377 static $strcache = false;
1379 if (empty($CFG->version) or $CFG->version < 2013051400 or during_initial_install()) {
1380 // Do not filter anything during installation or before upgrade completes.
1381 return $string = strip_tags($string);
1384 if ($strcache === false or count($strcache) > 2000) {
1385 // This number might need some tuning to limit memory usage in cron.
1386 $strcache = array();
1389 if (is_numeric($options)) {
1390 // Legacy courseid usage.
1391 $options = array('context' => context_course::instance($options));
1392 } else {
1393 // Detach object, we can not modify it.
1394 $options = (array)$options;
1397 if (empty($options['context'])) {
1398 // Fallback to $PAGE->context this may be problematic in CLI and other non-standard pages :-(.
1399 $options['context'] = $PAGE->context;
1400 } else if (is_numeric($options['context'])) {
1401 $options['context'] = context::instance_by_id($options['context']);
1403 if (!isset($options['filter'])) {
1404 $options['filter'] = true;
1407 if (!$options['context']) {
1408 // We did not find any context? weird.
1409 return $string = strip_tags($string);
1412 // Calculate md5.
1413 $md5 = md5($string.'<+>'.$striplinks.'<+>'.$options['context']->id.'<+>'.current_language());
1415 // Fetch from cache if possible.
1416 if (isset($strcache[$md5])) {
1417 return $strcache[$md5];
1420 // First replace all ampersands not followed by html entity code
1421 // Regular expression moved to its own method for easier unit testing.
1422 $string = replace_ampersands_not_followed_by_entity($string);
1424 if (!empty($CFG->filterall) && $options['filter']) {
1425 $filtermanager = filter_manager::instance();
1426 $filtermanager->setup_page_for_filters($PAGE, $options['context']); // Setup global stuff filters may have.
1427 $string = $filtermanager->filter_string($string, $options['context']);
1430 // If the site requires it, strip ALL tags from this string.
1431 if (!empty($CFG->formatstringstriptags)) {
1432 $string = str_replace(array('<', '>'), array('&lt;', '&gt;'), strip_tags($string));
1434 } else {
1435 // Otherwise strip just links if that is required (default).
1436 if ($striplinks) {
1437 // Strip links in string.
1438 $string = strip_links($string);
1440 $string = clean_text($string);
1443 // Store to cache.
1444 $strcache[$md5] = $string;
1446 return $string;
1450 * Given a string, performs a negative lookahead looking for any ampersand character
1451 * that is not followed by a proper HTML entity. If any is found, it is replaced
1452 * by &amp;. The string is then returned.
1454 * @param string $string
1455 * @return string
1457 function replace_ampersands_not_followed_by_entity($string) {
1458 return preg_replace("/\&(?![a-zA-Z0-9#]{1,8};)/", "&amp;", $string);
1462 * Given a string, replaces all <a>.*</a> by .* and returns the string.
1464 * @param string $string
1465 * @return string
1467 function strip_links($string) {
1468 return preg_replace('/(<a\s[^>]+?>)(.+?)(<\/a>)/is', '$2', $string);
1472 * This expression turns links into something nice in a text format. (Russell Jungwirth)
1474 * @param string $string
1475 * @return string
1477 function wikify_links($string) {
1478 return preg_replace('~(<a [^<]*href=["|\']?([^ "\']*)["|\']?[^>]*>([^<]*)</a>)~i', '$3 [ $2 ]', $string);
1482 * Given text in a variety of format codings, this function returns the text as plain text suitable for plain email.
1484 * @param string $text The text to be formatted. This is raw text originally from user input.
1485 * @param int $format Identifier of the text format to be used
1486 * [FORMAT_MOODLE, FORMAT_HTML, FORMAT_PLAIN, FORMAT_WIKI, FORMAT_MARKDOWN]
1487 * @return string
1489 function format_text_email($text, $format) {
1491 switch ($format) {
1493 case FORMAT_PLAIN:
1494 return $text;
1495 break;
1497 case FORMAT_WIKI:
1498 // There should not be any of these any more!
1499 $text = wikify_links($text);
1500 return core_text::entities_to_utf8(strip_tags($text), true);
1501 break;
1503 case FORMAT_HTML:
1504 return html_to_text($text);
1505 break;
1507 case FORMAT_MOODLE:
1508 case FORMAT_MARKDOWN:
1509 default:
1510 $text = wikify_links($text);
1511 return core_text::entities_to_utf8(strip_tags($text), true);
1512 break;
1517 * Formats activity intro text
1519 * @param string $module name of module
1520 * @param object $activity instance of activity
1521 * @param int $cmid course module id
1522 * @param bool $filter filter resulting html text
1523 * @return string
1525 function format_module_intro($module, $activity, $cmid, $filter=true) {
1526 global $CFG;
1527 require_once("$CFG->libdir/filelib.php");
1528 $context = context_module::instance($cmid);
1529 $options = array('noclean' => true, 'para' => false, 'filter' => $filter, 'context' => $context, 'overflowdiv' => true);
1530 $intro = file_rewrite_pluginfile_urls($activity->intro, 'pluginfile.php', $context->id, 'mod_'.$module, 'intro', null);
1531 return trim(format_text($intro, $activity->introformat, $options, null));
1535 * Removes the usage of Moodle files from a text.
1537 * In some rare cases we need to re-use a text that already has embedded links
1538 * to some files hosted within Moodle. But the new area in which we will push
1539 * this content does not support files... therefore we need to remove those files.
1541 * @param string $source The text
1542 * @return string The stripped text
1544 function strip_pluginfile_content($source) {
1545 $baseurl = '@@PLUGINFILE@@';
1546 // Looking for something like < .* "@@pluginfile@@.*" .* >
1547 $pattern = '$<[^<>]+["\']' . $baseurl . '[^"\']*["\'][^<>]*>$';
1548 $stripped = preg_replace($pattern, '', $source);
1549 // Use purify html to rebalence potentially mismatched tags and generally cleanup.
1550 return purify_html($stripped);
1554 * Legacy function, used for cleaning of old forum and glossary text only.
1556 * @param string $text text that may contain legacy TRUSTTEXT marker
1557 * @return string text without legacy TRUSTTEXT marker
1559 function trusttext_strip($text) {
1560 while (true) { // Removing nested TRUSTTEXT.
1561 $orig = $text;
1562 $text = str_replace('#####TRUSTTEXT#####', '', $text);
1563 if (strcmp($orig, $text) === 0) {
1564 return $text;
1570 * Must be called before editing of all texts with trust flag. Removes all XSS nasties from texts stored in database if needed.
1572 * @param stdClass $object data object with xxx, xxxformat and xxxtrust fields
1573 * @param string $field name of text field
1574 * @param context $context active context
1575 * @return stdClass updated $object
1577 function trusttext_pre_edit($object, $field, $context) {
1578 $trustfield = $field.'trust';
1579 $formatfield = $field.'format';
1581 if (!$object->$trustfield or !trusttext_trusted($context)) {
1582 $object->$field = clean_text($object->$field, $object->$formatfield);
1585 return $object;
1589 * Is current user trusted to enter no dangerous XSS in this context?
1591 * Please note the user must be in fact trusted everywhere on this server!!
1593 * @param context $context
1594 * @return bool true if user trusted
1596 function trusttext_trusted($context) {
1597 return (trusttext_active() and has_capability('moodle/site:trustcontent', $context));
1601 * Is trusttext feature active?
1603 * @return bool
1605 function trusttext_active() {
1606 global $CFG;
1608 return !empty($CFG->enabletrusttext);
1612 * Cleans raw text removing nasties.
1614 * Given raw text (eg typed in by a user) this function cleans it up and removes any nasty tags that could mess up
1615 * Moodle pages through XSS attacks.
1617 * The result must be used as a HTML text fragment, this function can not cleanup random
1618 * parts of html tags such as url or src attributes.
1620 * NOTE: the format parameter was deprecated because we can safely clean only HTML.
1622 * @param string $text The text to be cleaned
1623 * @param int|string $format deprecated parameter, should always contain FORMAT_HTML or FORMAT_MOODLE
1624 * @param array $options Array of options; currently only option supported is 'allowid' (if true,
1625 * does not remove id attributes when cleaning)
1626 * @return string The cleaned up text
1628 function clean_text($text, $format = FORMAT_HTML, $options = array()) {
1629 $text = (string)$text;
1631 if ($format != FORMAT_HTML and $format != FORMAT_HTML) {
1632 // TODO: we need to standardise cleanup of text when loading it into editor first.
1633 // debugging('clean_text() is designed to work only with html');.
1636 if ($format == FORMAT_PLAIN) {
1637 return $text;
1640 if (is_purify_html_necessary($text)) {
1641 $text = purify_html($text, $options);
1644 // Originally we tried to neutralise some script events here, it was a wrong approach because
1645 // it was trivial to work around that (for example using style based XSS exploits).
1646 // We must not give false sense of security here - all developers MUST understand how to use
1647 // rawurlencode(), htmlentities(), htmlspecialchars(), p(), s(), moodle_url, html_writer and friends!!!
1649 return $text;
1653 * Is it necessary to use HTMLPurifier?
1655 * @private
1656 * @param string $text
1657 * @return bool false means html is safe and valid, true means use HTMLPurifier
1659 function is_purify_html_necessary($text) {
1660 if ($text === '') {
1661 return false;
1664 if ($text === (string)((int)$text)) {
1665 return false;
1668 if (strpos($text, '&') !== false or preg_match('|<[^pesb/]|', $text)) {
1669 // We need to normalise entities or other tags except p, em, strong and br present.
1670 return true;
1673 $altered = htmlspecialchars($text, ENT_NOQUOTES, 'UTF-8', true);
1674 if ($altered === $text) {
1675 // No < > or other special chars means this must be safe.
1676 return false;
1679 // Let's try to convert back some safe html tags.
1680 $altered = preg_replace('|&lt;p&gt;(.*?)&lt;/p&gt;|m', '<p>$1</p>', $altered);
1681 if ($altered === $text) {
1682 return false;
1684 $altered = preg_replace('|&lt;em&gt;([^<>]+?)&lt;/em&gt;|m', '<em>$1</em>', $altered);
1685 if ($altered === $text) {
1686 return false;
1688 $altered = preg_replace('|&lt;strong&gt;([^<>]+?)&lt;/strong&gt;|m', '<strong>$1</strong>', $altered);
1689 if ($altered === $text) {
1690 return false;
1692 $altered = str_replace('&lt;br /&gt;', '<br />', $altered);
1693 if ($altered === $text) {
1694 return false;
1697 return true;
1701 * KSES replacement cleaning function - uses HTML Purifier.
1703 * @param string $text The (X)HTML string to purify
1704 * @param array $options Array of options; currently only option supported is 'allowid' (if set,
1705 * does not remove id attributes when cleaning)
1706 * @return string
1708 function purify_html($text, $options = array()) {
1709 global $CFG;
1711 $text = (string)$text;
1713 static $purifiers = array();
1714 static $caches = array();
1716 // Purifier code can change only during major version upgrade.
1717 $version = empty($CFG->version) ? 0 : $CFG->version;
1718 $cachedir = "$CFG->localcachedir/htmlpurifier/$version";
1719 if (!file_exists($cachedir)) {
1720 // Purging of caches may remove the cache dir at any time,
1721 // luckily file_exists() results should be cached for all existing directories.
1722 $purifiers = array();
1723 $caches = array();
1724 gc_collect_cycles();
1726 make_localcache_directory('htmlpurifier', false);
1727 check_dir_exists($cachedir);
1730 $allowid = empty($options['allowid']) ? 0 : 1;
1731 $allowobjectembed = empty($CFG->allowobjectembed) ? 0 : 1;
1733 $type = 'type_'.$allowid.'_'.$allowobjectembed;
1735 if (!array_key_exists($type, $caches)) {
1736 $caches[$type] = cache::make('core', 'htmlpurifier', array('type' => $type));
1738 $cache = $caches[$type];
1740 // Add revision number and all options to the text key so that it is compatible with local cluster node caches.
1741 $key = "|$version|$allowobjectembed|$allowid|$text";
1742 $filteredtext = $cache->get($key);
1744 if ($filteredtext === true) {
1745 // The filtering did not change the text last time, no need to filter anything again.
1746 return $text;
1747 } else if ($filteredtext !== false) {
1748 return $filteredtext;
1751 if (empty($purifiers[$type])) {
1752 require_once $CFG->libdir.'/htmlpurifier/HTMLPurifier.safe-includes.php';
1753 require_once $CFG->libdir.'/htmlpurifier/locallib.php';
1754 $config = HTMLPurifier_Config::createDefault();
1756 $config->set('HTML.DefinitionID', 'moodlehtml');
1757 $config->set('HTML.DefinitionRev', 4);
1758 $config->set('Cache.SerializerPath', $cachedir);
1759 $config->set('Cache.SerializerPermissions', $CFG->directorypermissions);
1760 $config->set('Core.NormalizeNewlines', false);
1761 $config->set('Core.ConvertDocumentToFragment', true);
1762 $config->set('Core.Encoding', 'UTF-8');
1763 $config->set('HTML.Doctype', 'XHTML 1.0 Transitional');
1764 $config->set('URI.AllowedSchemes', array(
1765 'http' => true,
1766 'https' => true,
1767 'ftp' => true,
1768 'irc' => true,
1769 'nntp' => true,
1770 'news' => true,
1771 'rtsp' => true,
1772 'rtmp' => true,
1773 'teamspeak' => true,
1774 'gopher' => true,
1775 'mms' => true,
1776 'mailto' => true
1778 $config->set('Attr.AllowedFrameTargets', array('_blank'));
1780 if ($allowobjectembed) {
1781 $config->set('HTML.SafeObject', true);
1782 $config->set('Output.FlashCompat', true);
1783 $config->set('HTML.SafeEmbed', true);
1786 if ($allowid) {
1787 $config->set('Attr.EnableID', true);
1790 if ($def = $config->maybeGetRawHTMLDefinition()) {
1791 $def->addElement('nolink', 'Block', 'Flow', array()); // Skip our filters inside.
1792 $def->addElement('tex', 'Inline', 'Inline', array()); // Tex syntax, equivalent to $$xx$$.
1793 $def->addElement('algebra', 'Inline', 'Inline', array()); // Algebra syntax, equivalent to @@xx@@.
1794 $def->addElement('lang', 'Block', 'Flow', array(), array('lang'=>'CDATA')); // Original multilang style - only our hacked lang attribute.
1795 $def->addAttribute('span', 'xxxlang', 'CDATA'); // Current very problematic multilang.
1797 // Use the built-in Ruby module to add annotation support.
1798 $def->manager->addModule(new HTMLPurifier_HTMLModule_Ruby());
1800 // Use the custom Noreferrer module.
1801 $def->manager->addModule(new HTMLPurifier_HTMLModule_Noreferrer());
1804 $purifier = new HTMLPurifier($config);
1805 $purifiers[$type] = $purifier;
1806 } else {
1807 $purifier = $purifiers[$type];
1810 $multilang = (strpos($text, 'class="multilang"') !== false);
1812 $filteredtext = $text;
1813 if ($multilang) {
1814 $filteredtextregex = '/<span(\s+lang="([a-zA-Z0-9_-]+)"|\s+class="multilang"){2}\s*>/';
1815 $filteredtext = preg_replace($filteredtextregex, '<span xxxlang="${2}">', $filteredtext);
1817 $filteredtext = (string)$purifier->purify($filteredtext);
1818 if ($multilang) {
1819 $filteredtext = preg_replace('/<span xxxlang="([a-zA-Z0-9_-]+)">/', '<span lang="${1}" class="multilang">', $filteredtext);
1822 if ($text === $filteredtext) {
1823 // No need to store the filtered text, next time we will just return unfiltered text
1824 // because it was not changed by purifying.
1825 $cache->set($key, true);
1826 } else {
1827 $cache->set($key, $filteredtext);
1830 return $filteredtext;
1834 * Given plain text, makes it into HTML as nicely as possible.
1836 * May contain HTML tags already.
1838 * Do not abuse this function. It is intended as lower level formatting feature used
1839 * by {@link format_text()} to convert FORMAT_MOODLE to HTML. You are supposed
1840 * to call format_text() in most of cases.
1842 * @param string $text The string to convert.
1843 * @param boolean $smileyignored Was used to determine if smiley characters should convert to smiley images, ignored now
1844 * @param boolean $para If true then the returned string will be wrapped in div tags
1845 * @param boolean $newlines If true then lines newline breaks will be converted to HTML newline breaks.
1846 * @return string
1848 function text_to_html($text, $smileyignored = null, $para = true, $newlines = true) {
1849 // Remove any whitespace that may be between HTML tags.
1850 $text = preg_replace("~>([[:space:]]+)<~i", "><", $text);
1852 // Remove any returns that precede or follow HTML tags.
1853 $text = preg_replace("~([\n\r])<~i", " <", $text);
1854 $text = preg_replace("~>([\n\r])~i", "> ", $text);
1856 // Make returns into HTML newlines.
1857 if ($newlines) {
1858 $text = nl2br($text);
1861 // Wrap the whole thing in a div if required.
1862 if ($para) {
1863 // In 1.9 this was changed from a p => div.
1864 return '<div class="text_to_html">'.$text.'</div>';
1865 } else {
1866 return $text;
1871 * Given Markdown formatted text, make it into XHTML using external function
1873 * @param string $text The markdown formatted text to be converted.
1874 * @return string Converted text
1876 function markdown_to_html($text) {
1877 global $CFG;
1879 if ($text === '' or $text === null) {
1880 return $text;
1883 require_once($CFG->libdir .'/markdown/MarkdownInterface.php');
1884 require_once($CFG->libdir .'/markdown/Markdown.php');
1885 require_once($CFG->libdir .'/markdown/MarkdownExtra.php');
1887 return \Michelf\MarkdownExtra::defaultTransform($text);
1891 * Given HTML text, make it into plain text using external function
1893 * @param string $html The text to be converted.
1894 * @param integer $width Width to wrap the text at. (optional, default 75 which
1895 * is a good value for email. 0 means do not limit line length.)
1896 * @param boolean $dolinks By default, any links in the HTML are collected, and
1897 * printed as a list at the end of the HTML. If you don't want that, set this
1898 * argument to false.
1899 * @return string plain text equivalent of the HTML.
1901 function html_to_text($html, $width = 75, $dolinks = true) {
1902 global $CFG;
1904 require_once($CFG->libdir .'/html2text/lib.php');
1906 $options = array(
1907 'width' => $width,
1908 'do_links' => 'table',
1911 if (empty($dolinks)) {
1912 $options['do_links'] = 'none';
1914 $h2t = new core_html2text($html, $options);
1915 $result = $h2t->getText();
1917 return $result;
1921 * Converts content introduced in an editor to plain text.
1923 * @param string $content The text as entered by the user
1924 * @param int $contentformat The text format: FORMAT_MOODLE, FORMAT_HTML, FORMAT_PLAIN or FORMAT_MARKDOWN
1925 * @return string Plain text.
1927 function content_to_text($content, $contentformat) {
1929 switch ($contentformat) {
1930 case FORMAT_PLAIN:
1931 return $content;
1932 case FORMAT_MARKDOWN:
1933 $html = markdown_to_html($content);
1934 return html_to_text($html, 75, false);
1935 default:
1936 // FORMAT_HTML and FORMAT_MOODLE.
1937 return html_to_text($content, 75, false);
1942 * This function will highlight search words in a given string
1944 * It cares about HTML and will not ruin links. It's best to use
1945 * this function after performing any conversions to HTML.
1947 * @param string $needle The search string. Syntax like "word1 +word2 -word3" is dealt with correctly.
1948 * @param string $haystack The string (HTML) within which to highlight the search terms.
1949 * @param boolean $matchcase whether to do case-sensitive. Default case-insensitive.
1950 * @param string $prefix the string to put before each search term found.
1951 * @param string $suffix the string to put after each search term found.
1952 * @return string The highlighted HTML.
1954 function highlight($needle, $haystack, $matchcase = false,
1955 $prefix = '<span class="highlight">', $suffix = '</span>') {
1957 // Quick bail-out in trivial cases.
1958 if (empty($needle) or empty($haystack)) {
1959 return $haystack;
1962 // Break up the search term into words, discard any -words and build a regexp.
1963 $words = preg_split('/ +/', trim($needle));
1964 foreach ($words as $index => $word) {
1965 if (strpos($word, '-') === 0) {
1966 unset($words[$index]);
1967 } else if (strpos($word, '+') === 0) {
1968 $words[$index] = '\b' . preg_quote(ltrim($word, '+'), '/') . '\b'; // Match only as a complete word.
1969 } else {
1970 $words[$index] = preg_quote($word, '/');
1973 $regexp = '/(' . implode('|', $words) . ')/u'; // Char u is to do UTF-8 matching.
1974 if (!$matchcase) {
1975 $regexp .= 'i';
1978 // Another chance to bail-out if $search was only -words.
1979 if (empty($words)) {
1980 return $haystack;
1983 // Split the string into HTML tags and real content.
1984 $chunks = preg_split('/((?:<[^>]*>)+)/', $haystack, -1, PREG_SPLIT_DELIM_CAPTURE);
1986 // We have an array of alternating blocks of text, then HTML tags, then text, ...
1987 // Loop through replacing search terms in the text, and leaving the HTML unchanged.
1988 $ishtmlchunk = false;
1989 $result = '';
1990 foreach ($chunks as $chunk) {
1991 if ($ishtmlchunk) {
1992 $result .= $chunk;
1993 } else {
1994 $result .= preg_replace($regexp, $prefix . '$1' . $suffix, $chunk);
1996 $ishtmlchunk = !$ishtmlchunk;
1999 return $result;
2003 * This function will highlight instances of $needle in $haystack
2005 * It's faster that the above function {@link highlight()} and doesn't care about
2006 * HTML or anything.
2008 * @param string $needle The string to search for
2009 * @param string $haystack The string to search for $needle in
2010 * @return string The highlighted HTML
2012 function highlightfast($needle, $haystack) {
2014 if (empty($needle) or empty($haystack)) {
2015 return $haystack;
2018 $parts = explode(core_text::strtolower($needle), core_text::strtolower($haystack));
2020 if (count($parts) === 1) {
2021 return $haystack;
2024 $pos = 0;
2026 foreach ($parts as $key => $part) {
2027 $parts[$key] = substr($haystack, $pos, strlen($part));
2028 $pos += strlen($part);
2030 $parts[$key] .= '<span class="highlight">'.substr($haystack, $pos, strlen($needle)).'</span>';
2031 $pos += strlen($needle);
2034 return str_replace('<span class="highlight"></span>', '', join('', $parts));
2038 * Return a string containing 'lang', xml:lang and optionally 'dir' HTML attributes.
2040 * Internationalisation, for print_header and backup/restorelib.
2042 * @param bool $dir Default false
2043 * @return string Attributes
2045 function get_html_lang($dir = false) {
2046 $direction = '';
2047 if ($dir) {
2048 if (right_to_left()) {
2049 $direction = ' dir="rtl"';
2050 } else {
2051 $direction = ' dir="ltr"';
2054 // Accessibility: added the 'lang' attribute to $direction, used in theme <html> tag.
2055 $language = str_replace('_', '-', current_language());
2056 @header('Content-Language: '.$language);
2057 return ($direction.' lang="'.$language.'" xml:lang="'.$language.'"');
2061 // STANDARD WEB PAGE PARTS.
2064 * Send the HTTP headers that Moodle requires.
2066 * There is a backwards compatibility hack for legacy code
2067 * that needs to add custom IE compatibility directive.
2069 * Example:
2070 * <code>
2071 * if (!isset($CFG->additionalhtmlhead)) {
2072 * $CFG->additionalhtmlhead = '';
2074 * $CFG->additionalhtmlhead .= '<meta http-equiv="X-UA-Compatible" content="IE=8" />';
2075 * header('X-UA-Compatible: IE=8');
2076 * echo $OUTPUT->header();
2077 * </code>
2079 * Please note the $CFG->additionalhtmlhead alone might not work,
2080 * you should send the IE compatibility header() too.
2082 * @param string $contenttype
2083 * @param bool $cacheable Can this page be cached on back?
2084 * @return void, sends HTTP headers
2086 function send_headers($contenttype, $cacheable = true) {
2087 global $CFG;
2089 @header('Content-Type: ' . $contenttype);
2090 @header('Content-Script-Type: text/javascript');
2091 @header('Content-Style-Type: text/css');
2093 if (empty($CFG->additionalhtmlhead) or stripos($CFG->additionalhtmlhead, 'X-UA-Compatible') === false) {
2094 @header('X-UA-Compatible: IE=edge');
2097 if ($cacheable) {
2098 // Allow caching on "back" (but not on normal clicks).
2099 @header('Cache-Control: private, pre-check=0, post-check=0, max-age=0, no-transform');
2100 @header('Pragma: no-cache');
2101 @header('Expires: ');
2102 } else {
2103 // Do everything we can to always prevent clients and proxies caching.
2104 @header('Cache-Control: no-store, no-cache, must-revalidate');
2105 @header('Cache-Control: post-check=0, pre-check=0, no-transform', false);
2106 @header('Pragma: no-cache');
2107 @header('Expires: Mon, 20 Aug 1969 09:23:00 GMT');
2108 @header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
2110 @header('Accept-Ranges: none');
2112 if (empty($CFG->allowframembedding)) {
2113 @header('X-Frame-Options: sameorigin');
2118 * Return the right arrow with text ('next'), and optionally embedded in a link.
2120 * @param string $text HTML/plain text label (set to blank only for breadcrumb separator cases).
2121 * @param string $url An optional link to use in a surrounding HTML anchor.
2122 * @param bool $accesshide True if text should be hidden (for screen readers only).
2123 * @param string $addclass Additional class names for the link, or the arrow character.
2124 * @return string HTML string.
2126 function link_arrow_right($text, $url='', $accesshide=false, $addclass='') {
2127 global $OUTPUT; // TODO: move to output renderer.
2128 $arrowclass = 'arrow ';
2129 if (!$url) {
2130 $arrowclass .= $addclass;
2132 $arrow = '<span class="'.$arrowclass.'">'.$OUTPUT->rarrow().'</span>';
2133 $htmltext = '';
2134 if ($text) {
2135 $htmltext = '<span class="arrow_text">'.$text.'</span>&nbsp;';
2136 if ($accesshide) {
2137 $htmltext = get_accesshide($htmltext);
2140 if ($url) {
2141 $class = 'arrow_link';
2142 if ($addclass) {
2143 $class .= ' '.$addclass;
2145 return '<a class="'.$class.'" href="'.$url.'" title="'.preg_replace('/<.*?>/', '', $text).'">'.$htmltext.$arrow.'</a>';
2147 return $htmltext.$arrow;
2151 * Return the left arrow with text ('previous'), and optionally embedded in a link.
2153 * @param string $text HTML/plain text label (set to blank only for breadcrumb separator cases).
2154 * @param string $url An optional link to use in a surrounding HTML anchor.
2155 * @param bool $accesshide True if text should be hidden (for screen readers only).
2156 * @param string $addclass Additional class names for the link, or the arrow character.
2157 * @return string HTML string.
2159 function link_arrow_left($text, $url='', $accesshide=false, $addclass='') {
2160 global $OUTPUT; // TODO: move to utput renderer.
2161 $arrowclass = 'arrow ';
2162 if (! $url) {
2163 $arrowclass .= $addclass;
2165 $arrow = '<span class="'.$arrowclass.'">'.$OUTPUT->larrow().'</span>';
2166 $htmltext = '';
2167 if ($text) {
2168 $htmltext = '&nbsp;<span class="arrow_text">'.$text.'</span>';
2169 if ($accesshide) {
2170 $htmltext = get_accesshide($htmltext);
2173 if ($url) {
2174 $class = 'arrow_link';
2175 if ($addclass) {
2176 $class .= ' '.$addclass;
2178 return '<a class="'.$class.'" href="'.$url.'" title="'.preg_replace('/<.*?>/', '', $text).'">'.$arrow.$htmltext.'</a>';
2180 return $arrow.$htmltext;
2184 * Return a HTML element with the class "accesshide", for accessibility.
2186 * Please use cautiously - where possible, text should be visible!
2188 * @param string $text Plain text.
2189 * @param string $elem Lowercase element name, default "span".
2190 * @param string $class Additional classes for the element.
2191 * @param string $attrs Additional attributes string in the form, "name='value' name2='value2'"
2192 * @return string HTML string.
2194 function get_accesshide($text, $elem='span', $class='', $attrs='') {
2195 return "<$elem class=\"accesshide $class\" $attrs>$text</$elem>";
2199 * Return the breadcrumb trail navigation separator.
2201 * @return string HTML string.
2203 function get_separator() {
2204 // Accessibility: the 'hidden' slash is preferred for screen readers.
2205 return ' '.link_arrow_right($text='/', $url='', $accesshide=true, 'sep').' ';
2209 * Print (or return) a collapsible region, that has a caption that can be clicked to expand or collapse the region.
2211 * If JavaScript is off, then the region will always be expanded.
2213 * @param string $contents the contents of the box.
2214 * @param string $classes class names added to the div that is output.
2215 * @param string $id id added to the div that is output. Must not be blank.
2216 * @param string $caption text displayed at the top. Clicking on this will cause the region to expand or contract.
2217 * @param string $userpref the name of the user preference that stores the user's preferred default state.
2218 * (May be blank if you do not wish the state to be persisted.
2219 * @param boolean $default Initial collapsed state to use if the user_preference it not set.
2220 * @param boolean $return if true, return the HTML as a string, rather than printing it.
2221 * @return string|void If $return is false, returns nothing, otherwise returns a string of HTML.
2223 function print_collapsible_region($contents, $classes, $id, $caption, $userpref = '', $default = false, $return = false) {
2224 $output = print_collapsible_region_start($classes, $id, $caption, $userpref, $default, true);
2225 $output .= $contents;
2226 $output .= print_collapsible_region_end(true);
2228 if ($return) {
2229 return $output;
2230 } else {
2231 echo $output;
2236 * Print (or return) the start of a collapsible region
2238 * The collapsibleregion has a caption that can be clicked to expand or collapse the region. If JavaScript is off, then the region
2239 * will always be expanded.
2241 * @param string $classes class names added to the div that is output.
2242 * @param string $id id added to the div that is output. Must not be blank.
2243 * @param string $caption text displayed at the top. Clicking on this will cause the region to expand or contract.
2244 * @param string $userpref the name of the user preference that stores the user's preferred default state.
2245 * (May be blank if you do not wish the state to be persisted.
2246 * @param boolean $default Initial collapsed state to use if the user_preference it not set.
2247 * @param boolean $return if true, return the HTML as a string, rather than printing it.
2248 * @return string|void if $return is false, returns nothing, otherwise returns a string of HTML.
2250 function print_collapsible_region_start($classes, $id, $caption, $userpref = '', $default = false, $return = false) {
2251 global $PAGE;
2253 // Work out the initial state.
2254 if (!empty($userpref) and is_string($userpref)) {
2255 user_preference_allow_ajax_update($userpref, PARAM_BOOL);
2256 $collapsed = get_user_preferences($userpref, $default);
2257 } else {
2258 $collapsed = $default;
2259 $userpref = false;
2262 if ($collapsed) {
2263 $classes .= ' collapsed';
2266 $output = '';
2267 $output .= '<div id="' . $id . '" class="collapsibleregion ' . $classes . '">';
2268 $output .= '<div id="' . $id . '_sizer">';
2269 $output .= '<div id="' . $id . '_caption" class="collapsibleregioncaption">';
2270 $output .= $caption . ' ';
2271 $output .= '</div><div id="' . $id . '_inner" class="collapsibleregioninner">';
2272 $PAGE->requires->js_init_call('M.util.init_collapsible_region', array($id, $userpref, get_string('clicktohideshow')));
2274 if ($return) {
2275 return $output;
2276 } else {
2277 echo $output;
2282 * Close a region started with print_collapsible_region_start.
2284 * @param boolean $return if true, return the HTML as a string, rather than printing it.
2285 * @return string|void if $return is false, returns nothing, otherwise returns a string of HTML.
2287 function print_collapsible_region_end($return = false) {
2288 $output = '</div></div></div>';
2290 if ($return) {
2291 return $output;
2292 } else {
2293 echo $output;
2298 * Print a specified group's avatar.
2300 * @param array|stdClass $group A single {@link group} object OR array of groups.
2301 * @param int $courseid The course ID.
2302 * @param boolean $large Default small picture, or large.
2303 * @param boolean $return If false print picture, otherwise return the output as string
2304 * @param boolean $link Enclose image in a link to view specified course?
2305 * @return string|void Depending on the setting of $return
2307 function print_group_picture($group, $courseid, $large=false, $return=false, $link=true) {
2308 global $CFG;
2310 if (is_array($group)) {
2311 $output = '';
2312 foreach ($group as $g) {
2313 $output .= print_group_picture($g, $courseid, $large, true, $link);
2315 if ($return) {
2316 return $output;
2317 } else {
2318 echo $output;
2319 return;
2323 $context = context_course::instance($courseid);
2325 // If there is no picture, do nothing.
2326 if (!$group->picture) {
2327 return '';
2330 // If picture is hidden, only show to those with course:managegroups.
2331 if ($group->hidepicture and !has_capability('moodle/course:managegroups', $context)) {
2332 return '';
2335 if ($link or has_capability('moodle/site:accessallgroups', $context)) {
2336 $output = '<a href="'. $CFG->wwwroot .'/user/index.php?id='. $courseid .'&amp;group='. $group->id .'">';
2337 } else {
2338 $output = '';
2340 if ($large) {
2341 $file = 'f1';
2342 } else {
2343 $file = 'f2';
2346 $grouppictureurl = moodle_url::make_pluginfile_url($context->id, 'group', 'icon', $group->id, '/', $file);
2347 $grouppictureurl->param('rev', $group->picture);
2348 $output .= '<img class="grouppicture" src="'.$grouppictureurl.'"'.
2349 ' alt="'.s(get_string('group').' '.$group->name).'" title="'.s($group->name).'"/>';
2351 if ($link or has_capability('moodle/site:accessallgroups', $context)) {
2352 $output .= '</a>';
2355 if ($return) {
2356 return $output;
2357 } else {
2358 echo $output;
2364 * Display a recent activity note
2366 * @staticvar string $strftimerecent
2367 * @param int $time A timestamp int.
2368 * @param stdClass $user A user object from the database.
2369 * @param string $text Text for display for the note
2370 * @param string $link The link to wrap around the text
2371 * @param bool $return If set to true the HTML is returned rather than echo'd
2372 * @param string $viewfullnames
2373 * @return string If $retrun was true returns HTML for a recent activity notice.
2375 function print_recent_activity_note($time, $user, $text, $link, $return=false, $viewfullnames=null) {
2376 static $strftimerecent = null;
2377 $output = '';
2379 if (is_null($viewfullnames)) {
2380 $context = context_system::instance();
2381 $viewfullnames = has_capability('moodle/site:viewfullnames', $context);
2384 if (is_null($strftimerecent)) {
2385 $strftimerecent = get_string('strftimerecent');
2388 $output .= '<div class="head">';
2389 $output .= '<div class="date">'.userdate($time, $strftimerecent).'</div>';
2390 $output .= '<div class="name">'.fullname($user, $viewfullnames).'</div>';
2391 $output .= '</div>';
2392 $output .= '<div class="info"><a href="'.$link.'">'.format_string($text, true).'</a></div>';
2394 if ($return) {
2395 return $output;
2396 } else {
2397 echo $output;
2402 * Returns a popup menu with course activity modules
2404 * Given a course this function returns a small popup menu with all the course activity modules in it, as a navigation menu
2405 * outputs a simple list structure in XHTML.
2406 * The data is taken from the serialised array stored in the course record.
2408 * @param course $course A {@link $COURSE} object.
2409 * @param array $sections
2410 * @param course_modinfo $modinfo
2411 * @param string $strsection
2412 * @param string $strjumpto
2413 * @param int $width
2414 * @param string $cmid
2415 * @return string The HTML block
2417 function navmenulist($course, $sections, $modinfo, $strsection, $strjumpto, $width=50, $cmid=0) {
2419 global $CFG, $OUTPUT;
2421 $section = -1;
2422 $menu = array();
2423 $doneheading = false;
2425 $courseformatoptions = course_get_format($course)->get_format_options();
2426 $coursecontext = context_course::instance($course->id);
2428 $menu[] = '<ul class="navmenulist"><li class="jumpto section"><span>'.$strjumpto.'</span><ul>';
2429 foreach ($modinfo->cms as $mod) {
2430 if (!$mod->has_view()) {
2431 // Don't show modules which you can't link to!
2432 continue;
2435 // For course formats using 'numsections' do not show extra sections.
2436 if (isset($courseformatoptions['numsections']) && $mod->sectionnum > $courseformatoptions['numsections']) {
2437 break;
2440 if (!$mod->uservisible) { // Do not icnlude empty sections at all.
2441 continue;
2444 if ($mod->sectionnum >= 0 and $section != $mod->sectionnum) {
2445 $thissection = $sections[$mod->sectionnum];
2447 if ($thissection->visible or
2448 (isset($courseformatoptions['hiddensections']) and !$courseformatoptions['hiddensections']) or
2449 has_capability('moodle/course:viewhiddensections', $coursecontext)) {
2450 $thissection->summary = strip_tags(format_string($thissection->summary, true));
2451 if (!$doneheading) {
2452 $menu[] = '</ul></li>';
2454 if ($course->format == 'weeks' or empty($thissection->summary)) {
2455 $item = $strsection ." ". $mod->sectionnum;
2456 } else {
2457 if (core_text::strlen($thissection->summary) < ($width-3)) {
2458 $item = $thissection->summary;
2459 } else {
2460 $item = core_text::substr($thissection->summary, 0, $width).'...';
2463 $menu[] = '<li class="section"><span>'.$item.'</span>';
2464 $menu[] = '<ul>';
2465 $doneheading = true;
2467 $section = $mod->sectionnum;
2468 } else {
2469 // No activities from this hidden section shown.
2470 continue;
2474 $url = $mod->modname .'/view.php?id='. $mod->id;
2475 $mod->name = strip_tags(format_string($mod->name ,true));
2476 if (core_text::strlen($mod->name) > ($width+5)) {
2477 $mod->name = core_text::substr($mod->name, 0, $width).'...';
2479 if (!$mod->visible) {
2480 $mod->name = '('.$mod->name.')';
2482 $class = 'activity '.$mod->modname;
2483 $class .= ($cmid == $mod->id) ? ' selected' : '';
2484 $menu[] = '<li class="'.$class.'">'.
2485 '<img src="'.$OUTPUT->pix_url('icon', $mod->modname) . '" alt="" />'.
2486 '<a href="'.$CFG->wwwroot.'/mod/'.$url.'">'.$mod->name.'</a></li>';
2489 if ($doneheading) {
2490 $menu[] = '</ul></li>';
2492 $menu[] = '</ul></li></ul>';
2494 return implode("\n", $menu);
2498 * Prints a grade menu (as part of an existing form) with help showing all possible numerical grades and scales.
2500 * @todo Finish documenting this function
2501 * @todo Deprecate: this is only used in a few contrib modules
2503 * @param int $courseid The course ID
2504 * @param string $name
2505 * @param string $current
2506 * @param boolean $includenograde Include those with no grades
2507 * @param boolean $return If set to true returns rather than echo's
2508 * @return string|bool Depending on value of $return
2510 function print_grade_menu($courseid, $name, $current, $includenograde=true, $return=false) {
2511 global $OUTPUT;
2513 $output = '';
2514 $strscale = get_string('scale');
2515 $strscales = get_string('scales');
2517 $scales = get_scales_menu($courseid);
2518 foreach ($scales as $i => $scalename) {
2519 $grades[-$i] = $strscale .': '. $scalename;
2521 if ($includenograde) {
2522 $grades[0] = get_string('nograde');
2524 for ($i=100; $i>=1; $i--) {
2525 $grades[$i] = $i;
2527 $output .= html_writer::select($grades, $name, $current, false);
2529 $helppix = $OUTPUT->pix_url('help');
2530 $linkobject = '<span class="helplink"><img class="iconhelp" alt="'.$strscales.'" src="'.$helppix.'" /></span>';
2531 $link = new moodle_url('/course/scales.php', array('id' => $courseid, 'list' => 1));
2532 $action = new popup_action('click', $link, 'ratingscales', array('height' => 400, 'width' => 500));
2533 $output .= $OUTPUT->action_link($link, $linkobject, $action, array('title' => $strscales));
2535 if ($return) {
2536 return $output;
2537 } else {
2538 echo $output;
2543 * Print an error to STDOUT and exit with a non-zero code. For commandline scripts.
2545 * Default errorcode is 1.
2547 * Very useful for perl-like error-handling:
2548 * do_somethting() or mdie("Something went wrong");
2550 * @param string $msg Error message
2551 * @param integer $errorcode Error code to emit
2553 function mdie($msg='', $errorcode=1) {
2554 trigger_error($msg);
2555 exit($errorcode);
2559 * Print a message and exit.
2561 * @param string $message The message to print in the notice
2562 * @param string $link The link to use for the continue button
2563 * @param object $course A course object. Unused.
2564 * @return void This function simply exits
2566 function notice ($message, $link='', $course=null) {
2567 global $PAGE, $OUTPUT;
2569 $message = clean_text($message); // In case nasties are in here.
2571 if (CLI_SCRIPT) {
2572 echo("!!$message!!\n");
2573 exit(1); // No success.
2576 if (!$PAGE->headerprinted) {
2577 // Header not yet printed.
2578 $PAGE->set_title(get_string('notice'));
2579 echo $OUTPUT->header();
2580 } else {
2581 echo $OUTPUT->container_end_all(false);
2584 echo $OUTPUT->box($message, 'generalbox', 'notice');
2585 echo $OUTPUT->continue_button($link);
2587 echo $OUTPUT->footer();
2588 exit(1); // General error code.
2592 * Redirects the user to another page, after printing a notice.
2594 * This function calls the OUTPUT redirect method, echo's the output and then dies to ensure nothing else happens.
2596 * <strong>Good practice:</strong> You should call this method before starting page
2597 * output by using any of the OUTPUT methods.
2599 * @param moodle_url|string $url A moodle_url to redirect to. Strings are not to be trusted!
2600 * @param string $message The message to display to the user
2601 * @param int $delay The delay before redirecting
2602 * @param string $messagetype The type of notification to show the message in. See constants on \core\output\notification.
2603 * @throws moodle_exception
2605 function redirect($url, $message='', $delay=null, $messagetype = \core\output\notification::NOTIFY_INFO) {
2606 global $OUTPUT, $PAGE, $CFG;
2608 if (CLI_SCRIPT or AJAX_SCRIPT) {
2609 // This is wrong - developers should not use redirect in these scripts but it should not be very likely.
2610 throw new moodle_exception('redirecterrordetected', 'error');
2613 if ($delay === null) {
2614 $delay = -1;
2617 // Prevent debug errors - make sure context is properly initialised.
2618 if ($PAGE) {
2619 $PAGE->set_context(null);
2620 $PAGE->set_pagelayout('redirect'); // No header and footer needed.
2621 $PAGE->set_title(get_string('pageshouldredirect', 'moodle'));
2624 if ($url instanceof moodle_url) {
2625 $url = $url->out(false);
2628 $debugdisableredirect = false;
2629 do {
2630 if (defined('DEBUGGING_PRINTED')) {
2631 // Some debugging already printed, no need to look more.
2632 $debugdisableredirect = true;
2633 break;
2636 if (core_useragent::is_msword()) {
2637 // Clicking a URL from MS Word sends a request to the server without cookies. If that
2638 // causes a redirect Word will open a browser pointing the new URL. If not, the URL that
2639 // was clicked is opened. Because the request from Word is without cookies, it almost
2640 // always results in a redirect to the login page, even if the user is logged in in their
2641 // browser. This is not what we want, so prevent the redirect for requests from Word.
2642 $debugdisableredirect = true;
2643 break;
2646 if (empty($CFG->debugdisplay) or empty($CFG->debug)) {
2647 // No errors should be displayed.
2648 break;
2651 if (!function_exists('error_get_last') or !$lasterror = error_get_last()) {
2652 break;
2655 if (!($lasterror['type'] & $CFG->debug)) {
2656 // Last error not interesting.
2657 break;
2660 // Watch out here, @hidden() errors are returned from error_get_last() too.
2661 if (headers_sent()) {
2662 // We already started printing something - that means errors likely printed.
2663 $debugdisableredirect = true;
2664 break;
2667 if (ob_get_level() and ob_get_contents()) {
2668 // There is something waiting to be printed, hopefully it is the errors,
2669 // but it might be some error hidden by @ too - such as the timezone mess from setup.php.
2670 $debugdisableredirect = true;
2671 break;
2673 } while (false);
2675 // Technically, HTTP/1.1 requires Location: header to contain the absolute path.
2676 // (In practice browsers accept relative paths - but still, might as well do it properly.)
2677 // This code turns relative into absolute.
2678 if (!preg_match('|^[a-z]+:|i', $url)) {
2679 // Get host name http://www.wherever.com.
2680 $hostpart = preg_replace('|^(.*?[^:/])/.*$|', '$1', $CFG->wwwroot);
2681 if (preg_match('|^/|', $url)) {
2682 // URLs beginning with / are relative to web server root so we just add them in.
2683 $url = $hostpart.$url;
2684 } else {
2685 // URLs not beginning with / are relative to path of current script, so add that on.
2686 $url = $hostpart.preg_replace('|\?.*$|', '', me()).'/../'.$url;
2688 // Replace all ..s.
2689 while (true) {
2690 $newurl = preg_replace('|/(?!\.\.)[^/]*/\.\./|', '/', $url);
2691 if ($newurl == $url) {
2692 break;
2694 $url = $newurl;
2698 // Sanitise url - we can not rely on moodle_url or our URL cleaning
2699 // because they do not support all valid external URLs.
2700 $url = preg_replace('/[\x00-\x1F\x7F]/', '', $url);
2701 $url = str_replace('"', '%22', $url);
2702 $encodedurl = preg_replace("/\&(?![a-zA-Z0-9#]{1,8};)/", "&amp;", $url);
2703 $encodedurl = preg_replace('/^.*href="([^"]*)".*$/', "\\1", clean_text('<a href="'.$encodedurl.'" />', FORMAT_HTML));
2704 $url = str_replace('&amp;', '&', $encodedurl);
2706 if (!empty($message)) {
2707 if (!$debugdisableredirect && !headers_sent()) {
2708 // A message has been provided, and the headers have not yet been sent.
2709 // Display the message as a notification on the subsequent page.
2710 \core\notification::add($message, $messagetype);
2711 $message = null;
2712 $delay = 0;
2713 } else {
2714 if ($delay === -1 || !is_numeric($delay)) {
2715 $delay = 3;
2717 $message = clean_text($message);
2719 } else {
2720 $message = get_string('pageshouldredirect');
2721 $delay = 0;
2724 // Make sure the session is closed properly, this prevents problems in IIS
2725 // and also some potential PHP shutdown issues.
2726 \core\session\manager::write_close();
2728 if ($delay == 0 && !$debugdisableredirect && !headers_sent()) {
2729 // 302 might not work for POST requests, 303 is ignored by obsolete clients.
2730 @header($_SERVER['SERVER_PROTOCOL'] . ' 303 See Other');
2731 @header('Location: '.$url);
2732 echo bootstrap_renderer::plain_redirect_message($encodedurl);
2733 exit;
2736 // Include a redirect message, even with a HTTP redirect, because that is recommended practice.
2737 if ($PAGE) {
2738 $CFG->docroot = false; // To prevent the link to moodle docs from being displayed on redirect page.
2739 echo $OUTPUT->redirect_message($encodedurl, $message, $delay, $debugdisableredirect, $messagetype);
2740 exit;
2741 } else {
2742 echo bootstrap_renderer::early_redirect_message($encodedurl, $message, $delay);
2743 exit;
2748 * Given an email address, this function will return an obfuscated version of it.
2750 * @param string $email The email address to obfuscate
2751 * @return string The obfuscated email address
2753 function obfuscate_email($email) {
2754 $i = 0;
2755 $length = strlen($email);
2756 $obfuscated = '';
2757 while ($i < $length) {
2758 if (rand(0, 2) && $email{$i}!='@') { // MDL-20619 some browsers have problems unobfuscating @.
2759 $obfuscated.='%'.dechex(ord($email{$i}));
2760 } else {
2761 $obfuscated.=$email{$i};
2763 $i++;
2765 return $obfuscated;
2769 * This function takes some text and replaces about half of the characters
2770 * with HTML entity equivalents. Return string is obviously longer.
2772 * @param string $plaintext The text to be obfuscated
2773 * @return string The obfuscated text
2775 function obfuscate_text($plaintext) {
2776 $i=0;
2777 $length = core_text::strlen($plaintext);
2778 $obfuscated='';
2779 $prevobfuscated = false;
2780 while ($i < $length) {
2781 $char = core_text::substr($plaintext, $i, 1);
2782 $ord = core_text::utf8ord($char);
2783 $numerical = ($ord >= ord('0')) && ($ord <= ord('9'));
2784 if ($prevobfuscated and $numerical ) {
2785 $obfuscated.='&#'.$ord.';';
2786 } else if (rand(0, 2)) {
2787 $obfuscated.='&#'.$ord.';';
2788 $prevobfuscated = true;
2789 } else {
2790 $obfuscated.=$char;
2791 $prevobfuscated = false;
2793 $i++;
2795 return $obfuscated;
2799 * This function uses the {@link obfuscate_email()} and {@link obfuscate_text()}
2800 * to generate a fully obfuscated email link, ready to use.
2802 * @param string $email The email address to display
2803 * @param string $label The text to displayed as hyperlink to $email
2804 * @param boolean $dimmed If true then use css class 'dimmed' for hyperlink
2805 * @param string $subject The subject of the email in the mailto link
2806 * @param string $body The content of the email in the mailto link
2807 * @return string The obfuscated mailto link
2809 function obfuscate_mailto($email, $label='', $dimmed=false, $subject = '', $body = '') {
2811 if (empty($label)) {
2812 $label = $email;
2815 $label = obfuscate_text($label);
2816 $email = obfuscate_email($email);
2817 $mailto = obfuscate_text('mailto');
2818 $url = new moodle_url("mailto:$email");
2819 $attrs = array();
2821 if (!empty($subject)) {
2822 $url->param('subject', format_string($subject));
2824 if (!empty($body)) {
2825 $url->param('body', format_string($body));
2828 // Use the obfuscated mailto.
2829 $url = preg_replace('/^mailto/', $mailto, $url->out());
2831 if ($dimmed) {
2832 $attrs['title'] = get_string('emaildisable');
2833 $attrs['class'] = 'dimmed';
2836 return html_writer::link($url, $label, $attrs);
2840 * This function is used to rebuild the <nolink> tag because some formats (PLAIN and WIKI)
2841 * will transform it to html entities
2843 * @param string $text Text to search for nolink tag in
2844 * @return string
2846 function rebuildnolinktag($text) {
2848 $text = preg_replace('/&lt;(\/*nolink)&gt;/i', '<$1>', $text);
2850 return $text;
2854 * Prints a maintenance message from $CFG->maintenance_message or default if empty.
2856 function print_maintenance_message() {
2857 global $CFG, $SITE, $PAGE, $OUTPUT;
2859 $PAGE->set_pagetype('maintenance-message');
2860 $PAGE->set_pagelayout('maintenance');
2861 $PAGE->set_title(strip_tags($SITE->fullname));
2862 $PAGE->set_heading($SITE->fullname);
2863 echo $OUTPUT->header();
2864 echo $OUTPUT->heading(get_string('sitemaintenance', 'admin'));
2865 if (isset($CFG->maintenance_message) and !html_is_blank($CFG->maintenance_message)) {
2866 echo $OUTPUT->box_start('maintenance_message generalbox boxwidthwide boxaligncenter');
2867 echo $CFG->maintenance_message;
2868 echo $OUTPUT->box_end();
2870 echo $OUTPUT->footer();
2871 die;
2875 * Returns a string containing a nested list, suitable for formatting into tabs with CSS.
2877 * It is not recommended to use this function in Moodle 2.5 but it is left for backward
2878 * compartibility.
2880 * Example how to print a single line tabs:
2881 * $rows = array(
2882 * new tabobject(...),
2883 * new tabobject(...)
2884 * );
2885 * echo $OUTPUT->tabtree($rows, $selectedid);
2887 * Multiple row tabs may not look good on some devices but if you want to use them
2888 * you can specify ->subtree for the active tabobject.
2890 * @param array $tabrows An array of rows where each row is an array of tab objects
2891 * @param string $selected The id of the selected tab (whatever row it's on)
2892 * @param array $inactive An array of ids of inactive tabs that are not selectable.
2893 * @param array $activated An array of ids of other tabs that are currently activated
2894 * @param bool $return If true output is returned rather then echo'd
2895 * @return string HTML output if $return was set to true.
2897 function print_tabs($tabrows, $selected = null, $inactive = null, $activated = null, $return = false) {
2898 global $OUTPUT;
2900 $tabrows = array_reverse($tabrows);
2901 $subtree = array();
2902 foreach ($tabrows as $row) {
2903 $tree = array();
2905 foreach ($row as $tab) {
2906 $tab->inactive = is_array($inactive) && in_array((string)$tab->id, $inactive);
2907 $tab->activated = is_array($activated) && in_array((string)$tab->id, $activated);
2908 $tab->selected = (string)$tab->id == $selected;
2910 if ($tab->activated || $tab->selected) {
2911 $tab->subtree = $subtree;
2913 $tree[] = $tab;
2915 $subtree = $tree;
2917 $output = $OUTPUT->tabtree($subtree);
2918 if ($return) {
2919 return $output;
2920 } else {
2921 print $output;
2922 return !empty($output);
2927 * Alter debugging level for the current request,
2928 * the change is not saved in database.
2930 * @param int $level one of the DEBUG_* constants
2931 * @param bool $debugdisplay
2933 function set_debugging($level, $debugdisplay = null) {
2934 global $CFG;
2936 $CFG->debug = (int)$level;
2937 $CFG->debugdeveloper = (($CFG->debug & DEBUG_DEVELOPER) === DEBUG_DEVELOPER);
2939 if ($debugdisplay !== null) {
2940 $CFG->debugdisplay = (bool)$debugdisplay;
2945 * Standard Debugging Function
2947 * Returns true if the current site debugging settings are equal or above specified level.
2948 * If passed a parameter it will emit a debugging notice similar to trigger_error(). The
2949 * routing of notices is controlled by $CFG->debugdisplay
2950 * eg use like this:
2952 * 1) debugging('a normal debug notice');
2953 * 2) debugging('something really picky', DEBUG_ALL);
2954 * 3) debugging('annoying debug message only for developers', DEBUG_DEVELOPER);
2955 * 4) if (debugging()) { perform extra debugging operations (do not use print or echo) }
2957 * In code blocks controlled by debugging() (such as example 4)
2958 * any output should be routed via debugging() itself, or the lower-level
2959 * trigger_error() or error_log(). Using echo or print will break XHTML
2960 * JS and HTTP headers.
2962 * It is also possible to define NO_DEBUG_DISPLAY which redirects the message to error_log.
2964 * @param string $message a message to print
2965 * @param int $level the level at which this debugging statement should show
2966 * @param array $backtrace use different backtrace
2967 * @return bool
2969 function debugging($message = '', $level = DEBUG_NORMAL, $backtrace = null) {
2970 global $CFG, $USER;
2972 $forcedebug = false;
2973 if (!empty($CFG->debugusers) && $USER) {
2974 $debugusers = explode(',', $CFG->debugusers);
2975 $forcedebug = in_array($USER->id, $debugusers);
2978 if (!$forcedebug and (empty($CFG->debug) || ($CFG->debug != -1 and $CFG->debug < $level))) {
2979 return false;
2982 if (!isset($CFG->debugdisplay)) {
2983 $CFG->debugdisplay = ini_get_bool('display_errors');
2986 if ($message) {
2987 if (!$backtrace) {
2988 $backtrace = debug_backtrace();
2990 $from = format_backtrace($backtrace, CLI_SCRIPT || NO_DEBUG_DISPLAY);
2991 if (PHPUNIT_TEST) {
2992 if (phpunit_util::debugging_triggered($message, $level, $from)) {
2993 // We are inside test, the debug message was logged.
2994 return true;
2998 if (NO_DEBUG_DISPLAY) {
2999 // Script does not want any errors or debugging in output,
3000 // we send the info to error log instead.
3001 error_log('Debugging: ' . $message . ' in '. PHP_EOL . $from);
3003 } else if ($forcedebug or $CFG->debugdisplay) {
3004 if (!defined('DEBUGGING_PRINTED')) {
3005 define('DEBUGGING_PRINTED', 1); // Indicates we have printed something.
3007 if (CLI_SCRIPT) {
3008 echo "++ $message ++\n$from";
3009 } else {
3010 echo '<div class="notifytiny debuggingmessage" data-rel="debugging">' , $message , $from , '</div>';
3013 } else {
3014 trigger_error($message . $from, E_USER_NOTICE);
3017 return true;
3021 * Outputs a HTML comment to the browser.
3023 * This is used for those hard-to-debug pages that use bits from many different files in very confusing ways (e.g. blocks).
3025 * <code>print_location_comment(__FILE__, __LINE__);</code>
3027 * @param string $file
3028 * @param integer $line
3029 * @param boolean $return Whether to return or print the comment
3030 * @return string|void Void unless true given as third parameter
3032 function print_location_comment($file, $line, $return = false) {
3033 if ($return) {
3034 return "<!-- $file at line $line -->\n";
3035 } else {
3036 echo "<!-- $file at line $line -->\n";
3042 * Returns true if the user is using a right-to-left language.
3044 * @return boolean true if the current language is right-to-left (Hebrew, Arabic etc)
3046 function right_to_left() {
3047 return (get_string('thisdirection', 'langconfig') === 'rtl');
3052 * Returns swapped left<=> right if in RTL environment.
3054 * Part of RTL Moodles support.
3056 * @param string $align align to check
3057 * @return string
3059 function fix_align_rtl($align) {
3060 if (!right_to_left()) {
3061 return $align;
3063 if ($align == 'left') {
3064 return 'right';
3066 if ($align == 'right') {
3067 return 'left';
3069 return $align;
3074 * Returns true if the page is displayed in a popup window.
3076 * Gets the information from the URL parameter inpopup.
3078 * @todo Use a central function to create the popup calls all over Moodle and
3079 * In the moment only works with resources and probably questions.
3081 * @return boolean
3083 function is_in_popup() {
3084 $inpopup = optional_param('inpopup', '', PARAM_BOOL);
3086 return ($inpopup);
3090 * Progress bar class.
3092 * Manages the display of a progress bar.
3094 * To use this class.
3095 * - construct
3096 * - call create (or use the 3rd param to the constructor)
3097 * - call update or update_full() or update() repeatedly
3099 * @copyright 2008 jamiesensei
3100 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3101 * @package core
3103 class progress_bar {
3104 /** @var string html id */
3105 private $html_id;
3106 /** @var int total width */
3107 private $width;
3108 /** @var int last percentage printed */
3109 private $percent = 0;
3110 /** @var int time when last printed */
3111 private $lastupdate = 0;
3112 /** @var int when did we start printing this */
3113 private $time_start = 0;
3116 * Constructor
3118 * Prints JS code if $autostart true.
3120 * @param string $html_id
3121 * @param int $width
3122 * @param bool $autostart Default to false
3124 public function __construct($htmlid = '', $width = 500, $autostart = false) {
3125 if (!empty($htmlid)) {
3126 $this->html_id = $htmlid;
3127 } else {
3128 $this->html_id = 'pbar_'.uniqid();
3131 $this->width = $width;
3133 if ($autostart) {
3134 $this->create();
3139 * Create a new progress bar, this function will output html.
3141 * @return void Echo's output
3143 public function create() {
3144 global $PAGE;
3146 $this->time_start = microtime(true);
3147 if (CLI_SCRIPT) {
3148 return; // Temporary solution for cli scripts.
3151 $PAGE->requires->string_for_js('secondsleft', 'moodle');
3153 $htmlcode = <<<EOT
3154 <div class="progressbar_container" style="width: {$this->width}px;" id="{$this->html_id}">
3155 <h2></h2>
3156 <div class="progress progress-striped active">
3157 <div class="bar" role="progressbar" aria-valuemin="0" aria-valuemax="100" aria-valuenow="0">&nbsp;</div>
3158 </div>
3159 <p></p>
3160 </div>
3161 EOT;
3162 flush();
3163 echo $htmlcode;
3164 flush();
3168 * Update the progress bar
3170 * @param int $percent from 1-100
3171 * @param string $msg
3172 * @return void Echo's output
3173 * @throws coding_exception
3175 private function _update($percent, $msg) {
3176 if (empty($this->time_start)) {
3177 throw new coding_exception('You must call create() (or use the $autostart ' .
3178 'argument to the constructor) before you try updating the progress bar.');
3181 if (CLI_SCRIPT) {
3182 return; // Temporary solution for cli scripts.
3185 $estimate = $this->estimate($percent);
3187 if ($estimate === null) {
3188 // Always do the first and last updates.
3189 } else if ($estimate == 0) {
3190 // Always do the last updates.
3191 } else if ($this->lastupdate + 20 < time()) {
3192 // We must update otherwise browser would time out.
3193 } else if (round($this->percent, 2) === round($percent, 2)) {
3194 // No significant change, no need to update anything.
3195 return;
3197 if (is_numeric($estimate)) {
3198 $estimate = get_string('secondsleft', 'moodle', round($estimate, 2));
3201 $this->percent = round($percent, 2);
3202 $this->lastupdate = microtime(true);
3204 echo html_writer::script(js_writer::function_call('updateProgressBar',
3205 array($this->html_id, $this->percent, $msg, $estimate)));
3206 flush();
3210 * Estimate how much time it is going to take.
3212 * @param int $pt from 1-100
3213 * @return mixed Null (unknown), or int
3215 private function estimate($pt) {
3216 if ($this->lastupdate == 0) {
3217 return null;
3219 if ($pt < 0.00001) {
3220 return null; // We do not know yet how long it will take.
3222 if ($pt > 99.99999) {
3223 return 0; // Nearly done, right?
3225 $consumed = microtime(true) - $this->time_start;
3226 if ($consumed < 0.001) {
3227 return null;
3230 return (100 - $pt) * ($consumed / $pt);
3234 * Update progress bar according percent
3236 * @param int $percent from 1-100
3237 * @param string $msg the message needed to be shown
3239 public function update_full($percent, $msg) {
3240 $percent = max(min($percent, 100), 0);
3241 $this->_update($percent, $msg);
3245 * Update progress bar according the number of tasks
3247 * @param int $cur current task number
3248 * @param int $total total task number
3249 * @param string $msg message
3251 public function update($cur, $total, $msg) {
3252 $percent = ($cur / $total) * 100;
3253 $this->update_full($percent, $msg);
3257 * Restart the progress bar.
3259 public function restart() {
3260 $this->percent = 0;
3261 $this->lastupdate = 0;
3262 $this->time_start = 0;
3267 * Progress trace class.
3269 * Use this class from long operations where you want to output occasional information about
3270 * what is going on, but don't know if, or in what format, the output should be.
3272 * @copyright 2009 Tim Hunt
3273 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3274 * @package core
3276 abstract class progress_trace {
3278 * Output an progress message in whatever format.
3280 * @param string $message the message to output.
3281 * @param integer $depth indent depth for this message.
3283 abstract public function output($message, $depth = 0);
3286 * Called when the processing is finished.
3288 public function finished() {
3293 * This subclass of progress_trace does not ouput anything.
3295 * @copyright 2009 Tim Hunt
3296 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3297 * @package core
3299 class null_progress_trace extends progress_trace {
3301 * Does Nothing
3303 * @param string $message
3304 * @param int $depth
3305 * @return void Does Nothing
3307 public function output($message, $depth = 0) {
3312 * This subclass of progress_trace outputs to plain text.
3314 * @copyright 2009 Tim Hunt
3315 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3316 * @package core
3318 class text_progress_trace extends progress_trace {
3320 * Output the trace message.
3322 * @param string $message
3323 * @param int $depth
3324 * @return void Output is echo'd
3326 public function output($message, $depth = 0) {
3327 echo str_repeat(' ', $depth), $message, "\n";
3328 flush();
3333 * This subclass of progress_trace outputs as HTML.
3335 * @copyright 2009 Tim Hunt
3336 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3337 * @package core
3339 class html_progress_trace extends progress_trace {
3341 * Output the trace message.
3343 * @param string $message
3344 * @param int $depth
3345 * @return void Output is echo'd
3347 public function output($message, $depth = 0) {
3348 echo '<p>', str_repeat('&#160;&#160;', $depth), htmlspecialchars($message), "</p>\n";
3349 flush();
3354 * HTML List Progress Tree
3356 * @copyright 2009 Tim Hunt
3357 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3358 * @package core
3360 class html_list_progress_trace extends progress_trace {
3361 /** @var int */
3362 protected $currentdepth = -1;
3365 * Echo out the list
3367 * @param string $message The message to display
3368 * @param int $depth
3369 * @return void Output is echoed
3371 public function output($message, $depth = 0) {
3372 $samedepth = true;
3373 while ($this->currentdepth > $depth) {
3374 echo "</li>\n</ul>\n";
3375 $this->currentdepth -= 1;
3376 if ($this->currentdepth == $depth) {
3377 echo '<li>';
3379 $samedepth = false;
3381 while ($this->currentdepth < $depth) {
3382 echo "<ul>\n<li>";
3383 $this->currentdepth += 1;
3384 $samedepth = false;
3386 if ($samedepth) {
3387 echo "</li>\n<li>";
3389 echo htmlspecialchars($message);
3390 flush();
3394 * Called when the processing is finished.
3396 public function finished() {
3397 while ($this->currentdepth >= 0) {
3398 echo "</li>\n</ul>\n";
3399 $this->currentdepth -= 1;
3405 * This subclass of progress_trace outputs to error log.
3407 * @copyright Petr Skoda {@link http://skodak.org}
3408 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3409 * @package core
3411 class error_log_progress_trace extends progress_trace {
3412 /** @var string log prefix */
3413 protected $prefix;
3416 * Constructor.
3417 * @param string $prefix optional log prefix
3419 public function __construct($prefix = '') {
3420 $this->prefix = $prefix;
3424 * Output the trace message.
3426 * @param string $message
3427 * @param int $depth
3428 * @return void Output is sent to error log.
3430 public function output($message, $depth = 0) {
3431 error_log($this->prefix . str_repeat(' ', $depth) . $message);
3436 * Special type of trace that can be used for catching of output of other traces.
3438 * @copyright Petr Skoda {@link http://skodak.org}
3439 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3440 * @package core
3442 class progress_trace_buffer extends progress_trace {
3443 /** @var progres_trace */
3444 protected $trace;
3445 /** @var bool do we pass output out */
3446 protected $passthrough;
3447 /** @var string output buffer */
3448 protected $buffer;
3451 * Constructor.
3453 * @param progress_trace $trace
3454 * @param bool $passthrough true means output and buffer, false means just buffer and no output
3456 public function __construct(progress_trace $trace, $passthrough = true) {
3457 $this->trace = $trace;
3458 $this->passthrough = $passthrough;
3459 $this->buffer = '';
3463 * Output the trace message.
3465 * @param string $message the message to output.
3466 * @param int $depth indent depth for this message.
3467 * @return void output stored in buffer
3469 public function output($message, $depth = 0) {
3470 ob_start();
3471 $this->trace->output($message, $depth);
3472 $this->buffer .= ob_get_contents();
3473 if ($this->passthrough) {
3474 ob_end_flush();
3475 } else {
3476 ob_end_clean();
3481 * Called when the processing is finished.
3483 public function finished() {
3484 ob_start();
3485 $this->trace->finished();
3486 $this->buffer .= ob_get_contents();
3487 if ($this->passthrough) {
3488 ob_end_flush();
3489 } else {
3490 ob_end_clean();
3495 * Reset internal text buffer.
3497 public function reset_buffer() {
3498 $this->buffer = '';
3502 * Return internal text buffer.
3503 * @return string buffered plain text
3505 public function get_buffer() {
3506 return $this->buffer;
3511 * Special type of trace that can be used for redirecting to multiple other traces.
3513 * @copyright Petr Skoda {@link http://skodak.org}
3514 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3515 * @package core
3517 class combined_progress_trace extends progress_trace {
3520 * An array of traces.
3521 * @var array
3523 protected $traces;
3526 * Constructs a new instance.
3528 * @param array $traces multiple traces
3530 public function __construct(array $traces) {
3531 $this->traces = $traces;
3535 * Output an progress message in whatever format.
3537 * @param string $message the message to output.
3538 * @param integer $depth indent depth for this message.
3540 public function output($message, $depth = 0) {
3541 foreach ($this->traces as $trace) {
3542 $trace->output($message, $depth);
3547 * Called when the processing is finished.
3549 public function finished() {
3550 foreach ($this->traces as $trace) {
3551 $trace->finished();
3557 * Returns a localized sentence in the current language summarizing the current password policy
3559 * @todo this should be handled by a function/method in the language pack library once we have a support for it
3560 * @uses $CFG
3561 * @return string
3563 function print_password_policy() {
3564 global $CFG;
3566 $message = '';
3567 if (!empty($CFG->passwordpolicy)) {
3568 $messages = array();
3569 $messages[] = get_string('informminpasswordlength', 'auth', $CFG->minpasswordlength);
3570 if (!empty($CFG->minpassworddigits)) {
3571 $messages[] = get_string('informminpassworddigits', 'auth', $CFG->minpassworddigits);
3573 if (!empty($CFG->minpasswordlower)) {
3574 $messages[] = get_string('informminpasswordlower', 'auth', $CFG->minpasswordlower);
3576 if (!empty($CFG->minpasswordupper)) {
3577 $messages[] = get_string('informminpasswordupper', 'auth', $CFG->minpasswordupper);
3579 if (!empty($CFG->minpasswordnonalphanum)) {
3580 $messages[] = get_string('informminpasswordnonalphanum', 'auth', $CFG->minpasswordnonalphanum);
3583 $messages = join(', ', $messages); // This is ugly but we do not have anything better yet...
3584 $message = get_string('informpasswordpolicy', 'auth', $messages);
3586 return $message;
3590 * Get the value of a help string fully prepared for display in the current language.
3592 * @param string $identifier The identifier of the string to search for.
3593 * @param string $component The module the string is associated with.
3594 * @param boolean $ajax Whether this help is called from an AJAX script.
3595 * This is used to influence text formatting and determines
3596 * which format to output the doclink in.
3597 * @param string|object|array $a An object, string or number that can be used
3598 * within translation strings
3599 * @return Object An object containing:
3600 * - heading: Any heading that there may be for this help string.
3601 * - text: The wiki-formatted help string.
3602 * - doclink: An object containing a link, the linktext, and any additional
3603 * CSS classes to apply to that link. Only present if $ajax = false.
3604 * - completedoclink: A text representation of the doclink. Only present if $ajax = true.
3606 function get_formatted_help_string($identifier, $component, $ajax = false, $a = null) {
3607 global $CFG, $OUTPUT;
3608 $sm = get_string_manager();
3610 // Do not rebuild caches here!
3611 // Devs need to learn to purge all caches after any change or disable $CFG->langstringcache.
3613 $data = new stdClass();
3615 if ($sm->string_exists($identifier, $component)) {
3616 $data->heading = format_string(get_string($identifier, $component));
3617 } else {
3618 // Gracefully fall back to an empty string.
3619 $data->heading = '';
3622 if ($sm->string_exists($identifier . '_help', $component)) {
3623 $options = new stdClass();
3624 $options->trusted = false;
3625 $options->noclean = false;
3626 $options->smiley = false;
3627 $options->filter = false;
3628 $options->para = true;
3629 $options->newlines = false;
3630 $options->overflowdiv = !$ajax;
3632 // Should be simple wiki only MDL-21695.
3633 $data->text = format_text(get_string($identifier.'_help', $component, $a), FORMAT_MARKDOWN, $options);
3635 $helplink = $identifier . '_link';
3636 if ($sm->string_exists($helplink, $component)) { // Link to further info in Moodle docs.
3637 $link = get_string($helplink, $component);
3638 $linktext = get_string('morehelp');
3640 $data->doclink = new stdClass();
3641 $url = new moodle_url(get_docs_url($link));
3642 if ($ajax) {
3643 $data->doclink->link = $url->out();
3644 $data->doclink->linktext = $linktext;
3645 $data->doclink->class = ($CFG->doctonewwindow) ? 'helplinkpopup' : '';
3646 } else {
3647 $data->completedoclink = html_writer::tag('div', $OUTPUT->doc_link($link, $linktext),
3648 array('class' => 'helpdoclink'));
3651 } else {
3652 $data->text = html_writer::tag('p',
3653 html_writer::tag('strong', 'TODO') . ": missing help string [{$identifier}_help, {$component}]");
3655 return $data;
3659 * Renders a hidden password field so that browsers won't incorrectly autofill password fields with the user's password.
3661 * @since 3.0
3662 * @return string HTML to prevent password autofill
3664 function prevent_form_autofill_password() {
3665 return '<div class="hide"><input type="password" /></div>';