MDL-24450 - searching in mapcourses fails
[moodle.git] / lib / weblib.php
1 <?php
3 // This file is part of Moodle - http://moodle.org/
4 //
5 // Moodle is free software: you can redistribute it and/or modify
6 // it under the terms of the GNU General Public License as published by
7 // the Free Software Foundation, either version 3 of the License, or
8 // (at your option) any later version.
9 //
10 // Moodle is distributed in the hope that it will be useful,
11 // but WITHOUT ANY WARRANTY; without even the implied warranty of
12 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13 // GNU General Public License for more details.
14 //
15 // You should have received a copy of the GNU General Public License
16 // along with Moodle.  If not, see <http://www.gnu.org/licenses/>.
18 /**
19  * Library of functions for web output
20  *
21  * Library of all general-purpose Moodle PHP functions and constants
22  * that produce HTML output
23  *
24  * Other main libraries:
25  * - datalib.php - functions that access the database.
26  * - moodlelib.php - general-purpose Moodle functions.
27  *
28  * @package    core
29  * @subpackage lib
30  * @copyright  1999 onwards Martin Dougiamas {@link http://moodle.com}
31  * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
32  */
34 defined('MOODLE_INTERNAL') || die();
36 /// Constants
38 /// Define text formatting types ... eventually we can add Wiki, BBcode etc
40 /**
41  * Does all sorts of transformations and filtering
42  */
43 define('FORMAT_MOODLE',   '0');   // Does all sorts of transformations and filtering
45 /**
46  * Plain HTML (with some tags stripped)
47  */
48 define('FORMAT_HTML',     '1');   // Plain HTML (with some tags stripped)
50 /**
51  * Plain text (even tags are printed in full)
52  */
53 define('FORMAT_PLAIN',    '2');   // Plain text (even tags are printed in full)
55 /**
56  * Wiki-formatted text
57  * Deprecated: left here just to note that '3' is not used (at the moment)
58  * and to catch any latent wiki-like text (which generates an error)
59  */
60 define('FORMAT_WIKI',     '3');   // Wiki-formatted text
62 /**
63  * Markdown-formatted text http://daringfireball.net/projects/markdown/
64  */
65 define('FORMAT_MARKDOWN', '4');   // Markdown-formatted text http://daringfireball.net/projects/markdown/
67 /**
68  * TRUSTTEXT marker - if present in text, text cleaning should be bypassed
69  */
70 define('TRUSTTEXT', '#####TRUSTTEXT#####');
72 /**
73  * A moodle_url comparison using this flag will return true if the base URLs match, params are ignored
74  */
75 define('URL_MATCH_BASE', 0);
76 /**
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
78  */
79 define('URL_MATCH_PARAMS', 1);
80 /**
81  * A moodle_url comparison using this flag will return true if the two URLs are identical, except for the order of the params
82  */
83 define('URL_MATCH_EXACT', 2);
85 /**
86  * Allowed tags - string of html tags that can be tested against for safe html tags
87  * @global string $ALLOWED_TAGS
88  * @name $ALLOWED_TAGS
89  */
90 global $ALLOWED_TAGS;
91 $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>';
94 /**
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
98  */
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
104 /// Functions
106 /**
107  * Add quotes to HTML characters
108  *
109  * Returns $var with HTML characters (like "<", ">", etc.) properly quoted.
110  * This function is very similar to {@link p()}
111  *
112  * @todo Remove obsolete param $obsolete if not used anywhere
113  *
114  * @param string $var the string potentially containing HTML characters
115  * @param boolean $obsolete no longer used.
116  * @return string
117  */
118 function s($var, $obsolete = false) {
120     if ($var === '0' or $var === false or $var === 0) {
121         return '0';
122     }
124     return preg_replace("/&amp;#(\d+|x[0-7a-fA-F]+);/i", "&#$1;", htmlspecialchars($var, ENT_QUOTES, 'UTF-8', true));
127 /**
128  * Add quotes to HTML characters
129  *
130  * Prints $var with HTML characters (like "<", ">", etc.) properly quoted.
131  * This function simply calls {@link s()}
132  * @see s()
133  *
134  * @todo Remove obsolete param $obsolete if not used anywhere
135  *
136  * @param string $var the string potentially containing HTML characters
137  * @param boolean $obsolete no longer used.
138  * @return string
139  */
140 function p($var, $obsolete = false) {
141     echo s($var, $obsolete);
144 /**
145  * Does proper javascript quoting.
146  *
147  * Do not use addslashes anymore, because it does not work when magic_quotes_sybase is enabled.
148  *
149  * @param mixed $var String, Array, or Object to add slashes to
150  * @return mixed quoted result
151  */
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);
163         }
164         $var = (object)$a;
165     }
166     return $var;
169 /**
170  * Remove query string from url
171  *
172  * Takes in a URL and returns it without the querystring portion
173  *
174  * @param string $url the url which may have a query string attached
175  * @return string The remaining URL
176  */
177  function strip_querystring($url) {
179     if ($commapos = strpos($url, '?')) {
180         return substr($url, 0, $commapos);
181     } else {
182         return $url;
183     }
186 /**
187  * Returns the URL of the HTTP_REFERER, less the querystring portion if required
188  *
189  * @uses $_SERVER
190  * @param boolean $stripquery if true, also removes the query part of the url.
191  * @return string The resulting referer or empty string
192  */
193 function get_referer($stripquery=true) {
194     if (isset($_SERVER['HTTP_REFERER'])) {
195         if ($stripquery) {
196             return strip_querystring($_SERVER['HTTP_REFERER']);
197         } else {
198             return $_SERVER['HTTP_REFERER'];
199         }
200     } else {
201         return '';
202     }
206 /**
207  * Returns the name of the current script, WITH the querystring portion.
208  *
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.
213  *
214  * @global string
215  * @return mixed String, or false if the global variables needed are not set
216  */
217 function me() {
218     global $ME;
219     return $ME;
222 /**
223  * Returns the name of the current script, WITH the full URL.
224  *
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.
229  *
230  * Like {@link me()} but returns a full URL
231  * @see me()
232  *
233  * @global string
234  * @return mixed String, or false if the global variables needed are not set
235  */
236 function qualified_me() {
237     global $FULLME;
238     return $FULLME;
241 /**
242  * Class for creating and manipulating urls.
243  *
244  * It can be used in moodle pages where config.php has been included without any further includes.
245  *
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
254  *
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
258  */
259 class moodle_url {
260     /**
261      * Scheme, ex.: http, https
262      * @var string
263      */
264     protected $scheme = '';
265     /**
266      * hostname
267      * @var string
268      */
269     protected $host = '';
270     /**
271      * Port number, empty means default 80 or 443 in case of http
272      * @var unknown_type
273      */
274     protected $port = '';
275     /**
276      * Username for http auth
277      * @var string
278      */
279     protected $user = '';
280     /**
281      * Password for http auth
282      * @var string
283      */
284     protected $pass = '';
285     /**
286      * Script path
287      * @var string
288      */
289     protected $path = '';
290     /**
291      * Optional slash argument value
292      * @var string
293      */
294     protected $slashargument = '';
295     /**
296      * Anchor, may be also empty, null means none
297      * @var string
298      */
299     protected $anchor = null;
300     /**
301      * Url parameters as associative array
302      * @var array
303      */
304     protected $params = array(); // Associative array of query string params
306     /**
307      * Create new instance of moodle_url.
308      *
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
314      */
315     public function __construct($url, array $params = null) {
316         global $CFG;
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;
329         } else {
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);
337             }
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;
344             }
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);
350                 }
351             }
353             // parse the $url
354             $parts = parse_url($url);
355             if ($parts === false) {
356                 throw new moodle_exception('invalidurl');
357             }
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('&amp;', '&', $parts['query']), $this->params);
362             }
363             unset($parts['query']);
364             foreach ($parts as $key => $value) {
365                 $this->$key = $value;
366             }
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);
373             }
374         }
376         $this->params($params);
377     }
379     /**
380      * Add an array of params to the params for this url.
381      *
382      * The added params override existing ones if they have the same name.
383      *
384      * @param array $params Defaults to null. If null then returns all params.
385      * @return array Array of Params for url.
386      */
387     public function params(array $params = null) {
388         $params = (array)$params;
390         foreach ($params as $key=>$value) {
391             if (is_int($key)) {
392                 throw new coding_exception('Url parameters can not have numeric keys!');
393             }
394             if (is_array($value)) {
395                 throw new coding_exception('Url parameters values can not be arrays!');
396             }
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!');
399             }
400             $this->params[$key] = (string)$value;
401         }
402         return $this->params;
403     }
405     /**
406      * Remove all params if no arguments passed.
407      * Remove selected params if arguments are passed.
408      *
409      * Can be called as either remove_params('param1', 'param2')
410      * or remove_params(array('param1', 'param2')).
411      *
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
415      */
416     public function remove_params($params = null) {
417         if (!is_array($params)) {
418             $params = func_get_args();
419         }
420         foreach ($params as $param) {
421             unset($this->params[$param]);
422         }
423         return $this->params;
424     }
426     /**
427      * Remove all url parameters
428      * @param $params
429      * @return void
430      */
431     public function remove_all_params($params = null) {
432         $this->params = array();
433         $this->slashargument = '';
434     }
436     /**
437      * Add a param to the params for this url.
438      *
439      * The added param overrides existing one if they have the same name.
440      *
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
444      */
445     public function param($paramname, $newvalue = '') {
446         if (func_num_args() > 1) {
447             // set new value
448             $this->params(array($paramname=>$newvalue));
449         }
450         if (isset($this->params[$paramname])) {
451             return $this->params[$paramname];
452         } else {
453             return null;
454         }
455     }
457     /**
458      * Merges parameters and validates them
459      * @param array $overrideparams
460      * @return array merged parameters
461      */
462     protected function merge_overrideparams(array $overrideparams = null) {
463         $overrideparams = (array)$overrideparams;
464         $params = $this->params;
465         foreach ($overrideparams as $key=>$value) {
466             if (is_int($key)) {
467                 throw new coding_exception('Overridden parameters can not have numeric keys!');
468             }
469             if (is_array($value)) {
470                 throw new coding_exception('Overridden parameters values can not be arrays!');
471             }
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!');
474             }
475             $params[$key] = (string)$value;
476         }
477         return $params;
478     }
480     /**
481      * Get the params as as a query string.
482      * This method should not be used outside of this method.
483      *
484      * @param boolean $escaped Use &amp; 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.
488      */
489     public function get_query_string($escaped = true, array $overrideparams = null) {
490         $arr = array();
491         $params = $this->merge_overrideparams($overrideparams);
492         foreach ($params as $key => $val) {
493            $arr[] = rawurlencode($key)."=".rawurlencode($val);
494         }
495         if ($escaped) {
496             return implode('&amp;', $arr);
497         } else {
498             return implode('&', $arr);
499         }
500     }
502     /**
503      * Shortcut for printing of encoded URL.
504      * @return string
505      */
506     public function __toString() {
507         return $this->out(true);
508     }
510     /**
511      * Output url
512      *
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.
515      *
516      * @param boolean $escaped Use &amp; 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
519      */
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.');
523         }
525         $uri = $this->out_omit_querystring().$this->slashargument;
527         $querystring = $this->get_query_string($escaped, $overrideparams);
528         if ($querystring !== '') {
529             $uri .= '?' . $querystring;
530         }
531         if (!is_null($this->anchor)) {
532             $uri .= '#'.$this->anchor;
533         }
535         return $uri;
536     }
538     /**
539      * Returns url without parameters, everything before '?'.
540      * @return string
541      */
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 : '';
548         return $uri;
549     }
551     /**
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)
556      * @return boolean
557      */
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';
566         }
567         if (substr($baseother,-1)=='/') {
568             $baseother .= 'index.php';
569         }
571         // Compare the two base URLs
572         if ($baseself != $baseother) {
573             return false;
574         }
576         if ($matchtype == URL_MATCH_BASE) {
577             return true;
578         }
580         $urlparams = $url->params();
581         foreach ($this->params() as $param => $value) {
582             if ($param == 'sesskey') {
583                 continue;
584             }
585             if (!array_key_exists($param, $urlparams) || $urlparams[$param] != $value) {
586                 return false;
587             }
588         }
590         if ($matchtype == URL_MATCH_PARAMS) {
591             return true;
592         }
594         foreach ($urlparams as $param => $value) {
595             if ($param == 'sesskey') {
596                 continue;
597             }
598             if (!array_key_exists($param, $this->params()) || $this->param($param) != $value) {
599                 return false;
600             }
601         }
603         return true;
604     }
606     /**
607      * Sets the anchor for the URI (the bit after the hash)
608      * @param string $anchor null means remove previous
609      */
610     public function set_anchor($anchor) {
611         if (is_null($anchor)) {
612             // remove
613             $this->anchor = null;
614         } else if ($anchor === '') {
615             // special case, used as empty link
616             $this->anchor = '';
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;
620         } else {
621             // bad luck, no valid anchor found
622             $this->anchor = null;
623         }
624     }
626     /**
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
631      * @return void
632      */
633     public function set_slashargument($path, $parameter = 'file', $supported = NULL) {
634         global $CFG;
635         if (is_null($supported)) {
636             $supported = $CFG->slasharguments;
637         }
639         if ($supported) {
640             $parts = explode('/', $path);
641             $parts = array_map('rawurlencode', $parts);
642             $path  = implode('/', $parts);
643             $this->slashargument = $path;
644             unset($this->params[$parameter]);
646         } else {
647             $this->slashargument = '';
648             $this->params[$parameter] = $path;
649         }
650     }
652     // == static factory methods ==
654     /**
655      * General moodle file url.
656      * @param string $urlbase the script serving the file
657      * @param string $path
658      * @param bool $forcedownload
659      * @return moodle_url
660      */
661     public static function make_file_url($urlbase, $path, $forcedownload = false) {
662         global $CFG;
664         $params = array();
665         if ($forcedownload) {
666             $params['forcedownload'] = 1;
667         }
669         $url = new moodle_url($urlbase, $params);
670         $url->set_slashargument($path);
672         return $url;
673     }
675     /**
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
682      * @param int $itemid
683      * @param string $pathname
684      * @param string $filename
685      * @param bool $forcedownload
686      * @return moodle_url
687      */
688     public static function make_pluginfile_url($contextid, $component, $area, $itemid, $pathname, $filename, $forcedownload = false) {
689         global $CFG;
690         $urlbase = "$CFG->httpswwwroot/pluginfile.php";
691         if ($itemid === NULL) {
692             return self::make_file_url($urlbase, "/$contextid/$component/$area".$pathname.$filename, $forcedownload);
693         } else {
694             return self::make_file_url($urlbase, "/$contextid/$component/$area/$itemid".$pathname.$filename, $forcedownload);
695         }
696     }
698     /**
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
705      * @return moodle_url
706      */
707     public static function make_draftfile_url($draftid, $pathname, $filename, $forcedownload = false) {
708         global $CFG, $USER;
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);
713     }
715     /**
716      * Factory method for creating of links to legacy
717      * course files.
718      * @param int $courseid
719      * @param string $filepath
720      * @param bool $forcedownload
721      * @return moodle_url
722      */
723     public static function make_legacyfile_url($courseid, $filepath, $forcedownload = false) {
724         global $CFG;
726         $urlbase = "$CFG->wwwroot/file.php";
727         return self::make_file_url($urlbase, '/'.$courseid.'/'.$filepath, $forcedownload);
728     }
731 /**
732  * Determine if there is data waiting to be processed from a form
733  *
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
738  *
739  * Checks that submitted POST data exists and returns it as object.
740  *
741  * @uses $_POST
742  * @return mixed false or object
743  */
744 function data_submitted() {
746     if (empty($_POST)) {
747         return false;
748     } else {
749         return (object)$_POST;
750     }
753 /**
754  * Given some normal text this function will break up any
755  * long words to a given size by inserting the given character
756  *
757  * It's multibyte savvy and doesn't change anything inside html tags.
758  *
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
762  * @return string
763  */
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
770     $tags = array();
771     filter_save_tags($string,$tags);
773 /// Process the string adding the cut when necessary
774     $output = '';
775     $length = $textlib->strlen($string);
776     $wordlength = 0;
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 == ">") {
781             $wordlength = 0;
782         } else {
783             $wordlength++;
784             if ($wordlength > $maxsize) {
785                 $output .= $cutchar;
786                 $wordlength = 0;
787             }
788         }
789         $output .= $char;
790     }
792 /// Finally load the tags back again
793     if (!empty($tags)) {
794         $output = str_replace(array_keys($tags), $tags, $output);
795     }
797     return $output;
800 /**
801  * Try and close the current window using JavaScript, either immediately, or after a delay.
802  *
803  * Echo's out the resulting XHTML & javascript
804  *
805  * @global object
806  * @global object
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.
810  */
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();
817     } else {
818         $OUTPUT->container_end_all(false);
819     }
821     if ($reloadopener) {
822         $function = 'close_window_reloading_opener';
823     } else {
824         $function = 'close_window';
825     }
826     echo '<p class="centerpara">' . get_string('windowclosing') . '</p>';
828     $PAGE->requires->js_function_call($function, null, false, $delay);
830     echo $OUTPUT->footer();
831     exit;
834 /**
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.
837  *
838  * @global object
839  * @global object
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
843  */
844 function page_doc_link($text='') {
845     global $CFG, $PAGE, $OUTPUT;
847     if (empty($CFG->docroot) || during_initial_install()) {
848         return '';
849     }
850     if (!has_capability('moodle/site:doclinks', $PAGE->context)) {
851         return '';
852     }
854     $path = $PAGE->docspath;
855     if (!$path) {
856         return '';
857     }
858     return $OUTPUT->doc_link($path, $text);
862 /**
863  * Validates an email to make sure it makes sense.
864  *
865  * @param string $address The email address to validate.
866  * @return boolean
867  */
868 function validate_email($address) {
870     return (preg_match('#^[-!\#$%&\'*+\\/0-9=?A-Z^_`a-z{|}~]+'.
871                  '(\.[-!\#$%&\'*+\\/0-9=?A-Z^_`a-z{|}~]+)*'.
872                   '@'.
873                   '[-!\#$%&\'*+\\/0-9=?A-Z^_`a-z{|}~]+\.'.
874                   '[-!\#$%&\'*+\\./0-9=?A-Z^_`a-z{|}~]+$#',
875                   $address));
878 /**
879  * Extracts file argument either from file parameter or PATH_INFO
880  * Note: $scriptname parameter is not needed anymore
881  *
882  * @global string
883  * @uses $_SERVER
884  * @uses PARAM_PATH
885  * @return string file path (only safe characters)
886  */
887 function get_file_argument() {
888     global $SCRIPT;
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);
897         }
898     }
900     // note: we are not using any other way because they are not compatible with unicode file names ;-)
902     return $relativepath;
905 /**
906  * Just returns an array of text formats suitable for a popup menu
907  *
908  * @uses FORMAT_MOODLE
909  * @uses FORMAT_HTML
910  * @uses FORMAT_PLAIN
911  * @uses FORMAT_MARKDOWN
912  * @return array
913  */
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'));
921 /**
922  * Given text in a variety of format codings, this function returns
923  * the text as safe HTML.
924  *
925  * This function should mainly be used for long strings like posts,
926  * answers, glossary items etc. For short strings @see format_string().
927  *
928  * @todo Finish documenting this function
929  *
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
936  * @return string
937  */
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();
943     if ($text === '') {
944         return ''; // no need to do any filters and cleaning
945     }
947     $options = (array)$options; // detach object, we can not modify it
950     if (!isset($options['trusted'])) {
951         $options['trusted'] = false;
952     }
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;
957         } else {
958             $options['noclean'] = false;
959         }
960     }
961     if (!isset($options['nocache'])) {
962         $options['nocache'] = false;
963     }
964     if (!isset($options['smiley'])) {
965         $options['smiley'] = true;
966     }
967     if (!isset($options['filter'])) {
968         $options['filter'] = true;
969     }
970     if (!isset($options['para'])) {
971         $options['para'] = true;
972     }
973     if (!isset($options['newlines'])) {
974         $options['newlines'] = true;
975     }
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
980         $context = null;
982     } else if (isset($options['context'])) { // first by explicit passed context option
983         if (is_object($options['context'])) {
984             $context = $options['context'];
985         } else {
986             $context = get_context_instance_by_id($context);
987         }
988     } else if ($courseid_do_not_use) {
989         // legacy courseid
990         $context = get_context_instance(CONTEXT_COURSE, $courseid_do_not_use);
991     } else {
992         // fallback to $PAGE->context this may be problematic in CLI and other non-standard pages :-(
993         $context = $PAGE->context;
994     }
996     if (!$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;
1000     }
1002     if ($options['filter']) {
1003         $filtermanager = filter_manager::instance();
1004     } else {
1005         $filtermanager = new null_filter_manager();
1006     }
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);
1015         if (CLI_SCRIPT) {
1016             if (isset($croncache[$md5key])) {
1017                 return $croncache[$md5key];
1018             }
1019         }
1021         if ($oldcacheitem = $DB->get_record('cache_text', array('md5key'=>$md5key), '*', IGNORE_MULTIPLE)) {
1022             if ($oldcacheitem->timemodified >= $time) {
1023                 if (CLI_SCRIPT) {
1024                     if (count($croncache) > 150) {
1025                         reset($croncache);
1026                         $key = key($croncache);
1027                         unset($croncache[$key]);
1028                     }
1029                     $croncache[$md5key] = $oldcacheitem->formattedtext;
1030                 }
1031                 return $oldcacheitem->formattedtext;
1032             }
1033         }
1034     }
1036     switch ($format) {
1037         case FORMAT_HTML:
1038             if ($options['smiley']) {
1039                 replace_smilies($text);
1040             }
1041             if (!$options['noclean']) {
1042                 $text = clean_text($text, FORMAT_HTML);
1043             }
1044             $text = $filtermanager->filter_text($text, $context);
1045             break;
1047         case FORMAT_PLAIN:
1048             $text = s($text); // cleans dangerous JS
1049             $text = rebuildnolinktag($text);
1050             $text = str_replace('  ', '&nbsp; ', $text);
1051             $text = nl2br($text);
1052             break;
1054         case FORMAT_WIKI:
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);
1060             break;
1062         case FORMAT_MARKDOWN:
1063             $text = markdown_to_html($text);
1064             if ($options['smiley']) {
1065                 replace_smilies($text);
1066             }
1067             if (!$options['noclean']) {
1068                 $text = clean_text($text, FORMAT_HTML);
1069             }
1070             $text = $filtermanager->filter_text($text, $context);
1071             break;
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);
1077             }
1078             $text = $filtermanager->filter_text($text, $context);
1079             break;
1080     }
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);
1089     }
1091     if (empty($options['nocache']) and !empty($CFG->cachetext)) {
1092         if (CLI_SCRIPT) {
1093             // special static cron cache - no need to store it in db if its not already there
1094             if (count($croncache) > 150) {
1095                 reset($croncache);
1096                 $key = key($croncache);
1097                 unset($croncache[$key]);
1098             }
1099             $croncache[$md5key] = $text;
1100             return $text;
1101         }
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;
1109             try {
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.
1115             }
1116         } else {
1117             try {
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.
1125             }
1126         }
1127     }
1129     return $text;
1132 /**
1133  * Converts the text format from the value to the 'internal'
1134  * name or vice versa.
1135  *
1136  * $key can either be the value or the name and you get the other back.
1137  *
1138  * @uses FORMAT_MOODLE
1139  * @uses FORMAT_HTML
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!
1144  */
1145 function text_format_name($key) {
1146   $lookup = array();
1147   $lookup[FORMAT_MOODLE] = 'moodle';
1148   $lookup[FORMAT_HTML] = 'html';
1149   $lookup[FORMAT_PLAIN] = 'plain';
1150   $lookup[FORMAT_MARKDOWN] = 'markdown';
1151   $value = "error";
1152   if (!is_numeric($key)) {
1153     $key = strtolower( $key );
1154     $value = array_search( $key, $lookup );
1155   }
1156   else {
1157     if (isset( $lookup[$key] )) {
1158       $value =  $lookup[ $key ];
1159     }
1160   }
1161   return $value;
1164 /**
1165  * Resets all data related to filters, called during upgrade or when filter settings change.
1166  *
1167  * @global object
1168  * @global object
1169  * @return void
1170  */
1171 function reset_text_filters_cache() {
1172     global $CFG, $DB;
1174     $DB->delete_records('cache_text');
1175     $purifdir = $CFG->dataroot.'/cache/htmlpurifier';
1176     remove_dir($purifdir, true);
1179 /**
1180  * Given a simple string, this function returns the string
1181  * processed by enabled string filters if $CFG->filterall is enabled
1182  *
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.
1186  *
1187  * @global object
1188  * @global object
1189  * @global object
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
1195  * @return string
1196  */
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);
1206     }
1208     if ($strcache === false or count($strcache) > 2000) { // this number might need some tuning to limit memory usage in cron
1209         $strcache = array();
1210     }
1212     if (is_numeric($options)) {
1213         // legacy courseid usage
1214         $options  = array('context'=>get_context_instance(CONTEXT_COURSE, $options));
1215     } else {
1216         $options = (array)$options; // detach object, we can not modify it
1217     }
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']);
1224     }
1226     if (!$options['context']) {
1227         // we did not find any context? weird
1228         return $string = strip_tags($string);
1229     }
1231     //Calculate md5
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];
1237     }
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']);
1245     }
1247     // If the site requires it, strip ALL tags from this string
1248     if (!empty($CFG->formatstringstriptags)) {
1249         $string = strip_tags($string);
1251     } else {
1252         // Otherwise strip just links if that is required (default)
1253         if ($striplinks) {  //strip links in string
1254             $string = strip_links($string);
1255         }
1256         $string = clean_text($string);
1257     }
1259     //Store to cache
1260     $strcache[$md5] = $string;
1262     return $string;
1265 /**
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 &amp;. The string is then returned.
1269  *
1270  * @param string $string
1271  * @return string
1272  */
1273 function replace_ampersands_not_followed_by_entity($string) {
1274     return preg_replace("/\&(?![a-zA-Z0-9#]{1,8};)/", "&amp;", $string);
1277 /**
1278  * Given a string, replaces all <a>.*</a> by .* and returns the string.
1279  *
1280  * @param string $string
1281  * @return string
1282  */
1283 function strip_links($string) {
1284     return preg_replace('/(<a\s[^>]+?>)(.+?)(<\/a>)/is','$2',$string);
1287 /**
1288  * This expression turns links into something nice in a text format. (Russell Jungwirth)
1289  *
1290  * @param string $string
1291  * @return string
1292  */
1293 function wikify_links($string) {
1294     return preg_replace('~(<a [^<]*href=["|\']?([^ "\']*)["|\']?[^>]*>([^<]*)</a>)~i','$3 [ $2 ]', $string);
1297 /**
1298  * Replaces non-standard HTML entities
1299  *
1300  * @param string $string
1301  * @return string
1302  */
1303 function fix_non_standard_entities($string) {
1304     $text = preg_replace('/&#0*([0-9]+);?/', '&#$1;', $string);
1305     $text = preg_replace('/&#x0*([0-9a-fA-F]+);?/', '&#x$1;', $text);
1306     return $text;
1309 /**
1310  * Given text in a variety of format codings, this function returns
1311  * the text as plain text suitable for plain email.
1312  *
1313  * @uses FORMAT_MOODLE
1314  * @uses FORMAT_HTML
1315  * @uses FORMAT_PLAIN
1316  * @uses FORMAT_WIKI
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]
1321  * @return string
1322  */
1323 function format_text_email($text, $format) {
1325     switch ($format) {
1327         case FORMAT_PLAIN:
1328             return $text;
1329             break;
1331         case FORMAT_WIKI:
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)));
1335             break;
1337         case FORMAT_HTML:
1338             return html_to_text($text);
1339             break;
1341         case FORMAT_MOODLE:
1342         case FORMAT_MARKDOWN:
1343         default:
1344             $text = wikify_links($text);
1345             return strtr(strip_tags($text), array_flip(get_html_translation_table(HTML_ENTITIES)));
1346             break;
1347     }
1350 /**
1351  * Formats activity intro text
1352  *
1353  * @global object
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
1359  * @return text
1360  */
1361 function format_module_intro($module, $activity, $cmid, $filter=true) {
1362     global $CFG;
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));
1370 /**
1371  * Legacy function, used for cleaning of old forum and glossary text only.
1372  *
1373  * @global object
1374  * @param string $text text that may contain TRUSTTEXT marker
1375  * @return text without any TRUSTTEXT marker
1376  */
1377 function trusttext_strip($text) {
1378     global $CFG;
1380     while (true) { //removing nested TRUSTTEXT
1381         $orig = $text;
1382         $text = str_replace('#####TRUSTTEXT#####', '', $text);
1383         if (strcmp($orig, $text) === 0) {
1384             return $text;
1385         }
1386     }
1389 /**
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.
1393  *
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
1398  */
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);
1405     }
1407     return $object;
1410 /**
1411  * Is current user trusted to enter no dangerous XSS in this context?
1412  *
1413  * Please note the user must be in fact trusted everywhere on this server!!
1414  *
1415  * @param object $context
1416  * @return bool true if user trusted
1417  */
1418 function trusttext_trusted($context) {
1419     return (trusttext_active() and has_capability('moodle/site:trustcontent', $context));
1422 /**
1423  * Is trusttext feature active?
1424  *
1425  * @global object
1426  * @param object $context
1427  * @return bool
1428  */
1429 function trusttext_active() {
1430     global $CFG;
1432     return !empty($CFG->enabletrusttext);
1435 /**
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.
1438  *
1439  * @global string
1440  * @global object
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
1445  */
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;
1451     }
1453     switch ($format) {
1454         case FORMAT_PLAIN:
1455         case FORMAT_MARKDOWN:
1456             return $text;
1458         default:
1460             if (!empty($CFG->enablehtmlpurifier)) {
1461                 $text = purify_html($text);
1462             } else {
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);
1475             }
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);
1481             return $text;
1482     }
1485 /**
1486  * KSES replacement cleaning function - uses HTML Purifier.
1487  *
1488  * @global object
1489  * @param string $text The (X)HTML string to purify
1490  */
1491 function purify_html($text) {
1492     global $CFG;
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);
1518         }
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);
1528     }
1530     $multilang = (strpos($text, 'class="multilang"') !== false);
1532     if ($multilang) {
1533         $text = preg_replace('/<span(\s+lang="([a-zA-Z0-9_-]+)"|\s+class="multilang"){2}\s*>/', '<span xxxlang="${2}">', $text);
1534     }
1535     $text = $purifier->purify($text);
1536     if ($multilang) {
1537         $text = preg_replace('/<span xxxlang="([a-zA-Z0-9_-]+)">/', '<span lang="${1}" class="multilang">', $text);
1538     }
1540     return $text;
1543 /**
1544  * This function takes a string and examines it for HTML tags.
1545  *
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
1548  *
1549  * @param string $str The string to be examined for html tags
1550  * @return string
1551  */
1552 function cleanAttributes($str){
1553     $result = preg_replace_callback(
1554             '%(<[^>]*(>|$)|>)%m', #search for html tags
1555             "cleanAttributes2",
1556             $str
1557             );
1558     return  $result;
1561 /**
1562  * This function takes a string with an html tag and strips out any unallowed
1563  * protocols e.g. javascript:
1564  *
1565  * It calls ancillary functions in kses which are prefixed by kses
1566  *
1567  * @global object
1568  * @global string
1569  * @param array $htmlArray An array from {@link cleanAttributes()}, containing in its 1st
1570  *              element the html to be cleared
1571  * @return string
1572  */
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 '&gt;';  //a single character ">" detected
1581     }
1582     if (!preg_match('%^<\s*(/\s*)?([a-zA-Z0-9]+)([^>]*)>?$%', $htmlTag, $matches)) {
1583         return ''; // It's seriously malformed
1584     }
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);
1591     $attStr = '';
1592     foreach ($attrArray as $arreach) {
1593         $arreach['name'] = strtolower($arreach['name']);
1594         if ($arreach['name'] == 'style') {
1595             $value = $arreach['value'];
1596             while (true) {
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;
1605                     break;
1606                 }
1607             }
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']);
1615         }
1616         $attStr .=  ' '.$arreach['name'].'="'.$arreach['value'].'"';
1617     }
1619     $xhtml_slash = '';
1620     if (preg_match('%/\s*$%', $attrlist)) {
1621         $xhtml_slash = ' /';
1622     }
1623     return '<'. $slash . $elem . $attStr . $xhtml_slash .'>';
1626 /**
1627  * Replaces all known smileys in the text with image equivalents
1628  *
1629  * @global object
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.
1634  * @return string
1635  */
1636 function replace_smilies(&$text) {
1637     global $CFG, $OUTPUT;
1639     if (empty($CFG->emoticons)) { /// No emoticons defined, nothing to process here
1640         return;
1641     }
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];
1656             }
1657         }
1658     }
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 === '') {
1666                 $alttext = $image;
1667             }
1668             $e[$lang][] = $emoticon;
1669             $img[$lang][] = '<img alt="'. $alttext .'" width="15" height="15" src="'. $OUTPUT->pix_url('s/' . $image) . '" />';
1670         }
1671     }
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.
1676     //       - Eloy
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;
1685     }
1686     if ($excludes) {
1687         $text = str_replace($excludes,array_keys($excludes),$text);
1688     }
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
1694     if ($excludes) {
1695         $text = str_replace(array_keys($excludes),$excludes,$text);
1696     }
1699 /**
1700  * This code is called from help.php to inject a list of smilies into the
1701  * emoticons help file.
1702  *
1703  * @global object
1704  * @global object
1705  * @return string HTML for a list of smilies.
1706  */
1707 function get_emoticons_list_for_help_file() {
1708     global $CFG, $SESSION, $PAGE, $OUTPUT;
1709     if (empty($CFG->emoticons)) {
1710         return '';
1711     }
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>';
1719     }
1720     $output .= '</ul>';
1721     if (!empty($SESSION->inserttextform)) {
1722         $formname = $SESSION->inserttextform;
1723         $fieldname = $SESSION->inserttextfield;
1724     } else {
1725         $formname = 'theform';
1726         $fieldname = 'message';
1727     }
1729     $PAGE->requires->yui2_lib('event');
1730     $PAGE->requires->js_function_call('emoticons_help.init', array($formname, $fieldname, 'emoticonlist'));
1731     return $output;
1735 /**
1736  * Given plain text, makes it into HTML as nicely as possible.
1737  * May contain HTML tags already
1738  *
1739  * @global object
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.
1744  * @return string
1745  */
1747 function text_to_html($text, $smiley=true, $para=true, $newlines=true) {
1748 ///
1750     global $CFG;
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.
1762     if ($newlines) {
1763         $text = nl2br($text);
1764     }
1766 /// Turn smileys into images.
1767     if ($smiley) {
1768         replace_smilies($text);
1769     }
1771 /// Wrap the whole thing in a div if required
1772     if ($para) {
1773         //return '<p>'.$text.'</p>'; //1.9 version
1774         return '<div class="text_to_html">'.$text.'</div>';
1775     } else {
1776         return $text;
1777     }
1780 /**
1781  * Given Markdown formatted text, make it into XHTML using external function
1782  *
1783  * @global object
1784  * @param string $text The markdown formatted text to be converted.
1785  * @return string Converted text
1786  */
1787 function markdown_to_html($text) {
1788     global $CFG;
1790     if ($text === '' or $text === NULL) {
1791         return $text;
1792     }
1794     require_once($CFG->libdir .'/markdown.php');
1796     return Markdown($text);
1799 /**
1800  * Given HTML text, make it into plain text using external function
1801  *
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.
1809  */
1810 function html_to_text($html, $width = 75, $dolinks = true) {
1812     global $CFG;
1814     require_once($CFG->libdir .'/html2text.php');
1816     $h2t = new html2text($html, false, $dolinks, $width);
1817     $result = $h2t->get_text();
1819     return $result;
1822 /**
1823  * Given some text this function converts any URLs it finds into HTML links
1824  *
1825  * @param string $text Passed in by reference. The string to be searched for urls.
1826  */
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:
1831     //<a href="blah">
1832     //&lt;a href="blah"&gt;
1833     //&lt;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,
1847     }
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);
1860     }
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);
1865     }
1868 /**
1869  * This function will highlight search words in a given string
1870  *
1871  * It cares about HTML and will not ruin links.  It's best to use
1872  * this function after performing any conversions to HTML.
1873  *
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.
1880  */
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)) {
1886         return $haystack;
1887     }
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.
1896         } else {
1897             $words[$index] = preg_quote($word, '/');
1898         }
1899     }
1900     $regexp = '/(' . implode('|', $words) . ')/u'; // u is do UTF-8 matching.
1901     if (!$matchcase) {
1902         $regexp .= 'i';
1903     }
1905 /// Another chance to bail-out if $search was only -words
1906     if (empty($words)) {
1907         return $haystack;
1908     }
1910 /// Find all the HTML tags in the input, and store them in a placeholders array.
1911     $placeholders = array();
1912     $matches = array();
1913     preg_match_all('/<[^>]*>/', $haystack, $matches);
1914     foreach (array_unique($matches[0]) as $key => $htmltag) {
1915         $placeholders['<|' . $key . '|>'] = $htmltag;
1916     }
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);
1927     return $haystack;
1930 /**
1931  * This function will highlight instances of $needle in $haystack
1932  *
1933  * It's faster that the above function {@link highlight()} and doesn't care about
1934  * HTML or anything.
1935  *
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
1939  */
1940 function highlightfast($needle, $haystack) {
1942     if (empty($needle) or empty($haystack)) {
1943         return $haystack;
1944     }
1946     $parts = explode(moodle_strtolower($needle), moodle_strtolower($haystack));
1948     if (count($parts) === 1) {
1949         return $haystack;
1950     }
1952     $pos = 0;
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);
1960     }
1962     return str_replace('<span class="highlight"></span>', '', join('', $parts));
1965 /**
1966  * Return a string containing 'lang', xml:lang and optionally 'dir' HTML attributes.
1967  * Internationalisation, for print_header and backup/restorelib.
1968  *
1969  * @param bool $dir Default false
1970  * @return string Attributes
1971  */
1972 function get_html_lang($dir = false) {
1973     $direction = '';
1974     if ($dir) {
1975         if (right_to_left()) {
1976             $direction = ' dir="rtl"';
1977         } else {
1978             $direction = ' dir="ltr"';
1979         }
1980     }
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 ///////////////////////////////////////////////////
1990 /**
1991  * Send the HTTP headers that Moodle requires.
1992  * @param $cacheable Can this page be cached on back?
1993  */
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');
1999     if ($cacheable) {
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: ');
2004     } else {
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');
2011     }
2012     @header('Accept-Ranges: none');
2015 /**
2016  * Return the right arrow with text ('next'), and optionally embedded in a link.
2017  *
2018  * @global object
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.
2024  */
2025 function link_arrow_right($text, $url='', $accesshide=false, $addclass='') {
2026     global $OUTPUT; //TODO: move to output renderer
2027     $arrowclass = 'arrow ';
2028     if (! $url) {
2029         $arrowclass .= $addclass;
2030     }
2031     $arrow = '<span class="'.$arrowclass.'">'.$OUTPUT->rarrow().'</span>';
2032     $htmltext = '';
2033     if ($text) {
2034         $htmltext = '<span class="arrow_text">'.$text.'</span>&nbsp;';
2035         if ($accesshide) {
2036             $htmltext = get_accesshide($htmltext);
2037         }
2038     }
2039     if ($url) {
2040         $class = 'arrow_link';
2041         if ($addclass) {
2042             $class .= ' '.$addclass;
2043         }
2044         return '<a class="'.$class.'" href="'.$url.'" title="'.preg_replace('/<.*?>/','',$text).'">'.$htmltext.$arrow.'</a>';
2045     }
2046     return $htmltext.$arrow;
2049 /**
2050  * Return the left arrow with text ('previous'), and optionally embedded in a link.
2051  *
2052  * @global object
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.
2058  */
2059 function link_arrow_left($text, $url='', $accesshide=false, $addclass='') {
2060     global $OUTPUT; // TODO: move to utput renderer
2061     $arrowclass = 'arrow ';
2062     if (! $url) {
2063         $arrowclass .= $addclass;
2064     }
2065     $arrow = '<span class="'.$arrowclass.'">'.$OUTPUT->larrow().'</span>';
2066     $htmltext = '';
2067     if ($text) {
2068         $htmltext = '&nbsp;<span class="arrow_text">'.$text.'</span>';
2069         if ($accesshide) {
2070             $htmltext = get_accesshide($htmltext);
2071         }
2072     }
2073     if ($url) {
2074         $class = 'arrow_link';
2075         if ($addclass) {
2076             $class .= ' '.$addclass;
2077         }
2078         return '<a class="'.$class.'" href="'.$url.'" title="'.preg_replace('/<.*?>/','',$text).'">'.$arrow.$htmltext.'</a>';
2079     }
2080     return $arrow.$htmltext;
2083 /**
2084  * Return a HTML element with the class "accesshide", for accessibility.
2085  * Please use cautiously - where possible, text should be visible!
2086  *
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.
2092  */
2093 function get_accesshide($text, $elem='span', $class='', $attrs='') {
2094     return "<$elem class=\"accesshide $class\" $attrs>$text</$elem>";
2097 /**
2098  * Return the breadcrumb trail navigation separator.
2099  *
2100  * @return string HTML string.
2101  */
2102 function get_separator() {
2103     //Accessibility: the 'hidden' slash is preferred for screen readers.
2104     return ' '.link_arrow_right($text='/', $url='', $accesshide=true, 'sep').' ';
2107 /**
2108  * Print (or return) a collapsible region, that has a caption that can
2109  * be clicked to expand or collapse the region.
2110  *
2111  * If JavaScript is off, then the region will always be expanded.
2112  *
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.
2122  */
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);
2128     if ($return) {
2129         return $output;
2130     } else {
2131         echo $output;
2132     }
2135 /**
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.
2139  *
2140  * @global object
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.
2149  */
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);
2157     } else {
2158         $collapsed = $default;
2159         $userpref = false;
2160     }
2162     if ($collapsed) {
2163         $classes .= ' collapsed';
2164     }
2166     $output = '';
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')));
2174     if ($return) {
2175         return $output;
2176     } else {
2177         echo $output;
2178     }
2181 /**
2182  * Close a region started with print_collapsible_region_start.
2183  *
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.
2186  */
2187 function print_collapsible_region_end($return = false) {
2188     $output = '</div></div></div>';
2190     if ($return) {
2191         return $output;
2192     } else {
2193         echo $output;
2194     }
2197 /**
2198  * Print a specified group's avatar.
2199  *
2200  * @global object
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
2208  */
2209 function print_group_picture($group, $courseid, $large=false, $return=false, $link=true) {
2210     global $CFG;
2212     if (is_array($group)) {
2213         $output = '';
2214         foreach($group as $g) {
2215             $output .= print_group_picture($g, $courseid, $large, true, $link);
2216         }
2217         if ($return) {
2218             return $output;
2219         } else {
2220             echo $output;
2221             return;
2222         }
2223     }
2225     $context = get_context_instance(CONTEXT_COURSE, $courseid);
2227     // If there is no picture, do nothing
2228     if (!$group->picture) {
2229         return '';
2230     }
2232     // If picture is hidden, only show to those with course:managegroups
2233     if ($group->hidepicture and !has_capability('moodle/course:managegroups', $context)) {
2234         return '';
2235     }
2237     if ($link or has_capability('moodle/site:accessallgroups', $context)) {
2238         $output = '<a href="'. $CFG->wwwroot .'/user/index.php?id='. $courseid .'&amp;group='. $group->id .'">';
2239     } else {
2240         $output = '';
2241     }
2242     if ($large) {
2243         $file = 'f1';
2244     } else {
2245         $file = 'f2';
2246     }
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)) {
2253         $output .= '</a>';
2254     }
2256     if ($return) {
2257         return $output;
2258     } else {
2259         echo $output;
2260     }
2264 /**
2265  * Display a recent activity note
2266  *
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
2275  */
2276 function print_recent_activity_note($time, $user, $text, $link, $return=false, $viewfullnames=null) {
2277     static $strftimerecent = null;
2278     $output = '';
2280     if (is_null($viewfullnames)) {
2281         $context = get_context_instance(CONTEXT_SYSTEM);
2282         $viewfullnames = has_capability('moodle/site:viewfullnames', $context);
2283     }
2285     if (is_null($strftimerecent)) {
2286         $strftimerecent = get_string('strftimerecent');
2287     }
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>';
2295     if ($return) {
2296         return $output;
2297     } else {
2298         echo $output;
2299     }
2302 /**
2303  * Returns a popup menu with course activity modules
2304  *
2305  * Given a course
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
2310  * the course record
2311  *
2312  * @todo Finish documenting this function
2313  *
2314  * @global object
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
2321  * @param int $width
2322  * @param string $cmid
2323  * @return string The HTML block
2324  */
2325 function navmenulist($course, $sections, $modinfo, $strsection, $strjumpto, $width=50, $cmid=0) {
2327     global $CFG, $OUTPUT;
2329     $section = -1;
2330     $url = '';
2331     $menu = array();
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') {
2339             continue;
2340         }
2342         if ($mod->sectionnum > $course->numsections) {   /// Don't show excess hidden sections
2343             break;
2344         }
2346         if (!$mod->uservisible) { // do not icnlude empty sections at all
2347             continue;
2348         }
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>';
2358                 }
2359                 if ($course->format == 'weeks' or empty($thissection->summary)) {
2360                     $item = $strsection ." ". $mod->sectionnum;
2361                 } else {
2362                     if (strlen($thissection->summary) < ($width-3)) {
2363                         $item = $thissection->summary;
2364                     } else {
2365                         $item = substr($thissection->summary, 0, $width).'...';
2366                     }
2367                 }
2368                 $menu[] = '<li class="section"><span>'.$item.'</span>';
2369                 $menu[] = '<ul>';
2370                 $doneheading = true;
2372                 $section = $mod->sectionnum;
2373             } else {
2374                 // no activities from this hidden section shown
2375                 continue;
2376             }
2377         }
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).'...';
2383         }
2384         if (!$mod->visible) {
2385             $mod->name = '('.$mod->name.')';
2386         }
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>';
2392     }
2394     if ($doneheading) {
2395         $menu[] = '</ul></li>';
2396     }
2397     $menu[] = '</ul></li></ul>';
2399     return implode("\n", $menu);
2402 /**
2403  * Prints a grade menu (as part of an existing form) with help
2404  * Showing all possible numerical grades and scales
2405  *
2406  * @todo Finish documenting this function
2407  * @todo Deprecate: this is only used in a few contrib modules
2408  *
2409  * @global object
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
2416  */
2417 function print_grade_menu($courseid, $name, $current, $includenograde=true, $return=false) {
2419     global $CFG, $OUTPUT;
2421     $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;
2428     }
2429     if ($includenograde) {
2430         $grades[0] = get_string('nograde');
2431     }
2432     for ($i=100; $i>=1; $i--) {
2433         $grades[$i] = $i;
2434     }
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));
2442     if ($return) {
2443         return $output;
2444     } else {
2445         echo $output;
2446     }
2449 /**
2450  * Print an error to STDOUT and exit with a non-zero code. For commandline scripts.
2451  * Default errorcode is 1.
2452  *
2453  * Very useful for perl-like error-handling:
2454  *
2455  * do_somethting() or mdie("Something went wrong");
2456  *
2457  * @param string  $msg       Error message
2458  * @param integer $errorcode Error code to emit
2459  */
2460 function mdie($msg='', $errorcode=1) {
2461     trigger_error($msg);
2462     exit($errorcode);
2465 /**
2466  * Print a message and exit.
2467  *
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
2472  */
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
2478     if (CLI_SCRIPT) {
2479         echo("!!$message!!\n");
2480         exit(1); // no success
2481     }
2483     if (!$PAGE->headerprinted) {
2484         //header not yet printed
2485         $PAGE->set_title(get_string('notice'));
2486         echo $OUTPUT->header();
2487     } else {
2488         echo $OUTPUT->container_end_all(false);
2489     }
2491     echo $OUTPUT->box($message, 'generalbox', 'notice');
2492     echo $OUTPUT->continue_button($link);
2494     echo $OUTPUT->footer();
2495     exit(1); // general error code
2498 /**
2499  * Redirects the user to another page, after printing a notice
2500  *
2501  * This function calls the OUTPUT redirect method, echo's the output
2502  * and then dies to ensure nothing else happens.
2503  *
2504  * <strong>Good practice:</strong> You should call this method before starting page
2505  * output by using any of the OUTPUT methods.
2506  *
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!
2511  */
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');
2519     }
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);
2526     }
2528     if (!empty($CFG->usesid) && !isset($_COOKIE[session_name()])) {
2529        $url = $SESSION->sid_process_url($url);
2530     }
2532     $debugdisableredirect = false;
2533     do {
2534         if (defined('DEBUGGING_PRINTED')) {
2535             // some debugging already printed, no need to look more
2536             $debugdisableredirect = true;
2537             break;
2538         }
2540         if (empty($CFG->debugdisplay) or empty($CFG->debug)) {
2541             // no errors should be displayed
2542             break;
2543         }
2545         if (!function_exists('error_get_last') or !$lasterror = error_get_last()) {
2546             break;
2547         }
2549         if (!($lasterror['type'] & $CFG->debug)) {
2550             //last error not interesting
2551             break;
2552         }
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;
2558             break;
2559         }
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;
2565             break;
2566         }
2567     } while (false);
2569     if (!empty($message)) {
2570         if ($delay === -1 || !is_numeric($delay)) {
2571             $delay = 3;
2572         }
2573         $message = clean_text($message);
2574     } else {
2575         $message = get_string('pageshouldredirect');
2576         $delay = 0;
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;
2584             } else {
2585                 // URLs not beginning with / are relative to path of current script, so add that on.
2586                 $url = $hostpart.preg_replace('|\?.*$|','',me()).'/../'.$url;
2587             }
2588             // Replace all ..s
2589             while (true) {
2590                 $newurl = preg_replace('|/(?!\.\.)[^/]*/\.\./|', '/', $url);
2591                 if ($newurl == $url) {
2592                     break;
2593                 }
2594                 $url = $newurl;
2595             }
2596         }
2597     }
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']);
2603         }
2604     }
2606     $encodedurl = preg_replace("/\&(?![a-zA-Z0-9#]{1,8};)/", "&amp;", $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);
2614         exit;
2615     }
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);
2621     exit;
2624 /**
2625  * Given an email address, this function will return an obfuscated version of it
2626  *
2627  * @param string $email The email address to obfuscate
2628  * @return string The obfuscated email address
2629  */
2630  function obfuscate_email($email) {
2632     $i = 0;
2633     $length = strlen($email);
2634     $obfuscated = '';
2635     while ($i < $length) {
2636         if (rand(0,2) && $email{$i}!='@') { //MDL-20619 some browsers have problems unobfuscating @
2637             $obfuscated.='%'.dechex(ord($email{$i}));
2638         } else {
2639             $obfuscated.=$email{$i};
2640         }
2641         $i++;
2642     }
2643     return $obfuscated;
2646 /**
2647  * This function takes some text and replaces about half of the characters
2648  * with HTML entity equivalents.   Return string is obviously longer.
2649  *
2650  * @param string $plaintext The text to be obfuscated
2651  * @return string The obfuscated text
2652  */
2653 function obfuscate_text($plaintext) {
2655     $i=0;
2656     $length = strlen($plaintext);
2657     $obfuscated='';
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;
2667         } else {
2668             $obfuscated.=$plaintext{$i};
2669             $prev_obfuscated = false;
2670         }
2671       $i++;
2672     }
2673     return $obfuscated;
2676 /**
2677  * This function uses the {@link obfuscate_email()} and {@link obfuscate_text()}
2678  * to generate a fully obfuscated email link, ready to use.
2679  *
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
2684  */
2685 function obfuscate_mailto($email, $label='', $dimmed=false) {
2687     if (empty($label)) {
2688         $label = $email;
2689     }
2690     if ($dimmed) {
2691         $title = get_string('emaildisable');
2692         $dimmed = ' class="dimmed"';
2693     } else {
2694         $title = '';
2695         $dimmed = '';
2696     }
2697     return sprintf("<a href=\"%s:%s\" $dimmed title=\"$title\">%s</a>",
2698                     obfuscate_text('mailto'), obfuscate_email($email),
2699                     obfuscate_text($label));
2702 /**
2703  * This function is used to rebuild the <nolink> tag because some formats (PLAIN and WIKI)
2704  * will transform it to html entities
2705  *
2706  * @param string $text Text to search for nolink tag in
2707  * @return string
2708  */
2709 function rebuildnolinktag($text) {
2711     $text = preg_replace('/&lt;(\/*nolink)&gt;/i','<$1>',$text);
2713     return $text;
2716 /**
2717  * Prints a maintenance message from $CFG->maintenance_message or default if empty
2718  * @return void
2719  */
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();
2733     }
2734     echo $OUTPUT->footer();
2735     die;
2738 /**
2739  * Adjust the list of allowed tags based on $CFG->allowobjectembed and user roles (admin)
2740  *
2741  * @global object
2742  * @global string
2743  * @return void
2744  */
2745 function adjust_allowed_tags() {
2747     global $CFG, $ALLOWED_TAGS;
2749     if (!empty($CFG->allowobjectembed)) {
2750         $ALLOWED_TAGS .= '<embed><object>';
2751     }
2754 /**
2755  * A class for tabs, Some code to print tabs
2756  *
2757  * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2758  * @package moodlecore
2759  */
2760 class tabobject {
2761     /**
2762      * @var string
2763      */
2764     var $id;
2765     var $link;
2766     var $text;
2767     /**
2768      * @var bool
2769      */
2770     var $linkedwhenselected;
2772     /**
2773      * A constructor just because I like constructors
2774      *
2775      * @param string $id
2776      * @param string $link
2777      * @param string $text
2778      * @param string $title
2779      * @param bool $linkedwhenselected
2780      */
2781     function tabobject ($id, $link='', $text='', $title='', $linkedwhenselected=false) {
2782         $this->id   = $id;
2783         $this->link = $link;
2784         $this->text = $text;
2785         $this->title = $title ? $title : $text;
2786         $this->linkedwhenselected = $linkedwhenselected;
2787     }
2792 /**
2793  * Returns a string containing a nested list, suitable for formatting into tabs with CSS.
2794  *
2795  * @global object
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
2801  **/
2802 function print_tabs($tabrows, $selected=NULL, $inactive=NULL, $activated=NULL, $return=false) {
2803     global $CFG;
2805 /// $inactive must be an array
2806     if (!is_array($inactive)) {
2807         $inactive = array();
2808     }
2810 /// $activated must be an array
2811     if (!is_array($activated)) {
2812         $activated = array();
2813     }
2815 /// Convert the tab rows into a tree that's easier to process
2816     if (!$tree = convert_tabrows_to_tree($tabrows, $selected, $inactive, $activated)) {
2817         return false;
2818     }
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";
2826 /// We're done!
2828     if ($return) {
2829         return $output;
2830     }
2831     echo $output;
2834 /**
2835  * Converts a nested array tree into HTML ul:li [recursive]
2836  *
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
2840  */
2841 function convert_tree_to_html($tree, $row=0) {
2843     $str = "\n".'<ul class="tabrow'.$row.'">'."\n";
2845     $first = true;
2846     $count = count($tree);
2848     foreach ($tree as $tab) {
2849         $count--;   // countdown to zero
2851         $liclass = '';
2853         if ($first && ($count == 0)) {   // Just one in the row
2854             $liclass = 'first last';
2855             $first = false;
2856         } else if ($first) {
2857             $liclass = 'first';
2858             $first = false;
2859         } else if ($count == 0) {
2860             $liclass = 'last';
2861         }
2863         if ((empty($tab->subtree)) && (!empty($tab->selected))) {
2864             $liclass .= (empty($liclass)) ? 'onerow' : ' onerow';
2865         }
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';
2872             }
2873         }
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>';
2880         } else {
2881             $str .= '<a href="'.$tab->link.'" title="'.$tab->title.'"><span>'.$tab->text.'</span></a>';
2882         }
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">&nbsp;</div>'."\n";
2888         }
2890         $str .= ' </li>'."\n";
2891     }
2892     $str .= '</ul>'."\n";
2894     return $str;
2897 /**
2898  * Convert nested tabrows to a nested array
2899  *
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
2905  */
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);
2912     $subtree = array();
2914     foreach ($tabrows as $row) {
2915         $tree = array();
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) {
2923                 if ($subtree) {
2924                     $tab->subtree = $subtree;
2925                 }
2926             }
2927             $tree[] = $tab;
2928         }
2929         $subtree = $tree;
2930     }
2932     return $subtree;
2935 /**
2936  * Returns the Moodle Docs URL in the users language
2937  *
2938  * @global object
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}
2941  */
2942 function get_docs_url($path) {
2943     global $CFG;
2944     return $CFG->docroot . '/' . current_language() . '/' . $path;
2948 /**
2949  * Standard Debugging Function
2950  *
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
2954  * eg use like this:
2955  *
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) }
2960  *
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.
2965  *
2966  * It is also possible to define NO_DEBUG_DISPLAY which redirects the message to error_log.
2967  *
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
2972  * @return bool
2973  */
2974 function debugging($message = '', $level = DEBUG_NORMAL, $backtrace = null) {
2975     global $CFG, $UNITTEST;
2977     if (empty($CFG->debug) || $CFG->debug < $level) {
2978         return false;
2979     }
2981     if (!isset($CFG->debugdisplay)) {
2982         $CFG->debugdisplay = ini_get_bool('display_errors');
2983     }
2985     if ($message) {
2986         if (!$backtrace) {
2987             $backtrace = debug_backtrace();
2988         }
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
3006             }
3007             echo '<div class="notifytiny">' . $message . $from . '</div>';
3009         } else {
3010             trigger_error($message . $from, E_USER_NOTICE);
3011         }
3012     }
3013     return true;
3016 /**
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
3026 */
3027 function print_location_comment($file, $line, $return = false)
3029     if ($return) {
3030         return "<!-- $file at line $line -->\n";
3031     } else {
3032         echo "<!-- $file at line $line -->\n";
3033     }
3037 /**
3038  * @return boolean true if the current language is right-to-left (Hebrew, Arabic etc)
3039  */
3040 function right_to_left() {
3041     return (get_string('thisdirection', 'langconfig') === 'rtl');
3045 /**
3046  * Returns swapped left<=>right if in RTL environment.
3047  * part of RTL support
3048  *
3049  * @param string $align align to check
3050  * @return string
3051  */
3052 function fix_align_rtl($align) {
3053     if (!right_to_left()) {
3054         return $align;
3055     }
3056     if ($align=='left')  { return 'right'; }
3057     if ($align=='right') { return 'left'; }
3058     return $align;
3062 /**
3063  * Returns true if the page is displayed in a popup window.
3064  * Gets the information from the URL parameter inpopup.
3065  *
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.
3068  *
3069  * @return boolean
3070  */
3071 function is_in_popup() {
3072     $inpopup = optional_param('inpopup', '', PARAM_BOOL);
3074     return ($inpopup);
3077 /**
3078  * To use this class.
3079  * - construct
3080  * - call create (or use the 3rd param to the constructor)
3081  * - call update or update_full repeatedly
3082  *
3083  * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3084  * @package moodlecore
3085  */
3086 class progress_bar {
3087     /** @var string html id */
3088     private $html_id;
3089     /** @var int */
3090     private $percent;
3091     /** @var int */
3092     private $width;
3093     /** @var int */
3094     private $lastcall;
3095     /** @var int */
3096     private $time_start;
3097     private $minimum_time = 2; //min time between updates.
3098     /**
3099      * Constructor
3100      *
3101      * @param string $html_id
3102      * @param int $width
3103      * @param bool $autostart Default to false
3104      */
3105     public function __construct($html_id = '', $width = 500, $autostart = false){
3106         if (!empty($html_id)) {
3107             $this->html_id  = $html_id;
3108         } else {
3109             $this->html_id  = uniqid();
3110         }
3111         $this->width = $width;
3112         $this->restart();
3113         if($autostart){
3114             $this->create();
3115         }
3116     }
3117     /**
3118       * Create a new progress bar, this function will output html.
3119       *
3120       * @return void Echo's output
3121       */
3122     public function create(){
3123             flush();
3124             $this->lastcall->pt = 0;
3125             $this->lastcall->time = microtime(true);
3126             if (CLI_SCRIPT) {
3127                 return; // temporary solution for cli scripts
3128             }
3129             $htmlcode = <<<EOT
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;">&nbsp;<span id="pt_{$this->html_id}"></span>
3137                     </div>
3138                 </div>
3139             </div>
3140 EOT;
3141             echo $htmlcode;
3142             flush();
3143     }
3144     /**
3145      * Update the progress bar
3146      *
3147      * @param int $percent from 1-100
3148      * @param string $msg
3149      * @param mixed $es
3150      * @return void Echo's output
3151      */
3152     private function _update($percent, $msg, $es){
3153         global $PAGE;
3154         if(empty($this->time_start)){
3155             $this->time_start = microtime(true);
3156         }
3157         $this->percent = $percent;
3158         $this->lastcall->time = microtime(true);
3159         $this->lastcall->pt   = $percent;
3160         $w = $this->percent * $this->width;
3161         if (CLI_SCRIPT) {
3162             return; // temporary solution for cli scripts
3163         }
3164         if ($es === null){
3165             $es = "Infinity";
3166         }
3167         echo html_writer::script(js_writer::function_call('update_progress_bar', Array($this->html_id, $w, $this->percent, $msg, $es)));
3168         flush();
3169     }
3170     /**
3171       * estimate time
3172       *
3173       * @param int $curtime the time call this function
3174       * @param int $percent from 1-100
3175       * @return mixed Null, or int
3176       */
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;
3184         } else {
3185             return null;
3186         }
3187         if($left < 0) {
3188             return 0;
3189         } else {
3190             return $left;
3191         }
3192     }
3193     /**
3194       * Update progress bar according percent
3195       *
3196       * @param int $percent from 1-100
3197       * @param string $msg the message needed to be shown
3198       */
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)){
3202             return;
3203         }
3204         $this->_update($percent, 100, $msg);
3205     }
3206     /**
3207       * Update progress bar according the number of tasks
3208       *
3209       * @param int $cur current task number
3210       * @param int $total total task number
3211       * @param string $msg message
3212       */
3213     public function update($cur, $total, $msg){
3214         $cur = max($cur, 0);
3215         if ($cur >= $total){
3216             $percent = 1;
3217         } else {
3218             $percent = $cur / $total;
3219         }
3220         /**
3221         if ($percent != 1 && ($this->lastcall->time + $this->minimum_time) > microtime(true)){
3222             return;
3223         }
3224         */
3225         $es = $this->estimate(microtime(true), $percent);
3226         $this->_update($percent, $msg, $es);
3227     }
3228     /**
3229      * Restart the progress bar.
3230      */
3231     public function restart(){
3232         $this->percent  = 0;
3233         $this->lastcall = new stdClass;
3234         $this->lastcall->pt = 0;
3235         $this->lastcall->time = microtime(true);
3236         $this->time_start  = 0;
3237     }
3240 /**
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.
3243  *
3244  * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3245  * @package moodlecore
3246  */
3247 abstract class progress_trace {
3248     /**
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.
3252      */
3253     abstract public function output($message, $depth = 0);
3255     /**
3256      * Called when the processing is finished.
3257      */
3258     public function finished() {
3259     }
3262 /**
3263  * This subclass of progress_trace does not ouput anything.
3264  *
3265  * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3266  * @package moodlecore
3267  */
3268 class null_progress_trace extends progress_trace {
3269     /**
3270      * Does Nothing
3271      *
3272      * @param string $message
3273      * @param int $depth
3274      * @return void Does Nothing
3275      */
3276     public function output($message, $depth = 0) {
3277     }
3280 /**
3281  * This subclass of progress_trace outputs to plain text.
3282  *
3283  * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3284  * @package moodlecore
3285  */
3286 class text_progress_trace extends progress_trace {
3287     /**
3288      * Output the trace message
3289      *
3290      * @param string $message
3291      * @param int $depth
3292      * @return void Output is echo'd
3293      */
3294     public function output($message, $depth = 0) {
3295         echo str_repeat('  ', $depth), $message, "\n";
3296         flush();
3297     }
3300 /**
3301  * This subclass of progress_trace outputs as HTML.
3302  *
3303  * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3304  * @package moodlecore
3305  */
3306 class html_progress_trace extends progress_trace {
3307     /**
3308      * Output the trace message
3309      *
3310      * @param string $message
3311      * @param int $depth
3312      * @return void Output is echo'd
3313      */
3314     public function output($message, $depth = 0) {
3315         echo '<p>', str_repeat('&#160;&#160;', $depth), htmlspecialchars($message), "</p>\n";
3316         flush();
3317     }
3320 /**
3321  * HTML List Progress Tree
3322  *
3323  * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3324  * @package moodlecore
3325  */
3326 class html_list_progress_trace extends progress_trace {
3327     /** @var int */
3328     protected $currentdepth = -1;
3330     /**
3331      * Echo out the list
3332      *
3333      * @param string $message The message to display
3334      * @param int $depth
3335      * @return void Output is echoed
3336      */
3337     public function output($message, $depth = 0) {
3338         $samedepth = true;
3339         while ($this->currentdepth > $depth) {
3340             echo "</li>\n</ul>\n";
3341             $this->currentdepth -= 1;
3342             if ($this->currentdepth == $depth) {
3343                 echo '<li>';
3344             }
3345             $samedepth = false;
3346         }
3347         while ($this->currentdepth < $depth) {
3348             echo "<ul>\n<li>";
3349             $this->currentdepth += 1;
3350             $samedepth = false;
3351         }
3352         if ($samedepth) {
3353             echo "</li>\n<li>";
3354         }
3355         echo htmlspecialchars($message);
3356         flush();
3357     }
3359     /**
3360      * Called when the processing is finished.
3361      */
3362     public function finished() {
3363         while ($this->currentdepth >= 0) {
3364             echo "</li>\n</ul>\n";
3365             $this->currentdepth -= 1;
3366         }
3367     }
3370 /**
3371  * Returns a localized sentence in the current language summarizing the current password policy
3372  *
3373  * @todo this should be handled by a function/method in the language pack library once we have a support for it
3374  * @uses $CFG
3375  * @return string
3376  */
3377 function print_password_policy() {
3378     global $CFG;
3380     $message = '';
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);
3386         }
3387         if (!empty($CFG->minpasswordlower)) {
3388             $messages[] = get_string('informminpasswordlower', 'auth', $CFG->minpasswordlower);
3389         }
3390         if (!empty($CFG->minpasswordupper)) {
3391             $messages[] = get_string('informminpasswordupper', 'auth', $CFG->minpasswordupper);
3392         }
3393         if (!empty($CFG->minpasswordnonalphanum)) {
3394             $messages[] = get_string('informminpasswordnonalphanum', 'auth', $CFG->minpasswordnonalphanum);
3395         }
3397         $messages = join(', ', $messages); // this is ugly but we do not have anything better yet...
3398         $message = get_string('informpasswordpolicy', 'auth', $messages);
3399     }
3400     return $message;
3403 function create_ufo_inline($id, $args) {
3404     global $CFG;
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)));
3409     return $jsoutput;
3412 function create_flowplayer($id, $fileurl, $type='flv', $color='#000000') {
3413     global $CFG;
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)));
3423     }
3425     return $jsoutput;