MDL-52927 qtype ddwtos and ddimageortext focus using keyboard
[moodle.git] / lib / weblib.php
blob2f2adf77bfdc84065e7d729fab0a8250ec493ab6
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) {
556 if (!is_bool($escaped)) {
557 debugging('Escape parameter must be of type boolean, '.gettype($escaped).' given instead.');
560 $uri = $this->out_omit_querystring().$this->slashargument;
562 $querystring = $this->get_query_string($escaped, $overrideparams);
563 if ($querystring !== '') {
564 $uri .= '?' . $querystring;
566 if (!is_null($this->anchor)) {
567 $uri .= '#'.$this->anchor;
570 return $uri;
574 * Returns url without parameters, everything before '?'.
576 * @param bool $includeanchor if {@link self::anchor} is defined, should it be returned?
577 * @return string
579 public function out_omit_querystring($includeanchor = false) {
581 $uri = $this->scheme ? $this->scheme.':'.((strtolower($this->scheme) == 'mailto') ? '':'//'): '';
582 $uri .= $this->user ? $this->user.($this->pass? ':'.$this->pass:'').'@':'';
583 $uri .= $this->host ? $this->host : '';
584 $uri .= $this->port ? ':'.$this->port : '';
585 $uri .= $this->path ? $this->path : '';
586 if ($includeanchor and !is_null($this->anchor)) {
587 $uri .= '#' . $this->anchor;
590 return $uri;
594 * Compares this moodle_url with another.
596 * See documentation of constants for an explanation of the comparison flags.
598 * @param moodle_url $url The moodle_url object to compare
599 * @param int $matchtype The type of comparison (URL_MATCH_BASE, URL_MATCH_PARAMS, URL_MATCH_EXACT)
600 * @return bool
602 public function compare(moodle_url $url, $matchtype = URL_MATCH_EXACT) {
604 $baseself = $this->out_omit_querystring();
605 $baseother = $url->out_omit_querystring();
607 // Append index.php if there is no specific file.
608 if (substr($baseself, -1) == '/') {
609 $baseself .= 'index.php';
611 if (substr($baseother, -1) == '/') {
612 $baseother .= 'index.php';
615 // Compare the two base URLs.
616 if ($baseself != $baseother) {
617 return false;
620 if ($matchtype == URL_MATCH_BASE) {
621 return true;
624 $urlparams = $url->params();
625 foreach ($this->params() as $param => $value) {
626 if ($param == 'sesskey') {
627 continue;
629 if (!array_key_exists($param, $urlparams) || $urlparams[$param] != $value) {
630 return false;
634 if ($matchtype == URL_MATCH_PARAMS) {
635 return true;
638 foreach ($urlparams as $param => $value) {
639 if ($param == 'sesskey') {
640 continue;
642 if (!array_key_exists($param, $this->params()) || $this->param($param) != $value) {
643 return false;
647 if ($url->anchor !== $this->anchor) {
648 return false;
651 return true;
655 * Sets the anchor for the URI (the bit after the hash)
657 * @param string $anchor null means remove previous
659 public function set_anchor($anchor) {
660 if (is_null($anchor)) {
661 // Remove.
662 $this->anchor = null;
663 } else if ($anchor === '') {
664 // Special case, used as empty link.
665 $this->anchor = '';
666 } else if (preg_match('|[a-zA-Z\_\:][a-zA-Z0-9\_\-\.\:]*|', $anchor)) {
667 // Match the anchor against the NMTOKEN spec.
668 $this->anchor = $anchor;
669 } else {
670 // Bad luck, no valid anchor found.
671 $this->anchor = null;
676 * Sets the scheme for the URI (the bit before ://)
678 * @param string $scheme
680 public function set_scheme($scheme) {
681 // See http://www.ietf.org/rfc/rfc3986.txt part 3.1.
682 if (preg_match('/^[a-zA-Z][a-zA-Z0-9+.-]*$/', $scheme)) {
683 $this->scheme = $scheme;
684 } else {
685 throw new coding_exception('Bad URL scheme.');
690 * Sets the url slashargument value.
692 * @param string $path usually file path
693 * @param string $parameter name of page parameter if slasharguments not supported
694 * @param bool $supported usually null, then it depends on $CFG->slasharguments, use true or false for other servers
695 * @return void
697 public function set_slashargument($path, $parameter = 'file', $supported = null) {
698 global $CFG;
699 if (is_null($supported)) {
700 $supported = !empty($CFG->slasharguments);
703 if ($supported) {
704 $parts = explode('/', $path);
705 $parts = array_map('rawurlencode', $parts);
706 $path = implode('/', $parts);
707 $this->slashargument = $path;
708 unset($this->params[$parameter]);
710 } else {
711 $this->slashargument = '';
712 $this->params[$parameter] = $path;
716 // Static factory methods.
719 * General moodle file url.
721 * @param string $urlbase the script serving the file
722 * @param string $path
723 * @param bool $forcedownload
724 * @return moodle_url
726 public static function make_file_url($urlbase, $path, $forcedownload = false) {
727 $params = array();
728 if ($forcedownload) {
729 $params['forcedownload'] = 1;
731 $path = rtrim($path, '/');
732 $url = new moodle_url($urlbase, $params);
733 $url->set_slashargument($path);
734 return $url;
738 * Factory method for creation of url pointing to plugin file.
740 * Please note this method can be used only from the plugins to
741 * create urls of own files, it must not be used outside of plugins!
743 * @param int $contextid
744 * @param string $component
745 * @param string $area
746 * @param int $itemid
747 * @param string $pathname
748 * @param string $filename
749 * @param bool $forcedownload
750 * @return moodle_url
752 public static function make_pluginfile_url($contextid, $component, $area, $itemid, $pathname, $filename,
753 $forcedownload = false) {
754 global $CFG;
755 $urlbase = "$CFG->httpswwwroot/pluginfile.php";
756 if ($itemid === null) {
757 return self::make_file_url($urlbase, "/$contextid/$component/$area".$pathname.$filename, $forcedownload);
758 } else {
759 return self::make_file_url($urlbase, "/$contextid/$component/$area/$itemid".$pathname.$filename, $forcedownload);
764 * Factory method for creation of url pointing to plugin file.
765 * This method is the same that make_pluginfile_url but pointing to the webservice pluginfile.php script.
766 * It should be used only in external functions.
768 * @since 2.8
769 * @param int $contextid
770 * @param string $component
771 * @param string $area
772 * @param int $itemid
773 * @param string $pathname
774 * @param string $filename
775 * @param bool $forcedownload
776 * @return moodle_url
778 public static function make_webservice_pluginfile_url($contextid, $component, $area, $itemid, $pathname, $filename,
779 $forcedownload = false) {
780 global $CFG;
781 $urlbase = "$CFG->httpswwwroot/webservice/pluginfile.php";
782 if ($itemid === null) {
783 return self::make_file_url($urlbase, "/$contextid/$component/$area".$pathname.$filename, $forcedownload);
784 } else {
785 return self::make_file_url($urlbase, "/$contextid/$component/$area/$itemid".$pathname.$filename, $forcedownload);
790 * Factory method for creation of url pointing to draft file of current user.
792 * @param int $draftid draft item id
793 * @param string $pathname
794 * @param string $filename
795 * @param bool $forcedownload
796 * @return moodle_url
798 public static function make_draftfile_url($draftid, $pathname, $filename, $forcedownload = false) {
799 global $CFG, $USER;
800 $urlbase = "$CFG->httpswwwroot/draftfile.php";
801 $context = context_user::instance($USER->id);
803 return self::make_file_url($urlbase, "/$context->id/user/draft/$draftid".$pathname.$filename, $forcedownload);
807 * Factory method for creating of links to legacy course files.
809 * @param int $courseid
810 * @param string $filepath
811 * @param bool $forcedownload
812 * @return moodle_url
814 public static function make_legacyfile_url($courseid, $filepath, $forcedownload = false) {
815 global $CFG;
817 $urlbase = "$CFG->wwwroot/file.php";
818 return self::make_file_url($urlbase, '/'.$courseid.'/'.$filepath, $forcedownload);
822 * Returns URL a relative path from $CFG->wwwroot
824 * Can be used for passing around urls with the wwwroot stripped
826 * @param boolean $escaped Use &amp; as params separator instead of plain &
827 * @param array $overrideparams params to add to the output url, these override existing ones with the same name.
828 * @return string Resulting URL
829 * @throws coding_exception if called on a non-local url
831 public function out_as_local_url($escaped = true, array $overrideparams = null) {
832 global $CFG;
834 $url = $this->out($escaped, $overrideparams);
835 $httpswwwroot = str_replace("http://", "https://", $CFG->wwwroot);
837 // Url should be equal to wwwroot or httpswwwroot. If not then throw exception.
838 if (($url === $CFG->wwwroot) || (strpos($url, $CFG->wwwroot.'/') === 0)) {
839 $localurl = substr($url, strlen($CFG->wwwroot));
840 return !empty($localurl) ? $localurl : '';
841 } else if (($url === $httpswwwroot) || (strpos($url, $httpswwwroot.'/') === 0)) {
842 $localurl = substr($url, strlen($httpswwwroot));
843 return !empty($localurl) ? $localurl : '';
844 } else {
845 throw new coding_exception('out_as_local_url called on a non-local URL');
850 * Returns the 'path' portion of a URL. For example, if the URL is
851 * http://www.example.org:447/my/file/is/here.txt?really=1 then this will
852 * return '/my/file/is/here.txt'.
854 * By default the path includes slash-arguments (for example,
855 * '/myfile.php/extra/arguments') so it is what you would expect from a
856 * URL path. If you don't want this behaviour, you can opt to exclude the
857 * slash arguments. (Be careful: if the $CFG variable slasharguments is
858 * disabled, these URLs will have a different format and you may need to
859 * look at the 'file' parameter too.)
861 * @param bool $includeslashargument If true, includes slash arguments
862 * @return string Path of URL
864 public function get_path($includeslashargument = true) {
865 return $this->path . ($includeslashargument ? $this->slashargument : '');
869 * Returns a given parameter value from the URL.
871 * @param string $name Name of parameter
872 * @return string Value of parameter or null if not set
874 public function get_param($name) {
875 if (array_key_exists($name, $this->params)) {
876 return $this->params[$name];
877 } else {
878 return null;
883 * Returns the 'scheme' portion of a URL. For example, if the URL is
884 * http://www.example.org:447/my/file/is/here.txt?really=1 then this will
885 * return 'http' (without the colon).
887 * @return string Scheme of the URL.
889 public function get_scheme() {
890 return $this->scheme;
894 * Returns the 'host' portion of a URL. For example, if the URL is
895 * http://www.example.org:447/my/file/is/here.txt?really=1 then this will
896 * return 'www.example.org'.
898 * @return string Host of the URL.
900 public function get_host() {
901 return $this->host;
905 * Returns the 'port' portion of a URL. For example, if the URL is
906 * http://www.example.org:447/my/file/is/here.txt?really=1 then this will
907 * return '447'.
909 * @return string Port of the URL.
911 public function get_port() {
912 return $this->port;
917 * Determine if there is data waiting to be processed from a form
919 * Used on most forms in Moodle to check for data
920 * Returns the data as an object, if it's found.
921 * This object can be used in foreach loops without
922 * casting because it's cast to (array) automatically
924 * Checks that submitted POST data exists and returns it as object.
926 * @return mixed false or object
928 function data_submitted() {
930 if (empty($_POST)) {
931 return false;
932 } else {
933 return (object)fix_utf8($_POST);
938 * Given some normal text this function will break up any
939 * long words to a given size by inserting the given character
941 * It's multibyte savvy and doesn't change anything inside html tags.
943 * @param string $string the string to be modified
944 * @param int $maxsize maximum length of the string to be returned
945 * @param string $cutchar the string used to represent word breaks
946 * @return string
948 function break_up_long_words($string, $maxsize=20, $cutchar=' ') {
950 // First of all, save all the tags inside the text to skip them.
951 $tags = array();
952 filter_save_tags($string, $tags);
954 // Process the string adding the cut when necessary.
955 $output = '';
956 $length = core_text::strlen($string);
957 $wordlength = 0;
959 for ($i=0; $i<$length; $i++) {
960 $char = core_text::substr($string, $i, 1);
961 if ($char == ' ' or $char == "\t" or $char == "\n" or $char == "\r" or $char == "<" or $char == ">") {
962 $wordlength = 0;
963 } else {
964 $wordlength++;
965 if ($wordlength > $maxsize) {
966 $output .= $cutchar;
967 $wordlength = 0;
970 $output .= $char;
973 // Finally load the tags back again.
974 if (!empty($tags)) {
975 $output = str_replace(array_keys($tags), $tags, $output);
978 return $output;
982 * Try and close the current window using JavaScript, either immediately, or after a delay.
984 * Echo's out the resulting XHTML & javascript
986 * @param integer $delay a delay in seconds before closing the window. Default 0.
987 * @param boolean $reloadopener if true, we will see if this window was a pop-up, and try
988 * to reload the parent window before this one closes.
990 function close_window($delay = 0, $reloadopener = false) {
991 global $PAGE, $OUTPUT;
993 if (!$PAGE->headerprinted) {
994 $PAGE->set_title(get_string('closewindow'));
995 echo $OUTPUT->header();
996 } else {
997 $OUTPUT->container_end_all(false);
1000 if ($reloadopener) {
1001 // Trigger the reload immediately, even if the reload is after a delay.
1002 $PAGE->requires->js_function_call('window.opener.location.reload', array(true));
1004 $OUTPUT->notification(get_string('windowclosing'), 'notifysuccess');
1006 $PAGE->requires->js_function_call('close_window', array(new stdClass()), false, $delay);
1008 echo $OUTPUT->footer();
1009 exit;
1013 * Returns a string containing a link to the user documentation for the current page.
1015 * Also contains an icon by default. Shown to teachers and admin only.
1017 * @param string $text The text to be displayed for the link
1018 * @return string The link to user documentation for this current page
1020 function page_doc_link($text='') {
1021 global $OUTPUT, $PAGE;
1022 $path = page_get_doc_link_path($PAGE);
1023 if (!$path) {
1024 return '';
1026 return $OUTPUT->doc_link($path, $text);
1030 * Returns the path to use when constructing a link to the docs.
1032 * @since Moodle 2.5.1 2.6
1033 * @param moodle_page $page
1034 * @return string
1036 function page_get_doc_link_path(moodle_page $page) {
1037 global $CFG;
1039 if (empty($CFG->docroot) || during_initial_install()) {
1040 return '';
1042 if (!has_capability('moodle/site:doclinks', $page->context)) {
1043 return '';
1046 $path = $page->docspath;
1047 if (!$path) {
1048 return '';
1050 return $path;
1055 * Validates an email to make sure it makes sense.
1057 * @param string $address The email address to validate.
1058 * @return boolean
1060 function validate_email($address) {
1062 return (preg_match('#^[-!\#$%&\'*+\\/0-9=?A-Z^_`a-z{|}~]+'.
1063 '(\.[-!\#$%&\'*+\\/0-9=?A-Z^_`a-z{|}~]+)*'.
1064 '@'.
1065 '[-!\#$%&\'*+\\/0-9=?A-Z^_`a-z{|}~]+\.'.
1066 '[-!\#$%&\'*+\\./0-9=?A-Z^_`a-z{|}~]+$#',
1067 $address));
1071 * Extracts file argument either from file parameter or PATH_INFO
1073 * Note: $scriptname parameter is not needed anymore
1075 * @return string file path (only safe characters)
1077 function get_file_argument() {
1078 global $SCRIPT;
1080 $relativepath = optional_param('file', false, PARAM_PATH);
1082 if ($relativepath !== false and $relativepath !== '') {
1083 return $relativepath;
1085 $relativepath = false;
1087 // Then try extract file from the slasharguments.
1088 if (stripos($_SERVER['SERVER_SOFTWARE'], 'iis') !== false) {
1089 // NOTE: IIS tends to convert all file paths to single byte DOS encoding,
1090 // we can not use other methods because they break unicode chars,
1091 // the only ways are to use URL rewriting
1092 // OR
1093 // to properly set the 'FastCGIUtf8ServerVariables' registry key.
1094 if (isset($_SERVER['PATH_INFO']) and $_SERVER['PATH_INFO'] !== '') {
1095 // Check that PATH_INFO works == must not contain the script name.
1096 if (strpos($_SERVER['PATH_INFO'], $SCRIPT) === false) {
1097 $relativepath = clean_param(urldecode($_SERVER['PATH_INFO']), PARAM_PATH);
1100 } else {
1101 // All other apache-like servers depend on PATH_INFO.
1102 if (isset($_SERVER['PATH_INFO'])) {
1103 if (isset($_SERVER['SCRIPT_NAME']) and strpos($_SERVER['PATH_INFO'], $_SERVER['SCRIPT_NAME']) === 0) {
1104 $relativepath = substr($_SERVER['PATH_INFO'], strlen($_SERVER['SCRIPT_NAME']));
1105 } else {
1106 $relativepath = $_SERVER['PATH_INFO'];
1108 $relativepath = clean_param($relativepath, PARAM_PATH);
1112 return $relativepath;
1116 * Just returns an array of text formats suitable for a popup menu
1118 * @return array
1120 function format_text_menu() {
1121 return array (FORMAT_MOODLE => get_string('formattext'),
1122 FORMAT_HTML => get_string('formathtml'),
1123 FORMAT_PLAIN => get_string('formatplain'),
1124 FORMAT_MARKDOWN => get_string('formatmarkdown'));
1128 * Given text in a variety of format codings, this function returns the text as safe HTML.
1130 * This function should mainly be used for long strings like posts,
1131 * answers, glossary items etc. For short strings {@link format_string()}.
1133 * <pre>
1134 * Options:
1135 * trusted : If true the string won't be cleaned. Default false required noclean=true.
1136 * noclean : If true the string won't be cleaned. Default false required trusted=true.
1137 * nocache : If true the strign will not be cached and will be formatted every call. Default false.
1138 * filter : If true the string will be run through applicable filters as well. Default true.
1139 * para : If true then the returned string will be wrapped in div tags. Default true.
1140 * newlines : If true then lines newline breaks will be converted to HTML newline breaks. Default true.
1141 * context : The context that will be used for filtering.
1142 * overflowdiv : If set to true the formatted text will be encased in a div
1143 * with the class no-overflow before being returned. Default false.
1144 * allowid : If true then id attributes will not be removed, even when
1145 * using htmlpurifier. Default false.
1146 * </pre>
1148 * @staticvar array $croncache
1149 * @param string $text The text to be formatted. This is raw text originally from user input.
1150 * @param int $format Identifier of the text format to be used
1151 * [FORMAT_MOODLE, FORMAT_HTML, FORMAT_PLAIN, FORMAT_MARKDOWN]
1152 * @param object/array $options text formatting options
1153 * @param int $courseiddonotuse deprecated course id, use context option instead
1154 * @return string
1156 function format_text($text, $format = FORMAT_MOODLE, $options = null, $courseiddonotuse = null) {
1157 global $CFG, $DB, $PAGE;
1159 if ($text === '' || is_null($text)) {
1160 // No need to do any filters and cleaning.
1161 return '';
1164 // Detach object, we can not modify it.
1165 $options = (array)$options;
1167 if (!isset($options['trusted'])) {
1168 $options['trusted'] = false;
1170 if (!isset($options['noclean'])) {
1171 if ($options['trusted'] and trusttext_active()) {
1172 // No cleaning if text trusted and noclean not specified.
1173 $options['noclean'] = true;
1174 } else {
1175 $options['noclean'] = false;
1178 if (!isset($options['nocache'])) {
1179 $options['nocache'] = false;
1181 if (!isset($options['filter'])) {
1182 $options['filter'] = true;
1184 if (!isset($options['para'])) {
1185 $options['para'] = true;
1187 if (!isset($options['newlines'])) {
1188 $options['newlines'] = true;
1190 if (!isset($options['overflowdiv'])) {
1191 $options['overflowdiv'] = false;
1194 // Calculate best context.
1195 if (empty($CFG->version) or $CFG->version < 2013051400 or during_initial_install()) {
1196 // Do not filter anything during installation or before upgrade completes.
1197 $context = null;
1199 } else if (isset($options['context'])) { // First by explicit passed context option.
1200 if (is_object($options['context'])) {
1201 $context = $options['context'];
1202 } else {
1203 $context = context::instance_by_id($options['context']);
1205 } else if ($courseiddonotuse) {
1206 // Legacy courseid.
1207 $context = context_course::instance($courseiddonotuse);
1208 } else {
1209 // Fallback to $PAGE->context this may be problematic in CLI and other non-standard pages :-(.
1210 $context = $PAGE->context;
1213 if (!$context) {
1214 // Either install/upgrade or something has gone really wrong because context does not exist (yet?).
1215 $options['nocache'] = true;
1216 $options['filter'] = false;
1219 if ($options['filter']) {
1220 $filtermanager = filter_manager::instance();
1221 $filtermanager->setup_page_for_filters($PAGE, $context); // Setup global stuff filters may have.
1222 $filteroptions = array(
1223 'originalformat' => $format,
1224 'noclean' => $options['noclean'],
1226 } else {
1227 $filtermanager = new null_filter_manager();
1228 $filteroptions = array();
1231 switch ($format) {
1232 case FORMAT_HTML:
1233 if (!$options['noclean']) {
1234 $text = clean_text($text, FORMAT_HTML, $options);
1236 $text = $filtermanager->filter_text($text, $context, $filteroptions);
1237 break;
1239 case FORMAT_PLAIN:
1240 $text = s($text); // Cleans dangerous JS.
1241 $text = rebuildnolinktag($text);
1242 $text = str_replace(' ', '&nbsp; ', $text);
1243 $text = nl2br($text);
1244 break;
1246 case FORMAT_WIKI:
1247 // This format is deprecated.
1248 $text = '<p>NOTICE: Wiki-like formatting has been removed from Moodle. You should not be seeing
1249 this message as all texts should have been converted to Markdown format instead.
1250 Please post a bug report to http://moodle.org/bugs with information about where you
1251 saw this message.</p>'.s($text);
1252 break;
1254 case FORMAT_MARKDOWN:
1255 $text = markdown_to_html($text);
1256 if (!$options['noclean']) {
1257 $text = clean_text($text, FORMAT_HTML, $options);
1259 $text = $filtermanager->filter_text($text, $context, $filteroptions);
1260 break;
1262 default: // FORMAT_MOODLE or anything else.
1263 $text = text_to_html($text, null, $options['para'], $options['newlines']);
1264 if (!$options['noclean']) {
1265 $text = clean_text($text, FORMAT_HTML, $options);
1267 $text = $filtermanager->filter_text($text, $context, $filteroptions);
1268 break;
1270 if ($options['filter']) {
1271 // At this point there should not be any draftfile links any more,
1272 // this happens when developers forget to post process the text.
1273 // The only potential problem is that somebody might try to format
1274 // the text before storing into database which would be itself big bug..
1275 $text = str_replace("\"$CFG->httpswwwroot/draftfile.php", "\"$CFG->httpswwwroot/brokenfile.php#", $text);
1277 if ($CFG->debugdeveloper) {
1278 if (strpos($text, '@@PLUGINFILE@@/') !== false) {
1279 debugging('Before calling format_text(), the content must be processed with file_rewrite_pluginfile_urls()',
1280 DEBUG_DEVELOPER);
1285 if (!empty($options['overflowdiv'])) {
1286 $text = html_writer::tag('div', $text, array('class' => 'no-overflow'));
1289 return $text;
1293 * Resets some data related to filters, called during upgrade or when general filter settings change.
1295 * @param bool $phpunitreset true means called from our PHPUnit integration test reset
1296 * @return void
1298 function reset_text_filters_cache($phpunitreset = false) {
1299 global $CFG, $DB;
1301 if ($phpunitreset) {
1302 // HTMLPurifier does not change, DB is already reset to defaults,
1303 // nothing to do here, the dataroot was cleared too.
1304 return;
1307 // The purge_all_caches() deals with cachedir and localcachedir purging,
1308 // the individual filter caches are invalidated as necessary elsewhere.
1310 // Update $CFG->filterall cache flag.
1311 if (empty($CFG->stringfilters)) {
1312 set_config('filterall', 0);
1313 return;
1315 $installedfilters = core_component::get_plugin_list('filter');
1316 $filters = explode(',', $CFG->stringfilters);
1317 foreach ($filters as $filter) {
1318 if (isset($installedfilters[$filter])) {
1319 set_config('filterall', 1);
1320 return;
1323 set_config('filterall', 0);
1327 * Given a simple string, this function returns the string
1328 * processed by enabled string filters if $CFG->filterall is enabled
1330 * This function should be used to print short strings (non html) that
1331 * need filter processing e.g. activity titles, post subjects,
1332 * glossary concepts.
1334 * @staticvar bool $strcache
1335 * @param string $string The string to be filtered. Should be plain text, expect
1336 * possibly for multilang tags.
1337 * @param boolean $striplinks To strip any link in the result text. Moodle 1.8 default changed from false to true! MDL-8713
1338 * @param array $options options array/object or courseid
1339 * @return string
1341 function format_string($string, $striplinks = true, $options = null) {
1342 global $CFG, $PAGE;
1344 // We'll use a in-memory cache here to speed up repeated strings.
1345 static $strcache = false;
1347 if (empty($CFG->version) or $CFG->version < 2013051400 or during_initial_install()) {
1348 // Do not filter anything during installation or before upgrade completes.
1349 return $string = strip_tags($string);
1352 if ($strcache === false or count($strcache) > 2000) {
1353 // This number might need some tuning to limit memory usage in cron.
1354 $strcache = array();
1357 if (is_numeric($options)) {
1358 // Legacy courseid usage.
1359 $options = array('context' => context_course::instance($options));
1360 } else {
1361 // Detach object, we can not modify it.
1362 $options = (array)$options;
1365 if (empty($options['context'])) {
1366 // Fallback to $PAGE->context this may be problematic in CLI and other non-standard pages :-(.
1367 $options['context'] = $PAGE->context;
1368 } else if (is_numeric($options['context'])) {
1369 $options['context'] = context::instance_by_id($options['context']);
1371 if (!isset($options['filter'])) {
1372 $options['filter'] = true;
1375 if (!$options['context']) {
1376 // We did not find any context? weird.
1377 return $string = strip_tags($string);
1380 // Calculate md5.
1381 $md5 = md5($string.'<+>'.$striplinks.'<+>'.$options['context']->id.'<+>'.current_language());
1383 // Fetch from cache if possible.
1384 if (isset($strcache[$md5])) {
1385 return $strcache[$md5];
1388 // First replace all ampersands not followed by html entity code
1389 // Regular expression moved to its own method for easier unit testing.
1390 $string = replace_ampersands_not_followed_by_entity($string);
1392 if (!empty($CFG->filterall) && $options['filter']) {
1393 $filtermanager = filter_manager::instance();
1394 $filtermanager->setup_page_for_filters($PAGE, $options['context']); // Setup global stuff filters may have.
1395 $string = $filtermanager->filter_string($string, $options['context']);
1398 // If the site requires it, strip ALL tags from this string.
1399 if (!empty($CFG->formatstringstriptags)) {
1400 $string = str_replace(array('<', '>'), array('&lt;', '&gt;'), strip_tags($string));
1402 } else {
1403 // Otherwise strip just links if that is required (default).
1404 if ($striplinks) {
1405 // Strip links in string.
1406 $string = strip_links($string);
1408 $string = clean_text($string);
1411 // Store to cache.
1412 $strcache[$md5] = $string;
1414 return $string;
1418 * Given a string, performs a negative lookahead looking for any ampersand character
1419 * that is not followed by a proper HTML entity. If any is found, it is replaced
1420 * by &amp;. The string is then returned.
1422 * @param string $string
1423 * @return string
1425 function replace_ampersands_not_followed_by_entity($string) {
1426 return preg_replace("/\&(?![a-zA-Z0-9#]{1,8};)/", "&amp;", $string);
1430 * Given a string, replaces all <a>.*</a> by .* and returns the string.
1432 * @param string $string
1433 * @return string
1435 function strip_links($string) {
1436 return preg_replace('/(<a\s[^>]+?>)(.+?)(<\/a>)/is', '$2', $string);
1440 * This expression turns links into something nice in a text format. (Russell Jungwirth)
1442 * @param string $string
1443 * @return string
1445 function wikify_links($string) {
1446 return preg_replace('~(<a [^<]*href=["|\']?([^ "\']*)["|\']?[^>]*>([^<]*)</a>)~i', '$3 [ $2 ]', $string);
1450 * Given text in a variety of format codings, this function returns the text as plain text suitable for plain email.
1452 * @param string $text The text to be formatted. This is raw text originally from user input.
1453 * @param int $format Identifier of the text format to be used
1454 * [FORMAT_MOODLE, FORMAT_HTML, FORMAT_PLAIN, FORMAT_WIKI, FORMAT_MARKDOWN]
1455 * @return string
1457 function format_text_email($text, $format) {
1459 switch ($format) {
1461 case FORMAT_PLAIN:
1462 return $text;
1463 break;
1465 case FORMAT_WIKI:
1466 // There should not be any of these any more!
1467 $text = wikify_links($text);
1468 return core_text::entities_to_utf8(strip_tags($text), true);
1469 break;
1471 case FORMAT_HTML:
1472 return html_to_text($text);
1473 break;
1475 case FORMAT_MOODLE:
1476 case FORMAT_MARKDOWN:
1477 default:
1478 $text = wikify_links($text);
1479 return core_text::entities_to_utf8(strip_tags($text), true);
1480 break;
1485 * Formats activity intro text
1487 * @param string $module name of module
1488 * @param object $activity instance of activity
1489 * @param int $cmid course module id
1490 * @param bool $filter filter resulting html text
1491 * @return string
1493 function format_module_intro($module, $activity, $cmid, $filter=true) {
1494 global $CFG;
1495 require_once("$CFG->libdir/filelib.php");
1496 $context = context_module::instance($cmid);
1497 $options = array('noclean' => true, 'para' => false, 'filter' => $filter, 'context' => $context, 'overflowdiv' => true);
1498 $intro = file_rewrite_pluginfile_urls($activity->intro, 'pluginfile.php', $context->id, 'mod_'.$module, 'intro', null);
1499 return trim(format_text($intro, $activity->introformat, $options, null));
1503 * Removes the usage of Moodle files from a text.
1505 * In some rare cases we need to re-use a text that already has embedded links
1506 * to some files hosted within Moodle. But the new area in which we will push
1507 * this content does not support files... therefore we need to remove those files.
1509 * @param string $source The text
1510 * @return string The stripped text
1512 function strip_pluginfile_content($source) {
1513 $baseurl = '@@PLUGINFILE@@';
1514 // Looking for something like < .* "@@pluginfile@@.*" .* >
1515 $pattern = '$<[^<>]+["\']' . $baseurl . '[^"\']*["\'][^<>]*>$';
1516 $stripped = preg_replace($pattern, '', $source);
1517 // Use purify html to rebalence potentially mismatched tags and generally cleanup.
1518 return purify_html($stripped);
1522 * Legacy function, used for cleaning of old forum and glossary text only.
1524 * @param string $text text that may contain legacy TRUSTTEXT marker
1525 * @return string text without legacy TRUSTTEXT marker
1527 function trusttext_strip($text) {
1528 while (true) { // Removing nested TRUSTTEXT.
1529 $orig = $text;
1530 $text = str_replace('#####TRUSTTEXT#####', '', $text);
1531 if (strcmp($orig, $text) === 0) {
1532 return $text;
1538 * Must be called before editing of all texts with trust flag. Removes all XSS nasties from texts stored in database if needed.
1540 * @param stdClass $object data object with xxx, xxxformat and xxxtrust fields
1541 * @param string $field name of text field
1542 * @param context $context active context
1543 * @return stdClass updated $object
1545 function trusttext_pre_edit($object, $field, $context) {
1546 $trustfield = $field.'trust';
1547 $formatfield = $field.'format';
1549 if (!$object->$trustfield or !trusttext_trusted($context)) {
1550 $object->$field = clean_text($object->$field, $object->$formatfield);
1553 return $object;
1557 * Is current user trusted to enter no dangerous XSS in this context?
1559 * Please note the user must be in fact trusted everywhere on this server!!
1561 * @param context $context
1562 * @return bool true if user trusted
1564 function trusttext_trusted($context) {
1565 return (trusttext_active() and has_capability('moodle/site:trustcontent', $context));
1569 * Is trusttext feature active?
1571 * @return bool
1573 function trusttext_active() {
1574 global $CFG;
1576 return !empty($CFG->enabletrusttext);
1580 * Cleans raw text removing nasties.
1582 * Given raw text (eg typed in by a user) this function cleans it up and removes any nasty tags that could mess up
1583 * Moodle pages through XSS attacks.
1585 * The result must be used as a HTML text fragment, this function can not cleanup random
1586 * parts of html tags such as url or src attributes.
1588 * NOTE: the format parameter was deprecated because we can safely clean only HTML.
1590 * @param string $text The text to be cleaned
1591 * @param int|string $format deprecated parameter, should always contain FORMAT_HTML or FORMAT_MOODLE
1592 * @param array $options Array of options; currently only option supported is 'allowid' (if true,
1593 * does not remove id attributes when cleaning)
1594 * @return string The cleaned up text
1596 function clean_text($text, $format = FORMAT_HTML, $options = array()) {
1597 $text = (string)$text;
1599 if ($format != FORMAT_HTML and $format != FORMAT_HTML) {
1600 // TODO: we need to standardise cleanup of text when loading it into editor first.
1601 // debugging('clean_text() is designed to work only with html');.
1604 if ($format == FORMAT_PLAIN) {
1605 return $text;
1608 if (is_purify_html_necessary($text)) {
1609 $text = purify_html($text, $options);
1612 // Originally we tried to neutralise some script events here, it was a wrong approach because
1613 // it was trivial to work around that (for example using style based XSS exploits).
1614 // We must not give false sense of security here - all developers MUST understand how to use
1615 // rawurlencode(), htmlentities(), htmlspecialchars(), p(), s(), moodle_url, html_writer and friends!!!
1617 return $text;
1621 * Is it necessary to use HTMLPurifier?
1623 * @private
1624 * @param string $text
1625 * @return bool false means html is safe and valid, true means use HTMLPurifier
1627 function is_purify_html_necessary($text) {
1628 if ($text === '') {
1629 return false;
1632 if ($text === (string)((int)$text)) {
1633 return false;
1636 if (strpos($text, '&') !== false or preg_match('|<[^pesb/]|', $text)) {
1637 // We need to normalise entities or other tags except p, em, strong and br present.
1638 return true;
1641 $altered = htmlspecialchars($text, ENT_NOQUOTES, 'UTF-8', true);
1642 if ($altered === $text) {
1643 // No < > or other special chars means this must be safe.
1644 return false;
1647 // Let's try to convert back some safe html tags.
1648 $altered = preg_replace('|&lt;p&gt;(.*?)&lt;/p&gt;|m', '<p>$1</p>', $altered);
1649 if ($altered === $text) {
1650 return false;
1652 $altered = preg_replace('|&lt;em&gt;([^<>]+?)&lt;/em&gt;|m', '<em>$1</em>', $altered);
1653 if ($altered === $text) {
1654 return false;
1656 $altered = preg_replace('|&lt;strong&gt;([^<>]+?)&lt;/strong&gt;|m', '<strong>$1</strong>', $altered);
1657 if ($altered === $text) {
1658 return false;
1660 $altered = str_replace('&lt;br /&gt;', '<br />', $altered);
1661 if ($altered === $text) {
1662 return false;
1665 return true;
1669 * KSES replacement cleaning function - uses HTML Purifier.
1671 * @param string $text The (X)HTML string to purify
1672 * @param array $options Array of options; currently only option supported is 'allowid' (if set,
1673 * does not remove id attributes when cleaning)
1674 * @return string
1676 function purify_html($text, $options = array()) {
1677 global $CFG;
1679 $text = (string)$text;
1681 static $purifiers = array();
1682 static $caches = array();
1684 // Purifier code can change only during major version upgrade.
1685 $version = empty($CFG->version) ? 0 : $CFG->version;
1686 $cachedir = "$CFG->localcachedir/htmlpurifier/$version";
1687 if (!file_exists($cachedir)) {
1688 // Purging of caches may remove the cache dir at any time,
1689 // luckily file_exists() results should be cached for all existing directories.
1690 $purifiers = array();
1691 $caches = array();
1692 gc_collect_cycles();
1694 make_localcache_directory('htmlpurifier', false);
1695 check_dir_exists($cachedir);
1698 $allowid = empty($options['allowid']) ? 0 : 1;
1699 $allowobjectembed = empty($CFG->allowobjectembed) ? 0 : 1;
1701 $type = 'type_'.$allowid.'_'.$allowobjectembed;
1703 if (!array_key_exists($type, $caches)) {
1704 $caches[$type] = cache::make('core', 'htmlpurifier', array('type' => $type));
1706 $cache = $caches[$type];
1708 // Add revision number and all options to the text key so that it is compatible with local cluster node caches.
1709 $key = "|$version|$allowobjectembed|$allowid|$text";
1710 $filteredtext = $cache->get($key);
1712 if ($filteredtext === true) {
1713 // The filtering did not change the text last time, no need to filter anything again.
1714 return $text;
1715 } else if ($filteredtext !== false) {
1716 return $filteredtext;
1719 if (empty($purifiers[$type])) {
1720 require_once $CFG->libdir.'/htmlpurifier/HTMLPurifier.safe-includes.php';
1721 require_once $CFG->libdir.'/htmlpurifier/locallib.php';
1722 $config = HTMLPurifier_Config::createDefault();
1724 $config->set('HTML.DefinitionID', 'moodlehtml');
1725 $config->set('HTML.DefinitionRev', 3);
1726 $config->set('Cache.SerializerPath', $cachedir);
1727 $config->set('Cache.SerializerPermissions', $CFG->directorypermissions);
1728 $config->set('Core.NormalizeNewlines', false);
1729 $config->set('Core.ConvertDocumentToFragment', true);
1730 $config->set('Core.Encoding', 'UTF-8');
1731 $config->set('HTML.Doctype', 'XHTML 1.0 Transitional');
1732 $config->set('URI.AllowedSchemes', array(
1733 'http' => true,
1734 'https' => true,
1735 'ftp' => true,
1736 'irc' => true,
1737 'nntp' => true,
1738 'news' => true,
1739 'rtsp' => true,
1740 'rtmp' => true,
1741 'teamspeak' => true,
1742 'gopher' => true,
1743 'mms' => true,
1744 'mailto' => true
1746 $config->set('Attr.AllowedFrameTargets', array('_blank'));
1748 if ($allowobjectembed) {
1749 $config->set('HTML.SafeObject', true);
1750 $config->set('Output.FlashCompat', true);
1751 $config->set('HTML.SafeEmbed', true);
1754 if ($allowid) {
1755 $config->set('Attr.EnableID', true);
1758 if ($def = $config->maybeGetRawHTMLDefinition()) {
1759 $def->addElement('nolink', 'Block', 'Flow', array()); // Skip our filters inside.
1760 $def->addElement('tex', 'Inline', 'Inline', array()); // Tex syntax, equivalent to $$xx$$.
1761 $def->addElement('algebra', 'Inline', 'Inline', array()); // Algebra syntax, equivalent to @@xx@@.
1762 $def->addElement('lang', 'Block', 'Flow', array(), array('lang'=>'CDATA')); // Original multilang style - only our hacked lang attribute.
1763 $def->addAttribute('span', 'xxxlang', 'CDATA'); // Current very problematic multilang.
1765 // Use the built-in Ruby module to add annotation support.
1766 $def->manager->addModule(new HTMLPurifier_HTMLModule_Ruby());
1769 $purifier = new HTMLPurifier($config);
1770 $purifiers[$type] = $purifier;
1771 } else {
1772 $purifier = $purifiers[$type];
1775 $multilang = (strpos($text, 'class="multilang"') !== false);
1777 $filteredtext = $text;
1778 if ($multilang) {
1779 $filteredtextregex = '/<span(\s+lang="([a-zA-Z0-9_-]+)"|\s+class="multilang"){2}\s*>/';
1780 $filteredtext = preg_replace($filteredtextregex, '<span xxxlang="${2}">', $filteredtext);
1782 $filteredtext = (string)$purifier->purify($filteredtext);
1783 if ($multilang) {
1784 $filteredtext = preg_replace('/<span xxxlang="([a-zA-Z0-9_-]+)">/', '<span lang="${1}" class="multilang">', $filteredtext);
1787 if ($text === $filteredtext) {
1788 // No need to store the filtered text, next time we will just return unfiltered text
1789 // because it was not changed by purifying.
1790 $cache->set($key, true);
1791 } else {
1792 $cache->set($key, $filteredtext);
1795 return $filteredtext;
1799 * Given plain text, makes it into HTML as nicely as possible.
1801 * May contain HTML tags already.
1803 * Do not abuse this function. It is intended as lower level formatting feature used
1804 * by {@link format_text()} to convert FORMAT_MOODLE to HTML. You are supposed
1805 * to call format_text() in most of cases.
1807 * @param string $text The string to convert.
1808 * @param boolean $smileyignored Was used to determine if smiley characters should convert to smiley images, ignored now
1809 * @param boolean $para If true then the returned string will be wrapped in div tags
1810 * @param boolean $newlines If true then lines newline breaks will be converted to HTML newline breaks.
1811 * @return string
1813 function text_to_html($text, $smileyignored = null, $para = true, $newlines = true) {
1814 // Remove any whitespace that may be between HTML tags.
1815 $text = preg_replace("~>([[:space:]]+)<~i", "><", $text);
1817 // Remove any returns that precede or follow HTML tags.
1818 $text = preg_replace("~([\n\r])<~i", " <", $text);
1819 $text = preg_replace("~>([\n\r])~i", "> ", $text);
1821 // Make returns into HTML newlines.
1822 if ($newlines) {
1823 $text = nl2br($text);
1826 // Wrap the whole thing in a div if required.
1827 if ($para) {
1828 // In 1.9 this was changed from a p => div.
1829 return '<div class="text_to_html">'.$text.'</div>';
1830 } else {
1831 return $text;
1836 * Given Markdown formatted text, make it into XHTML using external function
1838 * @param string $text The markdown formatted text to be converted.
1839 * @return string Converted text
1841 function markdown_to_html($text) {
1842 global $CFG;
1844 if ($text === '' or $text === null) {
1845 return $text;
1848 require_once($CFG->libdir .'/markdown/MarkdownInterface.php');
1849 require_once($CFG->libdir .'/markdown/Markdown.php');
1850 require_once($CFG->libdir .'/markdown/MarkdownExtra.php');
1852 return \Michelf\MarkdownExtra::defaultTransform($text);
1856 * Given HTML text, make it into plain text using external function
1858 * @param string $html The text to be converted.
1859 * @param integer $width Width to wrap the text at. (optional, default 75 which
1860 * is a good value for email. 0 means do not limit line length.)
1861 * @param boolean $dolinks By default, any links in the HTML are collected, and
1862 * printed as a list at the end of the HTML. If you don't want that, set this
1863 * argument to false.
1864 * @return string plain text equivalent of the HTML.
1866 function html_to_text($html, $width = 75, $dolinks = true) {
1867 global $CFG;
1869 require_once($CFG->libdir .'/html2text/lib.php');
1871 $options = array(
1872 'width' => $width,
1873 'do_links' => 'table',
1876 if (empty($dolinks)) {
1877 $options['do_links'] = 'none';
1879 $h2t = new core_html2text($html, $options);
1880 $result = $h2t->getText();
1882 return $result;
1886 * This function will highlight search words in a given string
1888 * It cares about HTML and will not ruin links. It's best to use
1889 * this function after performing any conversions to HTML.
1891 * @param string $needle The search string. Syntax like "word1 +word2 -word3" is dealt with correctly.
1892 * @param string $haystack The string (HTML) within which to highlight the search terms.
1893 * @param boolean $matchcase whether to do case-sensitive. Default case-insensitive.
1894 * @param string $prefix the string to put before each search term found.
1895 * @param string $suffix the string to put after each search term found.
1896 * @return string The highlighted HTML.
1898 function highlight($needle, $haystack, $matchcase = false,
1899 $prefix = '<span class="highlight">', $suffix = '</span>') {
1901 // Quick bail-out in trivial cases.
1902 if (empty($needle) or empty($haystack)) {
1903 return $haystack;
1906 // Break up the search term into words, discard any -words and build a regexp.
1907 $words = preg_split('/ +/', trim($needle));
1908 foreach ($words as $index => $word) {
1909 if (strpos($word, '-') === 0) {
1910 unset($words[$index]);
1911 } else if (strpos($word, '+') === 0) {
1912 $words[$index] = '\b' . preg_quote(ltrim($word, '+'), '/') . '\b'; // Match only as a complete word.
1913 } else {
1914 $words[$index] = preg_quote($word, '/');
1917 $regexp = '/(' . implode('|', $words) . ')/u'; // Char u is to do UTF-8 matching.
1918 if (!$matchcase) {
1919 $regexp .= 'i';
1922 // Another chance to bail-out if $search was only -words.
1923 if (empty($words)) {
1924 return $haystack;
1927 // Split the string into HTML tags and real content.
1928 $chunks = preg_split('/((?:<[^>]*>)+)/', $haystack, -1, PREG_SPLIT_DELIM_CAPTURE);
1930 // We have an array of alternating blocks of text, then HTML tags, then text, ...
1931 // Loop through replacing search terms in the text, and leaving the HTML unchanged.
1932 $ishtmlchunk = false;
1933 $result = '';
1934 foreach ($chunks as $chunk) {
1935 if ($ishtmlchunk) {
1936 $result .= $chunk;
1937 } else {
1938 $result .= preg_replace($regexp, $prefix . '$1' . $suffix, $chunk);
1940 $ishtmlchunk = !$ishtmlchunk;
1943 return $result;
1947 * This function will highlight instances of $needle in $haystack
1949 * It's faster that the above function {@link highlight()} and doesn't care about
1950 * HTML or anything.
1952 * @param string $needle The string to search for
1953 * @param string $haystack The string to search for $needle in
1954 * @return string The highlighted HTML
1956 function highlightfast($needle, $haystack) {
1958 if (empty($needle) or empty($haystack)) {
1959 return $haystack;
1962 $parts = explode(core_text::strtolower($needle), core_text::strtolower($haystack));
1964 if (count($parts) === 1) {
1965 return $haystack;
1968 $pos = 0;
1970 foreach ($parts as $key => $part) {
1971 $parts[$key] = substr($haystack, $pos, strlen($part));
1972 $pos += strlen($part);
1974 $parts[$key] .= '<span class="highlight">'.substr($haystack, $pos, strlen($needle)).'</span>';
1975 $pos += strlen($needle);
1978 return str_replace('<span class="highlight"></span>', '', join('', $parts));
1982 * Return a string containing 'lang', xml:lang and optionally 'dir' HTML attributes.
1984 * Internationalisation, for print_header and backup/restorelib.
1986 * @param bool $dir Default false
1987 * @return string Attributes
1989 function get_html_lang($dir = false) {
1990 $direction = '';
1991 if ($dir) {
1992 if (right_to_left()) {
1993 $direction = ' dir="rtl"';
1994 } else {
1995 $direction = ' dir="ltr"';
1998 // Accessibility: added the 'lang' attribute to $direction, used in theme <html> tag.
1999 $language = str_replace('_', '-', current_language());
2000 @header('Content-Language: '.$language);
2001 return ($direction.' lang="'.$language.'" xml:lang="'.$language.'"');
2005 // STANDARD WEB PAGE PARTS.
2008 * Send the HTTP headers that Moodle requires.
2010 * There is a backwards compatibility hack for legacy code
2011 * that needs to add custom IE compatibility directive.
2013 * Example:
2014 * <code>
2015 * if (!isset($CFG->additionalhtmlhead)) {
2016 * $CFG->additionalhtmlhead = '';
2018 * $CFG->additionalhtmlhead .= '<meta http-equiv="X-UA-Compatible" content="IE=8" />';
2019 * header('X-UA-Compatible: IE=8');
2020 * echo $OUTPUT->header();
2021 * </code>
2023 * Please note the $CFG->additionalhtmlhead alone might not work,
2024 * you should send the IE compatibility header() too.
2026 * @param string $contenttype
2027 * @param bool $cacheable Can this page be cached on back?
2028 * @return void, sends HTTP headers
2030 function send_headers($contenttype, $cacheable = true) {
2031 global $CFG;
2033 @header('Content-Type: ' . $contenttype);
2034 @header('Content-Script-Type: text/javascript');
2035 @header('Content-Style-Type: text/css');
2037 if (empty($CFG->additionalhtmlhead) or stripos($CFG->additionalhtmlhead, 'X-UA-Compatible') === false) {
2038 @header('X-UA-Compatible: IE=edge');
2041 if ($cacheable) {
2042 // Allow caching on "back" (but not on normal clicks).
2043 @header('Cache-Control: private, pre-check=0, post-check=0, max-age=0, no-transform');
2044 @header('Pragma: no-cache');
2045 @header('Expires: ');
2046 } else {
2047 // Do everything we can to always prevent clients and proxies caching.
2048 @header('Cache-Control: no-store, no-cache, must-revalidate');
2049 @header('Cache-Control: post-check=0, pre-check=0, no-transform', false);
2050 @header('Pragma: no-cache');
2051 @header('Expires: Mon, 20 Aug 1969 09:23:00 GMT');
2052 @header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
2054 @header('Accept-Ranges: none');
2056 if (empty($CFG->allowframembedding)) {
2057 @header('X-Frame-Options: sameorigin');
2062 * Return the right arrow with text ('next'), and optionally embedded in a link.
2064 * @param string $text HTML/plain text label (set to blank only for breadcrumb separator cases).
2065 * @param string $url An optional link to use in a surrounding HTML anchor.
2066 * @param bool $accesshide True if text should be hidden (for screen readers only).
2067 * @param string $addclass Additional class names for the link, or the arrow character.
2068 * @return string HTML string.
2070 function link_arrow_right($text, $url='', $accesshide=false, $addclass='') {
2071 global $OUTPUT; // TODO: move to output renderer.
2072 $arrowclass = 'arrow ';
2073 if (!$url) {
2074 $arrowclass .= $addclass;
2076 $arrow = '<span class="'.$arrowclass.'">'.$OUTPUT->rarrow().'</span>';
2077 $htmltext = '';
2078 if ($text) {
2079 $htmltext = '<span class="arrow_text">'.$text.'</span>&nbsp;';
2080 if ($accesshide) {
2081 $htmltext = get_accesshide($htmltext);
2084 if ($url) {
2085 $class = 'arrow_link';
2086 if ($addclass) {
2087 $class .= ' '.$addclass;
2089 return '<a class="'.$class.'" href="'.$url.'" title="'.preg_replace('/<.*?>/', '', $text).'">'.$htmltext.$arrow.'</a>';
2091 return $htmltext.$arrow;
2095 * Return the left arrow with text ('previous'), and optionally embedded in a link.
2097 * @param string $text HTML/plain text label (set to blank only for breadcrumb separator cases).
2098 * @param string $url An optional link to use in a surrounding HTML anchor.
2099 * @param bool $accesshide True if text should be hidden (for screen readers only).
2100 * @param string $addclass Additional class names for the link, or the arrow character.
2101 * @return string HTML string.
2103 function link_arrow_left($text, $url='', $accesshide=false, $addclass='') {
2104 global $OUTPUT; // TODO: move to utput renderer.
2105 $arrowclass = 'arrow ';
2106 if (! $url) {
2107 $arrowclass .= $addclass;
2109 $arrow = '<span class="'.$arrowclass.'">'.$OUTPUT->larrow().'</span>';
2110 $htmltext = '';
2111 if ($text) {
2112 $htmltext = '&nbsp;<span class="arrow_text">'.$text.'</span>';
2113 if ($accesshide) {
2114 $htmltext = get_accesshide($htmltext);
2117 if ($url) {
2118 $class = 'arrow_link';
2119 if ($addclass) {
2120 $class .= ' '.$addclass;
2122 return '<a class="'.$class.'" href="'.$url.'" title="'.preg_replace('/<.*?>/', '', $text).'">'.$arrow.$htmltext.'</a>';
2124 return $arrow.$htmltext;
2128 * Return a HTML element with the class "accesshide", for accessibility.
2130 * Please use cautiously - where possible, text should be visible!
2132 * @param string $text Plain text.
2133 * @param string $elem Lowercase element name, default "span".
2134 * @param string $class Additional classes for the element.
2135 * @param string $attrs Additional attributes string in the form, "name='value' name2='value2'"
2136 * @return string HTML string.
2138 function get_accesshide($text, $elem='span', $class='', $attrs='') {
2139 return "<$elem class=\"accesshide $class\" $attrs>$text</$elem>";
2143 * Return the breadcrumb trail navigation separator.
2145 * @return string HTML string.
2147 function get_separator() {
2148 // Accessibility: the 'hidden' slash is preferred for screen readers.
2149 return ' '.link_arrow_right($text='/', $url='', $accesshide=true, 'sep').' ';
2153 * Print (or return) a collapsible region, that has a caption that can be clicked to expand or collapse the region.
2155 * If JavaScript is off, then the region will always be expanded.
2157 * @param string $contents the contents of the box.
2158 * @param string $classes class names added to the div that is output.
2159 * @param string $id id added to the div that is output. Must not be blank.
2160 * @param string $caption text displayed at the top. Clicking on this will cause the region to expand or contract.
2161 * @param string $userpref the name of the user preference that stores the user's preferred default state.
2162 * (May be blank if you do not wish the state to be persisted.
2163 * @param boolean $default Initial collapsed state to use if the user_preference it not set.
2164 * @param boolean $return if true, return the HTML as a string, rather than printing it.
2165 * @return string|void If $return is false, returns nothing, otherwise returns a string of HTML.
2167 function print_collapsible_region($contents, $classes, $id, $caption, $userpref = '', $default = false, $return = false) {
2168 $output = print_collapsible_region_start($classes, $id, $caption, $userpref, $default, true);
2169 $output .= $contents;
2170 $output .= print_collapsible_region_end(true);
2172 if ($return) {
2173 return $output;
2174 } else {
2175 echo $output;
2180 * Print (or return) the start of a collapsible region
2182 * The collapsibleregion has a caption that can be clicked to expand or collapse the region. If JavaScript is off, then the region
2183 * will always be expanded.
2185 * @param string $classes class names added to the div that is output.
2186 * @param string $id id added to the div that is output. Must not be blank.
2187 * @param string $caption text displayed at the top. Clicking on this will cause the region to expand or contract.
2188 * @param string $userpref the name of the user preference that stores the user's preferred default state.
2189 * (May be blank if you do not wish the state to be persisted.
2190 * @param boolean $default Initial collapsed state to use if the user_preference it not set.
2191 * @param boolean $return if true, return the HTML as a string, rather than printing it.
2192 * @return string|void if $return is false, returns nothing, otherwise returns a string of HTML.
2194 function print_collapsible_region_start($classes, $id, $caption, $userpref = '', $default = false, $return = false) {
2195 global $PAGE;
2197 // Work out the initial state.
2198 if (!empty($userpref) and is_string($userpref)) {
2199 user_preference_allow_ajax_update($userpref, PARAM_BOOL);
2200 $collapsed = get_user_preferences($userpref, $default);
2201 } else {
2202 $collapsed = $default;
2203 $userpref = false;
2206 if ($collapsed) {
2207 $classes .= ' collapsed';
2210 $output = '';
2211 $output .= '<div id="' . $id . '" class="collapsibleregion ' . $classes . '">';
2212 $output .= '<div id="' . $id . '_sizer">';
2213 $output .= '<div id="' . $id . '_caption" class="collapsibleregioncaption">';
2214 $output .= $caption . ' ';
2215 $output .= '</div><div id="' . $id . '_inner" class="collapsibleregioninner">';
2216 $PAGE->requires->js_init_call('M.util.init_collapsible_region', array($id, $userpref, get_string('clicktohideshow')));
2218 if ($return) {
2219 return $output;
2220 } else {
2221 echo $output;
2226 * Close a region started with print_collapsible_region_start.
2228 * @param boolean $return if true, return the HTML as a string, rather than printing it.
2229 * @return string|void if $return is false, returns nothing, otherwise returns a string of HTML.
2231 function print_collapsible_region_end($return = false) {
2232 $output = '</div></div></div>';
2234 if ($return) {
2235 return $output;
2236 } else {
2237 echo $output;
2242 * Print a specified group's avatar.
2244 * @param array|stdClass $group A single {@link group} object OR array of groups.
2245 * @param int $courseid The course ID.
2246 * @param boolean $large Default small picture, or large.
2247 * @param boolean $return If false print picture, otherwise return the output as string
2248 * @param boolean $link Enclose image in a link to view specified course?
2249 * @return string|void Depending on the setting of $return
2251 function print_group_picture($group, $courseid, $large=false, $return=false, $link=true) {
2252 global $CFG;
2254 if (is_array($group)) {
2255 $output = '';
2256 foreach ($group as $g) {
2257 $output .= print_group_picture($g, $courseid, $large, true, $link);
2259 if ($return) {
2260 return $output;
2261 } else {
2262 echo $output;
2263 return;
2267 $context = context_course::instance($courseid);
2269 // If there is no picture, do nothing.
2270 if (!$group->picture) {
2271 return '';
2274 // If picture is hidden, only show to those with course:managegroups.
2275 if ($group->hidepicture and !has_capability('moodle/course:managegroups', $context)) {
2276 return '';
2279 if ($link or has_capability('moodle/site:accessallgroups', $context)) {
2280 $output = '<a href="'. $CFG->wwwroot .'/user/index.php?id='. $courseid .'&amp;group='. $group->id .'">';
2281 } else {
2282 $output = '';
2284 if ($large) {
2285 $file = 'f1';
2286 } else {
2287 $file = 'f2';
2290 $grouppictureurl = moodle_url::make_pluginfile_url($context->id, 'group', 'icon', $group->id, '/', $file);
2291 $grouppictureurl->param('rev', $group->picture);
2292 $output .= '<img class="grouppicture" src="'.$grouppictureurl.'"'.
2293 ' alt="'.s(get_string('group').' '.$group->name).'" title="'.s($group->name).'"/>';
2295 if ($link or has_capability('moodle/site:accessallgroups', $context)) {
2296 $output .= '</a>';
2299 if ($return) {
2300 return $output;
2301 } else {
2302 echo $output;
2308 * Display a recent activity note
2310 * @staticvar string $strftimerecent
2311 * @param int $time A timestamp int.
2312 * @param stdClass $user A user object from the database.
2313 * @param string $text Text for display for the note
2314 * @param string $link The link to wrap around the text
2315 * @param bool $return If set to true the HTML is returned rather than echo'd
2316 * @param string $viewfullnames
2317 * @return string If $retrun was true returns HTML for a recent activity notice.
2319 function print_recent_activity_note($time, $user, $text, $link, $return=false, $viewfullnames=null) {
2320 static $strftimerecent = null;
2321 $output = '';
2323 if (is_null($viewfullnames)) {
2324 $context = context_system::instance();
2325 $viewfullnames = has_capability('moodle/site:viewfullnames', $context);
2328 if (is_null($strftimerecent)) {
2329 $strftimerecent = get_string('strftimerecent');
2332 $output .= '<div class="head">';
2333 $output .= '<div class="date">'.userdate($time, $strftimerecent).'</div>';
2334 $output .= '<div class="name">'.fullname($user, $viewfullnames).'</div>';
2335 $output .= '</div>';
2336 $output .= '<div class="info"><a href="'.$link.'">'.format_string($text, true).'</a></div>';
2338 if ($return) {
2339 return $output;
2340 } else {
2341 echo $output;
2346 * Returns a popup menu with course activity modules
2348 * Given a course this function returns a small popup menu with all the course activity modules in it, as a navigation menu
2349 * outputs a simple list structure in XHTML.
2350 * The data is taken from the serialised array stored in the course record.
2352 * @param course $course A {@link $COURSE} object.
2353 * @param array $sections
2354 * @param course_modinfo $modinfo
2355 * @param string $strsection
2356 * @param string $strjumpto
2357 * @param int $width
2358 * @param string $cmid
2359 * @return string The HTML block
2361 function navmenulist($course, $sections, $modinfo, $strsection, $strjumpto, $width=50, $cmid=0) {
2363 global $CFG, $OUTPUT;
2365 $section = -1;
2366 $menu = array();
2367 $doneheading = false;
2369 $courseformatoptions = course_get_format($course)->get_format_options();
2370 $coursecontext = context_course::instance($course->id);
2372 $menu[] = '<ul class="navmenulist"><li class="jumpto section"><span>'.$strjumpto.'</span><ul>';
2373 foreach ($modinfo->cms as $mod) {
2374 if (!$mod->has_view()) {
2375 // Don't show modules which you can't link to!
2376 continue;
2379 // For course formats using 'numsections' do not show extra sections.
2380 if (isset($courseformatoptions['numsections']) && $mod->sectionnum > $courseformatoptions['numsections']) {
2381 break;
2384 if (!$mod->uservisible) { // Do not icnlude empty sections at all.
2385 continue;
2388 if ($mod->sectionnum >= 0 and $section != $mod->sectionnum) {
2389 $thissection = $sections[$mod->sectionnum];
2391 if ($thissection->visible or
2392 (isset($courseformatoptions['hiddensections']) and !$courseformatoptions['hiddensections']) or
2393 has_capability('moodle/course:viewhiddensections', $coursecontext)) {
2394 $thissection->summary = strip_tags(format_string($thissection->summary, true));
2395 if (!$doneheading) {
2396 $menu[] = '</ul></li>';
2398 if ($course->format == 'weeks' or empty($thissection->summary)) {
2399 $item = $strsection ." ". $mod->sectionnum;
2400 } else {
2401 if (core_text::strlen($thissection->summary) < ($width-3)) {
2402 $item = $thissection->summary;
2403 } else {
2404 $item = core_text::substr($thissection->summary, 0, $width).'...';
2407 $menu[] = '<li class="section"><span>'.$item.'</span>';
2408 $menu[] = '<ul>';
2409 $doneheading = true;
2411 $section = $mod->sectionnum;
2412 } else {
2413 // No activities from this hidden section shown.
2414 continue;
2418 $url = $mod->modname .'/view.php?id='. $mod->id;
2419 $mod->name = strip_tags(format_string($mod->name ,true));
2420 if (core_text::strlen($mod->name) > ($width+5)) {
2421 $mod->name = core_text::substr($mod->name, 0, $width).'...';
2423 if (!$mod->visible) {
2424 $mod->name = '('.$mod->name.')';
2426 $class = 'activity '.$mod->modname;
2427 $class .= ($cmid == $mod->id) ? ' selected' : '';
2428 $menu[] = '<li class="'.$class.'">'.
2429 '<img src="'.$OUTPUT->pix_url('icon', $mod->modname) . '" alt="" />'.
2430 '<a href="'.$CFG->wwwroot.'/mod/'.$url.'">'.$mod->name.'</a></li>';
2433 if ($doneheading) {
2434 $menu[] = '</ul></li>';
2436 $menu[] = '</ul></li></ul>';
2438 return implode("\n", $menu);
2442 * Prints a grade menu (as part of an existing form) with help showing all possible numerical grades and scales.
2444 * @todo Finish documenting this function
2445 * @todo Deprecate: this is only used in a few contrib modules
2447 * @param int $courseid The course ID
2448 * @param string $name
2449 * @param string $current
2450 * @param boolean $includenograde Include those with no grades
2451 * @param boolean $return If set to true returns rather than echo's
2452 * @return string|bool Depending on value of $return
2454 function print_grade_menu($courseid, $name, $current, $includenograde=true, $return=false) {
2455 global $OUTPUT;
2457 $output = '';
2458 $strscale = get_string('scale');
2459 $strscales = get_string('scales');
2461 $scales = get_scales_menu($courseid);
2462 foreach ($scales as $i => $scalename) {
2463 $grades[-$i] = $strscale .': '. $scalename;
2465 if ($includenograde) {
2466 $grades[0] = get_string('nograde');
2468 for ($i=100; $i>=1; $i--) {
2469 $grades[$i] = $i;
2471 $output .= html_writer::select($grades, $name, $current, false);
2473 $helppix = $OUTPUT->pix_url('help');
2474 $linkobject = '<span class="helplink"><img class="iconhelp" alt="'.$strscales.'" src="'.$helppix.'" /></span>';
2475 $link = new moodle_url('/course/scales.php', array('id' => $courseid, 'list' => 1));
2476 $action = new popup_action('click', $link, 'ratingscales', array('height' => 400, 'width' => 500));
2477 $output .= $OUTPUT->action_link($link, $linkobject, $action, array('title' => $strscales));
2479 if ($return) {
2480 return $output;
2481 } else {
2482 echo $output;
2487 * Print an error to STDOUT and exit with a non-zero code. For commandline scripts.
2489 * Default errorcode is 1.
2491 * Very useful for perl-like error-handling:
2492 * do_somethting() or mdie("Something went wrong");
2494 * @param string $msg Error message
2495 * @param integer $errorcode Error code to emit
2497 function mdie($msg='', $errorcode=1) {
2498 trigger_error($msg);
2499 exit($errorcode);
2503 * Print a message and exit.
2505 * @param string $message The message to print in the notice
2506 * @param string $link The link to use for the continue button
2507 * @param object $course A course object. Unused.
2508 * @return void This function simply exits
2510 function notice ($message, $link='', $course=null) {
2511 global $PAGE, $OUTPUT;
2513 $message = clean_text($message); // In case nasties are in here.
2515 if (CLI_SCRIPT) {
2516 echo("!!$message!!\n");
2517 exit(1); // No success.
2520 if (!$PAGE->headerprinted) {
2521 // Header not yet printed.
2522 $PAGE->set_title(get_string('notice'));
2523 echo $OUTPUT->header();
2524 } else {
2525 echo $OUTPUT->container_end_all(false);
2528 echo $OUTPUT->box($message, 'generalbox', 'notice');
2529 echo $OUTPUT->continue_button($link);
2531 echo $OUTPUT->footer();
2532 exit(1); // General error code.
2536 * Redirects the user to another page, after printing a notice.
2538 * This function calls the OUTPUT redirect method, echo's the output and then dies to ensure nothing else happens.
2540 * <strong>Good practice:</strong> You should call this method before starting page
2541 * output by using any of the OUTPUT methods.
2543 * @param moodle_url|string $url A moodle_url to redirect to. Strings are not to be trusted!
2544 * @param string $message The message to display to the user
2545 * @param int $delay The delay before redirecting
2546 * @throws moodle_exception
2548 function redirect($url, $message='', $delay=-1) {
2549 global $OUTPUT, $PAGE, $CFG;
2551 if (CLI_SCRIPT or AJAX_SCRIPT) {
2552 // This is wrong - developers should not use redirect in these scripts but it should not be very likely.
2553 throw new moodle_exception('redirecterrordetected', 'error');
2556 // Prevent debug errors - make sure context is properly initialised.
2557 if ($PAGE) {
2558 $PAGE->set_context(null);
2559 $PAGE->set_pagelayout('redirect'); // No header and footer needed.
2560 $PAGE->set_title(get_string('pageshouldredirect', 'moodle'));
2563 if ($url instanceof moodle_url) {
2564 $url = $url->out(false);
2567 $debugdisableredirect = false;
2568 do {
2569 if (defined('DEBUGGING_PRINTED')) {
2570 // Some debugging already printed, no need to look more.
2571 $debugdisableredirect = true;
2572 break;
2575 if (core_useragent::is_msword()) {
2576 // Clicking a URL from MS Word sends a request to the server without cookies. If that
2577 // causes a redirect Word will open a browser pointing the new URL. If not, the URL that
2578 // was clicked is opened. Because the request from Word is without cookies, it almost
2579 // always results in a redirect to the login page, even if the user is logged in in their
2580 // browser. This is not what we want, so prevent the redirect for requests from Word.
2581 $debugdisableredirect = true;
2582 break;
2585 if (empty($CFG->debugdisplay) or empty($CFG->debug)) {
2586 // No errors should be displayed.
2587 break;
2590 if (!function_exists('error_get_last') or !$lasterror = error_get_last()) {
2591 break;
2594 if (!($lasterror['type'] & $CFG->debug)) {
2595 // Last error not interesting.
2596 break;
2599 // Watch out here, @hidden() errors are returned from error_get_last() too.
2600 if (headers_sent()) {
2601 // We already started printing something - that means errors likely printed.
2602 $debugdisableredirect = true;
2603 break;
2606 if (ob_get_level() and ob_get_contents()) {
2607 // There is something waiting to be printed, hopefully it is the errors,
2608 // but it might be some error hidden by @ too - such as the timezone mess from setup.php.
2609 $debugdisableredirect = true;
2610 break;
2612 } while (false);
2614 // Technically, HTTP/1.1 requires Location: header to contain the absolute path.
2615 // (In practice browsers accept relative paths - but still, might as well do it properly.)
2616 // This code turns relative into absolute.
2617 if (!preg_match('|^[a-z]+:|i', $url)) {
2618 // Get host name http://www.wherever.com.
2619 $hostpart = preg_replace('|^(.*?[^:/])/.*$|', '$1', $CFG->wwwroot);
2620 if (preg_match('|^/|', $url)) {
2621 // URLs beginning with / are relative to web server root so we just add them in.
2622 $url = $hostpart.$url;
2623 } else {
2624 // URLs not beginning with / are relative to path of current script, so add that on.
2625 $url = $hostpart.preg_replace('|\?.*$|', '', me()).'/../'.$url;
2627 // Replace all ..s.
2628 while (true) {
2629 $newurl = preg_replace('|/(?!\.\.)[^/]*/\.\./|', '/', $url);
2630 if ($newurl == $url) {
2631 break;
2633 $url = $newurl;
2637 // Sanitise url - we can not rely on moodle_url or our URL cleaning
2638 // because they do not support all valid external URLs.
2639 $url = preg_replace('/[\x00-\x1F\x7F]/', '', $url);
2640 $url = str_replace('"', '%22', $url);
2641 $encodedurl = preg_replace("/\&(?![a-zA-Z0-9#]{1,8};)/", "&amp;", $url);
2642 $encodedurl = preg_replace('/^.*href="([^"]*)".*$/', "\\1", clean_text('<a href="'.$encodedurl.'" />', FORMAT_HTML));
2643 $url = str_replace('&amp;', '&', $encodedurl);
2645 if (!empty($message)) {
2646 if ($delay === -1 || !is_numeric($delay)) {
2647 $delay = 3;
2649 $message = clean_text($message);
2650 } else {
2651 $message = get_string('pageshouldredirect');
2652 $delay = 0;
2655 // Make sure the session is closed properly, this prevents problems in IIS
2656 // and also some potential PHP shutdown issues.
2657 \core\session\manager::write_close();
2659 if ($delay == 0 && !$debugdisableredirect && !headers_sent()) {
2660 // 302 might not work for POST requests, 303 is ignored by obsolete clients.
2661 @header($_SERVER['SERVER_PROTOCOL'] . ' 303 See Other');
2662 @header('Location: '.$url);
2663 echo bootstrap_renderer::plain_redirect_message($encodedurl);
2664 exit;
2667 // Include a redirect message, even with a HTTP redirect, because that is recommended practice.
2668 if ($PAGE) {
2669 $CFG->docroot = false; // To prevent the link to moodle docs from being displayed on redirect page.
2670 echo $OUTPUT->redirect_message($encodedurl, $message, $delay, $debugdisableredirect);
2671 exit;
2672 } else {
2673 echo bootstrap_renderer::early_redirect_message($encodedurl, $message, $delay);
2674 exit;
2679 * Given an email address, this function will return an obfuscated version of it.
2681 * @param string $email The email address to obfuscate
2682 * @return string The obfuscated email address
2684 function obfuscate_email($email) {
2685 $i = 0;
2686 $length = strlen($email);
2687 $obfuscated = '';
2688 while ($i < $length) {
2689 if (rand(0, 2) && $email{$i}!='@') { // MDL-20619 some browsers have problems unobfuscating @.
2690 $obfuscated.='%'.dechex(ord($email{$i}));
2691 } else {
2692 $obfuscated.=$email{$i};
2694 $i++;
2696 return $obfuscated;
2700 * This function takes some text and replaces about half of the characters
2701 * with HTML entity equivalents. Return string is obviously longer.
2703 * @param string $plaintext The text to be obfuscated
2704 * @return string The obfuscated text
2706 function obfuscate_text($plaintext) {
2707 $i=0;
2708 $length = core_text::strlen($plaintext);
2709 $obfuscated='';
2710 $prevobfuscated = false;
2711 while ($i < $length) {
2712 $char = core_text::substr($plaintext, $i, 1);
2713 $ord = core_text::utf8ord($char);
2714 $numerical = ($ord >= ord('0')) && ($ord <= ord('9'));
2715 if ($prevobfuscated and $numerical ) {
2716 $obfuscated.='&#'.$ord.';';
2717 } else if (rand(0, 2)) {
2718 $obfuscated.='&#'.$ord.';';
2719 $prevobfuscated = true;
2720 } else {
2721 $obfuscated.=$char;
2722 $prevobfuscated = false;
2724 $i++;
2726 return $obfuscated;
2730 * This function uses the {@link obfuscate_email()} and {@link obfuscate_text()}
2731 * to generate a fully obfuscated email link, ready to use.
2733 * @param string $email The email address to display
2734 * @param string $label The text to displayed as hyperlink to $email
2735 * @param boolean $dimmed If true then use css class 'dimmed' for hyperlink
2736 * @param string $subject The subject of the email in the mailto link
2737 * @param string $body The content of the email in the mailto link
2738 * @return string The obfuscated mailto link
2740 function obfuscate_mailto($email, $label='', $dimmed=false, $subject = '', $body = '') {
2742 if (empty($label)) {
2743 $label = $email;
2746 $label = obfuscate_text($label);
2747 $email = obfuscate_email($email);
2748 $mailto = obfuscate_text('mailto');
2749 $url = new moodle_url("mailto:$email");
2750 $attrs = array();
2752 if (!empty($subject)) {
2753 $url->param('subject', format_string($subject));
2755 if (!empty($body)) {
2756 $url->param('body', format_string($body));
2759 // Use the obfuscated mailto.
2760 $url = preg_replace('/^mailto/', $mailto, $url->out());
2762 if ($dimmed) {
2763 $attrs['title'] = get_string('emaildisable');
2764 $attrs['class'] = 'dimmed';
2767 return html_writer::link($url, $label, $attrs);
2771 * This function is used to rebuild the <nolink> tag because some formats (PLAIN and WIKI)
2772 * will transform it to html entities
2774 * @param string $text Text to search for nolink tag in
2775 * @return string
2777 function rebuildnolinktag($text) {
2779 $text = preg_replace('/&lt;(\/*nolink)&gt;/i', '<$1>', $text);
2781 return $text;
2785 * Prints a maintenance message from $CFG->maintenance_message or default if empty.
2787 function print_maintenance_message() {
2788 global $CFG, $SITE, $PAGE, $OUTPUT;
2790 $PAGE->set_pagetype('maintenance-message');
2791 $PAGE->set_pagelayout('maintenance');
2792 $PAGE->set_title(strip_tags($SITE->fullname));
2793 $PAGE->set_heading($SITE->fullname);
2794 echo $OUTPUT->header();
2795 echo $OUTPUT->heading(get_string('sitemaintenance', 'admin'));
2796 if (isset($CFG->maintenance_message) and !html_is_blank($CFG->maintenance_message)) {
2797 echo $OUTPUT->box_start('maintenance_message generalbox boxwidthwide boxaligncenter');
2798 echo $CFG->maintenance_message;
2799 echo $OUTPUT->box_end();
2801 echo $OUTPUT->footer();
2802 die;
2806 * Returns a string containing a nested list, suitable for formatting into tabs with CSS.
2808 * It is not recommended to use this function in Moodle 2.5 but it is left for backward
2809 * compartibility.
2811 * Example how to print a single line tabs:
2812 * $rows = array(
2813 * new tabobject(...),
2814 * new tabobject(...)
2815 * );
2816 * echo $OUTPUT->tabtree($rows, $selectedid);
2818 * Multiple row tabs may not look good on some devices but if you want to use them
2819 * you can specify ->subtree for the active tabobject.
2821 * @param array $tabrows An array of rows where each row is an array of tab objects
2822 * @param string $selected The id of the selected tab (whatever row it's on)
2823 * @param array $inactive An array of ids of inactive tabs that are not selectable.
2824 * @param array $activated An array of ids of other tabs that are currently activated
2825 * @param bool $return If true output is returned rather then echo'd
2826 * @return string HTML output if $return was set to true.
2828 function print_tabs($tabrows, $selected = null, $inactive = null, $activated = null, $return = false) {
2829 global $OUTPUT;
2831 $tabrows = array_reverse($tabrows);
2832 $subtree = array();
2833 foreach ($tabrows as $row) {
2834 $tree = array();
2836 foreach ($row as $tab) {
2837 $tab->inactive = is_array($inactive) && in_array((string)$tab->id, $inactive);
2838 $tab->activated = is_array($activated) && in_array((string)$tab->id, $activated);
2839 $tab->selected = (string)$tab->id == $selected;
2841 if ($tab->activated || $tab->selected) {
2842 $tab->subtree = $subtree;
2844 $tree[] = $tab;
2846 $subtree = $tree;
2848 $output = $OUTPUT->tabtree($subtree);
2849 if ($return) {
2850 return $output;
2851 } else {
2852 print $output;
2853 return !empty($output);
2858 * Alter debugging level for the current request,
2859 * the change is not saved in database.
2861 * @param int $level one of the DEBUG_* constants
2862 * @param bool $debugdisplay
2864 function set_debugging($level, $debugdisplay = null) {
2865 global $CFG;
2867 $CFG->debug = (int)$level;
2868 $CFG->debugdeveloper = (($CFG->debug & DEBUG_DEVELOPER) === DEBUG_DEVELOPER);
2870 if ($debugdisplay !== null) {
2871 $CFG->debugdisplay = (bool)$debugdisplay;
2876 * Standard Debugging Function
2878 * Returns true if the current site debugging settings are equal or above specified level.
2879 * If passed a parameter it will emit a debugging notice similar to trigger_error(). The
2880 * routing of notices is controlled by $CFG->debugdisplay
2881 * eg use like this:
2883 * 1) debugging('a normal debug notice');
2884 * 2) debugging('something really picky', DEBUG_ALL);
2885 * 3) debugging('annoying debug message only for developers', DEBUG_DEVELOPER);
2886 * 4) if (debugging()) { perform extra debugging operations (do not use print or echo) }
2888 * In code blocks controlled by debugging() (such as example 4)
2889 * any output should be routed via debugging() itself, or the lower-level
2890 * trigger_error() or error_log(). Using echo or print will break XHTML
2891 * JS and HTTP headers.
2893 * It is also possible to define NO_DEBUG_DISPLAY which redirects the message to error_log.
2895 * @param string $message a message to print
2896 * @param int $level the level at which this debugging statement should show
2897 * @param array $backtrace use different backtrace
2898 * @return bool
2900 function debugging($message = '', $level = DEBUG_NORMAL, $backtrace = null) {
2901 global $CFG, $USER;
2903 $forcedebug = false;
2904 if (!empty($CFG->debugusers) && $USER) {
2905 $debugusers = explode(',', $CFG->debugusers);
2906 $forcedebug = in_array($USER->id, $debugusers);
2909 if (!$forcedebug and (empty($CFG->debug) || ($CFG->debug != -1 and $CFG->debug < $level))) {
2910 return false;
2913 if (!isset($CFG->debugdisplay)) {
2914 $CFG->debugdisplay = ini_get_bool('display_errors');
2917 if ($message) {
2918 if (!$backtrace) {
2919 $backtrace = debug_backtrace();
2921 $from = format_backtrace($backtrace, CLI_SCRIPT || NO_DEBUG_DISPLAY);
2922 if (PHPUNIT_TEST) {
2923 if (phpunit_util::debugging_triggered($message, $level, $from)) {
2924 // We are inside test, the debug message was logged.
2925 return true;
2929 if (NO_DEBUG_DISPLAY) {
2930 // Script does not want any errors or debugging in output,
2931 // we send the info to error log instead.
2932 error_log('Debugging: ' . $message . ' in '. PHP_EOL . $from);
2934 } else if ($forcedebug or $CFG->debugdisplay) {
2935 if (!defined('DEBUGGING_PRINTED')) {
2936 define('DEBUGGING_PRINTED', 1); // Indicates we have printed something.
2938 if (CLI_SCRIPT) {
2939 echo "++ $message ++\n$from";
2940 } else {
2941 echo '<div class="notifytiny debuggingmessage" data-rel="debugging">' , $message , $from , '</div>';
2944 } else {
2945 trigger_error($message . $from, E_USER_NOTICE);
2948 return true;
2952 * Outputs a HTML comment to the browser.
2954 * This is used for those hard-to-debug pages that use bits from many different files in very confusing ways (e.g. blocks).
2956 * <code>print_location_comment(__FILE__, __LINE__);</code>
2958 * @param string $file
2959 * @param integer $line
2960 * @param boolean $return Whether to return or print the comment
2961 * @return string|void Void unless true given as third parameter
2963 function print_location_comment($file, $line, $return = false) {
2964 if ($return) {
2965 return "<!-- $file at line $line -->\n";
2966 } else {
2967 echo "<!-- $file at line $line -->\n";
2973 * Returns true if the user is using a right-to-left language.
2975 * @return boolean true if the current language is right-to-left (Hebrew, Arabic etc)
2977 function right_to_left() {
2978 return (get_string('thisdirection', 'langconfig') === 'rtl');
2983 * Returns swapped left<=> right if in RTL environment.
2985 * Part of RTL Moodles support.
2987 * @param string $align align to check
2988 * @return string
2990 function fix_align_rtl($align) {
2991 if (!right_to_left()) {
2992 return $align;
2994 if ($align == 'left') {
2995 return 'right';
2997 if ($align == 'right') {
2998 return 'left';
3000 return $align;
3005 * Returns true if the page is displayed in a popup window.
3007 * Gets the information from the URL parameter inpopup.
3009 * @todo Use a central function to create the popup calls all over Moodle and
3010 * In the moment only works with resources and probably questions.
3012 * @return boolean
3014 function is_in_popup() {
3015 $inpopup = optional_param('inpopup', '', PARAM_BOOL);
3017 return ($inpopup);
3021 * Progress bar class.
3023 * Manages the display of a progress bar.
3025 * To use this class.
3026 * - construct
3027 * - call create (or use the 3rd param to the constructor)
3028 * - call update or update_full() or update() repeatedly
3030 * @copyright 2008 jamiesensei
3031 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3032 * @package core
3034 class progress_bar {
3035 /** @var string html id */
3036 private $html_id;
3037 /** @var int total width */
3038 private $width;
3039 /** @var int last percentage printed */
3040 private $percent = 0;
3041 /** @var int time when last printed */
3042 private $lastupdate = 0;
3043 /** @var int when did we start printing this */
3044 private $time_start = 0;
3047 * Constructor
3049 * Prints JS code if $autostart true.
3051 * @param string $html_id
3052 * @param int $width
3053 * @param bool $autostart Default to false
3055 public function __construct($htmlid = '', $width = 500, $autostart = false) {
3056 if (!empty($htmlid)) {
3057 $this->html_id = $htmlid;
3058 } else {
3059 $this->html_id = 'pbar_'.uniqid();
3062 $this->width = $width;
3064 if ($autostart) {
3065 $this->create();
3070 * Create a new progress bar, this function will output html.
3072 * @return void Echo's output
3074 public function create() {
3075 global $PAGE;
3077 $this->time_start = microtime(true);
3078 if (CLI_SCRIPT) {
3079 return; // Temporary solution for cli scripts.
3082 $PAGE->requires->string_for_js('secondsleft', 'moodle');
3084 $htmlcode = <<<EOT
3085 <div class="progressbar_container" style="width: {$this->width}px;" id="{$this->html_id}">
3086 <h2></h2>
3087 <div class="progress progress-striped active">
3088 <div class="bar" role="progressbar" aria-valuemin="0" aria-valuemax="100" aria-valuenow="0">&nbsp;</div>
3089 </div>
3090 <p></p>
3091 </div>
3092 EOT;
3093 flush();
3094 echo $htmlcode;
3095 flush();
3099 * Update the progress bar
3101 * @param int $percent from 1-100
3102 * @param string $msg
3103 * @return void Echo's output
3104 * @throws coding_exception
3106 private function _update($percent, $msg) {
3107 if (empty($this->time_start)) {
3108 throw new coding_exception('You must call create() (or use the $autostart ' .
3109 'argument to the constructor) before you try updating the progress bar.');
3112 if (CLI_SCRIPT) {
3113 return; // Temporary solution for cli scripts.
3116 $estimate = $this->estimate($percent);
3118 if ($estimate === null) {
3119 // Always do the first and last updates.
3120 } else if ($estimate == 0) {
3121 // Always do the last updates.
3122 } else if ($this->lastupdate + 20 < time()) {
3123 // We must update otherwise browser would time out.
3124 } else if (round($this->percent, 2) === round($percent, 2)) {
3125 // No significant change, no need to update anything.
3126 return;
3128 if (is_numeric($estimate)) {
3129 $estimate = get_string('secondsleft', 'moodle', round($estimate, 2));
3132 $this->percent = round($percent, 2);
3133 $this->lastupdate = microtime(true);
3135 echo html_writer::script(js_writer::function_call('updateProgressBar',
3136 array($this->html_id, $this->percent, $msg, $estimate)));
3137 flush();
3141 * Estimate how much time it is going to take.
3143 * @param int $pt from 1-100
3144 * @return mixed Null (unknown), or int
3146 private function estimate($pt) {
3147 if ($this->lastupdate == 0) {
3148 return null;
3150 if ($pt < 0.00001) {
3151 return null; // We do not know yet how long it will take.
3153 if ($pt > 99.99999) {
3154 return 0; // Nearly done, right?
3156 $consumed = microtime(true) - $this->time_start;
3157 if ($consumed < 0.001) {
3158 return null;
3161 return (100 - $pt) * ($consumed / $pt);
3165 * Update progress bar according percent
3167 * @param int $percent from 1-100
3168 * @param string $msg the message needed to be shown
3170 public function update_full($percent, $msg) {
3171 $percent = max(min($percent, 100), 0);
3172 $this->_update($percent, $msg);
3176 * Update progress bar according the number of tasks
3178 * @param int $cur current task number
3179 * @param int $total total task number
3180 * @param string $msg message
3182 public function update($cur, $total, $msg) {
3183 $percent = ($cur / $total) * 100;
3184 $this->update_full($percent, $msg);
3188 * Restart the progress bar.
3190 public function restart() {
3191 $this->percent = 0;
3192 $this->lastupdate = 0;
3193 $this->time_start = 0;
3198 * Progress trace class.
3200 * Use this class from long operations where you want to output occasional information about
3201 * what is going on, but don't know if, or in what format, the output should be.
3203 * @copyright 2009 Tim Hunt
3204 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3205 * @package core
3207 abstract class progress_trace {
3209 * Output an progress message in whatever format.
3211 * @param string $message the message to output.
3212 * @param integer $depth indent depth for this message.
3214 abstract public function output($message, $depth = 0);
3217 * Called when the processing is finished.
3219 public function finished() {
3224 * This subclass of progress_trace does not ouput anything.
3226 * @copyright 2009 Tim Hunt
3227 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3228 * @package core
3230 class null_progress_trace extends progress_trace {
3232 * Does Nothing
3234 * @param string $message
3235 * @param int $depth
3236 * @return void Does Nothing
3238 public function output($message, $depth = 0) {
3243 * This subclass of progress_trace outputs to plain text.
3245 * @copyright 2009 Tim Hunt
3246 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3247 * @package core
3249 class text_progress_trace extends progress_trace {
3251 * Output the trace message.
3253 * @param string $message
3254 * @param int $depth
3255 * @return void Output is echo'd
3257 public function output($message, $depth = 0) {
3258 echo str_repeat(' ', $depth), $message, "\n";
3259 flush();
3264 * This subclass of progress_trace outputs as HTML.
3266 * @copyright 2009 Tim Hunt
3267 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3268 * @package core
3270 class html_progress_trace extends progress_trace {
3272 * Output the trace message.
3274 * @param string $message
3275 * @param int $depth
3276 * @return void Output is echo'd
3278 public function output($message, $depth = 0) {
3279 echo '<p>', str_repeat('&#160;&#160;', $depth), htmlspecialchars($message), "</p>\n";
3280 flush();
3285 * HTML List Progress Tree
3287 * @copyright 2009 Tim Hunt
3288 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3289 * @package core
3291 class html_list_progress_trace extends progress_trace {
3292 /** @var int */
3293 protected $currentdepth = -1;
3296 * Echo out the list
3298 * @param string $message The message to display
3299 * @param int $depth
3300 * @return void Output is echoed
3302 public function output($message, $depth = 0) {
3303 $samedepth = true;
3304 while ($this->currentdepth > $depth) {
3305 echo "</li>\n</ul>\n";
3306 $this->currentdepth -= 1;
3307 if ($this->currentdepth == $depth) {
3308 echo '<li>';
3310 $samedepth = false;
3312 while ($this->currentdepth < $depth) {
3313 echo "<ul>\n<li>";
3314 $this->currentdepth += 1;
3315 $samedepth = false;
3317 if ($samedepth) {
3318 echo "</li>\n<li>";
3320 echo htmlspecialchars($message);
3321 flush();
3325 * Called when the processing is finished.
3327 public function finished() {
3328 while ($this->currentdepth >= 0) {
3329 echo "</li>\n</ul>\n";
3330 $this->currentdepth -= 1;
3336 * This subclass of progress_trace outputs to error log.
3338 * @copyright Petr Skoda {@link http://skodak.org}
3339 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3340 * @package core
3342 class error_log_progress_trace extends progress_trace {
3343 /** @var string log prefix */
3344 protected $prefix;
3347 * Constructor.
3348 * @param string $prefix optional log prefix
3350 public function __construct($prefix = '') {
3351 $this->prefix = $prefix;
3355 * Output the trace message.
3357 * @param string $message
3358 * @param int $depth
3359 * @return void Output is sent to error log.
3361 public function output($message, $depth = 0) {
3362 error_log($this->prefix . str_repeat(' ', $depth) . $message);
3367 * Special type of trace that can be used for catching of output of other traces.
3369 * @copyright Petr Skoda {@link http://skodak.org}
3370 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3371 * @package core
3373 class progress_trace_buffer extends progress_trace {
3374 /** @var progres_trace */
3375 protected $trace;
3376 /** @var bool do we pass output out */
3377 protected $passthrough;
3378 /** @var string output buffer */
3379 protected $buffer;
3382 * Constructor.
3384 * @param progress_trace $trace
3385 * @param bool $passthrough true means output and buffer, false means just buffer and no output
3387 public function __construct(progress_trace $trace, $passthrough = true) {
3388 $this->trace = $trace;
3389 $this->passthrough = $passthrough;
3390 $this->buffer = '';
3394 * Output the trace message.
3396 * @param string $message the message to output.
3397 * @param int $depth indent depth for this message.
3398 * @return void output stored in buffer
3400 public function output($message, $depth = 0) {
3401 ob_start();
3402 $this->trace->output($message, $depth);
3403 $this->buffer .= ob_get_contents();
3404 if ($this->passthrough) {
3405 ob_end_flush();
3406 } else {
3407 ob_end_clean();
3412 * Called when the processing is finished.
3414 public function finished() {
3415 ob_start();
3416 $this->trace->finished();
3417 $this->buffer .= ob_get_contents();
3418 if ($this->passthrough) {
3419 ob_end_flush();
3420 } else {
3421 ob_end_clean();
3426 * Reset internal text buffer.
3428 public function reset_buffer() {
3429 $this->buffer = '';
3433 * Return internal text buffer.
3434 * @return string buffered plain text
3436 public function get_buffer() {
3437 return $this->buffer;
3442 * Special type of trace that can be used for redirecting to multiple other traces.
3444 * @copyright Petr Skoda {@link http://skodak.org}
3445 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3446 * @package core
3448 class combined_progress_trace extends progress_trace {
3451 * An array of traces.
3452 * @var array
3454 protected $traces;
3457 * Constructs a new instance.
3459 * @param array $traces multiple traces
3461 public function __construct(array $traces) {
3462 $this->traces = $traces;
3466 * Output an progress message in whatever format.
3468 * @param string $message the message to output.
3469 * @param integer $depth indent depth for this message.
3471 public function output($message, $depth = 0) {
3472 foreach ($this->traces as $trace) {
3473 $trace->output($message, $depth);
3478 * Called when the processing is finished.
3480 public function finished() {
3481 foreach ($this->traces as $trace) {
3482 $trace->finished();
3488 * Returns a localized sentence in the current language summarizing the current password policy
3490 * @todo this should be handled by a function/method in the language pack library once we have a support for it
3491 * @uses $CFG
3492 * @return string
3494 function print_password_policy() {
3495 global $CFG;
3497 $message = '';
3498 if (!empty($CFG->passwordpolicy)) {
3499 $messages = array();
3500 $messages[] = get_string('informminpasswordlength', 'auth', $CFG->minpasswordlength);
3501 if (!empty($CFG->minpassworddigits)) {
3502 $messages[] = get_string('informminpassworddigits', 'auth', $CFG->minpassworddigits);
3504 if (!empty($CFG->minpasswordlower)) {
3505 $messages[] = get_string('informminpasswordlower', 'auth', $CFG->minpasswordlower);
3507 if (!empty($CFG->minpasswordupper)) {
3508 $messages[] = get_string('informminpasswordupper', 'auth', $CFG->minpasswordupper);
3510 if (!empty($CFG->minpasswordnonalphanum)) {
3511 $messages[] = get_string('informminpasswordnonalphanum', 'auth', $CFG->minpasswordnonalphanum);
3514 $messages = join(', ', $messages); // This is ugly but we do not have anything better yet...
3515 $message = get_string('informpasswordpolicy', 'auth', $messages);
3517 return $message;
3521 * Get the value of a help string fully prepared for display in the current language.
3523 * @param string $identifier The identifier of the string to search for.
3524 * @param string $component The module the string is associated with.
3525 * @param boolean $ajax Whether this help is called from an AJAX script.
3526 * This is used to influence text formatting and determines
3527 * which format to output the doclink in.
3528 * @param string|object|array $a An object, string or number that can be used
3529 * within translation strings
3530 * @return Object An object containing:
3531 * - heading: Any heading that there may be for this help string.
3532 * - text: The wiki-formatted help string.
3533 * - doclink: An object containing a link, the linktext, and any additional
3534 * CSS classes to apply to that link. Only present if $ajax = false.
3535 * - completedoclink: A text representation of the doclink. Only present if $ajax = true.
3537 function get_formatted_help_string($identifier, $component, $ajax = false, $a = null) {
3538 global $CFG, $OUTPUT;
3539 $sm = get_string_manager();
3541 // Do not rebuild caches here!
3542 // Devs need to learn to purge all caches after any change or disable $CFG->langstringcache.
3544 $data = new stdClass();
3546 if ($sm->string_exists($identifier, $component)) {
3547 $data->heading = format_string(get_string($identifier, $component));
3548 } else {
3549 // Gracefully fall back to an empty string.
3550 $data->heading = '';
3553 if ($sm->string_exists($identifier . '_help', $component)) {
3554 $options = new stdClass();
3555 $options->trusted = false;
3556 $options->noclean = false;
3557 $options->smiley = false;
3558 $options->filter = false;
3559 $options->para = true;
3560 $options->newlines = false;
3561 $options->overflowdiv = !$ajax;
3563 // Should be simple wiki only MDL-21695.
3564 $data->text = format_text(get_string($identifier.'_help', $component, $a), FORMAT_MARKDOWN, $options);
3566 $helplink = $identifier . '_link';
3567 if ($sm->string_exists($helplink, $component)) { // Link to further info in Moodle docs.
3568 $link = get_string($helplink, $component);
3569 $linktext = get_string('morehelp');
3571 $data->doclink = new stdClass();
3572 $url = new moodle_url(get_docs_url($link));
3573 if ($ajax) {
3574 $data->doclink->link = $url->out();
3575 $data->doclink->linktext = $linktext;
3576 $data->doclink->class = ($CFG->doctonewwindow) ? 'helplinkpopup' : '';
3577 } else {
3578 $data->completedoclink = html_writer::tag('div', $OUTPUT->doc_link($link, $linktext),
3579 array('class' => 'helpdoclink'));
3582 } else {
3583 $data->text = html_writer::tag('p',
3584 html_writer::tag('strong', 'TODO') . ": missing help string [{$identifier}_help, {$component}]");
3586 return $data;
3590 * Renders a hidden password field so that browsers won't incorrectly autofill password fields with the user's password.
3592 * @since 3.0
3593 * @return string HTML to prevent password autofill
3595 function prevent_form_autofill_password() {
3596 return '<div class="hide"><input type="password" /></div>';