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