MDL-14589 improved param name
[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 moodlecore
29  * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
30  * @license   http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
31  */
33 /// Constants
35 /// Define text formatting types ... eventually we can add Wiki, BBcode etc
37 /**
38  * Does all sorts of transformations and filtering
39  */
40 define('FORMAT_MOODLE',   '0');   // Does all sorts of transformations and filtering
42 /**
43  * Plain HTML (with some tags stripped)
44  */
45 define('FORMAT_HTML',     '1');   // Plain HTML (with some tags stripped)
47 /**
48  * Plain text (even tags are printed in full)
49  */
50 define('FORMAT_PLAIN',    '2');   // Plain text (even tags are printed in full)
52 /**
53  * Wiki-formatted text
54  * Deprecated: left here just to note that '3' is not used (at the moment)
55  * and to catch any latent wiki-like text (which generates an error)
56  */
57 define('FORMAT_WIKI',     '3');   // Wiki-formatted text
59 /**
60  * Markdown-formatted text http://daringfireball.net/projects/markdown/
61  */
62 define('FORMAT_MARKDOWN', '4');   // Markdown-formatted text http://daringfireball.net/projects/markdown/
64 /**
65  * TRUSTTEXT marker - if present in text, text cleaning should be bypassed
66  */
67 define('TRUSTTEXT', '#####TRUSTTEXT#####');
69 /**
70  * A moodle_url comparison using this flag will return true if the base URLs match, params are ignored
71  */
72 define('URL_MATCH_BASE', 0);
73 /**
74  * A moodle_url comparison using this flag will return true if the base URLs match and the params of url1 are part of url2
75  */
76 define('URL_MATCH_PARAMS', 1);
77 /**
78  * A moodle_url comparison using this flag will return true if the two URLs are identical, except for the order of the params
79  */
80 define('URL_MATCH_EXACT', 2);
82 /**
83  * Allowed tags - string of html tags that can be tested against for safe html tags
84  * @global string $ALLOWED_TAGS
85  * @name $ALLOWED_TAGS
86  */
87 global $ALLOWED_TAGS;
88 $ALLOWED_TAGS =
89 '<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>';
91 /**
92  * Allowed protocols - array of protocols that are safe to use in links and so on
93  * @global string $ALLOWED_PROTOCOLS
94  * @name $ALLOWED_PROTOCOLS
95  */
96 $ALLOWED_PROTOCOLS = array('http', 'https', 'ftp', 'news', 'mailto', 'rtsp', 'teamspeak', 'gopher', 'mms',
97                            'color', 'callto', 'cursor', 'text-align', 'font-size', 'font-weight', 'font-style', 'font-family',
98                            'border', 'margin', 'padding', 'background', 'background-color', 'text-decoration');   // CSS as well to get through kses
101 /// Functions
103 /**
104  * Add quotes to HTML characters
105  *
106  * Returns $var with HTML characters (like "<", ">", etc.) properly quoted.
107  * This function is very similar to {@link p()}
108  *
109  * @todo Remove obsolete param $obsolete if not used anywhere
110  *
111  * @param string $var the string potentially containing HTML characters
112  * @param boolean $obsolete no longer used.
113  * @return string
114  */
115 function s($var, $obsolete = false) {
117     if ($var === '0' or $var === false or $var === 0) {
118         return '0';
119     }
121     return preg_replace("/&amp;(#\d+);/i", "&$1;", htmlspecialchars($var));
124 /**
125  * Add quotes to HTML characters
126  *
127  * Prints $var with HTML characters (like "<", ">", etc.) properly quoted.
128  * This function simply calls {@link s()}
129  * @see s()
130  *
131  * @todo Remove obsolete param $obsolete if not used anywhere
132  *
133  * @param string $var the string potentially containing HTML characters
134  * @param boolean $obsolete no longer used.
135  * @return string
136  */
137 function p($var, $obsolete = false) {
138     echo s($var, $obsolete);
141 /**
142  * Does proper javascript quoting.
143  *
144  * Do not use addslashes anymore, because it does not work when magic_quotes_sybase is enabled.
145  *
146  * @param mixed $var String, Array, or Object to add slashes to
147  * @return mixed quoted result
148  */
149 function addslashes_js($var) {
150     if (is_string($var)) {
151         $var = str_replace('\\', '\\\\', $var);
152         $var = str_replace(array('\'', '"', "\n", "\r", "\0"), array('\\\'', '\\"', '\\n', '\\r', '\\0'), $var);
153         $var = str_replace('</', '<\/', $var);   // XHTML compliance
154     } else if (is_array($var)) {
155         $var = array_map('addslashes_js', $var);
156     } else if (is_object($var)) {
157         $a = get_object_vars($var);
158         foreach ($a as $key=>$value) {
159           $a[$key] = addslashes_js($value);
160         }
161         $var = (object)$a;
162     }
163     return $var;
166 /**
167  * Remove query string from url
168  *
169  * Takes in a URL and returns it without the querystring portion
170  *
171  * @param string $url the url which may have a query string attached
172  * @return string The remaining URL
173  */
174  function strip_querystring($url) {
176     if ($commapos = strpos($url, '?')) {
177         return substr($url, 0, $commapos);
178     } else {
179         return $url;
180     }
183 /**
184  * Returns the URL of the HTTP_REFERER, less the querystring portion if required
185  *
186  * @uses $_SERVER
187  * @param boolean $stripquery if true, also removes the query part of the url.
188  * @return string The resulting referer or empty string
189  */
190 function get_referer($stripquery=true) {
191     if (isset($_SERVER['HTTP_REFERER'])) {
192         if ($stripquery) {
193             return strip_querystring($_SERVER['HTTP_REFERER']);
194         } else {
195             return $_SERVER['HTTP_REFERER'];
196         }
197     } else {
198         return '';
199     }
203 /**
204  * Returns the name of the current script, WITH the querystring portion.
205  *
206  * This function is necessary because PHP_SELF and REQUEST_URI and SCRIPT_NAME
207  * return different things depending on a lot of things like your OS, Web
208  * server, and the way PHP is compiled (ie. as a CGI, module, ISAPI, etc.)
209  * <b>NOTE:</b> This function returns false if the global variables needed are not set.
210  *
211  * @global string
212  * @return mixed String, or false if the global variables needed are not set
213  */
214 function me() {
215     global $ME;
216     return $ME;
219 /**
220  * Returns the name of the current script, WITH the full URL.
221  *
222  * This function is necessary because PHP_SELF and REQUEST_URI and SCRIPT_NAME
223  * return different things depending on a lot of things like your OS, Web
224  * server, and the way PHP is compiled (ie. as a CGI, module, ISAPI, etc.
225  * <b>NOTE:</b> This function returns false if the global variables needed are not set.
226  *
227  * Like {@link me()} but returns a full URL
228  * @see me()
229  *
230  * @global string
231  * @return mixed String, or false if the global variables needed are not set
232  */
233 function qualified_me() {
234     global $FULLME;
235     return $FULLME;
238 /**
239  * Class for creating and manipulating urls.
240  *
241  * It can be used in moodle pages where config.php has been included without any further includes.
242  *
243  * It is useful for manipulating urls with long lists of params.
244  * One situation where it will be useful is a page which links to itself to perform various actions
245  * and / or to process form data. A moodle_url object :
246  * can be created for a page to refer to itself with all the proper get params being passed from page call to
247  * page call and methods can be used to output a url including all the params, optionally adding and overriding
248  * params and can also be used to
249  *     - output the url without any get params
250  *     - and output the params as hidden fields to be output within a form
251  *
252  * @link http://docs.moodle.org/en/Development:lib/weblib.php_moodle_url See short write up here
253  * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
254  * @package moodlecore
255  */
256 class moodle_url {
257     /**
258      * Scheme, ex.: http, https
259      * @var string
260      */
261     protected $scheme = '';
262     /**
263      * hostname
264      * @var string
265      */
266     protected $host = '';
267     /**
268      * Port number, empty means default 80 or 443 in case of http
269      * @var unknown_type
270      */
271     protected $port = '';
272     /**
273      * Username for http auth
274      * @var string
275      */
276     protected $user = '';
277     /**
278      * Password for http auth
279      * @var string
280      */
281     protected $pass = '';
282     /**
283      * Script path
284      * @var string
285      */
286     protected $path = '';
287     /**
288      * Optional slash argument value
289      * @var string
290      */
291     protected $slashargument = '';
292     /**
293      * Anchor, may be also empty, null means none
294      * @var string
295      */
296     protected $anchor = null;
297     /**
298      * Url parameters as associative array
299      * @var array
300      */
301     protected $params = array(); // Associative array of query string params
303     /**
304      * Create new instance of moodle_url.
305      *
306      * @param moodle_url|string $url - moodle_url means make a copy of another
307      *      moodle_url and change parameters, string means full url or shortened
308      *      form (ex.: '/course/view.php'). It is strongly encouraged to not include
309      *      query string because it may result in double encoded values
310      * @param array $params these params override current params or add new
311      */
312     public function __construct($url, array $params = null) {
313         global $CFG;
315         if ($url instanceof moodle_url) {
316             $this->scheme = $url->scheme;
317             $this->host = $url->host;
318             $this->port = $url->port;
319             $this->user = $url->user;
320             $this->pass = $url->pass;
321             $this->path = $url->path;
322             $this->slashargument = $url->slashargument;
323             $this->params = $url->params;
324             $this->anchor = $url->anchor;
326         } else {
327             // detect if anchor used
328             $apos = strpos($url, '#');
329             if ($apos !== false) {
330                 $anchor = substr($url, $apos);
331                 $anchor = ltrim($anchor, '#');
332                 $this->set_anchor($anchor);
333                 $url = substr($url, 0, $apos);
334             }
336             // normalise shortened form of our url ex.: '/course/view.php'
337             if (strpos($url, '/') === 0) {
338                 // we must not use httpswwwroot here, because it might be url of other page,
339                 // devs have to use httpswwwroot explicitly when creating new moodle_url
340                 $url = $CFG->wwwroot.$url;
341             }
343             // now fix the admin links if needed, no need to mess with httpswwwroot
344             if ($CFG->admin !== 'admin') {
345                 if (strpos($url, "$CFG->wwwroot/admin/") === 0) {
346                     $url = str_replace("$CFG->wwwroot/admin/", "$CFG->wwwroot/$CFG->admin/", $url);
347                 }
348             }
350             // parse the $url
351             $parts = parse_url($url);
352             if ($parts === false) {
353                 throw new moodle_exception('invalidurl');
354             }
355             if (isset($parts['query'])) {
356                 // note: the values may not be correctly decoded,
357                 //       url parameters should be always passed as array
358                 parse_str(str_replace('&amp;', '&', $parts['query']), $this->params);
359             }
360             unset($parts['query']);
361             foreach ($parts as $key => $value) {
362                 $this->$key = $value;
363             }
365             // detect slashargument value from path - we do not support directory names ending with .php
366             $pos = strpos($this->path, '.php/');
367             if ($pos !== false) {
368                 $this->slashargument = substr($this->path, $pos + 4);
369                 $this->path = substr($this->path, 0, $pos + 4);
370             }
371         }
373         $this->params($params);
374     }
376     /**
377      * Add an array of params to the params for this url.
378      *
379      * The added params override existing ones if they have the same name.
380      *
381      * @param array $params Defaults to null. If null then returns all params.
382      * @return array Array of Params for url.
383      */
384     public function params(array $params = null) {
385         $params = (array)$params;
387         foreach ($params as $key=>$value) {
388             if (is_int($key)) {
389                 throw new coding_exception('Url parameters can not have numeric keys!');
390             }
391             if (is_array($value)) {
392                 throw new coding_exception('Url parameters values can not be arrays!');
393             }
394             if (is_object($value) and !method_exists($value, '__toString')) {
395                 throw new coding_exception('Url parameters values can not be objects, unless __toString() is defined!');
396             }
397             $this->params[$key] = (string)$value;
398         }
399         return $this->params;
400     }
402     /**
403      * Remove all params if no arguments passed.
404      * Remove selected params if arguments are passed.
405      *
406      * Can be called as either remove_params('param1', 'param2')
407      * or remove_params(array('param1', 'param2')).
408      *
409      * @param mixed $params either an array of param names, or a string param name,
410      * @param string $params,... any number of additional param names.
411      * @return array url parameters
412      */
413     public function remove_params($params = null) {
414         if (!is_array($params)) {
415             $params = func_get_args();
416         }
417         foreach ($params as $param) {
418             unset($this->params[$param]);
419         }
420         return $this->params;
421     }
423     /**
424      * Remove all url parameters
425      * @param $params
426      * @return void
427      */
428     public function remove_all_params($params = null) {
429         $this->params = array();
430         $this->slashargument = '';
431     }
433     /**
434      * Add a param to the params for this url.
435      *
436      * The added param overrides existing one if they have the same name.
437      *
438      * @param string $paramname name
439      * @param string $newvalue Param value. If new value specified current value is overriden or parameter is added
440      * @return mixed string parameter value, null if parameter does not exist
441      */
442     public function param($paramname, $newvalue = '') {
443         if (func_num_args() > 1) {
444             // set new value
445             $this->params(array($paramname=>$newvalue));
446         }
447         if (isset($this->params[$paramname])) {
448             return $this->params[$paramname];
449         } else {
450             return null;
451         }
452     }
454     /**
455      * Merges parameters and validates them
456      * @param array $overrideparams
457      * @return array merged parameters
458      */
459     protected function merge_overrideparams(array $overrideparams = null) {
460         $overrideparams = (array)$overrideparams;
461         $params = $this->params;
462         foreach ($overrideparams as $key=>$value) {
463             if (is_int($key)) {
464                 throw new coding_error('Overriden parameters can not have numeric keys!');
465             }
466             if (is_array($value)) {
467                 throw new coding_error('Overriden parameters values can not be arrays!');
468             }
469             if (is_object($value) and !method_exists($value, '__toString')) {
470                 throw new coding_error('Overriden parameters values can not be objects, unless __toString() is defined!');
471             }
472             $params[$key] = (string)$value;
473         }
474         return $params;
475     }
477     /**
478      * Get the params as as a query string.
479      * This method should not be used outside of this method.
480      *
481      * @param boolean $escaped Use &amp; as params separator instead of plain &
482      * @param array $overrideparams params to add to the output params, these
483      *      override existing ones with the same name.
484      * @return string query string that can be added to a url.
485      */
486     public function get_query_string($escaped = true, array $overrideparams = null) {
487         $arr = array();
488         $params = $this->merge_overrideparams($overrideparams);
489         foreach ($params as $key => $val) {
490            $arr[] = rawurlencode($key)."=".rawurlencode($val);
491         }
492         if ($escaped) {
493             return implode('&amp;', $arr);
494         } else {
495             return implode('&', $arr);
496         }
497     }
499     /**
500      * Shortcut for printing of encoded URL.
501      * @return string
502      */
503     public function __toString() {
504         return $this->out(true);
505     }
507     /**
508      * Output url
509      *
510      * If you use the returned URL in HTML code, you want the escaped ampersands. If you use
511      * the returned URL in HTTP headers, you want $escaped=false.
512      *
513      * @param boolean $escaped Use &amp; as params separator instead of plain &
514      * @param array $overrideparams params to add to the output url, these override existing ones with the same name.
515      * @return string Resulting URL
516      */
517     public function out($escaped = true, array $overrideparams = null) {
518         if (!is_bool($escaped)) {
519             debugging('Escape parameter must be of type boolean, '.gettype($escaped).' given instead.');
520         }
522         $uri = $this->out_omit_querystring().$this->slashargument;
524         $querystring = $this->get_query_string($escaped, $overrideparams);
525         if ($querystring !== '') {
526             $uri .= '?' . $querystring;
527         }
528         if (!is_null($this->anchor)) {
529             $uri .= '#'.$this->anchor;
530         }
532         return $uri;
533     }
535     /**
536      * Returns url without parameters, everything before '?'.
537      * @return string
538      */
539     public function out_omit_querystring() {
540         $uri = $this->scheme ? $this->scheme.':'.((strtolower($this->scheme) == 'mailto') ? '':'//'): '';
541         $uri .= $this->user ? $this->user.($this->pass? ':'.$this->pass:'').'@':'';
542         $uri .= $this->host ? $this->host : '';
543         $uri .= $this->port ? ':'.$this->port : '';
544         $uri .= $this->path ? $this->path : '';
545         return $uri;
546     }
548     /**
549      * Compares this moodle_url with another
550      * See documentation of constants for an explanation of the comparison flags.
551      * @param moodle_url $url The moodle_url object to compare
552      * @param int $matchtype The type of comparison (URL_MATCH_BASE, URL_MATCH_PARAMS, URL_MATCH_EXACT)
553      * @return boolean
554      */
555     public function compare(moodle_url $url, $matchtype = URL_MATCH_EXACT) {
557         $baseself = $this->out_omit_querystring();
558         $baseother = $url->out_omit_querystring();
560         // Append index.php if there is no specific file
561         if (substr($baseself,-1)=='/') {
562             $baseself .= 'index.php';
563         }
564         if (substr($baseother,-1)=='/') {
565             $baseother .= 'index.php';
566         }
568         // Compare the two base URLs
569         if ($baseself != $baseother) {
570             return false;
571         }
573         if ($matchtype == URL_MATCH_BASE) {
574             return true;
575         }
577         $urlparams = $url->params();
578         foreach ($this->params() as $param => $value) {
579             if ($param == 'sesskey') {
580                 continue;
581             }
582             if (!array_key_exists($param, $urlparams) || $urlparams[$param] != $value) {
583                 return false;
584             }
585         }
587         if ($matchtype == URL_MATCH_PARAMS) {
588             return true;
589         }
591         foreach ($urlparams as $param => $value) {
592             if ($param == 'sesskey') {
593                 continue;
594             }
595             if (!array_key_exists($param, $this->params()) || $this->param($param) != $value) {
596                 return false;
597             }
598         }
600         return true;
601     }
603     /**
604      * Sets the anchor for the URI (the bit after the hash)
605      * @param string $anchor null means remove previous
606      */
607     public function set_anchor($anchor) {
608         if (is_null($anchor)) {
609             // remove
610             $this->anchor = null;
611         } else if ($anchor === '') {
612             // special case, used as empty link
613             $this->anchor = '';
614         } else if (preg_match('|[a-zA-Z\_\:][a-zA-Z0-9\_\-\.\:]*|', $anchor)) {
615             // Match the anchor against the NMTOKEN spec
616             $this->anchor = $anchor;
617         } else {
618             // bad luck, no valid anchor found
619             $this->anchor = null;
620         }
621     }
623     /**
624      * Sets the url slashargument value
625      * @param string $path usually file path
626      * @param string $parameter name of page parameter if slasharguments not supported
627      * @param bool $supported usually null, then it depends on $CFG->slasharguments, use true or false for other servers
628      * @return void
629      */
630     public function set_slashargument($path, $parameter = 'file', $supported = NULL) {
631         global $CFG;
632         if (is_null($supported)) {
633             $supported = $CFG->slasharguments;
634         }
636         if ($supported) {
637             $parts = explode('/', $path);
638             $parts = array_map('rawurlencode', $parts);
639             $path  = implode('/', $parts);
640             $this->slashargument = $path;
641             unset($this->params[$parameter]);
643         } else {
644             $this->slashargument = '';
645             $this->params[$parameter] = $path;
646         }
647     }
649     // == static factory methods ==
651     /**
652      * General moodle file url.
653      * @param string $urlbase the script serving the file
654      * @param string $path
655      * @param bool $forcedownload
656      * @return moodle_url
657      */
658     public static function make_file_url($urlbase, $path, $forcedownload = false) {
659         global $CFG;
661         $params = array();
662         if ($forcedownload) {
663             $params['forcedownload'] = 1;
664         }
666         $url = new moodle_url($urlbase, $params);
667         $url->set_slashargument($path);
669         return $url;
670     }
672     /**
673      * Factory method for creation of url pointing to plugin file.
674      * Please note this method can be used only from the plugins to
675      * create urls of own files, it must not be used outside of plugins!
676      * @param int $contextid
677      * @param string $component
678      * @param string $area
679      * @param int $itemid
680      * @param string $pathname
681      * @param string $filename
682      * @param bool $forcedownload
683      * @return moodle_url
684      */
685     public static function make_pluginfile_url($contextid, $component, $area, $itemid, $pathname, $filename, $forcedownload = false) {
686         global $CFG;
687         $urlbase = "$CFG->httpswwwroot/pluginfile.php";
688         if ($itemid === NULL) {
689             return self::make_file_url($urlbase, "/$contextid/$component/$area".$pathname.$filename, $forcedownload);
690         } else {
691             return self::make_file_url($urlbase, "/$contextid/$component/$area/$itemid".$pathname.$filename, $forcedownload);
692         }
693     }
695     /**
696      * Factory method for creation of url pointing to draft
697      * file of current user.
698      * @param int $draftid draft item id
699      * @param string $pathname
700      * @param string $filename
701      * @param bool $forcedownload
702      * @return moodle_url
703      */
704     public static function make_draftfile_url($draftid, $pathname, $filename, $forcedownload = false) {
705         global $CFG, $USER;
706         $urlbase = "$CFG->httpswwwroot/draftfile.php";
707         $context = get_context_instance(CONTEXT_USER, $USER->id);
709         return self::make_file_url($urlbase, "/$context->id/user/draft/$draftid".$pathname.$filename, $forcedownload);
710     }
712     /**
713      * Factory method for creating of links to legacy
714      * course files.
715      * @param int $courseid
716      * @param string $filepath
717      * @param bool $forcedownload
718      * @return moodle_url
719      */
720     public static function make_legacyfile_url($courseid, $filepath, $forcedownload = false) {
721         global $CFG;
723         $urlbase = "$CFG->wwwroot/file.php";
724         return self::make_file_url($urlbase, '/'.$courseid.'/'.$filepath, $forcedownload);
725     }
728 /**
729  * Determine if there is data waiting to be processed from a form
730  *
731  * Used on most forms in Moodle to check for data
732  * Returns the data as an object, if it's found.
733  * This object can be used in foreach loops without
734  * casting because it's cast to (array) automatically
735  *
736  * Checks that submitted POST data exists and returns it as object.
737  *
738  * @uses $_POST
739  * @return mixed false or object
740  */
741 function data_submitted() {
743     if (empty($_POST)) {
744         return false;
745     } else {
746         return (object)$_POST;
747     }
750 /**
751  * Given some normal text this function will break up any
752  * long words to a given size by inserting the given character
753  *
754  * It's multibyte savvy and doesn't change anything inside html tags.
755  *
756  * @param string $string the string to be modified
757  * @param int $maxsize maximum length of the string to be returned
758  * @param string $cutchar the string used to represent word breaks
759  * @return string
760  */
761 function break_up_long_words($string, $maxsize=20, $cutchar=' ') {
763 /// Loading the textlib singleton instance. We are going to need it.
764     $textlib = textlib_get_instance();
766 /// First of all, save all the tags inside the text to skip them
767     $tags = array();
768     filter_save_tags($string,$tags);
770 /// Process the string adding the cut when necessary
771     $output = '';
772     $length = $textlib->strlen($string);
773     $wordlength = 0;
775     for ($i=0; $i<$length; $i++) {
776         $char = $textlib->substr($string, $i, 1);
777         if ($char == ' ' or $char == "\t" or $char == "\n" or $char == "\r" or $char == "<" or $char == ">") {
778             $wordlength = 0;
779         } else {
780             $wordlength++;
781             if ($wordlength > $maxsize) {
782                 $output .= $cutchar;
783                 $wordlength = 0;
784             }
785         }
786         $output .= $char;
787     }
789 /// Finally load the tags back again
790     if (!empty($tags)) {
791         $output = str_replace(array_keys($tags), $tags, $output);
792     }
794     return $output;
797 /**
798  * Try and close the current window using JavaScript, either immediately, or after a delay.
799  *
800  * Echo's out the resulting XHTML & javascript
801  *
802  * @global object
803  * @global object
804  * @param integer $delay a delay in seconds before closing the window. Default 0.
805  * @param boolean $reloadopener if true, we will see if this window was a pop-up, and try
806  *      to reload the parent window before this one closes.
807  */
808 function close_window($delay = 0, $reloadopener = false) {
809     global $PAGE, $OUTPUT;
811     if (!$PAGE->headerprinted) {
812         $PAGE->set_title(get_string('closewindow'));
813         echo $OUTPUT->header();
814     } else {
815         $OUTPUT->container_end_all(false);
816     }
818     if ($reloadopener) {
819         $function = 'close_window_reloading_opener';
820     } else {
821         $function = 'close_window';
822     }
823     echo '<p class="centerpara">' . get_string('windowclosing') . '</p>';
825     $PAGE->requires->js_function_call($function, null, false, $delay);
827     echo $OUTPUT->footer();
828     exit;
831 /**
832  * Returns a string containing a link to the user documentation for the current
833  * page. Also contains an icon by default. Shown to teachers and admin only.
834  *
835  * @global object
836  * @global object
837  * @param string $text The text to be displayed for the link
838  * @param string $iconpath The path to the icon to be displayed
839  * @return string The link to user documentation for this current page
840  */
841 function page_doc_link($text='') {
842     global $CFG, $PAGE, $OUTPUT;
844     if (empty($CFG->docroot) || during_initial_install()) {
845         return '';
846     }
847     if (!has_capability('moodle/site:doclinks', $PAGE->context)) {
848         return '';
849     }
851     $path = $PAGE->docspath;
852     if (!$path) {
853         return '';
854     }
855     return $OUTPUT->doc_link($path, $text);
859 /**
860  * Validates an email to make sure it makes sense.
861  *
862  * @param string $address The email address to validate.
863  * @return boolean
864  */
865 function validate_email($address) {
867     return (preg_match('#^[-!\#$%&\'*+\\/0-9=?A-Z^_`a-z{|}~]+'.
868                  '(\.[-!\#$%&\'*+\\/0-9=?A-Z^_`a-z{|}~]+)*'.
869                   '@'.
870                   '[-!\#$%&\'*+\\/0-9=?A-Z^_`a-z{|}~]+\.'.
871                   '[-!\#$%&\'*+\\./0-9=?A-Z^_`a-z{|}~]+$#',
872                   $address));
875 /**
876  * Extracts file argument either from file parameter or PATH_INFO
877  * Note: $scriptname parameter is not needed anymore
878  *
879  * @global string
880  * @uses $_SERVER
881  * @uses PARAM_PATH
882  * @return string file path (only safe characters)
883  */
884 function get_file_argument() {
885     global $SCRIPT;
887     $relativepath = optional_param('file', FALSE, PARAM_PATH);
889     // then try extract file from PATH_INFO (slasharguments method)
890     if ($relativepath === false and isset($_SERVER['PATH_INFO']) and $_SERVER['PATH_INFO'] !== '') {
891         // check that PATH_INFO works == must not contain the script name
892         if (strpos($_SERVER['PATH_INFO'], $SCRIPT) === false) {
893             $relativepath = clean_param(urldecode($_SERVER['PATH_INFO']), PARAM_PATH);
894         }
895     }
897     // note: we are not using any other way because they are not compatible with unicode file names ;-)
899     return $relativepath;
902 /**
903  * Just returns an array of text formats suitable for a popup menu
904  *
905  * @uses FORMAT_MOODLE
906  * @uses FORMAT_HTML
907  * @uses FORMAT_PLAIN
908  * @uses FORMAT_MARKDOWN
909  * @return array
910  */
911 function format_text_menu() {
913     return array (FORMAT_MOODLE => get_string('formattext'),
914                   FORMAT_HTML   => get_string('formathtml'),
915                   FORMAT_PLAIN  => get_string('formatplain'),
916                   FORMAT_MARKDOWN  => get_string('formatmarkdown'));
919 /**
920  * Given text in a variety of format codings, this function returns
921  * the text as safe HTML.
922  *
923  * This function should mainly be used for long strings like posts,
924  * answers, glossary items etc. For short strings @see format_string().
925  *
926  * @todo Finish documenting this function
927  *
928  * @global object
929  * @global object
930  * @global object
931  * @global object
932  * @uses FORMAT_MOODLE
933  * @uses FORMAT_HTML
934  * @uses FORMAT_PLAIN
935  * @uses FORMAT_WIKI
936  * @uses FORMAT_MARKDOWN
937  * @uses CLI_SCRIPT
938  * @staticvar array $croncache
939  * @param string $text The text to be formatted. This is raw text originally from user input.
940  * @param int $format Identifier of the text format to be used
941  *            [FORMAT_MOODLE, FORMAT_HTML, FORMAT_PLAIN, FORMAT_WIKI, FORMAT_MARKDOWN]
942  * @param object $options ?
943  * @param int $courseid The courseid to use, defaults to $COURSE->courseid
944  * @return string
945  */
946 function format_text($text, $format=FORMAT_MOODLE, $options=NULL, $courseid=NULL) {
947     global $CFG, $COURSE, $DB, $PAGE;
949     static $croncache = array();
951     $hashstr = '';
953     if ($text === '') {
954         return ''; // no need to do any filters and cleaning
955     }
956     if (!empty($options->comments) && !empty($CFG->usecomments)) {
957         require_once($CFG->dirroot . '/comment/lib.php');
958         $comment = new comment($options->comments);
959         $cmt = $comment->output(true);
960     } else {
961         $cmt = '';
962     }
965     if (!isset($options->trusted)) {
966         $options->trusted = false;
967     }
968     if (!isset($options->noclean)) {
969         if ($options->trusted and trusttext_active()) {
970             // no cleaning if text trusted and noclean not specified
971             $options->noclean=true;
972         } else {
973             $options->noclean=false;
974         }
975     }
976     if (!isset($options->nocache)) {
977         $options->nocache=false;
978     }
979     if (!isset($options->smiley)) {
980         $options->smiley=true;
981     }
982     if (!isset($options->filter)) {
983         $options->filter=true;
984     }
985     if (!isset($options->para)) {
986         $options->para=true;
987     }
988     if (!isset($options->newlines)) {
989         $options->newlines=true;
990     }
991     if (empty($courseid)) {
992         $courseid = $COURSE->id;
993     }
995     if ($options->filter) {
996         $filtermanager = filter_manager::instance();
997     } else {
998         $filtermanager = new null_filter_manager();
999     }
1000     $context = $PAGE->context;
1002     if (!empty($CFG->cachetext) and empty($options->nocache)) {
1003         $hashstr .= $text.'-'.$filtermanager->text_filtering_hash($context, $courseid).'-'.(int)$courseid.'-'.current_language().'-'.
1004                 (int)$format.(int)$options->trusted.(int)$options->noclean.(int)$options->smiley.
1005                 (int)$options->filter.(int)$options->para.(int)$options->newlines;
1007         $time = time() - $CFG->cachetext;
1008         $md5key = md5($hashstr);
1009         if (CLI_SCRIPT) {
1010             if (isset($croncache[$md5key])) {
1011                 return $croncache[$md5key].$cmt;
1012             }
1013         }
1015         if ($oldcacheitem = $DB->get_record('cache_text', array('md5key'=>$md5key), '*', IGNORE_MULTIPLE)) {
1016             if ($oldcacheitem->timemodified >= $time) {
1017                 if (CLI_SCRIPT) {
1018                     if (count($croncache) > 150) {
1019                         reset($croncache);
1020                         $key = key($croncache);
1021                         unset($croncache[$key]);
1022                     }
1023                     $croncache[$md5key] = $oldcacheitem->formattedtext;
1024                 }
1025                 return $oldcacheitem->formattedtext.$cmt;
1026             }
1027         }
1028     }
1030     switch ($format) {
1031         case FORMAT_HTML:
1032             if ($options->smiley) {
1033                 replace_smilies($text);
1034             }
1035             if (!$options->noclean) {
1036                 $text = clean_text($text, FORMAT_HTML);
1037             }
1038             $text = $filtermanager->filter_text($text, $context, $courseid);
1039             break;
1041         case FORMAT_PLAIN:
1042             $text = s($text); // cleans dangerous JS
1043             $text = rebuildnolinktag($text);
1044             $text = str_replace('  ', '&nbsp; ', $text);
1045             $text = nl2br($text);
1046             break;
1048         case FORMAT_WIKI:
1049             // this format is deprecated
1050             $text = '<p>NOTICE: Wiki-like formatting has been removed from Moodle.  You should not be seeing
1051                      this message as all texts should have been converted to Markdown format instead.
1052                      Please post a bug report to http://moodle.org/bugs with information about where you
1053                      saw this message.</p>'.s($text);
1054             break;
1056         case FORMAT_MARKDOWN:
1057             $text = markdown_to_html($text);
1058             if ($options->smiley) {
1059                 replace_smilies($text);
1060             }
1061             if (!$options->noclean) {
1062                 $text = clean_text($text, FORMAT_HTML);
1063             }
1064             $text = $filtermanager->filter_text($text, $context, $courseid);
1065             break;
1067         default:  // FORMAT_MOODLE or anything else
1068             $text = text_to_html($text, $options->smiley, $options->para, $options->newlines);
1069             if (!$options->noclean) {
1070                 $text = clean_text($text, FORMAT_HTML);
1071             }
1072             $text = $filtermanager->filter_text($text, $context, $courseid);
1073             break;
1074     }
1076     // Warn people that we have removed this old mechanism, just in case they
1077     // were stupid enough to rely on it.
1078     if (isset($CFG->currenttextiscacheable)) {
1079         debugging('Once upon a time, Moodle had a truly evil use of global variables ' .
1080                 'called $CFG->currenttextiscacheable. The good news is that this no ' .
1081                 'longer exists. The bad news is that you seem to be using a filter that '.
1082                 'relies on it. Please seek out and destroy that filter code.', DEBUG_DEVELOPER);
1083     }
1085     if (empty($options->nocache) and !empty($CFG->cachetext)) {
1086         if (CLI_SCRIPT) {
1087             // special static cron cache - no need to store it in db if its not already there
1088             if (count($croncache) > 150) {
1089                 reset($croncache);
1090                 $key = key($croncache);
1091                 unset($croncache[$key]);
1092             }
1093             $croncache[$md5key] = $text;
1094             return $text.$cmt;
1095         }
1097         $newcacheitem = new object();
1098         $newcacheitem->md5key = $md5key;
1099         $newcacheitem->formattedtext = $text;
1100         $newcacheitem->timemodified = time();
1101         if ($oldcacheitem) {                               // See bug 4677 for discussion
1102             $newcacheitem->id = $oldcacheitem->id;
1103             try {
1104                 $DB->update_record('cache_text', $newcacheitem);   // Update existing record in the cache table
1105             } catch (dml_exception $e) {
1106                // It's unlikely that the cron cache cleaner could have
1107                // deleted this entry in the meantime, as it allows
1108                // some extra time to cover these cases.
1109             }
1110         } else {
1111             try {
1112                 $DB->insert_record('cache_text', $newcacheitem);   // Insert a new record in the cache table
1113             } catch (dml_exception $e) {
1114                // Again, it's possible that another user has caused this
1115                // record to be created already in the time that it took
1116                // to traverse this function.  That's OK too, as the
1117                // call above handles duplicate entries, and eventually
1118                // the cron cleaner will delete them.
1119             }
1120         }
1121     }
1122     return $text.$cmt;
1126 /**
1127  * Converts the text format from the value to the 'internal'
1128  * name or vice versa.
1129  *
1130  * $key can either be the value or the name and you get the other back.
1131  *
1132  * @uses FORMAT_MOODLE
1133  * @uses FORMAT_HTML
1134  * @uses FORMAT_PLAIN
1135  * @uses FORMAT_MARKDOWN
1136  * @param mixed $key int 0-4 or string one of 'moodle','html','plain','markdown'
1137  * @return mixed as above but the other way around!
1138  */
1139 function text_format_name( $key ) {
1140   $lookup = array();
1141   $lookup[FORMAT_MOODLE] = 'moodle';
1142   $lookup[FORMAT_HTML] = 'html';
1143   $lookup[FORMAT_PLAIN] = 'plain';
1144   $lookup[FORMAT_MARKDOWN] = 'markdown';
1145   $value = "error";
1146   if (!is_numeric($key)) {
1147     $key = strtolower( $key );
1148     $value = array_search( $key, $lookup );
1149   }
1150   else {
1151     if (isset( $lookup[$key] )) {
1152       $value =  $lookup[ $key ];
1153     }
1154   }
1155   return $value;
1158 /**
1159  * Resets all data related to filters, called during upgrade or when filter settings change.
1160  *
1161  * @global object
1162  * @global object
1163  * @return void
1164  */
1165 function reset_text_filters_cache() {
1166     global $CFG, $DB;
1168     $DB->delete_records('cache_text');
1169     $purifdir = $CFG->dataroot.'/cache/htmlpurifier';
1170     remove_dir($purifdir, true);
1173 /**
1174  * Given a simple string, this function returns the string
1175  * processed by enabled string filters if $CFG->filterall is enabled
1176  *
1177  * This function should be used to print short strings (non html) that
1178  * need filter processing e.g. activity titles, post subjects,
1179  * glossary concepts.
1180  *
1181  * @global object
1182  * @global object
1183  * @global object
1184  * @staticvar bool $strcache
1185  * @param string $string The string to be filtered.
1186  * @param boolean $striplinks To strip any link in the result text.
1187                               Moodle 1.8 default changed from false to true! MDL-8713
1188  * @param int $courseid Current course as filters can, potentially, use it
1189  * @return string
1190  */
1191 function format_string($string, $striplinks=true, $courseid=NULL ) {
1192     global $CFG, $COURSE, $PAGE;
1194     //We'll use a in-memory cache here to speed up repeated strings
1195     static $strcache = false;
1197     if ($strcache === false or count($strcache) > 2000 ) { // this number might need some tuning to limit memory usage in cron
1198         $strcache = array();
1199     }
1201     //init course id
1202     if (empty($courseid)) {
1203         $courseid = $COURSE->id;
1204     }
1206     //Calculate md5
1207     $md5 = md5($string.'<+>'.$striplinks.'<+>'.$courseid.'<+>'.current_language());
1209     //Fetch from cache if possible
1210     if (isset($strcache[$md5])) {
1211         return $strcache[$md5];
1212     }
1214     // First replace all ampersands not followed by html entity code
1215     // Regular expression moved to its own method for easier unit testing
1216     $string = replace_ampersands_not_followed_by_entity($string);
1218     if (!empty($CFG->filterall) && $CFG->version >= 2009040600) { // Avoid errors during the upgrade to the new system.
1219         $context = $PAGE->context;
1220         $string = filter_manager::instance()->filter_string($string, $context, $courseid);
1221     }
1223     // If the site requires it, strip ALL tags from this string
1224     if (!empty($CFG->formatstringstriptags)) {
1225         $string = strip_tags($string);
1227     } else {
1228         // Otherwise strip just links if that is required (default)
1229         if ($striplinks) {  //strip links in string
1230             $string = strip_links($string);
1231         }
1232         $string = clean_text($string);
1233     }
1235     //Store to cache
1236     $strcache[$md5] = $string;
1238     return $string;
1241 /**
1242  * Given a string, performs a negative lookahead looking for any ampersand character
1243  * that is not followed by a proper HTML entity. If any is found, it is replaced
1244  * by &amp;. The string is then returned.
1245  *
1246  * @param string $string
1247  * @return string
1248  */
1249 function replace_ampersands_not_followed_by_entity($string) {
1250     return preg_replace("/\&(?![a-zA-Z0-9#]{1,8};)/", "&amp;", $string);
1253 /**
1254  * Given a string, replaces all <a>.*</a> by .* and returns the string.
1255  *
1256  * @param string $string
1257  * @return string
1258  */
1259 function strip_links($string) {
1260     return preg_replace('/(<a\s[^>]+?>)(.+?)(<\/a>)/is','$2',$string);
1263 /**
1264  * This expression turns links into something nice in a text format. (Russell Jungwirth)
1265  *
1266  * @param string $string
1267  * @return string
1268  */
1269 function wikify_links($string) {
1270     return preg_replace('~(<a [^<]*href=["|\']?([^ "\']*)["|\']?[^>]*>([^<]*)</a>)~i','$3 [ $2 ]', $string);
1273 /**
1274  * Replaces non-standard HTML entities
1275  *
1276  * @param string $string
1277  * @return string
1278  */
1279 function fix_non_standard_entities($string) {
1280     $text = preg_replace('/&#0*([0-9]+);?/', '&#$1;', $string);
1281     $text = preg_replace('/&#x0*([0-9a-fA-F]+);?/', '&#x$1;', $text);
1282     return $text;
1285 /**
1286  * Given text in a variety of format codings, this function returns
1287  * the text as plain text suitable for plain email.
1288  *
1289  * @uses FORMAT_MOODLE
1290  * @uses FORMAT_HTML
1291  * @uses FORMAT_PLAIN
1292  * @uses FORMAT_WIKI
1293  * @uses FORMAT_MARKDOWN
1294  * @param string $text The text to be formatted. This is raw text originally from user input.
1295  * @param int $format Identifier of the text format to be used
1296  *            [FORMAT_MOODLE, FORMAT_HTML, FORMAT_PLAIN, FORMAT_WIKI, FORMAT_MARKDOWN]
1297  * @return string
1298  */
1299 function format_text_email($text, $format) {
1301     switch ($format) {
1303         case FORMAT_PLAIN:
1304             return $text;
1305             break;
1307         case FORMAT_WIKI:
1308             $text = wiki_to_html($text);
1309             $text = wikify_links($text);
1310             return strtr(strip_tags($text), array_flip(get_html_translation_table(HTML_ENTITIES)));
1311             break;
1313         case FORMAT_HTML:
1314             return html_to_text($text);
1315             break;
1317         case FORMAT_MOODLE:
1318         case FORMAT_MARKDOWN:
1319         default:
1320             $text = wikify_links($text);
1321             return strtr(strip_tags($text), array_flip(get_html_translation_table(HTML_ENTITIES)));
1322             break;
1323     }
1326 /**
1327  * Given some text in HTML format, this function will pass it
1328  * through any filters that have been configured for this context.
1329  *
1330  * @global object
1331  * @global object
1332  * @global object
1333  * @param string $text The text to be passed through format filters
1334  * @param int $courseid The current course.
1335  * @return string the filtered string.
1336  */
1337 function filter_text($text, $courseid=NULL) {
1338     global $CFG, $COURSE, $PAGE;
1340     if (empty($courseid)) {
1341         $courseid = $COURSE->id;       // (copied from format_text)
1342     }
1344     $context = $PAGE->context;
1346     return filter_manager::instance()->filter_text($text, $context, $courseid);
1348 /**
1349  * Formats activity intro text
1350  *
1351  * @global object
1352  * @uses CONTEXT_MODULE
1353  * @param string $module name of module
1354  * @param object $activity instance of activity
1355  * @param int $cmid course module id
1356  * @param bool $filter filter resulting html text
1357  * @return text
1358  */
1359 function format_module_intro($module, $activity, $cmid, $filter=true) {
1360     global $CFG;
1361     require_once("$CFG->libdir/filelib.php");
1362     $options = (object)array('noclean'=>true, 'para'=>false, 'filter'=>false);
1363     $context = get_context_instance(CONTEXT_MODULE, $cmid);
1364     $intro = file_rewrite_pluginfile_urls($activity->intro, 'pluginfile.php', $context->id, 'mod_'.$module, 'intro', null);
1365     return trim(format_text($intro, $activity->introformat, $options));
1368 /**
1369  * Legacy function, used for cleaning of old forum and glossary text only.
1370  *
1371  * @global object
1372  * @param string $text text that may contain TRUSTTEXT marker
1373  * @return text without any TRUSTTEXT marker
1374  */
1375 function trusttext_strip($text) {
1376     global $CFG;
1378     while (true) { //removing nested TRUSTTEXT
1379         $orig = $text;
1380         $text = str_replace('#####TRUSTTEXT#####', '', $text);
1381         if (strcmp($orig, $text) === 0) {
1382             return $text;
1383         }
1384     }
1387 /**
1388  * Must be called before editing of all texts
1389  * with trust flag. Removes all XSS nasties
1390  * from texts stored in database if needed.
1391  *
1392  * @param object $object data object with xxx, xxxformat and xxxtrust fields
1393  * @param string $field name of text field
1394  * @param object $context active context
1395  * @return object updated $object
1396  */
1397 function trusttext_pre_edit($object, $field, $context) {
1398     $trustfield  = $field.'trust';
1399     $formatfield = $field.'format';
1401     if (!$object->$trustfield or !trusttext_trusted($context)) {
1402         $object->$field = clean_text($object->$field, $object->$formatfield);
1403     }
1405     return $object;
1408 /**
1409  * Is current user trusted to enter no dangerous XSS in this context?
1410  *
1411  * Please note the user must be in fact trusted everywhere on this server!!
1412  *
1413  * @param object $context
1414  * @return bool true if user trusted
1415  */
1416 function trusttext_trusted($context) {
1417     return (trusttext_active() and has_capability('moodle/site:trustcontent', $context));
1420 /**
1421  * Is trusttext feature active?
1422  *
1423  * @global object
1424  * @param object $context
1425  * @return bool
1426  */
1427 function trusttext_active() {
1428     global $CFG;
1430     return !empty($CFG->enabletrusttext);
1433 /**
1434  * Given raw text (eg typed in by a user), this function cleans it up
1435  * and removes any nasty tags that could mess up Moodle pages.
1436  *
1437  * @uses FORMAT_MOODLE
1438  * @uses FORMAT_PLAIN
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) {
1448     global $ALLOWED_TAGS, $CFG;
1450     if (empty($text) or is_numeric($text)) {
1451        return (string)$text;
1452     }
1454     switch ($format) {
1455         case FORMAT_PLAIN:
1456         case FORMAT_MARKDOWN:
1457             return $text;
1459         default:
1461             if (!empty($CFG->enablehtmlpurifier)) {
1462                 $text = purify_html($text);
1463             } else {
1464             /// Fix non standard entity notations
1465                 $text = fix_non_standard_entities($text);
1467             /// Remove tags that are not allowed
1468                 $text = strip_tags($text, $ALLOWED_TAGS);
1470             /// Clean up embedded scripts and , using kses
1471                 $text = cleanAttributes($text);
1473             /// Again remove tags that are not allowed
1474                 $text = strip_tags($text, $ALLOWED_TAGS);
1476             }
1478         /// Remove potential script events - some extra protection for undiscovered bugs in our code
1479             $text = preg_replace("~([^a-z])language([[:space:]]*)=~i", "$1Xlanguage=", $text);
1480             $text = preg_replace("~([^a-z])on([a-z]+)([[:space:]]*)=~i", "$1Xon$2=", $text);
1482             return $text;
1483     }
1486 /**
1487  * KSES replacement cleaning function - uses HTML Purifier.
1488  *
1489  * @global object
1490  * @param string $text The (X)HTML string to purify
1491  */
1492 function purify_html($text) {
1493     global $CFG;
1495     // this can not be done only once because we sometimes need to reset the cache
1496     $cachedir = $CFG->dataroot.'/cache/htmlpurifier';
1497     $status = check_dir_exists($cachedir, true, true);
1499     static $purifier = false;
1500     static $config;
1501     if ($purifier === false) {
1502         require_once $CFG->libdir.'/htmlpurifier/HTMLPurifier.safe-includes.php';
1503         $config = HTMLPurifier_Config::createDefault();
1504         $config->set('Output.Newline', "\n");
1505         $config->set('Core.ConvertDocumentToFragment', true);
1506         $config->set('Core.Encoding', 'UTF-8');
1507         $config->set('HTML.Doctype', 'XHTML 1.0 Transitional');
1508         $config->set('Cache.SerializerPath', $cachedir);
1509         $config->set('URI.AllowedSchemes', array('http'=>1, 'https'=>1, 'ftp'=>1, 'irc'=>1, 'nntp'=>1, 'news'=>1, 'rtsp'=>1, 'teamspeak'=>1, 'gopher'=>1, 'mms'=>1));
1510         $config->set('Attr.AllowedFrameTargets', array('_blank'));
1511         $purifier = new HTMLPurifier($config);
1512     }
1513     return $purifier->purify($text);
1516 /**
1517  * This function takes a string and examines it for HTML tags.
1518  *
1519  * If tags are detected it passes the string to a helper function {@link cleanAttributes2()}
1520  * which checks for attributes and filters them for malicious content
1521  *
1522  * @param string $str The string to be examined for html tags
1523  * @return string
1524  */
1525 function cleanAttributes($str){
1526     $result = preg_replace_callback(
1527             '%(<[^>]*(>|$)|>)%m', #search for html tags
1528             "cleanAttributes2",
1529             $str
1530             );
1531     return  $result;
1534 /**
1535  * This function takes a string with an html tag and strips out any unallowed
1536  * protocols e.g. javascript:
1537  *
1538  * It calls ancillary functions in kses which are prefixed by kses
1539  *
1540  * @global object
1541  * @global string
1542  * @param array $htmlArray An array from {@link cleanAttributes()}, containing in its 1st
1543  *              element the html to be cleared
1544  * @return string
1545  */
1546 function cleanAttributes2($htmlArray){
1548     global $CFG, $ALLOWED_PROTOCOLS;
1549     require_once($CFG->libdir .'/kses.php');
1551     $htmlTag = $htmlArray[1];
1552     if (substr($htmlTag, 0, 1) != '<') {
1553         return '&gt;';  //a single character ">" detected
1554     }
1555     if (!preg_match('%^<\s*(/\s*)?([a-zA-Z0-9]+)([^>]*)>?$%', $htmlTag, $matches)) {
1556         return ''; // It's seriously malformed
1557     }
1558     $slash = trim($matches[1]); //trailing xhtml slash
1559     $elem = $matches[2];    //the element name
1560     $attrlist = $matches[3]; // the list of attributes as a string
1562     $attrArray = kses_hair($attrlist, $ALLOWED_PROTOCOLS);
1564     $attStr = '';
1565     foreach ($attrArray as $arreach) {
1566         $arreach['name'] = strtolower($arreach['name']);
1567         if ($arreach['name'] == 'style') {
1568             $value = $arreach['value'];
1569             while (true) {
1570                 $prevvalue = $value;
1571                 $value = kses_no_null($value);
1572                 $value = preg_replace("/\/\*.*\*\//Us", '', $value);
1573                 $value = kses_decode_entities($value);
1574                 $value = preg_replace('/(&#[0-9]+)(;?)/', "\\1;", $value);
1575                 $value = preg_replace('/(&#x[0-9a-fA-F]+)(;?)/', "\\1;", $value);
1576                 if ($value === $prevvalue) {
1577                     $arreach['value'] = $value;
1578                     break;
1579                 }
1580             }
1581             $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']);
1582             $arreach['value'] = preg_replace("/v\s*b\s*s\s*c\s*r\s*i\s*p\s*t/i", "Xvbscript", $arreach['value']);
1583             $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']);
1584             $arreach['value'] = preg_replace("/b\s*i\s*n\s*d\s*i\s*n\s*g/i", "Xbinding", $arreach['value']);
1585         } else if ($arreach['name'] == 'href') {
1586             //Adobe Acrobat Reader XSS protection
1587             $arreach['value'] = preg_replace('/(\.(pdf|fdf|xfdf|xdp|xfd)[^#]*)#.*$/i', '$1', $arreach['value']);
1588         }
1589         $attStr .=  ' '.$arreach['name'].'="'.$arreach['value'].'"';
1590     }
1592     $xhtml_slash = '';
1593     if (preg_match('%/\s*$%', $attrlist)) {
1594         $xhtml_slash = ' /';
1595     }
1596     return '<'. $slash . $elem . $attStr . $xhtml_slash .'>';
1599 /**
1600  * Replaces all known smileys in the text with image equivalents
1601  *
1602  * @global object
1603  * @staticvar array $e
1604  * @staticvar array $img
1605  * @staticvar array $emoticons
1606  * @param string $text Passed by reference. The string to search for smiley strings.
1607  * @return string
1608  */
1609 function replace_smilies(&$text) {
1610     global $CFG, $OUTPUT;
1612     if (empty($CFG->emoticons)) { /// No emoticons defined, nothing to process here
1613         return;
1614     }
1616     $lang = current_language();
1617     $emoticonstring = $CFG->emoticons;
1618     static $e = array();
1619     static $img = array();
1620     static $emoticons = null;
1622     if (is_null($emoticons)) {
1623         $emoticons = array();
1624         if ($emoticonstring) {
1625             $items = explode('{;}', $CFG->emoticons);
1626             foreach ($items as $item) {
1627                $item = explode('{:}', $item);
1628               $emoticons[$item[0]] = $item[1];
1629             }
1630         }
1631     }
1633     if (empty($img[$lang])) {  /// After the first time this is not run again
1634         $e[$lang] = array();
1635         $img[$lang] = array();
1636         foreach ($emoticons as $emoticon => $image){
1637             $alttext = get_string($image, 'pix');
1638             if ($alttext === '') {
1639                 $alttext = $image;
1640             }
1641             $e[$lang][] = $emoticon;
1642             $img[$lang][] = '<img alt="'. $alttext .'" width="15" height="15" src="'. $OUTPUT->pix_url('s/' . $image) . '" />';
1643         }
1644     }
1646     // Exclude from transformations all the code inside <script> tags
1647     // Needed to solve Bug 1185. Thanks to jouse 2001 detecting it. :-)
1648     // Based on code from glossary filter by Williams Castillo.
1649     //       - Eloy
1651     // Detect all the <script> zones to take out
1652     $excludes = array();
1653     preg_match_all('/<script language(.+?)<\/script>/is',$text,$list_of_excludes);
1655     // Take out all the <script> zones from text
1656     foreach (array_unique($list_of_excludes[0]) as $key=>$value) {
1657         $excludes['<+'.$key.'+>'] = $value;
1658     }
1659     if ($excludes) {
1660         $text = str_replace($excludes,array_keys($excludes),$text);
1661     }
1663 /// this is the meat of the code - this is run every time
1664     $text = str_replace($e[$lang], $img[$lang], $text);
1666     // Recover all the <script> zones to text
1667     if ($excludes) {
1668         $text = str_replace(array_keys($excludes),$excludes,$text);
1669     }
1672 /**
1673  * This code is called from help.php to inject a list of smilies into the
1674  * emoticons help file.
1675  *
1676  * @global object
1677  * @global object
1678  * @return string HTML for a list of smilies.
1679  */
1680 function get_emoticons_list_for_help_file() {
1681     global $CFG, $SESSION, $PAGE, $OUTPUT;
1682     if (empty($CFG->emoticons)) {
1683         return '';
1684     }
1686     $items = explode('{;}', $CFG->emoticons);
1687     $output = '<ul id="emoticonlist">';
1688     foreach ($items as $item) {
1689         $item = explode('{:}', $item);
1690         $output .= '<li><img src="' . $OUTPUT->pix_url('s/' . $item[1]) . '" alt="' .
1691                 $item[0] . '" /><code>' . $item[0] . '</code></li>';
1692     }
1693     $output .= '</ul>';
1694     if (!empty($SESSION->inserttextform)) {
1695         $formname = $SESSION->inserttextform;
1696         $fieldname = $SESSION->inserttextfield;
1697     } else {
1698         $formname = 'theform';
1699         $fieldname = 'message';
1700     }
1702     $PAGE->requires->yui2_lib('event');
1703     $PAGE->requires->js_function_call('emoticons_help.init', array($formname, $fieldname, 'emoticonlist'));
1704     return $output;
1708 /**
1709  * Given plain text, makes it into HTML as nicely as possible.
1710  * May contain HTML tags already
1711  *
1712  * @global object
1713  * @param string $text The string to convert.
1714  * @param boolean $smiley Convert any smiley characters to smiley images?
1715  * @param boolean $para If true then the returned string will be wrapped in div tags
1716  * @param boolean $newlines If true then lines newline breaks will be converted to HTML newline breaks.
1717  * @return string
1718  */
1720 function text_to_html($text, $smiley=true, $para=true, $newlines=true) {
1721 ///
1723     global $CFG;
1725 /// Remove any whitespace that may be between HTML tags
1726     $text = preg_replace("~>([[:space:]]+)<~i", "><", $text);
1728 /// Remove any returns that precede or follow HTML tags
1729     $text = preg_replace("~([\n\r])<~i", " <", $text);
1730     $text = preg_replace("~>([\n\r])~i", "> ", $text);
1732     convert_urls_into_links($text);
1734 /// Make returns into HTML newlines.
1735     if ($newlines) {
1736         $text = nl2br($text);
1737     }
1739 /// Turn smileys into images.
1740     if ($smiley) {
1741         replace_smilies($text);
1742     }
1744 /// Wrap the whole thing in a div if required
1745     if ($para) {
1746         //return '<p>'.$text.'</p>'; //1.9 version
1747         return '<div class="text_to_html">'.$text.'</div>';
1748     } else {
1749         return $text;
1750     }
1753 /**
1754  * Given Markdown formatted text, make it into XHTML using external function
1755  *
1756  * @global object
1757  * @param string $text The markdown formatted text to be converted.
1758  * @return string Converted text
1759  */
1760 function markdown_to_html($text) {
1761     global $CFG;
1763     if ($text === '' or $text === NULL) {
1764         return $text;
1765     }
1767     require_once($CFG->libdir .'/markdown.php');
1769     return Markdown($text);
1772 /**
1773  * Given HTML text, make it into plain text using external function
1774  *
1775  * @global object
1776  * @param string $html The text to be converted.
1777  * @return string
1778  */
1779 function html_to_text($html) {
1781     global $CFG;
1783     require_once($CFG->libdir .'/html2text.php');
1785     $h2t = new html2text($html);
1786     $result = $h2t->get_text();
1788     return $result;
1791 /**
1792  * Given some text this function converts any URLs it finds into HTML links
1793  *
1794  * @param string $text Passed in by reference. The string to be searched for urls.
1795  */
1796 function convert_urls_into_links(&$text) {
1797     //I've added img tags to this list of tags to ignore.
1798     //See MDL-21168 for more info. A better way to ignore tags whether or not
1799     //they are escaped partially or completely would be desirable. For example:
1800     //<a href="blah">
1801     //&lt;a href="blah"&gt;
1802     //&lt;a href="blah">
1803     $filterignoretagsopen  = array('<a\s[^>]+?>');
1804     $filterignoretagsclose = array('</a>');
1805     filter_save_ignore_tags($text,$filterignoretagsopen,$filterignoretagsclose,$ignoretags);
1807     // Check if we support unicode modifiers in regular expressions. Cache it.
1808     // TODO: this check should be a environment requirement in Moodle 2.0, as far as unicode
1809     // chars are going to arrive to URLs officially really soon (2010?)
1810     // Original RFC regex from: http://www.bytemycode.com/snippets/snippet/796/
1811     // Various ideas from: http://alanstorm.com/url_regex_explained
1812     // Unicode check, negative assertion and other bits from Moodle.
1813     static $unicoderegexp;
1814     if (!isset($unicoderegexp)) {
1815         $unicoderegexp = @preg_match('/\pL/u', 'a'); // This will fail silently, returning false,
1816     }
1818     //todo: MDL-21296 - use of unicode modifiers may cause a timeout
1819     if ($unicoderegexp) { //We can use unicode modifiers
1820         $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',
1821                              '<a href="\\1" class="_blanktarget">\\1</a>', $text);
1822         $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',
1823                              '<a href="http://\\1" class="_blanktarget">\\1</a>', $text);
1824     } else { //We cannot use unicode modifiers
1825         $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',
1826                              '<a href="\\1" class="_blanktarget">\\1</a>', $text);
1827         $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',
1828                              '<a href="http://\\1" class="_blanktarget">\\1</a>', $text);
1829     }
1831     if (!empty($ignoretags)) {
1832         $ignoretags = array_reverse($ignoretags); /// Reversed so "progressive" str_replace() will solve some nesting problems.
1833         $text = str_replace(array_keys($ignoretags),$ignoretags,$text);
1834     }
1837 /**
1838  * This function will highlight search words in a given string
1839  *
1840  * It cares about HTML and will not ruin links.  It's best to use
1841  * this function after performing any conversions to HTML.
1842  *
1843  * @param string $needle The search string. Syntax like "word1 +word2 -word3" is dealt with correctly.
1844  * @param string $haystack The string (HTML) within which to highlight the search terms.
1845  * @param boolean $matchcase whether to do case-sensitive. Default case-insensitive.
1846  * @param string $prefix the string to put before each search term found.
1847  * @param string $suffix the string to put after each search term found.
1848  * @return string The highlighted HTML.
1849  */
1850 function highlight($needle, $haystack, $matchcase = false,
1851         $prefix = '<span class="highlight">', $suffix = '</span>') {
1853 /// Quick bail-out in trivial cases.
1854     if (empty($needle) or empty($haystack)) {
1855         return $haystack;
1856     }
1858 /// Break up the search term into words, discard any -words and build a regexp.
1859     $words = preg_split('/ +/', trim($needle));
1860     foreach ($words as $index => $word) {
1861         if (strpos($word, '-') === 0) {
1862             unset($words[$index]);
1863         } else if (strpos($word, '+') === 0) {
1864             $words[$index] = '\b' . preg_quote(ltrim($word, '+'), '/') . '\b'; // Match only as a complete word.
1865         } else {
1866             $words[$index] = preg_quote($word, '/');
1867         }
1868     }
1869     $regexp = '/(' . implode('|', $words) . ')/u'; // u is do UTF-8 matching.
1870     if (!$matchcase) {
1871         $regexp .= 'i';
1872     }
1874 /// Another chance to bail-out if $search was only -words
1875     if (empty($words)) {
1876         return $haystack;
1877     }
1879 /// Find all the HTML tags in the input, and store them in a placeholders array.
1880     $placeholders = array();
1881     $matches = array();
1882     preg_match_all('/<[^>]*>/', $haystack, $matches);
1883     foreach (array_unique($matches[0]) as $key => $htmltag) {
1884         $placeholders['<|' . $key . '|>'] = $htmltag;
1885     }
1887 /// In $hastack, replace each HTML tag with the corresponding placeholder.
1888     $haystack = str_replace($placeholders, array_keys($placeholders), $haystack);
1890 /// In the resulting string, Do the highlighting.
1891     $haystack = preg_replace($regexp, $prefix . '$1' . $suffix, $haystack);
1893 /// Turn the placeholders back into HTML tags.
1894     $haystack = str_replace(array_keys($placeholders), $placeholders, $haystack);
1896     return $haystack;
1899 /**
1900  * This function will highlight instances of $needle in $haystack
1901  *
1902  * It's faster that the above function {@link highlight()} and doesn't care about
1903  * HTML or anything.
1904  *
1905  * @param string $needle The string to search for
1906  * @param string $haystack The string to search for $needle in
1907  * @return string The highlighted HTML
1908  */
1909 function highlightfast($needle, $haystack) {
1911     if (empty($needle) or empty($haystack)) {
1912         return $haystack;
1913     }
1915     $parts = explode(moodle_strtolower($needle), moodle_strtolower($haystack));
1917     if (count($parts) === 1) {
1918         return $haystack;
1919     }
1921     $pos = 0;
1923     foreach ($parts as $key => $part) {
1924         $parts[$key] = substr($haystack, $pos, strlen($part));
1925         $pos += strlen($part);
1927         $parts[$key] .= '<span class="highlight">'.substr($haystack, $pos, strlen($needle)).'</span>';
1928         $pos += strlen($needle);
1929     }
1931     return str_replace('<span class="highlight"></span>', '', join('', $parts));
1934 /**
1935  * Return a string containing 'lang', xml:lang and optionally 'dir' HTML attributes.
1936  * Internationalisation, for print_header and backup/restorelib.
1937  *
1938  * @param bool $dir Default false
1939  * @return string Attributes
1940  */
1941 function get_html_lang($dir = false) {
1942     $direction = '';
1943     if ($dir) {
1944         if (right_to_left()) {
1945             $direction = ' dir="rtl"';
1946         } else {
1947             $direction = ' dir="ltr"';
1948         }
1949     }
1950     //Accessibility: added the 'lang' attribute to $direction, used in theme <html> tag.
1951     $language = str_replace('_', '-', current_language());
1952     @header('Content-Language: '.$language);
1953     return ($direction.' lang="'.$language.'" xml:lang="'.$language.'"');
1957 /// STANDARD WEB PAGE PARTS ///////////////////////////////////////////////////
1959 /**
1960  * Send the HTTP headers that Moodle requires.
1961  * @param $cacheable Can this page be cached on back?
1962  */
1963 function send_headers($contenttype, $cacheable = true) {
1964     @header('Content-Type: ' . $contenttype);
1965     @header('Content-Script-Type: text/javascript');
1966     @header('Content-Style-Type: text/css');
1968     if ($cacheable) {
1969         // Allow caching on "back" (but not on normal clicks)
1970         @header('Cache-Control: private, pre-check=0, post-check=0, max-age=0');
1971         @header('Pragma: no-cache');
1972         @header('Expires: ');
1973     } else {
1974         // Do everything we can to always prevent clients and proxies caching
1975         @header('Cache-Control: no-store, no-cache, must-revalidate');
1976         @header('Cache-Control: post-check=0, pre-check=0', false);
1977         @header('Pragma: no-cache');
1978         @header('Expires: Mon, 20 Aug 1969 09:23:00 GMT');
1979         @header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
1980     }
1981     @header('Accept-Ranges: none');
1984 /**
1985  * Return the right arrow with text ('next'), and optionally embedded in a link.
1986  *
1987  * @global object
1988  * @param string $text HTML/plain text label (set to blank only for breadcrumb separator cases).
1989  * @param string $url An optional link to use in a surrounding HTML anchor.
1990  * @param bool $accesshide True if text should be hidden (for screen readers only).
1991  * @param string $addclass Additional class names for the link, or the arrow character.
1992  * @return string HTML string.
1993  */
1994 function link_arrow_right($text, $url='', $accesshide=false, $addclass='') {
1995     global $OUTPUT; //TODO: move to output renderer
1996     $arrowclass = 'arrow ';
1997     if (! $url) {
1998         $arrowclass .= $addclass;
1999     }
2000     $arrow = '<span class="'.$arrowclass.'">'.$OUTPUT->rarrow().'</span>';
2001     $htmltext = '';
2002     if ($text) {
2003         $htmltext = '<span class="arrow_text">'.$text.'</span>&nbsp;';
2004         if ($accesshide) {
2005             $htmltext = get_accesshide($htmltext);
2006         }
2007     }
2008     if ($url) {
2009         $class = 'arrow_link';
2010         if ($addclass) {
2011             $class .= ' '.$addclass;
2012         }
2013         return '<a class="'.$class.'" href="'.$url.'" title="'.preg_replace('/<.*?>/','',$text).'">'.$htmltext.$arrow.'</a>';
2014     }
2015     return $htmltext.$arrow;
2018 /**
2019  * Return the left arrow with text ('previous'), and optionally embedded in a link.
2020  *
2021  * @global object
2022  * @param string $text HTML/plain text label (set to blank only for breadcrumb separator cases).
2023  * @param string $url An optional link to use in a surrounding HTML anchor.
2024  * @param bool $accesshide True if text should be hidden (for screen readers only).
2025  * @param string $addclass Additional class names for the link, or the arrow character.
2026  * @return string HTML string.
2027  */
2028 function link_arrow_left($text, $url='', $accesshide=false, $addclass='') {
2029     global $OUTPUT; // TODO: move to utput renderer
2030     $arrowclass = 'arrow ';
2031     if (! $url) {
2032         $arrowclass .= $addclass;
2033     }
2034     $arrow = '<span class="'.$arrowclass.'">'.$OUTPUT->larrow().'</span>';
2035     $htmltext = '';
2036     if ($text) {
2037         $htmltext = '&nbsp;<span class="arrow_text">'.$text.'</span>';
2038         if ($accesshide) {
2039             $htmltext = get_accesshide($htmltext);
2040         }
2041     }
2042     if ($url) {
2043         $class = 'arrow_link';
2044         if ($addclass) {
2045             $class .= ' '.$addclass;
2046         }
2047         return '<a class="'.$class.'" href="'.$url.'" title="'.preg_replace('/<.*?>/','',$text).'">'.$arrow.$htmltext.'</a>';
2048     }
2049     return $arrow.$htmltext;
2052 /**
2053  * Return a HTML element with the class "accesshide", for accessibility.
2054  * Please use cautiously - where possible, text should be visible!
2055  *
2056  * @param string $text Plain text.
2057  * @param string $elem Lowercase element name, default "span".
2058  * @param string $class Additional classes for the element.
2059  * @param string $attrs Additional attributes string in the form, "name='value' name2='value2'"
2060  * @return string HTML string.
2061  */
2062 function get_accesshide($text, $elem='span', $class='', $attrs='') {
2063     return "<$elem class=\"accesshide $class\" $attrs>$text</$elem>";
2066 /**
2067  * Return the breadcrumb trail navigation separator.
2068  *
2069  * @return string HTML string.
2070  */
2071 function get_separator() {
2072     //Accessibility: the 'hidden' slash is preferred for screen readers.
2073     return ' '.link_arrow_right($text='/', $url='', $accesshide=true, 'sep').' ';
2076 /**
2077  * Print (or return) a collapsible region, that has a caption that can
2078  * be clicked to expand or collapse the region.
2079  *
2080  * If JavaScript is off, then the region will always be expanded.
2081  *
2082  * @param string $contents the contents of the box.
2083  * @param string $classes class names added to the div that is output.
2084  * @param string $id id added to the div that is output. Must not be blank.
2085  * @param string $caption text displayed at the top. Clicking on this will cause the region to expand or contract.
2086  * @param string $userpref the name of the user preference that stores the user's preferred default state.
2087  *      (May be blank if you do not wish the state to be persisted.
2088  * @param boolean $default Initial collapsed state to use if the user_preference it not set.
2089  * @param boolean $return if true, return the HTML as a string, rather than printing it.
2090  * @return string|void If $return is false, returns nothing, otherwise returns a string of HTML.
2091  */
2092 function print_collapsible_region($contents, $classes, $id, $caption, $userpref = '', $default = false, $return = false) {
2093     $output  = print_collapsible_region_start($classes, $id, $caption, $userpref, true, true);
2094     $output .= $contents;
2095     $output .= print_collapsible_region_end(true);
2097     if ($return) {
2098         return $output;
2099     } else {
2100         echo $output;
2101     }
2104 /**
2105  * Print (or return) the start of a collapsible region, that has a caption that can
2106  * be clicked to expand or collapse the region. If JavaScript is off, then the region
2107  * will always be expanded.
2108  *
2109  * @global object
2110  * @param string $classes class names added to the div that is output.
2111  * @param string $id id added to the div that is output. Must not be blank.
2112  * @param string $caption text displayed at the top. Clicking on this will cause the region to expand or contract.
2113  * @param boolean $userpref the name of the user preference that stores the user's preferred default state.
2114  *      (May be blank if you do not wish the state to be persisted.
2115  * @param boolean $default Initial collapsed state to use if the user_preference it not set.
2116  * @param boolean $return if true, return the HTML as a string, rather than printing it.
2117  * @return string|void if $return is false, returns nothing, otherwise returns a string of HTML.
2118  */
2119 function print_collapsible_region_start($classes, $id, $caption, $userpref = false, $default = false, $return = false) {
2120     global $CFG, $PAGE, $OUTPUT;
2122     // Work out the initial state.
2123     if (is_string($userpref)) {
2124         user_preference_allow_ajax_update($userpref, PARAM_BOOL);
2125         $collapsed = get_user_preferences($userpref, $default);
2126     } else {
2127         $collapsed = $default;
2128         $userpref = false;
2129     }
2131     if ($collapsed) {
2132         $classes .= ' collapsed';
2133     }
2135     $output = '';
2136     $output .= '<div id="' . $id . '" class="collapsibleregion ' . $classes . '">';
2137     $output .= '<div id="' . $id . '_sizer">';
2138     $output .= '<div id="' . $id . '_caption" class="collapsibleregioncaption">';
2139     $output .= $caption . ' ';
2140     $output .= '</div><div id="' . $id . '_inner" class="collapsibleregioninner">';
2141     $PAGE->requires->js_init_call('M.util.init_collapsible_region', array($id, $userpref, get_string('clicktohideshow')));
2143     if ($return) {
2144         return $output;
2145     } else {
2146         echo $output;
2147     }
2150 /**
2151  * Close a region started with print_collapsible_region_start.
2152  *
2153  * @param boolean $return if true, return the HTML as a string, rather than printing it.
2154  * @return string|void if $return is false, returns nothing, otherwise returns a string of HTML.
2155  */
2156 function print_collapsible_region_end($return = false) {
2157     $output = '</div></div></div>';
2159     if ($return) {
2160         return $output;
2161     } else {
2162         echo $output;
2163     }
2166 /**
2167  * Print a specified group's avatar.
2168  *
2169  * @global object
2170  * @uses CONTEXT_COURSE
2171  * @param array $group A single {@link group} object OR array of groups.
2172  * @param int $courseid The course ID.
2173  * @param boolean $large Default small picture, or large.
2174  * @param boolean $return If false print picture, otherwise return the output as string
2175  * @param boolean $link Enclose image in a link to view specified course?
2176  * @return string|void Depending on the setting of $return
2177  */
2178 function print_group_picture($group, $courseid, $large=false, $return=false, $link=true) {
2179     global $CFG;
2181     if (is_array($group)) {
2182         $output = '';
2183         foreach($group as $g) {
2184             $output .= print_group_picture($g, $courseid, $large, true, $link);
2185         }
2186         if ($return) {
2187             return $output;
2188         } else {
2189             echo $output;
2190             return;
2191         }
2192     }
2194     $context = get_context_instance(CONTEXT_COURSE, $courseid);
2196     // If there is no picture, do nothing
2197     if (!$group->picture) {
2198         return '';
2199     }
2201     // If picture is hidden, only show to those with course:managegroups
2202     if ($group->hidepicture and !has_capability('moodle/course:managegroups', $context)) {
2203         return '';
2204     }
2206     if ($link or has_capability('moodle/site:accessallgroups', $context)) {
2207         $output = '<a href="'. $CFG->wwwroot .'/user/index.php?id='. $courseid .'&amp;group='. $group->id .'">';
2208     } else {
2209         $output = '';
2210     }
2211     if ($large) {
2212         $file = 'f1';
2213     } else {
2214         $file = 'f2';
2215     }
2217     // Print custom group picture
2218     require_once($CFG->libdir.'/filelib.php');
2219     $grouppictureurl = get_file_url($group->id.'/'.$file.'.jpg', null, 'usergroup');
2220     $output .= '<img class="grouppicture" src="'.$grouppictureurl.'"'.
2221         ' alt="'.s(get_string('group').' '.$group->name).'" title="'.s($group->name).'"/>';
2223     if ($link or has_capability('moodle/site:accessallgroups', $context)) {
2224         $output .= '</a>';
2225     }
2227     if ($return) {
2228         return $output;
2229     } else {
2230         echo $output;
2231     }
2235 /**
2236  * Display a recent activity note
2237  *
2238  * @uses CONTEXT_SYSTEM
2239  * @staticvar string $strftimerecent
2240  * @param object A time object
2241  * @param object A user object
2242  * @param string $text Text for display for the note
2243  * @param string $link The link to wrap around the text
2244  * @param bool $return If set to true the HTML is returned rather than echo'd
2245  * @param string $viewfullnames
2246  */
2247 function print_recent_activity_note($time, $user, $text, $link, $return=false, $viewfullnames=null) {
2248     static $strftimerecent = null;
2249     $output = '';
2251     if (is_null($viewfullnames)) {
2252         $context = get_context_instance(CONTEXT_SYSTEM);
2253         $viewfullnames = has_capability('moodle/site:viewfullnames', $context);
2254     }
2256     if (is_null($strftimerecent)) {
2257         $strftimerecent = get_string('strftimerecent');
2258     }
2260     $output .= '<div class="head">';
2261     $output .= '<div class="date">'.userdate($time, $strftimerecent).'</div>';
2262     $output .= '<div class="name">'.fullname($user, $viewfullnames).'</div>';
2263     $output .= '</div>';
2264     $output .= '<div class="info"><a href="'.$link.'">'.format_string($text,true).'</a></div>';
2266     if ($return) {
2267         return $output;
2268     } else {
2269         echo $output;
2270     }
2273 /**
2274  * Returns a popup menu with course activity modules
2275  *
2276  * Given a course
2277  * This function returns a small popup menu with all the
2278  * course activity modules in it, as a navigation menu
2279  * outputs a simple list structure in XHTML
2280  * The data is taken from the serialised array stored in
2281  * the course record
2282  *
2283  * @todo Finish documenting this function
2284  *
2285  * @global object
2286  * @uses CONTEXT_COURSE
2287  * @param course $course A {@link $COURSE} object.
2288  * @param string $sections
2289  * @param string $modinfo
2290  * @param string $strsection
2291  * @param string $strjumpto
2292  * @param int $width
2293  * @param string $cmid
2294  * @return string The HTML block
2295  */
2296 function navmenulist($course, $sections, $modinfo, $strsection, $strjumpto, $width=50, $cmid=0) {
2298     global $CFG;
2300     $section = -1;
2301     $url = '';
2302     $menu = array();
2303     $doneheading = false;
2305     $coursecontext = get_context_instance(CONTEXT_COURSE, $course->id);
2307     $menu[] = '<ul class="navmenulist"><li class="jumpto section"><span>'.$strjumpto.'</span><ul>';
2308     foreach ($modinfo->cms as $mod) {
2309         if ($mod->modname == 'label') {
2310             continue;
2311         }
2313         if ($mod->sectionnum > $course->numsections) {   /// Don't show excess hidden sections
2314             break;
2315         }
2317         if (!$mod->uservisible) { // do not icnlude empty sections at all
2318             continue;
2319         }
2321         if ($mod->sectionnum >= 0 and $section != $mod->sectionnum) {
2322             $thissection = $sections[$mod->sectionnum];
2324             if ($thissection->visible or !$course->hiddensections or
2325                       has_capability('moodle/course:viewhiddensections', $coursecontext)) {
2326                 $thissection->summary = strip_tags(format_string($thissection->summary,true));
2327                 if (!$doneheading) {
2328                     $menu[] = '</ul></li>';
2329                 }
2330                 if ($course->format == 'weeks' or empty($thissection->summary)) {
2331                     $item = $strsection ." ". $mod->sectionnum;
2332                 } else {
2333                     if (strlen($thissection->summary) < ($width-3)) {
2334                         $item = $thissection->summary;
2335                     } else {
2336                         $item = substr($thissection->summary, 0, $width).'...';
2337                     }
2338                 }
2339                 $menu[] = '<li class="section"><span>'.$item.'</span>';
2340                 $menu[] = '<ul>';
2341                 $doneheading = true;
2343                 $section = $mod->sectionnum;
2344             } else {
2345                 // no activities from this hidden section shown
2346                 continue;
2347             }
2348         }
2350         $url = $mod->modname .'/view.php?id='. $mod->id;
2351         $mod->name = strip_tags(format_string($mod->name ,true));
2352         if (strlen($mod->name) > ($width+5)) {
2353             $mod->name = substr($mod->name, 0, $width).'...';
2354         }
2355         if (!$mod->visible) {
2356             $mod->name = '('.$mod->name.')';
2357         }
2358         $class = 'activity '.$mod->modname;
2359         $class .= ($cmid == $mod->id) ? ' selected' : '';
2360         $menu[] = '<li class="'.$class.'">'.
2361                   '<img src="'.$OUTPUT->pix_url('icon', $mod->modname) . '" alt="" />'.
2362                   '<a href="'.$CFG->wwwroot.'/mod/'.$url.'">'.$mod->name.'</a></li>';
2363     }
2365     if ($doneheading) {
2366         $menu[] = '</ul></li>';
2367     }
2368     $menu[] = '</ul></li></ul>';
2370     return implode("\n", $menu);
2373 /**
2374  * Prints a grade menu (as part of an existing form) with help
2375  * Showing all possible numerical grades and scales
2376  *
2377  * @todo Finish documenting this function
2378  * @todo Deprecate: this is only used in a few contrib modules
2379  *
2380  * @global object
2381  * @param int $courseid The course ID
2382  * @param string $name
2383  * @param string $current
2384  * @param boolean $includenograde Include those with no grades
2385  * @param boolean $return If set to true returns rather than echo's
2386  * @return string|bool Depending on value of $return
2387  */
2388 function print_grade_menu($courseid, $name, $current, $includenograde=true, $return=false) {
2390     global $CFG, $OUTPUT;
2392     $output = '';
2393     $strscale = get_string('scale');
2394     $strscales = get_string('scales');
2396     $scales = get_scales_menu($courseid);
2397     foreach ($scales as $i => $scalename) {
2398         $grades[-$i] = $strscale .': '. $scalename;
2399     }
2400     if ($includenograde) {
2401         $grades[0] = get_string('nograde');
2402     }
2403     for ($i=100; $i>=1; $i--) {
2404         $grades[$i] = $i;
2405     }
2406     $output .= html_writer::select($grades, $name, $current, false);
2408     $linkobject = '<span class="helplink"><img class="iconhelp" alt="'.$strscales.'" src="'.$OUTPUT->pix_url('help') . '" /></span>';
2409     $link = new moodle_url('/course/scales.php', array('id'=>$courseid, 'list'=>1));
2410     $action = new popup_action('click', $link->url, 'ratingscales', array('height' => 400, 'width' => 500));
2411     $output .= $OUTPUT->action_link($link, $linkobject, $action, array('title'=>$strscales));
2413     if ($return) {
2414         return $output;
2415     } else {
2416         echo $output;
2417     }
2420 /**
2421  * Print an error to STDOUT and exit with a non-zero code. For commandline scripts.
2422  * Default errorcode is 1.
2423  *
2424  * Very useful for perl-like error-handling:
2425  *
2426  * do_somethting() or mdie("Something went wrong");
2427  *
2428  * @param string  $msg       Error message
2429  * @param integer $errorcode Error code to emit
2430  */
2431 function mdie($msg='', $errorcode=1) {
2432     trigger_error($msg);
2433     exit($errorcode);
2436 /**
2437  * Returns html code to be used as help icon of modgrade form element
2438  *
2439  * Is used as a callback in modgrade setHelpButton()
2440  *
2441  * @param int $courseid id of the course the scales should be shown from
2442  * @return string to be echoed
2443  */
2444 function modgradehelpbutton($courseid){
2445     global $CFG, $OUTPUT;
2447     $url = new moodle_url('/course/scales.php', array('id' => $courseid, 'list' => true));
2448     $text = '<span class="helplink"><img alt="' . get_string('scales') . '" class="iconhelp" src="' . $OUTPUT->pix_url('help') . '" /></span>';
2449     $action = new popup_action('click', $link->url, 'ratingscales', array('height' => 400, 'width' => 500));
2451     return $OUTPUT->action_link($url, $text, $action, array('title'=>get_string('newwindow')));
2454 /**
2455  * Print a message and exit.
2456  *
2457  * @param string $message The message to print in the notice
2458  * @param string $link The link to use for the continue button
2459  * @param object $course A course object
2460  * @return void This function simply exits
2461  */
2462 function notice ($message, $link='', $course=NULL) {
2463     global $CFG, $SITE, $COURSE, $PAGE, $OUTPUT;
2465     $message = clean_text($message);   // In case nasties are in here
2467     if (CLI_SCRIPT) {
2468         echo("!!$message!!\n");
2469         exit(1); // no success
2470     }
2472     if (!$PAGE->headerprinted) {
2473         //header not yet printed
2474         $PAGE->set_title(get_string('notice'));
2475         echo $OUTPUT->header();
2476     } else {
2477         echo $OUTPUT->container_end_all(false);
2478     }
2480     echo $OUTPUT->box($message, 'generalbox', 'notice');
2481     echo $OUTPUT->continue_button($link);
2483     echo $OUTPUT->footer();
2484     exit(1); // general error code
2487 /**
2488  * Redirects the user to another page, after printing a notice
2489  *
2490  * This function calls the OUTPUT redirect method, echo's the output
2491  * and then dies to ensure nothing else happens.
2492  *
2493  * <strong>Good practice:</strong> You should call this method before starting page
2494  * output by using any of the OUTPUT methods.
2495  *
2496  * @param moodle_url $url A moodle_url to redirect to. Strings are not to be trusted!
2497  * @param string $message The message to display to the user
2498  * @param int $delay The delay before redirecting
2499  * @return void
2500  */
2501 function redirect($url, $message='', $delay=-1) {
2502     global $OUTPUT, $PAGE, $SESSION, $CFG;
2504     if (CLI_SCRIPT or AJAX_SCRIPT) {
2505         // this is wrong - developers should not use redirect in these scripts,
2506         // but it should not be very likely
2507         throw new moodle_exception('redirecterrordetected', 'error');
2508     }
2510     if ($url instanceof moodle_url) {
2511         $url = $url->out(false);
2512     }
2514     if (!empty($CFG->usesid) && !isset($_COOKIE[session_name()])) {
2515        $url = $SESSION->sid_process_url($url);
2516     }
2518     if (function_exists('error_get_last')) {
2519         $lasterror = error_get_last();
2520     }
2521     $debugdisableredirect = defined('DEBUGGING_PRINTED') ||
2522             (!empty($CFG->debugdisplay) && !empty($lasterror) && ($lasterror['type'] & DEBUG_DEVELOPER));
2524     $usingmsg = false;
2525     if (!empty($message)) {
2526         if ($delay === -1 || !is_numeric($delay)) {
2527             $delay = 3;
2528         }
2529         $message = clean_text($message);
2530     } else {
2531         $message = get_string('pageshouldredirect');
2532         $delay = 0;
2533         // We are going to try to use a HTTP redirect, so we need a full URL.
2534         if (!preg_match('|^[a-z]+:|', $url)) {
2535             // Get host name http://www.wherever.com
2536             $hostpart = preg_replace('|^(.*?[^:/])/.*$|', '$1', $CFG->wwwroot);
2537             if (preg_match('|^/|', $url)) {
2538                 // URLs beginning with / are relative to web server root so we just add them in
2539                 $url = $hostpart.$url;
2540             } else {
2541                 // URLs not beginning with / are relative to path of current script, so add that on.
2542                 $url = $hostpart.preg_replace('|\?.*$|','',me()).'/../'.$url;
2543             }
2544             // Replace all ..s
2545             while (true) {
2546                 $newurl = preg_replace('|/(?!\.\.)[^/]*/\.\./|', '/', $url);
2547                 if ($newurl == $url) {
2548                     break;
2549                 }
2550                 $url = $newurl;
2551             }
2552         }
2553     }
2555     if (defined('MDL_PERF') || (!empty($CFG->perfdebug) and $CFG->perfdebug > 7)) {
2556         if (defined('MDL_PERFTOLOG') && !function_exists('register_shutdown_function')) {
2557             $perf = get_performance_info();
2558             error_log("PERF: " . $perf['txt']);
2559         }
2560     }
2562     $encodedurl = preg_replace("/\&(?![a-zA-Z0-9#]{1,8};)/", "&amp;", $url);
2563     $encodedurl = preg_replace('/^.*href="([^"]*)".*$/', "\\1", clean_text('<a href="'.$encodedurl.'" />'));
2565     if ($delay == 0 && !$debugdisableredirect && !headers_sent()) {
2566         //302 might not work for POST requests, 303 is ignored by obsolete clients.
2567         @header($_SERVER['SERVER_PROTOCOL'] . ' 303 See Other');
2568         @header('Location: '.$url);
2569         echo bootstrap_renderer::plain_redirect_message($encodedurl);
2570         exit;
2571     }
2573     // Include a redirect message, even with a HTTP redirect, because that is recommended practice.
2574     $PAGE->set_pagelayout('embedded');  // No header and footer needed
2575     $CFG->docroot = false; // to prevent the link to moodle docs from being displayed on redirect page.
2576     echo $OUTPUT->redirect_message($encodedurl, $message, $delay, $debugdisableredirect);
2577     exit;
2580 /**
2581  * Given an email address, this function will return an obfuscated version of it
2582  *
2583  * @param string $email The email address to obfuscate
2584  * @return string The obfuscated email address
2585  */
2586  function obfuscate_email($email) {
2588     $i = 0;
2589     $length = strlen($email);
2590     $obfuscated = '';
2591     while ($i < $length) {
2592         if (rand(0,2) && $email{$i}!='@') { //MDL-20619 some browsers have problems unobfuscating @
2593             $obfuscated.='%'.dechex(ord($email{$i}));
2594         } else {
2595             $obfuscated.=$email{$i};
2596         }
2597         $i++;
2598     }
2599     return $obfuscated;
2602 /**
2603  * This function takes some text and replaces about half of the characters
2604  * with HTML entity equivalents.   Return string is obviously longer.
2605  *
2606  * @param string $plaintext The text to be obfuscated
2607  * @return string The obfuscated text
2608  */
2609 function obfuscate_text($plaintext) {
2611     $i=0;
2612     $length = strlen($plaintext);
2613     $obfuscated='';
2614     $prev_obfuscated = false;
2615     while ($i < $length) {
2616         $c = ord($plaintext{$i});
2617         $numerical = ($c >= ord('0')) && ($c <= ord('9'));
2618         if ($prev_obfuscated and $numerical ) {
2619             $obfuscated.='&#'.ord($plaintext{$i}).';';
2620         } else if (rand(0,2)) {
2621             $obfuscated.='&#'.ord($plaintext{$i}).';';
2622             $prev_obfuscated = true;
2623         } else {
2624             $obfuscated.=$plaintext{$i};
2625             $prev_obfuscated = false;
2626         }
2627       $i++;
2628     }
2629     return $obfuscated;
2632 /**
2633  * This function uses the {@link obfuscate_email()} and {@link obfuscate_text()}
2634  * to generate a fully obfuscated email link, ready to use.
2635  *
2636  * @param string $email The email address to display
2637  * @param string $label The text to displayed as hyperlink to $email
2638  * @param boolean $dimmed If true then use css class 'dimmed' for hyperlink
2639  * @return string The obfuscated mailto link
2640  */
2641 function obfuscate_mailto($email, $label='', $dimmed=false) {
2643     if (empty($label)) {
2644         $label = $email;
2645     }
2646     if ($dimmed) {
2647         $title = get_string('emaildisable');
2648         $dimmed = ' class="dimmed"';
2649     } else {
2650         $title = '';
2651         $dimmed = '';
2652     }
2653     return sprintf("<a href=\"%s:%s\" $dimmed title=\"$title\">%s</a>",
2654                     obfuscate_text('mailto'), obfuscate_email($email),
2655                     obfuscate_text($label));
2658 /**
2659  * This function is used to rebuild the <nolink> tag because some formats (PLAIN and WIKI)
2660  * will transform it to html entities
2661  *
2662  * @param string $text Text to search for nolink tag in
2663  * @return string
2664  */
2665 function rebuildnolinktag($text) {
2667     $text = preg_replace('/&lt;(\/*nolink)&gt;/i','<$1>',$text);
2669     return $text;
2672 /**
2673  * Prints a maintenance message from $CFG->maintenance_message or default if empty
2674  * @return void
2675  */
2676 function print_maintenance_message() {
2677     global $CFG, $SITE, $PAGE, $OUTPUT;
2679     $PAGE->set_pagetype('maintenance-message');
2680     $PAGE->set_pagelayout('maintenance');
2681     $PAGE->set_title(strip_tags($SITE->fullname));
2682     $PAGE->set_heading($SITE->fullname);
2683     echo $OUTPUT->header();
2684     echo $OUTPUT->heading(get_string('sitemaintenance', 'admin'));
2685     if (isset($CFG->maintenance_message) and !html_is_blank($CFG->maintenance_message)) {
2686         echo $OUTPUT->box_start('maintenance_message generalbox boxwidthwide boxaligncenter');
2687         echo $CFG->maintenance_message;
2688         echo $OUTPUT->box_end();
2689     }
2690     echo $OUTPUT->footer();
2691     die;
2694 /**
2695  * Adjust the list of allowed tags based on $CFG->allowobjectembed and user roles (admin)
2696  *
2697  * @global object
2698  * @global string
2699  * @return void
2700  */
2701 function adjust_allowed_tags() {
2703     global $CFG, $ALLOWED_TAGS;
2705     if (!empty($CFG->allowobjectembed)) {
2706         $ALLOWED_TAGS .= '<embed><object>';
2707     }
2710 /**
2711  * A class for tabs, Some code to print tabs
2712  *
2713  * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2714  * @package moodlecore
2715  */
2716 class tabobject {
2717     /**
2718      * @var string
2719      */
2720     var $id;
2721     var $link;
2722     var $text;
2723     /**
2724      * @var bool
2725      */
2726     var $linkedwhenselected;
2728     /**
2729      * A constructor just because I like constructors
2730      *
2731      * @param string $id
2732      * @param string $link
2733      * @param string $text
2734      * @param string $title
2735      * @param bool $linkedwhenselected
2736      */
2737     function tabobject ($id, $link='', $text='', $title='', $linkedwhenselected=false) {
2738         $this->id   = $id;
2739         $this->link = $link;
2740         $this->text = $text;
2741         $this->title = $title ? $title : $text;
2742         $this->linkedwhenselected = $linkedwhenselected;
2743     }
2748 /**
2749  * Returns a string containing a nested list, suitable for formatting into tabs with CSS.
2750  *
2751  * @global object
2752  * @param array $tabrows An array of rows where each row is an array of tab objects
2753  * @param string $selected  The id of the selected tab (whatever row it's on)
2754  * @param array  $inactive  An array of ids of inactive tabs that are not selectable.
2755  * @param array  $activated An array of ids of other tabs that are currently activated
2756  * @param bool $return If true output is returned rather then echo'd
2757  **/
2758 function print_tabs($tabrows, $selected=NULL, $inactive=NULL, $activated=NULL, $return=false) {
2759     global $CFG;
2761 /// $inactive must be an array
2762     if (!is_array($inactive)) {
2763         $inactive = array();
2764     }
2766 /// $activated must be an array
2767     if (!is_array($activated)) {
2768         $activated = array();
2769     }
2771 /// Convert the tab rows into a tree that's easier to process
2772     if (!$tree = convert_tabrows_to_tree($tabrows, $selected, $inactive, $activated)) {
2773         return false;
2774     }
2776 /// Print out the current tree of tabs (this function is recursive)
2778     $output = convert_tree_to_html($tree);
2780     $output = "\n\n".'<div class="tabtree">'.$output.'</div><div class="clearer"> </div>'."\n\n";
2782 /// We're done!
2784     if ($return) {
2785         return $output;
2786     }
2787     echo $output;
2790 /**
2791  * Converts a nested array tree into HTML ul:li [recursive]
2792  *
2793  * @param array $tree A tree array to convert
2794  * @param int $row Used in identifying the iteration level and in ul classes
2795  * @return string HTML structure
2796  */
2797 function convert_tree_to_html($tree, $row=0) {
2799     $str = "\n".'<ul class="tabrow'.$row.'">'."\n";
2801     $first = true;
2802     $count = count($tree);
2804     foreach ($tree as $tab) {
2805         $count--;   // countdown to zero
2807         $liclass = '';
2809         if ($first && ($count == 0)) {   // Just one in the row
2810             $liclass = 'first last';
2811             $first = false;
2812         } else if ($first) {
2813             $liclass = 'first';
2814             $first = false;
2815         } else if ($count == 0) {
2816             $liclass = 'last';
2817         }
2819         if ((empty($tab->subtree)) && (!empty($tab->selected))) {
2820             $liclass .= (empty($liclass)) ? 'onerow' : ' onerow';
2821         }
2823         if ($tab->inactive || $tab->active || $tab->selected) {
2824             if ($tab->selected) {
2825                 $liclass .= (empty($liclass)) ? 'here selected' : ' here selected';
2826             } else if ($tab->active) {
2827                 $liclass .= (empty($liclass)) ? 'here active' : ' here active';
2828             }
2829         }
2831         $str .= (!empty($liclass)) ? '<li class="'.$liclass.'">' : '<li>';
2833         if ($tab->inactive || $tab->active || ($tab->selected && !$tab->linkedwhenselected)) {
2834             // The a tag is used for styling
2835             $str .= '<a class="nolink"><span>'.$tab->text.'</span></a>';
2836         } else {
2837             $str .= '<a href="'.$tab->link.'" title="'.$tab->title.'"><span>'.$tab->text.'</span></a>';
2838         }
2840         if (!empty($tab->subtree)) {
2841             $str .= convert_tree_to_html($tab->subtree, $row+1);
2842         } else if ($tab->selected) {
2843             $str .= '<div class="tabrow'.($row+1).' empty">&nbsp;</div>'."\n";
2844         }
2846         $str .= ' </li>'."\n";
2847     }
2848     $str .= '</ul>'."\n";
2850     return $str;
2853 /**
2854  * Convert nested tabrows to a nested array
2855  *
2856  * @param array $tabrows A [nested] array of tab row objects
2857  * @param string $selected The tabrow to select (by id)
2858  * @param array $inactive An array of tabrow id's to make inactive
2859  * @param array $activated An array of tabrow id's to make active
2860  * @return array The nested array
2861  */
2862 function convert_tabrows_to_tree($tabrows, $selected, $inactive, $activated) {
2864 /// Work backwards through the rows (bottom to top) collecting the tree as we go.
2866     $tabrows = array_reverse($tabrows);
2868     $subtree = array();
2870     foreach ($tabrows as $row) {
2871         $tree = array();
2873         foreach ($row as $tab) {
2874             $tab->inactive = in_array((string)$tab->id, $inactive);
2875             $tab->active = in_array((string)$tab->id, $activated);
2876             $tab->selected = (string)$tab->id == $selected;
2878             if ($tab->active || $tab->selected) {
2879                 if ($subtree) {
2880                     $tab->subtree = $subtree;
2881                 }
2882             }
2883             $tree[] = $tab;
2884         }
2885         $subtree = $tree;
2886     }
2888     return $subtree;
2891 /**
2892  * Returns the Moodle Docs URL in the users language
2893  *
2894  * @global object
2895  * @param string $path the end of the URL.
2896  * @return string The MoodleDocs URL in the user's language. for example {@link http://docs.moodle.org/en/ http://docs.moodle.org/en/$path}
2897  */
2898 function get_docs_url($path) {
2899     global $CFG;
2900     return $CFG->docroot . '/' . current_language() . '/' . $path;
2904 /**
2905  * Standard Debugging Function
2906  *
2907  * Returns true if the current site debugging settings are equal or above specified level.
2908  * If passed a parameter it will emit a debugging notice similar to trigger_error(). The
2909  * routing of notices is controlled by $CFG->debugdisplay
2910  * eg use like this:
2911  *
2912  * 1)  debugging('a normal debug notice');
2913  * 2)  debugging('something really picky', DEBUG_ALL);
2914  * 3)  debugging('annoying debug message only for developers', DEBUG_DEVELOPER);
2915  * 4)  if (debugging()) { perform extra debugging operations (do not use print or echo) }
2916  *
2917  * In code blocks controlled by debugging() (such as example 4)
2918  * any output should be routed via debugging() itself, or the lower-level
2919  * trigger_error() or error_log(). Using echo or print will break XHTML
2920  * JS and HTTP headers.
2921  *
2922  * It is also possible to define NO_DEBUG_DISPLAY which redirects the message to error_log.
2923  *
2924  * @uses DEBUG_NORMAL
2925  * @param string $message a message to print
2926  * @param int $level the level at which this debugging statement should show
2927  * @param array $backtrace use different backtrace
2928  * @return bool
2929  */
2930 function debugging($message = '', $level = DEBUG_NORMAL, $backtrace = null) {
2931     global $CFG, $UNITTEST;
2933     if (empty($CFG->debug) || $CFG->debug < $level) {
2934         return false;
2935     }
2937     if (!isset($CFG->debugdisplay)) {
2938         $CFG->debugdisplay = ini_get_bool('display_errors');
2939     }
2941     if ($message) {
2942         if (!$backtrace) {
2943             $backtrace = debug_backtrace();
2944         }
2945         $from = format_backtrace($backtrace, CLI_SCRIPT);
2946         if (!empty($UNITTEST->running)) {
2947             // When the unit tests are running, any call to trigger_error
2948             // is intercepted by the test framework and reported as an exception.
2949             // Therefore, we cannot use trigger_error during unit tests.
2950             // At the same time I do not think we should just discard those messages,
2951             // so displaying them on-screen seems like the only option. (MDL-20398)
2952             echo '<div class="notifytiny">' . $message . $from . '</div>';
2954         } else if (NO_DEBUG_DISPLAY) {
2955             // script does not want any errors or debugging in output,
2956             // we send the info to error log instead
2957             error_log('Debugging: ' . $message . $from);
2959         } else if ($CFG->debugdisplay) {
2960             if (!defined('DEBUGGING_PRINTED')) {
2961                 define('DEBUGGING_PRINTED', 1); // indicates we have printed something
2962             }
2963             echo '<div class="notifytiny">' . $message . $from . '</div>';
2965         } else {
2966             trigger_error($message . $from, E_USER_NOTICE);
2967         }
2968     }
2969     return true;
2972 /**
2973 * Outputs a HTML comment to the browser. This is used for those hard-to-debug
2974 * pages that use bits from many different files in very confusing ways (e.g. blocks).
2976 * <code>print_location_comment(__FILE__, __LINE__);</code>
2978 * @param string $file
2979 * @param integer $line
2980 * @param boolean $return Whether to return or print the comment
2981 * @return string|void Void unless true given as third parameter
2982 */
2983 function print_location_comment($file, $line, $return = false)
2985     if ($return) {
2986         return "<!-- $file at line $line -->\n";
2987     } else {
2988         echo "<!-- $file at line $line -->\n";
2989     }
2993 /**
2994  * @return boolean true if the current language is right-to-left (Hebrew, Arabic etc)
2995  */
2996 function right_to_left() {
2997     return (get_string('thisdirection', 'langconfig') === 'rtl');
3001 /**
3002  * Returns swapped left<=>right if in RTL environment.
3003  * part of RTL support
3004  *
3005  * @param string $align align to check
3006  * @return string
3007  */
3008 function fix_align_rtl($align) {
3009     if (!right_to_left()) {
3010         return $align;
3011     }
3012     if ($align=='left')  { return 'right'; }
3013     if ($align=='right') { return 'left'; }
3014     return $align;
3018 /**
3019  * Returns true if the page is displayed in a popup window.
3020  * Gets the information from the URL parameter inpopup.
3021  *
3022  * @todo Use a central function to create the popup calls all over Moodle and
3023  * In the moment only works with resources and probably questions.
3024  *
3025  * @return boolean
3026  */
3027 function is_in_popup() {
3028     $inpopup = optional_param('inpopup', '', PARAM_BOOL);
3030     return ($inpopup);
3033 /**
3034  * To use this class.
3035  * - construct
3036  * - call create (or use the 3rd param to the constructor)
3037  * - call update or update_full repeatedly
3038  *
3039  * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3040  * @package moodlecore
3041  */
3042 class progress_bar {
3043     /** @var string html id */
3044     private $html_id;
3045     /** @var int */
3046     private $percent;
3047     /** @var int */
3048     private $width;
3049     /** @var int */
3050     private $lastcall;
3051     /** @var int */
3052     private $time_start;
3053     private $minimum_time = 2; //min time between updates.
3054     /**
3055      * Constructor
3056      *
3057      * @param string $html_id
3058      * @param int $width
3059      * @param bool $autostart Default to false
3060      */
3061     public function __construct($html_id = '', $width = 500, $autostart = false){
3062         if (!empty($html_id)) {
3063             $this->html_id  = $html_id;
3064         } else {
3065             $this->html_id  = uniqid();
3066         }
3067         $this->width = $width;
3068         $this->restart();
3069         if($autostart){
3070             $this->create();
3071         }
3072     }
3073     /**
3074       * Create a new progress bar, this function will output html.
3075       *
3076       * @return void Echo's output
3077       */
3078     public function create(){
3079             flush();
3080             $this->lastcall->pt = 0;
3081             $this->lastcall->time = microtime(true);
3082             if (CLI_SCRIPT) {
3083                 return; // temporary solution for cli scripts
3084             }
3085             $htmlcode = <<<EOT
3086             <div style="text-align:center;width:{$this->width}px;clear:both;padding:0;margin:0 auto;">
3087                 <h2 id="status_{$this->html_id}" style="text-align: center;margin:0 auto"></h2>
3088                 <p id="time_{$this->html_id}"></p>
3089                 <div id="bar_{$this->html_id}" style="border-style:solid;border-width:1px;width:500px;height:50px;">
3090                     <div id="progress_{$this->html_id}"
3091                     style="text-align:center;background:#FFCC66;width:4px;border:1px
3092                     solid gray;height:38px; padding-top:10px;">&nbsp;<span id="pt_{$this->html_id}"></span>
3093                     </div>
3094                 </div>
3095             </div>
3096 EOT;
3097             echo $htmlcode;
3098             flush();
3099     }
3100     /**
3101      * Update the progress bar
3102      *
3103      * @param int $percent from 1-100
3104      * @param string $msg
3105      * @param mixed $es
3106      * @return void Echo's output
3107      */
3108     private function _update($percent, $msg, $es){
3109         global $PAGE;
3110         if(empty($this->time_start)){
3111             $this->time_start = microtime(true);
3112         }
3113         $this->percent = $percent;
3114         $this->lastcall->time = microtime(true);
3115         $this->lastcall->pt   = $percent;
3116         $w = $this->percent * $this->width;
3117         if (CLI_SCRIPT) {
3118             return; // temporary solution for cli scripts
3119         }
3120         if ($es === null){
3121             $es = "Infinity";
3122         }
3123         echo html_writer::script(js_writer::function_call('update_progress_bar', Array($this->html_id, $w, $this->percent, $msg, $es)));
3124         flush();
3125     }
3126     /**
3127       * estimate time
3128       *
3129       * @param int $curtime the time call this function
3130       * @param int $percent from 1-100
3131       * @return mixed Null, or int
3132       */
3133     private function estimate($curtime, $pt){
3134         $consume = $curtime - $this->time_start;
3135         $one = $curtime - $this->lastcall->time;
3136         $this->percent = $pt;
3137         $percent = $pt - $this->lastcall->pt;
3138         if ($percent != 0) {
3139             $left = ($one / $percent) - $consume;
3140         } else {
3141             return null;
3142         }
3143         if($left < 0) {
3144             return 0;
3145         } else {
3146             return $left;
3147         }
3148     }
3149     /**
3150       * Update progress bar according percent
3151       *
3152       * @param int $percent from 1-100
3153       * @param string $msg the message needed to be shown
3154       */
3155     public function update_full($percent, $msg){
3156         $percent = max(min($percent, 100), 0);
3157         if ($percent != 100 && ($this->lastcall->time + $this->minimum_time) > microtime(true)){
3158             return;
3159         }
3160         $this->_update($percent/100, $msg);
3161     }
3162     /**
3163       * Update progress bar according the number of tasks
3164       *
3165       * @param int $cur current task number
3166       * @param int $total total task number
3167       * @param string $msg message
3168       */
3169     public function update($cur, $total, $msg){
3170         $cur = max($cur, 0);
3171         if ($cur >= $total){
3172             $percent = 1;
3173         } else {
3174             $percent = $cur / $total;
3175         }
3176         /**
3177         if ($percent != 1 && ($this->lastcall->time + $this->minimum_time) > microtime(true)){
3178             return;
3179         }
3180         */
3181         $es = $this->estimate(microtime(true), $percent);
3182         $this->_update($percent, $msg, $es);
3183     }
3184     /**
3185      * Restart the progress bar.
3186      */
3187     public function restart(){
3188         $this->percent  = 0;
3189         $this->lastcall = new stdClass;
3190         $this->lastcall->pt = 0;
3191         $this->lastcall->time = microtime(true);
3192         $this->time_start  = 0;
3193     }
3196 /**
3197  * Use this class from long operations where you want to output occasional information about
3198  * what is going on, but don't know if, or in what format, the output should be.
3199  *
3200  * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3201  * @package moodlecore
3202  */
3203 abstract class progress_trace {
3204     /**
3205      * Ouput an progress message in whatever format.
3206      * @param string $message the message to output.
3207      * @param integer $depth indent depth for this message.
3208      */
3209     abstract public function output($message, $depth = 0);
3211     /**
3212      * Called when the processing is finished.
3213      */
3214     public function finished() {
3215     }
3218 /**
3219  * This subclass of progress_trace does not ouput anything.
3220  *
3221  * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3222  * @package moodlecore
3223  */
3224 class null_progress_trace extends progress_trace {
3225     /**
3226      * Does Nothing
3227      *
3228      * @param string $message
3229      * @param int $depth
3230      * @return void Does Nothing
3231      */
3232     public function output($message, $depth = 0) {
3233     }
3236 /**
3237  * This subclass of progress_trace outputs to plain text.
3238  *
3239  * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3240  * @package moodlecore
3241  */
3242 class text_progress_trace extends progress_trace {
3243     /**
3244      * Output the trace message
3245      *
3246      * @param string $message
3247      * @param int $depth
3248      * @return void Output is echo'd
3249      */
3250     public function output($message, $depth = 0) {
3251         echo str_repeat('  ', $depth), $message, "\n";
3252         flush();
3253     }
3256 /**
3257  * This subclass of progress_trace outputs as HTML.
3258  *
3259  * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3260  * @package moodlecore
3261  */
3262 class html_progress_trace extends progress_trace {
3263     /**
3264      * Output the trace message
3265      *
3266      * @param string $message
3267      * @param int $depth
3268      * @return void Output is echo'd
3269      */
3270     public function output($message, $depth = 0) {
3271         echo '<p>', str_repeat('&#160;&#160;', $depth), htmlspecialchars($message), "</p>\n";
3272         flush();
3273     }
3276 /**
3277  * HTML List Progress Tree
3278  *
3279  * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3280  * @package moodlecore
3281  */
3282 class html_list_progress_trace extends progress_trace {
3283     /** @var int */
3284     protected $currentdepth = -1;
3286     /**
3287      * Echo out the list
3288      *
3289      * @param string $message The message to display
3290      * @param int $depth
3291      * @return void Output is echoed
3292      */
3293     public function output($message, $depth = 0) {
3294         $samedepth = true;
3295         while ($this->currentdepth > $depth) {
3296             echo "</li>\n</ul>\n";
3297             $this->currentdepth -= 1;
3298             if ($this->currentdepth == $depth) {
3299                 echo '<li>';
3300             }
3301             $samedepth = false;
3302         }
3303         while ($this->currentdepth < $depth) {
3304             echo "<ul>\n<li>";
3305             $this->currentdepth += 1;
3306             $samedepth = false;
3307         }
3308         if ($samedepth) {
3309             echo "</li>\n<li>";
3310         }
3311         echo htmlspecialchars($message);
3312         flush();
3313     }
3315     /**
3316      * Called when the processing is finished.
3317      */
3318     public function finished() {
3319         while ($this->currentdepth >= 0) {
3320             echo "</li>\n</ul>\n";
3321             $this->currentdepth -= 1;
3322         }
3323     }
3326 /**
3327  * Returns a localized sentence in the current language summarizing the current password policy
3328  *
3329  * @todo this should be handled by a function/method in the language pack library once we have a support for it
3330  * @uses $CFG
3331  * @return string
3332  */
3333 function print_password_policy() {
3334     global $CFG;
3336     $message = '';
3337     if (!empty($CFG->passwordpolicy)) {
3338         $messages = array();
3339         $messages[] = get_string('informminpasswordlength', 'auth', $CFG->minpasswordlength);
3340         if (!empty($CFG->minpassworddigits)) {
3341             $messages[] = get_string('informminpassworddigits', 'auth', $CFG->minpassworddigits);
3342         }
3343         if (!empty($CFG->minpasswordlower)) {
3344             $messages[] = get_string('informminpasswordlower', 'auth', $CFG->minpasswordlower);
3345         }
3346         if (!empty($CFG->minpasswordupper)) {
3347             $messages[] = get_string('informminpasswordupper', 'auth', $CFG->minpasswordupper);
3348         }
3349         if (!empty($CFG->minpasswordnonalphanum)) {
3350             $messages[] = get_string('informminpasswordnonalphanum', 'auth', $CFG->minpasswordnonalphanum);
3351         }
3353         $messages = join(', ', $messages); // this is ugly but we do not have anything better yet...
3354         $message = get_string('informpasswordpolicy', 'auth', $messages);
3355     }
3356     return $message;
3359 function create_ufo_inline($id, $args) {
3360     global $CFG;
3361     // must not use $PAGE, $THEME, $COURSE etc. because the result is cached!
3362     // unfortunately this ufo.js can not be cached properly because we do not have access to current $CFG either
3363     $jsoutput = html_writer::script('', $CFG->wwwroot.'/lib/ufo.js');
3364     $jsoutput .= html_writer::script(js_writer::function_call('M.util.create_UFO_object', array($id, $args)));
3365     return $jsoutput;