2 // This file is part of Moodle - http://moodle.org/
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.
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/>.
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.
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();
37 // Define text formatting types ... eventually we can add Wiki, BBcode etc.
40 * Does all sorts of transformations and filtering.
42 define('FORMAT_MOODLE', '0');
45 * Plain HTML (with some tags stripped).
47 define('FORMAT_HTML', '1');
50 * Plain text (even tags are printed in full).
52 define('FORMAT_PLAIN', '2');
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');
63 * Markdown-formatted text http://daringfireball.net/projects/markdown/
65 define('FORMAT_MARKDOWN', '4');
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);
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);
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);
85 * Add quotes to HTML characters.
87 * Returns $var with HTML characters (like "<", ">", etc.) properly quoted.
88 * This function is very similar to {@link p()}
90 * @param string $var the string potentially containing HTML characters
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('/&#(\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 {@link s()}
112 * @todo Remove obsolete param $obsolete if not used anywhere
114 * @param string $var the string potentially containing HTML characters
115 * @param boolean $obsolete no longer used.
118 function p($var, $obsolete = false) {
119 echo s($var, $obsolete);
123 * Does proper javascript quoting.
125 * Do not use addslashes anymore, because it does not work when magic_quotes_sybase is enabled.
127 * @param mixed $var String, Array, or Object to add slashes to
128 * @return mixed quoted result
130 function addslashes_js($var) {
131 if (is_string($var)) {
132 $var = str_replace('\\', '\\\\', $var);
133 $var = str_replace(array('\'', '"', "\n", "\r", "\0"), array('\\\'', '\\"', '\\n', '\\r', '\\0'), $var);
134 $var = str_replace('</', '<\/', $var); // XHTML compliance.
135 } else if (is_array($var)) {
136 $var = array_map('addslashes_js', $var);
137 } else if (is_object($var)) {
138 $a = get_object_vars($var);
139 foreach ($a as $key => $value) {
140 $a[$key] = addslashes_js($value);
148 * Remove query string from url.
150 * Takes in a URL and returns it without the querystring portion.
152 * @param string $url the url which may have a query string attached.
153 * @return string The remaining URL.
155 function strip_querystring($url) {
157 if ($commapos = strpos($url, '?')) {
158 return substr($url, 0, $commapos);
165 * Returns the URL of the HTTP_REFERER, less the querystring portion if required.
167 * @param boolean $stripquery if true, also removes the query part of the url.
168 * @return string The resulting referer or empty string.
170 function get_referer($stripquery=true) {
171 if (isset($_SERVER['HTTP_REFERER'])) {
173 return strip_querystring($_SERVER['HTTP_REFERER']);
175 return $_SERVER['HTTP_REFERER'];
183 * Returns the name of the current script, WITH the querystring portion.
185 * This function is necessary because PHP_SELF and REQUEST_URI and SCRIPT_NAME
186 * return different things depending on a lot of things like your OS, Web
187 * server, and the way PHP is compiled (ie. as a CGI, module, ISAPI, etc.)
188 * <b>NOTE:</b> This function returns false if the global variables needed are not set.
190 * @return mixed String or false if the global variables needed are not set.
198 * Guesses the full URL of the current script.
200 * This function is using $PAGE->url, but may fall back to $FULLME which
201 * is constructed from PHP_SELF and REQUEST_URI or SCRIPT_NAME
203 * @return mixed full page URL string or false if unknown
205 function qualified_me() {
206 global $FULLME, $PAGE, $CFG;
208 if (isset($PAGE) and $PAGE->has_set_url()) {
209 // This is the only recommended way to find out current page.
210 return $PAGE->url
->out(false);
213 if ($FULLME === null) {
214 // CLI script most probably.
217 if (!empty($CFG->sslproxy
)) {
218 // Return only https links when using SSL proxy.
219 return preg_replace('/^http:/', 'https:', $FULLME, 1);
227 * Determines whether or not the Moodle site is being served over HTTPS.
229 * This is done simply by checking the value of $CFG->httpswwwroot, which seems
230 * to be the only reliable method.
232 * @return boolean True if site is served over HTTPS, false otherwise.
234 function is_https() {
237 return (strpos($CFG->httpswwwroot
, 'https://') === 0);
241 * Returns the cleaned local URL of the HTTP_REFERER less the URL query string parameters if required.
243 * If you need to get an external referer, you can do so by using clean_param($_SERVER['HTTP_REFERER'], PARAM_URL)
244 * and optionally stripquerystring().
246 * @param bool $stripquery if true, also removes the query part of the url.
247 * @return string The resulting referer or empty string.
249 function get_local_referer($stripquery = true) {
250 if (isset($_SERVER['HTTP_REFERER'])) {
251 $referer = clean_param($_SERVER['HTTP_REFERER'], PARAM_LOCALURL
);
253 return strip_querystring($referer);
263 * Class for creating and manipulating urls.
265 * It can be used in moodle pages where config.php has been included without any further includes.
267 * It is useful for manipulating urls with long lists of params.
268 * One situation where it will be useful is a page which links to itself to perform various actions
269 * and / or to process form data. A moodle_url object :
270 * can be created for a page to refer to itself with all the proper get params being passed from page call to
271 * page call and methods can be used to output a url including all the params, optionally adding and overriding
272 * params and can also be used to
273 * - output the url without any get params
274 * - and output the params as hidden fields to be output within a form
276 * @copyright 2007 jamiesensei
277 * @link http://docs.moodle.org/dev/lib/weblib.php_moodle_url See short write up here
278 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
284 * Scheme, ex.: http, https
287 protected $scheme = '';
293 protected $host = '';
296 * Port number, empty means default 80 or 443 in case of http.
299 protected $port = '';
302 * Username for http auth.
305 protected $user = '';
308 * Password for http auth.
311 protected $pass = '';
317 protected $path = '';
320 * Optional slash argument value.
323 protected $slashargument = '';
326 * Anchor, may be also empty, null means none.
329 protected $anchor = null;
332 * Url parameters as associative array.
335 protected $params = array();
338 * Create new instance of moodle_url.
340 * @param moodle_url|string $url - moodle_url means make a copy of another
341 * moodle_url and change parameters, string means full url or shortened
342 * form (ex.: '/course/view.php'). It is strongly encouraged to not include
343 * query string because it may result in double encoded values. Use the
344 * $params instead. For admin URLs, just use /admin/script.php, this
345 * class takes care of the $CFG->admin issue.
346 * @param array $params these params override current params or add new
347 * @param string $anchor The anchor to use as part of the URL if there is one.
348 * @throws moodle_exception
350 public function __construct($url, array $params = null, $anchor = null) {
353 if ($url instanceof moodle_url
) {
354 $this->scheme
= $url->scheme
;
355 $this->host
= $url->host
;
356 $this->port
= $url->port
;
357 $this->user
= $url->user
;
358 $this->pass
= $url->pass
;
359 $this->path
= $url->path
;
360 $this->slashargument
= $url->slashargument
;
361 $this->params
= $url->params
;
362 $this->anchor
= $url->anchor
;
365 // Detect if anchor used.
366 $apos = strpos($url, '#');
367 if ($apos !== false) {
368 $anchor = substr($url, $apos);
369 $anchor = ltrim($anchor, '#');
370 $this->set_anchor($anchor);
371 $url = substr($url, 0, $apos);
374 // Normalise shortened form of our url ex.: '/course/view.php'.
375 if (strpos($url, '/') === 0) {
376 // We must not use httpswwwroot here, because it might be url of other page,
377 // devs have to use httpswwwroot explicitly when creating new moodle_url.
378 $url = $CFG->wwwroot
.$url;
381 // Now fix the admin links if needed, no need to mess with httpswwwroot.
382 if ($CFG->admin
!== 'admin') {
383 if (strpos($url, "$CFG->wwwroot/admin/") === 0) {
384 $url = str_replace("$CFG->wwwroot/admin/", "$CFG->wwwroot/$CFG->admin/", $url);
389 $parts = parse_url($url);
390 if ($parts === false) {
391 throw new moodle_exception('invalidurl');
393 if (isset($parts['query'])) {
394 // Note: the values may not be correctly decoded, url parameters should be always passed as array.
395 parse_str(str_replace('&', '&', $parts['query']), $this->params
);
397 unset($parts['query']);
398 foreach ($parts as $key => $value) {
399 $this->$key = $value;
402 // Detect slashargument value from path - we do not support directory names ending with .php.
403 $pos = strpos($this->path
, '.php/');
404 if ($pos !== false) {
405 $this->slashargument
= substr($this->path
, $pos +
4);
406 $this->path
= substr($this->path
, 0, $pos +
4);
410 $this->params($params);
411 if ($anchor !== null) {
412 $this->anchor
= (string)$anchor;
417 * Add an array of params to the params for this url.
419 * The added params override existing ones if they have the same name.
421 * @param array $params Defaults to null. If null then returns all params.
422 * @return array Array of Params for url.
423 * @throws coding_exception
425 public function params(array $params = null) {
426 $params = (array)$params;
428 foreach ($params as $key => $value) {
430 throw new coding_exception('Url parameters can not have numeric keys!');
432 if (!is_string($value)) {
433 if (is_array($value)) {
434 throw new coding_exception('Url parameters values can not be arrays!');
436 if (is_object($value) and !method_exists($value, '__toString')) {
437 throw new coding_exception('Url parameters values can not be objects, unless __toString() is defined!');
440 $this->params
[$key] = (string)$value;
442 return $this->params
;
446 * Remove all params if no arguments passed.
447 * Remove selected params if arguments are passed.
449 * Can be called as either remove_params('param1', 'param2')
450 * or remove_params(array('param1', 'param2')).
452 * @param string[]|string $params,... either an array of param names, or 1..n string params to remove as args.
453 * @return array url parameters
455 public function remove_params($params = null) {
456 if (!is_array($params)) {
457 $params = func_get_args();
459 foreach ($params as $param) {
460 unset($this->params
[$param]);
462 return $this->params
;
466 * Remove all url parameters.
468 * @todo remove the unused param.
469 * @param array $params Unused param
472 public function remove_all_params($params = null) {
473 $this->params
= array();
474 $this->slashargument
= '';
478 * Add a param to the params for this url.
480 * The added param overrides existing one if they have the same name.
482 * @param string $paramname name
483 * @param string $newvalue Param value. If new value specified current value is overriden or parameter is added
484 * @return mixed string parameter value, null if parameter does not exist
486 public function param($paramname, $newvalue = '') {
487 if (func_num_args() > 1) {
489 $this->params(array($paramname => $newvalue));
491 if (isset($this->params
[$paramname])) {
492 return $this->params
[$paramname];
499 * Merges parameters and validates them
501 * @param array $overrideparams
502 * @return array merged parameters
503 * @throws coding_exception
505 protected function merge_overrideparams(array $overrideparams = null) {
506 $overrideparams = (array)$overrideparams;
507 $params = $this->params
;
508 foreach ($overrideparams as $key => $value) {
510 throw new coding_exception('Overridden parameters can not have numeric keys!');
512 if (is_array($value)) {
513 throw new coding_exception('Overridden parameters values can not be arrays!');
515 if (is_object($value) and !method_exists($value, '__toString')) {
516 throw new coding_exception('Overridden parameters values can not be objects, unless __toString() is defined!');
518 $params[$key] = (string)$value;
524 * Get the params as as a query string.
526 * This method should not be used outside of this method.
528 * @param bool $escaped Use & as params separator instead of plain &
529 * @param array $overrideparams params to add to the output params, these
530 * override existing ones with the same name.
531 * @return string query string that can be added to a url.
533 public function get_query_string($escaped = true, array $overrideparams = null) {
535 if ($overrideparams !== null) {
536 $params = $this->merge_overrideparams($overrideparams);
538 $params = $this->params
;
540 foreach ($params as $key => $val) {
541 if (is_array($val)) {
542 foreach ($val as $index => $value) {
543 $arr[] = rawurlencode($key.'['.$index.']')."=".rawurlencode($value);
546 if (isset($val) && $val !== '') {
547 $arr[] = rawurlencode($key)."=".rawurlencode($val);
549 $arr[] = rawurlencode($key);
554 return implode('&', $arr);
556 return implode('&', $arr);
561 * Shortcut for printing of encoded URL.
565 public function __toString() {
566 return $this->out(true);
572 * If you use the returned URL in HTML code, you want the escaped ampersands. If you use
573 * the returned URL in HTTP headers, you want $escaped=false.
575 * @param bool $escaped Use & as params separator instead of plain &
576 * @param array $overrideparams params to add to the output url, these override existing ones with the same name.
577 * @return string Resulting URL
579 public function out($escaped = true, array $overrideparams = null) {
580 if (!is_bool($escaped)) {
581 debugging('Escape parameter must be of type boolean, '.gettype($escaped).' given instead.');
584 $uri = $this->out_omit_querystring().$this->slashargument
;
586 $querystring = $this->get_query_string($escaped, $overrideparams);
587 if ($querystring !== '') {
588 $uri .= '?' . $querystring;
590 if (!is_null($this->anchor
)) {
591 $uri .= '#'.$this->anchor
;
598 * Returns url without parameters, everything before '?'.
600 * @param bool $includeanchor if {@link self::anchor} is defined, should it be returned?
603 public function out_omit_querystring($includeanchor = false) {
605 $uri = $this->scheme ?
$this->scheme
.':'.((strtolower($this->scheme
) == 'mailto') ?
'':'//'): '';
606 $uri .= $this->user ?
$this->user
.($this->pass?
':'.$this->pass
:'').'@':'';
607 $uri .= $this->host ?
$this->host
: '';
608 $uri .= $this->port ?
':'.$this->port
: '';
609 $uri .= $this->path ?
$this->path
: '';
610 if ($includeanchor and !is_null($this->anchor
)) {
611 $uri .= '#' . $this->anchor
;
618 * Compares this moodle_url with another.
620 * See documentation of constants for an explanation of the comparison flags.
622 * @param moodle_url $url The moodle_url object to compare
623 * @param int $matchtype The type of comparison (URL_MATCH_BASE, URL_MATCH_PARAMS, URL_MATCH_EXACT)
626 public function compare(moodle_url
$url, $matchtype = URL_MATCH_EXACT
) {
628 $baseself = $this->out_omit_querystring();
629 $baseother = $url->out_omit_querystring();
631 // Append index.php if there is no specific file.
632 if (substr($baseself, -1) == '/') {
633 $baseself .= 'index.php';
635 if (substr($baseother, -1) == '/') {
636 $baseother .= 'index.php';
639 // Compare the two base URLs.
640 if ($baseself != $baseother) {
644 if ($matchtype == URL_MATCH_BASE
) {
648 $urlparams = $url->params();
649 foreach ($this->params() as $param => $value) {
650 if ($param == 'sesskey') {
653 if (!array_key_exists($param, $urlparams) ||
$urlparams[$param] != $value) {
658 if ($matchtype == URL_MATCH_PARAMS
) {
662 foreach ($urlparams as $param => $value) {
663 if ($param == 'sesskey') {
666 if (!array_key_exists($param, $this->params()) ||
$this->param($param) != $value) {
671 if ($url->anchor
!== $this->anchor
) {
679 * Sets the anchor for the URI (the bit after the hash)
681 * @param string $anchor null means remove previous
683 public function set_anchor($anchor) {
684 if (is_null($anchor)) {
686 $this->anchor
= null;
687 } else if ($anchor === '') {
688 // Special case, used as empty link.
690 } else if (preg_match('|[a-zA-Z\_\:][a-zA-Z0-9\_\-\.\:]*|', $anchor)) {
691 // Match the anchor against the NMTOKEN spec.
692 $this->anchor
= $anchor;
694 // Bad luck, no valid anchor found.
695 $this->anchor
= null;
700 * Sets the url slashargument value.
702 * @param string $path usually file path
703 * @param string $parameter name of page parameter if slasharguments not supported
704 * @param bool $supported usually null, then it depends on $CFG->slasharguments, use true or false for other servers
707 public function set_slashargument($path, $parameter = 'file', $supported = null) {
709 if (is_null($supported)) {
710 $supported = $CFG->slasharguments
;
714 $parts = explode('/', $path);
715 $parts = array_map('rawurlencode', $parts);
716 $path = implode('/', $parts);
717 $this->slashargument
= $path;
718 unset($this->params
[$parameter]);
721 $this->slashargument
= '';
722 $this->params
[$parameter] = $path;
726 // Static factory methods.
729 * General moodle file url.
731 * @param string $urlbase the script serving the file
732 * @param string $path
733 * @param bool $forcedownload
736 public static function make_file_url($urlbase, $path, $forcedownload = false) {
738 if ($forcedownload) {
739 $params['forcedownload'] = 1;
742 $url = new moodle_url($urlbase, $params);
743 $url->set_slashargument($path);
748 * Factory method for creation of url pointing to plugin file.
750 * Please note this method can be used only from the plugins to
751 * create urls of own files, it must not be used outside of plugins!
753 * @param int $contextid
754 * @param string $component
755 * @param string $area
757 * @param string $pathname
758 * @param string $filename
759 * @param bool $forcedownload
762 public static function make_pluginfile_url($contextid, $component, $area, $itemid, $pathname, $filename,
763 $forcedownload = false) {
765 $urlbase = "$CFG->httpswwwroot/pluginfile.php";
766 if ($itemid === null) {
767 return self
::make_file_url($urlbase, "/$contextid/$component/$area".$pathname.$filename, $forcedownload);
769 return self
::make_file_url($urlbase, "/$contextid/$component/$area/$itemid".$pathname.$filename, $forcedownload);
774 * Factory method for creation of url pointing to plugin file.
775 * This method is the same that make_pluginfile_url but pointing to the webservice pluginfile.php script.
776 * It should be used only in external functions.
779 * @param int $contextid
780 * @param string $component
781 * @param string $area
783 * @param string $pathname
784 * @param string $filename
785 * @param bool $forcedownload
788 public static function make_webservice_pluginfile_url($contextid, $component, $area, $itemid, $pathname, $filename,
789 $forcedownload = false) {
791 $urlbase = "$CFG->httpswwwroot/webservice/pluginfile.php";
792 if ($itemid === null) {
793 return self
::make_file_url($urlbase, "/$contextid/$component/$area".$pathname.$filename, $forcedownload);
795 return self
::make_file_url($urlbase, "/$contextid/$component/$area/$itemid".$pathname.$filename, $forcedownload);
800 * Factory method for creation of url pointing to draft file of current user.
802 * @param int $draftid draft item id
803 * @param string $pathname
804 * @param string $filename
805 * @param bool $forcedownload
808 public static function make_draftfile_url($draftid, $pathname, $filename, $forcedownload = false) {
810 $urlbase = "$CFG->httpswwwroot/draftfile.php";
811 $context = context_user
::instance($USER->id
);
813 return self
::make_file_url($urlbase, "/$context->id/user/draft/$draftid".$pathname.$filename, $forcedownload);
817 * Factory method for creating of links to legacy course files.
819 * @param int $courseid
820 * @param string $filepath
821 * @param bool $forcedownload
824 public static function make_legacyfile_url($courseid, $filepath, $forcedownload = false) {
827 $urlbase = "$CFG->wwwroot/file.php";
828 return self
::make_file_url($urlbase, '/'.$courseid.'/'.$filepath, $forcedownload);
832 * Returns URL a relative path from $CFG->wwwroot
834 * Can be used for passing around urls with the wwwroot stripped
836 * @param boolean $escaped Use & as params separator instead of plain &
837 * @param array $overrideparams params to add to the output url, these override existing ones with the same name.
838 * @return string Resulting URL
839 * @throws coding_exception if called on a non-local url
841 public function out_as_local_url($escaped = true, array $overrideparams = null) {
844 $url = $this->out($escaped, $overrideparams);
845 $httpswwwroot = str_replace("http://", "https://", $CFG->wwwroot
);
847 // Url should be equal to wwwroot or httpswwwroot. If not then throw exception.
848 if (($url === $CFG->wwwroot
) ||
(strpos($url, $CFG->wwwroot
.'/') === 0)) {
849 $localurl = substr($url, strlen($CFG->wwwroot
));
850 return !empty($localurl) ?
$localurl : '';
851 } else if (($url === $httpswwwroot) ||
(strpos($url, $httpswwwroot.'/') === 0)) {
852 $localurl = substr($url, strlen($httpswwwroot));
853 return !empty($localurl) ?
$localurl : '';
855 throw new coding_exception('out_as_local_url called on a non-local URL');
860 * Returns the 'path' portion of a URL. For example, if the URL is
861 * http://www.example.org:447/my/file/is/here.txt?really=1 then this will
862 * return '/my/file/is/here.txt'.
864 * By default the path includes slash-arguments (for example,
865 * '/myfile.php/extra/arguments') so it is what you would expect from a
866 * URL path. If you don't want this behaviour, you can opt to exclude the
867 * slash arguments. (Be careful: if the $CFG variable slasharguments is
868 * disabled, these URLs will have a different format and you may need to
869 * look at the 'file' parameter too.)
871 * @param bool $includeslashargument If true, includes slash arguments
872 * @return string Path of URL
874 public function get_path($includeslashargument = true) {
875 return $this->path
. ($includeslashargument ?
$this->slashargument
: '');
879 * Returns a given parameter value from the URL.
881 * @param string $name Name of parameter
882 * @return string Value of parameter or null if not set
884 public function get_param($name) {
885 if (array_key_exists($name, $this->params
)) {
886 return $this->params
[$name];
893 * Returns the 'scheme' portion of a URL. For example, if the URL is
894 * http://www.example.org:447/my/file/is/here.txt?really=1 then this will
895 * return 'http' (without the colon).
897 * @return string Scheme of the URL.
899 public function get_scheme() {
900 return $this->scheme
;
904 * Returns the 'host' portion of a URL. For example, if the URL is
905 * http://www.example.org:447/my/file/is/here.txt?really=1 then this will
906 * return 'www.example.org'.
908 * @return string Host of the URL.
910 public function get_host() {
915 * Returns the 'port' portion of a URL. For example, if the URL is
916 * http://www.example.org:447/my/file/is/here.txt?really=1 then this will
919 * @return string Port of the URL.
921 public function get_port() {
927 * Determine if there is data waiting to be processed from a form
929 * Used on most forms in Moodle to check for data
930 * Returns the data as an object, if it's found.
931 * This object can be used in foreach loops without
932 * casting because it's cast to (array) automatically
934 * Checks that submitted POST data exists and returns it as object.
936 * @return mixed false or object
938 function data_submitted() {
943 return (object)fix_utf8($_POST);
948 * Given some normal text this function will break up any
949 * long words to a given size by inserting the given character
951 * It's multibyte savvy and doesn't change anything inside html tags.
953 * @param string $string the string to be modified
954 * @param int $maxsize maximum length of the string to be returned
955 * @param string $cutchar the string used to represent word breaks
958 function break_up_long_words($string, $maxsize=20, $cutchar=' ') {
960 // First of all, save all the tags inside the text to skip them.
962 filter_save_tags($string, $tags);
964 // Process the string adding the cut when necessary.
966 $length = core_text
::strlen($string);
969 for ($i=0; $i<$length; $i++
) {
970 $char = core_text
::substr($string, $i, 1);
971 if ($char == ' ' or $char == "\t" or $char == "\n" or $char == "\r" or $char == "<" or $char == ">") {
975 if ($wordlength > $maxsize) {
983 // Finally load the tags back again.
985 $output = str_replace(array_keys($tags), $tags, $output);
992 * Try and close the current window using JavaScript, either immediately, or after a delay.
994 * Echo's out the resulting XHTML & javascript
996 * @param integer $delay a delay in seconds before closing the window. Default 0.
997 * @param boolean $reloadopener if true, we will see if this window was a pop-up, and try
998 * to reload the parent window before this one closes.
1000 function close_window($delay = 0, $reloadopener = false) {
1001 global $PAGE, $OUTPUT;
1003 if (!$PAGE->headerprinted
) {
1004 $PAGE->set_title(get_string('closewindow'));
1005 echo $OUTPUT->header();
1007 $OUTPUT->container_end_all(false);
1010 if ($reloadopener) {
1011 // Trigger the reload immediately, even if the reload is after a delay.
1012 $PAGE->requires
->js_function_call('window.opener.location.reload', array(true));
1014 $OUTPUT->notification(get_string('windowclosing'), 'notifysuccess');
1016 $PAGE->requires
->js_function_call('close_window', array(new stdClass()), false, $delay);
1018 echo $OUTPUT->footer();
1023 * Returns a string containing a link to the user documentation for the current page.
1025 * Also contains an icon by default. Shown to teachers and admin only.
1027 * @param string $text The text to be displayed for the link
1028 * @return string The link to user documentation for this current page
1030 function page_doc_link($text='') {
1031 global $OUTPUT, $PAGE;
1032 $path = page_get_doc_link_path($PAGE);
1036 return $OUTPUT->doc_link($path, $text);
1040 * Returns the path to use when constructing a link to the docs.
1042 * @since Moodle 2.5.1 2.6
1043 * @param moodle_page $page
1046 function page_get_doc_link_path(moodle_page
$page) {
1049 if (empty($CFG->docroot
) ||
during_initial_install()) {
1052 if (!has_capability('moodle/site:doclinks', $page->context
)) {
1056 $path = $page->docspath
;
1065 * Validates an email to make sure it makes sense.
1067 * @param string $address The email address to validate.
1070 function validate_email($address) {
1072 return (preg_match('#^[-!\#$%&\'*+\\/0-9=?A-Z^_`a-z{|}~]+'.
1073 '(\.[-!\#$%&\'*+\\/0-9=?A-Z^_`a-z{|}~]+)*'.
1075 '[-!\#$%&\'*+\\/0-9=?A-Z^_`a-z{|}~]+\.'.
1076 '[-!\#$%&\'*+\\./0-9=?A-Z^_`a-z{|}~]+$#',
1081 * Extracts file argument either from file parameter or PATH_INFO
1083 * Note: $scriptname parameter is not needed anymore
1085 * @return string file path (only safe characters)
1087 function get_file_argument() {
1090 $relativepath = optional_param('file', false, PARAM_PATH
);
1092 if ($relativepath !== false and $relativepath !== '') {
1093 return $relativepath;
1095 $relativepath = false;
1097 // Then try extract file from the slasharguments.
1098 if (stripos($_SERVER['SERVER_SOFTWARE'], 'iis') !== false) {
1099 // NOTE: IIS tends to convert all file paths to single byte DOS encoding,
1100 // we can not use other methods because they break unicode chars,
1101 // the only ways are to use URL rewriting
1103 // to properly set the 'FastCGIUtf8ServerVariables' registry key.
1104 if (isset($_SERVER['PATH_INFO']) and $_SERVER['PATH_INFO'] !== '') {
1105 // Check that PATH_INFO works == must not contain the script name.
1106 if (strpos($_SERVER['PATH_INFO'], $SCRIPT) === false) {
1107 $relativepath = clean_param(urldecode($_SERVER['PATH_INFO']), PARAM_PATH
);
1111 // All other apache-like servers depend on PATH_INFO.
1112 if (isset($_SERVER['PATH_INFO'])) {
1113 if (isset($_SERVER['SCRIPT_NAME']) and strpos($_SERVER['PATH_INFO'], $_SERVER['SCRIPT_NAME']) === 0) {
1114 $relativepath = substr($_SERVER['PATH_INFO'], strlen($_SERVER['SCRIPT_NAME']));
1116 $relativepath = $_SERVER['PATH_INFO'];
1118 $relativepath = clean_param($relativepath, PARAM_PATH
);
1122 return $relativepath;
1126 * Just returns an array of text formats suitable for a popup menu
1130 function format_text_menu() {
1131 return array (FORMAT_MOODLE
=> get_string('formattext'),
1132 FORMAT_HTML
=> get_string('formathtml'),
1133 FORMAT_PLAIN
=> get_string('formatplain'),
1134 FORMAT_MARKDOWN
=> get_string('formatmarkdown'));
1138 * Given text in a variety of format codings, this function returns the text as safe HTML.
1140 * This function should mainly be used for long strings like posts,
1141 * answers, glossary items etc. For short strings {@link format_string()}.
1145 * trusted : If true the string won't be cleaned. Default false required noclean=true.
1146 * noclean : If true the string won't be cleaned. Default false required trusted=true.
1147 * nocache : If true the strign will not be cached and will be formatted every call. Default false.
1148 * filter : If true the string will be run through applicable filters as well. Default true.
1149 * para : If true then the returned string will be wrapped in div tags. Default true.
1150 * newlines : If true then lines newline breaks will be converted to HTML newline breaks. Default true.
1151 * context : The context that will be used for filtering.
1152 * overflowdiv : If set to true the formatted text will be encased in a div
1153 * with the class no-overflow before being returned. Default false.
1154 * allowid : If true then id attributes will not be removed, even when
1155 * using htmlpurifier. Default false.
1158 * @staticvar array $croncache
1159 * @param string $text The text to be formatted. This is raw text originally from user input.
1160 * @param int $format Identifier of the text format to be used
1161 * [FORMAT_MOODLE, FORMAT_HTML, FORMAT_PLAIN, FORMAT_MARKDOWN]
1162 * @param object/array $options text formatting options
1163 * @param int $courseiddonotuse deprecated course id, use context option instead
1166 function format_text($text, $format = FORMAT_MOODLE
, $options = null, $courseiddonotuse = null) {
1167 global $CFG, $DB, $PAGE;
1169 if ($text === '' ||
is_null($text)) {
1170 // No need to do any filters and cleaning.
1174 // Detach object, we can not modify it.
1175 $options = (array)$options;
1177 if (!isset($options['trusted'])) {
1178 $options['trusted'] = false;
1180 if (!isset($options['noclean'])) {
1181 if ($options['trusted'] and trusttext_active()) {
1182 // No cleaning if text trusted and noclean not specified.
1183 $options['noclean'] = true;
1185 $options['noclean'] = false;
1188 if (!isset($options['nocache'])) {
1189 $options['nocache'] = false;
1191 if (!isset($options['filter'])) {
1192 $options['filter'] = true;
1194 if (!isset($options['para'])) {
1195 $options['para'] = true;
1197 if (!isset($options['newlines'])) {
1198 $options['newlines'] = true;
1200 if (!isset($options['overflowdiv'])) {
1201 $options['overflowdiv'] = false;
1204 // Calculate best context.
1205 if (empty($CFG->version
) or $CFG->version
< 2013051400 or during_initial_install()) {
1206 // Do not filter anything during installation or before upgrade completes.
1209 } else if (isset($options['context'])) { // First by explicit passed context option.
1210 if (is_object($options['context'])) {
1211 $context = $options['context'];
1213 $context = context
::instance_by_id($options['context']);
1215 } else if ($courseiddonotuse) {
1217 $context = context_course
::instance($courseiddonotuse);
1219 // Fallback to $PAGE->context this may be problematic in CLI and other non-standard pages :-(.
1220 $context = $PAGE->context
;
1224 // Either install/upgrade or something has gone really wrong because context does not exist (yet?).
1225 $options['nocache'] = true;
1226 $options['filter'] = false;
1229 if ($options['filter']) {
1230 $filtermanager = filter_manager
::instance();
1231 $filtermanager->setup_page_for_filters($PAGE, $context); // Setup global stuff filters may have.
1233 $filtermanager = new null_filter_manager();
1238 if (!$options['noclean']) {
1239 $text = clean_text($text, FORMAT_HTML
, $options);
1241 $text = $filtermanager->filter_text($text, $context, array(
1242 'originalformat' => FORMAT_HTML
,
1243 'noclean' => $options['noclean']
1248 $text = s($text); // Cleans dangerous JS.
1249 $text = rebuildnolinktag($text);
1250 $text = str_replace(' ', ' ', $text);
1251 $text = nl2br($text);
1255 // This format is deprecated.
1256 $text = '<p>NOTICE: Wiki-like formatting has been removed from Moodle. You should not be seeing
1257 this message as all texts should have been converted to Markdown format instead.
1258 Please post a bug report to http://moodle.org/bugs with information about where you
1259 saw this message.</p>'.s($text);
1262 case FORMAT_MARKDOWN
:
1263 $text = markdown_to_html($text);
1264 if (!$options['noclean']) {
1265 $text = clean_text($text, FORMAT_HTML
, $options);
1267 $text = $filtermanager->filter_text($text, $context, array(
1268 'originalformat' => FORMAT_MARKDOWN
,
1269 'noclean' => $options['noclean']
1273 default: // FORMAT_MOODLE or anything else.
1274 $text = text_to_html($text, null, $options['para'], $options['newlines']);
1275 if (!$options['noclean']) {
1276 $text = clean_text($text, FORMAT_HTML
, $options);
1278 $text = $filtermanager->filter_text($text, $context, array(
1279 'originalformat' => $format,
1280 'noclean' => $options['noclean']
1284 if ($options['filter']) {
1285 // At this point there should not be any draftfile links any more,
1286 // this happens when developers forget to post process the text.
1287 // The only potential problem is that somebody might try to format
1288 // the text before storing into database which would be itself big bug..
1289 $text = str_replace("\"$CFG->httpswwwroot/draftfile.php", "\"$CFG->httpswwwroot/brokenfile.php#", $text);
1291 if ($CFG->debugdeveloper
) {
1292 if (strpos($text, '@@PLUGINFILE@@/') !== false) {
1293 debugging('Before calling format_text(), the content must be processed with file_rewrite_pluginfile_urls()',
1299 if (!empty($options['overflowdiv'])) {
1300 $text = html_writer
::tag('div', $text, array('class' => 'no-overflow'));
1307 * Resets some data related to filters, called during upgrade or when general filter settings change.
1309 * @param bool $phpunitreset true means called from our PHPUnit integration test reset
1312 function reset_text_filters_cache($phpunitreset = false) {
1315 if ($phpunitreset) {
1316 // HTMLPurifier does not change, DB is already reset to defaults,
1317 // nothing to do here, the dataroot was cleared too.
1321 // The purge_all_caches() deals with cachedir and localcachedir purging,
1322 // the individual filter caches are invalidated as necessary elsewhere.
1324 // Update $CFG->filterall cache flag.
1325 if (empty($CFG->stringfilters
)) {
1326 set_config('filterall', 0);
1329 $installedfilters = core_component
::get_plugin_list('filter');
1330 $filters = explode(',', $CFG->stringfilters
);
1331 foreach ($filters as $filter) {
1332 if (isset($installedfilters[$filter])) {
1333 set_config('filterall', 1);
1337 set_config('filterall', 0);
1341 * Given a simple string, this function returns the string
1342 * processed by enabled string filters if $CFG->filterall is enabled
1344 * This function should be used to print short strings (non html) that
1345 * need filter processing e.g. activity titles, post subjects,
1346 * glossary concepts.
1348 * @staticvar bool $strcache
1349 * @param string $string The string to be filtered. Should be plain text, expect
1350 * possibly for multilang tags.
1351 * @param boolean $striplinks To strip any link in the result text. Moodle 1.8 default changed from false to true! MDL-8713
1352 * @param array $options options array/object or courseid
1355 function format_string($string, $striplinks = true, $options = null) {
1358 // We'll use a in-memory cache here to speed up repeated strings.
1359 static $strcache = false;
1361 if (empty($CFG->version
) or $CFG->version
< 2013051400 or during_initial_install()) {
1362 // Do not filter anything during installation or before upgrade completes.
1363 return $string = strip_tags($string);
1366 if ($strcache === false or count($strcache) > 2000) {
1367 // This number might need some tuning to limit memory usage in cron.
1368 $strcache = array();
1371 if (is_numeric($options)) {
1372 // Legacy courseid usage.
1373 $options = array('context' => context_course
::instance($options));
1375 // Detach object, we can not modify it.
1376 $options = (array)$options;
1379 if (empty($options['context'])) {
1380 // Fallback to $PAGE->context this may be problematic in CLI and other non-standard pages :-(.
1381 $options['context'] = $PAGE->context
;
1382 } else if (is_numeric($options['context'])) {
1383 $options['context'] = context
::instance_by_id($options['context']);
1386 if (!$options['context']) {
1387 // We did not find any context? weird.
1388 return $string = strip_tags($string);
1392 $md5 = md5($string.'<+>'.$striplinks.'<+>'.$options['context']->id
.'<+>'.current_language());
1394 // Fetch from cache if possible.
1395 if (isset($strcache[$md5])) {
1396 return $strcache[$md5];
1399 // First replace all ampersands not followed by html entity code
1400 // Regular expression moved to its own method for easier unit testing.
1401 $string = replace_ampersands_not_followed_by_entity($string);
1403 if (!empty($CFG->filterall
)) {
1404 $filtermanager = filter_manager
::instance();
1405 $filtermanager->setup_page_for_filters($PAGE, $options['context']); // Setup global stuff filters may have.
1406 $string = $filtermanager->filter_string($string, $options['context']);
1409 // If the site requires it, strip ALL tags from this string.
1410 if (!empty($CFG->formatstringstriptags
)) {
1411 $string = str_replace(array('<', '>'), array('<', '>'), strip_tags($string));
1414 // Otherwise strip just links if that is required (default).
1416 // Strip links in string.
1417 $string = strip_links($string);
1419 $string = clean_text($string);
1423 $strcache[$md5] = $string;
1429 * Given a string, performs a negative lookahead looking for any ampersand character
1430 * that is not followed by a proper HTML entity. If any is found, it is replaced
1431 * by &. The string is then returned.
1433 * @param string $string
1436 function replace_ampersands_not_followed_by_entity($string) {
1437 return preg_replace("/\&(?![a-zA-Z0-9#]{1,8};)/", "&", $string);
1441 * Given a string, replaces all <a>.*</a> by .* and returns the string.
1443 * @param string $string
1446 function strip_links($string) {
1447 return preg_replace('/(<a\s[^>]+?>)(.+?)(<\/a>)/is', '$2', $string);
1451 * This expression turns links into something nice in a text format. (Russell Jungwirth)
1453 * @param string $string
1456 function wikify_links($string) {
1457 return preg_replace('~(<a [^<]*href=["|\']?([^ "\']*)["|\']?[^>]*>([^<]*)</a>)~i', '$3 [ $2 ]', $string);
1461 * Given text in a variety of format codings, this function returns the text as plain text suitable for plain email.
1463 * @param string $text The text to be formatted. This is raw text originally from user input.
1464 * @param int $format Identifier of the text format to be used
1465 * [FORMAT_MOODLE, FORMAT_HTML, FORMAT_PLAIN, FORMAT_WIKI, FORMAT_MARKDOWN]
1468 function format_text_email($text, $format) {
1477 // There should not be any of these any more!
1478 $text = wikify_links($text);
1479 return core_text
::entities_to_utf8(strip_tags($text), true);
1483 return html_to_text($text);
1487 case FORMAT_MARKDOWN
:
1489 $text = wikify_links($text);
1490 return core_text
::entities_to_utf8(strip_tags($text), true);
1496 * Formats activity intro text
1498 * @param string $module name of module
1499 * @param object $activity instance of activity
1500 * @param int $cmid course module id
1501 * @param bool $filter filter resulting html text
1504 function format_module_intro($module, $activity, $cmid, $filter=true) {
1506 require_once("$CFG->libdir/filelib.php");
1507 $context = context_module
::instance($cmid);
1508 $options = array('noclean' => true, 'para' => false, 'filter' => $filter, 'context' => $context, 'overflowdiv' => true);
1509 $intro = file_rewrite_pluginfile_urls($activity->intro
, 'pluginfile.php', $context->id
, 'mod_'.$module, 'intro', null);
1510 return trim(format_text($intro, $activity->introformat
, $options, null));
1514 * Removes the usage of Moodle files from a text.
1516 * In some rare cases we need to re-use a text that already has embedded links
1517 * to some files hosted within Moodle. But the new area in which we will push
1518 * this content does not support files... therefore we need to remove those files.
1520 * @param string $source The text
1521 * @return string The stripped text
1523 function strip_pluginfile_content($source) {
1524 $baseurl = '@@PLUGINFILE@@';
1525 // Looking for something like < .* "@@pluginfile@@.*" .* >
1526 $pattern = '$<[^<>]+["\']' . $baseurl . '[^"\']*["\'][^<>]*>$';
1527 $stripped = preg_replace($pattern, '', $source);
1528 // Use purify html to rebalence potentially mismatched tags and generally cleanup.
1529 return purify_html($stripped);
1533 * Legacy function, used for cleaning of old forum and glossary text only.
1535 * @param string $text text that may contain legacy TRUSTTEXT marker
1536 * @return string text without legacy TRUSTTEXT marker
1538 function trusttext_strip($text) {
1539 while (true) { // Removing nested TRUSTTEXT.
1541 $text = str_replace('#####TRUSTTEXT#####', '', $text);
1542 if (strcmp($orig, $text) === 0) {
1549 * Must be called before editing of all texts with trust flag. Removes all XSS nasties from texts stored in database if needed.
1551 * @param stdClass $object data object with xxx, xxxformat and xxxtrust fields
1552 * @param string $field name of text field
1553 * @param context $context active context
1554 * @return stdClass updated $object
1556 function trusttext_pre_edit($object, $field, $context) {
1557 $trustfield = $field.'trust';
1558 $formatfield = $field.'format';
1560 if (!$object->$trustfield or !trusttext_trusted($context)) {
1561 $object->$field = clean_text($object->$field, $object->$formatfield);
1568 * Is current user trusted to enter no dangerous XSS in this context?
1570 * Please note the user must be in fact trusted everywhere on this server!!
1572 * @param context $context
1573 * @return bool true if user trusted
1575 function trusttext_trusted($context) {
1576 return (trusttext_active() and has_capability('moodle/site:trustcontent', $context));
1580 * Is trusttext feature active?
1584 function trusttext_active() {
1587 return !empty($CFG->enabletrusttext
);
1591 * Cleans raw text removing nasties.
1593 * Given raw text (eg typed in by a user) this function cleans it up and removes any nasty tags that could mess up
1594 * Moodle pages through XSS attacks.
1596 * The result must be used as a HTML text fragment, this function can not cleanup random
1597 * parts of html tags such as url or src attributes.
1599 * NOTE: the format parameter was deprecated because we can safely clean only HTML.
1601 * @param string $text The text to be cleaned
1602 * @param int|string $format deprecated parameter, should always contain FORMAT_HTML or FORMAT_MOODLE
1603 * @param array $options Array of options; currently only option supported is 'allowid' (if true,
1604 * does not remove id attributes when cleaning)
1605 * @return string The cleaned up text
1607 function clean_text($text, $format = FORMAT_HTML
, $options = array()) {
1608 $text = (string)$text;
1610 if ($format != FORMAT_HTML
and $format != FORMAT_HTML
) {
1611 // TODO: we need to standardise cleanup of text when loading it into editor first.
1612 // debugging('clean_text() is designed to work only with html');.
1615 if ($format == FORMAT_PLAIN
) {
1619 if (is_purify_html_necessary($text)) {
1620 $text = purify_html($text, $options);
1623 // Originally we tried to neutralise some script events here, it was a wrong approach because
1624 // it was trivial to work around that (for example using style based XSS exploits).
1625 // We must not give false sense of security here - all developers MUST understand how to use
1626 // rawurlencode(), htmlentities(), htmlspecialchars(), p(), s(), moodle_url, html_writer and friends!!!
1632 * Is it necessary to use HTMLPurifier?
1635 * @param string $text
1636 * @return bool false means html is safe and valid, true means use HTMLPurifier
1638 function is_purify_html_necessary($text) {
1643 if ($text === (string)((int)$text)) {
1647 if (strpos($text, '&') !== false or preg_match('|<[^pesb/]|', $text)) {
1648 // We need to normalise entities or other tags except p, em, strong and br present.
1652 $altered = htmlspecialchars($text, ENT_NOQUOTES
, 'UTF-8', true);
1653 if ($altered === $text) {
1654 // No < > or other special chars means this must be safe.
1658 // Let's try to convert back some safe html tags.
1659 $altered = preg_replace('|<p>(.*?)</p>|m', '<p>$1</p>', $altered);
1660 if ($altered === $text) {
1663 $altered = preg_replace('|<em>([^<>]+?)</em>|m', '<em>$1</em>', $altered);
1664 if ($altered === $text) {
1667 $altered = preg_replace('|<strong>([^<>]+?)</strong>|m', '<strong>$1</strong>', $altered);
1668 if ($altered === $text) {
1671 $altered = str_replace('<br />', '<br />', $altered);
1672 if ($altered === $text) {
1680 * KSES replacement cleaning function - uses HTML Purifier.
1682 * @param string $text The (X)HTML string to purify
1683 * @param array $options Array of options; currently only option supported is 'allowid' (if set,
1684 * does not remove id attributes when cleaning)
1687 function purify_html($text, $options = array()) {
1690 $text = (string)$text;
1692 static $purifiers = array();
1693 static $caches = array();
1695 // Purifier code can change only during major version upgrade.
1696 $version = empty($CFG->version
) ?
0 : $CFG->version
;
1697 $cachedir = "$CFG->localcachedir/htmlpurifier/$version";
1698 if (!file_exists($cachedir)) {
1699 // Purging of caches may remove the cache dir at any time,
1700 // luckily file_exists() results should be cached for all existing directories.
1701 $purifiers = array();
1703 gc_collect_cycles();
1705 make_localcache_directory('htmlpurifier', false);
1706 check_dir_exists($cachedir);
1709 $allowid = empty($options['allowid']) ?
0 : 1;
1710 $allowobjectembed = empty($CFG->allowobjectembed
) ?
0 : 1;
1712 $type = 'type_'.$allowid.'_'.$allowobjectembed;
1714 if (!array_key_exists($type, $caches)) {
1715 $caches[$type] = cache
::make('core', 'htmlpurifier', array('type' => $type));
1717 $cache = $caches[$type];
1719 // Add revision number and all options to the text key so that it is compatible with local cluster node caches.
1720 $key = "|$version|$allowobjectembed|$allowid|$text";
1721 $filteredtext = $cache->get($key);
1723 if ($filteredtext === true) {
1724 // The filtering did not change the text last time, no need to filter anything again.
1726 } else if ($filteredtext !== false) {
1727 return $filteredtext;
1730 if (empty($purifiers[$type])) {
1731 require_once $CFG->libdir
.'/htmlpurifier/HTMLPurifier.safe-includes.php';
1732 require_once $CFG->libdir
.'/htmlpurifier/locallib.php';
1733 $config = HTMLPurifier_Config
::createDefault();
1735 $config->set('HTML.DefinitionID', 'moodlehtml');
1736 $config->set('HTML.DefinitionRev', 4);
1737 $config->set('Cache.SerializerPath', $cachedir);
1738 $config->set('Cache.SerializerPermissions', $CFG->directorypermissions
);
1739 $config->set('Core.NormalizeNewlines', false);
1740 $config->set('Core.ConvertDocumentToFragment', true);
1741 $config->set('Core.Encoding', 'UTF-8');
1742 $config->set('HTML.Doctype', 'XHTML 1.0 Transitional');
1743 $config->set('URI.AllowedSchemes', array(
1752 'teamspeak' => true,
1757 $config->set('Attr.AllowedFrameTargets', array('_blank'));
1759 if ($allowobjectembed) {
1760 $config->set('HTML.SafeObject', true);
1761 $config->set('Output.FlashCompat', true);
1762 $config->set('HTML.SafeEmbed', true);
1766 $config->set('Attr.EnableID', true);
1769 if ($def = $config->maybeGetRawHTMLDefinition()) {
1770 $def->addElement('nolink', 'Block', 'Flow', array()); // Skip our filters inside.
1771 $def->addElement('tex', 'Inline', 'Inline', array()); // Tex syntax, equivalent to $$xx$$.
1772 $def->addElement('algebra', 'Inline', 'Inline', array()); // Algebra syntax, equivalent to @@xx@@.
1773 $def->addElement('lang', 'Block', 'Flow', array(), array('lang'=>'CDATA')); // Original multilang style - only our hacked lang attribute.
1774 $def->addAttribute('span', 'xxxlang', 'CDATA'); // Current very problematic multilang.
1776 // Use the built-in Ruby module to add annotation support.
1777 $def->manager
->addModule(new HTMLPurifier_HTMLModule_Ruby());
1779 // Use the custom Noreferrer module.
1780 $def->manager
->addModule(new HTMLPurifier_HTMLModule_Noreferrer());
1783 $purifier = new HTMLPurifier($config);
1784 $purifiers[$type] = $purifier;
1786 $purifier = $purifiers[$type];
1789 $multilang = (strpos($text, 'class="multilang"') !== false);
1791 $filteredtext = $text;
1793 $filteredtextregex = '/<span(\s+lang="([a-zA-Z0-9_-]+)"|\s+class="multilang"){2}\s*>/';
1794 $filteredtext = preg_replace($filteredtextregex, '<span xxxlang="${2}">', $filteredtext);
1796 $filteredtext = (string)$purifier->purify($filteredtext);
1798 $filteredtext = preg_replace('/<span xxxlang="([a-zA-Z0-9_-]+)">/', '<span lang="${1}" class="multilang">', $filteredtext);
1801 if ($text === $filteredtext) {
1802 // No need to store the filtered text, next time we will just return unfiltered text
1803 // because it was not changed by purifying.
1804 $cache->set($key, true);
1806 $cache->set($key, $filteredtext);
1809 return $filteredtext;
1813 * Given plain text, makes it into HTML as nicely as possible.
1815 * May contain HTML tags already.
1817 * Do not abuse this function. It is intended as lower level formatting feature used
1818 * by {@link format_text()} to convert FORMAT_MOODLE to HTML. You are supposed
1819 * to call format_text() in most of cases.
1821 * @param string $text The string to convert.
1822 * @param boolean $smileyignored Was used to determine if smiley characters should convert to smiley images, ignored now
1823 * @param boolean $para If true then the returned string will be wrapped in div tags
1824 * @param boolean $newlines If true then lines newline breaks will be converted to HTML newline breaks.
1827 function text_to_html($text, $smileyignored = null, $para = true, $newlines = true) {
1828 // Remove any whitespace that may be between HTML tags.
1829 $text = preg_replace("~>([[:space:]]+)<~i", "><", $text);
1831 // Remove any returns that precede or follow HTML tags.
1832 $text = preg_replace("~([\n\r])<~i", " <", $text);
1833 $text = preg_replace("~>([\n\r])~i", "> ", $text);
1835 // Make returns into HTML newlines.
1837 $text = nl2br($text);
1840 // Wrap the whole thing in a div if required.
1842 // In 1.9 this was changed from a p => div.
1843 return '<div class="text_to_html">'.$text.'</div>';
1850 * Given Markdown formatted text, make it into XHTML using external function
1852 * @param string $text The markdown formatted text to be converted.
1853 * @return string Converted text
1855 function markdown_to_html($text) {
1858 if ($text === '' or $text === null) {
1862 require_once($CFG->libdir
.'/markdown/MarkdownInterface.php');
1863 require_once($CFG->libdir
.'/markdown/Markdown.php');
1864 require_once($CFG->libdir
.'/markdown/MarkdownExtra.php');
1866 return \Michelf\MarkdownExtra
::defaultTransform($text);
1870 * Given HTML text, make it into plain text using external function
1872 * @param string $html The text to be converted.
1873 * @param integer $width Width to wrap the text at. (optional, default 75 which
1874 * is a good value for email. 0 means do not limit line length.)
1875 * @param boolean $dolinks By default, any links in the HTML are collected, and
1876 * printed as a list at the end of the HTML. If you don't want that, set this
1877 * argument to false.
1878 * @return string plain text equivalent of the HTML.
1880 function html_to_text($html, $width = 75, $dolinks = true) {
1884 require_once($CFG->libdir
.'/html2text.php');
1886 $h2t = new html2text($html, false, $dolinks, $width);
1887 $result = $h2t->get_text();
1893 * This function will highlight search words in a given string
1895 * It cares about HTML and will not ruin links. It's best to use
1896 * this function after performing any conversions to HTML.
1898 * @param string $needle The search string. Syntax like "word1 +word2 -word3" is dealt with correctly.
1899 * @param string $haystack The string (HTML) within which to highlight the search terms.
1900 * @param boolean $matchcase whether to do case-sensitive. Default case-insensitive.
1901 * @param string $prefix the string to put before each search term found.
1902 * @param string $suffix the string to put after each search term found.
1903 * @return string The highlighted HTML.
1905 function highlight($needle, $haystack, $matchcase = false,
1906 $prefix = '<span class="highlight">', $suffix = '</span>') {
1908 // Quick bail-out in trivial cases.
1909 if (empty($needle) or empty($haystack)) {
1913 // Break up the search term into words, discard any -words and build a regexp.
1914 $words = preg_split('/ +/', trim($needle));
1915 foreach ($words as $index => $word) {
1916 if (strpos($word, '-') === 0) {
1917 unset($words[$index]);
1918 } else if (strpos($word, '+') === 0) {
1919 $words[$index] = '\b' . preg_quote(ltrim($word, '+'), '/') . '\b'; // Match only as a complete word.
1921 $words[$index] = preg_quote($word, '/');
1924 $regexp = '/(' . implode('|', $words) . ')/u'; // Char u is to do UTF-8 matching.
1929 // Another chance to bail-out if $search was only -words.
1930 if (empty($words)) {
1934 // Split the string into HTML tags and real content.
1935 $chunks = preg_split('/((?:<[^>]*>)+)/', $haystack, -1, PREG_SPLIT_DELIM_CAPTURE
);
1937 // We have an array of alternating blocks of text, then HTML tags, then text, ...
1938 // Loop through replacing search terms in the text, and leaving the HTML unchanged.
1939 $ishtmlchunk = false;
1941 foreach ($chunks as $chunk) {
1945 $result .= preg_replace($regexp, $prefix . '$1' . $suffix, $chunk);
1947 $ishtmlchunk = !$ishtmlchunk;
1954 * This function will highlight instances of $needle in $haystack
1956 * It's faster that the above function {@link highlight()} and doesn't care about
1959 * @param string $needle The string to search for
1960 * @param string $haystack The string to search for $needle in
1961 * @return string The highlighted HTML
1963 function highlightfast($needle, $haystack) {
1965 if (empty($needle) or empty($haystack)) {
1969 $parts = explode(core_text
::strtolower($needle), core_text
::strtolower($haystack));
1971 if (count($parts) === 1) {
1977 foreach ($parts as $key => $part) {
1978 $parts[$key] = substr($haystack, $pos, strlen($part));
1979 $pos +
= strlen($part);
1981 $parts[$key] .= '<span class="highlight">'.substr($haystack, $pos, strlen($needle)).'</span>';
1982 $pos +
= strlen($needle);
1985 return str_replace('<span class="highlight"></span>', '', join('', $parts));
1989 * Return a string containing 'lang', xml:lang and optionally 'dir' HTML attributes.
1991 * Internationalisation, for print_header and backup/restorelib.
1993 * @param bool $dir Default false
1994 * @return string Attributes
1996 function get_html_lang($dir = false) {
1999 if (right_to_left()) {
2000 $direction = ' dir="rtl"';
2002 $direction = ' dir="ltr"';
2005 // Accessibility: added the 'lang' attribute to $direction, used in theme <html> tag.
2006 $language = str_replace('_', '-', current_language());
2007 @header
('Content-Language: '.$language);
2008 return ($direction.' lang="'.$language.'" xml:lang="'.$language.'"');
2012 // STANDARD WEB PAGE PARTS.
2015 * Send the HTTP headers that Moodle requires.
2017 * There is a backwards compatibility hack for legacy code
2018 * that needs to add custom IE compatibility directive.
2022 * if (!isset($CFG->additionalhtmlhead)) {
2023 * $CFG->additionalhtmlhead = '';
2025 * $CFG->additionalhtmlhead .= '<meta http-equiv="X-UA-Compatible" content="IE=8" />';
2026 * header('X-UA-Compatible: IE=8');
2027 * echo $OUTPUT->header();
2030 * Please note the $CFG->additionalhtmlhead alone might not work,
2031 * you should send the IE compatibility header() too.
2033 * @param string $contenttype
2034 * @param bool $cacheable Can this page be cached on back?
2035 * @return void, sends HTTP headers
2037 function send_headers($contenttype, $cacheable = true) {
2040 @header
('Content-Type: ' . $contenttype);
2041 @header
('Content-Script-Type: text/javascript');
2042 @header
('Content-Style-Type: text/css');
2044 if (empty($CFG->additionalhtmlhead
) or stripos($CFG->additionalhtmlhead
, 'X-UA-Compatible') === false) {
2045 @header
('X-UA-Compatible: IE=edge');
2049 // Allow caching on "back" (but not on normal clicks).
2050 @header
('Cache-Control: private, pre-check=0, post-check=0, max-age=0, no-transform');
2051 @header
('Pragma: no-cache');
2052 @header
('Expires: ');
2054 // Do everything we can to always prevent clients and proxies caching.
2055 @header
('Cache-Control: no-store, no-cache, must-revalidate');
2056 @header
('Cache-Control: post-check=0, pre-check=0, no-transform', false);
2057 @header
('Pragma: no-cache');
2058 @header
('Expires: Mon, 20 Aug 1969 09:23:00 GMT');
2059 @header
('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
2061 @header
('Accept-Ranges: none');
2063 if (empty($CFG->allowframembedding
)) {
2064 @header
('X-Frame-Options: sameorigin');
2069 * Return the right arrow with text ('next'), and optionally embedded in a link.
2071 * @param string $text HTML/plain text label (set to blank only for breadcrumb separator cases).
2072 * @param string $url An optional link to use in a surrounding HTML anchor.
2073 * @param bool $accesshide True if text should be hidden (for screen readers only).
2074 * @param string $addclass Additional class names for the link, or the arrow character.
2075 * @return string HTML string.
2077 function link_arrow_right($text, $url='', $accesshide=false, $addclass='') {
2078 global $OUTPUT; // TODO: move to output renderer.
2079 $arrowclass = 'arrow ';
2081 $arrowclass .= $addclass;
2083 $arrow = '<span class="'.$arrowclass.'">'.$OUTPUT->rarrow().'</span>';
2086 $htmltext = '<span class="arrow_text">'.$text.'</span> ';
2088 $htmltext = get_accesshide($htmltext);
2092 $class = 'arrow_link';
2094 $class .= ' '.$addclass;
2096 return '<a class="'.$class.'" href="'.$url.'" title="'.preg_replace('/<.*?>/', '', $text).'">'.$htmltext.$arrow.'</a>';
2098 return $htmltext.$arrow;
2102 * Return the left arrow with text ('previous'), and optionally embedded in a link.
2104 * @param string $text HTML/plain text label (set to blank only for breadcrumb separator cases).
2105 * @param string $url An optional link to use in a surrounding HTML anchor.
2106 * @param bool $accesshide True if text should be hidden (for screen readers only).
2107 * @param string $addclass Additional class names for the link, or the arrow character.
2108 * @return string HTML string.
2110 function link_arrow_left($text, $url='', $accesshide=false, $addclass='') {
2111 global $OUTPUT; // TODO: move to utput renderer.
2112 $arrowclass = 'arrow ';
2114 $arrowclass .= $addclass;
2116 $arrow = '<span class="'.$arrowclass.'">'.$OUTPUT->larrow().'</span>';
2119 $htmltext = ' <span class="arrow_text">'.$text.'</span>';
2121 $htmltext = get_accesshide($htmltext);
2125 $class = 'arrow_link';
2127 $class .= ' '.$addclass;
2129 return '<a class="'.$class.'" href="'.$url.'" title="'.preg_replace('/<.*?>/', '', $text).'">'.$arrow.$htmltext.'</a>';
2131 return $arrow.$htmltext;
2135 * Return a HTML element with the class "accesshide", for accessibility.
2137 * Please use cautiously - where possible, text should be visible!
2139 * @param string $text Plain text.
2140 * @param string $elem Lowercase element name, default "span".
2141 * @param string $class Additional classes for the element.
2142 * @param string $attrs Additional attributes string in the form, "name='value' name2='value2'"
2143 * @return string HTML string.
2145 function get_accesshide($text, $elem='span', $class='', $attrs='') {
2146 return "<$elem class=\"accesshide $class\" $attrs>$text</$elem>";
2150 * Return the breadcrumb trail navigation separator.
2152 * @return string HTML string.
2154 function get_separator() {
2155 // Accessibility: the 'hidden' slash is preferred for screen readers.
2156 return ' '.link_arrow_right($text='/', $url='', $accesshide=true, 'sep').' ';
2160 * Print (or return) a collapsible region, that has a caption that can be clicked to expand or collapse the region.
2162 * If JavaScript is off, then the region will always be expanded.
2164 * @param string $contents the contents of the box.
2165 * @param string $classes class names added to the div that is output.
2166 * @param string $id id added to the div that is output. Must not be blank.
2167 * @param string $caption text displayed at the top. Clicking on this will cause the region to expand or contract.
2168 * @param string $userpref the name of the user preference that stores the user's preferred default state.
2169 * (May be blank if you do not wish the state to be persisted.
2170 * @param boolean $default Initial collapsed state to use if the user_preference it not set.
2171 * @param boolean $return if true, return the HTML as a string, rather than printing it.
2172 * @return string|void If $return is false, returns nothing, otherwise returns a string of HTML.
2174 function print_collapsible_region($contents, $classes, $id, $caption, $userpref = '', $default = false, $return = false) {
2175 $output = print_collapsible_region_start($classes, $id, $caption, $userpref, $default, true);
2176 $output .= $contents;
2177 $output .= print_collapsible_region_end(true);
2187 * Print (or return) the start of a collapsible region
2189 * The collapsibleregion has a caption that can be clicked to expand or collapse the region. If JavaScript is off, then the region
2190 * will always be expanded.
2192 * @param string $classes class names added to the div that is output.
2193 * @param string $id id added to the div that is output. Must not be blank.
2194 * @param string $caption text displayed at the top. Clicking on this will cause the region to expand or contract.
2195 * @param string $userpref the name of the user preference that stores the user's preferred default state.
2196 * (May be blank if you do not wish the state to be persisted.
2197 * @param boolean $default Initial collapsed state to use if the user_preference it not set.
2198 * @param boolean $return if true, return the HTML as a string, rather than printing it.
2199 * @return string|void if $return is false, returns nothing, otherwise returns a string of HTML.
2201 function print_collapsible_region_start($classes, $id, $caption, $userpref = '', $default = false, $return = false) {
2204 // Work out the initial state.
2205 if (!empty($userpref) and is_string($userpref)) {
2206 user_preference_allow_ajax_update($userpref, PARAM_BOOL
);
2207 $collapsed = get_user_preferences($userpref, $default);
2209 $collapsed = $default;
2214 $classes .= ' collapsed';
2218 $output .= '<div id="' . $id . '" class="collapsibleregion ' . $classes . '">';
2219 $output .= '<div id="' . $id . '_sizer">';
2220 $output .= '<div id="' . $id . '_caption" class="collapsibleregioncaption">';
2221 $output .= $caption . ' ';
2222 $output .= '</div><div id="' . $id . '_inner" class="collapsibleregioninner">';
2223 $PAGE->requires
->js_init_call('M.util.init_collapsible_region', array($id, $userpref, get_string('clicktohideshow')));
2233 * Close a region started with print_collapsible_region_start.
2235 * @param boolean $return if true, return the HTML as a string, rather than printing it.
2236 * @return string|void if $return is false, returns nothing, otherwise returns a string of HTML.
2238 function print_collapsible_region_end($return = false) {
2239 $output = '</div></div></div>';
2249 * Print a specified group's avatar.
2251 * @param array|stdClass $group A single {@link group} object OR array of groups.
2252 * @param int $courseid The course ID.
2253 * @param boolean $large Default small picture, or large.
2254 * @param boolean $return If false print picture, otherwise return the output as string
2255 * @param boolean $link Enclose image in a link to view specified course?
2256 * @return string|void Depending on the setting of $return
2258 function print_group_picture($group, $courseid, $large=false, $return=false, $link=true) {
2261 if (is_array($group)) {
2263 foreach ($group as $g) {
2264 $output .= print_group_picture($g, $courseid, $large, true, $link);
2274 $context = context_course
::instance($courseid);
2276 // If there is no picture, do nothing.
2277 if (!$group->picture
) {
2281 // If picture is hidden, only show to those with course:managegroups.
2282 if ($group->hidepicture
and !has_capability('moodle/course:managegroups', $context)) {
2286 if ($link or has_capability('moodle/site:accessallgroups', $context)) {
2287 $output = '<a href="'. $CFG->wwwroot
.'/user/index.php?id='. $courseid .'&group='. $group->id
.'">';
2297 $grouppictureurl = moodle_url
::make_pluginfile_url($context->id
, 'group', 'icon', $group->id
, '/', $file);
2298 $grouppictureurl->param('rev', $group->picture
);
2299 $output .= '<img class="grouppicture" src="'.$grouppictureurl.'"'.
2300 ' alt="'.s(get_string('group').' '.$group->name
).'" title="'.s($group->name
).'"/>';
2302 if ($link or has_capability('moodle/site:accessallgroups', $context)) {
2315 * Display a recent activity note
2317 * @staticvar string $strftimerecent
2318 * @param int $time A timestamp int.
2319 * @param stdClass $user A user object from the database.
2320 * @param string $text Text for display for the note
2321 * @param string $link The link to wrap around the text
2322 * @param bool $return If set to true the HTML is returned rather than echo'd
2323 * @param string $viewfullnames
2324 * @return string If $retrun was true returns HTML for a recent activity notice.
2326 function print_recent_activity_note($time, $user, $text, $link, $return=false, $viewfullnames=null) {
2327 static $strftimerecent = null;
2330 if (is_null($viewfullnames)) {
2331 $context = context_system
::instance();
2332 $viewfullnames = has_capability('moodle/site:viewfullnames', $context);
2335 if (is_null($strftimerecent)) {
2336 $strftimerecent = get_string('strftimerecent');
2339 $output .= '<div class="head">';
2340 $output .= '<div class="date">'.userdate($time, $strftimerecent).'</div>';
2341 $output .= '<div class="name">'.fullname($user, $viewfullnames).'</div>';
2342 $output .= '</div>';
2343 $output .= '<div class="info"><a href="'.$link.'">'.format_string($text, true).'</a></div>';
2353 * Returns a popup menu with course activity modules
2355 * Given a course this function returns a small popup menu with all the course activity modules in it, as a navigation menu
2356 * outputs a simple list structure in XHTML.
2357 * The data is taken from the serialised array stored in the course record.
2359 * @param course $course A {@link $COURSE} object.
2360 * @param array $sections
2361 * @param course_modinfo $modinfo
2362 * @param string $strsection
2363 * @param string $strjumpto
2365 * @param string $cmid
2366 * @return string The HTML block
2368 function navmenulist($course, $sections, $modinfo, $strsection, $strjumpto, $width=50, $cmid=0) {
2370 global $CFG, $OUTPUT;
2374 $doneheading = false;
2376 $courseformatoptions = course_get_format($course)->get_format_options();
2377 $coursecontext = context_course
::instance($course->id
);
2379 $menu[] = '<ul class="navmenulist"><li class="jumpto section"><span>'.$strjumpto.'</span><ul>';
2380 foreach ($modinfo->cms
as $mod) {
2381 if (!$mod->has_view()) {
2382 // Don't show modules which you can't link to!
2386 // For course formats using 'numsections' do not show extra sections.
2387 if (isset($courseformatoptions['numsections']) && $mod->sectionnum
> $courseformatoptions['numsections']) {
2391 if (!$mod->uservisible
) { // Do not icnlude empty sections at all.
2395 if ($mod->sectionnum
>= 0 and $section != $mod->sectionnum
) {
2396 $thissection = $sections[$mod->sectionnum
];
2398 if ($thissection->visible
or
2399 (isset($courseformatoptions['hiddensections']) and !$courseformatoptions['hiddensections']) or
2400 has_capability('moodle/course:viewhiddensections', $coursecontext)) {
2401 $thissection->summary
= strip_tags(format_string($thissection->summary
, true));
2402 if (!$doneheading) {
2403 $menu[] = '</ul></li>';
2405 if ($course->format
== 'weeks' or empty($thissection->summary
)) {
2406 $item = $strsection ." ". $mod->sectionnum
;
2408 if (core_text
::strlen($thissection->summary
) < ($width-3)) {
2409 $item = $thissection->summary
;
2411 $item = core_text
::substr($thissection->summary
, 0, $width).'...';
2414 $menu[] = '<li class="section"><span>'.$item.'</span>';
2416 $doneheading = true;
2418 $section = $mod->sectionnum
;
2420 // No activities from this hidden section shown.
2425 $url = $mod->modname
.'/view.php?id='. $mod->id
;
2426 $mod->name
= strip_tags(format_string($mod->name
,true));
2427 if (core_text
::strlen($mod->name
) > ($width+
5)) {
2428 $mod->name
= core_text
::substr($mod->name
, 0, $width).'...';
2430 if (!$mod->visible
) {
2431 $mod->name
= '('.$mod->name
.')';
2433 $class = 'activity '.$mod->modname
;
2434 $class .= ($cmid == $mod->id
) ?
' selected' : '';
2435 $menu[] = '<li class="'.$class.'">'.
2436 '<img src="'.$OUTPUT->pix_url('icon', $mod->modname
) . '" alt="" />'.
2437 '<a href="'.$CFG->wwwroot
.'/mod/'.$url.'">'.$mod->name
.'</a></li>';
2441 $menu[] = '</ul></li>';
2443 $menu[] = '</ul></li></ul>';
2445 return implode("\n", $menu);
2449 * Prints a grade menu (as part of an existing form) with help showing all possible numerical grades and scales.
2451 * @todo Finish documenting this function
2452 * @todo Deprecate: this is only used in a few contrib modules
2454 * @param int $courseid The course ID
2455 * @param string $name
2456 * @param string $current
2457 * @param boolean $includenograde Include those with no grades
2458 * @param boolean $return If set to true returns rather than echo's
2459 * @return string|bool Depending on value of $return
2461 function print_grade_menu($courseid, $name, $current, $includenograde=true, $return=false) {
2465 $strscale = get_string('scale');
2466 $strscales = get_string('scales');
2468 $scales = get_scales_menu($courseid);
2469 foreach ($scales as $i => $scalename) {
2470 $grades[-$i] = $strscale .': '. $scalename;
2472 if ($includenograde) {
2473 $grades[0] = get_string('nograde');
2475 for ($i=100; $i>=1; $i--) {
2478 $output .= html_writer
::select($grades, $name, $current, false);
2480 $helppix = $OUTPUT->pix_url('help');
2481 $linkobject = '<span class="helplink"><img class="iconhelp" alt="'.$strscales.'" src="'.$helppix.'" /></span>';
2482 $link = new moodle_url('/course/scales.php', array('id' => $courseid, 'list' => 1));
2483 $action = new popup_action('click', $link, 'ratingscales', array('height' => 400, 'width' => 500));
2484 $output .= $OUTPUT->action_link($link, $linkobject, $action, array('title' => $strscales));
2494 * Print an error to STDOUT and exit with a non-zero code. For commandline scripts.
2496 * Default errorcode is 1.
2498 * Very useful for perl-like error-handling:
2499 * do_somethting() or mdie("Something went wrong");
2501 * @param string $msg Error message
2502 * @param integer $errorcode Error code to emit
2504 function mdie($msg='', $errorcode=1) {
2505 trigger_error($msg);
2510 * Print a message and exit.
2512 * @param string $message The message to print in the notice
2513 * @param string $link The link to use for the continue button
2514 * @param object $course A course object. Unused.
2515 * @return void This function simply exits
2517 function notice ($message, $link='', $course=null) {
2518 global $PAGE, $OUTPUT;
2520 $message = clean_text($message); // In case nasties are in here.
2523 echo("!!$message!!\n");
2524 exit(1); // No success.
2527 if (!$PAGE->headerprinted
) {
2528 // Header not yet printed.
2529 $PAGE->set_title(get_string('notice'));
2530 echo $OUTPUT->header();
2532 echo $OUTPUT->container_end_all(false);
2535 echo $OUTPUT->box($message, 'generalbox', 'notice');
2536 echo $OUTPUT->continue_button($link);
2538 echo $OUTPUT->footer();
2539 exit(1); // General error code.
2543 * Redirects the user to another page, after printing a notice.
2545 * This function calls the OUTPUT redirect method, echo's the output and then dies to ensure nothing else happens.
2547 * <strong>Good practice:</strong> You should call this method before starting page
2548 * output by using any of the OUTPUT methods.
2550 * @param moodle_url|string $url A moodle_url to redirect to. Strings are not to be trusted!
2551 * @param string $message The message to display to the user
2552 * @param int $delay The delay before redirecting
2553 * @throws moodle_exception
2555 function redirect($url, $message='', $delay=-1) {
2556 global $OUTPUT, $PAGE, $CFG;
2558 if (CLI_SCRIPT
or AJAX_SCRIPT
) {
2559 // This is wrong - developers should not use redirect in these scripts but it should not be very likely.
2560 throw new moodle_exception('redirecterrordetected', 'error');
2563 // Prevent debug errors - make sure context is properly initialised.
2565 $PAGE->set_context(null);
2566 $PAGE->set_pagelayout('redirect'); // No header and footer needed.
2567 $PAGE->set_title(get_string('pageshouldredirect', 'moodle'));
2570 if ($url instanceof moodle_url
) {
2571 $url = $url->out(false);
2574 $debugdisableredirect = false;
2576 if (defined('DEBUGGING_PRINTED')) {
2577 // Some debugging already printed, no need to look more.
2578 $debugdisableredirect = true;
2582 if (core_useragent
::is_msword()) {
2583 // Clicking a URL from MS Word sends a request to the server without cookies. If that
2584 // causes a redirect Word will open a browser pointing the new URL. If not, the URL that
2585 // was clicked is opened. Because the request from Word is without cookies, it almost
2586 // always results in a redirect to the login page, even if the user is logged in in their
2587 // browser. This is not what we want, so prevent the redirect for requests from Word.
2588 $debugdisableredirect = true;
2592 if (empty($CFG->debugdisplay
) or empty($CFG->debug
)) {
2593 // No errors should be displayed.
2597 if (!function_exists('error_get_last') or !$lasterror = error_get_last()) {
2601 if (!($lasterror['type'] & $CFG->debug
)) {
2602 // Last error not interesting.
2606 // Watch out here, @hidden() errors are returned from error_get_last() too.
2607 if (headers_sent()) {
2608 // We already started printing something - that means errors likely printed.
2609 $debugdisableredirect = true;
2613 if (ob_get_level() and ob_get_contents()) {
2614 // There is something waiting to be printed, hopefully it is the errors,
2615 // but it might be some error hidden by @ too - such as the timezone mess from setup.php.
2616 $debugdisableredirect = true;
2621 // Technically, HTTP/1.1 requires Location: header to contain the absolute path.
2622 // (In practice browsers accept relative paths - but still, might as well do it properly.)
2623 // This code turns relative into absolute.
2624 if (!preg_match('|^[a-z]+:|i', $url)) {
2625 // Get host name http://www.wherever.com.
2626 $hostpart = preg_replace('|^(.*?[^:/])/.*$|', '$1', $CFG->wwwroot
);
2627 if (preg_match('|^/|', $url)) {
2628 // URLs beginning with / are relative to web server root so we just add them in.
2629 $url = $hostpart.$url;
2631 // URLs not beginning with / are relative to path of current script, so add that on.
2632 $url = $hostpart.preg_replace('|\?.*$|', '', me()).'/../'.$url;
2636 $newurl = preg_replace('|/(?!\.\.)[^/]*/\.\./|', '/', $url);
2637 if ($newurl == $url) {
2644 // Sanitise url - we can not rely on moodle_url or our URL cleaning
2645 // because they do not support all valid external URLs.
2646 $url = preg_replace('/[\x00-\x1F\x7F]/', '', $url);
2647 $url = str_replace('"', '%22', $url);
2648 $encodedurl = preg_replace("/\&(?![a-zA-Z0-9#]{1,8};)/", "&", $url);
2649 $encodedurl = preg_replace('/^.*href="([^"]*)".*$/', "\\1", clean_text('<a href="'.$encodedurl.'" />', FORMAT_HTML
));
2650 $url = str_replace('&', '&', $encodedurl);
2652 if (!empty($message)) {
2653 if ($delay === -1 ||
!is_numeric($delay)) {
2656 $message = clean_text($message);
2658 $message = get_string('pageshouldredirect');
2662 // Make sure the session is closed properly, this prevents problems in IIS
2663 // and also some potential PHP shutdown issues.
2664 \core\session\manager
::write_close();
2666 if ($delay == 0 && !$debugdisableredirect && !headers_sent()) {
2667 // 302 might not work for POST requests, 303 is ignored by obsolete clients.
2668 @header
($_SERVER['SERVER_PROTOCOL'] . ' 303 See Other');
2669 @header
('Location: '.$url);
2670 echo bootstrap_renderer
::plain_redirect_message($encodedurl);
2674 // Include a redirect message, even with a HTTP redirect, because that is recommended practice.
2676 $CFG->docroot
= false; // To prevent the link to moodle docs from being displayed on redirect page.
2677 echo $OUTPUT->redirect_message($encodedurl, $message, $delay, $debugdisableredirect);
2680 echo bootstrap_renderer
::early_redirect_message($encodedurl, $message, $delay);
2686 * Given an email address, this function will return an obfuscated version of it.
2688 * @param string $email The email address to obfuscate
2689 * @return string The obfuscated email address
2691 function obfuscate_email($email) {
2693 $length = strlen($email);
2695 while ($i < $length) {
2696 if (rand(0, 2) && $email{$i}!='@') { // MDL-20619 some browsers have problems unobfuscating @.
2697 $obfuscated.='%'.dechex(ord($email{$i}));
2699 $obfuscated.=$email{$i};
2707 * This function takes some text and replaces about half of the characters
2708 * with HTML entity equivalents. Return string is obviously longer.
2710 * @param string $plaintext The text to be obfuscated
2711 * @return string The obfuscated text
2713 function obfuscate_text($plaintext) {
2715 $length = core_text
::strlen($plaintext);
2717 $prevobfuscated = false;
2718 while ($i < $length) {
2719 $char = core_text
::substr($plaintext, $i, 1);
2720 $ord = core_text
::utf8ord($char);
2721 $numerical = ($ord >= ord('0')) && ($ord <= ord('9'));
2722 if ($prevobfuscated and $numerical ) {
2723 $obfuscated.='&#'.$ord.';';
2724 } else if (rand(0, 2)) {
2725 $obfuscated.='&#'.$ord.';';
2726 $prevobfuscated = true;
2729 $prevobfuscated = false;
2737 * This function uses the {@link obfuscate_email()} and {@link obfuscate_text()}
2738 * to generate a fully obfuscated email link, ready to use.
2740 * @param string $email The email address to display
2741 * @param string $label The text to displayed as hyperlink to $email
2742 * @param boolean $dimmed If true then use css class 'dimmed' for hyperlink
2743 * @param string $subject The subject of the email in the mailto link
2744 * @param string $body The content of the email in the mailto link
2745 * @return string The obfuscated mailto link
2747 function obfuscate_mailto($email, $label='', $dimmed=false, $subject = '', $body = '') {
2749 if (empty($label)) {
2753 $label = obfuscate_text($label);
2754 $email = obfuscate_email($email);
2755 $mailto = obfuscate_text('mailto');
2756 $url = new moodle_url("mailto:$email");
2759 if (!empty($subject)) {
2760 $url->param('subject', format_string($subject));
2762 if (!empty($body)) {
2763 $url->param('body', format_string($body));
2766 // Use the obfuscated mailto.
2767 $url = preg_replace('/^mailto/', $mailto, $url->out());
2770 $attrs['title'] = get_string('emaildisable');
2771 $attrs['class'] = 'dimmed';
2774 return html_writer
::link($url, $label, $attrs);
2778 * This function is used to rebuild the <nolink> tag because some formats (PLAIN and WIKI)
2779 * will transform it to html entities
2781 * @param string $text Text to search for nolink tag in
2784 function rebuildnolinktag($text) {
2786 $text = preg_replace('/<(\/*nolink)>/i', '<$1>', $text);
2792 * Prints a maintenance message from $CFG->maintenance_message or default if empty.
2794 function print_maintenance_message() {
2795 global $CFG, $SITE, $PAGE, $OUTPUT;
2797 $PAGE->set_pagetype('maintenance-message');
2798 $PAGE->set_pagelayout('maintenance');
2799 $PAGE->set_title(strip_tags($SITE->fullname
));
2800 $PAGE->set_heading($SITE->fullname
);
2801 echo $OUTPUT->header();
2802 echo $OUTPUT->heading(get_string('sitemaintenance', 'admin'));
2803 if (isset($CFG->maintenance_message
) and !html_is_blank($CFG->maintenance_message
)) {
2804 echo $OUTPUT->box_start('maintenance_message generalbox boxwidthwide boxaligncenter');
2805 echo $CFG->maintenance_message
;
2806 echo $OUTPUT->box_end();
2808 echo $OUTPUT->footer();
2813 * Returns a string containing a nested list, suitable for formatting into tabs with CSS.
2815 * It is not recommended to use this function in Moodle 2.5 but it is left for backward
2818 * Example how to print a single line tabs:
2820 * new tabobject(...),
2821 * new tabobject(...)
2823 * echo $OUTPUT->tabtree($rows, $selectedid);
2825 * Multiple row tabs may not look good on some devices but if you want to use them
2826 * you can specify ->subtree for the active tabobject.
2828 * @param array $tabrows An array of rows where each row is an array of tab objects
2829 * @param string $selected The id of the selected tab (whatever row it's on)
2830 * @param array $inactive An array of ids of inactive tabs that are not selectable.
2831 * @param array $activated An array of ids of other tabs that are currently activated
2832 * @param bool $return If true output is returned rather then echo'd
2833 * @return string HTML output if $return was set to true.
2835 function print_tabs($tabrows, $selected = null, $inactive = null, $activated = null, $return = false) {
2838 $tabrows = array_reverse($tabrows);
2840 foreach ($tabrows as $row) {
2843 foreach ($row as $tab) {
2844 $tab->inactive
= is_array($inactive) && in_array((string)$tab->id
, $inactive);
2845 $tab->activated
= is_array($activated) && in_array((string)$tab->id
, $activated);
2846 $tab->selected
= (string)$tab->id
== $selected;
2848 if ($tab->activated ||
$tab->selected
) {
2849 $tab->subtree
= $subtree;
2855 $output = $OUTPUT->tabtree($subtree);
2860 return !empty($output);
2865 * Alter debugging level for the current request,
2866 * the change is not saved in database.
2868 * @param int $level one of the DEBUG_* constants
2869 * @param bool $debugdisplay
2871 function set_debugging($level, $debugdisplay = null) {
2874 $CFG->debug
= (int)$level;
2875 $CFG->debugdeveloper
= (($CFG->debug
& DEBUG_DEVELOPER
) === DEBUG_DEVELOPER
);
2877 if ($debugdisplay !== null) {
2878 $CFG->debugdisplay
= (bool)$debugdisplay;
2883 * Standard Debugging Function
2885 * Returns true if the current site debugging settings are equal or above specified level.
2886 * If passed a parameter it will emit a debugging notice similar to trigger_error(). The
2887 * routing of notices is controlled by $CFG->debugdisplay
2890 * 1) debugging('a normal debug notice');
2891 * 2) debugging('something really picky', DEBUG_ALL);
2892 * 3) debugging('annoying debug message only for developers', DEBUG_DEVELOPER);
2893 * 4) if (debugging()) { perform extra debugging operations (do not use print or echo) }
2895 * In code blocks controlled by debugging() (such as example 4)
2896 * any output should be routed via debugging() itself, or the lower-level
2897 * trigger_error() or error_log(). Using echo or print will break XHTML
2898 * JS and HTTP headers.
2900 * It is also possible to define NO_DEBUG_DISPLAY which redirects the message to error_log.
2902 * @param string $message a message to print
2903 * @param int $level the level at which this debugging statement should show
2904 * @param array $backtrace use different backtrace
2907 function debugging($message = '', $level = DEBUG_NORMAL
, $backtrace = null) {
2910 $forcedebug = false;
2911 if (!empty($CFG->debugusers
) && $USER) {
2912 $debugusers = explode(',', $CFG->debugusers
);
2913 $forcedebug = in_array($USER->id
, $debugusers);
2916 if (!$forcedebug and (empty($CFG->debug
) ||
($CFG->debug
!= -1 and $CFG->debug
< $level))) {
2920 if (!isset($CFG->debugdisplay
)) {
2921 $CFG->debugdisplay
= ini_get_bool('display_errors');
2926 $backtrace = debug_backtrace();
2928 $from = format_backtrace($backtrace, CLI_SCRIPT || NO_DEBUG_DISPLAY
);
2930 if (phpunit_util
::debugging_triggered($message, $level, $from)) {
2931 // We are inside test, the debug message was logged.
2936 if (NO_DEBUG_DISPLAY
) {
2937 // Script does not want any errors or debugging in output,
2938 // we send the info to error log instead.
2939 error_log('Debugging: ' . $message . ' in '. PHP_EOL
. $from);
2941 } else if ($forcedebug or $CFG->debugdisplay
) {
2942 if (!defined('DEBUGGING_PRINTED')) {
2943 define('DEBUGGING_PRINTED', 1); // Indicates we have printed something.
2946 echo "++ $message ++\n$from";
2948 echo '<div class="notifytiny debuggingmessage" data-rel="debugging">' , $message , $from , '</div>';
2952 trigger_error($message . $from, E_USER_NOTICE
);
2959 * Outputs a HTML comment to the browser.
2961 * This is used for those hard-to-debug pages that use bits from many different files in very confusing ways (e.g. blocks).
2963 * <code>print_location_comment(__FILE__, __LINE__);</code>
2965 * @param string $file
2966 * @param integer $line
2967 * @param boolean $return Whether to return or print the comment
2968 * @return string|void Void unless true given as third parameter
2970 function print_location_comment($file, $line, $return = false) {
2972 return "<!-- $file at line $line -->\n";
2974 echo "<!-- $file at line $line -->\n";
2980 * Returns true if the user is using a right-to-left language.
2982 * @return boolean true if the current language is right-to-left (Hebrew, Arabic etc)
2984 function right_to_left() {
2985 return (get_string('thisdirection', 'langconfig') === 'rtl');
2990 * Returns swapped left<=> right if in RTL environment.
2992 * Part of RTL Moodles support.
2994 * @param string $align align to check
2997 function fix_align_rtl($align) {
2998 if (!right_to_left()) {
3001 if ($align == 'left') {
3004 if ($align == 'right') {
3012 * Returns true if the page is displayed in a popup window.
3014 * Gets the information from the URL parameter inpopup.
3016 * @todo Use a central function to create the popup calls all over Moodle and
3017 * In the moment only works with resources and probably questions.
3021 function is_in_popup() {
3022 $inpopup = optional_param('inpopup', '', PARAM_BOOL
);
3028 * Progress bar class.
3030 * Manages the display of a progress bar.
3032 * To use this class.
3034 * - call create (or use the 3rd param to the constructor)
3035 * - call update or update_full() or update() repeatedly
3037 * @copyright 2008 jamiesensei
3038 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3041 class progress_bar
{
3042 /** @var string html id */
3044 /** @var int total width */
3046 /** @var int last percentage printed */
3047 private $percent = 0;
3048 /** @var int time when last printed */
3049 private $lastupdate = 0;
3050 /** @var int when did we start printing this */
3051 private $time_start = 0;
3056 * Prints JS code if $autostart true.
3058 * @param string $html_id
3060 * @param bool $autostart Default to false
3062 public function __construct($htmlid = '', $width = 500, $autostart = false) {
3063 if (!empty($htmlid)) {
3064 $this->html_id
= $htmlid;
3066 $this->html_id
= 'pbar_'.uniqid();
3069 $this->width
= $width;
3077 * Create a new progress bar, this function will output html.
3079 * @return void Echo's output
3081 public function create() {
3084 $this->time_start
= microtime(true);
3086 return; // Temporary solution for cli scripts.
3089 $PAGE->requires
->string_for_js('secondsleft', 'moodle');
3092 <div class="progressbar_container" style="width: {$this->width}px;" id="{$this->html_id}">
3094 <div class="progress progress-striped active">
3095 <div class="bar" role="progressbar" aria-valuemin="0" aria-valuemax="100" aria-valuenow="0"> </div>
3106 * Update the progress bar
3108 * @param int $percent from 1-100
3109 * @param string $msg
3110 * @return void Echo's output
3111 * @throws coding_exception
3113 private function _update($percent, $msg) {
3114 if (empty($this->time_start
)) {
3115 throw new coding_exception('You must call create() (or use the $autostart ' .
3116 'argument to the constructor) before you try updating the progress bar.');
3120 return; // Temporary solution for cli scripts.
3123 $estimate = $this->estimate($percent);
3125 if ($estimate === null) {
3126 // Always do the first and last updates.
3127 } else if ($estimate == 0) {
3128 // Always do the last updates.
3129 } else if ($this->lastupdate +
20 < time()) {
3130 // We must update otherwise browser would time out.
3131 } else if (round($this->percent
, 2) === round($percent, 2)) {
3132 // No significant change, no need to update anything.
3135 if (is_numeric($estimate)) {
3136 $estimate = get_string('secondsleft', 'moodle', round($estimate, 2));
3139 $this->percent
= round($percent, 2);
3140 $this->lastupdate
= microtime(true);
3142 echo html_writer
::script(js_writer
::function_call('updateProgressBar',
3143 array($this->html_id
, $this->percent
, $msg, $estimate)));
3148 * Estimate how much time it is going to take.
3150 * @param int $pt from 1-100
3151 * @return mixed Null (unknown), or int
3153 private function estimate($pt) {
3154 if ($this->lastupdate
== 0) {
3157 if ($pt < 0.00001) {
3158 return null; // We do not know yet how long it will take.
3160 if ($pt > 99.99999) {
3161 return 0; // Nearly done, right?
3163 $consumed = microtime(true) - $this->time_start
;
3164 if ($consumed < 0.001) {
3168 return (100 - $pt) * ($consumed / $pt);
3172 * Update progress bar according percent
3174 * @param int $percent from 1-100
3175 * @param string $msg the message needed to be shown
3177 public function update_full($percent, $msg) {
3178 $percent = max(min($percent, 100), 0);
3179 $this->_update($percent, $msg);
3183 * Update progress bar according the number of tasks
3185 * @param int $cur current task number
3186 * @param int $total total task number
3187 * @param string $msg message
3189 public function update($cur, $total, $msg) {
3190 $percent = ($cur / $total) * 100;
3191 $this->update_full($percent, $msg);
3195 * Restart the progress bar.
3197 public function restart() {
3199 $this->lastupdate
= 0;
3200 $this->time_start
= 0;
3205 * Progress trace class.
3207 * Use this class from long operations where you want to output occasional information about
3208 * what is going on, but don't know if, or in what format, the output should be.
3210 * @copyright 2009 Tim Hunt
3211 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3214 abstract class progress_trace
{
3216 * Output an progress message in whatever format.
3218 * @param string $message the message to output.
3219 * @param integer $depth indent depth for this message.
3221 abstract public function output($message, $depth = 0);
3224 * Called when the processing is finished.
3226 public function finished() {
3231 * This subclass of progress_trace does not ouput anything.
3233 * @copyright 2009 Tim Hunt
3234 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3237 class null_progress_trace
extends progress_trace
{
3241 * @param string $message
3243 * @return void Does Nothing
3245 public function output($message, $depth = 0) {
3250 * This subclass of progress_trace outputs to plain text.
3252 * @copyright 2009 Tim Hunt
3253 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3256 class text_progress_trace
extends progress_trace
{
3258 * Output the trace message.
3260 * @param string $message
3262 * @return void Output is echo'd
3264 public function output($message, $depth = 0) {
3265 echo str_repeat(' ', $depth), $message, "\n";
3271 * This subclass of progress_trace outputs as HTML.
3273 * @copyright 2009 Tim Hunt
3274 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3277 class html_progress_trace
extends progress_trace
{
3279 * Output the trace message.
3281 * @param string $message
3283 * @return void Output is echo'd
3285 public function output($message, $depth = 0) {
3286 echo '<p>', str_repeat('  ', $depth), htmlspecialchars($message), "</p>\n";
3292 * HTML List Progress Tree
3294 * @copyright 2009 Tim Hunt
3295 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3298 class html_list_progress_trace
extends progress_trace
{
3300 protected $currentdepth = -1;
3305 * @param string $message The message to display
3307 * @return void Output is echoed
3309 public function output($message, $depth = 0) {
3311 while ($this->currentdepth
> $depth) {
3312 echo "</li>\n</ul>\n";
3313 $this->currentdepth
-= 1;
3314 if ($this->currentdepth
== $depth) {
3319 while ($this->currentdepth
< $depth) {
3321 $this->currentdepth +
= 1;
3327 echo htmlspecialchars($message);
3332 * Called when the processing is finished.
3334 public function finished() {
3335 while ($this->currentdepth
>= 0) {
3336 echo "</li>\n</ul>\n";
3337 $this->currentdepth
-= 1;
3343 * This subclass of progress_trace outputs to error log.
3345 * @copyright Petr Skoda {@link http://skodak.org}
3346 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3349 class error_log_progress_trace
extends progress_trace
{
3350 /** @var string log prefix */
3355 * @param string $prefix optional log prefix
3357 public function __construct($prefix = '') {
3358 $this->prefix
= $prefix;
3362 * Output the trace message.
3364 * @param string $message
3366 * @return void Output is sent to error log.
3368 public function output($message, $depth = 0) {
3369 error_log($this->prefix
. str_repeat(' ', $depth) . $message);
3374 * Special type of trace that can be used for catching of output of other traces.
3376 * @copyright Petr Skoda {@link http://skodak.org}
3377 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3380 class progress_trace_buffer
extends progress_trace
{
3381 /** @var progres_trace */
3383 /** @var bool do we pass output out */
3384 protected $passthrough;
3385 /** @var string output buffer */
3391 * @param progress_trace $trace
3392 * @param bool $passthrough true means output and buffer, false means just buffer and no output
3394 public function __construct(progress_trace
$trace, $passthrough = true) {
3395 $this->trace
= $trace;
3396 $this->passthrough
= $passthrough;
3401 * Output the trace message.
3403 * @param string $message the message to output.
3404 * @param int $depth indent depth for this message.
3405 * @return void output stored in buffer
3407 public function output($message, $depth = 0) {
3409 $this->trace
->output($message, $depth);
3410 $this->buffer
.= ob_get_contents();
3411 if ($this->passthrough
) {
3419 * Called when the processing is finished.
3421 public function finished() {
3423 $this->trace
->finished();
3424 $this->buffer
.= ob_get_contents();
3425 if ($this->passthrough
) {
3433 * Reset internal text buffer.
3435 public function reset_buffer() {
3440 * Return internal text buffer.
3441 * @return string buffered plain text
3443 public function get_buffer() {
3444 return $this->buffer
;
3449 * Special type of trace that can be used for redirecting to multiple other traces.
3451 * @copyright Petr Skoda {@link http://skodak.org}
3452 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3455 class combined_progress_trace
extends progress_trace
{
3458 * An array of traces.
3464 * Constructs a new instance.
3466 * @param array $traces multiple traces
3468 public function __construct(array $traces) {
3469 $this->traces
= $traces;
3473 * Output an progress message in whatever format.
3475 * @param string $message the message to output.
3476 * @param integer $depth indent depth for this message.
3478 public function output($message, $depth = 0) {
3479 foreach ($this->traces
as $trace) {
3480 $trace->output($message, $depth);
3485 * Called when the processing is finished.
3487 public function finished() {
3488 foreach ($this->traces
as $trace) {
3495 * Returns a localized sentence in the current language summarizing the current password policy
3497 * @todo this should be handled by a function/method in the language pack library once we have a support for it
3501 function print_password_policy() {
3505 if (!empty($CFG->passwordpolicy
)) {
3506 $messages = array();
3507 $messages[] = get_string('informminpasswordlength', 'auth', $CFG->minpasswordlength
);
3508 if (!empty($CFG->minpassworddigits
)) {
3509 $messages[] = get_string('informminpassworddigits', 'auth', $CFG->minpassworddigits
);
3511 if (!empty($CFG->minpasswordlower
)) {
3512 $messages[] = get_string('informminpasswordlower', 'auth', $CFG->minpasswordlower
);
3514 if (!empty($CFG->minpasswordupper
)) {
3515 $messages[] = get_string('informminpasswordupper', 'auth', $CFG->minpasswordupper
);
3517 if (!empty($CFG->minpasswordnonalphanum
)) {
3518 $messages[] = get_string('informminpasswordnonalphanum', 'auth', $CFG->minpasswordnonalphanum
);
3521 $messages = join(', ', $messages); // This is ugly but we do not have anything better yet...
3522 $message = get_string('informpasswordpolicy', 'auth', $messages);
3528 * Get the value of a help string fully prepared for display in the current language.
3530 * @param string $identifier The identifier of the string to search for.
3531 * @param string $component The module the string is associated with.
3532 * @param boolean $ajax Whether this help is called from an AJAX script.
3533 * This is used to influence text formatting and determines
3534 * which format to output the doclink in.
3535 * @param string|object|array $a An object, string or number that can be used
3536 * within translation strings
3537 * @return Object An object containing:
3538 * - heading: Any heading that there may be for this help string.
3539 * - text: The wiki-formatted help string.
3540 * - doclink: An object containing a link, the linktext, and any additional
3541 * CSS classes to apply to that link. Only present if $ajax = false.
3542 * - completedoclink: A text representation of the doclink. Only present if $ajax = true.
3544 function get_formatted_help_string($identifier, $component, $ajax = false, $a = null) {
3545 global $CFG, $OUTPUT;
3546 $sm = get_string_manager();
3548 // Do not rebuild caches here!
3549 // Devs need to learn to purge all caches after any change or disable $CFG->langstringcache.
3551 $data = new stdClass();
3553 if ($sm->string_exists($identifier, $component)) {
3554 $data->heading
= format_string(get_string($identifier, $component));
3556 // Gracefully fall back to an empty string.
3557 $data->heading
= '';
3560 if ($sm->string_exists($identifier . '_help', $component)) {
3561 $options = new stdClass();
3562 $options->trusted
= false;
3563 $options->noclean
= false;
3564 $options->smiley
= false;
3565 $options->filter
= false;
3566 $options->para
= true;
3567 $options->newlines
= false;
3568 $options->overflowdiv
= !$ajax;
3570 // Should be simple wiki only MDL-21695.
3571 $data->text
= format_text(get_string($identifier.'_help', $component, $a), FORMAT_MARKDOWN
, $options);
3573 $helplink = $identifier . '_link';
3574 if ($sm->string_exists($helplink, $component)) { // Link to further info in Moodle docs.
3575 $link = get_string($helplink, $component);
3576 $linktext = get_string('morehelp');
3578 $data->doclink
= new stdClass();
3579 $url = new moodle_url(get_docs_url($link));
3581 $data->doclink
->link
= $url->out();
3582 $data->doclink
->linktext
= $linktext;
3583 $data->doclink
->class = ($CFG->doctonewwindow
) ?
'helplinkpopup' : '';
3585 $data->completedoclink
= html_writer
::tag('div', $OUTPUT->doc_link($link, $linktext),
3586 array('class' => 'helpdoclink'));
3590 $data->text
= html_writer
::tag('p',
3591 html_writer
::tag('strong', 'TODO') . ": missing help string [{$identifier}_help, {$component}]");
3597 * Renders a hidden password field so that browsers won't incorrectly autofill password fields with the user's password.
3600 * @return string HTML to prevent password autofill
3602 function prevent_form_autofill_password() {
3603 return '<div class="hide"><input type="password" /></div>';