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