MDL-24041 format_module_intro() - observe the $filter parameter properly.
[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
0c34c7eb 124 return preg_replace("/&amp;(#\d+);/i", "&$1;", htmlspecialchars($var));
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) {
c426ef3a 1500 check_dir_exists($cachedir);
eb203ee4 1501 require_once $CFG->libdir.'/htmlpurifier/HTMLPurifier.safe-includes.php';
e0ac8448 1502 $config = HTMLPurifier_Config::createDefault();
8ac11ff2 1503 $config->set('Output.Newline', "\n");
6ec450fb 1504 $config->set('Core.ConvertDocumentToFragment', true);
1505 $config->set('Core.Encoding', 'UTF-8');
1506 $config->set('HTML.Doctype', 'XHTML 1.0 Transitional');
1507 $config->set('Cache.SerializerPath', $cachedir);
1508 $config->set('URI.AllowedSchemes', array('http'=>1, 'https'=>1, 'ftp'=>1, 'irc'=>1, 'nntp'=>1, 'news'=>1, 'rtsp'=>1, 'teamspeak'=>1, 'gopher'=>1, 'mms'=>1));
1509 $config->set('Attr.AllowedFrameTargets', array('_blank'));
e0ac8448 1510 $purifier = new HTMLPurifier($config);
1511 }
1512 return $purifier->purify($text);
1513}
1514
d48b00b4 1515/**
89dcb99d 1516 * This function takes a string and examines it for HTML tags.
449611af 1517 *
d48b00b4 1518 * If tags are detected it passes the string to a helper function {@link cleanAttributes2()}
449611af 1519 * which checks for attributes and filters them for malicious content
d48b00b4 1520 *
1521 * @param string $str The string to be examined for html tags
1522 * @return string
1523 */
3bd7ffec 1524function cleanAttributes($str){
4e8f2e6b 1525 $result = preg_replace_callback(
1526 '%(<[^>]*(>|$)|>)%m', #search for html tags
1527 "cleanAttributes2",
3bd7ffec 1528 $str
67ccec43 1529 );
3bd7ffec 1530 return $result;
67ccec43 1531}
1532
d48b00b4 1533/**
1534 * This function takes a string with an html tag and strips out any unallowed
1535 * protocols e.g. javascript:
449611af 1536 *
d48b00b4 1537 * It calls ancillary functions in kses which are prefixed by kses
d48b00b4 1538 *
449611af 1539 * @global object
1540 * @global string
4e8f2e6b 1541 * @param array $htmlArray An array from {@link cleanAttributes()}, containing in its 1st
1542 * element the html to be cleared
d48b00b4 1543 * @return string
1544 */
4e8f2e6b 1545function cleanAttributes2($htmlArray){
3bd7ffec 1546
037dcbb6 1547 global $CFG, $ALLOWED_PROTOCOLS;
b0ccd3fb 1548 require_once($CFG->libdir .'/kses.php');
3bd7ffec 1549
4e8f2e6b 1550 $htmlTag = $htmlArray[1];
037dcbb6 1551 if (substr($htmlTag, 0, 1) != '<') {
3bd7ffec 1552 return '&gt;'; //a single character ">" detected
1553 }
037dcbb6 1554 if (!preg_match('%^<\s*(/\s*)?([a-zA-Z0-9]+)([^>]*)>?$%', $htmlTag, $matches)) {
67ccec43 1555 return ''; // It's seriously malformed
1556 }
3bd7ffec 1557 $slash = trim($matches[1]); //trailing xhtml slash
67ccec43 1558 $elem = $matches[2]; //the element name
3bd7ffec 1559 $attrlist = $matches[3]; // the list of attributes as a string
1560
037dcbb6 1561 $attrArray = kses_hair($attrlist, $ALLOWED_PROTOCOLS);
3bd7ffec 1562
67ccec43 1563 $attStr = '';
037dcbb6 1564 foreach ($attrArray as $arreach) {
29939bea 1565 $arreach['name'] = strtolower($arreach['name']);
1566 if ($arreach['name'] == 'style') {
1567 $value = $arreach['value'];
1568 while (true) {
1569 $prevvalue = $value;
1570 $value = kses_no_null($value);
1571 $value = preg_replace("/\/\*.*\*\//Us", '', $value);
1572 $value = kses_decode_entities($value);
1573 $value = preg_replace('/(&#[0-9]+)(;?)/', "\\1;", $value);
1574 $value = preg_replace('/(&#x[0-9a-fA-F]+)(;?)/', "\\1;", $value);
1575 if ($value === $prevvalue) {
1576 $arreach['value'] = $value;
1577 break;
1578 }
1579 }
1580 $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 1581 $arreach['value'] = preg_replace("/v\s*b\s*s\s*c\s*r\s*i\s*p\s*t/i", "Xvbscript", $arreach['value']);
29939bea 1582 $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 1583 $arreach['value'] = preg_replace("/b\s*i\s*n\s*d\s*i\s*n\s*g/i", "Xbinding", $arreach['value']);
b8806ccc 1584 } else if ($arreach['name'] == 'href') {
ee7f231d 1585 //Adobe Acrobat Reader XSS protection
920337d1 1586 $arreach['value'] = preg_replace('/(\.(pdf|fdf|xfdf|xdp|xfd)[^#]*)#.*$/i', '$1', $arreach['value']);
29939bea 1587 }
049bd7db 1588 $attStr .= ' '.$arreach['name'].'="'.$arreach['value'].'"';
3bd7ffec 1589 }
713126cd 1590
3bd7ffec 1591 $xhtml_slash = '';
037dcbb6 1592 if (preg_match('%/\s*$%', $attrlist)) {
67ccec43 1593 $xhtml_slash = ' /';
3bd7ffec 1594 }
b0ccd3fb 1595 return '<'. $slash . $elem . $attStr . $xhtml_slash .'>';
3bd7ffec 1596}
1597
d48b00b4 1598/**
1599 * Replaces all known smileys in the text with image equivalents
1600 *
449611af 1601 * @global object
1602 * @staticvar array $e
1603 * @staticvar array $img
1604 * @staticvar array $emoticons
fa9f6bf6 1605 * @param string $text Passed by reference. The string to search for smiley strings.
d48b00b4 1606 * @return string
1607 */
5f350e8f 1608function replace_smilies(&$text) {
5d3b9994 1609 global $CFG, $OUTPUT;
183a13c2 1610
1611 if (empty($CFG->emoticons)) { /// No emoticons defined, nothing to process here
1612 return;
1613 }
1614
5a144b3a 1615 $lang = current_language();
93c61c18 1616 $emoticonstring = $CFG->emoticons;
69081931 1617 static $e = array();
1618 static $img = array();
93c61c18 1619 static $emoticons = null;
1620
1621 if (is_null($emoticons)) {
1622 $emoticons = array();
1623 if ($emoticonstring) {
1624 $items = explode('{;}', $CFG->emoticons);
1625 foreach ($items as $item) {
1626 $item = explode('{:}', $item);
c5659019 1627 $emoticons[$item[0]] = $item[1];
93c61c18 1628 }
1629 }
1630 }
1631
5a144b3a 1632 if (empty($img[$lang])) { /// After the first time this is not run again
1633 $e[$lang] = array();
1634 $img[$lang] = array();
617778f2 1635 foreach ($emoticons as $emoticon => $image){
fbfc2675 1636 $alttext = get_string($image, 'pix');
ef44fbed
PS
1637 if ($alttext === '') {
1638 $alttext = $image;
1345cc53 1639 }
5a144b3a 1640 $e[$lang][] = $emoticon;
b5d0cafc 1641 $img[$lang][] = '<img alt="'. $alttext .'" width="15" height="15" src="'. $OUTPUT->pix_url('s/' . $image) . '" />';
617778f2 1642 }
c0f728ba 1643 }
b7a3cf49 1644
8dcd43f3 1645 // Exclude from transformations all the code inside <script> tags
1646 // Needed to solve Bug 1185. Thanks to jouse 2001 detecting it. :-)
fa9f6bf6 1647 // Based on code from glossary filter by Williams Castillo.
8dcd43f3 1648 // - Eloy
1649
1650 // Detect all the <script> zones to take out
1651 $excludes = array();
1652 preg_match_all('/<script language(.+?)<\/script>/is',$text,$list_of_excludes);
1653
1654 // Take out all the <script> zones from text
1655 foreach (array_unique($list_of_excludes[0]) as $key=>$value) {
1656 $excludes['<+'.$key.'+>'] = $value;
1657 }
1658 if ($excludes) {
1659 $text = str_replace($excludes,array_keys($excludes),$text);
1660 }
1661
fbfc2675 1662/// this is the meat of the code - this is run every time
5a144b3a 1663 $text = str_replace($e[$lang], $img[$lang], $text);
8dcd43f3 1664
1665 // Recover all the <script> zones to text
1666 if ($excludes) {
1667 $text = str_replace(array_keys($excludes),$excludes,$text);
1668 }
1a072208 1669}
0095d5cd 1670
740939ec 1671/**
1672 * This code is called from help.php to inject a list of smilies into the
1673 * emoticons help file.
1674 *
449611af 1675 * @global object
1676 * @global object
740939ec 1677 * @return string HTML for a list of smilies.
1678 */
cf615522 1679function get_emoticons_list_for_help_file() {
ddedf979 1680 global $CFG, $SESSION, $PAGE, $OUTPUT;
740939ec 1681 if (empty($CFG->emoticons)) {
1682 return '';
1683 }
1684
740939ec 1685 $items = explode('{;}', $CFG->emoticons);
1686 $output = '<ul id="emoticonlist">';
1687 foreach ($items as $item) {
1688 $item = explode('{:}', $item);
b5d0cafc 1689 $output .= '<li><img src="' . $OUTPUT->pix_url('s/' . $item[1]) . '" alt="' .
740939ec 1690 $item[0] . '" /><code>' . $item[0] . '</code></li>';
1691 }
1692 $output .= '</ul>';
1693 if (!empty($SESSION->inserttextform)) {
1694 $formname = $SESSION->inserttextform;
1695 $fieldname = $SESSION->inserttextfield;
1696 } else {
1697 $formname = 'theform';
1698 $fieldname = 'message';
1699 }
fa583f5f 1700
f44b10ed 1701 $PAGE->requires->yui2_lib('event');
cf615522 1702 $PAGE->requires->js_function_call('emoticons_help.init', array($formname, $fieldname, 'emoticonlist'));
740939ec 1703 return $output;
1704
1705}
1706
89dcb99d 1707/**
1708 * Given plain text, makes it into HTML as nicely as possible.
1709 * May contain HTML tags already
1710 *
449611af 1711 * @global object
89dcb99d 1712 * @param string $text The string to convert.
1713 * @param boolean $smiley Convert any smiley characters to smiley images?
b075eb8e 1714 * @param boolean $para If true then the returned string will be wrapped in div tags
89dcb99d 1715 * @param boolean $newlines If true then lines newline breaks will be converted to HTML newline breaks.
1716 * @return string
1717 */
1718
b7a3d3b2 1719function text_to_html($text, $smiley=true, $para=true, $newlines=true) {
772e78be 1720///
f9903ed0 1721
27326a3e 1722 global $CFG;
1723
c1d57101 1724/// Remove any whitespace that may be between HTML tags
6dbcacee 1725 $text = preg_replace("~>([[:space:]]+)<~i", "><", $text);
7b3be1b1 1726
c1d57101 1727/// Remove any returns that precede or follow HTML tags
6dbcacee 1728 $text = preg_replace("~([\n\r])<~i", " <", $text);
1729 $text = preg_replace("~>([\n\r])~i", "> ", $text);
7b3be1b1 1730
5f350e8f 1731 convert_urls_into_links($text);
f9903ed0 1732
c1d57101 1733/// Make returns into HTML newlines.
b7a3d3b2 1734 if ($newlines) {
1735 $text = nl2br($text);
1736 }
f9903ed0 1737
c1d57101 1738/// Turn smileys into images.
d69cb7f4 1739 if ($smiley) {
5f350e8f 1740 replace_smilies($text);
d69cb7f4 1741 }
f9903ed0 1742
b075eb8e 1743/// Wrap the whole thing in a div if required
909f539d 1744 if ($para) {
b075eb8e
AD
1745 //return '<p>'.$text.'</p>'; //1.9 version
1746 return '<div class="text_to_html">'.$text.'</div>';
909f539d 1747 } else {
1748 return $text;
1749 }
f9903ed0 1750}
1751
d48b00b4 1752/**
1753 * Given Markdown formatted text, make it into XHTML using external function
1754 *
449611af 1755 * @global object
89dcb99d 1756 * @param string $text The markdown formatted text to be converted.
1757 * @return string Converted text
d48b00b4 1758 */
e7cdcd18 1759function markdown_to_html($text) {
e7cdcd18 1760 global $CFG;
1761
a4a0c9d9
PS
1762 if ($text === '' or $text === NULL) {
1763 return $text;
1764 }
1765
b0ccd3fb 1766 require_once($CFG->libdir .'/markdown.php');
e7cdcd18 1767
1768 return Markdown($text);
1769}
1770
d48b00b4 1771/**
89dcb99d 1772 * Given HTML text, make it into plain text using external function
d48b00b4 1773 *
d48b00b4 1774 * @param string $html The text to be converted.
a194c218
TH
1775 * @param integer $width Width to wrap the text at. (optional, default 75 which
1776 * is a good value for email. 0 means do not limit line length.)
dc3e95c0
TH
1777 * @param boolean $dolinks By default, any links in the HTML are collected, and
1778 * printed as a list at the end of the HTML. If you don't want that, set this
1779 * argument to false.
a194c218 1780 * @return string plain text equivalent of the HTML.
d48b00b4 1781 */
dc3e95c0 1782function html_to_text($html, $width = 75, $dolinks = true) {
89dcb99d 1783
428aaa29 1784 global $CFG;
6ff45b59 1785
b0ccd3fb 1786 require_once($CFG->libdir .'/html2text.php');
6ff45b59 1787
dc3e95c0 1788 $h2t = new html2text($html, false, $dolinks, $width);
588acd06 1789 $result = $h2t->get_text();
07e9a300 1790
977b3d31 1791 return $result;
6ff45b59 1792}
1793
d48b00b4 1794/**
1795 * Given some text this function converts any URLs it finds into HTML links
1796 *
1797 * @param string $text Passed in by reference. The string to be searched for urls.
1798 */
5f350e8f 1799function convert_urls_into_links(&$text) {
c013b316
AD
1800 //I've added img tags to this list of tags to ignore.
1801 //See MDL-21168 for more info. A better way to ignore tags whether or not
1802 //they are escaped partially or completely would be desirable. For example:
1803 //<a href="blah">
1804 //&lt;a href="blah"&gt;
1805 //&lt;a href="blah">
bd9255c5
EL
1806 $filterignoretagsopen = array('<a\s[^>]+?>');
1807 $filterignoretagsclose = array('</a>');
9c7a301b 1808 filter_save_ignore_tags($text,$filterignoretagsopen,$filterignoretagsclose,$ignoretags);
c013b316 1809
9c7a301b
AD
1810 // Check if we support unicode modifiers in regular expressions. Cache it.
1811 // TODO: this check should be a environment requirement in Moodle 2.0, as far as unicode
1812 // chars are going to arrive to URLs officially really soon (2010?)
1813 // Original RFC regex from: http://www.bytemycode.com/snippets/snippet/796/
1814 // Various ideas from: http://alanstorm.com/url_regex_explained
1815 // Unicode check, negative assertion and other bits from Moodle.
1816 static $unicoderegexp;
1817 if (!isset($unicoderegexp)) {
fa9f6bf6 1818 $unicoderegexp = @preg_match('/\pL/u', 'a'); // This will fail silently, returning false,
9c7a301b
AD
1819 }
1820
b245afc0 1821 //todo: MDL-21296 - use of unicode modifiers may cause a timeout
9c7a301b 1822 if ($unicoderegexp) { //We can use unicode modifiers
2b2acf75 1823 $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 1824 '<a href="\\1" class="_blanktarget">\\1</a>', $text);
2b2acf75 1825 $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 1826 '<a href="http://\\1" class="_blanktarget">\\1</a>', $text);
9c7a301b 1827 } else { //We cannot use unicode modifiers
2b2acf75 1828 $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 1829 '<a href="\\1" class="_blanktarget">\\1</a>', $text);
2b2acf75 1830 $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 1831 '<a href="http://\\1" class="_blanktarget">\\1</a>', $text);
9c7a301b
AD
1832 }
1833
1834 if (!empty($ignoretags)) {
1835 $ignoretags = array_reverse($ignoretags); /// Reversed so "progressive" str_replace() will solve some nesting problems.
1836 $text = str_replace(array_keys($ignoretags),$ignoretags,$text);
1837 }
5f350e8f 1838}
1839
d48b00b4 1840/**
1841 * This function will highlight search words in a given string
449611af 1842 *
d48b00b4 1843 * It cares about HTML and will not ruin links. It's best to use
1844 * this function after performing any conversions to HTML.
d48b00b4 1845 *
9289e4c9 1846 * @param string $needle The search string. Syntax like "word1 +word2 -word3" is dealt with correctly.
1847 * @param string $haystack The string (HTML) within which to highlight the search terms.
1848 * @param boolean $matchcase whether to do case-sensitive. Default case-insensitive.
1849 * @param string $prefix the string to put before each search term found.
1850 * @param string $suffix the string to put after each search term found.
1851 * @return string The highlighted HTML.
d48b00b4 1852 */
9289e4c9 1853function highlight($needle, $haystack, $matchcase = false,
1854 $prefix = '<span class="highlight">', $suffix = '</span>') {
587c7040 1855
9289e4c9 1856/// Quick bail-out in trivial cases.
587c7040 1857 if (empty($needle) or empty($haystack)) {
69d51d3a 1858 return $haystack;
1859 }
1860
9289e4c9 1861/// Break up the search term into words, discard any -words and build a regexp.
1862 $words = preg_split('/ +/', trim($needle));
1863 foreach ($words as $index => $word) {
1864 if (strpos($word, '-') === 0) {
1865 unset($words[$index]);
1866 } else if (strpos($word, '+') === 0) {
1867 $words[$index] = '\b' . preg_quote(ltrim($word, '+'), '/') . '\b'; // Match only as a complete word.
1868 } else {
1869 $words[$index] = preg_quote($word, '/');
88438a58 1870 }
1871 }
9289e4c9 1872 $regexp = '/(' . implode('|', $words) . ')/u'; // u is do UTF-8 matching.
1873 if (!$matchcase) {
1874 $regexp .= 'i';
88438a58 1875 }
1876
9289e4c9 1877/// Another chance to bail-out if $search was only -words
1878 if (empty($words)) {
1879 return $haystack;
88438a58 1880 }
88438a58 1881
9289e4c9 1882/// Find all the HTML tags in the input, and store them in a placeholders array.
1883 $placeholders = array();
1884 $matches = array();
1885 preg_match_all('/<[^>]*>/', $haystack, $matches);
1886 foreach (array_unique($matches[0]) as $key => $htmltag) {
1887 $placeholders['<|' . $key . '|>'] = $htmltag;
1888 }
9ccdcd97 1889
9289e4c9 1890/// In $hastack, replace each HTML tag with the corresponding placeholder.
1891 $haystack = str_replace($placeholders, array_keys($placeholders), $haystack);
9ccdcd97 1892
9289e4c9 1893/// In the resulting string, Do the highlighting.
1894 $haystack = preg_replace($regexp, $prefix . '$1' . $suffix, $haystack);
9ccdcd97 1895
9289e4c9 1896/// Turn the placeholders back into HTML tags.
1897 $haystack = str_replace(array_keys($placeholders), $placeholders, $haystack);
88438a58 1898
f60e7cfe 1899 return $haystack;
88438a58 1900}
1901
d48b00b4 1902/**
1903 * This function will highlight instances of $needle in $haystack
449611af 1904 *
1905 * It's faster that the above function {@link highlight()} and doesn't care about
d48b00b4 1906 * HTML or anything.
1907 *
1908 * @param string $needle The string to search for
1909 * @param string $haystack The string to search for $needle in
449611af 1910 * @return string The highlighted HTML
d48b00b4 1911 */
88438a58 1912function highlightfast($needle, $haystack) {
5af78ed2 1913
587c7040 1914 if (empty($needle) or empty($haystack)) {
1915 return $haystack;
1916 }
1917
57f1b914 1918 $parts = explode(moodle_strtolower($needle), moodle_strtolower($haystack));
5af78ed2 1919
587c7040 1920 if (count($parts) === 1) {
1921 return $haystack;
1922 }
1923
5af78ed2 1924 $pos = 0;
1925
1926 foreach ($parts as $key => $part) {
1927 $parts[$key] = substr($haystack, $pos, strlen($part));
1928 $pos += strlen($part);
1929
b0ccd3fb 1930 $parts[$key] .= '<span class="highlight">'.substr($haystack, $pos, strlen($needle)).'</span>';
5af78ed2 1931 $pos += strlen($needle);
ab9f24ad 1932 }
5af78ed2 1933
587c7040 1934 return str_replace('<span class="highlight"></span>', '', join('', $parts));
5af78ed2 1935}
1936
2ab4e4b8 1937/**
1938 * Return a string containing 'lang', xml:lang and optionally 'dir' HTML attributes.
1939 * Internationalisation, for print_header and backup/restorelib.
449611af 1940 *
1941 * @param bool $dir Default false
1942 * @return string Attributes
2ab4e4b8 1943 */
1944function get_html_lang($dir = false) {
1945 $direction = '';
1946 if ($dir) {
e372f4c7 1947 if (right_to_left()) {
2ab4e4b8 1948 $direction = ' dir="rtl"';
1949 } else {
1950 $direction = ' dir="ltr"';
1951 }
1952 }
1953 //Accessibility: added the 'lang' attribute to $direction, used in theme <html> tag.
3a915b06 1954 $language = str_replace('_', '-', current_language());
0946fff4 1955 @header('Content-Language: '.$language);
84e3d2cc 1956 return ($direction.' lang="'.$language.'" xml:lang="'.$language.'"');
2ab4e4b8 1957}
1958
34a2777c 1959
1960/// STANDARD WEB PAGE PARTS ///////////////////////////////////////////////////
1961
5c355019 1962/**
34a2777c 1963 * Send the HTTP headers that Moodle requires.
1964 * @param $cacheable Can this page be cached on back?
5c355019 1965 */
34a2777c 1966function send_headers($contenttype, $cacheable = true) {
1967 @header('Content-Type: ' . $contenttype);
1968 @header('Content-Script-Type: text/javascript');
1969 @header('Content-Style-Type: text/css');
f9903ed0 1970
34a2777c 1971 if ($cacheable) {
1972 // Allow caching on "back" (but not on normal clicks)
1973 @header('Cache-Control: private, pre-check=0, post-check=0, max-age=0');
1974 @header('Pragma: no-cache');
1975 @header('Expires: ');
1976 } else {
1977 // Do everything we can to always prevent clients and proxies caching
1978 @header('Cache-Control: no-store, no-cache, must-revalidate');
1979 @header('Cache-Control: post-check=0, pre-check=0', false);
1980 @header('Pragma: no-cache');
1981 @header('Expires: Mon, 20 Aug 1969 09:23:00 GMT');
1982 @header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
1983 }
1984 @header('Accept-Ranges: none');
1985}
9fa49e22 1986
ce3735d4 1987/**
a84dea2c 1988 * Return the right arrow with text ('next'), and optionally embedded in a link.
449611af 1989 *
1990 * @global object
ac905235 1991 * @param string $text HTML/plain text label (set to blank only for breadcrumb separator cases).
a84dea2c 1992 * @param string $url An optional link to use in a surrounding HTML anchor.
1993 * @param bool $accesshide True if text should be hidden (for screen readers only).
1994 * @param string $addclass Additional class names for the link, or the arrow character.
1995 * @return string HTML string.
ce3735d4 1996 */
a84dea2c 1997function link_arrow_right($text, $url='', $accesshide=false, $addclass='') {
92e01ab7 1998 global $OUTPUT; //TODO: move to output renderer
a84dea2c 1999 $arrowclass = 'arrow ';
2000 if (! $url) {
2001 $arrowclass .= $addclass;
2002 }
92e01ab7 2003 $arrow = '<span class="'.$arrowclass.'">'.$OUTPUT->rarrow().'</span>';
a84dea2c 2004 $htmltext = '';
2005 if ($text) {
388794fd 2006 $htmltext = '<span class="arrow_text">'.$text.'</span>&nbsp;';
a84dea2c 2007 if ($accesshide) {
1d75edd0 2008 $htmltext = get_accesshide($htmltext);
a84dea2c 2009 }
ce3735d4 2010 }
a84dea2c 2011 if ($url) {
388794fd 2012 $class = 'arrow_link';
a84dea2c 2013 if ($addclass) {
388794fd 2014 $class .= ' '.$addclass;
a84dea2c 2015 }
388794fd 2016 return '<a class="'.$class.'" href="'.$url.'" title="'.preg_replace('/<.*?>/','',$text).'">'.$htmltext.$arrow.'</a>';
a84dea2c 2017 }
2018 return $htmltext.$arrow;
ce3735d4 2019}
2020
2021/**
a84dea2c 2022 * Return the left arrow with text ('previous'), and optionally embedded in a link.
449611af 2023 *
2024 * @global object
ac905235 2025 * @param string $text HTML/plain text label (set to blank only for breadcrumb separator cases).
a84dea2c 2026 * @param string $url An optional link to use in a surrounding HTML anchor.
2027 * @param bool $accesshide True if text should be hidden (for screen readers only).
2028 * @param string $addclass Additional class names for the link, or the arrow character.
2029 * @return string HTML string.
ce3735d4 2030 */
a84dea2c 2031function link_arrow_left($text, $url='', $accesshide=false, $addclass='') {
92e01ab7 2032 global $OUTPUT; // TODO: move to utput renderer
a84dea2c 2033 $arrowclass = 'arrow ';
2034 if (! $url) {
2035 $arrowclass .= $addclass;
2036 }
92e01ab7 2037 $arrow = '<span class="'.$arrowclass.'">'.$OUTPUT->larrow().'</span>';
a84dea2c 2038 $htmltext = '';
2039 if ($text) {
388794fd 2040 $htmltext = '&nbsp;<span class="arrow_text">'.$text.'</span>';
a84dea2c 2041 if ($accesshide) {
1d75edd0 2042 $htmltext = get_accesshide($htmltext);
a84dea2c 2043 }
ce3735d4 2044 }
a84dea2c 2045 if ($url) {
388794fd 2046 $class = 'arrow_link';
a84dea2c 2047 if ($addclass) {
388794fd 2048 $class .= ' '.$addclass;
a84dea2c 2049 }
388794fd 2050 return '<a class="'.$class.'" href="'.$url.'" title="'.preg_replace('/<.*?>/','',$text).'">'.$arrow.$htmltext.'</a>';
a84dea2c 2051 }
2052 return $arrow.$htmltext;
2053}
2054
1d75edd0 2055/**
2056 * Return a HTML element with the class "accesshide", for accessibility.
449611af 2057 * Please use cautiously - where possible, text should be visible!
2058 *
1d75edd0 2059 * @param string $text Plain text.
2060 * @param string $elem Lowercase element name, default "span".
2061 * @param string $class Additional classes for the element.
2062 * @param string $attrs Additional attributes string in the form, "name='value' name2='value2'"
2063 * @return string HTML string.
2064 */
2065function get_accesshide($text, $elem='span', $class='', $attrs='') {
2066 return "<$elem class=\"accesshide $class\" $attrs>$text</$elem>";
2067}
2068
a84dea2c 2069/**
2070 * Return the breadcrumb trail navigation separator.
449611af 2071 *
a84dea2c 2072 * @return string HTML string.
2073 */
2074function get_separator() {
2075 //Accessibility: the 'hidden' slash is preferred for screen readers.
2076 return ' '.link_arrow_right($text='/', $url='', $accesshide=true, 'sep').' ';
ce3735d4 2077}
2078
512c5901 2079/**
fa9f6bf6 2080 * Print (or return) a collapsible region, that has a caption that can
449611af 2081 * be clicked to expand or collapse the region.
49c8c8d2 2082 *
fa9f6bf6 2083 * If JavaScript is off, then the region will always be expanded.
512c5901 2084 *
2085 * @param string $contents the contents of the box.
2086 * @param string $classes class names added to the div that is output.
2087 * @param string $id id added to the div that is output. Must not be blank.
2088 * @param string $caption text displayed at the top. Clicking on this will cause the region to expand or contract.
fa9f6bf6 2089 * @param string $userpref the name of the user preference that stores the user's preferred default state.
512c5901 2090 * (May be blank if you do not wish the state to be persisted.
fa9f6bf6 2091 * @param boolean $default Initial collapsed state to use if the user_preference it not set.
512c5901 2092 * @param boolean $return if true, return the HTML as a string, rather than printing it.
449611af 2093 * @return string|void If $return is false, returns nothing, otherwise returns a string of HTML.
512c5901 2094 */
f2eb5002 2095function print_collapsible_region($contents, $classes, $id, $caption, $userpref = '', $default = false, $return = false) {
e0fa3b81 2096 $output = print_collapsible_region_start($classes, $id, $caption, $userpref, true, true);
f2eb5002 2097 $output .= $contents;
2098 $output .= print_collapsible_region_end(true);
2099
2100 if ($return) {
2101 return $output;
2102 } else {
2103 echo $output;
2104 }
2105}
2106
512c5901 2107/**
fa9f6bf6 2108 * Print (or return) the start of a collapsible region, that has a caption that can
512c5901 2109 * be clicked to expand or collapse the region. If JavaScript is off, then the region
fa9f6bf6 2110 * will always be expanded.
512c5901 2111 *
449611af 2112 * @global object
512c5901 2113 * @param string $classes class names added to the div that is output.
2114 * @param string $id id added to the div that is output. Must not be blank.
2115 * @param string $caption text displayed at the top. Clicking on this will cause the region to expand or contract.
fa9f6bf6 2116 * @param boolean $userpref the name of the user preference that stores the user's preferred default state.
512c5901 2117 * (May be blank if you do not wish the state to be persisted.
fa9f6bf6 2118 * @param boolean $default Initial collapsed state to use if the user_preference it not set.
512c5901 2119 * @param boolean $return if true, return the HTML as a string, rather than printing it.
449611af 2120 * @return string|void if $return is false, returns nothing, otherwise returns a string of HTML.
512c5901 2121 */
f2eb5002 2122function print_collapsible_region_start($classes, $id, $caption, $userpref = false, $default = false, $return = false) {
a28c9253 2123 global $CFG, $PAGE, $OUTPUT;
f2eb5002 2124
f2eb5002 2125 // Work out the initial state.
2126 if (is_string($userpref)) {
2127 user_preference_allow_ajax_update($userpref, PARAM_BOOL);
2128 $collapsed = get_user_preferences($userpref, $default);
2129 } else {
2130 $collapsed = $default;
2131 $userpref = false;
2132 }
2133
67c8a3e8 2134 if ($collapsed) {
2135 $classes .= ' collapsed';
2136 }
2137
f2eb5002 2138 $output = '';
2139 $output .= '<div id="' . $id . '" class="collapsibleregion ' . $classes . '">';
67c8a3e8 2140 $output .= '<div id="' . $id . '_sizer">';
f2eb5002 2141 $output .= '<div id="' . $id . '_caption" class="collapsibleregioncaption">';
2142 $output .= $caption . ' ';
67c8a3e8 2143 $output .= '</div><div id="' . $id . '_inner" class="collapsibleregioninner">';
38224dcb 2144 $PAGE->requires->js_init_call('M.util.init_collapsible_region', array($id, $userpref, get_string('clicktohideshow')));
f2eb5002 2145
2146 if ($return) {
2147 return $output;
2148 } else {
2149 echo $output;
2150 }
2151}
2152
512c5901 2153/**
2154 * Close a region started with print_collapsible_region_start.
2155 *
2156 * @param boolean $return if true, return the HTML as a string, rather than printing it.
449611af 2157 * @return string|void if $return is false, returns nothing, otherwise returns a string of HTML.
512c5901 2158 */
f2eb5002 2159function print_collapsible_region_end($return = false) {
904998d8 2160 $output = '</div></div></div>';
f2eb5002 2161
2162 if ($return) {
2163 return $output;
2164 } else {
2165 echo $output;
2166 }
2167}
2168
d48b00b4 2169/**
2170 * Print a specified group's avatar.
2171 *
449611af 2172 * @global object
2173 * @uses CONTEXT_COURSE
2174 * @param array $group A single {@link group} object OR array of groups.
ce3735d4 2175 * @param int $courseid The course ID.
2176 * @param boolean $large Default small picture, or large.
2177 * @param boolean $return If false print picture, otherwise return the output as string
2178 * @param boolean $link Enclose image in a link to view specified course?
449611af 2179 * @return string|void Depending on the setting of $return
d48b00b4 2180 */
da4124be 2181function print_group_picture($group, $courseid, $large=false, $return=false, $link=true) {
f374fb10 2182 global $CFG;
2183
fdcd0f05 2184 if (is_array($group)) {
2185 $output = '';
2186 foreach($group as $g) {
2187 $output .= print_group_picture($g, $courseid, $large, true, $link);
2188 }
da4124be 2189 if ($return) {
fdcd0f05 2190 return $output;
2191 } else {
2192 echo $output;
2193 return;
2194 }
2195 }
2196
ec7a8b79 2197 $context = get_context_instance(CONTEXT_COURSE, $courseid);
97ea4833 2198
4a9cf90e
SM
2199 // If there is no picture, do nothing
2200 if (!$group->picture) {
2201 return '';
2202 }
2203
2204 // If picture is hidden, only show to those with course:managegroups
ec7a8b79 2205 if ($group->hidepicture and !has_capability('moodle/course:managegroups', $context)) {
3c0561cf 2206 return '';
2207 }
c3cbfe7f 2208
ec7a8b79 2209 if ($link or has_capability('moodle/site:accessallgroups', $context)) {
a756cf1d 2210 $output = '<a href="'. $CFG->wwwroot .'/user/index.php?id='. $courseid .'&amp;group='. $group->id .'">';
3c0561cf 2211 } else {
2212 $output = '';
2213 }
2214 if ($large) {
b0ccd3fb 2215 $file = 'f1';
3c0561cf 2216 } else {
b0ccd3fb 2217 $file = 'f2';
3c0561cf 2218 }
4a9cf90e 2219
e88dd876 2220 $grouppictureurl = moodle_url::make_pluginfile_url($context->id, 'group', 'icon', $group->id, '/', $file);
4a9cf90e
SM
2221 $output .= '<img class="grouppicture" src="'.$grouppictureurl.'"'.
2222 ' alt="'.s(get_string('group').' '.$group->name).'" title="'.s($group->name).'"/>';
2223
ec7a8b79 2224 if ($link or has_capability('moodle/site:accessallgroups', $context)) {
b0ccd3fb 2225 $output .= '</a>';
3c0561cf 2226 }
f374fb10 2227
da4124be 2228 if ($return) {
f374fb10 2229 return $output;
2230 } else {
2231 echo $output;
2232 }
2233}
2234
9fa49e22 2235
449611af 2236/**
2237 * Display a recent activity note
49c8c8d2 2238 *
449611af 2239 * @uses CONTEXT_SYSTEM
2240 * @staticvar string $strftimerecent
2241 * @param object A time object
2242 * @param object A user object
2243 * @param string $text Text for display for the note
2244 * @param string $link The link to wrap around the text
2245 * @param bool $return If set to true the HTML is returned rather than echo'd
2246 * @param string $viewfullnames
2247 */
dd97c328 2248function print_recent_activity_note($time, $user, $text, $link, $return=false, $viewfullnames=null) {
2249 static $strftimerecent = null;
da4124be 2250 $output = '';
2251
dd97c328 2252 if (is_null($viewfullnames)) {
12d06877 2253 $context = get_context_instance(CONTEXT_SYSTEM);
dd97c328 2254 $viewfullnames = has_capability('moodle/site:viewfullnames', $context);
2255 }
3f8a3834 2256
dd97c328 2257 if (is_null($strftimerecent)) {
8f7dc7f1 2258 $strftimerecent = get_string('strftimerecent');
2259 }
2260
da4124be 2261 $output .= '<div class="head">';
dd97c328 2262 $output .= '<div class="date">'.userdate($time, $strftimerecent).'</div>';
2263 $output .= '<div class="name">'.fullname($user, $viewfullnames).'</div>';
da4124be 2264 $output .= '</div>';
2265 $output .= '<div class="info"><a href="'.$link.'">'.format_string($text,true).'</a></div>';
2266
2267 if ($return) {
2268 return $output;
2269 } else {
2270 echo $output;
2271 }
8f7dc7f1 2272}
2273
f3a74e68 2274/**
449611af 2275 * Returns a popup menu with course activity modules
2276 *
a2b3f884 2277 * Given a course
f3a74e68 2278 * This function returns a small popup menu with all the
2279 * course activity modules in it, as a navigation menu
a2b3f884 2280 * outputs a simple list structure in XHTML
f3a74e68 2281 * The data is taken from the serialised array stored in
2282 * the course record
2283 *
f3a74e68 2284 * @todo Finish documenting this function
449611af 2285 *
2286 * @global object
2287 * @uses CONTEXT_COURSE
2288 * @param course $course A {@link $COURSE} object.
2289 * @param string $sections
2290 * @param string $modinfo
2291 * @param string $strsection
2292 * @param string $strjumpto
2293 * @param int $width
2294 * @param string $cmid
2295 * @return string The HTML block
f3a74e68 2296 */
85489a5b 2297function navmenulist($course, $sections, $modinfo, $strsection, $strjumpto, $width=50, $cmid=0) {
f3a74e68 2298
2299 global $CFG;
2300
f3a74e68 2301 $section = -1;
f3a74e68 2302 $url = '';
f3a74e68 2303 $menu = array();
dd97c328 2304 $doneheading = false;
f3a74e68 2305
85489a5b 2306 $coursecontext = get_context_instance(CONTEXT_COURSE, $course->id);
2307
36c446cb 2308 $menu[] = '<ul class="navmenulist"><li class="jumpto section"><span>'.$strjumpto.'</span><ul>';
dd97c328 2309 foreach ($modinfo->cms as $mod) {
2310 if ($mod->modname == 'label') {
f3a74e68 2311 continue;
2312 }
2313
76cbde41 2314 if ($mod->sectionnum > $course->numsections) { /// Don't show excess hidden sections
f3a74e68 2315 break;
2316 }
2317
dd97c328 2318 if (!$mod->uservisible) { // do not icnlude empty sections at all
2319 continue;
2320 }
2321
76cbde41 2322 if ($mod->sectionnum >= 0 and $section != $mod->sectionnum) {
2323 $thissection = $sections[$mod->sectionnum];
f3a74e68 2324
5ce73257 2325 if ($thissection->visible or !$course->hiddensections or
85489a5b 2326 has_capability('moodle/course:viewhiddensections', $coursecontext)) {
f3a74e68 2327 $thissection->summary = strip_tags(format_string($thissection->summary,true));
dd97c328 2328 if (!$doneheading) {
dfe66174 2329 $menu[] = '</ul></li>';
f3a74e68 2330 }
2331 if ($course->format == 'weeks' or empty($thissection->summary)) {
76cbde41 2332 $item = $strsection ." ". $mod->sectionnum;
f3a74e68 2333 } else {
2334 if (strlen($thissection->summary) < ($width-3)) {
b3ab80aa 2335 $item = $thissection->summary;
f3a74e68 2336 } else {
b3ab80aa 2337 $item = substr($thissection->summary, 0, $width).'...';
f3a74e68 2338 }
2339 }
36c446cb 2340 $menu[] = '<li class="section"><span>'.$item.'</span>';
f3a74e68 2341 $menu[] = '<ul>';
2342 $doneheading = true;
dd97c328 2343
76cbde41 2344 $section = $mod->sectionnum;
dd97c328 2345 } else {
2346 // no activities from this hidden section shown
2347 continue;
f3a74e68 2348 }
2349 }
2350
dd97c328 2351 $url = $mod->modname .'/view.php?id='. $mod->id;
9a9012dc 2352 $mod->name = strip_tags(format_string($mod->name ,true));
dd97c328 2353 if (strlen($mod->name) > ($width+5)) {
2354 $mod->name = substr($mod->name, 0, $width).'...';
f3a74e68 2355 }
dd97c328 2356 if (!$mod->visible) {
2357 $mod->name = '('.$mod->name.')';
2358 }
2359 $class = 'activity '.$mod->modname;
996c1a6f 2360 $class .= ($cmid == $mod->id) ? ' selected' : '';
dd97c328 2361 $menu[] = '<li class="'.$class.'">'.
b5d0cafc 2362 '<img src="'.$OUTPUT->pix_url('icon', $mod->modname) . '" alt="" />'.
dd97c328 2363 '<a href="'.$CFG->wwwroot.'/mod/'.$url.'">'.$mod->name.'</a></li>';
f3a74e68 2364 }
dd97c328 2365
dfe66174 2366 if ($doneheading) {
f713e270 2367 $menu[] = '</ul></li>';
dfe66174 2368 }
143211e5 2369 $menu[] = '</ul></li></ul>';
f3a74e68 2370
2371 return implode("\n", $menu);
2372}
2373
d48b00b4 2374/**
2375 * Prints a grade menu (as part of an existing form) with help
2376 * Showing all possible numerical grades and scales
2377 *
d48b00b4 2378 * @todo Finish documenting this function
f8065dd2 2379 * @todo Deprecate: this is only used in a few contrib modules
449611af 2380 *
2381 * @global object
2382 * @param int $courseid The course ID
49c8c8d2 2383 * @param string $name
2384 * @param string $current
449611af 2385 * @param boolean $includenograde Include those with no grades
2386 * @param boolean $return If set to true returns rather than echo's
2387 * @return string|bool Depending on value of $return
d48b00b4 2388 */
da4124be 2389function print_grade_menu($courseid, $name, $current, $includenograde=true, $return=false) {
62ca135d 2390
e63f88c9 2391 global $CFG, $OUTPUT;
62ca135d 2392
da4124be 2393 $output = '';
b0ccd3fb 2394 $strscale = get_string('scale');
2395 $strscales = get_string('scales');
62ca135d 2396
1f7deef6 2397 $scales = get_scales_menu($courseid);
62ca135d 2398 foreach ($scales as $i => $scalename) {
b0ccd3fb 2399 $grades[-$i] = $strscale .': '. $scalename;
62ca135d 2400 }
d6bdd9d5 2401 if ($includenograde) {
b0ccd3fb 2402 $grades[0] = get_string('nograde');
d6bdd9d5 2403 }
62ca135d 2404 for ($i=100; $i>=1; $i--) {
2405 $grades[$i] = $i;
2406 }
d776d59e 2407 $output .= html_writer::select($grades, $name, $current, false);
62ca135d 2408
b5d0cafc 2409 $linkobject = '<span class="helplink"><img class="iconhelp" alt="'.$strscales.'" src="'.$OUTPUT->pix_url('help') . '" /></span>';
57cd3739
PS
2410 $link = new moodle_url('/course/scales.php', array('id'=>$courseid, 'list'=>1));
2411 $action = new popup_action('click', $link->url, 'ratingscales', array('height' => 400, 'width' => 500));
2412 $output .= $OUTPUT->action_link($link, $linkobject, $action, array('title'=>$strscales));
da4124be 2413
2414 if ($return) {
2415 return $output;
2416 } else {
2417 echo $output;
2418 }
62ca135d 2419}
2420
7cfb11db 2421/**
2422 * Print an error to STDOUT and exit with a non-zero code. For commandline scripts.
2423 * Default errorcode is 1.
2424 *
2425 * Very useful for perl-like error-handling:
73f7ad71 2426 *
7cfb11db 2427 * do_somethting() or mdie("Something went wrong");
2428 *
2429 * @param string $msg Error message
73f7ad71 2430 * @param integer $errorcode Error code to emit
7cfb11db 2431 */
2432function mdie($msg='', $errorcode=1) {
2433 trigger_error($msg);
2434 exit($errorcode);
2435}
2436
0ea95ddc
DM
2437/**
2438 * Returns html code to be used as help icon of modgrade form element
2439 *
2440 * Is used as a callback in modgrade setHelpButton()
2441 *
2442 * @param int $courseid id of the course the scales should be shown from
2443 * @return string to be echoed
2444 */
2445function modgradehelpbutton($courseid){
2446 global $CFG, $OUTPUT;
2447
a6855934 2448 $url = new moodle_url('/course/scales.php', array('id' => $courseid, 'list' => true));
57cd3739
PS
2449 $text = '<span class="helplink"><img alt="' . get_string('scales') . '" class="iconhelp" src="' . $OUTPUT->pix_url('help') . '" /></span>';
2450 $action = new popup_action('click', $link->url, 'ratingscales', array('height' => 400, 'width' => 500));
0ea95ddc 2451
9bf16314 2452 return $OUTPUT->action_link($url, $text, $action, array('title'=>get_string('newwindow')));
0ea95ddc
DM
2453}
2454
d48b00b4 2455/**
2456 * Print a message and exit.
2457 *
449611af 2458 * @param string $message The message to print in the notice
2459 * @param string $link The link to use for the continue button
2460 * @param object $course A course object
2461 * @return void This function simply exits
d48b00b4 2462 */
1ae083e4 2463function notice ($message, $link='', $course=NULL) {
f6794ace 2464 global $CFG, $SITE, $COURSE, $PAGE, $OUTPUT;
9fa49e22 2465
d795bfdb 2466 $message = clean_text($message); // In case nasties are in here
9f7f1a74 2467
a91b910e 2468 if (CLI_SCRIPT) {
258d5322 2469 echo("!!$message!!\n");
1c39033f 2470 exit(1); // no success
d795bfdb 2471 }
2472
c13a5e71 2473 if (!$PAGE->headerprinted) {
d795bfdb 2474 //header not yet printed
de6d81e6 2475 $PAGE->set_title(get_string('notice'));
2476 echo $OUTPUT->header();
d795bfdb 2477 } else {
f6794ace 2478 echo $OUTPUT->container_end_all(false);
d795bfdb 2479 }
9fa49e22 2480
ea85e1ee 2481 echo $OUTPUT->box($message, 'generalbox', 'notice');
aa9a6867 2482 echo $OUTPUT->continue_button($link);
5ce73257 2483
7e0d6675 2484 echo $OUTPUT->footer();
1c39033f 2485 exit(1); // general error code
9fa49e22 2486}
2487
d48b00b4 2488/**
2489 * Redirects the user to another page, after printing a notice
2490 *
e8775320 2491 * This function calls the OUTPUT redirect method, echo's the output
2492 * and then dies to ensure nothing else happens.
2493 *
2494 * <strong>Good practice:</strong> You should call this method before starting page
2495 * output by using any of the OUTPUT methods.
449611af 2496 *
49c8c8d2 2497 * @param moodle_url $url A moodle_url to redirect to. Strings are not to be trusted!
e8775320 2498 * @param string $message The message to display to the user
2499 * @param int $delay The delay before redirecting
2500 * @return void
d48b00b4 2501 */
1ae083e4 2502function redirect($url, $message='', $delay=-1) {
8449364c 2503 global $OUTPUT, $PAGE, $SESSION, $CFG;
d3f9f1f8 2504
1adaa404
PS
2505 if (CLI_SCRIPT or AJAX_SCRIPT) {
2506 // this is wrong - developers should not use redirect in these scripts,
2507 // but it should not be very likely
2508 throw new moodle_exception('redirecterrordetected', 'error');
2509 }
2510
366c7499 2511 if ($url instanceof moodle_url) {
b9bc2019 2512 $url = $url->out(false);
366c7499 2513 }
2514
d3f9f1f8 2515 if (!empty($CFG->usesid) && !isset($_COOKIE[session_name()])) {
eee5d9bb 2516 $url = $SESSION->sid_process_url($url);
fd78420b 2517 }
2518
2871c450
AD
2519 if (function_exists('error_get_last')) {
2520 $lasterror = error_get_last();
2521 }
ae96b517 2522 $debugdisableredirect = defined('DEBUGGING_PRINTED') ||
2523 (!empty($CFG->debugdisplay) && !empty($lasterror) && ($lasterror['type'] & DEBUG_DEVELOPER));
2524
e8775320 2525 $usingmsg = false;
ae96b517 2526 if (!empty($message)) {
2527 if ($delay === -1 || !is_numeric($delay)) {
e8775320 2528 $delay = 3;
3446daa3 2529 }
e8775320 2530 $message = clean_text($message);
2531 } else {
ae96b517 2532 $message = get_string('pageshouldredirect');
e8775320 2533 $delay = 0;
ae96b517 2534 // We are going to try to use a HTTP redirect, so we need a full URL.
5ce73257 2535 if (!preg_match('|^[a-z]+:|', $url)) {
ecfdc901 2536 // Get host name http://www.wherever.com
aade3a4b 2537 $hostpart = preg_replace('|^(.*?[^:/])/.*$|', '$1', $CFG->wwwroot);
2538 if (preg_match('|^/|', $url)) {
2539 // URLs beginning with / are relative to web server root so we just add them in
2540 $url = $hostpart.$url;
ecfdc901 2541 } else {
aade3a4b 2542 // URLs not beginning with / are relative to path of current script, so add that on.
20e1b1e5 2543 $url = $hostpart.preg_replace('|\?.*$|','',me()).'/../'.$url;
ecfdc901 2544 }
fd2fff1e 2545 // Replace all ..s
aade3a4b 2546 while (true) {
23ff199c 2547 $newurl = preg_replace('|/(?!\.\.)[^/]*/\.\./|', '/', $url);
aade3a4b 2548 if ($newurl == $url) {
fd2fff1e 2549 break;
2550 }
aade3a4b 2551 $url = $newurl;
fd2fff1e 2552 }
2553 }
f231e867 2554 }
2deebecd 2555
e8775320 2556 if (defined('MDL_PERF') || (!empty($CFG->perfdebug) and $CFG->perfdebug > 7)) {
2557 if (defined('MDL_PERFTOLOG') && !function_exists('register_shutdown_function')) {
2558 $perf = get_performance_info();
2559 error_log("PERF: " . $perf['txt']);
2560 }
f231e867 2561 }
3eb89b99 2562
e8775320 2563 $encodedurl = preg_replace("/\&(?![a-zA-Z0-9#]{1,8};)/", "&amp;", $url);
2564 $encodedurl = preg_replace('/^.*href="([^"]*)".*$/', "\\1", clean_text('<a href="'.$encodedurl.'" />'));
3eb89b99 2565
ae96b517 2566 if ($delay == 0 && !$debugdisableredirect && !headers_sent()) {
2567 //302 might not work for POST requests, 303 is ignored by obsolete clients.
2568 @header($_SERVER['SERVER_PROTOCOL'] . ' 303 See Other');
2569 @header('Location: '.$url);
5e39d7aa 2570 echo bootstrap_renderer::plain_redirect_message($encodedurl);
2571 exit;
ae96b517 2572 }
b7009474 2573
ae96b517 2574 // Include a redirect message, even with a HTTP redirect, because that is recommended practice.
78946b9b 2575 $PAGE->set_pagelayout('embedded'); // No header and footer needed
317f94b0 2576 $CFG->docroot = false; // to prevent the link to moodle docs from being displayed on redirect page.
ae96b517 2577 echo $OUTPUT->redirect_message($encodedurl, $message, $delay, $debugdisableredirect);
2578 exit;
9fa49e22 2579}
2580
d48b00b4 2581/**
2582 * Given an email address, this function will return an obfuscated version of it
2583 *
89dcb99d 2584 * @param string $email The email address to obfuscate
449611af 2585 * @return string The obfuscated email address
d48b00b4 2586 */
2587 function obfuscate_email($email) {
2588
43373804 2589 $i = 0;
2590 $length = strlen($email);
b0ccd3fb 2591 $obfuscated = '';
43373804 2592 while ($i < $length) {
fa801e8c 2593 if (rand(0,2) && $email{$i}!='@') { //MDL-20619 some browsers have problems unobfuscating @
43373804 2594 $obfuscated.='%'.dechex(ord($email{$i}));
2595 } else {
2596 $obfuscated.=$email{$i};
2597 }
2598 $i++;
2599 }
2600 return $obfuscated;
2601}
2602
d48b00b4 2603/**
2604 * This function takes some text and replaces about half of the characters
2605 * with HTML entity equivalents. Return string is obviously longer.
2606 *
89dcb99d 2607 * @param string $plaintext The text to be obfuscated
449611af 2608 * @return string The obfuscated text
d48b00b4 2609 */
43373804 2610function obfuscate_text($plaintext) {
772e78be 2611
43373804 2612 $i=0;
2613 $length = strlen($plaintext);
b0ccd3fb 2614 $obfuscated='';
2b09e377 2615 $prev_obfuscated = false;
43373804 2616 while ($i < $length) {
2b09e377 2617 $c = ord($plaintext{$i});
2618 $numerical = ($c >= ord('0')) && ($c <= ord('9'));
2619 if ($prev_obfuscated and $numerical ) {
87d32352 2620 $obfuscated.='&#'.ord($plaintext{$i}).';';
2b09e377 2621 } else if (rand(0,2)) {
87d32352 2622 $obfuscated.='&#'.ord($plaintext{$i}).';';
2b09e377 2623 $prev_obfuscated = true;
43373804 2624 } else {
2625 $obfuscated.=$plaintext{$i};
2b09e377 2626 $prev_obfuscated = false;
43373804 2627 }
2b09e377 2628 $i++;
43373804 2629 }
2630 return $obfuscated;
2631}
2632
d48b00b4 2633/**
89dcb99d 2634 * This function uses the {@link obfuscate_email()} and {@link obfuscate_text()}
2635 * to generate a fully obfuscated email link, ready to use.
d48b00b4 2636 *
89dcb99d 2637 * @param string $email The email address to display
fa9f6bf6 2638 * @param string $label The text to displayed as hyperlink to $email
89dcb99d 2639 * @param boolean $dimmed If true then use css class 'dimmed' for hyperlink
449611af 2640 * @return string The obfuscated mailto link
d48b00b4 2641 */
b0ccd3fb 2642function obfuscate_mailto($email, $label='', $dimmed=false) {
43373804 2643
2644 if (empty($label)) {
2645 $label = $email;
2646 }
cadb96f2 2647 if ($dimmed) {
2648 $title = get_string('emaildisable');
2649 $dimmed = ' class="dimmed"';
2650 } else {
2651 $title = '';
2652 $dimmed = '';
2653 }
ab9f24ad 2654 return sprintf("<a href=\"%s:%s\" $dimmed title=\"$title\">%s</a>",
cadb96f2 2655 obfuscate_text('mailto'), obfuscate_email($email),
2656 obfuscate_text($label));
43373804 2657}
2658
d48b00b4 2659/**
2660 * This function is used to rebuild the <nolink> tag because some formats (PLAIN and WIKI)
2661 * will transform it to html entities
2662 *
89dcb99d 2663 * @param string $text Text to search for nolink tag in
2664 * @return string
d48b00b4 2665 */
ab892a4f 2666function rebuildnolinktag($text) {
ab9f24ad 2667
ab892a4f 2668 $text = preg_replace('/&lt;(\/*nolink)&gt;/i','<$1>',$text);
2669
2670 return $text;
2671}
2672
1695b680 2673/**
4fe2250a 2674 * Prints a maintenance message from $CFG->maintenance_message or default if empty
49c8c8d2 2675 * @return void
1695b680 2676 */
4fe2250a 2677function print_maintenance_message() {
3c159385 2678 global $CFG, $SITE, $PAGE, $OUTPUT;
a2b3f884 2679
ad5d5997 2680 $PAGE->set_pagetype('maintenance-message');
78946b9b 2681 $PAGE->set_pagelayout('maintenance');
de6d81e6 2682 $PAGE->set_title(strip_tags($SITE->fullname));
2683 $PAGE->set_heading($SITE->fullname);
2684 echo $OUTPUT->header();
3c159385 2685 echo $OUTPUT->heading(get_string('sitemaintenance', 'admin'));
4fe2250a 2686 if (isset($CFG->maintenance_message) and !html_is_blank($CFG->maintenance_message)) {
ea85e1ee 2687 echo $OUTPUT->box_start('maintenance_message generalbox boxwidthwide boxaligncenter');
4fe2250a 2688 echo $CFG->maintenance_message;
ea85e1ee 2689 echo $OUTPUT->box_end();
4fe2250a 2690 }
7e0d6675 2691 echo $OUTPUT->footer();
4fe2250a 2692 die;
1695b680 2693}
2694
5982740d 2695/**
2696 * Adjust the list of allowed tags based on $CFG->allowobjectembed and user roles (admin)
449611af 2697 *
2698 * @global object
2699 * @global string
2700 * @return void
5982740d 2701 */
2702function adjust_allowed_tags() {
1695b680 2703
5982740d 2704 global $CFG, $ALLOWED_TAGS;
2705
62af9bf9 2706 if (!empty($CFG->allowobjectembed)) {
5982740d 2707 $ALLOWED_TAGS .= '<embed><object>';
2708 }
2709}
f88ddd67 2710
449611af 2711/**
2712 * A class for tabs, Some code to print tabs
2713 *
2714 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2715 * @package moodlecore
2716 */
f88ddd67 2717class tabobject {
449611af 2718 /**
2719 * @var string
2720 */
f88ddd67 2721 var $id;
2722 var $link;
2723 var $text;
449611af 2724 /**
2725 * @var bool
2726 */
748e0925 2727 var $linkedwhenselected;
f88ddd67 2728
49c8c8d2 2729 /**
449611af 2730 * A constructor just because I like constructors
49c8c8d2 2731 *
449611af 2732 * @param string $id
2733 * @param string $link
2734 * @param string $text
2735 * @param string $title
2736 * @param bool $linkedwhenselected
2737 */
748e0925 2738 function tabobject ($id, $link='', $text='', $title='', $linkedwhenselected=false) {
f88ddd67 2739 $this->id = $id;
2740 $this->link = $link;
2741 $this->text = $text;
e7cb8f3e 2742 $this->title = $title ? $title : $text;
748e0925 2743 $this->linkedwhenselected = $linkedwhenselected;
f88ddd67 2744 }
f88ddd67 2745}
2746
2747
2748
2749/**
0b4f88a6 2750 * Returns a string containing a nested list, suitable for formatting into tabs with CSS.
f88ddd67 2751 *
449611af 2752 * @global object
f88ddd67 2753 * @param array $tabrows An array of rows where each row is an array of tab objects
0b4f88a6 2754 * @param string $selected The id of the selected tab (whatever row it's on)
2755 * @param array $inactive An array of ids of inactive tabs that are not selectable.
2756 * @param array $activated An array of ids of other tabs that are currently activated
449611af 2757 * @param bool $return If true output is returned rather then echo'd
2758 **/
0b4f88a6 2759function print_tabs($tabrows, $selected=NULL, $inactive=NULL, $activated=NULL, $return=false) {
f88ddd67 2760 global $CFG;
2761
f88ddd67 2762/// $inactive must be an array
2763 if (!is_array($inactive)) {
2764 $inactive = array();
2765 }
c06c8492 2766
0b4f88a6 2767/// $activated must be an array
2768 if (!is_array($activated)) {
2769 $activated = array();
3e8506b6 2770 }
f88ddd67 2771
6b25a26e 2772/// Convert the tab rows into a tree that's easier to process
0b4f88a6 2773 if (!$tree = convert_tabrows_to_tree($tabrows, $selected, $inactive, $activated)) {
6b25a26e 2774 return false;
2775 }
a2b3f884 2776
6b25a26e 2777/// Print out the current tree of tabs (this function is recursive)
84e3d2cc 2778
6b25a26e 2779 $output = convert_tree_to_html($tree);
2780
2781 $output = "\n\n".'<div class="tabtree">'.$output.'</div><div class="clearer"> </div>'."\n\n";
2782
2783/// We're done!
2784
2785 if ($return) {
2786 return $output;
2787 }
2788 echo $output;
2789}
031f8487 2790
449611af 2791/**
2792 * Converts a nested array tree into HTML ul:li [recursive]
2793 *
2794 * @param array $tree A tree array to convert
fa9f6bf6 2795 * @param int $row Used in identifying the iteration level and in ul classes
449611af 2796 * @return string HTML structure
2797 */
6b25a26e 2798function convert_tree_to_html($tree, $row=0) {
a2b3f884 2799
6b25a26e 2800 $str = "\n".'<ul class="tabrow'.$row.'">'."\n";
a2b3f884 2801
36e8c122 2802 $first = true;
2803 $count = count($tree);
2804
6b25a26e 2805 foreach ($tree as $tab) {
36e8c122 2806 $count--; // countdown to zero
2807
d11a1daa 2808 $liclass = '';
2809
65c8c793 2810 if ($first && ($count == 0)) { // Just one in the row
d11a1daa 2811 $liclass = 'first last';
65c8c793 2812 $first = false;
2813 } else if ($first) {
d11a1daa 2814 $liclass = 'first';
36e8c122 2815 $first = false;
2816 } else if ($count == 0) {
d11a1daa 2817 $liclass = 'last';
36e8c122 2818 }
a2b3f884 2819
d11a1daa 2820 if ((empty($tab->subtree)) && (!empty($tab->selected))) {
2821 $liclass .= (empty($liclass)) ? 'onerow' : ' onerow';
6b25a26e 2822 }
f88ddd67 2823
d1731fda 2824 if ($tab->inactive || $tab->active || $tab->selected) {
84e3d2cc 2825 if ($tab->selected) {
d11a1daa 2826 $liclass .= (empty($liclass)) ? 'here selected' : ' here selected';
84e3d2cc 2827 } else if ($tab->active) {
d11a1daa 2828 $liclass .= (empty($liclass)) ? 'here active' : ' here active';
2829 }
2830 }
2831
2832 $str .= (!empty($liclass)) ? '<li class="'.$liclass.'">' : '<li>';
2833
2834 if ($tab->inactive || $tab->active || ($tab->selected && !$tab->linkedwhenselected)) {
ca3b6e52 2835 // The a tag is used for styling
2836 $str .= '<a class="nolink"><span>'.$tab->text.'</span></a>';
6b25a26e 2837 } else {
d11a1daa 2838 $str .= '<a href="'.$tab->link.'" title="'.$tab->title.'"><span>'.$tab->text.'</span></a>';
f88ddd67 2839 }
a2b3f884 2840
84e3d2cc 2841 if (!empty($tab->subtree)) {
6b25a26e 2842 $str .= convert_tree_to_html($tab->subtree, $row+1);
36e8c122 2843 } else if ($tab->selected) {
d11a1daa 2844 $str .= '<div class="tabrow'.($row+1).' empty">&nbsp;</div>'."\n";
6b25a26e 2845 }
2846
a04c3b55 2847 $str .= ' </li>'."\n";
f88ddd67 2848 }
6b25a26e 2849 $str .= '</ul>'."\n";
a2b3f884 2850
6b25a26e 2851 return $str;
2852}
2853
449611af 2854/**
2855 * Convert nested tabrows to a nested array
2856 *
2857 * @param array $tabrows A [nested] array of tab row objects
2858 * @param string $selected The tabrow to select (by id)
2859 * @param array $inactive An array of tabrow id's to make inactive
2860 * @param array $activated An array of tabrow id's to make active
49c8c8d2 2861 * @return array The nested array
449611af 2862 */
0b4f88a6 2863function convert_tabrows_to_tree($tabrows, $selected, $inactive, $activated) {
6b25a26e 2864
2865/// Work backwards through the rows (bottom to top) collecting the tree as we go.
2866
2867 $tabrows = array_reverse($tabrows);
2868
2869 $subtree = array();
2870
2871 foreach ($tabrows as $row) {
2872 $tree = array();
2873
2874 foreach ($row as $tab) {
f522d310 2875 $tab->inactive = in_array((string)$tab->id, $inactive);
2876 $tab->active = in_array((string)$tab->id, $activated);
2877 $tab->selected = (string)$tab->id == $selected;
6b25a26e 2878
2879 if ($tab->active || $tab->selected) {
2880 if ($subtree) {
2881 $tab->subtree = $subtree;
2882 }
2883 }
2884 $tree[] = $tab;
2885 }
2886 $subtree = $tree;
027b0fe7 2887 }
6b25a26e 2888
3eb89b99 2889 return $subtree;
f88ddd67 2890}
2891
faf75fe7 2892/**
449611af 2893 * Returns the Moodle Docs URL in the users language
2894 *
2895 * @global object
faf75fe7 2896 * @param string $path the end of the URL.
449611af 2897 * @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 2898 */
2899function get_docs_url($path) {
2900 global $CFG;
3a915b06 2901 return $CFG->docroot . '/' . current_language() . '/' . $path;
faf75fe7 2902}
2903
b2118095 2904
fa989c38 2905/**
449611af 2906 * Standard Debugging Function
2907 *
7eb0b60a 2908 * Returns true if the current site debugging settings are equal or above specified level.
4bd0ddea 2909 * If passed a parameter it will emit a debugging notice similar to trigger_error(). The
2910 * routing of notices is controlled by $CFG->debugdisplay
fa989c38 2911 * eg use like this:
2912 *
7eb0b60a 2913 * 1) debugging('a normal debug notice');
2914 * 2) debugging('something really picky', DEBUG_ALL);
fa9f6bf6 2915 * 3) debugging('annoying debug message only for developers', DEBUG_DEVELOPER);
4bd0ddea 2916 * 4) if (debugging()) { perform extra debugging operations (do not use print or echo) }
2917 *
2918 * In code blocks controlled by debugging() (such as example 4)
2919 * any output should be routed via debugging() itself, or the lower-level
2920 * trigger_error() or error_log(). Using echo or print will break XHTML
2921 * JS and HTTP headers.
2922 *
2e9b772f 2923 * It is also possible to define NO_DEBUG_DISPLAY which redirects the message to error_log.
fa989c38 2924 *
449611af 2925 * @uses DEBUG_NORMAL
2fca6e0b 2926 * @param string $message a message to print
fa989c38 2927 * @param int $level the level at which this debugging statement should show
eee5d9bb 2928 * @param array $backtrace use different backtrace
fa989c38 2929 * @return bool
2930 */
34a2777c 2931function debugging($message = '', $level = DEBUG_NORMAL, $backtrace = null) {
4f19b365 2932 global $CFG, $UNITTEST;
fa989c38 2933
34a2777c 2934 if (empty($CFG->debug) || $CFG->debug < $level) {
fa989c38 2935 return false;
2936 }
2937
34a2777c 2938 if (!isset($CFG->debugdisplay)) {
2939 $CFG->debugdisplay = ini_get_bool('display_errors');
795a08ad 2940 }
2941
34a2777c 2942 if ($message) {
2943 if (!$backtrace) {
2944 $backtrace = debug_backtrace();
251387d0 2945 }
34a2777c 2946 $from = format_backtrace($backtrace, CLI_SCRIPT);
2e9b772f
PS
2947 if (!empty($UNITTEST->running)) {
2948 // When the unit tests are running, any call to trigger_error
2949 // is intercepted by the test framework and reported as an exception.
2950 // Therefore, we cannot use trigger_error during unit tests.
2951 // At the same time I do not think we should just discard those messages,
2952 // so displaying them on-screen seems like the only option. (MDL-20398)
2953 echo '<div class="notifytiny">' . $message . $from . '</div>';
2954
2955 } else if (NO_DEBUG_DISPLAY) {
2956 // script does not want any errors or debugging in output,
2957 // we send the info to error log instead
2958 error_log('Debugging: ' . $message . $from);
2959
2960 } else if ($CFG->debugdisplay) {
34a2777c 2961 if (!defined('DEBUGGING_PRINTED')) {
2962 define('DEBUGGING_PRINTED', 1); // indicates we have printed something
251387d0 2963 }
dc203659 2964 echo '<div class="notifytiny">' . $message . $from . '</div>';
2e9b772f 2965
34a2777c 2966 } else {
2967 trigger_error($message . $from, E_USER_NOTICE);
251387d0 2968 }
251387d0 2969 }
34a2777c 2970 return true;
251387d0 2971}
2972
4d0ccfa7 2973/**
2974* Outputs a HTML comment to the browser. This is used for those hard-to-debug
2975* pages that use bits from many different files in very confusing ways (e.g. blocks).
449611af 2976*
2977* <code>print_location_comment(__FILE__, __LINE__);</code>
2978*
4d0ccfa7 2979* @param string $file
2980* @param integer $line
2981* @param boolean $return Whether to return or print the comment
449611af 2982* @return string|void Void unless true given as third parameter
4d0ccfa7 2983*/
2984function print_location_comment($file, $line, $return = false)
2985{
2986 if ($return) {
2987 return "<!-- $file at line $line -->\n";
2988 } else {
2989 echo "<!-- $file at line $line -->\n";
2990 }
2991}
f145c248 2992
82b4da86 2993
f1af7aaa 2994/**
b7009474 2995 * @return boolean true if the current language is right-to-left (Hebrew, Arabic etc)
b2118095 2996 */
2997function right_to_left() {
e372f4c7 2998 return (get_string('thisdirection', 'langconfig') === 'rtl');
b2118095 2999}
3000
3001
3002/**
3003 * Returns swapped left<=>right if in RTL environment.
3004 * part of RTL support
3005 *
3006 * @param string $align align to check
3007 * @return string
3008 */
3009function fix_align_rtl($align) {
c5659019 3010 if (!right_to_left()) {
f1af7aaa 3011 return $align;
b2118095 3012 }
c5659019 3013 if ($align=='left') { return 'right'; }
3014 if ($align=='right') { return 'left'; }
3015 return $align;
b2118095 3016}
3017
3018
ee9beb53 3019/**
3020 * Returns true if the page is displayed in a popup window.
3021 * Gets the information from the URL parameter inpopup.
3022 *
fa9f6bf6 3023 * @todo Use a central function to create the popup calls all over Moodle and
449611af 3024 * In the moment only works with resources and probably questions.
ee9beb53 3025 *
449611af 3026 * @return boolean
ee9beb53 3027 */
f7c926ee 3028function is_in_popup() {
ee9beb53 3029 $inpopup = optional_param('inpopup', '', PARAM_BOOL);
c5659019 3030
ee9beb53 3031 return ($inpopup);
3032}
27bd819b 3033
c9ec505b 3034/**
3035 * To use this class.
3036 * - construct
3037 * - call create (or use the 3rd param to the constructor)
3038 * - call update or update_full repeatedly
449611af 3039 *
3040 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3041 * @package moodlecore
c9ec505b 3042 */
a6553373 3043class progress_bar {
fd4faf98 3044 /** @var string html id */
a6553373 3045 private $html_id;
fd4faf98 3046 /** @var int */
a6553373 3047 private $percent;
fd4faf98 3048 /** @var int */
a6553373 3049 private $width;
fd4faf98 3050 /** @var int */
a6553373 3051 private $lastcall;
fd4faf98 3052 /** @var int */
a6553373 3053 private $time_start;
3054 private $minimum_time = 2; //min time between updates.
449611af 3055 /**
fa9f6bf6 3056 * Constructor
449611af 3057 *
3058 * @param string $html_id
3059 * @param int $width
3060 * @param bool $autostart Default to false
3061 */
fd4faf98 3062 public function __construct($html_id = '', $width = 500, $autostart = false){
3063 if (!empty($html_id)) {
3064 $this->html_id = $html_id;
3065 } else {
3066 $this->html_id = uniqid();
3067 }
a6553373 3068 $this->width = $width;
3069 $this->restart();
3070 if($autostart){
3071 $this->create();
3072 }
3073 }
a6553373 3074 /**
449611af 3075 * Create a new progress bar, this function will output html.
49c8c8d2 3076 *
449611af 3077 * @return void Echo's output
a6553373 3078 */
fd4faf98 3079 public function create(){
a6553373 3080 flush();
3081 $this->lastcall->pt = 0;
3082 $this->lastcall->time = microtime(true);
3316fe24 3083 if (CLI_SCRIPT) {
3084 return; // temporary solution for cli scripts
3085 }
a6553373 3086 $htmlcode = <<<EOT
a6553373 3087 <div style="text-align:center;width:{$this->width}px;clear:both;padding:0;margin:0 auto;">
3088 <h2 id="status_{$this->html_id}" style="text-align: center;margin:0 auto"></h2>
3089 <p id="time_{$this->html_id}"></p>
3090 <div id="bar_{$this->html_id}" style="border-style:solid;border-width:1px;width:500px;height:50px;">
3091 <div id="progress_{$this->html_id}"
fd4faf98 3092 style="text-align:center;background:#FFCC66;width:4px;border:1px
a6553373 3093 solid gray;height:38px; padding-top:10px;">&nbsp;<span id="pt_{$this->html_id}"></span>
3094 </div>
3095 </div>
3096 </div>
3097EOT;
3098 echo $htmlcode;
3099 flush();
3100 }
449611af 3101 /**
3102 * Update the progress bar
3103 *
3104 * @param int $percent from 1-100
3105 * @param string $msg
3106 * @param mixed $es
3107 * @return void Echo's output
3108 */
fd4faf98 3109 private function _update($percent, $msg, $es){
e1524dbe 3110 global $PAGE;
a6553373 3111 if(empty($this->time_start)){
3112 $this->time_start = microtime(true);
3113 }
3114 $this->percent = $percent;
3115 $this->lastcall->time = microtime(true);
3116 $this->lastcall->pt = $percent;
3117 $w = $this->percent * $this->width;
3316fe24 3118 if (CLI_SCRIPT) {
3119 return; // temporary solution for cli scripts
3120 }
a6553373 3121 if ($es === null){
3122 $es = "Infinity";
3123 }
a62d5845 3124 echo html_writer::script(js_writer::function_call('update_progress_bar', Array($this->html_id, $w, $this->percent, $msg, $es)));
a6553373 3125 flush();
3126 }
3127 /**
3128 * estimate time
07e9a300 3129 *
449611af 3130 * @param int $curtime the time call this function
3131 * @param int $percent from 1-100
3132 * @return mixed Null, or int
a6553373 3133 */
fd4faf98 3134 private function estimate($curtime, $pt){
a6553373 3135 $consume = $curtime - $this->time_start;
3136 $one = $curtime - $this->lastcall->time;
3137 $this->percent = $pt;
07e9a300 3138 $percent = $pt - $this->lastcall->pt;
c9ec505b 3139 if ($percent != 0) {
a6553373 3140 $left = ($one / $percent) - $consume;
c9ec505b 3141 } else {
a6553373 3142 return null;
c9ec505b 3143 }
3144 if($left < 0) {
a6553373 3145 return 0;
c9ec505b 3146 } else {
a6553373 3147 return $left;
c9ec505b 3148 }
a6553373 3149 }
3150 /**
3151 * Update progress bar according