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