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