MDL-37894 Amend tests with new openclose rule.
[moodle.git] / lib / weblib.php
blob6c8ebab4d454de31b7d32c117f2c9a52a5e12d59
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 * @return mixed String, or false if the global variables needed are not set
192 function me() {
193 global $ME;
194 return $ME;
198 * Guesses the full URL of the current script.
200 * This function is using $PAGE->url, but may fall back to $FULLME which
201 * is constructed from PHP_SELF and REQUEST_URI or SCRIPT_NAME
203 * @return mixed full page URL string or false if unknown
205 function qualified_me() {
206 global $FULLME, $PAGE, $CFG;
208 if (isset($PAGE) and $PAGE->has_set_url()) {
209 // this is the only recommended way to find out current page
210 return $PAGE->url->out(false);
212 } else {
213 if ($FULLME === null) {
214 // CLI script most probably
215 return false;
217 if (!empty($CFG->sslproxy)) {
218 // return only https links when using SSL proxy
219 return preg_replace('/^http:/', 'https:', $FULLME, 1);
220 } else {
221 return $FULLME;
227 * Class for creating and manipulating urls.
229 * It can be used in moodle pages where config.php has been included without any further includes.
231 * It is useful for manipulating urls with long lists of params.
232 * One situation where it will be useful is a page which links to itself to perform various actions
233 * and / or to process form data. A moodle_url object :
234 * can be created for a page to refer to itself with all the proper get params being passed from page call to
235 * page call and methods can be used to output a url including all the params, optionally adding and overriding
236 * params and can also be used to
237 * - output the url without any get params
238 * - and output the params as hidden fields to be output within a form
240 * @link http://docs.moodle.org/dev/lib/weblib.php_moodle_url See short write up here
241 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
242 * @package moodlecore
244 class moodle_url {
246 * Scheme, ex.: http, https
247 * @var string
249 protected $scheme = '';
251 * hostname
252 * @var string
254 protected $host = '';
256 * Port number, empty means default 80 or 443 in case of http
257 * @var unknown_type
259 protected $port = '';
261 * Username for http auth
262 * @var string
264 protected $user = '';
266 * Password for http auth
267 * @var string
269 protected $pass = '';
271 * Script path
272 * @var string
274 protected $path = '';
276 * Optional slash argument value
277 * @var string
279 protected $slashargument = '';
281 * Anchor, may be also empty, null means none
282 * @var string
284 protected $anchor = null;
286 * Url parameters as associative array
287 * @var array
289 protected $params = array(); // Associative array of query string params
292 * Create new instance of moodle_url.
294 * @param moodle_url|string $url - moodle_url means make a copy of another
295 * moodle_url and change parameters, string means full url or shortened
296 * form (ex.: '/course/view.php'). It is strongly encouraged to not include
297 * query string because it may result in double encoded values. Use the
298 * $params instead. For admin URLs, just use /admin/script.php, this
299 * class takes care of the $CFG->admin issue.
300 * @param array $params these params override current params or add new
302 public function __construct($url, array $params = null) {
303 global $CFG;
305 if ($url instanceof moodle_url) {
306 $this->scheme = $url->scheme;
307 $this->host = $url->host;
308 $this->port = $url->port;
309 $this->user = $url->user;
310 $this->pass = $url->pass;
311 $this->path = $url->path;
312 $this->slashargument = $url->slashargument;
313 $this->params = $url->params;
314 $this->anchor = $url->anchor;
316 } else {
317 // detect if anchor used
318 $apos = strpos($url, '#');
319 if ($apos !== false) {
320 $anchor = substr($url, $apos);
321 $anchor = ltrim($anchor, '#');
322 $this->set_anchor($anchor);
323 $url = substr($url, 0, $apos);
326 // normalise shortened form of our url ex.: '/course/view.php'
327 if (strpos($url, '/') === 0) {
328 // we must not use httpswwwroot here, because it might be url of other page,
329 // devs have to use httpswwwroot explicitly when creating new moodle_url
330 $url = $CFG->wwwroot.$url;
333 // now fix the admin links if needed, no need to mess with httpswwwroot
334 if ($CFG->admin !== 'admin') {
335 if (strpos($url, "$CFG->wwwroot/admin/") === 0) {
336 $url = str_replace("$CFG->wwwroot/admin/", "$CFG->wwwroot/$CFG->admin/", $url);
340 // parse the $url
341 $parts = parse_url($url);
342 if ($parts === false) {
343 throw new moodle_exception('invalidurl');
345 if (isset($parts['query'])) {
346 // note: the values may not be correctly decoded,
347 // url parameters should be always passed as array
348 parse_str(str_replace('&amp;', '&', $parts['query']), $this->params);
350 unset($parts['query']);
351 foreach ($parts as $key => $value) {
352 $this->$key = $value;
355 // detect slashargument value from path - we do not support directory names ending with .php
356 $pos = strpos($this->path, '.php/');
357 if ($pos !== false) {
358 $this->slashargument = substr($this->path, $pos + 4);
359 $this->path = substr($this->path, 0, $pos + 4);
363 $this->params($params);
367 * Add an array of params to the params for this url.
369 * The added params override existing ones if they have the same name.
371 * @param array $params Defaults to null. If null then returns all params.
372 * @return array Array of Params for url.
374 public function params(array $params = null) {
375 $params = (array)$params;
377 foreach ($params as $key=>$value) {
378 if (is_int($key)) {
379 throw new coding_exception('Url parameters can not have numeric keys!');
381 if (!is_string($value)) {
382 if (is_array($value)) {
383 throw new coding_exception('Url parameters values can not be arrays!');
385 if (is_object($value) and !method_exists($value, '__toString')) {
386 throw new coding_exception('Url parameters values can not be objects, unless __toString() is defined!');
389 $this->params[$key] = (string)$value;
391 return $this->params;
395 * Remove all params if no arguments passed.
396 * Remove selected params if arguments are passed.
398 * Can be called as either remove_params('param1', 'param2')
399 * or remove_params(array('param1', 'param2')).
401 * @param mixed $params either an array of param names, or a string param name,
402 * @param string $params,... any number of additional param names.
403 * @return array url parameters
405 public function remove_params($params = null) {
406 if (!is_array($params)) {
407 $params = func_get_args();
409 foreach ($params as $param) {
410 unset($this->params[$param]);
412 return $this->params;
416 * Remove all url parameters
417 * @param $params
418 * @return void
420 public function remove_all_params($params = null) {
421 $this->params = array();
422 $this->slashargument = '';
426 * Add a param to the params for this url.
428 * The added param overrides existing one if they have the same name.
430 * @param string $paramname name
431 * @param string $newvalue Param value. If new value specified current value is overriden or parameter is added
432 * @return mixed string parameter value, null if parameter does not exist
434 public function param($paramname, $newvalue = '') {
435 if (func_num_args() > 1) {
436 // set new value
437 $this->params(array($paramname=>$newvalue));
439 if (isset($this->params[$paramname])) {
440 return $this->params[$paramname];
441 } else {
442 return null;
447 * Merges parameters and validates them
448 * @param array $overrideparams
449 * @return array merged parameters
451 protected function merge_overrideparams(array $overrideparams = null) {
452 $overrideparams = (array)$overrideparams;
453 $params = $this->params;
454 foreach ($overrideparams as $key=>$value) {
455 if (is_int($key)) {
456 throw new coding_exception('Overridden parameters can not have numeric keys!');
458 if (is_array($value)) {
459 throw new coding_exception('Overridden parameters values can not be arrays!');
461 if (is_object($value) and !method_exists($value, '__toString')) {
462 throw new coding_exception('Overridden parameters values can not be objects, unless __toString() is defined!');
464 $params[$key] = (string)$value;
466 return $params;
470 * Get the params as as a query string.
471 * This method should not be used outside of this method.
473 * @param boolean $escaped Use &amp; as params separator instead of plain &
474 * @param array $overrideparams params to add to the output params, these
475 * override existing ones with the same name.
476 * @return string query string that can be added to a url.
478 public function get_query_string($escaped = true, array $overrideparams = null) {
479 $arr = array();
480 if ($overrideparams !== null) {
481 $params = $this->merge_overrideparams($overrideparams);
482 } else {
483 $params = $this->params;
485 foreach ($params as $key => $val) {
486 if (is_array($val)) {
487 foreach ($val as $index => $value) {
488 $arr[] = rawurlencode($key.'['.$index.']')."=".rawurlencode($value);
490 } else {
491 $arr[] = rawurlencode($key)."=".rawurlencode($val);
494 if ($escaped) {
495 return implode('&amp;', $arr);
496 } else {
497 return implode('&', $arr);
502 * Shortcut for printing of encoded URL.
503 * @return string
505 public function __toString() {
506 return $this->out(true);
510 * Output url
512 * If you use the returned URL in HTML code, you want the escaped ampersands. If you use
513 * the returned URL in HTTP headers, you want $escaped=false.
515 * @param boolean $escaped Use &amp; as params separator instead of plain &
516 * @param array $overrideparams params to add to the output url, these override existing ones with the same name.
517 * @return string Resulting URL
519 public function out($escaped = true, array $overrideparams = null) {
520 if (!is_bool($escaped)) {
521 debugging('Escape parameter must be of type boolean, '.gettype($escaped).' given instead.');
524 $uri = $this->out_omit_querystring().$this->slashargument;
526 $querystring = $this->get_query_string($escaped, $overrideparams);
527 if ($querystring !== '') {
528 $uri .= '?' . $querystring;
530 if (!is_null($this->anchor)) {
531 $uri .= '#'.$this->anchor;
534 return $uri;
538 * Returns url without parameters, everything before '?'.
540 * @param bool $includeanchor if {@link self::anchor} is defined, should it be returned?
541 * @return string
543 public function out_omit_querystring($includeanchor = false) {
545 $uri = $this->scheme ? $this->scheme.':'.((strtolower($this->scheme) == 'mailto') ? '':'//'): '';
546 $uri .= $this->user ? $this->user.($this->pass? ':'.$this->pass:'').'@':'';
547 $uri .= $this->host ? $this->host : '';
548 $uri .= $this->port ? ':'.$this->port : '';
549 $uri .= $this->path ? $this->path : '';
550 if ($includeanchor and !is_null($this->anchor)) {
551 $uri .= '#' . $this->anchor;
554 return $uri;
558 * Compares this moodle_url with another
559 * See documentation of constants for an explanation of the comparison flags.
560 * @param moodle_url $url The moodle_url object to compare
561 * @param int $matchtype The type of comparison (URL_MATCH_BASE, URL_MATCH_PARAMS, URL_MATCH_EXACT)
562 * @return boolean
564 public function compare(moodle_url $url, $matchtype = URL_MATCH_EXACT) {
566 $baseself = $this->out_omit_querystring();
567 $baseother = $url->out_omit_querystring();
569 // Append index.php if there is no specific file
570 if (substr($baseself,-1)=='/') {
571 $baseself .= 'index.php';
573 if (substr($baseother,-1)=='/') {
574 $baseother .= 'index.php';
577 // Compare the two base URLs
578 if ($baseself != $baseother) {
579 return false;
582 if ($matchtype == URL_MATCH_BASE) {
583 return true;
586 $urlparams = $url->params();
587 foreach ($this->params() as $param => $value) {
588 if ($param == 'sesskey') {
589 continue;
591 if (!array_key_exists($param, $urlparams) || $urlparams[$param] != $value) {
592 return false;
596 if ($matchtype == URL_MATCH_PARAMS) {
597 return true;
600 foreach ($urlparams as $param => $value) {
601 if ($param == 'sesskey') {
602 continue;
604 if (!array_key_exists($param, $this->params()) || $this->param($param) != $value) {
605 return false;
609 return true;
613 * Sets the anchor for the URI (the bit after the hash)
614 * @param string $anchor null means remove previous
616 public function set_anchor($anchor) {
617 if (is_null($anchor)) {
618 // remove
619 $this->anchor = null;
620 } else if ($anchor === '') {
621 // special case, used as empty link
622 $this->anchor = '';
623 } else if (preg_match('|[a-zA-Z\_\:][a-zA-Z0-9\_\-\.\:]*|', $anchor)) {
624 // Match the anchor against the NMTOKEN spec
625 $this->anchor = $anchor;
626 } else {
627 // bad luck, no valid anchor found
628 $this->anchor = null;
633 * Sets the url slashargument value
634 * @param string $path usually file path
635 * @param string $parameter name of page parameter if slasharguments not supported
636 * @param bool $supported usually null, then it depends on $CFG->slasharguments, use true or false for other servers
637 * @return void
639 public function set_slashargument($path, $parameter = 'file', $supported = NULL) {
640 global $CFG;
641 if (is_null($supported)) {
642 $supported = $CFG->slasharguments;
645 if ($supported) {
646 $parts = explode('/', $path);
647 $parts = array_map('rawurlencode', $parts);
648 $path = implode('/', $parts);
649 $this->slashargument = $path;
650 unset($this->params[$parameter]);
652 } else {
653 $this->slashargument = '';
654 $this->params[$parameter] = $path;
658 // == static factory methods ==
661 * General moodle file url.
662 * @param string $urlbase the script serving the file
663 * @param string $path
664 * @param bool $forcedownload
665 * @return moodle_url
667 public static function make_file_url($urlbase, $path, $forcedownload = false) {
668 global $CFG;
670 $params = array();
671 if ($forcedownload) {
672 $params['forcedownload'] = 1;
675 $url = new moodle_url($urlbase, $params);
676 $url->set_slashargument($path);
678 return $url;
682 * Factory method for creation of url pointing to plugin file.
683 * Please note this method can be used only from the plugins to
684 * create urls of own files, it must not be used outside of plugins!
685 * @param int $contextid
686 * @param string $component
687 * @param string $area
688 * @param int $itemid
689 * @param string $pathname
690 * @param string $filename
691 * @param bool $forcedownload
692 * @return moodle_url
694 public static function make_pluginfile_url($contextid, $component, $area, $itemid, $pathname, $filename, $forcedownload = false) {
695 global $CFG;
696 $urlbase = "$CFG->httpswwwroot/pluginfile.php";
697 if ($itemid === NULL) {
698 return self::make_file_url($urlbase, "/$contextid/$component/$area".$pathname.$filename, $forcedownload);
699 } else {
700 return self::make_file_url($urlbase, "/$contextid/$component/$area/$itemid".$pathname.$filename, $forcedownload);
705 * Factory method for creation of url pointing to draft
706 * file of current user.
707 * @param int $draftid draft item id
708 * @param string $pathname
709 * @param string $filename
710 * @param bool $forcedownload
711 * @return moodle_url
713 public static function make_draftfile_url($draftid, $pathname, $filename, $forcedownload = false) {
714 global $CFG, $USER;
715 $urlbase = "$CFG->httpswwwroot/draftfile.php";
716 $context = get_context_instance(CONTEXT_USER, $USER->id);
718 return self::make_file_url($urlbase, "/$context->id/user/draft/$draftid".$pathname.$filename, $forcedownload);
722 * Factory method for creating of links to legacy
723 * course files.
724 * @param int $courseid
725 * @param string $filepath
726 * @param bool $forcedownload
727 * @return moodle_url
729 public static function make_legacyfile_url($courseid, $filepath, $forcedownload = false) {
730 global $CFG;
732 $urlbase = "$CFG->wwwroot/file.php";
733 return self::make_file_url($urlbase, '/'.$courseid.'/'.$filepath, $forcedownload);
737 * Returns URL a relative path from $CFG->wwwroot
739 * Can be used for passing around urls with the wwwroot stripped
741 * @param boolean $escaped Use &amp; as params separator instead of plain &
742 * @param array $overrideparams params to add to the output url, these override existing ones with the same name.
743 * @return string Resulting URL
744 * @throws coding_exception if called on a non-local url
746 public function out_as_local_url($escaped = true, array $overrideparams = null) {
747 global $CFG;
749 $url = $this->out($escaped, $overrideparams);
750 $httpswwwroot = str_replace("http://", "https://", $CFG->wwwroot);
752 // $url should be equal to wwwroot or httpswwwroot. If not then throw exception.
753 if (($url === $CFG->wwwroot) || (strpos($url, $CFG->wwwroot.'/') === 0)) {
754 $localurl = substr($url, strlen($CFG->wwwroot));
755 return !empty($localurl) ? $localurl : '';
756 } else if (($url === $httpswwwroot) || (strpos($url, $httpswwwroot.'/') === 0)) {
757 $localurl = substr($url, strlen($httpswwwroot));
758 return !empty($localurl) ? $localurl : '';
759 } else {
760 throw new coding_exception('out_as_local_url called on a non-local URL');
765 * Returns the 'path' portion of a URL. For example, if the URL is
766 * http://www.example.org:447/my/file/is/here.txt?really=1 then this will
767 * return '/my/file/is/here.txt'.
769 * By default the path includes slash-arguments (for example,
770 * '/myfile.php/extra/arguments') so it is what you would expect from a
771 * URL path. If you don't want this behaviour, you can opt to exclude the
772 * slash arguments. (Be careful: if the $CFG variable slasharguments is
773 * disabled, these URLs will have a different format and you may need to
774 * look at the 'file' parameter too.)
776 * @param bool $includeslashargument If true, includes slash arguments
777 * @return string Path of URL
779 public function get_path($includeslashargument = true) {
780 return $this->path . ($includeslashargument ? $this->slashargument : '');
784 * Returns a given parameter value from the URL.
786 * @param string $name Name of parameter
787 * @return string Value of parameter or null if not set
789 public function get_param($name) {
790 if (array_key_exists($name, $this->params)) {
791 return $this->params[$name];
792 } else {
793 return null;
799 * Determine if there is data waiting to be processed from a form
801 * Used on most forms in Moodle to check for data
802 * Returns the data as an object, if it's found.
803 * This object can be used in foreach loops without
804 * casting because it's cast to (array) automatically
806 * Checks that submitted POST data exists and returns it as object.
808 * @uses $_POST
809 * @return mixed false or object
811 function data_submitted() {
813 if (empty($_POST)) {
814 return false;
815 } else {
816 return (object)fix_utf8($_POST);
821 * Given some normal text this function will break up any
822 * long words to a given size by inserting the given character
824 * It's multibyte savvy and doesn't change anything inside html tags.
826 * @param string $string the string to be modified
827 * @param int $maxsize maximum length of the string to be returned
828 * @param string $cutchar the string used to represent word breaks
829 * @return string
831 function break_up_long_words($string, $maxsize=20, $cutchar=' ') {
833 /// First of all, save all the tags inside the text to skip them
834 $tags = array();
835 filter_save_tags($string,$tags);
837 /// Process the string adding the cut when necessary
838 $output = '';
839 $length = textlib::strlen($string);
840 $wordlength = 0;
842 for ($i=0; $i<$length; $i++) {
843 $char = textlib::substr($string, $i, 1);
844 if ($char == ' ' or $char == "\t" or $char == "\n" or $char == "\r" or $char == "<" or $char == ">") {
845 $wordlength = 0;
846 } else {
847 $wordlength++;
848 if ($wordlength > $maxsize) {
849 $output .= $cutchar;
850 $wordlength = 0;
853 $output .= $char;
856 /// Finally load the tags back again
857 if (!empty($tags)) {
858 $output = str_replace(array_keys($tags), $tags, $output);
861 return $output;
865 * Try and close the current window using JavaScript, either immediately, or after a delay.
867 * Echo's out the resulting XHTML & javascript
869 * @global object
870 * @global object
871 * @param integer $delay a delay in seconds before closing the window. Default 0.
872 * @param boolean $reloadopener if true, we will see if this window was a pop-up, and try
873 * to reload the parent window before this one closes.
875 function close_window($delay = 0, $reloadopener = false) {
876 global $PAGE, $OUTPUT;
878 if (!$PAGE->headerprinted) {
879 $PAGE->set_title(get_string('closewindow'));
880 echo $OUTPUT->header();
881 } else {
882 $OUTPUT->container_end_all(false);
885 if ($reloadopener) {
886 // Trigger the reload immediately, even if the reload is after a delay.
887 $PAGE->requires->js_function_call('window.opener.location.reload', array(true));
889 $OUTPUT->notification(get_string('windowclosing'), 'notifysuccess');
891 $PAGE->requires->js_function_call('close_window', array(new stdClass()), false, $delay);
893 echo $OUTPUT->footer();
894 exit;
898 * Returns a string containing a link to the user documentation for the current
899 * page. Also contains an icon by default. Shown to teachers and admin only.
901 * @global object
902 * @global object
903 * @param string $text The text to be displayed for the link
904 * @param string $iconpath The path to the icon to be displayed
905 * @return string The link to user documentation for this current page
907 function page_doc_link($text='') {
908 global $CFG, $PAGE, $OUTPUT;
910 if (empty($CFG->docroot) || during_initial_install()) {
911 return '';
913 if (!has_capability('moodle/site:doclinks', $PAGE->context)) {
914 return '';
917 $path = $PAGE->docspath;
918 if (!$path) {
919 return '';
921 return $OUTPUT->doc_link($path, $text);
926 * Validates an email to make sure it makes sense.
928 * @param string $address The email address to validate.
929 * @return boolean
931 function validate_email($address) {
933 return (preg_match('#^[-!\#$%&\'*+\\/0-9=?A-Z^_`a-z{|}~]+'.
934 '(\.[-!\#$%&\'*+\\/0-9=?A-Z^_`a-z{|}~]+)*'.
935 '@'.
936 '[-!\#$%&\'*+\\/0-9=?A-Z^_`a-z{|}~]+\.'.
937 '[-!\#$%&\'*+\\./0-9=?A-Z^_`a-z{|}~]+$#',
938 $address));
942 * Extracts file argument either from file parameter or PATH_INFO
943 * Note: $scriptname parameter is not needed anymore
945 * @global string
946 * @uses $_SERVER
947 * @uses PARAM_PATH
948 * @return string file path (only safe characters)
950 function get_file_argument() {
951 global $SCRIPT;
953 $relativepath = optional_param('file', FALSE, PARAM_PATH);
955 if ($relativepath !== false and $relativepath !== '') {
956 return $relativepath;
958 $relativepath = false;
960 // then try extract file from the slasharguments
961 if (stripos($_SERVER['SERVER_SOFTWARE'], 'iis') !== false) {
962 // NOTE: ISS tends to convert all file paths to single byte DOS encoding,
963 // we can not use other methods because they break unicode chars,
964 // the only way is to use URL rewriting
965 if (isset($_SERVER['PATH_INFO']) and $_SERVER['PATH_INFO'] !== '') {
966 // check that PATH_INFO works == must not contain the script name
967 if (strpos($_SERVER['PATH_INFO'], $SCRIPT) === false) {
968 $relativepath = clean_param(urldecode($_SERVER['PATH_INFO']), PARAM_PATH);
971 } else {
972 // all other apache-like servers depend on PATH_INFO
973 if (isset($_SERVER['PATH_INFO'])) {
974 if (isset($_SERVER['SCRIPT_NAME']) and strpos($_SERVER['PATH_INFO'], $_SERVER['SCRIPT_NAME']) === 0) {
975 $relativepath = substr($_SERVER['PATH_INFO'], strlen($_SERVER['SCRIPT_NAME']));
976 } else {
977 $relativepath = $_SERVER['PATH_INFO'];
979 $relativepath = clean_param($relativepath, PARAM_PATH);
984 return $relativepath;
988 * Just returns an array of text formats suitable for a popup menu
990 * @uses FORMAT_MOODLE
991 * @uses FORMAT_HTML
992 * @uses FORMAT_PLAIN
993 * @uses FORMAT_MARKDOWN
994 * @return array
996 function format_text_menu() {
997 return array (FORMAT_MOODLE => get_string('formattext'),
998 FORMAT_HTML => get_string('formathtml'),
999 FORMAT_PLAIN => get_string('formatplain'),
1000 FORMAT_MARKDOWN => get_string('formatmarkdown'));
1004 * Given text in a variety of format codings, this function returns
1005 * the text as safe HTML.
1007 * This function should mainly be used for long strings like posts,
1008 * answers, glossary items etc. For short strings @see format_string().
1010 * <pre>
1011 * Options:
1012 * trusted : If true the string won't be cleaned. Default false required noclean=true.
1013 * noclean : If true the string won't be cleaned. Default false required trusted=true.
1014 * nocache : If true the strign will not be cached and will be formatted every call. Default false.
1015 * filter : If true the string will be run through applicable filters as well. Default true.
1016 * para : If true then the returned string will be wrapped in div tags. Default true.
1017 * newlines : If true then lines newline breaks will be converted to HTML newline breaks. Default true.
1018 * context : The context that will be used for filtering.
1019 * overflowdiv : If set to true the formatted text will be encased in a div
1020 * with the class no-overflow before being returned. Default false.
1021 * allowid : If true then id attributes will not be removed, even when
1022 * using htmlpurifier. Default false.
1023 * </pre>
1025 * @todo Finish documenting this function
1027 * @staticvar array $croncache
1028 * @param string $text The text to be formatted. This is raw text originally from user input.
1029 * @param int $format Identifier of the text format to be used
1030 * [FORMAT_MOODLE, FORMAT_HTML, FORMAT_PLAIN, FORMAT_MARKDOWN]
1031 * @param object/array $options text formatting options
1032 * @param int $courseid_do_not_use deprecated course id, use context option instead
1033 * @return string
1035 function format_text($text, $format = FORMAT_MOODLE, $options = NULL, $courseid_do_not_use = NULL) {
1036 global $CFG, $COURSE, $DB, $PAGE;
1037 static $croncache = array();
1039 if ($text === '' || is_null($text)) {
1040 return ''; // no need to do any filters and cleaning
1043 $options = (array)$options; // detach object, we can not modify it
1045 if (!isset($options['trusted'])) {
1046 $options['trusted'] = false;
1048 if (!isset($options['noclean'])) {
1049 if ($options['trusted'] and trusttext_active()) {
1050 // no cleaning if text trusted and noclean not specified
1051 $options['noclean'] = true;
1052 } else {
1053 $options['noclean'] = false;
1056 if (!isset($options['nocache'])) {
1057 $options['nocache'] = false;
1059 if (!isset($options['filter'])) {
1060 $options['filter'] = true;
1062 if (!isset($options['para'])) {
1063 $options['para'] = true;
1065 if (!isset($options['newlines'])) {
1066 $options['newlines'] = true;
1068 if (!isset($options['overflowdiv'])) {
1069 $options['overflowdiv'] = false;
1072 // Calculate best context
1073 if (empty($CFG->version) or $CFG->version < 2010072800 or during_initial_install()) {
1074 // do not filter anything during installation or before upgrade completes
1075 $context = null;
1077 } else if (isset($options['context'])) { // first by explicit passed context option
1078 if (is_object($options['context'])) {
1079 $context = $options['context'];
1080 } else {
1081 $context = get_context_instance_by_id($options['context']);
1083 } else if ($courseid_do_not_use) {
1084 // legacy courseid
1085 $context = get_context_instance(CONTEXT_COURSE, $courseid_do_not_use);
1086 } else {
1087 // fallback to $PAGE->context this may be problematic in CLI and other non-standard pages :-(
1088 $context = $PAGE->context;
1091 if (!$context) {
1092 // either install/upgrade or something has gone really wrong because context does not exist (yet?)
1093 $options['nocache'] = true;
1094 $options['filter'] = false;
1097 if ($options['filter']) {
1098 $filtermanager = filter_manager::instance();
1099 $filtermanager->setup_page_for_filters($PAGE, $context); // Setup global stuff filters may have.
1100 } else {
1101 $filtermanager = new null_filter_manager();
1104 if (!empty($CFG->cachetext) and empty($options['nocache'])) {
1105 $hashstr = $text.'-'.$filtermanager->text_filtering_hash($context).'-'.$context->id.'-'.current_language().'-'.
1106 (int)$format.(int)$options['trusted'].(int)$options['noclean'].
1107 (int)$options['para'].(int)$options['newlines'];
1109 $time = time() - $CFG->cachetext;
1110 $md5key = md5($hashstr);
1111 if (CLI_SCRIPT) {
1112 if (isset($croncache[$md5key])) {
1113 return $croncache[$md5key];
1117 if ($oldcacheitem = $DB->get_record('cache_text', array('md5key'=>$md5key), '*', IGNORE_MULTIPLE)) {
1118 if ($oldcacheitem->timemodified >= $time) {
1119 if (CLI_SCRIPT) {
1120 if (count($croncache) > 150) {
1121 reset($croncache);
1122 $key = key($croncache);
1123 unset($croncache[$key]);
1125 $croncache[$md5key] = $oldcacheitem->formattedtext;
1127 return $oldcacheitem->formattedtext;
1132 switch ($format) {
1133 case FORMAT_HTML:
1134 if (!$options['noclean']) {
1135 $text = clean_text($text, FORMAT_HTML, $options);
1137 $text = $filtermanager->filter_text($text, $context, array('originalformat' => FORMAT_HTML, 'noclean' => $options['noclean']));
1138 break;
1140 case FORMAT_PLAIN:
1141 $text = s($text); // cleans dangerous JS
1142 $text = rebuildnolinktag($text);
1143 $text = str_replace(' ', '&nbsp; ', $text);
1144 $text = nl2br($text);
1145 break;
1147 case FORMAT_WIKI:
1148 // this format is deprecated
1149 $text = '<p>NOTICE: Wiki-like formatting has been removed from Moodle. You should not be seeing
1150 this message as all texts should have been converted to Markdown format instead.
1151 Please post a bug report to http://moodle.org/bugs with information about where you
1152 saw this message.</p>'.s($text);
1153 break;
1155 case FORMAT_MARKDOWN:
1156 $text = markdown_to_html($text);
1157 if (!$options['noclean']) {
1158 $text = clean_text($text, FORMAT_HTML, $options);
1160 $text = $filtermanager->filter_text($text, $context, array('originalformat' => FORMAT_MARKDOWN, 'noclean' => $options['noclean']));
1161 break;
1163 default: // FORMAT_MOODLE or anything else
1164 $text = text_to_html($text, null, $options['para'], $options['newlines']);
1165 if (!$options['noclean']) {
1166 $text = clean_text($text, FORMAT_HTML, $options);
1168 $text = $filtermanager->filter_text($text, $context, array('originalformat' => $format, 'noclean' => $options['noclean']));
1169 break;
1171 if ($options['filter']) {
1172 // at this point there should not be any draftfile links any more,
1173 // this happens when developers forget to post process the text.
1174 // The only potential problem is that somebody might try to format
1175 // the text before storing into database which would be itself big bug.
1176 $text = str_replace("\"$CFG->httpswwwroot/draftfile.php", "\"$CFG->httpswwwroot/brokenfile.php#", $text);
1179 // Warn people that we have removed this old mechanism, just in case they
1180 // were stupid enough to rely on it.
1181 if (isset($CFG->currenttextiscacheable)) {
1182 debugging('Once upon a time, Moodle had a truly evil use of global variables ' .
1183 'called $CFG->currenttextiscacheable. The good news is that this no ' .
1184 'longer exists. The bad news is that you seem to be using a filter that '.
1185 'relies on it. Please seek out and destroy that filter code.', DEBUG_DEVELOPER);
1188 if (!empty($options['overflowdiv'])) {
1189 $text = html_writer::tag('div', $text, array('class'=>'no-overflow'));
1192 if (empty($options['nocache']) and !empty($CFG->cachetext)) {
1193 if (CLI_SCRIPT) {
1194 // special static cron cache - no need to store it in db if its not already there
1195 if (count($croncache) > 150) {
1196 reset($croncache);
1197 $key = key($croncache);
1198 unset($croncache[$key]);
1200 $croncache[$md5key] = $text;
1201 return $text;
1204 $newcacheitem = new stdClass();
1205 $newcacheitem->md5key = $md5key;
1206 $newcacheitem->formattedtext = $text;
1207 $newcacheitem->timemodified = time();
1208 if ($oldcacheitem) { // See bug 4677 for discussion
1209 $newcacheitem->id = $oldcacheitem->id;
1210 try {
1211 $DB->update_record('cache_text', $newcacheitem); // Update existing record in the cache table
1212 } catch (dml_exception $e) {
1213 // It's unlikely that the cron cache cleaner could have
1214 // deleted this entry in the meantime, as it allows
1215 // some extra time to cover these cases.
1217 } else {
1218 try {
1219 $DB->insert_record('cache_text', $newcacheitem); // Insert a new record in the cache table
1220 } catch (dml_exception $e) {
1221 // Again, it's possible that another user has caused this
1222 // record to be created already in the time that it took
1223 // to traverse this function. That's OK too, as the
1224 // call above handles duplicate entries, and eventually
1225 // the cron cleaner will delete them.
1230 return $text;
1234 * Resets all data related to filters, called during upgrade or when filter settings change.
1236 * @global object
1237 * @global object
1238 * @return void
1240 function reset_text_filters_cache() {
1241 global $CFG, $DB;
1243 $DB->delete_records('cache_text');
1244 $purifdir = $CFG->cachedir.'/htmlpurifier';
1245 remove_dir($purifdir, true);
1249 * Given a simple string, this function returns the string
1250 * processed by enabled string filters if $CFG->filterall is enabled
1252 * This function should be used to print short strings (non html) that
1253 * need filter processing e.g. activity titles, post subjects,
1254 * glossary concepts.
1256 * @staticvar bool $strcache
1257 * @param string $string The string to be filtered. Should be plain text, expect
1258 * possibly for multilang tags.
1259 * @param boolean $striplinks To strip any link in the result text.
1260 Moodle 1.8 default changed from false to true! MDL-8713
1261 * @param array $options options array/object or courseid
1262 * @return string
1264 function format_string($string, $striplinks = true, $options = NULL) {
1265 global $CFG, $COURSE, $PAGE;
1267 //We'll use a in-memory cache here to speed up repeated strings
1268 static $strcache = false;
1270 if (empty($CFG->version) or $CFG->version < 2010072800 or during_initial_install()) {
1271 // do not filter anything during installation or before upgrade completes
1272 return $string = strip_tags($string);
1275 if ($strcache === false or count($strcache) > 2000) { // this number might need some tuning to limit memory usage in cron
1276 $strcache = array();
1279 if (is_numeric($options)) {
1280 // legacy courseid usage
1281 $options = array('context'=>get_context_instance(CONTEXT_COURSE, $options));
1282 } else {
1283 $options = (array)$options; // detach object, we can not modify it
1286 if (empty($options['context'])) {
1287 // fallback to $PAGE->context this may be problematic in CLI and other non-standard pages :-(
1288 $options['context'] = $PAGE->context;
1289 } else if (is_numeric($options['context'])) {
1290 $options['context'] = get_context_instance_by_id($options['context']);
1293 if (!$options['context']) {
1294 // we did not find any context? weird
1295 return $string = strip_tags($string);
1298 //Calculate md5
1299 $md5 = md5($string.'<+>'.$striplinks.'<+>'.$options['context']->id.'<+>'.current_language());
1301 //Fetch from cache if possible
1302 if (isset($strcache[$md5])) {
1303 return $strcache[$md5];
1306 // First replace all ampersands not followed by html entity code
1307 // Regular expression moved to its own method for easier unit testing
1308 $string = replace_ampersands_not_followed_by_entity($string);
1310 if (!empty($CFG->filterall)) {
1311 $filtermanager = filter_manager::instance();
1312 $filtermanager->setup_page_for_filters($PAGE, $options['context']); // Setup global stuff filters may have.
1313 $string = $filtermanager->filter_string($string, $options['context']);
1316 // If the site requires it, strip ALL tags from this string
1317 if (!empty($CFG->formatstringstriptags)) {
1318 $string = str_replace(array('<', '>'), array('&lt;', '&gt;'), strip_tags($string));
1320 } else {
1321 // Otherwise strip just links if that is required (default)
1322 if ($striplinks) { //strip links in string
1323 $string = strip_links($string);
1325 $string = clean_text($string);
1328 //Store to cache
1329 $strcache[$md5] = $string;
1331 return $string;
1335 * Given a string, performs a negative lookahead looking for any ampersand character
1336 * that is not followed by a proper HTML entity. If any is found, it is replaced
1337 * by &amp;. The string is then returned.
1339 * @param string $string
1340 * @return string
1342 function replace_ampersands_not_followed_by_entity($string) {
1343 return preg_replace("/\&(?![a-zA-Z0-9#]{1,8};)/", "&amp;", $string);
1347 * Given a string, replaces all <a>.*</a> by .* and returns the string.
1349 * @param string $string
1350 * @return string
1352 function strip_links($string) {
1353 return preg_replace('/(<a\s[^>]+?>)(.+?)(<\/a>)/is','$2',$string);
1357 * This expression turns links into something nice in a text format. (Russell Jungwirth)
1359 * @param string $string
1360 * @return string
1362 function wikify_links($string) {
1363 return preg_replace('~(<a [^<]*href=["|\']?([^ "\']*)["|\']?[^>]*>([^<]*)</a>)~i','$3 [ $2 ]', $string);
1367 * Given text in a variety of format codings, this function returns
1368 * the text as plain text suitable for plain email.
1370 * @uses FORMAT_MOODLE
1371 * @uses FORMAT_HTML
1372 * @uses FORMAT_PLAIN
1373 * @uses FORMAT_WIKI
1374 * @uses FORMAT_MARKDOWN
1375 * @param string $text The text to be formatted. This is raw text originally from user input.
1376 * @param int $format Identifier of the text format to be used
1377 * [FORMAT_MOODLE, FORMAT_HTML, FORMAT_PLAIN, FORMAT_WIKI, FORMAT_MARKDOWN]
1378 * @return string
1380 function format_text_email($text, $format) {
1382 switch ($format) {
1384 case FORMAT_PLAIN:
1385 return $text;
1386 break;
1388 case FORMAT_WIKI:
1389 // there should not be any of these any more!
1390 $text = wikify_links($text);
1391 return textlib::entities_to_utf8(strip_tags($text), true);
1392 break;
1394 case FORMAT_HTML:
1395 return html_to_text($text);
1396 break;
1398 case FORMAT_MOODLE:
1399 case FORMAT_MARKDOWN:
1400 default:
1401 $text = wikify_links($text);
1402 return textlib::entities_to_utf8(strip_tags($text), true);
1403 break;
1408 * Formats activity intro text
1410 * @global object
1411 * @uses CONTEXT_MODULE
1412 * @param string $module name of module
1413 * @param object $activity instance of activity
1414 * @param int $cmid course module id
1415 * @param bool $filter filter resulting html text
1416 * @return text
1418 function format_module_intro($module, $activity, $cmid, $filter=true) {
1419 global $CFG;
1420 require_once("$CFG->libdir/filelib.php");
1421 $context = get_context_instance(CONTEXT_MODULE, $cmid);
1422 $options = array('noclean'=>true, 'para'=>false, 'filter'=>$filter, 'context'=>$context, 'overflowdiv'=>true);
1423 $intro = file_rewrite_pluginfile_urls($activity->intro, 'pluginfile.php', $context->id, 'mod_'.$module, 'intro', null);
1424 return trim(format_text($intro, $activity->introformat, $options, null));
1428 * Legacy function, used for cleaning of old forum and glossary text only.
1430 * @global object
1431 * @param string $text text that may contain legacy TRUSTTEXT marker
1432 * @return text without legacy TRUSTTEXT marker
1434 function trusttext_strip($text) {
1435 while (true) { //removing nested TRUSTTEXT
1436 $orig = $text;
1437 $text = str_replace('#####TRUSTTEXT#####', '', $text);
1438 if (strcmp($orig, $text) === 0) {
1439 return $text;
1445 * Must be called before editing of all texts
1446 * with trust flag. Removes all XSS nasties
1447 * from texts stored in database if needed.
1449 * @param object $object data object with xxx, xxxformat and xxxtrust fields
1450 * @param string $field name of text field
1451 * @param object $context active context
1452 * @return object updated $object
1454 function trusttext_pre_edit($object, $field, $context) {
1455 $trustfield = $field.'trust';
1456 $formatfield = $field.'format';
1458 if (!$object->$trustfield or !trusttext_trusted($context)) {
1459 $object->$field = clean_text($object->$field, $object->$formatfield);
1462 return $object;
1466 * Is current user trusted to enter no dangerous XSS in this context?
1468 * Please note the user must be in fact trusted everywhere on this server!!
1470 * @param object $context
1471 * @return bool true if user trusted
1473 function trusttext_trusted($context) {
1474 return (trusttext_active() and has_capability('moodle/site:trustcontent', $context));
1478 * Is trusttext feature active?
1480 * @return bool
1482 function trusttext_active() {
1483 global $CFG;
1485 return !empty($CFG->enabletrusttext);
1489 * Given raw text (eg typed in by a user), this function cleans it up
1490 * and removes any nasty tags that could mess up Moodle pages through XSS attacks.
1492 * The result must be used as a HTML text fragment, this function can not cleanup random
1493 * parts of html tags such as url or src attributes.
1495 * NOTE: the format parameter was deprecated because we can safely clean only HTML.
1497 * @param string $text The text to be cleaned
1498 * @param int|string $format deprecated parameter, should always contain FORMAT_HTML or FORMAT_MOODLE
1499 * @param array $options Array of options; currently only option supported is 'allowid' (if true,
1500 * does not remove id attributes when cleaning)
1501 * @return string The cleaned up text
1503 function clean_text($text, $format = FORMAT_HTML, $options = array()) {
1504 $text = (string)$text;
1506 if ($format != FORMAT_HTML and $format != FORMAT_HTML) {
1507 // TODO: we need to standardise cleanup of text when loading it into editor first
1508 //debugging('clean_text() is designed to work only with html');
1511 if ($format == FORMAT_PLAIN) {
1512 return $text;
1515 if (is_purify_html_necessary($text)) {
1516 $text = purify_html($text, $options);
1519 // Originally we tried to neutralise some script events here, it was a wrong approach because
1520 // it was trivial to work around that (for example using style based XSS exploits).
1521 // We must not give false sense of security here - all developers MUST understand how to use
1522 // rawurlencode(), htmlentities(), htmlspecialchars(), p(), s(), moodle_url, html_writer and friends!!!
1524 return $text;
1528 * Is it necessary to use HTMLPurifier?
1529 * @private
1530 * @param string $text
1531 * @return bool false means html is safe and valid, true means use HTMLPurifier
1533 function is_purify_html_necessary($text) {
1534 if ($text === '') {
1535 return false;
1538 if ($text === (string)((int)$text)) {
1539 return false;
1542 if (strpos($text, '&') !== false or preg_match('|<[^pesb/]|', $text)) {
1543 // we need to normalise entities or other tags except p, em, strong and br present
1544 return true;
1547 $altered = htmlspecialchars($text, ENT_NOQUOTES, 'UTF-8', true);
1548 if ($altered === $text) {
1549 // no < > or other special chars means this must be safe
1550 return false;
1553 // let's try to convert back some safe html tags
1554 $altered = preg_replace('|&lt;p&gt;(.*?)&lt;/p&gt;|m', '<p>$1</p>', $altered);
1555 if ($altered === $text) {
1556 return false;
1558 $altered = preg_replace('|&lt;em&gt;([^<>]+?)&lt;/em&gt;|m', '<em>$1</em>', $altered);
1559 if ($altered === $text) {
1560 return false;
1562 $altered = preg_replace('|&lt;strong&gt;([^<>]+?)&lt;/strong&gt;|m', '<strong>$1</strong>', $altered);
1563 if ($altered === $text) {
1564 return false;
1566 $altered = str_replace('&lt;br /&gt;', '<br />', $altered);
1567 if ($altered === $text) {
1568 return false;
1571 return true;
1575 * KSES replacement cleaning function - uses HTML Purifier.
1577 * @param string $text The (X)HTML string to purify
1578 * @param array $options Array of options; currently only option supported is 'allowid' (if set,
1579 * does not remove id attributes when cleaning)
1580 * @return string
1582 function purify_html($text, $options = array()) {
1583 global $CFG;
1585 $type = !empty($options['allowid']) ? 'allowid' : 'normal';
1586 static $purifiers = array();
1587 if (empty($purifiers[$type])) {
1589 // make sure the serializer dir exists, it should be fine if it disappears later during cache reset
1590 $cachedir = $CFG->cachedir.'/htmlpurifier';
1591 check_dir_exists($cachedir);
1593 require_once $CFG->libdir.'/htmlpurifier/HTMLPurifier.safe-includes.php';
1594 require_once $CFG->libdir.'/htmlpurifier/locallib.php';
1595 $config = HTMLPurifier_Config::createDefault();
1597 $config->set('HTML.DefinitionID', 'moodlehtml');
1598 $config->set('HTML.DefinitionRev', 2);
1599 $config->set('Cache.SerializerPath', $cachedir);
1600 $config->set('Cache.SerializerPermissions', $CFG->directorypermissions);
1601 $config->set('Core.NormalizeNewlines', false);
1602 $config->set('Core.ConvertDocumentToFragment', true);
1603 $config->set('Core.Encoding', 'UTF-8');
1604 $config->set('HTML.Doctype', 'XHTML 1.0 Transitional');
1605 $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));
1606 $config->set('Attr.AllowedFrameTargets', array('_blank'));
1608 if (!empty($CFG->allowobjectembed)) {
1609 $config->set('HTML.SafeObject', true);
1610 $config->set('Output.FlashCompat', true);
1611 $config->set('HTML.SafeEmbed', true);
1614 if ($type === 'allowid') {
1615 $config->set('Attr.EnableID', true);
1618 if ($def = $config->maybeGetRawHTMLDefinition()) {
1619 $def->addElement('nolink', 'Block', 'Flow', array()); // skip our filters inside
1620 $def->addElement('tex', 'Inline', 'Inline', array()); // tex syntax, equivalent to $$xx$$
1621 $def->addElement('algebra', 'Inline', 'Inline', array()); // algebra syntax, equivalent to @@xx@@
1622 $def->addElement('lang', 'Block', 'Flow', array(), array('lang'=>'CDATA')); // old and future style multilang - only our hacked lang attribute
1623 $def->addAttribute('span', 'xxxlang', 'CDATA'); // current problematic multilang
1626 $purifier = new HTMLPurifier($config);
1627 $purifiers[$type] = $purifier;
1628 } else {
1629 $purifier = $purifiers[$type];
1632 $multilang = (strpos($text, 'class="multilang"') !== false);
1634 if ($multilang) {
1635 $text = preg_replace('/<span(\s+lang="([a-zA-Z0-9_-]+)"|\s+class="multilang"){2}\s*>/', '<span xxxlang="${2}">', $text);
1637 $text = $purifier->purify($text);
1638 if ($multilang) {
1639 $text = preg_replace('/<span xxxlang="([a-zA-Z0-9_-]+)">/', '<span lang="${1}" class="multilang">', $text);
1642 return $text;
1646 * Given plain text, makes it into HTML as nicely as possible.
1647 * May contain HTML tags already
1649 * Do not abuse this function. It is intended as lower level formatting feature used
1650 * by {@see format_text()} to convert FORMAT_MOODLE to HTML. You are supposed
1651 * to call format_text() in most of cases.
1653 * @param string $text The string to convert.
1654 * @param boolean $smiley_ignored Was used to determine if smiley characters should convert to smiley images, ignored now
1655 * @param boolean $para If true then the returned string will be wrapped in div tags
1656 * @param boolean $newlines If true then lines newline breaks will be converted to HTML newline breaks.
1657 * @return string
1659 function text_to_html($text, $smiley_ignored=null, $para=true, $newlines=true) {
1660 /// Remove any whitespace that may be between HTML tags
1661 $text = preg_replace("~>([[:space:]]+)<~i", "><", $text);
1663 /// Remove any returns that precede or follow HTML tags
1664 $text = preg_replace("~([\n\r])<~i", " <", $text);
1665 $text = preg_replace("~>([\n\r])~i", "> ", $text);
1667 /// Make returns into HTML newlines.
1668 if ($newlines) {
1669 $text = nl2br($text);
1672 /// Wrap the whole thing in a div if required
1673 if ($para) {
1674 //return '<p>'.$text.'</p>'; //1.9 version
1675 return '<div class="text_to_html">'.$text.'</div>';
1676 } else {
1677 return $text;
1682 * Given Markdown formatted text, make it into XHTML using external function
1684 * @global object
1685 * @param string $text The markdown formatted text to be converted.
1686 * @return string Converted text
1688 function markdown_to_html($text) {
1689 global $CFG;
1691 if ($text === '' or $text === NULL) {
1692 return $text;
1695 require_once($CFG->libdir .'/markdown.php');
1697 return Markdown($text);
1701 * Given HTML text, make it into plain text using external function
1703 * @param string $html The text to be converted.
1704 * @param integer $width Width to wrap the text at. (optional, default 75 which
1705 * is a good value for email. 0 means do not limit line length.)
1706 * @param boolean $dolinks By default, any links in the HTML are collected, and
1707 * printed as a list at the end of the HTML. If you don't want that, set this
1708 * argument to false.
1709 * @return string plain text equivalent of the HTML.
1711 function html_to_text($html, $width = 75, $dolinks = true) {
1713 global $CFG;
1715 require_once($CFG->libdir .'/html2text.php');
1717 $h2t = new html2text($html, false, $dolinks, $width);
1718 $result = $h2t->get_text();
1720 return $result;
1724 * This function will highlight search words in a given string
1726 * It cares about HTML and will not ruin links. It's best to use
1727 * this function after performing any conversions to HTML.
1729 * @param string $needle The search string. Syntax like "word1 +word2 -word3" is dealt with correctly.
1730 * @param string $haystack The string (HTML) within which to highlight the search terms.
1731 * @param boolean $matchcase whether to do case-sensitive. Default case-insensitive.
1732 * @param string $prefix the string to put before each search term found.
1733 * @param string $suffix the string to put after each search term found.
1734 * @return string The highlighted HTML.
1736 function highlight($needle, $haystack, $matchcase = false,
1737 $prefix = '<span class="highlight">', $suffix = '</span>') {
1739 /// Quick bail-out in trivial cases.
1740 if (empty($needle) or empty($haystack)) {
1741 return $haystack;
1744 /// Break up the search term into words, discard any -words and build a regexp.
1745 $words = preg_split('/ +/', trim($needle));
1746 foreach ($words as $index => $word) {
1747 if (strpos($word, '-') === 0) {
1748 unset($words[$index]);
1749 } else if (strpos($word, '+') === 0) {
1750 $words[$index] = '\b' . preg_quote(ltrim($word, '+'), '/') . '\b'; // Match only as a complete word.
1751 } else {
1752 $words[$index] = preg_quote($word, '/');
1755 $regexp = '/(' . implode('|', $words) . ')/u'; // u is do UTF-8 matching.
1756 if (!$matchcase) {
1757 $regexp .= 'i';
1760 /// Another chance to bail-out if $search was only -words
1761 if (empty($words)) {
1762 return $haystack;
1765 /// Find all the HTML tags in the input, and store them in a placeholders array.
1766 $placeholders = array();
1767 $matches = array();
1768 preg_match_all('/<[^>]*>/', $haystack, $matches);
1769 foreach (array_unique($matches[0]) as $key => $htmltag) {
1770 $placeholders['<|' . $key . '|>'] = $htmltag;
1773 /// In $hastack, replace each HTML tag with the corresponding placeholder.
1774 $haystack = str_replace($placeholders, array_keys($placeholders), $haystack);
1776 /// In the resulting string, Do the highlighting.
1777 $haystack = preg_replace($regexp, $prefix . '$1' . $suffix, $haystack);
1779 /// Turn the placeholders back into HTML tags.
1780 $haystack = str_replace(array_keys($placeholders), $placeholders, $haystack);
1782 return $haystack;
1786 * This function will highlight instances of $needle in $haystack
1788 * It's faster that the above function {@link highlight()} and doesn't care about
1789 * HTML or anything.
1791 * @param string $needle The string to search for
1792 * @param string $haystack The string to search for $needle in
1793 * @return string The highlighted HTML
1795 function highlightfast($needle, $haystack) {
1797 if (empty($needle) or empty($haystack)) {
1798 return $haystack;
1801 $parts = explode(textlib::strtolower($needle), textlib::strtolower($haystack));
1803 if (count($parts) === 1) {
1804 return $haystack;
1807 $pos = 0;
1809 foreach ($parts as $key => $part) {
1810 $parts[$key] = substr($haystack, $pos, strlen($part));
1811 $pos += strlen($part);
1813 $parts[$key] .= '<span class="highlight">'.substr($haystack, $pos, strlen($needle)).'</span>';
1814 $pos += strlen($needle);
1817 return str_replace('<span class="highlight"></span>', '', join('', $parts));
1821 * Return a string containing 'lang', xml:lang and optionally 'dir' HTML attributes.
1822 * Internationalisation, for print_header and backup/restorelib.
1824 * @param bool $dir Default false
1825 * @return string Attributes
1827 function get_html_lang($dir = false) {
1828 $direction = '';
1829 if ($dir) {
1830 if (right_to_left()) {
1831 $direction = ' dir="rtl"';
1832 } else {
1833 $direction = ' dir="ltr"';
1836 //Accessibility: added the 'lang' attribute to $direction, used in theme <html> tag.
1837 $language = str_replace('_', '-', current_language());
1838 @header('Content-Language: '.$language);
1839 return ($direction.' lang="'.$language.'" xml:lang="'.$language.'"');
1843 /// STANDARD WEB PAGE PARTS ///////////////////////////////////////////////////
1846 * Send the HTTP headers that Moodle requires.
1847 * @param $cacheable Can this page be cached on back?
1849 function send_headers($contenttype, $cacheable = true) {
1850 global $CFG;
1852 @header('Content-Type: ' . $contenttype);
1853 @header('Content-Script-Type: text/javascript');
1854 @header('Content-Style-Type: text/css');
1856 if ($cacheable) {
1857 // Allow caching on "back" (but not on normal clicks)
1858 @header('Cache-Control: private, pre-check=0, post-check=0, max-age=0');
1859 @header('Pragma: no-cache');
1860 @header('Expires: ');
1861 } else {
1862 // Do everything we can to always prevent clients and proxies caching
1863 @header('Cache-Control: no-store, no-cache, must-revalidate');
1864 @header('Cache-Control: post-check=0, pre-check=0', false);
1865 @header('Pragma: no-cache');
1866 @header('Expires: Mon, 20 Aug 1969 09:23:00 GMT');
1867 @header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
1869 @header('Accept-Ranges: none');
1871 if (empty($CFG->allowframembedding)) {
1872 @header('X-Frame-Options: sameorigin');
1877 * Return the right arrow with text ('next'), and optionally embedded in a link.
1879 * @global object
1880 * @param string $text HTML/plain text label (set to blank only for breadcrumb separator cases).
1881 * @param string $url An optional link to use in a surrounding HTML anchor.
1882 * @param bool $accesshide True if text should be hidden (for screen readers only).
1883 * @param string $addclass Additional class names for the link, or the arrow character.
1884 * @return string HTML string.
1886 function link_arrow_right($text, $url='', $accesshide=false, $addclass='') {
1887 global $OUTPUT; //TODO: move to output renderer
1888 $arrowclass = 'arrow ';
1889 if (! $url) {
1890 $arrowclass .= $addclass;
1892 $arrow = '<span class="'.$arrowclass.'">'.$OUTPUT->rarrow().'</span>';
1893 $htmltext = '';
1894 if ($text) {
1895 $htmltext = '<span class="arrow_text">'.$text.'</span>&nbsp;';
1896 if ($accesshide) {
1897 $htmltext = get_accesshide($htmltext);
1900 if ($url) {
1901 $class = 'arrow_link';
1902 if ($addclass) {
1903 $class .= ' '.$addclass;
1905 return '<a class="'.$class.'" href="'.$url.'" title="'.preg_replace('/<.*?>/','',$text).'">'.$htmltext.$arrow.'</a>';
1907 return $htmltext.$arrow;
1911 * Return the left arrow with text ('previous'), and optionally embedded in a link.
1913 * @global object
1914 * @param string $text HTML/plain text label (set to blank only for breadcrumb separator cases).
1915 * @param string $url An optional link to use in a surrounding HTML anchor.
1916 * @param bool $accesshide True if text should be hidden (for screen readers only).
1917 * @param string $addclass Additional class names for the link, or the arrow character.
1918 * @return string HTML string.
1920 function link_arrow_left($text, $url='', $accesshide=false, $addclass='') {
1921 global $OUTPUT; // TODO: move to utput renderer
1922 $arrowclass = 'arrow ';
1923 if (! $url) {
1924 $arrowclass .= $addclass;
1926 $arrow = '<span class="'.$arrowclass.'">'.$OUTPUT->larrow().'</span>';
1927 $htmltext = '';
1928 if ($text) {
1929 $htmltext = '&nbsp;<span class="arrow_text">'.$text.'</span>';
1930 if ($accesshide) {
1931 $htmltext = get_accesshide($htmltext);
1934 if ($url) {
1935 $class = 'arrow_link';
1936 if ($addclass) {
1937 $class .= ' '.$addclass;
1939 return '<a class="'.$class.'" href="'.$url.'" title="'.preg_replace('/<.*?>/','',$text).'">'.$arrow.$htmltext.'</a>';
1941 return $arrow.$htmltext;
1945 * Return a HTML element with the class "accesshide", for accessibility.
1946 * Please use cautiously - where possible, text should be visible!
1948 * @param string $text Plain text.
1949 * @param string $elem Lowercase element name, default "span".
1950 * @param string $class Additional classes for the element.
1951 * @param string $attrs Additional attributes string in the form, "name='value' name2='value2'"
1952 * @return string HTML string.
1954 function get_accesshide($text, $elem='span', $class='', $attrs='') {
1955 return "<$elem class=\"accesshide $class\" $attrs>$text</$elem>";
1959 * Return the breadcrumb trail navigation separator.
1961 * @return string HTML string.
1963 function get_separator() {
1964 //Accessibility: the 'hidden' slash is preferred for screen readers.
1965 return ' '.link_arrow_right($text='/', $url='', $accesshide=true, 'sep').' ';
1969 * Print (or return) a collapsible region, that has a caption that can
1970 * be clicked to expand or collapse the region.
1972 * If JavaScript is off, then the region will always be expanded.
1974 * @param string $contents the contents of the box.
1975 * @param string $classes class names added to the div that is output.
1976 * @param string $id id added to the div that is output. Must not be blank.
1977 * @param string $caption text displayed at the top. Clicking on this will cause the region to expand or contract.
1978 * @param string $userpref the name of the user preference that stores the user's preferred default state.
1979 * (May be blank if you do not wish the state to be persisted.
1980 * @param boolean $default Initial collapsed state to use if the user_preference it not set.
1981 * @param boolean $return if true, return the HTML as a string, rather than printing it.
1982 * @return string|void If $return is false, returns nothing, otherwise returns a string of HTML.
1984 function print_collapsible_region($contents, $classes, $id, $caption, $userpref = '', $default = false, $return = false) {
1985 $output = print_collapsible_region_start($classes, $id, $caption, $userpref, $default, true);
1986 $output .= $contents;
1987 $output .= print_collapsible_region_end(true);
1989 if ($return) {
1990 return $output;
1991 } else {
1992 echo $output;
1997 * Print (or return) the start of a collapsible region, that has a caption that can
1998 * be clicked to expand or collapse the region. If JavaScript is off, then the region
1999 * will always be expanded.
2001 * @param string $classes class names added to the div that is output.
2002 * @param string $id id added to the div that is output. Must not be blank.
2003 * @param string $caption text displayed at the top. Clicking on this will cause the region to expand or contract.
2004 * @param string $userpref the name of the user preference that stores the user's preferred default state.
2005 * (May be blank if you do not wish the state to be persisted.
2006 * @param boolean $default Initial collapsed state to use if the user_preference it not set.
2007 * @param boolean $return if true, return the HTML as a string, rather than printing it.
2008 * @return string|void if $return is false, returns nothing, otherwise returns a string of HTML.
2010 function print_collapsible_region_start($classes, $id, $caption, $userpref = '', $default = false, $return = false) {
2011 global $CFG, $PAGE, $OUTPUT;
2013 // Work out the initial state.
2014 if (!empty($userpref) and is_string($userpref)) {
2015 user_preference_allow_ajax_update($userpref, PARAM_BOOL);
2016 $collapsed = get_user_preferences($userpref, $default);
2017 } else {
2018 $collapsed = $default;
2019 $userpref = false;
2022 if ($collapsed) {
2023 $classes .= ' collapsed';
2026 $output = '';
2027 $output .= '<div id="' . $id . '" class="collapsibleregion ' . $classes . '">';
2028 $output .= '<div id="' . $id . '_sizer">';
2029 $output .= '<div id="' . $id . '_caption" class="collapsibleregioncaption">';
2030 $output .= $caption . ' ';
2031 $output .= '</div><div id="' . $id . '_inner" class="collapsibleregioninner">';
2032 $PAGE->requires->js_init_call('M.util.init_collapsible_region', array($id, $userpref, get_string('clicktohideshow')));
2034 if ($return) {
2035 return $output;
2036 } else {
2037 echo $output;
2042 * Close a region started with print_collapsible_region_start.
2044 * @param boolean $return if true, return the HTML as a string, rather than printing it.
2045 * @return string|void if $return is false, returns nothing, otherwise returns a string of HTML.
2047 function print_collapsible_region_end($return = false) {
2048 $output = '</div></div></div>';
2050 if ($return) {
2051 return $output;
2052 } else {
2053 echo $output;
2058 * Print a specified group's avatar.
2060 * @global object
2061 * @uses CONTEXT_COURSE
2062 * @param array|stdClass $group A single {@link group} object OR array of groups.
2063 * @param int $courseid The course ID.
2064 * @param boolean $large Default small picture, or large.
2065 * @param boolean $return If false print picture, otherwise return the output as string
2066 * @param boolean $link Enclose image in a link to view specified course?
2067 * @return string|void Depending on the setting of $return
2069 function print_group_picture($group, $courseid, $large=false, $return=false, $link=true) {
2070 global $CFG;
2072 if (is_array($group)) {
2073 $output = '';
2074 foreach($group as $g) {
2075 $output .= print_group_picture($g, $courseid, $large, true, $link);
2077 if ($return) {
2078 return $output;
2079 } else {
2080 echo $output;
2081 return;
2085 $context = get_context_instance(CONTEXT_COURSE, $courseid);
2087 // If there is no picture, do nothing
2088 if (!$group->picture) {
2089 return '';
2092 // If picture is hidden, only show to those with course:managegroups
2093 if ($group->hidepicture and !has_capability('moodle/course:managegroups', $context)) {
2094 return '';
2097 if ($link or has_capability('moodle/site:accessallgroups', $context)) {
2098 $output = '<a href="'. $CFG->wwwroot .'/user/index.php?id='. $courseid .'&amp;group='. $group->id .'">';
2099 } else {
2100 $output = '';
2102 if ($large) {
2103 $file = 'f1';
2104 } else {
2105 $file = 'f2';
2108 $grouppictureurl = moodle_url::make_pluginfile_url($context->id, 'group', 'icon', $group->id, '/', $file);
2109 $output .= '<img class="grouppicture" src="'.$grouppictureurl.'"'.
2110 ' alt="'.s(get_string('group').' '.$group->name).'" title="'.s($group->name).'"/>';
2112 if ($link or has_capability('moodle/site:accessallgroups', $context)) {
2113 $output .= '</a>';
2116 if ($return) {
2117 return $output;
2118 } else {
2119 echo $output;
2125 * Display a recent activity note
2127 * @uses CONTEXT_SYSTEM
2128 * @staticvar string $strftimerecent
2129 * @param object A time object
2130 * @param object A user object
2131 * @param string $text Text for display for the note
2132 * @param string $link The link to wrap around the text
2133 * @param bool $return If set to true the HTML is returned rather than echo'd
2134 * @param string $viewfullnames
2136 function print_recent_activity_note($time, $user, $text, $link, $return=false, $viewfullnames=null) {
2137 static $strftimerecent = null;
2138 $output = '';
2140 if (is_null($viewfullnames)) {
2141 $context = get_context_instance(CONTEXT_SYSTEM);
2142 $viewfullnames = has_capability('moodle/site:viewfullnames', $context);
2145 if (is_null($strftimerecent)) {
2146 $strftimerecent = get_string('strftimerecent');
2149 $output .= '<div class="head">';
2150 $output .= '<div class="date">'.userdate($time, $strftimerecent).'</div>';
2151 $output .= '<div class="name">'.fullname($user, $viewfullnames).'</div>';
2152 $output .= '</div>';
2153 $output .= '<div class="info"><a href="'.$link.'">'.format_string($text,true).'</a></div>';
2155 if ($return) {
2156 return $output;
2157 } else {
2158 echo $output;
2163 * Returns a popup menu with course activity modules
2165 * Given a course
2166 * This function returns a small popup menu with all the
2167 * course activity modules in it, as a navigation menu
2168 * outputs a simple list structure in XHTML
2169 * The data is taken from the serialised array stored in
2170 * the course record
2172 * @todo Finish documenting this function
2174 * @global object
2175 * @uses CONTEXT_COURSE
2176 * @param course $course A {@link $COURSE} object.
2177 * @param string $sections
2178 * @param string $modinfo
2179 * @param string $strsection
2180 * @param string $strjumpto
2181 * @param int $width
2182 * @param string $cmid
2183 * @return string The HTML block
2185 function navmenulist($course, $sections, $modinfo, $strsection, $strjumpto, $width=50, $cmid=0) {
2187 global $CFG, $OUTPUT;
2189 $section = -1;
2190 $url = '';
2191 $menu = array();
2192 $doneheading = false;
2194 $coursecontext = get_context_instance(CONTEXT_COURSE, $course->id);
2196 $menu[] = '<ul class="navmenulist"><li class="jumpto section"><span>'.$strjumpto.'</span><ul>';
2197 foreach ($modinfo->cms as $mod) {
2198 if (!$mod->has_view()) {
2199 // Don't show modules which you can't link to!
2200 continue;
2203 if ($mod->sectionnum > $course->numsections) { /// Don't show excess hidden sections
2204 break;
2207 if (!$mod->uservisible) { // do not icnlude empty sections at all
2208 continue;
2211 if ($mod->sectionnum >= 0 and $section != $mod->sectionnum) {
2212 $thissection = $sections[$mod->sectionnum];
2214 if ($thissection->visible or !$course->hiddensections or
2215 has_capability('moodle/course:viewhiddensections', $coursecontext)) {
2216 $thissection->summary = strip_tags(format_string($thissection->summary,true));
2217 if (!$doneheading) {
2218 $menu[] = '</ul></li>';
2220 if ($course->format == 'weeks' or empty($thissection->summary)) {
2221 $item = $strsection ." ". $mod->sectionnum;
2222 } else {
2223 if (textlib::strlen($thissection->summary) < ($width-3)) {
2224 $item = $thissection->summary;
2225 } else {
2226 $item = textlib::substr($thissection->summary, 0, $width).'...';
2229 $menu[] = '<li class="section"><span>'.$item.'</span>';
2230 $menu[] = '<ul>';
2231 $doneheading = true;
2233 $section = $mod->sectionnum;
2234 } else {
2235 // no activities from this hidden section shown
2236 continue;
2240 $url = $mod->modname .'/view.php?id='. $mod->id;
2241 $mod->name = strip_tags(format_string($mod->name ,true));
2242 if (textlib::strlen($mod->name) > ($width+5)) {
2243 $mod->name = textlib::substr($mod->name, 0, $width).'...';
2245 if (!$mod->visible) {
2246 $mod->name = '('.$mod->name.')';
2248 $class = 'activity '.$mod->modname;
2249 $class .= ($cmid == $mod->id) ? ' selected' : '';
2250 $menu[] = '<li class="'.$class.'">'.
2251 '<img src="'.$OUTPUT->pix_url('icon', $mod->modname) . '" alt="" />'.
2252 '<a href="'.$CFG->wwwroot.'/mod/'.$url.'">'.$mod->name.'</a></li>';
2255 if ($doneheading) {
2256 $menu[] = '</ul></li>';
2258 $menu[] = '</ul></li></ul>';
2260 return implode("\n", $menu);
2264 * Prints a grade menu (as part of an existing form) with help
2265 * Showing all possible numerical grades and scales
2267 * @todo Finish documenting this function
2268 * @todo Deprecate: this is only used in a few contrib modules
2270 * @global object
2271 * @param int $courseid The course ID
2272 * @param string $name
2273 * @param string $current
2274 * @param boolean $includenograde Include those with no grades
2275 * @param boolean $return If set to true returns rather than echo's
2276 * @return string|bool Depending on value of $return
2278 function print_grade_menu($courseid, $name, $current, $includenograde=true, $return=false) {
2280 global $CFG, $OUTPUT;
2282 $output = '';
2283 $strscale = get_string('scale');
2284 $strscales = get_string('scales');
2286 $scales = get_scales_menu($courseid);
2287 foreach ($scales as $i => $scalename) {
2288 $grades[-$i] = $strscale .': '. $scalename;
2290 if ($includenograde) {
2291 $grades[0] = get_string('nograde');
2293 for ($i=100; $i>=1; $i--) {
2294 $grades[$i] = $i;
2296 $output .= html_writer::select($grades, $name, $current, false);
2298 $linkobject = '<span class="helplink"><img class="iconhelp" alt="'.$strscales.'" src="'.$OUTPUT->pix_url('help') . '" /></span>';
2299 $link = new moodle_url('/course/scales.php', array('id'=>$courseid, 'list'=>1));
2300 $action = new popup_action('click', $link, 'ratingscales', array('height' => 400, 'width' => 500));
2301 $output .= $OUTPUT->action_link($link, $linkobject, $action, array('title'=>$strscales));
2303 if ($return) {
2304 return $output;
2305 } else {
2306 echo $output;
2311 * Print an error to STDOUT and exit with a non-zero code. For commandline scripts.
2312 * Default errorcode is 1.
2314 * Very useful for perl-like error-handling:
2316 * do_somethting() or mdie("Something went wrong");
2318 * @param string $msg Error message
2319 * @param integer $errorcode Error code to emit
2321 function mdie($msg='', $errorcode=1) {
2322 trigger_error($msg);
2323 exit($errorcode);
2327 * Print a message and exit.
2329 * @param string $message The message to print in the notice
2330 * @param string $link The link to use for the continue button
2331 * @param object $course A course object
2332 * @return void This function simply exits
2334 function notice ($message, $link='', $course=NULL) {
2335 global $CFG, $SITE, $COURSE, $PAGE, $OUTPUT;
2337 $message = clean_text($message); // In case nasties are in here
2339 if (CLI_SCRIPT) {
2340 echo("!!$message!!\n");
2341 exit(1); // no success
2344 if (!$PAGE->headerprinted) {
2345 //header not yet printed
2346 $PAGE->set_title(get_string('notice'));
2347 echo $OUTPUT->header();
2348 } else {
2349 echo $OUTPUT->container_end_all(false);
2352 echo $OUTPUT->box($message, 'generalbox', 'notice');
2353 echo $OUTPUT->continue_button($link);
2355 echo $OUTPUT->footer();
2356 exit(1); // general error code
2360 * Redirects the user to another page, after printing a notice
2362 * This function calls the OUTPUT redirect method, echo's the output
2363 * and then dies to ensure nothing else happens.
2365 * <strong>Good practice:</strong> You should call this method before starting page
2366 * output by using any of the OUTPUT methods.
2368 * @param moodle_url|string $url A moodle_url to redirect to. Strings are not to be trusted!
2369 * @param string $message The message to display to the user
2370 * @param int $delay The delay before redirecting
2371 * @return void - does not return!
2373 function redirect($url, $message='', $delay=-1) {
2374 global $OUTPUT, $PAGE, $SESSION, $CFG;
2376 if (CLI_SCRIPT or AJAX_SCRIPT) {
2377 // this is wrong - developers should not use redirect in these scripts,
2378 // but it should not be very likely
2379 throw new moodle_exception('redirecterrordetected', 'error');
2382 // prevent debug errors - make sure context is properly initialised
2383 if ($PAGE) {
2384 $PAGE->set_context(null);
2385 $PAGE->set_pagelayout('redirect'); // No header and footer needed
2388 if ($url instanceof moodle_url) {
2389 $url = $url->out(false);
2392 $debugdisableredirect = false;
2393 do {
2394 if (defined('DEBUGGING_PRINTED')) {
2395 // some debugging already printed, no need to look more
2396 $debugdisableredirect = true;
2397 break;
2400 if (empty($CFG->debugdisplay) or empty($CFG->debug)) {
2401 // no errors should be displayed
2402 break;
2405 if (!function_exists('error_get_last') or !$lasterror = error_get_last()) {
2406 break;
2409 if (!($lasterror['type'] & $CFG->debug)) {
2410 //last error not interesting
2411 break;
2414 // watch out here, @hidden() errors are returned from error_get_last() too
2415 if (headers_sent()) {
2416 //we already started printing something - that means errors likely printed
2417 $debugdisableredirect = true;
2418 break;
2421 if (ob_get_level() and ob_get_contents()) {
2422 // there is something waiting to be printed, hopefully it is the errors,
2423 // but it might be some error hidden by @ too - such as the timezone mess from setup.php
2424 $debugdisableredirect = true;
2425 break;
2427 } while (false);
2429 // Technically, HTTP/1.1 requires Location: header to contain the absolute path.
2430 // (In practice browsers accept relative paths - but still, might as well do it properly.)
2431 // This code turns relative into absolute.
2432 if (!preg_match('|^[a-z]+:|', $url)) {
2433 // Get host name http://www.wherever.com
2434 $hostpart = preg_replace('|^(.*?[^:/])/.*$|', '$1', $CFG->wwwroot);
2435 if (preg_match('|^/|', $url)) {
2436 // URLs beginning with / are relative to web server root so we just add them in
2437 $url = $hostpart.$url;
2438 } else {
2439 // URLs not beginning with / are relative to path of current script, so add that on.
2440 $url = $hostpart.preg_replace('|\?.*$|','',me()).'/../'.$url;
2442 // Replace all ..s
2443 while (true) {
2444 $newurl = preg_replace('|/(?!\.\.)[^/]*/\.\./|', '/', $url);
2445 if ($newurl == $url) {
2446 break;
2448 $url = $newurl;
2452 // Sanitise url - we can not rely on moodle_url or our URL cleaning
2453 // because they do not support all valid external URLs
2454 $url = preg_replace('/[\x00-\x1F\x7F]/', '', $url);
2455 $url = str_replace('"', '%22', $url);
2456 $encodedurl = preg_replace("/\&(?![a-zA-Z0-9#]{1,8};)/", "&amp;", $url);
2457 $encodedurl = preg_replace('/^.*href="([^"]*)".*$/', "\\1", clean_text('<a href="'.$encodedurl.'" />', FORMAT_HTML));
2458 $url = str_replace('&amp;', '&', $encodedurl);
2460 if (!empty($message)) {
2461 if ($delay === -1 || !is_numeric($delay)) {
2462 $delay = 3;
2464 $message = clean_text($message);
2465 } else {
2466 $message = get_string('pageshouldredirect');
2467 $delay = 0;
2470 if (defined('MDL_PERF') || (!empty($CFG->perfdebug) and $CFG->perfdebug > 7)) {
2471 if (defined('MDL_PERFTOLOG') && !function_exists('register_shutdown_function')) {
2472 $perf = get_performance_info();
2473 error_log("PERF: " . $perf['txt']);
2477 if ($delay == 0 && !$debugdisableredirect && !headers_sent()) {
2478 // workaround for IIS bug http://support.microsoft.com/kb/q176113/
2479 if (session_id()) {
2480 session_get_instance()->write_close();
2483 //302 might not work for POST requests, 303 is ignored by obsolete clients.
2484 @header($_SERVER['SERVER_PROTOCOL'] . ' 303 See Other');
2485 @header('Location: '.$url);
2486 echo bootstrap_renderer::plain_redirect_message($encodedurl);
2487 exit;
2490 // Include a redirect message, even with a HTTP redirect, because that is recommended practice.
2491 if ($PAGE) {
2492 $CFG->docroot = false; // to prevent the link to moodle docs from being displayed on redirect page.
2493 echo $OUTPUT->redirect_message($encodedurl, $message, $delay, $debugdisableredirect);
2494 exit;
2495 } else {
2496 echo bootstrap_renderer::early_redirect_message($encodedurl, $message, $delay);
2497 exit;
2502 * Given an email address, this function will return an obfuscated version of it
2504 * @param string $email The email address to obfuscate
2505 * @return string The obfuscated email address
2507 function obfuscate_email($email) {
2509 $i = 0;
2510 $length = strlen($email);
2511 $obfuscated = '';
2512 while ($i < $length) {
2513 if (rand(0,2) && $email{$i}!='@') { //MDL-20619 some browsers have problems unobfuscating @
2514 $obfuscated.='%'.dechex(ord($email{$i}));
2515 } else {
2516 $obfuscated.=$email{$i};
2518 $i++;
2520 return $obfuscated;
2524 * This function takes some text and replaces about half of the characters
2525 * with HTML entity equivalents. Return string is obviously longer.
2527 * @param string $plaintext The text to be obfuscated
2528 * @return string The obfuscated text
2530 function obfuscate_text($plaintext) {
2532 $i=0;
2533 $length = strlen($plaintext);
2534 $obfuscated='';
2535 $prev_obfuscated = false;
2536 while ($i < $length) {
2537 $c = ord($plaintext{$i});
2538 $numerical = ($c >= ord('0')) && ($c <= ord('9'));
2539 if ($prev_obfuscated and $numerical ) {
2540 $obfuscated.='&#'.ord($plaintext{$i}).';';
2541 } else if (rand(0,2)) {
2542 $obfuscated.='&#'.ord($plaintext{$i}).';';
2543 $prev_obfuscated = true;
2544 } else {
2545 $obfuscated.=$plaintext{$i};
2546 $prev_obfuscated = false;
2548 $i++;
2550 return $obfuscated;
2554 * This function uses the {@link obfuscate_email()} and {@link obfuscate_text()}
2555 * to generate a fully obfuscated email link, ready to use.
2557 * @param string $email The email address to display
2558 * @param string $label The text to displayed as hyperlink to $email
2559 * @param boolean $dimmed If true then use css class 'dimmed' for hyperlink
2560 * @return string The obfuscated mailto link
2562 function obfuscate_mailto($email, $label='', $dimmed=false) {
2564 if (empty($label)) {
2565 $label = $email;
2567 if ($dimmed) {
2568 $title = get_string('emaildisable');
2569 $dimmed = ' class="dimmed"';
2570 } else {
2571 $title = '';
2572 $dimmed = '';
2574 return sprintf("<a href=\"%s:%s\" $dimmed title=\"$title\">%s</a>",
2575 obfuscate_text('mailto'), obfuscate_email($email),
2576 obfuscate_text($label));
2580 * This function is used to rebuild the <nolink> tag because some formats (PLAIN and WIKI)
2581 * will transform it to html entities
2583 * @param string $text Text to search for nolink tag in
2584 * @return string
2586 function rebuildnolinktag($text) {
2588 $text = preg_replace('/&lt;(\/*nolink)&gt;/i','<$1>',$text);
2590 return $text;
2594 * Prints a maintenance message from $CFG->maintenance_message or default if empty
2595 * @return void
2597 function print_maintenance_message() {
2598 global $CFG, $SITE, $PAGE, $OUTPUT;
2600 $PAGE->set_pagetype('maintenance-message');
2601 $PAGE->set_pagelayout('maintenance');
2602 $PAGE->set_title(strip_tags($SITE->fullname));
2603 $PAGE->set_heading($SITE->fullname);
2604 echo $OUTPUT->header();
2605 echo $OUTPUT->heading(get_string('sitemaintenance', 'admin'));
2606 if (isset($CFG->maintenance_message) and !html_is_blank($CFG->maintenance_message)) {
2607 echo $OUTPUT->box_start('maintenance_message generalbox boxwidthwide boxaligncenter');
2608 echo $CFG->maintenance_message;
2609 echo $OUTPUT->box_end();
2611 echo $OUTPUT->footer();
2612 die;
2616 * A class for tabs, Some code to print tabs
2618 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2619 * @package moodlecore
2621 class tabobject {
2623 * @var string
2625 var $id;
2626 var $link;
2627 var $text;
2629 * @var bool
2631 var $linkedwhenselected;
2634 * A constructor just because I like constructors
2636 * @param string $id
2637 * @param string $link
2638 * @param string $text
2639 * @param string $title
2640 * @param bool $linkedwhenselected
2642 function tabobject ($id, $link='', $text='', $title='', $linkedwhenselected=false) {
2643 $this->id = $id;
2644 $this->link = $link;
2645 $this->text = $text;
2646 $this->title = $title ? $title : $text;
2647 $this->linkedwhenselected = $linkedwhenselected;
2654 * Returns a string containing a nested list, suitable for formatting into tabs with CSS.
2656 * @global object
2657 * @param array $tabrows An array of rows where each row is an array of tab objects
2658 * @param string $selected The id of the selected tab (whatever row it's on)
2659 * @param array $inactive An array of ids of inactive tabs that are not selectable.
2660 * @param array $activated An array of ids of other tabs that are currently activated
2661 * @param bool $return If true output is returned rather then echo'd
2663 function print_tabs($tabrows, $selected=NULL, $inactive=NULL, $activated=NULL, $return=false) {
2664 global $CFG;
2666 /// $inactive must be an array
2667 if (!is_array($inactive)) {
2668 $inactive = array();
2671 /// $activated must be an array
2672 if (!is_array($activated)) {
2673 $activated = array();
2676 /// Convert the tab rows into a tree that's easier to process
2677 if (!$tree = convert_tabrows_to_tree($tabrows, $selected, $inactive, $activated)) {
2678 return false;
2681 /// Print out the current tree of tabs (this function is recursive)
2683 $output = convert_tree_to_html($tree);
2685 $output = "\n\n".'<div class="tabtree">'.$output.'</div><div class="clearer"> </div>'."\n\n";
2687 /// We're done!
2689 if ($return) {
2690 return $output;
2692 echo $output;
2696 * Converts a nested array tree into HTML ul:li [recursive]
2698 * @param array $tree A tree array to convert
2699 * @param int $row Used in identifying the iteration level and in ul classes
2700 * @return string HTML structure
2702 function convert_tree_to_html($tree, $row=0) {
2704 $str = "\n".'<ul class="tabrow'.$row.'">'."\n";
2706 $first = true;
2707 $count = count($tree);
2709 foreach ($tree as $tab) {
2710 $count--; // countdown to zero
2712 $liclass = '';
2714 if ($first && ($count == 0)) { // Just one in the row
2715 $liclass = 'first last';
2716 $first = false;
2717 } else if ($first) {
2718 $liclass = 'first';
2719 $first = false;
2720 } else if ($count == 0) {
2721 $liclass = 'last';
2724 if ((empty($tab->subtree)) && (!empty($tab->selected))) {
2725 $liclass .= (empty($liclass)) ? 'onerow' : ' onerow';
2728 if ($tab->inactive || $tab->active || $tab->selected) {
2729 if ($tab->selected) {
2730 $liclass .= (empty($liclass)) ? 'here selected' : ' here selected';
2731 } else if ($tab->active) {
2732 $liclass .= (empty($liclass)) ? 'here active' : ' here active';
2736 $str .= (!empty($liclass)) ? '<li class="'.$liclass.'">' : '<li>';
2738 if ($tab->inactive || $tab->active || ($tab->selected && !$tab->linkedwhenselected)) {
2739 // The a tag is used for styling
2740 $str .= '<a class="nolink"><span>'.$tab->text.'</span></a>';
2741 } else {
2742 $str .= '<a href="'.$tab->link.'" title="'.$tab->title.'"><span>'.$tab->text.'</span></a>';
2745 if (!empty($tab->subtree)) {
2746 $str .= convert_tree_to_html($tab->subtree, $row+1);
2747 } else if ($tab->selected) {
2748 $str .= '<div class="tabrow'.($row+1).' empty">&nbsp;</div>'."\n";
2751 $str .= ' </li>'."\n";
2753 $str .= '</ul>'."\n";
2755 return $str;
2759 * Convert nested tabrows to a nested array
2761 * @param array $tabrows A [nested] array of tab row objects
2762 * @param string $selected The tabrow to select (by id)
2763 * @param array $inactive An array of tabrow id's to make inactive
2764 * @param array $activated An array of tabrow id's to make active
2765 * @return array The nested array
2767 function convert_tabrows_to_tree($tabrows, $selected, $inactive, $activated) {
2769 /// Work backwards through the rows (bottom to top) collecting the tree as we go.
2771 $tabrows = array_reverse($tabrows);
2773 $subtree = array();
2775 foreach ($tabrows as $row) {
2776 $tree = array();
2778 foreach ($row as $tab) {
2779 $tab->inactive = in_array((string)$tab->id, $inactive);
2780 $tab->active = in_array((string)$tab->id, $activated);
2781 $tab->selected = (string)$tab->id == $selected;
2783 if ($tab->active || $tab->selected) {
2784 if ($subtree) {
2785 $tab->subtree = $subtree;
2788 $tree[] = $tab;
2790 $subtree = $tree;
2793 return $subtree;
2797 * Standard Debugging Function
2799 * Returns true if the current site debugging settings are equal or above specified level.
2800 * If passed a parameter it will emit a debugging notice similar to trigger_error(). The
2801 * routing of notices is controlled by $CFG->debugdisplay
2802 * eg use like this:
2804 * 1) debugging('a normal debug notice');
2805 * 2) debugging('something really picky', DEBUG_ALL);
2806 * 3) debugging('annoying debug message only for developers', DEBUG_DEVELOPER);
2807 * 4) if (debugging()) { perform extra debugging operations (do not use print or echo) }
2809 * In code blocks controlled by debugging() (such as example 4)
2810 * any output should be routed via debugging() itself, or the lower-level
2811 * trigger_error() or error_log(). Using echo or print will break XHTML
2812 * JS and HTTP headers.
2814 * It is also possible to define NO_DEBUG_DISPLAY which redirects the message to error_log.
2816 * @uses DEBUG_NORMAL
2817 * @param string $message a message to print
2818 * @param int $level the level at which this debugging statement should show
2819 * @param array $backtrace use different backtrace
2820 * @return bool
2822 function debugging($message = '', $level = DEBUG_NORMAL, $backtrace = null) {
2823 global $CFG, $USER, $UNITTEST;
2825 $forcedebug = false;
2826 if (!empty($CFG->debugusers) && $USER) {
2827 $debugusers = explode(',', $CFG->debugusers);
2828 $forcedebug = in_array($USER->id, $debugusers);
2831 if (!$forcedebug and (empty($CFG->debug) || ($CFG->debug != -1 and $CFG->debug < $level))) {
2832 return false;
2835 if (!isset($CFG->debugdisplay)) {
2836 $CFG->debugdisplay = ini_get_bool('display_errors');
2839 if ($message) {
2840 if (!$backtrace) {
2841 $backtrace = debug_backtrace();
2843 $from = format_backtrace($backtrace, CLI_SCRIPT);
2844 if (PHPUNIT_TEST) {
2845 echo 'Debugging: ' . $message . "\n" . $from;
2847 } else if (!empty($UNITTEST->running)) {
2848 // When the unit tests are running, any call to trigger_error
2849 // is intercepted by the test framework and reported as an exception.
2850 // Therefore, we cannot use trigger_error during unit tests.
2851 // At the same time I do not think we should just discard those messages,
2852 // so displaying them on-screen seems like the only option. (MDL-20398)
2853 echo '<div class="notifytiny">' . $message . $from . '</div>';
2855 } else if (NO_DEBUG_DISPLAY) {
2856 // script does not want any errors or debugging in output,
2857 // we send the info to error log instead
2858 error_log('Debugging: ' . $message . $from);
2860 } else if ($forcedebug or $CFG->debugdisplay) {
2861 if (!defined('DEBUGGING_PRINTED')) {
2862 define('DEBUGGING_PRINTED', 1); // indicates we have printed something
2864 if (CLI_SCRIPT) {
2865 echo "++ $message ++\n$from";
2866 } else {
2867 echo '<div class="notifytiny">' . $message . $from . '</div>';
2870 } else {
2871 trigger_error($message . $from, E_USER_NOTICE);
2874 return true;
2878 * Outputs a HTML comment to the browser. This is used for those hard-to-debug
2879 * pages that use bits from many different files in very confusing ways (e.g. blocks).
2881 * <code>print_location_comment(__FILE__, __LINE__);</code>
2883 * @param string $file
2884 * @param integer $line
2885 * @param boolean $return Whether to return or print the comment
2886 * @return string|void Void unless true given as third parameter
2888 function print_location_comment($file, $line, $return = false)
2890 if ($return) {
2891 return "<!-- $file at line $line -->\n";
2892 } else {
2893 echo "<!-- $file at line $line -->\n";
2899 * @return boolean true if the current language is right-to-left (Hebrew, Arabic etc)
2901 function right_to_left() {
2902 return (get_string('thisdirection', 'langconfig') === 'rtl');
2907 * Returns swapped left<=>right if in RTL environment.
2908 * part of RTL support
2910 * @param string $align align to check
2911 * @return string
2913 function fix_align_rtl($align) {
2914 if (!right_to_left()) {
2915 return $align;
2917 if ($align=='left') { return 'right'; }
2918 if ($align=='right') { return 'left'; }
2919 return $align;
2924 * Returns true if the page is displayed in a popup window.
2925 * Gets the information from the URL parameter inpopup.
2927 * @todo Use a central function to create the popup calls all over Moodle and
2928 * In the moment only works with resources and probably questions.
2930 * @return boolean
2932 function is_in_popup() {
2933 $inpopup = optional_param('inpopup', '', PARAM_BOOL);
2935 return ($inpopup);
2939 * To use this class.
2940 * - construct
2941 * - call create (or use the 3rd param to the constructor)
2942 * - call update or update_full() or update() repeatedly
2944 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2945 * @package moodlecore
2947 class progress_bar {
2948 /** @var string html id */
2949 private $html_id;
2950 /** @var int total width */
2951 private $width;
2952 /** @var int last percentage printed */
2953 private $percent = 0;
2954 /** @var int time when last printed */
2955 private $lastupdate = 0;
2956 /** @var int when did we start printing this */
2957 private $time_start = 0;
2960 * Constructor
2962 * @param string $html_id
2963 * @param int $width
2964 * @param bool $autostart Default to false
2965 * @return void, prints JS code if $autostart true
2967 public function __construct($html_id = '', $width = 500, $autostart = false) {
2968 if (!empty($html_id)) {
2969 $this->html_id = $html_id;
2970 } else {
2971 $this->html_id = 'pbar_'.uniqid();
2974 $this->width = $width;
2976 if ($autostart){
2977 $this->create();
2982 * Create a new progress bar, this function will output html.
2984 * @return void Echo's output
2986 public function create() {
2987 $this->time_start = microtime(true);
2988 if (CLI_SCRIPT) {
2989 return; // temporary solution for cli scripts
2991 $htmlcode = <<<EOT
2992 <div style="text-align:center;width:{$this->width}px;clear:both;padding:0;margin:0 auto;">
2993 <h2 id="status_{$this->html_id}" style="text-align: center;margin:0 auto"></h2>
2994 <p id="time_{$this->html_id}"></p>
2995 <div id="bar_{$this->html_id}" style="border-style:solid;border-width:1px;width:500px;height:50px;">
2996 <div id="progress_{$this->html_id}"
2997 style="text-align:center;background:#FFCC66;width:4px;border:1px
2998 solid gray;height:38px; padding-top:10px;">&nbsp;<span id="pt_{$this->html_id}"></span>
2999 </div>
3000 </div>
3001 </div>
3002 EOT;
3003 flush();
3004 echo $htmlcode;
3005 flush();
3009 * Update the progress bar
3011 * @param int $percent from 1-100
3012 * @param string $msg
3013 * @return void Echo's output
3015 private function _update($percent, $msg) {
3016 if (empty($this->time_start)) {
3017 throw new coding_exception('You must call create() (or use the $autostart ' .
3018 'argument to the constructor) before you try updating the progress bar.');
3021 if (CLI_SCRIPT) {
3022 return; // temporary solution for cli scripts
3025 $es = $this->estimate($percent);
3027 if ($es === null) {
3028 // always do the first and last updates
3029 $es = "?";
3030 } else if ($es == 0) {
3031 // always do the last updates
3032 } else if ($this->lastupdate + 20 < time()) {
3033 // we must update otherwise browser would time out
3034 } else if (round($this->percent, 2) === round($percent, 2)) {
3035 // no significant change, no need to update anything
3036 return;
3039 $this->percent = $percent;
3040 $this->lastupdate = microtime(true);
3042 $w = ($this->percent/100) * $this->width;
3043 echo html_writer::script(js_writer::function_call('update_progress_bar', array($this->html_id, $w, $this->percent, $msg, $es)));
3044 flush();
3048 * Estimate how much time it is going to take.
3050 * @param int $curtime the time call this function
3051 * @param int $percent from 1-100
3052 * @return mixed Null (unknown), or int
3054 private function estimate($pt) {
3055 if ($this->lastupdate == 0) {
3056 return null;
3058 if ($pt < 0.00001) {
3059 return null; // we do not know yet how long it will take
3061 if ($pt > 99.99999) {
3062 return 0; // nearly done, right?
3064 $consumed = microtime(true) - $this->time_start;
3065 if ($consumed < 0.001) {
3066 return null;
3069 return (100 - $pt) * ($consumed / $pt);
3073 * Update progress bar according percent
3075 * @param int $percent from 1-100
3076 * @param string $msg the message needed to be shown
3078 public function update_full($percent, $msg) {
3079 $percent = max(min($percent, 100), 0);
3080 $this->_update($percent, $msg);
3084 * Update progress bar according the number of tasks
3086 * @param int $cur current task number
3087 * @param int $total total task number
3088 * @param string $msg message
3090 public function update($cur, $total, $msg) {
3091 $percent = ($cur / $total) * 100;
3092 $this->update_full($percent, $msg);
3096 * Restart the progress bar.
3098 public function restart() {
3099 $this->percent = 0;
3100 $this->lastupdate = 0;
3101 $this->time_start = 0;
3106 * Use this class from long operations where you want to output occasional information about
3107 * what is going on, but don't know if, or in what format, the output should be.
3109 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3110 * @package moodlecore
3112 abstract class progress_trace {
3114 * Ouput an progress message in whatever format.
3115 * @param string $message the message to output.
3116 * @param integer $depth indent depth for this message.
3118 abstract public function output($message, $depth = 0);
3121 * Called when the processing is finished.
3123 public function finished() {
3128 * This subclass of progress_trace does not ouput anything.
3130 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3131 * @package moodlecore
3133 class null_progress_trace extends progress_trace {
3135 * Does Nothing
3137 * @param string $message
3138 * @param int $depth
3139 * @return void Does Nothing
3141 public function output($message, $depth = 0) {
3146 * This subclass of progress_trace outputs to plain text.
3148 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3149 * @package moodlecore
3151 class text_progress_trace extends progress_trace {
3153 * Output the trace message
3155 * @param string $message
3156 * @param int $depth
3157 * @return void Output is echo'd
3159 public function output($message, $depth = 0) {
3160 echo str_repeat(' ', $depth), $message, "\n";
3161 flush();
3166 * This subclass of progress_trace outputs as HTML.
3168 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3169 * @package moodlecore
3171 class html_progress_trace extends progress_trace {
3173 * Output the trace message
3175 * @param string $message
3176 * @param int $depth
3177 * @return void Output is echo'd
3179 public function output($message, $depth = 0) {
3180 echo '<p>', str_repeat('&#160;&#160;', $depth), htmlspecialchars($message), "</p>\n";
3181 flush();
3186 * HTML List Progress Tree
3188 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3189 * @package moodlecore
3191 class html_list_progress_trace extends progress_trace {
3192 /** @var int */
3193 protected $currentdepth = -1;
3196 * Echo out the list
3198 * @param string $message The message to display
3199 * @param int $depth
3200 * @return void Output is echoed
3202 public function output($message, $depth = 0) {
3203 $samedepth = true;
3204 while ($this->currentdepth > $depth) {
3205 echo "</li>\n</ul>\n";
3206 $this->currentdepth -= 1;
3207 if ($this->currentdepth == $depth) {
3208 echo '<li>';
3210 $samedepth = false;
3212 while ($this->currentdepth < $depth) {
3213 echo "<ul>\n<li>";
3214 $this->currentdepth += 1;
3215 $samedepth = false;
3217 if ($samedepth) {
3218 echo "</li>\n<li>";
3220 echo htmlspecialchars($message);
3221 flush();
3225 * Called when the processing is finished.
3227 public function finished() {
3228 while ($this->currentdepth >= 0) {
3229 echo "</li>\n</ul>\n";
3230 $this->currentdepth -= 1;
3236 * Returns a localized sentence in the current language summarizing the current password policy
3238 * @todo this should be handled by a function/method in the language pack library once we have a support for it
3239 * @uses $CFG
3240 * @return string
3242 function print_password_policy() {
3243 global $CFG;
3245 $message = '';
3246 if (!empty($CFG->passwordpolicy)) {
3247 $messages = array();
3248 $messages[] = get_string('informminpasswordlength', 'auth', $CFG->minpasswordlength);
3249 if (!empty($CFG->minpassworddigits)) {
3250 $messages[] = get_string('informminpassworddigits', 'auth', $CFG->minpassworddigits);
3252 if (!empty($CFG->minpasswordlower)) {
3253 $messages[] = get_string('informminpasswordlower', 'auth', $CFG->minpasswordlower);
3255 if (!empty($CFG->minpasswordupper)) {
3256 $messages[] = get_string('informminpasswordupper', 'auth', $CFG->minpasswordupper);
3258 if (!empty($CFG->minpasswordnonalphanum)) {
3259 $messages[] = get_string('informminpasswordnonalphanum', 'auth', $CFG->minpasswordnonalphanum);
3262 $messages = join(', ', $messages); // this is ugly but we do not have anything better yet...
3263 $message = get_string('informpasswordpolicy', 'auth', $messages);
3265 return $message;