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