Merge branch 'wip-mdl-52066-m28' of https://github.com/rajeshtaneja/moodle into MOODL...
[moodle.git] / lib / weblib.php
bloba2bd45ab9bf40a365655862bf8fba8d3d1d7a812
1 <?php
2 // This file is part of Moodle - http://moodle.org/
3 //
4 // Moodle is free software: you can redistribute it and/or modify
5 // it under the terms of the GNU General Public License as published by
6 // the Free Software Foundation, either version 3 of the License, or
7 // (at your option) any later version.
8 //
9 // Moodle is distributed in the hope that it will be useful,
10 // but WITHOUT ANY WARRANTY; without even the implied warranty of
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 // GNU General Public License for more details.
14 // You should have received a copy of the GNU General Public License
15 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
17 /**
18 * Library of functions for web output
20 * Library of all general-purpose Moodle PHP functions and constants
21 * that produce HTML output
23 * Other main libraries:
24 * - datalib.php - functions that access the database.
25 * - moodlelib.php - general-purpose Moodle functions.
27 * @package core
28 * @subpackage lib
29 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
30 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
33 defined('MOODLE_INTERNAL') || die();
35 // Constants.
37 // Define text formatting types ... eventually we can add Wiki, BBcode etc.
39 /**
40 * Does all sorts of transformations and filtering.
42 define('FORMAT_MOODLE', '0');
44 /**
45 * Plain HTML (with some tags stripped).
47 define('FORMAT_HTML', '1');
49 /**
50 * Plain text (even tags are printed in full).
52 define('FORMAT_PLAIN', '2');
54 /**
55 * Wiki-formatted text.
56 * Deprecated: left here just to note that '3' is not used (at the moment)
57 * and to catch any latent wiki-like text (which generates an error)
58 * @deprecated since 2005!
60 define('FORMAT_WIKI', '3');
62 /**
63 * Markdown-formatted text http://daringfireball.net/projects/markdown/
65 define('FORMAT_MARKDOWN', '4');
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);
72 /**
73 * A moodle_url comparison using this flag will return true if the base URLs match and the params of url1 are part of url2.
75 define('URL_MATCH_PARAMS', 1);
77 /**
78 * A moodle_url comparison using this flag will return true if the two URLs are identical, except for the order of the params.
80 define('URL_MATCH_EXACT', 2);
82 // Functions.
84 /**
85 * Add quotes to HTML characters.
87 * Returns $var with HTML characters (like "<", ">", etc.) properly quoted.
88 * This function is very similar to {@link p()}
90 * @param string $var the string potentially containing HTML characters
91 * @return string
93 function s($var) {
95 if ($var === false) {
96 return '0';
99 // When we move to PHP 5.4 as a minimum version, change ENT_QUOTES on the
100 // next line to ENT_QUOTES | ENT_HTML5 | ENT_SUBSTITUTE, and remove the
101 // 'UTF-8' argument. Both bring a speed-increase.
102 return preg_replace('/&amp;#(\d+|x[0-9a-f]+);/i', '&#$1;', htmlspecialchars($var, ENT_QUOTES, 'UTF-8'));
106 * Add quotes to HTML characters.
108 * Prints $var with HTML characters (like "<", ">", etc.) properly quoted.
109 * This function simply calls {@link s()}
110 * @see s()
112 * @todo Remove obsolete param $obsolete if not used anywhere
114 * @param string $var the string potentially containing HTML characters
115 * @param boolean $obsolete no longer used.
116 * @return string
118 function p($var, $obsolete = false) {
119 echo s($var, $obsolete);
123 * Does proper javascript quoting.
125 * Do not use addslashes anymore, because it does not work when magic_quotes_sybase is enabled.
127 * @param mixed $var String, Array, or Object to add slashes to
128 * @return mixed quoted result
130 function addslashes_js($var) {
131 if (is_string($var)) {
132 $var = str_replace('\\', '\\\\', $var);
133 $var = str_replace(array('\'', '"', "\n", "\r", "\0"), array('\\\'', '\\"', '\\n', '\\r', '\\0'), $var);
134 $var = str_replace('</', '<\/', $var); // XHTML compliance.
135 } else if (is_array($var)) {
136 $var = array_map('addslashes_js', $var);
137 } else if (is_object($var)) {
138 $a = get_object_vars($var);
139 foreach ($a as $key => $value) {
140 $a[$key] = addslashes_js($value);
142 $var = (object)$a;
144 return $var;
148 * Remove query string from url.
150 * Takes in a URL and returns it without the querystring portion.
152 * @param string $url the url which may have a query string attached.
153 * @return string The remaining URL.
155 function strip_querystring($url) {
157 if ($commapos = strpos($url, '?')) {
158 return substr($url, 0, $commapos);
159 } else {
160 return $url;
165 * Returns the URL of the HTTP_REFERER, less the querystring portion if required.
167 * @param boolean $stripquery if true, also removes the query part of the url.
168 * @return string The resulting referer or empty string.
170 function get_referer($stripquery=true) {
171 if (isset($_SERVER['HTTP_REFERER'])) {
172 if ($stripquery) {
173 return strip_querystring($_SERVER['HTTP_REFERER']);
174 } else {
175 return $_SERVER['HTTP_REFERER'];
177 } else {
178 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 * Determines whether or not the Moodle site is being served over HTTPS.
229 * This is done simply by checking the value of $CFG->httpswwwroot, which seems
230 * to be the only reliable method.
232 * @return boolean True if site is served over HTTPS, false otherwise.
234 function is_https() {
235 global $CFG;
237 return (strpos($CFG->httpswwwroot, 'https://') === 0);
241 * Returns the cleaned local URL of the HTTP_REFERER less the URL query string parameters if required.
243 * If you need to get an external referer, you can do so by using clean_param($_SERVER['HTTP_REFERER'], PARAM_URL)
244 * and optionally stripquerystring().
246 * @param bool $stripquery if true, also removes the query part of the url.
247 * @return string The resulting referer or empty string.
249 function get_local_referer($stripquery = true) {
250 if (isset($_SERVER['HTTP_REFERER'])) {
251 $referer = clean_param($_SERVER['HTTP_REFERER'], PARAM_LOCALURL);
252 if ($stripquery) {
253 return strip_querystring($referer);
254 } else {
255 return $referer;
257 } else {
258 return '';
263 * Class for creating and manipulating urls.
265 * It can be used in moodle pages where config.php has been included without any further includes.
267 * It is useful for manipulating urls with long lists of params.
268 * One situation where it will be useful is a page which links to itself to perform various actions
269 * and / or to process form data. A moodle_url object :
270 * can be created for a page to refer to itself with all the proper get params being passed from page call to
271 * page call and methods can be used to output a url including all the params, optionally adding and overriding
272 * params and can also be used to
273 * - output the url without any get params
274 * - and output the params as hidden fields to be output within a form
276 * @copyright 2007 jamiesensei
277 * @link http://docs.moodle.org/dev/lib/weblib.php_moodle_url See short write up here
278 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
279 * @package core
281 class moodle_url {
284 * Scheme, ex.: http, https
285 * @var string
287 protected $scheme = '';
290 * Hostname.
291 * @var string
293 protected $host = '';
296 * Port number, empty means default 80 or 443 in case of http.
297 * @var int
299 protected $port = '';
302 * Username for http auth.
303 * @var string
305 protected $user = '';
308 * Password for http auth.
309 * @var string
311 protected $pass = '';
314 * Script path.
315 * @var string
317 protected $path = '';
320 * Optional slash argument value.
321 * @var string
323 protected $slashargument = '';
326 * Anchor, may be also empty, null means none.
327 * @var string
329 protected $anchor = null;
332 * Url parameters as associative array.
333 * @var array
335 protected $params = array();
338 * Create new instance of moodle_url.
340 * @param moodle_url|string $url - moodle_url means make a copy of another
341 * moodle_url and change parameters, string means full url or shortened
342 * form (ex.: '/course/view.php'). It is strongly encouraged to not include
343 * query string because it may result in double encoded values. Use the
344 * $params instead. For admin URLs, just use /admin/script.php, this
345 * class takes care of the $CFG->admin issue.
346 * @param array $params these params override current params or add new
347 * @param string $anchor The anchor to use as part of the URL if there is one.
348 * @throws moodle_exception
350 public function __construct($url, array $params = null, $anchor = null) {
351 global $CFG;
353 if ($url instanceof moodle_url) {
354 $this->scheme = $url->scheme;
355 $this->host = $url->host;
356 $this->port = $url->port;
357 $this->user = $url->user;
358 $this->pass = $url->pass;
359 $this->path = $url->path;
360 $this->slashargument = $url->slashargument;
361 $this->params = $url->params;
362 $this->anchor = $url->anchor;
364 } else {
365 // Detect if anchor used.
366 $apos = strpos($url, '#');
367 if ($apos !== false) {
368 $anchor = substr($url, $apos);
369 $anchor = ltrim($anchor, '#');
370 $this->set_anchor($anchor);
371 $url = substr($url, 0, $apos);
374 // Normalise shortened form of our url ex.: '/course/view.php'.
375 if (strpos($url, '/') === 0) {
376 // We must not use httpswwwroot here, because it might be url of other page,
377 // devs have to use httpswwwroot explicitly when creating new moodle_url.
378 $url = $CFG->wwwroot.$url;
381 // Now fix the admin links if needed, no need to mess with httpswwwroot.
382 if ($CFG->admin !== 'admin') {
383 if (strpos($url, "$CFG->wwwroot/admin/") === 0) {
384 $url = str_replace("$CFG->wwwroot/admin/", "$CFG->wwwroot/$CFG->admin/", $url);
388 // Parse the $url.
389 $parts = parse_url($url);
390 if ($parts === false) {
391 throw new moodle_exception('invalidurl');
393 if (isset($parts['query'])) {
394 // Note: the values may not be correctly decoded, url parameters should be always passed as array.
395 parse_str(str_replace('&amp;', '&', $parts['query']), $this->params);
397 unset($parts['query']);
398 foreach ($parts as $key => $value) {
399 $this->$key = $value;
402 // Detect slashargument value from path - we do not support directory names ending with .php.
403 $pos = strpos($this->path, '.php/');
404 if ($pos !== false) {
405 $this->slashargument = substr($this->path, $pos + 4);
406 $this->path = substr($this->path, 0, $pos + 4);
410 $this->params($params);
411 if ($anchor !== null) {
412 $this->anchor = (string)$anchor;
417 * Add an array of params to the params for this url.
419 * The added params override existing ones if they have the same name.
421 * @param array $params Defaults to null. If null then returns all params.
422 * @return array Array of Params for url.
423 * @throws coding_exception
425 public function params(array $params = null) {
426 $params = (array)$params;
428 foreach ($params as $key => $value) {
429 if (is_int($key)) {
430 throw new coding_exception('Url parameters can not have numeric keys!');
432 if (!is_string($value)) {
433 if (is_array($value)) {
434 throw new coding_exception('Url parameters values can not be arrays!');
436 if (is_object($value) and !method_exists($value, '__toString')) {
437 throw new coding_exception('Url parameters values can not be objects, unless __toString() is defined!');
440 $this->params[$key] = (string)$value;
442 return $this->params;
446 * Remove all params if no arguments passed.
447 * Remove selected params if arguments are passed.
449 * Can be called as either remove_params('param1', 'param2')
450 * or remove_params(array('param1', 'param2')).
452 * @param string[]|string $params,... either an array of param names, or 1..n string params to remove as args.
453 * @return array url parameters
455 public function remove_params($params = null) {
456 if (!is_array($params)) {
457 $params = func_get_args();
459 foreach ($params as $param) {
460 unset($this->params[$param]);
462 return $this->params;
466 * Remove all url parameters.
468 * @todo remove the unused param.
469 * @param array $params Unused param
470 * @return void
472 public function remove_all_params($params = null) {
473 $this->params = array();
474 $this->slashargument = '';
478 * Add a param to the params for this url.
480 * The added param overrides existing one if they have the same name.
482 * @param string $paramname name
483 * @param string $newvalue Param value. If new value specified current value is overriden or parameter is added
484 * @return mixed string parameter value, null if parameter does not exist
486 public function param($paramname, $newvalue = '') {
487 if (func_num_args() > 1) {
488 // Set new value.
489 $this->params(array($paramname => $newvalue));
491 if (isset($this->params[$paramname])) {
492 return $this->params[$paramname];
493 } else {
494 return null;
499 * Merges parameters and validates them
501 * @param array $overrideparams
502 * @return array merged parameters
503 * @throws coding_exception
505 protected function merge_overrideparams(array $overrideparams = null) {
506 $overrideparams = (array)$overrideparams;
507 $params = $this->params;
508 foreach ($overrideparams as $key => $value) {
509 if (is_int($key)) {
510 throw new coding_exception('Overridden parameters can not have numeric keys!');
512 if (is_array($value)) {
513 throw new coding_exception('Overridden parameters values can not be arrays!');
515 if (is_object($value) and !method_exists($value, '__toString')) {
516 throw new coding_exception('Overridden parameters values can not be objects, unless __toString() is defined!');
518 $params[$key] = (string)$value;
520 return $params;
524 * Get the params as as a query string.
526 * This method should not be used outside of this method.
528 * @param bool $escaped Use &amp; as params separator instead of plain &
529 * @param array $overrideparams params to add to the output params, these
530 * override existing ones with the same name.
531 * @return string query string that can be added to a url.
533 public function get_query_string($escaped = true, array $overrideparams = null) {
534 $arr = array();
535 if ($overrideparams !== null) {
536 $params = $this->merge_overrideparams($overrideparams);
537 } else {
538 $params = $this->params;
540 foreach ($params as $key => $val) {
541 if (is_array($val)) {
542 foreach ($val as $index => $value) {
543 $arr[] = rawurlencode($key.'['.$index.']')."=".rawurlencode($value);
545 } else {
546 if (isset($val) && $val !== '') {
547 $arr[] = rawurlencode($key)."=".rawurlencode($val);
548 } else {
549 $arr[] = rawurlencode($key);
553 if ($escaped) {
554 return implode('&amp;', $arr);
555 } else {
556 return implode('&', $arr);
561 * Shortcut for printing of encoded URL.
563 * @return string
565 public function __toString() {
566 return $this->out(true);
570 * Output url.
572 * If you use the returned URL in HTML code, you want the escaped ampersands. If you use
573 * the returned URL in HTTP headers, you want $escaped=false.
575 * @param bool $escaped Use &amp; as params separator instead of plain &
576 * @param array $overrideparams params to add to the output url, these override existing ones with the same name.
577 * @return string Resulting URL
579 public function out($escaped = true, array $overrideparams = null) {
580 if (!is_bool($escaped)) {
581 debugging('Escape parameter must be of type boolean, '.gettype($escaped).' given instead.');
584 $uri = $this->out_omit_querystring().$this->slashargument;
586 $querystring = $this->get_query_string($escaped, $overrideparams);
587 if ($querystring !== '') {
588 $uri .= '?' . $querystring;
590 if (!is_null($this->anchor)) {
591 $uri .= '#'.$this->anchor;
594 return $uri;
598 * Returns url without parameters, everything before '?'.
600 * @param bool $includeanchor if {@link self::anchor} is defined, should it be returned?
601 * @return string
603 public function out_omit_querystring($includeanchor = false) {
605 $uri = $this->scheme ? $this->scheme.':'.((strtolower($this->scheme) == 'mailto') ? '':'//'): '';
606 $uri .= $this->user ? $this->user.($this->pass? ':'.$this->pass:'').'@':'';
607 $uri .= $this->host ? $this->host : '';
608 $uri .= $this->port ? ':'.$this->port : '';
609 $uri .= $this->path ? $this->path : '';
610 if ($includeanchor and !is_null($this->anchor)) {
611 $uri .= '#' . $this->anchor;
614 return $uri;
618 * Compares this moodle_url with another.
620 * See documentation of constants for an explanation of the comparison flags.
622 * @param moodle_url $url The moodle_url object to compare
623 * @param int $matchtype The type of comparison (URL_MATCH_BASE, URL_MATCH_PARAMS, URL_MATCH_EXACT)
624 * @return bool
626 public function compare(moodle_url $url, $matchtype = URL_MATCH_EXACT) {
628 $baseself = $this->out_omit_querystring();
629 $baseother = $url->out_omit_querystring();
631 // Append index.php if there is no specific file.
632 if (substr($baseself, -1) == '/') {
633 $baseself .= 'index.php';
635 if (substr($baseother, -1) == '/') {
636 $baseother .= 'index.php';
639 // Compare the two base URLs.
640 if ($baseself != $baseother) {
641 return false;
644 if ($matchtype == URL_MATCH_BASE) {
645 return true;
648 $urlparams = $url->params();
649 foreach ($this->params() as $param => $value) {
650 if ($param == 'sesskey') {
651 continue;
653 if (!array_key_exists($param, $urlparams) || $urlparams[$param] != $value) {
654 return false;
658 if ($matchtype == URL_MATCH_PARAMS) {
659 return true;
662 foreach ($urlparams as $param => $value) {
663 if ($param == 'sesskey') {
664 continue;
666 if (!array_key_exists($param, $this->params()) || $this->param($param) != $value) {
667 return false;
671 if ($url->anchor !== $this->anchor) {
672 return false;
675 return true;
679 * Sets the anchor for the URI (the bit after the hash)
681 * @param string $anchor null means remove previous
683 public function set_anchor($anchor) {
684 if (is_null($anchor)) {
685 // Remove.
686 $this->anchor = null;
687 } else if ($anchor === '') {
688 // Special case, used as empty link.
689 $this->anchor = '';
690 } else if (preg_match('|[a-zA-Z\_\:][a-zA-Z0-9\_\-\.\:]*|', $anchor)) {
691 // Match the anchor against the NMTOKEN spec.
692 $this->anchor = $anchor;
693 } else {
694 // Bad luck, no valid anchor found.
695 $this->anchor = null;
700 * Sets the url slashargument value.
702 * @param string $path usually file path
703 * @param string $parameter name of page parameter if slasharguments not supported
704 * @param bool $supported usually null, then it depends on $CFG->slasharguments, use true or false for other servers
705 * @return void
707 public function set_slashargument($path, $parameter = 'file', $supported = null) {
708 global $CFG;
709 if (is_null($supported)) {
710 $supported = $CFG->slasharguments;
713 if ($supported) {
714 $parts = explode('/', $path);
715 $parts = array_map('rawurlencode', $parts);
716 $path = implode('/', $parts);
717 $this->slashargument = $path;
718 unset($this->params[$parameter]);
720 } else {
721 $this->slashargument = '';
722 $this->params[$parameter] = $path;
726 // Static factory methods.
729 * General moodle file url.
731 * @param string $urlbase the script serving the file
732 * @param string $path
733 * @param bool $forcedownload
734 * @return moodle_url
736 public static function make_file_url($urlbase, $path, $forcedownload = false) {
737 $params = array();
738 if ($forcedownload) {
739 $params['forcedownload'] = 1;
742 $url = new moodle_url($urlbase, $params);
743 $url->set_slashargument($path);
744 return $url;
748 * Factory method for creation of url pointing to plugin file.
750 * Please note this method can be used only from the plugins to
751 * create urls of own files, it must not be used outside of plugins!
753 * @param int $contextid
754 * @param string $component
755 * @param string $area
756 * @param int $itemid
757 * @param string $pathname
758 * @param string $filename
759 * @param bool $forcedownload
760 * @return moodle_url
762 public static function make_pluginfile_url($contextid, $component, $area, $itemid, $pathname, $filename,
763 $forcedownload = false) {
764 global $CFG;
765 $urlbase = "$CFG->httpswwwroot/pluginfile.php";
766 if ($itemid === null) {
767 return self::make_file_url($urlbase, "/$contextid/$component/$area".$pathname.$filename, $forcedownload);
768 } else {
769 return self::make_file_url($urlbase, "/$contextid/$component/$area/$itemid".$pathname.$filename, $forcedownload);
774 * Factory method for creation of url pointing to plugin file.
775 * This method is the same that make_pluginfile_url but pointing to the webservice pluginfile.php script.
776 * It should be used only in external functions.
778 * @since 2.8
779 * @param int $contextid
780 * @param string $component
781 * @param string $area
782 * @param int $itemid
783 * @param string $pathname
784 * @param string $filename
785 * @param bool $forcedownload
786 * @return moodle_url
788 public static function make_webservice_pluginfile_url($contextid, $component, $area, $itemid, $pathname, $filename,
789 $forcedownload = false) {
790 global $CFG;
791 $urlbase = "$CFG->httpswwwroot/webservice/pluginfile.php";
792 if ($itemid === null) {
793 return self::make_file_url($urlbase, "/$contextid/$component/$area".$pathname.$filename, $forcedownload);
794 } else {
795 return self::make_file_url($urlbase, "/$contextid/$component/$area/$itemid".$pathname.$filename, $forcedownload);
800 * Factory method for creation of url pointing to draft file of current user.
802 * @param int $draftid draft item id
803 * @param string $pathname
804 * @param string $filename
805 * @param bool $forcedownload
806 * @return moodle_url
808 public static function make_draftfile_url($draftid, $pathname, $filename, $forcedownload = false) {
809 global $CFG, $USER;
810 $urlbase = "$CFG->httpswwwroot/draftfile.php";
811 $context = context_user::instance($USER->id);
813 return self::make_file_url($urlbase, "/$context->id/user/draft/$draftid".$pathname.$filename, $forcedownload);
817 * Factory method for creating of links to legacy course files.
819 * @param int $courseid
820 * @param string $filepath
821 * @param bool $forcedownload
822 * @return moodle_url
824 public static function make_legacyfile_url($courseid, $filepath, $forcedownload = false) {
825 global $CFG;
827 $urlbase = "$CFG->wwwroot/file.php";
828 return self::make_file_url($urlbase, '/'.$courseid.'/'.$filepath, $forcedownload);
832 * Returns URL a relative path from $CFG->wwwroot
834 * Can be used for passing around urls with the wwwroot stripped
836 * @param boolean $escaped Use &amp; as params separator instead of plain &
837 * @param array $overrideparams params to add to the output url, these override existing ones with the same name.
838 * @return string Resulting URL
839 * @throws coding_exception if called on a non-local url
841 public function out_as_local_url($escaped = true, array $overrideparams = null) {
842 global $CFG;
844 $url = $this->out($escaped, $overrideparams);
845 $httpswwwroot = str_replace("http://", "https://", $CFG->wwwroot);
847 // Url should be equal to wwwroot or httpswwwroot. If not then throw exception.
848 if (($url === $CFG->wwwroot) || (strpos($url, $CFG->wwwroot.'/') === 0)) {
849 $localurl = substr($url, strlen($CFG->wwwroot));
850 return !empty($localurl) ? $localurl : '';
851 } else if (($url === $httpswwwroot) || (strpos($url, $httpswwwroot.'/') === 0)) {
852 $localurl = substr($url, strlen($httpswwwroot));
853 return !empty($localurl) ? $localurl : '';
854 } else {
855 throw new coding_exception('out_as_local_url called on a non-local URL');
860 * Returns the 'path' portion of a URL. For example, if the URL is
861 * http://www.example.org:447/my/file/is/here.txt?really=1 then this will
862 * return '/my/file/is/here.txt'.
864 * By default the path includes slash-arguments (for example,
865 * '/myfile.php/extra/arguments') so it is what you would expect from a
866 * URL path. If you don't want this behaviour, you can opt to exclude the
867 * slash arguments. (Be careful: if the $CFG variable slasharguments is
868 * disabled, these URLs will have a different format and you may need to
869 * look at the 'file' parameter too.)
871 * @param bool $includeslashargument If true, includes slash arguments
872 * @return string Path of URL
874 public function get_path($includeslashargument = true) {
875 return $this->path . ($includeslashargument ? $this->slashargument : '');
879 * Returns a given parameter value from the URL.
881 * @param string $name Name of parameter
882 * @return string Value of parameter or null if not set
884 public function get_param($name) {
885 if (array_key_exists($name, $this->params)) {
886 return $this->params[$name];
887 } else {
888 return null;
893 * Returns the 'scheme' portion of a URL. For example, if the URL is
894 * http://www.example.org:447/my/file/is/here.txt?really=1 then this will
895 * return 'http' (without the colon).
897 * @return string Scheme of the URL.
899 public function get_scheme() {
900 return $this->scheme;
904 * Returns the 'host' portion of a URL. For example, if the URL is
905 * http://www.example.org:447/my/file/is/here.txt?really=1 then this will
906 * return 'www.example.org'.
908 * @return string Host of the URL.
910 public function get_host() {
911 return $this->host;
915 * Returns the 'port' portion of a URL. For example, if the URL is
916 * http://www.example.org:447/my/file/is/here.txt?really=1 then this will
917 * return '447'.
919 * @return string Port of the URL.
921 public function get_port() {
922 return $this->port;
927 * Determine if there is data waiting to be processed from a form
929 * Used on most forms in Moodle to check for data
930 * Returns the data as an object, if it's found.
931 * This object can be used in foreach loops without
932 * casting because it's cast to (array) automatically
934 * Checks that submitted POST data exists and returns it as object.
936 * @return mixed false or object
938 function data_submitted() {
940 if (empty($_POST)) {
941 return false;
942 } else {
943 return (object)fix_utf8($_POST);
948 * Given some normal text this function will break up any
949 * long words to a given size by inserting the given character
951 * It's multibyte savvy and doesn't change anything inside html tags.
953 * @param string $string the string to be modified
954 * @param int $maxsize maximum length of the string to be returned
955 * @param string $cutchar the string used to represent word breaks
956 * @return string
958 function break_up_long_words($string, $maxsize=20, $cutchar=' ') {
960 // First of all, save all the tags inside the text to skip them.
961 $tags = array();
962 filter_save_tags($string, $tags);
964 // Process the string adding the cut when necessary.
965 $output = '';
966 $length = core_text::strlen($string);
967 $wordlength = 0;
969 for ($i=0; $i<$length; $i++) {
970 $char = core_text::substr($string, $i, 1);
971 if ($char == ' ' or $char == "\t" or $char == "\n" or $char == "\r" or $char == "<" or $char == ">") {
972 $wordlength = 0;
973 } else {
974 $wordlength++;
975 if ($wordlength > $maxsize) {
976 $output .= $cutchar;
977 $wordlength = 0;
980 $output .= $char;
983 // Finally load the tags back again.
984 if (!empty($tags)) {
985 $output = str_replace(array_keys($tags), $tags, $output);
988 return $output;
992 * Try and close the current window using JavaScript, either immediately, or after a delay.
994 * Echo's out the resulting XHTML & javascript
996 * @param integer $delay a delay in seconds before closing the window. Default 0.
997 * @param boolean $reloadopener if true, we will see if this window was a pop-up, and try
998 * to reload the parent window before this one closes.
1000 function close_window($delay = 0, $reloadopener = false) {
1001 global $PAGE, $OUTPUT;
1003 if (!$PAGE->headerprinted) {
1004 $PAGE->set_title(get_string('closewindow'));
1005 echo $OUTPUT->header();
1006 } else {
1007 $OUTPUT->container_end_all(false);
1010 if ($reloadopener) {
1011 // Trigger the reload immediately, even if the reload is after a delay.
1012 $PAGE->requires->js_function_call('window.opener.location.reload', array(true));
1014 $OUTPUT->notification(get_string('windowclosing'), 'notifysuccess');
1016 $PAGE->requires->js_function_call('close_window', array(new stdClass()), false, $delay);
1018 echo $OUTPUT->footer();
1019 exit;
1023 * Returns a string containing a link to the user documentation for the current page.
1025 * Also contains an icon by default. Shown to teachers and admin only.
1027 * @param string $text The text to be displayed for the link
1028 * @return string The link to user documentation for this current page
1030 function page_doc_link($text='') {
1031 global $OUTPUT, $PAGE;
1032 $path = page_get_doc_link_path($PAGE);
1033 if (!$path) {
1034 return '';
1036 return $OUTPUT->doc_link($path, $text);
1040 * Returns the path to use when constructing a link to the docs.
1042 * @since Moodle 2.5.1 2.6
1043 * @param moodle_page $page
1044 * @return string
1046 function page_get_doc_link_path(moodle_page $page) {
1047 global $CFG;
1049 if (empty($CFG->docroot) || during_initial_install()) {
1050 return '';
1052 if (!has_capability('moodle/site:doclinks', $page->context)) {
1053 return '';
1056 $path = $page->docspath;
1057 if (!$path) {
1058 return '';
1060 return $path;
1065 * Validates an email to make sure it makes sense.
1067 * @param string $address The email address to validate.
1068 * @return boolean
1070 function validate_email($address) {
1072 return (preg_match('#^[-!\#$%&\'*+\\/0-9=?A-Z^_`a-z{|}~]+'.
1073 '(\.[-!\#$%&\'*+\\/0-9=?A-Z^_`a-z{|}~]+)*'.
1074 '@'.
1075 '[-!\#$%&\'*+\\/0-9=?A-Z^_`a-z{|}~]+\.'.
1076 '[-!\#$%&\'*+\\./0-9=?A-Z^_`a-z{|}~]+$#',
1077 $address));
1081 * Extracts file argument either from file parameter or PATH_INFO
1083 * Note: $scriptname parameter is not needed anymore
1085 * @return string file path (only safe characters)
1087 function get_file_argument() {
1088 global $SCRIPT;
1090 $relativepath = optional_param('file', false, PARAM_PATH);
1092 if ($relativepath !== false and $relativepath !== '') {
1093 return $relativepath;
1095 $relativepath = false;
1097 // Then try extract file from the slasharguments.
1098 if (stripos($_SERVER['SERVER_SOFTWARE'], 'iis') !== false) {
1099 // NOTE: IIS tends to convert all file paths to single byte DOS encoding,
1100 // we can not use other methods because they break unicode chars,
1101 // the only ways are to use URL rewriting
1102 // OR
1103 // to properly set the 'FastCGIUtf8ServerVariables' registry key.
1104 if (isset($_SERVER['PATH_INFO']) and $_SERVER['PATH_INFO'] !== '') {
1105 // Check that PATH_INFO works == must not contain the script name.
1106 if (strpos($_SERVER['PATH_INFO'], $SCRIPT) === false) {
1107 $relativepath = clean_param(urldecode($_SERVER['PATH_INFO']), PARAM_PATH);
1110 } else {
1111 // All other apache-like servers depend on PATH_INFO.
1112 if (isset($_SERVER['PATH_INFO'])) {
1113 if (isset($_SERVER['SCRIPT_NAME']) and strpos($_SERVER['PATH_INFO'], $_SERVER['SCRIPT_NAME']) === 0) {
1114 $relativepath = substr($_SERVER['PATH_INFO'], strlen($_SERVER['SCRIPT_NAME']));
1115 } else {
1116 $relativepath = $_SERVER['PATH_INFO'];
1118 $relativepath = clean_param($relativepath, PARAM_PATH);
1122 return $relativepath;
1126 * Just returns an array of text formats suitable for a popup menu
1128 * @return array
1130 function format_text_menu() {
1131 return array (FORMAT_MOODLE => get_string('formattext'),
1132 FORMAT_HTML => get_string('formathtml'),
1133 FORMAT_PLAIN => get_string('formatplain'),
1134 FORMAT_MARKDOWN => get_string('formatmarkdown'));
1138 * Given text in a variety of format codings, this function returns the text as safe HTML.
1140 * This function should mainly be used for long strings like posts,
1141 * answers, glossary items etc. For short strings {@link format_string()}.
1143 * <pre>
1144 * Options:
1145 * trusted : If true the string won't be cleaned. Default false required noclean=true.
1146 * noclean : If true the string won't be cleaned. Default false required trusted=true.
1147 * nocache : If true the strign will not be cached and will be formatted every call. Default false.
1148 * filter : If true the string will be run through applicable filters as well. Default true.
1149 * para : If true then the returned string will be wrapped in div tags. Default true.
1150 * newlines : If true then lines newline breaks will be converted to HTML newline breaks. Default true.
1151 * context : The context that will be used for filtering.
1152 * overflowdiv : If set to true the formatted text will be encased in a div
1153 * with the class no-overflow before being returned. Default false.
1154 * allowid : If true then id attributes will not be removed, even when
1155 * using htmlpurifier. Default false.
1156 * </pre>
1158 * @staticvar array $croncache
1159 * @param string $text The text to be formatted. This is raw text originally from user input.
1160 * @param int $format Identifier of the text format to be used
1161 * [FORMAT_MOODLE, FORMAT_HTML, FORMAT_PLAIN, FORMAT_MARKDOWN]
1162 * @param object/array $options text formatting options
1163 * @param int $courseiddonotuse deprecated course id, use context option instead
1164 * @return string
1166 function format_text($text, $format = FORMAT_MOODLE, $options = null, $courseiddonotuse = null) {
1167 global $CFG, $DB, $PAGE;
1169 if ($text === '' || is_null($text)) {
1170 // No need to do any filters and cleaning.
1171 return '';
1174 // Detach object, we can not modify it.
1175 $options = (array)$options;
1177 if (!isset($options['trusted'])) {
1178 $options['trusted'] = false;
1180 if (!isset($options['noclean'])) {
1181 if ($options['trusted'] and trusttext_active()) {
1182 // No cleaning if text trusted and noclean not specified.
1183 $options['noclean'] = true;
1184 } else {
1185 $options['noclean'] = false;
1188 if (!isset($options['nocache'])) {
1189 $options['nocache'] = false;
1191 if (!isset($options['filter'])) {
1192 $options['filter'] = true;
1194 if (!isset($options['para'])) {
1195 $options['para'] = true;
1197 if (!isset($options['newlines'])) {
1198 $options['newlines'] = true;
1200 if (!isset($options['overflowdiv'])) {
1201 $options['overflowdiv'] = false;
1204 // Calculate best context.
1205 if (empty($CFG->version) or $CFG->version < 2013051400 or during_initial_install()) {
1206 // Do not filter anything during installation or before upgrade completes.
1207 $context = null;
1209 } else if (isset($options['context'])) { // First by explicit passed context option.
1210 if (is_object($options['context'])) {
1211 $context = $options['context'];
1212 } else {
1213 $context = context::instance_by_id($options['context']);
1215 } else if ($courseiddonotuse) {
1216 // Legacy courseid.
1217 $context = context_course::instance($courseiddonotuse);
1218 } else {
1219 // Fallback to $PAGE->context this may be problematic in CLI and other non-standard pages :-(.
1220 $context = $PAGE->context;
1223 if (!$context) {
1224 // Either install/upgrade or something has gone really wrong because context does not exist (yet?).
1225 $options['nocache'] = true;
1226 $options['filter'] = false;
1229 if ($options['filter']) {
1230 $filtermanager = filter_manager::instance();
1231 $filtermanager->setup_page_for_filters($PAGE, $context); // Setup global stuff filters may have.
1232 } else {
1233 $filtermanager = new null_filter_manager();
1236 switch ($format) {
1237 case FORMAT_HTML:
1238 if (!$options['noclean']) {
1239 $text = clean_text($text, FORMAT_HTML, $options);
1241 $text = $filtermanager->filter_text($text, $context, array(
1242 'originalformat' => FORMAT_HTML,
1243 'noclean' => $options['noclean']
1245 break;
1247 case FORMAT_PLAIN:
1248 $text = s($text); // Cleans dangerous JS.
1249 $text = rebuildnolinktag($text);
1250 $text = str_replace(' ', '&nbsp; ', $text);
1251 $text = nl2br($text);
1252 break;
1254 case FORMAT_WIKI:
1255 // This format is deprecated.
1256 $text = '<p>NOTICE: Wiki-like formatting has been removed from Moodle. You should not be seeing
1257 this message as all texts should have been converted to Markdown format instead.
1258 Please post a bug report to http://moodle.org/bugs with information about where you
1259 saw this message.</p>'.s($text);
1260 break;
1262 case FORMAT_MARKDOWN:
1263 $text = markdown_to_html($text);
1264 if (!$options['noclean']) {
1265 $text = clean_text($text, FORMAT_HTML, $options);
1267 $text = $filtermanager->filter_text($text, $context, array(
1268 'originalformat' => FORMAT_MARKDOWN,
1269 'noclean' => $options['noclean']
1271 break;
1273 default: // FORMAT_MOODLE or anything else.
1274 $text = text_to_html($text, null, $options['para'], $options['newlines']);
1275 if (!$options['noclean']) {
1276 $text = clean_text($text, FORMAT_HTML, $options);
1278 $text = $filtermanager->filter_text($text, $context, array(
1279 'originalformat' => $format,
1280 'noclean' => $options['noclean']
1282 break;
1284 if ($options['filter']) {
1285 // At this point there should not be any draftfile links any more,
1286 // this happens when developers forget to post process the text.
1287 // The only potential problem is that somebody might try to format
1288 // the text before storing into database which would be itself big bug..
1289 $text = str_replace("\"$CFG->httpswwwroot/draftfile.php", "\"$CFG->httpswwwroot/brokenfile.php#", $text);
1291 if ($CFG->debugdeveloper) {
1292 if (strpos($text, '@@PLUGINFILE@@/') !== false) {
1293 debugging('Before calling format_text(), the content must be processed with file_rewrite_pluginfile_urls()',
1294 DEBUG_DEVELOPER);
1299 if (!empty($options['overflowdiv'])) {
1300 $text = html_writer::tag('div', $text, array('class' => 'no-overflow'));
1303 return $text;
1307 * Resets some data related to filters, called during upgrade or when general filter settings change.
1309 * @param bool $phpunitreset true means called from our PHPUnit integration test reset
1310 * @return void
1312 function reset_text_filters_cache($phpunitreset = false) {
1313 global $CFG, $DB;
1315 if ($phpunitreset) {
1316 // HTMLPurifier does not change, DB is already reset to defaults,
1317 // nothing to do here, the dataroot was cleared too.
1318 return;
1321 // The purge_all_caches() deals with cachedir and localcachedir purging,
1322 // the individual filter caches are invalidated as necessary elsewhere.
1324 // Update $CFG->filterall cache flag.
1325 if (empty($CFG->stringfilters)) {
1326 set_config('filterall', 0);
1327 return;
1329 $installedfilters = core_component::get_plugin_list('filter');
1330 $filters = explode(',', $CFG->stringfilters);
1331 foreach ($filters as $filter) {
1332 if (isset($installedfilters[$filter])) {
1333 set_config('filterall', 1);
1334 return;
1337 set_config('filterall', 0);
1341 * Given a simple string, this function returns the string
1342 * processed by enabled string filters if $CFG->filterall is enabled
1344 * This function should be used to print short strings (non html) that
1345 * need filter processing e.g. activity titles, post subjects,
1346 * glossary concepts.
1348 * @staticvar bool $strcache
1349 * @param string $string The string to be filtered. Should be plain text, expect
1350 * possibly for multilang tags.
1351 * @param boolean $striplinks To strip any link in the result text. Moodle 1.8 default changed from false to true! MDL-8713
1352 * @param array $options options array/object or courseid
1353 * @return string
1355 function format_string($string, $striplinks = true, $options = null) {
1356 global $CFG, $PAGE;
1358 // We'll use a in-memory cache here to speed up repeated strings.
1359 static $strcache = false;
1361 if (empty($CFG->version) or $CFG->version < 2013051400 or during_initial_install()) {
1362 // Do not filter anything during installation or before upgrade completes.
1363 return $string = strip_tags($string);
1366 if ($strcache === false or count($strcache) > 2000) {
1367 // This number might need some tuning to limit memory usage in cron.
1368 $strcache = array();
1371 if (is_numeric($options)) {
1372 // Legacy courseid usage.
1373 $options = array('context' => context_course::instance($options));
1374 } else {
1375 // Detach object, we can not modify it.
1376 $options = (array)$options;
1379 if (empty($options['context'])) {
1380 // Fallback to $PAGE->context this may be problematic in CLI and other non-standard pages :-(.
1381 $options['context'] = $PAGE->context;
1382 } else if (is_numeric($options['context'])) {
1383 $options['context'] = context::instance_by_id($options['context']);
1386 if (!$options['context']) {
1387 // We did not find any context? weird.
1388 return $string = strip_tags($string);
1391 // Calculate md5.
1392 $md5 = md5($string.'<+>'.$striplinks.'<+>'.$options['context']->id.'<+>'.current_language());
1394 // Fetch from cache if possible.
1395 if (isset($strcache[$md5])) {
1396 return $strcache[$md5];
1399 // First replace all ampersands not followed by html entity code
1400 // Regular expression moved to its own method for easier unit testing.
1401 $string = replace_ampersands_not_followed_by_entity($string);
1403 if (!empty($CFG->filterall)) {
1404 $filtermanager = filter_manager::instance();
1405 $filtermanager->setup_page_for_filters($PAGE, $options['context']); // Setup global stuff filters may have.
1406 $string = $filtermanager->filter_string($string, $options['context']);
1409 // If the site requires it, strip ALL tags from this string.
1410 if (!empty($CFG->formatstringstriptags)) {
1411 $string = str_replace(array('<', '>'), array('&lt;', '&gt;'), strip_tags($string));
1413 } else {
1414 // Otherwise strip just links if that is required (default).
1415 if ($striplinks) {
1416 // Strip links in string.
1417 $string = strip_links($string);
1419 $string = clean_text($string);
1422 // Store to cache.
1423 $strcache[$md5] = $string;
1425 return $string;
1429 * Given a string, performs a negative lookahead looking for any ampersand character
1430 * that is not followed by a proper HTML entity. If any is found, it is replaced
1431 * by &amp;. The string is then returned.
1433 * @param string $string
1434 * @return string
1436 function replace_ampersands_not_followed_by_entity($string) {
1437 return preg_replace("/\&(?![a-zA-Z0-9#]{1,8};)/", "&amp;", $string);
1441 * Given a string, replaces all <a>.*</a> by .* and returns the string.
1443 * @param string $string
1444 * @return string
1446 function strip_links($string) {
1447 return preg_replace('/(<a\s[^>]+?>)(.+?)(<\/a>)/is', '$2', $string);
1451 * This expression turns links into something nice in a text format. (Russell Jungwirth)
1453 * @param string $string
1454 * @return string
1456 function wikify_links($string) {
1457 return preg_replace('~(<a [^<]*href=["|\']?([^ "\']*)["|\']?[^>]*>([^<]*)</a>)~i', '$3 [ $2 ]', $string);
1461 * Given text in a variety of format codings, this function returns the text as plain text suitable for plain email.
1463 * @param string $text The text to be formatted. This is raw text originally from user input.
1464 * @param int $format Identifier of the text format to be used
1465 * [FORMAT_MOODLE, FORMAT_HTML, FORMAT_PLAIN, FORMAT_WIKI, FORMAT_MARKDOWN]
1466 * @return string
1468 function format_text_email($text, $format) {
1470 switch ($format) {
1472 case FORMAT_PLAIN:
1473 return $text;
1474 break;
1476 case FORMAT_WIKI:
1477 // There should not be any of these any more!
1478 $text = wikify_links($text);
1479 return core_text::entities_to_utf8(strip_tags($text), true);
1480 break;
1482 case FORMAT_HTML:
1483 return html_to_text($text);
1484 break;
1486 case FORMAT_MOODLE:
1487 case FORMAT_MARKDOWN:
1488 default:
1489 $text = wikify_links($text);
1490 return core_text::entities_to_utf8(strip_tags($text), true);
1491 break;
1496 * Formats activity intro text
1498 * @param string $module name of module
1499 * @param object $activity instance of activity
1500 * @param int $cmid course module id
1501 * @param bool $filter filter resulting html text
1502 * @return string
1504 function format_module_intro($module, $activity, $cmid, $filter=true) {
1505 global $CFG;
1506 require_once("$CFG->libdir/filelib.php");
1507 $context = context_module::instance($cmid);
1508 $options = array('noclean' => true, 'para' => false, 'filter' => $filter, 'context' => $context, 'overflowdiv' => true);
1509 $intro = file_rewrite_pluginfile_urls($activity->intro, 'pluginfile.php', $context->id, 'mod_'.$module, 'intro', null);
1510 return trim(format_text($intro, $activity->introformat, $options, null));
1514 * Removes the usage of Moodle files from a text.
1516 * In some rare cases we need to re-use a text that already has embedded links
1517 * to some files hosted within Moodle. But the new area in which we will push
1518 * this content does not support files... therefore we need to remove those files.
1520 * @param string $source The text
1521 * @return string The stripped text
1523 function strip_pluginfile_content($source) {
1524 $baseurl = '@@PLUGINFILE@@';
1525 // Looking for something like < .* "@@pluginfile@@.*" .* >
1526 $pattern = '$<[^<>]+["\']' . $baseurl . '[^"\']*["\'][^<>]*>$';
1527 $stripped = preg_replace($pattern, '', $source);
1528 // Use purify html to rebalence potentially mismatched tags and generally cleanup.
1529 return purify_html($stripped);
1533 * Legacy function, used for cleaning of old forum and glossary text only.
1535 * @param string $text text that may contain legacy TRUSTTEXT marker
1536 * @return string text without legacy TRUSTTEXT marker
1538 function trusttext_strip($text) {
1539 while (true) { // Removing nested TRUSTTEXT.
1540 $orig = $text;
1541 $text = str_replace('#####TRUSTTEXT#####', '', $text);
1542 if (strcmp($orig, $text) === 0) {
1543 return $text;
1549 * Must be called before editing of all texts with trust flag. Removes all XSS nasties from texts stored in database if needed.
1551 * @param stdClass $object data object with xxx, xxxformat and xxxtrust fields
1552 * @param string $field name of text field
1553 * @param context $context active context
1554 * @return stdClass updated $object
1556 function trusttext_pre_edit($object, $field, $context) {
1557 $trustfield = $field.'trust';
1558 $formatfield = $field.'format';
1560 if (!$object->$trustfield or !trusttext_trusted($context)) {
1561 $object->$field = clean_text($object->$field, $object->$formatfield);
1564 return $object;
1568 * Is current user trusted to enter no dangerous XSS in this context?
1570 * Please note the user must be in fact trusted everywhere on this server!!
1572 * @param context $context
1573 * @return bool true if user trusted
1575 function trusttext_trusted($context) {
1576 return (trusttext_active() and has_capability('moodle/site:trustcontent', $context));
1580 * Is trusttext feature active?
1582 * @return bool
1584 function trusttext_active() {
1585 global $CFG;
1587 return !empty($CFG->enabletrusttext);
1591 * Cleans raw text removing nasties.
1593 * Given raw text (eg typed in by a user) this function cleans it up and removes any nasty tags that could mess up
1594 * Moodle pages through XSS attacks.
1596 * The result must be used as a HTML text fragment, this function can not cleanup random
1597 * parts of html tags such as url or src attributes.
1599 * NOTE: the format parameter was deprecated because we can safely clean only HTML.
1601 * @param string $text The text to be cleaned
1602 * @param int|string $format deprecated parameter, should always contain FORMAT_HTML or FORMAT_MOODLE
1603 * @param array $options Array of options; currently only option supported is 'allowid' (if true,
1604 * does not remove id attributes when cleaning)
1605 * @return string The cleaned up text
1607 function clean_text($text, $format = FORMAT_HTML, $options = array()) {
1608 $text = (string)$text;
1610 if ($format != FORMAT_HTML and $format != FORMAT_HTML) {
1611 // TODO: we need to standardise cleanup of text when loading it into editor first.
1612 // debugging('clean_text() is designed to work only with html');.
1615 if ($format == FORMAT_PLAIN) {
1616 return $text;
1619 if (is_purify_html_necessary($text)) {
1620 $text = purify_html($text, $options);
1623 // Originally we tried to neutralise some script events here, it was a wrong approach because
1624 // it was trivial to work around that (for example using style based XSS exploits).
1625 // We must not give false sense of security here - all developers MUST understand how to use
1626 // rawurlencode(), htmlentities(), htmlspecialchars(), p(), s(), moodle_url, html_writer and friends!!!
1628 return $text;
1632 * Is it necessary to use HTMLPurifier?
1634 * @private
1635 * @param string $text
1636 * @return bool false means html is safe and valid, true means use HTMLPurifier
1638 function is_purify_html_necessary($text) {
1639 if ($text === '') {
1640 return false;
1643 if ($text === (string)((int)$text)) {
1644 return false;
1647 if (strpos($text, '&') !== false or preg_match('|<[^pesb/]|', $text)) {
1648 // We need to normalise entities or other tags except p, em, strong and br present.
1649 return true;
1652 $altered = htmlspecialchars($text, ENT_NOQUOTES, 'UTF-8', true);
1653 if ($altered === $text) {
1654 // No < > or other special chars means this must be safe.
1655 return false;
1658 // Let's try to convert back some safe html tags.
1659 $altered = preg_replace('|&lt;p&gt;(.*?)&lt;/p&gt;|m', '<p>$1</p>', $altered);
1660 if ($altered === $text) {
1661 return false;
1663 $altered = preg_replace('|&lt;em&gt;([^<>]+?)&lt;/em&gt;|m', '<em>$1</em>', $altered);
1664 if ($altered === $text) {
1665 return false;
1667 $altered = preg_replace('|&lt;strong&gt;([^<>]+?)&lt;/strong&gt;|m', '<strong>$1</strong>', $altered);
1668 if ($altered === $text) {
1669 return false;
1671 $altered = str_replace('&lt;br /&gt;', '<br />', $altered);
1672 if ($altered === $text) {
1673 return false;
1676 return true;
1680 * KSES replacement cleaning function - uses HTML Purifier.
1682 * @param string $text The (X)HTML string to purify
1683 * @param array $options Array of options; currently only option supported is 'allowid' (if set,
1684 * does not remove id attributes when cleaning)
1685 * @return string
1687 function purify_html($text, $options = array()) {
1688 global $CFG;
1690 $text = (string)$text;
1692 static $purifiers = array();
1693 static $caches = array();
1695 // Purifier code can change only during major version upgrade.
1696 $version = empty($CFG->version) ? 0 : $CFG->version;
1697 $cachedir = "$CFG->localcachedir/htmlpurifier/$version";
1698 if (!file_exists($cachedir)) {
1699 // Purging of caches may remove the cache dir at any time,
1700 // luckily file_exists() results should be cached for all existing directories.
1701 $purifiers = array();
1702 $caches = array();
1703 gc_collect_cycles();
1705 make_localcache_directory('htmlpurifier', false);
1706 check_dir_exists($cachedir);
1709 $allowid = empty($options['allowid']) ? 0 : 1;
1710 $allowobjectembed = empty($CFG->allowobjectembed) ? 0 : 1;
1712 $type = 'type_'.$allowid.'_'.$allowobjectembed;
1714 if (!array_key_exists($type, $caches)) {
1715 $caches[$type] = cache::make('core', 'htmlpurifier', array('type' => $type));
1717 $cache = $caches[$type];
1719 // Add revision number and all options to the text key so that it is compatible with local cluster node caches.
1720 $key = "|$version|$allowobjectembed|$allowid|$text";
1721 $filteredtext = $cache->get($key);
1723 if ($filteredtext === true) {
1724 // The filtering did not change the text last time, no need to filter anything again.
1725 return $text;
1726 } else if ($filteredtext !== false) {
1727 return $filteredtext;
1730 if (empty($purifiers[$type])) {
1731 require_once $CFG->libdir.'/htmlpurifier/HTMLPurifier.safe-includes.php';
1732 require_once $CFG->libdir.'/htmlpurifier/locallib.php';
1733 $config = HTMLPurifier_Config::createDefault();
1735 $config->set('HTML.DefinitionID', 'moodlehtml');
1736 $config->set('HTML.DefinitionRev', 3);
1737 $config->set('Cache.SerializerPath', $cachedir);
1738 $config->set('Cache.SerializerPermissions', $CFG->directorypermissions);
1739 $config->set('Core.NormalizeNewlines', false);
1740 $config->set('Core.ConvertDocumentToFragment', true);
1741 $config->set('Core.Encoding', 'UTF-8');
1742 $config->set('HTML.Doctype', 'XHTML 1.0 Transitional');
1743 $config->set('URI.AllowedSchemes', array(
1744 'http' => true,
1745 'https' => true,
1746 'ftp' => true,
1747 'irc' => true,
1748 'nntp' => true,
1749 'news' => true,
1750 'rtsp' => true,
1751 'rtmp' => true,
1752 'teamspeak' => true,
1753 'gopher' => true,
1754 'mms' => true,
1755 'mailto' => true
1757 $config->set('Attr.AllowedFrameTargets', array('_blank'));
1759 if ($allowobjectembed) {
1760 $config->set('HTML.SafeObject', true);
1761 $config->set('Output.FlashCompat', true);
1762 $config->set('HTML.SafeEmbed', true);
1765 if ($allowid) {
1766 $config->set('Attr.EnableID', true);
1769 if ($def = $config->maybeGetRawHTMLDefinition()) {
1770 $def->addElement('nolink', 'Block', 'Flow', array()); // Skip our filters inside.
1771 $def->addElement('tex', 'Inline', 'Inline', array()); // Tex syntax, equivalent to $$xx$$.
1772 $def->addElement('algebra', 'Inline', 'Inline', array()); // Algebra syntax, equivalent to @@xx@@.
1773 $def->addElement('lang', 'Block', 'Flow', array(), array('lang'=>'CDATA')); // Original multilang style - only our hacked lang attribute.
1774 $def->addAttribute('span', 'xxxlang', 'CDATA'); // Current very problematic multilang.
1776 // Use the built-in Ruby module to add annotation support.
1777 $def->manager->addModule(new HTMLPurifier_HTMLModule_Ruby());
1780 $purifier = new HTMLPurifier($config);
1781 $purifiers[$type] = $purifier;
1782 } else {
1783 $purifier = $purifiers[$type];
1786 $multilang = (strpos($text, 'class="multilang"') !== false);
1788 $filteredtext = $text;
1789 if ($multilang) {
1790 $filteredtextregex = '/<span(\s+lang="([a-zA-Z0-9_-]+)"|\s+class="multilang"){2}\s*>/';
1791 $filteredtext = preg_replace($filteredtextregex, '<span xxxlang="${2}">', $filteredtext);
1793 $filteredtext = (string)$purifier->purify($filteredtext);
1794 if ($multilang) {
1795 $filteredtext = preg_replace('/<span xxxlang="([a-zA-Z0-9_-]+)">/', '<span lang="${1}" class="multilang">', $filteredtext);
1798 if ($text === $filteredtext) {
1799 // No need to store the filtered text, next time we will just return unfiltered text
1800 // because it was not changed by purifying.
1801 $cache->set($key, true);
1802 } else {
1803 $cache->set($key, $filteredtext);
1806 return $filteredtext;
1810 * Given plain text, makes it into HTML as nicely as possible.
1812 * May contain HTML tags already.
1814 * Do not abuse this function. It is intended as lower level formatting feature used
1815 * by {@link format_text()} to convert FORMAT_MOODLE to HTML. You are supposed
1816 * to call format_text() in most of cases.
1818 * @param string $text The string to convert.
1819 * @param boolean $smileyignored Was used to determine if smiley characters should convert to smiley images, ignored now
1820 * @param boolean $para If true then the returned string will be wrapped in div tags
1821 * @param boolean $newlines If true then lines newline breaks will be converted to HTML newline breaks.
1822 * @return string
1824 function text_to_html($text, $smileyignored = null, $para = true, $newlines = true) {
1825 // Remove any whitespace that may be between HTML tags.
1826 $text = preg_replace("~>([[:space:]]+)<~i", "><", $text);
1828 // Remove any returns that precede or follow HTML tags.
1829 $text = preg_replace("~([\n\r])<~i", " <", $text);
1830 $text = preg_replace("~>([\n\r])~i", "> ", $text);
1832 // Make returns into HTML newlines.
1833 if ($newlines) {
1834 $text = nl2br($text);
1837 // Wrap the whole thing in a div if required.
1838 if ($para) {
1839 // In 1.9 this was changed from a p => div.
1840 return '<div class="text_to_html">'.$text.'</div>';
1841 } else {
1842 return $text;
1847 * Given Markdown formatted text, make it into XHTML using external function
1849 * @param string $text The markdown formatted text to be converted.
1850 * @return string Converted text
1852 function markdown_to_html($text) {
1853 global $CFG;
1855 if ($text === '' or $text === null) {
1856 return $text;
1859 require_once($CFG->libdir .'/markdown/MarkdownInterface.php');
1860 require_once($CFG->libdir .'/markdown/Markdown.php');
1861 require_once($CFG->libdir .'/markdown/MarkdownExtra.php');
1863 return \Michelf\MarkdownExtra::defaultTransform($text);
1867 * Given HTML text, make it into plain text using external function
1869 * @param string $html The text to be converted.
1870 * @param integer $width Width to wrap the text at. (optional, default 75 which
1871 * is a good value for email. 0 means do not limit line length.)
1872 * @param boolean $dolinks By default, any links in the HTML are collected, and
1873 * printed as a list at the end of the HTML. If you don't want that, set this
1874 * argument to false.
1875 * @return string plain text equivalent of the HTML.
1877 function html_to_text($html, $width = 75, $dolinks = true) {
1879 global $CFG;
1881 require_once($CFG->libdir .'/html2text.php');
1883 $h2t = new html2text($html, false, $dolinks, $width);
1884 $result = $h2t->get_text();
1886 return $result;
1890 * This function will highlight search words in a given string
1892 * It cares about HTML and will not ruin links. It's best to use
1893 * this function after performing any conversions to HTML.
1895 * @param string $needle The search string. Syntax like "word1 +word2 -word3" is dealt with correctly.
1896 * @param string $haystack The string (HTML) within which to highlight the search terms.
1897 * @param boolean $matchcase whether to do case-sensitive. Default case-insensitive.
1898 * @param string $prefix the string to put before each search term found.
1899 * @param string $suffix the string to put after each search term found.
1900 * @return string The highlighted HTML.
1902 function highlight($needle, $haystack, $matchcase = false,
1903 $prefix = '<span class="highlight">', $suffix = '</span>') {
1905 // Quick bail-out in trivial cases.
1906 if (empty($needle) or empty($haystack)) {
1907 return $haystack;
1910 // Break up the search term into words, discard any -words and build a regexp.
1911 $words = preg_split('/ +/', trim($needle));
1912 foreach ($words as $index => $word) {
1913 if (strpos($word, '-') === 0) {
1914 unset($words[$index]);
1915 } else if (strpos($word, '+') === 0) {
1916 $words[$index] = '\b' . preg_quote(ltrim($word, '+'), '/') . '\b'; // Match only as a complete word.
1917 } else {
1918 $words[$index] = preg_quote($word, '/');
1921 $regexp = '/(' . implode('|', $words) . ')/u'; // Char u is to do UTF-8 matching.
1922 if (!$matchcase) {
1923 $regexp .= 'i';
1926 // Another chance to bail-out if $search was only -words.
1927 if (empty($words)) {
1928 return $haystack;
1931 // Split the string into HTML tags and real content.
1932 $chunks = preg_split('/((?:<[^>]*>)+)/', $haystack, -1, PREG_SPLIT_DELIM_CAPTURE);
1934 // We have an array of alternating blocks of text, then HTML tags, then text, ...
1935 // Loop through replacing search terms in the text, and leaving the HTML unchanged.
1936 $ishtmlchunk = false;
1937 $result = '';
1938 foreach ($chunks as $chunk) {
1939 if ($ishtmlchunk) {
1940 $result .= $chunk;
1941 } else {
1942 $result .= preg_replace($regexp, $prefix . '$1' . $suffix, $chunk);
1944 $ishtmlchunk = !$ishtmlchunk;
1947 return $result;
1951 * This function will highlight instances of $needle in $haystack
1953 * It's faster that the above function {@link highlight()} and doesn't care about
1954 * HTML or anything.
1956 * @param string $needle The string to search for
1957 * @param string $haystack The string to search for $needle in
1958 * @return string The highlighted HTML
1960 function highlightfast($needle, $haystack) {
1962 if (empty($needle) or empty($haystack)) {
1963 return $haystack;
1966 $parts = explode(core_text::strtolower($needle), core_text::strtolower($haystack));
1968 if (count($parts) === 1) {
1969 return $haystack;
1972 $pos = 0;
1974 foreach ($parts as $key => $part) {
1975 $parts[$key] = substr($haystack, $pos, strlen($part));
1976 $pos += strlen($part);
1978 $parts[$key] .= '<span class="highlight">'.substr($haystack, $pos, strlen($needle)).'</span>';
1979 $pos += strlen($needle);
1982 return str_replace('<span class="highlight"></span>', '', join('', $parts));
1986 * Return a string containing 'lang', xml:lang and optionally 'dir' HTML attributes.
1988 * Internationalisation, for print_header and backup/restorelib.
1990 * @param bool $dir Default false
1991 * @return string Attributes
1993 function get_html_lang($dir = false) {
1994 $direction = '';
1995 if ($dir) {
1996 if (right_to_left()) {
1997 $direction = ' dir="rtl"';
1998 } else {
1999 $direction = ' dir="ltr"';
2002 // Accessibility: added the 'lang' attribute to $direction, used in theme <html> tag.
2003 $language = str_replace('_', '-', current_language());
2004 @header('Content-Language: '.$language);
2005 return ($direction.' lang="'.$language.'" xml:lang="'.$language.'"');
2009 // STANDARD WEB PAGE PARTS.
2012 * Send the HTTP headers that Moodle requires.
2014 * There is a backwards compatibility hack for legacy code
2015 * that needs to add custom IE compatibility directive.
2017 * Example:
2018 * <code>
2019 * if (!isset($CFG->additionalhtmlhead)) {
2020 * $CFG->additionalhtmlhead = '';
2022 * $CFG->additionalhtmlhead .= '<meta http-equiv="X-UA-Compatible" content="IE=8" />';
2023 * header('X-UA-Compatible: IE=8');
2024 * echo $OUTPUT->header();
2025 * </code>
2027 * Please note the $CFG->additionalhtmlhead alone might not work,
2028 * you should send the IE compatibility header() too.
2030 * @param string $contenttype
2031 * @param bool $cacheable Can this page be cached on back?
2032 * @return void, sends HTTP headers
2034 function send_headers($contenttype, $cacheable = true) {
2035 global $CFG;
2037 @header('Content-Type: ' . $contenttype);
2038 @header('Content-Script-Type: text/javascript');
2039 @header('Content-Style-Type: text/css');
2041 if (empty($CFG->additionalhtmlhead) or stripos($CFG->additionalhtmlhead, 'X-UA-Compatible') === false) {
2042 @header('X-UA-Compatible: IE=edge');
2045 if ($cacheable) {
2046 // Allow caching on "back" (but not on normal clicks).
2047 @header('Cache-Control: private, pre-check=0, post-check=0, max-age=0, no-transform');
2048 @header('Pragma: no-cache');
2049 @header('Expires: ');
2050 } else {
2051 // Do everything we can to always prevent clients and proxies caching.
2052 @header('Cache-Control: no-store, no-cache, must-revalidate');
2053 @header('Cache-Control: post-check=0, pre-check=0, no-transform', false);
2054 @header('Pragma: no-cache');
2055 @header('Expires: Mon, 20 Aug 1969 09:23:00 GMT');
2056 @header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
2058 @header('Accept-Ranges: none');
2060 if (empty($CFG->allowframembedding)) {
2061 @header('X-Frame-Options: sameorigin');
2066 * Return the right arrow with text ('next'), and optionally embedded in a link.
2068 * @param string $text HTML/plain text label (set to blank only for breadcrumb separator cases).
2069 * @param string $url An optional link to use in a surrounding HTML anchor.
2070 * @param bool $accesshide True if text should be hidden (for screen readers only).
2071 * @param string $addclass Additional class names for the link, or the arrow character.
2072 * @return string HTML string.
2074 function link_arrow_right($text, $url='', $accesshide=false, $addclass='') {
2075 global $OUTPUT; // TODO: move to output renderer.
2076 $arrowclass = 'arrow ';
2077 if (!$url) {
2078 $arrowclass .= $addclass;
2080 $arrow = '<span class="'.$arrowclass.'">'.$OUTPUT->rarrow().'</span>';
2081 $htmltext = '';
2082 if ($text) {
2083 $htmltext = '<span class="arrow_text">'.$text.'</span>&nbsp;';
2084 if ($accesshide) {
2085 $htmltext = get_accesshide($htmltext);
2088 if ($url) {
2089 $class = 'arrow_link';
2090 if ($addclass) {
2091 $class .= ' '.$addclass;
2093 return '<a class="'.$class.'" href="'.$url.'" title="'.preg_replace('/<.*?>/', '', $text).'">'.$htmltext.$arrow.'</a>';
2095 return $htmltext.$arrow;
2099 * Return the left arrow with text ('previous'), and optionally embedded in a link.
2101 * @param string $text HTML/plain text label (set to blank only for breadcrumb separator cases).
2102 * @param string $url An optional link to use in a surrounding HTML anchor.
2103 * @param bool $accesshide True if text should be hidden (for screen readers only).
2104 * @param string $addclass Additional class names for the link, or the arrow character.
2105 * @return string HTML string.
2107 function link_arrow_left($text, $url='', $accesshide=false, $addclass='') {
2108 global $OUTPUT; // TODO: move to utput renderer.
2109 $arrowclass = 'arrow ';
2110 if (! $url) {
2111 $arrowclass .= $addclass;
2113 $arrow = '<span class="'.$arrowclass.'">'.$OUTPUT->larrow().'</span>';
2114 $htmltext = '';
2115 if ($text) {
2116 $htmltext = '&nbsp;<span class="arrow_text">'.$text.'</span>';
2117 if ($accesshide) {
2118 $htmltext = get_accesshide($htmltext);
2121 if ($url) {
2122 $class = 'arrow_link';
2123 if ($addclass) {
2124 $class .= ' '.$addclass;
2126 return '<a class="'.$class.'" href="'.$url.'" title="'.preg_replace('/<.*?>/', '', $text).'">'.$arrow.$htmltext.'</a>';
2128 return $arrow.$htmltext;
2132 * Return a HTML element with the class "accesshide", for accessibility.
2134 * Please use cautiously - where possible, text should be visible!
2136 * @param string $text Plain text.
2137 * @param string $elem Lowercase element name, default "span".
2138 * @param string $class Additional classes for the element.
2139 * @param string $attrs Additional attributes string in the form, "name='value' name2='value2'"
2140 * @return string HTML string.
2142 function get_accesshide($text, $elem='span', $class='', $attrs='') {
2143 return "<$elem class=\"accesshide $class\" $attrs>$text</$elem>";
2147 * Return the breadcrumb trail navigation separator.
2149 * @return string HTML string.
2151 function get_separator() {
2152 // Accessibility: the 'hidden' slash is preferred for screen readers.
2153 return ' '.link_arrow_right($text='/', $url='', $accesshide=true, 'sep').' ';
2157 * Print (or return) a collapsible region, that has a caption that can be clicked to expand or collapse the region.
2159 * If JavaScript is off, then the region will always be expanded.
2161 * @param string $contents the contents of the box.
2162 * @param string $classes class names added to the div that is output.
2163 * @param string $id id added to the div that is output. Must not be blank.
2164 * @param string $caption text displayed at the top. Clicking on this will cause the region to expand or contract.
2165 * @param string $userpref the name of the user preference that stores the user's preferred default state.
2166 * (May be blank if you do not wish the state to be persisted.
2167 * @param boolean $default Initial collapsed state to use if the user_preference it not set.
2168 * @param boolean $return if true, return the HTML as a string, rather than printing it.
2169 * @return string|void If $return is false, returns nothing, otherwise returns a string of HTML.
2171 function print_collapsible_region($contents, $classes, $id, $caption, $userpref = '', $default = false, $return = false) {
2172 $output = print_collapsible_region_start($classes, $id, $caption, $userpref, $default, true);
2173 $output .= $contents;
2174 $output .= print_collapsible_region_end(true);
2176 if ($return) {
2177 return $output;
2178 } else {
2179 echo $output;
2184 * Print (or return) the start of a collapsible region
2186 * The collapsibleregion has a caption that can be clicked to expand or collapse the region. If JavaScript is off, then the region
2187 * will always be expanded.
2189 * @param string $classes class names added to the div that is output.
2190 * @param string $id id added to the div that is output. Must not be blank.
2191 * @param string $caption text displayed at the top. Clicking on this will cause the region to expand or contract.
2192 * @param string $userpref the name of the user preference that stores the user's preferred default state.
2193 * (May be blank if you do not wish the state to be persisted.
2194 * @param boolean $default Initial collapsed state to use if the user_preference it not set.
2195 * @param boolean $return if true, return the HTML as a string, rather than printing it.
2196 * @return string|void if $return is false, returns nothing, otherwise returns a string of HTML.
2198 function print_collapsible_region_start($classes, $id, $caption, $userpref = '', $default = false, $return = false) {
2199 global $PAGE;
2201 // Work out the initial state.
2202 if (!empty($userpref) and is_string($userpref)) {
2203 user_preference_allow_ajax_update($userpref, PARAM_BOOL);
2204 $collapsed = get_user_preferences($userpref, $default);
2205 } else {
2206 $collapsed = $default;
2207 $userpref = false;
2210 if ($collapsed) {
2211 $classes .= ' collapsed';
2214 $output = '';
2215 $output .= '<div id="' . $id . '" class="collapsibleregion ' . $classes . '">';
2216 $output .= '<div id="' . $id . '_sizer">';
2217 $output .= '<div id="' . $id . '_caption" class="collapsibleregioncaption">';
2218 $output .= $caption . ' ';
2219 $output .= '</div><div id="' . $id . '_inner" class="collapsibleregioninner">';
2220 $PAGE->requires->js_init_call('M.util.init_collapsible_region', array($id, $userpref, get_string('clicktohideshow')));
2222 if ($return) {
2223 return $output;
2224 } else {
2225 echo $output;
2230 * Close a region started with print_collapsible_region_start.
2232 * @param boolean $return if true, return the HTML as a string, rather than printing it.
2233 * @return string|void if $return is false, returns nothing, otherwise returns a string of HTML.
2235 function print_collapsible_region_end($return = false) {
2236 $output = '</div></div></div>';
2238 if ($return) {
2239 return $output;
2240 } else {
2241 echo $output;
2246 * Print a specified group's avatar.
2248 * @param array|stdClass $group A single {@link group} object OR array of groups.
2249 * @param int $courseid The course ID.
2250 * @param boolean $large Default small picture, or large.
2251 * @param boolean $return If false print picture, otherwise return the output as string
2252 * @param boolean $link Enclose image in a link to view specified course?
2253 * @return string|void Depending on the setting of $return
2255 function print_group_picture($group, $courseid, $large=false, $return=false, $link=true) {
2256 global $CFG;
2258 if (is_array($group)) {
2259 $output = '';
2260 foreach ($group as $g) {
2261 $output .= print_group_picture($g, $courseid, $large, true, $link);
2263 if ($return) {
2264 return $output;
2265 } else {
2266 echo $output;
2267 return;
2271 $context = context_course::instance($courseid);
2273 // If there is no picture, do nothing.
2274 if (!$group->picture) {
2275 return '';
2278 // If picture is hidden, only show to those with course:managegroups.
2279 if ($group->hidepicture and !has_capability('moodle/course:managegroups', $context)) {
2280 return '';
2283 if ($link or has_capability('moodle/site:accessallgroups', $context)) {
2284 $output = '<a href="'. $CFG->wwwroot .'/user/index.php?id='. $courseid .'&amp;group='. $group->id .'">';
2285 } else {
2286 $output = '';
2288 if ($large) {
2289 $file = 'f1';
2290 } else {
2291 $file = 'f2';
2294 $grouppictureurl = moodle_url::make_pluginfile_url($context->id, 'group', 'icon', $group->id, '/', $file);
2295 $grouppictureurl->param('rev', $group->picture);
2296 $output .= '<img class="grouppicture" src="'.$grouppictureurl.'"'.
2297 ' alt="'.s(get_string('group').' '.$group->name).'" title="'.s($group->name).'"/>';
2299 if ($link or has_capability('moodle/site:accessallgroups', $context)) {
2300 $output .= '</a>';
2303 if ($return) {
2304 return $output;
2305 } else {
2306 echo $output;
2312 * Display a recent activity note
2314 * @staticvar string $strftimerecent
2315 * @param int $time A timestamp int.
2316 * @param stdClass $user A user object from the database.
2317 * @param string $text Text for display for the note
2318 * @param string $link The link to wrap around the text
2319 * @param bool $return If set to true the HTML is returned rather than echo'd
2320 * @param string $viewfullnames
2321 * @return string If $retrun was true returns HTML for a recent activity notice.
2323 function print_recent_activity_note($time, $user, $text, $link, $return=false, $viewfullnames=null) {
2324 static $strftimerecent = null;
2325 $output = '';
2327 if (is_null($viewfullnames)) {
2328 $context = context_system::instance();
2329 $viewfullnames = has_capability('moodle/site:viewfullnames', $context);
2332 if (is_null($strftimerecent)) {
2333 $strftimerecent = get_string('strftimerecent');
2336 $output .= '<div class="head">';
2337 $output .= '<div class="date">'.userdate($time, $strftimerecent).'</div>';
2338 $output .= '<div class="name">'.fullname($user, $viewfullnames).'</div>';
2339 $output .= '</div>';
2340 $output .= '<div class="info"><a href="'.$link.'">'.format_string($text, true).'</a></div>';
2342 if ($return) {
2343 return $output;
2344 } else {
2345 echo $output;
2350 * Returns a popup menu with course activity modules
2352 * Given a course this function returns a small popup menu with all the course activity modules in it, as a navigation menu
2353 * outputs a simple list structure in XHTML.
2354 * The data is taken from the serialised array stored in the course record.
2356 * @param course $course A {@link $COURSE} object.
2357 * @param array $sections
2358 * @param course_modinfo $modinfo
2359 * @param string $strsection
2360 * @param string $strjumpto
2361 * @param int $width
2362 * @param string $cmid
2363 * @return string The HTML block
2365 function navmenulist($course, $sections, $modinfo, $strsection, $strjumpto, $width=50, $cmid=0) {
2367 global $CFG, $OUTPUT;
2369 $section = -1;
2370 $menu = array();
2371 $doneheading = false;
2373 $courseformatoptions = course_get_format($course)->get_format_options();
2374 $coursecontext = context_course::instance($course->id);
2376 $menu[] = '<ul class="navmenulist"><li class="jumpto section"><span>'.$strjumpto.'</span><ul>';
2377 foreach ($modinfo->cms as $mod) {
2378 if (!$mod->has_view()) {
2379 // Don't show modules which you can't link to!
2380 continue;
2383 // For course formats using 'numsections' do not show extra sections.
2384 if (isset($courseformatoptions['numsections']) && $mod->sectionnum > $courseformatoptions['numsections']) {
2385 break;
2388 if (!$mod->uservisible) { // Do not icnlude empty sections at all.
2389 continue;
2392 if ($mod->sectionnum >= 0 and $section != $mod->sectionnum) {
2393 $thissection = $sections[$mod->sectionnum];
2395 if ($thissection->visible or
2396 (isset($courseformatoptions['hiddensections']) and !$courseformatoptions['hiddensections']) or
2397 has_capability('moodle/course:viewhiddensections', $coursecontext)) {
2398 $thissection->summary = strip_tags(format_string($thissection->summary, true));
2399 if (!$doneheading) {
2400 $menu[] = '</ul></li>';
2402 if ($course->format == 'weeks' or empty($thissection->summary)) {
2403 $item = $strsection ." ". $mod->sectionnum;
2404 } else {
2405 if (core_text::strlen($thissection->summary) < ($width-3)) {
2406 $item = $thissection->summary;
2407 } else {
2408 $item = core_text::substr($thissection->summary, 0, $width).'...';
2411 $menu[] = '<li class="section"><span>'.$item.'</span>';
2412 $menu[] = '<ul>';
2413 $doneheading = true;
2415 $section = $mod->sectionnum;
2416 } else {
2417 // No activities from this hidden section shown.
2418 continue;
2422 $url = $mod->modname .'/view.php?id='. $mod->id;
2423 $mod->name = strip_tags(format_string($mod->name ,true));
2424 if (core_text::strlen($mod->name) > ($width+5)) {
2425 $mod->name = core_text::substr($mod->name, 0, $width).'...';
2427 if (!$mod->visible) {
2428 $mod->name = '('.$mod->name.')';
2430 $class = 'activity '.$mod->modname;
2431 $class .= ($cmid == $mod->id) ? ' selected' : '';
2432 $menu[] = '<li class="'.$class.'">'.
2433 '<img src="'.$OUTPUT->pix_url('icon', $mod->modname) . '" alt="" />'.
2434 '<a href="'.$CFG->wwwroot.'/mod/'.$url.'">'.$mod->name.'</a></li>';
2437 if ($doneheading) {
2438 $menu[] = '</ul></li>';
2440 $menu[] = '</ul></li></ul>';
2442 return implode("\n", $menu);
2446 * Prints a grade menu (as part of an existing form) with help showing all possible numerical grades and scales.
2448 * @todo Finish documenting this function
2449 * @todo Deprecate: this is only used in a few contrib modules
2451 * @param int $courseid The course ID
2452 * @param string $name
2453 * @param string $current
2454 * @param boolean $includenograde Include those with no grades
2455 * @param boolean $return If set to true returns rather than echo's
2456 * @return string|bool Depending on value of $return
2458 function print_grade_menu($courseid, $name, $current, $includenograde=true, $return=false) {
2459 global $OUTPUT;
2461 $output = '';
2462 $strscale = get_string('scale');
2463 $strscales = get_string('scales');
2465 $scales = get_scales_menu($courseid);
2466 foreach ($scales as $i => $scalename) {
2467 $grades[-$i] = $strscale .': '. $scalename;
2469 if ($includenograde) {
2470 $grades[0] = get_string('nograde');
2472 for ($i=100; $i>=1; $i--) {
2473 $grades[$i] = $i;
2475 $output .= html_writer::select($grades, $name, $current, false);
2477 $helppix = $OUTPUT->pix_url('help');
2478 $linkobject = '<span class="helplink"><img class="iconhelp" alt="'.$strscales.'" src="'.$helppix.'" /></span>';
2479 $link = new moodle_url('/course/scales.php', array('id' => $courseid, 'list' => 1));
2480 $action = new popup_action('click', $link, 'ratingscales', array('height' => 400, 'width' => 500));
2481 $output .= $OUTPUT->action_link($link, $linkobject, $action, array('title' => $strscales));
2483 if ($return) {
2484 return $output;
2485 } else {
2486 echo $output;
2491 * Print an error to STDOUT and exit with a non-zero code. For commandline scripts.
2493 * Default errorcode is 1.
2495 * Very useful for perl-like error-handling:
2496 * do_somethting() or mdie("Something went wrong");
2498 * @param string $msg Error message
2499 * @param integer $errorcode Error code to emit
2501 function mdie($msg='', $errorcode=1) {
2502 trigger_error($msg);
2503 exit($errorcode);
2507 * Print a message and exit.
2509 * @param string $message The message to print in the notice
2510 * @param string $link The link to use for the continue button
2511 * @param object $course A course object. Unused.
2512 * @return void This function simply exits
2514 function notice ($message, $link='', $course=null) {
2515 global $PAGE, $OUTPUT;
2517 $message = clean_text($message); // In case nasties are in here.
2519 if (CLI_SCRIPT) {
2520 echo("!!$message!!\n");
2521 exit(1); // No success.
2524 if (!$PAGE->headerprinted) {
2525 // Header not yet printed.
2526 $PAGE->set_title(get_string('notice'));
2527 echo $OUTPUT->header();
2528 } else {
2529 echo $OUTPUT->container_end_all(false);
2532 echo $OUTPUT->box($message, 'generalbox', 'notice');
2533 echo $OUTPUT->continue_button($link);
2535 echo $OUTPUT->footer();
2536 exit(1); // General error code.
2540 * Redirects the user to another page, after printing a notice.
2542 * This function calls the OUTPUT redirect method, echo's the output and then dies to ensure nothing else happens.
2544 * <strong>Good practice:</strong> You should call this method before starting page
2545 * output by using any of the OUTPUT methods.
2547 * @param moodle_url|string $url A moodle_url to redirect to. Strings are not to be trusted!
2548 * @param string $message The message to display to the user
2549 * @param int $delay The delay before redirecting
2550 * @throws moodle_exception
2552 function redirect($url, $message='', $delay=-1) {
2553 global $OUTPUT, $PAGE, $CFG;
2555 if (CLI_SCRIPT or AJAX_SCRIPT) {
2556 // This is wrong - developers should not use redirect in these scripts but it should not be very likely.
2557 throw new moodle_exception('redirecterrordetected', 'error');
2560 // Prevent debug errors - make sure context is properly initialised.
2561 if ($PAGE) {
2562 $PAGE->set_context(null);
2563 $PAGE->set_pagelayout('redirect'); // No header and footer needed.
2564 $PAGE->set_title(get_string('pageshouldredirect', 'moodle'));
2567 if ($url instanceof moodle_url) {
2568 $url = $url->out(false);
2571 $debugdisableredirect = false;
2572 do {
2573 if (defined('DEBUGGING_PRINTED')) {
2574 // Some debugging already printed, no need to look more.
2575 $debugdisableredirect = true;
2576 break;
2579 if (core_useragent::is_msword()) {
2580 // Clicking a URL from MS Word sends a request to the server without cookies. If that
2581 // causes a redirect Word will open a browser pointing the new URL. If not, the URL that
2582 // was clicked is opened. Because the request from Word is without cookies, it almost
2583 // always results in a redirect to the login page, even if the user is logged in in their
2584 // browser. This is not what we want, so prevent the redirect for requests from Word.
2585 $debugdisableredirect = true;
2586 break;
2589 if (empty($CFG->debugdisplay) or empty($CFG->debug)) {
2590 // No errors should be displayed.
2591 break;
2594 if (!function_exists('error_get_last') or !$lasterror = error_get_last()) {
2595 break;
2598 if (!($lasterror['type'] & $CFG->debug)) {
2599 // Last error not interesting.
2600 break;
2603 // Watch out here, @hidden() errors are returned from error_get_last() too.
2604 if (headers_sent()) {
2605 // We already started printing something - that means errors likely printed.
2606 $debugdisableredirect = true;
2607 break;
2610 if (ob_get_level() and ob_get_contents()) {
2611 // There is something waiting to be printed, hopefully it is the errors,
2612 // but it might be some error hidden by @ too - such as the timezone mess from setup.php.
2613 $debugdisableredirect = true;
2614 break;
2616 } while (false);
2618 // Technically, HTTP/1.1 requires Location: header to contain the absolute path.
2619 // (In practice browsers accept relative paths - but still, might as well do it properly.)
2620 // This code turns relative into absolute.
2621 if (!preg_match('|^[a-z]+:|i', $url)) {
2622 // Get host name http://www.wherever.com.
2623 $hostpart = preg_replace('|^(.*?[^:/])/.*$|', '$1', $CFG->wwwroot);
2624 if (preg_match('|^/|', $url)) {
2625 // URLs beginning with / are relative to web server root so we just add them in.
2626 $url = $hostpart.$url;
2627 } else {
2628 // URLs not beginning with / are relative to path of current script, so add that on.
2629 $url = $hostpart.preg_replace('|\?.*$|', '', me()).'/../'.$url;
2631 // Replace all ..s.
2632 while (true) {
2633 $newurl = preg_replace('|/(?!\.\.)[^/]*/\.\./|', '/', $url);
2634 if ($newurl == $url) {
2635 break;
2637 $url = $newurl;
2641 // Sanitise url - we can not rely on moodle_url or our URL cleaning
2642 // because they do not support all valid external URLs.
2643 $url = preg_replace('/[\x00-\x1F\x7F]/', '', $url);
2644 $url = str_replace('"', '%22', $url);
2645 $encodedurl = preg_replace("/\&(?![a-zA-Z0-9#]{1,8};)/", "&amp;", $url);
2646 $encodedurl = preg_replace('/^.*href="([^"]*)".*$/', "\\1", clean_text('<a href="'.$encodedurl.'" />', FORMAT_HTML));
2647 $url = str_replace('&amp;', '&', $encodedurl);
2649 if (!empty($message)) {
2650 if ($delay === -1 || !is_numeric($delay)) {
2651 $delay = 3;
2653 $message = clean_text($message);
2654 } else {
2655 $message = get_string('pageshouldredirect');
2656 $delay = 0;
2659 // Make sure the session is closed properly, this prevents problems in IIS
2660 // and also some potential PHP shutdown issues.
2661 \core\session\manager::write_close();
2663 if ($delay == 0 && !$debugdisableredirect && !headers_sent()) {
2664 // 302 might not work for POST requests, 303 is ignored by obsolete clients.
2665 @header($_SERVER['SERVER_PROTOCOL'] . ' 303 See Other');
2666 @header('Location: '.$url);
2667 echo bootstrap_renderer::plain_redirect_message($encodedurl);
2668 exit;
2671 // Include a redirect message, even with a HTTP redirect, because that is recommended practice.
2672 if ($PAGE) {
2673 $CFG->docroot = false; // To prevent the link to moodle docs from being displayed on redirect page.
2674 echo $OUTPUT->redirect_message($encodedurl, $message, $delay, $debugdisableredirect);
2675 exit;
2676 } else {
2677 echo bootstrap_renderer::early_redirect_message($encodedurl, $message, $delay);
2678 exit;
2683 * Given an email address, this function will return an obfuscated version of it.
2685 * @param string $email The email address to obfuscate
2686 * @return string The obfuscated email address
2688 function obfuscate_email($email) {
2689 $i = 0;
2690 $length = strlen($email);
2691 $obfuscated = '';
2692 while ($i < $length) {
2693 if (rand(0, 2) && $email{$i}!='@') { // MDL-20619 some browsers have problems unobfuscating @.
2694 $obfuscated.='%'.dechex(ord($email{$i}));
2695 } else {
2696 $obfuscated.=$email{$i};
2698 $i++;
2700 return $obfuscated;
2704 * This function takes some text and replaces about half of the characters
2705 * with HTML entity equivalents. Return string is obviously longer.
2707 * @param string $plaintext The text to be obfuscated
2708 * @return string The obfuscated text
2710 function obfuscate_text($plaintext) {
2711 $i=0;
2712 $length = core_text::strlen($plaintext);
2713 $obfuscated='';
2714 $prevobfuscated = false;
2715 while ($i < $length) {
2716 $char = core_text::substr($plaintext, $i, 1);
2717 $ord = core_text::utf8ord($char);
2718 $numerical = ($ord >= ord('0')) && ($ord <= ord('9'));
2719 if ($prevobfuscated and $numerical ) {
2720 $obfuscated.='&#'.$ord.';';
2721 } else if (rand(0, 2)) {
2722 $obfuscated.='&#'.$ord.';';
2723 $prevobfuscated = true;
2724 } else {
2725 $obfuscated.=$char;
2726 $prevobfuscated = false;
2728 $i++;
2730 return $obfuscated;
2734 * This function uses the {@link obfuscate_email()} and {@link obfuscate_text()}
2735 * to generate a fully obfuscated email link, ready to use.
2737 * @param string $email The email address to display
2738 * @param string $label The text to displayed as hyperlink to $email
2739 * @param boolean $dimmed If true then use css class 'dimmed' for hyperlink
2740 * @param string $subject The subject of the email in the mailto link
2741 * @param string $body The content of the email in the mailto link
2742 * @return string The obfuscated mailto link
2744 function obfuscate_mailto($email, $label='', $dimmed=false, $subject = '', $body = '') {
2746 if (empty($label)) {
2747 $label = $email;
2750 $label = obfuscate_text($label);
2751 $email = obfuscate_email($email);
2752 $mailto = obfuscate_text('mailto');
2753 $url = new moodle_url("mailto:$email");
2754 $attrs = array();
2756 if (!empty($subject)) {
2757 $url->param('subject', format_string($subject));
2759 if (!empty($body)) {
2760 $url->param('body', format_string($body));
2763 // Use the obfuscated mailto.
2764 $url = preg_replace('/^mailto/', $mailto, $url->out());
2766 if ($dimmed) {
2767 $attrs['title'] = get_string('emaildisable');
2768 $attrs['class'] = 'dimmed';
2771 return html_writer::link($url, $label, $attrs);
2775 * This function is used to rebuild the <nolink> tag because some formats (PLAIN and WIKI)
2776 * will transform it to html entities
2778 * @param string $text Text to search for nolink tag in
2779 * @return string
2781 function rebuildnolinktag($text) {
2783 $text = preg_replace('/&lt;(\/*nolink)&gt;/i', '<$1>', $text);
2785 return $text;
2789 * Prints a maintenance message from $CFG->maintenance_message or default if empty.
2791 function print_maintenance_message() {
2792 global $CFG, $SITE, $PAGE, $OUTPUT;
2794 $PAGE->set_pagetype('maintenance-message');
2795 $PAGE->set_pagelayout('maintenance');
2796 $PAGE->set_title(strip_tags($SITE->fullname));
2797 $PAGE->set_heading($SITE->fullname);
2798 echo $OUTPUT->header();
2799 echo $OUTPUT->heading(get_string('sitemaintenance', 'admin'));
2800 if (isset($CFG->maintenance_message) and !html_is_blank($CFG->maintenance_message)) {
2801 echo $OUTPUT->box_start('maintenance_message generalbox boxwidthwide boxaligncenter');
2802 echo $CFG->maintenance_message;
2803 echo $OUTPUT->box_end();
2805 echo $OUTPUT->footer();
2806 die;
2810 * Returns a string containing a nested list, suitable for formatting into tabs with CSS.
2812 * It is not recommended to use this function in Moodle 2.5 but it is left for backward
2813 * compartibility.
2815 * Example how to print a single line tabs:
2816 * $rows = array(
2817 * new tabobject(...),
2818 * new tabobject(...)
2819 * );
2820 * echo $OUTPUT->tabtree($rows, $selectedid);
2822 * Multiple row tabs may not look good on some devices but if you want to use them
2823 * you can specify ->subtree for the active tabobject.
2825 * @param array $tabrows An array of rows where each row is an array of tab objects
2826 * @param string $selected The id of the selected tab (whatever row it's on)
2827 * @param array $inactive An array of ids of inactive tabs that are not selectable.
2828 * @param array $activated An array of ids of other tabs that are currently activated
2829 * @param bool $return If true output is returned rather then echo'd
2830 * @return string HTML output if $return was set to true.
2832 function print_tabs($tabrows, $selected = null, $inactive = null, $activated = null, $return = false) {
2833 global $OUTPUT;
2835 $tabrows = array_reverse($tabrows);
2836 $subtree = array();
2837 foreach ($tabrows as $row) {
2838 $tree = array();
2840 foreach ($row as $tab) {
2841 $tab->inactive = is_array($inactive) && in_array((string)$tab->id, $inactive);
2842 $tab->activated = is_array($activated) && in_array((string)$tab->id, $activated);
2843 $tab->selected = (string)$tab->id == $selected;
2845 if ($tab->activated || $tab->selected) {
2846 $tab->subtree = $subtree;
2848 $tree[] = $tab;
2850 $subtree = $tree;
2852 $output = $OUTPUT->tabtree($subtree);
2853 if ($return) {
2854 return $output;
2855 } else {
2856 print $output;
2857 return !empty($output);
2862 * Alter debugging level for the current request,
2863 * the change is not saved in database.
2865 * @param int $level one of the DEBUG_* constants
2866 * @param bool $debugdisplay
2868 function set_debugging($level, $debugdisplay = null) {
2869 global $CFG;
2871 $CFG->debug = (int)$level;
2872 $CFG->debugdeveloper = (($CFG->debug & DEBUG_DEVELOPER) === DEBUG_DEVELOPER);
2874 if ($debugdisplay !== null) {
2875 $CFG->debugdisplay = (bool)$debugdisplay;
2880 * Standard Debugging Function
2882 * Returns true if the current site debugging settings are equal or above specified level.
2883 * If passed a parameter it will emit a debugging notice similar to trigger_error(). The
2884 * routing of notices is controlled by $CFG->debugdisplay
2885 * eg use like this:
2887 * 1) debugging('a normal debug notice');
2888 * 2) debugging('something really picky', DEBUG_ALL);
2889 * 3) debugging('annoying debug message only for developers', DEBUG_DEVELOPER);
2890 * 4) if (debugging()) { perform extra debugging operations (do not use print or echo) }
2892 * In code blocks controlled by debugging() (such as example 4)
2893 * any output should be routed via debugging() itself, or the lower-level
2894 * trigger_error() or error_log(). Using echo or print will break XHTML
2895 * JS and HTTP headers.
2897 * It is also possible to define NO_DEBUG_DISPLAY which redirects the message to error_log.
2899 * @param string $message a message to print
2900 * @param int $level the level at which this debugging statement should show
2901 * @param array $backtrace use different backtrace
2902 * @return bool
2904 function debugging($message = '', $level = DEBUG_NORMAL, $backtrace = null) {
2905 global $CFG, $USER;
2907 $forcedebug = false;
2908 if (!empty($CFG->debugusers) && $USER) {
2909 $debugusers = explode(',', $CFG->debugusers);
2910 $forcedebug = in_array($USER->id, $debugusers);
2913 if (!$forcedebug and (empty($CFG->debug) || ($CFG->debug != -1 and $CFG->debug < $level))) {
2914 return false;
2917 if (!isset($CFG->debugdisplay)) {
2918 $CFG->debugdisplay = ini_get_bool('display_errors');
2921 if ($message) {
2922 if (!$backtrace) {
2923 $backtrace = debug_backtrace();
2925 $from = format_backtrace($backtrace, CLI_SCRIPT || NO_DEBUG_DISPLAY);
2926 if (PHPUNIT_TEST) {
2927 if (phpunit_util::debugging_triggered($message, $level, $from)) {
2928 // We are inside test, the debug message was logged.
2929 return true;
2933 if (NO_DEBUG_DISPLAY) {
2934 // Script does not want any errors or debugging in output,
2935 // we send the info to error log instead.
2936 error_log('Debugging: ' . $message . ' in '. PHP_EOL . $from);
2938 } else if ($forcedebug or $CFG->debugdisplay) {
2939 if (!defined('DEBUGGING_PRINTED')) {
2940 define('DEBUGGING_PRINTED', 1); // Indicates we have printed something.
2942 if (CLI_SCRIPT) {
2943 echo "++ $message ++\n$from";
2944 } else {
2945 echo '<div class="notifytiny debuggingmessage" data-rel="debugging">' , $message , $from , '</div>';
2948 } else {
2949 trigger_error($message . $from, E_USER_NOTICE);
2952 return true;
2956 * Outputs a HTML comment to the browser.
2958 * This is used for those hard-to-debug pages that use bits from many different files in very confusing ways (e.g. blocks).
2960 * <code>print_location_comment(__FILE__, __LINE__);</code>
2962 * @param string $file
2963 * @param integer $line
2964 * @param boolean $return Whether to return or print the comment
2965 * @return string|void Void unless true given as third parameter
2967 function print_location_comment($file, $line, $return = false) {
2968 if ($return) {
2969 return "<!-- $file at line $line -->\n";
2970 } else {
2971 echo "<!-- $file at line $line -->\n";
2977 * Returns true if the user is using a right-to-left language.
2979 * @return boolean true if the current language is right-to-left (Hebrew, Arabic etc)
2981 function right_to_left() {
2982 return (get_string('thisdirection', 'langconfig') === 'rtl');
2987 * Returns swapped left<=> right if in RTL environment.
2989 * Part of RTL Moodles support.
2991 * @param string $align align to check
2992 * @return string
2994 function fix_align_rtl($align) {
2995 if (!right_to_left()) {
2996 return $align;
2998 if ($align == 'left') {
2999 return 'right';
3001 if ($align == 'right') {
3002 return 'left';
3004 return $align;
3009 * Returns true if the page is displayed in a popup window.
3011 * Gets the information from the URL parameter inpopup.
3013 * @todo Use a central function to create the popup calls all over Moodle and
3014 * In the moment only works with resources and probably questions.
3016 * @return boolean
3018 function is_in_popup() {
3019 $inpopup = optional_param('inpopup', '', PARAM_BOOL);
3021 return ($inpopup);
3025 * Progress bar class.
3027 * Manages the display of a progress bar.
3029 * To use this class.
3030 * - construct
3031 * - call create (or use the 3rd param to the constructor)
3032 * - call update or update_full() or update() repeatedly
3034 * @copyright 2008 jamiesensei
3035 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3036 * @package core
3038 class progress_bar {
3039 /** @var string html id */
3040 private $html_id;
3041 /** @var int total width */
3042 private $width;
3043 /** @var int last percentage printed */
3044 private $percent = 0;
3045 /** @var int time when last printed */
3046 private $lastupdate = 0;
3047 /** @var int when did we start printing this */
3048 private $time_start = 0;
3051 * Constructor
3053 * Prints JS code if $autostart true.
3055 * @param string $html_id
3056 * @param int $width
3057 * @param bool $autostart Default to false
3059 public function __construct($htmlid = '', $width = 500, $autostart = false) {
3060 if (!empty($htmlid)) {
3061 $this->html_id = $htmlid;
3062 } else {
3063 $this->html_id = 'pbar_'.uniqid();
3066 $this->width = $width;
3068 if ($autostart) {
3069 $this->create();
3074 * Create a new progress bar, this function will output html.
3076 * @return void Echo's output
3078 public function create() {
3079 global $PAGE;
3081 $this->time_start = microtime(true);
3082 if (CLI_SCRIPT) {
3083 return; // Temporary solution for cli scripts.
3086 $PAGE->requires->string_for_js('secondsleft', 'moodle');
3088 $htmlcode = <<<EOT
3089 <div class="progressbar_container" style="width: {$this->width}px;" id="{$this->html_id}">
3090 <h2></h2>
3091 <div class="progress progress-striped active">
3092 <div class="bar" role="progressbar" aria-valuemin="0" aria-valuemax="100" aria-valuenow="0">&nbsp;</div>
3093 </div>
3094 <p></p>
3095 </div>
3096 EOT;
3097 flush();
3098 echo $htmlcode;
3099 flush();
3103 * Update the progress bar
3105 * @param int $percent from 1-100
3106 * @param string $msg
3107 * @return void Echo's output
3108 * @throws coding_exception
3110 private function _update($percent, $msg) {
3111 if (empty($this->time_start)) {
3112 throw new coding_exception('You must call create() (or use the $autostart ' .
3113 'argument to the constructor) before you try updating the progress bar.');
3116 if (CLI_SCRIPT) {
3117 return; // Temporary solution for cli scripts.
3120 $estimate = $this->estimate($percent);
3122 if ($estimate === null) {
3123 // Always do the first and last updates.
3124 } else if ($estimate == 0) {
3125 // Always do the last updates.
3126 } else if ($this->lastupdate + 20 < time()) {
3127 // We must update otherwise browser would time out.
3128 } else if (round($this->percent, 2) === round($percent, 2)) {
3129 // No significant change, no need to update anything.
3130 return;
3132 if (is_numeric($estimate)) {
3133 $estimate = get_string('secondsleft', 'moodle', round($estimate, 2));
3136 $this->percent = round($percent, 2);
3137 $this->lastupdate = microtime(true);
3139 echo html_writer::script(js_writer::function_call('updateProgressBar',
3140 array($this->html_id, $this->percent, $msg, $estimate)));
3141 flush();
3145 * Estimate how much time it is going to take.
3147 * @param int $pt from 1-100
3148 * @return mixed Null (unknown), or int
3150 private function estimate($pt) {
3151 if ($this->lastupdate == 0) {
3152 return null;
3154 if ($pt < 0.00001) {
3155 return null; // We do not know yet how long it will take.
3157 if ($pt > 99.99999) {
3158 return 0; // Nearly done, right?
3160 $consumed = microtime(true) - $this->time_start;
3161 if ($consumed < 0.001) {
3162 return null;
3165 return (100 - $pt) * ($consumed / $pt);
3169 * Update progress bar according percent
3171 * @param int $percent from 1-100
3172 * @param string $msg the message needed to be shown
3174 public function update_full($percent, $msg) {
3175 $percent = max(min($percent, 100), 0);
3176 $this->_update($percent, $msg);
3180 * Update progress bar according the number of tasks
3182 * @param int $cur current task number
3183 * @param int $total total task number
3184 * @param string $msg message
3186 public function update($cur, $total, $msg) {
3187 $percent = ($cur / $total) * 100;
3188 $this->update_full($percent, $msg);
3192 * Restart the progress bar.
3194 public function restart() {
3195 $this->percent = 0;
3196 $this->lastupdate = 0;
3197 $this->time_start = 0;
3202 * Progress trace class.
3204 * Use this class from long operations where you want to output occasional information about
3205 * what is going on, but don't know if, or in what format, the output should be.
3207 * @copyright 2009 Tim Hunt
3208 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3209 * @package core
3211 abstract class progress_trace {
3213 * Output an progress message in whatever format.
3215 * @param string $message the message to output.
3216 * @param integer $depth indent depth for this message.
3218 abstract public function output($message, $depth = 0);
3221 * Called when the processing is finished.
3223 public function finished() {
3228 * This subclass of progress_trace does not ouput anything.
3230 * @copyright 2009 Tim Hunt
3231 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3232 * @package core
3234 class null_progress_trace extends progress_trace {
3236 * Does Nothing
3238 * @param string $message
3239 * @param int $depth
3240 * @return void Does Nothing
3242 public function output($message, $depth = 0) {
3247 * This subclass of progress_trace outputs to plain text.
3249 * @copyright 2009 Tim Hunt
3250 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3251 * @package core
3253 class text_progress_trace extends progress_trace {
3255 * Output the trace message.
3257 * @param string $message
3258 * @param int $depth
3259 * @return void Output is echo'd
3261 public function output($message, $depth = 0) {
3262 echo str_repeat(' ', $depth), $message, "\n";
3263 flush();
3268 * This subclass of progress_trace outputs as HTML.
3270 * @copyright 2009 Tim Hunt
3271 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3272 * @package core
3274 class html_progress_trace extends progress_trace {
3276 * Output the trace message.
3278 * @param string $message
3279 * @param int $depth
3280 * @return void Output is echo'd
3282 public function output($message, $depth = 0) {
3283 echo '<p>', str_repeat('&#160;&#160;', $depth), htmlspecialchars($message), "</p>\n";
3284 flush();
3289 * HTML List Progress Tree
3291 * @copyright 2009 Tim Hunt
3292 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3293 * @package core
3295 class html_list_progress_trace extends progress_trace {
3296 /** @var int */
3297 protected $currentdepth = -1;
3300 * Echo out the list
3302 * @param string $message The message to display
3303 * @param int $depth
3304 * @return void Output is echoed
3306 public function output($message, $depth = 0) {
3307 $samedepth = true;
3308 while ($this->currentdepth > $depth) {
3309 echo "</li>\n</ul>\n";
3310 $this->currentdepth -= 1;
3311 if ($this->currentdepth == $depth) {
3312 echo '<li>';
3314 $samedepth = false;
3316 while ($this->currentdepth < $depth) {
3317 echo "<ul>\n<li>";
3318 $this->currentdepth += 1;
3319 $samedepth = false;
3321 if ($samedepth) {
3322 echo "</li>\n<li>";
3324 echo htmlspecialchars($message);
3325 flush();
3329 * Called when the processing is finished.
3331 public function finished() {
3332 while ($this->currentdepth >= 0) {
3333 echo "</li>\n</ul>\n";
3334 $this->currentdepth -= 1;
3340 * This subclass of progress_trace outputs to error log.
3342 * @copyright Petr Skoda {@link http://skodak.org}
3343 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3344 * @package core
3346 class error_log_progress_trace extends progress_trace {
3347 /** @var string log prefix */
3348 protected $prefix;
3351 * Constructor.
3352 * @param string $prefix optional log prefix
3354 public function __construct($prefix = '') {
3355 $this->prefix = $prefix;
3359 * Output the trace message.
3361 * @param string $message
3362 * @param int $depth
3363 * @return void Output is sent to error log.
3365 public function output($message, $depth = 0) {
3366 error_log($this->prefix . str_repeat(' ', $depth) . $message);
3371 * Special type of trace that can be used for catching of output of other traces.
3373 * @copyright Petr Skoda {@link http://skodak.org}
3374 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3375 * @package core
3377 class progress_trace_buffer extends progress_trace {
3378 /** @var progres_trace */
3379 protected $trace;
3380 /** @var bool do we pass output out */
3381 protected $passthrough;
3382 /** @var string output buffer */
3383 protected $buffer;
3386 * Constructor.
3388 * @param progress_trace $trace
3389 * @param bool $passthrough true means output and buffer, false means just buffer and no output
3391 public function __construct(progress_trace $trace, $passthrough = true) {
3392 $this->trace = $trace;
3393 $this->passthrough = $passthrough;
3394 $this->buffer = '';
3398 * Output the trace message.
3400 * @param string $message the message to output.
3401 * @param int $depth indent depth for this message.
3402 * @return void output stored in buffer
3404 public function output($message, $depth = 0) {
3405 ob_start();
3406 $this->trace->output($message, $depth);
3407 $this->buffer .= ob_get_contents();
3408 if ($this->passthrough) {
3409 ob_end_flush();
3410 } else {
3411 ob_end_clean();
3416 * Called when the processing is finished.
3418 public function finished() {
3419 ob_start();
3420 $this->trace->finished();
3421 $this->buffer .= ob_get_contents();
3422 if ($this->passthrough) {
3423 ob_end_flush();
3424 } else {
3425 ob_end_clean();
3430 * Reset internal text buffer.
3432 public function reset_buffer() {
3433 $this->buffer = '';
3437 * Return internal text buffer.
3438 * @return string buffered plain text
3440 public function get_buffer() {
3441 return $this->buffer;
3446 * Special type of trace that can be used for redirecting to multiple other traces.
3448 * @copyright Petr Skoda {@link http://skodak.org}
3449 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3450 * @package core
3452 class combined_progress_trace extends progress_trace {
3455 * An array of traces.
3456 * @var array
3458 protected $traces;
3461 * Constructs a new instance.
3463 * @param array $traces multiple traces
3465 public function __construct(array $traces) {
3466 $this->traces = $traces;
3470 * Output an progress message in whatever format.
3472 * @param string $message the message to output.
3473 * @param integer $depth indent depth for this message.
3475 public function output($message, $depth = 0) {
3476 foreach ($this->traces as $trace) {
3477 $trace->output($message, $depth);
3482 * Called when the processing is finished.
3484 public function finished() {
3485 foreach ($this->traces as $trace) {
3486 $trace->finished();
3492 * Returns a localized sentence in the current language summarizing the current password policy
3494 * @todo this should be handled by a function/method in the language pack library once we have a support for it
3495 * @uses $CFG
3496 * @return string
3498 function print_password_policy() {
3499 global $CFG;
3501 $message = '';
3502 if (!empty($CFG->passwordpolicy)) {
3503 $messages = array();
3504 $messages[] = get_string('informminpasswordlength', 'auth', $CFG->minpasswordlength);
3505 if (!empty($CFG->minpassworddigits)) {
3506 $messages[] = get_string('informminpassworddigits', 'auth', $CFG->minpassworddigits);
3508 if (!empty($CFG->minpasswordlower)) {
3509 $messages[] = get_string('informminpasswordlower', 'auth', $CFG->minpasswordlower);
3511 if (!empty($CFG->minpasswordupper)) {
3512 $messages[] = get_string('informminpasswordupper', 'auth', $CFG->minpasswordupper);
3514 if (!empty($CFG->minpasswordnonalphanum)) {
3515 $messages[] = get_string('informminpasswordnonalphanum', 'auth', $CFG->minpasswordnonalphanum);
3518 $messages = join(', ', $messages); // This is ugly but we do not have anything better yet...
3519 $message = get_string('informpasswordpolicy', 'auth', $messages);
3521 return $message;
3525 * Get the value of a help string fully prepared for display in the current language.
3527 * @param string $identifier The identifier of the string to search for.
3528 * @param string $component The module the string is associated with.
3529 * @param boolean $ajax Whether this help is called from an AJAX script.
3530 * This is used to influence text formatting and determines
3531 * which format to output the doclink in.
3532 * @param string|object|array $a An object, string or number that can be used
3533 * within translation strings
3534 * @return Object An object containing:
3535 * - heading: Any heading that there may be for this help string.
3536 * - text: The wiki-formatted help string.
3537 * - doclink: An object containing a link, the linktext, and any additional
3538 * CSS classes to apply to that link. Only present if $ajax = false.
3539 * - completedoclink: A text representation of the doclink. Only present if $ajax = true.
3541 function get_formatted_help_string($identifier, $component, $ajax = false, $a = null) {
3542 global $CFG, $OUTPUT;
3543 $sm = get_string_manager();
3545 // Do not rebuild caches here!
3546 // Devs need to learn to purge all caches after any change or disable $CFG->langstringcache.
3548 $data = new stdClass();
3550 if ($sm->string_exists($identifier, $component)) {
3551 $data->heading = format_string(get_string($identifier, $component));
3552 } else {
3553 // Gracefully fall back to an empty string.
3554 $data->heading = '';
3557 if ($sm->string_exists($identifier . '_help', $component)) {
3558 $options = new stdClass();
3559 $options->trusted = false;
3560 $options->noclean = false;
3561 $options->smiley = false;
3562 $options->filter = false;
3563 $options->para = true;
3564 $options->newlines = false;
3565 $options->overflowdiv = !$ajax;
3567 // Should be simple wiki only MDL-21695.
3568 $data->text = format_text(get_string($identifier.'_help', $component, $a), FORMAT_MARKDOWN, $options);
3570 $helplink = $identifier . '_link';
3571 if ($sm->string_exists($helplink, $component)) { // Link to further info in Moodle docs.
3572 $link = get_string($helplink, $component);
3573 $linktext = get_string('morehelp');
3575 $data->doclink = new stdClass();
3576 $url = new moodle_url(get_docs_url($link));
3577 if ($ajax) {
3578 $data->doclink->link = $url->out();
3579 $data->doclink->linktext = $linktext;
3580 $data->doclink->class = ($CFG->doctonewwindow) ? 'helplinkpopup' : '';
3581 } else {
3582 $data->completedoclink = html_writer::tag('div', $OUTPUT->doc_link($link, $linktext),
3583 array('class' => 'helpdoclink'));
3586 } else {
3587 $data->text = html_writer::tag('p',
3588 html_writer::tag('strong', 'TODO') . ": missing help string [{$identifier}_help, {$component}]");
3590 return $data;
3594 * Renders a hidden password field so that browsers won't incorrectly autofill password fields with the user's password.
3596 * @since 2.8.8
3597 * @return string HTML to prevent password autofill
3599 function prevent_form_autofill_password() {
3600 return '<div class="hide"><input type="password" /></div>';