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