Commit | Line | Data |
---|---|---|
449611af | 1 | <?php |
2 | ||
b868d3d9 | 3 | // This file is part of Moodle - http://moodle.org/ |
4 | // | |
449611af | 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. | |
b868d3d9 | 14 | // |
449611af | 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/>. | |
f9903ed0 | 17 | |
7cf1c7bd | 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. | |
449611af | 27 | * |
78bfb562 PS |
28 | * @package core |
29 | * @subpackage lib | |
30 | * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com} | |
31 | * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later | |
7cf1c7bd | 32 | */ |
772e78be | 33 | |
78bfb562 PS |
34 | defined('MOODLE_INTERNAL') || die(); |
35 | ||
0095d5cd | 36 | /// Constants |
37 | ||
c1d57101 | 38 | /// Define text formatting types ... eventually we can add Wiki, BBcode etc |
7cf1c7bd | 39 | |
40 | /** | |
41 | * Does all sorts of transformations and filtering | |
42 | */ | |
b0ccd3fb | 43 | define('FORMAT_MOODLE', '0'); // Does all sorts of transformations and filtering |
7cf1c7bd | 44 | |
45 | /** | |
46 | * Plain HTML (with some tags stripped) | |
47 | */ | |
b0ccd3fb | 48 | define('FORMAT_HTML', '1'); // Plain HTML (with some tags stripped) |
7cf1c7bd | 49 | |
50 | /** | |
51 | * Plain text (even tags are printed in full) | |
52 | */ | |
b0ccd3fb | 53 | define('FORMAT_PLAIN', '2'); // Plain text (even tags are printed in full) |
7cf1c7bd | 54 | |
55 | /** | |
56 | * Wiki-formatted text | |
6a6495ff | 57 | * Deprecated: left here just to note that '3' is not used (at the moment) |
58 | * and to catch any latent wiki-like text (which generates an error) | |
7cf1c7bd | 59 | */ |
b0ccd3fb | 60 | define('FORMAT_WIKI', '3'); // Wiki-formatted text |
7cf1c7bd | 61 | |
62 | /** | |
63 | * Markdown-formatted text http://daringfireball.net/projects/markdown/ | |
64 | */ | |
b0ccd3fb | 65 | define('FORMAT_MARKDOWN', '4'); // Markdown-formatted text http://daringfireball.net/projects/markdown/ |
0095d5cd | 66 | |
7d8a3cb0 | 67 | /** |
68 | * TRUSTTEXT marker - if present in text, text cleaning should be bypassed | |
69 | */ | |
70 | define('TRUSTTEXT', '#####TRUSTTEXT#####'); | |
71 | ||
827b2f7a | 72 | /** |
73 | * A moodle_url comparison using this flag will return true if the base URLs match, params are ignored | |
74 | */ | |
75 | define('URL_MATCH_BASE', 0); | |
76 | /** | |
77 | * A moodle_url comparison using this flag will return true if the base URLs match and the params of url1 are part of url2 | |
78 | */ | |
79 | define('URL_MATCH_PARAMS', 1); | |
80 | /** | |
ea85e1ee | 81 | * A moodle_url comparison using this flag will return true if the two URLs are identical, except for the order of the params |
827b2f7a | 82 | */ |
83 | define('URL_MATCH_EXACT', 2); | |
7cf1c7bd | 84 | |
85 | /** | |
86 | * Allowed tags - string of html tags that can be tested against for safe html tags | |
87 | * @global string $ALLOWED_TAGS | |
449611af | 88 | * @name $ALLOWED_TAGS |
7cf1c7bd | 89 | */ |
5ea4af22 | 90 | global $ALLOWED_TAGS; |
39dda0fc | 91 | $ALLOWED_TAGS = |
cf34d0ea | 92 | '<p><br><b><i><u><font><table><tbody><thead><tfoot><span><div><tr><td><th><ol><ul><dl><li><dt><dd><h1><h2><h3><h4><h5><h6><hr><img><a><strong><emphasis><em><sup><sub><address><cite><blockquote><pre><strike><param><acronym><nolink><lang><tex><algebra><math><mi><mn><mo><mtext><mspace><ms><mrow><mfrac><msqrt><mroot><mstyle><merror><mpadded><mphantom><mfenced><msub><msup><msubsup><munder><mover><munderover><mmultiscripts><mtable><mtr><mtd><maligngroup><malignmark><maction><cn><ci><apply><reln><fn><interval><inverse><sep><condition><declare><lambda><compose><ident><quotient><exp><factorial><divide><max><min><minus><plus><power><rem><times><root><gcd><and><or><xor><not><implies><forall><exists><abs><conjugate><eq><neq><gt><lt><geq><leq><ln><log><int><diff><partialdiff><lowlimit><uplimit><bvar><degree><set><list><union><intersect><in><notin><subset><prsubset><notsubset><notprsubset><setdiff><sum><product><limit><tendsto><mean><sdev><variance><median><mode><moment><vector><matrix><matrixrow><determinant><transpose><selector><annotation><semantics><annotation-xml><tt><code>'; |
d046ae55 | 93 | |
037dcbb6 | 94 | /** |
95 | * Allowed protocols - array of protocols that are safe to use in links and so on | |
96 | * @global string $ALLOWED_PROTOCOLS | |
449611af | 97 | * @name $ALLOWED_PROTOCOLS |
037dcbb6 | 98 | */ |
f941df22 | 99 | $ALLOWED_PROTOCOLS = array('http', 'https', 'ftp', 'news', 'mailto', 'rtsp', 'teamspeak', 'gopher', 'mms', |
f697a421 | 100 | 'color', 'callto', 'cursor', 'text-align', 'font-size', 'font-weight', 'font-style', 'font-family', |
62097c91 | 101 | 'border', 'margin', 'padding', 'background', 'background-color', 'text-decoration'); // CSS as well to get through kses |
037dcbb6 | 102 | |
103 | ||
0095d5cd | 104 | /// Functions |
105 | ||
7cf1c7bd | 106 | /** |
107 | * Add quotes to HTML characters | |
108 | * | |
109 | * Returns $var with HTML characters (like "<", ">", etc.) properly quoted. | |
110 | * This function is very similar to {@link p()} | |
111 | * | |
449611af | 112 | * @todo Remove obsolete param $obsolete if not used anywhere |
113 | * | |
7cf1c7bd | 114 | * @param string $var the string potentially containing HTML characters |
b4cf9371 | 115 | * @param boolean $obsolete no longer used. |
7cf1c7bd | 116 | * @return string |
117 | */ | |
b4cf9371 | 118 | function s($var, $obsolete = false) { |
d4a42ff4 | 119 | |
c676fe67 | 120 | if ($var === '0' or $var === false or $var === 0) { |
63e554d0 | 121 | return '0'; |
3662bce5 | 122 | } |
d4a42ff4 | 123 | |
e728447d | 124 | return preg_replace("/&#(\d+|x[0-7a-fA-F]+);/i", "&#$1;", htmlspecialchars($var, ENT_QUOTES, 'UTF-8', true)); |
f9903ed0 | 125 | } |
126 | ||
7cf1c7bd | 127 | /** |
128 | * Add quotes to HTML characters | |
129 | * | |
d48b00b4 | 130 | * Prints $var with HTML characters (like "<", ">", etc.) properly quoted. |
449611af | 131 | * This function simply calls {@link s()} |
132 | * @see s() | |
133 | * | |
134 | * @todo Remove obsolete param $obsolete if not used anywhere | |
7cf1c7bd | 135 | * |
136 | * @param string $var the string potentially containing HTML characters | |
b4cf9371 | 137 | * @param boolean $obsolete no longer used. |
7cf1c7bd | 138 | * @return string |
139 | */ | |
b4cf9371 | 140 | function p($var, $obsolete = false) { |
141 | echo s($var, $obsolete); | |
f9903ed0 | 142 | } |
143 | ||
0d1cd0ea | 144 | /** |
145 | * Does proper javascript quoting. | |
449611af | 146 | * |
5ce73257 | 147 | * Do not use addslashes anymore, because it does not work when magic_quotes_sybase is enabled. |
148 | * | |
449611af | 149 | * @param mixed $var String, Array, or Object to add slashes to |
0d1cd0ea | 150 | * @return mixed quoted result |
151 | */ | |
152 | function addslashes_js($var) { | |
153 | if (is_string($var)) { | |
154 | $var = str_replace('\\', '\\\\', $var); | |
155 | $var = str_replace(array('\'', '"', "\n", "\r", "\0"), array('\\\'', '\\"', '\\n', '\\r', '\\0'), $var); | |
4702be4e | 156 | $var = str_replace('</', '<\/', $var); // XHTML compliance |
0d1cd0ea | 157 | } else if (is_array($var)) { |
158 | $var = array_map('addslashes_js', $var); | |
159 | } else if (is_object($var)) { | |
160 | $a = get_object_vars($var); | |
161 | foreach ($a as $key=>$value) { | |
162 | $a[$key] = addslashes_js($value); | |
163 | } | |
164 | $var = (object)$a; | |
165 | } | |
166 | return $var; | |
167 | } | |
7cf1c7bd | 168 | |
7cf1c7bd | 169 | /** |
170 | * Remove query string from url | |
171 | * | |
172 | * Takes in a URL and returns it without the querystring portion | |
173 | * | |
174 | * @param string $url the url which may have a query string attached | |
449611af | 175 | * @return string The remaining URL |
7cf1c7bd | 176 | */ |
177 | function strip_querystring($url) { | |
f9903ed0 | 178 | |
b9b8ab69 | 179 | if ($commapos = strpos($url, '?')) { |
180 | return substr($url, 0, $commapos); | |
181 | } else { | |
182 | return $url; | |
183 | } | |
f9903ed0 | 184 | } |
185 | ||
7cf1c7bd | 186 | /** |
c8135a35 | 187 | * Returns the URL of the HTTP_REFERER, less the querystring portion if required |
449611af | 188 | * |
189 | * @uses $_SERVER | |
9ea04325 | 190 | * @param boolean $stripquery if true, also removes the query part of the url. |
fa9f6bf6 | 191 | * @return string The resulting referer or empty string |
7cf1c7bd | 192 | */ |
c8135a35 | 193 | function get_referer($stripquery=true) { |
d90ffc1f | 194 | if (isset($_SERVER['HTTP_REFERER'])) { |
c8135a35 | 195 | if ($stripquery) { |
196 | return strip_querystring($_SERVER['HTTP_REFERER']); | |
197 | } else { | |
198 | return $_SERVER['HTTP_REFERER']; | |
199 | } | |
d90ffc1f | 200 | } else { |
5ce73257 | 201 | return ''; |
d90ffc1f | 202 | } |
f9903ed0 | 203 | } |
204 | ||
c1d57101 | 205 | |
7cf1c7bd | 206 | /** |
207 | * Returns the name of the current script, WITH the querystring portion. | |
449611af | 208 | * |
209 | * This function is necessary because PHP_SELF and REQUEST_URI and SCRIPT_NAME | |
7cf1c7bd | 210 | * return different things depending on a lot of things like your OS, Web |
211 | * server, and the way PHP is compiled (ie. as a CGI, module, ISAPI, etc.) | |
d48b00b4 | 212 | * <b>NOTE:</b> This function returns false if the global variables needed are not set. |
213 | * | |
449611af | 214 | * @global string |
215 | * @return mixed String, or false if the global variables needed are not set | |
7cf1c7bd | 216 | */ |
b03fc392 | 217 | function me() { |
218 | global $ME; | |
219 | return $ME; | |
f9903ed0 | 220 | } |
221 | ||
7cf1c7bd | 222 | /** |
449611af | 223 | * Returns the name of the current script, WITH the full URL. |
224 | * | |
225 | * This function is necessary because PHP_SELF and REQUEST_URI and SCRIPT_NAME | |
226 | * return different things depending on a lot of things like your OS, Web | |
227 | * server, and the way PHP is compiled (ie. as a CGI, module, ISAPI, etc. | |
228 | * <b>NOTE:</b> This function returns false if the global variables needed are not set. | |
229 | * | |
d48b00b4 | 230 | * Like {@link me()} but returns a full URL |
7cf1c7bd | 231 | * @see me() |
449611af | 232 | * |
233 | * @global string | |
234 | * @return mixed String, or false if the global variables needed are not set | |
7cf1c7bd | 235 | */ |
f9903ed0 | 236 | function qualified_me() { |
11e7b506 | 237 | global $FULLME; |
238 | return $FULLME; | |
f9903ed0 | 239 | } |
240 | ||
360e503e | 241 | /** |
242 | * Class for creating and manipulating urls. | |
84e3d2cc | 243 | * |
449611af | 244 | * It can be used in moodle pages where config.php has been included without any further includes. |
245 | * | |
49c8c8d2 | 246 | * It is useful for manipulating urls with long lists of params. |
fa9f6bf6 | 247 | * One situation where it will be useful is a page which links to itself to perform various actions |
449611af | 248 | * and / or to process form data. A moodle_url object : |
49c8c8d2 | 249 | * can be created for a page to refer to itself with all the proper get params being passed from page call to |
250 | * page call and methods can be used to output a url including all the params, optionally adding and overriding | |
449611af | 251 | * params and can also be used to |
252 | * - output the url without any get params | |
49c8c8d2 | 253 | * - and output the params as hidden fields to be output within a form |
449611af | 254 | * |
449611af | 255 | * @link http://docs.moodle.org/en/Development:lib/weblib.php_moodle_url See short write up here |
256 | * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later | |
257 | * @package moodlecore | |
360e503e | 258 | */ |
259 | class moodle_url { | |
449611af | 260 | /** |
a6855934 PS |
261 | * Scheme, ex.: http, https |
262 | * @var string | |
263 | */ | |
264 | protected $scheme = ''; | |
265 | /** | |
266 | * hostname | |
449611af | 267 | * @var string |
449611af | 268 | */ |
7ceb61d8 | 269 | protected $host = ''; |
a6855934 PS |
270 | /** |
271 | * Port number, empty means default 80 or 443 in case of http | |
272 | * @var unknown_type | |
273 | */ | |
7ceb61d8 | 274 | protected $port = ''; |
a6855934 PS |
275 | /** |
276 | * Username for http auth | |
277 | * @var string | |
278 | */ | |
7ceb61d8 | 279 | protected $user = ''; |
a6855934 PS |
280 | /** |
281 | * Password for http auth | |
282 | * @var string | |
283 | */ | |
7ceb61d8 | 284 | protected $pass = ''; |
a6855934 | 285 | /** |
7dff555f | 286 | * Script path |
a6855934 PS |
287 | * @var string |
288 | */ | |
7ceb61d8 | 289 | protected $path = ''; |
7dff555f PS |
290 | /** |
291 | * Optional slash argument value | |
292 | * @var string | |
293 | */ | |
294 | protected $slashargument = ''; | |
449611af | 295 | /** |
a6855934 PS |
296 | * Anchor, may be also empty, null means none |
297 | * @var string | |
298 | */ | |
299 | protected $anchor = null; | |
300 | /** | |
301 | * Url parameters as associative array | |
49c8c8d2 | 302 | * @var array |
449611af | 303 | */ |
7ceb61d8 | 304 | protected $params = array(); // Associative array of query string params |
84e3d2cc | 305 | |
360e503e | 306 | /** |
a6855934 | 307 | * Create new instance of moodle_url. |
84e3d2cc | 308 | * |
a6855934 PS |
309 | * @param moodle_url|string $url - moodle_url means make a copy of another |
310 | * moodle_url and change parameters, string means full url or shortened | |
311 | * form (ex.: '/course/view.php'). It is strongly encouraged to not include | |
312 | * query string because it may result in double encoded values | |
313 | * @param array $params these params override current params or add new | |
360e503e | 314 | */ |
a6855934 PS |
315 | public function __construct($url, array $params = null) { |
316 | global $CFG; | |
2b3fcef9 | 317 | |
a6855934 | 318 | if ($url instanceof moodle_url) { |
75781f87 | 319 | $this->scheme = $url->scheme; |
320 | $this->host = $url->host; | |
321 | $this->port = $url->port; | |
322 | $this->user = $url->user; | |
323 | $this->pass = $url->pass; | |
ad52c04f | 324 | $this->path = $url->path; |
7dff555f | 325 | $this->slashargument = $url->slashargument; |
75781f87 | 326 | $this->params = $url->params; |
a6855934 | 327 | $this->anchor = $url->anchor; |
2b3fcef9 | 328 | |
75781f87 | 329 | } else { |
a6855934 PS |
330 | // detect if anchor used |
331 | $apos = strpos($url, '#'); | |
332 | if ($apos !== false) { | |
333 | $anchor = substr($url, $apos); | |
334 | $anchor = ltrim($anchor, '#'); | |
335 | $this->set_anchor($anchor); | |
336 | $url = substr($url, 0, $apos); | |
360e503e | 337 | } |
a6855934 PS |
338 | |
339 | // normalise shortened form of our url ex.: '/course/view.php' | |
340 | if (strpos($url, '/') === 0) { | |
341 | // we must not use httpswwwroot here, because it might be url of other page, | |
342 | // devs have to use httpswwwroot explicitly when creating new moodle_url | |
343 | $url = $CFG->wwwroot.$url; | |
75781f87 | 344 | } |
a6855934 PS |
345 | |
346 | // now fix the admin links if needed, no need to mess with httpswwwroot | |
347 | if ($CFG->admin !== 'admin') { | |
348 | if (strpos($url, "$CFG->wwwroot/admin/") === 0) { | |
349 | $url = str_replace("$CFG->wwwroot/admin/", "$CFG->wwwroot/$CFG->admin/", $url); | |
350 | } | |
351 | } | |
352 | ||
353 | // parse the $url | |
354 | $parts = parse_url($url); | |
355 | if ($parts === false) { | |
75781f87 | 356 | throw new moodle_exception('invalidurl'); |
360e503e | 357 | } |
7ceb61d8 | 358 | if (isset($parts['query'])) { |
a6855934 PS |
359 | // note: the values may not be correctly decoded, |
360 | // url parameters should be always passed as array | |
24a905f9 | 361 | parse_str(str_replace('&', '&', $parts['query']), $this->params); |
360e503e | 362 | } |
363 | unset($parts['query']); | |
7ceb61d8 | 364 | foreach ($parts as $key => $value) { |
360e503e | 365 | $this->$key = $value; |
366 | } | |
7dff555f PS |
367 | |
368 | // detect slashargument value from path - we do not support directory names ending with .php | |
369 | $pos = strpos($this->path, '.php/'); | |
370 | if ($pos !== false) { | |
371 | $this->slashargument = substr($this->path, $pos + 4); | |
372 | $this->path = substr($this->path, 0, $pos + 4); | |
373 | } | |
360e503e | 374 | } |
2b3fcef9 | 375 | |
75781f87 | 376 | $this->params($params); |
84e3d2cc | 377 | } |
7ceb61d8 | 378 | |
360e503e | 379 | /** |
2b3fcef9 | 380 | * Add an array of params to the params for this url. |
449611af | 381 | * |
382 | * The added params override existing ones if they have the same name. | |
360e503e | 383 | * |
f8065dd2 | 384 | * @param array $params Defaults to null. If null then returns all params. |
449611af | 385 | * @return array Array of Params for url. |
360e503e | 386 | */ |
2b3fcef9 PS |
387 | public function params(array $params = null) { |
388 | $params = (array)$params; | |
389 | ||
390 | foreach ($params as $key=>$value) { | |
391 | if (is_int($key)) { | |
d8ae33a9 | 392 | throw new coding_exception('Url parameters can not have numeric keys!'); |
2b3fcef9 PS |
393 | } |
394 | if (is_array($value)) { | |
d8ae33a9 | 395 | throw new coding_exception('Url parameters values can not be arrays!'); |
2b3fcef9 PS |
396 | } |
397 | if (is_object($value) and !method_exists($value, '__toString')) { | |
d8ae33a9 | 398 | throw new coding_exception('Url parameters values can not be objects, unless __toString() is defined!'); |
2b3fcef9 PS |
399 | } |
400 | $this->params[$key] = (string)$value; | |
c1f41c59 | 401 | } |
2b3fcef9 | 402 | return $this->params; |
360e503e | 403 | } |
84e3d2cc | 404 | |
360e503e | 405 | /** |
49c8c8d2 | 406 | * Remove all params if no arguments passed. |
407 | * Remove selected params if arguments are passed. | |
449611af | 408 | * |
409 | * Can be called as either remove_params('param1', 'param2') | |
75781f87 | 410 | * or remove_params(array('param1', 'param2')). |
360e503e | 411 | * |
75781f87 | 412 | * @param mixed $params either an array of param names, or a string param name, |
413 | * @param string $params,... any number of additional param names. | |
2b3fcef9 | 414 | * @return array url parameters |
360e503e | 415 | */ |
2b3fcef9 | 416 | public function remove_params($params = null) { |
75781f87 | 417 | if (!is_array($params)) { |
418 | $params = func_get_args(); | |
419 | } | |
420 | foreach ($params as $param) { | |
2b3fcef9 | 421 | unset($this->params[$param]); |
360e503e | 422 | } |
2b3fcef9 PS |
423 | return $this->params; |
424 | } | |
425 | ||
426 | /** | |
427 | * Remove all url parameters | |
428 | * @param $params | |
429 | * @return void | |
430 | */ | |
431 | public function remove_all_params($params = null) { | |
432 | $this->params = array(); | |
7dff555f | 433 | $this->slashargument = ''; |
360e503e | 434 | } |
435 | ||
436 | /** | |
2b3fcef9 | 437 | * Add a param to the params for this url. |
449611af | 438 | * |
2b3fcef9 | 439 | * The added param overrides existing one if they have the same name. |
360e503e | 440 | * |
441 | * @param string $paramname name | |
2b3fcef9 PS |
442 | * @param string $newvalue Param value. If new value specified current value is overriden or parameter is added |
443 | * @return mixed string parameter value, null if parameter does not exist | |
360e503e | 444 | */ |
2b3fcef9 PS |
445 | public function param($paramname, $newvalue = '') { |
446 | if (func_num_args() > 1) { | |
447 | // set new value | |
448 | $this->params(array($paramname=>$newvalue)); | |
449 | } | |
450 | if (isset($this->params[$paramname])) { | |
5762b36e | 451 | return $this->params[$paramname]; |
cf615522 | 452 | } else { |
453 | return null; | |
c1f41c59 | 454 | } |
360e503e | 455 | } |
456 | ||
2b3fcef9 PS |
457 | /** |
458 | * Merges parameters and validates them | |
459 | * @param array $overrideparams | |
460 | * @return array merged parameters | |
461 | */ | |
462 | protected function merge_overrideparams(array $overrideparams = null) { | |
463 | $overrideparams = (array)$overrideparams; | |
464 | $params = $this->params; | |
465 | foreach ($overrideparams as $key=>$value) { | |
466 | if (is_int($key)) { | |
cdefaa86 | 467 | throw new coding_exception('Overridden parameters can not have numeric keys!'); |
2b3fcef9 PS |
468 | } |
469 | if (is_array($value)) { | |
cdefaa86 | 470 | throw new coding_exception('Overridden parameters values can not be arrays!'); |
2b3fcef9 PS |
471 | } |
472 | if (is_object($value) and !method_exists($value, '__toString')) { | |
cdefaa86 | 473 | throw new coding_exception('Overridden parameters values can not be objects, unless __toString() is defined!'); |
2b3fcef9 PS |
474 | } |
475 | $params[$key] = (string)$value; | |
476 | } | |
477 | return $params; | |
478 | } | |
479 | ||
7ceb61d8 | 480 | /** |
481 | * Get the params as as a query string. | |
8afba50b | 482 | * This method should not be used outside of this method. |
449611af | 483 | * |
8afba50b | 484 | * @param boolean $escaped Use & as params separator instead of plain & |
7ceb61d8 | 485 | * @param array $overrideparams params to add to the output params, these |
486 | * override existing ones with the same name. | |
487 | * @return string query string that can be added to a url. | |
488 | */ | |
8afba50b | 489 | public function get_query_string($escaped = true, array $overrideparams = null) { |
360e503e | 490 | $arr = array(); |
2b3fcef9 | 491 | $params = $this->merge_overrideparams($overrideparams); |
7ceb61d8 | 492 | foreach ($params as $key => $val) { |
7dff555f | 493 | $arr[] = rawurlencode($key)."=".rawurlencode($val); |
360e503e | 494 | } |
c7f5e16a | 495 | if ($escaped) { |
496 | return implode('&', $arr); | |
497 | } else { | |
498 | return implode('&', $arr); | |
499 | } | |
360e503e | 500 | } |
7ceb61d8 | 501 | |
2b3fcef9 PS |
502 | /** |
503 | * Shortcut for printing of encoded URL. | |
504 | * @return string | |
505 | */ | |
506 | public function __toString() { | |
b9bc2019 | 507 | return $this->out(true); |
2b3fcef9 PS |
508 | } |
509 | ||
360e503e | 510 | /** |
511 | * Output url | |
84e3d2cc | 512 | * |
c7f5e16a | 513 | * If you use the returned URL in HTML code, you want the escaped ampersands. If you use |
514 | * the returned URL in HTTP headers, you want $escaped=false. | |
515 | * | |
c7f5e16a | 516 | * @param boolean $escaped Use & as params separator instead of plain & |
b9bc2019 | 517 | * @param array $overrideparams params to add to the output url, these override existing ones with the same name. |
449611af | 518 | * @return string Resulting URL |
360e503e | 519 | */ |
b9bc2019 PS |
520 | public function out($escaped = true, array $overrideparams = null) { |
521 | if (!is_bool($escaped)) { | |
522 | debugging('Escape parameter must be of type boolean, '.gettype($escaped).' given instead.'); | |
523 | } | |
524 | ||
7dff555f | 525 | $uri = $this->out_omit_querystring().$this->slashargument; |
244a32c6 | 526 | |
8afba50b | 527 | $querystring = $this->get_query_string($escaped, $overrideparams); |
7dff555f | 528 | if ($querystring !== '') { |
eb788065 PS |
529 | $uri .= '?' . $querystring; |
530 | } | |
531 | if (!is_null($this->anchor)) { | |
532 | $uri .= '#'.$this->anchor; | |
360e503e | 533 | } |
a6855934 | 534 | |
84e3d2cc | 535 | return $uri; |
360e503e | 536 | } |
7ceb61d8 | 537 | |
eb788065 PS |
538 | /** |
539 | * Returns url without parameters, everything before '?'. | |
540 | * @return string | |
541 | */ | |
542 | public function out_omit_querystring() { | |
543 | $uri = $this->scheme ? $this->scheme.':'.((strtolower($this->scheme) == 'mailto') ? '':'//'): ''; | |
544 | $uri .= $this->user ? $this->user.($this->pass? ':'.$this->pass:'').'@':''; | |
545 | $uri .= $this->host ? $this->host : ''; | |
546 | $uri .= $this->port ? ':'.$this->port : ''; | |
547 | $uri .= $this->path ? $this->path : ''; | |
548 | return $uri; | |
b5d0cafc PS |
549 | } |
550 | ||
827b2f7a | 551 | /** |
552 | * Compares this moodle_url with another | |
553 | * See documentation of constants for an explanation of the comparison flags. | |
554 | * @param moodle_url $url The moodle_url object to compare | |
555 | * @param int $matchtype The type of comparison (URL_MATCH_BASE, URL_MATCH_PARAMS, URL_MATCH_EXACT) | |
556 | * @return boolean | |
557 | */ | |
558 | public function compare(moodle_url $url, $matchtype = URL_MATCH_EXACT) { | |
c705a24e | 559 | |
eb788065 PS |
560 | $baseself = $this->out_omit_querystring(); |
561 | $baseother = $url->out_omit_querystring(); | |
bf6c37c7 | 562 | |
563 | // Append index.php if there is no specific file | |
564 | if (substr($baseself,-1)=='/') { | |
565 | $baseself .= 'index.php'; | |
566 | } | |
567 | if (substr($baseother,-1)=='/') { | |
568 | $baseother .= 'index.php'; | |
569 | } | |
570 | ||
571 | // Compare the two base URLs | |
572 | if ($baseself != $baseother) { | |
827b2f7a | 573 | return false; |
574 | } | |
575 | ||
576 | if ($matchtype == URL_MATCH_BASE) { | |
577 | return true; | |
578 | } | |
579 | ||
580 | $urlparams = $url->params(); | |
581 | foreach ($this->params() as $param => $value) { | |
582 | if ($param == 'sesskey') { | |
583 | continue; | |
584 | } | |
585 | if (!array_key_exists($param, $urlparams) || $urlparams[$param] != $value) { | |
586 | return false; | |
587 | } | |
588 | } | |
589 | ||
590 | if ($matchtype == URL_MATCH_PARAMS) { | |
591 | return true; | |
592 | } | |
593 | ||
594 | foreach ($urlparams as $param => $value) { | |
595 | if ($param == 'sesskey') { | |
596 | continue; | |
597 | } | |
598 | if (!array_key_exists($param, $this->params()) || $this->param($param) != $value) { | |
599 | return false; | |
600 | } | |
601 | } | |
602 | ||
603 | return true; | |
604 | } | |
13b0b271 SH |
605 | |
606 | /** | |
607 | * Sets the anchor for the URI (the bit after the hash) | |
a6855934 | 608 | * @param string $anchor null means remove previous |
13b0b271 SH |
609 | */ |
610 | public function set_anchor($anchor) { | |
a6855934 PS |
611 | if (is_null($anchor)) { |
612 | // remove | |
613 | $this->anchor = null; | |
614 | } else if ($anchor === '') { | |
615 | // special case, used as empty link | |
616 | $this->anchor = ''; | |
617 | } else if (preg_match('|[a-zA-Z\_\:][a-zA-Z0-9\_\-\.\:]*|', $anchor)) { | |
618 | // Match the anchor against the NMTOKEN spec | |
619 | $this->anchor = $anchor; | |
620 | } else { | |
621 | // bad luck, no valid anchor found | |
622 | $this->anchor = null; | |
13b0b271 SH |
623 | } |
624 | } | |
7dff555f | 625 | |
4e40406d PS |
626 | /** |
627 | * Sets the url slashargument value | |
628 | * @param string $path usually file path | |
629 | * @param string $parameter name of page parameter if slasharguments not supported | |
630 | * @param bool $supported usually null, then it depends on $CFG->slasharguments, use true or false for other servers | |
631 | * @return void | |
632 | */ | |
f28ee49e | 633 | public function set_slashargument($path, $parameter = 'file', $supported = NULL) { |
4e40406d PS |
634 | global $CFG; |
635 | if (is_null($supported)) { | |
636 | $supported = $CFG->slasharguments; | |
637 | } | |
638 | ||
639 | if ($supported) { | |
640 | $parts = explode('/', $path); | |
641 | $parts = array_map('rawurlencode', $parts); | |
642 | $path = implode('/', $parts); | |
643 | $this->slashargument = $path; | |
644 | unset($this->params[$parameter]); | |
645 | ||
646 | } else { | |
647 | $this->slashargument = ''; | |
648 | $this->params[$parameter] = $path; | |
649 | } | |
650 | } | |
651 | ||
7dff555f PS |
652 | // == static factory methods == |
653 | ||
654 | /** | |
acdb9177 PS |
655 | * General moodle file url. |
656 | * @param string $urlbase the script serving the file | |
657 | * @param string $path | |
7dff555f PS |
658 | * @param bool $forcedownload |
659 | * @return moodle_url | |
660 | */ | |
f28ee49e | 661 | public static function make_file_url($urlbase, $path, $forcedownload = false) { |
acdb9177 PS |
662 | global $CFG; |
663 | ||
7dff555f | 664 | $params = array(); |
7dff555f PS |
665 | if ($forcedownload) { |
666 | $params['forcedownload'] = 1; | |
667 | } | |
acdb9177 | 668 | |
4e40406d PS |
669 | $url = new moodle_url($urlbase, $params); |
670 | $url->set_slashargument($path); | |
671 | ||
672 | return $url; | |
7dff555f PS |
673 | } |
674 | ||
675 | /** | |
676 | * Factory method for creation of url pointing to plugin file. | |
677 | * Please note this method can be used only from the plugins to | |
678 | * create urls of own files, it must not be used outside of plugins! | |
679 | * @param int $contextid | |
f28ee49e | 680 | * @param string $component |
7dff555f PS |
681 | * @param string $area |
682 | * @param int $itemid | |
683 | * @param string $pathname | |
684 | * @param string $filename | |
685 | * @param bool $forcedownload | |
686 | * @return moodle_url | |
687 | */ | |
f28ee49e | 688 | public static function make_pluginfile_url($contextid, $component, $area, $itemid, $pathname, $filename, $forcedownload = false) { |
7dff555f PS |
689 | global $CFG; |
690 | $urlbase = "$CFG->httpswwwroot/pluginfile.php"; | |
f28ee49e PS |
691 | if ($itemid === NULL) { |
692 | return self::make_file_url($urlbase, "/$contextid/$component/$area".$pathname.$filename, $forcedownload); | |
693 | } else { | |
694 | return self::make_file_url($urlbase, "/$contextid/$component/$area/$itemid".$pathname.$filename, $forcedownload); | |
695 | } | |
7dff555f PS |
696 | } |
697 | ||
698 | /** | |
699 | * Factory method for creation of url pointing to draft | |
700 | * file of current user. | |
37416d5d | 701 | * @param int $draftid draft item id |
7dff555f PS |
702 | * @param string $pathname |
703 | * @param string $filename | |
704 | * @param bool $forcedownload | |
705 | * @return moodle_url | |
706 | */ | |
37416d5d | 707 | public static function make_draftfile_url($draftid, $pathname, $filename, $forcedownload = false) { |
7dff555f PS |
708 | global $CFG, $USER; |
709 | $urlbase = "$CFG->httpswwwroot/draftfile.php"; | |
710 | $context = get_context_instance(CONTEXT_USER, $USER->id); | |
711 | ||
37416d5d | 712 | return self::make_file_url($urlbase, "/$context->id/user/draft/$draftid".$pathname.$filename, $forcedownload); |
7dff555f | 713 | } |
ed77a56f PS |
714 | |
715 | /** | |
716 | * Factory method for creating of links to legacy | |
717 | * course files. | |
718 | * @param int $courseid | |
719 | * @param string $filepath | |
720 | * @param bool $forcedownload | |
721 | * @return moodle_url | |
722 | */ | |
f28ee49e | 723 | public static function make_legacyfile_url($courseid, $filepath, $forcedownload = false) { |
ed77a56f PS |
724 | global $CFG; |
725 | ||
acdb9177 PS |
726 | $urlbase = "$CFG->wwwroot/file.php"; |
727 | return self::make_file_url($urlbase, '/'.$courseid.'/'.$filepath, $forcedownload); | |
ed77a56f | 728 | } |
360e503e | 729 | } |
730 | ||
7cf1c7bd | 731 | /** |
732 | * Determine if there is data waiting to be processed from a form | |
733 | * | |
734 | * Used on most forms in Moodle to check for data | |
735 | * Returns the data as an object, if it's found. | |
736 | * This object can be used in foreach loops without | |
737 | * casting because it's cast to (array) automatically | |
772e78be | 738 | * |
9c0f063b | 739 | * Checks that submitted POST data exists and returns it as object. |
d48b00b4 | 740 | * |
449611af | 741 | * @uses $_POST |
9c0f063b | 742 | * @return mixed false or object |
7cf1c7bd | 743 | */ |
294ce987 | 744 | function data_submitted() { |
d48b00b4 | 745 | |
607809b3 | 746 | if (empty($_POST)) { |
36b4f985 | 747 | return false; |
748 | } else { | |
294ce987 | 749 | return (object)$_POST; |
36b4f985 | 750 | } |
751 | } | |
752 | ||
7cf1c7bd | 753 | /** |
d48b00b4 | 754 | * Given some normal text this function will break up any |
755 | * long words to a given size by inserting the given character | |
756 | * | |
6aaa17c7 | 757 | * It's multibyte savvy and doesn't change anything inside html tags. |
758 | * | |
7cf1c7bd | 759 | * @param string $string the string to be modified |
89dcb99d | 760 | * @param int $maxsize maximum length of the string to be returned |
7cf1c7bd | 761 | * @param string $cutchar the string used to represent word breaks |
762 | * @return string | |
763 | */ | |
4a5644e5 | 764 | function break_up_long_words($string, $maxsize=20, $cutchar=' ') { |
a2b3f884 | 765 | |
6aaa17c7 | 766 | /// Loading the textlib singleton instance. We are going to need it. |
767 | $textlib = textlib_get_instance(); | |
8f7dc7f1 | 768 | |
6aaa17c7 | 769 | /// First of all, save all the tags inside the text to skip them |
770 | $tags = array(); | |
771 | filter_save_tags($string,$tags); | |
5b07d990 | 772 | |
6aaa17c7 | 773 | /// Process the string adding the cut when necessary |
4a5644e5 | 774 | $output = ''; |
810944af | 775 | $length = $textlib->strlen($string); |
4a5644e5 | 776 | $wordlength = 0; |
777 | ||
778 | for ($i=0; $i<$length; $i++) { | |
810944af | 779 | $char = $textlib->substr($string, $i, 1); |
6aaa17c7 | 780 | if ($char == ' ' or $char == "\t" or $char == "\n" or $char == "\r" or $char == "<" or $char == ">") { |
4a5644e5 | 781 | $wordlength = 0; |
782 | } else { | |
783 | $wordlength++; | |
784 | if ($wordlength > $maxsize) { | |
785 | $output .= $cutchar; | |
786 | $wordlength = 0; | |
787 | } | |
788 | } | |
789 | $output .= $char; | |
790 | } | |
6aaa17c7 | 791 | |
792 | /// Finally load the tags back again | |
793 | if (!empty($tags)) { | |
794 | $output = str_replace(array_keys($tags), $tags, $output); | |
795 | } | |
796 | ||
4a5644e5 | 797 | return $output; |
798 | } | |
799 | ||
de6d81e6 | 800 | /** |
b166403f | 801 | * Try and close the current window using JavaScript, either immediately, or after a delay. |
449611af | 802 | * |
803 | * Echo's out the resulting XHTML & javascript | |
804 | * | |
805 | * @global object | |
806 | * @global object | |
b166403f | 807 | * @param integer $delay a delay in seconds before closing the window. Default 0. |
808 | * @param boolean $reloadopener if true, we will see if this window was a pop-up, and try | |
809 | * to reload the parent window before this one closes. | |
08396bb2 | 810 | */ |
b166403f | 811 | function close_window($delay = 0, $reloadopener = false) { |
f6794ace | 812 | global $PAGE, $OUTPUT; |
08396bb2 | 813 | |
c13a5e71 | 814 | if (!$PAGE->headerprinted) { |
de6d81e6 | 815 | $PAGE->set_title(get_string('closewindow')); |
816 | echo $OUTPUT->header(); | |
b166403f | 817 | } else { |
f6794ace | 818 | $OUTPUT->container_end_all(false); |
b166403f | 819 | } |
820 | ||
821 | if ($reloadopener) { | |
822 | $function = 'close_window_reloading_opener'; | |
823 | } else { | |
824 | $function = 'close_window'; | |
825 | } | |
826 | echo '<p class="centerpara">' . get_string('windowclosing') . '</p>'; | |
cf615522 | 827 | |
593f9b87 | 828 | $PAGE->requires->js_function_call($function, null, false, $delay); |
b166403f | 829 | |
7e0d6675 | 830 | echo $OUTPUT->footer(); |
b166403f | 831 | exit; |
832 | } | |
08396bb2 | 833 | |
28fbce88 | 834 | /** |
835 | * Returns a string containing a link to the user documentation for the current | |
836 | * page. Also contains an icon by default. Shown to teachers and admin only. | |
837 | * | |
838 | * @global object | |
839 | * @global object | |
840 | * @param string $text The text to be displayed for the link | |
841 | * @param string $iconpath The path to the icon to be displayed | |
842 | * @return string The link to user documentation for this current page | |
843 | */ | |
8ae8bf8a | 844 | function page_doc_link($text='') { |
28fbce88 | 845 | global $CFG, $PAGE, $OUTPUT; |
846 | ||
847 | if (empty($CFG->docroot) || during_initial_install()) { | |
848 | return ''; | |
849 | } | |
850 | if (!has_capability('moodle/site:doclinks', $PAGE->context)) { | |
851 | return ''; | |
852 | } | |
853 | ||
854 | $path = $PAGE->docspath; | |
855 | if (!$path) { | |
856 | return ''; | |
857 | } | |
8ae8bf8a | 858 | return $OUTPUT->doc_link($path, $text); |
28fbce88 | 859 | } |
860 | ||
14040797 | 861 | |
d48b00b4 | 862 | /** |
863 | * Validates an email to make sure it makes sense. | |
864 | * | |
865 | * @param string $address The email address to validate. | |
866 | * @return boolean | |
867 | */ | |
89dcb99d | 868 | function validate_email($address) { |
d48b00b4 | 869 | |
69593309 AD |
870 | return (preg_match('#^[-!\#$%&\'*+\\/0-9=?A-Z^_`a-z{|}~]+'. |
871 | '(\.[-!\#$%&\'*+\\/0-9=?A-Z^_`a-z{|}~]+)*'. | |
f9903ed0 | 872 | '@'. |
69593309 AD |
873 | '[-!\#$%&\'*+\\/0-9=?A-Z^_`a-z{|}~]+\.'. |
874 | '[-!\#$%&\'*+\\./0-9=?A-Z^_`a-z{|}~]+$#', | |
f9903ed0 | 875 | $address)); |
876 | } | |
877 | ||
690f358b | 878 | /** |
879 | * Extracts file argument either from file parameter or PATH_INFO | |
11e7b506 | 880 | * Note: $scriptname parameter is not needed anymore |
690f358b | 881 | * |
449611af | 882 | * @global string |
883 | * @uses $_SERVER | |
884 | * @uses PARAM_PATH | |
690f358b | 885 | * @return string file path (only safe characters) |
886 | */ | |
11e7b506 | 887 | function get_file_argument() { |
888 | global $SCRIPT; | |
690f358b | 889 | |
690f358b | 890 | $relativepath = optional_param('file', FALSE, PARAM_PATH); |
891 | ||
892 | // then try extract file from PATH_INFO (slasharguments method) | |
11e7b506 | 893 | if ($relativepath === false and isset($_SERVER['PATH_INFO']) and $_SERVER['PATH_INFO'] !== '') { |
690f358b | 894 | // check that PATH_INFO works == must not contain the script name |
11e7b506 | 895 | if (strpos($_SERVER['PATH_INFO'], $SCRIPT) === false) { |
896 | $relativepath = clean_param(urldecode($_SERVER['PATH_INFO']), PARAM_PATH); | |
690f358b | 897 | } |
898 | } | |
899 | ||
11e7b506 | 900 | // note: we are not using any other way because they are not compatible with unicode file names ;-) |
690f358b | 901 | |
902 | return $relativepath; | |
903 | } | |
904 | ||
d48b00b4 | 905 | /** |
89dcb99d | 906 | * Just returns an array of text formats suitable for a popup menu |
d48b00b4 | 907 | * |
89dcb99d | 908 | * @uses FORMAT_MOODLE |
909 | * @uses FORMAT_HTML | |
910 | * @uses FORMAT_PLAIN | |
89dcb99d | 911 | * @uses FORMAT_MARKDOWN |
912 | * @return array | |
d48b00b4 | 913 | */ |
0095d5cd | 914 | function format_text_menu() { |
b0ccd3fb | 915 | return array (FORMAT_MOODLE => get_string('formattext'), |
916 | FORMAT_HTML => get_string('formathtml'), | |
917 | FORMAT_PLAIN => get_string('formatplain'), | |
b0ccd3fb | 918 | FORMAT_MARKDOWN => get_string('formatmarkdown')); |
0095d5cd | 919 | } |
920 | ||
d48b00b4 | 921 | /** |
922 | * Given text in a variety of format codings, this function returns | |
772e78be | 923 | * the text as safe HTML. |
d48b00b4 | 924 | * |
c5659019 | 925 | * This function should mainly be used for long strings like posts, |
e8276c10 | 926 | * answers, glossary items etc. For short strings @see format_string(). |
927 | * | |
449611af | 928 | * @todo Finish documenting this function |
929 | * | |
449611af | 930 | * @staticvar array $croncache |
89dcb99d | 931 | * @param string $text The text to be formatted. This is raw text originally from user input. |
772e78be | 932 | * @param int $format Identifier of the text format to be used |
35716b86 PS |
933 | * [FORMAT_MOODLE, FORMAT_HTML, FORMAT_PLAIN, FORMAT_MARKDOWN] |
934 | * @param object/array $options text formatting options | |
935 | * @param int $courseid_do_not_use deprecated course id, use context option instead | |
89dcb99d | 936 | * @return string |
d48b00b4 | 937 | */ |
35716b86 | 938 | function format_text($text, $format = FORMAT_MOODLE, $options = NULL, $courseid_do_not_use = NULL) { |
e3e40b43 | 939 | global $CFG, $COURSE, $DB, $PAGE; |
c4ae4fa1 | 940 | |
1cc54a45 | 941 | static $croncache = array(); |
795a08ad | 942 | |
d53ca6ad | 943 | if ($text === '') { |
944 | return ''; // no need to do any filters and cleaning | |
945 | } | |
1bcb7eb5 | 946 | |
35716b86 | 947 | $options = (array)$options; // detach object, we can not modify it |
d53ca6ad | 948 | |
35716b86 PS |
949 | |
950 | if (!isset($options['trusted'])) { | |
951 | $options['trusted'] = false; | |
7d8a3cb0 | 952 | } |
35716b86 PS |
953 | if (!isset($options['noclean'])) { |
954 | if ($options['trusted'] and trusttext_active()) { | |
cbc2b5df | 955 | // no cleaning if text trusted and noclean not specified |
35716b86 | 956 | $options['noclean'] = true; |
cbc2b5df | 957 | } else { |
35716b86 | 958 | $options['noclean'] = false; |
cbc2b5df | 959 | } |
e7a47153 | 960 | } |
35716b86 PS |
961 | if (!isset($options['nocache'])) { |
962 | $options['nocache'] = false; | |
a17c57b5 | 963 | } |
35716b86 PS |
964 | if (!isset($options['smiley'])) { |
965 | $options['smiley'] = true; | |
e7a47153 | 966 | } |
35716b86 PS |
967 | if (!isset($options['filter'])) { |
968 | $options['filter'] = true; | |
e7a47153 | 969 | } |
35716b86 PS |
970 | if (!isset($options['para'])) { |
971 | $options['para'] = true; | |
e7a47153 | 972 | } |
35716b86 PS |
973 | if (!isset($options['newlines'])) { |
974 | $options['newlines'] = true; | |
f0aa2fed | 975 | } |
35716b86 PS |
976 | |
977 | // Calculate best context | |
8d39cbb3 PS |
978 | if (empty($CFG->version) or $CFG->version < 2010072800 or during_initial_install()) { |
979 | // do not filter anything during installation or before upgrade completes | |
980 | $context = null; | |
8d39cbb3 PS |
981 | |
982 | } else if (isset($options['context'])) { // first by explicit passed context option | |
35716b86 PS |
983 | if (is_object($options['context'])) { |
984 | $context = $options['context']; | |
985 | } else { | |
986 | $context = get_context_instance_by_id($context); | |
987 | } | |
988 | } else if ($courseid_do_not_use) { | |
989 | // legacy courseid | |
990 | $context = get_context_instance(CONTEXT_COURSE, $courseid_do_not_use); | |
991 | } else { | |
992 | // fallback to $PAGE->context this may be problematic in CLI and other non-standard pages :-( | |
993 | $context = $PAGE->context; | |
c4ae4fa1 | 994 | } |
a751a4e5 | 995 | |
f22b7397 PS |
996 | if (!$context) { |
997 | // either install/upgrade or something has gone really wrong because context does not exist (yet?) | |
998 | $options['nocache'] = true; | |
999 | $options['filter'] = false; | |
1000 | } | |
1001 | ||
35716b86 | 1002 | if ($options['filter']) { |
ccc161f8 | 1003 | $filtermanager = filter_manager::instance(); |
1004 | } else { | |
1005 | $filtermanager = new null_filter_manager(); | |
9e3f34d1 | 1006 | } |
ccc161f8 | 1007 | |
35716b86 PS |
1008 | if (!empty($CFG->cachetext) and empty($options['nocache'])) { |
1009 | $hashstr = $text.'-'.$filtermanager->text_filtering_hash($context).'-'.$context->id.'-'.current_language().'-'. | |
1010 | (int)$format.(int)$options['trusted'].(int)$options['noclean'].(int)$options['smiley']. | |
1011 | (int)$options['para'].(int)$options['newlines']; | |
1cc54a45 | 1012 | |
9e3f34d1 | 1013 | $time = time() - $CFG->cachetext; |
795a08ad | 1014 | $md5key = md5($hashstr); |
a91b910e | 1015 | if (CLI_SCRIPT) { |
1cc54a45 | 1016 | if (isset($croncache[$md5key])) { |
35716b86 | 1017 | return $croncache[$md5key]; |
1cc54a45 | 1018 | } |
1019 | } | |
1020 | ||
6c7f5374 | 1021 | if ($oldcacheitem = $DB->get_record('cache_text', array('md5key'=>$md5key), '*', IGNORE_MULTIPLE)) { |
a9743837 | 1022 | if ($oldcacheitem->timemodified >= $time) { |
a91b910e | 1023 | if (CLI_SCRIPT) { |
1cc54a45 | 1024 | if (count($croncache) > 150) { |
5087c945 | 1025 | reset($croncache); |
1026 | $key = key($croncache); | |
1027 | unset($croncache[$key]); | |
1cc54a45 | 1028 | } |
1029 | $croncache[$md5key] = $oldcacheitem->formattedtext; | |
1030 | } | |
35716b86 | 1031 | return $oldcacheitem->formattedtext; |
a9743837 | 1032 | } |
e7a47153 | 1033 | } |
1034 | } | |
1035 | ||
0095d5cd | 1036 | switch ($format) { |
73f8658c | 1037 | case FORMAT_HTML: |
35716b86 | 1038 | if ($options['smiley']) { |
e7a47153 | 1039 | replace_smilies($text); |
1040 | } | |
35716b86 | 1041 | if (!$options['noclean']) { |
5c6347ce | 1042 | $text = clean_text($text, FORMAT_HTML); |
9d40806d | 1043 | } |
35716b86 | 1044 | $text = $filtermanager->filter_text($text, $context); |
73f8658c | 1045 | break; |
1046 | ||
6901fa79 | 1047 | case FORMAT_PLAIN: |
5c6347ce | 1048 | $text = s($text); // cleans dangerous JS |
ab892a4f | 1049 | $text = rebuildnolinktag($text); |
b0ccd3fb | 1050 | $text = str_replace(' ', ' ', $text); |
6901fa79 | 1051 | $text = nl2br($text); |
6901fa79 | 1052 | break; |
1053 | ||
d342c763 | 1054 | case FORMAT_WIKI: |
6a6495ff | 1055 | // this format is deprecated |
572fe9ab | 1056 | $text = '<p>NOTICE: Wiki-like formatting has been removed from Moodle. You should not be seeing |
1057 | this message as all texts should have been converted to Markdown format instead. | |
ce50cc70 | 1058 | Please post a bug report to http://moodle.org/bugs with information about where you |
e7a47153 | 1059 | saw this message.</p>'.s($text); |
d342c763 | 1060 | break; |
1061 | ||
e7cdcd18 | 1062 | case FORMAT_MARKDOWN: |
1063 | $text = markdown_to_html($text); | |
35716b86 | 1064 | if ($options['smiley']) { |
e7a47153 | 1065 | replace_smilies($text); |
1066 | } | |
35716b86 | 1067 | if (!$options['noclean']) { |
5c6347ce | 1068 | $text = clean_text($text, FORMAT_HTML); |
9d40806d | 1069 | } |
35716b86 | 1070 | $text = $filtermanager->filter_text($text, $context); |
e7cdcd18 | 1071 | break; |
1072 | ||
73f8658c | 1073 | default: // FORMAT_MOODLE or anything else |
35716b86 PS |
1074 | $text = text_to_html($text, $options['smiley'], $options['para'], $options['newlines']); |
1075 | if (!$options['noclean']) { | |
5c6347ce | 1076 | $text = clean_text($text, FORMAT_HTML); |
9d40806d | 1077 | } |
35716b86 | 1078 | $text = $filtermanager->filter_text($text, $context); |
0095d5cd | 1079 | break; |
0095d5cd | 1080 | } |
f0aa2fed | 1081 | |
ccc161f8 | 1082 | // Warn people that we have removed this old mechanism, just in case they |
1083 | // were stupid enough to rely on it. | |
1084 | if (isset($CFG->currenttextiscacheable)) { | |
1085 | debugging('Once upon a time, Moodle had a truly evil use of global variables ' . | |
1086 | 'called $CFG->currenttextiscacheable. The good news is that this no ' . | |
1087 | 'longer exists. The bad news is that you seem to be using a filter that '. | |
1088 | 'relies on it. Please seek out and destroy that filter code.', DEBUG_DEVELOPER); | |
1089 | } | |
1090 | ||
35716b86 | 1091 | if (empty($options['nocache']) and !empty($CFG->cachetext)) { |
a91b910e | 1092 | if (CLI_SCRIPT) { |
1cc54a45 | 1093 | // special static cron cache - no need to store it in db if its not already there |
1094 | if (count($croncache) > 150) { | |
5087c945 | 1095 | reset($croncache); |
1096 | $key = key($croncache); | |
1097 | unset($croncache[$key]); | |
1cc54a45 | 1098 | } |
1099 | $croncache[$md5key] = $text; | |
35716b86 | 1100 | return $text; |
1cc54a45 | 1101 | } |
1102 | ||
365a5941 | 1103 | $newcacheitem = new stdClass(); |
a9743837 | 1104 | $newcacheitem->md5key = $md5key; |
f33e1ed4 | 1105 | $newcacheitem->formattedtext = $text; |
a9743837 | 1106 | $newcacheitem->timemodified = time(); |
1107 | if ($oldcacheitem) { // See bug 4677 for discussion | |
1108 | $newcacheitem->id = $oldcacheitem->id; | |
f6949ddb | 1109 | try { |
1110 | $DB->update_record('cache_text', $newcacheitem); // Update existing record in the cache table | |
1111 | } catch (dml_exception $e) { | |
1112 | // It's unlikely that the cron cache cleaner could have | |
1113 | // deleted this entry in the meantime, as it allows | |
1114 | // some extra time to cover these cases. | |
1115 | } | |
a9743837 | 1116 | } else { |
f6949ddb | 1117 | try { |
1118 | $DB->insert_record('cache_text', $newcacheitem); // Insert a new record in the cache table | |
1119 | } catch (dml_exception $e) { | |
1120 | // Again, it's possible that another user has caused this | |
1121 | // record to be created already in the time that it took | |
1122 | // to traverse this function. That's OK too, as the | |
1123 | // call above handles duplicate entries, and eventually | |
1124 | // the cron cleaner will delete them. | |
1125 | } | |
a9743837 | 1126 | } |
f0aa2fed | 1127 | } |
49c8c8d2 | 1128 | |
35716b86 | 1129 | return $text; |
0095d5cd | 1130 | } |
1131 | ||
449611af | 1132 | /** |
1133 | * Converts the text format from the value to the 'internal' | |
49c8c8d2 | 1134 | * name or vice versa. |
c06c8492 | 1135 | * |
449611af | 1136 | * $key can either be the value or the name and you get the other back. |
1137 | * | |
1138 | * @uses FORMAT_MOODLE | |
1139 | * @uses FORMAT_HTML | |
1140 | * @uses FORMAT_PLAIN | |
1141 | * @uses FORMAT_MARKDOWN | |
1142 | * @param mixed $key int 0-4 or string one of 'moodle','html','plain','markdown' | |
1143 | * @return mixed as above but the other way around! | |
4a28b5ca | 1144 | */ |
35716b86 | 1145 | function text_format_name($key) { |
4a28b5ca | 1146 | $lookup = array(); |
1147 | $lookup[FORMAT_MOODLE] = 'moodle'; | |
1148 | $lookup[FORMAT_HTML] = 'html'; | |
1149 | $lookup[FORMAT_PLAIN] = 'plain'; | |
1150 | $lookup[FORMAT_MARKDOWN] = 'markdown'; | |
1151 | $value = "error"; | |
1152 | if (!is_numeric($key)) { | |
1153 | $key = strtolower( $key ); | |
1154 | $value = array_search( $key, $lookup ); | |
1155 | } | |
1156 | else { | |
1157 | if (isset( $lookup[$key] )) { | |
1158 | $value = $lookup[ $key ]; | |
1159 | } | |
1160 | } | |
1161 | return $value; | |
1162 | } | |
1163 | ||
109e3cb2 | 1164 | /** |
1165 | * Resets all data related to filters, called during upgrade or when filter settings change. | |
449611af | 1166 | * |
1167 | * @global object | |
1168 | * @global object | |
109e3cb2 | 1169 | * @return void |
1170 | */ | |
1171 | function reset_text_filters_cache() { | |
8618fd2a | 1172 | global $CFG, $DB; |
109e3cb2 | 1173 | |
8618fd2a | 1174 | $DB->delete_records('cache_text'); |
109e3cb2 | 1175 | $purifdir = $CFG->dataroot.'/cache/htmlpurifier'; |
1176 | remove_dir($purifdir, true); | |
1177 | } | |
473d29eb | 1178 | |
49c8c8d2 | 1179 | /** |
449611af | 1180 | * Given a simple string, this function returns the string |
1181 | * processed by enabled string filters if $CFG->filterall is enabled | |
e8276c10 | 1182 | * |
449611af | 1183 | * This function should be used to print short strings (non html) that |
1184 | * need filter processing e.g. activity titles, post subjects, | |
1185 | * glossary concepts. | |
7b2c5e72 | 1186 | * |
449611af | 1187 | * @global object |
1188 | * @global object | |
1189 | * @global object | |
1190 | * @staticvar bool $strcache | |
1191 | * @param string $string The string to be filtered. | |
1192 | * @param boolean $striplinks To strip any link in the result text. | |
1193 | Moodle 1.8 default changed from false to true! MDL-8713 | |
35716b86 | 1194 | * @param array $options options array/object or courseid |
449611af | 1195 | * @return string |
7b2c5e72 | 1196 | */ |
35716b86 | 1197 | function format_string($string, $striplinks = true, $options = NULL) { |
e3e40b43 | 1198 | global $CFG, $COURSE, $PAGE; |
38701b69 | 1199 | |
2a3affe9 | 1200 | //We'll use a in-memory cache here to speed up repeated strings |
473d29eb | 1201 | static $strcache = false; |
1202 | ||
8d39cbb3 | 1203 | if (empty($CFG->version) or $CFG->version < 2010072800 or during_initial_install()) { |
57cddf6d PS |
1204 | // do not filter anything during installation or before upgrade completes |
1205 | return $string = strip_tags($string); | |
1206 | } | |
1207 | ||
35716b86 | 1208 | if ($strcache === false or count($strcache) > 2000) { // this number might need some tuning to limit memory usage in cron |
473d29eb | 1209 | $strcache = array(); |
1210 | } | |
84e3d2cc | 1211 | |
35716b86 PS |
1212 | if (is_numeric($options)) { |
1213 | // legacy courseid usage | |
1214 | $options = array('context'=>get_context_instance(CONTEXT_COURSE, $options)); | |
1215 | } else { | |
1216 | $options = (array)$options; // detach object, we can not modify it | |
1217 | } | |
1218 | ||
1219 | if (empty($options['context'])) { | |
1220 | // fallback to $PAGE->context this may be problematic in CLI and other non-standard pages :-( | |
1221 | $options['context'] = $PAGE->context; | |
1222 | } else if (is_numeric($options['context'])) { | |
1223 | $options['context'] = get_context_instance_by_id($options['context']); | |
1224 | } | |
1225 | ||
1226 | if (!$options['context']) { | |
1227 | // we did not find any context? weird | |
57cddf6d | 1228 | return $string = strip_tags($string); |
38701b69 | 1229 | } |
1230 | ||
2a3affe9 | 1231 | //Calculate md5 |
35716b86 | 1232 | $md5 = md5($string.'<+>'.$striplinks.'<+>'.$options['context']->id.'<+>'.current_language()); |
2a3affe9 | 1233 | |
1234 | //Fetch from cache if possible | |
38701b69 | 1235 | if (isset($strcache[$md5])) { |
2a3affe9 | 1236 | return $strcache[$md5]; |
1237 | } | |
1238 | ||
dacb47c0 | 1239 | // First replace all ampersands not followed by html entity code |
6dbcacee | 1240 | // Regular expression moved to its own method for easier unit testing |
1241 | $string = replace_ampersands_not_followed_by_entity($string); | |
268ddd50 | 1242 | |
57cddf6d | 1243 | if (!empty($CFG->filterall)) { |
35716b86 | 1244 | $string = filter_manager::instance()->filter_string($string, $options['context']); |
7b2c5e72 | 1245 | } |
84e3d2cc | 1246 | |
9fbed9c9 | 1247 | // If the site requires it, strip ALL tags from this string |
1248 | if (!empty($CFG->formatstringstriptags)) { | |
1249 | $string = strip_tags($string); | |
1250 | ||
408d5327 | 1251 | } else { |
1252 | // Otherwise strip just links if that is required (default) | |
1253 | if ($striplinks) { //strip links in string | |
31c2087d | 1254 | $string = strip_links($string); |
408d5327 | 1255 | } |
1256 | $string = clean_text($string); | |
3e6691ee | 1257 | } |
1258 | ||
2a3affe9 | 1259 | //Store to cache |
1260 | $strcache[$md5] = $string; | |
84e3d2cc | 1261 | |
7b2c5e72 | 1262 | return $string; |
1263 | } | |
1264 | ||
6dbcacee | 1265 | /** |
1266 | * Given a string, performs a negative lookahead looking for any ampersand character | |
1267 | * that is not followed by a proper HTML entity. If any is found, it is replaced | |
1268 | * by &. The string is then returned. | |
1269 | * | |
1270 | * @param string $string | |
1271 | * @return string | |
1272 | */ | |
1273 | function replace_ampersands_not_followed_by_entity($string) { | |
1274 | return preg_replace("/\&(?![a-zA-Z0-9#]{1,8};)/", "&", $string); | |
1275 | } | |
1276 | ||
31c2087d | 1277 | /** |
1278 | * Given a string, replaces all <a>.*</a> by .* and returns the string. | |
49c8c8d2 | 1279 | * |
31c2087d | 1280 | * @param string $string |
1281 | * @return string | |
1282 | */ | |
1283 | function strip_links($string) { | |
1284 | return preg_replace('/(<a\s[^>]+?>)(.+?)(<\/a>)/is','$2',$string); | |
1285 | } | |
1286 | ||
1287 | /** | |
1288 | * This expression turns links into something nice in a text format. (Russell Jungwirth) | |
1289 | * | |
1290 | * @param string $string | |
1291 | * @return string | |
1292 | */ | |
1293 | function wikify_links($string) { | |
1294 | return preg_replace('~(<a [^<]*href=["|\']?([^ "\']*)["|\']?[^>]*>([^<]*)</a>)~i','$3 [ $2 ]', $string); | |
1295 | } | |
1296 | ||
1297 | /** | |
1298 | * Replaces non-standard HTML entities | |
49c8c8d2 | 1299 | * |
31c2087d | 1300 | * @param string $string |
1301 | * @return string | |
1302 | */ | |
1303 | function fix_non_standard_entities($string) { | |
7e4763ef PS |
1304 | $text = preg_replace('/�*([0-9]+);?/', '&#$1;', $string); |
1305 | $text = preg_replace('/�*([0-9a-fA-F]+);?/', '&#x$1;', $text); | |
31c2087d | 1306 | return $text; |
1307 | } | |
1308 | ||
d48b00b4 | 1309 | /** |
1310 | * Given text in a variety of format codings, this function returns | |
1311 | * the text as plain text suitable for plain email. | |
d48b00b4 | 1312 | * |
89dcb99d | 1313 | * @uses FORMAT_MOODLE |
1314 | * @uses FORMAT_HTML | |
1315 | * @uses FORMAT_PLAIN | |
1316 | * @uses FORMAT_WIKI | |
1317 | * @uses FORMAT_MARKDOWN | |
1318 | * @param string $text The text to be formatted. This is raw text originally from user input. | |
772e78be | 1319 | * @param int $format Identifier of the text format to be used |
449611af | 1320 | * [FORMAT_MOODLE, FORMAT_HTML, FORMAT_PLAIN, FORMAT_WIKI, FORMAT_MARKDOWN] |
89dcb99d | 1321 | * @return string |
d48b00b4 | 1322 | */ |
d342c763 | 1323 | function format_text_email($text, $format) { |
d342c763 | 1324 | |
1325 | switch ($format) { | |
1326 | ||
1327 | case FORMAT_PLAIN: | |
1328 | return $text; | |
1329 | break; | |
1330 | ||
1331 | case FORMAT_WIKI: | |
cbc5d132 | 1332 | // there should not be any of these any more! |
31c2087d | 1333 | $text = wikify_links($text); |
7c55a29b | 1334 | return strtr(strip_tags($text), array_flip(get_html_translation_table(HTML_ENTITIES))); |
d342c763 | 1335 | break; |
1336 | ||
6ff45b59 | 1337 | case FORMAT_HTML: |
1338 | return html_to_text($text); | |
1339 | break; | |
1340 | ||
e7cdcd18 | 1341 | case FORMAT_MOODLE: |
1342 | case FORMAT_MARKDOWN: | |
67ccec43 | 1343 | default: |
31c2087d | 1344 | $text = wikify_links($text); |
7c55a29b | 1345 | return strtr(strip_tags($text), array_flip(get_html_translation_table(HTML_ENTITIES))); |
d342c763 | 1346 | break; |
1347 | } | |
1348 | } | |
0095d5cd | 1349 | |
dc5c2bd9 | 1350 | /** |
1351 | * Formats activity intro text | |
449611af | 1352 | * |
1353 | * @global object | |
1354 | * @uses CONTEXT_MODULE | |
dc5c2bd9 | 1355 | * @param string $module name of module |
1356 | * @param object $activity instance of activity | |
1357 | * @param int $cmid course module id | |
43b44d5e | 1358 | * @param bool $filter filter resulting html text |
dc5c2bd9 | 1359 | * @return text |
1360 | */ | |
43b44d5e | 1361 | function format_module_intro($module, $activity, $cmid, $filter=true) { |
ac3668bf | 1362 | global $CFG; |
1363 | require_once("$CFG->libdir/filelib.php"); | |
dc5c2bd9 | 1364 | $context = get_context_instance(CONTEXT_MODULE, $cmid); |
11d62334 | 1365 | $options = (object)array('noclean'=>true, 'para'=>false, 'filter'=>$filter, 'context'=>$context); |
64f93798 | 1366 | $intro = file_rewrite_pluginfile_urls($activity->intro, 'pluginfile.php', $context->id, 'mod_'.$module, 'intro', null); |
35716b86 | 1367 | return trim(format_text($intro, $activity->introformat, $options, null)); |
dc5c2bd9 | 1368 | } |
cbdfb929 | 1369 | |
7d8a3cb0 | 1370 | /** |
cbc2b5df | 1371 | * Legacy function, used for cleaning of old forum and glossary text only. |
449611af | 1372 | * |
1373 | * @global object | |
5ce73257 | 1374 | * @param string $text text that may contain TRUSTTEXT marker |
7d8a3cb0 | 1375 | * @return text without any TRUSTTEXT marker |
1376 | */ | |
1377 | function trusttext_strip($text) { | |
1378 | global $CFG; | |
1379 | ||
1380 | while (true) { //removing nested TRUSTTEXT | |
5ce73257 | 1381 | $orig = $text; |
cbc2b5df | 1382 | $text = str_replace('#####TRUSTTEXT#####', '', $text); |
7d8a3cb0 | 1383 | if (strcmp($orig, $text) === 0) { |
1384 | return $text; | |
1385 | } | |
1386 | } | |
1387 | } | |
1388 | ||
cbc2b5df | 1389 | /** |
1390 | * Must be called before editing of all texts | |
1391 | * with trust flag. Removes all XSS nasties | |
1392 | * from texts stored in database if needed. | |
449611af | 1393 | * |
cbc2b5df | 1394 | * @param object $object data object with xxx, xxxformat and xxxtrust fields |
1395 | * @param string $field name of text field | |
1396 | * @param object $context active context | |
1397 | * @return object updated $object | |
1398 | */ | |
1399 | function trusttext_pre_edit($object, $field, $context) { | |
1400 | $trustfield = $field.'trust'; | |
49c8c8d2 | 1401 | $formatfield = $field.'format'; |
1402 | ||
cbc2b5df | 1403 | if (!$object->$trustfield or !trusttext_trusted($context)) { |
1404 | $object->$field = clean_text($object->$field, $object->$formatfield); | |
1405 | } | |
1406 | ||
1407 | return $object; | |
1408 | } | |
1409 | ||
1410 | /** | |
449611af | 1411 | * Is current user trusted to enter no dangerous XSS in this context? |
1412 | * | |
cbc2b5df | 1413 | * Please note the user must be in fact trusted everywhere on this server!! |
449611af | 1414 | * |
1415 | * @param object $context | |
cbc2b5df | 1416 | * @return bool true if user trusted |
1417 | */ | |
1418 | function trusttext_trusted($context) { | |
49c8c8d2 | 1419 | return (trusttext_active() and has_capability('moodle/site:trustcontent', $context)); |
cbc2b5df | 1420 | } |
1421 | ||
1422 | /** | |
1423 | * Is trusttext feature active? | |
449611af | 1424 | * |
1425 | * @global object | |
1426 | * @param object $context | |
cbc2b5df | 1427 | * @return bool |
1428 | */ | |
1429 | function trusttext_active() { | |
1430 | global $CFG; | |
1431 | ||
49c8c8d2 | 1432 | return !empty($CFG->enabletrusttext); |
cbc2b5df | 1433 | } |
1434 | ||
d48b00b4 | 1435 | /** |
1436 | * Given raw text (eg typed in by a user), this function cleans it up | |
1437 | * and removes any nasty tags that could mess up Moodle pages. | |
1438 | * | |
449611af | 1439 | * @global string |
1440 | * @global object | |
89dcb99d | 1441 | * @param string $text The text to be cleaned |
772e78be | 1442 | * @param int $format Identifier of the text format to be used |
449611af | 1443 | * [FORMAT_MOODLE, FORMAT_HTML, FORMAT_PLAIN, FORMAT_WIKI, FORMAT_MARKDOWN] |
89dcb99d | 1444 | * @return string The cleaned up text |
d48b00b4 | 1445 | */ |
35716b86 | 1446 | function clean_text($text, $format = FORMAT_MOODLE) { |
85fbf884 | 1447 | global $ALLOWED_TAGS, $CFG; |
1448 | ||
e0ac8448 | 1449 | if (empty($text) or is_numeric($text)) { |
84e3d2cc | 1450 | return (string)$text; |
e0ac8448 | 1451 | } |
3fe3851d | 1452 | |
ab9f24ad | 1453 | switch ($format) { |
e7cdcd18 | 1454 | case FORMAT_PLAIN: |
8f660562 | 1455 | case FORMAT_MARKDOWN: |
e7cdcd18 | 1456 | return $text; |
1457 | ||
1458 | default: | |
1459 | ||
e0ac8448 | 1460 | if (!empty($CFG->enablehtmlpurifier)) { |
1461 | $text = purify_html($text); | |
1462 | } else { | |
1463 | /// Fix non standard entity notations | |
31c2087d | 1464 | $text = fix_non_standard_entities($text); |
84e3d2cc | 1465 | |
e0ac8448 | 1466 | /// Remove tags that are not allowed |
1467 | $text = strip_tags($text, $ALLOWED_TAGS); | |
84e3d2cc | 1468 | |
e0ac8448 | 1469 | /// Clean up embedded scripts and , using kses |
1470 | $text = cleanAttributes($text); | |
a33c44c4 | 1471 | |
1472 | /// Again remove tags that are not allowed | |
1473 | $text = strip_tags($text, $ALLOWED_TAGS); | |
1474 | ||
e0ac8448 | 1475 | } |
7789ffbf | 1476 | |
e0ac8448 | 1477 | /// Remove potential script events - some extra protection for undiscovered bugs in our code |
6dbcacee | 1478 | $text = preg_replace("~([^a-z])language([[:space:]]*)=~i", "$1Xlanguage=", $text); |
1479 | $text = preg_replace("~([^a-z])on([a-z]+)([[:space:]]*)=~i", "$1Xon$2=", $text); | |
6901fa79 | 1480 | |
6901fa79 | 1481 | return $text; |
0095d5cd | 1482 | } |
b7a3cf49 | 1483 | } |
f9903ed0 | 1484 | |
e0ac8448 | 1485 | /** |
1486 | * KSES replacement cleaning function - uses HTML Purifier. | |
449611af | 1487 | * |
1488 | * @global object | |
1489 | * @param string $text The (X)HTML string to purify | |
e0ac8448 | 1490 | */ |
1491 | function purify_html($text) { | |
1492 | global $CFG; | |
1493 | ||
109e3cb2 | 1494 | // this can not be done only once because we sometimes need to reset the cache |
eb203ee4 | 1495 | $cachedir = $CFG->dataroot.'/cache/htmlpurifier'; |
c426ef3a | 1496 | check_dir_exists($cachedir); |
109e3cb2 | 1497 | |
e0ac8448 | 1498 | static $purifier = false; |
109e3cb2 | 1499 | if ($purifier === false) { |
eb203ee4 | 1500 | require_once $CFG->libdir.'/htmlpurifier/HTMLPurifier.safe-includes.php'; |
e0ac8448 | 1501 | $config = HTMLPurifier_Config::createDefault(); |
f71c7f00 PS |
1502 | |
1503 | $config->set('HTML.DefinitionID', 'moodlehtml'); | |
1504 | $config->set('HTML.DefinitionRev', 1); | |
1505 | $config->set('Cache.SerializerPath', $cachedir); | |
1506 | //$config->set('Cache.SerializerPermission', $CFG->directorypermissions); // it would be nice to get this upstream | |
1507 | $config->set('Core.NormalizeNewlines', false); | |
6ec450fb | 1508 | $config->set('Core.ConvertDocumentToFragment', true); |
1509 | $config->set('Core.Encoding', 'UTF-8'); | |
1510 | $config->set('HTML.Doctype', 'XHTML 1.0 Transitional'); | |
f71c7f00 | 1511 | $config->set('URI.AllowedSchemes', array('http'=>true, 'https'=>true, 'ftp'=>true, 'irc'=>true, 'nntp'=>true, 'news'=>true, 'rtsp'=>true, 'teamspeak'=>true, 'gopher'=>true, 'mms'=>true)); |
6ec450fb | 1512 | $config->set('Attr.AllowedFrameTargets', array('_blank')); |
f71c7f00 | 1513 | |
cbe44fb2 PS |
1514 | if (!empty($CFG->allowobjectembed)) { |
1515 | $config->set('HTML.SafeObject', true); | |
1516 | $config->set('Output.FlashCompat', true); | |
a0f97768 | 1517 | $config->set('HTML.SafeEmbed', true); |
cbe44fb2 PS |
1518 | } |
1519 | ||
f71c7f00 PS |
1520 | $def = $config->getHTMLDefinition(true); |
1521 | $def->addElement('nolink', 'Block', 'Flow', array()); // skip our filters inside | |
1522 | $def->addElement('tex', 'Inline', 'Inline', array()); // tex syntax, equivalent to $$xx$$ | |
1523 | $def->addElement('algebra', 'Inline', 'Inline', array()); // algebra syntax, equivalent to @@xx@@ | |
1524 | $def->addElement('lang', 'Block', 'Flow', array(), array('lang'=>'CDATA')); // old anf future style multilang - only our hacked lang attribute | |
1525 | $def->addAttribute('span', 'xxxlang', 'CDATA'); // current problematic multilang | |
1526 | ||
e0ac8448 | 1527 | $purifier = new HTMLPurifier($config); |
1528 | } | |
f71c7f00 PS |
1529 | |
1530 | $multilang = (strpos($text, 'class="multilang"') !== false); | |
1531 | ||
1532 | if ($multilang) { | |
1533 | $text = preg_replace('/<span(\s+lang="([a-zA-Z0-9_-]+)"|\s+class="multilang"){2}\s*>/', '<span xxxlang="${2}">', $text); | |
1534 | } | |
1535 | $text = $purifier->purify($text); | |
1536 | if ($multilang) { | |
1537 | $text = preg_replace('/<span xxxlang="([a-zA-Z0-9_-]+)">/', '<span lang="${1}" class="multilang">', $text); | |
1538 | } | |
1539 | ||
1540 | return $text; | |
e0ac8448 | 1541 | } |
1542 | ||
d48b00b4 | 1543 | /** |
89dcb99d | 1544 | * This function takes a string and examines it for HTML tags. |
449611af | 1545 | * |
d48b00b4 | 1546 | * If tags are detected it passes the string to a helper function {@link cleanAttributes2()} |
449611af | 1547 | * which checks for attributes and filters them for malicious content |
d48b00b4 | 1548 | * |
1549 | * @param string $str The string to be examined for html tags | |
1550 | * @return string | |
1551 | */ | |
3bd7ffec | 1552 | function cleanAttributes($str){ |
4e8f2e6b | 1553 | $result = preg_replace_callback( |
1554 | '%(<[^>]*(>|$)|>)%m', #search for html tags | |
1555 | "cleanAttributes2", | |
3bd7ffec | 1556 | $str |
67ccec43 | 1557 | ); |
3bd7ffec | 1558 | return $result; |
67ccec43 | 1559 | } |
1560 | ||
d48b00b4 | 1561 | /** |
1562 | * This function takes a string with an html tag and strips out any unallowed | |
1563 | * protocols e.g. javascript: | |
449611af | 1564 | * |
d48b00b4 | 1565 | * It calls ancillary functions in kses which are prefixed by kses |
d48b00b4 | 1566 | * |
449611af | 1567 | * @global object |
1568 | * @global string | |
4e8f2e6b | 1569 | * @param array $htmlArray An array from {@link cleanAttributes()}, containing in its 1st |
1570 | * element the html to be cleared | |
d48b00b4 | 1571 | * @return string |
1572 | */ | |
4e8f2e6b | 1573 | function cleanAttributes2($htmlArray){ |
3bd7ffec | 1574 | |
037dcbb6 | 1575 | global $CFG, $ALLOWED_PROTOCOLS; |
b0ccd3fb | 1576 | require_once($CFG->libdir .'/kses.php'); |
3bd7ffec | 1577 | |
4e8f2e6b | 1578 | $htmlTag = $htmlArray[1]; |
037dcbb6 | 1579 | if (substr($htmlTag, 0, 1) != '<') { |
3bd7ffec | 1580 | return '>'; //a single character ">" detected |
1581 | } | |
037dcbb6 | 1582 | if (!preg_match('%^<\s*(/\s*)?([a-zA-Z0-9]+)([^>]*)>?$%', $htmlTag, $matches)) { |
67ccec43 | 1583 | return ''; // It's seriously malformed |
1584 | } | |
3bd7ffec | 1585 | $slash = trim($matches[1]); //trailing xhtml slash |
67ccec43 | 1586 | $elem = $matches[2]; //the element name |
3bd7ffec | 1587 | $attrlist = $matches[3]; // the list of attributes as a string |
1588 | ||
037dcbb6 | 1589 | $attrArray = kses_hair($attrlist, $ALLOWED_PROTOCOLS); |
3bd7ffec | 1590 | |
67ccec43 | 1591 | $attStr = ''; |
037dcbb6 | 1592 | foreach ($attrArray as $arreach) { |
29939bea | 1593 | $arreach['name'] = strtolower($arreach['name']); |
1594 | if ($arreach['name'] == 'style') { | |
1595 | $value = $arreach['value']; | |
1596 | while (true) { | |
1597 | $prevvalue = $value; | |
1598 | $value = kses_no_null($value); | |
1599 | $value = preg_replace("/\/\*.*\*\//Us", '', $value); | |
1600 | $value = kses_decode_entities($value); | |
1601 | $value = preg_replace('/(&#[0-9]+)(;?)/', "\\1;", $value); | |
1602 | $value = preg_replace('/(&#x[0-9a-fA-F]+)(;?)/', "\\1;", $value); | |
1603 | if ($value === $prevvalue) { | |
1604 | $arreach['value'] = $value; | |
1605 | break; | |
1606 | } | |
1607 | } | |
1608 | $arreach['value'] = preg_replace("/j\s*a\s*v\s*a\s*s\s*c\s*r\s*i\s*p\s*t/i", "Xjavascript", $arreach['value']); | |
704c5dfe | 1609 | $arreach['value'] = preg_replace("/v\s*b\s*s\s*c\s*r\s*i\s*p\s*t/i", "Xvbscript", $arreach['value']); |
29939bea | 1610 | $arreach['value'] = preg_replace("/e\s*x\s*p\s*r\s*e\s*s\s*s\s*i\s*o\s*n/i", "Xexpression", $arreach['value']); |
8cd2314b | 1611 | $arreach['value'] = preg_replace("/b\s*i\s*n\s*d\s*i\s*n\s*g/i", "Xbinding", $arreach['value']); |
b8806ccc | 1612 | } else if ($arreach['name'] == 'href') { |
ee7f231d | 1613 | //Adobe Acrobat Reader XSS protection |
920337d1 | 1614 | $arreach['value'] = preg_replace('/(\.(pdf|fdf|xfdf|xdp|xfd)[^#]*)#.*$/i', '$1', $arreach['value']); |
29939bea | 1615 | } |
049bd7db | 1616 | $attStr .= ' '.$arreach['name'].'="'.$arreach['value'].'"'; |
3bd7ffec | 1617 | } |
713126cd | 1618 | |
3bd7ffec | 1619 | $xhtml_slash = ''; |
037dcbb6 | 1620 | if (preg_match('%/\s*$%', $attrlist)) { |
67ccec43 | 1621 | $xhtml_slash = ' /'; |
3bd7ffec | 1622 | } |
b0ccd3fb | 1623 | return '<'. $slash . $elem . $attStr . $xhtml_slash .'>'; |
3bd7ffec | 1624 | } |
1625 | ||
d48b00b4 | 1626 | /** |
1627 | * Replaces all known smileys in the text with image equivalents | |
1628 | * | |
449611af | 1629 | * @global object |
1630 | * @staticvar array $e | |
1631 | * @staticvar array $img | |
1632 | * @staticvar array $emoticons | |
fa9f6bf6 | 1633 | * @param string $text Passed by reference. The string to search for smiley strings. |
d48b00b4 | 1634 | * @return string |
1635 | */ | |
5f350e8f | 1636 | function replace_smilies(&$text) { |
5d3b9994 | 1637 | global $CFG, $OUTPUT; |
183a13c2 | 1638 | |
1639 | if (empty($CFG->emoticons)) { /// No emoticons defined, nothing to process here | |
1640 | return; | |
1641 | } | |
1642 | ||
5a144b3a | 1643 | $lang = current_language(); |
93c61c18 | 1644 | $emoticonstring = $CFG->emoticons; |
69081931 | 1645 | static $e = array(); |
1646 | static $img = array(); | |
93c61c18 | 1647 | static $emoticons = null; |
1648 | ||
1649 | if (is_null($emoticons)) { | |
1650 | $emoticons = array(); | |
1651 | if ($emoticonstring) { | |
1652 | $items = explode('{;}', $CFG->emoticons); | |
1653 | foreach ($items as $item) { | |
1654 | $item = explode('{:}', $item); | |
c5659019 | 1655 | $emoticons[$item[0]] = $item[1]; |
93c61c18 | 1656 | } |
1657 | } | |
1658 | } | |
1659 | ||
5a144b3a | 1660 | if (empty($img[$lang])) { /// After the first time this is not run again |
1661 | $e[$lang] = array(); | |
1662 | $img[$lang] = array(); | |
617778f2 | 1663 | foreach ($emoticons as $emoticon => $image){ |
fbfc2675 | 1664 | $alttext = get_string($image, 'pix'); |
ef44fbed PS |
1665 | if ($alttext === '') { |
1666 | $alttext = $image; | |
1345cc53 | 1667 | } |
5a144b3a | 1668 | $e[$lang][] = $emoticon; |
b5d0cafc | 1669 | $img[$lang][] = '<img alt="'. $alttext .'" width="15" height="15" src="'. $OUTPUT->pix_url('s/' . $image) . '" />'; |
617778f2 | 1670 | } |
c0f728ba | 1671 | } |
b7a3cf49 | 1672 | |
8dcd43f3 | 1673 | // Exclude from transformations all the code inside <script> tags |
1674 | // Needed to solve Bug 1185. Thanks to jouse 2001 detecting it. :-) | |
fa9f6bf6 | 1675 | // Based on code from glossary filter by Williams Castillo. |
8dcd43f3 | 1676 | // - Eloy |
1677 | ||
1678 | // Detect all the <script> zones to take out | |
1679 | $excludes = array(); | |
1680 | preg_match_all('/<script language(.+?)<\/script>/is',$text,$list_of_excludes); | |
1681 | ||
1682 | // Take out all the <script> zones from text | |
1683 | foreach (array_unique($list_of_excludes[0]) as $key=>$value) { | |
1684 | $excludes['<+'.$key.'+>'] = $value; | |
1685 | } | |
1686 | if ($excludes) { | |
1687 | $text = str_replace($excludes,array_keys($excludes),$text); | |
1688 | } | |
1689 | ||
fbfc2675 | 1690 | /// this is the meat of the code - this is run every time |
5a144b3a | 1691 | $text = str_replace($e[$lang], $img[$lang], $text); |
8dcd43f3 | 1692 | |
1693 | // Recover all the <script> zones to text | |
1694 | if ($excludes) { | |
1695 | $text = str_replace(array_keys($excludes),$excludes,$text); | |
1696 | } | |
1a072208 | 1697 | } |
0095d5cd | 1698 | |
740939ec | 1699 | /** |
1700 | * This code is called from help.php to inject a list of smilies into the | |
1701 | * emoticons help file. | |
1702 | * | |
449611af | 1703 | * @global object |
1704 | * @global object | |
740939ec | 1705 | * @return string HTML for a list of smilies. |
1706 | */ | |
cf615522 | 1707 | function get_emoticons_list_for_help_file() { |
ddedf979 | 1708 | global $CFG, $SESSION, $PAGE, $OUTPUT; |
740939ec | 1709 | if (empty($CFG->emoticons)) { |
1710 | return ''; | |
1711 | } | |
1712 | ||
740939ec | 1713 | $items = explode('{;}', $CFG->emoticons); |
1714 | $output = '<ul id="emoticonlist">'; | |
1715 | foreach ($items as $item) { | |
1716 | $item = explode('{:}', $item); | |
b5d0cafc | 1717 | $output .= '<li><img src="' . $OUTPUT->pix_url('s/' . $item[1]) . '" alt="' . |
740939ec | 1718 | $item[0] . '" /><code>' . $item[0] . '</code></li>'; |
1719 | } | |
1720 | $output .= '</ul>'; | |
1721 | if (!empty($SESSION->inserttextform)) { | |
1722 | $formname = $SESSION->inserttextform; | |
1723 | $fieldname = $SESSION->inserttextfield; | |
1724 | } else { | |
1725 | $formname = 'theform'; | |
1726 | $fieldname = 'message'; | |
1727 | } | |
fa583f5f | 1728 | |
f44b10ed | 1729 | $PAGE->requires->yui2_lib('event'); |
cf615522 | 1730 | $PAGE->requires->js_function_call('emoticons_help.init', array($formname, $fieldname, 'emoticonlist')); |
740939ec | 1731 | return $output; |
1732 | ||
1733 | } | |
1734 | ||
89dcb99d | 1735 | /** |
1736 | * Given plain text, makes it into HTML as nicely as possible. | |
1737 | * May contain HTML tags already | |
1738 | * | |
449611af | 1739 | * @global object |
89dcb99d | 1740 | * @param string $text The string to convert. |
1741 | * @param boolean $smiley Convert any smiley characters to smiley images? | |
b075eb8e | 1742 | * @param boolean $para If true then the returned string will be wrapped in div tags |
89dcb99d | 1743 | * @param boolean $newlines If true then lines newline breaks will be converted to HTML newline breaks. |
1744 | * @return string | |
1745 | */ | |
1746 | ||
b7a3d3b2 | 1747 | function text_to_html($text, $smiley=true, $para=true, $newlines=true) { |
772e78be | 1748 | /// |
f9903ed0 | 1749 | |
27326a3e | 1750 | global $CFG; |
1751 | ||
c1d57101 | 1752 | /// Remove any whitespace that may be between HTML tags |
6dbcacee | 1753 | $text = preg_replace("~>([[:space:]]+)<~i", "><", $text); |
7b3be1b1 | 1754 | |
c1d57101 | 1755 | /// Remove any returns that precede or follow HTML tags |
6dbcacee | 1756 | $text = preg_replace("~([\n\r])<~i", " <", $text); |
1757 | $text = preg_replace("~>([\n\r])~i", "> ", $text); | |
7b3be1b1 | 1758 | |
5f350e8f | 1759 | convert_urls_into_links($text); |
f9903ed0 | 1760 | |
c1d57101 | 1761 | /// Make returns into HTML newlines. |
b7a3d3b2 | 1762 | if ($newlines) { |
1763 | $text = nl2br($text); | |
1764 | } | |
f9903ed0 | 1765 | |
c1d57101 | 1766 | /// Turn smileys into images. |
d69cb7f4 | 1767 | if ($smiley) { |
5f350e8f | 1768 | replace_smilies($text); |
d69cb7f4 | 1769 | } |
f9903ed0 | 1770 | |
b075eb8e | 1771 | /// Wrap the whole thing in a div if required |
909f539d | 1772 | if ($para) { |
b075eb8e AD |
1773 | //return '<p>'.$text.'</p>'; //1.9 version |
1774 | return '<div class="text_to_html">'.$text.'</div>'; | |
909f539d | 1775 | } else { |
1776 | return $text; | |
1777 | } | |
f9903ed0 | 1778 | } |
1779 | ||
d48b00b4 | 1780 | /** |
1781 | * Given Markdown formatted text, make it into XHTML using external function | |
1782 | * | |
449611af | 1783 | * @global object |
89dcb99d | 1784 | * @param string $text The markdown formatted text to be converted. |
1785 | * @return string Converted text | |
d48b00b4 | 1786 | */ |
e7cdcd18 | 1787 | function markdown_to_html($text) { |
e7cdcd18 | 1788 | global $CFG; |
1789 | ||
a4a0c9d9 PS |
1790 | if ($text === '' or $text === NULL) { |
1791 | return $text; | |
1792 | } | |
1793 | ||
b0ccd3fb | 1794 | require_once($CFG->libdir .'/markdown.php'); |
e7cdcd18 | 1795 | |
1796 | return Markdown($text); | |
1797 | } | |
1798 | ||
d48b00b4 | 1799 | /** |
89dcb99d | 1800 | * Given HTML text, make it into plain text using external function |
d48b00b4 | 1801 | * |
d48b00b4 | 1802 | * @param string $html The text to be converted. |
a194c218 TH |
1803 | * @param integer $width Width to wrap the text at. (optional, default 75 which |
1804 | * is a good value for email. 0 means do not limit line length.) | |
dc3e95c0 TH |
1805 | * @param boolean $dolinks By default, any links in the HTML are collected, and |
1806 | * printed as a list at the end of the HTML. If you don't want that, set this | |
1807 | * argument to false. | |
a194c218 | 1808 | * @return string plain text equivalent of the HTML. |
d48b00b4 | 1809 | */ |
dc3e95c0 | 1810 | function html_to_text($html, $width = 75, $dolinks = true) { |
89dcb99d | 1811 | |
428aaa29 | 1812 | global $CFG; |
6ff45b59 | 1813 | |
b0ccd3fb | 1814 | require_once($CFG->libdir .'/html2text.php'); |
6ff45b59 | 1815 | |
dc3e95c0 | 1816 | $h2t = new html2text($html, false, $dolinks, $width); |
588acd06 | 1817 | $result = $h2t->get_text(); |
07e9a300 | 1818 | |
977b3d31 | 1819 | return $result; |
6ff45b59 | 1820 | } |
1821 | ||
d48b00b4 | 1822 | /** |
1823 | * Given some text this function converts any URLs it finds into HTML links | |
1824 | * | |
1825 | * @param string $text Passed in by reference. The string to be searched for urls. | |
1826 | */ | |
5f350e8f | 1827 | function convert_urls_into_links(&$text) { |
c013b316 AD |
1828 | //I've added img tags to this list of tags to ignore. |
1829 | //See MDL-21168 for more info. A better way to ignore tags whether or not | |
1830 | //they are escaped partially or completely would be desirable. For example: | |
1831 | //<a href="blah"> | |
1832 | //<a href="blah"> | |
1833 | //<a href="blah"> | |
bd9255c5 EL |
1834 | $filterignoretagsopen = array('<a\s[^>]+?>'); |
1835 | $filterignoretagsclose = array('</a>'); | |
9c7a301b | 1836 | filter_save_ignore_tags($text,$filterignoretagsopen,$filterignoretagsclose,$ignoretags); |
c013b316 | 1837 | |
9c7a301b AD |
1838 | // Check if we support unicode modifiers in regular expressions. Cache it. |
1839 | // TODO: this check should be a environment requirement in Moodle 2.0, as far as unicode | |
1840 | // chars are going to arrive to URLs officially really soon (2010?) | |
1841 | // Original RFC regex from: http://www.bytemycode.com/snippets/snippet/796/ | |
1842 | // Various ideas from: http://alanstorm.com/url_regex_explained | |
1843 | // Unicode check, negative assertion and other bits from Moodle. | |
1844 | static $unicoderegexp; | |
1845 | if (!isset($unicoderegexp)) { | |
fa9f6bf6 | 1846 | $unicoderegexp = @preg_match('/\pL/u', 'a'); // This will fail silently, returning false, |
9c7a301b AD |
1847 | } |
1848 | ||
b245afc0 | 1849 | //todo: MDL-21296 - use of unicode modifiers may cause a timeout |
9c7a301b | 1850 | if ($unicoderegexp) { //We can use unicode modifiers |
2b2acf75 | 1851 | $text = preg_replace('#(?<!=["\'])(((http(s?))://)(((([\pLl0-9]([\pLl0-9]|-)*[\pLl0-9]|[\pLl0-9])\.)+([\pLl]([\pLl0-9]|-)*[\pLl0-9]|[\pLl]))|(([0-9]{1,3}\.){3}[0-9]{1,3}))(:[\pL0-9]*)?(/([\pLl0-9\.!$&\'\(\)*+,;=_~:@-]|%[a-fA-F0-9]{2})*)*(\?([\pLl0-9\.!$&\'\(\)*+,;=_~:@/?-]|%[a-fA-F0-9]{2})*)?(\#[\pLl0-9\.!$&\'\(\)*+,;=_~:@/?-]*)?)(?<![,.;])#iu', |
53ad47f2 | 1852 | '<a href="\\1" class="_blanktarget">\\1</a>', $text); |
2b2acf75 | 1853 | $text = preg_replace('#(?<!=["\']|//)((www\.([\pLl0-9]([\pLl0-9]|-)*[\pLl0-9]|[\pLl0-9])\.)+([\pLl]([\pLl0-9]|-)*[\pLl0-9]|[\pLl])(:[\pL0-9]*)?(/([\pLl0-9\.!$&\'\(\)*+,;=_~:@-]|%[a-fA-F0-9]{2})*)*(\?([\pLl0-9\.!$&\'\(\)*+,;=_~:@/?-]|%[a-fA-F0-9]{2})*)?(\#[\pLl0-9\.!$&\'\(\)*+,;=_~:@/?-]*)?)(?<![,.;])#iu', |
53ad47f2 | 1854 | '<a href="http://\\1" class="_blanktarget">\\1</a>', $text); |
9c7a301b | 1855 | } else { //We cannot use unicode modifiers |
2b2acf75 | 1856 | $text = preg_replace('#(?<!=["\'])(((http(s?))://)(((([a-z0-9]([a-z0-9]|-)*[a-z0-9]|[a-z0-9])\.)+([a-z]([a-z0-9]|-)*[a-z0-9]|[a-z]))|(([0-9]{1,3}\.){3}[0-9]{1,3}))(:[a-zA-Z0-9]*)?(/([a-z0-9\.!$&\'\(\)*+,;=_~:@-]|%[a-f0-9]{2})*)*(\?([a-z0-9\.!$&\'\(\)*+,;=_~:@/?-]|%[a-fA-F0-9]{2})*)?(\#[a-z0-9\.!$&\'\(\)*+,;=_~:@/?-]*)?)(?<![,.;])#i', |
53ad47f2 | 1857 | '<a href="\\1" class="_blanktarget">\\1</a>', $text); |
2b2acf75 | 1858 | $text = preg_replace('#(?<!=["\']|//)((www\.([a-z0-9]([a-z0-9]|-)*[a-z0-9]|[a-z0-9])\.)+([a-z]([a-z0-9]|-)*[a-z0-9]|[a-z])(:[a-zA-Z0-9]*)?(/([a-z0-9\.!$&\'\(\)*+,;=_~:@-]|%[a-f0-9]{2})*)*(\?([a-z0-9\.!$&\'\(\)*+,;=_~:@/?-]|%[a-fA-F0-9]{2})*)?(\#[a-z0-9\.!$&\'\(\)*+,;=_~:@/?-]*)?)(?<![,.;])#i', |
53ad47f2 | 1859 | '<a href="http://\\1" class="_blanktarget">\\1</a>', $text); |
9c7a301b AD |
1860 | } |
1861 | ||
1862 | if (!empty($ignoretags)) { | |
1863 | $ignoretags = array_reverse($ignoretags); /// Reversed so "progressive" str_replace() will solve some nesting problems. | |
1864 | $text = str_replace(array_keys($ignoretags),$ignoretags,$text); | |
1865 | } | |
5f350e8f | 1866 | } |
1867 | ||
d48b00b4 | 1868 | /** |
1869 | * This function will highlight search words in a given string | |
449611af | 1870 | * |
d48b00b4 | 1871 | * It cares about HTML and will not ruin links. It's best to use |
1872 | * this function after performing any conversions to HTML. | |
d48b00b4 | 1873 | * |
9289e4c9 | 1874 | * @param string $needle The search string. Syntax like "word1 +word2 -word3" is dealt with correctly. |
1875 | * @param string $haystack The string (HTML) within which to highlight the search terms. | |
1876 | * @param boolean $matchcase whether to do case-sensitive. Default case-insensitive. | |
1877 | * @param string $prefix the string to put before each search term found. | |
1878 | * @param string $suffix the string to put after each search term found. | |
1879 | * @return string The highlighted HTML. | |
d48b00b4 | 1880 | */ |
9289e4c9 | 1881 | function highlight($needle, $haystack, $matchcase = false, |
1882 | $prefix = '<span class="highlight">', $suffix = '</span>') { | |
587c7040 | 1883 | |
9289e4c9 | 1884 | /// Quick bail-out in trivial cases. |
587c7040 | 1885 | if (empty($needle) or empty($haystack)) { |
69d51d3a | 1886 | return $haystack; |
1887 | } | |
1888 | ||
9289e4c9 | 1889 | /// Break up the search term into words, discard any -words and build a regexp. |
1890 | $words = preg_split('/ +/', trim($needle)); | |
1891 | foreach ($words as $index => $word) { | |
1892 | if (strpos($word, '-') === 0) { | |
1893 | unset($words[$index]); | |
1894 | } else if (strpos($word, '+') === 0) { | |
1895 | $words[$index] = '\b' . preg_quote(ltrim($word, '+'), '/') . '\b'; // Match only as a complete word. | |
1896 | } else { | |
1897 | $words[$index] = preg_quote($word, '/'); | |
88438a58 | 1898 | } |
1899 | } | |
9289e4c9 | 1900 | $regexp = '/(' . implode('|', $words) . ')/u'; // u is do UTF-8 matching. |
1901 | if (!$matchcase) { | |
1902 | $regexp .= 'i'; | |
88438a58 | 1903 | } |
1904 | ||
9289e4c9 | 1905 | /// Another chance to bail-out if $search was only -words |
1906 | if (empty($words)) { | |
1907 | return $haystack; | |
88438a58 | 1908 | } |
88438a58 | 1909 | |
9289e4c9 | 1910 | /// Find all the HTML tags in the input, and store them in a placeholders array. |
1911 | $placeholders = array(); | |
1912 | $matches = array(); | |
1913 | preg_match_all('/<[^>]*>/', $haystack, $matches); | |
1914 | foreach (array_unique($matches[0]) as $key => $htmltag) { | |
1915 | $placeholders['<|' . $key . '|>'] = $htmltag; | |
1916 | } | |
9ccdcd97 | 1917 | |
9289e4c9 | 1918 | /// In $hastack, replace each HTML tag with the corresponding placeholder. |
1919 | $haystack = str_replace($placeholders, array_keys($placeholders), $haystack); | |
9ccdcd97 | 1920 | |
9289e4c9 | 1921 | /// In the resulting string, Do the highlighting. |
1922 | $haystack = preg_replace($regexp, $prefix . '$1' . $suffix, $haystack); | |
9ccdcd97 | 1923 | |
9289e4c9 | 1924 | /// Turn the placeholders back into HTML tags. |
1925 | $haystack = str_replace(array_keys($placeholders), $placeholders, $haystack); | |
88438a58 | 1926 | |
f60e7cfe | 1927 | return $haystack; |
88438a58 | 1928 | } |
1929 | ||
d48b00b4 | 1930 | /** |
1931 | * This function will highlight instances of $needle in $haystack | |
449611af | 1932 | * |
1933 | * It's faster that the above function {@link highlight()} and doesn't care about | |
d48b00b4 | 1934 | * HTML or anything. |
1935 | * | |
1936 | * @param string $needle The string to search for | |
1937 | * @param string $haystack The string to search for $needle in | |
449611af | 1938 | * @return string The highlighted HTML |
d48b00b4 | 1939 | */ |
88438a58 | 1940 | function highlightfast($needle, $haystack) { |
5af78ed2 | 1941 | |
587c7040 | 1942 | if (empty($needle) or empty($haystack)) { |
1943 | return $haystack; | |
1944 | } | |
1945 | ||
57f1b914 | 1946 | $parts = explode(moodle_strtolower($needle), moodle_strtolower($haystack)); |
5af78ed2 | 1947 | |
587c7040 | 1948 | if (count($parts) === 1) { |
1949 | return $haystack; | |
1950 | } | |
1951 | ||
5af78ed2 | 1952 | $pos = 0; |
1953 | ||
1954 | foreach ($parts as $key => $part) { | |
1955 | $parts[$key] = substr($haystack, $pos, strlen($part)); | |
1956 | $pos += strlen($part); | |
1957 | ||
b0ccd3fb | 1958 | $parts[$key] .= '<span class="highlight">'.substr($haystack, $pos, strlen($needle)).'</span>'; |
5af78ed2 | 1959 | $pos += strlen($needle); |
ab9f24ad | 1960 | } |
5af78ed2 | 1961 | |
587c7040 | 1962 | return str_replace('<span class="highlight"></span>', '', join('', $parts)); |
5af78ed2 | 1963 | } |
1964 | ||
2ab4e4b8 | 1965 | /** |
1966 | * Return a string containing 'lang', xml:lang and optionally 'dir' HTML attributes. | |
1967 | * Internationalisation, for print_header and backup/restorelib. | |
449611af | 1968 | * |
1969 | * @param bool $dir Default false | |
1970 | * @return string Attributes | |
2ab4e4b8 | 1971 | */ |
1972 | function get_html_lang($dir = false) { | |
1973 | $direction = ''; | |
1974 | if ($dir) { | |
e372f4c7 | 1975 | if (right_to_left()) { |
2ab4e4b8 | 1976 | $direction = ' dir="rtl"'; |
1977 | } else { | |
1978 | $direction = ' dir="ltr"'; | |
1979 | } | |
1980 | } | |
1981 | //Accessibility: added the 'lang' attribute to $direction, used in theme <html> tag. | |
3a915b06 | 1982 | $language = str_replace('_', '-', current_language()); |
0946fff4 | 1983 | @header('Content-Language: '.$language); |
84e3d2cc | 1984 | return ($direction.' lang="'.$language.'" xml:lang="'.$language.'"'); |
2ab4e4b8 | 1985 | } |
1986 | ||
34a2777c | 1987 | |
1988 | /// STANDARD WEB PAGE PARTS /////////////////////////////////////////////////// | |
1989 | ||
5c355019 | 1990 | /** |
34a2777c | 1991 | * Send the HTTP headers that Moodle requires. |
1992 | * @param $cacheable Can this page be cached on back? | |
5c355019 | 1993 | */ |
34a2777c | 1994 | function send_headers($contenttype, $cacheable = true) { |
1995 | @header('Content-Type: ' . $contenttype); | |
1996 | @header('Content-Script-Type: text/javascript'); | |
1997 | @header('Content-Style-Type: text/css'); | |
f9903ed0 | 1998 | |
34a2777c | 1999 | if ($cacheable) { |
2000 | // Allow caching on "back" (but not on normal clicks) | |
2001 | @header('Cache-Control: private, pre-check=0, post-check=0, max-age=0'); | |
2002 | @header('Pragma: no-cache'); | |
2003 | @header('Expires: '); | |
2004 | } else { | |
2005 | // Do everything we can to always prevent clients and proxies caching | |
2006 | @header('Cache-Control: no-store, no-cache, must-revalidate'); | |
2007 | @header('Cache-Control: post-check=0, pre-check=0', false); | |
2008 | @header('Pragma: no-cache'); | |
2009 | @header('Expires: Mon, 20 Aug 1969 09:23:00 GMT'); | |
2010 | @header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT'); | |
2011 | } | |
2012 | @header('Accept-Ranges: none'); | |
2013 | } | |
9fa49e22 | 2014 | |
ce3735d4 | 2015 | /** |
a84dea2c | 2016 | * Return the right arrow with text ('next'), and optionally embedded in a link. |
449611af | 2017 | * |
2018 | * @global object | |
ac905235 | 2019 | * @param string $text HTML/plain text label (set to blank only for breadcrumb separator cases). |
a84dea2c | 2020 | * @param string $url An optional link to use in a surrounding HTML anchor. |
2021 | * @param bool $accesshide True if text should be hidden (for screen readers only). | |
2022 | * @param string $addclass Additional class names for the link, or the arrow character. | |
2023 | * @return string HTML string. | |
ce3735d4 | 2024 | */ |
a84dea2c | 2025 | function link_arrow_right($text, $url='', $accesshide=false, $addclass='') { |
92e01ab7 | 2026 | global $OUTPUT; //TODO: move to output renderer |
a84dea2c | 2027 | $arrowclass = 'arrow '; |
2028 | if (! $url) { | |
2029 | $arrowclass .= $addclass; | |
2030 | } | |
92e01ab7 | 2031 | $arrow = '<span class="'.$arrowclass.'">'.$OUTPUT->rarrow().'</span>'; |
a84dea2c | 2032 | $htmltext = ''; |
2033 | if ($text) { | |
388794fd | 2034 | $htmltext = '<span class="arrow_text">'.$text.'</span> '; |
a84dea2c | 2035 | if ($accesshide) { |
1d75edd0 | 2036 | $htmltext = get_accesshide($htmltext); |
a84dea2c | 2037 | } |
ce3735d4 | 2038 | } |
a84dea2c | 2039 | if ($url) { |
388794fd | 2040 | $class = 'arrow_link'; |
a84dea2c | 2041 | if ($addclass) { |
388794fd | 2042 | $class .= ' '.$addclass; |
a84dea2c | 2043 | } |
388794fd | 2044 | return '<a class="'.$class.'" href="'.$url.'" title="'.preg_replace('/<.*?>/','',$text).'">'.$htmltext.$arrow.'</a>'; |
a84dea2c | 2045 | } |
2046 | return $htmltext.$arrow; | |
ce3735d4 | 2047 | } |
2048 | ||
2049 | /** | |
a84dea2c | 2050 | * Return the left arrow with text ('previous'), and optionally embedded in a link. |
449611af | 2051 | * |
2052 | * @global object | |
ac905235 | 2053 | * @param string $text HTML/plain text label (set to blank only for breadcrumb separator cases). |
a84dea2c | 2054 | * @param string $url An optional link to use in a surrounding HTML anchor. |
2055 | * @param bool $accesshide True if text should be hidden (for screen readers only). | |
2056 | * @param string $addclass Additional class names for the link, or the arrow character. | |
2057 | * @return string HTML string. | |
ce3735d4 | 2058 | */ |
a84dea2c | 2059 | function link_arrow_left($text, $url='', $accesshide=false, $addclass='') { |
92e01ab7 | 2060 | global $OUTPUT; // TODO: move to utput renderer |
a84dea2c | 2061 | $arrowclass = 'arrow '; |
2062 | if (! $url) { | |
2063 | $arrowclass .= $addclass; | |
2064 | } | |
92e01ab7 | 2065 | $arrow = '<span class="'.$arrowclass.'">'.$OUTPUT->larrow().'</span>'; |
a84dea2c | 2066 | $htmltext = ''; |
2067 | if ($text) { | |
388794fd | 2068 | $htmltext = ' <span class="arrow_text">'.$text.'</span>'; |
a84dea2c | 2069 | if ($accesshide) { |
1d75edd0 | 2070 | $htmltext = get_accesshide($htmltext); |
a84dea2c | 2071 | } |
ce3735d4 | 2072 | } |
a84dea2c | 2073 | if ($url) { |
388794fd | 2074 | $class = 'arrow_link'; |
a84dea2c | 2075 | if ($addclass) { |
388794fd | 2076 | $class .= ' '.$addclass; |
a84dea2c | 2077 | } |
388794fd | 2078 | return '<a class="'.$class.'" href="'.$url.'" title="'.preg_replace('/<.*?>/','',$text).'">'.$arrow.$htmltext.'</a>'; |
a84dea2c | 2079 | } |
2080 | return $arrow.$htmltext; | |
2081 | } | |
2082 | ||
1d75edd0 | 2083 | /** |
2084 | * Return a HTML element with the class "accesshide", for accessibility. | |
449611af | 2085 | * Please use cautiously - where possible, text should be visible! |
2086 | * | |
1d75edd0 | 2087 | * @param string $text Plain text. |
2088 | * @param string $elem Lowercase element name, default "span". | |
2089 | * @param string $class Additional classes for the element. | |
2090 | * @param string $attrs Additional attributes string in the form, "name='value' name2='value2'" | |
2091 | * @return string HTML string. | |
2092 | */ | |
2093 | function get_accesshide($text, $elem='span', $class='', $attrs='') { | |
2094 | return "<$elem class=\"accesshide $class\" $attrs>$text</$elem>"; | |
2095 | } | |
2096 | ||
a84dea2c | 2097 | /** |
2098 | * Return the breadcrumb trail navigation separator. | |
449611af | 2099 | * |
a84dea2c | 2100 | * @return string HTML string. |
2101 | */ | |
2102 | function get_separator() { | |
2103 | //Accessibility: the 'hidden' slash is preferred for screen readers. | |
2104 | return ' '.link_arrow_right($text='/', $url='', $accesshide=true, 'sep').' '; | |
ce3735d4 | 2105 | } |
2106 | ||
512c5901 | 2107 | /** |
fa9f6bf6 | 2108 | * Print (or return) a collapsible region, that has a caption that can |
449611af | 2109 | * be clicked to expand or collapse the region. |
49c8c8d2 | 2110 | * |
fa9f6bf6 | 2111 | * If JavaScript is off, then the region will always be expanded. |
512c5901 | 2112 | * |
2113 | * @param string $contents the contents of the box. | |
2114 | * @param string $classes class names added to the div that is output. | |
2115 | * @param string $id id added to the div that is output. Must not be blank. | |
2116 | * @param string $caption text displayed at the top. Clicking on this will cause the region to expand or contract. | |
fa9f6bf6 | 2117 | * @param string $userpref the name of the user preference that stores the user's preferred default state. |
512c5901 | 2118 | * (May be blank if you do not wish the state to be persisted. |
fa9f6bf6 | 2119 | * @param boolean $default Initial collapsed state to use if the user_preference it not set. |
512c5901 | 2120 | * @param boolean $return if true, return the HTML as a string, rather than printing it. |
449611af | 2121 | * @return string|void If $return is false, returns nothing, otherwise returns a string of HTML. |
512c5901 | 2122 | */ |
f2eb5002 | 2123 | function print_collapsible_region($contents, $classes, $id, $caption, $userpref = '', $default = false, $return = false) { |
e0fa3b81 | 2124 | $output = print_collapsible_region_start($classes, $id, $caption, $userpref, true, true); |
f2eb5002 | 2125 | $output .= $contents; |
2126 | $output .= print_collapsible_region_end(true); | |
2127 | ||
2128 | if ($return) { | |
2129 | return $output; | |
2130 | } else { | |
2131 | echo $output; | |
2132 | } | |
2133 | } | |
2134 | ||
512c5901 | 2135 | /** |
fa9f6bf6 | 2136 | * Print (or return) the start of a collapsible region, that has a caption that can |
512c5901 | 2137 | * be clicked to expand or collapse the region. If JavaScript is off, then the region |
fa9f6bf6 | 2138 | * will always be expanded. |
512c5901 | 2139 | * |
449611af | 2140 | * @global object |
512c5901 | 2141 | * @param string $classes class names added to the div that is output. |
2142 | * @param string $id id added to the div that is output. Must not be blank. | |
2143 | * @param string $caption text displayed at the top. Clicking on this will cause the region to expand or contract. | |
fa9f6bf6 | 2144 | * @param boolean $userpref the name of the user preference that stores the user's preferred default state. |
512c5901 | 2145 | * (May be blank if you do not wish the state to be persisted. |
fa9f6bf6 | 2146 | * @param boolean $default Initial collapsed state to use if the user_preference it not set. |
512c5901 | 2147 | * @param boolean $return if true, return the HTML as a string, rather than printing it. |
449611af | 2148 | * @return string|void if $return is false, returns nothing, otherwise returns a string of HTML. |
512c5901 | 2149 | */ |
f2eb5002 | 2150 | function print_collapsible_region_start($classes, $id, $caption, $userpref = false, $default = false, $return = false) { |
a28c9253 | 2151 | global $CFG, $PAGE, $OUTPUT; |
f2eb5002 | 2152 | |
f2eb5002 | 2153 | // Work out the initial state. |
2154 | if (is_string($userpref)) { | |
2155 | user_preference_allow_ajax_update($userpref, PARAM_BOOL); | |
2156 | $collapsed = get_user_preferences($userpref, $default); | |
2157 | } else { | |
2158 | $collapsed = $default; | |
2159 | $userpref = false; | |
2160 | } | |
2161 | ||
67c8a3e8 | 2162 | if ($collapsed) { |
2163 | $classes .= ' collapsed'; | |
2164 | } | |
2165 | ||
f2eb5002 | 2166 | $output = ''; |
2167 | $output .= '<div id="' . $id . '" class="collapsibleregion ' . $classes . '">'; | |
67c8a3e8 | 2168 | $output .= '<div id="' . $id . '_sizer">'; |
f2eb5002 | 2169 | $output .= '<div id="' . $id . '_caption" class="collapsibleregioncaption">'; |
2170 | $output .= $caption . ' '; | |
67c8a3e8 | 2171 | $output .= '</div><div id="' . $id . '_inner" class="collapsibleregioninner">'; |
38224dcb | 2172 | $PAGE->requires->js_init_call('M.util.init_collapsible_region', array($id, $userpref, get_string('clicktohideshow'))); |
f2eb5002 | 2173 | |
2174 | if ($return) { | |
2175 | return $output; | |
2176 | } else { | |
2177 | echo $output; | |
2178 | } | |
2179 | } | |
2180 | ||
512c5901 | 2181 | /** |
2182 | * Close a region started with print_collapsible_region_start. | |
2183 | * | |
2184 | * @param boolean $return if true, return the HTML as a string, rather than printing it. | |
449611af | 2185 | * @return string|void if $return is false, returns nothing, otherwise returns a string of HTML. |
512c5901 | 2186 | */ |
f2eb5002 | 2187 | function print_collapsible_region_end($return = false) { |
904998d8 | 2188 | $output = '</div></div></div>'; |
f2eb5002 | 2189 | |
2190 | if ($return) { | |
2191 | return $output; | |
2192 | } else { | |
2193 | echo $output; | |
2194 | } | |
2195 | } | |
2196 | ||
d48b00b4 | 2197 | /** |
2198 | * Print a specified group's avatar. | |
2199 | * | |
449611af | 2200 | * @global object |
2201 | * @uses CONTEXT_COURSE | |
a8ff9488 | 2202 | * @param array|stdClass $group A single {@link group} object OR array of groups. |
ce3735d4 | 2203 | * @param int $courseid The course ID. |
2204 | * @param boolean $large Default small picture, or large. | |
2205 | * @param boolean $return If false print picture, otherwise return the output as string | |
2206 | * @param boolean $link Enclose image in a link to view specified course? | |
449611af | 2207 | * @return string|void Depending on the setting of $return |
d48b00b4 | 2208 | */ |
da4124be | 2209 | function print_group_picture($group, $courseid, $large=false, $return=false, $link=true) { |
f374fb10 | 2210 | global $CFG; |
2211 | ||
fdcd0f05 | 2212 | if (is_array($group)) { |
2213 | $output = ''; | |
2214 | foreach($group as $g) { | |
2215 | $output .= print_group_picture($g, $courseid, $large, true, $link); | |
2216 | } | |
da4124be | 2217 | if ($return) { |
fdcd0f05 | 2218 | return $output; |
2219 | } else { | |
2220 | echo $output; | |
2221 | return; | |
2222 | } | |
2223 | } | |
2224 | ||
ec7a8b79 | 2225 | $context = get_context_instance(CONTEXT_COURSE, $courseid); |
97ea4833 | 2226 | |
4a9cf90e SM |
2227 | // If there is no picture, do nothing |
2228 | if (!$group->picture) { | |
2229 | return ''; | |
2230 | } | |
2231 | ||
2232 | // If picture is hidden, only show to those with course:managegroups | |
ec7a8b79 | 2233 | if ($group->hidepicture and !has_capability('moodle/course:managegroups', $context)) { |
3c0561cf | 2234 | return ''; |
2235 | } | |
c3cbfe7f | 2236 | |
ec7a8b79 | 2237 | if ($link or has_capability('moodle/site:accessallgroups', $context)) { |
a756cf1d | 2238 | $output = '<a href="'. $CFG->wwwroot .'/user/index.php?id='. $courseid .'&group='. $group->id .'">'; |
3c0561cf | 2239 | } else { |
2240 | $output = ''; | |
2241 | } | |
2242 | if ($large) { | |
b0ccd3fb | 2243 | $file = 'f1'; |
3c0561cf | 2244 | } else { |
b0ccd3fb | 2245 | $file = 'f2'; |
3c0561cf | 2246 | } |
4a9cf90e | 2247 | |
e88dd876 | 2248 | $grouppictureurl = moodle_url::make_pluginfile_url($context->id, 'group', 'icon', $group->id, '/', $file); |
4a9cf90e SM |
2249 | $output .= '<img class="grouppicture" src="'.$grouppictureurl.'"'. |
2250 | ' alt="'.s(get_string('group').' '.$group->name).'" title="'.s($group->name).'"/>'; | |
2251 | ||
ec7a8b79 | 2252 | if ($link or has_capability('moodle/site:accessallgroups', $context)) { |
b0ccd3fb | 2253 | $output .= '</a>'; |
3c0561cf | 2254 | } |
f374fb10 | 2255 | |
da4124be | 2256 | if ($return) { |
f374fb10 | 2257 | return $output; |
2258 | } else { | |
2259 | echo $output; | |
2260 | } | |
2261 | } | |
2262 | ||
9fa49e22 | 2263 | |
449611af | 2264 | /** |
2265 | * Display a recent activity note | |
49c8c8d2 | 2266 | * |
449611af | 2267 | * @uses CONTEXT_SYSTEM |
2268 | * @staticvar string $strftimerecent | |
2269 | * @param object A time object | |
2270 | * @param object A user object | |
2271 | * @param string $text Text for display for the note | |
2272 | * @param string $link The link to wrap around the text | |
2273 | * @param bool $return If set to true the HTML is returned rather than echo'd | |
2274 | * @param string $viewfullnames | |
2275 | */ | |
dd97c328 | 2276 | function print_recent_activity_note($time, $user, $text, $link, $return=false, $viewfullnames=null) { |
2277 | static $strftimerecent = null; | |
da4124be | 2278 | $output = ''; |
2279 | ||
dd97c328 | 2280 | if (is_null($viewfullnames)) { |
12d06877 | 2281 | $context = get_context_instance(CONTEXT_SYSTEM); |
dd97c328 | 2282 | $viewfullnames = has_capability('moodle/site:viewfullnames', $context); |
2283 | } | |
3f8a3834 | 2284 | |
dd97c328 | 2285 | if (is_null($strftimerecent)) { |
8f7dc7f1 | 2286 | $strftimerecent = get_string('strftimerecent'); |
2287 | } | |
2288 | ||
da4124be | 2289 | $output .= '<div class="head">'; |
dd97c328 | 2290 | $output .= '<div class="date">'.userdate($time, $strftimerecent).'</div>'; |
2291 | $output .= '<div class="name">'.fullname($user, $viewfullnames).'</div>'; | |
da4124be | 2292 | $output .= '</div>'; |
2293 | $output .= '<div class="info"><a href="'.$link.'">'.format_string($text,true).'</a></div>'; | |
2294 | ||
2295 | if ($return) { | |
2296 | return $output; | |
2297 | } else { | |
2298 | echo $output; | |
2299 | } | |
8f7dc7f1 | 2300 | } |
2301 | ||
f3a74e68 | 2302 | /** |
449611af | 2303 | * Returns a popup menu with course activity modules |
2304 | * | |
a2b3f884 | 2305 | * Given a course |
f3a74e68 | 2306 | * This function returns a small popup menu with all the |
2307 | * course activity modules in it, as a navigation menu | |
a2b3f884 | 2308 | * outputs a simple list structure in XHTML |
f3a74e68 | 2309 | * The data is taken from the serialised array stored in |
2310 | * the course record | |
2311 | * | |
f3a74e68 | 2312 | * @todo Finish documenting this function |
449611af | 2313 | * |
2314 | * @global object | |
2315 | * @uses CONTEXT_COURSE | |
2316 | * @param course $course A {@link $COURSE} object. | |
2317 | * @param string $sections | |
2318 | * @param string $modinfo | |
2319 | * @param string $strsection | |
2320 | * @param string $strjumpto | |
2321 | * @param int $width | |
2322 | * @param string $cmid | |
2323 | * @return string The HTML block | |
f3a74e68 | 2324 | */ |
85489a5b | 2325 | function navmenulist($course, $sections, $modinfo, $strsection, $strjumpto, $width=50, $cmid=0) { |
f3a74e68 | 2326 | |
4bc685df | 2327 | global $CFG, $OUTPUT; |
f3a74e68 | 2328 | |
f3a74e68 | 2329 | $section = -1; |
f3a74e68 | 2330 | $url = ''; |
f3a74e68 | 2331 | $menu = array(); |
dd97c328 | 2332 | $doneheading = false; |
f3a74e68 | 2333 | |
85489a5b | 2334 | $coursecontext = get_context_instance(CONTEXT_COURSE, $course->id); |
2335 | ||
36c446cb | 2336 | $menu[] = '<ul class="navmenulist"><li class="jumpto section"><span>'.$strjumpto.'</span><ul>'; |
dd97c328 | 2337 | foreach ($modinfo->cms as $mod) { |
2338 | if ($mod->modname == 'label') { | |
f3a74e68 | 2339 | continue; |
2340 | } | |
2341 | ||
76cbde41 | 2342 | if ($mod->sectionnum > $course->numsections) { /// Don't show excess hidden sections |
f3a74e68 | 2343 | break; |
2344 | } | |
2345 | ||
dd97c328 | 2346 | if (!$mod->uservisible) { // do not icnlude empty sections at all |
2347 | continue; | |
2348 | } | |
2349 | ||
76cbde41 | 2350 | if ($mod->sectionnum >= 0 and $section != $mod->sectionnum) { |
2351 | $thissection = $sections[$mod->sectionnum]; | |
f3a74e68 | 2352 | |
5ce73257 | 2353 | if ($thissection->visible or !$course->hiddensections or |
85489a5b | 2354 | has_capability('moodle/course:viewhiddensections', $coursecontext)) { |
f3a74e68 | 2355 | $thissection->summary = strip_tags(format_string($thissection->summary,true)); |
dd97c328 | 2356 | if (!$doneheading) { |
dfe66174 | 2357 | $menu[] = '</ul></li>'; |
f3a74e68 | 2358 | } |
2359 | if ($course->format == 'weeks' or empty($thissection->summary)) { | |
76cbde41 | 2360 | $item = $strsection ." ". $mod->sectionnum; |
f3a74e68 | 2361 | } else { |
2362 | if (strlen($thissection->summary) < ($width-3)) { | |
b3ab80aa | 2363 | $item = $thissection->summary; |
f3a74e68 | 2364 | } else { |
b3ab80aa | 2365 | $item = substr($thissection->summary, 0, $width).'...'; |
f3a74e68 | 2366 | } |
2367 | } | |
36c446cb | 2368 | $menu[] = '<li class="section"><span>'.$item.'</span>'; |
f3a74e68 | 2369 | $menu[] = '<ul>'; |
2370 | $doneheading = true; | |
dd97c328 | 2371 | |
76cbde41 | 2372 | $section = $mod->sectionnum; |
dd97c328 | 2373 | } else { |
2374 | // no activities from this hidden section shown | |
2375 | continue; | |
f3a74e68 | 2376 | } |
2377 | } | |
2378 | ||
dd97c328 | 2379 | $url = $mod->modname .'/view.php?id='. $mod->id; |
9a9012dc | 2380 | $mod->name = strip_tags(format_string($mod->name ,true)); |
dd97c328 | 2381 | if (strlen($mod->name) > ($width+5)) { |
2382 | $mod->name = substr($mod->name, 0, $width).'...'; | |
f3a74e68 | 2383 | } |
dd97c328 | 2384 | if (!$mod->visible) { |
2385 | $mod->name = '('.$mod->name.')'; | |
2386 | } | |
2387 | $class = 'activity '.$mod->modname; | |
996c1a6f | 2388 | $class .= ($cmid == $mod->id) ? ' selected' : ''; |
dd97c328 | 2389 | $menu[] = '<li class="'.$class.'">'. |
b5d0cafc | 2390 | '<img src="'.$OUTPUT->pix_url('icon', $mod->modname) . '" alt="" />'. |
dd97c328 | 2391 | '<a href="'.$CFG->wwwroot.'/mod/'.$url.'">'.$mod->name.'</a></li>'; |
f3a74e68 | 2392 | } |
dd97c328 | 2393 | |
dfe66174 | 2394 | if ($doneheading) { |
f713e270 | 2395 | $menu[] = '</ul></li>'; |
dfe66174 | 2396 | } |
143211e5 | 2397 | $menu[] = '</ul></li></ul>'; |
f3a74e68 | 2398 | |
2399 | return implode("\n", $menu); | |
2400 | } | |
2401 | ||
d48b00b4 | 2402 | /** |
2403 | * Prints a grade menu (as part of an existing form) with help | |
2404 | * Showing all possible numerical grades and scales | |
2405 | * | |
d48b00b4 | 2406 | * @todo Finish documenting this function |
f8065dd2 | 2407 | * @todo Deprecate: this is only used in a few contrib modules |
449611af | 2408 | * |
2409 | * @global object | |
2410 | * @param int $courseid The course ID | |
49c8c8d2 | 2411 | * @param string $name |
2412 | * @param string $current | |
449611af | 2413 | * @param boolean $includenograde Include those with no grades |
2414 | * @param boolean $return If set to true returns rather than echo's | |
2415 | * @return string|bool Depending on value of $return | |
d48b00b4 | 2416 | */ |
da4124be | 2417 | function print_grade_menu($courseid, $name, $current, $includenograde=true, $return=false) { |
62ca135d | 2418 | |
e63f88c9 | 2419 | global $CFG, $OUTPUT; |
62ca135d | 2420 | |
da4124be | 2421 | $output = ''; |
b0ccd3fb | 2422 | $strscale = get_string('scale'); |
2423 | $strscales = get_string('scales'); | |
62ca135d | 2424 | |
1f7deef6 | 2425 | $scales = get_scales_menu($courseid); |
62ca135d | 2426 | foreach ($scales as $i => $scalename) { |
b0ccd3fb | 2427 | $grades[-$i] = $strscale .': '. $scalename; |
62ca135d | 2428 | } |
d6bdd9d5 | 2429 | if ($includenograde) { |
b0ccd3fb | 2430 | $grades[0] = get_string('nograde'); |
d6bdd9d5 | 2431 | } |
62ca135d | 2432 | for ($i=100; $i>=1; $i--) { |
2433 | $grades[$i] = $i; | |
2434 | } | |
d776d59e | 2435 | $output .= html_writer::select($grades, $name, $current, false); |
62ca135d | 2436 | |
b5d0cafc | 2437 | $linkobject = '<span class="helplink"><img class="iconhelp" alt="'.$strscales.'" src="'.$OUTPUT->pix_url('help') . '" /></span>'; |
57cd3739 PS |
2438 | $link = new moodle_url('/course/scales.php', array('id'=>$courseid, 'list'=>1)); |
2439 | $action = new popup_action('click', $link->url, 'ratingscales', array('height' => 400, 'width' => 500)); | |
2440 | $output .= $OUTPUT->action_link($link, $linkobject, $action, array('title'=>$strscales)); | |
da4124be | 2441 | |
2442 | if ($return) { | |
2443 | return $output; | |
2444 | } else { | |
2445 | echo $output; | |
2446 | } | |
62ca135d | 2447 | } |
2448 | ||
7cfb11db | 2449 | /** |
2450 | * Print an error to STDOUT and exit with a non-zero code. For commandline scripts. | |
2451 | * Default errorcode is 1. | |
2452 | * | |
2453 | * Very useful for perl-like error-handling: | |
73f7ad71 | 2454 | * |
7cfb11db | 2455 | * do_somethting() or mdie("Something went wrong"); |
2456 | * | |
2457 | * @param string $msg Error message | |
73f7ad71 | 2458 | * @param integer $errorcode Error code to emit |
7cfb11db | 2459 | */ |
2460 | function mdie($msg='', $errorcode=1) { | |
2461 | trigger_error($msg); | |
2462 | exit($errorcode); | |
2463 | } | |
2464 | ||
d48b00b4 | 2465 | /** |
2466 | * Print a message and exit. | |
2467 | * | |
449611af | 2468 | * @param string $message The message to print in the notice |
2469 | * @param string $link The link to use for the continue button | |
2470 | * @param object $course A course object | |
2471 | * @return void This function simply exits | |
d48b00b4 | 2472 | */ |
1ae083e4 | 2473 | function notice ($message, $link='', $course=NULL) { |
f6794ace | 2474 | global $CFG, $SITE, $COURSE, $PAGE, $OUTPUT; |
9fa49e22 | 2475 | |
d795bfdb | 2476 | $message = clean_text($message); // In case nasties are in here |
9f7f1a74 | 2477 | |
a91b910e | 2478 | if (CLI_SCRIPT) { |
258d5322 | 2479 | echo("!!$message!!\n"); |
1c39033f | 2480 | exit(1); // no success |
d795bfdb | 2481 | } |
2482 | ||
c13a5e71 | 2483 | if (!$PAGE->headerprinted) { |
d795bfdb | 2484 | //header not yet printed |
de6d81e6 | 2485 | $PAGE->set_title(get_string('notice')); |
2486 | echo $OUTPUT->header(); | |
d795bfdb | 2487 | } else { |
f6794ace | 2488 | echo $OUTPUT->container_end_all(false); |
d795bfdb | 2489 | } |
9fa49e22 | 2490 | |
ea85e1ee | 2491 | echo $OUTPUT->box($message, 'generalbox', 'notice'); |
aa9a6867 | 2492 | echo $OUTPUT->continue_button($link); |
5ce73257 | 2493 | |
7e0d6675 | 2494 | echo $OUTPUT->footer(); |
1c39033f | 2495 | exit(1); // general error code |
9fa49e22 | 2496 | } |
2497 | ||
d48b00b4 | 2498 | /** |
2499 | * Redirects the user to another page, after printing a notice | |
2500 | * | |
e8775320 | 2501 | * This function calls the OUTPUT redirect method, echo's the output |
2502 | * and then dies to ensure nothing else happens. | |
2503 | * | |
2504 | * <strong>Good practice:</strong> You should call this method before starting page | |
2505 | * output by using any of the OUTPUT methods. | |
449611af | 2506 | * |
db82872e | 2507 | * @param moodle_url|string $url A moodle_url to redirect to. Strings are not to be trusted! |
e8775320 | 2508 | * @param string $message The message to display to the user |
2509 | * @param int $delay The delay before redirecting | |
7def9d43 | 2510 | * @return void - does not return! |
d48b00b4 | 2511 | */ |
1ae083e4 | 2512 | function redirect($url, $message='', $delay=-1) { |
8449364c | 2513 | global $OUTPUT, $PAGE, $SESSION, $CFG; |
d3f9f1f8 | 2514 | |
1adaa404 PS |
2515 | if (CLI_SCRIPT or AJAX_SCRIPT) { |
2516 | // this is wrong - developers should not use redirect in these scripts, | |
2517 | // but it should not be very likely | |
2518 | throw new moodle_exception('redirecterrordetected', 'error'); | |
2519 | } | |
2520 | ||
afa7cfa8 | 2521 | // prevent debug errors - make sure context is properly initialised |
9b540305 PS |
2522 | if ($PAGE) { |
2523 | $PAGE->set_context(null); | |
2524 | } | |
afa7cfa8 | 2525 | |
366c7499 | 2526 | if ($url instanceof moodle_url) { |
b9bc2019 | 2527 | $url = $url->out(false); |
366c7499 | 2528 | } |
2529 | ||
d3f9f1f8 | 2530 | if (!empty($CFG->usesid) && !isset($_COOKIE[session_name()])) { |
eee5d9bb | 2531 | $url = $SESSION->sid_process_url($url); |
fd78420b | 2532 | } |
2533 | ||
afa7cfa8 PS |
2534 | $debugdisableredirect = false; |
2535 | do { | |
2536 | if (defined('DEBUGGING_PRINTED')) { | |
2537 | // some debugging already printed, no need to look more | |
2538 | $debugdisableredirect = true; | |
2539 | break; | |
2540 | } | |
2541 | ||
2542 | if (empty($CFG->debugdisplay) or empty($CFG->debug)) { | |
2543 | // no errors should be displayed | |
2544 | break; | |
2545 | } | |
2546 | ||
2547 | if (!function_exists('error_get_last') or !$lasterror = error_get_last()) { | |
2548 | break; | |
2549 | } | |
2550 | ||
2551 | if (!($lasterror['type'] & $CFG->debug)) { | |
2552 | //last error not interesting | |
2553 | break; | |
2554 | } | |
2555 | ||
2556 | // watch out here, @hidden() errors are returned from error_get_last() too | |
2557 | if (headers_sent()) { | |
2558 | //we already started printing something - that means errors likely printed | |
2559 | $debugdisableredirect = true; | |
2560 | break; | |
2561 | } | |
2562 | ||
2563 | if (ob_get_level() and ob_get_contents()) { | |
2564 | // there is something waiting to be printed, hopefully it is the errors, | |
2565 | // but it might be some error hidden by @ too - such as the timezone mess from setup.php | |
2566 | $debugdisableredirect = true; | |
2567 | break; | |
2568 | } | |
2569 | } while (false); | |
ae96b517 | 2570 | |
ae96b517 | 2571 | if (!empty($message)) { |
2572 | if ($delay === -1 || !is_numeric($delay)) { | |
e8775320 | 2573 | $delay = 3; |
3446daa3 | 2574 | } |
e8775320 | 2575 | $message = clean_text($message); |
2576 | } else { | |
ae96b517 | 2577 | $message = get_string('pageshouldredirect'); |
e8775320 | 2578 | $delay = 0; |
ae96b517 | 2579 | // We are going to try to use a HTTP redirect, so we need a full URL. |
5ce73257 | 2580 | if (!preg_match('|^[a-z]+:|', $url)) { |
ecfdc901 | 2581 | // Get host name http://www.wherever.com |
aade3a4b | 2582 | $hostpart = preg_replace('|^(.*?[^:/])/.*$|', '$1', $CFG->wwwroot); |
2583 | if (preg_match('|^/|', $url)) { | |
2584 | // URLs beginning with / are relative to web server root so we just add them in | |
2585 | $url = $hostpart.$url; | |
ecfdc901 | 2586 | } else { |
aade3a4b | 2587 | // URLs not beginning with / are relative to path of current script, so add that on. |
20e1b1e5 | 2588 | $url = $hostpart.preg_replace('|\?.*$|','',me()).'/../'.$url; |
ecfdc901 | 2589 | } |
fd2fff1e | 2590 | // Replace all ..s |
aade3a4b | 2591 | while (true) { |
23ff199c | 2592 | $newurl = preg_replace('|/(?!\.\.)[^/]*/\.\./|', '/', $url); |
aade3a4b | 2593 | if ($newurl == $url) { |
fd2fff1e | 2594 | break; |
2595 | } | |
aade3a4b | 2596 | $url = $newurl; |
fd2fff1e | 2597 | } |
2598 | } | |
f231e867 | 2599 | } |
2deebecd | 2600 | |
e8775320 | 2601 | if (defined('MDL_PERF') || (!empty($CFG->perfdebug) and $CFG->perfdebug > 7)) { |
2602 | if (defined('MDL_PERFTOLOG') && !function_exists('register_shutdown_function')) { | |
2603 | $perf = get_performance_info(); | |
2604 | error_log("PERF: " . $perf['txt']); | |
2605 | } | |
f231e867 | 2606 | } |
3eb89b99 | 2607 | |
e8775320 | 2608 | $encodedurl = preg_replace("/\&(?![a-zA-Z0-9#]{1,8};)/", "&", $url); |
2609 | $encodedurl = preg_replace('/^.*href="([^"]*)".*$/', "\\1", clean_text('<a href="'.$encodedurl.'" />')); | |
3eb89b99 | 2610 | |
ae96b517 | 2611 | if ($delay == 0 && !$debugdisableredirect && !headers_sent()) { |
2612 | //302 might not work for POST requests, 303 is ignored by obsolete clients. | |
2613 | @header($_SERVER['SERVER_PROTOCOL'] . ' 303 See Other'); | |
2614 | @header('Location: '.$url); | |
5e39d7aa | 2615 | echo bootstrap_renderer::plain_redirect_message($encodedurl); |
2616 | exit; | |
ae96b517 | 2617 | } |
b7009474 | 2618 | |
ae96b517 | 2619 | // Include a redirect message, even with a HTTP redirect, because that is recommended practice. |
78946b9b | 2620 | $PAGE->set_pagelayout('embedded'); // No header and footer needed |
317f94b0 | 2621 | $CFG->docroot = false; // to prevent the link to moodle docs from being displayed on redirect page. |
ae96b517 | 2622 | echo $OUTPUT->redirect_message($encodedurl, $message, $delay, $debugdisableredirect); |
2623 | exit; | |
9fa49e22 | 2624 | } |
2625 | ||
d48b00b4 | 2626 | /** |
2627 | * Given an email address, this function will return an obfuscated version of it | |
2628 | * | |
89dcb99d | 2629 | * @param string $email The email address to obfuscate |
449611af | 2630 | * @return string The obfuscated email address |
d48b00b4 | 2631 | */ |
2632 | function obfuscate_email($email) { | |
2633 | ||
43373804 | 2634 | $i = 0; |
2635 | $length = strlen($email); | |
b0ccd3fb | 2636 | $obfuscated = ''; |
43373804 | 2637 | while ($i < $length) { |
fa801e8c | 2638 | if (rand(0,2) && $email{$i}!='@') { //MDL-20619 some browsers have problems unobfuscating @ |
43373804 | 2639 | $obfuscated.='%'.dechex(ord($email{$i})); |
2640 | } else { | |
2641 | $obfuscated.=$email{$i}; | |
2642 | } | |
2643 | $i++; | |
2644 | } | |
2645 | return $obfuscated; | |
2646 | } | |
2647 | ||
d48b00b4 | 2648 | /** |
2649 | * This function takes some text and replaces about half of the characters | |
2650 | * with HTML entity equivalents. Return string is obviously longer. | |
2651 | * | |
89dcb99d | 2652 | * @param string $plaintext The text to be obfuscated |
449611af | 2653 | * @return string The obfuscated text |
d48b00b4 | 2654 | */ |
43373804 | 2655 | function obfuscate_text($plaintext) { |
772e78be | 2656 | |
43373804 | 2657 | $i=0; |
2658 | $length = strlen($plaintext); | |
b0ccd3fb | 2659 | $obfuscated=''; |
2b09e377 | 2660 | $prev_obfuscated = false; |
43373804 | 2661 | while ($i < $length) { |
2b09e377 | 2662 | $c = ord($plaintext{$i}); |
2663 | $numerical = ($c >= ord('0')) && ($c <= ord('9')); | |
2664 | if ($prev_obfuscated and $numerical ) { | |
87d32352 | 2665 | $obfuscated.='&#'.ord($plaintext{$i}).';'; |
2b09e377 | 2666 | } else if (rand(0,2)) { |
87d32352 | 2667 | $obfuscated.='&#'.ord($plaintext{$i}).';'; |
2b09e377 | 2668 | $prev_obfuscated = true; |
43373804 | 2669 | } else { |
2670 | $obfuscated.=$plaintext{$i}; | |
2b09e377 | 2671 | $prev_obfuscated = false; |
43373804 | 2672 | } |
2b09e377 | 2673 | $i++; |
43373804 | 2674 | } |
2675 | return $obfuscated; | |
2676 | } | |
2677 | ||
d48b00b4 | 2678 | /** |
89dcb99d | 2679 | * This function uses the {@link obfuscate_email()} and {@link obfuscate_text()} |
2680 | * to generate a fully obfuscated email link, ready to use. | |
d48b00b4 | 2681 | * |
89dcb99d | 2682 | * @param string $email The email address to display |
fa9f6bf6 | 2683 | * @param string $label The text to displayed as hyperlink to $email |
89dcb99d | 2684 | * @param boolean $dimmed If true then use css class 'dimmed' for hyperlink |
449611af | 2685 | * @return string The obfuscated mailto link |
d48b00b4 | 2686 | */ |
b0ccd3fb | 2687 | function obfuscate_mailto($email, $label='', $dimmed=false) { |
43373804 | 2688 | |
2689 | if (empty($label)) { | |
2690 | $label = $email; | |
2691 | } | |
cadb96f2 | 2692 | if ($dimmed) { |
2693 | $title = get_string('emaildisable'); | |
2694 | $dimmed = ' class="dimmed"'; | |
2695 | } else { | |
2696 | $title = ''; | |
2697 | $dimmed = ''; | |
2698 | } | |
ab9f24ad | 2699 | return sprintf("<a href=\"%s:%s\" $dimmed title=\"$title\">%s</a>", |
cadb96f2 | 2700 | obfuscate_text('mailto'), obfuscate_email($email), |
2701 | obfuscate_text($label)); | |
43373804 | 2702 | } |
2703 | ||
d48b00b4 | 2704 | /** |
2705 | * This function is used to rebuild the <nolink> tag because some formats (PLAIN and WIKI) | |
2706 | * will transform it to html entities | |
2707 | * | |
89dcb99d | 2708 | * @param string $text Text to search for nolink tag in |
2709 | * @return string | |
d48b00b4 | 2710 | */ |
ab892a4f | 2711 | function rebuildnolinktag($text) { |
ab9f24ad | 2712 | |
ab892a4f | 2713 | $text = preg_replace('/<(\/*nolink)>/i','<$1>',$text); |
2714 | ||
2715 | return $text; | |
2716 | } | |
2717 | ||
1695b680 | 2718 | /** |
4fe2250a | 2719 | * Prints a maintenance message from $CFG->maintenance_message or default if empty |
49c8c8d2 | 2720 | * @return void |
1695b680 | 2721 | */ |
4fe2250a | 2722 | function print_maintenance_message() { |
3c159385 | 2723 | global $CFG, $SITE, $PAGE, $OUTPUT; |
a2b3f884 | 2724 | |
ad5d5997 | 2725 | $PAGE->set_pagetype('maintenance-message'); |
78946b9b | 2726 | $PAGE->set_pagelayout('maintenance'); |
de6d81e6 | 2727 | $PAGE->set_title(strip_tags($SITE->fullname)); |
2728 | $PAGE->set_heading($SITE->fullname); | |
2729 | echo $OUTPUT->header(); | |
3c159385 | 2730 | echo $OUTPUT->heading(get_string('sitemaintenance', 'admin')); |
4fe2250a | 2731 | if (isset($CFG->maintenance_message) and !html_is_blank($CFG->maintenance_message)) { |
ea85e1ee | 2732 | echo $OUTPUT->box_start('maintenance_message generalbox boxwidthwide boxaligncenter'); |
4fe2250a | 2733 | echo $CFG->maintenance_message; |
ea85e1ee | 2734 | echo $OUTPUT->box_end(); |
4fe2250a | 2735 | } |
7e0d6675 | 2736 | echo $OUTPUT->footer(); |
4fe2250a | 2737 | die; |
1695b680 | 2738 | } |
2739 | ||
5982740d | 2740 | /** |
2741 | * Adjust the list of allowed tags based on $CFG->allowobjectembed and user roles (admin) | |
449611af | 2742 | * |
2743 | * @global object | |
2744 | * @global string | |
2745 | * @return void | |
5982740d | 2746 | */ |
2747 | function adjust_allowed_tags() { | |
1695b680 | 2748 | |
5982740d | 2749 | global $CFG, $ALLOWED_TAGS; |
2750 | ||
62af9bf9 | 2751 | if (!empty($CFG->allowobjectembed)) { |
5982740d | 2752 | $ALLOWED_TAGS .= '<embed><object>'; |
2753 | } | |
2754 | } | |
f88ddd67 | 2755 | |
449611af | 2756 | /** |
2757 | * A class for tabs, Some code to print tabs | |
2758 | * | |
2759 | * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later | |
2760 | * @package moodlecore | |
2761 | */ | |
f88ddd67 | 2762 | class tabobject { |
449611af | 2763 | /** |
2764 | * @var string | |
2765 | */ | |
f88ddd67 | 2766 | var $id; |
2767 | var $link; | |
2768 | var $text; | |
449611af | 2769 | /** |
2770 | * @var bool | |
2771 | */ | |
748e0925 | 2772 | var $linkedwhenselected; |
f88ddd67 | 2773 | |
49c8c8d2 | 2774 | /** |
449611af | 2775 | * A constructor just because I like constructors |
49c8c8d2 | 2776 | * |
449611af | 2777 | * @param string $id |
2778 | * @param string $link | |
2779 | * @param string $text | |
2780 | * @param string $title | |
2781 | * @param bool $linkedwhenselected | |
2782 | */ | |
748e0925 | 2783 | function tabobject ($id, $link='', $text='', $title='', $linkedwhenselected=false) { |
f88ddd67 | 2784 | $this->id = $id; |
2785 | $this->link = $link; | |
2786 | $this->text = $text; | |
e7cb8f3e | 2787 | $this->title = $title ? $title : $text; |
748e0925 | 2788 | $this->linkedwhenselected = $linkedwhenselected; |
f88ddd67 | 2789 | } |
f88ddd67 | 2790 | } |
2791 | ||
2792 | ||
2793 | ||
2794 | /** | |
0b4f88a6 | 2795 | * Returns a string containing a nested list, suitable for formatting into tabs with CSS. |
f88ddd67 | 2796 | * |
449611af | 2797 | * @global object |
f88ddd67 | 2798 | * @param array $tabrows An array of rows where each row is an array of tab objects |
0b4f88a6 | 2799 | * @param string $selected The id of the selected tab (whatever row it's on) |
2800 | * @param array $inactive An array of ids of inactive tabs that are not selectable. | |
2801 | * @param array $activated An array of ids of other tabs that are currently activated | |
449611af | 2802 | * @param bool $return If true output is returned rather then echo'd |
2803 | **/ | |
0b4f88a6 | 2804 | function print_tabs($tabrows, $selected=NULL, $inactive=NULL, $activated=NULL, $return=false) { |
f88ddd67 | 2805 | global $CFG; |
2806 | ||
f88ddd67 | 2807 | /// $inactive must be an array |
2808 | if (!is_array($inactive)) { | |
2809 | $inactive = array(); | |
2810 | } | |
c06c8492 | 2811 | |
0b4f88a6 | 2812 | /// $activated must be an array |
2813 | if (!is_array($activated)) { | |
2814 | $activated = array(); | |
3e8506b6 | 2815 | } |
f88ddd67 | 2816 | |
6b25a26e | 2817 | /// Convert the tab rows into a tree that's easier to process |
0b4f88a6 | 2818 | if (!$tree = convert_tabrows_to_tree($tabrows, $selected, $inactive, $activated)) { |
6b25a26e | 2819 | return false; |
2820 | } | |
a2b3f884 | 2821 | |
6b25a26e | 2822 | /// Print out the current tree of tabs (this function is recursive) |
84e3d2cc | 2823 | |
6b25a26e | 2824 | $output = convert_tree_to_html($tree); |
2825 | ||
2826 | $output = "\n\n".'<div class="tabtree">'.$output.'</div><div class="clearer"> </div>'."\n\n"; | |
2827 | ||
2828 | /// We're done! | |
2829 | ||
2830 | if ($return) { | |
2831 | return $output; | |
2832 | } | |
2833 | echo $output; | |
2834 | } | |
031f8487 | 2835 | |
449611af | 2836 | /** |
2837 | * Converts a nested array tree into HTML ul:li [recursive] | |
2838 | * | |
2839 | * @param array $tree A tree array to convert | |
fa9f6bf6 | 2840 | * @param int $row Used in identifying the iteration level and in ul classes |
449611af | 2841 | * @return string HTML structure |
2842 | */ | |
6b25a26e | 2843 | function convert_tree_to_html($tree, $row=0) { |
a2b3f884 | 2844 | |
6b25a26e | 2845 | $str = "\n".'<ul class="tabrow'.$row.'">'."\n"; |
a2b3f884 | 2846 | |
36e8c122 | 2847 | $first = true; |
2848 | $count = count($tree); | |
2849 | ||
6b25a26e | 2850 | foreach ($tree as $tab) { |
36e8c122 | 2851 | $count--; // countdown to zero |
2852 | ||
d11a1daa | 2853 | $liclass = ''; |
2854 | ||
65c8c793 | 2855 | if ($first && ($count == 0)) { // Just one in the row |
d11a1daa | 2856 | $liclass = 'first last'; |
65c8c793 | 2857 | $first = false; |
2858 | } else if ($first) { | |
d11a1daa | 2859 | $liclass = 'first'; |
36e8c122 | 2860 | $first = false; |
2861 | } else if ($count == 0) { | |
d11a1daa | 2862 | $liclass = 'last'; |
36e8c122 | 2863 | } |
a2b3f884 | 2864 | |
d11a1daa | 2865 | if ((empty($tab->subtree)) && (!empty($tab->selected))) { |
2866 | $liclass .= (empty($liclass)) ? 'onerow' : ' onerow'; | |
6b25a26e | 2867 | } |
f88ddd67 | 2868 | |
d1731fda | 2869 | if ($tab->inactive || $tab->active || $tab->selected) { |
84e3d2cc | 2870 | if ($tab->selected) { |
d11a1daa | 2871 | $liclass .= (empty($liclass)) ? 'here selected' : ' here selected'; |
84e3d2cc | 2872 | } else if ($tab->active) { |
d11a1daa | 2873 | $liclass .= (empty($liclass)) ? 'here active' : ' here active'; |
2874 | } | |
2875 | } | |
2876 | ||
2877 | $str .= (!empty($liclass)) ? '<li class="'.$liclass.'">' : '<li>'; | |
2878 | ||
2879 | if ($tab->inactive || $tab->active || ($tab->selected && !$tab->linkedwhenselected)) { | |
ca3b6e52 | 2880 | // The a tag is used for styling |
2881 | $str .= '<a class="nolink"><span>'.$tab->text.'</span></a>'; | |
6b25a26e | 2882 | } else { |
d11a1daa | 2883 | $str .= '<a href="'.$tab->link.'" title="'.$tab->title.'"><span>'.$tab->text.'</span></a>'; |
f88ddd67 | 2884 | } |
a2b3f884 | 2885 | |
84e3d2cc | 2886 | if (!empty($tab->subtree)) { |
6b25a26e | 2887 | $str .= convert_tree_to_html($tab->subtree, $row+1); |
36e8c122 | 2888 | } else if ($tab->selected) { |
d11a1daa | 2889 | $str .= '<div class="tabrow'.($row+1).' empty"> </div>'."\n"; |
6b25a26e | 2890 | } |
2891 | ||
a04c3b55 | 2892 | $str .= ' </li>'."\n"; |
f88ddd67 | 2893 | } |
6b25a26e | 2894 | $str .= '</ul>'."\n"; |
a2b3f884 | 2895 | |
6b25a26e | 2896 | return $str; |
2897 | } | |
2898 | ||
449611af | 2899 | /** |
2900 | * Convert nested tabrows to a nested array | |
2901 | * | |
2902 | * @param array $tabrows A [nested] array of tab row objects | |
2903 | * @param string $selected The tabrow to select (by id) | |
2904 | * @param array $inactive An array of tabrow id's to make inactive | |
2905 | * @param array $activated An array of tabrow id's to make active | |
49c8c8d2 | 2906 | * @return array The nested array |
449611af | 2907 | */ |
0b4f88a6 | 2908 | function convert_tabrows_to_tree($tabrows, $selected, $inactive, $activated) { |
6b25a26e | 2909 | |
2910 | /// Work backwards through the rows (bottom to top) collecting the tree as we go. | |
2911 | ||
2912 | $tabrows = array_reverse($tabrows); | |
2913 | ||
2914 | $subtree = array(); | |
2915 | ||
2916 | foreach ($tabrows as $row) { | |
2917 | $tree = array(); | |
2918 | ||
2919 | foreach ($row as $tab) { | |
f522d310 | 2920 | $tab->inactive = in_array((string)$tab->id, $inactive); |
2921 | $tab->active = in_array((string)$tab->id, $activated); | |
2922 | $tab->selected = (string)$tab->id == $selected; | |
6b25a26e | 2923 | |
2924 | if ($tab->active || $tab->selected) { | |
2925 | if ($subtree) { | |
2926 | $tab->subtree = $subtree; | |
2927 | } | |
2928 | } | |
2929 | $tree[] = $tab; | |
2930 | } | |
2931 | $subtree = $tree; | |
027b0fe7 | 2932 | } |
6b25a26e | 2933 | |
3eb89b99 | 2934 | return $subtree; |
f88ddd67 | 2935 | } |
2936 | ||
faf75fe7 | 2937 | /** |
449611af | 2938 | * Returns the Moodle Docs URL in the users language |
2939 | * | |
2940 | * @global object | |
faf75fe7 | 2941 | * @param string $path the end of the URL. |
449611af | 2942 | * @return string The MoodleDocs URL in the user's language. for example {@link http://docs.moodle.org/en/ http://docs.moodle.org/en/$path} |
faf75fe7 | 2943 | */ |
2944 | function get_docs_url($path) { | |
2945 | global $CFG; | |
3a915b06 | 2946 | return $CFG->docroot . '/' . current_language() . '/' . $path; |
faf75fe7 | 2947 | } |
2948 | ||
b2118095 | 2949 | |
fa989c38 | 2950 | /** |
449611af | 2951 | * Standard Debugging Function |
2952 | * | |
7eb0b60a | 2953 | * Returns true if the current site debugging settings are equal or above specified level. |
4bd0ddea | 2954 | * If passed a parameter it will emit a debugging notice similar to trigger_error(). The |
2955 | * routing of notices is controlled by $CFG->debugdisplay | |
fa989c38 | 2956 | * eg use like this: |
2957 | * | |
7eb0b60a | 2958 | * 1) debugging('a normal debug notice'); |
2959 | * 2) debugging('something really picky', DEBUG_ALL); | |
fa9f6bf6 | 2960 | * 3) debugging('annoying debug message only for developers', DEBUG_DEVELOPER); |
4bd0ddea | 2961 | * 4) if (debugging()) { perform extra debugging operations (do not use print or echo) } |
2962 | * | |
2963 | * In code blocks controlled by debugging() (such as example 4) | |
2964 | * any output should be routed via debugging() itself, or the lower-level | |
2965 | * trigger_error() or error_log(). Using echo or print will break XHTML | |
2966 | * JS and HTTP headers. | |
2967 | * | |
2e9b772f | 2968 | * It is also possible to define NO_DEBUG_DISPLAY which redirects the message to error_log. |
fa989c38 | 2969 | * |
449611af | 2970 | * @uses DEBUG_NORMAL |
2fca6e0b | 2971 | * @param string $message a message to print |
fa989c38 | 2972 | * @param int $level the level at which this debugging statement should show |
eee5d9bb | 2973 | * @param array $backtrace use different backtrace |
fa989c38 | 2974 | * @return bool |
2975 | */ | |
34a2777c | 2976 | function debugging($message = '', $level = DEBUG_NORMAL, $backtrace = null) { |
4f19b365 | 2977 | global $CFG, $UNITTEST; |
fa989c38 | 2978 | |
34a2777c | 2979 | if (empty($CFG->debug) || $CFG->debug < $level) { |
fa989c38 | 2980 | return false; |
2981 | } | |
2982 | ||
34a2777c | 2983 | if (!isset($CFG->debugdisplay)) { |
2984 | $CFG->debugdisplay = ini_get_bool('display_errors'); | |
795a08ad | 2985 | } |
2986 | ||
34a2777c | 2987 | if ($message) { |
2988 | if (!$backtrace) { | |
2989 | $backtrace = debug_backtrace(); | |
251387d0 | 2990 | } |
34a2777c | 2991 | $from = format_backtrace($backtrace, CLI_SCRIPT); |
2e9b772f PS |
2992 | if (!empty($UNITTEST->running)) { |
2993 | // When the unit tests are running, any call to trigger_error | |
2994 | // is intercepted by the test framework and reported as an exception. | |
2995 | // Therefore, we cannot use trigger_error during unit tests. | |
2996 | // At the same time I do not think we should just discard those messages, | |
2997 | // so displaying them on-screen seems like the only option. (MDL-20398) | |
2998 | echo '<div class="notifytiny">' . $message . $from . '</div>'; | |
2999 | ||
3000 | } else if (NO_DEBUG_DISPLAY) { | |
3001 | // script does not want any errors or debugging in output, | |
3002 | // we send the info to error log instead | |
3003 | error_log('Debugging: ' . $message . $from); | |
3004 | ||
3005 | } else if ($CFG->debugdisplay) { | |
34a2777c | 3006 | if (!defined('DEBUGGING_PRINTED')) { |
3007 | define('DEBUGGING_PRINTED', 1); // indicates we have printed something | |
251387d0 | 3008 | } |
dc203659 | 3009 | echo '<div class="notifytiny">' . $message . $from . '</div>'; |
2e9b772f | 3010 | |
34a2777c | 3011 | } else { |
3012 | trigger_error($message . $from, E_USER_NOTICE); | |
251387d0 | 3013 | } |
251387d0 | 3014 | } |
34a2777c | 3015 | return true; |
251387d0 | 3016 | } |
3017 | ||
4d0ccfa7 | 3018 | /** |
3019 | * Outputs a HTML comment to the browser. This is used for those hard-to-debug | |
3020 | * pages that use bits from many different files in very confusing ways (e.g. blocks). | |
449611af | 3021 | * |
3022 | * <code>print_location_comment(__FILE__, __LINE__);</code> | |
3023 | * | |
4d0ccfa7 | 3024 | * @param string $file |
3025 | * @param integer $line | |
3026 | * @param boolean $return Whether to return or print the comment | |
449611af | 3027 | * @return string|void Void unless true given as third parameter |
4d0ccfa7 | 3028 | */ |
3029 | function print_location_comment($file, $line, $return = false) | |
3030 | { | |
3031 | if ($return) { | |
3032 | return "<!-- $file at line $line -->\n"; | |
3033 | } else { | |
3034 | echo "<!-- $file at line $line -->\n"; | |
3035 | } | |
3036 | } | |
f145c248 | 3037 | |
82b4da86 | 3038 | |
f1af7aaa | 3039 | /** |
b7009474 | 3040 | * @return boolean true if the current language is right-to-left (Hebrew, Arabic etc) |
b2118095 | 3041 | */ |
3042 | function right_to_left() { | |
e372f4c7 | 3043 | return (get_string('thisdirection', 'langconfig') === 'rtl'); |
b2118095 | 3044 | } |
3045 | ||
3046 | ||
3047 | /** | |
3048 | * Returns swapped left<=>right if in RTL environment. | |
3049 | * part of RTL support | |
3050 | * | |
3051 | * @param string $align align to check | |
3052 | * @return string | |
3053 | */ | |
3054 | function fix_align_rtl($align) { | |
c5659019 | 3055 | if (!right_to_left()) { |
f1af7aaa | 3056 | return $align; |
b2118095 | 3057 | } |
c5659019 | 3058 | if ($align=='left') { return 'right'; } |
3059 | if ($align=='right') { return 'left'; } | |
3060 | return $align; | |
b2118095 | 3061 | } |
3062 | ||
3063 | ||
ee9beb53 | 3064 | /** |
3065 | * Returns true if the page is displayed in a popup window. | |
3066 | * Gets the information from the URL parameter inpopup. | |
3067 | * | |
fa9f6bf6 | 3068 | * @todo Use a central function to create the popup calls all over Moodle and |
449611af | 3069 | * In the moment only works with resources and probably questions. |
ee9beb53 | 3070 | * |
449611af | 3071 | * @return boolean |
ee9beb53 | 3072 | */ |
f7c926ee | 3073 | function is_in_popup() { |
ee9beb53 | 3074 | $inpopup = optional_param('inpopup', '', PARAM_BOOL); |
c5659019 | 3075 | |
ee9beb53 | 3076 | return ($inpopup); |
3077 | } | |
27bd819b | 3078 | |
c9ec505b | 3079 | /** |
3080 | * To use this class. | |
3081 | * - construct | |
3082 | * - call create (or use the 3rd param to the constructor) | |
3083 | * - call update or update_full repeatedly | |
449611af | 3084 | * |
3085 | * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later | |
3086 | * @package moodlecore | |
c9ec505b | 3087 | */ |
a6553373 | 3088 | class progress_bar { |
fd4faf98 | 3089 | /** @var string html id */ |
a6553373 | 3090 | private $html_id; |
fd4faf98 | 3091 | /** @var int */ |
a6553373 | 3092 | private $percent; |
fd4faf98 | 3093 | /** @var int */ |
a6553373 | 3094 | private $width; |
fd4faf98 | 3095 | /** @var int */ |
a6553373 | 3096 | private $lastcall; |
fd4faf98 | 3097 | /** @var int */ |
a6553373 | 3098 | private $time_start; |
3099 | private $minimum_time = 2; //min time between updates. | |
449611af | 3100 | /** |
fa9f6bf6 | 3101 | * Constructor |
449611af | 3102 | * |
3103 | * @param string $html_id | |
3104 | * @param int $width | |
3105 | * @param bool $autostart Default to false | |
3106 | */ | |
fd4faf98 | 3107 | public function __construct($html_id = '', $width = 500, $autostart = false){ |
3108 | if (!empty($html_id)) { | |
3109 | $this->html_id = $html_id; | |
3110 | } else { | |
3111 | $this->html_id = uniqid(); | |
3112 | } | |
a6553373 | 3113 | $this->width = $width; |
3114 | $this->restart(); | |
3115 | if($autostart){ | |
3116 | $this->create(); | |
3117 | } | |
3118 | } | |
a6553373 | 3119 | /** |
449611af | 3120 | * Create a new progress bar, this function will output html. |
49c8c8d2 | 3121 | * |
449611af | 3122 | * @return void Echo's output |
a6553373 | 3123 | */ |
fd4faf98 | 3124 | public function create(){ |
a6553373 | 3125 | flush(); |
3126 | $this->lastcall->pt = 0; | |
3127 | $this->lastcall->time = microtime(true); | |
3316fe24 | 3128 | if (CLI_SCRIPT) { |
3129 | return; // temporary solution for cli scripts | |
3130 | } | |
a6553373 | 3131 | $htmlcode = <<<EOT |
a6553373 | 3132 | <div style="text-align:center;width:{$this->width}px;clear:both;padding:0;margin:0 auto;"> |
3133 | <h2 id="status_{$this->html_id}" style="text-align: center;margin:0 auto"></h2> | |
3134 | <p id="time_{$this->html_id}"></p> | |
3135 | <div id="bar_{$this->html_id}" style="border-style:solid;border-width:1px;width:500px;height:50px;"> | |
3136 | <div id="progress_{$this->html_id}" | |
fd4faf98 | 3137 | style="text-align:center;background:#FFCC66;width:4px;border:1px |
a6553373 | 3138 | solid gray;height:38px; padding-top:10px;"> <span id="pt_{$this->html_id}"></span> |
3139 | </div> | |
3140 | </div> | |
3141 | </div> | |
3142 | EOT; | |
3143 | echo $htmlcode; | |
3144 | flush(); | |
3145 | } | |
449611af | 3146 | /** |
3147 | * Update the progress bar | |
3148 | * | |
3149 | * @param int $percent from 1-100 | |
3150 | * @param string $msg | |
3151 | * @param mixed $es | |
3152 | * @return void Echo's output | |
3153 | */ | |
fd4faf98 | 3154 | private function _update($percent, $msg, $es){ |
e1524dbe | 3155 | global $PAGE; |
a6553373 | 3156 | if(empty($this->time_start)){ |
3157 | $this->time_start = microtime(true); | |
3158< |