3 // This file is part of Moodle - http://moodle.org/
5 // Moodle is free software: you can redistribute it and/or modify
6 // it under the terms of the GNU General Public License as published by
7 // the Free Software Foundation, either version 3 of the License, or
8 // (at your option) any later version.
10 // Moodle is distributed in the hope that it will be useful,
11 // but WITHOUT ANY WARRANTY; without even the implied warranty of
12 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 // GNU General Public License for more details.
15 // You should have received a copy of the GNU General Public License
16 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
19 * Library of functions for web output
21 * Library of all general-purpose Moodle PHP functions and constants
22 * that produce HTML output
24 * Other main libraries:
25 * - datalib.php - functions that access the database.
26 * - moodlelib.php - general-purpose Moodle functions.
30 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
31 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
34 defined('MOODLE_INTERNAL') || die();
38 /// Define text formatting types ... eventually we can add Wiki, BBcode etc
41 * Does all sorts of transformations and filtering
43 define('FORMAT_MOODLE', '0'); // Does all sorts of transformations and filtering
46 * Plain HTML (with some tags stripped)
48 define('FORMAT_HTML', '1'); // Plain HTML (with some tags stripped)
51 * Plain text (even tags are printed in full)
53 define('FORMAT_PLAIN', '2'); // Plain text (even tags are printed in full)
57 * Deprecated: left here just to note that '3' is not used (at the moment)
58 * and to catch any latent wiki-like text (which generates an error)
60 define('FORMAT_WIKI', '3'); // Wiki-formatted text
63 * Markdown-formatted text http://daringfireball.net/projects/markdown/
65 define('FORMAT_MARKDOWN', '4'); // Markdown-formatted text http://daringfireball.net/projects/markdown/
68 * TRUSTTEXT marker - if present in text, text cleaning should be bypassed
70 define('TRUSTTEXT', '#####TRUSTTEXT#####');
73 * A moodle_url comparison using this flag will return true if the base URLs match, params are ignored
75 define('URL_MATCH_BASE', 0);
77 * A moodle_url comparison using this flag will return true if the base URLs match and the params of url1 are part of url2
79 define('URL_MATCH_PARAMS', 1);
81 * A moodle_url comparison using this flag will return true if the two URLs are identical, except for the order of the params
83 define('URL_MATCH_EXACT', 2);
86 * Allowed tags - string of html tags that can be tested against for safe html tags
87 * @global string $ALLOWED_TAGS
92 '<p><br><b><i><u><font><table><tbody><thead><tfoot><span><div><tr><td><th><ol><ul><dl><li><dt><dd><h1><h2><h3><h4><h5><h6><hr><img><a><strong><emphasis><em><sup><sub><address><cite><blockquote><pre><strike><param><acronym><nolink><lang><tex><algebra><math><mi><mn><mo><mtext><mspace><ms><mrow><mfrac><msqrt><mroot><mstyle><merror><mpadded><mphantom><mfenced><msub><msup><msubsup><munder><mover><munderover><mmultiscripts><mtable><mtr><mtd><maligngroup><malignmark><maction><cn><ci><apply><reln><fn><interval><inverse><sep><condition><declare><lambda><compose><ident><quotient><exp><factorial><divide><max><min><minus><plus><power><rem><times><root><gcd><and><or><xor><not><implies><forall><exists><abs><conjugate><eq><neq><gt><lt><geq><leq><ln><log><int><diff><partialdiff><lowlimit><uplimit><bvar><degree><set><list><union><intersect><in><notin><subset><prsubset><notsubset><notprsubset><setdiff><sum><product><limit><tendsto><mean><sdev><variance><median><mode><moment><vector><matrix><matrixrow><determinant><transpose><selector><annotation><semantics><annotation-xml><tt><code>';
95 * Allowed protocols - array of protocols that are safe to use in links and so on
96 * @global string $ALLOWED_PROTOCOLS
97 * @name $ALLOWED_PROTOCOLS
99 $ALLOWED_PROTOCOLS = array('http', 'https', 'ftp', 'news', 'mailto', 'rtsp', 'teamspeak', 'gopher', 'mms',
100 'color', 'callto', 'cursor', 'text-align', 'font-size', 'font-weight', 'font-style', 'font-family',
101 'border', 'margin', 'padding', 'background', 'background-color', 'text-decoration'); // CSS as well to get through kses
107 * Add quotes to HTML characters
109 * Returns $var with HTML characters (like "<", ">", etc.) properly quoted.
110 * This function is very similar to {@link p()}
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.
118 function s($var, $obsolete = false) {
120 if ($var === '0' or $var === false or $var === 0) {
124 return preg_replace("/&#(\d+|x[0-7a-fA-F]+);/i", "&#$1;", htmlspecialchars($var, ENT_QUOTES, 'UTF-8', true));
128 * Add quotes to HTML characters
130 * Prints $var with HTML characters (like "<", ">", etc.) properly quoted.
131 * This function simply calls {@link s()}
134 * @todo Remove obsolete param $obsolete if not used anywhere
136 * @param string $var the string potentially containing HTML characters
137 * @param boolean $obsolete no longer used.
140 function p($var, $obsolete = false) {
141 echo s($var, $obsolete);
145 * Does proper javascript quoting.
147 * Do not use addslashes anymore, because it does not work when magic_quotes_sybase is enabled.
149 * @param mixed $var String, Array, or Object to add slashes to
150 * @return mixed quoted result
152 function addslashes_js($var) {
153 if (is_string($var)) {
154 $var = str_replace('\\', '\\\\', $var);
155 $var = str_replace(array('\'', '"', "\n", "\r", "\0"), array('\\\'', '\\"', '\\n', '\\r', '\\0'), $var);
156 $var = str_replace('</', '<\/', $var); // XHTML compliance
157 } else if (is_array($var)) {
158 $var = array_map('addslashes_js', $var);
159 } else if (is_object($var)) {
160 $a = get_object_vars($var);
161 foreach ($a as $key=>$value) {
162 $a[$key] = addslashes_js($value);
170 * Remove query string from url
172 * Takes in a URL and returns it without the querystring portion
174 * @param string $url the url which may have a query string attached
175 * @return string The remaining URL
177 function strip_querystring($url) {
179 if ($commapos = strpos($url, '?')) {
180 return substr($url, 0, $commapos);
187 * Returns the URL of the HTTP_REFERER, less the querystring portion if required
190 * @param boolean $stripquery if true, also removes the query part of the url.
191 * @return string The resulting referer or empty string
193 function get_referer($stripquery=true) {
194 if (isset($_SERVER['HTTP_REFERER'])) {
196 return strip_querystring($_SERVER['HTTP_REFERER']);
198 return $_SERVER['HTTP_REFERER'];
207 * Returns the name of the current script, WITH the querystring portion.
209 * This function is necessary because PHP_SELF and REQUEST_URI and SCRIPT_NAME
210 * return different things depending on a lot of things like your OS, Web
211 * server, and the way PHP is compiled (ie. as a CGI, module, ISAPI, etc.)
212 * <b>NOTE:</b> This function returns false if the global variables needed are not set.
215 * @return mixed String, or false if the global variables needed are not set
223 * Returns the name of the current script, WITH the full URL.
225 * This function is necessary because PHP_SELF and REQUEST_URI and SCRIPT_NAME
226 * return different things depending on a lot of things like your OS, Web
227 * server, and the way PHP is compiled (ie. as a CGI, module, ISAPI, etc.
228 * <b>NOTE:</b> This function returns false if the global variables needed are not set.
230 * Like {@link me()} but returns a full URL
234 * @return mixed String, or false if the global variables needed are not set
236 function qualified_me() {
242 * Class for creating and manipulating urls.
244 * It can be used in moodle pages where config.php has been included without any further includes.
246 * It is useful for manipulating urls with long lists of params.
247 * One situation where it will be useful is a page which links to itself to perform various actions
248 * and / or to process form data. A moodle_url object :
249 * can be created for a page to refer to itself with all the proper get params being passed from page call to
250 * page call and methods can be used to output a url including all the params, optionally adding and overriding
251 * params and can also be used to
252 * - output the url without any get params
253 * - and output the params as hidden fields to be output within a form
255 * @link http://docs.moodle.org/en/Development:lib/weblib.php_moodle_url See short write up here
256 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
257 * @package moodlecore
261 * Scheme, ex.: http, https
264 protected $scheme = '';
269 protected $host = '';
271 * Port number, empty means default 80 or 443 in case of http
274 protected $port = '';
276 * Username for http auth
279 protected $user = '';
281 * Password for http auth
284 protected $pass = '';
289 protected $path = '';
291 * Optional slash argument value
294 protected $slashargument = '';
296 * Anchor, may be also empty, null means none
299 protected $anchor = null;
301 * Url parameters as associative array
304 protected $params = array(); // Associative array of query string params
307 * Create new instance of moodle_url.
309 * @param moodle_url|string $url - moodle_url means make a copy of another
310 * moodle_url and change parameters, string means full url or shortened
311 * form (ex.: '/course/view.php'). It is strongly encouraged to not include
312 * query string because it may result in double encoded values
313 * @param array $params these params override current params or add new
315 public function __construct($url, array $params = null) {
318 if ($url instanceof moodle_url) {
319 $this->scheme = $url->scheme;
320 $this->host = $url->host;
321 $this->port = $url->port;
322 $this->user = $url->user;
323 $this->pass = $url->pass;
324 $this->path = $url->path;
325 $this->slashargument = $url->slashargument;
326 $this->params = $url->params;
327 $this->anchor = $url->anchor;
330 // detect if anchor used
331 $apos = strpos($url, '#');
332 if ($apos !== false) {
333 $anchor = substr($url, $apos);
334 $anchor = ltrim($anchor, '#');
335 $this->set_anchor($anchor);
336 $url = substr($url, 0, $apos);
339 // normalise shortened form of our url ex.: '/course/view.php'
340 if (strpos($url, '/') === 0) {
341 // we must not use httpswwwroot here, because it might be url of other page,
342 // devs have to use httpswwwroot explicitly when creating new moodle_url
343 $url = $CFG->wwwroot.$url;
346 // now fix the admin links if needed, no need to mess with httpswwwroot
347 if ($CFG->admin !== 'admin') {
348 if (strpos($url, "$CFG->wwwroot/admin/") === 0) {
349 $url = str_replace("$CFG->wwwroot/admin/", "$CFG->wwwroot/$CFG->admin/", $url);
354 $parts = parse_url($url);
355 if ($parts === false) {
356 throw new moodle_exception('invalidurl');
358 if (isset($parts['query'])) {
359 // note: the values may not be correctly decoded,
360 // url parameters should be always passed as array
361 parse_str(str_replace('&', '&', $parts['query']), $this->params);
363 unset($parts['query']);
364 foreach ($parts as $key => $value) {
365 $this->$key = $value;
368 // detect slashargument value from path - we do not support directory names ending with .php
369 $pos = strpos($this->path, '.php/');
370 if ($pos !== false) {
371 $this->slashargument = substr($this->path, $pos + 4);
372 $this->path = substr($this->path, 0, $pos + 4);
376 $this->params($params);
380 * Add an array of params to the params for this url.
382 * The added params override existing ones if they have the same name.
384 * @param array $params Defaults to null. If null then returns all params.
385 * @return array Array of Params for url.
387 public function params(array $params = null) {
388 $params = (array)$params;
390 foreach ($params as $key=>$value) {
392 throw new coding_exception('Url parameters can not have numeric keys!');
394 if (is_array($value)) {
395 throw new coding_exception('Url parameters values can not be arrays!');
397 if (is_object($value) and !method_exists($value, '__toString')) {
398 throw new coding_exception('Url parameters values can not be objects, unless __toString() is defined!');
400 $this->params[$key] = (string)$value;
402 return $this->params;
406 * Remove all params if no arguments passed.
407 * Remove selected params if arguments are passed.
409 * Can be called as either remove_params('param1', 'param2')
410 * or remove_params(array('param1', 'param2')).
412 * @param mixed $params either an array of param names, or a string param name,
413 * @param string $params,... any number of additional param names.
414 * @return array url parameters
416 public function remove_params($params = null) {
417 if (!is_array($params)) {
418 $params = func_get_args();
420 foreach ($params as $param) {
421 unset($this->params[$param]);
423 return $this->params;
427 * Remove all url parameters
431 public function remove_all_params($params = null) {
432 $this->params = array();
433 $this->slashargument = '';
437 * Add a param to the params for this url.
439 * The added param overrides existing one if they have the same name.
441 * @param string $paramname name
442 * @param string $newvalue Param value. If new value specified current value is overriden or parameter is added
443 * @return mixed string parameter value, null if parameter does not exist
445 public function param($paramname, $newvalue = '') {
446 if (func_num_args() > 1) {
448 $this->params(array($paramname=>$newvalue));
450 if (isset($this->params[$paramname])) {
451 return $this->params[$paramname];
458 * Merges parameters and validates them
459 * @param array $overrideparams
460 * @return array merged parameters
462 protected function merge_overrideparams(array $overrideparams = null) {
463 $overrideparams = (array)$overrideparams;
464 $params = $this->params;
465 foreach ($overrideparams as $key=>$value) {
467 throw new coding_exception('Overridden parameters can not have numeric keys!');
469 if (is_array($value)) {
470 throw new coding_exception('Overridden parameters values can not be arrays!');
472 if (is_object($value) and !method_exists($value, '__toString')) {
473 throw new coding_exception('Overridden parameters values can not be objects, unless __toString() is defined!');
475 $params[$key] = (string)$value;
481 * Get the params as as a query string.
482 * This method should not be used outside of this method.
484 * @param boolean $escaped Use & as params separator instead of plain &
485 * @param array $overrideparams params to add to the output params, these
486 * override existing ones with the same name.
487 * @return string query string that can be added to a url.
489 public function get_query_string($escaped = true, array $overrideparams = null) {
491 $params = $this->merge_overrideparams($overrideparams);
492 foreach ($params as $key => $val) {
493 $arr[] = rawurlencode($key)."=".rawurlencode($val);
496 return implode('&', $arr);
498 return implode('&', $arr);
503 * Shortcut for printing of encoded URL.
506 public function __toString() {
507 return $this->out(true);
513 * If you use the returned URL in HTML code, you want the escaped ampersands. If you use
514 * the returned URL in HTTP headers, you want $escaped=false.
516 * @param boolean $escaped Use & as params separator instead of plain &
517 * @param array $overrideparams params to add to the output url, these override existing ones with the same name.
518 * @return string Resulting URL
520 public function out($escaped = true, array $overrideparams = null) {
521 if (!is_bool($escaped)) {
522 debugging('Escape parameter must be of type boolean, '.gettype($escaped).' given instead.');
525 $uri = $this->out_omit_querystring().$this->slashargument;
527 $querystring = $this->get_query_string($escaped, $overrideparams);
528 if ($querystring !== '') {
529 $uri .= '?' . $querystring;
531 if (!is_null($this->anchor)) {
532 $uri .= '#'.$this->anchor;
539 * Returns url without parameters, everything before '?'.
542 public function out_omit_querystring() {
543 $uri = $this->scheme ? $this->scheme.':'.((strtolower($this->scheme) == 'mailto') ? '':'//'): '';
544 $uri .= $this->user ? $this->user.($this->pass? ':'.$this->pass:'').'@':'';
545 $uri .= $this->host ? $this->host : '';
546 $uri .= $this->port ? ':'.$this->port : '';
547 $uri .= $this->path ? $this->path : '';
552 * Compares this moodle_url with another
553 * See documentation of constants for an explanation of the comparison flags.
554 * @param moodle_url $url The moodle_url object to compare
555 * @param int $matchtype The type of comparison (URL_MATCH_BASE, URL_MATCH_PARAMS, URL_MATCH_EXACT)
558 public function compare(moodle_url $url, $matchtype = URL_MATCH_EXACT) {
560 $baseself = $this->out_omit_querystring();
561 $baseother = $url->out_omit_querystring();
563 // Append index.php if there is no specific file
564 if (substr($baseself,-1)=='/') {
565 $baseself .= 'index.php';
567 if (substr($baseother,-1)=='/') {
568 $baseother .= 'index.php';
571 // Compare the two base URLs
572 if ($baseself != $baseother) {
576 if ($matchtype == URL_MATCH_BASE) {
580 $urlparams = $url->params();
581 foreach ($this->params() as $param => $value) {
582 if ($param == 'sesskey') {
585 if (!array_key_exists($param, $urlparams) || $urlparams[$param] != $value) {
590 if ($matchtype == URL_MATCH_PARAMS) {
594 foreach ($urlparams as $param => $value) {
595 if ($param == 'sesskey') {
598 if (!array_key_exists($param, $this->params()) || $this->param($param) != $value) {
607 * Sets the anchor for the URI (the bit after the hash)
608 * @param string $anchor null means remove previous
610 public function set_anchor($anchor) {
611 if (is_null($anchor)) {
613 $this->anchor = null;
614 } else if ($anchor === '') {
615 // special case, used as empty link
617 } else if (preg_match('|[a-zA-Z\_\:][a-zA-Z0-9\_\-\.\:]*|', $anchor)) {
618 // Match the anchor against the NMTOKEN spec
619 $this->anchor = $anchor;
621 // bad luck, no valid anchor found
622 $this->anchor = null;
627 * Sets the url slashargument value
628 * @param string $path usually file path
629 * @param string $parameter name of page parameter if slasharguments not supported
630 * @param bool $supported usually null, then it depends on $CFG->slasharguments, use true or false for other servers
633 public function set_slashargument($path, $parameter = 'file', $supported = NULL) {
635 if (is_null($supported)) {
636 $supported = $CFG->slasharguments;
640 $parts = explode('/', $path);
641 $parts = array_map('rawurlencode', $parts);
642 $path = implode('/', $parts);
643 $this->slashargument = $path;
644 unset($this->params[$parameter]);
647 $this->slashargument = '';
648 $this->params[$parameter] = $path;
652 // == static factory methods ==
655 * General moodle file url.
656 * @param string $urlbase the script serving the file
657 * @param string $path
658 * @param bool $forcedownload
661 public static function make_file_url($urlbase, $path, $forcedownload = false) {
665 if ($forcedownload) {
666 $params['forcedownload'] = 1;
669 $url = new moodle_url($urlbase, $params);
670 $url->set_slashargument($path);
676 * Factory method for creation of url pointing to plugin file.
677 * Please note this method can be used only from the plugins to
678 * create urls of own files, it must not be used outside of plugins!
679 * @param int $contextid
680 * @param string $component
681 * @param string $area
683 * @param string $pathname
684 * @param string $filename
685 * @param bool $forcedownload
688 public static function make_pluginfile_url($contextid, $component, $area, $itemid, $pathname, $filename, $forcedownload = false) {
690 $urlbase = "$CFG->httpswwwroot/pluginfile.php";
691 if ($itemid === NULL) {
692 return self::make_file_url($urlbase, "/$contextid/$component/$area".$pathname.$filename, $forcedownload);
694 return self::make_file_url($urlbase, "/$contextid/$component/$area/$itemid".$pathname.$filename, $forcedownload);
699 * Factory method for creation of url pointing to draft
700 * file of current user.
701 * @param int $draftid draft item id
702 * @param string $pathname
703 * @param string $filename
704 * @param bool $forcedownload
707 public static function make_draftfile_url($draftid, $pathname, $filename, $forcedownload = false) {
709 $urlbase = "$CFG->httpswwwroot/draftfile.php";
710 $context = get_context_instance(CONTEXT_USER, $USER->id);
712 return self::make_file_url($urlbase, "/$context->id/user/draft/$draftid".$pathname.$filename, $forcedownload);
716 * Factory method for creating of links to legacy
718 * @param int $courseid
719 * @param string $filepath
720 * @param bool $forcedownload
723 public static function make_legacyfile_url($courseid, $filepath, $forcedownload = false) {
726 $urlbase = "$CFG->wwwroot/file.php";
727 return self::make_file_url($urlbase, '/'.$courseid.'/'.$filepath, $forcedownload);
732 * Determine if there is data waiting to be processed from a form
734 * Used on most forms in Moodle to check for data
735 * Returns the data as an object, if it's found.
736 * This object can be used in foreach loops without
737 * casting because it's cast to (array) automatically
739 * Checks that submitted POST data exists and returns it as object.
742 * @return mixed false or object
744 function data_submitted() {
749 return (object)$_POST;
754 * Given some normal text this function will break up any
755 * long words to a given size by inserting the given character
757 * It's multibyte savvy and doesn't change anything inside html tags.
759 * @param string $string the string to be modified
760 * @param int $maxsize maximum length of the string to be returned
761 * @param string $cutchar the string used to represent word breaks
764 function break_up_long_words($string, $maxsize=20, $cutchar=' ') {
766 /// Loading the textlib singleton instance. We are going to need it.
767 $textlib = textlib_get_instance();
769 /// First of all, save all the tags inside the text to skip them
771 filter_save_tags($string,$tags);
773 /// Process the string adding the cut when necessary
775 $length = $textlib->strlen($string);
778 for ($i=0; $i<$length; $i++) {
779 $char = $textlib->substr($string, $i, 1);
780 if ($char == ' ' or $char == "\t" or $char == "\n" or $char == "\r" or $char == "<" or $char == ">") {
784 if ($wordlength > $maxsize) {
792 /// Finally load the tags back again
794 $output = str_replace(array_keys($tags), $tags, $output);
801 * Try and close the current window using JavaScript, either immediately, or after a delay.
803 * Echo's out the resulting XHTML & javascript
807 * @param integer $delay a delay in seconds before closing the window. Default 0.
808 * @param boolean $reloadopener if true, we will see if this window was a pop-up, and try
809 * to reload the parent window before this one closes.
811 function close_window($delay = 0, $reloadopener = false) {
812 global $PAGE, $OUTPUT;
814 if (!$PAGE->headerprinted) {
815 $PAGE->set_title(get_string('closewindow'));
816 echo $OUTPUT->header();
818 $OUTPUT->container_end_all(false);
822 $function = 'close_window_reloading_opener';
824 $function = 'close_window';
826 echo '<p class="centerpara">' . get_string('windowclosing') . '</p>';
828 $PAGE->requires->js_function_call($function, null, false, $delay);
830 echo $OUTPUT->footer();
835 * Returns a string containing a link to the user documentation for the current
836 * page. Also contains an icon by default. Shown to teachers and admin only.
840 * @param string $text The text to be displayed for the link
841 * @param string $iconpath The path to the icon to be displayed
842 * @return string The link to user documentation for this current page
844 function page_doc_link($text='') {
845 global $CFG, $PAGE, $OUTPUT;
847 if (empty($CFG->docroot) || during_initial_install()) {
850 if (!has_capability('moodle/site:doclinks', $PAGE->context)) {
854 $path = $PAGE->docspath;
858 return $OUTPUT->doc_link($path, $text);
863 * Validates an email to make sure it makes sense.
865 * @param string $address The email address to validate.
868 function validate_email($address) {
870 return (preg_match('#^[-!\#$%&\'*+\\/0-9=?A-Z^_`a-z{|}~]+'.
871 '(\.[-!\#$%&\'*+\\/0-9=?A-Z^_`a-z{|}~]+)*'.
873 '[-!\#$%&\'*+\\/0-9=?A-Z^_`a-z{|}~]+\.'.
874 '[-!\#$%&\'*+\\./0-9=?A-Z^_`a-z{|}~]+$#',
879 * Extracts file argument either from file parameter or PATH_INFO
880 * Note: $scriptname parameter is not needed anymore
885 * @return string file path (only safe characters)
887 function get_file_argument() {
890 $relativepath = optional_param('file', FALSE, PARAM_PATH);
892 // then try extract file from PATH_INFO (slasharguments method)
893 if ($relativepath === false and isset($_SERVER['PATH_INFO']) and $_SERVER['PATH_INFO'] !== '') {
894 // check that PATH_INFO works == must not contain the script name
895 if (strpos($_SERVER['PATH_INFO'], $SCRIPT) === false) {
896 $relativepath = clean_param(urldecode($_SERVER['PATH_INFO']), PARAM_PATH);
900 // note: we are not using any other way because they are not compatible with unicode file names ;-)
902 return $relativepath;
906 * Just returns an array of text formats suitable for a popup menu
908 * @uses FORMAT_MOODLE
911 * @uses FORMAT_MARKDOWN
914 function format_text_menu() {
915 return array (FORMAT_MOODLE => get_string('formattext'),
916 FORMAT_HTML => get_string('formathtml'),
917 FORMAT_PLAIN => get_string('formatplain'),
918 FORMAT_MARKDOWN => get_string('formatmarkdown'));
922 * Given text in a variety of format codings, this function returns
923 * the text as safe HTML.
925 * This function should mainly be used for long strings like posts,
926 * answers, glossary items etc. For short strings @see format_string().
928 * @todo Finish documenting this function
930 * @staticvar array $croncache
931 * @param string $text The text to be formatted. This is raw text originally from user input.
932 * @param int $format Identifier of the text format to be used
933 * [FORMAT_MOODLE, FORMAT_HTML, FORMAT_PLAIN, FORMAT_MARKDOWN]
934 * @param object/array $options text formatting options
935 * @param int $courseid_do_not_use deprecated course id, use context option instead
938 function format_text($text, $format = FORMAT_MOODLE, $options = NULL, $courseid_do_not_use = NULL) {
939 global $CFG, $COURSE, $DB, $PAGE;
941 static $croncache = array();
944 return ''; // no need to do any filters and cleaning
947 $options = (array)$options; // detach object, we can not modify it
950 if (!isset($options['trusted'])) {
951 $options['trusted'] = false;
953 if (!isset($options['noclean'])) {
954 if ($options['trusted'] and trusttext_active()) {
955 // no cleaning if text trusted and noclean not specified
956 $options['noclean'] = true;
958 $options['noclean'] = false;
961 if (!isset($options['nocache'])) {
962 $options['nocache'] = false;
964 if (!isset($options['smiley'])) {
965 $options['smiley'] = true;
967 if (!isset($options['filter'])) {
968 $options['filter'] = true;
970 if (!isset($options['para'])) {
971 $options['para'] = true;
973 if (!isset($options['newlines'])) {
974 $options['newlines'] = true;
977 // Calculate best context
978 if (empty($CFG->version) or $CFG->version < 2010072800 or during_initial_install()) {
979 // do not filter anything during installation or before upgrade completes
982 } else if (isset($options['context'])) { // first by explicit passed context option
983 if (is_object($options['context'])) {
984 $context = $options['context'];
986 $context = get_context_instance_by_id($context);
988 } else if ($courseid_do_not_use) {
990 $context = get_context_instance(CONTEXT_COURSE, $courseid_do_not_use);
992 // fallback to $PAGE->context this may be problematic in CLI and other non-standard pages :-(
993 $context = $PAGE->context;
997 // either install/upgrade or something has gone really wrong because context does not exist (yet?)
998 $options['nocache'] = true;
999 $options['filter'] = false;
1002 if ($options['filter']) {
1003 $filtermanager = filter_manager::instance();
1005 $filtermanager = new null_filter_manager();
1008 if (!empty($CFG->cachetext) and empty($options['nocache'])) {
1009 $hashstr = $text.'-'.$filtermanager->text_filtering_hash($context).'-'.$context->id.'-'.current_language().'-'.
1010 (int)$format.(int)$options['trusted'].(int)$options['noclean'].(int)$options['smiley'].
1011 (int)$options['para'].(int)$options['newlines'];
1013 $time = time() - $CFG->cachetext;
1014 $md5key = md5($hashstr);
1016 if (isset($croncache[$md5key])) {
1017 return $croncache[$md5key];
1021 if ($oldcacheitem = $DB->get_record('cache_text', array('md5key'=>$md5key), '*', IGNORE_MULTIPLE)) {
1022 if ($oldcacheitem->timemodified >= $time) {
1024 if (count($croncache) > 150) {
1026 $key = key($croncache);
1027 unset($croncache[$key]);
1029 $croncache[$md5key] = $oldcacheitem->formattedtext;
1031 return $oldcacheitem->formattedtext;
1038 if ($options['smiley']) {
1039 replace_smilies($text);
1041 if (!$options['noclean']) {
1042 $text = clean_text($text, FORMAT_HTML);
1044 $text = $filtermanager->filter_text($text, $context);
1048 $text = s($text); // cleans dangerous JS
1049 $text = rebuildnolinktag($text);
1050 $text = str_replace(' ', ' ', $text);
1051 $text = nl2br($text);
1055 // this format is deprecated
1056 $text = '<p>NOTICE: Wiki-like formatting has been removed from Moodle. You should not be seeing
1057 this message as all texts should have been converted to Markdown format instead.
1058 Please post a bug report to http://moodle.org/bugs with information about where you
1059 saw this message.</p>'.s($text);
1062 case FORMAT_MARKDOWN:
1063 $text = markdown_to_html($text);
1064 if ($options['smiley']) {
1065 replace_smilies($text);
1067 if (!$options['noclean']) {
1068 $text = clean_text($text, FORMAT_HTML);
1070 $text = $filtermanager->filter_text($text, $context);
1073 default: // FORMAT_MOODLE or anything else
1074 $text = text_to_html($text, $options['smiley'], $options['para'], $options['newlines']);
1075 if (!$options['noclean']) {
1076 $text = clean_text($text, FORMAT_HTML);
1078 $text = $filtermanager->filter_text($text, $context);
1082 // Warn people that we have removed this old mechanism, just in case they
1083 // were stupid enough to rely on it.
1084 if (isset($CFG->currenttextiscacheable)) {
1085 debugging('Once upon a time, Moodle had a truly evil use of global variables ' .
1086 'called $CFG->currenttextiscacheable. The good news is that this no ' .
1087 'longer exists. The bad news is that you seem to be using a filter that '.
1088 'relies on it. Please seek out and destroy that filter code.', DEBUG_DEVELOPER);
1091 if (empty($options['nocache']) and !empty($CFG->cachetext)) {
1093 // special static cron cache - no need to store it in db if its not already there
1094 if (count($croncache) > 150) {
1096 $key = key($croncache);
1097 unset($croncache[$key]);
1099 $croncache[$md5key] = $text;
1103 $newcacheitem = new stdClass();
1104 $newcacheitem->md5key = $md5key;
1105 $newcacheitem->formattedtext = $text;
1106 $newcacheitem->timemodified = time();
1107 if ($oldcacheitem) { // See bug 4677 for discussion
1108 $newcacheitem->id = $oldcacheitem->id;
1110 $DB->update_record('cache_text', $newcacheitem); // Update existing record in the cache table
1111 } catch (dml_exception $e) {
1112 // It's unlikely that the cron cache cleaner could have
1113 // deleted this entry in the meantime, as it allows
1114 // some extra time to cover these cases.
1118 $DB->insert_record('cache_text', $newcacheitem); // Insert a new record in the cache table
1119 } catch (dml_exception $e) {
1120 // Again, it's possible that another user has caused this
1121 // record to be created already in the time that it took
1122 // to traverse this function. That's OK too, as the
1123 // call above handles duplicate entries, and eventually
1124 // the cron cleaner will delete them.
1133 * Converts the text format from the value to the 'internal'
1134 * name or vice versa.
1136 * $key can either be the value or the name and you get the other back.
1138 * @uses FORMAT_MOODLE
1140 * @uses FORMAT_PLAIN
1141 * @uses FORMAT_MARKDOWN
1142 * @param mixed $key int 0-4 or string one of 'moodle','html','plain','markdown'
1143 * @return mixed as above but the other way around!
1145 function text_format_name($key) {
1147 $lookup[FORMAT_MOODLE] = 'moodle';
1148 $lookup[FORMAT_HTML] = 'html';
1149 $lookup[FORMAT_PLAIN] = 'plain';
1150 $lookup[FORMAT_MARKDOWN] = 'markdown';
1152 if (!is_numeric($key)) {
1153 $key = strtolower( $key );
1154 $value = array_search( $key, $lookup );
1157 if (isset( $lookup[$key] )) {
1158 $value = $lookup[ $key ];
1165 * Resets all data related to filters, called during upgrade or when filter settings change.
1171 function reset_text_filters_cache() {
1174 $DB->delete_records('cache_text');
1175 $purifdir = $CFG->dataroot.'/cache/htmlpurifier';
1176 remove_dir($purifdir, true);
1180 * Given a simple string, this function returns the string
1181 * processed by enabled string filters if $CFG->filterall is enabled
1183 * This function should be used to print short strings (non html) that
1184 * need filter processing e.g. activity titles, post subjects,
1185 * glossary concepts.
1190 * @staticvar bool $strcache
1191 * @param string $string The string to be filtered.
1192 * @param boolean $striplinks To strip any link in the result text.
1193 Moodle 1.8 default changed from false to true! MDL-8713
1194 * @param array $options options array/object or courseid
1197 function format_string($string, $striplinks = true, $options = NULL) {
1198 global $CFG, $COURSE, $PAGE;
1200 //We'll use a in-memory cache here to speed up repeated strings
1201 static $strcache = false;
1203 if (empty($CFG->version) or $CFG->version < 2010072800 or during_initial_install()) {
1204 // do not filter anything during installation or before upgrade completes
1205 return $string = strip_tags($string);
1208 if ($strcache === false or count($strcache) > 2000) { // this number might need some tuning to limit memory usage in cron
1209 $strcache = array();
1212 if (is_numeric($options)) {
1213 // legacy courseid usage
1214 $options = array('context'=>get_context_instance(CONTEXT_COURSE, $options));
1216 $options = (array)$options; // detach object, we can not modify it
1219 if (empty($options['context'])) {
1220 // fallback to $PAGE->context this may be problematic in CLI and other non-standard pages :-(
1221 $options['context'] = $PAGE->context;
1222 } else if (is_numeric($options['context'])) {
1223 $options['context'] = get_context_instance_by_id($options['context']);
1226 if (!$options['context']) {
1227 // we did not find any context? weird
1228 return $string = strip_tags($string);
1232 $md5 = md5($string.'<+>'.$striplinks.'<+>'.$options['context']->id.'<+>'.current_language());
1234 //Fetch from cache if possible
1235 if (isset($strcache[$md5])) {
1236 return $strcache[$md5];
1239 // First replace all ampersands not followed by html entity code
1240 // Regular expression moved to its own method for easier unit testing
1241 $string = replace_ampersands_not_followed_by_entity($string);
1243 if (!empty($CFG->filterall)) {
1244 $string = filter_manager::instance()->filter_string($string, $options['context']);
1247 // If the site requires it, strip ALL tags from this string
1248 if (!empty($CFG->formatstringstriptags)) {
1249 $string = strip_tags($string);
1252 // Otherwise strip just links if that is required (default)
1253 if ($striplinks) { //strip links in string
1254 $string = strip_links($string);
1256 $string = clean_text($string);
1260 $strcache[$md5] = $string;
1266 * Given a string, performs a negative lookahead looking for any ampersand character
1267 * that is not followed by a proper HTML entity. If any is found, it is replaced
1268 * by &. The string is then returned.
1270 * @param string $string
1273 function replace_ampersands_not_followed_by_entity($string) {
1274 return preg_replace("/\&(?![a-zA-Z0-9#]{1,8};)/", "&", $string);
1278 * Given a string, replaces all <a>.*</a> by .* and returns the string.
1280 * @param string $string
1283 function strip_links($string) {
1284 return preg_replace('/(<a\s[^>]+?>)(.+?)(<\/a>)/is','$2',$string);
1288 * This expression turns links into something nice in a text format. (Russell Jungwirth)
1290 * @param string $string
1293 function wikify_links($string) {
1294 return preg_replace('~(<a [^<]*href=["|\']?([^ "\']*)["|\']?[^>]*>([^<]*)</a>)~i','$3 [ $2 ]', $string);
1298 * Replaces non-standard HTML entities
1300 * @param string $string
1303 function fix_non_standard_entities($string) {
1304 $text = preg_replace('/�*([0-9]+);?/', '&#$1;', $string);
1305 $text = preg_replace('/�*([0-9a-fA-F]+);?/', '&#x$1;', $text);
1310 * Given text in a variety of format codings, this function returns
1311 * the text as plain text suitable for plain email.
1313 * @uses FORMAT_MOODLE
1315 * @uses FORMAT_PLAIN
1317 * @uses FORMAT_MARKDOWN
1318 * @param string $text The text to be formatted. This is raw text originally from user input.
1319 * @param int $format Identifier of the text format to be used
1320 * [FORMAT_MOODLE, FORMAT_HTML, FORMAT_PLAIN, FORMAT_WIKI, FORMAT_MARKDOWN]
1323 function format_text_email($text, $format) {
1332 // there should not be any of these any more!
1333 $text = wikify_links($text);
1334 return strtr(strip_tags($text), array_flip(get_html_translation_table(HTML_ENTITIES)));
1338 return html_to_text($text);
1342 case FORMAT_MARKDOWN:
1344 $text = wikify_links($text);
1345 return strtr(strip_tags($text), array_flip(get_html_translation_table(HTML_ENTITIES)));
1351 * Formats activity intro text
1354 * @uses CONTEXT_MODULE
1355 * @param string $module name of module
1356 * @param object $activity instance of activity
1357 * @param int $cmid course module id
1358 * @param bool $filter filter resulting html text
1361 function format_module_intro($module, $activity, $cmid, $filter=true) {
1363 require_once("$CFG->libdir/filelib.php");
1364 $context = get_context_instance(CONTEXT_MODULE, $cmid);
1365 $options = (object)array('noclean'=>true, 'para'=>false, 'filter'=>$filter, 'context'=>$context);
1366 $intro = file_rewrite_pluginfile_urls($activity->intro, 'pluginfile.php', $context->id, 'mod_'.$module, 'intro', null);
1367 return trim(format_text($intro, $activity->introformat, $options, null));
1371 * Legacy function, used for cleaning of old forum and glossary text only.
1374 * @param string $text text that may contain TRUSTTEXT marker
1375 * @return text without any TRUSTTEXT marker
1377 function trusttext_strip($text) {
1380 while (true) { //removing nested TRUSTTEXT
1382 $text = str_replace('#####TRUSTTEXT#####', '', $text);
1383 if (strcmp($orig, $text) === 0) {
1390 * Must be called before editing of all texts
1391 * with trust flag. Removes all XSS nasties
1392 * from texts stored in database if needed.
1394 * @param object $object data object with xxx, xxxformat and xxxtrust fields
1395 * @param string $field name of text field
1396 * @param object $context active context
1397 * @return object updated $object
1399 function trusttext_pre_edit($object, $field, $context) {
1400 $trustfield = $field.'trust';
1401 $formatfield = $field.'format';
1403 if (!$object->$trustfield or !trusttext_trusted($context)) {
1404 $object->$field = clean_text($object->$field, $object->$formatfield);
1411 * Is current user trusted to enter no dangerous XSS in this context?
1413 * Please note the user must be in fact trusted everywhere on this server!!
1415 * @param object $context
1416 * @return bool true if user trusted
1418 function trusttext_trusted($context) {
1419 return (trusttext_active() and has_capability('moodle/site:trustcontent', $context));
1423 * Is trusttext feature active?
1426 * @param object $context
1429 function trusttext_active() {
1432 return !empty($CFG->enabletrusttext);
1436 * Given raw text (eg typed in by a user), this function cleans it up
1437 * and removes any nasty tags that could mess up Moodle pages.
1441 * @param string $text The text to be cleaned
1442 * @param int $format Identifier of the text format to be used
1443 * [FORMAT_MOODLE, FORMAT_HTML, FORMAT_PLAIN, FORMAT_WIKI, FORMAT_MARKDOWN]
1444 * @return string The cleaned up text
1446 function clean_text($text, $format = FORMAT_MOODLE) {
1447 global $ALLOWED_TAGS, $CFG;
1449 if (empty($text) or is_numeric($text)) {
1450 return (string)$text;
1455 case FORMAT_MARKDOWN:
1460 if (!empty($CFG->enablehtmlpurifier)) {
1461 $text = purify_html($text);
1463 /// Fix non standard entity notations
1464 $text = fix_non_standard_entities($text);
1466 /// Remove tags that are not allowed
1467 $text = strip_tags($text, $ALLOWED_TAGS);
1469 /// Clean up embedded scripts and , using kses
1470 $text = cleanAttributes($text);
1472 /// Again remove tags that are not allowed
1473 $text = strip_tags($text, $ALLOWED_TAGS);
1477 /// Remove potential script events - some extra protection for undiscovered bugs in our code
1478 $text = preg_replace("~([^a-z])language([[:space:]]*)=~i", "$1Xlanguage=", $text);
1479 $text = preg_replace("~([^a-z])on([a-z]+)([[:space:]]*)=~i", "$1Xon$2=", $text);
1486 * KSES replacement cleaning function - uses HTML Purifier.
1489 * @param string $text The (X)HTML string to purify
1491 function purify_html($text) {
1494 // this can not be done only once because we sometimes need to reset the cache
1495 $cachedir = $CFG->dataroot.'/cache/htmlpurifier';
1496 check_dir_exists($cachedir);
1498 static $purifier = false;
1499 if ($purifier === false) {
1500 require_once $CFG->libdir.'/htmlpurifier/HTMLPurifier.safe-includes.php';
1501 $config = HTMLPurifier_Config::createDefault();
1503 $config->set('HTML.DefinitionID', 'moodlehtml');
1504 $config->set('HTML.DefinitionRev', 1);
1505 $config->set('Cache.SerializerPath', $cachedir);
1506 //$config->set('Cache.SerializerPermission', $CFG->directorypermissions); // it would be nice to get this upstream
1507 $config->set('Core.NormalizeNewlines', false);
1508 $config->set('Core.ConvertDocumentToFragment', true);
1509 $config->set('Core.Encoding', 'UTF-8');
1510 $config->set('HTML.Doctype', 'XHTML 1.0 Transitional');
1511 $config->set('URI.AllowedSchemes', array('http'=>true, 'https'=>true, 'ftp'=>true, 'irc'=>true, 'nntp'=>true, 'news'=>true, 'rtsp'=>true, 'teamspeak'=>true, 'gopher'=>true, 'mms'=>true));
1512 $config->set('Attr.AllowedFrameTargets', array('_blank'));
1514 if (!empty($CFG->allowobjectembed)) {
1515 $config->set('HTML.SafeObject', true);
1516 $config->set('Output.FlashCompat', true);
1517 $config->set('HTML.SafeEmbed', true);
1520 $def = $config->getHTMLDefinition(true);
1521 $def->addElement('nolink', 'Block', 'Flow', array()); // skip our filters inside
1522 $def->addElement('tex', 'Inline', 'Inline', array()); // tex syntax, equivalent to $$xx$$
1523 $def->addElement('algebra', 'Inline', 'Inline', array()); // algebra syntax, equivalent to @@xx@@
1524 $def->addElement('lang', 'Block', 'Flow', array(), array('lang'=>'CDATA')); // old anf future style multilang - only our hacked lang attribute
1525 $def->addAttribute('span', 'xxxlang', 'CDATA'); // current problematic multilang
1527 $purifier = new HTMLPurifier($config);
1530 $multilang = (strpos($text, 'class="multilang"') !== false);
1533 $text = preg_replace('/<span(\s+lang="([a-zA-Z0-9_-]+)"|\s+class="multilang"){2}\s*>/', '<span xxxlang="${2}">', $text);
1535 $text = $purifier->purify($text);
1537 $text = preg_replace('/<span xxxlang="([a-zA-Z0-9_-]+)">/', '<span lang="${1}" class="multilang">', $text);
1544 * This function takes a string and examines it for HTML tags.
1546 * If tags are detected it passes the string to a helper function {@link cleanAttributes2()}
1547 * which checks for attributes and filters them for malicious content
1549 * @param string $str The string to be examined for html tags
1552 function cleanAttributes($str){
1553 $result = preg_replace_callback(
1554 '%(<[^>]*(>|$)|>)%m', #search for html tags
1562 * This function takes a string with an html tag and strips out any unallowed
1563 * protocols e.g. javascript:
1565 * It calls ancillary functions in kses which are prefixed by kses
1569 * @param array $htmlArray An array from {@link cleanAttributes()}, containing in its 1st
1570 * element the html to be cleared
1573 function cleanAttributes2($htmlArray){
1575 global $CFG, $ALLOWED_PROTOCOLS;
1576 require_once($CFG->libdir .'/kses.php');
1578 $htmlTag = $htmlArray[1];
1579 if (substr($htmlTag, 0, 1) != '<') {
1580 return '>'; //a single character ">" detected
1582 if (!preg_match('%^<\s*(/\s*)?([a-zA-Z0-9]+)([^>]*)>?$%', $htmlTag, $matches)) {
1583 return ''; // It's seriously malformed
1585 $slash = trim($matches[1]); //trailing xhtml slash
1586 $elem = $matches[2]; //the element name
1587 $attrlist = $matches[3]; // the list of attributes as a string
1589 $attrArray = kses_hair($attrlist, $ALLOWED_PROTOCOLS);
1592 foreach ($attrArray as $arreach) {
1593 $arreach['name'] = strtolower($arreach['name']);
1594 if ($arreach['name'] == 'style') {
1595 $value = $arreach['value'];
1597 $prevvalue = $value;
1598 $value = kses_no_null($value);
1599 $value = preg_replace("/\/\*.*\*\//Us", '', $value);
1600 $value = kses_decode_entities($value);
1601 $value = preg_replace('/(&#[0-9]+)(;?)/', "\\1;", $value);
1602 $value = preg_replace('/(&#x[0-9a-fA-F]+)(;?)/', "\\1;", $value);
1603 if ($value === $prevvalue) {
1604 $arreach['value'] = $value;
1608 $arreach['value'] = preg_replace("/j\s*a\s*v\s*a\s*s\s*c\s*r\s*i\s*p\s*t/i", "Xjavascript", $arreach['value']);
1609 $arreach['value'] = preg_replace("/v\s*b\s*s\s*c\s*r\s*i\s*p\s*t/i", "Xvbscript", $arreach['value']);
1610 $arreach['value'] = preg_replace("/e\s*x\s*p\s*r\s*e\s*s\s*s\s*i\s*o\s*n/i", "Xexpression", $arreach['value']);
1611 $arreach['value'] = preg_replace("/b\s*i\s*n\s*d\s*i\s*n\s*g/i", "Xbinding", $arreach['value']);
1612 } else if ($arreach['name'] == 'href') {
1613 //Adobe Acrobat Reader XSS protection
1614 $arreach['value'] = preg_replace('/(\.(pdf|fdf|xfdf|xdp|xfd)[^#]*)#.*$/i', '$1', $arreach['value']);
1616 $attStr .= ' '.$arreach['name'].'="'.$arreach['value'].'"';
1620 if (preg_match('%/\s*$%', $attrlist)) {
1621 $xhtml_slash = ' /';
1623 return '<'. $slash . $elem . $attStr . $xhtml_slash .'>';
1627 * Replaces all known smileys in the text with image equivalents
1630 * @staticvar array $e
1631 * @staticvar array $img
1632 * @staticvar array $emoticons
1633 * @param string $text Passed by reference. The string to search for smiley strings.
1636 function replace_smilies(&$text) {
1637 global $CFG, $OUTPUT;
1639 if (empty($CFG->emoticons)) { /// No emoticons defined, nothing to process here
1643 $lang = current_language();
1644 $emoticonstring = $CFG->emoticons;
1645 static $e = array();
1646 static $img = array();
1647 static $emoticons = null;
1649 if (is_null($emoticons)) {
1650 $emoticons = array();
1651 if ($emoticonstring) {
1652 $items = explode('{;}', $CFG->emoticons);
1653 foreach ($items as $item) {
1654 $item = explode('{:}', $item);
1655 $emoticons[$item[0]] = $item[1];
1660 if (empty($img[$lang])) { /// After the first time this is not run again
1661 $e[$lang] = array();
1662 $img[$lang] = array();
1663 foreach ($emoticons as $emoticon => $image){
1664 $alttext = get_string($image, 'pix');
1665 if ($alttext === '') {
1668 $e[$lang][] = $emoticon;
1669 $img[$lang][] = '<img alt="'. $alttext .'" width="15" height="15" src="'. $OUTPUT->pix_url('s/' . $image) . '" />';
1673 // Exclude from transformations all the code inside <script> tags
1674 // Needed to solve Bug 1185. Thanks to jouse 2001 detecting it. :-)
1675 // Based on code from glossary filter by Williams Castillo.
1678 // Detect all the <script> zones to take out
1679 $excludes = array();
1680 preg_match_all('/<script language(.+?)<\/script>/is',$text,$list_of_excludes);
1682 // Take out all the <script> zones from text
1683 foreach (array_unique($list_of_excludes[0]) as $key=>$value) {
1684 $excludes['<+'.$key.'+>'] = $value;
1687 $text = str_replace($excludes,array_keys($excludes),$text);
1690 /// this is the meat of the code - this is run every time
1691 $text = str_replace($e[$lang], $img[$lang], $text);
1693 // Recover all the <script> zones to text
1695 $text = str_replace(array_keys($excludes),$excludes,$text);
1700 * This code is called from help.php to inject a list of smilies into the
1701 * emoticons help file.
1705 * @return string HTML for a list of smilies.
1707 function get_emoticons_list_for_help_file() {
1708 global $CFG, $SESSION, $PAGE, $OUTPUT;
1709 if (empty($CFG->emoticons)) {
1713 $items = explode('{;}', $CFG->emoticons);
1714 $output = '<ul id="emoticonlist">';
1715 foreach ($items as $item) {
1716 $item = explode('{:}', $item);
1717 $output .= '<li><img src="' . $OUTPUT->pix_url('s/' . $item[1]) . '" alt="' .
1718 $item[0] . '" /><code>' . $item[0] . '</code></li>';
1721 if (!empty($SESSION->inserttextform)) {
1722 $formname = $SESSION->inserttextform;
1723 $fieldname = $SESSION->inserttextfield;
1725 $formname = 'theform';
1726 $fieldname = 'message';
1729 $PAGE->requires->yui2_lib('event');
1730 $PAGE->requires->js_function_call('emoticons_help.init', array($formname, $fieldname, 'emoticonlist'));
1736 * Given plain text, makes it into HTML as nicely as possible.
1737 * May contain HTML tags already
1740 * @param string $text The string to convert.
1741 * @param boolean $smiley Convert any smiley characters to smiley images?
1742 * @param boolean $para If true then the returned string will be wrapped in div tags
1743 * @param boolean $newlines If true then lines newline breaks will be converted to HTML newline breaks.
1747 function text_to_html($text, $smiley=true, $para=true, $newlines=true) {
1752 /// Remove any whitespace that may be between HTML tags
1753 $text = preg_replace("~>([[:space:]]+)<~i", "><", $text);
1755 /// Remove any returns that precede or follow HTML tags
1756 $text = preg_replace("~([\n\r])<~i", " <", $text);
1757 $text = preg_replace("~>([\n\r])~i", "> ", $text);
1759 convert_urls_into_links($text);
1761 /// Make returns into HTML newlines.
1763 $text = nl2br($text);
1766 /// Turn smileys into images.
1768 replace_smilies($text);
1771 /// Wrap the whole thing in a div if required
1773 //return '<p>'.$text.'</p>'; //1.9 version
1774 return '<div class="text_to_html">'.$text.'</div>';
1781 * Given Markdown formatted text, make it into XHTML using external function
1784 * @param string $text The markdown formatted text to be converted.
1785 * @return string Converted text
1787 function markdown_to_html($text) {
1790 if ($text === '' or $text === NULL) {
1794 require_once($CFG->libdir .'/markdown.php');
1796 return Markdown($text);
1800 * Given HTML text, make it into plain text using external function
1802 * @param string $html The text to be converted.
1803 * @param integer $width Width to wrap the text at. (optional, default 75 which
1804 * is a good value for email. 0 means do not limit line length.)
1805 * @param boolean $dolinks By default, any links in the HTML are collected, and
1806 * printed as a list at the end of the HTML. If you don't want that, set this
1807 * argument to false.
1808 * @return string plain text equivalent of the HTML.
1810 function html_to_text($html, $width = 75, $dolinks = true) {
1814 require_once($CFG->libdir .'/html2text.php');
1816 $h2t = new html2text($html, false, $dolinks, $width);
1817 $result = $h2t->get_text();
1823 * Given some text this function converts any URLs it finds into HTML links
1825 * @param string $text Passed in by reference. The string to be searched for urls.
1827 function convert_urls_into_links(&$text) {
1828 //I've added img tags to this list of tags to ignore.
1829 //See MDL-21168 for more info. A better way to ignore tags whether or not
1830 //they are escaped partially or completely would be desirable. For example:
1832 //<a href="blah">
1833 //<a href="blah">
1834 $filterignoretagsopen = array('<a\s[^>]+?>');
1835 $filterignoretagsclose = array('</a>');
1836 filter_save_ignore_tags($text,$filterignoretagsopen,$filterignoretagsclose,$ignoretags);
1838 // Check if we support unicode modifiers in regular expressions. Cache it.
1839 // TODO: this check should be a environment requirement in Moodle 2.0, as far as unicode
1840 // chars are going to arrive to URLs officially really soon (2010?)
1841 // Original RFC regex from: http://www.bytemycode.com/snippets/snippet/796/
1842 // Various ideas from: http://alanstorm.com/url_regex_explained
1843 // Unicode check, negative assertion and other bits from Moodle.
1844 static $unicoderegexp;
1845 if (!isset($unicoderegexp)) {
1846 $unicoderegexp = @preg_match('/\pL/u', 'a'); // This will fail silently, returning false,
1849 //todo: MDL-21296 - use of unicode modifiers may cause a timeout
1850 if ($unicoderegexp) { //We can use unicode modifiers
1851 $text = preg_replace('#(?<!=["\'])(((http(s?))://)(((([\pLl0-9]([\pLl0-9]|-)*[\pLl0-9]|[\pLl0-9])\.)+([\pLl]([\pLl0-9]|-)*[\pLl0-9]|[\pLl]))|(([0-9]{1,3}\.){3}[0-9]{1,3}))(:[\pL0-9]*)?(/([\pLl0-9\.!$&\'\(\)*+,;=_~:@-]|%[a-fA-F0-9]{2})*)*(\?([\pLl0-9\.!$&\'\(\)*+,;=_~:@/?-]|%[a-fA-F0-9]{2})*)?(\#[\pLl0-9\.!$&\'\(\)*+,;=_~:@/?-]*)?)(?<![,.;])#iu',
1852 '<a href="\\1" class="_blanktarget">\\1</a>', $text);
1853 $text = preg_replace('#(?<!=["\']|//)((www\.([\pLl0-9]([\pLl0-9]|-)*[\pLl0-9]|[\pLl0-9])\.)+([\pLl]([\pLl0-9]|-)*[\pLl0-9]|[\pLl])(:[\pL0-9]*)?(/([\pLl0-9\.!$&\'\(\)*+,;=_~:@-]|%[a-fA-F0-9]{2})*)*(\?([\pLl0-9\.!$&\'\(\)*+,;=_~:@/?-]|%[a-fA-F0-9]{2})*)?(\#[\pLl0-9\.!$&\'\(\)*+,;=_~:@/?-]*)?)(?<![,.;])#iu',
1854 '<a href="http://\\1" class="_blanktarget">\\1</a>', $text);
1855 } else { //We cannot use unicode modifiers
1856 $text = preg_replace('#(?<!=["\'])(((http(s?))://)(((([a-z0-9]([a-z0-9]|-)*[a-z0-9]|[a-z0-9])\.)+([a-z]([a-z0-9]|-)*[a-z0-9]|[a-z]))|(([0-9]{1,3}\.){3}[0-9]{1,3}))(:[a-zA-Z0-9]*)?(/([a-z0-9\.!$&\'\(\)*+,;=_~:@-]|%[a-f0-9]{2})*)*(\?([a-z0-9\.!$&\'\(\)*+,;=_~:@/?-]|%[a-fA-F0-9]{2})*)?(\#[a-z0-9\.!$&\'\(\)*+,;=_~:@/?-]*)?)(?<![,.;])#i',
1857 '<a href="\\1" class="_blanktarget">\\1</a>', $text);
1858 $text = preg_replace('#(?<!=["\']|//)((www\.([a-z0-9]([a-z0-9]|-)*[a-z0-9]|[a-z0-9])\.)+([a-z]([a-z0-9]|-)*[a-z0-9]|[a-z])(:[a-zA-Z0-9]*)?(/([a-z0-9\.!$&\'\(\)*+,;=_~:@-]|%[a-f0-9]{2})*)*(\?([a-z0-9\.!$&\'\(\)*+,;=_~:@/?-]|%[a-fA-F0-9]{2})*)?(\#[a-z0-9\.!$&\'\(\)*+,;=_~:@/?-]*)?)(?<![,.;])#i',
1859 '<a href="http://\\1" class="_blanktarget">\\1</a>', $text);
1862 if (!empty($ignoretags)) {
1863 $ignoretags = array_reverse($ignoretags); /// Reversed so "progressive" str_replace() will solve some nesting problems.
1864 $text = str_replace(array_keys($ignoretags),$ignoretags,$text);
1869 * This function will highlight search words in a given string
1871 * It cares about HTML and will not ruin links. It's best to use
1872 * this function after performing any conversions to HTML.
1874 * @param string $needle The search string. Syntax like "word1 +word2 -word3" is dealt with correctly.
1875 * @param string $haystack The string (HTML) within which to highlight the search terms.
1876 * @param boolean $matchcase whether to do case-sensitive. Default case-insensitive.
1877 * @param string $prefix the string to put before each search term found.
1878 * @param string $suffix the string to put after each search term found.
1879 * @return string The highlighted HTML.
1881 function highlight($needle, $haystack, $matchcase = false,
1882 $prefix = '<span class="highlight">', $suffix = '</span>') {
1884 /// Quick bail-out in trivial cases.
1885 if (empty($needle) or empty($haystack)) {
1889 /// Break up the search term into words, discard any -words and build a regexp.
1890 $words = preg_split('/ +/', trim($needle));
1891 foreach ($words as $index => $word) {
1892 if (strpos($word, '-') === 0) {
1893 unset($words[$index]);
1894 } else if (strpos($word, '+') === 0) {
1895 $words[$index] = '\b' . preg_quote(ltrim($word, '+'), '/') . '\b'; // Match only as a complete word.
1897 $words[$index] = preg_quote($word, '/');
1900 $regexp = '/(' . implode('|', $words) . ')/u'; // u is do UTF-8 matching.
1905 /// Another chance to bail-out if $search was only -words
1906 if (empty($words)) {
1910 /// Find all the HTML tags in the input, and store them in a placeholders array.
1911 $placeholders = array();
1913 preg_match_all('/<[^>]*>/', $haystack, $matches);
1914 foreach (array_unique($matches[0]) as $key => $htmltag) {
1915 $placeholders['<|' . $key . '|>'] = $htmltag;
1918 /// In $hastack, replace each HTML tag with the corresponding placeholder.
1919 $haystack = str_replace($placeholders, array_keys($placeholders), $haystack);
1921 /// In the resulting string, Do the highlighting.
1922 $haystack = preg_replace($regexp, $prefix . '$1' . $suffix, $haystack);
1924 /// Turn the placeholders back into HTML tags.
1925 $haystack = str_replace(array_keys($placeholders), $placeholders, $haystack);
1931 * This function will highlight instances of $needle in $haystack
1933 * It's faster that the above function {@link highlight()} and doesn't care about
1936 * @param string $needle The string to search for
1937 * @param string $haystack The string to search for $needle in
1938 * @return string The highlighted HTML
1940 function highlightfast($needle, $haystack) {
1942 if (empty($needle) or empty($haystack)) {
1946 $parts = explode(moodle_strtolower($needle), moodle_strtolower($haystack));
1948 if (count($parts) === 1) {
1954 foreach ($parts as $key => $part) {
1955 $parts[$key] = substr($haystack, $pos, strlen($part));
1956 $pos += strlen($part);
1958 $parts[$key] .= '<span class="highlight">'.substr($haystack, $pos, strlen($needle)).'</span>';
1959 $pos += strlen($needle);
1962 return str_replace('<span class="highlight"></span>', '', join('', $parts));
1966 * Return a string containing 'lang', xml:lang and optionally 'dir' HTML attributes.
1967 * Internationalisation, for print_header and backup/restorelib.
1969 * @param bool $dir Default false
1970 * @return string Attributes
1972 function get_html_lang($dir = false) {
1975 if (right_to_left()) {
1976 $direction = ' dir="rtl"';
1978 $direction = ' dir="ltr"';
1981 //Accessibility: added the 'lang' attribute to $direction, used in theme <html> tag.
1982 $language = str_replace('_', '-', current_language());
1983 @header('Content-Language: '.$language);
1984 return ($direction.' lang="'.$language.'" xml:lang="'.$language.'"');
1988 /// STANDARD WEB PAGE PARTS ///////////////////////////////////////////////////
1991 * Send the HTTP headers that Moodle requires.
1992 * @param $cacheable Can this page be cached on back?
1994 function send_headers($contenttype, $cacheable = true) {
1995 @header('Content-Type: ' . $contenttype);
1996 @header('Content-Script-Type: text/javascript');
1997 @header('Content-Style-Type: text/css');
2000 // Allow caching on "back" (but not on normal clicks)
2001 @header('Cache-Control: private, pre-check=0, post-check=0, max-age=0');
2002 @header('Pragma: no-cache');
2003 @header('Expires: ');
2005 // Do everything we can to always prevent clients and proxies caching
2006 @header('Cache-Control: no-store, no-cache, must-revalidate');
2007 @header('Cache-Control: post-check=0, pre-check=0', false);
2008 @header('Pragma: no-cache');
2009 @header('Expires: Mon, 20 Aug 1969 09:23:00 GMT');
2010 @header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
2012 @header('Accept-Ranges: none');
2016 * Return the right arrow with text ('next'), and optionally embedded in a link.
2019 * @param string $text HTML/plain text label (set to blank only for breadcrumb separator cases).
2020 * @param string $url An optional link to use in a surrounding HTML anchor.
2021 * @param bool $accesshide True if text should be hidden (for screen readers only).
2022 * @param string $addclass Additional class names for the link, or the arrow character.
2023 * @return string HTML string.
2025 function link_arrow_right($text, $url='', $accesshide=false, $addclass='') {
2026 global $OUTPUT; //TODO: move to output renderer
2027 $arrowclass = 'arrow ';
2029 $arrowclass .= $addclass;
2031 $arrow = '<span class="'.$arrowclass.'">'.$OUTPUT->rarrow().'</span>';
2034 $htmltext = '<span class="arrow_text">'.$text.'</span> ';
2036 $htmltext = get_accesshide($htmltext);
2040 $class = 'arrow_link';
2042 $class .= ' '.$addclass;
2044 return '<a class="'.$class.'" href="'.$url.'" title="'.preg_replace('/<.*?>/','',$text).'">'.$htmltext.$arrow.'</a>';
2046 return $htmltext.$arrow;
2050 * Return the left arrow with text ('previous'), and optionally embedded in a link.
2053 * @param string $text HTML/plain text label (set to blank only for breadcrumb separator cases).
2054 * @param string $url An optional link to use in a surrounding HTML anchor.
2055 * @param bool $accesshide True if text should be hidden (for screen readers only).
2056 * @param string $addclass Additional class names for the link, or the arrow character.
2057 * @return string HTML string.
2059 function link_arrow_left($text, $url='', $accesshide=false, $addclass='') {
2060 global $OUTPUT; // TODO: move to utput renderer
2061 $arrowclass = 'arrow ';
2063 $arrowclass .= $addclass;
2065 $arrow = '<span class="'.$arrowclass.'">'.$OUTPUT->larrow().'</span>';
2068 $htmltext = ' <span class="arrow_text">'.$text.'</span>';
2070 $htmltext = get_accesshide($htmltext);
2074 $class = 'arrow_link';
2076 $class .= ' '.$addclass;
2078 return '<a class="'.$class.'" href="'.$url.'" title="'.preg_replace('/<.*?>/','',$text).'">'.$arrow.$htmltext.'</a>';
2080 return $arrow.$htmltext;
2084 * Return a HTML element with the class "accesshide", for accessibility.
2085 * Please use cautiously - where possible, text should be visible!
2087 * @param string $text Plain text.
2088 * @param string $elem Lowercase element name, default "span".
2089 * @param string $class Additional classes for the element.
2090 * @param string $attrs Additional attributes string in the form, "name='value' name2='value2'"
2091 * @return string HTML string.
2093 function get_accesshide($text, $elem='span', $class='', $attrs='') {
2094 return "<$elem class=\"accesshide $class\" $attrs>$text</$elem>";
2098 * Return the breadcrumb trail navigation separator.
2100 * @return string HTML string.
2102 function get_separator() {
2103 //Accessibility: the 'hidden' slash is preferred for screen readers.
2104 return ' '.link_arrow_right($text='/', $url='', $accesshide=true, 'sep').' ';
2108 * Print (or return) a collapsible region, that has a caption that can
2109 * be clicked to expand or collapse the region.
2111 * If JavaScript is off, then the region will always be expanded.
2113 * @param string $contents the contents of the box.
2114 * @param string $classes class names added to the div that is output.
2115 * @param string $id id added to the div that is output. Must not be blank.
2116 * @param string $caption text displayed at the top. Clicking on this will cause the region to expand or contract.
2117 * @param string $userpref the name of the user preference that stores the user's preferred default state.
2118 * (May be blank if you do not wish the state to be persisted.
2119 * @param boolean $default Initial collapsed state to use if the user_preference it not set.
2120 * @param boolean $return if true, return the HTML as a string, rather than printing it.
2121 * @return string|void If $return is false, returns nothing, otherwise returns a string of HTML.
2123 function print_collapsible_region($contents, $classes, $id, $caption, $userpref = '', $default = false, $return = false) {
2124 $output = print_collapsible_region_start($classes, $id, $caption, $userpref, true, true);
2125 $output .= $contents;
2126 $output .= print_collapsible_region_end(true);
2136 * Print (or return) the start of a collapsible region, that has a caption that can
2137 * be clicked to expand or collapse the region. If JavaScript is off, then the region
2138 * will always be expanded.
2141 * @param string $classes class names added to the div that is output.
2142 * @param string $id id added to the div that is output. Must not be blank.
2143 * @param string $caption text displayed at the top. Clicking on this will cause the region to expand or contract.
2144 * @param boolean $userpref the name of the user preference that stores the user's preferred default state.
2145 * (May be blank if you do not wish the state to be persisted.
2146 * @param boolean $default Initial collapsed state to use if the user_preference it not set.
2147 * @param boolean $return if true, return the HTML as a string, rather than printing it.
2148 * @return string|void if $return is false, returns nothing, otherwise returns a string of HTML.
2150 function print_collapsible_region_start($classes, $id, $caption, $userpref = false, $default = false, $return = false) {
2151 global $CFG, $PAGE, $OUTPUT;
2153 // Work out the initial state.
2154 if (is_string($userpref)) {
2155 user_preference_allow_ajax_update($userpref, PARAM_BOOL);
2156 $collapsed = get_user_preferences($userpref, $default);
2158 $collapsed = $default;
2163 $classes .= ' collapsed';
2167 $output .= '<div id="' . $id . '" class="collapsibleregion ' . $classes . '">';
2168 $output .= '<div id="' . $id . '_sizer">';
2169 $output .= '<div id="' . $id . '_caption" class="collapsibleregioncaption">';
2170 $output .= $caption . ' ';
2171 $output .= '</div><div id="' . $id . '_inner" class="collapsibleregioninner">';
2172 $PAGE->requires->js_init_call('M.util.init_collapsible_region', array($id, $userpref, get_string('clicktohideshow')));
2182 * Close a region started with print_collapsible_region_start.
2184 * @param boolean $return if true, return the HTML as a string, rather than printing it.
2185 * @return string|void if $return is false, returns nothing, otherwise returns a string of HTML.
2187 function print_collapsible_region_end($return = false) {
2188 $output = '</div></div></div>';
2198 * Print a specified group's avatar.
2201 * @uses CONTEXT_COURSE
2202 * @param array|stdClass $group A single {@link group} object OR array of groups.
2203 * @param int $courseid The course ID.
2204 * @param boolean $large Default small picture, or large.
2205 * @param boolean $return If false print picture, otherwise return the output as string
2206 * @param boolean $link Enclose image in a link to view specified course?
2207 * @return string|void Depending on the setting of $return
2209 function print_group_picture($group, $courseid, $large=false, $return=false, $link=true) {
2212 if (is_array($group)) {
2214 foreach($group as $g) {
2215 $output .= print_group_picture($g, $courseid, $large, true, $link);
2225 $context = get_context_instance(CONTEXT_COURSE, $courseid);
2227 // If there is no picture, do nothing
2228 if (!$group->picture) {
2232 // If picture is hidden, only show to those with course:managegroups
2233 if ($group->hidepicture and !has_capability('moodle/course:managegroups', $context)) {
2237 if ($link or has_capability('moodle/site:accessallgroups', $context)) {
2238 $output = '<a href="'. $CFG->wwwroot .'/user/index.php?id='. $courseid .'&group='. $group->id .'">';
2248 $grouppictureurl = moodle_url::make_pluginfile_url($context->id, 'group', 'icon', $group->id, '/', $file);
2249 $output .= '<img class="grouppicture" src="'.$grouppictureurl.'"'.
2250 ' alt="'.s(get_string('group').' '.$group->name).'" title="'.s($group->name).'"/>';
2252 if ($link or has_capability('moodle/site:accessallgroups', $context)) {
2265 * Display a recent activity note
2267 * @uses CONTEXT_SYSTEM
2268 * @staticvar string $strftimerecent
2269 * @param object A time object
2270 * @param object A user object
2271 * @param string $text Text for display for the note
2272 * @param string $link The link to wrap around the text
2273 * @param bool $return If set to true the HTML is returned rather than echo'd
2274 * @param string $viewfullnames
2276 function print_recent_activity_note($time, $user, $text, $link, $return=false, $viewfullnames=null) {
2277 static $strftimerecent = null;
2280 if (is_null($viewfullnames)) {
2281 $context = get_context_instance(CONTEXT_SYSTEM);
2282 $viewfullnames = has_capability('moodle/site:viewfullnames', $context);
2285 if (is_null($strftimerecent)) {
2286 $strftimerecent = get_string('strftimerecent');
2289 $output .= '<div class="head">';
2290 $output .= '<div class="date">'.userdate($time, $strftimerecent).'</div>';
2291 $output .= '<div class="name">'.fullname($user, $viewfullnames).'</div>';
2292 $output .= '</div>';
2293 $output .= '<div class="info"><a href="'.$link.'">'.format_string($text,true).'</a></div>';
2303 * Returns a popup menu with course activity modules
2306 * This function returns a small popup menu with all the
2307 * course activity modules in it, as a navigation menu
2308 * outputs a simple list structure in XHTML
2309 * The data is taken from the serialised array stored in
2312 * @todo Finish documenting this function
2315 * @uses CONTEXT_COURSE
2316 * @param course $course A {@link $COURSE} object.
2317 * @param string $sections
2318 * @param string $modinfo
2319 * @param string $strsection
2320 * @param string $strjumpto
2322 * @param string $cmid
2323 * @return string The HTML block
2325 function navmenulist($course, $sections, $modinfo, $strsection, $strjumpto, $width=50, $cmid=0) {
2327 global $CFG, $OUTPUT;
2332 $doneheading = false;
2334 $coursecontext = get_context_instance(CONTEXT_COURSE, $course->id);
2336 $menu[] = '<ul class="navmenulist"><li class="jumpto section"><span>'.$strjumpto.'</span><ul>';
2337 foreach ($modinfo->cms as $mod) {
2338 if ($mod->modname == 'label') {
2342 if ($mod->sectionnum > $course->numsections) { /// Don't show excess hidden sections
2346 if (!$mod->uservisible) { // do not icnlude empty sections at all
2350 if ($mod->sectionnum >= 0 and $section != $mod->sectionnum) {
2351 $thissection = $sections[$mod->sectionnum];
2353 if ($thissection->visible or !$course->hiddensections or
2354 has_capability('moodle/course:viewhiddensections', $coursecontext)) {
2355 $thissection->summary = strip_tags(format_string($thissection->summary,true));
2356 if (!$doneheading) {
2357 $menu[] = '</ul></li>';
2359 if ($course->format == 'weeks' or empty($thissection->summary)) {
2360 $item = $strsection ." ". $mod->sectionnum;
2362 if (strlen($thissection->summary) < ($width-3)) {
2363 $item = $thissection->summary;
2365 $item = substr($thissection->summary, 0, $width).'...';
2368 $menu[] = '<li class="section"><span>'.$item.'</span>';
2370 $doneheading = true;
2372 $section = $mod->sectionnum;
2374 // no activities from this hidden section shown
2379 $url = $mod->modname .'/view.php?id='. $mod->id;
2380 $mod->name = strip_tags(format_string($mod->name ,true));
2381 if (strlen($mod->name) > ($width+5)) {
2382 $mod->name = substr($mod->name, 0, $width).'...';
2384 if (!$mod->visible) {
2385 $mod->name = '('.$mod->name.')';
2387 $class = 'activity '.$mod->modname;
2388 $class .= ($cmid == $mod->id) ? ' selected' : '';
2389 $menu[] = '<li class="'.$class.'">'.
2390 '<img src="'.$OUTPUT->pix_url('icon', $mod->modname) . '" alt="" />'.
2391 '<a href="'.$CFG->wwwroot.'/mod/'.$url.'">'.$mod->name.'</a></li>';
2395 $menu[] = '</ul></li>';
2397 $menu[] = '</ul></li></ul>';
2399 return implode("\n", $menu);
2403 * Prints a grade menu (as part of an existing form) with help
2404 * Showing all possible numerical grades and scales
2406 * @todo Finish documenting this function
2407 * @todo Deprecate: this is only used in a few contrib modules
2410 * @param int $courseid The course ID
2411 * @param string $name
2412 * @param string $current
2413 * @param boolean $includenograde Include those with no grades
2414 * @param boolean $return If set to true returns rather than echo's
2415 * @return string|bool Depending on value of $return
2417 function print_grade_menu($courseid, $name, $current, $includenograde=true, $return=false) {
2419 global $CFG, $OUTPUT;
2422 $strscale = get_string('scale');
2423 $strscales = get_string('scales');
2425 $scales = get_scales_menu($courseid);
2426 foreach ($scales as $i => $scalename) {
2427 $grades[-$i] = $strscale .': '. $scalename;
2429 if ($includenograde) {
2430 $grades[0] = get_string('nograde');
2432 for ($i=100; $i>=1; $i--) {
2435 $output .= html_writer::select($grades, $name, $current, false);
2437 $linkobject = '<span class="helplink"><img class="iconhelp" alt="'.$strscales.'" src="'.$OUTPUT->pix_url('help') . '" /></span>';
2438 $link = new moodle_url('/course/scales.php', array('id'=>$courseid, 'list'=>1));
2439 $action = new popup_action('click', $link->url, 'ratingscales', array('height' => 400, 'width' => 500));
2440 $output .= $OUTPUT->action_link($link, $linkobject, $action, array('title'=>$strscales));
2450 * Print an error to STDOUT and exit with a non-zero code. For commandline scripts.
2451 * Default errorcode is 1.
2453 * Very useful for perl-like error-handling:
2455 * do_somethting() or mdie("Something went wrong");
2457 * @param string $msg Error message
2458 * @param integer $errorcode Error code to emit
2460 function mdie($msg='', $errorcode=1) {
2461 trigger_error($msg);
2466 * Print a message and exit.
2468 * @param string $message The message to print in the notice
2469 * @param string $link The link to use for the continue button
2470 * @param object $course A course object
2471 * @return void This function simply exits
2473 function notice ($message, $link='', $course=NULL) {
2474 global $CFG, $SITE, $COURSE, $PAGE, $OUTPUT;
2476 $message = clean_text($message); // In case nasties are in here
2479 echo("!!$message!!\n");
2480 exit(1); // no success
2483 if (!$PAGE->headerprinted) {
2484 //header not yet printed
2485 $PAGE->set_title(get_string('notice'));
2486 echo $OUTPUT->header();
2488 echo $OUTPUT->container_end_all(false);
2491 echo $OUTPUT->box($message, 'generalbox', 'notice');
2492 echo $OUTPUT->continue_button($link);
2494 echo $OUTPUT->footer();
2495 exit(1); // general error code
2499 * Redirects the user to another page, after printing a notice
2501 * This function calls the OUTPUT redirect method, echo's the output
2502 * and then dies to ensure nothing else happens.
2504 * <strong>Good practice:</strong> You should call this method before starting page
2505 * output by using any of the OUTPUT methods.
2507 * @param moodle_url|string $url A moodle_url to redirect to. Strings are not to be trusted!
2508 * @param string $message The message to display to the user
2509 * @param int $delay The delay before redirecting
2510 * @return void - does not return!
2512 function redirect($url, $message='', $delay=-1) {
2513 global $OUTPUT, $PAGE, $SESSION, $CFG;
2515 if (CLI_SCRIPT or AJAX_SCRIPT) {
2516 // this is wrong - developers should not use redirect in these scripts,
2517 // but it should not be very likely
2518 throw new moodle_exception('redirecterrordetected', 'error');
2521 // prevent debug errors - make sure context is properly initialised
2522 $PAGE->set_context(null);
2524 if ($url instanceof moodle_url) {
2525 $url = $url->out(false);
2528 if (!empty($CFG->usesid) && !isset($_COOKIE[session_name()])) {
2529 $url = $SESSION->sid_process_url($url);
2532 $debugdisableredirect = false;
2534 if (defined('DEBUGGING_PRINTED')) {
2535 // some debugging already printed, no need to look more
2536 $debugdisableredirect = true;
2540 if (empty($CFG->debugdisplay) or empty($CFG->debug)) {
2541 // no errors should be displayed
2545 if (!function_exists('error_get_last') or !$lasterror = error_get_last()) {
2549 if (!($lasterror['type'] & $CFG->debug)) {
2550 //last error not interesting
2554 // watch out here, @hidden() errors are returned from error_get_last() too
2555 if (headers_sent()) {
2556 //we already started printing something - that means errors likely printed
2557 $debugdisableredirect = true;
2561 if (ob_get_level() and ob_get_contents()) {
2562 // there is something waiting to be printed, hopefully it is the errors,
2563 // but it might be some error hidden by @ too - such as the timezone mess from setup.php
2564 $debugdisableredirect = true;
2569 if (!empty($message)) {
2570 if ($delay === -1 || !is_numeric($delay)) {
2573 $message = clean_text($message);
2575 $message = get_string('pageshouldredirect');
2577 // We are going to try to use a HTTP redirect, so we need a full URL.
2578 if (!preg_match('|^[a-z]+:|', $url)) {
2579 // Get host name http://www.wherever.com
2580 $hostpart = preg_replace('|^(.*?[^:/])/.*$|', '$1', $CFG->wwwroot);
2581 if (preg_match('|^/|', $url)) {
2582 // URLs beginning with / are relative to web server root so we just add them in
2583 $url = $hostpart.$url;
2585 // URLs not beginning with / are relative to path of current script, so add that on.
2586 $url = $hostpart.preg_replace('|\?.*$|','',me()).'/../'.$url;
2590 $newurl = preg_replace('|/(?!\.\.)[^/]*/\.\./|', '/', $url);
2591 if ($newurl == $url) {
2599 if (defined('MDL_PERF') || (!empty($CFG->perfdebug) and $CFG->perfdebug > 7)) {
2600 if (defined('MDL_PERFTOLOG') && !function_exists('register_shutdown_function')) {
2601 $perf = get_performance_info();
2602 error_log("PERF: " . $perf['txt']);
2606 $encodedurl = preg_replace("/\&(?![a-zA-Z0-9#]{1,8};)/", "&", $url);
2607 $encodedurl = preg_replace('/^.*href="([^"]*)".*$/', "\\1", clean_text('<a href="'.$encodedurl.'" />'));
2609 if ($delay == 0 && !$debugdisableredirect && !headers_sent()) {
2610 //302 might not work for POST requests, 303 is ignored by obsolete clients.
2611 @header($_SERVER['SERVER_PROTOCOL'] . ' 303 See Other');
2612 @header('Location: '.$url);
2613 echo bootstrap_renderer::plain_redirect_message($encodedurl);
2617 // Include a redirect message, even with a HTTP redirect, because that is recommended practice.
2618 $PAGE->set_pagelayout('embedded'); // No header and footer needed
2619 $CFG->docroot = false; // to prevent the link to moodle docs from being displayed on redirect page.
2620 echo $OUTPUT->redirect_message($encodedurl, $message, $delay, $debugdisableredirect);
2625 * Given an email address, this function will return an obfuscated version of it
2627 * @param string $email The email address to obfuscate
2628 * @return string The obfuscated email address
2630 function obfuscate_email($email) {
2633 $length = strlen($email);
2635 while ($i < $length) {
2636 if (rand(0,2) && $email{$i}!='@') { //MDL-20619 some browsers have problems unobfuscating @
2637 $obfuscated.='%'.dechex(ord($email{$i}));
2639 $obfuscated.=$email{$i};
2647 * This function takes some text and replaces about half of the characters
2648 * with HTML entity equivalents. Return string is obviously longer.
2650 * @param string $plaintext The text to be obfuscated
2651 * @return string The obfuscated text
2653 function obfuscate_text($plaintext) {
2656 $length = strlen($plaintext);
2658 $prev_obfuscated = false;
2659 while ($i < $length) {
2660 $c = ord($plaintext{$i});
2661 $numerical = ($c >= ord('0')) && ($c <= ord('9'));
2662 if ($prev_obfuscated and $numerical ) {
2663 $obfuscated.='&#'.ord($plaintext{$i}).';';
2664 } else if (rand(0,2)) {
2665 $obfuscated.='&#'.ord($plaintext{$i}).';';
2666 $prev_obfuscated = true;
2668 $obfuscated.=$plaintext{$i};
2669 $prev_obfuscated = false;
2677 * This function uses the {@link obfuscate_email()} and {@link obfuscate_text()}
2678 * to generate a fully obfuscated email link, ready to use.
2680 * @param string $email The email address to display
2681 * @param string $label The text to displayed as hyperlink to $email
2682 * @param boolean $dimmed If true then use css class 'dimmed' for hyperlink
2683 * @return string The obfuscated mailto link
2685 function obfuscate_mailto($email, $label='', $dimmed=false) {
2687 if (empty($label)) {
2691 $title = get_string('emaildisable');
2692 $dimmed = ' class="dimmed"';
2697 return sprintf("<a href=\"%s:%s\" $dimmed title=\"$title\">%s</a>",
2698 obfuscate_text('mailto'), obfuscate_email($email),
2699 obfuscate_text($label));
2703 * This function is used to rebuild the <nolink> tag because some formats (PLAIN and WIKI)
2704 * will transform it to html entities
2706 * @param string $text Text to search for nolink tag in
2709 function rebuildnolinktag($text) {
2711 $text = preg_replace('/<(\/*nolink)>/i','<$1>',$text);
2717 * Prints a maintenance message from $CFG->maintenance_message or default if empty
2720 function print_maintenance_message() {
2721 global $CFG, $SITE, $PAGE, $OUTPUT;
2723 $PAGE->set_pagetype('maintenance-message');
2724 $PAGE->set_pagelayout('maintenance');
2725 $PAGE->set_title(strip_tags($SITE->fullname));
2726 $PAGE->set_heading($SITE->fullname);
2727 echo $OUTPUT->header();
2728 echo $OUTPUT->heading(get_string('sitemaintenance', 'admin'));
2729 if (isset($CFG->maintenance_message) and !html_is_blank($CFG->maintenance_message)) {
2730 echo $OUTPUT->box_start('maintenance_message generalbox boxwidthwide boxaligncenter');
2731 echo $CFG->maintenance_message;
2732 echo $OUTPUT->box_end();
2734 echo $OUTPUT->footer();
2739 * Adjust the list of allowed tags based on $CFG->allowobjectembed and user roles (admin)
2745 function adjust_allowed_tags() {
2747 global $CFG, $ALLOWED_TAGS;
2749 if (!empty($CFG->allowobjectembed)) {
2750 $ALLOWED_TAGS .= '<embed><object>';
2755 * A class for tabs, Some code to print tabs
2757 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2758 * @package moodlecore
2770 var $linkedwhenselected;
2773 * A constructor just because I like constructors
2776 * @param string $link
2777 * @param string $text
2778 * @param string $title
2779 * @param bool $linkedwhenselected
2781 function tabobject ($id, $link='', $text='', $title='', $linkedwhenselected=false) {
2783 $this->link = $link;
2784 $this->text = $text;
2785 $this->title = $title ? $title : $text;
2786 $this->linkedwhenselected = $linkedwhenselected;
2793 * Returns a string containing a nested list, suitable for formatting into tabs with CSS.
2796 * @param array $tabrows An array of rows where each row is an array of tab objects
2797 * @param string $selected The id of the selected tab (whatever row it's on)
2798 * @param array $inactive An array of ids of inactive tabs that are not selectable.
2799 * @param array $activated An array of ids of other tabs that are currently activated
2800 * @param bool $return If true output is returned rather then echo'd
2802 function print_tabs($tabrows, $selected=NULL, $inactive=NULL, $activated=NULL, $return=false) {
2805 /// $inactive must be an array
2806 if (!is_array($inactive)) {
2807 $inactive = array();
2810 /// $activated must be an array
2811 if (!is_array($activated)) {
2812 $activated = array();
2815 /// Convert the tab rows into a tree that's easier to process
2816 if (!$tree = convert_tabrows_to_tree($tabrows, $selected, $inactive, $activated)) {
2820 /// Print out the current tree of tabs (this function is recursive)
2822 $output = convert_tree_to_html($tree);
2824 $output = "\n\n".'<div class="tabtree">'.$output.'</div><div class="clearer"> </div>'."\n\n";
2835 * Converts a nested array tree into HTML ul:li [recursive]
2837 * @param array $tree A tree array to convert
2838 * @param int $row Used in identifying the iteration level and in ul classes
2839 * @return string HTML structure
2841 function convert_tree_to_html($tree, $row=0) {
2843 $str = "\n".'<ul class="tabrow'.$row.'">'."\n";
2846 $count = count($tree);
2848 foreach ($tree as $tab) {
2849 $count--; // countdown to zero
2853 if ($first && ($count == 0)) { // Just one in the row
2854 $liclass = 'first last';
2856 } else if ($first) {
2859 } else if ($count == 0) {
2863 if ((empty($tab->subtree)) && (!empty($tab->selected))) {
2864 $liclass .= (empty($liclass)) ? 'onerow' : ' onerow';
2867 if ($tab->inactive || $tab->active || $tab->selected) {
2868 if ($tab->selected) {
2869 $liclass .= (empty($liclass)) ? 'here selected' : ' here selected';
2870 } else if ($tab->active) {
2871 $liclass .= (empty($liclass)) ? 'here active' : ' here active';
2875 $str .= (!empty($liclass)) ? '<li class="'.$liclass.'">' : '<li>';
2877 if ($tab->inactive || $tab->active || ($tab->selected && !$tab->linkedwhenselected)) {
2878 // The a tag is used for styling
2879 $str .= '<a class="nolink"><span>'.$tab->text.'</span></a>';
2881 $str .= '<a href="'.$tab->link.'" title="'.$tab->title.'"><span>'.$tab->text.'</span></a>';
2884 if (!empty($tab->subtree)) {
2885 $str .= convert_tree_to_html($tab->subtree, $row+1);
2886 } else if ($tab->selected) {
2887 $str .= '<div class="tabrow'.($row+1).' empty"> </div>'."\n";
2890 $str .= ' </li>'."\n";
2892 $str .= '</ul>'."\n";
2898 * Convert nested tabrows to a nested array
2900 * @param array $tabrows A [nested] array of tab row objects
2901 * @param string $selected The tabrow to select (by id)
2902 * @param array $inactive An array of tabrow id's to make inactive
2903 * @param array $activated An array of tabrow id's to make active
2904 * @return array The nested array
2906 function convert_tabrows_to_tree($tabrows, $selected, $inactive, $activated) {
2908 /// Work backwards through the rows (bottom to top) collecting the tree as we go.
2910 $tabrows = array_reverse($tabrows);
2914 foreach ($tabrows as $row) {
2917 foreach ($row as $tab) {
2918 $tab->inactive = in_array((string)$tab->id, $inactive);
2919 $tab->active = in_array((string)$tab->id, $activated);
2920 $tab->selected = (string)$tab->id == $selected;
2922 if ($tab->active || $tab->selected) {
2924 $tab->subtree = $subtree;
2936 * Returns the Moodle Docs URL in the users language
2939 * @param string $path the end of the URL.
2940 * @return string The MoodleDocs URL in the user's language. for example {@link http://docs.moodle.org/en/ http://docs.moodle.org/en/$path}
2942 function get_docs_url($path) {
2944 return $CFG->docroot . '/' . current_language() . '/' . $path;
2949 * Standard Debugging Function
2951 * Returns true if the current site debugging settings are equal or above specified level.
2952 * If passed a parameter it will emit a debugging notice similar to trigger_error(). The
2953 * routing of notices is controlled by $CFG->debugdisplay
2956 * 1) debugging('a normal debug notice');
2957 * 2) debugging('something really picky', DEBUG_ALL);
2958 * 3) debugging('annoying debug message only for developers', DEBUG_DEVELOPER);
2959 * 4) if (debugging()) { perform extra debugging operations (do not use print or echo) }
2961 * In code blocks controlled by debugging() (such as example 4)
2962 * any output should be routed via debugging() itself, or the lower-level
2963 * trigger_error() or error_log(). Using echo or print will break XHTML
2964 * JS and HTTP headers.
2966 * It is also possible to define NO_DEBUG_DISPLAY which redirects the message to error_log.
2968 * @uses DEBUG_NORMAL
2969 * @param string $message a message to print
2970 * @param int $level the level at which this debugging statement should show
2971 * @param array $backtrace use different backtrace
2974 function debugging($message = '', $level = DEBUG_NORMAL, $backtrace = null) {
2975 global $CFG, $UNITTEST;
2977 if (empty($CFG->debug) || $CFG->debug < $level) {
2981 if (!isset($CFG->debugdisplay)) {
2982 $CFG->debugdisplay = ini_get_bool('display_errors');
2987 $backtrace = debug_backtrace();
2989 $from = format_backtrace($backtrace, CLI_SCRIPT);
2990 if (!empty($UNITTEST->running)) {
2991 // When the unit tests are running, any call to trigger_error
2992 // is intercepted by the test framework and reported as an exception.
2993 // Therefore, we cannot use trigger_error during unit tests.
2994 // At the same time I do not think we should just discard those messages,
2995 // so displaying them on-screen seems like the only option. (MDL-20398)
2996 echo '<div class="notifytiny">' . $message . $from . '</div>';
2998 } else if (NO_DEBUG_DISPLAY) {
2999 // script does not want any errors or debugging in output,
3000 // we send the info to error log instead
3001 error_log('Debugging: ' . $message . $from);
3003 } else if ($CFG->debugdisplay) {
3004 if (!defined('DEBUGGING_PRINTED')) {
3005 define('DEBUGGING_PRINTED', 1); // indicates we have printed something
3007 echo '<div class="notifytiny">' . $message . $from . '</div>';
3010 trigger_error($message . $from, E_USER_NOTICE);
3017 * Outputs a HTML comment to the browser. This is used for those hard-to-debug
3018 * pages that use bits from many different files in very confusing ways (e.g. blocks).
3020 * <code>print_location_comment(__FILE__, __LINE__);</code>
3022 * @param string $file
3023 * @param integer $line
3024 * @param boolean $return Whether to return or print the comment
3025 * @return string|void Void unless true given as third parameter
3027 function print_location_comment($file, $line, $return = false)
3030 return "<!-- $file at line $line -->\n";
3032 echo "<!-- $file at line $line -->\n";
3038 * @return boolean true if the current language is right-to-left (Hebrew, Arabic etc)
3040 function right_to_left() {
3041 return (get_string('thisdirection', 'langconfig') === 'rtl');
3046 * Returns swapped left<=>right if in RTL environment.
3047 * part of RTL support
3049 * @param string $align align to check
3052 function fix_align_rtl($align) {
3053 if (!right_to_left()) {
3056 if ($align=='left') { return 'right'; }
3057 if ($align=='right') { return 'left'; }
3063 * Returns true if the page is displayed in a popup window.
3064 * Gets the information from the URL parameter inpopup.
3066 * @todo Use a central function to create the popup calls all over Moodle and
3067 * In the moment only works with resources and probably questions.
3071 function is_in_popup() {
3072 $inpopup = optional_param('inpopup', '', PARAM_BOOL);
3078 * To use this class.
3080 * - call create (or use the 3rd param to the constructor)
3081 * - call update or update_full repeatedly
3083 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3084 * @package moodlecore
3086 class progress_bar {
3087 /** @var string html id */
3096 private $time_start;
3097 private $minimum_time = 2; //min time between updates.
3101 * @param string $html_id
3103 * @param bool $autostart Default to false
3105 public function __construct($html_id = '', $width = 500, $autostart = false){
3106 if (!empty($html_id)) {
3107 $this->html_id = $html_id;
3109 $this->html_id = uniqid();
3111 $this->width = $width;
3118 * Create a new progress bar, this function will output html.
3120 * @return void Echo's output
3122 public function create(){
3124 $this->lastcall->pt = 0;
3125 $this->lastcall->time = microtime(true);
3127 return; // temporary solution for cli scripts
3130 <div style="text-align:center;width:{$this->width}px;clear:both;padding:0;margin:0 auto;">
3131 <h2 id="status_{$this->html_id}" style="text-align: center;margin:0 auto"></h2>
3132 <p id="time_{$this->html_id}"></p>
3133 <div id="bar_{$this->html_id}" style="border-style:solid;border-width:1px;width:500px;height:50px;">
3134 <div id="progress_{$this->html_id}"
3135 style="text-align:center;background:#FFCC66;width:4px;border:1px
3136 solid gray;height:38px; padding-top:10px;"> <span id="pt_{$this->html_id}"></span>
3145 * Update the progress bar
3147 * @param int $percent from 1-100
3148 * @param string $msg
3150 * @return void Echo's output
3152 private function _update($percent, $msg, $es){
3154 if(empty($this->time_start)){
3155 $this->time_start = microtime(true);
3157 $this->percent = $percent;
3158 $this->lastcall->time = microtime(true);
3159 $this->lastcall->pt = $percent;
3160 $w = $this->percent * $this->width;
3162 return; // temporary solution for cli scripts
3167 echo html_writer::script(js_writer::function_call('update_progress_bar', Array($this->html_id, $w, $this->percent, $msg, $es)));
3173 * @param int $curtime the time call this function
3174 * @param int $percent from 1-100
3175 * @return mixed Null, or int
3177 private function estimate($curtime, $pt){
3178 $consume = $curtime - $this->time_start;
3179 $one = $curtime - $this->lastcall->time;
3180 $this->percent = $pt;
3181 $percent = $pt - $this->lastcall->pt;
3182 if ($percent != 0) {
3183 $left = ($one / $percent) - $consume;
3194 * Update progress bar according percent
3196 * @param int $percent from 1-100
3197 * @param string $msg the message needed to be shown
3199 public function update_full($percent, $msg){
3200 $percent = max(min($percent, 100), 0);
3201 if ($percent != 100 && ($this->lastcall->time + $this->minimum_time) > microtime(true)){
3204 $this->_update($percent, 100, $msg);
3207 * Update progress bar according the number of tasks
3209 * @param int $cur current task number
3210 * @param int $total total task number
3211 * @param string $msg message
3213 public function update($cur, $total, $msg){
3214 $cur = max($cur, 0);
3215 if ($cur >= $total){
3218 $percent = $cur / $total;
3221 if ($percent != 1 && ($this->lastcall->time + $this->minimum_time) > microtime(true)){
3225 $es = $this->estimate(microtime(true), $percent);
3226 $this->_update($percent, $msg, $es);
3229 * Restart the progress bar.
3231 public function restart(){
3233 $this->lastcall = new stdClass;
3234 $this->lastcall->pt = 0;
3235 $this->lastcall->time = microtime(true);
3236 $this->time_start = 0;
3241 * Use this class from long operations where you want to output occasional information about
3242 * what is going on, but don't know if, or in what format, the output should be.
3244 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3245 * @package moodlecore
3247 abstract class progress_trace {
3249 * Ouput an progress message in whatever format.
3250 * @param string $message the message to output.
3251 * @param integer $depth indent depth for this message.
3253 abstract public function output($message, $depth = 0);
3256 * Called when the processing is finished.
3258 public function finished() {
3263 * This subclass of progress_trace does not ouput anything.
3265 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3266 * @package moodlecore
3268 class null_progress_trace extends progress_trace {
3272 * @param string $message
3274 * @return void Does Nothing
3276 public function output($message, $depth = 0) {
3281 * This subclass of progress_trace outputs to plain text.
3283 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3284 * @package moodlecore
3286 class text_progress_trace extends progress_trace {
3288 * Output the trace message
3290 * @param string $message
3292 * @return void Output is echo'd
3294 public function output($message, $depth = 0) {
3295 echo str_repeat(' ', $depth), $message, "\n";
3301 * This subclass of progress_trace outputs as HTML.
3303 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3304 * @package moodlecore
3306 class html_progress_trace extends progress_trace {
3308 * Output the trace message
3310 * @param string $message
3312 * @return void Output is echo'd
3314 public function output($message, $depth = 0) {
3315 echo '<p>', str_repeat('  ', $depth), htmlspecialchars($message), "</p>\n";
3321 * HTML List Progress Tree
3323 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3324 * @package moodlecore
3326 class html_list_progress_trace extends progress_trace {
3328 protected $currentdepth = -1;
3333 * @param string $message The message to display
3335 * @return void Output is echoed
3337 public function output($message, $depth = 0) {
3339 while ($this->currentdepth > $depth) {
3340 echo "</li>\n</ul>\n";
3341 $this->currentdepth -= 1;
3342 if ($this->currentdepth == $depth) {
3347 while ($this->currentdepth < $depth) {
3349 $this->currentdepth += 1;
3355 echo htmlspecialchars($message);
3360 * Called when the processing is finished.
3362 public function finished() {
3363 while ($this->currentdepth >= 0) {
3364 echo "</li>\n</ul>\n";
3365 $this->currentdepth -= 1;
3371 * Returns a localized sentence in the current language summarizing the current password policy
3373 * @todo this should be handled by a function/method in the language pack library once we have a support for it
3377 function print_password_policy() {
3381 if (!empty($CFG->passwordpolicy)) {
3382 $messages = array();
3383 $messages[] = get_string('informminpasswordlength', 'auth', $CFG->minpasswordlength);
3384 if (!empty($CFG->minpassworddigits)) {
3385 $messages[] = get_string('informminpassworddigits', 'auth', $CFG->minpassworddigits);
3387 if (!empty($CFG->minpasswordlower)) {
3388 $messages[] = get_string('informminpasswordlower', 'auth', $CFG->minpasswordlower);
3390 if (!empty($CFG->minpasswordupper)) {
3391 $messages[] = get_string('informminpasswordupper', 'auth', $CFG->minpasswordupper);
3393 if (!empty($CFG->minpasswordnonalphanum)) {
3394 $messages[] = get_string('informminpasswordnonalphanum', 'auth', $CFG->minpasswordnonalphanum);
3397 $messages = join(', ', $messages); // this is ugly but we do not have anything better yet...
3398 $message = get_string('informpasswordpolicy', 'auth', $messages);
3403 function create_ufo_inline($id, $args) {
3405 // must not use $PAGE, $THEME, $COURSE etc. because the result is cached!
3406 // unfortunately this ufo.js can not be cached properly because we do not have access to current $CFG either
3407 $jsoutput = html_writer::script('', $CFG->wwwroot.'/lib/ufo.js');
3408 $jsoutput .= html_writer::script(js_writer::function_call('M.util.create_UFO_object', array($id, $args)));
3412 function create_flowplayer($id, $fileurl, $type='flv', $color='#000000') {
3415 $playerpath = $CFG->wwwroot.'/filter/mediaplugin/'.$type.'player.swf';
3416 $jsoutput = html_writer::script('', $CFG->wwwroot.'/lib/flowplayer.js');
3418 if ($type == 'flv') {
3419 $jsoutput .= html_writer::script(js_writer::function_call('M.util.init_flvflowplayer', array($id, $playerpath, $fileurl)));
3420 } else if ($type == 'mp3') {
3421 $audioplayerpath = $CFG->wwwroot .'/filter/mediaplugin/flowplayer.audio.swf';
3422 $jsoutput .= html_writer::script(js_writer::function_call('M.util.init_mp3flowplayerplugin', array($id, $playerpath, $audioplayerpath, $fileurl, $color)));