Merge branch 'm25_MDL-40200_Notices_When_Viewing_Profile_Invalid_UserId' of https...
[moodle.git] / lib / weblib.php
blob55c2ee1ba2671cb0a6afd0b8225208a257ff4963
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 * @param string $var the string potentially containing HTML characters
89 * @return string
91 function s($var) {
93 if ($var === false) {
94 return '0';
97 // When we move to PHP 5.4 as a minimum version, change ENT_QUOTES on the
98 // next line to ENT_QUOTES | ENT_HTML5 | ENT_SUBSTITUTE, and remove the
99 // 'UTF-8' argument. Both bring a speed-increase.
100 return preg_replace('/&amp;#(\d+|x[0-9a-f]+);/i', '&#$1;', htmlspecialchars($var, ENT_QUOTES, 'UTF-8'));
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 if (isset($val) && $val !== '') {
492 $arr[] = rawurlencode($key)."=".rawurlencode($val);
493 } else {
494 $arr[] = rawurlencode($key);
498 if ($escaped) {
499 return implode('&amp;', $arr);
500 } else {
501 return implode('&', $arr);
506 * Shortcut for printing of encoded URL.
507 * @return string
509 public function __toString() {
510 return $this->out(true);
514 * Output url
516 * If you use the returned URL in HTML code, you want the escaped ampersands. If you use
517 * the returned URL in HTTP headers, you want $escaped=false.
519 * @param boolean $escaped Use &amp; as params separator instead of plain &
520 * @param array $overrideparams params to add to the output url, these override existing ones with the same name.
521 * @return string Resulting URL
523 public function out($escaped = true, array $overrideparams = null) {
524 if (!is_bool($escaped)) {
525 debugging('Escape parameter must be of type boolean, '.gettype($escaped).' given instead.');
528 $uri = $this->out_omit_querystring().$this->slashargument;
530 $querystring = $this->get_query_string($escaped, $overrideparams);
531 if ($querystring !== '') {
532 $uri .= '?' . $querystring;
534 if (!is_null($this->anchor)) {
535 $uri .= '#'.$this->anchor;
538 return $uri;
542 * Returns url without parameters, everything before '?'.
544 * @param bool $includeanchor if {@link self::anchor} is defined, should it be returned?
545 * @return string
547 public function out_omit_querystring($includeanchor = false) {
549 $uri = $this->scheme ? $this->scheme.':'.((strtolower($this->scheme) == 'mailto') ? '':'//'): '';
550 $uri .= $this->user ? $this->user.($this->pass? ':'.$this->pass:'').'@':'';
551 $uri .= $this->host ? $this->host : '';
552 $uri .= $this->port ? ':'.$this->port : '';
553 $uri .= $this->path ? $this->path : '';
554 if ($includeanchor and !is_null($this->anchor)) {
555 $uri .= '#' . $this->anchor;
558 return $uri;
562 * Compares this moodle_url with another
563 * See documentation of constants for an explanation of the comparison flags.
564 * @param moodle_url $url The moodle_url object to compare
565 * @param int $matchtype The type of comparison (URL_MATCH_BASE, URL_MATCH_PARAMS, URL_MATCH_EXACT)
566 * @return boolean
568 public function compare(moodle_url $url, $matchtype = URL_MATCH_EXACT) {
570 $baseself = $this->out_omit_querystring();
571 $baseother = $url->out_omit_querystring();
573 // Append index.php if there is no specific file
574 if (substr($baseself,-1)=='/') {
575 $baseself .= 'index.php';
577 if (substr($baseother,-1)=='/') {
578 $baseother .= 'index.php';
581 // Compare the two base URLs
582 if ($baseself != $baseother) {
583 return false;
586 if ($matchtype == URL_MATCH_BASE) {
587 return true;
590 $urlparams = $url->params();
591 foreach ($this->params() as $param => $value) {
592 if ($param == 'sesskey') {
593 continue;
595 if (!array_key_exists($param, $urlparams) || $urlparams[$param] != $value) {
596 return false;
600 if ($matchtype == URL_MATCH_PARAMS) {
601 return true;
604 foreach ($urlparams as $param => $value) {
605 if ($param == 'sesskey') {
606 continue;
608 if (!array_key_exists($param, $this->params()) || $this->param($param) != $value) {
609 return false;
613 return true;
617 * Sets the anchor for the URI (the bit after the hash)
618 * @param string $anchor null means remove previous
620 public function set_anchor($anchor) {
621 if (is_null($anchor)) {
622 // remove
623 $this->anchor = null;
624 } else if ($anchor === '') {
625 // special case, used as empty link
626 $this->anchor = '';
627 } else if (preg_match('|[a-zA-Z\_\:][a-zA-Z0-9\_\-\.\:]*|', $anchor)) {
628 // Match the anchor against the NMTOKEN spec
629 $this->anchor = $anchor;
630 } else {
631 // bad luck, no valid anchor found
632 $this->anchor = null;
637 * Sets the url slashargument value
638 * @param string $path usually file path
639 * @param string $parameter name of page parameter if slasharguments not supported
640 * @param bool $supported usually null, then it depends on $CFG->slasharguments, use true or false for other servers
641 * @return void
643 public function set_slashargument($path, $parameter = 'file', $supported = NULL) {
644 global $CFG;
645 if (is_null($supported)) {
646 $supported = $CFG->slasharguments;
649 if ($supported) {
650 $parts = explode('/', $path);
651 $parts = array_map('rawurlencode', $parts);
652 $path = implode('/', $parts);
653 $this->slashargument = $path;
654 unset($this->params[$parameter]);
656 } else {
657 $this->slashargument = '';
658 $this->params[$parameter] = $path;
662 // == static factory methods ==
665 * General moodle file url.
666 * @param string $urlbase the script serving the file
667 * @param string $path
668 * @param bool $forcedownload
669 * @return moodle_url
671 public static function make_file_url($urlbase, $path, $forcedownload = false) {
672 global $CFG;
674 $params = array();
675 if ($forcedownload) {
676 $params['forcedownload'] = 1;
679 $url = new moodle_url($urlbase, $params);
680 $url->set_slashargument($path);
682 return $url;
686 * Factory method for creation of url pointing to plugin file.
687 * Please note this method can be used only from the plugins to
688 * create urls of own files, it must not be used outside of plugins!
689 * @param int $contextid
690 * @param string $component
691 * @param string $area
692 * @param int $itemid
693 * @param string $pathname
694 * @param string $filename
695 * @param bool $forcedownload
696 * @return moodle_url
698 public static function make_pluginfile_url($contextid, $component, $area, $itemid, $pathname, $filename, $forcedownload = false) {
699 global $CFG;
700 $urlbase = "$CFG->httpswwwroot/pluginfile.php";
701 if ($itemid === NULL) {
702 return self::make_file_url($urlbase, "/$contextid/$component/$area".$pathname.$filename, $forcedownload);
703 } else {
704 return self::make_file_url($urlbase, "/$contextid/$component/$area/$itemid".$pathname.$filename, $forcedownload);
709 * Factory method for creation of url pointing to draft
710 * file of current user.
711 * @param int $draftid draft item id
712 * @param string $pathname
713 * @param string $filename
714 * @param bool $forcedownload
715 * @return moodle_url
717 public static function make_draftfile_url($draftid, $pathname, $filename, $forcedownload = false) {
718 global $CFG, $USER;
719 $urlbase = "$CFG->httpswwwroot/draftfile.php";
720 $context = context_user::instance($USER->id);
722 return self::make_file_url($urlbase, "/$context->id/user/draft/$draftid".$pathname.$filename, $forcedownload);
726 * Factory method for creating of links to legacy
727 * course files.
728 * @param int $courseid
729 * @param string $filepath
730 * @param bool $forcedownload
731 * @return moodle_url
733 public static function make_legacyfile_url($courseid, $filepath, $forcedownload = false) {
734 global $CFG;
736 $urlbase = "$CFG->wwwroot/file.php";
737 return self::make_file_url($urlbase, '/'.$courseid.'/'.$filepath, $forcedownload);
741 * Returns URL a relative path from $CFG->wwwroot
743 * Can be used for passing around urls with the wwwroot stripped
745 * @param boolean $escaped Use &amp; as params separator instead of plain &
746 * @param array $overrideparams params to add to the output url, these override existing ones with the same name.
747 * @return string Resulting URL
748 * @throws coding_exception if called on a non-local url
750 public function out_as_local_url($escaped = true, array $overrideparams = null) {
751 global $CFG;
753 $url = $this->out($escaped, $overrideparams);
754 $httpswwwroot = str_replace("http://", "https://", $CFG->wwwroot);
756 // $url should be equal to wwwroot or httpswwwroot. If not then throw exception.
757 if (($url === $CFG->wwwroot) || (strpos($url, $CFG->wwwroot.'/') === 0)) {
758 $localurl = substr($url, strlen($CFG->wwwroot));
759 return !empty($localurl) ? $localurl : '';
760 } else if (($url === $httpswwwroot) || (strpos($url, $httpswwwroot.'/') === 0)) {
761 $localurl = substr($url, strlen($httpswwwroot));
762 return !empty($localurl) ? $localurl : '';
763 } else {
764 throw new coding_exception('out_as_local_url called on a non-local URL');
769 * Returns the 'path' portion of a URL. For example, if the URL is
770 * http://www.example.org:447/my/file/is/here.txt?really=1 then this will
771 * return '/my/file/is/here.txt'.
773 * By default the path includes slash-arguments (for example,
774 * '/myfile.php/extra/arguments') so it is what you would expect from a
775 * URL path. If you don't want this behaviour, you can opt to exclude the
776 * slash arguments. (Be careful: if the $CFG variable slasharguments is
777 * disabled, these URLs will have a different format and you may need to
778 * look at the 'file' parameter too.)
780 * @param bool $includeslashargument If true, includes slash arguments
781 * @return string Path of URL
783 public function get_path($includeslashargument = true) {
784 return $this->path . ($includeslashargument ? $this->slashargument : '');
788 * Returns a given parameter value from the URL.
790 * @param string $name Name of parameter
791 * @return string Value of parameter or null if not set
793 public function get_param($name) {
794 if (array_key_exists($name, $this->params)) {
795 return $this->params[$name];
796 } else {
797 return null;
803 * Determine if there is data waiting to be processed from a form
805 * Used on most forms in Moodle to check for data
806 * Returns the data as an object, if it's found.
807 * This object can be used in foreach loops without
808 * casting because it's cast to (array) automatically
810 * Checks that submitted POST data exists and returns it as object.
812 * @uses $_POST
813 * @return mixed false or object
815 function data_submitted() {
817 if (empty($_POST)) {
818 return false;
819 } else {
820 return (object)fix_utf8($_POST);
825 * Given some normal text this function will break up any
826 * long words to a given size by inserting the given character
828 * It's multibyte savvy and doesn't change anything inside html tags.
830 * @param string $string the string to be modified
831 * @param int $maxsize maximum length of the string to be returned
832 * @param string $cutchar the string used to represent word breaks
833 * @return string
835 function break_up_long_words($string, $maxsize=20, $cutchar=' ') {
837 /// First of all, save all the tags inside the text to skip them
838 $tags = array();
839 filter_save_tags($string,$tags);
841 /// Process the string adding the cut when necessary
842 $output = '';
843 $length = textlib::strlen($string);
844 $wordlength = 0;
846 for ($i=0; $i<$length; $i++) {
847 $char = textlib::substr($string, $i, 1);
848 if ($char == ' ' or $char == "\t" or $char == "\n" or $char == "\r" or $char == "<" or $char == ">") {
849 $wordlength = 0;
850 } else {
851 $wordlength++;
852 if ($wordlength > $maxsize) {
853 $output .= $cutchar;
854 $wordlength = 0;
857 $output .= $char;
860 /// Finally load the tags back again
861 if (!empty($tags)) {
862 $output = str_replace(array_keys($tags), $tags, $output);
865 return $output;
869 * Try and close the current window using JavaScript, either immediately, or after a delay.
871 * Echo's out the resulting XHTML & javascript
873 * @global object
874 * @global object
875 * @param integer $delay a delay in seconds before closing the window. Default 0.
876 * @param boolean $reloadopener if true, we will see if this window was a pop-up, and try
877 * to reload the parent window before this one closes.
879 function close_window($delay = 0, $reloadopener = false) {
880 global $PAGE, $OUTPUT;
882 if (!$PAGE->headerprinted) {
883 $PAGE->set_title(get_string('closewindow'));
884 echo $OUTPUT->header();
885 } else {
886 $OUTPUT->container_end_all(false);
889 if ($reloadopener) {
890 // Trigger the reload immediately, even if the reload is after a delay.
891 $PAGE->requires->js_function_call('window.opener.location.reload', array(true));
893 $OUTPUT->notification(get_string('windowclosing'), 'notifysuccess');
895 $PAGE->requires->js_function_call('close_window', array(new stdClass()), false, $delay);
897 echo $OUTPUT->footer();
898 exit;
902 * Returns a string containing a link to the user documentation for the current
903 * page. Also contains an icon by default. Shown to teachers and admin only.
905 * @global object
906 * @global object
907 * @param string $text The text to be displayed for the link
908 * @param string $iconpath The path to the icon to be displayed
909 * @return string The link to user documentation for this current page
911 function page_doc_link($text='') {
912 global $OUTPUT, $PAGE;
913 $path = page_get_doc_link_path($PAGE);
914 if (!$path) {
915 return '';
917 return $OUTPUT->doc_link($path, $text);
921 * Returns the path to use when constructing a link to the docs.
923 * @since 2.5.1 2.6
924 * @global stdClass $CFG
925 * @param moodle_page $page
926 * @return string
928 function page_get_doc_link_path(moodle_page $page) {
929 global $CFG;
931 if (empty($CFG->docroot) || during_initial_install()) {
932 return '';
934 if (!has_capability('moodle/site:doclinks', $page->context)) {
935 return '';
938 $path = $page->docspath;
939 if (!$path) {
940 return '';
942 return $path;
947 * Validates an email to make sure it makes sense.
949 * @param string $address The email address to validate.
950 * @return boolean
952 function validate_email($address) {
954 return (preg_match('#^[-!\#$%&\'*+\\/0-9=?A-Z^_`a-z{|}~]+'.
955 '(\.[-!\#$%&\'*+\\/0-9=?A-Z^_`a-z{|}~]+)*'.
956 '@'.
957 '[-!\#$%&\'*+\\/0-9=?A-Z^_`a-z{|}~]+\.'.
958 '[-!\#$%&\'*+\\./0-9=?A-Z^_`a-z{|}~]+$#',
959 $address));
963 * Extracts file argument either from file parameter or PATH_INFO
964 * Note: $scriptname parameter is not needed anymore
966 * @global string
967 * @uses $_SERVER
968 * @uses PARAM_PATH
969 * @return string file path (only safe characters)
971 function get_file_argument() {
972 global $SCRIPT;
974 $relativepath = optional_param('file', FALSE, PARAM_PATH);
976 if ($relativepath !== false and $relativepath !== '') {
977 return $relativepath;
979 $relativepath = false;
981 // then try extract file from the slasharguments
982 if (stripos($_SERVER['SERVER_SOFTWARE'], 'iis') !== false) {
983 // NOTE: ISS tends to convert all file paths to single byte DOS encoding,
984 // we can not use other methods because they break unicode chars,
985 // the only way is to use URL rewriting
986 if (isset($_SERVER['PATH_INFO']) and $_SERVER['PATH_INFO'] !== '') {
987 // check that PATH_INFO works == must not contain the script name
988 if (strpos($_SERVER['PATH_INFO'], $SCRIPT) === false) {
989 $relativepath = clean_param(urldecode($_SERVER['PATH_INFO']), PARAM_PATH);
992 } else {
993 // all other apache-like servers depend on PATH_INFO
994 if (isset($_SERVER['PATH_INFO'])) {
995 if (isset($_SERVER['SCRIPT_NAME']) and strpos($_SERVER['PATH_INFO'], $_SERVER['SCRIPT_NAME']) === 0) {
996 $relativepath = substr($_SERVER['PATH_INFO'], strlen($_SERVER['SCRIPT_NAME']));
997 } else {
998 $relativepath = $_SERVER['PATH_INFO'];
1000 $relativepath = clean_param($relativepath, PARAM_PATH);
1005 return $relativepath;
1009 * Just returns an array of text formats suitable for a popup menu
1011 * @uses FORMAT_MOODLE
1012 * @uses FORMAT_HTML
1013 * @uses FORMAT_PLAIN
1014 * @uses FORMAT_MARKDOWN
1015 * @return array
1017 function format_text_menu() {
1018 return array (FORMAT_MOODLE => get_string('formattext'),
1019 FORMAT_HTML => get_string('formathtml'),
1020 FORMAT_PLAIN => get_string('formatplain'),
1021 FORMAT_MARKDOWN => get_string('formatmarkdown'));
1025 * Given text in a variety of format codings, this function returns
1026 * the text as safe HTML.
1028 * This function should mainly be used for long strings like posts,
1029 * answers, glossary items etc. For short strings @see format_string().
1031 * <pre>
1032 * Options:
1033 * trusted : If true the string won't be cleaned. Default false required noclean=true.
1034 * noclean : If true the string won't be cleaned. Default false required trusted=true.
1035 * nocache : If true the strign will not be cached and will be formatted every call. Default false.
1036 * filter : If true the string will be run through applicable filters as well. Default true.
1037 * para : If true then the returned string will be wrapped in div tags. Default true.
1038 * newlines : If true then lines newline breaks will be converted to HTML newline breaks. Default true.
1039 * context : The context that will be used for filtering.
1040 * overflowdiv : If set to true the formatted text will be encased in a div
1041 * with the class no-overflow before being returned. Default false.
1042 * allowid : If true then id attributes will not be removed, even when
1043 * using htmlpurifier. Default false.
1044 * </pre>
1046 * @todo Finish documenting this function
1048 * @staticvar array $croncache
1049 * @param string $text The text to be formatted. This is raw text originally from user input.
1050 * @param int $format Identifier of the text format to be used
1051 * [FORMAT_MOODLE, FORMAT_HTML, FORMAT_PLAIN, FORMAT_MARKDOWN]
1052 * @param object/array $options text formatting options
1053 * @param int $courseid_do_not_use deprecated course id, use context option instead
1054 * @return string
1056 function format_text($text, $format = FORMAT_MOODLE, $options = NULL, $courseid_do_not_use = NULL) {
1057 global $CFG, $COURSE, $DB, $PAGE;
1058 static $croncache = array();
1060 if ($text === '' || is_null($text)) {
1061 return ''; // no need to do any filters and cleaning
1064 $options = (array)$options; // detach object, we can not modify it
1066 if (!isset($options['trusted'])) {
1067 $options['trusted'] = false;
1069 if (!isset($options['noclean'])) {
1070 if ($options['trusted'] and trusttext_active()) {
1071 // no cleaning if text trusted and noclean not specified
1072 $options['noclean'] = true;
1073 } else {
1074 $options['noclean'] = false;
1077 if (!isset($options['nocache'])) {
1078 $options['nocache'] = false;
1080 if (!isset($options['filter'])) {
1081 $options['filter'] = true;
1083 if (!isset($options['para'])) {
1084 $options['para'] = true;
1086 if (!isset($options['newlines'])) {
1087 $options['newlines'] = true;
1089 if (!isset($options['overflowdiv'])) {
1090 $options['overflowdiv'] = false;
1093 // Calculate best context
1094 if (empty($CFG->version) or $CFG->version < 2013051400 or during_initial_install()) {
1095 // do not filter anything during installation or before upgrade completes
1096 $context = null;
1098 } else if (isset($options['context'])) { // first by explicit passed context option
1099 if (is_object($options['context'])) {
1100 $context = $options['context'];
1101 } else {
1102 $context = context::instance_by_id($options['context']);
1104 } else if ($courseid_do_not_use) {
1105 // legacy courseid
1106 $context = context_course::instance($courseid_do_not_use);
1107 } else {
1108 // fallback to $PAGE->context this may be problematic in CLI and other non-standard pages :-(
1109 $context = $PAGE->context;
1112 if (!$context) {
1113 // either install/upgrade or something has gone really wrong because context does not exist (yet?)
1114 $options['nocache'] = true;
1115 $options['filter'] = false;
1118 if ($options['filter']) {
1119 $filtermanager = filter_manager::instance();
1120 $filtermanager->setup_page_for_filters($PAGE, $context); // Setup global stuff filters may have.
1121 } else {
1122 $filtermanager = new null_filter_manager();
1125 if (!empty($CFG->cachetext) and empty($options['nocache'])) {
1126 $hashstr = $text.'-'.$filtermanager->text_filtering_hash($context).'-'.$context->id.'-'.current_language().'-'.
1127 (int)$format.(int)$options['trusted'].(int)$options['noclean'].
1128 (int)$options['para'].(int)$options['newlines'];
1130 $time = time() - $CFG->cachetext;
1131 $md5key = md5($hashstr);
1132 if (CLI_SCRIPT) {
1133 if (isset($croncache[$md5key])) {
1134 return $croncache[$md5key];
1138 if ($oldcacheitem = $DB->get_record('cache_text', array('md5key'=>$md5key), '*', IGNORE_MULTIPLE)) {
1139 if ($oldcacheitem->timemodified >= $time) {
1140 if (CLI_SCRIPT) {
1141 if (count($croncache) > 150) {
1142 reset($croncache);
1143 $key = key($croncache);
1144 unset($croncache[$key]);
1146 $croncache[$md5key] = $oldcacheitem->formattedtext;
1148 return $oldcacheitem->formattedtext;
1153 switch ($format) {
1154 case FORMAT_HTML:
1155 if (!$options['noclean']) {
1156 $text = clean_text($text, FORMAT_HTML, $options);
1158 $text = $filtermanager->filter_text($text, $context, array('originalformat' => FORMAT_HTML, 'noclean' => $options['noclean']));
1159 break;
1161 case FORMAT_PLAIN:
1162 $text = s($text); // cleans dangerous JS
1163 $text = rebuildnolinktag($text);
1164 $text = str_replace(' ', '&nbsp; ', $text);
1165 $text = nl2br($text);
1166 break;
1168 case FORMAT_WIKI:
1169 // this format is deprecated
1170 $text = '<p>NOTICE: Wiki-like formatting has been removed from Moodle. You should not be seeing
1171 this message as all texts should have been converted to Markdown format instead.
1172 Please post a bug report to http://moodle.org/bugs with information about where you
1173 saw this message.</p>'.s($text);
1174 break;
1176 case FORMAT_MARKDOWN:
1177 $text = markdown_to_html($text);
1178 if (!$options['noclean']) {
1179 $text = clean_text($text, FORMAT_HTML, $options);
1181 $text = $filtermanager->filter_text($text, $context, array('originalformat' => FORMAT_MARKDOWN, 'noclean' => $options['noclean']));
1182 break;
1184 default: // FORMAT_MOODLE or anything else
1185 $text = text_to_html($text, null, $options['para'], $options['newlines']);
1186 if (!$options['noclean']) {
1187 $text = clean_text($text, FORMAT_HTML, $options);
1189 $text = $filtermanager->filter_text($text, $context, array('originalformat' => $format, 'noclean' => $options['noclean']));
1190 break;
1192 if ($options['filter']) {
1193 // at this point there should not be any draftfile links any more,
1194 // this happens when developers forget to post process the text.
1195 // The only potential problem is that somebody might try to format
1196 // the text before storing into database which would be itself big bug.
1197 $text = str_replace("\"$CFG->httpswwwroot/draftfile.php", "\"$CFG->httpswwwroot/brokenfile.php#", $text);
1200 // Warn people that we have removed this old mechanism, just in case they
1201 // were stupid enough to rely on it.
1202 if (isset($CFG->currenttextiscacheable)) {
1203 debugging('Once upon a time, Moodle had a truly evil use of global variables ' .
1204 'called $CFG->currenttextiscacheable. The good news is that this no ' .
1205 'longer exists. The bad news is that you seem to be using a filter that '.
1206 'relies on it. Please seek out and destroy that filter code.', DEBUG_DEVELOPER);
1209 if (!empty($options['overflowdiv'])) {
1210 $text = html_writer::tag('div', $text, array('class'=>'no-overflow'));
1213 if (empty($options['nocache']) and !empty($CFG->cachetext)) {
1214 if (CLI_SCRIPT) {
1215 // special static cron cache - no need to store it in db if its not already there
1216 if (count($croncache) > 150) {
1217 reset($croncache);
1218 $key = key($croncache);
1219 unset($croncache[$key]);
1221 $croncache[$md5key] = $text;
1222 return $text;
1225 $newcacheitem = new stdClass();
1226 $newcacheitem->md5key = $md5key;
1227 $newcacheitem->formattedtext = $text;
1228 $newcacheitem->timemodified = time();
1229 if ($oldcacheitem) { // See bug 4677 for discussion
1230 $newcacheitem->id = $oldcacheitem->id;
1231 try {
1232 $DB->update_record('cache_text', $newcacheitem); // Update existing record in the cache table
1233 } catch (dml_exception $e) {
1234 // It's unlikely that the cron cache cleaner could have
1235 // deleted this entry in the meantime, as it allows
1236 // some extra time to cover these cases.
1238 } else {
1239 try {
1240 $DB->insert_record('cache_text', $newcacheitem); // Insert a new record in the cache table
1241 } catch (dml_exception $e) {
1242 // Again, it's possible that another user has caused this
1243 // record to be created already in the time that it took
1244 // to traverse this function. That's OK too, as the
1245 // call above handles duplicate entries, and eventually
1246 // the cron cleaner will delete them.
1251 return $text;
1255 * Resets all data related to filters, called during upgrade or when filter settings change.
1257 * @param bool $phpunitreset true means called from our PHPUnit integration test reset
1258 * @return void
1260 function reset_text_filters_cache($phpunitreset = false) {
1261 global $CFG, $DB;
1263 if (!$phpunitreset) {
1264 $DB->delete_records('cache_text');
1267 $purifdir = $CFG->cachedir.'/htmlpurifier';
1268 remove_dir($purifdir, true);
1272 * Given a simple string, this function returns the string
1273 * processed by enabled string filters if $CFG->filterall is enabled
1275 * This function should be used to print short strings (non html) that
1276 * need filter processing e.g. activity titles, post subjects,
1277 * glossary concepts.
1279 * @staticvar bool $strcache
1280 * @param string $string The string to be filtered. Should be plain text, expect
1281 * possibly for multilang tags.
1282 * @param boolean $striplinks To strip any link in the result text.
1283 Moodle 1.8 default changed from false to true! MDL-8713
1284 * @param array $options options array/object or courseid
1285 * @return string
1287 function format_string($string, $striplinks = true, $options = NULL) {
1288 global $CFG, $COURSE, $PAGE;
1290 //We'll use a in-memory cache here to speed up repeated strings
1291 static $strcache = false;
1293 if (empty($CFG->version) or $CFG->version < 2010072800 or during_initial_install()) {
1294 // do not filter anything during installation or before upgrade completes
1295 return $string = strip_tags($string);
1298 if ($strcache === false or count($strcache) > 2000) { // this number might need some tuning to limit memory usage in cron
1299 $strcache = array();
1302 if (is_numeric($options)) {
1303 // legacy courseid usage
1304 $options = array('context'=>context_course::instance($options));
1305 } else {
1306 $options = (array)$options; // detach object, we can not modify it
1309 if (empty($options['context'])) {
1310 // fallback to $PAGE->context this may be problematic in CLI and other non-standard pages :-(
1311 $options['context'] = $PAGE->context;
1312 } else if (is_numeric($options['context'])) {
1313 $options['context'] = context::instance_by_id($options['context']);
1316 if (!$options['context']) {
1317 // we did not find any context? weird
1318 return $string = strip_tags($string);
1321 //Calculate md5
1322 $md5 = md5($string.'<+>'.$striplinks.'<+>'.$options['context']->id.'<+>'.current_language());
1324 //Fetch from cache if possible
1325 if (isset($strcache[$md5])) {
1326 return $strcache[$md5];
1329 // First replace all ampersands not followed by html entity code
1330 // Regular expression moved to its own method for easier unit testing
1331 $string = replace_ampersands_not_followed_by_entity($string);
1333 if (!empty($CFG->filterall)) {
1334 $filtermanager = filter_manager::instance();
1335 $filtermanager->setup_page_for_filters($PAGE, $options['context']); // Setup global stuff filters may have.
1336 $string = $filtermanager->filter_string($string, $options['context']);
1339 // If the site requires it, strip ALL tags from this string
1340 if (!empty($CFG->formatstringstriptags)) {
1341 $string = str_replace(array('<', '>'), array('&lt;', '&gt;'), strip_tags($string));
1343 } else {
1344 // Otherwise strip just links if that is required (default)
1345 if ($striplinks) { //strip links in string
1346 $string = strip_links($string);
1348 $string = clean_text($string);
1351 //Store to cache
1352 $strcache[$md5] = $string;
1354 return $string;
1358 * Given a string, performs a negative lookahead looking for any ampersand character
1359 * that is not followed by a proper HTML entity. If any is found, it is replaced
1360 * by &amp;. The string is then returned.
1362 * @param string $string
1363 * @return string
1365 function replace_ampersands_not_followed_by_entity($string) {
1366 return preg_replace("/\&(?![a-zA-Z0-9#]{1,8};)/", "&amp;", $string);
1370 * Given a string, replaces all <a>.*</a> by .* and returns the string.
1372 * @param string $string
1373 * @return string
1375 function strip_links($string) {
1376 return preg_replace('/(<a\s[^>]+?>)(.+?)(<\/a>)/is','$2',$string);
1380 * This expression turns links into something nice in a text format. (Russell Jungwirth)
1382 * @param string $string
1383 * @return string
1385 function wikify_links($string) {
1386 return preg_replace('~(<a [^<]*href=["|\']?([^ "\']*)["|\']?[^>]*>([^<]*)</a>)~i','$3 [ $2 ]', $string);
1390 * Given text in a variety of format codings, this function returns
1391 * the text as plain text suitable for plain email.
1393 * @uses FORMAT_MOODLE
1394 * @uses FORMAT_HTML
1395 * @uses FORMAT_PLAIN
1396 * @uses FORMAT_WIKI
1397 * @uses FORMAT_MARKDOWN
1398 * @param string $text The text to be formatted. This is raw text originally from user input.
1399 * @param int $format Identifier of the text format to be used
1400 * [FORMAT_MOODLE, FORMAT_HTML, FORMAT_PLAIN, FORMAT_WIKI, FORMAT_MARKDOWN]
1401 * @return string
1403 function format_text_email($text, $format) {
1405 switch ($format) {
1407 case FORMAT_PLAIN:
1408 return $text;
1409 break;
1411 case FORMAT_WIKI:
1412 // there should not be any of these any more!
1413 $text = wikify_links($text);
1414 return textlib::entities_to_utf8(strip_tags($text), true);
1415 break;
1417 case FORMAT_HTML:
1418 return html_to_text($text);
1419 break;
1421 case FORMAT_MOODLE:
1422 case FORMAT_MARKDOWN:
1423 default:
1424 $text = wikify_links($text);
1425 return textlib::entities_to_utf8(strip_tags($text), true);
1426 break;
1431 * Formats activity intro text
1433 * @global object
1434 * @uses CONTEXT_MODULE
1435 * @param string $module name of module
1436 * @param object $activity instance of activity
1437 * @param int $cmid course module id
1438 * @param bool $filter filter resulting html text
1439 * @return text
1441 function format_module_intro($module, $activity, $cmid, $filter=true) {
1442 global $CFG;
1443 require_once("$CFG->libdir/filelib.php");
1444 $context = context_module::instance($cmid);
1445 $options = array('noclean'=>true, 'para'=>false, 'filter'=>$filter, 'context'=>$context, 'overflowdiv'=>true);
1446 $intro = file_rewrite_pluginfile_urls($activity->intro, 'pluginfile.php', $context->id, 'mod_'.$module, 'intro', null);
1447 return trim(format_text($intro, $activity->introformat, $options, null));
1451 * Legacy function, used for cleaning of old forum and glossary text only.
1453 * @global object
1454 * @param string $text text that may contain legacy TRUSTTEXT marker
1455 * @return text without legacy TRUSTTEXT marker
1457 function trusttext_strip($text) {
1458 while (true) { //removing nested TRUSTTEXT
1459 $orig = $text;
1460 $text = str_replace('#####TRUSTTEXT#####', '', $text);
1461 if (strcmp($orig, $text) === 0) {
1462 return $text;
1468 * Must be called before editing of all texts
1469 * with trust flag. Removes all XSS nasties
1470 * from texts stored in database if needed.
1472 * @param object $object data object with xxx, xxxformat and xxxtrust fields
1473 * @param string $field name of text field
1474 * @param object $context active context
1475 * @return object updated $object
1477 function trusttext_pre_edit($object, $field, $context) {
1478 $trustfield = $field.'trust';
1479 $formatfield = $field.'format';
1481 if (!$object->$trustfield or !trusttext_trusted($context)) {
1482 $object->$field = clean_text($object->$field, $object->$formatfield);
1485 return $object;
1489 * Is current user trusted to enter no dangerous XSS in this context?
1491 * Please note the user must be in fact trusted everywhere on this server!!
1493 * @param object $context
1494 * @return bool true if user trusted
1496 function trusttext_trusted($context) {
1497 return (trusttext_active() and has_capability('moodle/site:trustcontent', $context));
1501 * Is trusttext feature active?
1503 * @return bool
1505 function trusttext_active() {
1506 global $CFG;
1508 return !empty($CFG->enabletrusttext);
1512 * Given raw text (eg typed in by a user), this function cleans it up
1513 * and removes any nasty tags that could mess up Moodle pages through XSS attacks.
1515 * The result must be used as a HTML text fragment, this function can not cleanup random
1516 * parts of html tags such as url or src attributes.
1518 * NOTE: the format parameter was deprecated because we can safely clean only HTML.
1520 * @param string $text The text to be cleaned
1521 * @param int|string $format deprecated parameter, should always contain FORMAT_HTML or FORMAT_MOODLE
1522 * @param array $options Array of options; currently only option supported is 'allowid' (if true,
1523 * does not remove id attributes when cleaning)
1524 * @return string The cleaned up text
1526 function clean_text($text, $format = FORMAT_HTML, $options = array()) {
1527 $text = (string)$text;
1529 if ($format != FORMAT_HTML and $format != FORMAT_HTML) {
1530 // TODO: we need to standardise cleanup of text when loading it into editor first
1531 //debugging('clean_text() is designed to work only with html');
1534 if ($format == FORMAT_PLAIN) {
1535 return $text;
1538 if (is_purify_html_necessary($text)) {
1539 $text = purify_html($text, $options);
1542 // Originally we tried to neutralise some script events here, it was a wrong approach because
1543 // it was trivial to work around that (for example using style based XSS exploits).
1544 // We must not give false sense of security here - all developers MUST understand how to use
1545 // rawurlencode(), htmlentities(), htmlspecialchars(), p(), s(), moodle_url, html_writer and friends!!!
1547 return $text;
1551 * Is it necessary to use HTMLPurifier?
1552 * @private
1553 * @param string $text
1554 * @return bool false means html is safe and valid, true means use HTMLPurifier
1556 function is_purify_html_necessary($text) {
1557 if ($text === '') {
1558 return false;
1561 if ($text === (string)((int)$text)) {
1562 return false;
1565 if (strpos($text, '&') !== false or preg_match('|<[^pesb/]|', $text)) {
1566 // we need to normalise entities or other tags except p, em, strong and br present
1567 return true;
1570 $altered = htmlspecialchars($text, ENT_NOQUOTES, 'UTF-8', true);
1571 if ($altered === $text) {
1572 // no < > or other special chars means this must be safe
1573 return false;
1576 // let's try to convert back some safe html tags
1577 $altered = preg_replace('|&lt;p&gt;(.*?)&lt;/p&gt;|m', '<p>$1</p>', $altered);
1578 if ($altered === $text) {
1579 return false;
1581 $altered = preg_replace('|&lt;em&gt;([^<>]+?)&lt;/em&gt;|m', '<em>$1</em>', $altered);
1582 if ($altered === $text) {
1583 return false;
1585 $altered = preg_replace('|&lt;strong&gt;([^<>]+?)&lt;/strong&gt;|m', '<strong>$1</strong>', $altered);
1586 if ($altered === $text) {
1587 return false;
1589 $altered = str_replace('&lt;br /&gt;', '<br />', $altered);
1590 if ($altered === $text) {
1591 return false;
1594 return true;
1598 * KSES replacement cleaning function - uses HTML Purifier.
1600 * @param string $text The (X)HTML string to purify
1601 * @param array $options Array of options; currently only option supported is 'allowid' (if set,
1602 * does not remove id attributes when cleaning)
1603 * @return string
1605 function purify_html($text, $options = array()) {
1606 global $CFG;
1608 static $purifiers = array();
1609 static $caches = array();
1611 $type = !empty($options['allowid']) ? 'allowid' : 'normal';
1613 if (!array_key_exists($type, $caches)) {
1614 $caches[$type] = cache::make('core', 'htmlpurifier', array('type' => $type));
1616 $cache = $caches[$type];
1618 $filteredtext = $cache->get($text);
1619 if ($filteredtext !== false) {
1620 return $filteredtext;
1623 if (empty($purifiers[$type])) {
1625 // make sure the serializer dir exists, it should be fine if it disappears later during cache reset
1626 $cachedir = $CFG->cachedir.'/htmlpurifier';
1627 check_dir_exists($cachedir);
1629 require_once $CFG->libdir.'/htmlpurifier/HTMLPurifier.safe-includes.php';
1630 require_once $CFG->libdir.'/htmlpurifier/locallib.php';
1631 $config = HTMLPurifier_Config::createDefault();
1633 $config->set('HTML.DefinitionID', 'moodlehtml');
1634 $config->set('HTML.DefinitionRev', 2);
1635 $config->set('Cache.SerializerPath', $cachedir);
1636 $config->set('Cache.SerializerPermissions', $CFG->directorypermissions);
1637 $config->set('Core.NormalizeNewlines', false);
1638 $config->set('Core.ConvertDocumentToFragment', true);
1639 $config->set('Core.Encoding', 'UTF-8');
1640 $config->set('HTML.Doctype', 'XHTML 1.0 Transitional');
1641 $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));
1642 $config->set('Attr.AllowedFrameTargets', array('_blank'));
1644 if (!empty($CFG->allowobjectembed)) {
1645 $config->set('HTML.SafeObject', true);
1646 $config->set('Output.FlashCompat', true);
1647 $config->set('HTML.SafeEmbed', true);
1650 if ($type === 'allowid') {
1651 $config->set('Attr.EnableID', true);
1654 if ($def = $config->maybeGetRawHTMLDefinition()) {
1655 $def->addElement('nolink', 'Block', 'Flow', array()); // skip our filters inside
1656 $def->addElement('tex', 'Inline', 'Inline', array()); // tex syntax, equivalent to $$xx$$
1657 $def->addElement('algebra', 'Inline', 'Inline', array()); // algebra syntax, equivalent to @@xx@@
1658 $def->addElement('lang', 'Block', 'Flow', array(), array('lang'=>'CDATA')); // old and future style multilang - only our hacked lang attribute
1659 $def->addAttribute('span', 'xxxlang', 'CDATA'); // current problematic multilang
1662 $purifier = new HTMLPurifier($config);
1663 $purifiers[$type] = $purifier;
1664 } else {
1665 $purifier = $purifiers[$type];
1668 $multilang = (strpos($text, 'class="multilang"') !== false);
1670 $filteredtext = $text;
1671 if ($multilang) {
1672 $filteredtext = preg_replace('/<span(\s+lang="([a-zA-Z0-9_-]+)"|\s+class="multilang"){2}\s*>/', '<span xxxlang="${2}">', $filteredtext);
1674 $filteredtext = $purifier->purify($filteredtext);
1675 if ($multilang) {
1676 $filteredtext = preg_replace('/<span xxxlang="([a-zA-Z0-9_-]+)">/', '<span lang="${1}" class="multilang">', $filteredtext);
1678 $cache->set($text, $filteredtext);
1680 return $filteredtext;
1684 * Given plain text, makes it into HTML as nicely as possible.
1685 * May contain HTML tags already
1687 * Do not abuse this function. It is intended as lower level formatting feature used
1688 * by {@see format_text()} to convert FORMAT_MOODLE to HTML. You are supposed
1689 * to call format_text() in most of cases.
1691 * @param string $text The string to convert.
1692 * @param boolean $smiley_ignored Was used to determine if smiley characters should convert to smiley images, ignored now
1693 * @param boolean $para If true then the returned string will be wrapped in div tags
1694 * @param boolean $newlines If true then lines newline breaks will be converted to HTML newline breaks.
1695 * @return string
1697 function text_to_html($text, $smiley_ignored=null, $para=true, $newlines=true) {
1698 /// Remove any whitespace that may be between HTML tags
1699 $text = preg_replace("~>([[:space:]]+)<~i", "><", $text);
1701 /// Remove any returns that precede or follow HTML tags
1702 $text = preg_replace("~([\n\r])<~i", " <", $text);
1703 $text = preg_replace("~>([\n\r])~i", "> ", $text);
1705 /// Make returns into HTML newlines.
1706 if ($newlines) {
1707 $text = nl2br($text);
1710 /// Wrap the whole thing in a div if required
1711 if ($para) {
1712 //return '<p>'.$text.'</p>'; //1.9 version
1713 return '<div class="text_to_html">'.$text.'</div>';
1714 } else {
1715 return $text;
1720 * Given Markdown formatted text, make it into XHTML using external function
1722 * @global object
1723 * @param string $text The markdown formatted text to be converted.
1724 * @return string Converted text
1726 function markdown_to_html($text) {
1727 global $CFG;
1729 if ($text === '' or $text === NULL) {
1730 return $text;
1733 require_once($CFG->libdir .'/markdown.php');
1735 return Markdown($text);
1739 * Given HTML text, make it into plain text using external function
1741 * @param string $html The text to be converted.
1742 * @param integer $width Width to wrap the text at. (optional, default 75 which
1743 * is a good value for email. 0 means do not limit line length.)
1744 * @param boolean $dolinks By default, any links in the HTML are collected, and
1745 * printed as a list at the end of the HTML. If you don't want that, set this
1746 * argument to false.
1747 * @return string plain text equivalent of the HTML.
1749 function html_to_text($html, $width = 75, $dolinks = true) {
1751 global $CFG;
1753 require_once($CFG->libdir .'/html2text.php');
1755 $h2t = new html2text($html, false, $dolinks, $width);
1756 $result = $h2t->get_text();
1758 return $result;
1762 * This function will highlight search words in a given string
1764 * It cares about HTML and will not ruin links. It's best to use
1765 * this function after performing any conversions to HTML.
1767 * @param string $needle The search string. Syntax like "word1 +word2 -word3" is dealt with correctly.
1768 * @param string $haystack The string (HTML) within which to highlight the search terms.
1769 * @param boolean $matchcase whether to do case-sensitive. Default case-insensitive.
1770 * @param string $prefix the string to put before each search term found.
1771 * @param string $suffix the string to put after each search term found.
1772 * @return string The highlighted HTML.
1774 function highlight($needle, $haystack, $matchcase = false,
1775 $prefix = '<span class="highlight">', $suffix = '</span>') {
1777 /// Quick bail-out in trivial cases.
1778 if (empty($needle) or empty($haystack)) {
1779 return $haystack;
1782 /// Break up the search term into words, discard any -words and build a regexp.
1783 $words = preg_split('/ +/', trim($needle));
1784 foreach ($words as $index => $word) {
1785 if (strpos($word, '-') === 0) {
1786 unset($words[$index]);
1787 } else if (strpos($word, '+') === 0) {
1788 $words[$index] = '\b' . preg_quote(ltrim($word, '+'), '/') . '\b'; // Match only as a complete word.
1789 } else {
1790 $words[$index] = preg_quote($word, '/');
1793 $regexp = '/(' . implode('|', $words) . ')/u'; // u is do UTF-8 matching.
1794 if (!$matchcase) {
1795 $regexp .= 'i';
1798 /// Another chance to bail-out if $search was only -words
1799 if (empty($words)) {
1800 return $haystack;
1803 /// Find all the HTML tags in the input, and store them in a placeholders array.
1804 $placeholders = array();
1805 $matches = array();
1806 preg_match_all('/<[^>]*>/', $haystack, $matches);
1807 foreach (array_unique($matches[0]) as $key => $htmltag) {
1808 $placeholders['<|' . $key . '|>'] = $htmltag;
1811 /// In $hastack, replace each HTML tag with the corresponding placeholder.
1812 $haystack = str_replace($placeholders, array_keys($placeholders), $haystack);
1814 /// In the resulting string, Do the highlighting.
1815 $haystack = preg_replace($regexp, $prefix . '$1' . $suffix, $haystack);
1817 /// Turn the placeholders back into HTML tags.
1818 $haystack = str_replace(array_keys($placeholders), $placeholders, $haystack);
1820 return $haystack;
1824 * This function will highlight instances of $needle in $haystack
1826 * It's faster that the above function {@link highlight()} and doesn't care about
1827 * HTML or anything.
1829 * @param string $needle The string to search for
1830 * @param string $haystack The string to search for $needle in
1831 * @return string The highlighted HTML
1833 function highlightfast($needle, $haystack) {
1835 if (empty($needle) or empty($haystack)) {
1836 return $haystack;
1839 $parts = explode(textlib::strtolower($needle), textlib::strtolower($haystack));
1841 if (count($parts) === 1) {
1842 return $haystack;
1845 $pos = 0;
1847 foreach ($parts as $key => $part) {
1848 $parts[$key] = substr($haystack, $pos, strlen($part));
1849 $pos += strlen($part);
1851 $parts[$key] .= '<span class="highlight">'.substr($haystack, $pos, strlen($needle)).'</span>';
1852 $pos += strlen($needle);
1855 return str_replace('<span class="highlight"></span>', '', join('', $parts));
1859 * Return a string containing 'lang', xml:lang and optionally 'dir' HTML attributes.
1860 * Internationalisation, for print_header and backup/restorelib.
1862 * @param bool $dir Default false
1863 * @return string Attributes
1865 function get_html_lang($dir = false) {
1866 $direction = '';
1867 if ($dir) {
1868 if (right_to_left()) {
1869 $direction = ' dir="rtl"';
1870 } else {
1871 $direction = ' dir="ltr"';
1874 //Accessibility: added the 'lang' attribute to $direction, used in theme <html> tag.
1875 $language = str_replace('_', '-', current_language());
1876 @header('Content-Language: '.$language);
1877 return ($direction.' lang="'.$language.'" xml:lang="'.$language.'"');
1881 /// STANDARD WEB PAGE PARTS ///////////////////////////////////////////////////
1884 * Send the HTTP headers that Moodle requires.
1886 * There is a backwards compatibility hack for legacy code
1887 * that needs to add custom IE compatibility directive.
1889 * Example:
1890 * <code>
1891 * if (!isset($CFG->additionalhtmlhead)) {
1892 * $CFG->additionalhtmlhead = '';
1894 * $CFG->additionalhtmlhead .= '<meta http-equiv="X-UA-Compatible" content="IE=8" />';
1895 * header('X-UA-Compatible: IE=8');
1896 * echo $OUTPUT->header();
1897 * </code>
1899 * Please note the $CFG->additionalhtmlhead alone might not work,
1900 * you should send the IE compatibility header() too.
1902 * @param string $contenttype
1903 * @param bool $cacheable Can this page be cached on back?
1904 * @return void, sends HTTP headers
1906 function send_headers($contenttype, $cacheable = true) {
1907 global $CFG;
1909 @header('Content-Type: ' . $contenttype);
1910 @header('Content-Script-Type: text/javascript');
1911 @header('Content-Style-Type: text/css');
1913 if (empty($CFG->additionalhtmlhead) or stripos($CFG->additionalhtmlhead, 'X-UA-Compatible') === false) {
1914 @header('X-UA-Compatible: IE=edge');
1917 if ($cacheable) {
1918 // Allow caching on "back" (but not on normal clicks)
1919 @header('Cache-Control: private, pre-check=0, post-check=0, max-age=0');
1920 @header('Pragma: no-cache');
1921 @header('Expires: ');
1922 } else {
1923 // Do everything we can to always prevent clients and proxies caching
1924 @header('Cache-Control: no-store, no-cache, must-revalidate');
1925 @header('Cache-Control: post-check=0, pre-check=0', false);
1926 @header('Pragma: no-cache');
1927 @header('Expires: Mon, 20 Aug 1969 09:23:00 GMT');
1928 @header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
1930 @header('Accept-Ranges: none');
1932 if (empty($CFG->allowframembedding)) {
1933 @header('X-Frame-Options: sameorigin');
1938 * Return the right arrow with text ('next'), and optionally embedded in a link.
1940 * @global object
1941 * @param string $text HTML/plain text label (set to blank only for breadcrumb separator cases).
1942 * @param string $url An optional link to use in a surrounding HTML anchor.
1943 * @param bool $accesshide True if text should be hidden (for screen readers only).
1944 * @param string $addclass Additional class names for the link, or the arrow character.
1945 * @return string HTML string.
1947 function link_arrow_right($text, $url='', $accesshide=false, $addclass='') {
1948 global $OUTPUT; //TODO: move to output renderer
1949 $arrowclass = 'arrow ';
1950 if (! $url) {
1951 $arrowclass .= $addclass;
1953 $arrow = '<span class="'.$arrowclass.'">'.$OUTPUT->rarrow().'</span>';
1954 $htmltext = '';
1955 if ($text) {
1956 $htmltext = '<span class="arrow_text">'.$text.'</span>&nbsp;';
1957 if ($accesshide) {
1958 $htmltext = get_accesshide($htmltext);
1961 if ($url) {
1962 $class = 'arrow_link';
1963 if ($addclass) {
1964 $class .= ' '.$addclass;
1966 return '<a class="'.$class.'" href="'.$url.'" title="'.preg_replace('/<.*?>/','',$text).'">'.$htmltext.$arrow.'</a>';
1968 return $htmltext.$arrow;
1972 * Return the left arrow with text ('previous'), and optionally embedded in a link.
1974 * @global object
1975 * @param string $text HTML/plain text label (set to blank only for breadcrumb separator cases).
1976 * @param string $url An optional link to use in a surrounding HTML anchor.
1977 * @param bool $accesshide True if text should be hidden (for screen readers only).
1978 * @param string $addclass Additional class names for the link, or the arrow character.
1979 * @return string HTML string.
1981 function link_arrow_left($text, $url='', $accesshide=false, $addclass='') {
1982 global $OUTPUT; // TODO: move to utput renderer
1983 $arrowclass = 'arrow ';
1984 if (! $url) {
1985 $arrowclass .= $addclass;
1987 $arrow = '<span class="'.$arrowclass.'">'.$OUTPUT->larrow().'</span>';
1988 $htmltext = '';
1989 if ($text) {
1990 $htmltext = '&nbsp;<span class="arrow_text">'.$text.'</span>';
1991 if ($accesshide) {
1992 $htmltext = get_accesshide($htmltext);
1995 if ($url) {
1996 $class = 'arrow_link';
1997 if ($addclass) {
1998 $class .= ' '.$addclass;
2000 return '<a class="'.$class.'" href="'.$url.'" title="'.preg_replace('/<.*?>/','',$text).'">'.$arrow.$htmltext.'</a>';
2002 return $arrow.$htmltext;
2006 * Return a HTML element with the class "accesshide", for accessibility.
2007 * Please use cautiously - where possible, text should be visible!
2009 * @param string $text Plain text.
2010 * @param string $elem Lowercase element name, default "span".
2011 * @param string $class Additional classes for the element.
2012 * @param string $attrs Additional attributes string in the form, "name='value' name2='value2'"
2013 * @return string HTML string.
2015 function get_accesshide($text, $elem='span', $class='', $attrs='') {
2016 return "<$elem class=\"accesshide $class\" $attrs>$text</$elem>";
2020 * Return the breadcrumb trail navigation separator.
2022 * @return string HTML string.
2024 function get_separator() {
2025 //Accessibility: the 'hidden' slash is preferred for screen readers.
2026 return ' '.link_arrow_right($text='/', $url='', $accesshide=true, 'sep').' ';
2030 * Print (or return) a collapsible region, that has a caption that can
2031 * be clicked to expand or collapse the region.
2033 * If JavaScript is off, then the region will always be expanded.
2035 * @param string $contents the contents of the box.
2036 * @param string $classes class names added to the div that is output.
2037 * @param string $id id added to the div that is output. Must not be blank.
2038 * @param string $caption text displayed at the top. Clicking on this will cause the region to expand or contract.
2039 * @param string $userpref the name of the user preference that stores the user's preferred default state.
2040 * (May be blank if you do not wish the state to be persisted.
2041 * @param boolean $default Initial collapsed state to use if the user_preference it not set.
2042 * @param boolean $return if true, return the HTML as a string, rather than printing it.
2043 * @return string|void If $return is false, returns nothing, otherwise returns a string of HTML.
2045 function print_collapsible_region($contents, $classes, $id, $caption, $userpref = '', $default = false, $return = false) {
2046 $output = print_collapsible_region_start($classes, $id, $caption, $userpref, $default, true);
2047 $output .= $contents;
2048 $output .= print_collapsible_region_end(true);
2050 if ($return) {
2051 return $output;
2052 } else {
2053 echo $output;
2058 * Print (or return) the start of a collapsible region, that has a caption that can
2059 * be clicked to expand or collapse the region. If JavaScript is off, then the region
2060 * will always be expanded.
2062 * @param string $classes class names added to the div that is output.
2063 * @param string $id id added to the div that is output. Must not be blank.
2064 * @param string $caption text displayed at the top. Clicking on this will cause the region to expand or contract.
2065 * @param string $userpref the name of the user preference that stores the user's preferred default state.
2066 * (May be blank if you do not wish the state to be persisted.
2067 * @param boolean $default Initial collapsed state to use if the user_preference it not set.
2068 * @param boolean $return if true, return the HTML as a string, rather than printing it.
2069 * @return string|void if $return is false, returns nothing, otherwise returns a string of HTML.
2071 function print_collapsible_region_start($classes, $id, $caption, $userpref = '', $default = false, $return = false) {
2072 global $CFG, $PAGE, $OUTPUT;
2074 // Work out the initial state.
2075 if (!empty($userpref) and is_string($userpref)) {
2076 user_preference_allow_ajax_update($userpref, PARAM_BOOL);
2077 $collapsed = get_user_preferences($userpref, $default);
2078 } else {
2079 $collapsed = $default;
2080 $userpref = false;
2083 if ($collapsed) {
2084 $classes .= ' collapsed';
2087 $output = '';
2088 $output .= '<div id="' . $id . '" class="collapsibleregion ' . $classes . '">';
2089 $output .= '<div id="' . $id . '_sizer">';
2090 $output .= '<div id="' . $id . '_caption" class="collapsibleregioncaption">';
2091 $output .= $caption . ' ';
2092 $output .= '</div><div id="' . $id . '_inner" class="collapsibleregioninner">';
2093 $PAGE->requires->js_init_call('M.util.init_collapsible_region', array($id, $userpref, get_string('clicktohideshow')));
2095 if ($return) {
2096 return $output;
2097 } else {
2098 echo $output;
2103 * Close a region started with print_collapsible_region_start.
2105 * @param boolean $return if true, return the HTML as a string, rather than printing it.
2106 * @return string|void if $return is false, returns nothing, otherwise returns a string of HTML.
2108 function print_collapsible_region_end($return = false) {
2109 $output = '</div></div></div>';
2111 if ($return) {
2112 return $output;
2113 } else {
2114 echo $output;
2119 * Print a specified group's avatar.
2121 * @global object
2122 * @uses CONTEXT_COURSE
2123 * @param array|stdClass $group A single {@link group} object OR array of groups.
2124 * @param int $courseid The course ID.
2125 * @param boolean $large Default small picture, or large.
2126 * @param boolean $return If false print picture, otherwise return the output as string
2127 * @param boolean $link Enclose image in a link to view specified course?
2128 * @return string|void Depending on the setting of $return
2130 function print_group_picture($group, $courseid, $large=false, $return=false, $link=true) {
2131 global $CFG;
2133 if (is_array($group)) {
2134 $output = '';
2135 foreach($group as $g) {
2136 $output .= print_group_picture($g, $courseid, $large, true, $link);
2138 if ($return) {
2139 return $output;
2140 } else {
2141 echo $output;
2142 return;
2146 $context = context_course::instance($courseid);
2148 // If there is no picture, do nothing
2149 if (!$group->picture) {
2150 return '';
2153 // If picture is hidden, only show to those with course:managegroups
2154 if ($group->hidepicture and !has_capability('moodle/course:managegroups', $context)) {
2155 return '';
2158 if ($link or has_capability('moodle/site:accessallgroups', $context)) {
2159 $output = '<a href="'. $CFG->wwwroot .'/user/index.php?id='. $courseid .'&amp;group='. $group->id .'">';
2160 } else {
2161 $output = '';
2163 if ($large) {
2164 $file = 'f1';
2165 } else {
2166 $file = 'f2';
2169 $grouppictureurl = moodle_url::make_pluginfile_url($context->id, 'group', 'icon', $group->id, '/', $file);
2170 $output .= '<img class="grouppicture" src="'.$grouppictureurl.'"'.
2171 ' alt="'.s(get_string('group').' '.$group->name).'" title="'.s($group->name).'"/>';
2173 if ($link or has_capability('moodle/site:accessallgroups', $context)) {
2174 $output .= '</a>';
2177 if ($return) {
2178 return $output;
2179 } else {
2180 echo $output;
2186 * Display a recent activity note
2188 * @uses CONTEXT_SYSTEM
2189 * @staticvar string $strftimerecent
2190 * @param object A time object
2191 * @param object A user object
2192 * @param string $text Text for display for the note
2193 * @param string $link The link to wrap around the text
2194 * @param bool $return If set to true the HTML is returned rather than echo'd
2195 * @param string $viewfullnames
2197 function print_recent_activity_note($time, $user, $text, $link, $return=false, $viewfullnames=null) {
2198 static $strftimerecent = null;
2199 $output = '';
2201 if (is_null($viewfullnames)) {
2202 $context = context_system::instance();
2203 $viewfullnames = has_capability('moodle/site:viewfullnames', $context);
2206 if (is_null($strftimerecent)) {
2207 $strftimerecent = get_string('strftimerecent');
2210 $output .= '<div class="head">';
2211 $output .= '<div class="date">'.userdate($time, $strftimerecent).'</div>';
2212 $output .= '<div class="name">'.fullname($user, $viewfullnames).'</div>';
2213 $output .= '</div>';
2214 $output .= '<div class="info"><a href="'.$link.'">'.format_string($text,true).'</a></div>';
2216 if ($return) {
2217 return $output;
2218 } else {
2219 echo $output;
2224 * Returns a popup menu with course activity modules
2226 * Given a course
2227 * This function returns a small popup menu with all the
2228 * course activity modules in it, as a navigation menu
2229 * outputs a simple list structure in XHTML
2230 * The data is taken from the serialised array stored in
2231 * the course record
2233 * @todo Finish documenting this function
2235 * @global object
2236 * @uses CONTEXT_COURSE
2237 * @param course $course A {@link $COURSE} object.
2238 * @param string $sections
2239 * @param string $modinfo
2240 * @param string $strsection
2241 * @param string $strjumpto
2242 * @param int $width
2243 * @param string $cmid
2244 * @return string The HTML block
2246 function navmenulist($course, $sections, $modinfo, $strsection, $strjumpto, $width=50, $cmid=0) {
2248 global $CFG, $OUTPUT;
2250 $section = -1;
2251 $url = '';
2252 $menu = array();
2253 $doneheading = false;
2255 $courseformatoptions = course_get_format($course)->get_format_options();
2256 $coursecontext = context_course::instance($course->id);
2258 $menu[] = '<ul class="navmenulist"><li class="jumpto section"><span>'.$strjumpto.'</span><ul>';
2259 foreach ($modinfo->cms as $mod) {
2260 if (!$mod->has_view()) {
2261 // Don't show modules which you can't link to!
2262 continue;
2265 // For course formats using 'numsections' do not show extra sections
2266 if (isset($courseformatoptions['numsections']) && $mod->sectionnum > $courseformatoptions['numsections']) {
2267 break;
2270 if (!$mod->uservisible) { // do not icnlude empty sections at all
2271 continue;
2274 if ($mod->sectionnum >= 0 and $section != $mod->sectionnum) {
2275 $thissection = $sections[$mod->sectionnum];
2277 if ($thissection->visible or
2278 (isset($courseformatoptions['hiddensections']) and !$courseformatoptions['hiddensections']) or
2279 has_capability('moodle/course:viewhiddensections', $coursecontext)) {
2280 $thissection->summary = strip_tags(format_string($thissection->summary,true));
2281 if (!$doneheading) {
2282 $menu[] = '</ul></li>';
2284 if ($course->format == 'weeks' or empty($thissection->summary)) {
2285 $item = $strsection ." ". $mod->sectionnum;
2286 } else {
2287 if (textlib::strlen($thissection->summary) < ($width-3)) {
2288 $item = $thissection->summary;
2289 } else {
2290 $item = textlib::substr($thissection->summary, 0, $width).'...';
2293 $menu[] = '<li class="section"><span>'.$item.'</span>';
2294 $menu[] = '<ul>';
2295 $doneheading = true;
2297 $section = $mod->sectionnum;
2298 } else {
2299 // no activities from this hidden section shown
2300 continue;
2304 $url = $mod->modname .'/view.php?id='. $mod->id;
2305 $mod->name = strip_tags(format_string($mod->name ,true));
2306 if (textlib::strlen($mod->name) > ($width+5)) {
2307 $mod->name = textlib::substr($mod->name, 0, $width).'...';
2309 if (!$mod->visible) {
2310 $mod->name = '('.$mod->name.')';
2312 $class = 'activity '.$mod->modname;
2313 $class .= ($cmid == $mod->id) ? ' selected' : '';
2314 $menu[] = '<li class="'.$class.'">'.
2315 '<img src="'.$OUTPUT->pix_url('icon', $mod->modname) . '" alt="" />'.
2316 '<a href="'.$CFG->wwwroot.'/mod/'.$url.'">'.$mod->name.'</a></li>';
2319 if ($doneheading) {
2320 $menu[] = '</ul></li>';
2322 $menu[] = '</ul></li></ul>';
2324 return implode("\n", $menu);
2328 * Prints a grade menu (as part of an existing form) with help
2329 * Showing all possible numerical grades and scales
2331 * @todo Finish documenting this function
2332 * @todo Deprecate: this is only used in a few contrib modules
2334 * @global object
2335 * @param int $courseid The course ID
2336 * @param string $name
2337 * @param string $current
2338 * @param boolean $includenograde Include those with no grades
2339 * @param boolean $return If set to true returns rather than echo's
2340 * @return string|bool Depending on value of $return
2342 function print_grade_menu($courseid, $name, $current, $includenograde=true, $return=false) {
2344 global $CFG, $OUTPUT;
2346 $output = '';
2347 $strscale = get_string('scale');
2348 $strscales = get_string('scales');
2350 $scales = get_scales_menu($courseid);
2351 foreach ($scales as $i => $scalename) {
2352 $grades[-$i] = $strscale .': '. $scalename;
2354 if ($includenograde) {
2355 $grades[0] = get_string('nograde');
2357 for ($i=100; $i>=1; $i--) {
2358 $grades[$i] = $i;
2360 $output .= html_writer::select($grades, $name, $current, false);
2362 $linkobject = '<span class="helplink"><img class="iconhelp" alt="'.$strscales.'" src="'.$OUTPUT->pix_url('help') . '" /></span>';
2363 $link = new moodle_url('/course/scales.php', array('id'=>$courseid, 'list'=>1));
2364 $action = new popup_action('click', $link, 'ratingscales', array('height' => 400, 'width' => 500));
2365 $output .= $OUTPUT->action_link($link, $linkobject, $action, array('title'=>$strscales));
2367 if ($return) {
2368 return $output;
2369 } else {
2370 echo $output;
2375 * Print an error to STDOUT and exit with a non-zero code. For commandline scripts.
2376 * Default errorcode is 1.
2378 * Very useful for perl-like error-handling:
2380 * do_somethting() or mdie("Something went wrong");
2382 * @param string $msg Error message
2383 * @param integer $errorcode Error code to emit
2385 function mdie($msg='', $errorcode=1) {
2386 trigger_error($msg);
2387 exit($errorcode);
2391 * Print a message and exit.
2393 * @param string $message The message to print in the notice
2394 * @param string $link The link to use for the continue button
2395 * @param object $course A course object
2396 * @return void This function simply exits
2398 function notice ($message, $link='', $course=NULL) {
2399 global $CFG, $SITE, $COURSE, $PAGE, $OUTPUT;
2401 $message = clean_text($message); // In case nasties are in here
2403 if (CLI_SCRIPT) {
2404 echo("!!$message!!\n");
2405 exit(1); // no success
2408 if (!$PAGE->headerprinted) {
2409 //header not yet printed
2410 $PAGE->set_title(get_string('notice'));
2411 echo $OUTPUT->header();
2412 } else {
2413 echo $OUTPUT->container_end_all(false);
2416 echo $OUTPUT->box($message, 'generalbox', 'notice');
2417 echo $OUTPUT->continue_button($link);
2419 echo $OUTPUT->footer();
2420 exit(1); // general error code
2424 * Redirects the user to another page, after printing a notice
2426 * This function calls the OUTPUT redirect method, echo's the output
2427 * and then dies to ensure nothing else happens.
2429 * <strong>Good practice:</strong> You should call this method before starting page
2430 * output by using any of the OUTPUT methods.
2432 * @param moodle_url|string $url A moodle_url to redirect to. Strings are not to be trusted!
2433 * @param string $message The message to display to the user
2434 * @param int $delay The delay before redirecting
2435 * @return void - does not return!
2437 function redirect($url, $message='', $delay=-1) {
2438 global $OUTPUT, $PAGE, $SESSION, $CFG;
2440 if (CLI_SCRIPT or AJAX_SCRIPT) {
2441 // this is wrong - developers should not use redirect in these scripts,
2442 // but it should not be very likely
2443 throw new moodle_exception('redirecterrordetected', 'error');
2446 // prevent debug errors - make sure context is properly initialised
2447 if ($PAGE) {
2448 $PAGE->set_context(null);
2449 $PAGE->set_pagelayout('redirect'); // No header and footer needed
2452 if ($url instanceof moodle_url) {
2453 $url = $url->out(false);
2456 $debugdisableredirect = false;
2457 do {
2458 if (defined('DEBUGGING_PRINTED')) {
2459 // some debugging already printed, no need to look more
2460 $debugdisableredirect = true;
2461 break;
2464 if (empty($CFG->debugdisplay) or empty($CFG->debug)) {
2465 // no errors should be displayed
2466 break;
2469 if (!function_exists('error_get_last') or !$lasterror = error_get_last()) {
2470 break;
2473 if (!($lasterror['type'] & $CFG->debug)) {
2474 //last error not interesting
2475 break;
2478 // watch out here, @hidden() errors are returned from error_get_last() too
2479 if (headers_sent()) {
2480 //we already started printing something - that means errors likely printed
2481 $debugdisableredirect = true;
2482 break;
2485 if (ob_get_level() and ob_get_contents()) {
2486 // there is something waiting to be printed, hopefully it is the errors,
2487 // but it might be some error hidden by @ too - such as the timezone mess from setup.php
2488 $debugdisableredirect = true;
2489 break;
2491 } while (false);
2493 // Technically, HTTP/1.1 requires Location: header to contain the absolute path.
2494 // (In practice browsers accept relative paths - but still, might as well do it properly.)
2495 // This code turns relative into absolute.
2496 if (!preg_match('|^[a-z]+:|', $url)) {
2497 // Get host name http://www.wherever.com
2498 $hostpart = preg_replace('|^(.*?[^:/])/.*$|', '$1', $CFG->wwwroot);
2499 if (preg_match('|^/|', $url)) {
2500 // URLs beginning with / are relative to web server root so we just add them in
2501 $url = $hostpart.$url;
2502 } else {
2503 // URLs not beginning with / are relative to path of current script, so add that on.
2504 $url = $hostpart.preg_replace('|\?.*$|','',me()).'/../'.$url;
2506 // Replace all ..s
2507 while (true) {
2508 $newurl = preg_replace('|/(?!\.\.)[^/]*/\.\./|', '/', $url);
2509 if ($newurl == $url) {
2510 break;
2512 $url = $newurl;
2516 // Sanitise url - we can not rely on moodle_url or our URL cleaning
2517 // because they do not support all valid external URLs
2518 $url = preg_replace('/[\x00-\x1F\x7F]/', '', $url);
2519 $url = str_replace('"', '%22', $url);
2520 $encodedurl = preg_replace("/\&(?![a-zA-Z0-9#]{1,8};)/", "&amp;", $url);
2521 $encodedurl = preg_replace('/^.*href="([^"]*)".*$/', "\\1", clean_text('<a href="'.$encodedurl.'" />', FORMAT_HTML));
2522 $url = str_replace('&amp;', '&', $encodedurl);
2524 if (!empty($message)) {
2525 if ($delay === -1 || !is_numeric($delay)) {
2526 $delay = 3;
2528 $message = clean_text($message);
2529 } else {
2530 $message = get_string('pageshouldredirect');
2531 $delay = 0;
2534 if (defined('MDL_PERF') || (!empty($CFG->perfdebug) and $CFG->perfdebug > 7)) {
2535 if (defined('MDL_PERFTOLOG') && !function_exists('register_shutdown_function')) {
2536 $perf = get_performance_info();
2537 error_log("PERF: " . $perf['txt']);
2541 if ($delay == 0 && !$debugdisableredirect && !headers_sent()) {
2542 // workaround for IIS bug http://support.microsoft.com/kb/q176113/
2543 if (session_id()) {
2544 session_get_instance()->write_close();
2547 //302 might not work for POST requests, 303 is ignored by obsolete clients.
2548 @header($_SERVER['SERVER_PROTOCOL'] . ' 303 See Other');
2549 @header('Location: '.$url);
2550 echo bootstrap_renderer::plain_redirect_message($encodedurl);
2551 exit;
2554 // Include a redirect message, even with a HTTP redirect, because that is recommended practice.
2555 if ($PAGE) {
2556 $CFG->docroot = false; // to prevent the link to moodle docs from being displayed on redirect page.
2557 echo $OUTPUT->redirect_message($encodedurl, $message, $delay, $debugdisableredirect);
2558 exit;
2559 } else {
2560 echo bootstrap_renderer::early_redirect_message($encodedurl, $message, $delay);
2561 exit;
2566 * Given an email address, this function will return an obfuscated version of it
2568 * @param string $email The email address to obfuscate
2569 * @return string The obfuscated email address
2571 function obfuscate_email($email) {
2573 $i = 0;
2574 $length = strlen($email);
2575 $obfuscated = '';
2576 while ($i < $length) {
2577 if (rand(0,2) && $email{$i}!='@') { //MDL-20619 some browsers have problems unobfuscating @
2578 $obfuscated.='%'.dechex(ord($email{$i}));
2579 } else {
2580 $obfuscated.=$email{$i};
2582 $i++;
2584 return $obfuscated;
2588 * This function takes some text and replaces about half of the characters
2589 * with HTML entity equivalents. Return string is obviously longer.
2591 * @param string $plaintext The text to be obfuscated
2592 * @return string The obfuscated text
2594 function obfuscate_text($plaintext) {
2596 $i=0;
2597 $length = textlib::strlen($plaintext);
2598 $obfuscated='';
2599 $prev_obfuscated = false;
2600 while ($i < $length) {
2601 $char = textlib::substr($plaintext, $i, 1);
2602 $ord = textlib::utf8ord($char);
2603 $numerical = ($ord >= ord('0')) && ($ord <= ord('9'));
2604 if ($prev_obfuscated and $numerical ) {
2605 $obfuscated.='&#'.$ord.';';
2606 } else if (rand(0,2)) {
2607 $obfuscated.='&#'.$ord.';';
2608 $prev_obfuscated = true;
2609 } else {
2610 $obfuscated.=$char;
2611 $prev_obfuscated = false;
2613 $i++;
2615 return $obfuscated;
2619 * This function uses the {@link obfuscate_email()} and {@link obfuscate_text()}
2620 * to generate a fully obfuscated email link, ready to use.
2622 * @param string $email The email address to display
2623 * @param string $label The text to displayed as hyperlink to $email
2624 * @param boolean $dimmed If true then use css class 'dimmed' for hyperlink
2625 * @param string $subject The subject of the email in the mailto link
2626 * @param string $body The content of the email in the mailto link
2627 * @return string The obfuscated mailto link
2629 function obfuscate_mailto($email, $label='', $dimmed=false, $subject = '', $body = '') {
2631 if (empty($label)) {
2632 $label = $email;
2635 $label = obfuscate_text($label);
2636 $email = obfuscate_email($email);
2637 $mailto = obfuscate_text('mailto');
2638 $url = new moodle_url("mailto:$email");
2639 $attrs = array();
2641 if (!empty($subject)) {
2642 $url->param('subject', format_string($subject));
2644 if (!empty($body)) {
2645 $url->param('body', format_string($body));
2648 // Use the obfuscated mailto
2649 $url = preg_replace('/^mailto/', $mailto, $url->out());
2651 if ($dimmed) {
2652 $attrs['title'] = get_string('emaildisable');
2653 $attrs['class'] = 'dimmed';
2656 return html_writer::link($url, $label, $attrs);
2660 * This function is used to rebuild the <nolink> tag because some formats (PLAIN and WIKI)
2661 * will transform it to html entities
2663 * @param string $text Text to search for nolink tag in
2664 * @return string
2666 function rebuildnolinktag($text) {
2668 $text = preg_replace('/&lt;(\/*nolink)&gt;/i','<$1>',$text);
2670 return $text;
2674 * Prints a maintenance message from $CFG->maintenance_message or default if empty
2675 * @return void
2677 function print_maintenance_message() {
2678 global $CFG, $SITE, $PAGE, $OUTPUT;
2680 $PAGE->set_pagetype('maintenance-message');
2681 $PAGE->set_pagelayout('maintenance');
2682 $PAGE->set_title(strip_tags($SITE->fullname));
2683 $PAGE->set_heading($SITE->fullname);
2684 echo $OUTPUT->header();
2685 echo $OUTPUT->heading(get_string('sitemaintenance', 'admin'));
2686 if (isset($CFG->maintenance_message) and !html_is_blank($CFG->maintenance_message)) {
2687 echo $OUTPUT->box_start('maintenance_message generalbox boxwidthwide boxaligncenter');
2688 echo $CFG->maintenance_message;
2689 echo $OUTPUT->box_end();
2691 echo $OUTPUT->footer();
2692 die;
2696 * Returns a string containing a nested list, suitable for formatting into tabs with CSS.
2698 * It is not recommended to use this function in Moodle 2.5 but it is left for backward
2699 * compartibility.
2701 * Example how to print a single line tabs:
2702 * $rows = array(
2703 * new tabobject(...),
2704 * new tabobject(...)
2705 * );
2706 * echo $OUTPUT->tabtree($rows, $selectedid);
2708 * Multiple row tabs may not look good on some devices but if you want to use them
2709 * you can specify ->subtree for the active tabobject.
2711 * @param array $tabrows An array of rows where each row is an array of tab objects
2712 * @param string $selected The id of the selected tab (whatever row it's on)
2713 * @param array $inactive An array of ids of inactive tabs that are not selectable.
2714 * @param array $activated An array of ids of other tabs that are currently activated
2715 * @param bool $return If true output is returned rather then echo'd
2717 function print_tabs($tabrows, $selected = null, $inactive = null, $activated = null, $return = false) {
2718 global $OUTPUT;
2720 $tabrows = array_reverse($tabrows);
2721 $subtree = array();
2722 foreach ($tabrows as $row) {
2723 $tree = array();
2725 foreach ($row as $tab) {
2726 $tab->inactive = is_array($inactive) && in_array((string)$tab->id, $inactive);
2727 $tab->activated = is_array($activated) && in_array((string)$tab->id, $activated);
2728 $tab->selected = (string)$tab->id == $selected;
2730 if ($tab->activated || $tab->selected) {
2731 $tab->subtree = $subtree;
2733 $tree[] = $tab;
2735 $subtree = $tree;
2737 $output = $OUTPUT->tabtree($subtree);
2738 if ($return) {
2739 return $output;
2740 } else {
2741 print $output;
2742 return !empty($output);
2747 * Standard Debugging Function
2749 * Returns true if the current site debugging settings are equal or above specified level.
2750 * If passed a parameter it will emit a debugging notice similar to trigger_error(). The
2751 * routing of notices is controlled by $CFG->debugdisplay
2752 * eg use like this:
2754 * 1) debugging('a normal debug notice');
2755 * 2) debugging('something really picky', DEBUG_ALL);
2756 * 3) debugging('annoying debug message only for developers', DEBUG_DEVELOPER);
2757 * 4) if (debugging()) { perform extra debugging operations (do not use print or echo) }
2759 * In code blocks controlled by debugging() (such as example 4)
2760 * any output should be routed via debugging() itself, or the lower-level
2761 * trigger_error() or error_log(). Using echo or print will break XHTML
2762 * JS and HTTP headers.
2764 * It is also possible to define NO_DEBUG_DISPLAY which redirects the message to error_log.
2766 * @uses DEBUG_NORMAL
2767 * @param string $message a message to print
2768 * @param int $level the level at which this debugging statement should show
2769 * @param array $backtrace use different backtrace
2770 * @return bool
2772 function debugging($message = '', $level = DEBUG_NORMAL, $backtrace = null) {
2773 global $CFG, $USER;
2775 $forcedebug = false;
2776 if (!empty($CFG->debugusers) && $USER) {
2777 $debugusers = explode(',', $CFG->debugusers);
2778 $forcedebug = in_array($USER->id, $debugusers);
2781 if (!$forcedebug and (empty($CFG->debug) || ($CFG->debug != -1 and $CFG->debug < $level))) {
2782 return false;
2785 if (!isset($CFG->debugdisplay)) {
2786 $CFG->debugdisplay = ini_get_bool('display_errors');
2789 if ($message) {
2790 if (!$backtrace) {
2791 $backtrace = debug_backtrace();
2793 $from = format_backtrace($backtrace, CLI_SCRIPT);
2794 if (PHPUNIT_TEST) {
2795 if (phpunit_util::debugging_triggered($message, $level, $from)) {
2796 // We are inside test, the debug message was logged.
2797 return true;
2801 if (NO_DEBUG_DISPLAY) {
2802 // script does not want any errors or debugging in output,
2803 // we send the info to error log instead
2804 error_log('Debugging: ' . $message . $from);
2806 } else if ($forcedebug or $CFG->debugdisplay) {
2807 if (!defined('DEBUGGING_PRINTED')) {
2808 define('DEBUGGING_PRINTED', 1); // indicates we have printed something
2810 if (CLI_SCRIPT) {
2811 echo "++ $message ++\n$from";
2812 } else {
2813 echo '<div class="notifytiny debuggingmessage">' . $message . $from . '</div>';
2816 } else {
2817 trigger_error($message . $from, E_USER_NOTICE);
2820 return true;
2824 * Outputs a HTML comment to the browser. This is used for those hard-to-debug
2825 * pages that use bits from many different files in very confusing ways (e.g. blocks).
2827 * <code>print_location_comment(__FILE__, __LINE__);</code>
2829 * @param string $file
2830 * @param integer $line
2831 * @param boolean $return Whether to return or print the comment
2832 * @return string|void Void unless true given as third parameter
2834 function print_location_comment($file, $line, $return = false)
2836 if ($return) {
2837 return "<!-- $file at line $line -->\n";
2838 } else {
2839 echo "<!-- $file at line $line -->\n";
2845 * @return boolean true if the current language is right-to-left (Hebrew, Arabic etc)
2847 function right_to_left() {
2848 return (get_string('thisdirection', 'langconfig') === 'rtl');
2853 * Returns swapped left<=>right if in RTL environment.
2854 * part of RTL support
2856 * @param string $align align to check
2857 * @return string
2859 function fix_align_rtl($align) {
2860 if (!right_to_left()) {
2861 return $align;
2863 if ($align=='left') { return 'right'; }
2864 if ($align=='right') { return 'left'; }
2865 return $align;
2870 * Returns true if the page is displayed in a popup window.
2871 * Gets the information from the URL parameter inpopup.
2873 * @todo Use a central function to create the popup calls all over Moodle and
2874 * In the moment only works with resources and probably questions.
2876 * @return boolean
2878 function is_in_popup() {
2879 $inpopup = optional_param('inpopup', '', PARAM_BOOL);
2881 return ($inpopup);
2885 * To use this class.
2886 * - construct
2887 * - call create (or use the 3rd param to the constructor)
2888 * - call update or update_full() or update() repeatedly
2890 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2891 * @package moodlecore
2893 class progress_bar {
2894 /** @var string html id */
2895 private $html_id;
2896 /** @var int total width */
2897 private $width;
2898 /** @var int last percentage printed */
2899 private $percent = 0;
2900 /** @var int time when last printed */
2901 private $lastupdate = 0;
2902 /** @var int when did we start printing this */
2903 private $time_start = 0;
2906 * Constructor
2908 * @param string $html_id
2909 * @param int $width
2910 * @param bool $autostart Default to false
2911 * @return void, prints JS code if $autostart true
2913 public function __construct($html_id = '', $width = 500, $autostart = false) {
2914 if (!empty($html_id)) {
2915 $this->html_id = $html_id;
2916 } else {
2917 $this->html_id = 'pbar_'.uniqid();
2920 $this->width = $width;
2922 if ($autostart){
2923 $this->create();
2928 * Create a new progress bar, this function will output html.
2930 * @return void Echo's output
2932 public function create() {
2933 $this->time_start = microtime(true);
2934 if (CLI_SCRIPT) {
2935 return; // temporary solution for cli scripts
2937 $htmlcode = <<<EOT
2938 <div style="text-align:center;width:{$this->width}px;clear:both;padding:0;margin:0 auto;">
2939 <h2 id="status_{$this->html_id}" style="text-align: center;margin:0 auto"></h2>
2940 <p id="time_{$this->html_id}"></p>
2941 <div id="bar_{$this->html_id}" style="border-style:solid;border-width:1px;width:500px;height:50px;">
2942 <div id="progress_{$this->html_id}"
2943 style="text-align:center;background:#FFCC66;width:4px;border:1px
2944 solid gray;height:38px; padding-top:10px;">&nbsp;<span id="pt_{$this->html_id}"></span>
2945 </div>
2946 </div>
2947 </div>
2948 EOT;
2949 flush();
2950 echo $htmlcode;
2951 flush();
2955 * Update the progress bar
2957 * @param int $percent from 1-100
2958 * @param string $msg
2959 * @return void Echo's output
2961 private function _update($percent, $msg) {
2962 if (empty($this->time_start)) {
2963 throw new coding_exception('You must call create() (or use the $autostart ' .
2964 'argument to the constructor) before you try updating the progress bar.');
2967 if (CLI_SCRIPT) {
2968 return; // temporary solution for cli scripts
2971 $es = $this->estimate($percent);
2973 if ($es === null) {
2974 // always do the first and last updates
2975 $es = "?";
2976 } else if ($es == 0) {
2977 // always do the last updates
2978 } else if ($this->lastupdate + 20 < time()) {
2979 // we must update otherwise browser would time out
2980 } else if (round($this->percent, 2) === round($percent, 2)) {
2981 // no significant change, no need to update anything
2982 return;
2985 $this->percent = $percent;
2986 $this->lastupdate = microtime(true);
2988 $w = ($this->percent/100) * $this->width;
2989 echo html_writer::script(js_writer::function_call('update_progress_bar', array($this->html_id, $w, $this->percent, $msg, $es)));
2990 flush();
2994 * Estimate how much time it is going to take.
2996 * @param int $curtime the time call this function
2997 * @param int $percent from 1-100
2998 * @return mixed Null (unknown), or int
3000 private function estimate($pt) {
3001 if ($this->lastupdate == 0) {
3002 return null;
3004 if ($pt < 0.00001) {
3005 return null; // we do not know yet how long it will take
3007 if ($pt > 99.99999) {
3008 return 0; // nearly done, right?
3010 $consumed = microtime(true) - $this->time_start;
3011 if ($consumed < 0.001) {
3012 return null;
3015 return (100 - $pt) * ($consumed / $pt);
3019 * Update progress bar according percent
3021 * @param int $percent from 1-100
3022 * @param string $msg the message needed to be shown
3024 public function update_full($percent, $msg) {
3025 $percent = max(min($percent, 100), 0);
3026 $this->_update($percent, $msg);
3030 * Update progress bar according the number of tasks
3032 * @param int $cur current task number
3033 * @param int $total total task number
3034 * @param string $msg message
3036 public function update($cur, $total, $msg) {
3037 $percent = ($cur / $total) * 100;
3038 $this->update_full($percent, $msg);
3042 * Restart the progress bar.
3044 public function restart() {
3045 $this->percent = 0;
3046 $this->lastupdate = 0;
3047 $this->time_start = 0;
3052 * Use this class from long operations where you want to output occasional information about
3053 * what is going on, but don't know if, or in what format, the output should be.
3055 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3056 * @package moodlecore
3058 abstract class progress_trace {
3060 * Output an progress message in whatever format.
3062 * @param string $message the message to output.
3063 * @param integer $depth indent depth for this message.
3065 abstract public function output($message, $depth = 0);
3068 * Called when the processing is finished.
3070 public function finished() {
3075 * This subclass of progress_trace does not ouput anything.
3077 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3078 * @package moodlecore
3080 class null_progress_trace extends progress_trace {
3082 * Does Nothing
3084 * @param string $message
3085 * @param int $depth
3086 * @return void Does Nothing
3088 public function output($message, $depth = 0) {
3093 * This subclass of progress_trace outputs to plain text.
3095 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3096 * @package moodlecore
3098 class text_progress_trace extends progress_trace {
3100 * Output the trace message.
3102 * @param string $message
3103 * @param int $depth
3104 * @return void Output is echo'd
3106 public function output($message, $depth = 0) {
3107 echo str_repeat(' ', $depth), $message, "\n";
3108 flush();
3113 * This subclass of progress_trace outputs as HTML.
3115 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3116 * @package moodlecore
3118 class html_progress_trace extends progress_trace {
3120 * Output the trace message.
3122 * @param string $message
3123 * @param int $depth
3124 * @return void Output is echo'd
3126 public function output($message, $depth = 0) {
3127 echo '<p>', str_repeat('&#160;&#160;', $depth), htmlspecialchars($message), "</p>\n";
3128 flush();
3133 * HTML List Progress Tree
3135 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3136 * @package moodlecore
3138 class html_list_progress_trace extends progress_trace {
3139 /** @var int */
3140 protected $currentdepth = -1;
3143 * Echo out the list
3145 * @param string $message The message to display
3146 * @param int $depth
3147 * @return void Output is echoed
3149 public function output($message, $depth = 0) {
3150 $samedepth = true;
3151 while ($this->currentdepth > $depth) {
3152 echo "</li>\n</ul>\n";
3153 $this->currentdepth -= 1;
3154 if ($this->currentdepth == $depth) {
3155 echo '<li>';
3157 $samedepth = false;
3159 while ($this->currentdepth < $depth) {
3160 echo "<ul>\n<li>";
3161 $this->currentdepth += 1;
3162 $samedepth = false;
3164 if ($samedepth) {
3165 echo "</li>\n<li>";
3167 echo htmlspecialchars($message);
3168 flush();
3172 * Called when the processing is finished.
3174 public function finished() {
3175 while ($this->currentdepth >= 0) {
3176 echo "</li>\n</ul>\n";
3177 $this->currentdepth -= 1;
3183 * This subclass of progress_trace outputs to error log.
3185 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3186 * @package moodlecore
3188 class error_log_progress_trace extends progress_trace {
3189 /** @var string log prefix */
3190 protected $prefix;
3193 * Constructor.
3194 * @param string $prefix optional log prefix
3196 public function __construct($prefix = '') {
3197 $this->prefix = $prefix;
3201 * Output the trace message.
3203 * @param string $message
3204 * @param int $depth
3205 * @return void Output is sent to error log.
3207 public function output($message, $depth = 0) {
3208 error_log($this->prefix . str_repeat(' ', $depth) . $message);
3213 * Special type of trace that can be used for catching of
3214 * output of other traces.
3216 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3217 * @package moodlecore
3219 class progress_trace_buffer extends progress_trace {
3220 /** @var progres_trace */
3221 protected $trace;
3222 /** @var bool do we pass output out */
3223 protected $passthrough;
3224 /** @var string output buffer */
3225 protected $buffer;
3228 * Constructor.
3230 * @param progress_trace $trace
3231 * @param bool $passthrough true means output and buffer, false means just buffer and no output
3233 public function __construct(progress_trace $trace, $passthrough = true) {
3234 $this->trace = $trace;
3235 $this->passthrough = $passthrough;
3236 $this->buffer = '';
3240 * Output the trace message.
3242 * @param string $message the message to output.
3243 * @param int $depth indent depth for this message.
3244 * @return void output stored in buffer
3246 public function output($message, $depth = 0) {
3247 ob_start();
3248 $this->trace->output($message, $depth);
3249 $this->buffer .= ob_get_contents();
3250 if ($this->passthrough) {
3251 ob_end_flush();
3252 } else {
3253 ob_end_clean();
3258 * Called when the processing is finished.
3260 public function finished() {
3261 ob_start();
3262 $this->trace->finished();
3263 $this->buffer .= ob_get_contents();
3264 if ($this->passthrough) {
3265 ob_end_flush();
3266 } else {
3267 ob_end_clean();
3272 * Reset internal text buffer.
3274 public function reset_buffer() {
3275 $this->buffer = '';
3279 * Return internal text buffer.
3280 * @return string buffered plain text
3282 public function get_buffer() {
3283 return $this->buffer;
3288 * Special type of trace that can be used for redirecting to multiple
3289 * other traces.
3291 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3292 * @package moodlecore
3294 class combined_progress_trace extends progress_trace {
3295 protected $traces;
3298 * @param array $traces multiple traces
3300 public function __construct(array $traces) {
3301 $this->traces = $traces;
3305 * Output an progress message in whatever format.
3307 * @param string $message the message to output.
3308 * @param integer $depth indent depth for this message.
3310 public function output($message, $depth = 0) {
3311 foreach($this->traces as $trace) {
3312 $trace->output($message, $depth);
3317 * Called when the processing is finished.
3319 public function finished() {
3320 foreach($this->traces as $trace) {
3321 $trace->finished();
3327 * Returns a localized sentence in the current language summarizing the current password policy
3329 * @todo this should be handled by a function/method in the language pack library once we have a support for it
3330 * @uses $CFG
3331 * @return string
3333 function print_password_policy() {
3334 global $CFG;
3336 $message = '';
3337 if (!empty($CFG->passwordpolicy)) {
3338 $messages = array();
3339 $messages[] = get_string('informminpasswordlength', 'auth', $CFG->minpasswordlength);
3340 if (!empty($CFG->minpassworddigits)) {
3341 $messages[] = get_string('informminpassworddigits', 'auth', $CFG->minpassworddigits);
3343 if (!empty($CFG->minpasswordlower)) {
3344 $messages[] = get_string('informminpasswordlower', 'auth', $CFG->minpasswordlower);
3346 if (!empty($CFG->minpasswordupper)) {
3347 $messages[] = get_string('informminpasswordupper', 'auth', $CFG->minpasswordupper);
3349 if (!empty($CFG->minpasswordnonalphanum)) {
3350 $messages[] = get_string('informminpasswordnonalphanum', 'auth', $CFG->minpasswordnonalphanum);
3353 $messages = join(', ', $messages); // this is ugly but we do not have anything better yet...
3354 $message = get_string('informpasswordpolicy', 'auth', $messages);
3356 return $message;
3360 * Get the value of a help string fully prepared for display in the current language.
3362 * @param string $identifier The identifier of the string to search for.
3363 * @param string $component The module the string is associated with.
3364 * @param boolean $ajax Whether this help is called from an AJAX script.
3365 * This is used to influence text formatting and determines
3366 * which format to output the doclink in.
3367 * @return Object An object containing:
3368 * - heading: Any heading that there may be for this help string.
3369 * - text: The wiki-formatted help string.
3370 * - doclink: An object containing a link, the linktext, and any additional
3371 * CSS classes to apply to that link. Only present if $ajax = false.
3372 * - completedoclink: A text representation of the doclink. Only present if $ajax = true.
3374 function get_formatted_help_string($identifier, $component, $ajax = false) {
3375 global $CFG, $OUTPUT;
3376 $sm = get_string_manager();
3378 if (!$sm->string_exists($identifier, $component) ||
3379 !$sm->string_exists($identifier . '_help', $component)) {
3380 // Strings in the on-disk cache may be dirty - try to rebuild it and check again.
3381 $sm->load_component_strings($component, current_language(), true);
3384 $data = new stdClass();
3386 if ($sm->string_exists($identifier, $component)) {
3387 $data->heading = format_string(get_string($identifier, $component));
3388 } else {
3389 // Gracefully fall back to an empty string.
3390 $data->heading = '';
3393 if ($sm->string_exists($identifier . '_help', $component)) {
3394 $options = new stdClass();
3395 $options->trusted = false;
3396 $options->noclean = false;
3397 $options->smiley = false;
3398 $options->filter = false;
3399 $options->para = true;
3400 $options->newlines = false;
3401 $options->overflowdiv = !$ajax;
3403 // Should be simple wiki only MDL-21695.
3404 $data->text = format_text(get_string($identifier.'_help', $component), FORMAT_MARKDOWN, $options);
3406 $helplink = $identifier . '_link';
3407 if ($sm->string_exists($helplink, $component)) { // Link to further info in Moodle docs
3408 $link = get_string($helplink, $component);
3409 $linktext = get_string('morehelp');
3411 $data->doclink = new stdClass();
3412 $url = new moodle_url(get_docs_url($link));
3413 if ($ajax) {
3414 $data->doclink->link = $url->out();
3415 $data->doclink->linktext = $linktext;
3416 $data->doclink->class = ($CFG->doctonewwindow) ? 'helplinkpopup' : '';
3417 } else {
3418 $data->completedoclink = html_writer::tag('div', $OUTPUT->doc_link($link, $linktext), array('class' => 'helpdoclink'));
3421 } else {
3422 $data->text = html_writer::tag('p',
3423 html_writer::tag('strong', 'TODO') . ": missing help string [{$identifier}_help, {$component}]");
3425 return $data;