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