Commit | Line | Data |
---|---|---|
449611af | 1 | <?php |
b868d3d9 | 2 | // This file is part of Moodle - http://moodle.org/ |
3 | // | |
449611af | 4 | // Moodle is free software: you can redistribute it and/or modify |
5 | // it under the terms of the GNU General Public License as published by | |
6 | // the Free Software Foundation, either version 3 of the License, or | |
7 | // (at your option) any later version. | |
8 | // | |
9 | // Moodle is distributed in the hope that it will be useful, | |
10 | // but WITHOUT ANY WARRANTY; without even the implied warranty of | |
11 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the | |
12 | // GNU General Public License for more details. | |
b868d3d9 | 13 | // |
449611af | 14 | // You should have received a copy of the GNU General Public License |
15 | // along with Moodle. If not, see <http://www.gnu.org/licenses/>. | |
f9903ed0 | 16 | |
7cf1c7bd | 17 | /** |
18 | * Library of functions for web output | |
19 | * | |
20 | * Library of all general-purpose Moodle PHP functions and constants | |
21 | * that produce HTML output | |
22 | * | |
23 | * Other main libraries: | |
24 | * - datalib.php - functions that access the database. | |
25 | * - moodlelib.php - general-purpose Moodle functions. | |
449611af | 26 | * |
78bfb562 PS |
27 | * @package core |
28 | * @subpackage lib | |
29 | * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com} | |
30 | * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later | |
7cf1c7bd | 31 | */ |
772e78be | 32 | |
78bfb562 PS |
33 | defined('MOODLE_INTERNAL') || die(); |
34 | ||
2e1d38db | 35 | // Constants. |
0095d5cd | 36 | |
2e1d38db | 37 | // Define text formatting types ... eventually we can add Wiki, BBcode etc. |
7cf1c7bd | 38 | |
39 | /** | |
2e1d38db | 40 | * Does all sorts of transformations and filtering. |
7cf1c7bd | 41 | */ |
2e1d38db | 42 | define('FORMAT_MOODLE', '0'); |
7cf1c7bd | 43 | |
44 | /** | |
2e1d38db | 45 | * Plain HTML (with some tags stripped). |
7cf1c7bd | 46 | */ |
2e1d38db | 47 | define('FORMAT_HTML', '1'); |
7cf1c7bd | 48 | |
49 | /** | |
2e1d38db | 50 | * Plain text (even tags are printed in full). |
7cf1c7bd | 51 | */ |
2e1d38db | 52 | define('FORMAT_PLAIN', '2'); |
7cf1c7bd | 53 | |
54 | /** | |
2e1d38db | 55 | * Wiki-formatted text. |
6a6495ff | 56 | * Deprecated: left here just to note that '3' is not used (at the moment) |
57 | * and to catch any latent wiki-like text (which generates an error) | |
2e1d38db | 58 | * @deprecated since 2005! |
7cf1c7bd | 59 | */ |
2e1d38db | 60 | define('FORMAT_WIKI', '3'); |
7cf1c7bd | 61 | |
62 | /** | |
63 | * Markdown-formatted text http://daringfireball.net/projects/markdown/ | |
64 | */ | |
2e1d38db | 65 | define('FORMAT_MARKDOWN', '4'); |
0095d5cd | 66 | |
827b2f7a | 67 | /** |
2e1d38db | 68 | * A moodle_url comparison using this flag will return true if the base URLs match, params are ignored. |
827b2f7a | 69 | */ |
70 | define('URL_MATCH_BASE', 0); | |
2e1d38db | 71 | |
827b2f7a | 72 | /** |
2e1d38db | 73 | * A moodle_url comparison using this flag will return true if the base URLs match and the params of url1 are part of url2. |
827b2f7a | 74 | */ |
75 | define('URL_MATCH_PARAMS', 1); | |
2e1d38db | 76 | |
827b2f7a | 77 | /** |
2e1d38db | 78 | * A moodle_url comparison using this flag will return true if the two URLs are identical, except for the order of the params. |
827b2f7a | 79 | */ |
80 | define('URL_MATCH_EXACT', 2); | |
7cf1c7bd | 81 | |
2e1d38db | 82 | // Functions. |
0095d5cd | 83 | |
7cf1c7bd | 84 | /** |
2e1d38db | 85 | * Add quotes to HTML characters. |
7cf1c7bd | 86 | * |
87 | * Returns $var with HTML characters (like "<", ">", etc.) properly quoted. | |
88661686 | 88 | * Related function {@link p()} simply prints the output of this function. |
7cf1c7bd | 89 | * |
90 | * @param string $var the string potentially containing HTML characters | |
91 | * @return string | |
92 | */ | |
328ac306 | 93 | function s($var) { |
d4a42ff4 | 94 | |
328ac306 | 95 | if ($var === false) { |
63e554d0 | 96 | return '0'; |
3662bce5 | 97 | } |
d4a42ff4 | 98 | |
b16b1f86 | 99 | return preg_replace('/&#(\d+|x[0-9a-f]+);/i', '&#$1;', |
100 | htmlspecialchars($var, ENT_QUOTES | ENT_HTML401 | ENT_SUBSTITUTE)); | |
f9903ed0 | 101 | } |
102 | ||
7cf1c7bd | 103 | /** |
2e1d38db | 104 | * Add quotes to HTML characters. |
7cf1c7bd | 105 | * |
d48b00b4 | 106 | * Prints $var with HTML characters (like "<", ">", etc.) properly quoted. |
88661686 | 107 | * This function simply calls & displays {@link s()}. |
449611af | 108 | * @see s() |
109 | * | |
7cf1c7bd | 110 | * @param string $var the string potentially containing HTML characters |
111 | * @return string | |
112 | */ | |
88661686 TM |
113 | function p($var) { |
114 | echo s($var); | |
f9903ed0 | 115 | } |
116 | ||
0d1cd0ea | 117 | /** |
118 | * Does proper javascript quoting. | |
449611af | 119 | * |
5ce73257 | 120 | * Do not use addslashes anymore, because it does not work when magic_quotes_sybase is enabled. |
121 | * | |
449611af | 122 | * @param mixed $var String, Array, or Object to add slashes to |
0d1cd0ea | 123 | * @return mixed quoted result |
124 | */ | |
125 | function addslashes_js($var) { | |
126 | if (is_string($var)) { | |
127 | $var = str_replace('\\', '\\\\', $var); | |
128 | $var = str_replace(array('\'', '"', "\n", "\r", "\0"), array('\\\'', '\\"', '\\n', '\\r', '\\0'), $var); | |
2e1d38db | 129 | $var = str_replace('</', '<\/', $var); // XHTML compliance. |
0d1cd0ea | 130 | } else if (is_array($var)) { |
131 | $var = array_map('addslashes_js', $var); | |
132 | } else if (is_object($var)) { | |
133 | $a = get_object_vars($var); | |
2e1d38db SH |
134 | foreach ($a as $key => $value) { |
135 | $a[$key] = addslashes_js($value); | |
0d1cd0ea | 136 | } |
137 | $var = (object)$a; | |
138 | } | |
139 | return $var; | |
140 | } | |
7cf1c7bd | 141 | |
7cf1c7bd | 142 | /** |
2e1d38db | 143 | * Remove query string from url. |
7cf1c7bd | 144 | * |
2e1d38db | 145 | * Takes in a URL and returns it without the querystring portion. |
7cf1c7bd | 146 | * |
2e1d38db SH |
147 | * @param string $url the url which may have a query string attached. |
148 | * @return string The remaining URL. | |
7cf1c7bd | 149 | */ |
2e1d38db | 150 | function strip_querystring($url) { |
f9903ed0 | 151 | |
b9b8ab69 | 152 | if ($commapos = strpos($url, '?')) { |
153 | return substr($url, 0, $commapos); | |
154 | } else { | |
155 | return $url; | |
156 | } | |
f9903ed0 | 157 | } |
158 | ||
7cf1c7bd | 159 | /** |
160 | * Returns the name of the current script, WITH the querystring portion. | |
449611af | 161 | * |
162 | * This function is necessary because PHP_SELF and REQUEST_URI and SCRIPT_NAME | |
7cf1c7bd | 163 | * return different things depending on a lot of things like your OS, Web |
164 | * server, and the way PHP is compiled (ie. as a CGI, module, ISAPI, etc.) | |
d48b00b4 | 165 | * <b>NOTE:</b> This function returns false if the global variables needed are not set. |
166 | * | |
2e1d38db | 167 | * @return mixed String or false if the global variables needed are not set. |
7cf1c7bd | 168 | */ |
b03fc392 | 169 | function me() { |
170 | global $ME; | |
171 | return $ME; | |
f9903ed0 | 172 | } |
173 | ||
7cf1c7bd | 174 | /** |
f0202ae9 | 175 | * Guesses the full URL of the current script. |
449611af | 176 | * |
f0202ae9 PS |
177 | * This function is using $PAGE->url, but may fall back to $FULLME which |
178 | * is constructed from PHP_SELF and REQUEST_URI or SCRIPT_NAME | |
449611af | 179 | * |
f0202ae9 | 180 | * @return mixed full page URL string or false if unknown |
7cf1c7bd | 181 | */ |
f9903ed0 | 182 | function qualified_me() { |
f0202ae9 PS |
183 | global $FULLME, $PAGE, $CFG; |
184 | ||
185 | if (isset($PAGE) and $PAGE->has_set_url()) { | |
2e1d38db | 186 | // This is the only recommended way to find out current page. |
f0202ae9 PS |
187 | return $PAGE->url->out(false); |
188 | ||
189 | } else { | |
190 | if ($FULLME === null) { | |
2e1d38db | 191 | // CLI script most probably. |
f0202ae9 PS |
192 | return false; |
193 | } | |
194 | if (!empty($CFG->sslproxy)) { | |
2e1d38db | 195 | // Return only https links when using SSL proxy. |
f0202ae9 PS |
196 | return preg_replace('/^http:/', 'https:', $FULLME, 1); |
197 | } else { | |
198 | return $FULLME; | |
199 | } | |
200 | } | |
f9903ed0 | 201 | } |
202 | ||
1e31f118 TB |
203 | /** |
204 | * Determines whether or not the Moodle site is being served over HTTPS. | |
205 | * | |
672f4836 | 206 | * This is done simply by checking the value of $CFG->wwwroot, which seems |
1e31f118 TB |
207 | * to be the only reliable method. |
208 | * | |
209 | * @return boolean True if site is served over HTTPS, false otherwise. | |
210 | */ | |
211 | function is_https() { | |
212 | global $CFG; | |
213 | ||
672f4836 | 214 | return (strpos($CFG->wwwroot, 'https://') === 0); |
1e31f118 TB |
215 | } |
216 | ||
dcee0b94 SL |
217 | /** |
218 | * Returns the cleaned local URL of the HTTP_REFERER less the URL query string parameters if required. | |
219 | * | |
220 | * @param bool $stripquery if true, also removes the query part of the url. | |
221 | * @return string The resulting referer or empty string. | |
222 | */ | |
223 | function get_local_referer($stripquery = true) { | |
224 | if (isset($_SERVER['HTTP_REFERER'])) { | |
225 | $referer = clean_param($_SERVER['HTTP_REFERER'], PARAM_LOCALURL); | |
226 | if ($stripquery) { | |
227 | return strip_querystring($referer); | |
228 | } else { | |
229 | return $referer; | |
230 | } | |
231 | } else { | |
232 | return ''; | |
233 | } | |
234 | } | |
235 | ||
360e503e | 236 | /** |
237 | * Class for creating and manipulating urls. | |
84e3d2cc | 238 | * |
449611af | 239 | * It can be used in moodle pages where config.php has been included without any further includes. |
240 | * | |
49c8c8d2 | 241 | * It is useful for manipulating urls with long lists of params. |
fa9f6bf6 | 242 | * One situation where it will be useful is a page which links to itself to perform various actions |
449611af | 243 | * and / or to process form data. A moodle_url object : |
49c8c8d2 | 244 | * can be created for a page to refer to itself with all the proper get params being passed from page call to |
245 | * page call and methods can be used to output a url including all the params, optionally adding and overriding | |
449611af | 246 | * params and can also be used to |
247 | * - output the url without any get params | |
49c8c8d2 | 248 | * - and output the params as hidden fields to be output within a form |
449611af | 249 | * |
2e1d38db | 250 | * @copyright 2007 jamiesensei |
728ebac7 | 251 | * @link http://docs.moodle.org/dev/lib/weblib.php_moodle_url See short write up here |
449611af | 252 | * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later |
2e1d38db | 253 | * @package core |
360e503e | 254 | */ |
255 | class moodle_url { | |
2e1d38db | 256 | |
449611af | 257 | /** |
a6855934 PS |
258 | * Scheme, ex.: http, https |
259 | * @var string | |
260 | */ | |
261 | protected $scheme = ''; | |
2e1d38db | 262 | |
a6855934 | 263 | /** |
2e1d38db | 264 | * Hostname. |
449611af | 265 | * @var string |
449611af | 266 | */ |
7ceb61d8 | 267 | protected $host = ''; |
2e1d38db | 268 | |
a6855934 | 269 | /** |
2e1d38db SH |
270 | * Port number, empty means default 80 or 443 in case of http. |
271 | * @var int | |
a6855934 | 272 | */ |
7ceb61d8 | 273 | protected $port = ''; |
2e1d38db | 274 | |
a6855934 | 275 | /** |
2e1d38db | 276 | * Username for http auth. |
a6855934 PS |
277 | * @var string |
278 | */ | |
7ceb61d8 | 279 | protected $user = ''; |
2e1d38db | 280 | |
a6855934 | 281 | /** |
2e1d38db | 282 | * Password for http auth. |
a6855934 PS |
283 | * @var string |
284 | */ | |
7ceb61d8 | 285 | protected $pass = ''; |
2e1d38db | 286 | |
a6855934 | 287 | /** |
2e1d38db | 288 | * Script path. |
a6855934 PS |
289 | * @var string |
290 | */ | |
7ceb61d8 | 291 | protected $path = ''; |
2e1d38db | 292 | |
7dff555f | 293 | /** |
2e1d38db | 294 | * Optional slash argument value. |
7dff555f PS |
295 | * @var string |
296 | */ | |
297 | protected $slashargument = ''; | |
2e1d38db | 298 | |
449611af | 299 | /** |
2e1d38db | 300 | * Anchor, may be also empty, null means none. |
a6855934 PS |
301 | * @var string |
302 | */ | |
303 | protected $anchor = null; | |
2e1d38db | 304 | |
a6855934 | 305 | /** |
2e1d38db | 306 | * Url parameters as associative array. |
49c8c8d2 | 307 | * @var array |
449611af | 308 | */ |
2e1d38db | 309 | protected $params = array(); |
84e3d2cc | 310 | |
360e503e | 311 | /** |
a6855934 | 312 | * Create new instance of moodle_url. |
84e3d2cc | 313 | * |
a6855934 PS |
314 | * @param moodle_url|string $url - moodle_url means make a copy of another |
315 | * moodle_url and change parameters, string means full url or shortened | |
316 | * form (ex.: '/course/view.php'). It is strongly encouraged to not include | |
2284c694 TH |
317 | * query string because it may result in double encoded values. Use the |
318 | * $params instead. For admin URLs, just use /admin/script.php, this | |
319 | * class takes care of the $CFG->admin issue. | |
a6855934 | 320 | * @param array $params these params override current params or add new |
61b223a6 | 321 | * @param string $anchor The anchor to use as part of the URL if there is one. |
2e1d38db | 322 | * @throws moodle_exception |
360e503e | 323 | */ |
61b223a6 | 324 | public function __construct($url, array $params = null, $anchor = null) { |
a6855934 | 325 | global $CFG; |
2b3fcef9 | 326 | |
a6855934 | 327 | if ($url instanceof moodle_url) { |
75781f87 | 328 | $this->scheme = $url->scheme; |
329 | $this->host = $url->host; | |
330 | $this->port = $url->port; | |
331 | $this->user = $url->user; | |
332 | $this->pass = $url->pass; | |
ad52c04f | 333 | $this->path = $url->path; |
7dff555f | 334 | $this->slashargument = $url->slashargument; |
75781f87 | 335 | $this->params = $url->params; |
a6855934 | 336 | $this->anchor = $url->anchor; |
2b3fcef9 | 337 | |
75781f87 | 338 | } else { |
2e1d38db | 339 | // Detect if anchor used. |
a6855934 PS |
340 | $apos = strpos($url, '#'); |
341 | if ($apos !== false) { | |
342 | $anchor = substr($url, $apos); | |
343 | $anchor = ltrim($anchor, '#'); | |
344 | $this->set_anchor($anchor); | |
345 | $url = substr($url, 0, $apos); | |
360e503e | 346 | } |
a6855934 | 347 | |
2e1d38db | 348 | // Normalise shortened form of our url ex.: '/course/view.php'. |
a6855934 | 349 | if (strpos($url, '/') === 0) { |
a6855934 | 350 | $url = $CFG->wwwroot.$url; |
75781f87 | 351 | } |
a6855934 | 352 | |
a6855934 PS |
353 | if ($CFG->admin !== 'admin') { |
354 | if (strpos($url, "$CFG->wwwroot/admin/") === 0) { | |
355 | $url = str_replace("$CFG->wwwroot/admin/", "$CFG->wwwroot/$CFG->admin/", $url); | |
356 | } | |
357 | } | |
358 | ||
2e1d38db | 359 | // Parse the $url. |
a6855934 PS |
360 | $parts = parse_url($url); |
361 | if ($parts === false) { | |
75781f87 | 362 | throw new moodle_exception('invalidurl'); |
360e503e | 363 | } |
7ceb61d8 | 364 | if (isset($parts['query'])) { |
2e1d38db | 365 | // Note: the values may not be correctly decoded, url parameters should be always passed as array. |
24a905f9 | 366 | parse_str(str_replace('&', '&', $parts['query']), $this->params); |
360e503e | 367 | } |
368 | unset($parts['query']); | |
7ceb61d8 | 369 | foreach ($parts as $key => $value) { |
360e503e | 370 | $this->$key = $value; |
371 | } | |
7dff555f | 372 | |
2e1d38db | 373 | // Detect slashargument value from path - we do not support directory names ending with .php. |
7dff555f PS |
374 | $pos = strpos($this->path, '.php/'); |
375 | if ($pos !== false) { | |
376 | $this->slashargument = substr($this->path, $pos + 4); | |
377 | $this->path = substr($this->path, 0, $pos + 4); | |
378 | } | |
360e503e | 379 | } |
2b3fcef9 | 380 | |
75781f87 | 381 | $this->params($params); |
61b223a6 SH |
382 | if ($anchor !== null) { |
383 | $this->anchor = (string)$anchor; | |
384 | } | |
84e3d2cc | 385 | } |
7ceb61d8 | 386 | |
360e503e | 387 | /** |
2b3fcef9 | 388 | * Add an array of params to the params for this url. |
449611af | 389 | * |
390 | * The added params override existing ones if they have the same name. | |
360e503e | 391 | * |
f8065dd2 | 392 | * @param array $params Defaults to null. If null then returns all params. |
449611af | 393 | * @return array Array of Params for url. |
2e1d38db | 394 | * @throws coding_exception |
360e503e | 395 | */ |
2b3fcef9 PS |
396 | public function params(array $params = null) { |
397 | $params = (array)$params; | |
398 | ||
2e1d38db | 399 | foreach ($params as $key => $value) { |
2b3fcef9 | 400 | if (is_int($key)) { |
d8ae33a9 | 401 | throw new coding_exception('Url parameters can not have numeric keys!'); |
2b3fcef9 | 402 | } |
27d6ab57 | 403 | if (!is_string($value)) { |
404 | if (is_array($value)) { | |
405 | throw new coding_exception('Url parameters values can not be arrays!'); | |
406 | } | |
407 | if (is_object($value) and !method_exists($value, '__toString')) { | |
408 | throw new coding_exception('Url parameters values can not be objects, unless __toString() is defined!'); | |
409 | } | |
2b3fcef9 PS |
410 | } |
411 | $this->params[$key] = (string)$value; | |
c1f41c59 | 412 | } |
2b3fcef9 | 413 | return $this->params; |
360e503e | 414 | } |
84e3d2cc | 415 | |
360e503e | 416 | /** |
49c8c8d2 | 417 | * Remove all params if no arguments passed. |
418 | * Remove selected params if arguments are passed. | |
449611af | 419 | * |
420 | * Can be called as either remove_params('param1', 'param2') | |
75781f87 | 421 | * or remove_params(array('param1', 'param2')). |
360e503e | 422 | * |
2e1d38db | 423 | * @param string[]|string $params,... either an array of param names, or 1..n string params to remove as args. |
2b3fcef9 | 424 | * @return array url parameters |
360e503e | 425 | */ |
2b3fcef9 | 426 | public function remove_params($params = null) { |
75781f87 | 427 | if (!is_array($params)) { |
428 | $params = func_get_args(); | |
429 | } | |
430 | foreach ($params as $param) { | |
2b3fcef9 | 431 | unset($this->params[$param]); |
360e503e | 432 | } |
2b3fcef9 PS |
433 | return $this->params; |
434 | } | |
435 | ||
436 | /** | |
2e1d38db SH |
437 | * Remove all url parameters. |
438 | * | |
439 | * @todo remove the unused param. | |
440 | * @param array $params Unused param | |
2b3fcef9 PS |
441 | * @return void |
442 | */ | |
443 | public function remove_all_params($params = null) { | |
444 | $this->params = array(); | |
7dff555f | 445 | $this->slashargument = ''; |
360e503e | 446 | } |
447 | ||
448 | /** | |
2b3fcef9 | 449 | * Add a param to the params for this url. |
449611af | 450 | * |
2b3fcef9 | 451 | * The added param overrides existing one if they have the same name. |
360e503e | 452 | * |
453 | * @param string $paramname name | |
2b3fcef9 PS |
454 | * @param string $newvalue Param value. If new value specified current value is overriden or parameter is added |
455 | * @return mixed string parameter value, null if parameter does not exist | |
360e503e | 456 | */ |
2b3fcef9 PS |
457 | public function param($paramname, $newvalue = '') { |
458 | if (func_num_args() > 1) { | |
2e1d38db SH |
459 | // Set new value. |
460 | $this->params(array($paramname => $newvalue)); | |
2b3fcef9 PS |
461 | } |
462 | if (isset($this->params[$paramname])) { | |
5762b36e | 463 | return $this->params[$paramname]; |
cf615522 | 464 | } else { |
465 | return null; | |
c1f41c59 | 466 | } |
360e503e | 467 | } |
468 | ||
2b3fcef9 PS |
469 | /** |
470 | * Merges parameters and validates them | |
2e1d38db | 471 | * |
2b3fcef9 PS |
472 | * @param array $overrideparams |
473 | * @return array merged parameters | |
2e1d38db | 474 | * @throws coding_exception |
2b3fcef9 PS |
475 | */ |
476 | protected function merge_overrideparams(array $overrideparams = null) { | |
477 | $overrideparams = (array)$overrideparams; | |
478 | $params = $this->params; | |
2e1d38db | 479 | foreach ($overrideparams as $key => $value) { |
2b3fcef9 | 480 | if (is_int($key)) { |
cdefaa86 | 481 | throw new coding_exception('Overridden parameters can not have numeric keys!'); |
2b3fcef9 PS |
482 | } |
483 | if (is_array($value)) { | |
cdefaa86 | 484 | throw new coding_exception('Overridden parameters values can not be arrays!'); |
2b3fcef9 PS |
485 | } |
486 | if (is_object($value) and !method_exists($value, '__toString')) { | |
cdefaa86 | 487 | throw new coding_exception('Overridden parameters values can not be objects, unless __toString() is defined!'); |
2b3fcef9 PS |
488 | } |
489 | $params[$key] = (string)$value; | |
490 | } | |
491 | return $params; | |
492 | } | |
493 | ||
7ceb61d8 | 494 | /** |
495 | * Get the params as as a query string. | |
2e1d38db | 496 | * |
8afba50b | 497 | * This method should not be used outside of this method. |
449611af | 498 | * |
2e1d38db | 499 | * @param bool $escaped Use & as params separator instead of plain & |
7ceb61d8 | 500 | * @param array $overrideparams params to add to the output params, these |
501 | * override existing ones with the same name. | |
502 | * @return string query string that can be added to a url. | |
503 | */ | |
8afba50b | 504 | public function get_query_string($escaped = true, array $overrideparams = null) { |
360e503e | 505 | $arr = array(); |
27d6ab57 | 506 | if ($overrideparams !== null) { |
507 | $params = $this->merge_overrideparams($overrideparams); | |
508 | } else { | |
509 | $params = $this->params; | |
510 | } | |
7ceb61d8 | 511 | foreach ($params as $key => $val) { |
ab82976f TH |
512 | if (is_array($val)) { |
513 | foreach ($val as $index => $value) { | |
514 | $arr[] = rawurlencode($key.'['.$index.']')."=".rawurlencode($value); | |
515 | } | |
516 | } else { | |
5c8f6817 SH |
517 | if (isset($val) && $val !== '') { |
518 | $arr[] = rawurlencode($key)."=".rawurlencode($val); | |
519 | } else { | |
520 | $arr[] = rawurlencode($key); | |
521 | } | |
ab82976f | 522 | } |
360e503e | 523 | } |
c7f5e16a | 524 | if ($escaped) { |
525 | return implode('&', $arr); | |
526 | } else { | |
527 | return implode('&', $arr); | |
528 | } | |
360e503e | 529 | } |
7ceb61d8 | 530 | |
2b3fcef9 PS |
531 | /** |
532 | * Shortcut for printing of encoded URL. | |
2e1d38db | 533 | * |
2b3fcef9 PS |
534 | * @return string |
535 | */ | |
536 | public function __toString() { | |
b9bc2019 | 537 | return $this->out(true); |
2b3fcef9 PS |
538 | } |
539 | ||
360e503e | 540 | /** |
2e1d38db | 541 | * Output url. |
84e3d2cc | 542 | * |
c7f5e16a | 543 | * If you use the returned URL in HTML code, you want the escaped ampersands. If you use |
544 | * the returned URL in HTTP headers, you want $escaped=false. | |
545 | * | |
2e1d38db | 546 | * @param bool $escaped Use & as params separator instead of plain & |
b9bc2019 | 547 | * @param array $overrideparams params to add to the output url, these override existing ones with the same name. |
449611af | 548 | * @return string Resulting URL |
360e503e | 549 | */ |
b9bc2019 | 550 | public function out($escaped = true, array $overrideparams = null) { |
2ab797c9 BH |
551 | |
552 | global $CFG; | |
553 | ||
554 | if (!is_bool($escaped)) { | |
555 | debugging('Escape parameter must be of type boolean, '.gettype($escaped).' given instead.'); | |
556 | } | |
557 | ||
558 | $url = $this; | |
559 | ||
560 | // Allow url's to be rewritten by a plugin. | |
561 | if (isset($CFG->urlrewriteclass) && !isset($CFG->upgraderunning)) { | |
562 | $class = $CFG->urlrewriteclass; | |
563 | $pluginurl = $class::url_rewrite($url); | |
564 | if ($pluginurl instanceof moodle_url) { | |
565 | $url = $pluginurl; | |
566 | } | |
567 | } | |
568 | ||
569 | return $url->raw_out($escaped, $overrideparams); | |
570 | ||
571 | } | |
572 | ||
573 | /** | |
574 | * Output url without any rewrites | |
575 | * | |
576 | * This is identical in signature and use to out() but doesn't call the rewrite handler. | |
577 | * | |
578 | * @param bool $escaped Use & as params separator instead of plain & | |
579 | * @param array $overrideparams params to add to the output url, these override existing ones with the same name. | |
580 | * @return string Resulting URL | |
581 | */ | |
582 | public function raw_out($escaped = true, array $overrideparams = null) { | |
b9bc2019 PS |
583 | if (!is_bool($escaped)) { |
584 | debugging('Escape parameter must be of type boolean, '.gettype($escaped).' given instead.'); | |
585 | } | |
586 | ||
7dff555f | 587 | $uri = $this->out_omit_querystring().$this->slashargument; |
244a32c6 | 588 | |
8afba50b | 589 | $querystring = $this->get_query_string($escaped, $overrideparams); |
7dff555f | 590 | if ($querystring !== '') { |
eb788065 PS |
591 | $uri .= '?' . $querystring; |
592 | } | |
593 | if (!is_null($this->anchor)) { | |
594 | $uri .= '#'.$this->anchor; | |
360e503e | 595 | } |
a6855934 | 596 | |
84e3d2cc | 597 | return $uri; |
360e503e | 598 | } |
7ceb61d8 | 599 | |
eb788065 PS |
600 | /** |
601 | * Returns url without parameters, everything before '?'. | |
5c6ee6ec DM |
602 | * |
603 | * @param bool $includeanchor if {@link self::anchor} is defined, should it be returned? | |
eb788065 PS |
604 | * @return string |
605 | */ | |
5c6ee6ec DM |
606 | public function out_omit_querystring($includeanchor = false) { |
607 | ||
eb788065 PS |
608 | $uri = $this->scheme ? $this->scheme.':'.((strtolower($this->scheme) == 'mailto') ? '':'//'): ''; |
609 | $uri .= $this->user ? $this->user.($this->pass? ':'.$this->pass:'').'@':''; | |
610 | $uri .= $this->host ? $this->host : ''; | |
611 | $uri .= $this->port ? ':'.$this->port : ''; | |
612 | $uri .= $this->path ? $this->path : ''; | |
5c6ee6ec DM |
613 | if ($includeanchor and !is_null($this->anchor)) { |
614 | $uri .= '#' . $this->anchor; | |
615 | } | |
616 | ||
eb788065 | 617 | return $uri; |
b5d0cafc PS |
618 | } |
619 | ||
827b2f7a | 620 | /** |
2e1d38db SH |
621 | * Compares this moodle_url with another. |
622 | * | |
827b2f7a | 623 | * See documentation of constants for an explanation of the comparison flags. |
2e1d38db | 624 | * |
827b2f7a | 625 | * @param moodle_url $url The moodle_url object to compare |
626 | * @param int $matchtype The type of comparison (URL_MATCH_BASE, URL_MATCH_PARAMS, URL_MATCH_EXACT) | |
2e1d38db | 627 | * @return bool |
827b2f7a | 628 | */ |
629 | public function compare(moodle_url $url, $matchtype = URL_MATCH_EXACT) { | |
c705a24e | 630 | |
eb788065 PS |
631 | $baseself = $this->out_omit_querystring(); |
632 | $baseother = $url->out_omit_querystring(); | |
bf6c37c7 | 633 | |
2e1d38db SH |
634 | // Append index.php if there is no specific file. |
635 | if (substr($baseself, -1) == '/') { | |
bf6c37c7 | 636 | $baseself .= 'index.php'; |
637 | } | |
2e1d38db | 638 | if (substr($baseother, -1) == '/') { |
bf6c37c7 | 639 | $baseother .= 'index.php'; |
640 | } | |
641 | ||
2e1d38db | 642 | // Compare the two base URLs. |
bf6c37c7 | 643 | if ($baseself != $baseother) { |
827b2f7a | 644 | return false; |
645 | } | |
646 | ||
647 | if ($matchtype == URL_MATCH_BASE) { | |
648 | return true; | |
649 | } | |
650 | ||
651 | $urlparams = $url->params(); | |
652 | foreach ($this->params() as $param => $value) { | |
653 | if ($param == 'sesskey') { | |
654 | continue; | |
655 | } | |
656 | if (!array_key_exists($param, $urlparams) || $urlparams[$param] != $value) { | |
657 | return false; | |
658 | } | |
659 | } | |
660 | ||
661 | if ($matchtype == URL_MATCH_PARAMS) { | |
662 | return true; | |
663 | } | |
664 | ||
665 | foreach ($urlparams as $param => $value) { | |
666 | if ($param == 'sesskey') { | |
667 | continue; | |
668 | } | |
669 | if (!array_key_exists($param, $this->params()) || $this->param($param) != $value) { | |
670 | return false; | |
671 | } | |
672 | } | |
673 | ||
99151092 SH |
674 | if ($url->anchor !== $this->anchor) { |
675 | return false; | |
676 | } | |
677 | ||
827b2f7a | 678 | return true; |
679 | } | |
13b0b271 SH |
680 | |
681 | /** | |
682 | * Sets the anchor for the URI (the bit after the hash) | |
2e1d38db | 683 | * |
a6855934 | 684 | * @param string $anchor null means remove previous |
13b0b271 SH |
685 | */ |
686 | public function set_anchor($anchor) { | |
a6855934 | 687 | if (is_null($anchor)) { |
2e1d38db | 688 | // Remove. |
a6855934 PS |
689 | $this->anchor = null; |
690 | } else if ($anchor === '') { | |
2e1d38db | 691 | // Special case, used as empty link. |
a6855934 PS |
692 | $this->anchor = ''; |
693 | } else if (preg_match('|[a-zA-Z\_\:][a-zA-Z0-9\_\-\.\:]*|', $anchor)) { | |
2e1d38db | 694 | // Match the anchor against the NMTOKEN spec. |
a6855934 PS |
695 | $this->anchor = $anchor; |
696 | } else { | |
2e1d38db | 697 | // Bad luck, no valid anchor found. |
a6855934 | 698 | $this->anchor = null; |
13b0b271 SH |
699 | } |
700 | } | |
462065e8 BH |
701 | |
702 | /** | |
703 | * Sets the scheme for the URI (the bit before ://) | |
704 | * | |
705 | * @param string $scheme | |
706 | */ | |
707 | public function set_scheme($scheme) { | |
708 | // See http://www.ietf.org/rfc/rfc3986.txt part 3.1. | |
709 | if (preg_match('/^[a-zA-Z][a-zA-Z0-9+.-]*$/', $scheme)) { | |
710 | $this->scheme = $scheme; | |
711 | } else { | |
712 | throw new coding_exception('Bad URL scheme.'); | |
713 | } | |
714 | } | |
7dff555f | 715 | |
4e40406d | 716 | /** |
2e1d38db SH |
717 | * Sets the url slashargument value. |
718 | * | |
4e40406d PS |
719 | * @param string $path usually file path |
720 | * @param string $parameter name of page parameter if slasharguments not supported | |
721 | * @param bool $supported usually null, then it depends on $CFG->slasharguments, use true or false for other servers | |
722 | * @return void | |
723 | */ | |
2e1d38db | 724 | public function set_slashargument($path, $parameter = 'file', $supported = null) { |
4e40406d PS |
725 | global $CFG; |
726 | if (is_null($supported)) { | |
c95442b2 | 727 | $supported = !empty($CFG->slasharguments); |
4e40406d PS |
728 | } |
729 | ||
730 | if ($supported) { | |
731 | $parts = explode('/', $path); | |
732 | $parts = array_map('rawurlencode', $parts); | |
733 | $path = implode('/', $parts); | |
734 | $this->slashargument = $path; | |
735 | unset($this->params[$parameter]); | |
736 | ||
737 | } else { | |
738 | $this->slashargument = ''; | |
739 | $this->params[$parameter] = $path; | |
740 | } | |
741 | } | |
742 | ||
2e1d38db | 743 | // Static factory methods. |
7dff555f PS |
744 | |
745 | /** | |
acdb9177 | 746 | * General moodle file url. |
2e1d38db | 747 | * |
acdb9177 PS |
748 | * @param string $urlbase the script serving the file |
749 | * @param string $path | |
7dff555f PS |
750 | * @param bool $forcedownload |
751 | * @return moodle_url | |
752 | */ | |
f28ee49e | 753 | public static function make_file_url($urlbase, $path, $forcedownload = false) { |
7dff555f | 754 | $params = array(); |
7dff555f PS |
755 | if ($forcedownload) { |
756 | $params['forcedownload'] = 1; | |
757 | } | |
4e40406d PS |
758 | $url = new moodle_url($urlbase, $params); |
759 | $url->set_slashargument($path); | |
4e40406d | 760 | return $url; |
7dff555f PS |
761 | } |
762 | ||
763 | /** | |
764 | * Factory method for creation of url pointing to plugin file. | |
2e1d38db | 765 | * |
7dff555f PS |
766 | * Please note this method can be used only from the plugins to |
767 | * create urls of own files, it must not be used outside of plugins! | |
2e1d38db | 768 | * |
7dff555f | 769 | * @param int $contextid |
f28ee49e | 770 | * @param string $component |
7dff555f PS |
771 | * @param string $area |
772 | * @param int $itemid | |
773 | * @param string $pathname | |
774 | * @param string $filename | |
775 | * @param bool $forcedownload | |
26e778d1 JL |
776 | * @param mixed $includetoken Whether to use a user token when displaying this group image. |
777 | * True indicates to generate a token for current user, and integer value indicates to generate a token for the | |
778 | * user whose id is the value indicated. | |
883f6555 AN |
779 | * If the group picture is included in an e-mail or some other location where the audience is a specific |
780 | * user who will not be logged in when viewing, then we use a token to authenticate the user. | |
7dff555f PS |
781 | * @return moodle_url |
782 | */ | |
2e1d38db | 783 | public static function make_pluginfile_url($contextid, $component, $area, $itemid, $pathname, $filename, |
883f6555 AN |
784 | $forcedownload = false, $includetoken = false) { |
785 | global $CFG, $USER; | |
786 | ||
787 | $path = []; | |
788 | ||
789 | if ($includetoken) { | |
790 | $urlbase = "$CFG->wwwroot/tokenpluginfile.php"; | |
26e778d1 JL |
791 | $userid = $includetoken === true ? $USER->id : $includetoken; |
792 | $token = get_user_key('core_files', $userid); | |
883f6555 AN |
793 | if ($CFG->slasharguments) { |
794 | $path[] = $token; | |
795 | } | |
f28ee49e | 796 | } else { |
883f6555 AN |
797 | $urlbase = "$CFG->wwwroot/pluginfile.php"; |
798 | } | |
799 | $path[] = $contextid; | |
800 | $path[] = $component; | |
801 | $path[] = $area; | |
802 | ||
803 | if ($itemid !== null) { | |
804 | $path[] = $itemid; | |
f28ee49e | 805 | } |
883f6555 AN |
806 | |
807 | $path = "/" . implode('/', $path) . "{$pathname}{$filename}"; | |
808 | ||
809 | $url = self::make_file_url($urlbase, $path, $forcedownload, $includetoken); | |
810 | if ($includetoken && empty($CFG->slasharguments)) { | |
811 | $url->param('token', $token); | |
812 | } | |
813 | return $url; | |
7dff555f PS |
814 | } |
815 | ||
da1be050 JL |
816 | /** |
817 | * Factory method for creation of url pointing to plugin file. | |
818 | * This method is the same that make_pluginfile_url but pointing to the webservice pluginfile.php script. | |
819 | * It should be used only in external functions. | |
820 | * | |
821 | * @since 2.8 | |
822 | * @param int $contextid | |
823 | * @param string $component | |
824 | * @param string $area | |
825 | * @param int $itemid | |
826 | * @param string $pathname | |
827 | * @param string $filename | |
828 | * @param bool $forcedownload | |
829 | * @return moodle_url | |
830 | */ | |
831 | public static function make_webservice_pluginfile_url($contextid, $component, $area, $itemid, $pathname, $filename, | |
832 | $forcedownload = false) { | |
833 | global $CFG; | |
672f4836 | 834 | $urlbase = "$CFG->wwwroot/webservice/pluginfile.php"; |
da1be050 JL |
835 | if ($itemid === null) { |
836 | return self::make_file_url($urlbase, "/$contextid/$component/$area".$pathname.$filename, $forcedownload); | |
837 | } else { | |
838 | return self::make_file_url($urlbase, "/$contextid/$component/$area/$itemid".$pathname.$filename, $forcedownload); | |
839 | } | |
840 | } | |
841 | ||
7dff555f | 842 | /** |
2e1d38db SH |
843 | * Factory method for creation of url pointing to draft file of current user. |
844 | * | |
37416d5d | 845 | * @param int $draftid draft item id |
7dff555f PS |
846 | * @param string $pathname |
847 | * @param string $filename | |
848 | * @param bool $forcedownload | |
849 | * @return moodle_url | |
850 | */ | |
37416d5d | 851 | public static function make_draftfile_url($draftid, $pathname, $filename, $forcedownload = false) { |
7dff555f | 852 | global $CFG, $USER; |
672f4836 | 853 | $urlbase = "$CFG->wwwroot/draftfile.php"; |
b0c6dc1c | 854 | $context = context_user::instance($USER->id); |
7dff555f | 855 | |
37416d5d | 856 | return self::make_file_url($urlbase, "/$context->id/user/draft/$draftid".$pathname.$filename, $forcedownload); |
7dff555f | 857 | } |
ed77a56f PS |
858 | |
859 | /** | |
2e1d38db SH |
860 | * Factory method for creating of links to legacy course files. |
861 | * | |
ed77a56f PS |
862 | * @param int $courseid |
863 | * @param string $filepath | |
864 | * @param bool $forcedownload | |
865 | * @return moodle_url | |
866 | */ | |
f28ee49e | 867 | public static function make_legacyfile_url($courseid, $filepath, $forcedownload = false) { |
ed77a56f PS |
868 | global $CFG; |
869 | ||
acdb9177 PS |
870 | $urlbase = "$CFG->wwwroot/file.php"; |
871 | return self::make_file_url($urlbase, '/'.$courseid.'/'.$filepath, $forcedownload); | |
ed77a56f | 872 | } |
48ddc9bf DP |
873 | |
874 | /** | |
875 | * Returns URL a relative path from $CFG->wwwroot | |
876 | * | |
877 | * Can be used for passing around urls with the wwwroot stripped | |
878 | * | |
879 | * @param boolean $escaped Use & as params separator instead of plain & | |
880 | * @param array $overrideparams params to add to the output url, these override existing ones with the same name. | |
881 | * @return string Resulting URL | |
882 | * @throws coding_exception if called on a non-local url | |
883 | */ | |
884 | public function out_as_local_url($escaped = true, array $overrideparams = null) { | |
885 | global $CFG; | |
886 | ||
887 | $url = $this->out($escaped, $overrideparams); | |
72b181ba | 888 | |
672f4836 | 889 | // Url should be equal to wwwroot. If not then throw exception. |
72b181ba RT |
890 | if (($url === $CFG->wwwroot) || (strpos($url, $CFG->wwwroot.'/') === 0)) { |
891 | $localurl = substr($url, strlen($CFG->wwwroot)); | |
892 | return !empty($localurl) ? $localurl : ''; | |
72b181ba | 893 | } else { |
48ddc9bf DP |
894 | throw new coding_exception('out_as_local_url called on a non-local URL'); |
895 | } | |
48ddc9bf | 896 | } |
ffe4de97 | 897 | |
898 | /** | |
899 | * Returns the 'path' portion of a URL. For example, if the URL is | |
900 | * http://www.example.org:447/my/file/is/here.txt?really=1 then this will | |
901 | * return '/my/file/is/here.txt'. | |
902 | * | |
903 | * By default the path includes slash-arguments (for example, | |
904 | * '/myfile.php/extra/arguments') so it is what you would expect from a | |
905 | * URL path. If you don't want this behaviour, you can opt to exclude the | |
a3c17aed | 906 | * slash arguments. (Be careful: if the $CFG variable slasharguments is |
907 | * disabled, these URLs will have a different format and you may need to | |
908 | * look at the 'file' parameter too.) | |
ffe4de97 | 909 | * |
910 | * @param bool $includeslashargument If true, includes slash arguments | |
911 | * @return string Path of URL | |
912 | */ | |
913 | public function get_path($includeslashargument = true) { | |
914 | return $this->path . ($includeslashargument ? $this->slashargument : ''); | |
915 | } | |
a3c17aed | 916 | |
917 | /** | |
918 | * Returns a given parameter value from the URL. | |
919 | * | |
920 | * @param string $name Name of parameter | |
921 | * @return string Value of parameter or null if not set | |
922 | */ | |
923 | public function get_param($name) { | |
924 | if (array_key_exists($name, $this->params)) { | |
925 | return $this->params[$name]; | |
926 | } else { | |
927 | return null; | |
928 | } | |
929 | } | |
d06ffbdf SC |
930 | |
931 | /** | |
932 | * Returns the 'scheme' portion of a URL. For example, if the URL is | |
933 | * http://www.example.org:447/my/file/is/here.txt?really=1 then this will | |
934 | * return 'http' (without the colon). | |
935 | * | |
936 | * @return string Scheme of the URL. | |
937 | */ | |
938 | public function get_scheme() { | |
939 | return $this->scheme; | |
940 | } | |
941 | ||
942 | /** | |
943 | * Returns the 'host' portion of a URL. For example, if the URL is | |
944 | * http://www.example.org:447/my/file/is/here.txt?really=1 then this will | |
945 | * return 'www.example.org'. | |
946 | * | |
947 | * @return string Host of the URL. | |
948 | */ | |
949 | public function get_host() { | |
950 | return $this->host; | |
951 | } | |
952 | ||
953 | /** | |
954 | * Returns the 'port' portion of a URL. For example, if the URL is | |
955 | * http://www.example.org:447/my/file/is/here.txt?really=1 then this will | |
956 | * return '447'. | |
957 | * | |
958 | * @return string Port of the URL. | |
959 | */ | |
960 | public function get_port() { | |
961 | return $this->port; | |
962 | } | |
360e503e | 963 | } |
964 | ||
7cf1c7bd | 965 | /** |
966 | * Determine if there is data waiting to be processed from a form | |
967 | * | |
968 | * Used on most forms in Moodle to check for data | |
969 | * Returns the data as an object, if it's found. | |
970 | * This object can be used in foreach loops without | |
971 | * casting because it's cast to (array) automatically | |
772e78be | 972 | * |
9c0f063b | 973 | * Checks that submitted POST data exists and returns it as object. |
d48b00b4 | 974 | * |
9c0f063b | 975 | * @return mixed false or object |
7cf1c7bd | 976 | */ |
294ce987 | 977 | function data_submitted() { |
d48b00b4 | 978 | |
607809b3 | 979 | if (empty($_POST)) { |
36b4f985 | 980 | return false; |
981 | } else { | |
78fcdb5f | 982 | return (object)fix_utf8($_POST); |
36b4f985 | 983 | } |
984 | } | |
985 | ||
7cf1c7bd | 986 | /** |
d48b00b4 | 987 | * Given some normal text this function will break up any |
988 | * long words to a given size by inserting the given character | |
989 | * | |
6aaa17c7 | 990 | * It's multibyte savvy and doesn't change anything inside html tags. |
991 | * | |
7cf1c7bd | 992 | * @param string $string the string to be modified |
89dcb99d | 993 | * @param int $maxsize maximum length of the string to be returned |
7cf1c7bd | 994 | * @param string $cutchar the string used to represent word breaks |
995 | * @return string | |
996 | */ | |
4a5644e5 | 997 | function break_up_long_words($string, $maxsize=20, $cutchar=' ') { |
a2b3f884 | 998 | |
2e1d38db | 999 | // First of all, save all the tags inside the text to skip them. |
6aaa17c7 | 1000 | $tags = array(); |
2e1d38db | 1001 | filter_save_tags($string, $tags); |
5b07d990 | 1002 | |
2e1d38db | 1003 | // Process the string adding the cut when necessary. |
4a5644e5 | 1004 | $output = ''; |
2f1e464a | 1005 | $length = core_text::strlen($string); |
4a5644e5 | 1006 | $wordlength = 0; |
1007 | ||
1008 | for ($i=0; $i<$length; $i++) { | |
2f1e464a | 1009 | $char = core_text::substr($string, $i, 1); |
6aaa17c7 | 1010 | if ($char == ' ' or $char == "\t" or $char == "\n" or $char == "\r" or $char == "<" or $char == ">") { |
4a5644e5 | 1011 | $wordlength = 0; |
1012 | } else { | |
1013 | $wordlength++; | |
1014 | if ($wordlength > $maxsize) { | |
1015 | $output .= $cutchar; | |
1016 | $wordlength = 0; | |
1017 | } | |
1018 | } | |
1019 | $output .= $char; | |
1020 | } | |
6aaa17c7 | 1021 | |
2e1d38db | 1022 | // Finally load the tags back again. |
6aaa17c7 | 1023 | if (!empty($tags)) { |
1024 | $output = str_replace(array_keys($tags), $tags, $output); | |
1025 | } | |
1026 | ||
4a5644e5 | 1027 | return $output; |
1028 | } | |
1029 | ||
de6d81e6 | 1030 | /** |
b166403f | 1031 | * Try and close the current window using JavaScript, either immediately, or after a delay. |
449611af | 1032 | * |
1033 | * Echo's out the resulting XHTML & javascript | |
1034 | * | |
b166403f | 1035 | * @param integer $delay a delay in seconds before closing the window. Default 0. |
1036 | * @param boolean $reloadopener if true, we will see if this window was a pop-up, and try | |
1037 | * to reload the parent window before this one closes. | |
08396bb2 | 1038 | */ |
b166403f | 1039 | function close_window($delay = 0, $reloadopener = false) { |
f6794ace | 1040 | global $PAGE, $OUTPUT; |
08396bb2 | 1041 | |
c13a5e71 | 1042 | if (!$PAGE->headerprinted) { |
de6d81e6 | 1043 | $PAGE->set_title(get_string('closewindow')); |
1044 | echo $OUTPUT->header(); | |
b166403f | 1045 | } else { |
f6794ace | 1046 | $OUTPUT->container_end_all(false); |
b166403f | 1047 | } |
1048 | ||
1049 | if ($reloadopener) { | |
87113602 TH |
1050 | // Trigger the reload immediately, even if the reload is after a delay. |
1051 | $PAGE->requires->js_function_call('window.opener.location.reload', array(true)); | |
b166403f | 1052 | } |
87113602 | 1053 | $OUTPUT->notification(get_string('windowclosing'), 'notifysuccess'); |
cf615522 | 1054 | |
87113602 | 1055 | $PAGE->requires->js_function_call('close_window', array(new stdClass()), false, $delay); |
b166403f | 1056 | |
7e0d6675 | 1057 | echo $OUTPUT->footer(); |
b166403f | 1058 | exit; |
1059 | } | |
08396bb2 | 1060 | |
28fbce88 | 1061 | /** |
2e1d38db SH |
1062 | * Returns a string containing a link to the user documentation for the current page. |
1063 | * | |
1064 | * Also contains an icon by default. Shown to teachers and admin only. | |
28fbce88 | 1065 | * |
28fbce88 | 1066 | * @param string $text The text to be displayed for the link |
28fbce88 | 1067 | * @return string The link to user documentation for this current page |
1068 | */ | |
8ae8bf8a | 1069 | function page_doc_link($text='') { |
06a72e01 SH |
1070 | global $OUTPUT, $PAGE; |
1071 | $path = page_get_doc_link_path($PAGE); | |
1072 | if (!$path) { | |
1073 | return ''; | |
1074 | } | |
1075 | return $OUTPUT->doc_link($path, $text); | |
1076 | } | |
1077 | ||
1078 | /** | |
1079 | * Returns the path to use when constructing a link to the docs. | |
1080 | * | |
5bcfd504 | 1081 | * @since Moodle 2.5.1 2.6 |
06a72e01 SH |
1082 | * @param moodle_page $page |
1083 | * @return string | |
1084 | */ | |
1085 | function page_get_doc_link_path(moodle_page $page) { | |
1086 | global $CFG; | |
28fbce88 | 1087 | |
1088 | if (empty($CFG->docroot) || during_initial_install()) { | |
1089 | return ''; | |
1090 | } | |
06a72e01 | 1091 | if (!has_capability('moodle/site:doclinks', $page->context)) { |
28fbce88 | 1092 | return ''; |
1093 | } | |
1094 | ||
06a72e01 | 1095 | $path = $page->docspath; |
28fbce88 | 1096 | if (!$path) { |
1097 | return ''; | |
1098 | } | |
06a72e01 | 1099 | return $path; |
28fbce88 | 1100 | } |
1101 | ||
14040797 | 1102 | |
d48b00b4 | 1103 | /** |
1104 | * Validates an email to make sure it makes sense. | |
1105 | * | |
1106 | * @param string $address The email address to validate. | |
1107 | * @return boolean | |
1108 | */ | |
89dcb99d | 1109 | function validate_email($address) { |
4b71e995 AL |
1110 | global $CFG; |
1111 | require_once($CFG->libdir.'/phpmailer/moodle_phpmailer.php'); | |
d48b00b4 | 1112 | |
4b71e995 | 1113 | return moodle_phpmailer::validateAddress($address); |
f9903ed0 | 1114 | } |
1115 | ||
690f358b | 1116 | /** |
1117 | * Extracts file argument either from file parameter or PATH_INFO | |
2e1d38db | 1118 | * |
11e7b506 | 1119 | * Note: $scriptname parameter is not needed anymore |
690f358b | 1120 | * |
690f358b | 1121 | * @return string file path (only safe characters) |
1122 | */ | |
11e7b506 | 1123 | function get_file_argument() { |
1124 | global $SCRIPT; | |
690f358b | 1125 | |
cdf8238b MS |
1126 | $relativepath = false; |
1127 | $hasforcedslashargs = false; | |
1128 | ||
1129 | if (isset($_SERVER['REQUEST_URI']) && !empty($_SERVER['REQUEST_URI'])) { | |
1130 | // Checks whether $_SERVER['REQUEST_URI'] contains '/pluginfile.php/' | |
1131 | // instead of '/pluginfile.php?', when serving a file from e.g. mod_imscp or mod_scorm. | |
1132 | if ((strpos($_SERVER['REQUEST_URI'], '/pluginfile.php/') !== false) | |
1133 | && isset($_SERVER['PATH_INFO']) && !empty($_SERVER['PATH_INFO'])) { | |
1134 | // Exclude edge cases like '/pluginfile.php/?file='. | |
1135 | $args = explode('/', ltrim($_SERVER['PATH_INFO'], '/')); | |
1136 | $hasforcedslashargs = (count($args) > 2); // Always at least: context, component and filearea. | |
1137 | } | |
1138 | } | |
1139 | if (!$hasforcedslashargs) { | |
1140 | $relativepath = optional_param('file', false, PARAM_PATH); | |
1141 | } | |
690f358b | 1142 | |
c281862a PS |
1143 | if ($relativepath !== false and $relativepath !== '') { |
1144 | return $relativepath; | |
1145 | } | |
1146 | $relativepath = false; | |
1147 | ||
2e1d38db | 1148 | // Then try extract file from the slasharguments. |
c281862a | 1149 | if (stripos($_SERVER['SERVER_SOFTWARE'], 'iis') !== false) { |
ce1cc198 | 1150 | // NOTE: IIS tends to convert all file paths to single byte DOS encoding, |
c281862a | 1151 | // we can not use other methods because they break unicode chars, |
ce1cc198 MS |
1152 | // the only ways are to use URL rewriting |
1153 | // OR | |
1154 | // to properly set the 'FastCGIUtf8ServerVariables' registry key. | |
c281862a | 1155 | if (isset($_SERVER['PATH_INFO']) and $_SERVER['PATH_INFO'] !== '') { |
2e1d38db | 1156 | // Check that PATH_INFO works == must not contain the script name. |
c281862a PS |
1157 | if (strpos($_SERVER['PATH_INFO'], $SCRIPT) === false) { |
1158 | $relativepath = clean_param(urldecode($_SERVER['PATH_INFO']), PARAM_PATH); | |
1159 | } | |
1160 | } | |
1161 | } else { | |
2e1d38db | 1162 | // All other apache-like servers depend on PATH_INFO. |
c281862a PS |
1163 | if (isset($_SERVER['PATH_INFO'])) { |
1164 | if (isset($_SERVER['SCRIPT_NAME']) and strpos($_SERVER['PATH_INFO'], $_SERVER['SCRIPT_NAME']) === 0) { | |
1165 | $relativepath = substr($_SERVER['PATH_INFO'], strlen($_SERVER['SCRIPT_NAME'])); | |
1166 | } else { | |
1167 | $relativepath = $_SERVER['PATH_INFO']; | |
1168 | } | |
1169 | $relativepath = clean_param($relativepath, PARAM_PATH); | |
690f358b | 1170 | } |
1171 | } | |
1172 | ||
690f358b | 1173 | return $relativepath; |
1174 | } | |
1175 | ||
d48b00b4 | 1176 | /** |
89dcb99d | 1177 | * Just returns an array of text formats suitable for a popup menu |
d48b00b4 | 1178 | * |
89dcb99d | 1179 | * @return array |
d48b00b4 | 1180 | */ |
0095d5cd | 1181 | function format_text_menu() { |
b0ccd3fb | 1182 | return array (FORMAT_MOODLE => get_string('formattext'), |
2e1d38db SH |
1183 | FORMAT_HTML => get_string('formathtml'), |
1184 | FORMAT_PLAIN => get_string('formatplain'), | |
1185 | FORMAT_MARKDOWN => get_string('formatmarkdown')); | |
0095d5cd | 1186 | } |
1187 | ||
d48b00b4 | 1188 | /** |
2e1d38db | 1189 | * Given text in a variety of format codings, this function returns the text as safe HTML. |
d48b00b4 | 1190 | * |
c5659019 | 1191 | * This function should mainly be used for long strings like posts, |
2e1d38db | 1192 | * answers, glossary items etc. For short strings {@link format_string()}. |
e8276c10 | 1193 | * |
367a75fa SH |
1194 | * <pre> |
1195 | * Options: | |
1196 | * trusted : If true the string won't be cleaned. Default false required noclean=true. | |
4b82c15c | 1197 | * noclean : If true the string won't be cleaned, unless $CFG->forceclean is set. Default false required trusted=true. |
367a75fa SH |
1198 | * nocache : If true the strign will not be cached and will be formatted every call. Default false. |
1199 | * filter : If true the string will be run through applicable filters as well. Default true. | |
1200 | * para : If true then the returned string will be wrapped in div tags. Default true. | |
1201 | * newlines : If true then lines newline breaks will be converted to HTML newline breaks. Default true. | |
1202 | * context : The context that will be used for filtering. | |
1203 | * overflowdiv : If set to true the formatted text will be encased in a div | |
1204 | * with the class no-overflow before being returned. Default false. | |
b031caf8 | 1205 | * allowid : If true then id attributes will not be removed, even when |
1206 | * using htmlpurifier. Default false. | |
bf997487 | 1207 | * blanktarget : If true all <a> tags will have target="_blank" added unless target is explicitly specified. |
367a75fa SH |
1208 | * </pre> |
1209 | * | |
449611af | 1210 | * @staticvar array $croncache |
89dcb99d | 1211 | * @param string $text The text to be formatted. This is raw text originally from user input. |
772e78be | 1212 | * @param int $format Identifier of the text format to be used |
35716b86 PS |
1213 | * [FORMAT_MOODLE, FORMAT_HTML, FORMAT_PLAIN, FORMAT_MARKDOWN] |
1214 | * @param object/array $options text formatting options | |
2e1d38db | 1215 | * @param int $courseiddonotuse deprecated course id, use context option instead |
89dcb99d | 1216 | * @return string |
d48b00b4 | 1217 | */ |
2e1d38db SH |
1218 | function format_text($text, $format = FORMAT_MOODLE, $options = null, $courseiddonotuse = null) { |
1219 | global $CFG, $DB, $PAGE; | |
795a08ad | 1220 | |
6e571603 | 1221 | if ($text === '' || is_null($text)) { |
2e1d38db SH |
1222 | // No need to do any filters and cleaning. |
1223 | return ''; | |
d53ca6ad | 1224 | } |
1bcb7eb5 | 1225 | |
2e1d38db SH |
1226 | // Detach object, we can not modify it. |
1227 | $options = (array)$options; | |
d53ca6ad | 1228 | |
35716b86 PS |
1229 | if (!isset($options['trusted'])) { |
1230 | $options['trusted'] = false; | |
7d8a3cb0 | 1231 | } |
35716b86 PS |
1232 | if (!isset($options['noclean'])) { |
1233 | if ($options['trusted'] and trusttext_active()) { | |
2e1d38db | 1234 | // No cleaning if text trusted and noclean not specified. |
35716b86 | 1235 | $options['noclean'] = true; |
cbc2b5df | 1236 | } else { |
35716b86 | 1237 | $options['noclean'] = false; |
cbc2b5df | 1238 | } |
e7a47153 | 1239 | } |
4b82c15c DM |
1240 | if (!empty($CFG->forceclean)) { |
1241 | // Whatever the caller claims, the admin wants all content cleaned anyway. | |
1242 | $options['noclean'] = false; | |
1243 | } | |
35716b86 PS |
1244 | if (!isset($options['nocache'])) { |
1245 | $options['nocache'] = false; | |
a17c57b5 | 1246 | } |
35716b86 PS |
1247 | if (!isset($options['filter'])) { |
1248 | $options['filter'] = true; | |
e7a47153 | 1249 | } |
35716b86 PS |
1250 | if (!isset($options['para'])) { |
1251 | $options['para'] = true; | |
e7a47153 | 1252 | } |
35716b86 PS |
1253 | if (!isset($options['newlines'])) { |
1254 | $options['newlines'] = true; | |
f0aa2fed | 1255 | } |
367a75fa SH |
1256 | if (!isset($options['overflowdiv'])) { |
1257 | $options['overflowdiv'] = false; | |
1258 | } | |
bf997487 | 1259 | $options['blanktarget'] = !empty($options['blanktarget']); |
35716b86 | 1260 | |
2e1d38db | 1261 | // Calculate best context. |
c3bc6f12 | 1262 | if (empty($CFG->version) or $CFG->version < 2013051400 or during_initial_install()) { |
2e1d38db | 1263 | // Do not filter anything during installation or before upgrade completes. |
8d39cbb3 | 1264 | $context = null; |
8d39cbb3 | 1265 | |
2e1d38db | 1266 | } else if (isset($options['context'])) { // First by explicit passed context option. |
35716b86 PS |
1267 | if (is_object($options['context'])) { |
1268 | $context = $options['context']; | |
1269 | } else { | |
d197ea43 | 1270 | $context = context::instance_by_id($options['context']); |
35716b86 | 1271 | } |
2e1d38db SH |
1272 | } else if ($courseiddonotuse) { |
1273 | // Legacy courseid. | |
1274 | $context = context_course::instance($courseiddonotuse); | |
35716b86 | 1275 | } else { |
2e1d38db | 1276 | // Fallback to $PAGE->context this may be problematic in CLI and other non-standard pages :-(. |
35716b86 | 1277 | $context = $PAGE->context; |
c4ae4fa1 | 1278 | } |
a751a4e5 | 1279 | |
f22b7397 | 1280 | if (!$context) { |
2e1d38db | 1281 | // Either install/upgrade or something has gone really wrong because context does not exist (yet?). |
f22b7397 PS |
1282 | $options['nocache'] = true; |
1283 | $options['filter'] = false; | |
1284 | } | |
1285 | ||
35716b86 | 1286 | if ($options['filter']) { |
ccc161f8 | 1287 | $filtermanager = filter_manager::instance(); |
6c5dbbb3 | 1288 | $filtermanager->setup_page_for_filters($PAGE, $context); // Setup global stuff filters may have. |
7d94679f TH |
1289 | $filteroptions = array( |
1290 | 'originalformat' => $format, | |
1291 | 'noclean' => $options['noclean'], | |
1292 | ); | |
ccc161f8 | 1293 | } else { |
1294 | $filtermanager = new null_filter_manager(); | |
7d94679f | 1295 | $filteroptions = array(); |
9e3f34d1 | 1296 | } |
ccc161f8 | 1297 | |
0095d5cd | 1298 | switch ($format) { |
73f8658c | 1299 | case FORMAT_HTML: |
35716b86 | 1300 | if (!$options['noclean']) { |
b031caf8 | 1301 | $text = clean_text($text, FORMAT_HTML, $options); |
9d40806d | 1302 | } |
7d94679f | 1303 | $text = $filtermanager->filter_text($text, $context, $filteroptions); |
73f8658c | 1304 | break; |
1305 | ||
6901fa79 | 1306 | case FORMAT_PLAIN: |
2e1d38db | 1307 | $text = s($text); // Cleans dangerous JS. |
ab892a4f | 1308 | $text = rebuildnolinktag($text); |
b0ccd3fb | 1309 | $text = str_replace(' ', ' ', $text); |
6901fa79 | 1310 | $text = nl2br($text); |
6901fa79 | 1311 | break; |
1312 | ||
d342c763 | 1313 | case FORMAT_WIKI: |
2e1d38db | 1314 | // This format is deprecated. |
572fe9ab | 1315 | $text = '<p>NOTICE: Wiki-like formatting has been removed from Moodle. You should not be seeing |
1316 | this message as all texts should have been converted to Markdown format instead. | |
ce50cc70 | 1317 | Please post a bug report to http://moodle.org/bugs with information about where you |
e7a47153 | 1318 | saw this message.</p>'.s($text); |
d342c763 | 1319 | break; |
1320 | ||
e7cdcd18 | 1321 | case FORMAT_MARKDOWN: |
1322 | $text = markdown_to_html($text); | |
35716b86 | 1323 | if (!$options['noclean']) { |
b031caf8 | 1324 | $text = clean_text($text, FORMAT_HTML, $options); |
9d40806d | 1325 | } |
7d94679f | 1326 | $text = $filtermanager->filter_text($text, $context, $filteroptions); |
e7cdcd18 | 1327 | break; |
1328 | ||
2e1d38db | 1329 | default: // FORMAT_MOODLE or anything else. |
84a8bedd | 1330 | $text = text_to_html($text, null, $options['para'], $options['newlines']); |
35716b86 | 1331 | if (!$options['noclean']) { |
b031caf8 | 1332 | $text = clean_text($text, FORMAT_HTML, $options); |
9d40806d | 1333 | } |
7d94679f | 1334 | $text = $filtermanager->filter_text($text, $context, $filteroptions); |
0095d5cd | 1335 | break; |
0095d5cd | 1336 | } |
893fe4b6 | 1337 | if ($options['filter']) { |
2e1d38db | 1338 | // At this point there should not be any draftfile links any more, |
893fe4b6 PS |
1339 | // this happens when developers forget to post process the text. |
1340 | // The only potential problem is that somebody might try to format | |
2e1d38db | 1341 | // the text before storing into database which would be itself big bug.. |
672f4836 | 1342 | $text = str_replace("\"$CFG->wwwroot/draftfile.php", "\"$CFG->wwwroot/brokenfile.php#", $text); |
3633c257 | 1343 | |
96f81ea3 | 1344 | if ($CFG->debugdeveloper) { |
3633c257 | 1345 | if (strpos($text, '@@PLUGINFILE@@/') !== false) { |
2e1d38db SH |
1346 | debugging('Before calling format_text(), the content must be processed with file_rewrite_pluginfile_urls()', |
1347 | DEBUG_DEVELOPER); | |
3633c257 DM |
1348 | } |
1349 | } | |
893fe4b6 | 1350 | } |
f0aa2fed | 1351 | |
367a75fa | 1352 | if (!empty($options['overflowdiv'])) { |
2e1d38db | 1353 | $text = html_writer::tag('div', $text, array('class' => 'no-overflow')); |
367a75fa SH |
1354 | } |
1355 | ||
bf997487 CB |
1356 | if ($options['blanktarget']) { |
1357 | $domdoc = new DOMDocument(); | |
f31e1e8b | 1358 | libxml_use_internal_errors(true); |
2c4e6d62 | 1359 | $domdoc->loadHTML('<?xml version="1.0" encoding="UTF-8" ?>' . $text); |
f31e1e8b | 1360 | libxml_clear_errors(); |
bf997487 CB |
1361 | foreach ($domdoc->getElementsByTagName('a') as $link) { |
1362 | if ($link->hasAttribute('target') && strpos($link->getAttribute('target'), '_blank') === false) { | |
1363 | continue; | |
1364 | } | |
1365 | $link->setAttribute('target', '_blank'); | |
1366 | if (strpos($link->getAttribute('rel'), 'noreferrer') === false) { | |
1367 | $link->setAttribute('rel', trim($link->getAttribute('rel') . ' noreferrer')); | |
1368 | } | |
1369 | } | |
1370 | ||
1371 | // This regex is nasty and I don't like it. The correct way to solve this is by loading the HTML like so: | |
1372 | // $domdoc->loadHTML($text, LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD); however it seems like the libxml | |
1373 | // version that travis uses doesn't work properly and ends up leaving <html><body>, so I'm forced to use | |
1374 | // this regex to remove those tags. | |
2549f46f | 1375 | $text = trim(preg_replace('~<(?:!DOCTYPE|/?(?:html|body))[^>]*>\s*~i', '', $domdoc->saveHTML($domdoc->documentElement))); |
bf997487 CB |
1376 | } |
1377 | ||
35716b86 | 1378 | return $text; |
0095d5cd | 1379 | } |
1380 | ||
109e3cb2 | 1381 | /** |
62c80325 | 1382 | * Resets some data related to filters, called during upgrade or when general filter settings change. |
449611af | 1383 | * |
a46e11b5 | 1384 | * @param bool $phpunitreset true means called from our PHPUnit integration test reset |
109e3cb2 | 1385 | * @return void |
1386 | */ | |
a46e11b5 | 1387 | function reset_text_filters_cache($phpunitreset = false) { |
8618fd2a | 1388 | global $CFG, $DB; |
109e3cb2 | 1389 | |
b2ea1793 PS |
1390 | if ($phpunitreset) { |
1391 | // HTMLPurifier does not change, DB is already reset to defaults, | |
62c80325 | 1392 | // nothing to do here, the dataroot was cleared too. |
b2ea1793 | 1393 | return; |
a46e11b5 PS |
1394 | } |
1395 | ||
62c80325 PŠ |
1396 | // The purge_all_caches() deals with cachedir and localcachedir purging, |
1397 | // the individual filter caches are invalidated as necessary elsewhere. | |
b2ea1793 PS |
1398 | |
1399 | // Update $CFG->filterall cache flag. | |
1400 | if (empty($CFG->stringfilters)) { | |
1401 | set_config('filterall', 0); | |
1402 | return; | |
1403 | } | |
1404 | $installedfilters = core_component::get_plugin_list('filter'); | |
1405 | $filters = explode(',', $CFG->stringfilters); | |
1406 | foreach ($filters as $filter) { | |
1407 | if (isset($installedfilters[$filter])) { | |
1408 | set_config('filterall', 1); | |
1409 | return; | |
1410 | } | |
1411 | } | |
1412 | set_config('filterall', 0); | |
109e3cb2 | 1413 | } |
473d29eb | 1414 | |
49c8c8d2 | 1415 | /** |
449611af | 1416 | * Given a simple string, this function returns the string |
1417 | * processed by enabled string filters if $CFG->filterall is enabled | |
e8276c10 | 1418 | * |
449611af | 1419 | * This function should be used to print short strings (non html) that |
1420 | * need filter processing e.g. activity titles, post subjects, | |
1421 | * glossary concepts. | |
7b2c5e72 | 1422 | * |
449611af | 1423 | * @staticvar bool $strcache |
d07f7be8 TH |
1424 | * @param string $string The string to be filtered. Should be plain text, expect |
1425 | * possibly for multilang tags. | |
2e1d38db | 1426 | * @param boolean $striplinks To strip any link in the result text. Moodle 1.8 default changed from false to true! MDL-8713 |
35716b86 | 1427 | * @param array $options options array/object or courseid |
449611af | 1428 | * @return string |
7b2c5e72 | 1429 | */ |
2e1d38db SH |
1430 | function format_string($string, $striplinks = true, $options = null) { |
1431 | global $CFG, $PAGE; | |
38701b69 | 1432 | |
2e1d38db | 1433 | // We'll use a in-memory cache here to speed up repeated strings. |
473d29eb | 1434 | static $strcache = false; |
1435 | ||
f18c764a | 1436 | if (empty($CFG->version) or $CFG->version < 2013051400 or during_initial_install()) { |
2e1d38db | 1437 | // Do not filter anything during installation or before upgrade completes. |
57cddf6d PS |
1438 | return $string = strip_tags($string); |
1439 | } | |
1440 | ||
2e1d38db SH |
1441 | if ($strcache === false or count($strcache) > 2000) { |
1442 | // This number might need some tuning to limit memory usage in cron. | |
473d29eb | 1443 | $strcache = array(); |
1444 | } | |
84e3d2cc | 1445 | |
35716b86 | 1446 | if (is_numeric($options)) { |
2e1d38db SH |
1447 | // Legacy courseid usage. |
1448 | $options = array('context' => context_course::instance($options)); | |
35716b86 | 1449 | } else { |
2e1d38db SH |
1450 | // Detach object, we can not modify it. |
1451 | $options = (array)$options; | |
35716b86 PS |
1452 | } |
1453 | ||
1454 | if (empty($options['context'])) { | |
2e1d38db | 1455 | // Fallback to $PAGE->context this may be problematic in CLI and other non-standard pages :-(. |
35716b86 PS |
1456 | $options['context'] = $PAGE->context; |
1457 | } else if (is_numeric($options['context'])) { | |
d197ea43 | 1458 | $options['context'] = context::instance_by_id($options['context']); |
35716b86 | 1459 | } |
08bda175 DW |
1460 | if (!isset($options['filter'])) { |
1461 | $options['filter'] = true; | |
1462 | } | |
35716b86 | 1463 | |
6fb1a717 CB |
1464 | $options['escape'] = !isset($options['escape']) || $options['escape']; |
1465 | ||
35716b86 | 1466 | if (!$options['context']) { |
2e1d38db | 1467 | // We did not find any context? weird. |
57cddf6d | 1468 | return $string = strip_tags($string); |
38701b69 | 1469 | } |
1470 | ||
2e1d38db | 1471 | // Calculate md5. |
74854585 RW |
1472 | $cachekeys = array($string, $striplinks, $options['context']->id, |
1473 | $options['escape'], current_language(), $options['filter']); | |
1474 | $md5 = md5(implode('<+>', $cachekeys)); | |
2a3affe9 | 1475 | |
2e1d38db | 1476 | // Fetch from cache if possible. |
38701b69 | 1477 | if (isset($strcache[$md5])) { |
2a3affe9 | 1478 | return $strcache[$md5]; |
1479 | } | |
1480 | ||
dacb47c0 | 1481 | // First replace all ampersands not followed by html entity code |
2e1d38db | 1482 | // Regular expression moved to its own method for easier unit testing. |
6fb1a717 | 1483 | $string = $options['escape'] ? replace_ampersands_not_followed_by_entity($string) : $string; |
268ddd50 | 1484 | |
08bda175 | 1485 | if (!empty($CFG->filterall) && $options['filter']) { |
b4402278 | 1486 | $filtermanager = filter_manager::instance(); |
6c5dbbb3 | 1487 | $filtermanager->setup_page_for_filters($PAGE, $options['context']); // Setup global stuff filters may have. |
b9647509 | 1488 | $string = $filtermanager->filter_string($string, $options['context']); |
7b2c5e72 | 1489 | } |
84e3d2cc | 1490 | |
2e1d38db | 1491 | // If the site requires it, strip ALL tags from this string. |
9fbed9c9 | 1492 | if (!empty($CFG->formatstringstriptags)) { |
6fb1a717 CB |
1493 | if ($options['escape']) { |
1494 | $string = str_replace(array('<', '>'), array('<', '>'), strip_tags($string)); | |
1495 | } else { | |
1496 | $string = strip_tags($string); | |
1497 | } | |
408d5327 | 1498 | } else { |
2e1d38db SH |
1499 | // Otherwise strip just links if that is required (default). |
1500 | if ($striplinks) { | |
1501 | // Strip links in string. | |
31c2087d | 1502 | $string = strip_links($string); |
408d5327 | 1503 | } |
1504 | $string = clean_text($string); | |
3e6691ee | 1505 | } |
1506 | ||
2e1d38db | 1507 | // Store to cache. |
2a3affe9 | 1508 | $strcache[$md5] = $string; |
84e3d2cc | 1509 | |
7b2c5e72 | 1510 | return $string; |
1511 | } | |
1512 | ||
6dbcacee | 1513 | /** |
1514 | * Given a string, performs a negative lookahead looking for any ampersand character | |
1515 | * that is not followed by a proper HTML entity. If any is found, it is replaced | |
1516 | * by &. The string is then returned. | |
1517 | * | |
1518 | * @param string $string | |
1519 | * @return string | |
1520 | */ | |
1521 | function replace_ampersands_not_followed_by_entity($string) { | |
1522 | return preg_replace("/\&(?![a-zA-Z0-9#]{1,8};)/", "&", $string); | |
1523 | } | |
1524 | ||
31c2087d | 1525 | /** |
1526 | * Given a string, replaces all <a>.*</a> by .* and returns the string. | |
49c8c8d2 | 1527 | * |
31c2087d | 1528 | * @param string $string |
1529 | * @return string | |
1530 | */ | |
1531 | function strip_links($string) { | |
2e1d38db | 1532 | return preg_replace('/(<a\s[^>]+?>)(.+?)(<\/a>)/is', '$2', $string); |
31c2087d | 1533 | } |
1534 | ||
1535 | /** | |
1536 | * This expression turns links into something nice in a text format. (Russell Jungwirth) | |
1537 | * | |
1538 | * @param string $string | |
1539 | * @return string | |
1540 | */ | |
1541 | function wikify_links($string) { | |
2e1d38db | 1542 | return preg_replace('~(<a [^<]*href=["|\']?([^ "\']*)["|\']?[^>]*>([^<]*)</a>)~i', '$3 [ $2 ]', $string); |
31c2087d | 1543 | } |
1544 | ||
d48b00b4 | 1545 | /** |
2e1d38db | 1546 | * Given text in a variety of format codings, this function returns the text as plain text suitable for plain email. |
d48b00b4 | 1547 | * |
89dcb99d | 1548 | * @param string $text The text to be formatted. This is raw text originally from user input. |
772e78be | 1549 | * @param int $format Identifier of the text format to be used |
449611af | 1550 | * [FORMAT_MOODLE, FORMAT_HTML, FORMAT_PLAIN, FORMAT_WIKI, FORMAT_MARKDOWN] |
89dcb99d | 1551 | * @return string |
d48b00b4 | 1552 | */ |
d342c763 | 1553 | function format_text_email($text, $format) { |
d342c763 | 1554 | |
1555 | switch ($format) { | |
1556 | ||
1557 | case FORMAT_PLAIN: | |
1558 | return $text; | |
1559 | break; | |
1560 | ||
1561 | case FORMAT_WIKI: | |
2e1d38db | 1562 | // There should not be any of these any more! |
31c2087d | 1563 | $text = wikify_links($text); |
2f1e464a | 1564 | return core_text::entities_to_utf8(strip_tags($text), true); |
d342c763 | 1565 | break; |
1566 | ||
6ff45b59 | 1567 | case FORMAT_HTML: |
1568 | return html_to_text($text); | |
1569 | break; | |
1570 | ||
e7cdcd18 | 1571 | case FORMAT_MOODLE: |
1572 | case FORMAT_MARKDOWN: | |
67ccec43 | 1573 | default: |
31c2087d | 1574 | $text = wikify_links($text); |
2f1e464a | 1575 | return core_text::entities_to_utf8(strip_tags($text), true); |
d342c763 | 1576 | break; |
1577 | } | |
1578 | } | |
0095d5cd | 1579 | |
dc5c2bd9 | 1580 | /** |
1581 | * Formats activity intro text | |
449611af | 1582 | * |
dc5c2bd9 | 1583 | * @param string $module name of module |
1584 | * @param object $activity instance of activity | |
1585 | * @param int $cmid course module id | |
43b44d5e | 1586 | * @param bool $filter filter resulting html text |
2e1d38db | 1587 | * @return string |
dc5c2bd9 | 1588 | */ |
43b44d5e | 1589 | function format_module_intro($module, $activity, $cmid, $filter=true) { |
ac3668bf | 1590 | global $CFG; |
1591 | require_once("$CFG->libdir/filelib.php"); | |
b0c6dc1c | 1592 | $context = context_module::instance($cmid); |
2e1d38db | 1593 | $options = array('noclean' => true, 'para' => false, 'filter' => $filter, 'context' => $context, 'overflowdiv' => true); |
64f93798 | 1594 | $intro = file_rewrite_pluginfile_urls($activity->intro, 'pluginfile.php', $context->id, 'mod_'.$module, 'intro', null); |
35716b86 | 1595 | return trim(format_text($intro, $activity->introformat, $options, null)); |
dc5c2bd9 | 1596 | } |
cbdfb929 | 1597 | |
0a8b3583 FM |
1598 | /** |
1599 | * Removes the usage of Moodle files from a text. | |
1600 | * | |
1601 | * In some rare cases we need to re-use a text that already has embedded links | |
1602 | * to some files hosted within Moodle. But the new area in which we will push | |
1603 | * this content does not support files... therefore we need to remove those files. | |
1604 | * | |
1605 | * @param string $source The text | |
1606 | * @return string The stripped text | |
1607 | */ | |
1608 | function strip_pluginfile_content($source) { | |
1609 | $baseurl = '@@PLUGINFILE@@'; | |
1610 | // Looking for something like < .* "@@pluginfile@@.*" .* > | |
1611 | $pattern = '$<[^<>]+["\']' . $baseurl . '[^"\']*["\'][^<>]*>$'; | |
1612 | $stripped = preg_replace($pattern, '', $source); | |
1613 | // Use purify html to rebalence potentially mismatched tags and generally cleanup. | |
1614 | return purify_html($stripped); | |
1615 | } | |
1616 | ||
7d8a3cb0 | 1617 | /** |
cbc2b5df | 1618 | * Legacy function, used for cleaning of old forum and glossary text only. |
449611af | 1619 | * |
54f53184 | 1620 | * @param string $text text that may contain legacy TRUSTTEXT marker |
2e1d38db | 1621 | * @return string text without legacy TRUSTTEXT marker |
7d8a3cb0 | 1622 | */ |
1623 | function trusttext_strip($text) { | |
3bf04828 | 1624 | if (!is_string($text)) { |
1625 | // This avoids the potential for an endless loop below. | |
1626 | throw new coding_exception('trusttext_strip parameter must be a string'); | |
1627 | } | |
2e1d38db | 1628 | while (true) { // Removing nested TRUSTTEXT. |
5ce73257 | 1629 | $orig = $text; |
cbc2b5df | 1630 | $text = str_replace('#####TRUSTTEXT#####', '', $text); |
7d8a3cb0 | 1631 | if (strcmp($orig, $text) === 0) { |
1632 | return $text; | |
1633 | } | |
1634 | } | |
1635 | } | |
1636 | ||
cbc2b5df | 1637 | /** |
2e1d38db | 1638 | * Must be called before editing of all texts with trust flag. Removes all XSS nasties from texts stored in database if needed. |
449611af | 1639 | * |
2e1d38db | 1640 | * @param stdClass $object data object with xxx, xxxformat and xxxtrust fields |
cbc2b5df | 1641 | * @param string $field name of text field |
2e1d38db SH |
1642 | * @param context $context active context |
1643 | * @return stdClass updated $object | |
cbc2b5df | 1644 | */ |
1645 | function trusttext_pre_edit($object, $field, $context) { | |
1646 | $trustfield = $field.'trust'; | |
49c8c8d2 | 1647 | $formatfield = $field.'format'; |
1648 | ||
cbc2b5df | 1649 | if (!$object->$trustfield or !trusttext_trusted($context)) { |
1650 | $object->$field = clean_text($object->$field, $object->$formatfield); | |
1651 | } | |
1652 | ||
1653 | return $object; | |
1654 | } | |
1655 | ||
1656 | /** | |
449611af | 1657 | * Is current user trusted to enter no dangerous XSS in this context? |
1658 | * | |
cbc2b5df | 1659 | * Please note the user must be in fact trusted everywhere on this server!! |
449611af | 1660 | * |
2e1d38db | 1661 | * @param context $context |
cbc2b5df | 1662 | * @return bool true if user trusted |
1663 | */ | |
1664 | function trusttext_trusted($context) { | |
49c8c8d2 | 1665 | return (trusttext_active() and has_capability('moodle/site:trustcontent', $context)); |
cbc2b5df | 1666 | } |
1667 | ||
1668 | /** | |
1669 | * Is trusttext feature active? | |
449611af | 1670 | * |
cbc2b5df | 1671 | * @return bool |
1672 | */ | |
1673 | function trusttext_active() { | |
1674 | global $CFG; | |
1675 | ||
49c8c8d2 | 1676 | return !empty($CFG->enabletrusttext); |
cbc2b5df | 1677 | } |
1678 | ||
d48b00b4 | 1679 | /** |
2e1d38db SH |
1680 | * Cleans raw text removing nasties. |
1681 | * | |
1682 | * Given raw text (eg typed in by a user) this function cleans it up and removes any nasty tags that could mess up | |
1683 | * Moodle pages through XSS attacks. | |
4e8d084b PS |
1684 | * |
1685 | * The result must be used as a HTML text fragment, this function can not cleanup random | |
1686 | * parts of html tags such as url or src attributes. | |
d48b00b4 | 1687 | * |
e6906df2 PS |
1688 | * NOTE: the format parameter was deprecated because we can safely clean only HTML. |
1689 | * | |
89dcb99d | 1690 | * @param string $text The text to be cleaned |
4e8d084b | 1691 | * @param int|string $format deprecated parameter, should always contain FORMAT_HTML or FORMAT_MOODLE |
b031caf8 | 1692 | * @param array $options Array of options; currently only option supported is 'allowid' (if true, |
1693 | * does not remove id attributes when cleaning) | |
89dcb99d | 1694 | * @return string The cleaned up text |
d48b00b4 | 1695 | */ |
b031caf8 | 1696 | function clean_text($text, $format = FORMAT_HTML, $options = array()) { |
986f8ea2 | 1697 | $text = (string)$text; |
3fe3851d | 1698 | |
e6906df2 | 1699 | if ($format != FORMAT_HTML and $format != FORMAT_HTML) { |
2e1d38db SH |
1700 | // TODO: we need to standardise cleanup of text when loading it into editor first. |
1701 | // debugging('clean_text() is designed to work only with html');. | |
e6906df2 | 1702 | } |
e7cdcd18 | 1703 | |
e6906df2 PS |
1704 | if ($format == FORMAT_PLAIN) { |
1705 | return $text; | |
1706 | } | |
e7cdcd18 | 1707 | |
986f8ea2 PS |
1708 | if (is_purify_html_necessary($text)) { |
1709 | $text = purify_html($text, $options); | |
1710 | } | |
7789ffbf | 1711 | |
4e8d084b PS |
1712 | // Originally we tried to neutralise some script events here, it was a wrong approach because |
1713 | // it was trivial to work around that (for example using style based XSS exploits). | |
1714 | // We must not give false sense of security here - all developers MUST understand how to use | |
1715 | // rawurlencode(), htmlentities(), htmlspecialchars(), p(), s(), moodle_url, html_writer and friends!!! | |
6901fa79 | 1716 | |
e6906df2 | 1717 | return $text; |
b7a3cf49 | 1718 | } |
f9903ed0 | 1719 | |
986f8ea2 PS |
1720 | /** |
1721 | * Is it necessary to use HTMLPurifier? | |
2e1d38db | 1722 | * |
986f8ea2 PS |
1723 | * @private |
1724 | * @param string $text | |
1725 | * @return bool false means html is safe and valid, true means use HTMLPurifier | |
1726 | */ | |
1727 | function is_purify_html_necessary($text) { | |
1728 | if ($text === '') { | |
1729 | return false; | |
1730 | } | |
1731 | ||
1732 | if ($text === (string)((int)$text)) { | |
1733 | return false; | |
1734 | } | |
1735 | ||
1736 | if (strpos($text, '&') !== false or preg_match('|<[^pesb/]|', $text)) { | |
2e1d38db | 1737 | // We need to normalise entities or other tags except p, em, strong and br present. |
986f8ea2 PS |
1738 | return true; |
1739 | } | |
1740 | ||
1741 | $altered = htmlspecialchars($text, ENT_NOQUOTES, 'UTF-8', true); | |
1742 | if ($altered === $text) { | |
2e1d38db | 1743 | // No < > or other special chars means this must be safe. |
986f8ea2 PS |
1744 | return false; |
1745 | } | |
1746 | ||
2e1d38db | 1747 | // Let's try to convert back some safe html tags. |
986f8ea2 PS |
1748 | $altered = preg_replace('|<p>(.*?)</p>|m', '<p>$1</p>', $altered); |
1749 | if ($altered === $text) { | |
1750 | return false; | |
1751 | } | |
1752 | $altered = preg_replace('|<em>([^<>]+?)</em>|m', '<em>$1</em>', $altered); | |
1753 | if ($altered === $text) { | |
1754 | return false; | |
1755 | } | |
1756 | $altered = preg_replace('|<strong>([^<>]+?)</strong>|m', '<strong>$1</strong>', $altered); | |
1757 | if ($altered === $text) { | |
1758 | return false; | |
1759 | } | |
1760 | $altered = str_replace('<br />', '<br />', $altered); | |
1761 | if ($altered === $text) { | |
1762 | return false; | |
1763 | } | |
1764 | ||
1765 | return true; | |
1766 | } | |
1767 | ||
e0ac8448 | 1768 | /** |
1769 | * KSES replacement cleaning function - uses HTML Purifier. | |
449611af | 1770 | * |
449611af | 1771 | * @param string $text The (X)HTML string to purify |
b031caf8 | 1772 | * @param array $options Array of options; currently only option supported is 'allowid' (if set, |
1773 | * does not remove id attributes when cleaning) | |
73b309e6 | 1774 | * @return string |
e0ac8448 | 1775 | */ |
b031caf8 | 1776 | function purify_html($text, $options = array()) { |
e0ac8448 | 1777 | global $CFG; |
1778 | ||
528a7b44 PS |
1779 | $text = (string)$text; |
1780 | ||
b031caf8 | 1781 | static $purifiers = array(); |
e85c56cc SH |
1782 | static $caches = array(); |
1783 | ||
528a7b44 PS |
1784 | // Purifier code can change only during major version upgrade. |
1785 | $version = empty($CFG->version) ? 0 : $CFG->version; | |
1786 | $cachedir = "$CFG->localcachedir/htmlpurifier/$version"; | |
1787 | if (!file_exists($cachedir)) { | |
1788 | // Purging of caches may remove the cache dir at any time, | |
1789 | // luckily file_exists() results should be cached for all existing directories. | |
1790 | $purifiers = array(); | |
1791 | $caches = array(); | |
1792 | gc_collect_cycles(); | |
1793 | ||
1794 | make_localcache_directory('htmlpurifier', false); | |
1795 | check_dir_exists($cachedir); | |
1796 | } | |
1797 | ||
1798 | $allowid = empty($options['allowid']) ? 0 : 1; | |
1799 | $allowobjectembed = empty($CFG->allowobjectembed) ? 0 : 1; | |
1800 | ||
1801 | $type = 'type_'.$allowid.'_'.$allowobjectembed; | |
e85c56cc SH |
1802 | |
1803 | if (!array_key_exists($type, $caches)) { | |
1804 | $caches[$type] = cache::make('core', 'htmlpurifier', array('type' => $type)); | |
1805 | } | |
1806 | $cache = $caches[$type]; | |
1807 | ||
528a7b44 PS |
1808 | // Add revision number and all options to the text key so that it is compatible with local cluster node caches. |
1809 | $key = "|$version|$allowobjectembed|$allowid|$text"; | |
1810 | $filteredtext = $cache->get($key); | |
1811 | ||
1812 | if ($filteredtext === true) { | |
1813 | // The filtering did not change the text last time, no need to filter anything again. | |
1814 | return $text; | |
1815 | } else if ($filteredtext !== false) { | |
e85c56cc SH |
1816 | return $filteredtext; |
1817 | } | |
1818 | ||
b031caf8 | 1819 | if (empty($purifiers[$type])) { |
eb203ee4 | 1820 | require_once $CFG->libdir.'/htmlpurifier/HTMLPurifier.safe-includes.php'; |
590abcf8 | 1821 | require_once $CFG->libdir.'/htmlpurifier/locallib.php'; |
e0ac8448 | 1822 | $config = HTMLPurifier_Config::createDefault(); |
f71c7f00 PS |
1823 | |
1824 | $config->set('HTML.DefinitionID', 'moodlehtml'); | |
f34d7af0 | 1825 | $config->set('HTML.DefinitionRev', 6); |
f71c7f00 | 1826 | $config->set('Cache.SerializerPath', $cachedir); |
7df50029 | 1827 | $config->set('Cache.SerializerPermissions', $CFG->directorypermissions); |
f71c7f00 | 1828 | $config->set('Core.NormalizeNewlines', false); |
6ec450fb | 1829 | $config->set('Core.ConvertDocumentToFragment', true); |
1830 | $config->set('Core.Encoding', 'UTF-8'); | |
1831 | $config->set('HTML.Doctype', 'XHTML 1.0 Transitional'); | |
2e1d38db SH |
1832 | $config->set('URI.AllowedSchemes', array( |
1833 | 'http' => true, | |
1834 | 'https' => true, | |
1835 | 'ftp' => true, | |
1836 | 'irc' => true, | |
1837 | 'nntp' => true, | |
1838 | 'news' => true, | |
1839 | 'rtsp' => true, | |
817b2020 | 1840 | 'rtmp' => true, |
2e1d38db SH |
1841 | 'teamspeak' => true, |
1842 | 'gopher' => true, | |
1843 | 'mms' => true, | |
1844 | 'mailto' => true | |
1845 | )); | |
6ec450fb | 1846 | $config->set('Attr.AllowedFrameTargets', array('_blank')); |
f71c7f00 | 1847 | |
528a7b44 | 1848 | if ($allowobjectembed) { |
cbe44fb2 PS |
1849 | $config->set('HTML.SafeObject', true); |
1850 | $config->set('Output.FlashCompat', true); | |
a0f97768 | 1851 | $config->set('HTML.SafeEmbed', true); |
cbe44fb2 PS |
1852 | } |
1853 | ||
528a7b44 | 1854 | if ($allowid) { |
b031caf8 | 1855 | $config->set('Attr.EnableID', true); |
1856 | } | |
1857 | ||
7df50029 | 1858 | if ($def = $config->maybeGetRawHTMLDefinition()) { |
528a7b44 PS |
1859 | $def->addElement('nolink', 'Block', 'Flow', array()); // Skip our filters inside. |
1860 | $def->addElement('tex', 'Inline', 'Inline', array()); // Tex syntax, equivalent to $$xx$$. | |
1861 | $def->addElement('algebra', 'Inline', 'Inline', array()); // Algebra syntax, equivalent to @@xx@@. | |
1862 | $def->addElement('lang', 'Block', 'Flow', array(), array('lang'=>'CDATA')); // Original multilang style - only our hacked lang attribute. | |
1863 | $def->addAttribute('span', 'xxxlang', 'CDATA'); // Current very problematic multilang. | |
171b4563 | 1864 | |
37c10287 CB |
1865 | // Media elements. |
1866 | // https://html.spec.whatwg.org/#the-video-element | |
28e27ac8 | 1867 | $def->addElement('video', 'Block', 'Optional: #PCDATA | Flow | source | track', 'Common', [ |
37c10287 CB |
1868 | 'src' => 'URI', |
1869 | 'crossorigin' => 'Enum#anonymous,use-credentials', | |
1870 | 'poster' => 'URI', | |
1871 | 'preload' => 'Enum#auto,metadata,none', | |
1872 | 'autoplay' => 'Bool', | |
1873 | 'playsinline' => 'Bool', | |
1874 | 'loop' => 'Bool', | |
1875 | 'muted' => 'Bool', | |
1876 | 'controls' => 'Bool', | |
1877 | 'width' => 'Length', | |
1878 | 'height' => 'Length', | |
1879 | ]); | |
1880 | // https://html.spec.whatwg.org/#the-audio-element | |
28e27ac8 | 1881 | $def->addElement('audio', 'Block', 'Optional: #PCDATA | Flow | source | track', 'Common', [ |
37c10287 CB |
1882 | 'src' => 'URI', |
1883 | 'crossorigin' => 'Enum#anonymous,use-credentials', | |
1884 | 'preload' => 'Enum#auto,metadata,none', | |
1885 | 'autoplay' => 'Bool', | |
1886 | 'loop' => 'Bool', | |
1887 | 'muted' => 'Bool', | |
1888 | 'controls' => 'Bool' | |
1889 | ]); | |
1890 | // https://html.spec.whatwg.org/#the-source-element | |
28e27ac8 | 1891 | $def->addElement('source', false, 'Empty', null, [ |
37c10287 CB |
1892 | 'src' => 'URI', |
1893 | 'type' => 'Text' | |
1894 | ]); | |
28e27ac8 MG |
1895 | // https://html.spec.whatwg.org/#the-track-element |
1896 | $def->addElement('track', false, 'Empty', null, [ | |
1897 | 'src' => 'URI', | |
1898 | 'kind' => 'Enum#subtitles,captions,descriptions,chapters,metadata', | |
1899 | 'srclang' => 'Text', | |
1900 | 'label' => 'Text', | |
1901 | 'default' => 'Bool', | |
1902 | ]); | |
37c10287 | 1903 | |
171b4563 JC |
1904 | // Use the built-in Ruby module to add annotation support. |
1905 | $def->manager->addModule(new HTMLPurifier_HTMLModule_Ruby()); | |
7df50029 | 1906 | } |
f71c7f00 | 1907 | |
e0ac8448 | 1908 | $purifier = new HTMLPurifier($config); |
b031caf8 | 1909 | $purifiers[$type] = $purifier; |
1910 | } else { | |
1911 | $purifier = $purifiers[$type]; | |
e0ac8448 | 1912 | } |
f71c7f00 PS |
1913 | |
1914 | $multilang = (strpos($text, 'class="multilang"') !== false); | |
1915 | ||
e85c56cc | 1916 | $filteredtext = $text; |
f71c7f00 | 1917 | if ($multilang) { |
2e1d38db SH |
1918 | $filteredtextregex = '/<span(\s+lang="([a-zA-Z0-9_-]+)"|\s+class="multilang"){2}\s*>/'; |
1919 | $filteredtext = preg_replace($filteredtextregex, '<span xxxlang="${2}">', $filteredtext); | |
f71c7f00 | 1920 | } |
528a7b44 | 1921 | $filteredtext = (string)$purifier->purify($filteredtext); |
f71c7f00 | 1922 | if ($multilang) { |
e85c56cc | 1923 | $filteredtext = preg_replace('/<span xxxlang="([a-zA-Z0-9_-]+)">/', '<span lang="${1}" class="multilang">', $filteredtext); |
f71c7f00 | 1924 | } |
528a7b44 PS |
1925 | |
1926 | if ($text === $filteredtext) { | |
1927 | // No need to store the filtered text, next time we will just return unfiltered text | |
1928 | // because it was not changed by purifying. | |
1929 | $cache->set($key, true); | |
1930 | } else { | |
1931 | $cache->set($key, $filteredtext); | |
1932 | } | |
f71c7f00 | 1933 | |
e85c56cc | 1934 | return $filteredtext; |
e0ac8448 | 1935 | } |
1936 | ||
89dcb99d | 1937 | /** |
1938 | * Given plain text, makes it into HTML as nicely as possible. | |
2e1d38db SH |
1939 | * |
1940 | * May contain HTML tags already. | |
89dcb99d | 1941 | * |
84a8bedd | 1942 | * Do not abuse this function. It is intended as lower level formatting feature used |
2e1d38db | 1943 | * by {@link format_text()} to convert FORMAT_MOODLE to HTML. You are supposed |
84a8bedd DM |
1944 | * to call format_text() in most of cases. |
1945 | * | |
89dcb99d | 1946 | * @param string $text The string to convert. |
2e1d38db | 1947 | * @param boolean $smileyignored Was used to determine if smiley characters should convert to smiley images, ignored now |
b075eb8e | 1948 | * @param boolean $para If true then the returned string will be wrapped in div tags |
89dcb99d | 1949 | * @param boolean $newlines If true then lines newline breaks will be converted to HTML newline breaks. |
1950 | * @return string | |
1951 | */ | |
2e1d38db SH |
1952 | function text_to_html($text, $smileyignored = null, $para = true, $newlines = true) { |
1953 | // Remove any whitespace that may be between HTML tags. | |
6dbcacee | 1954 | $text = preg_replace("~>([[:space:]]+)<~i", "><", $text); |
7b3be1b1 | 1955 | |
2e1d38db | 1956 | // Remove any returns that precede or follow HTML tags. |
6dbcacee | 1957 | $text = preg_replace("~([\n\r])<~i", " <", $text); |
1958 | $text = preg_replace("~>([\n\r])~i", "> ", $text); | |
7b3be1b1 | 1959 | |
2e1d38db | 1960 | // Make returns into HTML newlines. |
b7a3d3b2 | 1961 | if ($newlines) { |
1962 | $text = nl2br($text); | |
1963 | } | |
f9903ed0 | 1964 | |
2e1d38db | 1965 | // Wrap the whole thing in a div if required. |
909f539d | 1966 | if ($para) { |
2e1d38db | 1967 | // In 1.9 this was changed from a p => div. |
b075eb8e | 1968 | return '<div class="text_to_html">'.$text.'</div>'; |
909f539d | 1969 | } else { |
1970 | return $text; | |
1971 | } | |
f9903ed0 | 1972 | } |
1973 | ||
d48b00b4 | 1974 | /** |
1975 | * Given Markdown formatted text, make it into XHTML using external function | |
1976 | * | |
89dcb99d | 1977 | * @param string $text The markdown formatted text to be converted. |
1978 | * @return string Converted text | |
d48b00b4 | 1979 | */ |
e7cdcd18 | 1980 | function markdown_to_html($text) { |
e7cdcd18 | 1981 | global $CFG; |
1982 | ||
2e1d38db | 1983 | if ($text === '' or $text === null) { |
a4a0c9d9 PS |
1984 | return $text; |
1985 | } | |
1986 | ||
cfc9130e | 1987 | require_once($CFG->libdir .'/markdown/MarkdownInterface.php'); |
baf3d690 PS |
1988 | require_once($CFG->libdir .'/markdown/Markdown.php'); |
1989 | require_once($CFG->libdir .'/markdown/MarkdownExtra.php'); | |
e7cdcd18 | 1990 | |
baf3d690 | 1991 | return \Michelf\MarkdownExtra::defaultTransform($text); |
e7cdcd18 | 1992 | } |
1993 | ||
d48b00b4 | 1994 | /** |
89dcb99d | 1995 | * Given HTML text, make it into plain text using external function |
d48b00b4 | 1996 | * |
d48b00b4 | 1997 | * @param string $html The text to be converted. |
a194c218 TH |
1998 | * @param integer $width Width to wrap the text at. (optional, default 75 which |
1999 | * is a good value for email. 0 means do not limit line length.) | |
dc3e95c0 TH |
2000 | * @param boolean $dolinks By default, any links in the HTML are collected, and |
2001 | * printed as a list at the end of the HTML. If you don't want that, set this | |
2002 | * argument to false. | |
a194c218 | 2003 | * @return string plain text equivalent of the HTML. |
d48b00b4 | 2004 | */ |
dc3e95c0 | 2005 | function html_to_text($html, $width = 75, $dolinks = true) { |
428aaa29 | 2006 | global $CFG; |
6ff45b59 | 2007 | |
ec2d33df AN |
2008 | require_once($CFG->libdir .'/html2text/lib.php'); |
2009 | ||
2010 | $options = array( | |
2011 | 'width' => $width, | |
2012 | 'do_links' => 'table', | |
2013 | ); | |
6ff45b59 | 2014 | |
ec2d33df AN |
2015 | if (empty($dolinks)) { |
2016 | $options['do_links'] = 'none'; | |
2017 | } | |
2018 | $h2t = new core_html2text($html, $options); | |
2019 | $result = $h2t->getText(); | |
07e9a300 | 2020 | |
977b3d31 | 2021 | return $result; |
6ff45b59 | 2022 | } |
2023 | ||
69d66020 | 2024 | /** |
505ce884 DM |
2025 | * Converts texts or strings to plain text. |
2026 | * | |
2027 | * - When used to convert user input introduced in an editor the text format needs to be passed in $contentformat like we usually | |
2028 | * do in format_text. | |
2029 | * - When this function is used for strings that are usually passed through format_string before displaying them | |
2030 | * we need to set $contentformat to false. This will execute html_to_text as these strings can contain multilang tags if | |
2031 | * multilang filter is applied to headings. | |
69d66020 DM |
2032 | * |
2033 | * @param string $content The text as entered by the user | |
505ce884 | 2034 | * @param int|false $contentformat False for strings or the text format: FORMAT_MOODLE/FORMAT_HTML/FORMAT_PLAIN/FORMAT_MARKDOWN |
69d66020 DM |
2035 | * @return string Plain text. |
2036 | */ | |
2037 | function content_to_text($content, $contentformat) { | |
2038 | ||
2039 | switch ($contentformat) { | |
2040 | case FORMAT_PLAIN: | |
505ce884 DM |
2041 | // Nothing here. |
2042 | break; | |
69d66020 | 2043 | case FORMAT_MARKDOWN: |
505ce884 DM |
2044 | $content = markdown_to_html($content); |
2045 | $content = html_to_text($content, 75, false); | |
2046 | break; | |
69d66020 | 2047 | default: |
505ce884 DM |
2048 | // FORMAT_HTML, FORMAT_MOODLE and $contentformat = false, the later one are strings usually formatted through |
2049 | // format_string, we need to convert them from html because they can contain HTML (multilang filter). | |
2050 | $content = html_to_text($content, 75, false); | |
69d66020 | 2051 | } |
505ce884 DM |
2052 | |
2053 | return trim($content, "\r\n "); | |
69d66020 DM |
2054 | } |
2055 | ||
7d7d3b17 CF |
2056 | /** |
2057 | * Factory method for extracting draft file links from arbitrary text using regular expressions. Only text | |
2058 | * is required; other file fields may be passed to filter. | |
2059 | * | |
2060 | * @param string $text Some html content. | |
2061 | * @param bool $forcehttps force https urls. | |
2062 | * @param int $contextid This parameter and the next three identify the file area to save to. | |
2063 | * @param string $component The component name. | |
2064 | * @param string $filearea The filearea. | |
2065 | * @param int $itemid The item id for the filearea. | |
2066 | * @param string $filename The specific filename of the file. | |
2067 | * @return array | |
2068 | */ | |
2069 | function extract_draft_file_urls_from_text($text, $forcehttps = false, $contextid = null, $component = null, | |
c353ad20 | 2070 | $filearea = null, $itemid = null, $filename = null) { |
7d7d3b17 CF |
2071 | global $CFG; |
2072 | ||
2073 | $wwwroot = $CFG->wwwroot; | |
2074 | if ($forcehttps) { | |
2075 | $wwwroot = str_replace('http://', 'https://', $wwwroot); | |
2076 | } | |
2077 | $urlstring = '/' . preg_quote($wwwroot, '/'); | |
2078 | ||
2079 | $urlbase = preg_quote('draftfile.php'); | |
2080 | $urlstring .= "\/(?<urlbase>{$urlbase})"; | |
2081 | ||
2082 | if (is_null($contextid)) { | |
2083 | $contextid = '[0-9]+'; | |
2084 | } | |
2085 | $urlstring .= "\/(?<contextid>{$contextid})"; | |
2086 | ||
2087 | if (is_null($component)) { | |
2088 | $component = '[a-z_]+'; | |
2089 | } | |
2090 | $urlstring .= "\/(?<component>{$component})"; | |
2091 | ||
2092 | if (is_null($filearea)) { | |
2093 | $filearea = '[a-z_]+'; | |
2094 | } | |
2095 | $urlstring .= "\/(?<filearea>{$filearea})"; | |
2096 | ||
2097 | if (is_null($itemid)) { | |
2098 | $itemid = '[0-9]+'; | |
2099 | } | |
2100 | $urlstring .= "\/(?<itemid>{$itemid})"; | |
2101 | ||
2102 | // Filename matching magic based on file_rewrite_urls_to_pluginfile(). | |
2103 | if (is_null($filename)) { | |
2104 | $filename = '[^\'\",&<>|`\s:\\\\]+'; | |
2105 | } | |
2106 | $urlstring .= "\/(?<filename>{$filename})/"; | |
2107 | ||
2108 | // Regular expression which matches URLs and returns their components. | |
2109 | preg_match_all($urlstring, $text, $urls, PREG_SET_ORDER); | |
2110 | return $urls; | |
2111 | } | |
2112 | ||
d48b00b4 | 2113 | /** |
2114 | * This function will highlight search words in a given string | |
449611af | 2115 | * |
d48b00b4 | 2116 | * It cares about HTML and will not ruin links. It's best to use |
2117 | * this function after performing any conversions to HTML. | |
d48b00b4 | 2118 | * |
9289e4c9 | 2119 | * @param string $needle The search string. Syntax like "word1 +word2 -word3" is dealt with correctly. |
2120 | * @param string $haystack The string (HTML) within which to highlight the search terms. | |
2121 | * @param boolean $matchcase whether to do case-sensitive. Default case-insensitive. | |
2122 | * @param string $prefix the string to put before each search term found. | |
2123 | * @param string $suffix the string to put after each search term found. | |
2124 | * @return string The highlighted HTML. | |
d48b00b4 | 2125 | */ |
9289e4c9 | 2126 | function highlight($needle, $haystack, $matchcase = false, |
2127 | $prefix = '<span class="highlight">', $suffix = '</span>') { | |
587c7040 | 2128 | |
2e1d38db | 2129 | // Quick bail-out in trivial cases. |
587c7040 | 2130 | if (empty($needle) or empty($haystack)) { |
69d51d3a | 2131 | return $haystack; |
2132 | } | |
2133 | ||
2e1d38db | 2134 | // Break up the search term into words, discard any -words and build a regexp. |
9289e4c9 | 2135 | $words = preg_split('/ +/', trim($needle)); |
2136 | foreach ($words as $index => $word) { | |
2137 | if (strpos($word, '-') === 0) { | |
2138 | unset($words[$index]); | |
2139 | } else if (strpos($word, '+') === 0) { | |
2140 | $words[$index] = '\b' . preg_quote(ltrim($word, '+'), '/') . '\b'; // Match only as a complete word. | |
2141 | } else { | |
2142 | $words[$index] = preg_quote($word, '/'); | |
88438a58 | 2143 | } |
2144 | } | |
2e1d38db | 2145 | $regexp = '/(' . implode('|', $words) . ')/u'; // Char u is to do UTF-8 matching. |
9289e4c9 | 2146 | if (!$matchcase) { |
2147 | $regexp .= 'i'; | |
88438a58 | 2148 | } |
2149 | ||
2e1d38db | 2150 | // Another chance to bail-out if $search was only -words. |
9289e4c9 | 2151 | if (empty($words)) { |
2152 | return $haystack; | |
88438a58 | 2153 | } |
88438a58 | 2154 | |
1fa2823d TH |
2155 | // Split the string into HTML tags and real content. |
2156 | $chunks = preg_split('/((?:<[^>]*>)+)/', $haystack, -1, PREG_SPLIT_DELIM_CAPTURE); | |
2157 | ||
2158 | // We have an array of alternating blocks of text, then HTML tags, then text, ... | |
2159 | // Loop through replacing search terms in the text, and leaving the HTML unchanged. | |
2160 | $ishtmlchunk = false; | |
2161 | $result = ''; | |
2162 | foreach ($chunks as $chunk) { | |
2163 | if ($ishtmlchunk) { | |
2164 | $result .= $chunk; | |
2165 | } else { | |
2166 | $result .= preg_replace($regexp, $prefix . '$1' . $suffix, $chunk); | |
2167 | } | |
2168 | $ishtmlchunk = !$ishtmlchunk; | |
9289e4c9 | 2169 | } |
9ccdcd97 | 2170 | |
1fa2823d | 2171 | return $result; |
88438a58 | 2172 | } |
2173 | ||
d48b00b4 | 2174 | /** |
2175 | * This function will highlight instances of $needle in $haystack | |
449611af | 2176 | * |
2177 | * It's faster that the above function {@link highlight()} and doesn't care about | |
d48b00b4 | 2178 | * HTML or anything. |
2179 | * | |
2180 | * @param string $needle The string to search for | |
2181 | * @param string $haystack The string to search for $needle in | |
449611af | 2182 | * @return string The highlighted HTML |
d48b00b4 | 2183 | */ |
88438a58 | 2184 | function highlightfast($needle, $haystack) { |
5af78ed2 | 2185 | |
587c7040 | 2186 | if (empty($needle) or empty($haystack)) { |
2187 | return $haystack; | |
2188 | } | |
2189 | ||
2f1e464a | 2190 | $parts = explode(core_text::strtolower($needle), core_text::strtolower($haystack)); |
5af78ed2 | 2191 | |
587c7040 | 2192 | if (count($parts) === 1) { |
2193 | return $haystack; | |
2194 | } | |
2195 | ||
5af78ed2 | 2196 | $pos = 0; |
2197 | ||
2198 | foreach ($parts as $key => $part) { | |
2199 | $parts[$key] = substr($haystack, $pos, strlen($part)); | |
2200 | $pos += strlen($part); | |
2201 | ||
b0ccd3fb | 2202 | $parts[$key] .= '<span class="highlight">'.substr($haystack, $pos, strlen($needle)).'</span>'; |
5af78ed2 | 2203 | $pos += strlen($needle); |
ab9f24ad | 2204 | } |
5af78ed2 | 2205 | |
587c7040 | 2206 | return str_replace('<span class="highlight"></span>', '', join('', $parts)); |
5af78ed2 | 2207 | } |
2208 | ||
2ab4e4b8 | 2209 | /** |
2210 | * Return a string containing 'lang', xml:lang and optionally 'dir' HTML attributes. | |
2e1d38db | 2211 | * |
2ab4e4b8 | 2212 | * Internationalisation, for print_header and backup/restorelib. |
449611af | 2213 | * |
2214 | * @param bool $dir Default false | |
2215 | * @return string Attributes | |
2ab4e4b8 | 2216 | */ |
2217 | function get_html_lang($dir = false) { | |
2218 | $direction = ''; | |
2219 | if ($dir) { | |
e372f4c7 | 2220 | if (right_to_left()) { |
2ab4e4b8 | 2221 | $direction = ' dir="rtl"'; |
2222 | } else { | |
2223 | $direction = ' dir="ltr"'; | |
2224 | } | |
2225 | } | |
2e1d38db | 2226 | // Accessibility: added the 'lang' attribute to $direction, used in theme <html> tag. |
3a915b06 | 2227 | $language = str_replace('_', '-', current_language()); |
0946fff4 | 2228 | @header('Content-Language: '.$language); |
84e3d2cc | 2229 | return ($direction.' lang="'.$language.'" xml:lang="'.$language.'"'); |
2ab4e4b8 | 2230 | } |
2231 | ||
34a2777c | 2232 | |
2e1d38db | 2233 | // STANDARD WEB PAGE PARTS. |
34a2777c | 2234 | |
5c355019 | 2235 | /** |
34a2777c | 2236 | * Send the HTTP headers that Moodle requires. |
9172fd82 PS |
2237 | * |
2238 | * There is a backwards compatibility hack for legacy code | |
2239 | * that needs to add custom IE compatibility directive. | |
2240 | * | |
2241 | * Example: | |
2242 | * <code> | |
2243 | * if (!isset($CFG->additionalhtmlhead)) { | |
2244 | * $CFG->additionalhtmlhead = ''; | |
2245 | * } | |
2246 | * $CFG->additionalhtmlhead .= '<meta http-equiv="X-UA-Compatible" content="IE=8" />'; | |
2247 | * header('X-UA-Compatible: IE=8'); | |
2248 | * echo $OUTPUT->header(); | |
2249 | * </code> | |
2250 | * | |
2251 | * Please note the $CFG->additionalhtmlhead alone might not work, | |
2252 | * you should send the IE compatibility header() too. | |
2253 | * | |
2254 | * @param string $contenttype | |
2255 | * @param bool $cacheable Can this page be cached on back? | |
2256 | * @return void, sends HTTP headers | |
5c355019 | 2257 | */ |
34a2777c | 2258 | function send_headers($contenttype, $cacheable = true) { |
5c754932 PS |
2259 | global $CFG; |
2260 | ||
34a2777c | 2261 | @header('Content-Type: ' . $contenttype); |
2262 | @header('Content-Script-Type: text/javascript'); | |
2263 | @header('Content-Style-Type: text/css'); | |
79192273 PS |
2264 | |
2265 | if (empty($CFG->additionalhtmlhead) or stripos($CFG->additionalhtmlhead, 'X-UA-Compatible') === false) { | |
2266 | @header('X-UA-Compatible: IE=edge'); | |
2267 | } | |
f9903ed0 | 2268 | |
34a2777c | 2269 | if ($cacheable) { |
2e1d38db | 2270 | // Allow caching on "back" (but not on normal clicks). |
c3a3f540 | 2271 | @header('Cache-Control: private, pre-check=0, post-check=0, max-age=0, no-transform'); |
34a2777c | 2272 | @header('Pragma: no-cache'); |
2273 | @header('Expires: '); | |
2274 | } else { | |
2e1d38db | 2275 | // Do everything we can to always prevent clients and proxies caching. |
34a2777c | 2276 | @header('Cache-Control: no-store, no-cache, must-revalidate'); |
c3a3f540 | 2277 | @header('Cache-Control: post-check=0, pre-check=0, no-transform', false); |
34a2777c | 2278 | @header('Pragma: no-cache'); |
2279 | @header('Expires: Mon, 20 Aug 1969 09:23:00 GMT'); | |
2280 | @header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT'); | |
2281 | } | |
2282 | @header('Accept-Ranges: none'); | |
5c754932 | 2283 | |
b5d889be JL |
2284 | // The Moodle app must be allowed to embed content always. |
2285 | if (empty($CFG->allowframembedding) && !core_useragent::is_moodle_app()) { | |
5c754932 PS |
2286 | @header('X-Frame-Options: sameorigin'); |
2287 | } | |
34a2777c | 2288 | } |
9fa49e22 | 2289 | |
ce3735d4 | 2290 | /** |
a84dea2c | 2291 | * Return the right arrow with text ('next'), and optionally embedded in a link. |
449611af | 2292 | * |
ac905235 | 2293 | * @param string $text HTML/plain text label (set to blank only for breadcrumb separator cases). |
a84dea2c | 2294 | * @param string $url An optional link to use in a surrounding HTML anchor. |
2295 | * @param bool $accesshide True if text should be hidden (for screen readers only). | |
2296 | * @param string $addclass Additional class names for the link, or the arrow character. | |
2297 | * @return string HTML string. | |
ce3735d4 | 2298 | */ |
162f90e5 | 2299 | function link_arrow_right($text, $url='', $accesshide=false, $addclass='', $addparams = []) { |
2e1d38db | 2300 | global $OUTPUT; // TODO: move to output renderer. |
a84dea2c | 2301 | $arrowclass = 'arrow '; |
2e1d38db | 2302 | if (!$url) { |
a84dea2c | 2303 | $arrowclass .= $addclass; |
2304 | } | |
92e01ab7 | 2305 | $arrow = '<span class="'.$arrowclass.'">'.$OUTPUT->rarrow().'</span>'; |
a84dea2c | 2306 | $htmltext = ''; |
2307 | if ($text) { | |
388794fd | 2308 | $htmltext = '<span class="arrow_text">'.$text.'</span> '; |
a84dea2c | 2309 | if ($accesshide) { |
1d75edd0 | 2310 | $htmltext = get_accesshide($htmltext); |
a84dea2c | 2311 | } |
ce3735d4 | 2312 | } |
a84dea2c | 2313 | if ($url) { |
388794fd | 2314 | $class = 'arrow_link'; |
a84dea2c | 2315 | if ($addclass) { |
388794fd | 2316 | $class .= ' '.$addclass; |
a84dea2c | 2317 | } |
162f90e5 AN |
2318 | |
2319 | $linkparams = [ | |
2320 | 'class' => $class, | |
2321 | 'href' => $url, | |
2322 | 'title' => preg_replace('/<.*?>/', '', $text), | |
2323 | ]; | |
2324 | ||
2325 | $linkparams += $addparams; | |
2326 | ||
2327 | return html_writer::link($url, $htmltext . $arrow, $linkparams); | |
a84dea2c | 2328 | } |
2329 | return $htmltext.$arrow; | |
ce3735d4 | 2330 | } |
2331 | ||
2332 | /** | |
a84dea2c | 2333 | * Return the left arrow with text ('previous'), and optionally embedded in a link. |
449611af | 2334 | * |
ac905235 | 2335 | * @param string $text HTML/plain text label (set to blank only for breadcrumb separator cases). |
a84dea2c | 2336 | * @param string $url An optional link to use in a surrounding HTML anchor. |
2337 | * @param bool $accesshide True if text should be hidden (for screen readers only). | |
2338 | * @param string $addclass Additional class names for the link, or the arrow character. | |
2339 | * @return string HTML string. | |
ce3735d4 | 2340 | */ |
162f90e5 | 2341 | function link_arrow_left($text, $url='', $accesshide=false, $addclass='', $addparams = []) { |
2e1d38db | 2342 | global $OUTPUT; // TODO: move to utput renderer. |
a84dea2c | 2343 | $arrowclass = 'arrow '; |
2344 | if (! $url) { | |
2345 | $arrowclass .= $addclass; | |
2346 | } | |
92e01ab7 | 2347 | $arrow = '<span class="'.$arrowclass.'">'.$OUTPUT->larrow().'</span>'; |
a84dea2c | 2348 | $htmltext = ''; |
2349 | if ($text) { | |
388794fd | 2350 | $htmltext = ' <span class="arrow_text">'.$text.'</span>'; |
a84dea2c | 2351 | if ($accesshide) { |
1d75edd0 | 2352 | $htmltext = get_accesshide($htmltext); |
a84dea2c | 2353 | } |
ce3735d4 | 2354 | } |
a84dea2c | 2355 | if ($url) { |
388794fd | 2356 | $class = 'arrow_link'; |
a84dea2c | 2357 | if ($addclass) { |
388794fd | 2358 | $class .= ' '.$addclass; |
a84dea2c | 2359 | } |
162f90e5 AN |
2360 | |
2361 | $linkparams = [ | |
2362 | 'class' => $class, | |
2363 | 'href' => $url, | |
2364 | 'title' => preg_replace('/<.*?>/', '', $text), | |
2365 | ]; | |
2366 | ||
2367 | $linkparams += $addparams; | |
2368 | ||
2369 | return html_writer::link($url, $arrow . $htmltext, $linkparams); | |
a84dea2c | 2370 | } |
2371 | return $arrow.$htmltext; | |
2372 | } | |
2373 | ||
1d75edd0 | 2374 | /** |
2375 | * Return a HTML element with the class "accesshide", for accessibility. | |
2e1d38db | 2376 | * |
449611af | 2377 | * Please use cautiously - where possible, text should be visible! |
2378 | * | |
1d75edd0 | 2379 | * @param string $text Plain text. |
2380 | * @param string $elem Lowercase element name, default "span". | |
2381 | * @param string $class Additional classes for the element. | |
2382 | * @param string $attrs Additional attributes string in the form, "name='value' name2='value2'" | |
2383 | * @return string HTML string. | |
2384 | */ | |
2385 | function get_accesshide($text, $elem='span', $class='', $attrs='') { | |
2386 | return "<$elem class=\"accesshide $class\" $attrs>$text</$elem>"; | |
2387 | } | |
2388 | ||
a84dea2c | 2389 | /** |
2390 | * Return the breadcrumb trail navigation separator. | |
449611af | 2391 | * |
a84dea2c | 2392 | * @return string HTML string. |
2393 | */ | |
2394 | function get_separator() { | |
2e1d38db | 2395 | // Accessibility: the 'hidden' slash is preferred for screen readers. |
a84dea2c | 2396 | return ' '.link_arrow_right($text='/', $url='', $accesshide=true, 'sep').' '; |
ce3735d4 | 2397 | } |
2398 | ||
512c5901 | 2399 | /** |
2e1d38db | 2400 | * Print (or return) a collapsible region, that has a caption that can be clicked to expand or collapse the region. |
49c8c8d2 | 2401 | * |
fa9f6bf6 | 2402 | * If JavaScript is off, then the region will always be expanded. |
512c5901 | 2403 | * |
2404 | * @param string $contents the contents of the box. | |
2405 | * @param string $classes class names added to the div that is output. | |
2406 | * @param string $id id added to the div that is output. Must not be blank. | |
2407 | * @param string $caption text displayed at the top. Clicking on this will cause the region to expand or contract. | |
fa9f6bf6 | 2408 | * @param string $userpref the name of the user preference that stores the user's preferred default state. |
512c5901 | 2409 | * (May be blank if you do not wish the state to be persisted. |
fa9f6bf6 | 2410 | * @param boolean $default Initial collapsed state to use if the user_preference it not set. |
512c5901 | 2411 | * @param boolean $return if true, return the HTML as a string, rather than printing it. |
449611af | 2412 | * @return string|void If $return is false, returns nothing, otherwise returns a string of HTML. |
512c5901 | 2413 | */ |
f2eb5002 | 2414 | function print_collapsible_region($contents, $classes, $id, $caption, $userpref = '', $default = false, $return = false) { |
ad9ab4df | 2415 | $output = print_collapsible_region_start($classes, $id, $caption, $userpref, $default, true); |
f2eb5002 | 2416 | $output .= $contents; |
2417 | $output .= print_collapsible_region_end(true); | |
2418 | ||
2419 | if ($return) { | |
2420 | return $output; | |
2421 | } else { | |
2422 | echo $output; | |
2423 | } | |
2424 | } | |
2425 | ||
512c5901 | 2426 | /** |
2e1d38db SH |
2427 | * Print (or return) the start of a collapsible region |
2428 | * | |
2429 | * The collapsibleregion has a caption that can be clicked to expand or collapse the region. If JavaScript is off, then the region | |
fa9f6bf6 | 2430 | * will always be expanded. |
512c5901 | 2431 | * |
2432 | * @param string $classes class names added to the div that is output. | |
2433 | * @param string $id id added to the div that is output. Must not be blank. | |
2434 | * @param string $caption text displayed at the top. Clicking on this will cause the region to expand or contract. | |
ad9ab4df | 2435 | * @param string $userpref the name of the user preference that stores the user's preferred default state. |
512c5901 | 2436 | * (May be blank if you do not wish the state to be persisted. |
fa9f6bf6 | 2437 | * @param boolean $default Initial collapsed state to use if the user_preference it not set. |
512c5901 | 2438 | * @param boolean $return if true, return the HTML as a string, rather than printing it. |
449611af | 2439 | * @return string|void if $return is false, returns nothing, otherwise returns a string of HTML. |
512c5901 | 2440 | */ |
ad9ab4df | 2441 | function print_collapsible_region_start($classes, $id, $caption, $userpref = '', $default = false, $return = false) { |
2e1d38db | 2442 | global $PAGE; |
f2eb5002 | 2443 | |
f2eb5002 | 2444 | // Work out the initial state. |
ad9ab4df | 2445 | if (!empty($userpref) and is_string($userpref)) { |
f2eb5002 | 2446 | user_preference_allow_ajax_update($userpref, PARAM_BOOL); |
2447 | $collapsed = get_user_preferences($userpref, $default); | |
2448 | } else { | |
2449 | $collapsed = $default; | |
2450 | $userpref = false; | |
2451 | } | |
2452 | ||
67c8a3e8 | 2453 | if ($collapsed) { |
2454 | $classes .= ' collapsed'; | |
2455 | } | |
2456 | ||
f2eb5002 | 2457 | $output = ''; |
2458 | $output .= '<div id="' . $id . '" class="collapsibleregion ' . $classes . '">'; | |
67c8a3e8 | 2459 | $output .= '<div id="' . $id . '_sizer">'; |
f2eb5002 | 2460 | $output .= '<div id="' . $id . '_caption" class="collapsibleregioncaption">'; |
2461 | $output .= $caption . ' '; | |
67c8a3e8 | 2462 | $output .= '</div><div id="' . $id . '_inner" class="collapsibleregioninner">'; |
38224dcb | 2463 | $PAGE->requires->js_init_call('M.util.init_collapsible_region', array($id, $userpref, get_string('clicktohideshow'))); |
f2eb5002 | 2464 | |
2465 | if ($return) { | |
2466 | return $output; | |
2467 | } else { | |
2468 | echo $output; | |
2469 | } | |
2470 | } | |
2471 | ||
512c5901 | 2472 | /** |
2473 | * Close a region started with print_collapsible_region_start. | |
2474 | * | |
2475 | * @param boolean $return if true, return the HTML as a string, rather than printing it. | |
449611af | 2476 | * @return string|void if $return is false, returns nothing, otherwise returns a string of HTML. |
512c5901 | 2477 | */ |
f2eb5002 | 2478 | function print_collapsible_region_end($return = false) { |
904998d8 | 2479 | $output = '</div></div></div>'; |
f2eb5002 | 2480 | |
2481 | if ($return) { | |
2482 | return $output; | |
2483 | } else { | |
2484 | echo $output; | |
2485 | } | |
2486 | } | |
2487 | ||
d48b00b4 | 2488 | /** |
2489 | * Print a specified group's avatar. | |
2490 | * | |
a8ff9488 | 2491 | * @param array|stdClass $group A single {@link group} object OR array of groups. |
ce3735d4 | 2492 | * @param int $courseid The course ID. |
2493 | * @param boolean $large Default small picture, or large. | |
2494 | * @param boolean $return If false print picture, otherwise return the output as string | |
2495 | * @param boolean $link Enclose image in a link to view specified course? | |
883f6555 | 2496 | * @param boolean $includetoken Whether to use a user token when displaying this group image. |
26e778d1 JL |
2497 | * True indicates to generate a token for current user, and integer value indicates to generate a token for the |
2498 | * user whose id is the value indicated. | |
883f6555 AN |
2499 | * If the group picture is included in an e-mail or some other location where the audience is a specific |
2500 | * user who will not be logged in when viewing, then we use a token to authenticate the user. | |
449611af | 2501 | * @return string|void Depending on the setting of $return |
d48b00b4 | 2502 | */ |
883f6555 | 2503 | function print_group_picture($group, $courseid, $large = false, $return = false, $link = true, $includetoken = false) { |
f374fb10 | 2504 | global $CFG; |
2505 | ||
fdcd0f05 | 2506 | if (is_array($group)) { |
2507 | $output = ''; | |
2e1d38db | 2508 | foreach ($group as $g) { |
883f6555 | 2509 | $output .= print_group_picture($g, $courseid, $large, true, $link, $includetoken); |
fdcd0f05 | 2510 | } |
da4124be | 2511 | if ($return) { |
fdcd0f05 | 2512 | return $output; |
2513 | } else { | |
2514 | echo $output; | |
2515 | return; | |
2516 | } | |
2517 | } | |
2518 | ||
883f6555 | 2519 | $pictureurl = get_group_picture_url($group, $courseid, $large, $includetoken); |
c550fd0e AG |
2520 | |
2521 | // If there is no picture, do nothing. | |
2522 | if (!isset($pictureurl)) { | |
2523 | return; | |
2524 | } | |
2525 | ||
2526 | $context = context_course::instance($courseid); | |
2527 | ||
2528 | $groupname = s($group->name); | |
2529 | $pictureimage = html_writer::img($pictureurl, $groupname, ['title' => $groupname]); | |
2530 | ||
2531 | $output = ''; | |
2532 | if ($link or has_capability('moodle/site:accessallgroups', $context)) { | |
2533 | $linkurl = new moodle_url('/user/index.php', ['id' => $courseid, 'group' => $group->id]); | |
2534 | $output .= html_writer::link($linkurl, $pictureimage); | |
2535 | } else { | |
2536 | $output .= $pictureimage; | |
2537 | } | |
2538 | ||
2539 | if ($return) { | |
2540 | return $output; | |
2541 | } else { | |
2542 | echo $output; | |
2543 | } | |
2544 | } | |
2545 | ||
2546 | /** | |
2547 | * Return the url to the group picture. | |
2548 | * | |
2549 | * @param stdClass $group A group object. | |
2550 | * @param int $courseid The course ID for the group. | |
2551 | * @param bool $large A large or small group picture? Default is small. | |
883f6555 | 2552 | * @param boolean $includetoken Whether to use a user token when displaying this group image. |
26e778d1 JL |
2553 | * True indicates to generate a token for current user, and integer value indicates to generate a token for the |
2554 | * user whose id is the value indicated. | |
883f6555 AN |
2555 | * If the group picture is included in an e-mail or some other location where the audience is a specific |
2556 | * user who will not be logged in when viewing, then we use a token to authenticate the user. | |
c550fd0e AG |
2557 | * @return moodle_url Returns the url for the group picture. |
2558 | */ | |
883f6555 | 2559 | function get_group_picture_url($group, $courseid, $large = false, $includetoken = false) { |
c550fd0e AG |
2560 | global $CFG; |
2561 | ||
b0c6dc1c | 2562 | $context = context_course::instance($courseid); |
97ea4833 | 2563 | |
2e1d38db | 2564 | // If there is no picture, do nothing. |
4a9cf90e | 2565 | if (!$group->picture) { |
c550fd0e | 2566 | return; |
4a9cf90e SM |
2567 | } |
2568 | ||
2e1d38db | 2569 | // If picture is hidden, only show to those with course:managegroups. |
ec7a8b79 | 2570 | if ($group->hidepicture and !has_capability('moodle/course:managegroups', $context)) { |
c550fd0e | 2571 | return; |
3c0561cf | 2572 | } |
c3cbfe7f | 2573 | |
3c0561cf | 2574 | if ($large) { |
b0ccd3fb | 2575 | $file = 'f1'; |
3c0561cf | 2576 | } else { |
b0ccd3fb | 2577 | $file = 'f2'; |
3c0561cf | 2578 | } |
4a9cf90e | 2579 | |
883f6555 AN |
2580 | $grouppictureurl = moodle_url::make_pluginfile_url( |
2581 | $context->id, 'group', 'icon', $group->id, '/', $file, false, $includetoken); | |
21449d01 | 2582 | $grouppictureurl->param('rev', $group->picture); |
c550fd0e | 2583 | return $grouppictureurl; |
f374fb10 | 2584 | } |
2585 | ||
9fa49e22 | 2586 | |
449611af | 2587 | /** |
2588 | * Display a recent activity note | |
49c8c8d2 | 2589 | * |
449611af | 2590 | * @staticvar string $strftimerecent |
2e1d38db SH |
2591 | * @param int $time A timestamp int. |
2592 | * @param stdClass $user A user object from the database. | |
449611af | 2593 | * @param string $text Text for display for the note |
2594 | * @param string $link The link to wrap around the text | |
2595 | * @param bool $return If set to true the HTML is returned rather than echo'd | |
2596 | * @param string $viewfullnames | |
2e1d38db | 2597 | * @return string If $retrun was true returns HTML for a recent activity notice. |
449611af | 2598 | */ |
dd97c328 | 2599 | function print_recent_activity_note($time, $user, $text, $link, $return=false, $viewfullnames=null) { |
2600 | static $strftimerecent = null; | |
da4124be | 2601 | $output = ''; |
2602 | ||
dd97c328 | 2603 | if (is_null($viewfullnames)) { |
b0c6dc1c | 2604 | $context = context_system::instance(); |
dd97c328 | 2605 | $viewfullnames = has_capability('moodle/site:viewfullnames', $context); |
2606 | } | |
3f8a3834 | 2607 | |
dd97c328 | 2608 | if (is_null($strftimerecent)) { |
8f7dc7f1 | 2609 | $strftimerecent = get_string('strftimerecent'); |
2610 | } | |
2611 | ||
da4124be | 2612 | $output .= '<div class="head">'; |
dd97c328 | 2613 | $output .= '<div class="date">'.userdate($time, $strftimerecent).'</div>'; |
2614 | $output .= '<div class="name">'.fullname($user, $viewfullnames).'</div>'; | |
da4124be | 2615 | $output .= '</div>'; |
2e1d38db | 2616 | $output .= '<div class="info"><a href="'.$link.'">'.format_string($text, true).'</a></div>'; |
da4124be | 2617 | |
2618 | if ($return) { | |
2619 | return $output; | |
2620 | } else { | |
2621 | echo $output; | |
2622 | } | |
8f7dc7f1 | 2623 | } |
2624 | ||
f3a74e68 | 2625 | /** |
449611af | 2626 | * Returns a popup menu with course activity modules |
2627 | * | |
2e1d38db SH |
2628 | * Given a course this function returns a small popup menu with all the course activity modules in it, as a navigation menu |
2629 | * outputs a simple list structure in XHTML. | |
2630 | * The data is taken from the serialised array stored in the course record. | |
449611af | 2631 | * |
449611af | 2632 | * @param course $course A {@link $COURSE} object. |
2e1d38db SH |
2633 | * @param array $sections |
2634 | * @param course_modinfo $modinfo | |
449611af | 2635 | * @param string $strsection |
2636 | * @param string $strjumpto | |
2637 | * @param int $width | |
2638 | * @param string $cmid | |
2639 | * @return string The HTML block | |
f3a74e68 | 2640 | */ |
85489a5b | 2641 | function navmenulist($course, $sections, $modinfo, $strsection, $strjumpto, $width=50, $cmid=0) { |
f3a74e68 | 2642 | |
4bc685df | 2643 | global $CFG, $OUTPUT; |
f3a74e68 | 2644 | |
f3a74e68 | 2645 | $section = -1; |
f3a74e68 | 2646 | $menu = array(); |
dd97c328 | 2647 | $doneheading = false; |
f3a74e68 | 2648 | |
850acb35 | 2649 | $courseformatoptions = course_get_format($course)->get_format_options(); |
b0c6dc1c | 2650 | $coursecontext = context_course::instance($course->id); |
85489a5b | 2651 | |
36c446cb | 2652 | $menu[] = '<ul class="navmenulist"><li class="jumpto section"><span>'.$strjumpto.'</span><ul>'; |
dd97c328 | 2653 | foreach ($modinfo->cms as $mod) { |
0d8b6a69 | 2654 | if (!$mod->has_view()) { |
2655 | // Don't show modules which you can't link to! | |
f3a74e68 | 2656 | continue; |
2657 | } | |
2658 | ||
2e1d38db | 2659 | // For course formats using 'numsections' do not show extra sections. |
850acb35 | 2660 | if (isset($courseformatoptions['numsections']) && $mod->sectionnum > $courseformatoptions['numsections']) { |
f3a74e68 | 2661 | break; |
2662 | } | |
2663 | ||
2e1d38db | 2664 | if (!$mod->uservisible) { // Do not icnlude empty sections at all. |
dd97c328 | 2665 | continue; |
2666 | } | |
2667 | ||
76cbde41 | 2668 | if ($mod->sectionnum >= 0 and $section != $mod->sectionnum) { |
2669 | $thissection = $sections[$mod->sectionnum]; | |
f3a74e68 | 2670 | |
850acb35 MG |
2671 | if ($thissection->visible or |
2672 | (isset($courseformatoptions['hiddensections']) and !$courseformatoptions['hiddensections']) or | |
2673 | has_capability('moodle/course:viewhiddensections', $coursecontext)) { | |
2e1d38db | 2674 | $thissection->summary = strip_tags(format_string($thissection->summary, true)); |
dd97c328 | 2675 | if (!$doneheading) { |
dfe66174 | 2676 | $menu[] = '</ul></li>'; |
f3a74e68 | 2677 | } |
2678 | if ($course->format == 'weeks' or empty($thissection->summary)) { | |
76cbde41 | 2679 | $item = $strsection ." ". $mod->sectionnum; |
f3a74e68 | 2680 | } else { |
2f1e464a | 2681 | if (core_text::strlen($thissection->summary) < ($width-3)) { |
b3ab80aa | 2682 | $item = $thissection->summary; |
f3a74e68 | 2683 | } else { |
2f1e464a | 2684 | $item = core_text::substr($thissection->summary, 0, $width).'...'; |
f3a74e68 | 2685 | } |
2686 | } | |
36c446cb | 2687 | $menu[] = '<li class="section"><span>'.$item.'</span>'; |
f3a74e68 | 2688 | $menu[] = '<ul>'; |
2689 | $doneheading = true; | |
dd97c328 | 2690 | |
76cbde41 | 2691 | $section = $mod->sectionnum; |
dd97c328 | 2692 | } else { |
2e1d38db | 2693 | // No activities from this hidden section shown. |
dd97c328 | 2694 | continue; |
f3a74e68 | 2695 | } |
2696 | } | |
2697 | ||
dd97c328 | 2698 | $url = $mod->modname .'/view.php?id='. $mod->id; |
9a9012dc | 2699 | $mod->name = strip_tags(format_string($mod->name ,true)); |
2f1e464a PS |
2700 | if (core_text::strlen($mod->name) > ($width+5)) { |
2701 | $mod->name = core_text::substr($mod->name, 0, $width).'...'; | |
f3a74e68 | 2702 | } |
dd97c328 | 2703 | if (!$mod->visible) { |
2704 | $mod->name = '('.$mod->name.')'; | |
2705 | } | |
2706 | $class = 'activity '.$mod->modname; | |
996c1a6f | 2707 | $class .= ($cmid == $mod->id) ? ' selected' : ''; |
dd97c328 | 2708 | $menu[] = '<li class="'.$class.'">'. |
3e6adcd6 | 2709 | $OUTPUT->image_icon('icon', '', $mod->modname). |
dd97c328 | 2710 | '<a href="'.$CFG->wwwroot.'/mod/'.$url.'">'.$mod->name.'</a></li>'; |
f3a74e68 | 2711 | } |
dd97c328 | 2712 | |
dfe66174 | 2713 | if ($doneheading) { |
f713e270 | 2714 | $menu[] = '</ul></li>'; |
dfe66174 | 2715 | } |
143211e5 | 2716 | $menu[] = '</ul></li></ul>'; |
f3a74e68 | 2717 | |
2718 | return implode("\n", $menu); | |
2719 | } | |
2720 | ||
d48b00b4 | 2721 | /** |
2e1d38db | 2722 | * Prints a grade menu (as part of an existing form) with help showing all possible numerical grades and scales. |
d48b00b4 | 2723 | * |
d48b00b4 | 2724 | * @todo Finish documenting this function |
f8065dd2 | 2725 | * @todo Deprecate: this is only used in a few contrib modules |
449611af | 2726 | * |
449611af | 2727 | * @param int $courseid The course ID |
49c8c8d2 | 2728 | * @param string $name |
2729 | * @param string $current | |
449611af | 2730 | * @param boolean $includenograde Include those with no grades |
2731 | * @param boolean $return If set to true returns rather than echo's | |
2732 | * @return string|bool Depending on value of $return | |
d48b00b4 | 2733 | */ |
da4124be | 2734 | function print_grade_menu($courseid, $name, $current, $includenograde=true, $return=false) { |
2e1d38db | 2735 | global $OUTPUT; |
62ca135d | 2736 | |
da4124be | 2737 | $output = ''; |
b0ccd3fb | 2738 | $strscale = get_string('scale'); |
2739 | $strscales = get_string('scales'); | |
62ca135d | 2740 | |
1f7deef6 | 2741 | $scales = get_scales_menu($courseid); |
62ca135d | 2742 | foreach ($scales as $i => $scalename) { |
b0ccd3fb | 2743 | $grades[-$i] = $strscale .': '. $scalename; |
62ca135d | 2744 | } |
d6bdd9d5 | 2745 | if ($includenograde) { |
b0ccd3fb | 2746 | $grades[0] = get_string('nograde'); |
d6bdd9d5 | 2747 | } |
62ca135d | 2748 | for ($i=100; $i>=1; $i--) { |
2749 | $grades[$i] = $i; | |
2750 | } | |
d776d59e | 2751 | $output .= html_writer::select($grades, $name, $current, false); |
62ca135d | 2752 | |
663640f5 | 2753 | $linkobject = '<span class="helplink">' . $OUTPUT->pix_icon('help', $strscales) . '</span>'; |
2e1d38db | 2754 | $link = new moodle_url('/course/scales.php', array('id' => $courseid, 'list' => 1)); |
48561e1b | 2755 | $action = new popup_action('click', $link, 'ratingscales', array('height' => 400, 'width' => 500)); |
2e1d38db | 2756 | $output .= $OUTPUT->action_link($link, $linkobject, $action, array('title' => $strscales)); |
da4124be | 2757 | |
2758 | if ($return) { | |
2759 | return $output; | |
2760 | } else { | |
2761 | echo $output; | |
2762 | } | |
62ca135d | 2763 | } |
2764 | ||
7cfb11db | 2765 | /** |
2766 | * Print an error to STDOUT and exit with a non-zero code. For commandline scripts. | |
2e1d38db | 2767 | * |
7cfb11db | 2768 | * Default errorcode is 1. |
2769 | * | |
2770 | * Very useful for perl-like error-handling: | |
7cfb11db | 2771 | * do_somethting() or mdie("Something went wrong"); |
2772 | * | |
2773 | * @param string $msg Error message | |
73f7ad71 | 2774 | * @param integer $errorcode Error code to emit |
7cfb11db | 2775 | */ |
2776 | function mdie($msg='', $errorcode=1) { | |
2777 | trigger_error($msg); | |
2778 | exit($errorcode); | |
2779 | } | |
2780 | ||
d48b00b4 | 2781 | /** |
2782 | * Print a message and exit. | |
2783 | * | |
449611af | 2784 | * @param string $message The message to print in the notice |
745212bd | 2785 | * @param moodle_url|string $link The link to use for the continue button |
2e1d38db | 2786 | * @param object $course A course object. Unused. |
449611af | 2787 | * @return void This function simply exits |
d48b00b4 | 2788 | */ |
2e1d38db SH |
2789 | function notice ($message, $link='', $course=null) { |
2790 | global $PAGE, $OUTPUT; | |
9fa49e22 | 2791 | |
2e1d38db | 2792 | $message = clean_text($message); // In case nasties are in here. |
9f7f1a74 | 2793 | |
a91b910e | 2794 | if (CLI_SCRIPT) { |
258d5322 | 2795 | echo("!!$message!!\n"); |
2e1d38db | 2796 | exit(1); // No success. |
d795bfdb | 2797 | } |
2798 | ||
c13a5e71 | 2799 | if (!$PAGE->headerprinted) { |
2e1d38db | 2800 | // Header not yet printed. |
de6d81e6 | 2801 | $PAGE->set_title(get_string('notice')); |
2802 | echo $OUTPUT->header(); | |
d795bfdb | 2803 | } else { |
f6794ace | 2804 | echo $OUTPUT->container_end_all(false); |
d795bfdb | 2805 | } |
9fa49e22 | 2806 | |
ea85e1ee | 2807 | echo $OUTPUT->box($message, 'generalbox', 'notice'); |
aa9a6867 | 2808 | echo $OUTPUT->continue_button($link); |
5ce73257 | 2809 | |
7e0d6675 | 2810 | echo $OUTPUT->footer(); |
2e1d38db | 2811 | exit(1); // General error code. |
9fa49e22 | 2812 | } |
2813 | ||
d48b00b4 | 2814 | /** |
2e1d38db | 2815 | * Redirects the user to another page, after printing a notice. |
d48b00b4 | 2816 | * |
2e1d38db | 2817 | * This function calls the OUTPUT redirect method, echo's the output and then dies to ensure nothing else happens. |
e8775320 | 2818 | * |
2819 | * <strong>Good practice:</strong> You should call this method before starting page | |
2820 | * output by using any of the OUTPUT methods. | |
449611af | 2821 | * |
db82872e | 2822 | * @param moodle_url|string $url A moodle_url to redirect to. Strings are not to be trusted! |
e8775320 | 2823 | * @param string $message The message to display to the user |
2824 | * @param int $delay The delay before redirecting | |
3ad96419 | 2825 | * @param string $messagetype The type of notification to show the message in. See constants on \core\output\notification. |
2e1d38db | 2826 | * @throws moodle_exception |
d48b00b4 | 2827 | */ |
372d6b92 | 2828 | function redirect($url, $message='', $delay=null, $messagetype = \core\output\notification::NOTIFY_INFO) { |
2e1d38db | 2829 | global $OUTPUT, $PAGE, $CFG; |
d3f9f1f8 | 2830 | |
1adaa404 | 2831 | if (CLI_SCRIPT or AJAX_SCRIPT) { |
2e1d38db | 2832 | // This is wrong - developers should not use redirect in these scripts but it should not be very likely. |
1adaa404 PS |
2833 | throw new moodle_exception('redirecterrordetected', 'error'); |
2834 | } | |
2835 | ||
372d6b92 AN |
2836 | if ($delay === null) { |
2837 | $delay = -1; | |
2838 | } | |
2839 | ||
2e1d38db | 2840 | // Prevent debug errors - make sure context is properly initialised. |
9b540305 PS |
2841 | if ($PAGE) { |
2842 | $PAGE->set_context(null); | |
2e1d38db | 2843 | $PAGE->set_pagelayout('redirect'); // No header and footer needed. |
e3288953 | 2844 | $PAGE->set_title(get_string('pageshouldredirect', 'moodle')); |
9b540305 | 2845 | } |
afa7cfa8 | 2846 | |
366c7499 | 2847 | if ($url instanceof moodle_url) { |
b9bc2019 | 2848 | $url = $url->out(false); |
366c7499 | 2849 | } |
2850 | ||
afa7cfa8 PS |
2851 | $debugdisableredirect = false; |
2852 | do { | |
2853 | if (defined('DEBUGGING_PRINTED')) { | |
2e1d38db | 2854 | // Some debugging already printed, no need to look more. |
afa7cfa8 PS |
2855 | $debugdisableredirect = true; |
2856 | break; | |
2857 | } | |
2858 | ||
f63dec4b FM |
2859 | if (core_useragent::is_msword()) { |
2860 | // Clicking a URL from MS Word sends a request to the server without cookies. If that | |
2861 | // causes a redirect Word will open a browser pointing the new URL. If not, the URL that | |
2862 | // was clicked is opened. Because the request from Word is without cookies, it almost | |
2863 | // always results in a redirect to the login page, even if the user is logged in in their | |
2864 | // browser. This is not what we want, so prevent the redirect for requests from Word. | |
2865 | $debugdisableredirect = true; | |
2866 | break; | |
2867 | } | |
2868 | ||
afa7cfa8 | 2869 | if (empty($CFG->debugdisplay) or empty($CFG->debug)) { |
2e1d38db | 2870 | // No errors should be displayed. |
afa7cfa8 PS |
2871 | break; |
2872 | } | |
2873 | ||
2874 | if (!function_exists('error_get_last') or !$lasterror = error_get_last()) { | |
2875 | break; | |
2876 | } | |
2877 | ||
2878 | if (!($lasterror['type'] & $CFG->debug)) { | |
2e1d38db | 2879 | // Last error not interesting. |
afa7cfa8 PS |
2880 | break; |
2881 | } | |
2882 | ||
2e1d38db | 2883 | // Watch out here, @hidden() errors are returned from error_get_last() too. |
afa7cfa8 | 2884 | if (headers_sent()) { |
2e1d38db | 2885 | // We already started printing something - that means errors likely printed. |
afa7cfa8 PS |
2886 | $debugdisableredirect = true; |
2887 | break; | |
2888 | } | |
2889 | ||
2890 | if (ob_get_level() and ob_get_contents()) { | |
2e1d38db SH |
2891 | // There is something waiting to be printed, hopefully it is the errors, |
2892 | // but it might be some error hidden by @ too - such as the timezone mess from setup.php. | |
afa7cfa8 PS |
2893 | $debugdisableredirect = true; |
2894 | break; | |
2895 | } | |
2896 | } while (false); | |
ae96b517 | 2897 | |
581e8dba PS |
2898 | // Technically, HTTP/1.1 requires Location: header to contain the absolute path. |
2899 | // (In practice browsers accept relative paths - but still, might as well do it properly.) | |
2900 | // This code turns relative into absolute. | |
3c3d38d0 | 2901 | if (!preg_match('|^[a-z]+:|i', $url)) { |
2e1d38db | 2902 | // Get host name http://www.wherever.com. |
581e8dba PS |
2903 | $hostpart = preg_replace('|^(.*?[^:/])/.*$|', '$1', $CFG->wwwroot); |
2904 | if (preg_match('|^/|', $url)) { | |
2e1d38db | 2905 | // URLs beginning with / are relative to web server root so we just add them in. |
581e8dba PS |
2906 | $url = $hostpart.$url; |
2907 | } else { | |
2908 | // URLs not beginning with / are relative to path of current script, so add that on. | |
2e1d38db | 2909 | $url = $hostpart.preg_replace('|\?.*$|', '', me()).'/../'.$url; |
581e8dba | 2910 | } |
2e1d38db | 2911 | // Replace all ..s. |
581e8dba PS |
2912 | while (true) { |
2913 | $newurl = preg_replace('|/(?!\.\.)[^/]*/\.\./|', '/', $url); | |
2914 | if ($newurl == $url) { | |
2915 | break; | |
2916 | } | |
2917 | $url = $newurl; | |
2918 | } | |
2919 | } | |
2920 | ||
2921 | // Sanitise url - we can not rely on moodle_url or our URL cleaning | |
2e1d38db | 2922 | // because they do not support all valid external URLs. |
581e8dba PS |
2923 | $url = preg_replace('/[\x00-\x1F\x7F]/', '', $url); |
2924 | $url = str_replace('"', '%22', $url); | |
2925 | $encodedurl = preg_replace("/\&(?![a-zA-Z0-9#]{1,8};)/", "&", $url); | |
2926 | $encodedurl = preg_replace('/^.*href="([^"]*)".*$/', "\\1", clean_text('<a href="'.$encodedurl.'" />', FORMAT_HTML)); | |
2927 | $url = str_replace('&', '&', $encodedurl); | |
2928 | ||
ae96b517 | 2929 | if (!empty($message)) { |
3ad96419 AN |
2930 | if (!$debugdisableredirect && !headers_sent()) { |
2931 | // A message has been provided, and the headers have not yet been sent. | |
2932 | // Display the message as a notification on the subsequent page. | |
2933 | \core\notification::add($message, $messagetype); | |
2934 | $message = null; | |
2935 | $delay = 0; | |
2936 | } else { | |
2937 | if ($delay === -1 || !is_numeric($delay)) { | |
2938 | $delay = 3; | |
2939 | } | |
2940 | $message = clean_text($message); | |
3446daa3 | 2941 | } |
e8775320 | 2942 | } else { |
ae96b517 | 2943 | $message = get_string('pageshouldredirect'); |
e8775320 | 2944 | $delay = 0; |
f231e867 | 2945 | } |
2deebecd | 2946 | |
d79d5ac2 PS |
2947 | // Make sure the session is closed properly, this prevents problems in IIS |
2948 | // and also some potential PHP shutdown issues. | |
2949 | \core\session\manager::write_close(); | |
b399e435 | 2950 | |
d79d5ac2 | 2951 | if ($delay == 0 && !$debugdisableredirect && !headers_sent()) { |
2e1d38db | 2952 | // 302 might not work for POST requests, 303 is ignored by obsolete clients. |
ae96b517 | 2953 | @header($_SERVER['SERVER_PROTOCOL'] . ' 303 See Other'); |
2954 | @header('Location: '.$url); | |
5e39d7aa | 2955 | echo bootstrap_renderer::plain_redirect_message($encodedurl); |
2956 | exit; | |
ae96b517 | 2957 | } |
b7009474 | 2958 | |
ae96b517 | 2959 | // Include a redirect message, even with a HTTP redirect, because that is recommended practice. |
f0f8f9a7 | 2960 | if ($PAGE) { |
2e1d38db | 2961 | $CFG->docroot = false; // To prevent the link to moodle docs from being displayed on redirect page. |
3ad96419 | 2962 | echo $OUTPUT->redirect_message($encodedurl, $message, $delay, $debugdisableredirect, $messagetype); |
f0f8f9a7 PS |
2963 | exit; |
2964 | } else { | |
2965 | echo bootstrap_renderer::early_redirect_message($encodedurl, $message, $delay); | |
2966 | exit; | |
2967 | } | |
9fa49e22 | 2968 | } |
2969 | ||
d48b00b4 | 2970 | /** |
2e1d38db | 2971 | * Given an email address, this function will return an obfuscated version of it. |
d48b00b4 | 2972 | * |
89dcb99d | 2973 | * @param string $email The email address to obfuscate |
449611af | 2974 | * @return string The obfuscated email address |
d48b00b4 | 2975 | */ |
2e1d38db | 2976 | function obfuscate_email($email) { |
43373804 | 2977 | $i = 0; |
2978 | $length = strlen($email); | |
b0ccd3fb | 2979 | $obfuscated = ''; |
43373804 | 2980 | while ($i < $length) { |
2e1d38db | 2981 | if (rand(0, 2) && $email{$i}!='@') { // MDL-20619 some browsers have problems unobfuscating @. |
43373804 | 2982 | $obfuscated.='%'.dechex(ord($email{$i})); |
2983 | } else { | |
2984 | $obfuscated.=$email{$i}; | |
2985 | } | |
2986 | $i++; | |
2987 | } | |
2988 | return $obfuscated; | |
2989 | } | |
2990 | ||
d48b00b4 | 2991 | /** |
2992 | * This function takes some text and replaces about half of the characters | |
2993 | * with HTML entity equivalents. Return string is obviously longer. | |
2994 | * | |
89dcb99d | 2995 | * @param string $plaintext The text to be obfuscated |
449611af | 2996 | * @return string The obfuscated text |
d48b00b4 | 2997 | */ |
43373804 | 2998 | function obfuscate_text($plaintext) { |
43373804 | 2999 | $i=0; |
2f1e464a | 3000 | $length = core_text::strlen($plaintext); |
b0ccd3fb | 3001 | $obfuscated=''; |
2e1d38db | 3002 | $prevobfuscated = false; |
43373804 | 3003 | while ($i < $length) { |
2f1e464a PS |
3004 | $char = core_text::substr($plaintext, $i, 1); |
3005 | $ord = core_text::utf8ord($char); | |
66056f99 | 3006 | $numerical = ($ord >= ord('0')) && ($ord <= ord('9')); |
2e1d38db | 3007 | if ($prevobfuscated and $numerical ) { |
66056f99 | 3008 | $obfuscated.='&#'.$ord.';'; |
2e1d38db | 3009 | } else if (rand(0, 2)) { |
66056f99 | 3010 | $obfuscated.='&#'.$ord.';'; |
2e1d38db | 3011 | $prevobfuscated = true; |
43373804 | 3012 | } else { |
66056f99 | 3013 | $obfuscated.=$char; |
2e1d38db | 3014 | $prevobfuscated = false; |
43373804 | 3015 | } |
2e1d38db | 3016 | $i++; |
43373804 | 3017 | } |
3018 | return $obfuscated; | |
3019 | } | |
3020 | ||
d48b00b4 | 3021 | /** |
89dcb99d | 3022 | * This function uses the {@link obfuscate_email()} and {@link obfuscate_text()} |
3023 | * to generate a fully obfuscated email link, ready to use. | |
d48b00b4 | 3024 | * |
89dcb99d | 3025 | * @param string $email The email address to display |
fa9f6bf6 | 3026 | * @param string $label The text to displayed as hyperlink to $email |
89dcb99d | 3027 | * @param boolean $dimmed If true then use css class 'dimmed' for hyperlink |
c216eb20 FM |
3028 | * @param string $subject The subject of the email in the mailto link |
3029 | * @param string $body The content of the email in the mailto link | |
449611af | 3030 | * @return string The obfuscated mailto link |
d48b00b4 | 3031 | */ |
c216eb20 | 3032 | function obfuscate_mailto($email, $label='', $dimmed=false, $subject = '', $body = '') { |
43373804 | 3033 | |
3034 | if (empty($label)) { | |
3035 | $label = $email; | |
3036 | } | |
c216eb20 FM |
3037 | |
3038 | $label = obfuscate_text($label); | |
3039 | $email = obfuscate_email($email); | |
3040 | $mailto = obfuscate_text('mailto'); | |
3041 | $url = new moodle_url("mailto:$email"); | |
3042 | $attrs = array(); | |
3043 | ||
3044 | if (!empty($subject)) { | |
3045 | $url->param('subject', format_string($subject)); | |
3046 | } | |
3047 | if (!empty($body)) { | |
3048 | $url->param('body', format_string($body)); | |
3049 | } | |
3050 | ||
2e1d38db | 3051 | // Use the obfuscated mailto. |
c216eb20 FM |
3052 | $url = preg_replace('/^mailto/', $mailto, $url->out()); |
3053 | ||
cadb96f2 | 3054 | if ($dimmed) { |
c216eb20 FM |
3055 | $attrs['title'] = get_string('emaildisable'); |
3056 | $attrs['class'] = 'dimmed'; | |
cadb96f2 | 3057 | } |
c216eb20 FM |
3058 | |
3059 | return html_writer::link($url, $label, $attrs); | |
43373804 | 3060 | } |
3061 | ||
d48b00b4 | 3062 | /** |
3063 | * This function is used to rebuild the <nolink> tag because some formats (PLAIN and WIKI) | |
3064 | * will transform it to html entities | |
3065 | * | |
89dcb99d | 3066 | * @param string $text Text to search for nolink tag in |
3067 | * @return string | |
d48b00b4 | 3068 | */ |
ab892a4f | 3069 | function rebuildnolinktag($text) { |
ab9f24ad | 3070 | |
2e1d38db | 3071 | $text = preg_replace('/<(\/*nolink)>/i', '<$1>', $text); |
ab892a4f | 3072 | |
3073 | return $text; | |
3074 | } | |
3075 | ||
1695b680 | 3076 | /** |
2e1d38db | 3077 | * Prints a maintenance message from $CFG->maintenance_message or default if empty. |
1695b680 | 3078 | */ |
4fe2250a | 3079 | function print_maintenance_message() { |
3c159385 | 3080 | global $CFG, $SITE, $PAGE, $OUTPUT; |
a2b3f884 | 3081 | |
f1c6d647 BH |
3082 | header($_SERVER['SERVER_PROTOCOL'] . ' 503 Moodle under maintenance'); |
3083 | header('Status: 503 Moodle under maintenance'); | |
3084 | header('Retry-After: 300'); | |
3085 | ||
ad5d5997 | 3086 | $PAGE->set_pagetype('maintenance-message'); |
78946b9b | 3087 | $PAGE->set_pagelayout('maintenance'); |
de6d81e6 | 3088 | $PAGE->set_title(strip_tags($SITE->fullname)); |
3089 | $PAGE->set_heading($SITE->fullname); | |
3090 | echo $OUTPUT->header(); | |
3c159385 | 3091 | echo $OUTPUT->heading(get_string('sitemaintenance', 'admin')); |
4fe2250a | 3092 | if (isset($CFG->maintenance_message) and !html_is_blank($CFG->maintenance_message)) { |
ea85e1ee | 3093 | echo $OUTPUT->box_start('maintenance_message generalbox boxwidthwide boxaligncenter'); |
4fe2250a | 3094 | echo $CFG->maintenance_message; |
ea85e1ee | 3095 | echo $OUTPUT->box_end(); |
4fe2250a | 3096 | } |
7e0d6675 | 3097 | echo $OUTPUT->footer(); |
4fe2250a | 3098 | die; |
1695b680 | 3099 | } |
3100 | ||
f88ddd67 | 3101 | /** |
0b4f88a6 | 3102 | * Returns a string containing a nested list, suitable for formatting into tabs with CSS. |
f88ddd67 | 3103 | * |
c269b9d1 MG |
3104 | * It is not recommended to use this function in Moodle 2.5 but it is left for backward |
3105 | * compartibility. | |
3106 | * | |
3107 | * Example how to print a single line tabs: | |
3108 | * $rows = array( | |
3109 | * new tabobject(...), | |
3110 | * new tabobject(...) | |
3111 | * ); | |
3112 | * echo $OUTPUT->tabtree($rows, $selectedid); | |
3113 | * | |
3114 | * Multiple row tabs may not look good on some devices but if you want to use them | |
3115 | * you can specify ->subtree for the active tabobject. | |
3116 | * | |
f88ddd67 | 3117 | * @param array $tabrows An array of rows where each row is an array of tab objects |
0b4f88a6 | 3118 | * @param string $selected The id of the selected tab (whatever row it's on) |
3119 | * @param array $inactive An array of ids of inactive tabs that are not selectable. | |
3120 | * @param array $activated An array of ids of other tabs that are currently activated | |
449611af | 3121 | * @param bool $return If true output is returned rather then echo'd |
2e1d38db SH |
3122 | * @return string HTML output if $return was set to true. |
3123 | */ | |
c269b9d1 MG |