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