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