MDL-29030 standardise report_courseoverview
[moodle.git] / lib / weblib.php
blob155b2b0c07d967455de0da0a4111a09873448773
1 <?php
3 // This file is part of Moodle - http://moodle.org/
4 //
5 // Moodle is free software: you can redistribute it and/or modify
6 // it under the terms of the GNU General Public License as published by
7 // the Free Software Foundation, either version 3 of the License, or
8 // (at your option) any later version.
9 //
10 // Moodle is distributed in the hope that it will be useful,
11 // but WITHOUT ANY WARRANTY; without even the implied warranty of
12 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 // GNU General Public License for more details.
15 // You should have received a copy of the GNU General Public License
16 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
18 /**
19 * Library of functions for web output
21 * Library of all general-purpose Moodle PHP functions and constants
22 * that produce HTML output
24 * Other main libraries:
25 * - datalib.php - functions that access the database.
26 * - moodlelib.php - general-purpose Moodle functions.
28 * @package core
29 * @subpackage lib
30 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
31 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
34 defined('MOODLE_INTERNAL') || die();
36 /// Constants
38 /// Define text formatting types ... eventually we can add Wiki, BBcode etc
40 /**
41 * Does all sorts of transformations and filtering
43 define('FORMAT_MOODLE', '0'); // Does all sorts of transformations and filtering
45 /**
46 * Plain HTML (with some tags stripped)
48 define('FORMAT_HTML', '1'); // Plain HTML (with some tags stripped)
50 /**
51 * Plain text (even tags are printed in full)
53 define('FORMAT_PLAIN', '2'); // Plain text (even tags are printed in full)
55 /**
56 * Wiki-formatted text
57 * Deprecated: left here just to note that '3' is not used (at the moment)
58 * and to catch any latent wiki-like text (which generates an error)
60 define('FORMAT_WIKI', '3'); // Wiki-formatted text
62 /**
63 * Markdown-formatted text http://daringfireball.net/projects/markdown/
65 define('FORMAT_MARKDOWN', '4'); // Markdown-formatted text http://daringfireball.net/projects/markdown/
67 /**
68 * A moodle_url comparison using this flag will return true if the base URLs match, params are ignored
70 define('URL_MATCH_BASE', 0);
71 /**
72 * A moodle_url comparison using this flag will return true if the base URLs match and the params of url1 are part of url2
74 define('URL_MATCH_PARAMS', 1);
75 /**
76 * A moodle_url comparison using this flag will return true if the two URLs are identical, except for the order of the params
78 define('URL_MATCH_EXACT', 2);
80 /// Functions
82 /**
83 * Add quotes to HTML characters
85 * Returns $var with HTML characters (like "<", ">", etc.) properly quoted.
86 * This function is very similar to {@link p()}
88 * @todo Remove obsolete param $obsolete if not used anywhere
90 * @param string $var the string potentially containing HTML characters
91 * @param boolean $obsolete no longer used.
92 * @return string
94 function s($var, $obsolete = false) {
96 if ($var === '0' or $var === false or $var === 0) {
97 return '0';
100 return preg_replace("/&amp;#(\d+|x[0-7a-fA-F]+);/i", "&#$1;", htmlspecialchars($var, ENT_QUOTES, 'UTF-8', true));
104 * Add quotes to HTML characters
106 * Prints $var with HTML characters (like "<", ">", etc.) properly quoted.
107 * This function simply calls {@link s()}
108 * @see s()
110 * @todo Remove obsolete param $obsolete if not used anywhere
112 * @param string $var the string potentially containing HTML characters
113 * @param boolean $obsolete no longer used.
114 * @return string
116 function p($var, $obsolete = false) {
117 echo s($var, $obsolete);
121 * Does proper javascript quoting.
123 * Do not use addslashes anymore, because it does not work when magic_quotes_sybase is enabled.
125 * @param mixed $var String, Array, or Object to add slashes to
126 * @return mixed quoted result
128 function addslashes_js($var) {
129 if (is_string($var)) {
130 $var = str_replace('\\', '\\\\', $var);
131 $var = str_replace(array('\'', '"', "\n", "\r", "\0"), array('\\\'', '\\"', '\\n', '\\r', '\\0'), $var);
132 $var = str_replace('</', '<\/', $var); // XHTML compliance
133 } else if (is_array($var)) {
134 $var = array_map('addslashes_js', $var);
135 } else if (is_object($var)) {
136 $a = get_object_vars($var);
137 foreach ($a as $key=>$value) {
138 $a[$key] = addslashes_js($value);
140 $var = (object)$a;
142 return $var;
146 * Remove query string from url
148 * Takes in a URL and returns it without the querystring portion
150 * @param string $url the url which may have a query string attached
151 * @return string The remaining URL
153 function strip_querystring($url) {
155 if ($commapos = strpos($url, '?')) {
156 return substr($url, 0, $commapos);
157 } else {
158 return $url;
163 * Returns the URL of the HTTP_REFERER, less the querystring portion if required
165 * @uses $_SERVER
166 * @param boolean $stripquery if true, also removes the query part of the url.
167 * @return string The resulting referer or empty string
169 function get_referer($stripquery=true) {
170 if (isset($_SERVER['HTTP_REFERER'])) {
171 if ($stripquery) {
172 return strip_querystring($_SERVER['HTTP_REFERER']);
173 } else {
174 return $_SERVER['HTTP_REFERER'];
176 } else {
177 return '';
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 * @global string
191 * @return mixed String, or false if the global variables needed are not set
193 function me() {
194 global $ME;
195 return $ME;
199 * Returns the name of the current script, WITH the full URL.
201 * This function is necessary because PHP_SELF and REQUEST_URI and SCRIPT_NAME
202 * return different things depending on a lot of things like your OS, Web
203 * server, and the way PHP is compiled (ie. as a CGI, module, ISAPI, etc.
204 * <b>NOTE:</b> This function returns false if the global variables needed are not set.
206 * Like {@link me()} but returns a full URL
207 * @see me()
209 * @global string
210 * @return mixed String, or false if the global variables needed are not set
212 function qualified_me() {
213 global $FULLME;
214 return $FULLME;
218 * Class for creating and manipulating urls.
220 * It can be used in moodle pages where config.php has been included without any further includes.
222 * It is useful for manipulating urls with long lists of params.
223 * One situation where it will be useful is a page which links to itself to perform various actions
224 * and / or to process form data. A moodle_url object :
225 * can be created for a page to refer to itself with all the proper get params being passed from page call to
226 * page call and methods can be used to output a url including all the params, optionally adding and overriding
227 * params and can also be used to
228 * - output the url without any get params
229 * - and output the params as hidden fields to be output within a form
231 * @link http://docs.moodle.org/dev/lib/weblib.php_moodle_url See short write up here
232 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
233 * @package moodlecore
235 class moodle_url {
237 * Scheme, ex.: http, https
238 * @var string
240 protected $scheme = '';
242 * hostname
243 * @var string
245 protected $host = '';
247 * Port number, empty means default 80 or 443 in case of http
248 * @var unknown_type
250 protected $port = '';
252 * Username for http auth
253 * @var string
255 protected $user = '';
257 * Password for http auth
258 * @var string
260 protected $pass = '';
262 * Script path
263 * @var string
265 protected $path = '';
267 * Optional slash argument value
268 * @var string
270 protected $slashargument = '';
272 * Anchor, may be also empty, null means none
273 * @var string
275 protected $anchor = null;
277 * Url parameters as associative array
278 * @var array
280 protected $params = array(); // Associative array of query string params
283 * Create new instance of moodle_url.
285 * @param moodle_url|string $url - moodle_url means make a copy of another
286 * moodle_url and change parameters, string means full url or shortened
287 * form (ex.: '/course/view.php'). It is strongly encouraged to not include
288 * query string because it may result in double encoded values. Use the
289 * $params instead. For admin URLs, just use /admin/script.php, this
290 * class takes care of the $CFG->admin issue.
291 * @param array $params these params override current params or add new
293 public function __construct($url, array $params = null) {
294 global $CFG;
296 if ($url instanceof moodle_url) {
297 $this->scheme = $url->scheme;
298 $this->host = $url->host;
299 $this->port = $url->port;
300 $this->user = $url->user;
301 $this->pass = $url->pass;
302 $this->path = $url->path;
303 $this->slashargument = $url->slashargument;
304 $this->params = $url->params;
305 $this->anchor = $url->anchor;
307 } else {
308 // detect if anchor used
309 $apos = strpos($url, '#');
310 if ($apos !== false) {
311 $anchor = substr($url, $apos);
312 $anchor = ltrim($anchor, '#');
313 $this->set_anchor($anchor);
314 $url = substr($url, 0, $apos);
317 // normalise shortened form of our url ex.: '/course/view.php'
318 if (strpos($url, '/') === 0) {
319 // we must not use httpswwwroot here, because it might be url of other page,
320 // devs have to use httpswwwroot explicitly when creating new moodle_url
321 $url = $CFG->wwwroot.$url;
324 // now fix the admin links if needed, no need to mess with httpswwwroot
325 if ($CFG->admin !== 'admin') {
326 if (strpos($url, "$CFG->wwwroot/admin/") === 0) {
327 $url = str_replace("$CFG->wwwroot/admin/", "$CFG->wwwroot/$CFG->admin/", $url);
331 // parse the $url
332 $parts = parse_url($url);
333 if ($parts === false) {
334 throw new moodle_exception('invalidurl');
336 if (isset($parts['query'])) {
337 // note: the values may not be correctly decoded,
338 // url parameters should be always passed as array
339 parse_str(str_replace('&amp;', '&', $parts['query']), $this->params);
341 unset($parts['query']);
342 foreach ($parts as $key => $value) {
343 $this->$key = $value;
346 // detect slashargument value from path - we do not support directory names ending with .php
347 $pos = strpos($this->path, '.php/');
348 if ($pos !== false) {
349 $this->slashargument = substr($this->path, $pos + 4);
350 $this->path = substr($this->path, 0, $pos + 4);
354 $this->params($params);
358 * Add an array of params to the params for this url.
360 * The added params override existing ones if they have the same name.
362 * @param array $params Defaults to null. If null then returns all params.
363 * @return array Array of Params for url.
365 public function params(array $params = null) {
366 $params = (array)$params;
368 foreach ($params as $key=>$value) {
369 if (is_int($key)) {
370 throw new coding_exception('Url parameters can not have numeric keys!');
372 if (!is_string($value)) {
373 if (is_array($value)) {
374 throw new coding_exception('Url parameters values can not be arrays!');
376 if (is_object($value) and !method_exists($value, '__toString')) {
377 throw new coding_exception('Url parameters values can not be objects, unless __toString() is defined!');
380 $this->params[$key] = (string)$value;
382 return $this->params;
386 * Remove all params if no arguments passed.
387 * Remove selected params if arguments are passed.
389 * Can be called as either remove_params('param1', 'param2')
390 * or remove_params(array('param1', 'param2')).
392 * @param mixed $params either an array of param names, or a string param name,
393 * @param string $params,... any number of additional param names.
394 * @return array url parameters
396 public function remove_params($params = null) {
397 if (!is_array($params)) {
398 $params = func_get_args();
400 foreach ($params as $param) {
401 unset($this->params[$param]);
403 return $this->params;
407 * Remove all url parameters
408 * @param $params
409 * @return void
411 public function remove_all_params($params = null) {
412 $this->params = array();
413 $this->slashargument = '';
417 * Add a param to the params for this url.
419 * The added param overrides existing one if they have the same name.
421 * @param string $paramname name
422 * @param string $newvalue Param value. If new value specified current value is overriden or parameter is added
423 * @return mixed string parameter value, null if parameter does not exist
425 public function param($paramname, $newvalue = '') {
426 if (func_num_args() > 1) {
427 // set new value
428 $this->params(array($paramname=>$newvalue));
430 if (isset($this->params[$paramname])) {
431 return $this->params[$paramname];
432 } else {
433 return null;
438 * Merges parameters and validates them
439 * @param array $overrideparams
440 * @return array merged parameters
442 protected function merge_overrideparams(array $overrideparams = null) {
443 $overrideparams = (array)$overrideparams;
444 $params = $this->params;
445 foreach ($overrideparams as $key=>$value) {
446 if (is_int($key)) {
447 throw new coding_exception('Overridden parameters can not have numeric keys!');
449 if (is_array($value)) {
450 throw new coding_exception('Overridden parameters values can not be arrays!');
452 if (is_object($value) and !method_exists($value, '__toString')) {
453 throw new coding_exception('Overridden parameters values can not be objects, unless __toString() is defined!');
455 $params[$key] = (string)$value;
457 return $params;
461 * Get the params as as a query string.
462 * This method should not be used outside of this method.
464 * @param boolean $escaped Use &amp; as params separator instead of plain &
465 * @param array $overrideparams params to add to the output params, these
466 * override existing ones with the same name.
467 * @return string query string that can be added to a url.
469 public function get_query_string($escaped = true, array $overrideparams = null) {
470 $arr = array();
471 if ($overrideparams !== null) {
472 $params = $this->merge_overrideparams($overrideparams);
473 } else {
474 $params = $this->params;
476 foreach ($params as $key => $val) {
477 $arr[] = rawurlencode($key)."=".rawurlencode($val);
479 if ($escaped) {
480 return implode('&amp;', $arr);
481 } else {
482 return implode('&', $arr);
487 * Shortcut for printing of encoded URL.
488 * @return string
490 public function __toString() {
491 return $this->out(true);
495 * Output url
497 * If you use the returned URL in HTML code, you want the escaped ampersands. If you use
498 * the returned URL in HTTP headers, you want $escaped=false.
500 * @param boolean $escaped Use &amp; as params separator instead of plain &
501 * @param array $overrideparams params to add to the output url, these override existing ones with the same name.
502 * @return string Resulting URL
504 public function out($escaped = true, array $overrideparams = null) {
505 if (!is_bool($escaped)) {
506 debugging('Escape parameter must be of type boolean, '.gettype($escaped).' given instead.');
509 $uri = $this->out_omit_querystring().$this->slashargument;
511 $querystring = $this->get_query_string($escaped, $overrideparams);
512 if ($querystring !== '') {
513 $uri .= '?' . $querystring;
515 if (!is_null($this->anchor)) {
516 $uri .= '#'.$this->anchor;
519 return $uri;
523 * Returns url without parameters, everything before '?'.
525 * @param bool $includeanchor if {@link self::anchor} is defined, should it be returned?
526 * @return string
528 public function out_omit_querystring($includeanchor = false) {
530 $uri = $this->scheme ? $this->scheme.':'.((strtolower($this->scheme) == 'mailto') ? '':'//'): '';
531 $uri .= $this->user ? $this->user.($this->pass? ':'.$this->pass:'').'@':'';
532 $uri .= $this->host ? $this->host : '';
533 $uri .= $this->port ? ':'.$this->port : '';
534 $uri .= $this->path ? $this->path : '';
535 if ($includeanchor and !is_null($this->anchor)) {
536 $uri .= '#' . $this->anchor;
539 return $uri;
543 * Compares this moodle_url with another
544 * See documentation of constants for an explanation of the comparison flags.
545 * @param moodle_url $url The moodle_url object to compare
546 * @param int $matchtype The type of comparison (URL_MATCH_BASE, URL_MATCH_PARAMS, URL_MATCH_EXACT)
547 * @return boolean
549 public function compare(moodle_url $url, $matchtype = URL_MATCH_EXACT) {
551 $baseself = $this->out_omit_querystring();
552 $baseother = $url->out_omit_querystring();
554 // Append index.php if there is no specific file
555 if (substr($baseself,-1)=='/') {
556 $baseself .= 'index.php';
558 if (substr($baseother,-1)=='/') {
559 $baseother .= 'index.php';
562 // Compare the two base URLs
563 if ($baseself != $baseother) {
564 return false;
567 if ($matchtype == URL_MATCH_BASE) {
568 return true;
571 $urlparams = $url->params();
572 foreach ($this->params() as $param => $value) {
573 if ($param == 'sesskey') {
574 continue;
576 if (!array_key_exists($param, $urlparams) || $urlparams[$param] != $value) {
577 return false;
581 if ($matchtype == URL_MATCH_PARAMS) {
582 return true;
585 foreach ($urlparams as $param => $value) {
586 if ($param == 'sesskey') {
587 continue;
589 if (!array_key_exists($param, $this->params()) || $this->param($param) != $value) {
590 return false;
594 return true;
598 * Sets the anchor for the URI (the bit after the hash)
599 * @param string $anchor null means remove previous
601 public function set_anchor($anchor) {
602 if (is_null($anchor)) {
603 // remove
604 $this->anchor = null;
605 } else if ($anchor === '') {
606 // special case, used as empty link
607 $this->anchor = '';
608 } else if (preg_match('|[a-zA-Z\_\:][a-zA-Z0-9\_\-\.\:]*|', $anchor)) {
609 // Match the anchor against the NMTOKEN spec
610 $this->anchor = $anchor;
611 } else {
612 // bad luck, no valid anchor found
613 $this->anchor = null;
618 * Sets the url slashargument value
619 * @param string $path usually file path
620 * @param string $parameter name of page parameter if slasharguments not supported
621 * @param bool $supported usually null, then it depends on $CFG->slasharguments, use true or false for other servers
622 * @return void
624 public function set_slashargument($path, $parameter = 'file', $supported = NULL) {
625 global $CFG;
626 if (is_null($supported)) {
627 $supported = $CFG->slasharguments;
630 if ($supported) {
631 $parts = explode('/', $path);
632 $parts = array_map('rawurlencode', $parts);
633 $path = implode('/', $parts);
634 $this->slashargument = $path;
635 unset($this->params[$parameter]);
637 } else {
638 $this->slashargument = '';
639 $this->params[$parameter] = $path;
643 // == static factory methods ==
646 * General moodle file url.
647 * @param string $urlbase the script serving the file
648 * @param string $path
649 * @param bool $forcedownload
650 * @return moodle_url
652 public static function make_file_url($urlbase, $path, $forcedownload = false) {
653 global $CFG;
655 $params = array();
656 if ($forcedownload) {
657 $params['forcedownload'] = 1;
660 $url = new moodle_url($urlbase, $params);
661 $url->set_slashargument($path);
663 return $url;
667 * Factory method for creation of url pointing to plugin file.
668 * Please note this method can be used only from the plugins to
669 * create urls of own files, it must not be used outside of plugins!
670 * @param int $contextid
671 * @param string $component
672 * @param string $area
673 * @param int $itemid
674 * @param string $pathname
675 * @param string $filename
676 * @param bool $forcedownload
677 * @return moodle_url
679 public static function make_pluginfile_url($contextid, $component, $area, $itemid, $pathname, $filename, $forcedownload = false) {
680 global $CFG;
681 $urlbase = "$CFG->httpswwwroot/pluginfile.php";
682 if ($itemid === NULL) {
683 return self::make_file_url($urlbase, "/$contextid/$component/$area".$pathname.$filename, $forcedownload);
684 } else {
685 return self::make_file_url($urlbase, "/$contextid/$component/$area/$itemid".$pathname.$filename, $forcedownload);
690 * Factory method for creation of url pointing to draft
691 * file of current user.
692 * @param int $draftid draft item id
693 * @param string $pathname
694 * @param string $filename
695 * @param bool $forcedownload
696 * @return moodle_url
698 public static function make_draftfile_url($draftid, $pathname, $filename, $forcedownload = false) {
699 global $CFG, $USER;
700 $urlbase = "$CFG->httpswwwroot/draftfile.php";
701 $context = get_context_instance(CONTEXT_USER, $USER->id);
703 return self::make_file_url($urlbase, "/$context->id/user/draft/$draftid".$pathname.$filename, $forcedownload);
707 * Factory method for creating of links to legacy
708 * course files.
709 * @param int $courseid
710 * @param string $filepath
711 * @param bool $forcedownload
712 * @return moodle_url
714 public static function make_legacyfile_url($courseid, $filepath, $forcedownload = false) {
715 global $CFG;
717 $urlbase = "$CFG->wwwroot/file.php";
718 return self::make_file_url($urlbase, '/'.$courseid.'/'.$filepath, $forcedownload);
723 * Determine if there is data waiting to be processed from a form
725 * Used on most forms in Moodle to check for data
726 * Returns the data as an object, if it's found.
727 * This object can be used in foreach loops without
728 * casting because it's cast to (array) automatically
730 * Checks that submitted POST data exists and returns it as object.
732 * @uses $_POST
733 * @return mixed false or object
735 function data_submitted() {
737 if (empty($_POST)) {
738 return false;
739 } else {
740 return (object)fix_utf8($_POST);
745 * Given some normal text this function will break up any
746 * long words to a given size by inserting the given character
748 * It's multibyte savvy and doesn't change anything inside html tags.
750 * @param string $string the string to be modified
751 * @param int $maxsize maximum length of the string to be returned
752 * @param string $cutchar the string used to represent word breaks
753 * @return string
755 function break_up_long_words($string, $maxsize=20, $cutchar=' ') {
757 /// Loading the textlib singleton instance. We are going to need it.
758 $textlib = textlib_get_instance();
760 /// First of all, save all the tags inside the text to skip them
761 $tags = array();
762 filter_save_tags($string,$tags);
764 /// Process the string adding the cut when necessary
765 $output = '';
766 $length = $textlib->strlen($string);
767 $wordlength = 0;
769 for ($i=0; $i<$length; $i++) {
770 $char = $textlib->substr($string, $i, 1);
771 if ($char == ' ' or $char == "\t" or $char == "\n" or $char == "\r" or $char == "<" or $char == ">") {
772 $wordlength = 0;
773 } else {
774 $wordlength++;
775 if ($wordlength > $maxsize) {
776 $output .= $cutchar;
777 $wordlength = 0;
780 $output .= $char;
783 /// Finally load the tags back again
784 if (!empty($tags)) {
785 $output = str_replace(array_keys($tags), $tags, $output);
788 return $output;
792 * Try and close the current window using JavaScript, either immediately, or after a delay.
794 * Echo's out the resulting XHTML & javascript
796 * @global object
797 * @global object
798 * @param integer $delay a delay in seconds before closing the window. Default 0.
799 * @param boolean $reloadopener if true, we will see if this window was a pop-up, and try
800 * to reload the parent window before this one closes.
802 function close_window($delay = 0, $reloadopener = false) {
803 global $PAGE, $OUTPUT;
805 if (!$PAGE->headerprinted) {
806 $PAGE->set_title(get_string('closewindow'));
807 echo $OUTPUT->header();
808 } else {
809 $OUTPUT->container_end_all(false);
812 if ($reloadopener) {
813 // Trigger the reload immediately, even if the reload is after a delay.
814 $PAGE->requires->js_function_call('window.opener.location.reload', array(true));
816 $OUTPUT->notification(get_string('windowclosing'), 'notifysuccess');
818 $PAGE->requires->js_function_call('close_window', array(new stdClass()), false, $delay);
820 echo $OUTPUT->footer();
821 exit;
825 * Returns a string containing a link to the user documentation for the current
826 * page. Also contains an icon by default. Shown to teachers and admin only.
828 * @global object
829 * @global object
830 * @param string $text The text to be displayed for the link
831 * @param string $iconpath The path to the icon to be displayed
832 * @return string The link to user documentation for this current page
834 function page_doc_link($text='') {
835 global $CFG, $PAGE, $OUTPUT;
837 if (empty($CFG->docroot) || during_initial_install()) {
838 return '';
840 if (!has_capability('moodle/site:doclinks', $PAGE->context)) {
841 return '';
844 $path = $PAGE->docspath;
845 if (!$path) {
846 return '';
848 return $OUTPUT->doc_link($path, $text);
853 * Validates an email to make sure it makes sense.
855 * @param string $address The email address to validate.
856 * @return boolean
858 function validate_email($address) {
860 return (preg_match('#^[-!\#$%&\'*+\\/0-9=?A-Z^_`a-z{|}~]+'.
861 '(\.[-!\#$%&\'*+\\/0-9=?A-Z^_`a-z{|}~]+)*'.
862 '@'.
863 '[-!\#$%&\'*+\\/0-9=?A-Z^_`a-z{|}~]+\.'.
864 '[-!\#$%&\'*+\\./0-9=?A-Z^_`a-z{|}~]+$#',
865 $address));
869 * Extracts file argument either from file parameter or PATH_INFO
870 * Note: $scriptname parameter is not needed anymore
872 * @global string
873 * @uses $_SERVER
874 * @uses PARAM_PATH
875 * @return string file path (only safe characters)
877 function get_file_argument() {
878 global $SCRIPT;
880 $relativepath = optional_param('file', FALSE, PARAM_PATH);
882 if ($relativepath !== false and $relativepath !== '') {
883 return $relativepath;
885 $relativepath = false;
887 // then try extract file from the slasharguments
888 if (stripos($_SERVER['SERVER_SOFTWARE'], 'iis') !== false) {
889 // NOTE: ISS tends to convert all file paths to single byte DOS encoding,
890 // we can not use other methods because they break unicode chars,
891 // the only way is to use URL rewriting
892 if (isset($_SERVER['PATH_INFO']) and $_SERVER['PATH_INFO'] !== '') {
893 // check that PATH_INFO works == must not contain the script name
894 if (strpos($_SERVER['PATH_INFO'], $SCRIPT) === false) {
895 $relativepath = clean_param(urldecode($_SERVER['PATH_INFO']), PARAM_PATH);
898 } else {
899 // all other apache-like servers depend on PATH_INFO
900 if (isset($_SERVER['PATH_INFO'])) {
901 if (isset($_SERVER['SCRIPT_NAME']) and strpos($_SERVER['PATH_INFO'], $_SERVER['SCRIPT_NAME']) === 0) {
902 $relativepath = substr($_SERVER['PATH_INFO'], strlen($_SERVER['SCRIPT_NAME']));
903 } else {
904 $relativepath = $_SERVER['PATH_INFO'];
906 $relativepath = clean_param($relativepath, PARAM_PATH);
911 return $relativepath;
915 * Just returns an array of text formats suitable for a popup menu
917 * @uses FORMAT_MOODLE
918 * @uses FORMAT_HTML
919 * @uses FORMAT_PLAIN
920 * @uses FORMAT_MARKDOWN
921 * @return array
923 function format_text_menu() {
924 return array (FORMAT_MOODLE => get_string('formattext'),
925 FORMAT_HTML => get_string('formathtml'),
926 FORMAT_PLAIN => get_string('formatplain'),
927 FORMAT_MARKDOWN => get_string('formatmarkdown'));
931 * Given text in a variety of format codings, this function returns
932 * the text as safe HTML.
934 * This function should mainly be used for long strings like posts,
935 * answers, glossary items etc. For short strings @see format_string().
937 * <pre>
938 * Options:
939 * trusted : If true the string won't be cleaned. Default false required noclean=true.
940 * noclean : If true the string won't be cleaned. Default false required trusted=true.
941 * nocache : If true the strign will not be cached and will be formatted every call. Default false.
942 * filter : If true the string will be run through applicable filters as well. Default true.
943 * para : If true then the returned string will be wrapped in div tags. Default true.
944 * newlines : If true then lines newline breaks will be converted to HTML newline breaks. Default true.
945 * context : The context that will be used for filtering.
946 * overflowdiv : If set to true the formatted text will be encased in a div
947 * with the class no-overflow before being returned. Default false.
948 * allowid : If true then id attributes will not be removed, even when
949 * using htmlpurifier. Default false.
950 * </pre>
952 * @todo Finish documenting this function
954 * @staticvar array $croncache
955 * @param string $text The text to be formatted. This is raw text originally from user input.
956 * @param int $format Identifier of the text format to be used
957 * [FORMAT_MOODLE, FORMAT_HTML, FORMAT_PLAIN, FORMAT_MARKDOWN]
958 * @param object/array $options text formatting options
959 * @param int $courseid_do_not_use deprecated course id, use context option instead
960 * @return string
962 function format_text($text, $format = FORMAT_MOODLE, $options = NULL, $courseid_do_not_use = NULL) {
963 global $CFG, $COURSE, $DB, $PAGE;
964 static $croncache = array();
966 if ($text === '' || is_null($text)) {
967 return ''; // no need to do any filters and cleaning
970 $options = (array)$options; // detach object, we can not modify it
972 if (!isset($options['trusted'])) {
973 $options['trusted'] = false;
975 if (!isset($options['noclean'])) {
976 if ($options['trusted'] and trusttext_active()) {
977 // no cleaning if text trusted and noclean not specified
978 $options['noclean'] = true;
979 } else {
980 $options['noclean'] = false;
983 if (!isset($options['nocache'])) {
984 $options['nocache'] = false;
986 if (!isset($options['filter'])) {
987 $options['filter'] = true;
989 if (!isset($options['para'])) {
990 $options['para'] = true;
992 if (!isset($options['newlines'])) {
993 $options['newlines'] = true;
995 if (!isset($options['overflowdiv'])) {
996 $options['overflowdiv'] = false;
999 // Calculate best context
1000 if (empty($CFG->version) or $CFG->version < 2010072800 or during_initial_install()) {
1001 // do not filter anything during installation or before upgrade completes
1002 $context = null;
1004 } else if (isset($options['context'])) { // first by explicit passed context option
1005 if (is_object($options['context'])) {
1006 $context = $options['context'];
1007 } else {
1008 $context = get_context_instance_by_id($options['context']);
1010 } else if ($courseid_do_not_use) {
1011 // legacy courseid
1012 $context = get_context_instance(CONTEXT_COURSE, $courseid_do_not_use);
1013 } else {
1014 // fallback to $PAGE->context this may be problematic in CLI and other non-standard pages :-(
1015 $context = $PAGE->context;
1018 if (!$context) {
1019 // either install/upgrade or something has gone really wrong because context does not exist (yet?)
1020 $options['nocache'] = true;
1021 $options['filter'] = false;
1024 if ($options['filter']) {
1025 $filtermanager = filter_manager::instance();
1026 } else {
1027 $filtermanager = new null_filter_manager();
1030 if (!empty($CFG->cachetext) and empty($options['nocache'])) {
1031 $hashstr = $text.'-'.$filtermanager->text_filtering_hash($context).'-'.$context->id.'-'.current_language().'-'.
1032 (int)$format.(int)$options['trusted'].(int)$options['noclean'].
1033 (int)$options['para'].(int)$options['newlines'];
1035 $time = time() - $CFG->cachetext;
1036 $md5key = md5($hashstr);
1037 if (CLI_SCRIPT) {
1038 if (isset($croncache[$md5key])) {
1039 return $croncache[$md5key];
1043 if ($oldcacheitem = $DB->get_record('cache_text', array('md5key'=>$md5key), '*', IGNORE_MULTIPLE)) {
1044 if ($oldcacheitem->timemodified >= $time) {
1045 if (CLI_SCRIPT) {
1046 if (count($croncache) > 150) {
1047 reset($croncache);
1048 $key = key($croncache);
1049 unset($croncache[$key]);
1051 $croncache[$md5key] = $oldcacheitem->formattedtext;
1053 return $oldcacheitem->formattedtext;
1058 switch ($format) {
1059 case FORMAT_HTML:
1060 if (!$options['noclean']) {
1061 $text = clean_text($text, FORMAT_HTML, $options);
1063 $text = $filtermanager->filter_text($text, $context, array('originalformat' => FORMAT_HTML, 'noclean' => $options['noclean']));
1064 break;
1066 case FORMAT_PLAIN:
1067 $text = s($text); // cleans dangerous JS
1068 $text = rebuildnolinktag($text);
1069 $text = str_replace(' ', '&nbsp; ', $text);
1070 $text = nl2br($text);
1071 break;
1073 case FORMAT_WIKI:
1074 // this format is deprecated
1075 $text = '<p>NOTICE: Wiki-like formatting has been removed from Moodle. You should not be seeing
1076 this message as all texts should have been converted to Markdown format instead.
1077 Please post a bug report to http://moodle.org/bugs with information about where you
1078 saw this message.</p>'.s($text);
1079 break;
1081 case FORMAT_MARKDOWN:
1082 $text = markdown_to_html($text);
1083 if (!$options['noclean']) {
1084 $text = clean_text($text, FORMAT_HTML, $options);
1086 $text = $filtermanager->filter_text($text, $context, array('originalformat' => FORMAT_MARKDOWN, 'noclean' => $options['noclean']));
1087 break;
1089 default: // FORMAT_MOODLE or anything else
1090 $text = text_to_html($text, null, $options['para'], $options['newlines']);
1091 if (!$options['noclean']) {
1092 $text = clean_text($text, FORMAT_HTML, $options);
1094 $text = $filtermanager->filter_text($text, $context, array('originalformat' => $format, 'noclean' => $options['noclean']));
1095 break;
1097 if ($options['filter']) {
1098 // at this point there should not be any draftfile links any more,
1099 // this happens when developers forget to post process the text.
1100 // The only potential problem is that somebody might try to format
1101 // the text before storing into database which would be itself big bug.
1102 $text = str_replace("\"$CFG->httpswwwroot/draftfile.php", "\"$CFG->httpswwwroot/brokenfile.php#", $text);
1105 // Warn people that we have removed this old mechanism, just in case they
1106 // were stupid enough to rely on it.
1107 if (isset($CFG->currenttextiscacheable)) {
1108 debugging('Once upon a time, Moodle had a truly evil use of global variables ' .
1109 'called $CFG->currenttextiscacheable. The good news is that this no ' .
1110 'longer exists. The bad news is that you seem to be using a filter that '.
1111 'relies on it. Please seek out and destroy that filter code.', DEBUG_DEVELOPER);
1114 if (!empty($options['overflowdiv'])) {
1115 $text = html_writer::tag('div', $text, array('class'=>'no-overflow'));
1118 if (empty($options['nocache']) and !empty($CFG->cachetext)) {
1119 if (CLI_SCRIPT) {
1120 // special static cron cache - no need to store it in db if its not already there
1121 if (count($croncache) > 150) {
1122 reset($croncache);
1123 $key = key($croncache);
1124 unset($croncache[$key]);
1126 $croncache[$md5key] = $text;
1127 return $text;
1130 $newcacheitem = new stdClass();
1131 $newcacheitem->md5key = $md5key;
1132 $newcacheitem->formattedtext = $text;
1133 $newcacheitem->timemodified = time();
1134 if ($oldcacheitem) { // See bug 4677 for discussion
1135 $newcacheitem->id = $oldcacheitem->id;
1136 try {
1137 $DB->update_record('cache_text', $newcacheitem); // Update existing record in the cache table
1138 } catch (dml_exception $e) {
1139 // It's unlikely that the cron cache cleaner could have
1140 // deleted this entry in the meantime, as it allows
1141 // some extra time to cover these cases.
1143 } else {
1144 try {
1145 $DB->insert_record('cache_text', $newcacheitem); // Insert a new record in the cache table
1146 } catch (dml_exception $e) {
1147 // Again, it's possible that another user has caused this
1148 // record to be created already in the time that it took
1149 // to traverse this function. That's OK too, as the
1150 // call above handles duplicate entries, and eventually
1151 // the cron cleaner will delete them.
1156 return $text;
1160 * Resets all data related to filters, called during upgrade or when filter settings change.
1162 * @global object
1163 * @global object
1164 * @return void
1166 function reset_text_filters_cache() {
1167 global $CFG, $DB;
1169 $DB->delete_records('cache_text');
1170 $purifdir = $CFG->cachedir.'/htmlpurifier';
1171 remove_dir($purifdir, true);
1175 * Given a simple string, this function returns the string
1176 * processed by enabled string filters if $CFG->filterall is enabled
1178 * This function should be used to print short strings (non html) that
1179 * need filter processing e.g. activity titles, post subjects,
1180 * glossary concepts.
1182 * @global object
1183 * @global object
1184 * @global object
1185 * @staticvar bool $strcache
1186 * @param string $string The string to be filtered.
1187 * @param boolean $striplinks To strip any link in the result text.
1188 Moodle 1.8 default changed from false to true! MDL-8713
1189 * @param array $options options array/object or courseid
1190 * @return string
1192 function format_string($string, $striplinks = true, $options = NULL) {
1193 global $CFG, $COURSE, $PAGE;
1195 //We'll use a in-memory cache here to speed up repeated strings
1196 static $strcache = false;
1198 if (empty($CFG->version) or $CFG->version < 2010072800 or during_initial_install()) {
1199 // do not filter anything during installation or before upgrade completes
1200 return $string = strip_tags($string);
1203 if ($strcache === false or count($strcache) > 2000) { // this number might need some tuning to limit memory usage in cron
1204 $strcache = array();
1207 if (is_numeric($options)) {
1208 // legacy courseid usage
1209 $options = array('context'=>get_context_instance(CONTEXT_COURSE, $options));
1210 } else {
1211 $options = (array)$options; // detach object, we can not modify it
1214 if (empty($options['context'])) {
1215 // fallback to $PAGE->context this may be problematic in CLI and other non-standard pages :-(
1216 $options['context'] = $PAGE->context;
1217 } else if (is_numeric($options['context'])) {
1218 $options['context'] = get_context_instance_by_id($options['context']);
1221 if (!$options['context']) {
1222 // we did not find any context? weird
1223 return $string = strip_tags($string);
1226 //Calculate md5
1227 $md5 = md5($string.'<+>'.$striplinks.'<+>'.$options['context']->id.'<+>'.current_language());
1229 //Fetch from cache if possible
1230 if (isset($strcache[$md5])) {
1231 return $strcache[$md5];
1234 // First replace all ampersands not followed by html entity code
1235 // Regular expression moved to its own method for easier unit testing
1236 $string = replace_ampersands_not_followed_by_entity($string);
1238 if (!empty($CFG->filterall)) {
1239 $string = filter_manager::instance()->filter_string($string, $options['context']);
1242 // If the site requires it, strip ALL tags from this string
1243 if (!empty($CFG->formatstringstriptags)) {
1244 $string = strip_tags($string);
1246 } else {
1247 // Otherwise strip just links if that is required (default)
1248 if ($striplinks) { //strip links in string
1249 $string = strip_links($string);
1251 $string = clean_text($string);
1254 //Store to cache
1255 $strcache[$md5] = $string;
1257 return $string;
1261 * Given a string, performs a negative lookahead looking for any ampersand character
1262 * that is not followed by a proper HTML entity. If any is found, it is replaced
1263 * by &amp;. The string is then returned.
1265 * @param string $string
1266 * @return string
1268 function replace_ampersands_not_followed_by_entity($string) {
1269 return preg_replace("/\&(?![a-zA-Z0-9#]{1,8};)/", "&amp;", $string);
1273 * Given a string, replaces all <a>.*</a> by .* and returns the string.
1275 * @param string $string
1276 * @return string
1278 function strip_links($string) {
1279 return preg_replace('/(<a\s[^>]+?>)(.+?)(<\/a>)/is','$2',$string);
1283 * This expression turns links into something nice in a text format. (Russell Jungwirth)
1285 * @param string $string
1286 * @return string
1288 function wikify_links($string) {
1289 return preg_replace('~(<a [^<]*href=["|\']?([^ "\']*)["|\']?[^>]*>([^<]*)</a>)~i','$3 [ $2 ]', $string);
1293 * Given text in a variety of format codings, this function returns
1294 * the text as plain text suitable for plain email.
1296 * @uses FORMAT_MOODLE
1297 * @uses FORMAT_HTML
1298 * @uses FORMAT_PLAIN
1299 * @uses FORMAT_WIKI
1300 * @uses FORMAT_MARKDOWN
1301 * @param string $text The text to be formatted. This is raw text originally from user input.
1302 * @param int $format Identifier of the text format to be used
1303 * [FORMAT_MOODLE, FORMAT_HTML, FORMAT_PLAIN, FORMAT_WIKI, FORMAT_MARKDOWN]
1304 * @return string
1306 function format_text_email($text, $format) {
1308 switch ($format) {
1310 case FORMAT_PLAIN:
1311 return $text;
1312 break;
1314 case FORMAT_WIKI:
1315 // there should not be any of these any more!
1316 $text = wikify_links($text);
1317 return strtr(strip_tags($text), array_flip(get_html_translation_table(HTML_ENTITIES)));
1318 break;
1320 case FORMAT_HTML:
1321 return html_to_text($text);
1322 break;
1324 case FORMAT_MOODLE:
1325 case FORMAT_MARKDOWN:
1326 default:
1327 $text = wikify_links($text);
1328 return strtr(strip_tags($text), array_flip(get_html_translation_table(HTML_ENTITIES)));
1329 break;
1334 * Formats activity intro text
1336 * @global object
1337 * @uses CONTEXT_MODULE
1338 * @param string $module name of module
1339 * @param object $activity instance of activity
1340 * @param int $cmid course module id
1341 * @param bool $filter filter resulting html text
1342 * @return text
1344 function format_module_intro($module, $activity, $cmid, $filter=true) {
1345 global $CFG;
1346 require_once("$CFG->libdir/filelib.php");
1347 $context = get_context_instance(CONTEXT_MODULE, $cmid);
1348 $options = array('noclean'=>true, 'para'=>false, 'filter'=>$filter, 'context'=>$context, 'overflowdiv'=>true);
1349 $intro = file_rewrite_pluginfile_urls($activity->intro, 'pluginfile.php', $context->id, 'mod_'.$module, 'intro', null);
1350 return trim(format_text($intro, $activity->introformat, $options, null));
1354 * Legacy function, used for cleaning of old forum and glossary text only.
1356 * @global object
1357 * @param string $text text that may contain legacy TRUSTTEXT marker
1358 * @return text without legacy TRUSTTEXT marker
1360 function trusttext_strip($text) {
1361 while (true) { //removing nested TRUSTTEXT
1362 $orig = $text;
1363 $text = str_replace('#####TRUSTTEXT#####', '', $text);
1364 if (strcmp($orig, $text) === 0) {
1365 return $text;
1371 * Must be called before editing of all texts
1372 * with trust flag. Removes all XSS nasties
1373 * from texts stored in database if needed.
1375 * @param object $object data object with xxx, xxxformat and xxxtrust fields
1376 * @param string $field name of text field
1377 * @param object $context active context
1378 * @return object updated $object
1380 function trusttext_pre_edit($object, $field, $context) {
1381 $trustfield = $field.'trust';
1382 $formatfield = $field.'format';
1384 if (!$object->$trustfield or !trusttext_trusted($context)) {
1385 $object->$field = clean_text($object->$field, $object->$formatfield);
1388 return $object;
1392 * Is current user trusted to enter no dangerous XSS in this context?
1394 * Please note the user must be in fact trusted everywhere on this server!!
1396 * @param object $context
1397 * @return bool true if user trusted
1399 function trusttext_trusted($context) {
1400 return (trusttext_active() and has_capability('moodle/site:trustcontent', $context));
1404 * Is trusttext feature active?
1406 * @return bool
1408 function trusttext_active() {
1409 global $CFG;
1411 return !empty($CFG->enabletrusttext);
1415 * Given raw text (eg typed in by a user), this function cleans it up
1416 * and removes any nasty tags that could mess up Moodle pages.
1418 * NOTE: the format parameter was deprecated because we can safely clean only HTML.
1420 * @param string $text The text to be cleaned
1421 * @param int $format deprecated parameter, should always contain FORMAT_HTML or FORMAT_MOODLE
1422 * @param array $options Array of options; currently only option supported is 'allowid' (if true,
1423 * does not remove id attributes when cleaning)
1424 * @return string The cleaned up text
1426 function clean_text($text, $format = FORMAT_HTML, $options = array()) {
1427 if (empty($text) or is_numeric($text)) {
1428 return (string)$text;
1431 if ($format != FORMAT_HTML and $format != FORMAT_HTML) {
1432 // TODO: we need to standardise cleanup of text when loading it into editor first
1433 //debugging('clean_text() is designed to work only with html');
1436 if ($format == FORMAT_PLAIN) {
1437 return $text;
1440 $text = purify_html($text, $options);
1442 // Remove potential script events - some extra protection for undiscovered bugs in our code
1443 $text = preg_replace("~([^a-z])language([[:space:]]*)=~i", "$1Xlanguage=", $text);
1444 $text = preg_replace("~([^a-z])on([a-z]+)([[:space:]]*)=~i", "$1Xon$2=", $text);
1446 return $text;
1450 * KSES replacement cleaning function - uses HTML Purifier.
1452 * @param string $text The (X)HTML string to purify
1453 * @param array $options Array of options; currently only option supported is 'allowid' (if set,
1454 * does not remove id attributes when cleaning)
1455 * @return string
1457 function purify_html($text, $options = array()) {
1458 global $CFG;
1460 $type = !empty($options['allowid']) ? 'allowid' : 'normal';
1461 static $purifiers = array();
1462 if (empty($purifiers[$type])) {
1464 // make sure the serializer dir exists, it should be fine if it disappears later during cache reset
1465 $cachedir = $CFG->cachedir.'/htmlpurifier';
1466 check_dir_exists($cachedir);
1468 require_once $CFG->libdir.'/htmlpurifier/HTMLPurifier.safe-includes.php';
1469 $config = HTMLPurifier_Config::createDefault();
1471 $config->set('HTML.DefinitionID', 'moodlehtml');
1472 $config->set('HTML.DefinitionRev', 2);
1473 $config->set('Cache.SerializerPath', $cachedir);
1474 $config->set('Cache.SerializerPermissions', $CFG->directorypermissions);
1475 $config->set('Core.NormalizeNewlines', false);
1476 $config->set('Core.ConvertDocumentToFragment', true);
1477 $config->set('Core.Encoding', 'UTF-8');
1478 $config->set('HTML.Doctype', 'XHTML 1.0 Transitional');
1479 $config->set('URI.AllowedSchemes', array('http'=>true, 'https'=>true, 'ftp'=>true, 'irc'=>true, 'nntp'=>true, 'news'=>true, 'rtsp'=>true, 'teamspeak'=>true, 'gopher'=>true, 'mms'=>true, 'mailto'=>true));
1480 $config->set('Attr.AllowedFrameTargets', array('_blank'));
1482 if (!empty($CFG->allowobjectembed)) {
1483 $config->set('HTML.SafeObject', true);
1484 $config->set('Output.FlashCompat', true);
1485 $config->set('HTML.SafeEmbed', true);
1488 if ($type === 'allowid') {
1489 $config->set('Attr.EnableID', true);
1492 if ($def = $config->maybeGetRawHTMLDefinition()) {
1493 $def->addElement('nolink', 'Block', 'Flow', array()); // skip our filters inside
1494 $def->addElement('tex', 'Inline', 'Inline', array()); // tex syntax, equivalent to $$xx$$
1495 $def->addElement('algebra', 'Inline', 'Inline', array()); // algebra syntax, equivalent to @@xx@@
1496 $def->addElement('lang', 'Block', 'Flow', array(), array('lang'=>'CDATA')); // old and future style multilang - only our hacked lang attribute
1497 $def->addAttribute('span', 'xxxlang', 'CDATA'); // current problematic multilang
1500 $purifier = new HTMLPurifier($config);
1501 $purifiers[$type] = $purifier;
1502 } else {
1503 $purifier = $purifiers[$type];
1506 $multilang = (strpos($text, 'class="multilang"') !== false);
1508 if ($multilang) {
1509 $text = preg_replace('/<span(\s+lang="([a-zA-Z0-9_-]+)"|\s+class="multilang"){2}\s*>/', '<span xxxlang="${2}">', $text);
1511 $text = $purifier->purify($text);
1512 if ($multilang) {
1513 $text = preg_replace('/<span xxxlang="([a-zA-Z0-9_-]+)">/', '<span lang="${1}" class="multilang">', $text);
1516 return $text;
1520 * Given plain text, makes it into HTML as nicely as possible.
1521 * May contain HTML tags already
1523 * Do not abuse this function. It is intended as lower level formatting feature used
1524 * by {@see format_text()} to convert FORMAT_MOODLE to HTML. You are supposed
1525 * to call format_text() in most of cases.
1527 * @param string $text The string to convert.
1528 * @param boolean $smiley_ignored Was used to determine if smiley characters should convert to smiley images, ignored now
1529 * @param boolean $para If true then the returned string will be wrapped in div tags
1530 * @param boolean $newlines If true then lines newline breaks will be converted to HTML newline breaks.
1531 * @return string
1534 function text_to_html($text, $smiley_ignored=null, $para=true, $newlines=true) {
1535 /// Remove any whitespace that may be between HTML tags
1536 $text = preg_replace("~>([[:space:]]+)<~i", "><", $text);
1538 /// Remove any returns that precede or follow HTML tags
1539 $text = preg_replace("~([\n\r])<~i", " <", $text);
1540 $text = preg_replace("~>([\n\r])~i", "> ", $text);
1542 /// Make returns into HTML newlines.
1543 if ($newlines) {
1544 $text = nl2br($text);
1547 /// Wrap the whole thing in a div if required
1548 if ($para) {
1549 //return '<p>'.$text.'</p>'; //1.9 version
1550 return '<div class="text_to_html">'.$text.'</div>';
1551 } else {
1552 return $text;
1557 * Given Markdown formatted text, make it into XHTML using external function
1559 * @global object
1560 * @param string $text The markdown formatted text to be converted.
1561 * @return string Converted text
1563 function markdown_to_html($text) {
1564 global $CFG;
1566 if ($text === '' or $text === NULL) {
1567 return $text;
1570 require_once($CFG->libdir .'/markdown.php');
1572 return Markdown($text);
1576 * Given HTML text, make it into plain text using external function
1578 * @param string $html The text to be converted.
1579 * @param integer $width Width to wrap the text at. (optional, default 75 which
1580 * is a good value for email. 0 means do not limit line length.)
1581 * @param boolean $dolinks By default, any links in the HTML are collected, and
1582 * printed as a list at the end of the HTML. If you don't want that, set this
1583 * argument to false.
1584 * @return string plain text equivalent of the HTML.
1586 function html_to_text($html, $width = 75, $dolinks = true) {
1588 global $CFG;
1590 require_once($CFG->libdir .'/html2text.php');
1592 $h2t = new html2text($html, false, $dolinks, $width);
1593 $result = $h2t->get_text();
1595 return $result;
1599 * This function will highlight search words in a given string
1601 * It cares about HTML and will not ruin links. It's best to use
1602 * this function after performing any conversions to HTML.
1604 * @param string $needle The search string. Syntax like "word1 +word2 -word3" is dealt with correctly.
1605 * @param string $haystack The string (HTML) within which to highlight the search terms.
1606 * @param boolean $matchcase whether to do case-sensitive. Default case-insensitive.
1607 * @param string $prefix the string to put before each search term found.
1608 * @param string $suffix the string to put after each search term found.
1609 * @return string The highlighted HTML.
1611 function highlight($needle, $haystack, $matchcase = false,
1612 $prefix = '<span class="highlight">', $suffix = '</span>') {
1614 /// Quick bail-out in trivial cases.
1615 if (empty($needle) or empty($haystack)) {
1616 return $haystack;
1619 /// Break up the search term into words, discard any -words and build a regexp.
1620 $words = preg_split('/ +/', trim($needle));
1621 foreach ($words as $index => $word) {
1622 if (strpos($word, '-') === 0) {
1623 unset($words[$index]);
1624 } else if (strpos($word, '+') === 0) {
1625 $words[$index] = '\b' . preg_quote(ltrim($word, '+'), '/') . '\b'; // Match only as a complete word.
1626 } else {
1627 $words[$index] = preg_quote($word, '/');
1630 $regexp = '/(' . implode('|', $words) . ')/u'; // u is do UTF-8 matching.
1631 if (!$matchcase) {
1632 $regexp .= 'i';
1635 /// Another chance to bail-out if $search was only -words
1636 if (empty($words)) {
1637 return $haystack;
1640 /// Find all the HTML tags in the input, and store them in a placeholders array.
1641 $placeholders = array();
1642 $matches = array();
1643 preg_match_all('/<[^>]*>/', $haystack, $matches);
1644 foreach (array_unique($matches[0]) as $key => $htmltag) {
1645 $placeholders['<|' . $key . '|>'] = $htmltag;
1648 /// In $hastack, replace each HTML tag with the corresponding placeholder.
1649 $haystack = str_replace($placeholders, array_keys($placeholders), $haystack);
1651 /// In the resulting string, Do the highlighting.
1652 $haystack = preg_replace($regexp, $prefix . '$1' . $suffix, $haystack);
1654 /// Turn the placeholders back into HTML tags.
1655 $haystack = str_replace(array_keys($placeholders), $placeholders, $haystack);
1657 return $haystack;
1661 * This function will highlight instances of $needle in $haystack
1663 * It's faster that the above function {@link highlight()} and doesn't care about
1664 * HTML or anything.
1666 * @param string $needle The string to search for
1667 * @param string $haystack The string to search for $needle in
1668 * @return string The highlighted HTML
1670 function highlightfast($needle, $haystack) {
1672 if (empty($needle) or empty($haystack)) {
1673 return $haystack;
1676 $parts = explode(moodle_strtolower($needle), moodle_strtolower($haystack));
1678 if (count($parts) === 1) {
1679 return $haystack;
1682 $pos = 0;
1684 foreach ($parts as $key => $part) {
1685 $parts[$key] = substr($haystack, $pos, strlen($part));
1686 $pos += strlen($part);
1688 $parts[$key] .= '<span class="highlight">'.substr($haystack, $pos, strlen($needle)).'</span>';
1689 $pos += strlen($needle);
1692 return str_replace('<span class="highlight"></span>', '', join('', $parts));
1696 * Return a string containing 'lang', xml:lang and optionally 'dir' HTML attributes.
1697 * Internationalisation, for print_header and backup/restorelib.
1699 * @param bool $dir Default false
1700 * @return string Attributes
1702 function get_html_lang($dir = false) {
1703 $direction = '';
1704 if ($dir) {
1705 if (right_to_left()) {
1706 $direction = ' dir="rtl"';
1707 } else {
1708 $direction = ' dir="ltr"';
1711 //Accessibility: added the 'lang' attribute to $direction, used in theme <html> tag.
1712 $language = str_replace('_', '-', current_language());
1713 @header('Content-Language: '.$language);
1714 return ($direction.' lang="'.$language.'" xml:lang="'.$language.'"');
1718 /// STANDARD WEB PAGE PARTS ///////////////////////////////////////////////////
1721 * Send the HTTP headers that Moodle requires.
1722 * @param $cacheable Can this page be cached on back?
1724 function send_headers($contenttype, $cacheable = true) {
1725 global $CFG;
1727 @header('Content-Type: ' . $contenttype);
1728 @header('Content-Script-Type: text/javascript');
1729 @header('Content-Style-Type: text/css');
1731 if ($cacheable) {
1732 // Allow caching on "back" (but not on normal clicks)
1733 @header('Cache-Control: private, pre-check=0, post-check=0, max-age=0');
1734 @header('Pragma: no-cache');
1735 @header('Expires: ');
1736 } else {
1737 // Do everything we can to always prevent clients and proxies caching
1738 @header('Cache-Control: no-store, no-cache, must-revalidate');
1739 @header('Cache-Control: post-check=0, pre-check=0', false);
1740 @header('Pragma: no-cache');
1741 @header('Expires: Mon, 20 Aug 1969 09:23:00 GMT');
1742 @header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
1744 @header('Accept-Ranges: none');
1746 if (empty($CFG->allowframembedding)) {
1747 @header('X-Frame-Options: sameorigin');
1752 * Return the right arrow with text ('next'), and optionally embedded in a link.
1754 * @global object
1755 * @param string $text HTML/plain text label (set to blank only for breadcrumb separator cases).
1756 * @param string $url An optional link to use in a surrounding HTML anchor.
1757 * @param bool $accesshide True if text should be hidden (for screen readers only).
1758 * @param string $addclass Additional class names for the link, or the arrow character.
1759 * @return string HTML string.
1761 function link_arrow_right($text, $url='', $accesshide=false, $addclass='') {
1762 global $OUTPUT; //TODO: move to output renderer
1763 $arrowclass = 'arrow ';
1764 if (! $url) {
1765 $arrowclass .= $addclass;
1767 $arrow = '<span class="'.$arrowclass.'">'.$OUTPUT->rarrow().'</span>';
1768 $htmltext = '';
1769 if ($text) {
1770 $htmltext = '<span class="arrow_text">'.$text.'</span>&nbsp;';
1771 if ($accesshide) {
1772 $htmltext = get_accesshide($htmltext);
1775 if ($url) {
1776 $class = 'arrow_link';
1777 if ($addclass) {
1778 $class .= ' '.$addclass;
1780 return '<a class="'.$class.'" href="'.$url.'" title="'.preg_replace('/<.*?>/','',$text).'">'.$htmltext.$arrow.'</a>';
1782 return $htmltext.$arrow;
1786 * Return the left arrow with text ('previous'), and optionally embedded in a link.
1788 * @global object
1789 * @param string $text HTML/plain text label (set to blank only for breadcrumb separator cases).
1790 * @param string $url An optional link to use in a surrounding HTML anchor.
1791 * @param bool $accesshide True if text should be hidden (for screen readers only).
1792 * @param string $addclass Additional class names for the link, or the arrow character.
1793 * @return string HTML string.
1795 function link_arrow_left($text, $url='', $accesshide=false, $addclass='') {
1796 global $OUTPUT; // TODO: move to utput renderer
1797 $arrowclass = 'arrow ';
1798 if (! $url) {
1799 $arrowclass .= $addclass;
1801 $arrow = '<span class="'.$arrowclass.'">'.$OUTPUT->larrow().'</span>';
1802 $htmltext = '';
1803 if ($text) {
1804 $htmltext = '&nbsp;<span class="arrow_text">'.$text.'</span>';
1805 if ($accesshide) {
1806 $htmltext = get_accesshide($htmltext);
1809 if ($url) {
1810 $class = 'arrow_link';
1811 if ($addclass) {
1812 $class .= ' '.$addclass;
1814 return '<a class="'.$class.'" href="'.$url.'" title="'.preg_replace('/<.*?>/','',$text).'">'.$arrow.$htmltext.'</a>';
1816 return $arrow.$htmltext;
1820 * Return a HTML element with the class "accesshide", for accessibility.
1821 * Please use cautiously - where possible, text should be visible!
1823 * @param string $text Plain text.
1824 * @param string $elem Lowercase element name, default "span".
1825 * @param string $class Additional classes for the element.
1826 * @param string $attrs Additional attributes string in the form, "name='value' name2='value2'"
1827 * @return string HTML string.
1829 function get_accesshide($text, $elem='span', $class='', $attrs='') {
1830 return "<$elem class=\"accesshide $class\" $attrs>$text</$elem>";
1834 * Return the breadcrumb trail navigation separator.
1836 * @return string HTML string.
1838 function get_separator() {
1839 //Accessibility: the 'hidden' slash is preferred for screen readers.
1840 return ' '.link_arrow_right($text='/', $url='', $accesshide=true, 'sep').' ';
1844 * Print (or return) a collapsible region, that has a caption that can
1845 * be clicked to expand or collapse the region.
1847 * If JavaScript is off, then the region will always be expanded.
1849 * @param string $contents the contents of the box.
1850 * @param string $classes class names added to the div that is output.
1851 * @param string $id id added to the div that is output. Must not be blank.
1852 * @param string $caption text displayed at the top. Clicking on this will cause the region to expand or contract.
1853 * @param string $userpref the name of the user preference that stores the user's preferred default state.
1854 * (May be blank if you do not wish the state to be persisted.
1855 * @param boolean $default Initial collapsed state to use if the user_preference it not set.
1856 * @param boolean $return if true, return the HTML as a string, rather than printing it.
1857 * @return string|void If $return is false, returns nothing, otherwise returns a string of HTML.
1859 function print_collapsible_region($contents, $classes, $id, $caption, $userpref = '', $default = false, $return = false) {
1860 $output = print_collapsible_region_start($classes, $id, $caption, $userpref, $default, true);
1861 $output .= $contents;
1862 $output .= print_collapsible_region_end(true);
1864 if ($return) {
1865 return $output;
1866 } else {
1867 echo $output;
1872 * Print (or return) the start of a collapsible region, that has a caption that can
1873 * be clicked to expand or collapse the region. If JavaScript is off, then the region
1874 * will always be expanded.
1876 * @param string $classes class names added to the div that is output.
1877 * @param string $id id added to the div that is output. Must not be blank.
1878 * @param string $caption text displayed at the top. Clicking on this will cause the region to expand or contract.
1879 * @param string $userpref the name of the user preference that stores the user's preferred default state.
1880 * (May be blank if you do not wish the state to be persisted.
1881 * @param boolean $default Initial collapsed state to use if the user_preference it not set.
1882 * @param boolean $return if true, return the HTML as a string, rather than printing it.
1883 * @return string|void if $return is false, returns nothing, otherwise returns a string of HTML.
1885 function print_collapsible_region_start($classes, $id, $caption, $userpref = '', $default = false, $return = false) {
1886 global $CFG, $PAGE, $OUTPUT;
1888 // Work out the initial state.
1889 if (!empty($userpref) and is_string($userpref)) {
1890 user_preference_allow_ajax_update($userpref, PARAM_BOOL);
1891 $collapsed = get_user_preferences($userpref, $default);
1892 } else {
1893 $collapsed = $default;
1894 $userpref = false;
1897 if ($collapsed) {
1898 $classes .= ' collapsed';
1901 $output = '';
1902 $output .= '<div id="' . $id . '" class="collapsibleregion ' . $classes . '">';
1903 $output .= '<div id="' . $id . '_sizer">';
1904 $output .= '<div id="' . $id . '_caption" class="collapsibleregioncaption">';
1905 $output .= $caption . ' ';
1906 $output .= '</div><div id="' . $id . '_inner" class="collapsibleregioninner">';
1907 $PAGE->requires->js_init_call('M.util.init_collapsible_region', array($id, $userpref, get_string('clicktohideshow')));
1909 if ($return) {
1910 return $output;
1911 } else {
1912 echo $output;
1917 * Close a region started with print_collapsible_region_start.
1919 * @param boolean $return if true, return the HTML as a string, rather than printing it.
1920 * @return string|void if $return is false, returns nothing, otherwise returns a string of HTML.
1922 function print_collapsible_region_end($return = false) {
1923 $output = '</div></div></div>';
1925 if ($return) {
1926 return $output;
1927 } else {
1928 echo $output;
1933 * Print a specified group's avatar.
1935 * @global object
1936 * @uses CONTEXT_COURSE
1937 * @param array|stdClass $group A single {@link group} object OR array of groups.
1938 * @param int $courseid The course ID.
1939 * @param boolean $large Default small picture, or large.
1940 * @param boolean $return If false print picture, otherwise return the output as string
1941 * @param boolean $link Enclose image in a link to view specified course?
1942 * @return string|void Depending on the setting of $return
1944 function print_group_picture($group, $courseid, $large=false, $return=false, $link=true) {
1945 global $CFG;
1947 if (is_array($group)) {
1948 $output = '';
1949 foreach($group as $g) {
1950 $output .= print_group_picture($g, $courseid, $large, true, $link);
1952 if ($return) {
1953 return $output;
1954 } else {
1955 echo $output;
1956 return;
1960 $context = get_context_instance(CONTEXT_COURSE, $courseid);
1962 // If there is no picture, do nothing
1963 if (!$group->picture) {
1964 return '';
1967 // If picture is hidden, only show to those with course:managegroups
1968 if ($group->hidepicture and !has_capability('moodle/course:managegroups', $context)) {
1969 return '';
1972 if ($link or has_capability('moodle/site:accessallgroups', $context)) {
1973 $output = '<a href="'. $CFG->wwwroot .'/user/index.php?id='. $courseid .'&amp;group='. $group->id .'">';
1974 } else {
1975 $output = '';
1977 if ($large) {
1978 $file = 'f1';
1979 } else {
1980 $file = 'f2';
1983 $grouppictureurl = moodle_url::make_pluginfile_url($context->id, 'group', 'icon', $group->id, '/', $file);
1984 $output .= '<img class="grouppicture" src="'.$grouppictureurl.'"'.
1985 ' alt="'.s(get_string('group').' '.$group->name).'" title="'.s($group->name).'"/>';
1987 if ($link or has_capability('moodle/site:accessallgroups', $context)) {
1988 $output .= '</a>';
1991 if ($return) {
1992 return $output;
1993 } else {
1994 echo $output;
2000 * Display a recent activity note
2002 * @uses CONTEXT_SYSTEM
2003 * @staticvar string $strftimerecent
2004 * @param object A time object
2005 * @param object A user object
2006 * @param string $text Text for display for the note
2007 * @param string $link The link to wrap around the text
2008 * @param bool $return If set to true the HTML is returned rather than echo'd
2009 * @param string $viewfullnames
2011 function print_recent_activity_note($time, $user, $text, $link, $return=false, $viewfullnames=null) {
2012 static $strftimerecent = null;
2013 $output = '';
2015 if (is_null($viewfullnames)) {
2016 $context = get_context_instance(CONTEXT_SYSTEM);
2017 $viewfullnames = has_capability('moodle/site:viewfullnames', $context);
2020 if (is_null($strftimerecent)) {
2021 $strftimerecent = get_string('strftimerecent');
2024 $output .= '<div class="head">';
2025 $output .= '<div class="date">'.userdate($time, $strftimerecent).'</div>';
2026 $output .= '<div class="name">'.fullname($user, $viewfullnames).'</div>';
2027 $output .= '</div>';
2028 $output .= '<div class="info"><a href="'.$link.'">'.format_string($text,true).'</a></div>';
2030 if ($return) {
2031 return $output;
2032 } else {
2033 echo $output;
2038 * Returns a popup menu with course activity modules
2040 * Given a course
2041 * This function returns a small popup menu with all the
2042 * course activity modules in it, as a navigation menu
2043 * outputs a simple list structure in XHTML
2044 * The data is taken from the serialised array stored in
2045 * the course record
2047 * @todo Finish documenting this function
2049 * @global object
2050 * @uses CONTEXT_COURSE
2051 * @param course $course A {@link $COURSE} object.
2052 * @param string $sections
2053 * @param string $modinfo
2054 * @param string $strsection
2055 * @param string $strjumpto
2056 * @param int $width
2057 * @param string $cmid
2058 * @return string The HTML block
2060 function navmenulist($course, $sections, $modinfo, $strsection, $strjumpto, $width=50, $cmid=0) {
2062 global $CFG, $OUTPUT;
2064 $section = -1;
2065 $url = '';
2066 $menu = array();
2067 $doneheading = false;
2069 $coursecontext = get_context_instance(CONTEXT_COURSE, $course->id);
2071 $menu[] = '<ul class="navmenulist"><li class="jumpto section"><span>'.$strjumpto.'</span><ul>';
2072 foreach ($modinfo->cms as $mod) {
2073 if (!$mod->has_view()) {
2074 // Don't show modules which you can't link to!
2075 continue;
2078 if ($mod->sectionnum > $course->numsections) { /// Don't show excess hidden sections
2079 break;
2082 if (!$mod->uservisible) { // do not icnlude empty sections at all
2083 continue;
2086 if ($mod->sectionnum >= 0 and $section != $mod->sectionnum) {
2087 $thissection = $sections[$mod->sectionnum];
2089 if ($thissection->visible or !$course->hiddensections or
2090 has_capability('moodle/course:viewhiddensections', $coursecontext)) {
2091 $thissection->summary = strip_tags(format_string($thissection->summary,true));
2092 if (!$doneheading) {
2093 $menu[] = '</ul></li>';
2095 if ($course->format == 'weeks' or empty($thissection->summary)) {
2096 $item = $strsection ." ". $mod->sectionnum;
2097 } else {
2098 if (textlib::strlen($thissection->summary) < ($width-3)) {
2099 $item = $thissection->summary;
2100 } else {
2101 $item = textlib::substr($thissection->summary, 0, $width).'...';
2104 $menu[] = '<li class="section"><span>'.$item.'</span>';
2105 $menu[] = '<ul>';
2106 $doneheading = true;
2108 $section = $mod->sectionnum;
2109 } else {
2110 // no activities from this hidden section shown
2111 continue;
2115 $url = $mod->modname .'/view.php?id='. $mod->id;
2116 $mod->name = strip_tags(format_string($mod->name ,true));
2117 if (textlib::strlen($mod->name) > ($width+5)) {
2118 $mod->name = textlib::substr($mod->name, 0, $width).'...';
2120 if (!$mod->visible) {
2121 $mod->name = '('.$mod->name.')';
2123 $class = 'activity '.$mod->modname;
2124 $class .= ($cmid == $mod->id) ? ' selected' : '';
2125 $menu[] = '<li class="'.$class.'">'.
2126 '<img src="'.$OUTPUT->pix_url('icon', $mod->modname) . '" alt="" />'.
2127 '<a href="'.$CFG->wwwroot.'/mod/'.$url.'">'.$mod->name.'</a></li>';
2130 if ($doneheading) {
2131 $menu[] = '</ul></li>';
2133 $menu[] = '</ul></li></ul>';
2135 return implode("\n", $menu);
2139 * Prints a grade menu (as part of an existing form) with help
2140 * Showing all possible numerical grades and scales
2142 * @todo Finish documenting this function
2143 * @todo Deprecate: this is only used in a few contrib modules
2145 * @global object
2146 * @param int $courseid The course ID
2147 * @param string $name
2148 * @param string $current
2149 * @param boolean $includenograde Include those with no grades
2150 * @param boolean $return If set to true returns rather than echo's
2151 * @return string|bool Depending on value of $return
2153 function print_grade_menu($courseid, $name, $current, $includenograde=true, $return=false) {
2155 global $CFG, $OUTPUT;
2157 $output = '';
2158 $strscale = get_string('scale');
2159 $strscales = get_string('scales');
2161 $scales = get_scales_menu($courseid);
2162 foreach ($scales as $i => $scalename) {
2163 $grades[-$i] = $strscale .': '. $scalename;
2165 if ($includenograde) {
2166 $grades[0] = get_string('nograde');
2168 for ($i=100; $i>=1; $i--) {
2169 $grades[$i] = $i;
2171 $output .= html_writer::select($grades, $name, $current, false);
2173 $linkobject = '<span class="helplink"><img class="iconhelp" alt="'.$strscales.'" src="'.$OUTPUT->pix_url('help') . '" /></span>';
2174 $link = new moodle_url('/course/scales.php', array('id'=>$courseid, 'list'=>1));
2175 $action = new popup_action('click', $link, 'ratingscales', array('height' => 400, 'width' => 500));
2176 $output .= $OUTPUT->action_link($link, $linkobject, $action, array('title'=>$strscales));
2178 if ($return) {
2179 return $output;
2180 } else {
2181 echo $output;
2186 * Print an error to STDOUT and exit with a non-zero code. For commandline scripts.
2187 * Default errorcode is 1.
2189 * Very useful for perl-like error-handling:
2191 * do_somethting() or mdie("Something went wrong");
2193 * @param string $msg Error message
2194 * @param integer $errorcode Error code to emit
2196 function mdie($msg='', $errorcode=1) {
2197 trigger_error($msg);
2198 exit($errorcode);
2202 * Print a message and exit.
2204 * @param string $message The message to print in the notice
2205 * @param string $link The link to use for the continue button
2206 * @param object $course A course object
2207 * @return void This function simply exits
2209 function notice ($message, $link='', $course=NULL) {
2210 global $CFG, $SITE, $COURSE, $PAGE, $OUTPUT;
2212 $message = clean_text($message); // In case nasties are in here
2214 if (CLI_SCRIPT) {
2215 echo("!!$message!!\n");
2216 exit(1); // no success
2219 if (!$PAGE->headerprinted) {
2220 //header not yet printed
2221 $PAGE->set_title(get_string('notice'));
2222 echo $OUTPUT->header();
2223 } else {
2224 echo $OUTPUT->container_end_all(false);
2227 echo $OUTPUT->box($message, 'generalbox', 'notice');
2228 echo $OUTPUT->continue_button($link);
2230 echo $OUTPUT->footer();
2231 exit(1); // general error code
2235 * Redirects the user to another page, after printing a notice
2237 * This function calls the OUTPUT redirect method, echo's the output
2238 * and then dies to ensure nothing else happens.
2240 * <strong>Good practice:</strong> You should call this method before starting page
2241 * output by using any of the OUTPUT methods.
2243 * @param moodle_url|string $url A moodle_url to redirect to. Strings are not to be trusted!
2244 * @param string $message The message to display to the user
2245 * @param int $delay The delay before redirecting
2246 * @return void - does not return!
2248 function redirect($url, $message='', $delay=-1) {
2249 global $OUTPUT, $PAGE, $SESSION, $CFG;
2251 if (CLI_SCRIPT or AJAX_SCRIPT) {
2252 // this is wrong - developers should not use redirect in these scripts,
2253 // but it should not be very likely
2254 throw new moodle_exception('redirecterrordetected', 'error');
2257 // prevent debug errors - make sure context is properly initialised
2258 if ($PAGE) {
2259 $PAGE->set_context(null);
2260 $PAGE->set_pagelayout('redirect'); // No header and footer needed
2263 if ($url instanceof moodle_url) {
2264 $url = $url->out(false);
2267 $debugdisableredirect = false;
2268 do {
2269 if (defined('DEBUGGING_PRINTED')) {
2270 // some debugging already printed, no need to look more
2271 $debugdisableredirect = true;
2272 break;
2275 if (empty($CFG->debugdisplay) or empty($CFG->debug)) {
2276 // no errors should be displayed
2277 break;
2280 if (!function_exists('error_get_last') or !$lasterror = error_get_last()) {
2281 break;
2284 if (!($lasterror['type'] & $CFG->debug)) {
2285 //last error not interesting
2286 break;
2289 // watch out here, @hidden() errors are returned from error_get_last() too
2290 if (headers_sent()) {
2291 //we already started printing something - that means errors likely printed
2292 $debugdisableredirect = true;
2293 break;
2296 if (ob_get_level() and ob_get_contents()) {
2297 // there is something waiting to be printed, hopefully it is the errors,
2298 // but it might be some error hidden by @ too - such as the timezone mess from setup.php
2299 $debugdisableredirect = true;
2300 break;
2302 } while (false);
2304 // Technically, HTTP/1.1 requires Location: header to contain the absolute path.
2305 // (In practice browsers accept relative paths - but still, might as well do it properly.)
2306 // This code turns relative into absolute.
2307 if (!preg_match('|^[a-z]+:|', $url)) {
2308 // Get host name http://www.wherever.com
2309 $hostpart = preg_replace('|^(.*?[^:/])/.*$|', '$1', $CFG->wwwroot);
2310 if (preg_match('|^/|', $url)) {
2311 // URLs beginning with / are relative to web server root so we just add them in
2312 $url = $hostpart.$url;
2313 } else {
2314 // URLs not beginning with / are relative to path of current script, so add that on.
2315 $url = $hostpart.preg_replace('|\?.*$|','',me()).'/../'.$url;
2317 // Replace all ..s
2318 while (true) {
2319 $newurl = preg_replace('|/(?!\.\.)[^/]*/\.\./|', '/', $url);
2320 if ($newurl == $url) {
2321 break;
2323 $url = $newurl;
2327 // Sanitise url - we can not rely on moodle_url or our URL cleaning
2328 // because they do not support all valid external URLs
2329 $url = preg_replace('/[\x00-\x1F\x7F]/', '', $url);
2330 $url = str_replace('"', '%22', $url);
2331 $encodedurl = preg_replace("/\&(?![a-zA-Z0-9#]{1,8};)/", "&amp;", $url);
2332 $encodedurl = preg_replace('/^.*href="([^"]*)".*$/', "\\1", clean_text('<a href="'.$encodedurl.'" />', FORMAT_HTML));
2333 $url = str_replace('&amp;', '&', $encodedurl);
2335 if (!empty($message)) {
2336 if ($delay === -1 || !is_numeric($delay)) {
2337 $delay = 3;
2339 $message = clean_text($message);
2340 } else {
2341 $message = get_string('pageshouldredirect');
2342 $delay = 0;
2345 if (defined('MDL_PERF') || (!empty($CFG->perfdebug) and $CFG->perfdebug > 7)) {
2346 if (defined('MDL_PERFTOLOG') && !function_exists('register_shutdown_function')) {
2347 $perf = get_performance_info();
2348 error_log("PERF: " . $perf['txt']);
2352 if ($delay == 0 && !$debugdisableredirect && !headers_sent()) {
2353 // workaround for IIS bug http://support.microsoft.com/kb/q176113/
2354 if (session_id()) {
2355 session_get_instance()->write_close();
2358 //302 might not work for POST requests, 303 is ignored by obsolete clients.
2359 @header($_SERVER['SERVER_PROTOCOL'] . ' 303 See Other');
2360 @header('Location: '.$url);
2361 echo bootstrap_renderer::plain_redirect_message($encodedurl);
2362 exit;
2365 // Include a redirect message, even with a HTTP redirect, because that is recommended practice.
2366 if ($PAGE) {
2367 $CFG->docroot = false; // to prevent the link to moodle docs from being displayed on redirect page.
2368 echo $OUTPUT->redirect_message($encodedurl, $message, $delay, $debugdisableredirect);
2369 exit;
2370 } else {
2371 echo bootstrap_renderer::early_redirect_message($encodedurl, $message, $delay);
2372 exit;
2377 * Given an email address, this function will return an obfuscated version of it
2379 * @param string $email The email address to obfuscate
2380 * @return string The obfuscated email address
2382 function obfuscate_email($email) {
2384 $i = 0;
2385 $length = strlen($email);
2386 $obfuscated = '';
2387 while ($i < $length) {
2388 if (rand(0,2) && $email{$i}!='@') { //MDL-20619 some browsers have problems unobfuscating @
2389 $obfuscated.='%'.dechex(ord($email{$i}));
2390 } else {
2391 $obfuscated.=$email{$i};
2393 $i++;
2395 return $obfuscated;
2399 * This function takes some text and replaces about half of the characters
2400 * with HTML entity equivalents. Return string is obviously longer.
2402 * @param string $plaintext The text to be obfuscated
2403 * @return string The obfuscated text
2405 function obfuscate_text($plaintext) {
2407 $i=0;
2408 $length = strlen($plaintext);
2409 $obfuscated='';
2410 $prev_obfuscated = false;
2411 while ($i < $length) {
2412 $c = ord($plaintext{$i});
2413 $numerical = ($c >= ord('0')) && ($c <= ord('9'));
2414 if ($prev_obfuscated and $numerical ) {
2415 $obfuscated.='&#'.ord($plaintext{$i}).';';
2416 } else if (rand(0,2)) {
2417 $obfuscated.='&#'.ord($plaintext{$i}).';';
2418 $prev_obfuscated = true;
2419 } else {
2420 $obfuscated.=$plaintext{$i};
2421 $prev_obfuscated = false;
2423 $i++;
2425 return $obfuscated;
2429 * This function uses the {@link obfuscate_email()} and {@link obfuscate_text()}
2430 * to generate a fully obfuscated email link, ready to use.
2432 * @param string $email The email address to display
2433 * @param string $label The text to displayed as hyperlink to $email
2434 * @param boolean $dimmed If true then use css class 'dimmed' for hyperlink
2435 * @return string The obfuscated mailto link
2437 function obfuscate_mailto($email, $label='', $dimmed=false) {
2439 if (empty($label)) {
2440 $label = $email;
2442 if ($dimmed) {
2443 $title = get_string('emaildisable');
2444 $dimmed = ' class="dimmed"';
2445 } else {
2446 $title = '';
2447 $dimmed = '';
2449 return sprintf("<a href=\"%s:%s\" $dimmed title=\"$title\">%s</a>",
2450 obfuscate_text('mailto'), obfuscate_email($email),
2451 obfuscate_text($label));
2455 * This function is used to rebuild the <nolink> tag because some formats (PLAIN and WIKI)
2456 * will transform it to html entities
2458 * @param string $text Text to search for nolink tag in
2459 * @return string
2461 function rebuildnolinktag($text) {
2463 $text = preg_replace('/&lt;(\/*nolink)&gt;/i','<$1>',$text);
2465 return $text;
2469 * Prints a maintenance message from $CFG->maintenance_message or default if empty
2470 * @return void
2472 function print_maintenance_message() {
2473 global $CFG, $SITE, $PAGE, $OUTPUT;
2475 $PAGE->set_pagetype('maintenance-message');
2476 $PAGE->set_pagelayout('maintenance');
2477 $PAGE->set_title(strip_tags($SITE->fullname));
2478 $PAGE->set_heading($SITE->fullname);
2479 echo $OUTPUT->header();
2480 echo $OUTPUT->heading(get_string('sitemaintenance', 'admin'));
2481 if (isset($CFG->maintenance_message) and !html_is_blank($CFG->maintenance_message)) {
2482 echo $OUTPUT->box_start('maintenance_message generalbox boxwidthwide boxaligncenter');
2483 echo $CFG->maintenance_message;
2484 echo $OUTPUT->box_end();
2486 echo $OUTPUT->footer();
2487 die;
2491 * A class for tabs, Some code to print tabs
2493 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2494 * @package moodlecore
2496 class tabobject {
2498 * @var string
2500 var $id;
2501 var $link;
2502 var $text;
2504 * @var bool
2506 var $linkedwhenselected;
2509 * A constructor just because I like constructors
2511 * @param string $id
2512 * @param string $link
2513 * @param string $text
2514 * @param string $title
2515 * @param bool $linkedwhenselected
2517 function tabobject ($id, $link='', $text='', $title='', $linkedwhenselected=false) {
2518 $this->id = $id;
2519 $this->link = $link;
2520 $this->text = $text;
2521 $this->title = $title ? $title : $text;
2522 $this->linkedwhenselected = $linkedwhenselected;
2529 * Returns a string containing a nested list, suitable for formatting into tabs with CSS.
2531 * @global object
2532 * @param array $tabrows An array of rows where each row is an array of tab objects
2533 * @param string $selected The id of the selected tab (whatever row it's on)
2534 * @param array $inactive An array of ids of inactive tabs that are not selectable.
2535 * @param array $activated An array of ids of other tabs that are currently activated
2536 * @param bool $return If true output is returned rather then echo'd
2538 function print_tabs($tabrows, $selected=NULL, $inactive=NULL, $activated=NULL, $return=false) {
2539 global $CFG;
2541 /// $inactive must be an array
2542 if (!is_array($inactive)) {
2543 $inactive = array();
2546 /// $activated must be an array
2547 if (!is_array($activated)) {
2548 $activated = array();
2551 /// Convert the tab rows into a tree that's easier to process
2552 if (!$tree = convert_tabrows_to_tree($tabrows, $selected, $inactive, $activated)) {
2553 return false;
2556 /// Print out the current tree of tabs (this function is recursive)
2558 $output = convert_tree_to_html($tree);
2560 $output = "\n\n".'<div class="tabtree">'.$output.'</div><div class="clearer"> </div>'."\n\n";
2562 /// We're done!
2564 if ($return) {
2565 return $output;
2567 echo $output;
2571 * Converts a nested array tree into HTML ul:li [recursive]
2573 * @param array $tree A tree array to convert
2574 * @param int $row Used in identifying the iteration level and in ul classes
2575 * @return string HTML structure
2577 function convert_tree_to_html($tree, $row=0) {
2579 $str = "\n".'<ul class="tabrow'.$row.'">'."\n";
2581 $first = true;
2582 $count = count($tree);
2584 foreach ($tree as $tab) {
2585 $count--; // countdown to zero
2587 $liclass = '';
2589 if ($first && ($count == 0)) { // Just one in the row
2590 $liclass = 'first last';
2591 $first = false;
2592 } else if ($first) {
2593 $liclass = 'first';
2594 $first = false;
2595 } else if ($count == 0) {
2596 $liclass = 'last';
2599 if ((empty($tab->subtree)) && (!empty($tab->selected))) {
2600 $liclass .= (empty($liclass)) ? 'onerow' : ' onerow';
2603 if ($tab->inactive || $tab->active || $tab->selected) {
2604 if ($tab->selected) {
2605 $liclass .= (empty($liclass)) ? 'here selected' : ' here selected';
2606 } else if ($tab->active) {
2607 $liclass .= (empty($liclass)) ? 'here active' : ' here active';
2611 $str .= (!empty($liclass)) ? '<li class="'.$liclass.'">' : '<li>';
2613 if ($tab->inactive || $tab->active || ($tab->selected && !$tab->linkedwhenselected)) {
2614 // The a tag is used for styling
2615 $str .= '<a class="nolink"><span>'.$tab->text.'</span></a>';
2616 } else {
2617 $str .= '<a href="'.$tab->link.'" title="'.$tab->title.'"><span>'.$tab->text.'</span></a>';
2620 if (!empty($tab->subtree)) {
2621 $str .= convert_tree_to_html($tab->subtree, $row+1);
2622 } else if ($tab->selected) {
2623 $str .= '<div class="tabrow'.($row+1).' empty">&nbsp;</div>'."\n";
2626 $str .= ' </li>'."\n";
2628 $str .= '</ul>'."\n";
2630 return $str;
2634 * Convert nested tabrows to a nested array
2636 * @param array $tabrows A [nested] array of tab row objects
2637 * @param string $selected The tabrow to select (by id)
2638 * @param array $inactive An array of tabrow id's to make inactive
2639 * @param array $activated An array of tabrow id's to make active
2640 * @return array The nested array
2642 function convert_tabrows_to_tree($tabrows, $selected, $inactive, $activated) {
2644 /// Work backwards through the rows (bottom to top) collecting the tree as we go.
2646 $tabrows = array_reverse($tabrows);
2648 $subtree = array();
2650 foreach ($tabrows as $row) {
2651 $tree = array();
2653 foreach ($row as $tab) {
2654 $tab->inactive = in_array((string)$tab->id, $inactive);
2655 $tab->active = in_array((string)$tab->id, $activated);
2656 $tab->selected = (string)$tab->id == $selected;
2658 if ($tab->active || $tab->selected) {
2659 if ($subtree) {
2660 $tab->subtree = $subtree;
2663 $tree[] = $tab;
2665 $subtree = $tree;
2668 return $subtree;
2672 * Standard Debugging Function
2674 * Returns true if the current site debugging settings are equal or above specified level.
2675 * If passed a parameter it will emit a debugging notice similar to trigger_error(). The
2676 * routing of notices is controlled by $CFG->debugdisplay
2677 * eg use like this:
2679 * 1) debugging('a normal debug notice');
2680 * 2) debugging('something really picky', DEBUG_ALL);
2681 * 3) debugging('annoying debug message only for developers', DEBUG_DEVELOPER);
2682 * 4) if (debugging()) { perform extra debugging operations (do not use print or echo) }
2684 * In code blocks controlled by debugging() (such as example 4)
2685 * any output should be routed via debugging() itself, or the lower-level
2686 * trigger_error() or error_log(). Using echo or print will break XHTML
2687 * JS and HTTP headers.
2689 * It is also possible to define NO_DEBUG_DISPLAY which redirects the message to error_log.
2691 * @uses DEBUG_NORMAL
2692 * @param string $message a message to print
2693 * @param int $level the level at which this debugging statement should show
2694 * @param array $backtrace use different backtrace
2695 * @return bool
2697 function debugging($message = '', $level = DEBUG_NORMAL, $backtrace = null) {
2698 global $CFG, $USER, $UNITTEST;
2700 $forcedebug = false;
2701 if (!empty($CFG->debugusers)) {
2702 $debugusers = explode(',', $CFG->debugusers);
2703 $forcedebug = in_array($USER->id, $debugusers);
2706 if (!$forcedebug and (empty($CFG->debug) || $CFG->debug < $level)) {
2707 return false;
2710 if (!isset($CFG->debugdisplay)) {
2711 $CFG->debugdisplay = ini_get_bool('display_errors');
2714 if ($message) {
2715 if (!$backtrace) {
2716 $backtrace = debug_backtrace();
2718 $from = format_backtrace($backtrace, CLI_SCRIPT);
2719 if (!empty($UNITTEST->running)) {
2720 // When the unit tests are running, any call to trigger_error
2721 // is intercepted by the test framework and reported as an exception.
2722 // Therefore, we cannot use trigger_error during unit tests.
2723 // At the same time I do not think we should just discard those messages,
2724 // so displaying them on-screen seems like the only option. (MDL-20398)
2725 echo '<div class="notifytiny">' . $message . $from . '</div>';
2727 } else if (NO_DEBUG_DISPLAY) {
2728 // script does not want any errors or debugging in output,
2729 // we send the info to error log instead
2730 error_log('Debugging: ' . $message . $from);
2732 } else if ($forcedebug or $CFG->debugdisplay) {
2733 if (!defined('DEBUGGING_PRINTED')) {
2734 define('DEBUGGING_PRINTED', 1); // indicates we have printed something
2736 if (CLI_SCRIPT) {
2737 echo "++ $message ++\n$from";
2738 } else {
2739 echo '<div class="notifytiny">' . $message . $from . '</div>';
2742 } else {
2743 trigger_error($message . $from, E_USER_NOTICE);
2746 return true;
2750 * Outputs a HTML comment to the browser. This is used for those hard-to-debug
2751 * pages that use bits from many different files in very confusing ways (e.g. blocks).
2753 * <code>print_location_comment(__FILE__, __LINE__);</code>
2755 * @param string $file
2756 * @param integer $line
2757 * @param boolean $return Whether to return or print the comment
2758 * @return string|void Void unless true given as third parameter
2760 function print_location_comment($file, $line, $return = false)
2762 if ($return) {
2763 return "<!-- $file at line $line -->\n";
2764 } else {
2765 echo "<!-- $file at line $line -->\n";
2771 * @return boolean true if the current language is right-to-left (Hebrew, Arabic etc)
2773 function right_to_left() {
2774 return (get_string('thisdirection', 'langconfig') === 'rtl');
2779 * Returns swapped left<=>right if in RTL environment.
2780 * part of RTL support
2782 * @param string $align align to check
2783 * @return string
2785 function fix_align_rtl($align) {
2786 if (!right_to_left()) {
2787 return $align;
2789 if ($align=='left') { return 'right'; }
2790 if ($align=='right') { return 'left'; }
2791 return $align;
2796 * Returns true if the page is displayed in a popup window.
2797 * Gets the information from the URL parameter inpopup.
2799 * @todo Use a central function to create the popup calls all over Moodle and
2800 * In the moment only works with resources and probably questions.
2802 * @return boolean
2804 function is_in_popup() {
2805 $inpopup = optional_param('inpopup', '', PARAM_BOOL);
2807 return ($inpopup);
2811 * To use this class.
2812 * - construct
2813 * - call create (or use the 3rd param to the constructor)
2814 * - call update or update_full() or update() repeatedly
2816 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2817 * @package moodlecore
2819 class progress_bar {
2820 /** @var string html id */
2821 private $html_id;
2822 /** @var int total width */
2823 private $width;
2824 /** @var int last percentage printed */
2825 private $percent = 0;
2826 /** @var int time when last printed */
2827 private $lastupdate = 0;
2828 /** @var int when did we start printing this */
2829 private $time_start = 0;
2832 * Constructor
2834 * @param string $html_id
2835 * @param int $width
2836 * @param bool $autostart Default to false
2837 * @return void, prints JS code if $autostart true
2839 public function __construct($html_id = '', $width = 500, $autostart = false) {
2840 if (!empty($html_id)) {
2841 $this->html_id = $html_id;
2842 } else {
2843 $this->html_id = 'pbar_'.uniqid();
2846 $this->width = $width;
2848 if ($autostart){
2849 $this->create();
2854 * Create a new progress bar, this function will output html.
2856 * @return void Echo's output
2858 public function create() {
2859 $this->time_start = microtime(true);
2860 if (CLI_SCRIPT) {
2861 return; // temporary solution for cli scripts
2863 $htmlcode = <<<EOT
2864 <div style="text-align:center;width:{$this->width}px;clear:both;padding:0;margin:0 auto;">
2865 <h2 id="status_{$this->html_id}" style="text-align: center;margin:0 auto"></h2>
2866 <p id="time_{$this->html_id}"></p>
2867 <div id="bar_{$this->html_id}" style="border-style:solid;border-width:1px;width:500px;height:50px;">
2868 <div id="progress_{$this->html_id}"
2869 style="text-align:center;background:#FFCC66;width:4px;border:1px
2870 solid gray;height:38px; padding-top:10px;">&nbsp;<span id="pt_{$this->html_id}"></span>
2871 </div>
2872 </div>
2873 </div>
2874 EOT;
2875 flush();
2876 echo $htmlcode;
2877 flush();
2881 * Update the progress bar
2883 * @param int $percent from 1-100
2884 * @param string $msg
2885 * @return void Echo's output
2887 private function _update($percent, $msg) {
2888 if (empty($this->time_start)) {
2889 throw new coding_exception('You must call create() (or use the $autostart ' .
2890 'argument to the constructor) before you try updating the progress bar.');
2893 if (CLI_SCRIPT) {
2894 return; // temporary solution for cli scripts
2897 $es = $this->estimate($percent);
2899 if ($es === null) {
2900 // always do the first and last updates
2901 $es = "?";
2902 } else if ($es == 0) {
2903 // always do the last updates
2904 } else if ($this->lastupdate + 20 < time()) {
2905 // we must update otherwise browser would time out
2906 } else if (round($this->percent, 2) === round($percent, 2)) {
2907 // no significant change, no need to update anything
2908 return;
2911 $this->percent = $percent;
2912 $this->lastupdate = microtime(true);
2914 $w = ($this->percent/100) * $this->width;
2915 echo html_writer::script(js_writer::function_call('update_progress_bar', array($this->html_id, $w, $this->percent, $msg, $es)));
2916 flush();
2920 * Estimate how much time it is going to take.
2922 * @param int $curtime the time call this function
2923 * @param int $percent from 1-100
2924 * @return mixed Null (unknown), or int
2926 private function estimate($pt) {
2927 if ($this->lastupdate == 0) {
2928 return null;
2930 if ($pt < 0.00001) {
2931 return null; // we do not know yet how long it will take
2933 if ($pt > 99.99999) {
2934 return 0; // nearly done, right?
2936 $consumed = microtime(true) - $this->time_start;
2937 if ($consumed < 0.001) {
2938 return null;
2941 return (100 - $pt) * ($consumed / $pt);
2945 * Update progress bar according percent
2947 * @param int $percent from 1-100
2948 * @param string $msg the message needed to be shown
2950 public function update_full($percent, $msg) {
2951 $percent = max(min($percent, 100), 0);
2952 $this->_update($percent, $msg);
2956 * Update progress bar according the number of tasks
2958 * @param int $cur current task number
2959 * @param int $total total task number
2960 * @param string $msg message
2962 public function update($cur, $total, $msg) {
2963 $percent = ($cur / $total) * 100;
2964 $this->update_full($percent, $msg);
2968 * Restart the progress bar.
2970 public function restart() {
2971 $this->percent = 0;
2972 $this->lastupdate = 0;
2973 $this->time_start = 0;
2978 * Use this class from long operations where you want to output occasional information about
2979 * what is going on, but don't know if, or in what format, the output should be.
2981 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2982 * @package moodlecore
2984 abstract class progress_trace {
2986 * Ouput an progress message in whatever format.
2987 * @param string $message the message to output.
2988 * @param integer $depth indent depth for this message.
2990 abstract public function output($message, $depth = 0);
2993 * Called when the processing is finished.
2995 public function finished() {
3000 * This subclass of progress_trace does not ouput anything.
3002 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3003 * @package moodlecore
3005 class null_progress_trace extends progress_trace {
3007 * Does Nothing
3009 * @param string $message
3010 * @param int $depth
3011 * @return void Does Nothing
3013 public function output($message, $depth = 0) {
3018 * This subclass of progress_trace outputs to plain text.
3020 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3021 * @package moodlecore
3023 class text_progress_trace extends progress_trace {
3025 * Output the trace message
3027 * @param string $message
3028 * @param int $depth
3029 * @return void Output is echo'd
3031 public function output($message, $depth = 0) {
3032 echo str_repeat(' ', $depth), $message, "\n";
3033 flush();
3038 * This subclass of progress_trace outputs as HTML.
3040 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3041 * @package moodlecore
3043 class html_progress_trace extends progress_trace {
3045 * Output the trace message
3047 * @param string $message
3048 * @param int $depth
3049 * @return void Output is echo'd
3051 public function output($message, $depth = 0) {
3052 echo '<p>', str_repeat('&#160;&#160;', $depth), htmlspecialchars($message), "</p>\n";
3053 flush();
3058 * HTML List Progress Tree
3060 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3061 * @package moodlecore
3063 class html_list_progress_trace extends progress_trace {
3064 /** @var int */
3065 protected $currentdepth = -1;
3068 * Echo out the list
3070 * @param string $message The message to display
3071 * @param int $depth
3072 * @return void Output is echoed
3074 public function output($message, $depth = 0) {
3075 $samedepth = true;
3076 while ($this->currentdepth > $depth) {
3077 echo "</li>\n</ul>\n";
3078 $this->currentdepth -= 1;
3079 if ($this->currentdepth == $depth) {
3080 echo '<li>';
3082 $samedepth = false;
3084 while ($this->currentdepth < $depth) {
3085 echo "<ul>\n<li>";
3086 $this->currentdepth += 1;
3087 $samedepth = false;
3089 if ($samedepth) {
3090 echo "</li>\n<li>";
3092 echo htmlspecialchars($message);
3093 flush();
3097 * Called when the processing is finished.
3099 public function finished() {
3100 while ($this->currentdepth >= 0) {
3101 echo "</li>\n</ul>\n";
3102 $this->currentdepth -= 1;
3108 * Returns a localized sentence in the current language summarizing the current password policy
3110 * @todo this should be handled by a function/method in the language pack library once we have a support for it
3111 * @uses $CFG
3112 * @return string
3114 function print_password_policy() {
3115 global $CFG;
3117 $message = '';
3118 if (!empty($CFG->passwordpolicy)) {
3119 $messages = array();
3120 $messages[] = get_string('informminpasswordlength', 'auth', $CFG->minpasswordlength);
3121 if (!empty($CFG->minpassworddigits)) {
3122 $messages[] = get_string('informminpassworddigits', 'auth', $CFG->minpassworddigits);
3124 if (!empty($CFG->minpasswordlower)) {
3125 $messages[] = get_string('informminpasswordlower', 'auth', $CFG->minpasswordlower);
3127 if (!empty($CFG->minpasswordupper)) {
3128 $messages[] = get_string('informminpasswordupper', 'auth', $CFG->minpasswordupper);
3130 if (!empty($CFG->minpasswordnonalphanum)) {
3131 $messages[] = get_string('informminpasswordnonalphanum', 'auth', $CFG->minpasswordnonalphanum);
3134 $messages = join(', ', $messages); // this is ugly but we do not have anything better yet...
3135 $message = get_string('informpasswordpolicy', 'auth', $messages);
3137 return $message;