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