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