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