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