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