MDL-35141 Filelib: No icon for epub filetype
[moodle.git] / lib / weblib.php
blob1295b00182dac5b0f18aeb116c0621e5ec04fcee
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 = context_user::instance($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);
751 if (strpos($url, $CFG->wwwroot) !== 0) {
752 throw new coding_exception('out_as_local_url called on a non-local URL');
755 return str_replace($CFG->wwwroot, '', $url);
759 * Returns the 'path' portion of a URL. For example, if the URL is
760 * http://www.example.org:447/my/file/is/here.txt?really=1 then this will
761 * return '/my/file/is/here.txt'.
763 * By default the path includes slash-arguments (for example,
764 * '/myfile.php/extra/arguments') so it is what you would expect from a
765 * URL path. If you don't want this behaviour, you can opt to exclude the
766 * slash arguments. (Be careful: if the $CFG variable slasharguments is
767 * disabled, these URLs will have a different format and you may need to
768 * look at the 'file' parameter too.)
770 * @param bool $includeslashargument If true, includes slash arguments
771 * @return string Path of URL
773 public function get_path($includeslashargument = true) {
774 return $this->path . ($includeslashargument ? $this->slashargument : '');
778 * Returns a given parameter value from the URL.
780 * @param string $name Name of parameter
781 * @return string Value of parameter or null if not set
783 public function get_param($name) {
784 if (array_key_exists($name, $this->params)) {
785 return $this->params[$name];
786 } else {
787 return null;
793 * Determine if there is data waiting to be processed from a form
795 * Used on most forms in Moodle to check for data
796 * Returns the data as an object, if it's found.
797 * This object can be used in foreach loops without
798 * casting because it's cast to (array) automatically
800 * Checks that submitted POST data exists and returns it as object.
802 * @uses $_POST
803 * @return mixed false or object
805 function data_submitted() {
807 if (empty($_POST)) {
808 return false;
809 } else {
810 return (object)fix_utf8($_POST);
815 * Given some normal text this function will break up any
816 * long words to a given size by inserting the given character
818 * It's multibyte savvy and doesn't change anything inside html tags.
820 * @param string $string the string to be modified
821 * @param int $maxsize maximum length of the string to be returned
822 * @param string $cutchar the string used to represent word breaks
823 * @return string
825 function break_up_long_words($string, $maxsize=20, $cutchar=' ') {
827 /// First of all, save all the tags inside the text to skip them
828 $tags = array();
829 filter_save_tags($string,$tags);
831 /// Process the string adding the cut when necessary
832 $output = '';
833 $length = textlib::strlen($string);
834 $wordlength = 0;
836 for ($i=0; $i<$length; $i++) {
837 $char = textlib::substr($string, $i, 1);
838 if ($char == ' ' or $char == "\t" or $char == "\n" or $char == "\r" or $char == "<" or $char == ">") {
839 $wordlength = 0;
840 } else {
841 $wordlength++;
842 if ($wordlength > $maxsize) {
843 $output .= $cutchar;
844 $wordlength = 0;
847 $output .= $char;
850 /// Finally load the tags back again
851 if (!empty($tags)) {
852 $output = str_replace(array_keys($tags), $tags, $output);
855 return $output;
859 * Try and close the current window using JavaScript, either immediately, or after a delay.
861 * Echo's out the resulting XHTML & javascript
863 * @global object
864 * @global object
865 * @param integer $delay a delay in seconds before closing the window. Default 0.
866 * @param boolean $reloadopener if true, we will see if this window was a pop-up, and try
867 * to reload the parent window before this one closes.
869 function close_window($delay = 0, $reloadopener = false) {
870 global $PAGE, $OUTPUT;
872 if (!$PAGE->headerprinted) {
873 $PAGE->set_title(get_string('closewindow'));
874 echo $OUTPUT->header();
875 } else {
876 $OUTPUT->container_end_all(false);
879 if ($reloadopener) {
880 // Trigger the reload immediately, even if the reload is after a delay.
881 $PAGE->requires->js_function_call('window.opener.location.reload', array(true));
883 $OUTPUT->notification(get_string('windowclosing'), 'notifysuccess');
885 $PAGE->requires->js_function_call('close_window', array(new stdClass()), false, $delay);
887 echo $OUTPUT->footer();
888 exit;
892 * Returns a string containing a link to the user documentation for the current
893 * page. Also contains an icon by default. Shown to teachers and admin only.
895 * @global object
896 * @global object
897 * @param string $text The text to be displayed for the link
898 * @param string $iconpath The path to the icon to be displayed
899 * @return string The link to user documentation for this current page
901 function page_doc_link($text='') {
902 global $CFG, $PAGE, $OUTPUT;
904 if (empty($CFG->docroot) || during_initial_install()) {
905 return '';
907 if (!has_capability('moodle/site:doclinks', $PAGE->context)) {
908 return '';
911 $path = $PAGE->docspath;
912 if (!$path) {
913 return '';
915 return $OUTPUT->doc_link($path, $text);
920 * Validates an email to make sure it makes sense.
922 * @param string $address The email address to validate.
923 * @return boolean
925 function validate_email($address) {
927 return (preg_match('#^[-!\#$%&\'*+\\/0-9=?A-Z^_`a-z{|}~]+'.
928 '(\.[-!\#$%&\'*+\\/0-9=?A-Z^_`a-z{|}~]+)*'.
929 '@'.
930 '[-!\#$%&\'*+\\/0-9=?A-Z^_`a-z{|}~]+\.'.
931 '[-!\#$%&\'*+\\./0-9=?A-Z^_`a-z{|}~]+$#',
932 $address));
936 * Extracts file argument either from file parameter or PATH_INFO
937 * Note: $scriptname parameter is not needed anymore
939 * @global string
940 * @uses $_SERVER
941 * @uses PARAM_PATH
942 * @return string file path (only safe characters)
944 function get_file_argument() {
945 global $SCRIPT;
947 $relativepath = optional_param('file', FALSE, PARAM_PATH);
949 if ($relativepath !== false and $relativepath !== '') {
950 return $relativepath;
952 $relativepath = false;
954 // then try extract file from the slasharguments
955 if (stripos($_SERVER['SERVER_SOFTWARE'], 'iis') !== false) {
956 // NOTE: ISS tends to convert all file paths to single byte DOS encoding,
957 // we can not use other methods because they break unicode chars,
958 // the only way is to use URL rewriting
959 if (isset($_SERVER['PATH_INFO']) and $_SERVER['PATH_INFO'] !== '') {
960 // check that PATH_INFO works == must not contain the script name
961 if (strpos($_SERVER['PATH_INFO'], $SCRIPT) === false) {
962 $relativepath = clean_param(urldecode($_SERVER['PATH_INFO']), PARAM_PATH);
965 } else {
966 // all other apache-like servers depend on PATH_INFO
967 if (isset($_SERVER['PATH_INFO'])) {
968 if (isset($_SERVER['SCRIPT_NAME']) and strpos($_SERVER['PATH_INFO'], $_SERVER['SCRIPT_NAME']) === 0) {
969 $relativepath = substr($_SERVER['PATH_INFO'], strlen($_SERVER['SCRIPT_NAME']));
970 } else {
971 $relativepath = $_SERVER['PATH_INFO'];
973 $relativepath = clean_param($relativepath, PARAM_PATH);
978 return $relativepath;
982 * Just returns an array of text formats suitable for a popup menu
984 * @uses FORMAT_MOODLE
985 * @uses FORMAT_HTML
986 * @uses FORMAT_PLAIN
987 * @uses FORMAT_MARKDOWN
988 * @return array
990 function format_text_menu() {
991 return array (FORMAT_MOODLE => get_string('formattext'),
992 FORMAT_HTML => get_string('formathtml'),
993 FORMAT_PLAIN => get_string('formatplain'),
994 FORMAT_MARKDOWN => get_string('formatmarkdown'));
998 * Given text in a variety of format codings, this function returns
999 * the text as safe HTML.
1001 * This function should mainly be used for long strings like posts,
1002 * answers, glossary items etc. For short strings @see format_string().
1004 * <pre>
1005 * Options:
1006 * trusted : If true the string won't be cleaned. Default false required noclean=true.
1007 * noclean : If true the string won't be cleaned. Default false required trusted=true.
1008 * nocache : If true the strign will not be cached and will be formatted every call. Default false.
1009 * filter : If true the string will be run through applicable filters as well. Default true.
1010 * para : If true then the returned string will be wrapped in div tags. Default true.
1011 * newlines : If true then lines newline breaks will be converted to HTML newline breaks. Default true.
1012 * context : The context that will be used for filtering.
1013 * overflowdiv : If set to true the formatted text will be encased in a div
1014 * with the class no-overflow before being returned. Default false.
1015 * allowid : If true then id attributes will not be removed, even when
1016 * using htmlpurifier. Default false.
1017 * </pre>
1019 * @todo Finish documenting this function
1021 * @staticvar array $croncache
1022 * @param string $text The text to be formatted. This is raw text originally from user input.
1023 * @param int $format Identifier of the text format to be used
1024 * [FORMAT_MOODLE, FORMAT_HTML, FORMAT_PLAIN, FORMAT_MARKDOWN]
1025 * @param object/array $options text formatting options
1026 * @param int $courseid_do_not_use deprecated course id, use context option instead
1027 * @return string
1029 function format_text($text, $format = FORMAT_MOODLE, $options = NULL, $courseid_do_not_use = NULL) {
1030 global $CFG, $COURSE, $DB, $PAGE;
1031 static $croncache = array();
1033 if ($text === '' || is_null($text)) {
1034 return ''; // no need to do any filters and cleaning
1037 $options = (array)$options; // detach object, we can not modify it
1039 if (!isset($options['trusted'])) {
1040 $options['trusted'] = false;
1042 if (!isset($options['noclean'])) {
1043 if ($options['trusted'] and trusttext_active()) {
1044 // no cleaning if text trusted and noclean not specified
1045 $options['noclean'] = true;
1046 } else {
1047 $options['noclean'] = false;
1050 if (!isset($options['nocache'])) {
1051 $options['nocache'] = false;
1053 if (!isset($options['filter'])) {
1054 $options['filter'] = true;
1056 if (!isset($options['para'])) {
1057 $options['para'] = true;
1059 if (!isset($options['newlines'])) {
1060 $options['newlines'] = true;
1062 if (!isset($options['overflowdiv'])) {
1063 $options['overflowdiv'] = false;
1066 // Calculate best context
1067 if (empty($CFG->version) or $CFG->version < 2010072800 or during_initial_install()) {
1068 // do not filter anything during installation or before upgrade completes
1069 $context = null;
1071 } else if (isset($options['context'])) { // first by explicit passed context option
1072 if (is_object($options['context'])) {
1073 $context = $options['context'];
1074 } else {
1075 $context = get_context_instance_by_id($options['context']);
1077 } else if ($courseid_do_not_use) {
1078 // legacy courseid
1079 $context = context_course::instance($courseid_do_not_use);
1080 } else {
1081 // fallback to $PAGE->context this may be problematic in CLI and other non-standard pages :-(
1082 $context = $PAGE->context;
1085 if (!$context) {
1086 // either install/upgrade or something has gone really wrong because context does not exist (yet?)
1087 $options['nocache'] = true;
1088 $options['filter'] = false;
1091 if ($options['filter']) {
1092 $filtermanager = filter_manager::instance();
1093 $filtermanager->setup_page_for_filters($PAGE, $context); // Setup global stuff filters may have.
1094 } else {
1095 $filtermanager = new null_filter_manager();
1098 if (!empty($CFG->cachetext) and empty($options['nocache'])) {
1099 $hashstr = $text.'-'.$filtermanager->text_filtering_hash($context).'-'.$context->id.'-'.current_language().'-'.
1100 (int)$format.(int)$options['trusted'].(int)$options['noclean'].
1101 (int)$options['para'].(int)$options['newlines'];
1103 $time = time() - $CFG->cachetext;
1104 $md5key = md5($hashstr);
1105 if (CLI_SCRIPT) {
1106 if (isset($croncache[$md5key])) {
1107 return $croncache[$md5key];
1111 if ($oldcacheitem = $DB->get_record('cache_text', array('md5key'=>$md5key), '*', IGNORE_MULTIPLE)) {
1112 if ($oldcacheitem->timemodified >= $time) {
1113 if (CLI_SCRIPT) {
1114 if (count($croncache) > 150) {
1115 reset($croncache);
1116 $key = key($croncache);
1117 unset($croncache[$key]);
1119 $croncache[$md5key] = $oldcacheitem->formattedtext;
1121 return $oldcacheitem->formattedtext;
1126 switch ($format) {
1127 case FORMAT_HTML:
1128 if (!$options['noclean']) {
1129 $text = clean_text($text, FORMAT_HTML, $options);
1131 $text = $filtermanager->filter_text($text, $context, array('originalformat' => FORMAT_HTML, 'noclean' => $options['noclean']));
1132 break;
1134 case FORMAT_PLAIN:
1135 $text = s($text); // cleans dangerous JS
1136 $text = rebuildnolinktag($text);
1137 $text = str_replace(' ', '&nbsp; ', $text);
1138 $text = nl2br($text);
1139 break;
1141 case FORMAT_WIKI:
1142 // this format is deprecated
1143 $text = '<p>NOTICE: Wiki-like formatting has been removed from Moodle. You should not be seeing
1144 this message as all texts should have been converted to Markdown format instead.
1145 Please post a bug report to http://moodle.org/bugs with information about where you
1146 saw this message.</p>'.s($text);
1147 break;
1149 case FORMAT_MARKDOWN:
1150 $text = markdown_to_html($text);
1151 if (!$options['noclean']) {
1152 $text = clean_text($text, FORMAT_HTML, $options);
1154 $text = $filtermanager->filter_text($text, $context, array('originalformat' => FORMAT_MARKDOWN, 'noclean' => $options['noclean']));
1155 break;
1157 default: // FORMAT_MOODLE or anything else
1158 $text = text_to_html($text, null, $options['para'], $options['newlines']);
1159 if (!$options['noclean']) {
1160 $text = clean_text($text, FORMAT_HTML, $options);
1162 $text = $filtermanager->filter_text($text, $context, array('originalformat' => $format, 'noclean' => $options['noclean']));
1163 break;
1165 if ($options['filter']) {
1166 // at this point there should not be any draftfile links any more,
1167 // this happens when developers forget to post process the text.
1168 // The only potential problem is that somebody might try to format
1169 // the text before storing into database which would be itself big bug.
1170 $text = str_replace("\"$CFG->httpswwwroot/draftfile.php", "\"$CFG->httpswwwroot/brokenfile.php#", $text);
1173 // Warn people that we have removed this old mechanism, just in case they
1174 // were stupid enough to rely on it.
1175 if (isset($CFG->currenttextiscacheable)) {
1176 debugging('Once upon a time, Moodle had a truly evil use of global variables ' .
1177 'called $CFG->currenttextiscacheable. The good news is that this no ' .
1178 'longer exists. The bad news is that you seem to be using a filter that '.
1179 'relies on it. Please seek out and destroy that filter code.', DEBUG_DEVELOPER);
1182 if (!empty($options['overflowdiv'])) {
1183 $text = html_writer::tag('div', $text, array('class'=>'no-overflow'));
1186 if (empty($options['nocache']) and !empty($CFG->cachetext)) {
1187 if (CLI_SCRIPT) {
1188 // special static cron cache - no need to store it in db if its not already there
1189 if (count($croncache) > 150) {
1190 reset($croncache);
1191 $key = key($croncache);
1192 unset($croncache[$key]);
1194 $croncache[$md5key] = $text;
1195 return $text;
1198 $newcacheitem = new stdClass();
1199 $newcacheitem->md5key = $md5key;
1200 $newcacheitem->formattedtext = $text;
1201 $newcacheitem->timemodified = time();
1202 if ($oldcacheitem) { // See bug 4677 for discussion
1203 $newcacheitem->id = $oldcacheitem->id;
1204 try {
1205 $DB->update_record('cache_text', $newcacheitem); // Update existing record in the cache table
1206 } catch (dml_exception $e) {
1207 // It's unlikely that the cron cache cleaner could have
1208 // deleted this entry in the meantime, as it allows
1209 // some extra time to cover these cases.
1211 } else {
1212 try {
1213 $DB->insert_record('cache_text', $newcacheitem); // Insert a new record in the cache table
1214 } catch (dml_exception $e) {
1215 // Again, it's possible that another user has caused this
1216 // record to be created already in the time that it took
1217 // to traverse this function. That's OK too, as the
1218 // call above handles duplicate entries, and eventually
1219 // the cron cleaner will delete them.
1224 return $text;
1228 * Resets all data related to filters, called during upgrade or when filter settings change.
1230 * @global object
1231 * @global object
1232 * @return void
1234 function reset_text_filters_cache() {
1235 global $CFG, $DB;
1237 $DB->delete_records('cache_text');
1238 $purifdir = $CFG->cachedir.'/htmlpurifier';
1239 remove_dir($purifdir, true);
1243 * Given a simple string, this function returns the string
1244 * processed by enabled string filters if $CFG->filterall is enabled
1246 * This function should be used to print short strings (non html) that
1247 * need filter processing e.g. activity titles, post subjects,
1248 * glossary concepts.
1250 * @staticvar bool $strcache
1251 * @param string $string The string to be filtered. Should be plain text, expect
1252 * possibly for multilang tags.
1253 * @param boolean $striplinks To strip any link in the result text.
1254 Moodle 1.8 default changed from false to true! MDL-8713
1255 * @param array $options options array/object or courseid
1256 * @return string
1258 function format_string($string, $striplinks = true, $options = NULL) {
1259 global $CFG, $COURSE, $PAGE;
1261 //We'll use a in-memory cache here to speed up repeated strings
1262 static $strcache = false;
1264 if (empty($CFG->version) or $CFG->version < 2010072800 or during_initial_install()) {
1265 // do not filter anything during installation or before upgrade completes
1266 return $string = strip_tags($string);
1269 if ($strcache === false or count($strcache) > 2000) { // this number might need some tuning to limit memory usage in cron
1270 $strcache = array();
1273 if (is_numeric($options)) {
1274 // legacy courseid usage
1275 $options = array('context'=>context_course::instance($options));
1276 } else {
1277 $options = (array)$options; // detach object, we can not modify it
1280 if (empty($options['context'])) {
1281 // fallback to $PAGE->context this may be problematic in CLI and other non-standard pages :-(
1282 $options['context'] = $PAGE->context;
1283 } else if (is_numeric($options['context'])) {
1284 $options['context'] = get_context_instance_by_id($options['context']);
1287 if (!$options['context']) {
1288 // we did not find any context? weird
1289 return $string = strip_tags($string);
1292 //Calculate md5
1293 $md5 = md5($string.'<+>'.$striplinks.'<+>'.$options['context']->id.'<+>'.current_language());
1295 //Fetch from cache if possible
1296 if (isset($strcache[$md5])) {
1297 return $strcache[$md5];
1300 // First replace all ampersands not followed by html entity code
1301 // Regular expression moved to its own method for easier unit testing
1302 $string = replace_ampersands_not_followed_by_entity($string);
1304 if (!empty($CFG->filterall)) {
1305 $filtermanager = filter_manager::instance();
1306 $filtermanager->setup_page_for_filters($PAGE, $options['context']); // Setup global stuff filters may have.
1307 $string = $filtermanager->filter_string($string, $options['context']);
1310 // If the site requires it, strip ALL tags from this string
1311 if (!empty($CFG->formatstringstriptags)) {
1312 $string = str_replace(array('<', '>'), array('&lt;', '&gt;'), strip_tags($string));
1314 } else {
1315 // Otherwise strip just links if that is required (default)
1316 if ($striplinks) { //strip links in string
1317 $string = strip_links($string);
1319 $string = clean_text($string);
1322 //Store to cache
1323 $strcache[$md5] = $string;
1325 return $string;
1329 * Given a string, performs a negative lookahead looking for any ampersand character
1330 * that is not followed by a proper HTML entity. If any is found, it is replaced
1331 * by &amp;. The string is then returned.
1333 * @param string $string
1334 * @return string
1336 function replace_ampersands_not_followed_by_entity($string) {
1337 return preg_replace("/\&(?![a-zA-Z0-9#]{1,8};)/", "&amp;", $string);
1341 * Given a string, replaces all <a>.*</a> by .* and returns the string.
1343 * @param string $string
1344 * @return string
1346 function strip_links($string) {
1347 return preg_replace('/(<a\s[^>]+?>)(.+?)(<\/a>)/is','$2',$string);
1351 * This expression turns links into something nice in a text format. (Russell Jungwirth)
1353 * @param string $string
1354 * @return string
1356 function wikify_links($string) {
1357 return preg_replace('~(<a [^<]*href=["|\']?([^ "\']*)["|\']?[^>]*>([^<]*)</a>)~i','$3 [ $2 ]', $string);
1361 * Given text in a variety of format codings, this function returns
1362 * the text as plain text suitable for plain email.
1364 * @uses FORMAT_MOODLE
1365 * @uses FORMAT_HTML
1366 * @uses FORMAT_PLAIN
1367 * @uses FORMAT_WIKI
1368 * @uses FORMAT_MARKDOWN
1369 * @param string $text The text to be formatted. This is raw text originally from user input.
1370 * @param int $format Identifier of the text format to be used
1371 * [FORMAT_MOODLE, FORMAT_HTML, FORMAT_PLAIN, FORMAT_WIKI, FORMAT_MARKDOWN]
1372 * @return string
1374 function format_text_email($text, $format) {
1376 switch ($format) {
1378 case FORMAT_PLAIN:
1379 return $text;
1380 break;
1382 case FORMAT_WIKI:
1383 // there should not be any of these any more!
1384 $text = wikify_links($text);
1385 return strtr(strip_tags($text), array_flip(get_html_translation_table(HTML_ENTITIES)));
1386 break;
1388 case FORMAT_HTML:
1389 return html_to_text($text);
1390 break;
1392 case FORMAT_MOODLE:
1393 case FORMAT_MARKDOWN:
1394 default:
1395 $text = wikify_links($text);
1396 return strtr(strip_tags($text), array_flip(get_html_translation_table(HTML_ENTITIES)));
1397 break;
1402 * Formats activity intro text
1404 * @global object
1405 * @uses CONTEXT_MODULE
1406 * @param string $module name of module
1407 * @param object $activity instance of activity
1408 * @param int $cmid course module id
1409 * @param bool $filter filter resulting html text
1410 * @return text
1412 function format_module_intro($module, $activity, $cmid, $filter=true) {
1413 global $CFG;
1414 require_once("$CFG->libdir/filelib.php");
1415 $context = context_module::instance($cmid);
1416 $options = array('noclean'=>true, 'para'=>false, 'filter'=>$filter, 'context'=>$context, 'overflowdiv'=>true);
1417 $intro = file_rewrite_pluginfile_urls($activity->intro, 'pluginfile.php', $context->id, 'mod_'.$module, 'intro', null);
1418 return trim(format_text($intro, $activity->introformat, $options, null));
1422 * Legacy function, used for cleaning of old forum and glossary text only.
1424 * @global object
1425 * @param string $text text that may contain legacy TRUSTTEXT marker
1426 * @return text without legacy TRUSTTEXT marker
1428 function trusttext_strip($text) {
1429 while (true) { //removing nested TRUSTTEXT
1430 $orig = $text;
1431 $text = str_replace('#####TRUSTTEXT#####', '', $text);
1432 if (strcmp($orig, $text) === 0) {
1433 return $text;
1439 * Must be called before editing of all texts
1440 * with trust flag. Removes all XSS nasties
1441 * from texts stored in database if needed.
1443 * @param object $object data object with xxx, xxxformat and xxxtrust fields
1444 * @param string $field name of text field
1445 * @param object $context active context
1446 * @return object updated $object
1448 function trusttext_pre_edit($object, $field, $context) {
1449 $trustfield = $field.'trust';
1450 $formatfield = $field.'format';
1452 if (!$object->$trustfield or !trusttext_trusted($context)) {
1453 $object->$field = clean_text($object->$field, $object->$formatfield);
1456 return $object;
1460 * Is current user trusted to enter no dangerous XSS in this context?
1462 * Please note the user must be in fact trusted everywhere on this server!!
1464 * @param object $context
1465 * @return bool true if user trusted
1467 function trusttext_trusted($context) {
1468 return (trusttext_active() and has_capability('moodle/site:trustcontent', $context));
1472 * Is trusttext feature active?
1474 * @return bool
1476 function trusttext_active() {
1477 global $CFG;
1479 return !empty($CFG->enabletrusttext);
1483 * Given raw text (eg typed in by a user), this function cleans it up
1484 * and removes any nasty tags that could mess up Moodle pages through XSS attacks.
1486 * The result must be used as a HTML text fragment, this function can not cleanup random
1487 * parts of html tags such as url or src attributes.
1489 * NOTE: the format parameter was deprecated because we can safely clean only HTML.
1491 * @param string $text The text to be cleaned
1492 * @param int|string $format deprecated parameter, should always contain FORMAT_HTML or FORMAT_MOODLE
1493 * @param array $options Array of options; currently only option supported is 'allowid' (if true,
1494 * does not remove id attributes when cleaning)
1495 * @return string The cleaned up text
1497 function clean_text($text, $format = FORMAT_HTML, $options = array()) {
1498 $text = (string)$text;
1500 if ($format != FORMAT_HTML and $format != FORMAT_HTML) {
1501 // TODO: we need to standardise cleanup of text when loading it into editor first
1502 //debugging('clean_text() is designed to work only with html');
1505 if ($format == FORMAT_PLAIN) {
1506 return $text;
1509 if (is_purify_html_necessary($text)) {
1510 $text = purify_html($text, $options);
1513 // Originally we tried to neutralise some script events here, it was a wrong approach because
1514 // it was trivial to work around that (for example using style based XSS exploits).
1515 // We must not give false sense of security here - all developers MUST understand how to use
1516 // rawurlencode(), htmlentities(), htmlspecialchars(), p(), s(), moodle_url, html_writer and friends!!!
1518 return $text;
1522 * Is it necessary to use HTMLPurifier?
1523 * @private
1524 * @param string $text
1525 * @return bool false means html is safe and valid, true means use HTMLPurifier
1527 function is_purify_html_necessary($text) {
1528 if ($text === '') {
1529 return false;
1532 if ($text === (string)((int)$text)) {
1533 return false;
1536 if (strpos($text, '&') !== false or preg_match('|<[^pesb/]|', $text)) {
1537 // we need to normalise entities or other tags except p, em, strong and br present
1538 return true;
1541 $altered = htmlspecialchars($text, ENT_NOQUOTES, 'UTF-8', true);
1542 if ($altered === $text) {
1543 // no < > or other special chars means this must be safe
1544 return false;
1547 // let's try to convert back some safe html tags
1548 $altered = preg_replace('|&lt;p&gt;(.*?)&lt;/p&gt;|m', '<p>$1</p>', $altered);
1549 if ($altered === $text) {
1550 return false;
1552 $altered = preg_replace('|&lt;em&gt;([^<>]+?)&lt;/em&gt;|m', '<em>$1</em>', $altered);
1553 if ($altered === $text) {
1554 return false;
1556 $altered = preg_replace('|&lt;strong&gt;([^<>]+?)&lt;/strong&gt;|m', '<strong>$1</strong>', $altered);
1557 if ($altered === $text) {
1558 return false;
1560 $altered = str_replace('&lt;br /&gt;', '<br />', $altered);
1561 if ($altered === $text) {
1562 return false;
1565 return true;
1569 * KSES replacement cleaning function - uses HTML Purifier.
1571 * @param string $text The (X)HTML string to purify
1572 * @param array $options Array of options; currently only option supported is 'allowid' (if set,
1573 * does not remove id attributes when cleaning)
1574 * @return string
1576 function purify_html($text, $options = array()) {
1577 global $CFG;
1579 $type = !empty($options['allowid']) ? 'allowid' : 'normal';
1580 static $purifiers = array();
1581 if (empty($purifiers[$type])) {
1583 // make sure the serializer dir exists, it should be fine if it disappears later during cache reset
1584 $cachedir = $CFG->cachedir.'/htmlpurifier';
1585 check_dir_exists($cachedir);
1587 require_once $CFG->libdir.'/htmlpurifier/HTMLPurifier.safe-includes.php';
1588 require_once $CFG->libdir.'/htmlpurifier/locallib.php';
1589 $config = HTMLPurifier_Config::createDefault();
1591 $config->set('HTML.DefinitionID', 'moodlehtml');
1592 $config->set('HTML.DefinitionRev', 2);
1593 $config->set('Cache.SerializerPath', $cachedir);
1594 $config->set('Cache.SerializerPermissions', $CFG->directorypermissions);
1595 $config->set('Core.NormalizeNewlines', false);
1596 $config->set('Core.ConvertDocumentToFragment', true);
1597 $config->set('Core.Encoding', 'UTF-8');
1598 $config->set('HTML.Doctype', 'XHTML 1.0 Transitional');
1599 $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));
1600 $config->set('Attr.AllowedFrameTargets', array('_blank'));
1602 if (!empty($CFG->allowobjectembed)) {
1603 $config->set('HTML.SafeObject', true);
1604 $config->set('Output.FlashCompat', true);
1605 $config->set('HTML.SafeEmbed', true);
1608 if ($type === 'allowid') {
1609 $config->set('Attr.EnableID', true);
1612 if ($def = $config->maybeGetRawHTMLDefinition()) {
1613 $def->addElement('nolink', 'Block', 'Flow', array()); // skip our filters inside
1614 $def->addElement('tex', 'Inline', 'Inline', array()); // tex syntax, equivalent to $$xx$$
1615 $def->addElement('algebra', 'Inline', 'Inline', array()); // algebra syntax, equivalent to @@xx@@
1616 $def->addElement('lang', 'Block', 'Flow', array(), array('lang'=>'CDATA')); // old and future style multilang - only our hacked lang attribute
1617 $def->addAttribute('span', 'xxxlang', 'CDATA'); // current problematic multilang
1620 $purifier = new HTMLPurifier($config);
1621 $purifiers[$type] = $purifier;
1622 } else {
1623 $purifier = $purifiers[$type];
1626 $multilang = (strpos($text, 'class="multilang"') !== false);
1628 if ($multilang) {
1629 $text = preg_replace('/<span(\s+lang="([a-zA-Z0-9_-]+)"|\s+class="multilang"){2}\s*>/', '<span xxxlang="${2}">', $text);
1631 $text = $purifier->purify($text);
1632 if ($multilang) {
1633 $text = preg_replace('/<span xxxlang="([a-zA-Z0-9_-]+)">/', '<span lang="${1}" class="multilang">', $text);
1636 return $text;
1640 * Given plain text, makes it into HTML as nicely as possible.
1641 * May contain HTML tags already
1643 * Do not abuse this function. It is intended as lower level formatting feature used
1644 * by {@see format_text()} to convert FORMAT_MOODLE to HTML. You are supposed
1645 * to call format_text() in most of cases.
1647 * @param string $text The string to convert.
1648 * @param boolean $smiley_ignored Was used to determine if smiley characters should convert to smiley images, ignored now
1649 * @param boolean $para If true then the returned string will be wrapped in div tags
1650 * @param boolean $newlines If true then lines newline breaks will be converted to HTML newline breaks.
1651 * @return string
1653 function text_to_html($text, $smiley_ignored=null, $para=true, $newlines=true) {
1654 /// Remove any whitespace that may be between HTML tags
1655 $text = preg_replace("~>([[:space:]]+)<~i", "><", $text);
1657 /// Remove any returns that precede or follow HTML tags
1658 $text = preg_replace("~([\n\r])<~i", " <", $text);
1659 $text = preg_replace("~>([\n\r])~i", "> ", $text);
1661 /// Make returns into HTML newlines.
1662 if ($newlines) {
1663 $text = nl2br($text);
1666 /// Wrap the whole thing in a div if required
1667 if ($para) {
1668 //return '<p>'.$text.'</p>'; //1.9 version
1669 return '<div class="text_to_html">'.$text.'</div>';
1670 } else {
1671 return $text;
1676 * Given Markdown formatted text, make it into XHTML using external function
1678 * @global object
1679 * @param string $text The markdown formatted text to be converted.
1680 * @return string Converted text
1682 function markdown_to_html($text) {
1683 global $CFG;
1685 if ($text === '' or $text === NULL) {
1686 return $text;
1689 require_once($CFG->libdir .'/markdown.php');
1691 return Markdown($text);
1695 * Given HTML text, make it into plain text using external function
1697 * @param string $html The text to be converted.
1698 * @param integer $width Width to wrap the text at. (optional, default 75 which
1699 * is a good value for email. 0 means do not limit line length.)
1700 * @param boolean $dolinks By default, any links in the HTML are collected, and
1701 * printed as a list at the end of the HTML. If you don't want that, set this
1702 * argument to false.
1703 * @return string plain text equivalent of the HTML.
1705 function html_to_text($html, $width = 75, $dolinks = true) {
1707 global $CFG;
1709 require_once($CFG->libdir .'/html2text.php');
1711 $h2t = new html2text($html, false, $dolinks, $width);
1712 $result = $h2t->get_text();
1714 return $result;
1718 * This function will highlight search words in a given string
1720 * It cares about HTML and will not ruin links. It's best to use
1721 * this function after performing any conversions to HTML.
1723 * @param string $needle The search string. Syntax like "word1 +word2 -word3" is dealt with correctly.
1724 * @param string $haystack The string (HTML) within which to highlight the search terms.
1725 * @param boolean $matchcase whether to do case-sensitive. Default case-insensitive.
1726 * @param string $prefix the string to put before each search term found.
1727 * @param string $suffix the string to put after each search term found.
1728 * @return string The highlighted HTML.
1730 function highlight($needle, $haystack, $matchcase = false,
1731 $prefix = '<span class="highlight">', $suffix = '</span>') {
1733 /// Quick bail-out in trivial cases.
1734 if (empty($needle) or empty($haystack)) {
1735 return $haystack;
1738 /// Break up the search term into words, discard any -words and build a regexp.
1739 $words = preg_split('/ +/', trim($needle));
1740 foreach ($words as $index => $word) {
1741 if (strpos($word, '-') === 0) {
1742 unset($words[$index]);
1743 } else if (strpos($word, '+') === 0) {
1744 $words[$index] = '\b' . preg_quote(ltrim($word, '+'), '/') . '\b'; // Match only as a complete word.
1745 } else {
1746 $words[$index] = preg_quote($word, '/');
1749 $regexp = '/(' . implode('|', $words) . ')/u'; // u is do UTF-8 matching.
1750 if (!$matchcase) {
1751 $regexp .= 'i';
1754 /// Another chance to bail-out if $search was only -words
1755 if (empty($words)) {
1756 return $haystack;
1759 /// Find all the HTML tags in the input, and store them in a placeholders array.
1760 $placeholders = array();
1761 $matches = array();
1762 preg_match_all('/<[^>]*>/', $haystack, $matches);
1763 foreach (array_unique($matches[0]) as $key => $htmltag) {
1764 $placeholders['<|' . $key . '|>'] = $htmltag;
1767 /// In $hastack, replace each HTML tag with the corresponding placeholder.
1768 $haystack = str_replace($placeholders, array_keys($placeholders), $haystack);
1770 /// In the resulting string, Do the highlighting.
1771 $haystack = preg_replace($regexp, $prefix . '$1' . $suffix, $haystack);
1773 /// Turn the placeholders back into HTML tags.
1774 $haystack = str_replace(array_keys($placeholders), $placeholders, $haystack);
1776 return $haystack;
1780 * This function will highlight instances of $needle in $haystack
1782 * It's faster that the above function {@link highlight()} and doesn't care about
1783 * HTML or anything.
1785 * @param string $needle The string to search for
1786 * @param string $haystack The string to search for $needle in
1787 * @return string The highlighted HTML
1789 function highlightfast($needle, $haystack) {
1791 if (empty($needle) or empty($haystack)) {
1792 return $haystack;
1795 $parts = explode(textlib::strtolower($needle), textlib::strtolower($haystack));
1797 if (count($parts) === 1) {
1798 return $haystack;
1801 $pos = 0;
1803 foreach ($parts as $key => $part) {
1804 $parts[$key] = substr($haystack, $pos, strlen($part));
1805 $pos += strlen($part);
1807 $parts[$key] .= '<span class="highlight">'.substr($haystack, $pos, strlen($needle)).'</span>';
1808 $pos += strlen($needle);
1811 return str_replace('<span class="highlight"></span>', '', join('', $parts));
1815 * Return a string containing 'lang', xml:lang and optionally 'dir' HTML attributes.
1816 * Internationalisation, for print_header and backup/restorelib.
1818 * @param bool $dir Default false
1819 * @return string Attributes
1821 function get_html_lang($dir = false) {
1822 $direction = '';
1823 if ($dir) {
1824 if (right_to_left()) {
1825 $direction = ' dir="rtl"';
1826 } else {
1827 $direction = ' dir="ltr"';
1830 //Accessibility: added the 'lang' attribute to $direction, used in theme <html> tag.
1831 $language = str_replace('_', '-', current_language());
1832 @header('Content-Language: '.$language);
1833 return ($direction.' lang="'.$language.'" xml:lang="'.$language.'"');
1837 /// STANDARD WEB PAGE PARTS ///////////////////////////////////////////////////
1840 * Send the HTTP headers that Moodle requires.
1841 * @param $cacheable Can this page be cached on back?
1843 function send_headers($contenttype, $cacheable = true) {
1844 global $CFG;
1846 @header('Content-Type: ' . $contenttype);
1847 @header('Content-Script-Type: text/javascript');
1848 @header('Content-Style-Type: text/css');
1850 if ($cacheable) {
1851 // Allow caching on "back" (but not on normal clicks)
1852 @header('Cache-Control: private, pre-check=0, post-check=0, max-age=0');
1853 @header('Pragma: no-cache');
1854 @header('Expires: ');
1855 } else {
1856 // Do everything we can to always prevent clients and proxies caching
1857 @header('Cache-Control: no-store, no-cache, must-revalidate');
1858 @header('Cache-Control: post-check=0, pre-check=0', false);
1859 @header('Pragma: no-cache');
1860 @header('Expires: Mon, 20 Aug 1969 09:23:00 GMT');
1861 @header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
1863 @header('Accept-Ranges: none');
1865 if (empty($CFG->allowframembedding)) {
1866 @header('X-Frame-Options: sameorigin');
1871 * Return the right arrow with text ('next'), and optionally embedded in a link.
1873 * @global object
1874 * @param string $text HTML/plain text label (set to blank only for breadcrumb separator cases).
1875 * @param string $url An optional link to use in a surrounding HTML anchor.
1876 * @param bool $accesshide True if text should be hidden (for screen readers only).
1877 * @param string $addclass Additional class names for the link, or the arrow character.
1878 * @return string HTML string.
1880 function link_arrow_right($text, $url='', $accesshide=false, $addclass='') {
1881 global $OUTPUT; //TODO: move to output renderer
1882 $arrowclass = 'arrow ';
1883 if (! $url) {
1884 $arrowclass .= $addclass;
1886 $arrow = '<span class="'.$arrowclass.'">'.$OUTPUT->rarrow().'</span>';
1887 $htmltext = '';
1888 if ($text) {
1889 $htmltext = '<span class="arrow_text">'.$text.'</span>&nbsp;';
1890 if ($accesshide) {
1891 $htmltext = get_accesshide($htmltext);
1894 if ($url) {
1895 $class = 'arrow_link';
1896 if ($addclass) {
1897 $class .= ' '.$addclass;
1899 return '<a class="'.$class.'" href="'.$url.'" title="'.preg_replace('/<.*?>/','',$text).'">'.$htmltext.$arrow.'</a>';
1901 return $htmltext.$arrow;
1905 * Return the left arrow with text ('previous'), and optionally embedded in a link.
1907 * @global object
1908 * @param string $text HTML/plain text label (set to blank only for breadcrumb separator cases).
1909 * @param string $url An optional link to use in a surrounding HTML anchor.
1910 * @param bool $accesshide True if text should be hidden (for screen readers only).
1911 * @param string $addclass Additional class names for the link, or the arrow character.
1912 * @return string HTML string.
1914 function link_arrow_left($text, $url='', $accesshide=false, $addclass='') {
1915 global $OUTPUT; // TODO: move to utput renderer
1916 $arrowclass = 'arrow ';
1917 if (! $url) {
1918 $arrowclass .= $addclass;
1920 $arrow = '<span class="'.$arrowclass.'">'.$OUTPUT->larrow().'</span>';
1921 $htmltext = '';
1922 if ($text) {
1923 $htmltext = '&nbsp;<span class="arrow_text">'.$text.'</span>';
1924 if ($accesshide) {
1925 $htmltext = get_accesshide($htmltext);
1928 if ($url) {
1929 $class = 'arrow_link';
1930 if ($addclass) {
1931 $class .= ' '.$addclass;
1933 return '<a class="'.$class.'" href="'.$url.'" title="'.preg_replace('/<.*?>/','',$text).'">'.$arrow.$htmltext.'</a>';
1935 return $arrow.$htmltext;
1939 * Return a HTML element with the class "accesshide", for accessibility.
1940 * Please use cautiously - where possible, text should be visible!
1942 * @param string $text Plain text.
1943 * @param string $elem Lowercase element name, default "span".
1944 * @param string $class Additional classes for the element.
1945 * @param string $attrs Additional attributes string in the form, "name='value' name2='value2'"
1946 * @return string HTML string.
1948 function get_accesshide($text, $elem='span', $class='', $attrs='') {
1949 return "<$elem class=\"accesshide $class\" $attrs>$text</$elem>";
1953 * Return the breadcrumb trail navigation separator.
1955 * @return string HTML string.
1957 function get_separator() {
1958 //Accessibility: the 'hidden' slash is preferred for screen readers.
1959 return ' '.link_arrow_right($text='/', $url='', $accesshide=true, 'sep').' ';
1963 * Print (or return) a collapsible region, that has a caption that can
1964 * be clicked to expand or collapse the region.
1966 * If JavaScript is off, then the region will always be expanded.
1968 * @param string $contents the contents of the box.
1969 * @param string $classes class names added to the div that is output.
1970 * @param string $id id added to the div that is output. Must not be blank.
1971 * @param string $caption text displayed at the top. Clicking on this will cause the region to expand or contract.
1972 * @param string $userpref the name of the user preference that stores the user's preferred default state.
1973 * (May be blank if you do not wish the state to be persisted.
1974 * @param boolean $default Initial collapsed state to use if the user_preference it not set.
1975 * @param boolean $return if true, return the HTML as a string, rather than printing it.
1976 * @return string|void If $return is false, returns nothing, otherwise returns a string of HTML.
1978 function print_collapsible_region($contents, $classes, $id, $caption, $userpref = '', $default = false, $return = false) {
1979 $output = print_collapsible_region_start($classes, $id, $caption, $userpref, $default, true);
1980 $output .= $contents;
1981 $output .= print_collapsible_region_end(true);
1983 if ($return) {
1984 return $output;
1985 } else {
1986 echo $output;
1991 * Print (or return) the start of a collapsible region, that has a caption that can
1992 * be clicked to expand or collapse the region. If JavaScript is off, then the region
1993 * will always be expanded.
1995 * @param string $classes class names added to the div that is output.
1996 * @param string $id id added to the div that is output. Must not be blank.
1997 * @param string $caption text displayed at the top. Clicking on this will cause the region to expand or contract.
1998 * @param string $userpref the name of the user preference that stores the user's preferred default state.
1999 * (May be blank if you do not wish the state to be persisted.
2000 * @param boolean $default Initial collapsed state to use if the user_preference it not set.
2001 * @param boolean $return if true, return the HTML as a string, rather than printing it.
2002 * @return string|void if $return is false, returns nothing, otherwise returns a string of HTML.
2004 function print_collapsible_region_start($classes, $id, $caption, $userpref = '', $default = false, $return = false) {
2005 global $CFG, $PAGE, $OUTPUT;
2007 // Work out the initial state.
2008 if (!empty($userpref) and is_string($userpref)) {
2009 user_preference_allow_ajax_update($userpref, PARAM_BOOL);
2010 $collapsed = get_user_preferences($userpref, $default);
2011 } else {
2012 $collapsed = $default;
2013 $userpref = false;
2016 if ($collapsed) {
2017 $classes .= ' collapsed';
2020 $output = '';
2021 $output .= '<div id="' . $id . '" class="collapsibleregion ' . $classes . '">';
2022 $output .= '<div id="' . $id . '_sizer">';
2023 $output .= '<div id="' . $id . '_caption" class="collapsibleregioncaption">';
2024 $output .= $caption . ' ';
2025 $output .= '</div><div id="' . $id . '_inner" class="collapsibleregioninner">';
2026 $PAGE->requires->js_init_call('M.util.init_collapsible_region', array($id, $userpref, get_string('clicktohideshow')));
2028 if ($return) {
2029 return $output;
2030 } else {
2031 echo $output;
2036 * Close a region started with print_collapsible_region_start.
2038 * @param boolean $return if true, return the HTML as a string, rather than printing it.
2039 * @return string|void if $return is false, returns nothing, otherwise returns a string of HTML.
2041 function print_collapsible_region_end($return = false) {
2042 $output = '</div></div></div>';
2044 if ($return) {
2045 return $output;
2046 } else {
2047 echo $output;
2052 * Print a specified group's avatar.
2054 * @global object
2055 * @uses CONTEXT_COURSE
2056 * @param array|stdClass $group A single {@link group} object OR array of groups.
2057 * @param int $courseid The course ID.
2058 * @param boolean $large Default small picture, or large.
2059 * @param boolean $return If false print picture, otherwise return the output as string
2060 * @param boolean $link Enclose image in a link to view specified course?
2061 * @return string|void Depending on the setting of $return
2063 function print_group_picture($group, $courseid, $large=false, $return=false, $link=true) {
2064 global $CFG;
2066 if (is_array($group)) {
2067 $output = '';
2068 foreach($group as $g) {
2069 $output .= print_group_picture($g, $courseid, $large, true, $link);
2071 if ($return) {
2072 return $output;
2073 } else {
2074 echo $output;
2075 return;
2079 $context = context_course::instance($courseid);
2081 // If there is no picture, do nothing
2082 if (!$group->picture) {
2083 return '';
2086 // If picture is hidden, only show to those with course:managegroups
2087 if ($group->hidepicture and !has_capability('moodle/course:managegroups', $context)) {
2088 return '';
2091 if ($link or has_capability('moodle/site:accessallgroups', $context)) {
2092 $output = '<a href="'. $CFG->wwwroot .'/user/index.php?id='. $courseid .'&amp;group='. $group->id .'">';
2093 } else {
2094 $output = '';
2096 if ($large) {
2097 $file = 'f1';
2098 } else {
2099 $file = 'f2';
2102 $grouppictureurl = moodle_url::make_pluginfile_url($context->id, 'group', 'icon', $group->id, '/', $file);
2103 $output .= '<img class="grouppicture" src="'.$grouppictureurl.'"'.
2104 ' alt="'.s(get_string('group').' '.$group->name).'" title="'.s($group->name).'"/>';
2106 if ($link or has_capability('moodle/site:accessallgroups', $context)) {
2107 $output .= '</a>';
2110 if ($return) {
2111 return $output;
2112 } else {
2113 echo $output;
2119 * Display a recent activity note
2121 * @uses CONTEXT_SYSTEM
2122 * @staticvar string $strftimerecent
2123 * @param object A time object
2124 * @param object A user object
2125 * @param string $text Text for display for the note
2126 * @param string $link The link to wrap around the text
2127 * @param bool $return If set to true the HTML is returned rather than echo'd
2128 * @param string $viewfullnames
2130 function print_recent_activity_note($time, $user, $text, $link, $return=false, $viewfullnames=null) {
2131 static $strftimerecent = null;
2132 $output = '';
2134 if (is_null($viewfullnames)) {
2135 $context = context_system::instance();
2136 $viewfullnames = has_capability('moodle/site:viewfullnames', $context);
2139 if (is_null($strftimerecent)) {
2140 $strftimerecent = get_string('strftimerecent');
2143 $output .= '<div class="head">';
2144 $output .= '<div class="date">'.userdate($time, $strftimerecent).'</div>';
2145 $output .= '<div class="name">'.fullname($user, $viewfullnames).'</div>';
2146 $output .= '</div>';
2147 $output .= '<div class="info"><a href="'.$link.'">'.format_string($text,true).'</a></div>';
2149 if ($return) {
2150 return $output;
2151 } else {
2152 echo $output;
2157 * Returns a popup menu with course activity modules
2159 * Given a course
2160 * This function returns a small popup menu with all the
2161 * course activity modules in it, as a navigation menu
2162 * outputs a simple list structure in XHTML
2163 * The data is taken from the serialised array stored in
2164 * the course record
2166 * @todo Finish documenting this function
2168 * @global object
2169 * @uses CONTEXT_COURSE
2170 * @param course $course A {@link $COURSE} object.
2171 * @param string $sections
2172 * @param string $modinfo
2173 * @param string $strsection
2174 * @param string $strjumpto
2175 * @param int $width
2176 * @param string $cmid
2177 * @return string The HTML block
2179 function navmenulist($course, $sections, $modinfo, $strsection, $strjumpto, $width=50, $cmid=0) {
2181 global $CFG, $OUTPUT;
2183 $section = -1;
2184 $url = '';
2185 $menu = array();
2186 $doneheading = false;
2188 $coursecontext = context_course::instance($course->id);
2190 $menu[] = '<ul class="navmenulist"><li class="jumpto section"><span>'.$strjumpto.'</span><ul>';
2191 foreach ($modinfo->cms as $mod) {
2192 if (!$mod->has_view()) {
2193 // Don't show modules which you can't link to!
2194 continue;
2197 if ($mod->sectionnum > $course->numsections) { /// Don't show excess hidden sections
2198 break;
2201 if (!$mod->uservisible) { // do not icnlude empty sections at all
2202 continue;
2205 if ($mod->sectionnum >= 0 and $section != $mod->sectionnum) {
2206 $thissection = $sections[$mod->sectionnum];
2208 if ($thissection->visible or !$course->hiddensections or
2209 has_capability('moodle/course:viewhiddensections', $coursecontext)) {
2210 $thissection->summary = strip_tags(format_string($thissection->summary,true));
2211 if (!$doneheading) {
2212 $menu[] = '</ul></li>';
2214 if ($course->format == 'weeks' or empty($thissection->summary)) {
2215 $item = $strsection ." ". $mod->sectionnum;
2216 } else {
2217 if (textlib::strlen($thissection->summary) < ($width-3)) {
2218 $item = $thissection->summary;
2219 } else {
2220 $item = textlib::substr($thissection->summary, 0, $width).'...';
2223 $menu[] = '<li class="section"><span>'.$item.'</span>';
2224 $menu[] = '<ul>';
2225 $doneheading = true;
2227 $section = $mod->sectionnum;
2228 } else {
2229 // no activities from this hidden section shown
2230 continue;
2234 $url = $mod->modname .'/view.php?id='. $mod->id;
2235 $mod->name = strip_tags(format_string($mod->name ,true));
2236 if (textlib::strlen($mod->name) > ($width+5)) {
2237 $mod->name = textlib::substr($mod->name, 0, $width).'...';
2239 if (!$mod->visible) {
2240 $mod->name = '('.$mod->name.')';
2242 $class = 'activity '.$mod->modname;
2243 $class .= ($cmid == $mod->id) ? ' selected' : '';
2244 $menu[] = '<li class="'.$class.'">'.
2245 '<img src="'.$OUTPUT->pix_url('icon', $mod->modname) . '" alt="" />'.
2246 '<a href="'.$CFG->wwwroot.'/mod/'.$url.'">'.$mod->name.'</a></li>';
2249 if ($doneheading) {
2250 $menu[] = '</ul></li>';
2252 $menu[] = '</ul></li></ul>';
2254 return implode("\n", $menu);
2258 * Prints a grade menu (as part of an existing form) with help
2259 * Showing all possible numerical grades and scales
2261 * @todo Finish documenting this function
2262 * @todo Deprecate: this is only used in a few contrib modules
2264 * @global object
2265 * @param int $courseid The course ID
2266 * @param string $name
2267 * @param string $current
2268 * @param boolean $includenograde Include those with no grades
2269 * @param boolean $return If set to true returns rather than echo's
2270 * @return string|bool Depending on value of $return
2272 function print_grade_menu($courseid, $name, $current, $includenograde=true, $return=false) {
2274 global $CFG, $OUTPUT;
2276 $output = '';
2277 $strscale = get_string('scale');
2278 $strscales = get_string('scales');
2280 $scales = get_scales_menu($courseid);
2281 foreach ($scales as $i => $scalename) {
2282 $grades[-$i] = $strscale .': '. $scalename;
2284 if ($includenograde) {
2285 $grades[0] = get_string('nograde');
2287 for ($i=100; $i>=1; $i--) {
2288 $grades[$i] = $i;
2290 $output .= html_writer::select($grades, $name, $current, false);
2292 $linkobject = '<span class="helplink"><img class="iconhelp" alt="'.$strscales.'" src="'.$OUTPUT->pix_url('help') . '" /></span>';
2293 $link = new moodle_url('/course/scales.php', array('id'=>$courseid, 'list'=>1));
2294 $action = new popup_action('click', $link, 'ratingscales', array('height' => 400, 'width' => 500));
2295 $output .= $OUTPUT->action_link($link, $linkobject, $action, array('title'=>$strscales));
2297 if ($return) {
2298 return $output;
2299 } else {
2300 echo $output;
2305 * Print an error to STDOUT and exit with a non-zero code. For commandline scripts.
2306 * Default errorcode is 1.
2308 * Very useful for perl-like error-handling:
2310 * do_somethting() or mdie("Something went wrong");
2312 * @param string $msg Error message
2313 * @param integer $errorcode Error code to emit
2315 function mdie($msg='', $errorcode=1) {
2316 trigger_error($msg);
2317 exit($errorcode);
2321 * Print a message and exit.
2323 * @param string $message The message to print in the notice
2324 * @param string $link The link to use for the continue button
2325 * @param object $course A course object
2326 * @return void This function simply exits
2328 function notice ($message, $link='', $course=NULL) {
2329 global $CFG, $SITE, $COURSE, $PAGE, $OUTPUT;
2331 $message = clean_text($message); // In case nasties are in here
2333 if (CLI_SCRIPT) {
2334 echo("!!$message!!\n");
2335 exit(1); // no success
2338 if (!$PAGE->headerprinted) {
2339 //header not yet printed
2340 $PAGE->set_title(get_string('notice'));
2341 echo $OUTPUT->header();
2342 } else {
2343 echo $OUTPUT->container_end_all(false);
2346 echo $OUTPUT->box($message, 'generalbox', 'notice');
2347 echo $OUTPUT->continue_button($link);
2349 echo $OUTPUT->footer();
2350 exit(1); // general error code
2354 * Redirects the user to another page, after printing a notice
2356 * This function calls the OUTPUT redirect method, echo's the output
2357 * and then dies to ensure nothing else happens.
2359 * <strong>Good practice:</strong> You should call this method before starting page
2360 * output by using any of the OUTPUT methods.
2362 * @param moodle_url|string $url A moodle_url to redirect to. Strings are not to be trusted!
2363 * @param string $message The message to display to the user
2364 * @param int $delay The delay before redirecting
2365 * @return void - does not return!
2367 function redirect($url, $message='', $delay=-1) {
2368 global $OUTPUT, $PAGE, $SESSION, $CFG;
2370 if (CLI_SCRIPT or AJAX_SCRIPT) {
2371 // this is wrong - developers should not use redirect in these scripts,
2372 // but it should not be very likely
2373 throw new moodle_exception('redirecterrordetected', 'error');
2376 // prevent debug errors - make sure context is properly initialised
2377 if ($PAGE) {
2378 $PAGE->set_context(null);
2379 $PAGE->set_pagelayout('redirect'); // No header and footer needed
2382 if ($url instanceof moodle_url) {
2383 $url = $url->out(false);
2386 $debugdisableredirect = false;
2387 do {
2388 if (defined('DEBUGGING_PRINTED')) {
2389 // some debugging already printed, no need to look more
2390 $debugdisableredirect = true;
2391 break;
2394 if (empty($CFG->debugdisplay) or empty($CFG->debug)) {
2395 // no errors should be displayed
2396 break;
2399 if (!function_exists('error_get_last') or !$lasterror = error_get_last()) {
2400 break;
2403 if (!($lasterror['type'] & $CFG->debug)) {
2404 //last error not interesting
2405 break;
2408 // watch out here, @hidden() errors are returned from error_get_last() too
2409 if (headers_sent()) {
2410 //we already started printing something - that means errors likely printed
2411 $debugdisableredirect = true;
2412 break;
2415 if (ob_get_level() and ob_get_contents()) {
2416 // there is something waiting to be printed, hopefully it is the errors,
2417 // but it might be some error hidden by @ too - such as the timezone mess from setup.php
2418 $debugdisableredirect = true;
2419 break;
2421 } while (false);
2423 // Technically, HTTP/1.1 requires Location: header to contain the absolute path.
2424 // (In practice browsers accept relative paths - but still, might as well do it properly.)
2425 // This code turns relative into absolute.
2426 if (!preg_match('|^[a-z]+:|', $url)) {
2427 // Get host name http://www.wherever.com
2428 $hostpart = preg_replace('|^(.*?[^:/])/.*$|', '$1', $CFG->wwwroot);
2429 if (preg_match('|^/|', $url)) {
2430 // URLs beginning with / are relative to web server root so we just add them in
2431 $url = $hostpart.$url;
2432 } else {
2433 // URLs not beginning with / are relative to path of current script, so add that on.
2434 $url = $hostpart.preg_replace('|\?.*$|','',me()).'/../'.$url;
2436 // Replace all ..s
2437 while (true) {
2438 $newurl = preg_replace('|/(?!\.\.)[^/]*/\.\./|', '/', $url);
2439 if ($newurl == $url) {
2440 break;
2442 $url = $newurl;
2446 // Sanitise url - we can not rely on moodle_url or our URL cleaning
2447 // because they do not support all valid external URLs
2448 $url = preg_replace('/[\x00-\x1F\x7F]/', '', $url);
2449 $url = str_replace('"', '%22', $url);
2450 $encodedurl = preg_replace("/\&(?![a-zA-Z0-9#]{1,8};)/", "&amp;", $url);
2451 $encodedurl = preg_replace('/^.*href="([^"]*)".*$/', "\\1", clean_text('<a href="'.$encodedurl.'" />', FORMAT_HTML));
2452 $url = str_replace('&amp;', '&', $encodedurl);
2454 if (!empty($message)) {
2455 if ($delay === -1 || !is_numeric($delay)) {
2456 $delay = 3;
2458 $message = clean_text($message);
2459 } else {
2460 $message = get_string('pageshouldredirect');
2461 $delay = 0;
2464 if (defined('MDL_PERF') || (!empty($CFG->perfdebug) and $CFG->perfdebug > 7)) {
2465 if (defined('MDL_PERFTOLOG') && !function_exists('register_shutdown_function')) {
2466 $perf = get_performance_info();
2467 error_log("PERF: " . $perf['txt']);
2471 if ($delay == 0 && !$debugdisableredirect && !headers_sent()) {
2472 // workaround for IIS bug http://support.microsoft.com/kb/q176113/
2473 if (session_id()) {
2474 session_get_instance()->write_close();
2477 //302 might not work for POST requests, 303 is ignored by obsolete clients.
2478 @header($_SERVER['SERVER_PROTOCOL'] . ' 303 See Other');
2479 @header('Location: '.$url);
2480 echo bootstrap_renderer::plain_redirect_message($encodedurl);
2481 exit;
2484 // Include a redirect message, even with a HTTP redirect, because that is recommended practice.
2485 if ($PAGE) {
2486 $CFG->docroot = false; // to prevent the link to moodle docs from being displayed on redirect page.
2487 echo $OUTPUT->redirect_message($encodedurl, $message, $delay, $debugdisableredirect);
2488 exit;
2489 } else {
2490 echo bootstrap_renderer::early_redirect_message($encodedurl, $message, $delay);
2491 exit;
2496 * Given an email address, this function will return an obfuscated version of it
2498 * @param string $email The email address to obfuscate
2499 * @return string The obfuscated email address
2501 function obfuscate_email($email) {
2503 $i = 0;
2504 $length = strlen($email);
2505 $obfuscated = '';
2506 while ($i < $length) {
2507 if (rand(0,2) && $email{$i}!='@') { //MDL-20619 some browsers have problems unobfuscating @
2508 $obfuscated.='%'.dechex(ord($email{$i}));
2509 } else {
2510 $obfuscated.=$email{$i};
2512 $i++;
2514 return $obfuscated;
2518 * This function takes some text and replaces about half of the characters
2519 * with HTML entity equivalents. Return string is obviously longer.
2521 * @param string $plaintext The text to be obfuscated
2522 * @return string The obfuscated text
2524 function obfuscate_text($plaintext) {
2526 $i=0;
2527 $length = strlen($plaintext);
2528 $obfuscated='';
2529 $prev_obfuscated = false;
2530 while ($i < $length) {
2531 $c = ord($plaintext{$i});
2532 $numerical = ($c >= ord('0')) && ($c <= ord('9'));
2533 if ($prev_obfuscated and $numerical ) {
2534 $obfuscated.='&#'.ord($plaintext{$i}).';';
2535 } else if (rand(0,2)) {
2536 $obfuscated.='&#'.ord($plaintext{$i}).';';
2537 $prev_obfuscated = true;
2538 } else {
2539 $obfuscated.=$plaintext{$i};
2540 $prev_obfuscated = false;
2542 $i++;
2544 return $obfuscated;
2548 * This function uses the {@link obfuscate_email()} and {@link obfuscate_text()}
2549 * to generate a fully obfuscated email link, ready to use.
2551 * @param string $email The email address to display
2552 * @param string $label The text to displayed as hyperlink to $email
2553 * @param boolean $dimmed If true then use css class 'dimmed' for hyperlink
2554 * @param string $subject The subject of the email in the mailto link
2555 * @param string $body The content of the email in the mailto link
2556 * @return string The obfuscated mailto link
2558 function obfuscate_mailto($email, $label='', $dimmed=false, $subject = '', $body = '') {
2560 if (empty($label)) {
2561 $label = $email;
2564 $label = obfuscate_text($label);
2565 $email = obfuscate_email($email);
2566 $mailto = obfuscate_text('mailto');
2567 $url = new moodle_url("mailto:$email");
2568 $attrs = array();
2570 if (!empty($subject)) {
2571 $url->param('subject', format_string($subject));
2573 if (!empty($body)) {
2574 $url->param('body', format_string($body));
2577 // Use the obfuscated mailto
2578 $url = preg_replace('/^mailto/', $mailto, $url->out());
2580 if ($dimmed) {
2581 $attrs['title'] = get_string('emaildisable');
2582 $attrs['class'] = 'dimmed';
2585 return html_writer::link($url, $label, $attrs);
2589 * This function is used to rebuild the <nolink> tag because some formats (PLAIN and WIKI)
2590 * will transform it to html entities
2592 * @param string $text Text to search for nolink tag in
2593 * @return string
2595 function rebuildnolinktag($text) {
2597 $text = preg_replace('/&lt;(\/*nolink)&gt;/i','<$1>',$text);
2599 return $text;
2603 * Prints a maintenance message from $CFG->maintenance_message or default if empty
2604 * @return void
2606 function print_maintenance_message() {
2607 global $CFG, $SITE, $PAGE, $OUTPUT;
2609 $PAGE->set_pagetype('maintenance-message');
2610 $PAGE->set_pagelayout('maintenance');
2611 $PAGE->set_title(strip_tags($SITE->fullname));
2612 $PAGE->set_heading($SITE->fullname);
2613 echo $OUTPUT->header();
2614 echo $OUTPUT->heading(get_string('sitemaintenance', 'admin'));
2615 if (isset($CFG->maintenance_message) and !html_is_blank($CFG->maintenance_message)) {
2616 echo $OUTPUT->box_start('maintenance_message generalbox boxwidthwide boxaligncenter');
2617 echo $CFG->maintenance_message;
2618 echo $OUTPUT->box_end();
2620 echo $OUTPUT->footer();
2621 die;
2625 * A class for tabs, Some code to print tabs
2627 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2628 * @package moodlecore
2630 class tabobject {
2632 * @var string
2634 var $id;
2635 var $link;
2636 var $text;
2638 * @var bool
2640 var $linkedwhenselected;
2643 * A constructor just because I like constructors
2645 * @param string $id
2646 * @param string $link
2647 * @param string $text
2648 * @param string $title
2649 * @param bool $linkedwhenselected
2651 function tabobject ($id, $link='', $text='', $title='', $linkedwhenselected=false) {
2652 $this->id = $id;
2653 $this->link = $link;
2654 $this->text = $text;
2655 $this->title = $title ? $title : $text;
2656 $this->linkedwhenselected = $linkedwhenselected;
2663 * Returns a string containing a nested list, suitable for formatting into tabs with CSS.
2665 * @global object
2666 * @param array $tabrows An array of rows where each row is an array of tab objects
2667 * @param string $selected The id of the selected tab (whatever row it's on)
2668 * @param array $inactive An array of ids of inactive tabs that are not selectable.
2669 * @param array $activated An array of ids of other tabs that are currently activated
2670 * @param bool $return If true output is returned rather then echo'd
2672 function print_tabs($tabrows, $selected=NULL, $inactive=NULL, $activated=NULL, $return=false) {
2673 global $CFG;
2675 /// $inactive must be an array
2676 if (!is_array($inactive)) {
2677 $inactive = array();
2680 /// $activated must be an array
2681 if (!is_array($activated)) {
2682 $activated = array();
2685 /// Convert the tab rows into a tree that's easier to process
2686 if (!$tree = convert_tabrows_to_tree($tabrows, $selected, $inactive, $activated)) {
2687 return false;
2690 /// Print out the current tree of tabs (this function is recursive)
2692 $output = convert_tree_to_html($tree);
2694 $output = "\n\n".'<div class="tabtree">'.$output.'</div><div class="clearer"> </div>'."\n\n";
2696 /// We're done!
2698 if ($return) {
2699 return $output;
2701 echo $output;
2705 * Converts a nested array tree into HTML ul:li [recursive]
2707 * @param array $tree A tree array to convert
2708 * @param int $row Used in identifying the iteration level and in ul classes
2709 * @return string HTML structure
2711 function convert_tree_to_html($tree, $row=0) {
2713 $str = "\n".'<ul class="tabrow'.$row.'">'."\n";
2715 $first = true;
2716 $count = count($tree);
2718 foreach ($tree as $tab) {
2719 $count--; // countdown to zero
2721 $liclass = '';
2723 if ($first && ($count == 0)) { // Just one in the row
2724 $liclass = 'first last';
2725 $first = false;
2726 } else if ($first) {
2727 $liclass = 'first';
2728 $first = false;
2729 } else if ($count == 0) {
2730 $liclass = 'last';
2733 if ((empty($tab->subtree)) && (!empty($tab->selected))) {
2734 $liclass .= (empty($liclass)) ? 'onerow' : ' onerow';
2737 if ($tab->inactive || $tab->active || $tab->selected) {
2738 if ($tab->selected) {
2739 $liclass .= (empty($liclass)) ? 'here selected' : ' here selected';
2740 } else if ($tab->active) {
2741 $liclass .= (empty($liclass)) ? 'here active' : ' here active';
2745 $str .= (!empty($liclass)) ? '<li class="'.$liclass.'">' : '<li>';
2747 if ($tab->inactive || $tab->active || ($tab->selected && !$tab->linkedwhenselected)) {
2748 // The a tag is used for styling
2749 $str .= '<a class="nolink"><span>'.$tab->text.'</span></a>';
2750 } else {
2751 $str .= '<a href="'.$tab->link.'" title="'.$tab->title.'"><span>'.$tab->text.'</span></a>';
2754 if (!empty($tab->subtree)) {
2755 $str .= convert_tree_to_html($tab->subtree, $row+1);
2756 } else if ($tab->selected) {
2757 $str .= '<div class="tabrow'.($row+1).' empty">&nbsp;</div>'."\n";
2760 $str .= ' </li>'."\n";
2762 $str .= '</ul>'."\n";
2764 return $str;
2768 * Convert nested tabrows to a nested array
2770 * @param array $tabrows A [nested] array of tab row objects
2771 * @param string $selected The tabrow to select (by id)
2772 * @param array $inactive An array of tabrow id's to make inactive
2773 * @param array $activated An array of tabrow id's to make active
2774 * @return array The nested array
2776 function convert_tabrows_to_tree($tabrows, $selected, $inactive, $activated) {
2778 /// Work backwards through the rows (bottom to top) collecting the tree as we go.
2780 $tabrows = array_reverse($tabrows);
2782 $subtree = array();
2784 foreach ($tabrows as $row) {
2785 $tree = array();
2787 foreach ($row as $tab) {
2788 $tab->inactive = in_array((string)$tab->id, $inactive);
2789 $tab->active = in_array((string)$tab->id, $activated);
2790 $tab->selected = (string)$tab->id == $selected;
2792 if ($tab->active || $tab->selected) {
2793 if ($subtree) {
2794 $tab->subtree = $subtree;
2797 $tree[] = $tab;
2799 $subtree = $tree;
2802 return $subtree;
2806 * Standard Debugging Function
2808 * Returns true if the current site debugging settings are equal or above specified level.
2809 * If passed a parameter it will emit a debugging notice similar to trigger_error(). The
2810 * routing of notices is controlled by $CFG->debugdisplay
2811 * eg use like this:
2813 * 1) debugging('a normal debug notice');
2814 * 2) debugging('something really picky', DEBUG_ALL);
2815 * 3) debugging('annoying debug message only for developers', DEBUG_DEVELOPER);
2816 * 4) if (debugging()) { perform extra debugging operations (do not use print or echo) }
2818 * In code blocks controlled by debugging() (such as example 4)
2819 * any output should be routed via debugging() itself, or the lower-level
2820 * trigger_error() or error_log(). Using echo or print will break XHTML
2821 * JS and HTTP headers.
2823 * It is also possible to define NO_DEBUG_DISPLAY which redirects the message to error_log.
2825 * @uses DEBUG_NORMAL
2826 * @param string $message a message to print
2827 * @param int $level the level at which this debugging statement should show
2828 * @param array $backtrace use different backtrace
2829 * @return bool
2831 function debugging($message = '', $level = DEBUG_NORMAL, $backtrace = null) {
2832 global $CFG, $USER;
2834 $forcedebug = false;
2835 if (!empty($CFG->debugusers) && $USER) {
2836 $debugusers = explode(',', $CFG->debugusers);
2837 $forcedebug = in_array($USER->id, $debugusers);
2840 if (!$forcedebug and (empty($CFG->debug) || ($CFG->debug != -1 and $CFG->debug < $level))) {
2841 return false;
2844 if (!isset($CFG->debugdisplay)) {
2845 $CFG->debugdisplay = ini_get_bool('display_errors');
2848 if ($message) {
2849 if (!$backtrace) {
2850 $backtrace = debug_backtrace();
2852 $from = format_backtrace($backtrace, CLI_SCRIPT);
2853 if (PHPUNIT_TEST) {
2854 echo 'Debugging: ' . $message . "\n" . $from;
2856 } else if (NO_DEBUG_DISPLAY) {
2857 // script does not want any errors or debugging in output,
2858 // we send the info to error log instead
2859 error_log('Debugging: ' . $message . $from);
2861 } else if ($forcedebug or $CFG->debugdisplay) {
2862 if (!defined('DEBUGGING_PRINTED')) {
2863 define('DEBUGGING_PRINTED', 1); // indicates we have printed something
2865 if (CLI_SCRIPT) {
2866 echo "++ $message ++\n$from";
2867 } else {
2868 echo '<div class="notifytiny">' . $message . $from . '</div>';
2871 } else {
2872 trigger_error($message . $from, E_USER_NOTICE);
2875 return true;
2879 * Outputs a HTML comment to the browser. This is used for those hard-to-debug
2880 * pages that use bits from many different files in very confusing ways (e.g. blocks).
2882 * <code>print_location_comment(__FILE__, __LINE__);</code>
2884 * @param string $file
2885 * @param integer $line
2886 * @param boolean $return Whether to return or print the comment
2887 * @return string|void Void unless true given as third parameter
2889 function print_location_comment($file, $line, $return = false)
2891 if ($return) {
2892 return "<!-- $file at line $line -->\n";
2893 } else {
2894 echo "<!-- $file at line $line -->\n";
2900 * @return boolean true if the current language is right-to-left (Hebrew, Arabic etc)
2902 function right_to_left() {
2903 return (get_string('thisdirection', 'langconfig') === 'rtl');
2908 * Returns swapped left<=>right if in RTL environment.
2909 * part of RTL support
2911 * @param string $align align to check
2912 * @return string
2914 function fix_align_rtl($align) {
2915 if (!right_to_left()) {
2916 return $align;
2918 if ($align=='left') { return 'right'; }
2919 if ($align=='right') { return 'left'; }
2920 return $align;
2925 * Returns true if the page is displayed in a popup window.
2926 * Gets the information from the URL parameter inpopup.
2928 * @todo Use a central function to create the popup calls all over Moodle and
2929 * In the moment only works with resources and probably questions.
2931 * @return boolean
2933 function is_in_popup() {
2934 $inpopup = optional_param('inpopup', '', PARAM_BOOL);
2936 return ($inpopup);
2940 * To use this class.
2941 * - construct
2942 * - call create (or use the 3rd param to the constructor)
2943 * - call update or update_full() or update() repeatedly
2945 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2946 * @package moodlecore
2948 class progress_bar {
2949 /** @var string html id */
2950 private $html_id;
2951 /** @var int total width */
2952 private $width;
2953 /** @var int last percentage printed */
2954 private $percent = 0;
2955 /** @var int time when last printed */
2956 private $lastupdate = 0;
2957 /** @var int when did we start printing this */
2958 private $time_start = 0;
2961 * Constructor
2963 * @param string $html_id
2964 * @param int $width
2965 * @param bool $autostart Default to false
2966 * @return void, prints JS code if $autostart true
2968 public function __construct($html_id = '', $width = 500, $autostart = false) {
2969 if (!empty($html_id)) {
2970 $this->html_id = $html_id;
2971 } else {
2972 $this->html_id = 'pbar_'.uniqid();
2975 $this->width = $width;
2977 if ($autostart){
2978 $this->create();
2983 * Create a new progress bar, this function will output html.
2985 * @return void Echo's output
2987 public function create() {
2988 $this->time_start = microtime(true);
2989 if (CLI_SCRIPT) {
2990 return; // temporary solution for cli scripts
2992 $htmlcode = <<<EOT
2993 <div style="text-align:center;width:{$this->width}px;clear:both;padding:0;margin:0 auto;">
2994 <h2 id="status_{$this->html_id}" style="text-align: center;margin:0 auto"></h2>
2995 <p id="time_{$this->html_id}"></p>
2996 <div id="bar_{$this->html_id}" style="border-style:solid;border-width:1px;width:500px;height:50px;">
2997 <div id="progress_{$this->html_id}"
2998 style="text-align:center;background:#FFCC66;width:4px;border:1px
2999 solid gray;height:38px; padding-top:10px;">&nbsp;<span id="pt_{$this->html_id}"></span>
3000 </div>
3001 </div>
3002 </div>
3003 EOT;
3004 flush();
3005 echo $htmlcode;
3006 flush();
3010 * Update the progress bar
3012 * @param int $percent from 1-100
3013 * @param string $msg
3014 * @return void Echo's output
3016 private function _update($percent, $msg) {
3017 if (empty($this->time_start)) {
3018 throw new coding_exception('You must call create() (or use the $autostart ' .
3019 'argument to the constructor) before you try updating the progress bar.');
3022 if (CLI_SCRIPT) {
3023 return; // temporary solution for cli scripts
3026 $es = $this->estimate($percent);
3028 if ($es === null) {
3029 // always do the first and last updates
3030 $es = "?";
3031 } else if ($es == 0) {
3032 // always do the last updates
3033 } else if ($this->lastupdate + 20 < time()) {
3034 // we must update otherwise browser would time out
3035 } else if (round($this->percent, 2) === round($percent, 2)) {
3036 // no significant change, no need to update anything
3037 return;
3040 $this->percent = $percent;
3041 $this->lastupdate = microtime(true);
3043 $w = ($this->percent/100) * $this->width;
3044 echo html_writer::script(js_writer::function_call('update_progress_bar', array($this->html_id, $w, $this->percent, $msg, $es)));
3045 flush();
3049 * Estimate how much time it is going to take.
3051 * @param int $curtime the time call this function
3052 * @param int $percent from 1-100
3053 * @return mixed Null (unknown), or int
3055 private function estimate($pt) {
3056 if ($this->lastupdate == 0) {
3057 return null;
3059 if ($pt < 0.00001) {
3060 return null; // we do not know yet how long it will take
3062 if ($pt > 99.99999) {
3063 return 0; // nearly done, right?
3065 $consumed = microtime(true) - $this->time_start;
3066 if ($consumed < 0.001) {
3067 return null;
3070 return (100 - $pt) * ($consumed / $pt);
3074 * Update progress bar according percent
3076 * @param int $percent from 1-100
3077 * @param string $msg the message needed to be shown
3079 public function update_full($percent, $msg) {
3080 $percent = max(min($percent, 100), 0);
3081 $this->_update($percent, $msg);
3085 * Update progress bar according the number of tasks
3087 * @param int $cur current task number
3088 * @param int $total total task number
3089 * @param string $msg message
3091 public function update($cur, $total, $msg) {
3092 $percent = ($cur / $total) * 100;
3093 $this->update_full($percent, $msg);
3097 * Restart the progress bar.
3099 public function restart() {
3100 $this->percent = 0;
3101 $this->lastupdate = 0;
3102 $this->time_start = 0;
3107 * Use this class from long operations where you want to output occasional information about
3108 * what is going on, but don't know if, or in what format, the output should be.
3110 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3111 * @package moodlecore
3113 abstract class progress_trace {
3115 * Ouput an progress message in whatever format.
3116 * @param string $message the message to output.
3117 * @param integer $depth indent depth for this message.
3119 abstract public function output($message, $depth = 0);
3122 * Called when the processing is finished.
3124 public function finished() {
3129 * This subclass of progress_trace does not ouput anything.
3131 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3132 * @package moodlecore
3134 class null_progress_trace extends progress_trace {
3136 * Does Nothing
3138 * @param string $message
3139 * @param int $depth
3140 * @return void Does Nothing
3142 public function output($message, $depth = 0) {
3147 * This subclass of progress_trace outputs to plain text.
3149 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3150 * @package moodlecore
3152 class text_progress_trace extends progress_trace {
3154 * Output the trace message
3156 * @param string $message
3157 * @param int $depth
3158 * @return void Output is echo'd
3160 public function output($message, $depth = 0) {
3161 echo str_repeat(' ', $depth), $message, "\n";
3162 flush();
3167 * This subclass of progress_trace outputs as HTML.
3169 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3170 * @package moodlecore
3172 class html_progress_trace extends progress_trace {
3174 * Output the trace message
3176 * @param string $message
3177 * @param int $depth
3178 * @return void Output is echo'd
3180 public function output($message, $depth = 0) {
3181 echo '<p>', str_repeat('&#160;&#160;', $depth), htmlspecialchars($message), "</p>\n";
3182 flush();
3187 * HTML List Progress Tree
3189 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3190 * @package moodlecore
3192 class html_list_progress_trace extends progress_trace {
3193 /** @var int */
3194 protected $currentdepth = -1;
3197 * Echo out the list
3199 * @param string $message The message to display
3200 * @param int $depth
3201 * @return void Output is echoed
3203 public function output($message, $depth = 0) {
3204 $samedepth = true;
3205 while ($this->currentdepth > $depth) {
3206 echo "</li>\n</ul>\n";
3207 $this->currentdepth -= 1;
3208 if ($this->currentdepth == $depth) {
3209 echo '<li>';
3211 $samedepth = false;
3213 while ($this->currentdepth < $depth) {
3214 echo "<ul>\n<li>";
3215 $this->currentdepth += 1;
3216 $samedepth = false;
3218 if ($samedepth) {
3219 echo "</li>\n<li>";
3221 echo htmlspecialchars($message);
3222 flush();
3226 * Called when the processing is finished.
3228 public function finished() {
3229 while ($this->currentdepth >= 0) {
3230 echo "</li>\n</ul>\n";
3231 $this->currentdepth -= 1;
3237 * Returns a localized sentence in the current language summarizing the current password policy
3239 * @todo this should be handled by a function/method in the language pack library once we have a support for it
3240 * @uses $CFG
3241 * @return string
3243 function print_password_policy() {
3244 global $CFG;
3246 $message = '';
3247 if (!empty($CFG->passwordpolicy)) {
3248 $messages = array();
3249 $messages[] = get_string('informminpasswordlength', 'auth', $CFG->minpasswordlength);
3250 if (!empty($CFG->minpassworddigits)) {
3251 $messages[] = get_string('informminpassworddigits', 'auth', $CFG->minpassworddigits);
3253 if (!empty($CFG->minpasswordlower)) {
3254 $messages[] = get_string('informminpasswordlower', 'auth', $CFG->minpasswordlower);
3256 if (!empty($CFG->minpasswordupper)) {
3257 $messages[] = get_string('informminpasswordupper', 'auth', $CFG->minpasswordupper);
3259 if (!empty($CFG->minpasswordnonalphanum)) {
3260 $messages[] = get_string('informminpasswordnonalphanum', 'auth', $CFG->minpasswordnonalphanum);
3263 $messages = join(', ', $messages); // this is ugly but we do not have anything better yet...
3264 $message = get_string('informpasswordpolicy', 'auth', $messages);
3266 return $message;