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