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