MDL-30995 Completion Fixedup some more PHP DOC issues
[moodle.git] / lib / weblib.php
blob7de357d4f5bfc11225cee7088ac5b4d9e746c611
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 if (is_array($val)) {
478 foreach ($val as $index => $value) {
479 $arr[] = rawurlencode($key.'['.$index.']')."=".rawurlencode($value);
481 } else {
482 $arr[] = rawurlencode($key)."=".rawurlencode($val);
485 if ($escaped) {
486 return implode('&amp;', $arr);
487 } else {
488 return implode('&', $arr);
493 * Shortcut for printing of encoded URL.
494 * @return string
496 public function __toString() {
497 return $this->out(true);
501 * Output url
503 * If you use the returned URL in HTML code, you want the escaped ampersands. If you use
504 * the returned URL in HTTP headers, you want $escaped=false.
506 * @param boolean $escaped Use &amp; as params separator instead of plain &
507 * @param array $overrideparams params to add to the output url, these override existing ones with the same name.
508 * @return string Resulting URL
510 public function out($escaped = true, array $overrideparams = null) {
511 if (!is_bool($escaped)) {
512 debugging('Escape parameter must be of type boolean, '.gettype($escaped).' given instead.');
515 $uri = $this->out_omit_querystring().$this->slashargument;
517 $querystring = $this->get_query_string($escaped, $overrideparams);
518 if ($querystring !== '') {
519 $uri .= '?' . $querystring;
521 if (!is_null($this->anchor)) {
522 $uri .= '#'.$this->anchor;
525 return $uri;
529 * Returns url without parameters, everything before '?'.
531 * @param bool $includeanchor if {@link self::anchor} is defined, should it be returned?
532 * @return string
534 public function out_omit_querystring($includeanchor = false) {
536 $uri = $this->scheme ? $this->scheme.':'.((strtolower($this->scheme) == 'mailto') ? '':'//'): '';
537 $uri .= $this->user ? $this->user.($this->pass? ':'.$this->pass:'').'@':'';
538 $uri .= $this->host ? $this->host : '';
539 $uri .= $this->port ? ':'.$this->port : '';
540 $uri .= $this->path ? $this->path : '';
541 if ($includeanchor and !is_null($this->anchor)) {
542 $uri .= '#' . $this->anchor;
545 return $uri;
549 * Compares this moodle_url with another
550 * See documentation of constants for an explanation of the comparison flags.
551 * @param moodle_url $url The moodle_url object to compare
552 * @param int $matchtype The type of comparison (URL_MATCH_BASE, URL_MATCH_PARAMS, URL_MATCH_EXACT)
553 * @return boolean
555 public function compare(moodle_url $url, $matchtype = URL_MATCH_EXACT) {
557 $baseself = $this->out_omit_querystring();
558 $baseother = $url->out_omit_querystring();
560 // Append index.php if there is no specific file
561 if (substr($baseself,-1)=='/') {
562 $baseself .= 'index.php';
564 if (substr($baseother,-1)=='/') {
565 $baseother .= 'index.php';
568 // Compare the two base URLs
569 if ($baseself != $baseother) {
570 return false;
573 if ($matchtype == URL_MATCH_BASE) {
574 return true;
577 $urlparams = $url->params();
578 foreach ($this->params() as $param => $value) {
579 if ($param == 'sesskey') {
580 continue;
582 if (!array_key_exists($param, $urlparams) || $urlparams[$param] != $value) {
583 return false;
587 if ($matchtype == URL_MATCH_PARAMS) {
588 return true;
591 foreach ($urlparams as $param => $value) {
592 if ($param == 'sesskey') {
593 continue;
595 if (!array_key_exists($param, $this->params()) || $this->param($param) != $value) {
596 return false;
600 return true;
604 * Sets the anchor for the URI (the bit after the hash)
605 * @param string $anchor null means remove previous
607 public function set_anchor($anchor) {
608 if (is_null($anchor)) {
609 // remove
610 $this->anchor = null;
611 } else if ($anchor === '') {
612 // special case, used as empty link
613 $this->anchor = '';
614 } else if (preg_match('|[a-zA-Z\_\:][a-zA-Z0-9\_\-\.\:]*|', $anchor)) {
615 // Match the anchor against the NMTOKEN spec
616 $this->anchor = $anchor;
617 } else {
618 // bad luck, no valid anchor found
619 $this->anchor = null;
624 * Sets the url slashargument value
625 * @param string $path usually file path
626 * @param string $parameter name of page parameter if slasharguments not supported
627 * @param bool $supported usually null, then it depends on $CFG->slasharguments, use true or false for other servers
628 * @return void
630 public function set_slashargument($path, $parameter = 'file', $supported = NULL) {
631 global $CFG;
632 if (is_null($supported)) {
633 $supported = $CFG->slasharguments;
636 if ($supported) {
637 $parts = explode('/', $path);
638 $parts = array_map('rawurlencode', $parts);
639 $path = implode('/', $parts);
640 $this->slashargument = $path;
641 unset($this->params[$parameter]);
643 } else {
644 $this->slashargument = '';
645 $this->params[$parameter] = $path;
649 // == static factory methods ==
652 * General moodle file url.
653 * @param string $urlbase the script serving the file
654 * @param string $path
655 * @param bool $forcedownload
656 * @return moodle_url
658 public static function make_file_url($urlbase, $path, $forcedownload = false) {
659 global $CFG;
661 $params = array();
662 if ($forcedownload) {
663 $params['forcedownload'] = 1;
666 $url = new moodle_url($urlbase, $params);
667 $url->set_slashargument($path);
669 return $url;
673 * Factory method for creation of url pointing to plugin file.
674 * Please note this method can be used only from the plugins to
675 * create urls of own files, it must not be used outside of plugins!
676 * @param int $contextid
677 * @param string $component
678 * @param string $area
679 * @param int $itemid
680 * @param string $pathname
681 * @param string $filename
682 * @param bool $forcedownload
683 * @return moodle_url
685 public static function make_pluginfile_url($contextid, $component, $area, $itemid, $pathname, $filename, $forcedownload = false) {
686 global $CFG;
687 $urlbase = "$CFG->httpswwwroot/pluginfile.php";
688 if ($itemid === NULL) {
689 return self::make_file_url($urlbase, "/$contextid/$component/$area".$pathname.$filename, $forcedownload);
690 } else {
691 return self::make_file_url($urlbase, "/$contextid/$component/$area/$itemid".$pathname.$filename, $forcedownload);
696 * Factory method for creation of url pointing to draft
697 * file of current user.
698 * @param int $draftid draft item id
699 * @param string $pathname
700 * @param string $filename
701 * @param bool $forcedownload
702 * @return moodle_url
704 public static function make_draftfile_url($draftid, $pathname, $filename, $forcedownload = false) {
705 global $CFG, $USER;
706 $urlbase = "$CFG->httpswwwroot/draftfile.php";
707 $context = get_context_instance(CONTEXT_USER, $USER->id);
709 return self::make_file_url($urlbase, "/$context->id/user/draft/$draftid".$pathname.$filename, $forcedownload);
713 * Factory method for creating of links to legacy
714 * course files.
715 * @param int $courseid
716 * @param string $filepath
717 * @param bool $forcedownload
718 * @return moodle_url
720 public static function make_legacyfile_url($courseid, $filepath, $forcedownload = false) {
721 global $CFG;
723 $urlbase = "$CFG->wwwroot/file.php";
724 return self::make_file_url($urlbase, '/'.$courseid.'/'.$filepath, $forcedownload);
728 * Returns URL a relative path from $CFG->wwwroot
730 * Can be used for passing around urls with the wwwroot stripped
732 * @param boolean $escaped Use &amp; as params separator instead of plain &
733 * @param array $overrideparams params to add to the output url, these override existing ones with the same name.
734 * @return string Resulting URL
735 * @throws coding_exception if called on a non-local url
737 public function out_as_local_url($escaped = true, array $overrideparams = null) {
738 global $CFG;
740 $url = $this->out($escaped, $overrideparams);
742 if (strpos($url, $CFG->wwwroot) !== 0) {
743 throw new coding_exception('out_as_local_url called on a non-local URL');
746 return str_replace($CFG->wwwroot, '', $url);
751 * Determine if there is data waiting to be processed from a form
753 * Used on most forms in Moodle to check for data
754 * Returns the data as an object, if it's found.
755 * This object can be used in foreach loops without
756 * casting because it's cast to (array) automatically
758 * Checks that submitted POST data exists and returns it as object.
760 * @uses $_POST
761 * @return mixed false or object
763 function data_submitted() {
765 if (empty($_POST)) {
766 return false;
767 } else {
768 return (object)fix_utf8($_POST);
773 * Given some normal text this function will break up any
774 * long words to a given size by inserting the given character
776 * It's multibyte savvy and doesn't change anything inside html tags.
778 * @param string $string the string to be modified
779 * @param int $maxsize maximum length of the string to be returned
780 * @param string $cutchar the string used to represent word breaks
781 * @return string
783 function break_up_long_words($string, $maxsize=20, $cutchar=' ') {
785 /// First of all, save all the tags inside the text to skip them
786 $tags = array();
787 filter_save_tags($string,$tags);
789 /// Process the string adding the cut when necessary
790 $output = '';
791 $length = textlib::strlen($string);
792 $wordlength = 0;
794 for ($i=0; $i<$length; $i++) {
795 $char = textlib::substr($string, $i, 1);
796 if ($char == ' ' or $char == "\t" or $char == "\n" or $char == "\r" or $char == "<" or $char == ">") {
797 $wordlength = 0;
798 } else {
799 $wordlength++;
800 if ($wordlength > $maxsize) {
801 $output .= $cutchar;
802 $wordlength = 0;
805 $output .= $char;
808 /// Finally load the tags back again
809 if (!empty($tags)) {
810 $output = str_replace(array_keys($tags), $tags, $output);
813 return $output;
817 * Try and close the current window using JavaScript, either immediately, or after a delay.
819 * Echo's out the resulting XHTML & javascript
821 * @global object
822 * @global object
823 * @param integer $delay a delay in seconds before closing the window. Default 0.
824 * @param boolean $reloadopener if true, we will see if this window was a pop-up, and try
825 * to reload the parent window before this one closes.
827 function close_window($delay = 0, $reloadopener = false) {
828 global $PAGE, $OUTPUT;
830 if (!$PAGE->headerprinted) {
831 $PAGE->set_title(get_string('closewindow'));
832 echo $OUTPUT->header();
833 } else {
834 $OUTPUT->container_end_all(false);
837 if ($reloadopener) {
838 // Trigger the reload immediately, even if the reload is after a delay.
839 $PAGE->requires->js_function_call('window.opener.location.reload', array(true));
841 $OUTPUT->notification(get_string('windowclosing'), 'notifysuccess');
843 $PAGE->requires->js_function_call('close_window', array(new stdClass()), false, $delay);
845 echo $OUTPUT->footer();
846 exit;
850 * Returns a string containing a link to the user documentation for the current
851 * page. Also contains an icon by default. Shown to teachers and admin only.
853 * @global object
854 * @global object
855 * @param string $text The text to be displayed for the link
856 * @param string $iconpath The path to the icon to be displayed
857 * @return string The link to user documentation for this current page
859 function page_doc_link($text='') {
860 global $CFG, $PAGE, $OUTPUT;
862 if (empty($CFG->docroot) || during_initial_install()) {
863 return '';
865 if (!has_capability('moodle/site:doclinks', $PAGE->context)) {
866 return '';
869 $path = $PAGE->docspath;
870 if (!$path) {
871 return '';
873 return $OUTPUT->doc_link($path, $text);
878 * Validates an email to make sure it makes sense.
880 * @param string $address The email address to validate.
881 * @return boolean
883 function validate_email($address) {
885 return (preg_match('#^[-!\#$%&\'*+\\/0-9=?A-Z^_`a-z{|}~]+'.
886 '(\.[-!\#$%&\'*+\\/0-9=?A-Z^_`a-z{|}~]+)*'.
887 '@'.
888 '[-!\#$%&\'*+\\/0-9=?A-Z^_`a-z{|}~]+\.'.
889 '[-!\#$%&\'*+\\./0-9=?A-Z^_`a-z{|}~]+$#',
890 $address));
894 * Extracts file argument either from file parameter or PATH_INFO
895 * Note: $scriptname parameter is not needed anymore
897 * @global string
898 * @uses $_SERVER
899 * @uses PARAM_PATH
900 * @return string file path (only safe characters)
902 function get_file_argument() {
903 global $SCRIPT;
905 $relativepath = optional_param('file', FALSE, PARAM_PATH);
907 if ($relativepath !== false and $relativepath !== '') {
908 return $relativepath;
910 $relativepath = false;
912 // then try extract file from the slasharguments
913 if (stripos($_SERVER['SERVER_SOFTWARE'], 'iis') !== false) {
914 // NOTE: ISS tends to convert all file paths to single byte DOS encoding,
915 // we can not use other methods because they break unicode chars,
916 // the only way is to use URL rewriting
917 if (isset($_SERVER['PATH_INFO']) and $_SERVER['PATH_INFO'] !== '') {
918 // check that PATH_INFO works == must not contain the script name
919 if (strpos($_SERVER['PATH_INFO'], $SCRIPT) === false) {
920 $relativepath = clean_param(urldecode($_SERVER['PATH_INFO']), PARAM_PATH);
923 } else {
924 // all other apache-like servers depend on PATH_INFO
925 if (isset($_SERVER['PATH_INFO'])) {
926 if (isset($_SERVER['SCRIPT_NAME']) and strpos($_SERVER['PATH_INFO'], $_SERVER['SCRIPT_NAME']) === 0) {
927 $relativepath = substr($_SERVER['PATH_INFO'], strlen($_SERVER['SCRIPT_NAME']));
928 } else {
929 $relativepath = $_SERVER['PATH_INFO'];
931 $relativepath = clean_param($relativepath, PARAM_PATH);
936 return $relativepath;
940 * Just returns an array of text formats suitable for a popup menu
942 * @uses FORMAT_MOODLE
943 * @uses FORMAT_HTML
944 * @uses FORMAT_PLAIN
945 * @uses FORMAT_MARKDOWN
946 * @return array
948 function format_text_menu() {
949 return array (FORMAT_MOODLE => get_string('formattext'),
950 FORMAT_HTML => get_string('formathtml'),
951 FORMAT_PLAIN => get_string('formatplain'),
952 FORMAT_MARKDOWN => get_string('formatmarkdown'));
956 * Given text in a variety of format codings, this function returns
957 * the text as safe HTML.
959 * This function should mainly be used for long strings like posts,
960 * answers, glossary items etc. For short strings @see format_string().
962 * <pre>
963 * Options:
964 * trusted : If true the string won't be cleaned. Default false required noclean=true.
965 * noclean : If true the string won't be cleaned. Default false required trusted=true.
966 * nocache : If true the strign will not be cached and will be formatted every call. Default false.
967 * filter : If true the string will be run through applicable filters as well. Default true.
968 * para : If true then the returned string will be wrapped in div tags. Default true.
969 * newlines : If true then lines newline breaks will be converted to HTML newline breaks. Default true.
970 * context : The context that will be used for filtering.
971 * overflowdiv : If set to true the formatted text will be encased in a div
972 * with the class no-overflow before being returned. Default false.
973 * allowid : If true then id attributes will not be removed, even when
974 * using htmlpurifier. Default false.
975 * </pre>
977 * @todo Finish documenting this function
979 * @staticvar array $croncache
980 * @param string $text The text to be formatted. This is raw text originally from user input.
981 * @param int $format Identifier of the text format to be used
982 * [FORMAT_MOODLE, FORMAT_HTML, FORMAT_PLAIN, FORMAT_MARKDOWN]
983 * @param object/array $options text formatting options
984 * @param int $courseid_do_not_use deprecated course id, use context option instead
985 * @return string
987 function format_text($text, $format = FORMAT_MOODLE, $options = NULL, $courseid_do_not_use = NULL) {
988 global $CFG, $COURSE, $DB, $PAGE;
989 static $croncache = array();
991 if ($text === '' || is_null($text)) {
992 return ''; // no need to do any filters and cleaning
995 $options = (array)$options; // detach object, we can not modify it
997 if (!isset($options['trusted'])) {
998 $options['trusted'] = false;
1000 if (!isset($options['noclean'])) {
1001 if ($options['trusted'] and trusttext_active()) {
1002 // no cleaning if text trusted and noclean not specified
1003 $options['noclean'] = true;
1004 } else {
1005 $options['noclean'] = false;
1008 if (!isset($options['nocache'])) {
1009 $options['nocache'] = false;
1011 if (!isset($options['filter'])) {
1012 $options['filter'] = true;
1014 if (!isset($options['para'])) {
1015 $options['para'] = true;
1017 if (!isset($options['newlines'])) {
1018 $options['newlines'] = true;
1020 if (!isset($options['overflowdiv'])) {
1021 $options['overflowdiv'] = false;
1024 // Calculate best context
1025 if (empty($CFG->version) or $CFG->version < 2010072800 or during_initial_install()) {
1026 // do not filter anything during installation or before upgrade completes
1027 $context = null;
1029 } else if (isset($options['context'])) { // first by explicit passed context option
1030 if (is_object($options['context'])) {
1031 $context = $options['context'];
1032 } else {
1033 $context = get_context_instance_by_id($options['context']);
1035 } else if ($courseid_do_not_use) {
1036 // legacy courseid
1037 $context = get_context_instance(CONTEXT_COURSE, $courseid_do_not_use);
1038 } else {
1039 // fallback to $PAGE->context this may be problematic in CLI and other non-standard pages :-(
1040 $context = $PAGE->context;
1043 if (!$context) {
1044 // either install/upgrade or something has gone really wrong because context does not exist (yet?)
1045 $options['nocache'] = true;
1046 $options['filter'] = false;
1049 if ($options['filter']) {
1050 $filtermanager = filter_manager::instance();
1051 } else {
1052 $filtermanager = new null_filter_manager();
1055 if (!empty($CFG->cachetext) and empty($options['nocache'])) {
1056 $hashstr = $text.'-'.$filtermanager->text_filtering_hash($context).'-'.$context->id.'-'.current_language().'-'.
1057 (int)$format.(int)$options['trusted'].(int)$options['noclean'].
1058 (int)$options['para'].(int)$options['newlines'];
1060 $time = time() - $CFG->cachetext;
1061 $md5key = md5($hashstr);
1062 if (CLI_SCRIPT) {
1063 if (isset($croncache[$md5key])) {
1064 return $croncache[$md5key];
1068 if ($oldcacheitem = $DB->get_record('cache_text', array('md5key'=>$md5key), '*', IGNORE_MULTIPLE)) {
1069 if ($oldcacheitem->timemodified >= $time) {
1070 if (CLI_SCRIPT) {
1071 if (count($croncache) > 150) {
1072 reset($croncache);
1073 $key = key($croncache);
1074 unset($croncache[$key]);
1076 $croncache[$md5key] = $oldcacheitem->formattedtext;
1078 return $oldcacheitem->formattedtext;
1083 switch ($format) {
1084 case FORMAT_HTML:
1085 if (!$options['noclean']) {
1086 $text = clean_text($text, FORMAT_HTML, $options);
1088 $text = $filtermanager->filter_text($text, $context, array('originalformat' => FORMAT_HTML, 'noclean' => $options['noclean']));
1089 break;
1091 case FORMAT_PLAIN:
1092 $text = s($text); // cleans dangerous JS
1093 $text = rebuildnolinktag($text);
1094 $text = str_replace(' ', '&nbsp; ', $text);
1095 $text = nl2br($text);
1096 break;
1098 case FORMAT_WIKI:
1099 // this format is deprecated
1100 $text = '<p>NOTICE: Wiki-like formatting has been removed from Moodle. You should not be seeing
1101 this message as all texts should have been converted to Markdown format instead.
1102 Please post a bug report to http://moodle.org/bugs with information about where you
1103 saw this message.</p>'.s($text);
1104 break;
1106 case FORMAT_MARKDOWN:
1107 $text = markdown_to_html($text);
1108 if (!$options['noclean']) {
1109 $text = clean_text($text, FORMAT_HTML, $options);
1111 $text = $filtermanager->filter_text($text, $context, array('originalformat' => FORMAT_MARKDOWN, 'noclean' => $options['noclean']));
1112 break;
1114 default: // FORMAT_MOODLE or anything else
1115 $text = text_to_html($text, null, $options['para'], $options['newlines']);
1116 if (!$options['noclean']) {
1117 $text = clean_text($text, FORMAT_HTML, $options);
1119 $text = $filtermanager->filter_text($text, $context, array('originalformat' => $format, 'noclean' => $options['noclean']));
1120 break;
1122 if ($options['filter']) {
1123 // at this point there should not be any draftfile links any more,
1124 // this happens when developers forget to post process the text.
1125 // The only potential problem is that somebody might try to format
1126 // the text before storing into database which would be itself big bug.
1127 $text = str_replace("\"$CFG->httpswwwroot/draftfile.php", "\"$CFG->httpswwwroot/brokenfile.php#", $text);
1130 // Warn people that we have removed this old mechanism, just in case they
1131 // were stupid enough to rely on it.
1132 if (isset($CFG->currenttextiscacheable)) {
1133 debugging('Once upon a time, Moodle had a truly evil use of global variables ' .
1134 'called $CFG->currenttextiscacheable. The good news is that this no ' .
1135 'longer exists. The bad news is that you seem to be using a filter that '.
1136 'relies on it. Please seek out and destroy that filter code.', DEBUG_DEVELOPER);
1139 if (!empty($options['overflowdiv'])) {
1140 $text = html_writer::tag('div', $text, array('class'=>'no-overflow'));
1143 if (empty($options['nocache']) and !empty($CFG->cachetext)) {
1144 if (CLI_SCRIPT) {
1145 // special static cron cache - no need to store it in db if its not already there
1146 if (count($croncache) > 150) {
1147 reset($croncache);
1148 $key = key($croncache);
1149 unset($croncache[$key]);
1151 $croncache[$md5key] = $text;
1152 return $text;
1155 $newcacheitem = new stdClass();
1156 $newcacheitem->md5key = $md5key;
1157 $newcacheitem->formattedtext = $text;
1158 $newcacheitem->timemodified = time();
1159 if ($oldcacheitem) { // See bug 4677 for discussion
1160 $newcacheitem->id = $oldcacheitem->id;
1161 try {
1162 $DB->update_record('cache_text', $newcacheitem); // Update existing record in the cache table
1163 } catch (dml_exception $e) {
1164 // It's unlikely that the cron cache cleaner could have
1165 // deleted this entry in the meantime, as it allows
1166 // some extra time to cover these cases.
1168 } else {
1169 try {
1170 $DB->insert_record('cache_text', $newcacheitem); // Insert a new record in the cache table
1171 } catch (dml_exception $e) {
1172 // Again, it's possible that another user has caused this
1173 // record to be created already in the time that it took
1174 // to traverse this function. That's OK too, as the
1175 // call above handles duplicate entries, and eventually
1176 // the cron cleaner will delete them.
1181 return $text;
1185 * Resets all data related to filters, called during upgrade or when filter settings change.
1187 * @global object
1188 * @global object
1189 * @return void
1191 function reset_text_filters_cache() {
1192 global $CFG, $DB;
1194 $DB->delete_records('cache_text');
1195 $purifdir = $CFG->cachedir.'/htmlpurifier';
1196 remove_dir($purifdir, true);
1200 * Given a simple string, this function returns the string
1201 * processed by enabled string filters if $CFG->filterall is enabled
1203 * This function should be used to print short strings (non html) that
1204 * need filter processing e.g. activity titles, post subjects,
1205 * glossary concepts.
1207 * @staticvar bool $strcache
1208 * @param string $string The string to be filtered. Should be plain text, expect
1209 * possibly for multilang tags.
1210 * @param boolean $striplinks To strip any link in the result text.
1211 Moodle 1.8 default changed from false to true! MDL-8713
1212 * @param array $options options array/object or courseid
1213 * @return string
1215 function format_string($string, $striplinks = true, $options = NULL) {
1216 global $CFG, $COURSE, $PAGE;
1218 //We'll use a in-memory cache here to speed up repeated strings
1219 static $strcache = false;
1221 if (empty($CFG->version) or $CFG->version < 2010072800 or during_initial_install()) {
1222 // do not filter anything during installation or before upgrade completes
1223 return $string = strip_tags($string);
1226 if ($strcache === false or count($strcache) > 2000) { // this number might need some tuning to limit memory usage in cron
1227 $strcache = array();
1230 if (is_numeric($options)) {
1231 // legacy courseid usage
1232 $options = array('context'=>get_context_instance(CONTEXT_COURSE, $options));
1233 } else {
1234 $options = (array)$options; // detach object, we can not modify it
1237 if (empty($options['context'])) {
1238 // fallback to $PAGE->context this may be problematic in CLI and other non-standard pages :-(
1239 $options['context'] = $PAGE->context;
1240 } else if (is_numeric($options['context'])) {
1241 $options['context'] = get_context_instance_by_id($options['context']);
1244 if (!$options['context']) {
1245 // we did not find any context? weird
1246 return $string = strip_tags($string);
1249 //Calculate md5
1250 $md5 = md5($string.'<+>'.$striplinks.'<+>'.$options['context']->id.'<+>'.current_language());
1252 //Fetch from cache if possible
1253 if (isset($strcache[$md5])) {
1254 return $strcache[$md5];
1257 // First replace all ampersands not followed by html entity code
1258 // Regular expression moved to its own method for easier unit testing
1259 $string = replace_ampersands_not_followed_by_entity($string);
1261 if (!empty($CFG->filterall)) {
1262 $string = filter_manager::instance()->filter_string($string, $options['context']);
1265 // If the site requires it, strip ALL tags from this string
1266 if (!empty($CFG->formatstringstriptags)) {
1267 $string = str_replace(array('<', '>'), array('&lt;', '&gt;'), strip_tags($string));
1269 } else {
1270 // Otherwise strip just links if that is required (default)
1271 if ($striplinks) { //strip links in string
1272 $string = strip_links($string);
1274 $string = clean_text($string);
1277 //Store to cache
1278 $strcache[$md5] = $string;
1280 return $string;
1284 * Given a string, performs a negative lookahead looking for any ampersand character
1285 * that is not followed by a proper HTML entity. If any is found, it is replaced
1286 * by &amp;. The string is then returned.
1288 * @param string $string
1289 * @return string
1291 function replace_ampersands_not_followed_by_entity($string) {
1292 return preg_replace("/\&(?![a-zA-Z0-9#]{1,8};)/", "&amp;", $string);
1296 * Given a string, replaces all <a>.*</a> by .* and returns the string.
1298 * @param string $string
1299 * @return string
1301 function strip_links($string) {
1302 return preg_replace('/(<a\s[^>]+?>)(.+?)(<\/a>)/is','$2',$string);
1306 * This expression turns links into something nice in a text format. (Russell Jungwirth)
1308 * @param string $string
1309 * @return string
1311 function wikify_links($string) {
1312 return preg_replace('~(<a [^<]*href=["|\']?([^ "\']*)["|\']?[^>]*>([^<]*)</a>)~i','$3 [ $2 ]', $string);
1316 * Given text in a variety of format codings, this function returns
1317 * the text as plain text suitable for plain email.
1319 * @uses FORMAT_MOODLE
1320 * @uses FORMAT_HTML
1321 * @uses FORMAT_PLAIN
1322 * @uses FORMAT_WIKI
1323 * @uses FORMAT_MARKDOWN
1324 * @param string $text The text to be formatted. This is raw text originally from user input.
1325 * @param int $format Identifier of the text format to be used
1326 * [FORMAT_MOODLE, FORMAT_HTML, FORMAT_PLAIN, FORMAT_WIKI, FORMAT_MARKDOWN]
1327 * @return string
1329 function format_text_email($text, $format) {
1331 switch ($format) {
1333 case FORMAT_PLAIN:
1334 return $text;
1335 break;
1337 case FORMAT_WIKI:
1338 // there should not be any of these any more!
1339 $text = wikify_links($text);
1340 return strtr(strip_tags($text), array_flip(get_html_translation_table(HTML_ENTITIES)));
1341 break;
1343 case FORMAT_HTML:
1344 return html_to_text($text);
1345 break;
1347 case FORMAT_MOODLE:
1348 case FORMAT_MARKDOWN:
1349 default:
1350 $text = wikify_links($text);
1351 return strtr(strip_tags($text), array_flip(get_html_translation_table(HTML_ENTITIES)));
1352 break;
1357 * Formats activity intro text
1359 * @global object
1360 * @uses CONTEXT_MODULE
1361 * @param string $module name of module
1362 * @param object $activity instance of activity
1363 * @param int $cmid course module id
1364 * @param bool $filter filter resulting html text
1365 * @return text
1367 function format_module_intro($module, $activity, $cmid, $filter=true) {
1368 global $CFG;
1369 require_once("$CFG->libdir/filelib.php");
1370 $context = get_context_instance(CONTEXT_MODULE, $cmid);
1371 $options = array('noclean'=>true, 'para'=>false, 'filter'=>$filter, 'context'=>$context, 'overflowdiv'=>true);
1372 $intro = file_rewrite_pluginfile_urls($activity->intro, 'pluginfile.php', $context->id, 'mod_'.$module, 'intro', null);
1373 return trim(format_text($intro, $activity->introformat, $options, null));
1377 * Legacy function, used for cleaning of old forum and glossary text only.
1379 * @global object
1380 * @param string $text text that may contain legacy TRUSTTEXT marker
1381 * @return text without legacy TRUSTTEXT marker
1383 function trusttext_strip($text) {
1384 while (true) { //removing nested TRUSTTEXT
1385 $orig = $text;
1386 $text = str_replace('#####TRUSTTEXT#####', '', $text);
1387 if (strcmp($orig, $text) === 0) {
1388 return $text;
1394 * Must be called before editing of all texts
1395 * with trust flag. Removes all XSS nasties
1396 * from texts stored in database if needed.
1398 * @param object $object data object with xxx, xxxformat and xxxtrust fields
1399 * @param string $field name of text field
1400 * @param object $context active context
1401 * @return object updated $object
1403 function trusttext_pre_edit($object, $field, $context) {
1404 $trustfield = $field.'trust';
1405 $formatfield = $field.'format';
1407 if (!$object->$trustfield or !trusttext_trusted($context)) {
1408 $object->$field = clean_text($object->$field, $object->$formatfield);
1411 return $object;
1415 * Is current user trusted to enter no dangerous XSS in this context?
1417 * Please note the user must be in fact trusted everywhere on this server!!
1419 * @param object $context
1420 * @return bool true if user trusted
1422 function trusttext_trusted($context) {
1423 return (trusttext_active() and has_capability('moodle/site:trustcontent', $context));
1427 * Is trusttext feature active?
1429 * @return bool
1431 function trusttext_active() {
1432 global $CFG;
1434 return !empty($CFG->enabletrusttext);
1438 * Given raw text (eg typed in by a user), this function cleans it up
1439 * and removes any nasty tags that could mess up Moodle pages through XSS attacks.
1441 * The result must be used as a HTML text fragment, this function can not cleanup random
1442 * parts of html tags such as url or src attributes.
1444 * NOTE: the format parameter was deprecated because we can safely clean only HTML.
1446 * @param string $text The text to be cleaned
1447 * @param int|string $format deprecated parameter, should always contain FORMAT_HTML or FORMAT_MOODLE
1448 * @param array $options Array of options; currently only option supported is 'allowid' (if true,
1449 * does not remove id attributes when cleaning)
1450 * @return string The cleaned up text
1452 function clean_text($text, $format = FORMAT_HTML, $options = array()) {
1453 if (empty($text) or is_numeric($text)) {
1454 return (string)$text;
1457 if ($format != FORMAT_HTML and $format != FORMAT_HTML) {
1458 // TODO: we need to standardise cleanup of text when loading it into editor first
1459 //debugging('clean_text() is designed to work only with html');
1462 if ($format == FORMAT_PLAIN) {
1463 return $text;
1466 $text = purify_html($text, $options);
1468 // Originally we tried to neutralise some script events here, it was a wrong approach because
1469 // it was trivial to work around that (for example using style based XSS exploits).
1470 // We must not give false sense of security here - all developers MUST understand how to use
1471 // rawurlencode(), htmlentities(), htmlspecialchars(), p(), s(), moodle_url, html_writer and friends!!!
1473 return $text;
1477 * KSES replacement cleaning function - uses HTML Purifier.
1479 * @param string $text The (X)HTML string to purify
1480 * @param array $options Array of options; currently only option supported is 'allowid' (if set,
1481 * does not remove id attributes when cleaning)
1482 * @return string
1484 function purify_html($text, $options = array()) {
1485 global $CFG;
1487 $type = !empty($options['allowid']) ? 'allowid' : 'normal';
1488 static $purifiers = array();
1489 if (empty($purifiers[$type])) {
1491 // make sure the serializer dir exists, it should be fine if it disappears later during cache reset
1492 $cachedir = $CFG->cachedir.'/htmlpurifier';
1493 check_dir_exists($cachedir);
1495 require_once $CFG->libdir.'/htmlpurifier/HTMLPurifier.safe-includes.php';
1496 $config = HTMLPurifier_Config::createDefault();
1498 $config->set('HTML.DefinitionID', 'moodlehtml');
1499 $config->set('HTML.DefinitionRev', 2);
1500 $config->set('Cache.SerializerPath', $cachedir);
1501 $config->set('Cache.SerializerPermissions', $CFG->directorypermissions);
1502 $config->set('Core.NormalizeNewlines', false);
1503 $config->set('Core.ConvertDocumentToFragment', true);
1504 $config->set('Core.Encoding', 'UTF-8');
1505 $config->set('HTML.Doctype', 'XHTML 1.0 Transitional');
1506 $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));
1507 $config->set('Attr.AllowedFrameTargets', array('_blank'));
1509 if (!empty($CFG->allowobjectembed)) {
1510 $config->set('HTML.SafeObject', true);
1511 $config->set('Output.FlashCompat', true);
1512 $config->set('HTML.SafeEmbed', true);
1515 if ($type === 'allowid') {
1516 $config->set('Attr.EnableID', true);
1519 if ($def = $config->maybeGetRawHTMLDefinition()) {
1520 $def->addElement('nolink', 'Block', 'Flow', array()); // skip our filters inside
1521 $def->addElement('tex', 'Inline', 'Inline', array()); // tex syntax, equivalent to $$xx$$
1522 $def->addElement('algebra', 'Inline', 'Inline', array()); // algebra syntax, equivalent to @@xx@@
1523 $def->addElement('lang', 'Block', 'Flow', array(), array('lang'=>'CDATA')); // old and future style multilang - only our hacked lang attribute
1524 $def->addAttribute('span', 'xxxlang', 'CDATA'); // current problematic multilang
1527 $purifier = new HTMLPurifier($config);
1528 $purifiers[$type] = $purifier;
1529 } else {
1530 $purifier = $purifiers[$type];
1533 $multilang = (strpos($text, 'class="multilang"') !== false);
1535 if ($multilang) {
1536 $text = preg_replace('/<span(\s+lang="([a-zA-Z0-9_-]+)"|\s+class="multilang"){2}\s*>/', '<span xxxlang="${2}">', $text);
1538 $text = $purifier->purify($text);
1539 if ($multilang) {
1540 $text = preg_replace('/<span xxxlang="([a-zA-Z0-9_-]+)">/', '<span lang="${1}" class="multilang">', $text);
1543 return $text;
1547 * Given plain text, makes it into HTML as nicely as possible.
1548 * May contain HTML tags already
1550 * Do not abuse this function. It is intended as lower level formatting feature used
1551 * by {@see format_text()} to convert FORMAT_MOODLE to HTML. You are supposed
1552 * to call format_text() in most of cases.
1554 * @param string $text The string to convert.
1555 * @param boolean $smiley_ignored Was used to determine if smiley characters should convert to smiley images, ignored now
1556 * @param boolean $para If true then the returned string will be wrapped in div tags
1557 * @param boolean $newlines If true then lines newline breaks will be converted to HTML newline breaks.
1558 * @return string
1560 function text_to_html($text, $smiley_ignored=null, $para=true, $newlines=true) {
1561 /// Remove any whitespace that may be between HTML tags
1562 $text = preg_replace("~>([[:space:]]+)<~i", "><", $text);
1564 /// Remove any returns that precede or follow HTML tags
1565 $text = preg_replace("~([\n\r])<~i", " <", $text);
1566 $text = preg_replace("~>([\n\r])~i", "> ", $text);
1568 /// Make returns into HTML newlines.
1569 if ($newlines) {
1570 $text = nl2br($text);
1573 /// Wrap the whole thing in a div if required
1574 if ($para) {
1575 //return '<p>'.$text.'</p>'; //1.9 version
1576 return '<div class="text_to_html">'.$text.'</div>';
1577 } else {
1578 return $text;
1583 * Given Markdown formatted text, make it into XHTML using external function
1585 * @global object
1586 * @param string $text The markdown formatted text to be converted.
1587 * @return string Converted text
1589 function markdown_to_html($text) {
1590 global $CFG;
1592 if ($text === '' or $text === NULL) {
1593 return $text;
1596 require_once($CFG->libdir .'/markdown.php');
1598 return Markdown($text);
1602 * Given HTML text, make it into plain text using external function
1604 * @param string $html The text to be converted.
1605 * @param integer $width Width to wrap the text at. (optional, default 75 which
1606 * is a good value for email. 0 means do not limit line length.)
1607 * @param boolean $dolinks By default, any links in the HTML are collected, and
1608 * printed as a list at the end of the HTML. If you don't want that, set this
1609 * argument to false.
1610 * @return string plain text equivalent of the HTML.
1612 function html_to_text($html, $width = 75, $dolinks = true) {
1614 global $CFG;
1616 require_once($CFG->libdir .'/html2text.php');
1618 $h2t = new html2text($html, false, $dolinks, $width);
1619 $result = $h2t->get_text();
1621 return $result;
1625 * This function will highlight search words in a given string
1627 * It cares about HTML and will not ruin links. It's best to use
1628 * this function after performing any conversions to HTML.
1630 * @param string $needle The search string. Syntax like "word1 +word2 -word3" is dealt with correctly.
1631 * @param string $haystack The string (HTML) within which to highlight the search terms.
1632 * @param boolean $matchcase whether to do case-sensitive. Default case-insensitive.
1633 * @param string $prefix the string to put before each search term found.
1634 * @param string $suffix the string to put after each search term found.
1635 * @return string The highlighted HTML.
1637 function highlight($needle, $haystack, $matchcase = false,
1638 $prefix = '<span class="highlight">', $suffix = '</span>') {
1640 /// Quick bail-out in trivial cases.
1641 if (empty($needle) or empty($haystack)) {
1642 return $haystack;
1645 /// Break up the search term into words, discard any -words and build a regexp.
1646 $words = preg_split('/ +/', trim($needle));
1647 foreach ($words as $index => $word) {
1648 if (strpos($word, '-') === 0) {
1649 unset($words[$index]);
1650 } else if (strpos($word, '+') === 0) {
1651 $words[$index] = '\b' . preg_quote(ltrim($word, '+'), '/') . '\b'; // Match only as a complete word.
1652 } else {
1653 $words[$index] = preg_quote($word, '/');
1656 $regexp = '/(' . implode('|', $words) . ')/u'; // u is do UTF-8 matching.
1657 if (!$matchcase) {
1658 $regexp .= 'i';
1661 /// Another chance to bail-out if $search was only -words
1662 if (empty($words)) {
1663 return $haystack;
1666 /// Find all the HTML tags in the input, and store them in a placeholders array.
1667 $placeholders = array();
1668 $matches = array();
1669 preg_match_all('/<[^>]*>/', $haystack, $matches);
1670 foreach (array_unique($matches[0]) as $key => $htmltag) {
1671 $placeholders['<|' . $key . '|>'] = $htmltag;
1674 /// In $hastack, replace each HTML tag with the corresponding placeholder.
1675 $haystack = str_replace($placeholders, array_keys($placeholders), $haystack);
1677 /// In the resulting string, Do the highlighting.
1678 $haystack = preg_replace($regexp, $prefix . '$1' . $suffix, $haystack);
1680 /// Turn the placeholders back into HTML tags.
1681 $haystack = str_replace(array_keys($placeholders), $placeholders, $haystack);
1683 return $haystack;
1687 * This function will highlight instances of $needle in $haystack
1689 * It's faster that the above function {@link highlight()} and doesn't care about
1690 * HTML or anything.
1692 * @param string $needle The string to search for
1693 * @param string $haystack The string to search for $needle in
1694 * @return string The highlighted HTML
1696 function highlightfast($needle, $haystack) {
1698 if (empty($needle) or empty($haystack)) {
1699 return $haystack;
1702 $parts = explode(textlib::strtolower($needle), textlib::strtolower($haystack));
1704 if (count($parts) === 1) {
1705 return $haystack;
1708 $pos = 0;
1710 foreach ($parts as $key => $part) {
1711 $parts[$key] = substr($haystack, $pos, strlen($part));
1712 $pos += strlen($part);
1714 $parts[$key] .= '<span class="highlight">'.substr($haystack, $pos, strlen($needle)).'</span>';
1715 $pos += strlen($needle);
1718 return str_replace('<span class="highlight"></span>', '', join('', $parts));
1722 * Return a string containing 'lang', xml:lang and optionally 'dir' HTML attributes.
1723 * Internationalisation, for print_header and backup/restorelib.
1725 * @param bool $dir Default false
1726 * @return string Attributes
1728 function get_html_lang($dir = false) {
1729 $direction = '';
1730 if ($dir) {
1731 if (right_to_left()) {
1732 $direction = ' dir="rtl"';
1733 } else {
1734 $direction = ' dir="ltr"';
1737 //Accessibility: added the 'lang' attribute to $direction, used in theme <html> tag.
1738 $language = str_replace('_', '-', current_language());
1739 @header('Content-Language: '.$language);
1740 return ($direction.' lang="'.$language.'" xml:lang="'.$language.'"');
1744 /// STANDARD WEB PAGE PARTS ///////////////////////////////////////////////////
1747 * Send the HTTP headers that Moodle requires.
1748 * @param $cacheable Can this page be cached on back?
1750 function send_headers($contenttype, $cacheable = true) {
1751 global $CFG;
1753 @header('Content-Type: ' . $contenttype);
1754 @header('Content-Script-Type: text/javascript');
1755 @header('Content-Style-Type: text/css');
1757 if ($cacheable) {
1758 // Allow caching on "back" (but not on normal clicks)
1759 @header('Cache-Control: private, pre-check=0, post-check=0, max-age=0');
1760 @header('Pragma: no-cache');
1761 @header('Expires: ');
1762 } else {
1763 // Do everything we can to always prevent clients and proxies caching
1764 @header('Cache-Control: no-store, no-cache, must-revalidate');
1765 @header('Cache-Control: post-check=0, pre-check=0', false);
1766 @header('Pragma: no-cache');
1767 @header('Expires: Mon, 20 Aug 1969 09:23:00 GMT');
1768 @header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
1770 @header('Accept-Ranges: none');
1772 if (empty($CFG->allowframembedding)) {
1773 @header('X-Frame-Options: sameorigin');
1778 * Return the right arrow with text ('next'), and optionally embedded in a link.
1780 * @global object
1781 * @param string $text HTML/plain text label (set to blank only for breadcrumb separator cases).
1782 * @param string $url An optional link to use in a surrounding HTML anchor.
1783 * @param bool $accesshide True if text should be hidden (for screen readers only).
1784 * @param string $addclass Additional class names for the link, or the arrow character.
1785 * @return string HTML string.
1787 function link_arrow_right($text, $url='', $accesshide=false, $addclass='') {
1788 global $OUTPUT; //TODO: move to output renderer
1789 $arrowclass = 'arrow ';
1790 if (! $url) {
1791 $arrowclass .= $addclass;
1793 $arrow = '<span class="'.$arrowclass.'">'.$OUTPUT->rarrow().'</span>';
1794 $htmltext = '';
1795 if ($text) {
1796 $htmltext = '<span class="arrow_text">'.$text.'</span>&nbsp;';
1797 if ($accesshide) {
1798 $htmltext = get_accesshide($htmltext);
1801 if ($url) {
1802 $class = 'arrow_link';
1803 if ($addclass) {
1804 $class .= ' '.$addclass;
1806 return '<a class="'.$class.'" href="'.$url.'" title="'.preg_replace('/<.*?>/','',$text).'">'.$htmltext.$arrow.'</a>';
1808 return $htmltext.$arrow;
1812 * Return the left arrow with text ('previous'), and optionally embedded in a link.
1814 * @global object
1815 * @param string $text HTML/plain text label (set to blank only for breadcrumb separator cases).
1816 * @param string $url An optional link to use in a surrounding HTML anchor.
1817 * @param bool $accesshide True if text should be hidden (for screen readers only).
1818 * @param string $addclass Additional class names for the link, or the arrow character.
1819 * @return string HTML string.
1821 function link_arrow_left($text, $url='', $accesshide=false, $addclass='') {
1822 global $OUTPUT; // TODO: move to utput renderer
1823 $arrowclass = 'arrow ';
1824 if (! $url) {
1825 $arrowclass .= $addclass;
1827 $arrow = '<span class="'.$arrowclass.'">'.$OUTPUT->larrow().'</span>';
1828 $htmltext = '';
1829 if ($text) {
1830 $htmltext = '&nbsp;<span class="arrow_text">'.$text.'</span>';
1831 if ($accesshide) {
1832 $htmltext = get_accesshide($htmltext);
1835 if ($url) {
1836 $class = 'arrow_link';
1837 if ($addclass) {
1838 $class .= ' '.$addclass;
1840 return '<a class="'.$class.'" href="'.$url.'" title="'.preg_replace('/<.*?>/','',$text).'">'.$arrow.$htmltext.'</a>';
1842 return $arrow.$htmltext;
1846 * Return a HTML element with the class "accesshide", for accessibility.
1847 * Please use cautiously - where possible, text should be visible!
1849 * @param string $text Plain text.
1850 * @param string $elem Lowercase element name, default "span".
1851 * @param string $class Additional classes for the element.
1852 * @param string $attrs Additional attributes string in the form, "name='value' name2='value2'"
1853 * @return string HTML string.
1855 function get_accesshide($text, $elem='span', $class='', $attrs='') {
1856 return "<$elem class=\"accesshide $class\" $attrs>$text</$elem>";
1860 * Return the breadcrumb trail navigation separator.
1862 * @return string HTML string.
1864 function get_separator() {
1865 //Accessibility: the 'hidden' slash is preferred for screen readers.
1866 return ' '.link_arrow_right($text='/', $url='', $accesshide=true, 'sep').' ';
1870 * Print (or return) a collapsible region, that has a caption that can
1871 * be clicked to expand or collapse the region.
1873 * If JavaScript is off, then the region will always be expanded.
1875 * @param string $contents the contents of the box.
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($contents, $classes, $id, $caption, $userpref = '', $default = false, $return = false) {
1886 $output = print_collapsible_region_start($classes, $id, $caption, $userpref, $default, true);
1887 $output .= $contents;
1888 $output .= print_collapsible_region_end(true);
1890 if ($return) {
1891 return $output;
1892 } else {
1893 echo $output;
1898 * Print (or return) the start of a collapsible region, that has a caption that can
1899 * be clicked to expand or collapse the region. If JavaScript is off, then the region
1900 * will always be expanded.
1902 * @param string $classes class names added to the div that is output.
1903 * @param string $id id added to the div that is output. Must not be blank.
1904 * @param string $caption text displayed at the top. Clicking on this will cause the region to expand or contract.
1905 * @param string $userpref the name of the user preference that stores the user's preferred default state.
1906 * (May be blank if you do not wish the state to be persisted.
1907 * @param boolean $default Initial collapsed state to use if the user_preference it not set.
1908 * @param boolean $return if true, return the HTML as a string, rather than printing it.
1909 * @return string|void if $return is false, returns nothing, otherwise returns a string of HTML.
1911 function print_collapsible_region_start($classes, $id, $caption, $userpref = '', $default = false, $return = false) {
1912 global $CFG, $PAGE, $OUTPUT;
1914 // Work out the initial state.
1915 if (!empty($userpref) and is_string($userpref)) {
1916 user_preference_allow_ajax_update($userpref, PARAM_BOOL);
1917 $collapsed = get_user_preferences($userpref, $default);
1918 } else {
1919 $collapsed = $default;
1920 $userpref = false;
1923 if ($collapsed) {
1924 $classes .= ' collapsed';
1927 $output = '';
1928 $output .= '<div id="' . $id . '" class="collapsibleregion ' . $classes . '">';
1929 $output .= '<div id="' . $id . '_sizer">';
1930 $output .= '<div id="' . $id . '_caption" class="collapsibleregioncaption">';
1931 $output .= $caption . ' ';
1932 $output .= '</div><div id="' . $id . '_inner" class="collapsibleregioninner">';
1933 $PAGE->requires->js_init_call('M.util.init_collapsible_region', array($id, $userpref, get_string('clicktohideshow')));
1935 if ($return) {
1936 return $output;
1937 } else {
1938 echo $output;
1943 * Close a region started with print_collapsible_region_start.
1945 * @param boolean $return if true, return the HTML as a string, rather than printing it.
1946 * @return string|void if $return is false, returns nothing, otherwise returns a string of HTML.
1948 function print_collapsible_region_end($return = false) {
1949 $output = '</div></div></div>';
1951 if ($return) {
1952 return $output;
1953 } else {
1954 echo $output;
1959 * Print a specified group's avatar.
1961 * @global object
1962 * @uses CONTEXT_COURSE
1963 * @param array|stdClass $group A single {@link group} object OR array of groups.
1964 * @param int $courseid The course ID.
1965 * @param boolean $large Default small picture, or large.
1966 * @param boolean $return If false print picture, otherwise return the output as string
1967 * @param boolean $link Enclose image in a link to view specified course?
1968 * @return string|void Depending on the setting of $return
1970 function print_group_picture($group, $courseid, $large=false, $return=false, $link=true) {
1971 global $CFG;
1973 if (is_array($group)) {
1974 $output = '';
1975 foreach($group as $g) {
1976 $output .= print_group_picture($g, $courseid, $large, true, $link);
1978 if ($return) {
1979 return $output;
1980 } else {
1981 echo $output;
1982 return;
1986 $context = get_context_instance(CONTEXT_COURSE, $courseid);
1988 // If there is no picture, do nothing
1989 if (!$group->picture) {
1990 return '';
1993 // If picture is hidden, only show to those with course:managegroups
1994 if ($group->hidepicture and !has_capability('moodle/course:managegroups', $context)) {
1995 return '';
1998 if ($link or has_capability('moodle/site:accessallgroups', $context)) {
1999 $output = '<a href="'. $CFG->wwwroot .'/user/index.php?id='. $courseid .'&amp;group='. $group->id .'">';
2000 } else {
2001 $output = '';
2003 if ($large) {
2004 $file = 'f1';
2005 } else {
2006 $file = 'f2';
2009 $grouppictureurl = moodle_url::make_pluginfile_url($context->id, 'group', 'icon', $group->id, '/', $file);
2010 $output .= '<img class="grouppicture" src="'.$grouppictureurl.'"'.
2011 ' alt="'.s(get_string('group').' '.$group->name).'" title="'.s($group->name).'"/>';
2013 if ($link or has_capability('moodle/site:accessallgroups', $context)) {
2014 $output .= '</a>';
2017 if ($return) {
2018 return $output;
2019 } else {
2020 echo $output;
2026 * Display a recent activity note
2028 * @uses CONTEXT_SYSTEM
2029 * @staticvar string $strftimerecent
2030 * @param object A time object
2031 * @param object A user object
2032 * @param string $text Text for display for the note
2033 * @param string $link The link to wrap around the text
2034 * @param bool $return If set to true the HTML is returned rather than echo'd
2035 * @param string $viewfullnames
2037 function print_recent_activity_note($time, $user, $text, $link, $return=false, $viewfullnames=null) {
2038 static $strftimerecent = null;
2039 $output = '';
2041 if (is_null($viewfullnames)) {
2042 $context = get_context_instance(CONTEXT_SYSTEM);
2043 $viewfullnames = has_capability('moodle/site:viewfullnames', $context);
2046 if (is_null($strftimerecent)) {
2047 $strftimerecent = get_string('strftimerecent');
2050 $output .= '<div class="head">';
2051 $output .= '<div class="date">'.userdate($time, $strftimerecent).'</div>';
2052 $output .= '<div class="name">'.fullname($user, $viewfullnames).'</div>';
2053 $output .= '</div>';
2054 $output .= '<div class="info"><a href="'.$link.'">'.format_string($text,true).'</a></div>';
2056 if ($return) {
2057 return $output;
2058 } else {
2059 echo $output;
2064 * Returns a popup menu with course activity modules
2066 * Given a course
2067 * This function returns a small popup menu with all the
2068 * course activity modules in it, as a navigation menu
2069 * outputs a simple list structure in XHTML
2070 * The data is taken from the serialised array stored in
2071 * the course record
2073 * @todo Finish documenting this function
2075 * @global object
2076 * @uses CONTEXT_COURSE
2077 * @param course $course A {@link $COURSE} object.
2078 * @param string $sections
2079 * @param string $modinfo
2080 * @param string $strsection
2081 * @param string $strjumpto
2082 * @param int $width
2083 * @param string $cmid
2084 * @return string The HTML block
2086 function navmenulist($course, $sections, $modinfo, $strsection, $strjumpto, $width=50, $cmid=0) {
2088 global $CFG, $OUTPUT;
2090 $section = -1;
2091 $url = '';
2092 $menu = array();
2093 $doneheading = false;
2095 $coursecontext = get_context_instance(CONTEXT_COURSE, $course->id);
2097 $menu[] = '<ul class="navmenulist"><li class="jumpto section"><span>'.$strjumpto.'</span><ul>';
2098 foreach ($modinfo->cms as $mod) {
2099 if (!$mod->has_view()) {
2100 // Don't show modules which you can't link to!
2101 continue;
2104 if ($mod->sectionnum > $course->numsections) { /// Don't show excess hidden sections
2105 break;
2108 if (!$mod->uservisible) { // do not icnlude empty sections at all
2109 continue;
2112 if ($mod->sectionnum >= 0 and $section != $mod->sectionnum) {
2113 $thissection = $sections[$mod->sectionnum];
2115 if ($thissection->visible or !$course->hiddensections or
2116 has_capability('moodle/course:viewhiddensections', $coursecontext)) {
2117 $thissection->summary = strip_tags(format_string($thissection->summary,true));
2118 if (!$doneheading) {
2119 $menu[] = '</ul></li>';
2121 if ($course->format == 'weeks' or empty($thissection->summary)) {
2122 $item = $strsection ." ". $mod->sectionnum;
2123 } else {
2124 if (textlib::strlen($thissection->summary) < ($width-3)) {
2125 $item = $thissection->summary;
2126 } else {
2127 $item = textlib::substr($thissection->summary, 0, $width).'...';
2130 $menu[] = '<li class="section"><span>'.$item.'</span>';
2131 $menu[] = '<ul>';
2132 $doneheading = true;
2134 $section = $mod->sectionnum;
2135 } else {
2136 // no activities from this hidden section shown
2137 continue;
2141 $url = $mod->modname .'/view.php?id='. $mod->id;
2142 $mod->name = strip_tags(format_string($mod->name ,true));
2143 if (textlib::strlen($mod->name) > ($width+5)) {
2144 $mod->name = textlib::substr($mod->name, 0, $width).'...';
2146 if (!$mod->visible) {
2147 $mod->name = '('.$mod->name.')';
2149 $class = 'activity '.$mod->modname;
2150 $class .= ($cmid == $mod->id) ? ' selected' : '';
2151 $menu[] = '<li class="'.$class.'">'.
2152 '<img src="'.$OUTPUT->pix_url('icon', $mod->modname) . '" alt="" />'.
2153 '<a href="'.$CFG->wwwroot.'/mod/'.$url.'">'.$mod->name.'</a></li>';
2156 if ($doneheading) {
2157 $menu[] = '</ul></li>';
2159 $menu[] = '</ul></li></ul>';
2161 return implode("\n", $menu);
2165 * Prints a grade menu (as part of an existing form) with help
2166 * Showing all possible numerical grades and scales
2168 * @todo Finish documenting this function
2169 * @todo Deprecate: this is only used in a few contrib modules
2171 * @global object
2172 * @param int $courseid The course ID
2173 * @param string $name
2174 * @param string $current
2175 * @param boolean $includenograde Include those with no grades
2176 * @param boolean $return If set to true returns rather than echo's
2177 * @return string|bool Depending on value of $return
2179 function print_grade_menu($courseid, $name, $current, $includenograde=true, $return=false) {
2181 global $CFG, $OUTPUT;
2183 $output = '';
2184 $strscale = get_string('scale');
2185 $strscales = get_string('scales');
2187 $scales = get_scales_menu($courseid);
2188 foreach ($scales as $i => $scalename) {
2189 $grades[-$i] = $strscale .': '. $scalename;
2191 if ($includenograde) {
2192 $grades[0] = get_string('nograde');
2194 for ($i=100; $i>=1; $i--) {
2195 $grades[$i] = $i;
2197 $output .= html_writer::select($grades, $name, $current, false);
2199 $linkobject = '<span class="helplink"><img class="iconhelp" alt="'.$strscales.'" src="'.$OUTPUT->pix_url('help') . '" /></span>';
2200 $link = new moodle_url('/course/scales.php', array('id'=>$courseid, 'list'=>1));
2201 $action = new popup_action('click', $link, 'ratingscales', array('height' => 400, 'width' => 500));
2202 $output .= $OUTPUT->action_link($link, $linkobject, $action, array('title'=>$strscales));
2204 if ($return) {
2205 return $output;
2206 } else {
2207 echo $output;
2212 * Print an error to STDOUT and exit with a non-zero code. For commandline scripts.
2213 * Default errorcode is 1.
2215 * Very useful for perl-like error-handling:
2217 * do_somethting() or mdie("Something went wrong");
2219 * @param string $msg Error message
2220 * @param integer $errorcode Error code to emit
2222 function mdie($msg='', $errorcode=1) {
2223 trigger_error($msg);
2224 exit($errorcode);
2228 * Print a message and exit.
2230 * @param string $message The message to print in the notice
2231 * @param string $link The link to use for the continue button
2232 * @param object $course A course object
2233 * @return void This function simply exits
2235 function notice ($message, $link='', $course=NULL) {
2236 global $CFG, $SITE, $COURSE, $PAGE, $OUTPUT;
2238 $message = clean_text($message); // In case nasties are in here
2240 if (CLI_SCRIPT) {
2241 echo("!!$message!!\n");
2242 exit(1); // no success
2245 if (!$PAGE->headerprinted) {
2246 //header not yet printed
2247 $PAGE->set_title(get_string('notice'));
2248 echo $OUTPUT->header();
2249 } else {
2250 echo $OUTPUT->container_end_all(false);
2253 echo $OUTPUT->box($message, 'generalbox', 'notice');
2254 echo $OUTPUT->continue_button($link);
2256 echo $OUTPUT->footer();
2257 exit(1); // general error code
2261 * Redirects the user to another page, after printing a notice
2263 * This function calls the OUTPUT redirect method, echo's the output
2264 * and then dies to ensure nothing else happens.
2266 * <strong>Good practice:</strong> You should call this method before starting page
2267 * output by using any of the OUTPUT methods.
2269 * @param moodle_url|string $url A moodle_url to redirect to. Strings are not to be trusted!
2270 * @param string $message The message to display to the user
2271 * @param int $delay The delay before redirecting
2272 * @return void - does not return!
2274 function redirect($url, $message='', $delay=-1) {
2275 global $OUTPUT, $PAGE, $SESSION, $CFG;
2277 if (CLI_SCRIPT or AJAX_SCRIPT) {
2278 // this is wrong - developers should not use redirect in these scripts,
2279 // but it should not be very likely
2280 throw new moodle_exception('redirecterrordetected', 'error');
2283 // prevent debug errors - make sure context is properly initialised
2284 if ($PAGE) {
2285 $PAGE->set_context(null);
2286 $PAGE->set_pagelayout('redirect'); // No header and footer needed
2289 if ($url instanceof moodle_url) {
2290 $url = $url->out(false);
2293 $debugdisableredirect = false;
2294 do {
2295 if (defined('DEBUGGING_PRINTED')) {
2296 // some debugging already printed, no need to look more
2297 $debugdisableredirect = true;
2298 break;
2301 if (empty($CFG->debugdisplay) or empty($CFG->debug)) {
2302 // no errors should be displayed
2303 break;
2306 if (!function_exists('error_get_last') or !$lasterror = error_get_last()) {
2307 break;
2310 if (!($lasterror['type'] & $CFG->debug)) {
2311 //last error not interesting
2312 break;
2315 // watch out here, @hidden() errors are returned from error_get_last() too
2316 if (headers_sent()) {
2317 //we already started printing something - that means errors likely printed
2318 $debugdisableredirect = true;
2319 break;
2322 if (ob_get_level() and ob_get_contents()) {
2323 // there is something waiting to be printed, hopefully it is the errors,
2324 // but it might be some error hidden by @ too - such as the timezone mess from setup.php
2325 $debugdisableredirect = true;
2326 break;
2328 } while (false);
2330 // Technically, HTTP/1.1 requires Location: header to contain the absolute path.
2331 // (In practice browsers accept relative paths - but still, might as well do it properly.)
2332 // This code turns relative into absolute.
2333 if (!preg_match('|^[a-z]+:|', $url)) {
2334 // Get host name http://www.wherever.com
2335 $hostpart = preg_replace('|^(.*?[^:/])/.*$|', '$1', $CFG->wwwroot);
2336 if (preg_match('|^/|', $url)) {
2337 // URLs beginning with / are relative to web server root so we just add them in
2338 $url = $hostpart.$url;
2339 } else {
2340 // URLs not beginning with / are relative to path of current script, so add that on.
2341 $url = $hostpart.preg_replace('|\?.*$|','',me()).'/../'.$url;
2343 // Replace all ..s
2344 while (true) {
2345 $newurl = preg_replace('|/(?!\.\.)[^/]*/\.\./|', '/', $url);
2346 if ($newurl == $url) {
2347 break;
2349 $url = $newurl;
2353 // Sanitise url - we can not rely on moodle_url or our URL cleaning
2354 // because they do not support all valid external URLs
2355 $url = preg_replace('/[\x00-\x1F\x7F]/', '', $url);
2356 $url = str_replace('"', '%22', $url);
2357 $encodedurl = preg_replace("/\&(?![a-zA-Z0-9#]{1,8};)/", "&amp;", $url);
2358 $encodedurl = preg_replace('/^.*href="([^"]*)".*$/', "\\1", clean_text('<a href="'.$encodedurl.'" />', FORMAT_HTML));
2359 $url = str_replace('&amp;', '&', $encodedurl);
2361 if (!empty($message)) {
2362 if ($delay === -1 || !is_numeric($delay)) {
2363 $delay = 3;
2365 $message = clean_text($message);
2366 } else {
2367 $message = get_string('pageshouldredirect');
2368 $delay = 0;
2371 if (defined('MDL_PERF') || (!empty($CFG->perfdebug) and $CFG->perfdebug > 7)) {
2372 if (defined('MDL_PERFTOLOG') && !function_exists('register_shutdown_function')) {
2373 $perf = get_performance_info();
2374 error_log("PERF: " . $perf['txt']);
2378 if ($delay == 0 && !$debugdisableredirect && !headers_sent()) {
2379 // workaround for IIS bug http://support.microsoft.com/kb/q176113/
2380 if (session_id()) {
2381 session_get_instance()->write_close();
2384 //302 might not work for POST requests, 303 is ignored by obsolete clients.
2385 @header($_SERVER['SERVER_PROTOCOL'] . ' 303 See Other');
2386 @header('Location: '.$url);
2387 echo bootstrap_renderer::plain_redirect_message($encodedurl);
2388 exit;
2391 // Include a redirect message, even with a HTTP redirect, because that is recommended practice.
2392 if ($PAGE) {
2393 $CFG->docroot = false; // to prevent the link to moodle docs from being displayed on redirect page.
2394 echo $OUTPUT->redirect_message($encodedurl, $message, $delay, $debugdisableredirect);
2395 exit;
2396 } else {
2397 echo bootstrap_renderer::early_redirect_message($encodedurl, $message, $delay);
2398 exit;
2403 * Given an email address, this function will return an obfuscated version of it
2405 * @param string $email The email address to obfuscate
2406 * @return string The obfuscated email address
2408 function obfuscate_email($email) {
2410 $i = 0;
2411 $length = strlen($email);
2412 $obfuscated = '';
2413 while ($i < $length) {
2414 if (rand(0,2) && $email{$i}!='@') { //MDL-20619 some browsers have problems unobfuscating @
2415 $obfuscated.='%'.dechex(ord($email{$i}));
2416 } else {
2417 $obfuscated.=$email{$i};
2419 $i++;
2421 return $obfuscated;
2425 * This function takes some text and replaces about half of the characters
2426 * with HTML entity equivalents. Return string is obviously longer.
2428 * @param string $plaintext The text to be obfuscated
2429 * @return string The obfuscated text
2431 function obfuscate_text($plaintext) {
2433 $i=0;
2434 $length = strlen($plaintext);
2435 $obfuscated='';
2436 $prev_obfuscated = false;
2437 while ($i < $length) {
2438 $c = ord($plaintext{$i});
2439 $numerical = ($c >= ord('0')) && ($c <= ord('9'));
2440 if ($prev_obfuscated and $numerical ) {
2441 $obfuscated.='&#'.ord($plaintext{$i}).';';
2442 } else if (rand(0,2)) {
2443 $obfuscated.='&#'.ord($plaintext{$i}).';';
2444 $prev_obfuscated = true;
2445 } else {
2446 $obfuscated.=$plaintext{$i};
2447 $prev_obfuscated = false;
2449 $i++;
2451 return $obfuscated;
2455 * This function uses the {@link obfuscate_email()} and {@link obfuscate_text()}
2456 * to generate a fully obfuscated email link, ready to use.
2458 * @param string $email The email address to display
2459 * @param string $label The text to displayed as hyperlink to $email
2460 * @param boolean $dimmed If true then use css class 'dimmed' for hyperlink
2461 * @return string The obfuscated mailto link
2463 function obfuscate_mailto($email, $label='', $dimmed=false) {
2465 if (empty($label)) {
2466 $label = $email;
2468 if ($dimmed) {
2469 $title = get_string('emaildisable');
2470 $dimmed = ' class="dimmed"';
2471 } else {
2472 $title = '';
2473 $dimmed = '';
2475 return sprintf("<a href=\"%s:%s\" $dimmed title=\"$title\">%s</a>",
2476 obfuscate_text('mailto'), obfuscate_email($email),
2477 obfuscate_text($label));
2481 * This function is used to rebuild the <nolink> tag because some formats (PLAIN and WIKI)
2482 * will transform it to html entities
2484 * @param string $text Text to search for nolink tag in
2485 * @return string
2487 function rebuildnolinktag($text) {
2489 $text = preg_replace('/&lt;(\/*nolink)&gt;/i','<$1>',$text);
2491 return $text;
2495 * Prints a maintenance message from $CFG->maintenance_message or default if empty
2496 * @return void
2498 function print_maintenance_message() {
2499 global $CFG, $SITE, $PAGE, $OUTPUT;
2501 $PAGE->set_pagetype('maintenance-message');
2502 $PAGE->set_pagelayout('maintenance');
2503 $PAGE->set_title(strip_tags($SITE->fullname));
2504 $PAGE->set_heading($SITE->fullname);
2505 echo $OUTPUT->header();
2506 echo $OUTPUT->heading(get_string('sitemaintenance', 'admin'));
2507 if (isset($CFG->maintenance_message) and !html_is_blank($CFG->maintenance_message)) {
2508 echo $OUTPUT->box_start('maintenance_message generalbox boxwidthwide boxaligncenter');
2509 echo $CFG->maintenance_message;
2510 echo $OUTPUT->box_end();
2512 echo $OUTPUT->footer();
2513 die;
2517 * A class for tabs, Some code to print tabs
2519 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2520 * @package moodlecore
2522 class tabobject {
2524 * @var string
2526 var $id;
2527 var $link;
2528 var $text;
2530 * @var bool
2532 var $linkedwhenselected;
2535 * A constructor just because I like constructors
2537 * @param string $id
2538 * @param string $link
2539 * @param string $text
2540 * @param string $title
2541 * @param bool $linkedwhenselected
2543 function tabobject ($id, $link='', $text='', $title='', $linkedwhenselected=false) {
2544 $this->id = $id;
2545 $this->link = $link;
2546 $this->text = $text;
2547 $this->title = $title ? $title : $text;
2548 $this->linkedwhenselected = $linkedwhenselected;
2555 * Returns a string containing a nested list, suitable for formatting into tabs with CSS.
2557 * @global object
2558 * @param array $tabrows An array of rows where each row is an array of tab objects
2559 * @param string $selected The id of the selected tab (whatever row it's on)
2560 * @param array $inactive An array of ids of inactive tabs that are not selectable.
2561 * @param array $activated An array of ids of other tabs that are currently activated
2562 * @param bool $return If true output is returned rather then echo'd
2564 function print_tabs($tabrows, $selected=NULL, $inactive=NULL, $activated=NULL, $return=false) {
2565 global $CFG;
2567 /// $inactive must be an array
2568 if (!is_array($inactive)) {
2569 $inactive = array();
2572 /// $activated must be an array
2573 if (!is_array($activated)) {
2574 $activated = array();
2577 /// Convert the tab rows into a tree that's easier to process
2578 if (!$tree = convert_tabrows_to_tree($tabrows, $selected, $inactive, $activated)) {
2579 return false;
2582 /// Print out the current tree of tabs (this function is recursive)
2584 $output = convert_tree_to_html($tree);
2586 $output = "\n\n".'<div class="tabtree">'.$output.'</div><div class="clearer"> </div>'."\n\n";
2588 /// We're done!
2590 if ($return) {
2591 return $output;
2593 echo $output;
2597 * Converts a nested array tree into HTML ul:li [recursive]
2599 * @param array $tree A tree array to convert
2600 * @param int $row Used in identifying the iteration level and in ul classes
2601 * @return string HTML structure
2603 function convert_tree_to_html($tree, $row=0) {
2605 $str = "\n".'<ul class="tabrow'.$row.'">'."\n";
2607 $first = true;
2608 $count = count($tree);
2610 foreach ($tree as $tab) {
2611 $count--; // countdown to zero
2613 $liclass = '';
2615 if ($first && ($count == 0)) { // Just one in the row
2616 $liclass = 'first last';
2617 $first = false;
2618 } else if ($first) {
2619 $liclass = 'first';
2620 $first = false;
2621 } else if ($count == 0) {
2622 $liclass = 'last';
2625 if ((empty($tab->subtree)) && (!empty($tab->selected))) {
2626 $liclass .= (empty($liclass)) ? 'onerow' : ' onerow';
2629 if ($tab->inactive || $tab->active || $tab->selected) {
2630 if ($tab->selected) {
2631 $liclass .= (empty($liclass)) ? 'here selected' : ' here selected';
2632 } else if ($tab->active) {
2633 $liclass .= (empty($liclass)) ? 'here active' : ' here active';
2637 $str .= (!empty($liclass)) ? '<li class="'.$liclass.'">' : '<li>';
2639 if ($tab->inactive || $tab->active || ($tab->selected && !$tab->linkedwhenselected)) {
2640 // The a tag is used for styling
2641 $str .= '<a class="nolink"><span>'.$tab->text.'</span></a>';
2642 } else {
2643 $str .= '<a href="'.$tab->link.'" title="'.$tab->title.'"><span>'.$tab->text.'</span></a>';
2646 if (!empty($tab->subtree)) {
2647 $str .= convert_tree_to_html($tab->subtree, $row+1);
2648 } else if ($tab->selected) {
2649 $str .= '<div class="tabrow'.($row+1).' empty">&nbsp;</div>'."\n";
2652 $str .= ' </li>'."\n";
2654 $str .= '</ul>'."\n";
2656 return $str;
2660 * Convert nested tabrows to a nested array
2662 * @param array $tabrows A [nested] array of tab row objects
2663 * @param string $selected The tabrow to select (by id)
2664 * @param array $inactive An array of tabrow id's to make inactive
2665 * @param array $activated An array of tabrow id's to make active
2666 * @return array The nested array
2668 function convert_tabrows_to_tree($tabrows, $selected, $inactive, $activated) {
2670 /// Work backwards through the rows (bottom to top) collecting the tree as we go.
2672 $tabrows = array_reverse($tabrows);
2674 $subtree = array();
2676 foreach ($tabrows as $row) {
2677 $tree = array();
2679 foreach ($row as $tab) {
2680 $tab->inactive = in_array((string)$tab->id, $inactive);
2681 $tab->active = in_array((string)$tab->id, $activated);
2682 $tab->selected = (string)$tab->id == $selected;
2684 if ($tab->active || $tab->selected) {
2685 if ($subtree) {
2686 $tab->subtree = $subtree;
2689 $tree[] = $tab;
2691 $subtree = $tree;
2694 return $subtree;
2698 * Standard Debugging Function
2700 * Returns true if the current site debugging settings are equal or above specified level.
2701 * If passed a parameter it will emit a debugging notice similar to trigger_error(). The
2702 * routing of notices is controlled by $CFG->debugdisplay
2703 * eg use like this:
2705 * 1) debugging('a normal debug notice');
2706 * 2) debugging('something really picky', DEBUG_ALL);
2707 * 3) debugging('annoying debug message only for developers', DEBUG_DEVELOPER);
2708 * 4) if (debugging()) { perform extra debugging operations (do not use print or echo) }
2710 * In code blocks controlled by debugging() (such as example 4)
2711 * any output should be routed via debugging() itself, or the lower-level
2712 * trigger_error() or error_log(). Using echo or print will break XHTML
2713 * JS and HTTP headers.
2715 * It is also possible to define NO_DEBUG_DISPLAY which redirects the message to error_log.
2717 * @uses DEBUG_NORMAL
2718 * @param string $message a message to print
2719 * @param int $level the level at which this debugging statement should show
2720 * @param array $backtrace use different backtrace
2721 * @return bool
2723 function debugging($message = '', $level = DEBUG_NORMAL, $backtrace = null) {
2724 global $CFG, $USER, $UNITTEST;
2726 $forcedebug = false;
2727 if (!empty($CFG->debugusers) && $USER) {
2728 $debugusers = explode(',', $CFG->debugusers);
2729 $forcedebug = in_array($USER->id, $debugusers);
2732 if (!$forcedebug and (empty($CFG->debug) || $CFG->debug < $level)) {
2733 return false;
2736 if (!isset($CFG->debugdisplay)) {
2737 $CFG->debugdisplay = ini_get_bool('display_errors');
2740 if ($message) {
2741 if (!$backtrace) {
2742 $backtrace = debug_backtrace();
2744 $from = format_backtrace($backtrace, CLI_SCRIPT);
2745 if (!empty($UNITTEST->running)) {
2746 // When the unit tests are running, any call to trigger_error
2747 // is intercepted by the test framework and reported as an exception.
2748 // Therefore, we cannot use trigger_error during unit tests.
2749 // At the same time I do not think we should just discard those messages,
2750 // so displaying them on-screen seems like the only option. (MDL-20398)
2751 echo '<div class="notifytiny">' . $message . $from . '</div>';
2753 } else if (NO_DEBUG_DISPLAY) {
2754 // script does not want any errors or debugging in output,
2755 // we send the info to error log instead
2756 error_log('Debugging: ' . $message . $from);
2758 } else if ($forcedebug or $CFG->debugdisplay) {
2759 if (!defined('DEBUGGING_PRINTED')) {
2760 define('DEBUGGING_PRINTED', 1); // indicates we have printed something
2762 if (CLI_SCRIPT) {
2763 echo "++ $message ++\n$from";
2764 } else {
2765 echo '<div class="notifytiny">' . $message . $from . '</div>';
2768 } else {
2769 trigger_error($message . $from, E_USER_NOTICE);
2772 return true;
2776 * Outputs a HTML comment to the browser. This is used for those hard-to-debug
2777 * pages that use bits from many different files in very confusing ways (e.g. blocks).
2779 * <code>print_location_comment(__FILE__, __LINE__);</code>
2781 * @param string $file
2782 * @param integer $line
2783 * @param boolean $return Whether to return or print the comment
2784 * @return string|void Void unless true given as third parameter
2786 function print_location_comment($file, $line, $return = false)
2788 if ($return) {
2789 return "<!-- $file at line $line -->\n";
2790 } else {
2791 echo "<!-- $file at line $line -->\n";
2797 * @return boolean true if the current language is right-to-left (Hebrew, Arabic etc)
2799 function right_to_left() {
2800 return (get_string('thisdirection', 'langconfig') === 'rtl');
2805 * Returns swapped left<=>right if in RTL environment.
2806 * part of RTL support
2808 * @param string $align align to check
2809 * @return string
2811 function fix_align_rtl($align) {
2812 if (!right_to_left()) {
2813 return $align;
2815 if ($align=='left') { return 'right'; }
2816 if ($align=='right') { return 'left'; }
2817 return $align;
2822 * Returns true if the page is displayed in a popup window.
2823 * Gets the information from the URL parameter inpopup.
2825 * @todo Use a central function to create the popup calls all over Moodle and
2826 * In the moment only works with resources and probably questions.
2828 * @return boolean
2830 function is_in_popup() {
2831 $inpopup = optional_param('inpopup', '', PARAM_BOOL);
2833 return ($inpopup);
2837 * To use this class.
2838 * - construct
2839 * - call create (or use the 3rd param to the constructor)
2840 * - call update or update_full() or update() repeatedly
2842 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2843 * @package moodlecore
2845 class progress_bar {
2846 /** @var string html id */
2847 private $html_id;
2848 /** @var int total width */
2849 private $width;
2850 /** @var int last percentage printed */
2851 private $percent = 0;
2852 /** @var int time when last printed */
2853 private $lastupdate = 0;
2854 /** @var int when did we start printing this */
2855 private $time_start = 0;
2858 * Constructor
2860 * @param string $html_id
2861 * @param int $width
2862 * @param bool $autostart Default to false
2863 * @return void, prints JS code if $autostart true
2865 public function __construct($html_id = '', $width = 500, $autostart = false) {
2866 if (!empty($html_id)) {
2867 $this->html_id = $html_id;
2868 } else {
2869 $this->html_id = 'pbar_'.uniqid();
2872 $this->width = $width;
2874 if ($autostart){
2875 $this->create();
2880 * Create a new progress bar, this function will output html.
2882 * @return void Echo's output
2884 public function create() {
2885 $this->time_start = microtime(true);
2886 if (CLI_SCRIPT) {
2887 return; // temporary solution for cli scripts
2889 $htmlcode = <<<EOT
2890 <div style="text-align:center;width:{$this->width}px;clear:both;padding:0;margin:0 auto;">
2891 <h2 id="status_{$this->html_id}" style="text-align: center;margin:0 auto"></h2>
2892 <p id="time_{$this->html_id}"></p>
2893 <div id="bar_{$this->html_id}" style="border-style:solid;border-width:1px;width:500px;height:50px;">
2894 <div id="progress_{$this->html_id}"
2895 style="text-align:center;background:#FFCC66;width:4px;border:1px
2896 solid gray;height:38px; padding-top:10px;">&nbsp;<span id="pt_{$this->html_id}"></span>
2897 </div>
2898 </div>
2899 </div>
2900 EOT;
2901 flush();
2902 echo $htmlcode;
2903 flush();
2907 * Update the progress bar
2909 * @param int $percent from 1-100
2910 * @param string $msg
2911 * @return void Echo's output
2913 private function _update($percent, $msg) {
2914 if (empty($this->time_start)) {
2915 throw new coding_exception('You must call create() (or use the $autostart ' .
2916 'argument to the constructor) before you try updating the progress bar.');
2919 if (CLI_SCRIPT) {
2920 return; // temporary solution for cli scripts
2923 $es = $this->estimate($percent);
2925 if ($es === null) {
2926 // always do the first and last updates
2927 $es = "?";
2928 } else if ($es == 0) {
2929 // always do the last updates
2930 } else if ($this->lastupdate + 20 < time()) {
2931 // we must update otherwise browser would time out
2932 } else if (round($this->percent, 2) === round($percent, 2)) {
2933 // no significant change, no need to update anything
2934 return;
2937 $this->percent = $percent;
2938 $this->lastupdate = microtime(true);
2940 $w = ($this->percent/100) * $this->width;
2941 echo html_writer::script(js_writer::function_call('update_progress_bar', array($this->html_id, $w, $this->percent, $msg, $es)));
2942 flush();
2946 * Estimate how much time it is going to take.
2948 * @param int $curtime the time call this function
2949 * @param int $percent from 1-100
2950 * @return mixed Null (unknown), or int
2952 private function estimate($pt) {
2953 if ($this->lastupdate == 0) {
2954 return null;
2956 if ($pt < 0.00001) {
2957 return null; // we do not know yet how long it will take
2959 if ($pt > 99.99999) {
2960 return 0; // nearly done, right?
2962 $consumed = microtime(true) - $this->time_start;
2963 if ($consumed < 0.001) {
2964 return null;
2967 return (100 - $pt) * ($consumed / $pt);
2971 * Update progress bar according percent
2973 * @param int $percent from 1-100
2974 * @param string $msg the message needed to be shown
2976 public function update_full($percent, $msg) {
2977 $percent = max(min($percent, 100), 0);
2978 $this->_update($percent, $msg);
2982 * Update progress bar according the number of tasks
2984 * @param int $cur current task number
2985 * @param int $total total task number
2986 * @param string $msg message
2988 public function update($cur, $total, $msg) {
2989 $percent = ($cur / $total) * 100;
2990 $this->update_full($percent, $msg);
2994 * Restart the progress bar.
2996 public function restart() {
2997 $this->percent = 0;
2998 $this->lastupdate = 0;
2999 $this->time_start = 0;
3004 * Use this class from long operations where you want to output occasional information about
3005 * what is going on, but don't know if, or in what format, the output should be.
3007 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3008 * @package moodlecore
3010 abstract class progress_trace {
3012 * Ouput an progress message in whatever format.
3013 * @param string $message the message to output.
3014 * @param integer $depth indent depth for this message.
3016 abstract public function output($message, $depth = 0);
3019 * Called when the processing is finished.
3021 public function finished() {
3026 * This subclass of progress_trace does not ouput anything.
3028 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3029 * @package moodlecore
3031 class null_progress_trace extends progress_trace {
3033 * Does Nothing
3035 * @param string $message
3036 * @param int $depth
3037 * @return void Does Nothing
3039 public function output($message, $depth = 0) {
3044 * This subclass of progress_trace outputs to plain text.
3046 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3047 * @package moodlecore
3049 class text_progress_trace extends progress_trace {
3051 * Output the trace message
3053 * @param string $message
3054 * @param int $depth
3055 * @return void Output is echo'd
3057 public function output($message, $depth = 0) {
3058 echo str_repeat(' ', $depth), $message, "\n";
3059 flush();
3064 * This subclass of progress_trace outputs as HTML.
3066 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3067 * @package moodlecore
3069 class html_progress_trace extends progress_trace {
3071 * Output the trace message
3073 * @param string $message
3074 * @param int $depth
3075 * @return void Output is echo'd
3077 public function output($message, $depth = 0) {
3078 echo '<p>', str_repeat('&#160;&#160;', $depth), htmlspecialchars($message), "</p>\n";
3079 flush();
3084 * HTML List Progress Tree
3086 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3087 * @package moodlecore
3089 class html_list_progress_trace extends progress_trace {
3090 /** @var int */
3091 protected $currentdepth = -1;
3094 * Echo out the list
3096 * @param string $message The message to display
3097 * @param int $depth
3098 * @return void Output is echoed
3100 public function output($message, $depth = 0) {
3101 $samedepth = true;
3102 while ($this->currentdepth > $depth) {
3103 echo "</li>\n</ul>\n";
3104 $this->currentdepth -= 1;
3105 if ($this->currentdepth == $depth) {
3106 echo '<li>';
3108 $samedepth = false;
3110 while ($this->currentdepth < $depth) {
3111 echo "<ul>\n<li>";
3112 $this->currentdepth += 1;
3113 $samedepth = false;
3115 if ($samedepth) {
3116 echo "</li>\n<li>";
3118 echo htmlspecialchars($message);
3119 flush();
3123 * Called when the processing is finished.
3125 public function finished() {
3126 while ($this->currentdepth >= 0) {
3127 echo "</li>\n</ul>\n";
3128 $this->currentdepth -= 1;
3134 * Returns a localized sentence in the current language summarizing the current password policy
3136 * @todo this should be handled by a function/method in the language pack library once we have a support for it
3137 * @uses $CFG
3138 * @return string
3140 function print_password_policy() {
3141 global $CFG;
3143 $message = '';
3144 if (!empty($CFG->passwordpolicy)) {
3145 $messages = array();
3146 $messages[] = get_string('informminpasswordlength', 'auth', $CFG->minpasswordlength);
3147 if (!empty($CFG->minpassworddigits)) {
3148 $messages[] = get_string('informminpassworddigits', 'auth', $CFG->minpassworddigits);
3150 if (!empty($CFG->minpasswordlower)) {
3151 $messages[] = get_string('informminpasswordlower', 'auth', $CFG->minpasswordlower);
3153 if (!empty($CFG->minpasswordupper)) {
3154 $messages[] = get_string('informminpasswordupper', 'auth', $CFG->minpasswordupper);
3156 if (!empty($CFG->minpasswordnonalphanum)) {
3157 $messages[] = get_string('informminpasswordnonalphanum', 'auth', $CFG->minpasswordnonalphanum);
3160 $messages = join(', ', $messages); // this is ugly but we do not have anything better yet...
3161 $message = get_string('informpasswordpolicy', 'auth', $messages);
3163 return $message;