moodle_page: MDL-12212 reimplement user_is_editing, deprecate isediting
[moodle.git] / lib / weblib.php
CommitLineData
abf45bed 1<?php // $Id$
f9903ed0 2
9fa49e22 3///////////////////////////////////////////////////////////////////////////
4// //
5// NOTICE OF COPYRIGHT //
6// //
7// Moodle - Modular Object-Oriented Dynamic Learning Environment //
8// http://moodle.com //
9// //
77344659 10// Copyright (C) 1999 onwards Martin Dougiamas http://dougiamas.com //
9fa49e22 11// //
12// This program is free software; you can redistribute it and/or modify //
13// it under the terms of the GNU General Public License as published by //
14// the Free Software Foundation; either version 2 of the License, or //
15// (at your option) any later version. //
16// //
17// This program is distributed in the hope that it will be useful, //
18// but WITHOUT ANY WARRANTY; without even the implied warranty of //
19// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the //
20// GNU General Public License for more details: //
21// //
22// http://www.gnu.org/copyleft/gpl.html //
23// //
24///////////////////////////////////////////////////////////////////////////
f9903ed0 25
7cf1c7bd 26/**
27 * Library of functions for web output
28 *
29 * Library of all general-purpose Moodle PHP functions and constants
30 * that produce HTML output
31 *
32 * Other main libraries:
33 * - datalib.php - functions that access the database.
34 * - moodlelib.php - general-purpose Moodle functions.
35 * @author Martin Dougiamas
549c2dd2 36 * @version $Id$
89dcb99d 37 * @license http://www.gnu.org/copyleft/gpl.html GNU Public License
7cf1c7bd 38 * @package moodlecore
39 */
772e78be 40
6aaa17c7 41/// We are going to uses filterlib functions here
42require_once("$CFG->libdir/filterlib.php");
43
a194510a 44require_once("$CFG->libdir/ajax/ajaxlib.php");
45
0095d5cd 46/// Constants
47
c1d57101 48/// Define text formatting types ... eventually we can add Wiki, BBcode etc
7cf1c7bd 49
50/**
51 * Does all sorts of transformations and filtering
52 */
b0ccd3fb 53define('FORMAT_MOODLE', '0'); // Does all sorts of transformations and filtering
7cf1c7bd 54
55/**
56 * Plain HTML (with some tags stripped)
57 */
b0ccd3fb 58define('FORMAT_HTML', '1'); // Plain HTML (with some tags stripped)
7cf1c7bd 59
60/**
61 * Plain text (even tags are printed in full)
62 */
b0ccd3fb 63define('FORMAT_PLAIN', '2'); // Plain text (even tags are printed in full)
7cf1c7bd 64
65/**
66 * Wiki-formatted text
6a6495ff 67 * Deprecated: left here just to note that '3' is not used (at the moment)
68 * and to catch any latent wiki-like text (which generates an error)
7cf1c7bd 69 */
b0ccd3fb 70define('FORMAT_WIKI', '3'); // Wiki-formatted text
7cf1c7bd 71
72/**
73 * Markdown-formatted text http://daringfireball.net/projects/markdown/
74 */
b0ccd3fb 75define('FORMAT_MARKDOWN', '4'); // Markdown-formatted text http://daringfireball.net/projects/markdown/
0095d5cd 76
7d8a3cb0 77/**
78 * TRUSTTEXT marker - if present in text, text cleaning should be bypassed
79 */
80define('TRUSTTEXT', '#####TRUSTTEXT#####');
81
7cf1c7bd 82
d795bfdb 83/**
84 * Javascript related defines
85 */
86define('REQUIREJS_BEFOREHEADER', 0);
87define('REQUIREJS_INHEADER', 1);
88define('REQUIREJS_AFTERHEADER', 2);
89
7cf1c7bd 90/**
91 * Allowed tags - string of html tags that can be tested against for safe html tags
92 * @global string $ALLOWED_TAGS
93 */
5ea4af22 94global $ALLOWED_TAGS;
39dda0fc 95$ALLOWED_TAGS =
cf34d0ea 96'<p><br><b><i><u><font><table><tbody><thead><tfoot><span><div><tr><td><th><ol><ul><dl><li><dt><dd><h1><h2><h3><h4><h5><h6><hr><img><a><strong><emphasis><em><sup><sub><address><cite><blockquote><pre><strike><param><acronym><nolink><lang><tex><algebra><math><mi><mn><mo><mtext><mspace><ms><mrow><mfrac><msqrt><mroot><mstyle><merror><mpadded><mphantom><mfenced><msub><msup><msubsup><munder><mover><munderover><mmultiscripts><mtable><mtr><mtd><maligngroup><malignmark><maction><cn><ci><apply><reln><fn><interval><inverse><sep><condition><declare><lambda><compose><ident><quotient><exp><factorial><divide><max><min><minus><plus><power><rem><times><root><gcd><and><or><xor><not><implies><forall><exists><abs><conjugate><eq><neq><gt><lt><geq><leq><ln><log><int><diff><partialdiff><lowlimit><uplimit><bvar><degree><set><list><union><intersect><in><notin><subset><prsubset><notsubset><notprsubset><setdiff><sum><product><limit><tendsto><mean><sdev><variance><median><mode><moment><vector><matrix><matrixrow><determinant><transpose><selector><annotation><semantics><annotation-xml><tt><code>';
d046ae55 97
037dcbb6 98/**
99 * Allowed protocols - array of protocols that are safe to use in links and so on
100 * @global string $ALLOWED_PROTOCOLS
101 */
f941df22 102$ALLOWED_PROTOCOLS = array('http', 'https', 'ftp', 'news', 'mailto', 'rtsp', 'teamspeak', 'gopher', 'mms',
f697a421 103 'color', 'callto', 'cursor', 'text-align', 'font-size', 'font-weight', 'font-style', 'font-family',
62097c91 104 'border', 'margin', 'padding', 'background', 'background-color', 'text-decoration'); // CSS as well to get through kses
037dcbb6 105
106
0095d5cd 107/// Functions
108
7cf1c7bd 109/**
110 * Add quotes to HTML characters
111 *
112 * Returns $var with HTML characters (like "<", ">", etc.) properly quoted.
113 * This function is very similar to {@link p()}
114 *
115 * @param string $var the string potentially containing HTML characters
b4cf9371 116 * @param boolean $obsolete no longer used.
7cf1c7bd 117 * @return string
118 */
b4cf9371 119function s($var, $obsolete = false) {
d4a42ff4 120
63e554d0 121 if ($var == '0') { // for integer 0, boolean false, string '0'
122 return '0';
3662bce5 123 }
d4a42ff4 124
0c34c7eb 125 return preg_replace("/&amp;(#\d+);/i", "&$1;", htmlspecialchars($var));
f9903ed0 126}
127
7cf1c7bd 128/**
129 * Add quotes to HTML characters
130 *
d48b00b4 131 * Prints $var with HTML characters (like "<", ">", etc.) properly quoted.
7cf1c7bd 132 * This function is very similar to {@link s()}
133 *
134 * @param string $var the string potentially containing HTML characters
b4cf9371 135 * @param boolean $obsolete no longer used.
7cf1c7bd 136 * @return string
137 */
b4cf9371 138function p($var, $obsolete = false) {
139 echo s($var, $obsolete);
f9903ed0 140}
141
0d1cd0ea 142/**
143 * Does proper javascript quoting.
5ce73257 144 * Do not use addslashes anymore, because it does not work when magic_quotes_sybase is enabled.
145 *
e2cd3ed0 146 * @since 1.8 - 22/02/2007
0d1cd0ea 147 * @param mixed value
148 * @return mixed quoted result
149 */
150function addslashes_js($var) {
151 if (is_string($var)) {
152 $var = str_replace('\\', '\\\\', $var);
153 $var = str_replace(array('\'', '"', "\n", "\r", "\0"), array('\\\'', '\\"', '\\n', '\\r', '\\0'), $var);
4702be4e 154 $var = str_replace('</', '<\/', $var); // XHTML compliance
0d1cd0ea 155 } else if (is_array($var)) {
156 $var = array_map('addslashes_js', $var);
157 } else if (is_object($var)) {
158 $a = get_object_vars($var);
159 foreach ($a as $key=>$value) {
160 $a[$key] = addslashes_js($value);
161 }
162 $var = (object)$a;
163 }
164 return $var;
165}
7cf1c7bd 166
7cf1c7bd 167/**
168 * Remove query string from url
169 *
170 * Takes in a URL and returns it without the querystring portion
171 *
172 * @param string $url the url which may have a query string attached
173 * @return string
174 */
175 function strip_querystring($url) {
f9903ed0 176
b9b8ab69 177 if ($commapos = strpos($url, '?')) {
178 return substr($url, 0, $commapos);
179 } else {
180 return $url;
181 }
f9903ed0 182}
183
7cf1c7bd 184/**
c8135a35 185 * Returns the URL of the HTTP_REFERER, less the querystring portion if required
9ea04325 186 * @param boolean $stripquery if true, also removes the query part of the url.
7cf1c7bd 187 * @return string
188 */
c8135a35 189function get_referer($stripquery=true) {
d90ffc1f 190 if (isset($_SERVER['HTTP_REFERER'])) {
c8135a35 191 if ($stripquery) {
192 return strip_querystring($_SERVER['HTTP_REFERER']);
193 } else {
194 return $_SERVER['HTTP_REFERER'];
195 }
d90ffc1f 196 } else {
5ce73257 197 return '';
d90ffc1f 198 }
f9903ed0 199}
200
c1d57101 201
7cf1c7bd 202/**
203 * Returns the name of the current script, WITH the querystring portion.
204 * this function is necessary because PHP_SELF and REQUEST_URI and SCRIPT_NAME
205 * return different things depending on a lot of things like your OS, Web
206 * server, and the way PHP is compiled (ie. as a CGI, module, ISAPI, etc.)
d48b00b4 207 * <b>NOTE:</b> This function returns false if the global variables needed are not set.
208 *
7cf1c7bd 209 * @return string
210 */
211 function me() {
11e7b506 212 global $ME;
213 return $ME;
f9903ed0 214}
215
7cf1c7bd 216/**
d48b00b4 217 * Like {@link me()} but returns a full URL
7cf1c7bd 218 * @see me()
7cf1c7bd 219 * @return string
220 */
f9903ed0 221function qualified_me() {
11e7b506 222 global $FULLME;
223 return $FULLME;
f9903ed0 224}
225
360e503e 226/**
227 * Class for creating and manipulating urls.
84e3d2cc 228 *
fae60ee3 229 * See short write up here http://docs.moodle.org/en/Development:lib/weblib.php_moodle_url
360e503e 230 */
231class moodle_url {
7ceb61d8 232 protected $scheme = ''; // e.g. http
233 protected $host = '';
234 protected $port = '';
235 protected $user = '';
236 protected $pass = '';
237 protected $path = '';
238 protected $fragment = '';
239 protected $params = array(); // Associative array of query string params
84e3d2cc 240
360e503e 241 /**
242 * Pass no arguments to create a url that refers to this page. Use empty string to create empty url.
84e3d2cc 243 *
75781f87 244 * @param mixed $url a number of different forms are accespted:
245 * null - create a URL that is the same as the URL used to load this page, but with no query string
246 * '' - and empty URL
247 * string - a URL, will be parsed into it's bits, including query string
248 * array - as returned from the PHP function parse_url
249 * moodle_url - make a copy of another moodle_url
7ceb61d8 250 * @param array $params these params override anything in the query string
251 * where params have the same name.
360e503e 252 */
7ceb61d8 253 public function __construct($url = null, $params = array()) {
75781f87 254 if ($url === '') {
255 // Leave URL blank.
256 } else if (is_a($url, 'moodle_url')) {
257 $this->scheme = $url->scheme;
258 $this->host = $url->host;
259 $this->port = $url->port;
260 $this->user = $url->user;
261 $this->pass = $url->pass;
ad52c04f 262 $this->path = $url->path;
75781f87 263 $this->fragment = $url->fragment;
264 $this->params = $url->params;
265 } else {
7ceb61d8 266 if ($url === null) {
75781f87 267 global $ME;
11e7b506 268 $url = $ME;
360e503e 269 }
75781f87 270 if (is_string($url)) {
271 $url = parse_url($url);
272 }
273 $parts = $url;
7ceb61d8 274 if ($parts === FALSE) {
75781f87 275 throw new moodle_exception('invalidurl');
360e503e 276 }
7ceb61d8 277 if (isset($parts['query'])) {
24a905f9 278 parse_str(str_replace('&amp;', '&', $parts['query']), $this->params);
360e503e 279 }
280 unset($parts['query']);
7ceb61d8 281 foreach ($parts as $key => $value) {
360e503e 282 $this->$key = $value;
283 }
284 }
75781f87 285 $this->params($params);
84e3d2cc 286 }
7ceb61d8 287
360e503e 288 /**
84e3d2cc 289 * Add an array of params to the params for this page. The added params override existing ones if they
360e503e 290 * have the same name.
291 *
7ceb61d8 292 * @param array $params Defaults to null. If null then return value of param 'name'.
c1f41c59 293 * @return array params for url.
360e503e 294 */
7ceb61d8 295 public function params($params = null) {
296 if (!is_null($params)) {
c1f41c59 297 return $this->params = $params + $this->params;
298 } else {
299 return $this->params;
300 }
360e503e 301 }
84e3d2cc 302
360e503e 303 /**
75781f87 304 * Remove all params if no arguments passed. Remove selected params if
305 * arguments are passed. Can be called as either remove_params('param1', 'param2')
306 * or remove_params(array('param1', 'param2')).
360e503e 307 *
75781f87 308 * @param mixed $params either an array of param names, or a string param name,
309 * @param string $params,... any number of additional param names.
360e503e 310 */
49127522 311 public function remove_params($params = NULL) {
75781f87 312 if (empty($params)) {
360e503e 313 $this->params = array();
75781f87 314 return;
315 }
316 if (!is_array($params)) {
317 $params = func_get_args();
318 }
319 foreach ($params as $param) {
320 if (isset($this->params[$param])) {
321 unset($this->params[$param]);
322 }
360e503e 323 }
324 }
325
326 /**
84e3d2cc 327 * Add a param to the params for this page. The added param overrides existing one if they
360e503e 328 * have the same name.
329 *
330 * @param string $paramname name
7ceb61d8 331 * @param string $param value. Defaults to null. If null then return value of param 'name'
360e503e 332 */
7ceb61d8 333 public function param($paramname, $param = null) {
334 if (!is_null($param)) {
c1f41c59 335 $this->params = array($paramname => $param) + $this->params;
336 } else {
5762b36e 337 return $this->params[$paramname];
c1f41c59 338 }
360e503e 339 }
340
7ceb61d8 341 /**
342 * Get the params as as a query string.
343 * @param array $overrideparams params to add to the output params, these
344 * override existing ones with the same name.
345 * @return string query string that can be added to a url.
346 */
347 public function get_query_string($overrideparams = array()) {
360e503e 348 $arr = array();
349 $params = $overrideparams + $this->params;
7ceb61d8 350 foreach ($params as $key => $val) {
360e503e 351 $arr[] = urlencode($key)."=".urlencode($val);
352 }
dc1f7683 353 return implode($arr, "&amp;");
360e503e 354 }
7ceb61d8 355
360e503e 356 /**
357 * Outputs params as hidden form elements.
fcdb06c4 358 *
fae60ee3 359 * @param array $exclude params to ignore
360 * @param integer $indent indentation
f44e4d14 361 * @param array $overrideparams params to add to the output params, these
7ceb61d8 362 * override existing ones with the same name.
360e503e 363 * @return string html for form elements.
364 */
7ceb61d8 365 public function hidden_params_out($exclude = array(), $indent = 0, $overrideparams=array()) {
360e503e 366 $tabindent = str_repeat("\t", $indent);
367 $str = '';
f44e4d14 368 $params = $overrideparams + $this->params;
7ceb61d8 369 foreach ($params as $key => $val) {
fcdb06c4 370 if (FALSE === array_search($key, $exclude)) {
83bc64db 371 $val = s($val);
fcdb06c4 372 $str.= "$tabindent<input type=\"hidden\" name=\"$key\" value=\"$val\" />\n";
373 }
360e503e 374 }
375 return $str;
376 }
7ceb61d8 377
360e503e 378 /**
379 * Output url
84e3d2cc 380 *
360e503e 381 * @param boolean $noquerystring whether to output page params as a query string in the url.
382 * @param array $overrideparams params to add to the output url, these override existing ones with the same name.
383 * @return string url
384 */
7ceb61d8 385 public function out($noquerystring = false, $overrideparams = array()) {
360e503e 386 $uri = $this->scheme ? $this->scheme.':'.((strtolower($this->scheme) == 'mailto') ? '':'//'): '';
387 $uri .= $this->user ? $this->user.($this->pass? ':'.$this->pass:'').'@':'';
388 $uri .= $this->host ? $this->host : '';
389 $uri .= $this->port ? ':'.$this->port : '';
390 $uri .= $this->path ? $this->path : '';
7ceb61d8 391 if (!$noquerystring) {
dc1f7683 392 $uri .= (count($this->params)||count($overrideparams)) ? '?'.$this->get_query_string($overrideparams) : '';
360e503e 393 }
394 $uri .= $this->fragment ? '#'.$this->fragment : '';
84e3d2cc 395 return $uri;
360e503e 396 }
7ceb61d8 397
360e503e 398 /**
399 * Output action url with sesskey
84e3d2cc 400 *
360e503e 401 * @param boolean $noquerystring whether to output page params as a query string in the url.
402 * @return string url
403 */
7ceb61d8 404 public function out_action($overrideparams = array()) {
360e503e 405 $overrideparams = array('sesskey'=> sesskey()) + $overrideparams;
dc1f7683 406 return $this->out(false, $overrideparams);
360e503e 407 }
408}
409
7cf1c7bd 410/**
411 * Determine if there is data waiting to be processed from a form
412 *
413 * Used on most forms in Moodle to check for data
414 * Returns the data as an object, if it's found.
415 * This object can be used in foreach loops without
416 * casting because it's cast to (array) automatically
772e78be 417 *
9c0f063b 418 * Checks that submitted POST data exists and returns it as object.
d48b00b4 419 *
9c0f063b 420 * @return mixed false or object
7cf1c7bd 421 */
294ce987 422function data_submitted() {
d48b00b4 423
607809b3 424 if (empty($_POST)) {
36b4f985 425 return false;
426 } else {
294ce987 427 return (object)$_POST;
36b4f985 428 }
429}
430
7cf1c7bd 431/**
d48b00b4 432 * Given some normal text this function will break up any
433 * long words to a given size by inserting the given character
434 *
6aaa17c7 435 * It's multibyte savvy and doesn't change anything inside html tags.
436 *
7cf1c7bd 437 * @param string $string the string to be modified
89dcb99d 438 * @param int $maxsize maximum length of the string to be returned
7cf1c7bd 439 * @param string $cutchar the string used to represent word breaks
440 * @return string
441 */
4a5644e5 442function break_up_long_words($string, $maxsize=20, $cutchar=' ') {
a2b3f884 443
6aaa17c7 444/// Loading the textlib singleton instance. We are going to need it.
445 $textlib = textlib_get_instance();
8f7dc7f1 446
6aaa17c7 447/// First of all, save all the tags inside the text to skip them
448 $tags = array();
449 filter_save_tags($string,$tags);
5b07d990 450
6aaa17c7 451/// Process the string adding the cut when necessary
4a5644e5 452 $output = '';
810944af 453 $length = $textlib->strlen($string);
4a5644e5 454 $wordlength = 0;
455
456 for ($i=0; $i<$length; $i++) {
810944af 457 $char = $textlib->substr($string, $i, 1);
6aaa17c7 458 if ($char == ' ' or $char == "\t" or $char == "\n" or $char == "\r" or $char == "<" or $char == ">") {
4a5644e5 459 $wordlength = 0;
460 } else {
461 $wordlength++;
462 if ($wordlength > $maxsize) {
463 $output .= $cutchar;
464 $wordlength = 0;
465 }
466 }
467 $output .= $char;
468 }
6aaa17c7 469
470/// Finally load the tags back again
471 if (!empty($tags)) {
472 $output = str_replace(array_keys($tags), $tags, $output);
473 }
474
4a5644e5 475 return $output;
476}
477
7cf1c7bd 478/**
fc5e9c40 479 * This function will print a button/link/etc. form element
480 * that will work on both Javascript and non-javascript browsers.
7cf1c7bd 481 * Relies on the Javascript function openpopup in javascript.php
d48b00b4 482 *
fc5e9c40 483 * All parameters default to null, only $type and $url are mandatory.
484 *
7cf1c7bd 485 * $url must be relative to home page eg /mod/survey/stuff.php
bed9cec8 486 * @param string $url Web link. Either relative to $CFG->wwwroot, or a full URL.
73f7ad71 487 * @param string $name Name to be assigned to the popup window (this is used by
a5fe6177 488 * client-side scripts to "talk" to the popup window)
7cf1c7bd 489 * @param string $linkname Text to be displayed as web link
89dcb99d 490 * @param int $height Height to assign to popup window
491 * @param int $width Height to assign to popup window
7cf1c7bd 492 * @param string $title Text to be displayed as popup page title
493 * @param string $options List of additional options for popup window
fc5e9c40 494 * @param string $return If true, return as a string, otherwise print
495 * @param string $id id added to the element
496 * @param string $class class added to the element
7cf1c7bd 497 * @return string
498 * @uses $CFG
499 */
fc5e9c40 500function element_to_popup_window ($type=null, $url=null, $name=null, $linkname=null,
c5659019 501 $height=400, $width=500, $title=null,
fc5e9c40 502 $options=null, $return=false, $id=null, $class=null) {
f9903ed0 503
c5659019 504 if (is_null($url)) {
b867e602 505 debugging('You must give the url to display in the popup. URL is missing - can\'t create popup window.', DEBUG_DEVELOPER);
2416a6f7 506 }
ff80e012 507
fc5e9c40 508 global $CFG;
f9903ed0 509
2416a6f7 510 if ($options == 'none') { // 'none' is legacy, should be removed in v2.0
c5659019 511 $options = null;
fc5e9c40 512 }
513
514 // add some sane default options for popup windows
c5659019 515 if (!$options) {
516 $options = 'menubar=0,location=0,scrollbars,resizable';
2416a6f7 517 }
c5659019 518 if ($width) {
519 $options .= ',width='. $width;
2416a6f7 520 }
c5659019 521 if ($height) {
522 $options .= ',height='. $height;
2416a6f7 523 }
c5659019 524 if ($id) {
525 $id = ' id="'.$id.'" ';
2416a6f7 526 }
c5659019 527 if ($class) {
528 $class = ' class="'.$class.'" ';
2416a6f7 529 }
b867e602 530 if ($name) {
4ba6b3e3 531 $_name = $name;
532 if (($name = preg_replace("/\s/", '_', $name)) != $_name) {
533 debugging('The $name of a popup window shouldn\'t contain spaces - string modified. '. $_name .' changed to '. $name, DEBUG_DEVELOPER);
534 }
b867e602 535 } else {
a5fe6177 536 $name = 'popup';
2416a6f7 537 }
73f7ad71 538
a5fe6177 539 // get some default string, using the localized version of legacy defaults
32ba2f0d 540 if (is_null($linkname) || $linkname === '') {
5df984eb 541 $linkname = get_string('clickhere');
2416a6f7 542 }
c5659019 543 if (!$title) {
5df984eb 544 $title = get_string('popupwindowname');
2416a6f7 545 }
fc5e9c40 546
c5659019 547 $fullscreen = 0; // must be passed to openpopup
fc5e9c40 548 $element = '';
549
550 switch ($type) {
bed9cec8 551 case 'button':
fc5e9c40 552 $element = '<input type="button" name="'. $name .'" title="'. $title .'" value="'. $linkname .'" '. $id . $class .
553 "onclick=\"return openpopup('$url', '$name', '$options', $fullscreen);\" />\n";
554 break;
bed9cec8 555 case 'link':
556 // Add wwwroot only if the URL does not already start with http:// or https://
557 if (!preg_match('|https?://|', $url)) {
558 $url = $CFG->wwwroot . $url;
fc5e9c40 559 }
bed9cec8 560 $element = '<a title="'. s(strip_tags($title)) .'" href="'. $url .'" '.
fc5e9c40 561 "onclick=\"this.target='$name'; return openpopup('$url', '$name', '$options', $fullscreen);\">$linkname</a>";
562 break;
563 default :
e49ef64a 564 print_error('cannotcreatepopupwin');
fc5e9c40 565 break;
c80b7585 566 }
567
1f2eec7b 568 if ($return) {
fc5e9c40 569 return $element;
1f2eec7b 570 } else {
fc5e9c40 571 echo $element;
1f2eec7b 572 }
f9903ed0 573}
574
7cf1c7bd 575/**
fc5e9c40 576 * Creates and displays (or returns) a link to a popup window, using element_to_popup_window function.
d48b00b4 577 *
fc5e9c40 578 * @return string html code to display a link to a popup window.
579 * @see element_to_popup_window()
7cf1c7bd 580 */
fc5e9c40 581function link_to_popup_window ($url, $name=null, $linkname=null,
582 $height=400, $width=500, $title=null,
583 $options=null, $return=false) {
52f1b496 584
fc5e9c40 585 return element_to_popup_window('link', $url, $name, $linkname, $height, $width, $title, $options, $return, null, null);
586}
0f7d4e5e 587
fc5e9c40 588/**
589 * Creates and displays (or returns) a buttons to a popup window, using element_to_popup_window function.
590 *
591 * @return string html code to display a button to a popup window.
592 * @see element_to_popup_window()
593 */
594function button_to_popup_window ($url, $name=null, $linkname=null,
595 $height=400, $width=500, $title=null, $options=null, $return=false,
596 $id=null, $class=null) {
52f1b496 597
fc5e9c40 598 return element_to_popup_window('button', $url, $name, $linkname, $height, $width, $title, $options, $return, $id, $class);
52f1b496 599}
600
601
7cf1c7bd 602/**
603 * Prints a simple button to close a window
9ea04325 604 * @param string $name name of the window to close
829eabfe 605 * @param boolean $return whether this function should return a string or output it.
606 * @param boolean $reloadopener if true, clicking the button will also reload
607 * the page that opend this popup window.
9ea04325 608 * @return string if $return is true, nothing otherwise
7cf1c7bd 609 */
829eabfe 610function close_window_button($name='closewindow', $return=false, $reloadopener = false) {
38d5ab86 611 global $CFG;
612
829eabfe 613 $js = 'self.close();';
614 if ($reloadopener) {
615 $js = 'window.opener.location.reload(1);' . $js;
616 }
617
eaeaf964 618 $output = '';
619
4079b3d7 620 $output .= '<div class="closewindow">' . "\n";
450522e3 621 $output .= '<form action="#"><div>';
829eabfe 622 $output .= '<input type="button" onclick="' . $js . '" value="'.get_string($name).'" />';
38d5ab86 623 $output .= '</div></form>';
4079b3d7 624 $output .= '</div>' . "\n";
eaeaf964 625
626 if ($return) {
627 return $output;
628 } else {
629 echo $output;
630 }
f9903ed0 631}
632
08396bb2 633/*
b166403f 634 * Try and close the current window using JavaScript, either immediately, or after a delay.
635 * @param integer $delay a delay in seconds before closing the window. Default 0.
636 * @param boolean $reloadopener if true, we will see if this window was a pop-up, and try
637 * to reload the parent window before this one closes.
08396bb2 638 */
b166403f 639function close_window($delay = 0, $reloadopener = false) {
c13a5e71 640 global $THEME, $PAGE;
08396bb2 641
c13a5e71 642 if (!$PAGE->headerprinted) {
b166403f 643 print_header(get_string('closewindow'));
644 } else {
645 print_container_end_all(false, $THEME->open_header_containers);
646 }
647
648 if ($reloadopener) {
649 $function = 'close_window_reloading_opener';
650 } else {
651 $function = 'close_window';
652 }
653 echo '<p class="centerpara">' . get_string('windowclosing') . '</p>';
654 print_delayed_js_call($delay, $function);
655
656 print_footer('empty');
657 exit;
658}
08396bb2 659
d48b00b4 660/**
75afe0e7 661 * Given an array of values, output the HTML for a select element with those options.
662 * Normally, you only need to use the first few parameters.
d48b00b4 663 *
75afe0e7 664 * @param array $options The options to offer. An array of the form
665 * $options[{value}] = {text displayed for that option};
666 * @param string $name the name of this form control, as in &lt;select name="..." ...
667 * @param string $selected the option to select initially, default none.
668 * @param string $nothing The label for the 'nothing is selected' option. Defaults to get_string('choose').
669 * Set this to '' if you don't want a 'nothing is selected' option.
670 * @param string $script in not '', then this is added to the &lt;select> element as an onchange handler.
671 * @param string $nothingvalue The value corresponding to the $nothing option. Defaults to 0.
672 * @param boolean $return if false (the default) the the output is printed directly, If true, the
673 * generated HTML is returned as a string.
674 * @param boolean $disabled if true, the select is generated in a disabled state. Default, false.
675 * @param int $tabindex if give, sets the tabindex attribute on the &lt;select> element. Default none.
676 * @param string $id value to use for the id attribute of the &lt;select> element. If none is given,
677 * then a suitable one is constructed.
1ea118e4 678 * @param mixed $listbox if false, display as a dropdown menu. If true, display as a list box.
679 * By default, the list box will have a number of rows equal to min(10, count($options)), but if
680 * $listbox is an integer, that number is used for size instead.
d7074a5d 681 * @param boolean $multiple if true, enable multiple selections, else only 1 item can be selected. Used
682 * when $listbox display is enabled
683 * @param string $class value to use for the class attribute of the &lt;select> element. If none is given,
684 * then a suitable one is constructed.
d48b00b4 685 */
c06c8492 686function choose_from_menu ($options, $name, $selected='', $nothing='choose', $script='',
1ea118e4 687 $nothingvalue='0', $return=false, $disabled=false, $tabindex=0,
d7074a5d 688 $id='', $listbox=false, $multiple=false, $class='') {
ab9f24ad 689
b0ccd3fb 690 if ($nothing == 'choose') {
691 $nothing = get_string('choose') .'...';
618b22c5 692 }
693
48e535bc 694 $attributes = ($script) ? 'onchange="'. $script .'"' : '';
695 if ($disabled) {
696 $attributes .= ' disabled="disabled"';
f9903ed0 697 }
9c9f7d77 698
25e5dbf9 699 if ($tabindex) {
700 $attributes .= ' tabindex="'.$tabindex.'"';
701 }
702
7850588a 703 if ($id ==='') {
a1c91f9a 704 $id = 'menu'.$name;
705 // name may contaion [], which would make an invalid id. e.g. numeric question type editing form, assignment quickgrading
706 $id = str_replace('[', '', $id);
707 $id = str_replace(']', '', $id);
7850588a 708 }
709
d7074a5d 710 if ($class ==='') {
caec4b6f 711 $class = 'menu'.$name;
d7074a5d 712 // name may contaion [], which would make an invalid class. e.g. numeric question type editing form, assignment quickgrading
713 $class = str_replace('[', '', $class);
714 $class = str_replace(']', '', $class);
715 }
caec4b6f 716 $class = 'select ' . $class; /// Add 'select' selector always
d7074a5d 717
1ea118e4 718 if ($listbox) {
719 if (is_integer($listbox)) {
720 $size = $listbox;
721 } else {
722 $numchoices = count($options);
723 if ($nothing) {
724 $numchoices += 1;
725 }
726 $size = min(10, $numchoices);
727 }
728 $attributes .= ' size="' . $size . '"';
729 if ($multiple) {
730 $attributes .= ' multiple="multiple"';
731 }
732 }
733
d7074a5d 734 $output = '<select id="'. $id .'" class="'. $class .'" name="'. $name .'" '. $attributes .'>' . "\n";
bda8d43a 735 if ($nothing) {
7850588a 736 $output .= ' <option value="'. s($nothingvalue) .'"'. "\n";
cec0a0fc 737 if ($nothingvalue === $selected) {
b0ccd3fb 738 $output .= ' selected="selected"';
bda8d43a 739 }
b0ccd3fb 740 $output .= '>'. $nothing .'</option>' . "\n";
873960de 741 }
1ea118e4 742
607809b3 743 if (!empty($options)) {
744 foreach ($options as $value => $label) {
7850588a 745 $output .= ' <option value="'. s($value) .'"';
1ea118e4 746 if ((string)$value == (string)$selected ||
747 (is_array($selected) && in_array($value, $selected))) {
b0ccd3fb 748 $output .= ' selected="selected"';
607809b3 749 }
b0ccd3fb 750 if ($label === '') {
751 $output .= '>'. $value .'</option>' . "\n";
a20c1090 752 } else {
b0ccd3fb 753 $output .= '>'. $label .'</option>' . "\n";
607809b3 754 }
f9903ed0 755 }
756 }
b0ccd3fb 757 $output .= '</select>' . "\n";
08056730 758
759 if ($return) {
760 return $output;
761 } else {
762 echo $output;
763 }
ab9f24ad 764}
f9903ed0 765
73d4db84 766/**
767 * Choose value 0 or 1 from a menu with options 'No' and 'Yes'.
768 * Other options like choose_from_menu.
9ea04325 769 * @param string $name
73f7ad71 770 * @param string $selected
9ea04325 771 * @param string $string (defaults to '')
772 * @param boolean $return whether this function should return a string or output it (defaults to false)
773 * @param boolean $disabled (defaults to false)
774 * @param int $tabindex
73d4db84 775 */
776function choose_from_menu_yesno($name, $selected, $script = '',
777 $return = false, $disabled = false, $tabindex = 0) {
778 return choose_from_menu(array(get_string('no'), get_string('yes')), $name,
779 $selected, '', $script, '0', $return, $disabled, $tabindex);
780}
781
14040797 782/**
783 * Just like choose_from_menu, but takes a nested array (2 levels) and makes a dropdown menu
784 * including option headings with the first level.
785 */
786function choose_from_menu_nested($options,$name,$selected='',$nothing='choose',$script = '',
787 $nothingvalue=0,$return=false,$disabled=false,$tabindex=0) {
788
789 if ($nothing == 'choose') {
790 $nothing = get_string('choose') .'...';
791 }
792
793 $attributes = ($script) ? 'onchange="'. $script .'"' : '';
794 if ($disabled) {
795 $attributes .= ' disabled="disabled"';
796 }
797
798 if ($tabindex) {
799 $attributes .= ' tabindex="'.$tabindex.'"';
800 }
801
802 $output = '<select id="menu'.$name.'" name="'. $name .'" '. $attributes .'>' . "\n";
803 if ($nothing) {
804 $output .= ' <option value="'. $nothingvalue .'"'. "\n";
805 if ($nothingvalue === $selected) {
806 $output .= ' selected="selected"';
807 }
808 $output .= '>'. $nothing .'</option>' . "\n";
809 }
810 if (!empty($options)) {
811 foreach ($options as $section => $values) {
84e3d2cc 812
dacb47c0 813 $output .= ' <optgroup label="'. s(format_string($section)) .'">'."\n";
14040797 814 foreach ($values as $value => $label) {
dacb47c0 815 $output .= ' <option value="'. format_string($value) .'"';
f332bd02 816 if ((string)$value == (string)$selected) {
14040797 817 $output .= ' selected="selected"';
818 }
819 if ($label === '') {
820 $output .= '>'. $value .'</option>' . "\n";
821 } else {
822 $output .= '>'. $label .'</option>' . "\n";
823 }
824 }
825 $output .= ' </optgroup>'."\n";
826 }
827 }
828 $output .= '</select>' . "\n";
829
830 if ($return) {
831 return $output;
832 } else {
833 echo $output;
834 }
835}
836
837
531a3cb2 838/**
839 * Given an array of values, creates a group of radio buttons to be part of a form
c06c8492 840 *
531a3cb2 841 * @param array $options An array of value-label pairs for the radio group (values as keys)
842 * @param string $name Name of the radiogroup (unique in the form)
843 * @param string $checked The value that is already checked
844 */
eaeaf964 845function choose_from_radio ($options, $name, $checked='', $return=false) {
531a3cb2 846
20cbef63 847 static $idcounter = 0;
848
531a3cb2 849 if (!$name) {
850 $name = 'unnamed';
851 }
852
853 $output = '<span class="radiogroup '.$name."\">\n";
854
855 if (!empty($options)) {
856 $currentradio = 0;
857 foreach ($options as $value => $label) {
20cbef63 858 $htmlid = 'auto-rb'.sprintf('%04d', ++$idcounter);
859 $output .= ' <span class="radioelement '.$name.' rb'.$currentradio."\">";
860 $output .= '<input name="'.$name.'" id="'.$htmlid.'" type="radio" value="'.$value.'"';
531a3cb2 861 if ($value == $checked) {
862 $output .= ' checked="checked"';
863 }
864 if ($label === '') {
20cbef63 865 $output .= ' /> <label for="'.$htmlid.'">'. $value .'</label></span>' . "\n";
531a3cb2 866 } else {
20cbef63 867 $output .= ' /> <label for="'.$htmlid.'">'. $label .'</label></span>' . "\n";
531a3cb2 868 }
869 $currentradio = ($currentradio + 1) % 2;
870 }
871 }
872
873 $output .= '</span>' . "\n";
874
eaeaf964 875 if ($return) {
876 return $output;
877 } else {
878 echo $output;
879 }
531a3cb2 880}
881
2481037f 882/** Display an standard html checkbox with an optional label
883 *
884 * @param string $name The name of the checkbox
885 * @param string $value The valus that the checkbox will pass when checked
886 * @param boolean $checked The flag to tell the checkbox initial state
887 * @param string $label The label to be showed near the checkbox
888 * @param string $alt The info to be inserted in the alt tag
889 */
d0d272e7 890function print_checkbox ($name, $value, $checked = true, $label = '', $alt = '', $script='',$return=false) {
2481037f 891
20cbef63 892 static $idcounter = 0;
893
2481037f 894 if (!$name) {
895 $name = 'unnamed';
896 }
897
27f79fda 898 if ($alt) {
899 $alt = strip_tags($alt);
900 } else {
2481037f 901 $alt = 'checkbox';
902 }
903
904 if ($checked) {
905 $strchecked = ' checked="checked"';
f89f924e 906 } else {
907 $strchecked = '';
2481037f 908 }
909
20cbef63 910 $htmlid = 'auto-cb'.sprintf('%04d', ++$idcounter);
2481037f 911 $output = '<span class="checkbox '.$name."\">";
fbe31d22 912 $output .= '<input name="'.$name.'" id="'.$htmlid.'" type="checkbox" value="'.$value.'" alt="'.$alt.'"'.$strchecked.' '.((!empty($script)) ? ' onclick="'.$script.'" ' : '').' />';
20cbef63 913 if(!empty($label)) {
914 $output .= ' <label for="'.$htmlid.'">'.$label.'</label>';
915 }
2481037f 916 $output .= '</span>'."\n";
917
d0d272e7 918 if (empty($return)) {
919 echo $output;
920 } else {
921 return $output;
922 }
2481037f 923
924}
925
d0d272e7 926/** Display an standard html text field with an optional label
927 *
928 * @param string $name The name of the text field
929 * @param string $value The value of the text field
930 * @param string $label The label to be showed near the text field
931 * @param string $alt The info to be inserted in the alt tag
932 */
eaeaf964 933function print_textfield ($name, $value, $alt = '',$size=50,$maxlength=0, $return=false) {
d0d272e7 934
935 static $idcounter = 0;
936
937 if (empty($name)) {
938 $name = 'unnamed';
939 }
940
941 if (empty($alt)) {
942 $alt = 'textfield';
943 }
944
945 if (!empty($maxlength)) {
946 $maxlength = ' maxlength="'.$maxlength.'" ';
947 }
948
ce432524 949 $htmlid = 'auto-tf'.sprintf('%04d', ++$idcounter);
d0d272e7 950 $output = '<span class="textfield '.$name."\">";
951 $output .= '<input name="'.$name.'" id="'.$htmlid.'" type="text" value="'.$value.'" size="'.$size.'" '.$maxlength.' alt="'.$alt.'" />';
c06c8492 952
d0d272e7 953 $output .= '</span>'."\n";
954
955 if (empty($return)) {
956 echo $output;
957 } else {
958 return $output;
959 }
960
961}
962
963
d48b00b4 964/**
fa583f5f 965 * Implements a complete little form with a dropdown menu. When JavaScript is on
966 * selecting an option from the dropdown automatically submits the form (while
967 * avoiding the usual acessibility problems with this appoach). With JavaScript
968 * off, a 'Go' button is printed.
d48b00b4 969 *
fa583f5f 970 * @param string $baseurl The target URL up to the point of the variable that changes
971 * @param array $options A list of value-label pairs for the popup list
972 * @param string $formid id for the control. Must be unique on the page. Used in the HTML.
973 * @param string $selected The option that is initially selected
89dcb99d 974 * @param string $nothing The label for the "no choice" option
975 * @param string $help The name of a help page if help is required
976 * @param string $helptext The name of the label for the help button
fa583f5f 977 * @param boolean $return Indicates whether the function should return the HTML
89dcb99d 978 * as a string or echo it directly to the page being rendered
772e78be 979 * @param string $targetwindow The name of the target page to open the linked page in.
1d75edd0 980 * @param string $selectlabel Text to place in a [label] element - preferred for accessibility.
fa583f5f 981 * @param array $optionsextra an array with the same keys as $options. The values are added within the corresponding <option ...> tag.
982 * @param string $submitvalue Optional label for the 'Go' button. Defaults to get_string('go').
983 * @param boolean $disabled If true, the menu will be displayed disabled.
ad70c470 984 * @param boolean $showbutton If true, the button will always be shown even if JavaScript is available
89dcb99d 985 * @return string If $return is true then the entire form is returned as a string.
986 * @todo Finish documenting this function<br>
89dcb99d 987 */
fa583f5f 988function popup_form($baseurl, $options, $formid, $selected='', $nothing='choose', $help='', $helptext='', $return=false,
ad70c470 989 $targetwindow='self', $selectlabel='', $optionsextra=NULL, $submitvalue='', $disabled=false, $showbutton=false) {
eee5d9bb 990 global $CFG, $SESSION;
b0542a1e 991 static $go, $choose; /// Locally cached, in case there's lots on a page
87180677 992
6f9f3b69 993 if (empty($options)) {
994 return '';
995 }
0d0baabf 996
fa583f5f 997 if (empty($submitvalue)){
998 if (!isset($go)) {
999 $go = get_string('go');
1000 $submitvalue=$go;
1001 }
037dcbb6 1002 }
b0ccd3fb 1003 if ($nothing == 'choose') {
037dcbb6 1004 if (!isset($choose)) {
1005 $choose = get_string('choose');
1006 }
1007 $nothing = $choose.'...';
618b22c5 1008 }
fa583f5f 1009 if ($disabled) {
3fb00221 1010 $disabled = ' disabled="disabled"';
fa583f5f 1011 } else {
1012 $disabled = '';
1013 }
618b22c5 1014
9d3c6ee5 1015 // changed reference to document.getElementById('id_abc') instead of document.abc
1016 // MDL-7861
4f24b3e3 1017 $output = '<form action="'.$CFG->wwwroot.'/course/jumpto.php"'.
fa738731 1018 ' method="get" '.
1019 $CFG->frametarget.
ee5567d1 1020 ' id="'.$formid.'"'.
c4d951e1 1021 ' class="popupform">';
4f24b3e3 1022 if ($help) {
1023 $button = helpbutton($help, $helptext, 'moodle', true, false, '', true);
1024 } else {
1025 $button = '';
1026 }
037dcbb6 1027
fcf9577a 1028 if ($selectlabel) {
1029 $selectlabel = '<label for="'.$formid.'_jump">'.$selectlabel.'</label>';
1030 }
1031
ad70c470 1032 if ($showbutton) {
1033 // Using the no-JavaScript version
1034 $javascript = '';
1035 } else if (check_browser_version('MSIE') || (check_browser_version('Opera') && !check_browser_operating_system("Linux"))) {
1036 //IE and Opera fire the onchange when ever you move into a dropdown list with the keyboard.
1037 //onfocus will call a function inside dropdown.js. It fixes this IE/Opera behavior.
1038 //Note: There is a bug on Opera+Linux with the javascript code (first mouse selection is inactive),
1039 //so we do not fix the Opera behavior on Linux
1040 $javascript = ' onfocus="initSelect(\''.$formid.'\','.$targetwindow.')"';
1041 } else {
1042 //Other browser
1043 $javascript = ' onchange="'.$targetwindow.
1044 '.location=document.getElementById(\''.$formid.
1045 '\').jump.options[document.getElementById(\''.
1046 $formid.'\').jump.selectedIndex].value;"';
795a08ad 1047 }
ad70c470 1048
3fb00221 1049 $output .= '<div style="white-space:nowrap">'.$selectlabel.$button.'<select id="'.$formid.'_jump" name="jump"'.$javascript.$disabled.'>'."\n";
73f7ad71 1050
b0ccd3fb 1051 if ($nothing != '') {
ffadf71b 1052 $selectlabeloption = '';
1053 if ($selected=='') {
1054 $selectlabeloption = ' selected="selected"';
1055 }
1056 foreach ($options as $value => $label) { //if one of the options is the empty value, don't make this the default
1057 if ($value == '') {
1058 $selected = '';
1059 }
1060 }
1061 $output .= " <option value=\"javascript:void(0)\"$selectlabeloption>$nothing</option>\n";
f9903ed0 1062 }
1063
72b4e283 1064 $inoptgroup = false;
89bfeee0 1065
f9903ed0 1066 foreach ($options as $value => $label) {
772e78be 1067
89bfeee0 1068 if ($label == '--') { /// we are ending previous optgroup
1069 /// Check to see if we already have a valid open optgroup
1070 /// XHTML demands that there be at least 1 option within an optgroup
1071 if ($inoptgroup and (count($optgr) > 1) ) {
1072 $output .= implode('', $optgr);
1073 $output .= ' </optgroup>';
1074 }
1075 $optgr = array();
1076 $inoptgroup = false;
1077 continue;
1078 } else if (substr($label,0,2) == '--') { /// we are starting a new optgroup
772e78be 1079
2a003a90 1080 /// Check to see if we already have a valid open optgroup
1081 /// XHTML demands that there be at least 1 option within an optgroup
1082 if ($inoptgroup and (count($optgr) > 1) ) {
1083 $output .= implode('', $optgr);
72b4e283 1084 $output .= ' </optgroup>';
72b4e283 1085 }
2a003a90 1086
1087 unset($optgr);
1088 $optgr = array();
1089
dacb47c0 1090 $optgr[] = ' <optgroup label="'. s(format_string(substr($label,2))) .'">'; // Plain labels
772e78be 1091
2a003a90 1092 $inoptgroup = true; /// everything following will be in an optgroup
3326450b 1093 continue;
772e78be 1094
d897cae4 1095 } else {
fd78420b 1096 if (!empty($CFG->usesid) && !isset($_COOKIE[session_name()]))
1097 {
fa583f5f 1098 $url = $SESSION->sid_process_url( $baseurl . $value );
fd78420b 1099 } else
1100 {
fa583f5f 1101 $url=$baseurl . $value;
fd78420b 1102 }
1103 $optstr = ' <option value="' . $url . '"';
772e78be 1104
d897cae4 1105 if ($value == $selected) {
2a003a90 1106 $optstr .= ' selected="selected"';
1107 }
772e78be 1108
b6b354e3 1109 if (!empty($optionsextra[$value])) {
1110 $optstr .= ' '.$optionsextra[$value];
1111 }
1112
2a003a90 1113 if ($label) {
1114 $optstr .= '>'. $label .'</option>' . "\n";
1115 } else {
1116 $optstr .= '>'. $value .'</option>' . "\n";
1117 }
772e78be 1118
2a003a90 1119 if ($inoptgroup) {
1120 $optgr[] = $optstr;
1121 } else {
1122 $output .= $optstr;
d897cae4 1123 }
f9903ed0 1124 }
772e78be 1125
f9903ed0 1126 }
2a003a90 1127
1128 /// catch the final group if not closed
1129 if ($inoptgroup and count($optgr) > 1) {
1130 $output .= implode('', $optgr);
72b4e283 1131 $output .= ' </optgroup>';
1132 }
2a003a90 1133
b0ccd3fb 1134 $output .= '</select>';
3435f39b 1135 $output .= '<input type="hidden" name="sesskey" value="'.sesskey().'" />';
ad70c470 1136 if (!$showbutton) {
1137 $output .= '<div id="noscript'.$formid.'" style="display: inline;">';
1138 }
fa583f5f 1139 $output .= '<input type="submit" value="'.$submitvalue.'" '.$disabled.' /></div>';
ad70c470 1140 if (!$showbutton) {
1141 $output .= '<script type="text/javascript">'.
1142 "\n//<![CDATA[\n".
1143 'document.getElementById("noscript'.$formid.'").style.display = "none";'.
1144 "\n//]]>\n".'</script>';
ad70c470 1145 }
9cef0c27 1146 $output .= '</div></form>';
d897cae4 1147
1148 if ($return) {
4f24b3e3 1149 return $output;
d897cae4 1150 } else {
4f24b3e3 1151 echo $output;
d897cae4 1152 }
f9903ed0 1153}
1154
1155
d48b00b4 1156/**
1157 * Prints some red text
1158 *
1159 * @param string $error The text to be displayed in red
1160 */
f9903ed0 1161function formerr($error) {
d48b00b4 1162
f9903ed0 1163 if (!empty($error)) {
7bc1c17f 1164 echo '<span class="error">'. $error .'</span>';
f9903ed0 1165 }
1166}
1167
d48b00b4 1168/**
1169 * Validates an email to make sure it makes sense.
1170 *
1171 * @param string $address The email address to validate.
1172 * @return boolean
1173 */
89dcb99d 1174function validate_email($address) {
d48b00b4 1175
78fbaeae 1176 return (ereg('^[-!#$%&\'*+\\/0-9=?A-Z^_`a-z{|}~]+'.
1177 '(\.[-!#$%&\'*+\\/0-9=?A-Z^_`a-z{|}~]+)*'.
f9903ed0 1178 '@'.
1179 '[-!#$%&\'*+\\/0-9=?A-Z^_`a-z{|}~]+\.'.
1180 '[-!#$%&\'*+\\./0-9=?A-Z^_`a-z{|}~]+$',
1181 $address));
1182}
1183
690f358b 1184/**
1185 * Extracts file argument either from file parameter or PATH_INFO
11e7b506 1186 * Note: $scriptname parameter is not needed anymore
690f358b 1187 *
690f358b 1188 * @return string file path (only safe characters)
1189 */
11e7b506 1190function get_file_argument() {
1191 global $SCRIPT;
690f358b 1192
690f358b 1193 $relativepath = optional_param('file', FALSE, PARAM_PATH);
1194
1195 // then try extract file from PATH_INFO (slasharguments method)
11e7b506 1196 if ($relativepath === false and isset($_SERVER['PATH_INFO']) and $_SERVER['PATH_INFO'] !== '') {
690f358b 1197 // check that PATH_INFO works == must not contain the script name
11e7b506 1198 if (strpos($_SERVER['PATH_INFO'], $SCRIPT) === false) {
1199 $relativepath = clean_param(urldecode($_SERVER['PATH_INFO']), PARAM_PATH);
690f358b 1200 }
1201 }
1202
11e7b506 1203 // note: we are not using any other way because they are not compatible with unicode file names ;-)
690f358b 1204
1205 return $relativepath;
1206}
1207
d48b00b4 1208/**
89dcb99d 1209 * Just returns an array of text formats suitable for a popup menu
d48b00b4 1210 *
89dcb99d 1211 * @uses FORMAT_MOODLE
1212 * @uses FORMAT_HTML
1213 * @uses FORMAT_PLAIN
89dcb99d 1214 * @uses FORMAT_MARKDOWN
1215 * @return array
d48b00b4 1216 */
0095d5cd 1217function format_text_menu() {
d48b00b4 1218
b0ccd3fb 1219 return array (FORMAT_MOODLE => get_string('formattext'),
1220 FORMAT_HTML => get_string('formathtml'),
1221 FORMAT_PLAIN => get_string('formatplain'),
b0ccd3fb 1222 FORMAT_MARKDOWN => get_string('formatmarkdown'));
0095d5cd 1223}
1224
d48b00b4 1225/**
1226 * Given text in a variety of format codings, this function returns
772e78be 1227 * the text as safe HTML.
d48b00b4 1228 *
c5659019 1229 * This function should mainly be used for long strings like posts,
e8276c10 1230 * answers, glossary items etc. For short strings @see format_string().
1231 *
d48b00b4 1232 * @uses $CFG
89dcb99d 1233 * @uses FORMAT_MOODLE
1234 * @uses FORMAT_HTML
1235 * @uses FORMAT_PLAIN
1236 * @uses FORMAT_WIKI
1237 * @uses FORMAT_MARKDOWN
1238 * @param string $text The text to be formatted. This is raw text originally from user input.
772e78be 1239 * @param int $format Identifier of the text format to be used
89dcb99d 1240 * (FORMAT_MOODLE, FORMAT_HTML, FORMAT_PLAIN, FORMAT_WIKI, FORMAT_MARKDOWN)
1241 * @param array $options ?
1242 * @param int $courseid ?
1243 * @return string
d48b00b4 1244 * @todo Finish documenting this function
1245 */
7d8a3cb0 1246function format_text($text, $format=FORMAT_MOODLE, $options=NULL, $courseid=NULL) {
e3e40b43 1247 global $CFG, $COURSE, $DB, $PAGE;
c4ae4fa1 1248
1cc54a45 1249 static $croncache = array();
795a08ad 1250
9e3f34d1 1251 $hashstr = '';
1cc54a45 1252
d53ca6ad 1253 if ($text === '') {
1254 return ''; // no need to do any filters and cleaning
1255 }
1256
cbc2b5df 1257 if (!isset($options->trusted)) {
1258 $options->trusted = false;
7d8a3cb0 1259 }
e7a47153 1260 if (!isset($options->noclean)) {
cbc2b5df 1261 if ($options->trusted and trusttext_active()) {
1262 // no cleaning if text trusted and noclean not specified
1263 $options->noclean=true;
1264 } else {
1265 $options->noclean=false;
1266 }
e7a47153 1267 }
a17c57b5 1268 if (!isset($options->nocache)) {
1269 $options->nocache=false;
1270 }
e7a47153 1271 if (!isset($options->smiley)) {
1272 $options->smiley=true;
1273 }
1274 if (!isset($options->filter)) {
1275 $options->filter=true;
1276 }
1277 if (!isset($options->para)) {
1278 $options->para=true;
1279 }
1280 if (!isset($options->newlines)) {
1281 $options->newlines=true;
f0aa2fed 1282 }
c4ae4fa1 1283 if (empty($courseid)) {
dcf6d93c 1284 $courseid = $COURSE->id;
c4ae4fa1 1285 }
a751a4e5 1286
ccc161f8 1287 if ($options->filter) {
1288 $filtermanager = filter_manager::instance();
1289 } else {
1290 $filtermanager = new null_filter_manager();
9e3f34d1 1291 }
e3e40b43 1292 $context = $PAGE->context;
ccc161f8 1293
a17c57b5 1294 if (!empty($CFG->cachetext) and empty($options->nocache)) {
ccc161f8 1295 $hashstr .= $text.'-'.$filtermanager->text_filtering_hash($context, $courseid).'-'.(int)$courseid.'-'.current_language().'-'.
cbc2b5df 1296 (int)$format.(int)$options->trusted.(int)$options->noclean.(int)$options->smiley.
ccc161f8 1297 (int)$options->filter.(int)$options->para.(int)$options->newlines;
1cc54a45 1298
9e3f34d1 1299 $time = time() - $CFG->cachetext;
795a08ad 1300 $md5key = md5($hashstr);
a91b910e 1301 if (CLI_SCRIPT) {
1cc54a45 1302 if (isset($croncache[$md5key])) {
1303 return $croncache[$md5key];
1304 }
1305 }
1306
f33e1ed4 1307 if ($oldcacheitem = $DB->get_record('cache_text', array('md5key'=>$md5key), '*', true)) {
a9743837 1308 if ($oldcacheitem->timemodified >= $time) {
a91b910e 1309 if (CLI_SCRIPT) {
1cc54a45 1310 if (count($croncache) > 150) {
5087c945 1311 reset($croncache);
1312 $key = key($croncache);
1313 unset($croncache[$key]);
1cc54a45 1314 }
1315 $croncache[$md5key] = $oldcacheitem->formattedtext;
1316 }
a9743837 1317 return $oldcacheitem->formattedtext;
1318 }
e7a47153 1319 }
1320 }
1321
0095d5cd 1322 switch ($format) {
73f8658c 1323 case FORMAT_HTML:
7d8a3cb0 1324 if ($options->smiley) {
e7a47153 1325 replace_smilies($text);
1326 }
7d8a3cb0 1327 if (!$options->noclean) {
5c6347ce 1328 $text = clean_text($text, FORMAT_HTML);
9d40806d 1329 }
ccc161f8 1330 $text = $filtermanager->filter_text($text, $context, $courseid);
73f8658c 1331 break;
1332
6901fa79 1333 case FORMAT_PLAIN:
5c6347ce 1334 $text = s($text); // cleans dangerous JS
ab892a4f 1335 $text = rebuildnolinktag($text);
b0ccd3fb 1336 $text = str_replace(' ', '&nbsp; ', $text);
6901fa79 1337 $text = nl2br($text);
6901fa79 1338 break;
1339
d342c763 1340 case FORMAT_WIKI:
6a6495ff 1341 // this format is deprecated
572fe9ab 1342 $text = '<p>NOTICE: Wiki-like formatting has been removed from Moodle. You should not be seeing
1343 this message as all texts should have been converted to Markdown format instead.
ce50cc70 1344 Please post a bug report to http://moodle.org/bugs with information about where you
e7a47153 1345 saw this message.</p>'.s($text);
d342c763 1346 break;
1347
e7cdcd18 1348 case FORMAT_MARKDOWN:
1349 $text = markdown_to_html($text);
7d8a3cb0 1350 if ($options->smiley) {
e7a47153 1351 replace_smilies($text);
1352 }
7d8a3cb0 1353 if (!$options->noclean) {
5c6347ce 1354 $text = clean_text($text, FORMAT_HTML);
9d40806d 1355 }
ccc161f8 1356 $text = $filtermanager->filter_text($text, $context, $courseid);
e7cdcd18 1357 break;
1358
73f8658c 1359 default: // FORMAT_MOODLE or anything else
b7a3d3b2 1360 $text = text_to_html($text, $options->smiley, $options->para, $options->newlines);
7d8a3cb0 1361 if (!$options->noclean) {
5c6347ce 1362 $text = clean_text($text, FORMAT_HTML);
9d40806d 1363 }
ccc161f8 1364 $text = $filtermanager->filter_text($text, $context, $courseid);
0095d5cd 1365 break;
0095d5cd 1366 }
f0aa2fed 1367
ccc161f8 1368 // Warn people that we have removed this old mechanism, just in case they
1369 // were stupid enough to rely on it.
1370 if (isset($CFG->currenttextiscacheable)) {
1371 debugging('Once upon a time, Moodle had a truly evil use of global variables ' .
1372 'called $CFG->currenttextiscacheable. The good news is that this no ' .
1373 'longer exists. The bad news is that you seem to be using a filter that '.
1374 'relies on it. Please seek out and destroy that filter code.', DEBUG_DEVELOPER);
1375 }
1376
1377 if (empty($options->nocache) and !empty($CFG->cachetext)) {
a91b910e 1378 if (CLI_SCRIPT) {
1cc54a45 1379 // special static cron cache - no need to store it in db if its not already there
1380 if (count($croncache) > 150) {
5087c945 1381 reset($croncache);
1382 $key = key($croncache);
1383 unset($croncache[$key]);
1cc54a45 1384 }
1385 $croncache[$md5key] = $text;
1386 return $text;
1387 }
1388
f47f4659 1389 $newcacheitem = new object();
a9743837 1390 $newcacheitem->md5key = $md5key;
f33e1ed4 1391 $newcacheitem->formattedtext = $text;
a9743837 1392 $newcacheitem->timemodified = time();
1393 if ($oldcacheitem) { // See bug 4677 for discussion
1394 $newcacheitem->id = $oldcacheitem->id;
f6949ddb 1395 try {
1396 $DB->update_record('cache_text', $newcacheitem); // Update existing record in the cache table
1397 } catch (dml_exception $e) {
1398 // It's unlikely that the cron cache cleaner could have
1399 // deleted this entry in the meantime, as it allows
1400 // some extra time to cover these cases.
1401 }
a9743837 1402 } else {
f6949ddb 1403 try {
1404 $DB->insert_record('cache_text', $newcacheitem); // Insert a new record in the cache table
1405 } catch (dml_exception $e) {
1406 // Again, it's possible that another user has caused this
1407 // record to be created already in the time that it took
1408 // to traverse this function. That's OK too, as the
1409 // call above handles duplicate entries, and eventually
1410 // the cron cleaner will delete them.
1411 }
a9743837 1412 }
f0aa2fed 1413 }
1414
1415 return $text;
0095d5cd 1416}
1417
4a28b5ca 1418/** Converts the text format from the value to the 'internal'
1419 * name or vice versa. $key can either be the value or the name
1420 * and you get the other back.
c06c8492 1421 *
4a28b5ca 1422 * @param mixed int 0-4 or string one of 'moodle','html','plain','markdown'
1423 * @return mixed as above but the other way around!
1424 */
1425function text_format_name( $key ) {
1426 $lookup = array();
1427 $lookup[FORMAT_MOODLE] = 'moodle';
1428 $lookup[FORMAT_HTML] = 'html';
1429 $lookup[FORMAT_PLAIN] = 'plain';
1430 $lookup[FORMAT_MARKDOWN] = 'markdown';
1431 $value = "error";
1432 if (!is_numeric($key)) {
1433 $key = strtolower( $key );
1434 $value = array_search( $key, $lookup );
1435 }
1436 else {
1437 if (isset( $lookup[$key] )) {
1438 $value = $lookup[ $key ];
1439 }
1440 }
1441 return $value;
1442}
1443
109e3cb2 1444/**
1445 * Resets all data related to filters, called during upgrade or when filter settings change.
1446 * @return void
1447 */
1448function reset_text_filters_cache() {
8618fd2a 1449 global $CFG, $DB;
109e3cb2 1450
8618fd2a 1451 $DB->delete_records('cache_text');
109e3cb2 1452 $purifdir = $CFG->dataroot.'/cache/htmlpurifier';
1453 remove_dir($purifdir, true);
1454}
473d29eb 1455
7b2c5e72 1456/** Given a simple string, this function returns the string
e8276c10 1457 * processed by enabled string filters if $CFG->filterall is enabled
1458 *
c5659019 1459 * This function should be used to print short strings (non html) that
1460 * need filter processing e.g. activity titles, post subjects,
e8276c10 1461 * glossary concepts.
7b2c5e72 1462 *
3e6691ee 1463 * @param string $string The string to be filtered.
fae83c8d 1464 * @param boolean $striplinks To strip any link in the result text (Moodle 1.8 default changed from false to true! MDL-8713)
3e6691ee 1465 * @param int $courseid Current course as filters can, potentially, use it
7b2c5e72 1466 * @return string
1467 */
ccc161f8 1468function format_string($string, $striplinks=true, $courseid=NULL ) {
e3e40b43 1469 global $CFG, $COURSE, $PAGE;
38701b69 1470
2a3affe9 1471 //We'll use a in-memory cache here to speed up repeated strings
473d29eb 1472 static $strcache = false;
1473
38701b69 1474 if ($strcache === false or count($strcache) > 2000 ) { // this number might need some tuning to limit memory usage in cron
473d29eb 1475 $strcache = array();
1476 }
84e3d2cc 1477
38701b69 1478 //init course id
a97e0ccb 1479 if (empty($courseid)) {
38701b69 1480 $courseid = $COURSE->id;
1481 }
1482
2a3affe9 1483 //Calculate md5
38701b69 1484 $md5 = md5($string.'<+>'.$striplinks.'<+>'.$courseid.'<+>'.current_language());
2a3affe9 1485
1486 //Fetch from cache if possible
38701b69 1487 if (isset($strcache[$md5])) {
2a3affe9 1488 return $strcache[$md5];
1489 }
1490
dacb47c0 1491 // First replace all ampersands not followed by html entity code
cb6a4f09 1492 $string = preg_replace("/\&(?![a-zA-Z0-9#]{1,8};)/", "&amp;", $string);
268ddd50 1493
14d20de1 1494 if (!empty($CFG->filterall) && $CFG->version >= 2009040600) { // Avoid errors during the upgrade to the new system.
e3e40b43 1495 $context = $PAGE->context;
ccc161f8 1496 $string = filter_manager::instance()->filter_string($string, $context, $courseid);
7b2c5e72 1497 }
84e3d2cc 1498
9fbed9c9 1499 // If the site requires it, strip ALL tags from this string
1500 if (!empty($CFG->formatstringstriptags)) {
1501 $string = strip_tags($string);
1502
408d5327 1503 } else {
1504 // Otherwise strip just links if that is required (default)
1505 if ($striplinks) { //strip links in string
1506 $string = preg_replace('/(<a\s[^>]+?>)(.+?)(<\/a>)/is','$2',$string);
1507 }
1508 $string = clean_text($string);
3e6691ee 1509 }
1510
2a3affe9 1511 //Store to cache
1512 $strcache[$md5] = $string;
84e3d2cc 1513
7b2c5e72 1514 return $string;
1515}
1516
d48b00b4 1517/**
1518 * Given text in a variety of format codings, this function returns
1519 * the text as plain text suitable for plain email.
d48b00b4 1520 *
89dcb99d 1521 * @uses FORMAT_MOODLE
1522 * @uses FORMAT_HTML
1523 * @uses FORMAT_PLAIN
1524 * @uses FORMAT_WIKI
1525 * @uses FORMAT_MARKDOWN
1526 * @param string $text The text to be formatted. This is raw text originally from user input.
772e78be 1527 * @param int $format Identifier of the text format to be used
89dcb99d 1528 * (FORMAT_MOODLE, FORMAT_HTML, FORMAT_PLAIN, FORMAT_WIKI, FORMAT_MARKDOWN)
1529 * @return string
d48b00b4 1530 */
d342c763 1531function format_text_email($text, $format) {
d342c763 1532
1533 switch ($format) {
1534
1535 case FORMAT_PLAIN:
1536 return $text;
1537 break;
1538
1539 case FORMAT_WIKI:
1540 $text = wiki_to_html($text);
5b472756 1541 /// This expression turns links into something nice in a text format. (Russell Jungwirth)
1542 /// From: http://php.net/manual/en/function.eregi-replace.php and simplified
76add072 1543 $text = eregi_replace('(<a [^<]*href=["|\']?([^ "\']*)["|\']?[^>]*>([^<]*)</a>)','\\3 [ \\2 ]', $text);
7c55a29b 1544 return strtr(strip_tags($text), array_flip(get_html_translation_table(HTML_ENTITIES)));
d342c763 1545 break;
1546
6ff45b59 1547 case FORMAT_HTML:
1548 return html_to_text($text);
1549 break;
1550
e7cdcd18 1551 case FORMAT_MOODLE:
1552 case FORMAT_MARKDOWN:
67ccec43 1553 default:
76add072 1554 $text = eregi_replace('(<a [^<]*href=["|\']?([^ "\']*)["|\']?[^>]*>([^<]*)</a>)','\\3 [ \\2 ]', $text);
7c55a29b 1555 return strtr(strip_tags($text), array_flip(get_html_translation_table(HTML_ENTITIES)));
d342c763 1556 break;
1557 }
1558}
0095d5cd 1559
d48b00b4 1560/**
1561 * Given some text in HTML format, this function will pass it
ccc161f8 1562 * through any filters that have been configured for this context.
d48b00b4 1563 *
89dcb99d 1564 * @param string $text The text to be passed through format filters
ccc161f8 1565 * @param int $courseid The current course.
1566 * @return string the filtered string.
d48b00b4 1567 */
c4ae4fa1 1568function filter_text($text, $courseid=NULL) {
e3e40b43 1569 global $CFG, $COURSE, $PAGE;
dcf6d93c 1570
1571 if (empty($courseid)) {
1572 $courseid = $COURSE->id; // (copied from format_text)
1573 }
e67b9e31 1574
e3e40b43 1575 $context = $PAGE->context;
9fbed9c9 1576
ccc161f8 1577 return filter_manager::instance()->filter_text($text, $context, $courseid);
cbdfb929 1578}
dc5c2bd9 1579/**
1580 * Formats activity intro text
1581 * @param string $module name of module
1582 * @param object $activity instance of activity
1583 * @param int $cmid course module id
43b44d5e 1584 * @param bool $filter filter resulting html text
dc5c2bd9 1585 * @return text
1586 */
43b44d5e 1587function format_module_intro($module, $activity, $cmid, $filter=true) {
ac3668bf 1588 global $CFG;
1589 require_once("$CFG->libdir/filelib.php");
43b44d5e 1590 $options = (object)array('noclean'=>true, 'para'=>false, 'filter'=>false);
dc5c2bd9 1591 $context = get_context_instance(CONTEXT_MODULE, $cmid);
7d2948bd 1592 $intro = file_rewrite_pluginfile_urls($activity->intro, 'pluginfile.php', $context->id, $module.'_intro', null);
ac3668bf 1593 return trim(format_text($intro, $activity->introformat, $options));
dc5c2bd9 1594}
cbdfb929 1595
7d8a3cb0 1596/**
cbc2b5df 1597 * Legacy function, used for cleaning of old forum and glossary text only.
5ce73257 1598 * @param string $text text that may contain TRUSTTEXT marker
7d8a3cb0 1599 * @return text without any TRUSTTEXT marker
1600 */
1601function trusttext_strip($text) {
1602 global $CFG;
1603
1604 while (true) { //removing nested TRUSTTEXT
5ce73257 1605 $orig = $text;
cbc2b5df 1606 $text = str_replace('#####TRUSTTEXT#####', '', $text);
7d8a3cb0 1607 if (strcmp($orig, $text) === 0) {
1608 return $text;
1609 }
1610 }
1611}
1612
cbc2b5df 1613/**
1614 * Must be called before editing of all texts
1615 * with trust flag. Removes all XSS nasties
1616 * from texts stored in database if needed.
1617 * @param object $object data object with xxx, xxxformat and xxxtrust fields
1618 * @param string $field name of text field
1619 * @param object $context active context
1620 * @return object updated $object
1621 */
1622function trusttext_pre_edit($object, $field, $context) {
1623 $trustfield = $field.'trust';
1624 $formatfield = $field.'format';
1625
1626 if (!$object->$trustfield or !trusttext_trusted($context)) {
1627 $object->$field = clean_text($object->$field, $object->$formatfield);
1628 }
1629
1630 return $object;
1631}
1632
1633/**
7467e721 1634 * Is urrent user trusted to enter no dangerous XSS in this context?
cbc2b5df 1635 * Please note the user must be in fact trusted everywhere on this server!!
1636 * @param $context
1637 * @return bool true if user trusted
1638 */
1639function trusttext_trusted($context) {
1640 return (trusttext_active() and has_capability('moodle/site:trustcontent', $context));
1641}
1642
1643/**
1644 * Is trusttext feature active?
1645 * @param $context
1646 * @return bool
1647 */
1648function trusttext_active() {
1649 global $CFG;
1650
1651 return !empty($CFG->enabletrusttext);
1652}
1653
d48b00b4 1654/**
1655 * Given raw text (eg typed in by a user), this function cleans it up
1656 * and removes any nasty tags that could mess up Moodle pages.
1657 *
89dcb99d 1658 * @uses FORMAT_MOODLE
1659 * @uses FORMAT_PLAIN
1660 * @uses ALLOWED_TAGS
1661 * @param string $text The text to be cleaned
772e78be 1662 * @param int $format Identifier of the text format to be used
89dcb99d 1663 * (FORMAT_MOODLE, FORMAT_HTML, FORMAT_PLAIN, FORMAT_WIKI, FORMAT_MARKDOWN)
1664 * @return string The cleaned up text
d48b00b4 1665 */
3da47524 1666function clean_text($text, $format=FORMAT_MOODLE) {
b7a3cf49 1667
85fbf884 1668 global $ALLOWED_TAGS, $CFG;
1669
e0ac8448 1670 if (empty($text) or is_numeric($text)) {
84e3d2cc 1671 return (string)$text;
e0ac8448 1672 }
3fe3851d 1673
ab9f24ad 1674 switch ($format) {
e7cdcd18 1675 case FORMAT_PLAIN:
8f660562 1676 case FORMAT_MARKDOWN:
e7cdcd18 1677 return $text;
1678
1679 default:
1680
e0ac8448 1681 if (!empty($CFG->enablehtmlpurifier)) {
1682 $text = purify_html($text);
1683 } else {
1684 /// Fix non standard entity notations
1685 $text = preg_replace('/(&#[0-9]+)(;?)/', "\\1;", $text);
1686 $text = preg_replace('/(&#x[0-9a-fA-F]+)(;?)/', "\\1;", $text);
84e3d2cc 1687
e0ac8448 1688 /// Remove tags that are not allowed
1689 $text = strip_tags($text, $ALLOWED_TAGS);
84e3d2cc 1690
e0ac8448 1691 /// Clean up embedded scripts and , using kses
1692 $text = cleanAttributes($text);
a33c44c4 1693
1694 /// Again remove tags that are not allowed
1695 $text = strip_tags($text, $ALLOWED_TAGS);
1696
e0ac8448 1697 }
7789ffbf 1698
e0ac8448 1699 /// Remove potential script events - some extra protection for undiscovered bugs in our code
ab9f24ad 1700 $text = eregi_replace("([^a-z])language([[:space:]]*)=", "\\1Xlanguage=", $text);
1701 $text = eregi_replace("([^a-z])on([a-z]+)([[:space:]]*)=", "\\1Xon\\2=", $text);
6901fa79 1702
6901fa79 1703 return $text;
0095d5cd 1704 }
b7a3cf49 1705}
f9903ed0 1706
e0ac8448 1707/**
1708 * KSES replacement cleaning function - uses HTML Purifier.
1709 */
1710function purify_html($text) {
1711 global $CFG;
1712
109e3cb2 1713 // this can not be done only once because we sometimes need to reset the cache
eb203ee4 1714 $cachedir = $CFG->dataroot.'/cache/htmlpurifier';
109e3cb2 1715 $status = check_dir_exists($cachedir, true, true);
1716
e0ac8448 1717 static $purifier = false;
eb203ee4 1718 static $config;
109e3cb2 1719 if ($purifier === false) {
eb203ee4 1720 require_once $CFG->libdir.'/htmlpurifier/HTMLPurifier.safe-includes.php';
e0ac8448 1721 $config = HTMLPurifier_Config::createDefault();
eb203ee4 1722 $config->set('Core', 'ConvertDocumentToFragment', true);
5adad310 1723 $config->set('Core', 'Encoding', 'UTF-8');
1724 $config->set('HTML', 'Doctype', 'XHTML 1.0 Transitional');
109e3cb2 1725 $config->set('Cache', 'SerializerPath', $cachedir);
e0ac8448 1726 $config->set('URI', 'AllowedSchemes', array('http'=>1, 'https'=>1, 'ftp'=>1, 'irc'=>1, 'nntp'=>1, 'news'=>1, 'rtsp'=>1, 'teamspeak'=>1, 'gopher'=>1, 'mms'=>1));
3c24a391 1727 $config->set('Attr', 'AllowedFrameTargets', array('_blank'));
e0ac8448 1728 $purifier = new HTMLPurifier($config);
1729 }
1730 return $purifier->purify($text);
1731}
1732
d48b00b4 1733/**
89dcb99d 1734 * This function takes a string and examines it for HTML tags.
d48b00b4 1735 * If tags are detected it passes the string to a helper function {@link cleanAttributes2()}
1736 * which checks for attributes and filters them for malicious content
1737 * 17/08/2004 :: Eamon DOT Costello AT dcu DOT ie
1738 *
1739 * @param string $str The string to be examined for html tags
1740 * @return string
1741 */
3bd7ffec 1742function cleanAttributes($str){
4e8f2e6b 1743 $result = preg_replace_callback(
1744 '%(<[^>]*(>|$)|>)%m', #search for html tags
1745 "cleanAttributes2",
3bd7ffec 1746 $str
67ccec43 1747 );
3bd7ffec 1748 return $result;
67ccec43 1749}
1750
d48b00b4 1751/**
1752 * This function takes a string with an html tag and strips out any unallowed
1753 * protocols e.g. javascript:
1754 * It calls ancillary functions in kses which are prefixed by kses
1755* 17/08/2004 :: Eamon DOT Costello AT dcu DOT ie
1756 *
4e8f2e6b 1757 * @param array $htmlArray An array from {@link cleanAttributes()}, containing in its 1st
1758 * element the html to be cleared
d48b00b4 1759 * @return string
1760 */
4e8f2e6b 1761function cleanAttributes2($htmlArray){
3bd7ffec 1762
037dcbb6 1763 global $CFG, $ALLOWED_PROTOCOLS;
b0ccd3fb 1764 require_once($CFG->libdir .'/kses.php');
3bd7ffec 1765
4e8f2e6b 1766 $htmlTag = $htmlArray[1];
037dcbb6 1767 if (substr($htmlTag, 0, 1) != '<') {
3bd7ffec 1768 return '&gt;'; //a single character ">" detected
1769 }
037dcbb6 1770 if (!preg_match('%^<\s*(/\s*)?([a-zA-Z0-9]+)([^>]*)>?$%', $htmlTag, $matches)) {
67ccec43 1771 return ''; // It's seriously malformed
1772 }
3bd7ffec 1773 $slash = trim($matches[1]); //trailing xhtml slash
67ccec43 1774 $elem = $matches[2]; //the element name
3bd7ffec 1775 $attrlist = $matches[3]; // the list of attributes as a string
1776
037dcbb6 1777 $attrArray = kses_hair($attrlist, $ALLOWED_PROTOCOLS);
3bd7ffec 1778
67ccec43 1779 $attStr = '';
037dcbb6 1780 foreach ($attrArray as $arreach) {
29939bea 1781 $arreach['name'] = strtolower($arreach['name']);
1782 if ($arreach['name'] == 'style') {
1783 $value = $arreach['value'];
1784 while (true) {
1785 $prevvalue = $value;
1786 $value = kses_no_null($value);
1787 $value = preg_replace("/\/\*.*\*\//Us", '', $value);
1788 $value = kses_decode_entities($value);
1789 $value = preg_replace('/(&#[0-9]+)(;?)/', "\\1;", $value);
1790 $value = preg_replace('/(&#x[0-9a-fA-F]+)(;?)/', "\\1;", $value);
1791 if ($value === $prevvalue) {
1792 $arreach['value'] = $value;
1793 break;
1794 }
1795 }
1796 $arreach['value'] = preg_replace("/j\s*a\s*v\s*a\s*s\s*c\s*r\s*i\s*p\s*t/i", "Xjavascript", $arreach['value']);
1797 $arreach['value'] = preg_replace("/e\s*x\s*p\s*r\s*e\s*s\s*s\s*i\s*o\s*n/i", "Xexpression", $arreach['value']);
8cd2314b 1798 $arreach['value'] = preg_replace("/b\s*i\s*n\s*d\s*i\s*n\s*g/i", "Xbinding", $arreach['value']);
b8806ccc 1799 } else if ($arreach['name'] == 'href') {
ee7f231d 1800 //Adobe Acrobat Reader XSS protection
920337d1 1801 $arreach['value'] = preg_replace('/(\.(pdf|fdf|xfdf|xdp|xfd)[^#]*)#.*$/i', '$1', $arreach['value']);
29939bea 1802 }
049bd7db 1803 $attStr .= ' '.$arreach['name'].'="'.$arreach['value'].'"';
3bd7ffec 1804 }
713126cd 1805
3bd7ffec 1806 $xhtml_slash = '';
037dcbb6 1807 if (preg_match('%/\s*$%', $attrlist)) {
67ccec43 1808 $xhtml_slash = ' /';
3bd7ffec 1809 }
b0ccd3fb 1810 return '<'. $slash . $elem . $attStr . $xhtml_slash .'>';
3bd7ffec 1811}
1812
d48b00b4 1813/**
1814 * Replaces all known smileys in the text with image equivalents
1815 *
1816 * @uses $CFG
1817 * @param string $text Passed by reference. The string to search for smily strings.
1818 * @return string
1819 */
5f350e8f 1820function replace_smilies(&$text) {
183a13c2 1821
2ea9027b 1822 global $CFG;
183a13c2 1823
1824 if (empty($CFG->emoticons)) { /// No emoticons defined, nothing to process here
1825 return;
1826 }
1827
5a144b3a 1828 $lang = current_language();
93c61c18 1829 $emoticonstring = $CFG->emoticons;
69081931 1830 static $e = array();
1831 static $img = array();
93c61c18 1832 static $emoticons = null;
1833
1834 if (is_null($emoticons)) {
1835 $emoticons = array();
1836 if ($emoticonstring) {
1837 $items = explode('{;}', $CFG->emoticons);
1838 foreach ($items as $item) {
1839 $item = explode('{:}', $item);
c5659019 1840 $emoticons[$item[0]] = $item[1];
93c61c18 1841 }
1842 }
1843 }
1844
5a144b3a 1845 if (empty($img[$lang])) { /// After the first time this is not run again
1846 $e[$lang] = array();
1847 $img[$lang] = array();
617778f2 1848 foreach ($emoticons as $emoticon => $image){
fbfc2675 1849 $alttext = get_string($image, 'pix');
4bfa414f 1850 $alttext = preg_replace('/^\[\[(.*)\]\]$/', '$1', $alttext); /// Clean alttext in case there isn't lang string for it.
5a144b3a 1851 $e[$lang][] = $emoticon;
1852 $img[$lang][] = '<img alt="'. $alttext .'" width="15" height="15" src="'. $CFG->pixpath .'/s/'. $image .'.gif" />';
617778f2 1853 }
c0f728ba 1854 }
b7a3cf49 1855
8dcd43f3 1856 // Exclude from transformations all the code inside <script> tags
1857 // Needed to solve Bug 1185. Thanks to jouse 2001 detecting it. :-)
1858 // Based on code from glossary fiter by Williams Castillo.
1859 // - Eloy
1860
1861 // Detect all the <script> zones to take out
1862 $excludes = array();
1863 preg_match_all('/<script language(.+?)<\/script>/is',$text,$list_of_excludes);
1864
1865 // Take out all the <script> zones from text
1866 foreach (array_unique($list_of_excludes[0]) as $key=>$value) {
1867 $excludes['<+'.$key.'+>'] = $value;
1868 }
1869 if ($excludes) {
1870 $text = str_replace($excludes,array_keys($excludes),$text);
1871 }
1872
fbfc2675 1873/// this is the meat of the code - this is run every time
5a144b3a 1874 $text = str_replace($e[$lang], $img[$lang], $text);
8dcd43f3 1875
1876 // Recover all the <script> zones to text
1877 if ($excludes) {
1878 $text = str_replace(array_keys($excludes),$excludes,$text);
1879 }
1a072208 1880}
0095d5cd 1881
740939ec 1882/**
1883 * This code is called from help.php to inject a list of smilies into the
1884 * emoticons help file.
1885 *
1886 * @return string HTML for a list of smilies.
1887 */
1888function get_emoticons_list_for_help_file(){
1889 global $CFG, $SESSION;
1890 if (empty($CFG->emoticons)) {
1891 return '';
1892 }
1893
1894 require_js(array('yui_yahoo', 'yui_event'));
1895 $items = explode('{;}', $CFG->emoticons);
1896 $output = '<ul id="emoticonlist">';
1897 foreach ($items as $item) {
1898 $item = explode('{:}', $item);
1899 $output .= '<li><img src="' . $CFG->pixpath.'/s/' . $item[1] . '.gif" alt="' .
1900 $item[0] . '" /><code>' . $item[0] . '</code></li>';
1901 }
1902 $output .= '</ul>';
1903 if (!empty($SESSION->inserttextform)) {
1904 $formname = $SESSION->inserttextform;
1905 $fieldname = $SESSION->inserttextfield;
1906 } else {
1907 $formname = 'theform';
1908 $fieldname = 'message';
1909 }
fa583f5f 1910
740939ec 1911 $output .= print_js_call('emoticons_help.init', array($formname, $fieldname, 'emoticonlist'), true);
1912 return $output;
1913
1914}
1915
89dcb99d 1916/**
1917 * Given plain text, makes it into HTML as nicely as possible.
1918 * May contain HTML tags already
1919 *
1920 * @uses $CFG
1921 * @param string $text The string to convert.
1922 * @param boolean $smiley Convert any smiley characters to smiley images?
1923 * @param boolean $para If true then the returned string will be wrapped in paragraph tags
1924 * @param boolean $newlines If true then lines newline breaks will be converted to HTML newline breaks.
1925 * @return string
1926 */
1927
b7a3d3b2 1928function text_to_html($text, $smiley=true, $para=true, $newlines=true) {
772e78be 1929///
f9903ed0 1930
27326a3e 1931 global $CFG;
1932
c1d57101 1933/// Remove any whitespace that may be between HTML tags
7b3be1b1 1934 $text = eregi_replace(">([[:space:]]+)<", "><", $text);
1935
c1d57101 1936/// Remove any returns that precede or follow HTML tags
0eae8049 1937 $text = eregi_replace("([\n\r])<", " <", $text);
1938 $text = eregi_replace(">([\n\r])", "> ", $text);
7b3be1b1 1939
5f350e8f 1940 convert_urls_into_links($text);
f9903ed0 1941
c1d57101 1942/// Make returns into HTML newlines.
b7a3d3b2 1943 if ($newlines) {
1944 $text = nl2br($text);
1945 }
f9903ed0 1946
c1d57101 1947/// Turn smileys into images.
d69cb7f4 1948 if ($smiley) {
5f350e8f 1949 replace_smilies($text);
d69cb7f4 1950 }
f9903ed0 1951
c1d57101 1952/// Wrap the whole thing in a paragraph tag if required
909f539d 1953 if ($para) {
b0ccd3fb 1954 return '<p>'.$text.'</p>';
909f539d 1955 } else {
1956 return $text;
1957 }
f9903ed0 1958}
1959
d48b00b4 1960/**
1961 * Given Markdown formatted text, make it into XHTML using external function
1962 *
89dcb99d 1963 * @uses $CFG
1964 * @param string $text The markdown formatted text to be converted.
1965 * @return string Converted text
d48b00b4 1966 */
e7cdcd18 1967function markdown_to_html($text) {
e7cdcd18 1968 global $CFG;
1969
b0ccd3fb 1970 require_once($CFG->libdir .'/markdown.php');
e7cdcd18 1971
1972 return Markdown($text);
1973}
1974
d48b00b4 1975/**
89dcb99d 1976 * Given HTML text, make it into plain text using external function
d48b00b4 1977 *
1978 * @uses $CFG
1979 * @param string $html The text to be converted.
1980 * @return string
1981 */
6ff45b59 1982function html_to_text($html) {
89dcb99d 1983
428aaa29 1984 global $CFG;
6ff45b59 1985
b0ccd3fb 1986 require_once($CFG->libdir .'/html2text.php');
6ff45b59 1987
588acd06 1988 $h2t = new html2text($html);
1989 $result = $h2t->get_text();
07e9a300 1990
588acd06 1991 // html2text does not fix HTML entities so handle those here.
4e42a90c 1992 $result = trim(html_entity_decode($result, ENT_NOQUOTES, 'UTF-8'));
07e9a300 1993
977b3d31 1994 return $result;
6ff45b59 1995}
1996
d48b00b4 1997/**
1998 * Given some text this function converts any URLs it finds into HTML links
1999 *
2000 * @param string $text Passed in by reference. The string to be searched for urls.
2001 */
5f350e8f 2002function convert_urls_into_links(&$text) {
5f350e8f 2003/// Make lone URLs into links. eg http://moodle.com/
3405b212 2004 $text = eregi_replace("([[:space:]]|^|\(|\[)([[:alnum:]]+)://([^[:space:]]*)([[:alnum:]#?/&=])",
bc01a2b8 2005 "\\1<a href=\"\\2://\\3\\4\" target=\"_blank\">\\2://\\3\\4</a>", $text);
5f350e8f 2006
2007/// eg www.moodle.com
ab9f24ad 2008 $text = eregi_replace("([[:space:]]|^|\(|\[)www\.([^[:space:]]*)([[:alnum:]#?/&=])",
bc01a2b8 2009 "\\1<a href=\"http://www.\\2\\3\" target=\"_blank\">www.\\2\\3</a>", $text);
5f350e8f 2010}
2011
d48b00b4 2012/**
2013 * This function will highlight search words in a given string
2014 * It cares about HTML and will not ruin links. It's best to use
2015 * this function after performing any conversions to HTML.
d48b00b4 2016 *
9289e4c9 2017 * @param string $needle The search string. Syntax like "word1 +word2 -word3" is dealt with correctly.
2018 * @param string $haystack The string (HTML) within which to highlight the search terms.
2019 * @param boolean $matchcase whether to do case-sensitive. Default case-insensitive.
2020 * @param string $prefix the string to put before each search term found.
2021 * @param string $suffix the string to put after each search term found.
2022 * @return string The highlighted HTML.
d48b00b4 2023 */
9289e4c9 2024function highlight($needle, $haystack, $matchcase = false,
2025 $prefix = '<span class="highlight">', $suffix = '</span>') {
587c7040 2026
9289e4c9 2027/// Quick bail-out in trivial cases.
587c7040 2028 if (empty($needle) or empty($haystack)) {
69d51d3a 2029 return $haystack;
2030 }
2031
9289e4c9 2032/// Break up the search term into words, discard any -words and build a regexp.
2033 $words = preg_split('/ +/', trim($needle));
2034 foreach ($words as $index => $word) {
2035 if (strpos($word, '-') === 0) {
2036 unset($words[$index]);
2037 } else if (strpos($word, '+') === 0) {
2038 $words[$index] = '\b' . preg_quote(ltrim($word, '+'), '/') . '\b'; // Match only as a complete word.
2039 } else {
2040 $words[$index] = preg_quote($word, '/');
88438a58 2041 }
2042 }
9289e4c9 2043 $regexp = '/(' . implode('|', $words) . ')/u'; // u is do UTF-8 matching.
2044 if (!$matchcase) {
2045 $regexp .= 'i';
88438a58 2046 }
2047
9289e4c9 2048/// Another chance to bail-out if $search was only -words
2049 if (empty($words)) {
2050 return $haystack;
88438a58 2051 }
88438a58 2052
9289e4c9 2053/// Find all the HTML tags in the input, and store them in a placeholders array.
2054 $placeholders = array();
2055 $matches = array();
2056 preg_match_all('/<[^>]*>/', $haystack, $matches);
2057 foreach (array_unique($matches[0]) as $key => $htmltag) {
2058 $placeholders['<|' . $key . '|>'] = $htmltag;
2059 }
9ccdcd97 2060
9289e4c9 2061/// In $hastack, replace each HTML tag with the corresponding placeholder.
2062 $haystack = str_replace($placeholders, array_keys($placeholders), $haystack);
9ccdcd97 2063
9289e4c9 2064/// In the resulting string, Do the highlighting.
2065 $haystack = preg_replace($regexp, $prefix . '$1' . $suffix, $haystack);
9ccdcd97 2066
9289e4c9 2067/// Turn the placeholders back into HTML tags.
2068 $haystack = str_replace(array_keys($placeholders), $placeholders, $haystack);
88438a58 2069
f60e7cfe 2070 return $haystack;
88438a58 2071}
2072
d48b00b4 2073/**
2074 * This function will highlight instances of $needle in $haystack
2075 * It's faster that the above function and doesn't care about
2076 * HTML or anything.
2077 *
2078 * @param string $needle The string to search for
2079 * @param string $haystack The string to search for $needle in
2080 * @return string
2081 */
88438a58 2082function highlightfast($needle, $haystack) {
5af78ed2 2083
587c7040 2084 if (empty($needle) or empty($haystack)) {
2085 return $haystack;
2086 }
2087
57f1b914 2088 $parts = explode(moodle_strtolower($needle), moodle_strtolower($haystack));
5af78ed2 2089
587c7040 2090 if (count($parts) === 1) {
2091 return $haystack;
2092 }
2093
5af78ed2 2094 $pos = 0;
2095
2096 foreach ($parts as $key => $part) {
2097 $parts[$key] = substr($haystack, $pos, strlen($part));
2098 $pos += strlen($part);
2099
b0ccd3fb 2100 $parts[$key] .= '<span class="highlight">'.substr($haystack, $pos, strlen($needle)).'</span>';
5af78ed2 2101 $pos += strlen($needle);
ab9f24ad 2102 }
5af78ed2 2103
587c7040 2104 return str_replace('<span class="highlight"></span>', '', join('', $parts));
5af78ed2 2105}
2106
2ab4e4b8 2107/**
2108 * Return a string containing 'lang', xml:lang and optionally 'dir' HTML attributes.
2109 * Internationalisation, for print_header and backup/restorelib.
2110 * @param $dir Default false.
2111 * @return string Attributes.
2112 */
2113function get_html_lang($dir = false) {
2114 $direction = '';
2115 if ($dir) {
2116 if (get_string('thisdirection') == 'rtl') {
2117 $direction = ' dir="rtl"';
2118 } else {
2119 $direction = ' dir="ltr"';
2120 }
2121 }
2122 //Accessibility: added the 'lang' attribute to $direction, used in theme <html> tag.
2123 $language = str_replace('_', '-', str_replace('_utf8', '', current_language()));
0946fff4 2124 @header('Content-Language: '.$language);
84e3d2cc 2125 return ($direction.' lang="'.$language.'" xml:lang="'.$language.'"');
2ab4e4b8 2126}
2127
5c355019 2128/**
2129 * Return the markup for the destination of the 'Skip to main content' links.
317d5ddc 2130 * Accessibility improvement for keyboard-only users.
2131 * Used in course formats, /index.php and /course/index.php
2132 * @return string HTML element.
5c355019 2133 */
2134function skip_main_destination() {
2135 return '<span id="maincontent"></span>';
2136}
2137
f9903ed0 2138
9fa49e22 2139/// STANDARD WEB PAGE PARTS ///////////////////////////////////////////////////
2140
d48b00b4 2141/**
2142 * Print a standard header
2143 *
89dcb99d 2144 * @uses $USER
2145 * @uses $CFG
89dcb99d 2146 * @uses $SESSION
f1af7aaa 2147 * @param string $title Appears at the top of the window
2148 * @param string $heading Appears at the top of the page
2149 * @param array $navigation Array of $navlinks arrays (keys: name, link, type) for use as breadcrumbs links
2150 * @param string $focus Indicates form element to get cursor focus on load eg inputform.password
2151 * @param string $meta Meta tags to be added to the header
89dcb99d 2152 * @param boolean $cache Should this page be cacheable?
f1af7aaa 2153 * @param string $button HTML code for a button (usually for module editing)
2154 * @param string $menu HTML code for a popup menu
89dcb99d 2155 * @param boolean $usexml use XML for this page
f1af7aaa 2156 * @param string $bodytags This text will be included verbatim in the <body> tag (useful for onload() etc)
2157 * @param bool $return If true, return the visible elements of the header instead of echoing them.
d48b00b4 2158 */
36b6bcec 2159function print_header ($title='', $heading='', $navigation='', $focus='',
2160 $meta='', $cache=true, $button='&nbsp;', $menu='',
2161 $usexml=false, $bodytags='', $return=false) {
63f3cbbd 2162
c13a5e71 2163 global $USER, $CFG, $THEME, $SESSION, $ME, $SITE, $COURSE, $PAGE;
84e3d2cc 2164
432038e0 2165 if (gettype($navigation) == 'string' && strlen($navigation) != 0 && $navigation != 'home') {
364fffda 2166 debugging("print_header() was sent a string as 3rd ($navigation) parameter. "
8ebb324b 2167 . "This is deprecated in favour of an array built by build_navigation(). Please upgrade your code.", DEBUG_DEVELOPER);
364fffda 2168 }
2169
c13a5e71 2170 $PAGE->set_state(moodle_page::STATE_PRINTING_HEADER);
2171
6ba65fa0 2172 $heading = format_string($heading); // Fix for MDL-8582
84e3d2cc 2173
fbd0c5e3 2174 if (CLI_SCRIPT) {
2f13f94c 2175 $output = $heading;
2176 if ($return) {
2177 return $output;
2178 } else {
27bd819b 2179 console_write($output . "\n",'',false);
2f13f94c 2180 return;
2181 }
2182 }
2183
c3f55692 2184/// Add the required stylesheets
d74d4f20 2185 $stylesheetshtml = '';
2186 foreach ($CFG->stylesheets as $stylesheet) {
2187 $stylesheetshtml .= '<link rel="stylesheet" type="text/css" href="'.$stylesheet.'" />'."\n";
c3f55692 2188 }
d74d4f20 2189 $meta = $stylesheetshtml.$meta;
e89fb61e 2190
84e3d2cc 2191
79f533c3 2192/// Add the meta page from the themes if any were requested
2193
2194 $metapage = '';
2195
2196 if (!isset($THEME->standardmetainclude) || $THEME->standardmetainclude) {
2197 ob_start();
2198 include_once($CFG->dirroot.'/theme/standard/meta.php');
2199 $metapage .= ob_get_contents();
2200 ob_end_clean();
2201 }
2202
2203 if ($THEME->parent && (!isset($THEME->parentmetainclude) || $THEME->parentmetainclude)) {
36e8c122 2204 if (file_exists($CFG->dirroot.'/theme/'.$THEME->parent.'/meta.php')) {
2205 ob_start();
2206 include_once($CFG->dirroot.'/theme/'.$THEME->parent.'/meta.php');
2207 $metapage .= ob_get_contents();
2208 ob_end_clean();
2209 }
79f533c3 2210 }
2211
2212 if (!isset($THEME->metainclude) || $THEME->metainclude) {
36e8c122 2213 if (file_exists($CFG->dirroot.'/theme/'.current_theme().'/meta.php')) {
2214 ob_start();
2215 include_once($CFG->dirroot.'/theme/'.current_theme().'/meta.php');
2216 $metapage .= ob_get_contents();
2217 ob_end_clean();
2218 }
79f533c3 2219 }
2220
2221 $meta = $meta."\n".$metapage;
2222
ca70075a 2223 $meta .= "\n".require_js('',1);
c77f9f07 2224
830c58b7 2225 $meta .= standard_js_config();
2226
c77f9f07 2227/// Set up some navigation variables
604c6341 2228
c77f9f07 2229 if (is_newnav($navigation)){
9d378732 2230 $home = false;
ac4feb59 2231 } else {
2232 if ($navigation == 'home') {
2233 $home = true;
2234 $navigation = '';
2235 } else {
2236 $home = false;
2237 }
9fa49e22 2238 }
2239
0d741155 2240/// This is another ugly hack to make navigation elements available to print_footer later
2241 $THEME->title = $title;
2242 $THEME->heading = $heading;
2243 $THEME->navigation = $navigation;
2244 $THEME->button = $button;
2245 $THEME->menu = $menu;
2507b2f5 2246 $navmenulist = isset($THEME->navmenulist) ? $THEME->navmenulist : '';
0d741155 2247
b0ccd3fb 2248 if ($button == '') {
2249 $button = '&nbsp;';
9fa49e22 2250 }
2251
a2353e9b 2252 if (file_exists($CFG->dataroot.'/'.SITEID.'/maintenance.html')) {
d1aa1e48 2253 $button = '<a href="'.$CFG->wwwroot.'/'.$CFG->admin.'/maintenance.php">'.get_string('maintenancemode', 'admin').'</a> '.$button;
a2353e9b 2254 if(!empty($title)) {
2255 $title .= ' - ';
2256 }
2257 $title .= get_string('maintenancemode', 'admin');
2258 }
2259
9fa49e22 2260 if (!$menu and $navigation) {
8a33e371 2261 if (empty($CFG->loginhttps)) {
2262 $wwwroot = $CFG->wwwroot;
2263 } else {
2c3432e6 2264 $wwwroot = str_replace('http:','https:',$CFG->wwwroot);
8a33e371 2265 }
60f9e36e 2266 $menu = user_login_string($COURSE);
9fa49e22 2267 }
67ccec43 2268
b4bac9b6 2269 if (isset($SESSION->justloggedin)) {
2270 unset($SESSION->justloggedin);
2271 if (!empty($CFG->displayloginfailures)) {
8f8ed475 2272 if (!empty($USER->username) and $USER->username != 'guest') {
b4bac9b6 2273 if ($count = count_login_failures($CFG->displayloginfailures, $USER->username, $USER->lastlogin)) {
2274 $menu .= '&nbsp;<font size="1">';
2275 if (empty($count->accounts)) {
2276 $menu .= get_string('failedloginattempts', '', $count);
2277 } else {
2278 $menu .= get_string('failedloginattemptsall', '', $count);
2279 }
a2e4bf7f 2280 if (has_capability('coursereport/log:view', get_context_instance(CONTEXT_SYSTEM))) {
52af9a35 2281 $menu .= ' (<a href="'.$CFG->wwwroot.'/course/report/log/index.php'.
839f2456 2282 '?chooselog=1&amp;id=1&amp;modid=site_errors">'.get_string('logs').'</a>)';
b4bac9b6 2283 }
2284 $menu .= '</font>';
2285 }
2286 }
2287 }
2288 }
9fa49e22 2289
47037513 2290
bc1bbaf4 2291 $meta = '<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />' .
c6f9234c 2292 "\n" . $meta . "\n";
03fe48e7 2293 if (!$usexml) {
bc1bbaf4 2294 @header('Content-Type: text/html; charset=utf-8');
03fe48e7 2295 }
bc1bbaf4 2296 @header('Content-Script-Type: text/javascript');
2297 @header('Content-Style-Type: text/css');
9fa49e22 2298
6575bfd4 2299 //Accessibility: added the 'lang' attribute to $direction, used in theme <html> tag.
2ab4e4b8 2300 $direction = get_html_lang($dir=true);
ab9f24ad 2301
5debee2d 2302 if ($cache) { // Allow caching on "back" (but not on normal clicks)
2303 @header('Cache-Control: private, pre-check=0, post-check=0, max-age=0');
2304 @header('Pragma: no-cache');
772e78be 2305 @header('Expires: ');
5debee2d 2306 } else { // Do everything we can to always prevent clients and proxies caching
03fe48e7 2307 @header('Cache-Control: no-store, no-cache, must-revalidate');
2308 @header('Cache-Control: post-check=0, pre-check=0', false);
2309 @header('Pragma: no-cache');
5debee2d 2310 @header('Expires: Mon, 20 Aug 1969 09:23:00 GMT');
2311 @header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
03fe48e7 2312
5debee2d 2313 $meta .= "\n<meta http-equiv=\"pragma\" content=\"no-cache\" />";
2314 $meta .= "\n<meta http-equiv=\"expires\" content=\"0\" />";
66a51452 2315 }
5debee2d 2316 @header('Accept-Ranges: none');
66a51452 2317
b0b4ffe1 2318 $currentlanguage = current_language();
2319
5ce73257 2320 if (empty($usexml)) {
27f79fda 2321 $direction = ' xmlns="http://www.w3.org/1999/xhtml"'. $direction; // See debug_header
2322 } else {
8f0cd6ef 2323 $mathplayer = preg_match("/MathPlayer/i", $_SERVER['HTTP_USER_AGENT']);
2324 if(!$mathplayer) {
2325 header('Content-Type: application/xhtml+xml');
2326 }
b0ccd3fb 2327 echo '<?xml version="1.0" ?>'."\n";
66a51452 2328 if (!empty($CFG->xml_stylesheets)) {
b0ccd3fb 2329 $stylesheets = explode(';', $CFG->xml_stylesheets);
66a51452 2330 foreach ($stylesheets as $stylesheet) {
b0ccd3fb 2331 echo '<?xml-stylesheet type="text/xsl" href="'. $CFG->wwwroot .'/'. $stylesheet .'" ?>' . "\n";
66a51452 2332 }
2333 }
b0ccd3fb 2334 echo '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1';
e4576482 2335 if (!empty($CFG->xml_doctype_extra)) {
b0ccd3fb 2336 echo ' plus '. $CFG->xml_doctype_extra;
e4576482 2337 }
b0ccd3fb 2338 echo '//' . strtoupper($currentlanguage) . '" "'. $CFG->xml_dtd .'">'."\n";
8f0cd6ef 2339 $direction = " xmlns=\"http://www.w3.org/1999/xhtml\"
2340 xmlns:math=\"http://www.w3.org/1998/Math/MathML\"
8f0cd6ef 2341 xmlns:xlink=\"http://www.w3.org/1999/xlink\"
2342 $direction";
2343 if($mathplayer) {
2344 $meta .= '<object id="mathplayer" classid="clsid:32F66A20-7614-11D4-BD11-00104BD3F987">' . "\n";
b0ccd3fb 2345 $meta .= '<!--comment required to prevent this becoming an empty tag-->'."\n";
2346 $meta .= '</object>'."\n";
8f0cd6ef 2347 $meta .= '<?import namespace="math" implementation="#mathplayer" ?>' . "\n";
2348 }
9fa49e22 2349 }
2350
7bb6d80f 2351 // Clean up the title
2352
268ddd50 2353 $title = format_string($title); // fix for MDL-8582
2eea2cce 2354 $title = str_replace('"', '&quot;', $title);
2355
7bb6d80f 2356 // Create class and id for this page
d529807a 2357 $pageid = $PAGE->pagetype;
753debd2 2358 $pageclass = $PAGE->bodyclasses;
7bb6d80f 2359 $bodytags .= ' class="'.$pageclass.'" id="'.$pageid.'"';
772e78be 2360
b26be9a9 2361 require_once($CFG->libdir .'/editor/htmlEditor.class.php');
b26be9a9 2362 $htmlEditorObject = new htmlEditor();
d074c20e 2363 $htmlEditor = $htmlEditorObject->configure(NULL, $COURSE->id);
b26be9a9 2364
6f8a7d39 2365 ob_start();
ea35ab87 2366 include($CFG->header);
6f8a7d39 2367 $output = ob_get_contents();
2368 ob_end_clean();
b26be9a9 2369
d795bfdb 2370 // container debugging info
2371 $THEME->open_header_containers = open_containers();
2372
317d5ddc 2373 // Skip to main content, see skip_main_destination().
2374 if ($pageid=='course-view' or $pageid=='site-index' or $pageid=='course-index') {
5c355019 2375 $skiplink = '<a class="skip" href="#maincontent">'.get_string('tocontent', 'access').'</a>';
d0b8e40d 2376 if (! preg_match('/(.*<div[^>]+id="page"[^>]*>)(.*)/s', $output, $matches)) {
5c355019 2377 preg_match('/(.*<body.*?>)(.*)/s', $output, $matches);
2378 }
2379 $output = $matches[1]."\n". $skiplink .$matches[2];
317d5ddc 2380 }
5c355019 2381
8af1b1ba 2382 $output = force_strict_header($output);
27f79fda 2383
cdf39255 2384 if (!empty($CFG->messaging)) {
36b6bcec 2385 $output .= message_popup_window();
2386 }
2387
ca70075a 2388 // Add in any extra JavaScript libraries that occurred during the header
2389 $output .= require_js('', 2);
3b0bf2e4 2390 $output .= print_js_call('moodle_initialise_body', array(), true);
ca70075a 2391
c13a5e71 2392 $PAGE->set_state(moodle_page::STATE_IN_BODY);
2393
36b6bcec 2394 if ($return) {
2395 return $output;
2396 } else {
2397 echo $output;
cdf39255 2398 }
9fa49e22 2399}
2400
ca70075a 2401/**
2402 * Used to include JavaScript libraries.
2403 *
2404 * When the $lib parameter is given, the function will ensure that the
e874af28 2405 * named library or libraries is loaded onto the page - either in the
2406 * HTML <head>, just after the header, or at an arbitrary later point in
2407 * the page, depending on where this function is called.
ca70075a 2408 *
2409 * Libraries will not be included more than once, so this works like
2410 * require_once in PHP.
2411 *
e874af28 2412 * There are two special-case calls to this function from print_header which are
fa583f5f 2413 * internal to weblib and use the second $extracthtml parameter:
ca70075a 2414 * $extracthtml = 1: this is used before printing the header.
e874af28 2415 * It returns the script tag code that should go inside the <head>.
ca70075a 2416 * $extracthtml = 2: this is used after printing the header and handles any
e874af28 2417 * require_js calls that occurred within the header itself.
ca70075a 2418 *
e874af28 2419 * @param mixed $lib The library or libraries to load (a string or array of strings)
2420 * There are three way to specify the library:
2421 * 1. a shorname like 'yui_yahoo'. The list of recognised values is in lib/ajax/ajaxlib.php
2422 * 2. the path to the library relative to wwwroot, for example 'lib/javascript-static.js'
2423 * 3. (legacy) a full URL like $CFG->wwwroot . '/lib/javascript-static.js'.
2424 * @param int $extracthtml Private. For internal weblib use only.
2425 * @return mixed No return value (except when doing the internal $extracthtml
2426 * calls, when it returns html code).
ca70075a 2427 */
e874af28 2428function require_js($lib, $extracthtml = 0) {
ca70075a 2429 global $CFG;
2430 static $loadlibs = array();
2431
2432 static $state = REQUIREJS_BEFOREHEADER;
2433 static $latecode = '';
2434
2435 if (!empty($lib)) {
2436 // Add the lib to the list of libs to be loaded, if it isn't already
2437 // in the list.
2438 if (is_array($lib)) {
2439 foreach($lib as $singlelib) {
2440 require_js($singlelib);
2441 }
2442 } else {
2443 $libpath = ajax_get_lib($lib);
2444 if (array_search($libpath, $loadlibs) === false) {
2445 $loadlibs[] = $libpath;
2446
2447 // For state other than 0 we need to take action as well as just
2448 // adding it to loadlibs
2449 if($state != REQUIREJS_BEFOREHEADER) {
2450 // Get the script statement for this library
2451 $scriptstatement=get_require_js_code(array($libpath));
2452
2453 if($state == REQUIREJS_AFTERHEADER) {
2454 // After the header, print it immediately
2455 print $scriptstatement;
2456 } else {
2457 // Haven't finished the header yet. Add it after the
2458 // header
2459 $latecode .= $scriptstatement;
2460 }
2461 }
2462 }
2463 }
2464 } else if($extracthtml==1) {
2465 if($state !== REQUIREJS_BEFOREHEADER) {
2466 debugging('Incorrect state in require_js (expected BEFOREHEADER): be careful not to call with empty $lib (except in print_header)');
2467 } else {
2468 $state = REQUIREJS_INHEADER;
2469 }
2470
2471 return get_require_js_code($loadlibs);
2472 } else if($extracthtml==2) {
2473 if($state !== REQUIREJS_INHEADER) {
2474 debugging('Incorrect state in require_js (expected INHEADER): be careful not to call with empty $lib (except in print_header)');
2475 return '';
2476 } else {
2477 $state = REQUIREJS_AFTERHEADER;
2478 return $latecode;
2479 }
2480 } else {
2481 debugging('Unexpected value for $extracthtml');
2482 }
2483}
2484
2485/**
2486 * Should not be called directly - use require_js. This function obtains the code
2487 * (script tags) needed to include JavaScript libraries.
2488 * @param array $loadlibs Array of library files to include
2489 * @return string HTML code to include them
2490 */
2491function get_require_js_code($loadlibs) {
2492 global $CFG;
2493 // Return the html needed to load the JavaScript files defined in
2494 // our list of libs to be loaded.
2495 $output = '';
2496 foreach ($loadlibs as $loadlib) {
2497 $output .= '<script type="text/javascript" ';
2498 $output .= " src=\"$loadlib\"></script>\n";
2499 if ($loadlib == $CFG->wwwroot.'/lib/yui/logger/logger-min.js') {
2500 // Special case, we need the CSS too.
2501 $output .= '<link type="text/css" rel="stylesheet" ';
2502 $output .= " href=\"{$CFG->wwwroot}/lib/yui/logger/assets/logger.css\" />\n";
2503 }
2504 }
2505 return $output;
2506}
2507
78b5eb25 2508/**
2509 * Generate the HTML for calling a javascript funtion. You often need to do this
2510 * if you have your javascript in an external file, and need to call one function
2511 * to initialise it.
2512 *
949cf26c 2513 * You can pass in an optional list of arguments, which are properly escaped for
2514 * you using the json_encode function.
78b5eb25 2515 *
2516 * @param string $function the name of the JavaScript function to call.
2517 * @param array $args an optional list of arguments to the function call.
2518 * @param boolean $return if true, return the HTML code, otherwise output it.
aa41944f 2519 * @return mixed string if $return is true, otherwise nothing.
78b5eb25 2520 */
2521function print_js_call($function, $args = array(), $return = false) {
2522 $quotedargs = array();
2523 foreach ($args as $arg) {
bef45cd3 2524 $quotedargs[] = json_encode($arg);
78b5eb25 2525 }
2526 $html = '';
2527 $html .= '<script type="text/javascript">//<![CDATA[' . "\n";
2528 $html .= $function . '(' . implode(', ', $quotedargs) . ");\n";
2529 $html .= "//]]></script>\n";
2530 if ($return) {
2531 return $html;
2532 } else {
2533 echo $html;
2534 }
2535}
ca70075a 2536
29305001 2537/**
2538 * Generate the HTML for calling a javascript funtion after a time delay.
2539 * In other respects, this function is the same as print_js_call.
2540 *
2541 * @param integer $delay the desired delay in seconds.
2542 * @param string $function the name of the JavaScript function to call.
2543 * @param array $args an optional list of arguments to the function call.
2544 * @param boolean $return if true, return the HTML code, otherwise output it.
2545 * @return mixed string if $return is true, otherwise nothing.
2546 */
2547function print_delayed_js_call($delay, $function, $args = array(), $return = false) {
2548 $quotedargs = array();
2549 foreach ($args as $arg) {
2550 $quotedargs[] = json_encode($arg);
2551 }
2552 $html = '';
2553 $html .= '<script type="text/javascript">//<![CDATA[' . "\n";
2554 $html .= 'setTimeout(function() {' . $function . '(' .
2555 implode(', ', $quotedargs) . ');}, ' . ($delay * 1000) . ");\n";
2556 $html .= "//]]></script>\n";
2557 if ($return) {
2558 return $html;
2559 } else {
2560 echo $html;
2561 }
2562}
2563
aa41944f 2564/**
2565 * Sometimes you need access to some values in your JavaScript that you can only
2566 * get from PHP code. You can handle this by generating your JS in PHP, but a
2567 * better idea is to write static javascrip code that reads some configuration
2568 * variable, and then just output the configuration variables from PHP using
2569 * this function.
2570 *
fa583f5f 2571 * For example, look at the code in question_init_qenginejs_script() in
aa41944f 2572 * lib/questionlib.php. It writes out a bunch of $settings like
2573 * 'pixpath' => $CFG->pixpath, with $prefix = 'qengine_config'. This gets output
2574 * in print_header, then the code in question/qengine.js can access these variables
2575 * as qengine_config.pixpath, and so on.
2576 *
2577 * This method will also work without a prefix, but it is better to avoid that
2578 * we don't want to add more things than necessary to the global JavaScript scope.
2579 *
2580 * This method automatically wrapps the values in quotes, and addslashes_js them.
2581 *
2582 * @param array $settings the values you want to write out, as variablename => value.
2583 * @param string $prefix a namespace prefix to use in the JavaScript.
2584 * @param boolean $return if true, return the HTML code, otherwise output it.
2585 * @return mixed string if $return is true, otherwise nothing.
2586 */
2587function print_js_config($settings = array(), $prefix='', $return = false) {
2588 $html = '';
2589 $html .= '<script type="text/javascript">//<![CDATA[' . "\n";
2590
2591 // Have to treat the prefix and no prefix cases separately.
2592 if ($prefix) {
2593 // Recommended way, only one thing in global scope.
740939ec 2594 $html .= "var $prefix = " . json_encode($settings) . "\n";
aa41944f 2595
2596 } else {
2597 // Old fashioned way.
2598 foreach ($settings as $name => $value) {
740939ec 2599 $html .= "var $name = '" . addslashes_js($value) . "'\n";
aa41944f 2600 }
2601 }
2602
2603 // Finish off and return/output.
2604 $html .= "//]]></script>\n";
2605 if ($return) {
2606 return $html;
2607 } else {
2608 echo $html;
2609 }
2610}
2611
830c58b7 2612/**
2613 * This function generates the code that defines the standard moodle_cfg object.
2614 * This object has a number of fields that are values that various pieces of
2615 * JavaScript code need access too. For example $CFG->wwwroot and $CFG->pixpath.
2616 *
2617 * @return string a <script> tag that defines the moodle_cfg object.
2618 */
2619function standard_js_config() {
2620 global $CFG;
e4749fcc 2621 $config = array(
830c58b7 2622 'wwwroot' => $CFG->httpswwwroot, // Yes, really.
2623 'pixpath' => $CFG->pixpath,
2624 'modpixpath' => $CFG->modpixpath,
bd1884fe 2625 'sesskey' => sesskey(),
e4749fcc 2626 );
2627 if (debugging('', DEBUG_DEVELOPER)) {
2628 $config['developerdebug'] = true;
2629 }
2630 return print_js_config($config, 'moodle_cfg', true);
830c58b7 2631}
2632
27f79fda 2633/**
2634 * Debugging aid: serve page as 'application/xhtml+xml' where possible,
2635 * and substitute the XHTML strict document type.
2636 * Note, requires the 'xmlns' fix in function print_header above.
2637 * See: http://tracker.moodle.org/browse/MDL-7883
2638 * TODO:
2639 */
8af1b1ba 2640function force_strict_header($output) {
27f79fda 2641 global $CFG;
2642 $strict = '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">';
2643 $xsl = '/lib/xhtml.xsl';
2644
8cf6cb90 2645 if (!headers_sent() && !empty($CFG->xmlstrictheaders)) { // With xml strict headers, the browser will barf
27f79fda 2646 $ctype = 'Content-Type: ';
2647 $prolog= "<?xml version='1.0' encoding='utf-8'?>\n";
2648
5ce73257 2649 if (isset($_SERVER['HTTP_ACCEPT'])
27f79fda 2650 && false !== strpos($_SERVER['HTTP_ACCEPT'], 'application/xhtml+xml')) {
2651 //|| false !== strpos($_SERVER['HTTP_USER_AGENT'], 'Safari') //Safari "Entity 'copy' not defined".
2652 // Firefox et al.
2653 $ctype .= 'application/xhtml+xml';
2654 $prolog .= "<!--\n DEBUG: $ctype \n-->\n";
2655
2656 } else if (file_exists($CFG->dirroot.$xsl)
2657 && preg_match('/MSIE.*Windows NT/', $_SERVER['HTTP_USER_AGENT'])) {
2658 // XSL hack for IE 5+ on Windows.
2659 //$www_xsl = preg_replace('/(http:\/\/.+?\/).*/', '', $CFG->wwwroot) .$xsl;
2660 $www_xsl = $CFG->wwwroot .$xsl;
2661 $ctype .= 'application/xml';
2662 $prolog .= "<?xml-stylesheet type='text/xsl' href='$www_xsl'?>\n";
2663 $prolog .= "<!--\n DEBUG: $ctype \n-->\n";
2664
2665 } else {
2666 //ELSE: Mac/IE, old/non-XML browsers.
2667 $ctype .= 'text/html';
2668 $prolog = '';
2669 }
2670 @header($ctype.'; charset=utf-8');
2671 $output = $prolog . $output;
2672
2673 // Test parser error-handling.
2674 if (isset($_GET['error'])) {
2675 $output .= "__ TEST: XML well-formed error < __\n";
2676 }
2677 }
8af1b1ba 2678
84dec541 2679 $output = preg_replace('/(<!DOCTYPE.+?>)/s', $strict, $output); // Always change the DOCTYPE to Strict 1.0
8af1b1ba 2680
27f79fda 2681 return $output;
2682}
2683
2684
2685
d48b00b4 2686/**
2687 * This version of print_header is simpler because the course name does not have to be
2688 * provided explicitly in the strings. It can be used on the site page as in courses
2689 * Eventually all print_header could be replaced by print_header_simple
2690 *
89dcb99d 2691 * @param string $title Appears at the top of the window
2692 * @param string $heading Appears at the top of the page
2693 * @param string $navigation Premade navigation string (for use as breadcrumbs links)
2694 * @param string $focus Indicates form element to get cursor focus on load eg inputform.password
2695 * @param string $meta Meta tags to be added to the header
2696 * @param boolean $cache Should this page be cacheable?
2697 * @param string $button HTML code for a button (usually for module editing)
2698 * @param string $menu HTML code for a popup menu
2699 * @param boolean $usexml use XML for this page
2700 * @param string $bodytags This text will be included verbatim in the <body> tag (useful for onload() etc)
36b6bcec 2701 * @param bool $return If true, return the visible elements of the header instead of echoing them.
d48b00b4 2702 */
b0ccd3fb 2703function print_header_simple($title='', $heading='', $navigation='', $focus='', $meta='',
36b6bcec 2704 $cache=true, $button='&nbsp;', $menu='', $usexml=false, $bodytags='', $return=false) {
90fcc576 2705
5ce73257 2706 global $COURSE, $CFG;
90fcc576 2707
5dc1e0be 2708 // if we have no navigation specified, build it
2709 if( empty($navigation) ){
2710 $navigation = build_navigation('');
2711 }
2712
84e3d2cc 2713 // If old style nav prepend course short name otherwise leave $navigation object alone
ac4feb59 2714 if (!is_newnav($navigation)) {
7243c7c8 2715 if ($COURSE->id != SITEID) {
2716 $shortname = '<a href="'.$CFG->wwwroot.'/course/view.php?id='. $COURSE->id .'">'. $COURSE->shortname .'</a> ->';
2717 $navigation = $shortname.' '.$navigation;
2718 }
ac4feb59 2719 }
2720
2721 $output = print_header($COURSE->shortname .': '. $title, $COURSE->fullname .' '. $heading, $navigation, $focus, $meta,
da4124be 2722 $cache, $button, $menu, $usexml, $bodytags, true);
36b6bcec 2723
2724 if ($return) {
2725 return $output;
2726 } else {
2727 echo $output;
2728 }
90fcc576 2729}
629b5885 2730
2731
d48b00b4 2732/**
2733 * Can provide a course object to make the footer contain a link to
2734 * to the course home page, otherwise the link will go to the site home
d48b00b4 2735 * @uses $USER
d795bfdb 2736 * @param mixed $course course object, used for course link button or
2737 * 'none' means no user link, only docs link
2738 * 'empty' means nothing printed in footer
2739 * 'home' special frontpage footer
2740 * @param object $usercourse course used in user link
2741 * @param boolean $return output as string
2742 * @return mixed string or void
d48b00b4 2743 */
469b6501 2744function print_footer($course=NULL, $usercourse=NULL, $return=false) {
c13a5e71 2745 global $USER, $CFG, $THEME, $COURSE, $SITE, $PAGE;
9fa49e22 2746
1ae083e4 2747 if (defined('ADMIN_EXT_HEADER_PRINTED') and !defined('ADMIN_EXT_FOOTER_PRINTED')) {
635773c6 2748 admin_externalpage_print_footer();
2749 return;
1ae083e4 2750 }
2751
c13a5e71 2752 $PAGE->set_state(moodle_page::STATE_PRINTING_FOOTER);
2753
d795bfdb 2754/// Course links or special footer
9fa49e22 2755 if ($course) {
d795bfdb 2756 if ($course === 'empty') {
2757 // special hack - sometimes we do not want even the docs link in footer
2758 $output = '';
2759 if (!empty($THEME->open_header_containers)) {
2760 for ($i=0; $i<$THEME->open_header_containers; $i++) {
2761 $output .= print_container_end_all(); // containers opened from header
2762 }
2763 } else {
2764 //1.8 theme compatibility
2765 $output .= "\n</div>"; // content div
2766 }
2767 $output .= "\n</div>\n</body>\n</html>"; // close page div started in header
2768 if ($return) {
2769 return $output;
2770 } else {
2771 echo $output;
2772 return;
2773 }
2774
2775 } else if ($course === 'none') { // Don't print any links etc
b3a2b9dd 2776 $homelink = '';
2777 $loggedinas = '';
0d741155 2778 $home = false;
d795bfdb 2779
2780 } else if ($course === 'home') { // special case for site home page - please do not remove
c23b0ea1 2781 $course = $SITE;
a77ac3dc 2782 $homelink = '<div class="sitelink">'.
8cd94820 2783 '<a title="Moodle '. $CFG->release .'" href="http://moodle.org/">'.
9ace5094 2784 '<img style="width:100px;height:30px" src="'.$CFG->wwwroot.'/pix/moodlelogo.gif" alt="moodlelogo" /></a></div>';
0d741155 2785 $home = true;
d795bfdb 2786
9ace5094 2787 } else if ($course === 'upgrade') {
2788 $home = false;
2789 $loggedinas = '';
2790 $homelink = '<div class="sitelink">'.
2791 '<a title="Moodle '. $CFG->target_release .'" href="http://docs.moodle.org/en/Administrator_documentation" onclick="this.target=\'_blank\'">'.
2792 '<img style="width:100px;height:30px" src="'.$CFG->wwwroot.'/pix/moodlelogo.gif" alt="moodlelogo" /></a></div>';
2793
9fa49e22 2794 } else {
fa738731 2795 $homelink = '<div class="homelink"><a '.$CFG->frametarget.' href="'.$CFG->wwwroot.
6ba65fa0 2796 '/course/view.php?id='.$course->id.'">'.format_string($course->shortname).'</a></div>';
0d741155 2797 $home = false;
9fa49e22 2798 }
d795bfdb 2799
9fa49e22 2800 } else {
c23b0ea1 2801 $course = $SITE; // Set course as site course by default
fa738731 2802 $homelink = '<div class="homelink"><a '.$CFG->frametarget.' href="'.$CFG->wwwroot.'/">'.get_string('home').'</a></div>';
0d741155 2803 $home = false;
9fa49e22 2804 }
2805
0d741155 2806/// Set up some other navigation links (passed from print_header by ugly hack)
2507b2f5 2807 $menu = isset($THEME->menu) ? str_replace('navmenu', 'navmenufooter', $THEME->menu) : '';
2808 $title = isset($THEME->title) ? $THEME->title : '';
2809 $button = isset($THEME->button) ? $THEME->button : '';
2810 $heading = isset($THEME->heading) ? $THEME->heading : '';
2811 $navigation = isset($THEME->navigation) ? $THEME->navigation : '';
2812 $navmenulist = isset($THEME->navmenulist) ? $THEME->navmenulist : '';
0d741155 2813
f940ee41 2814
b3a2b9dd 2815/// Set the user link if necessary
2816 if (!$usercourse and is_object($course)) {
1f2eec7b 2817 $usercourse = $course;
2818 }
2819
b3a2b9dd 2820 if (!isset($loggedinas)) {
2821 $loggedinas = user_login_string($usercourse, $USER);
2822 }
2823
0d741155 2824 if ($loggedinas == $menu) {
9e0d1983 2825 $menu = '';
0d741155 2826 }
2827
d795bfdb 2828/// there should be exactly the same number of open containers as after the header
2829 if ($THEME->open_header_containers != open_containers()) {
2830 debugging('Unexpected number of open containers: '.open_containers().', expecting '.$THEME->open_header_containers, DEBUG_DEVELOPER);
0ad439bb 2831 }
2832
b8cea9b2 2833/// Provide some performance info if required
c2fd9e95 2834 $performanceinfo = '';
afd2b299 2835 if (defined('MDL_PERF') || (!empty($CFG->perfdebug) and $CFG->perfdebug > 7)) {
c2fd9e95 2836 $perf = get_performance_info();
cf1348ca 2837 if (defined('MDL_PERFTOLOG') && !function_exists('register_shutdown_function')) {
853df85e 2838 error_log("PERF: " . $perf['txt']);
2839 }
ea82d6b6 2840 if (defined('MDL_PERFTOFOOT') || debugging() || $CFG->perfdebug > 7) {
c2fd9e95 2841 $performanceinfo = $perf['html'];
2842 }
572fe9ab 2843 }
b8cea9b2 2844
b3a2b9dd 2845/// Include the actual footer file
a282d0ff 2846
469b6501 2847 ob_start();
ea35ab87 2848 include($CFG->footer);
469b6501 2849 $output = ob_get_contents();
2850 ob_end_clean();
a9a9bdba 2851
c13a5e71 2852 $PAGE->set_state(moodle_page::STATE_DONE);
2853
469b6501 2854 if ($return) {
2855 return $output;
2856 } else {
2857 echo $output;
2858 }
a282d0ff 2859}
2860
c3f55692 2861/**
2862 * Returns the name of the current theme
2863 *
2864 * @uses $CFG
8f8210b3 2865 * @uses $USER
2866 * @uses $SESSION
2867 * @uses $COURSE
11e7b506 2868 * @uses $SCRIPT
c3f55692 2869 * @return string
2870 */
2871function current_theme() {
11e7b506 2872 global $CFG, $USER, $SESSION, $COURSE, $SCRIPT;
8f8210b3 2873
2874 if (empty($CFG->themeorder)) {
2875 $themeorder = array('page', 'course', 'category', 'session', 'user', 'site');
2876 } else {
2877 $themeorder = $CFG->themeorder;
2878 }
2879
7507f325 2880 if (isloggedin() and isset($CFG->mnet_localhost_id) and $USER->mnethostid != $CFG->mnet_localhost_id) {
1673e134 2881 require_once($CFG->dirroot.'/mnet/peer.php');
2882 $mnet_peer = new mnet_peer();
2883 $mnet_peer->set_id($USER->mnethostid);
2884 }
2885
8f8210b3 2886 $theme = '';
2887 foreach ($themeorder as $themetype) {
2888
2889 if (!empty($theme)) continue;
84e3d2cc 2890
8f8210b3 2891 switch ($themetype) {
2892 case 'page': // Page theme is for special page-only themes set by code
2893 if (!empty($CFG->pagetheme)) {
2894 $theme = $CFG->pagetheme;
2895 }
2896 break;
2897 case 'course':
2898 if (!empty($CFG->allowcoursethemes) and !empty($COURSE->theme)) {
2899 $theme = $COURSE->theme;
2900 }
2901 break;
2902 case 'category':
2903 if (!empty($CFG->allowcategorythemes)) {
2904 /// Nasty hack to check if we're in a category page
11e7b506 2905 if ($SCRIPT == '/course/category.php') {
8f8210b3 2906 global $id;
2907 if (!empty($id)) {
2908 $theme = current_category_theme($id);
2909 }
2910 /// Otherwise check if we're in a course that has a category theme set
2911 } else if (!empty($COURSE->category)) {
2912 $theme = current_category_theme($COURSE->category);
2913 }
2914 }
2915 break;
2916 case 'session':
2917 if (!empty($SESSION->theme)) {
2918 $theme = $SESSION->theme;
2919 }
2920 break;
2921 case 'user':
2922 if (!empty($CFG->allowuserthemes) and !empty($USER->theme)) {
178bcb75 2923 if (isloggedin() and $USER->mnethostid != $CFG->mnet_localhost_id && $mnet_peer->force_theme == 1 && $mnet_peer->theme != '') {
1673e134 2924 $theme = $mnet_peer->theme;
2925 } else {
2926 $theme = $USER->theme;
2927 }
8f8210b3 2928 }
2929 break;
2930 case 'site':
7507f325 2931 if (isloggedin() and isset($CFG->mnet_localhost_id) and $USER->mnethostid != $CFG->mnet_localhost_id && $mnet_peer->force_theme == 1 && $mnet_peer->theme != '') {
1673e134 2932 $theme = $mnet_peer->theme;
2933 } else {
2934 $theme = $CFG->theme;
2935 }
8f8210b3 2936 break;
2937 default:
2938 /// do nothing
2939 }
2940 }
c3f55692 2941
8f8210b3 2942/// A final check in case 'site' was not included in $CFG->themeorder
2943 if (empty($theme)) {
2944 $theme = $CFG->theme;
2945 }
c3f55692 2946
8f8210b3 2947 return $theme;
2948}
c3f55692 2949
8f8210b3 2950/**
2951 * Retrieves the category theme if one exists, otherwise checks the parent categories.
2952 * Recursive function.
2953 *
2954 * @uses $COURSE
2955 * @param integer $categoryid id of the category to check
2956 * @return string theme name
2957 */
2958function current_category_theme($categoryid=0) {
f33e1ed4 2959 global $COURSE, $DB;
84e3d2cc 2960
8f8210b3 2961/// Use the COURSE global if the categoryid not set
2962 if (empty($categoryid)) {
2963 if (!empty($COURSE->category)) {
2964 $categoryid = $COURSE->category;
2965 } else {
2966 return false;
2967 }
2968 }
84e3d2cc 2969
8f8210b3 2970/// Retrieve the current category
f33e1ed4 2971 if ($category = $DB->get_record('course_categories', array('id'=>$categoryid))) {
84e3d2cc 2972
8f8210b3 2973 /// Return the category theme if it exists
2974 if (!empty($category->theme)) {
2975 return $category->theme;
c3f55692 2976
8f8210b3 2977 /// Otherwise try the parent category if one exists
2978 } else if (!empty($category->parent)) {
2979 return current_category_theme($category->parent);
2980 }
c3f55692 2981
8f8210b3 2982/// Return false if we can't find the category record
c3f55692 2983 } else {
8f8210b3 2984 return false;
c3f55692 2985 }
2986}
2987
d48b00b4 2988/**
2989 * This function is called by stylesheets to set up the header
2990 * approriately as well as the current path
2991 *
2992 * @uses $CFG
89dcb99d 2993 * @param int $lastmodified ?
2994 * @param int $lifetime ?
2995 * @param string $thename ?
d48b00b4 2996 */
f31701c4 2997function style_sheet_setup($lastmodified=0, $lifetime=300, $themename='', $forceconfig='', $lang='') {
6535be85 2998
9c4e6e21 2999 global $CFG, $THEME;
ab9f24ad 3000
a2e2bf64 3001 // Fix for IE6 caching - we don't want the filemtime('styles.php'), instead use now.
3002 $lastmodified = time();
3003
b0ccd3fb 3004 header('Last-Modified: ' . gmdate("D, d M Y H:i:s", $lastmodified) . ' GMT');
3005 header('Expires: ' . gmdate("D, d M Y H:i:s", time() + $lifetime) . ' GMT');
a2e2bf64 3006 header('Cache-Control: max-age='. $lifetime);
b0ccd3fb 3007 header('Pragma: ');
c13a5e71 3008 header('Content-type: text/css'); // Correct MIME type
6535be85 3009
909ec807 3010 $DEFAULT_SHEET_LIST = array('styles_layout', 'styles_fonts', 'styles_color');
9c4e6e21 3011
3012 if (empty($themename)) {
c13a5e71 3013 $themename = current_theme(); // So we have something. Normally not needed.
ab25ce31 3014 } else {
3015 $themename = clean_param($themename, PARAM_SAFEDIR);
9c4e6e21 3016 }
3017
c13a5e71 3018 theme_setup($themename);
3019
3020 if (!empty($forceconfig)) { // Page wants to use the config from this theme instead
9c4e6e21 3021 unset($THEME);
a44091bf 3022 include($CFG->themedir.'/'.$forceconfig.'/'.'config.php');
9c4e6e21 3023 }
3024
3025/// If this is the standard theme calling us, then find out what sheets we need
9c4e6e21 3026 if ($themename == 'standard') {
3027 if (!isset($THEME->standardsheets) or $THEME->standardsheets === true) { // Use all the sheets we have
3028 $THEME->sheets = $DEFAULT_SHEET_LIST;
c13a5e71 3029 } else if (empty($THEME->standardsheets)) { // We can stop right now!
9c4e6e21 3030 echo "/***** Nothing required from this stylesheet by main theme *****/\n\n";
3031 exit;
c13a5e71 3032 } else { // Use the provided subset only
9c4e6e21 3033 $THEME->sheets = $THEME->standardsheets;
3034 }
3035
3036/// If we are a parent theme, then check for parent definitions
9c4e6e21 3037 } else if (!empty($THEME->parent) && $themename == $THEME->parent) {
3038 if (!isset($THEME->parentsheets) or $THEME->parentsheets === true) { // Use all the sheets we have
3039 $THEME->sheets = $DEFAULT_SHEET_LIST;
3040 } else if (empty($THEME->parentsheets)) { // We can stop right now!
3041 echo "/***** Nothing required from this stylesheet by main theme *****/\n\n";
3042 exit;
3043 } else { // Use the provided subset only
3044 $THEME->sheets = $THEME->parentsheets;
3045 }
3046 }
3047
3048/// Work out the last modified date for this theme
9c4e6e21 3049 foreach ($THEME->sheets as $sheet) {
a44091bf 3050 if (file_exists($CFG->themedir.'/'.$themename.'/'.$sheet.'.css')) {
3051 $sheetmodified = filemtime($CFG->themedir.'/'.$themename.'/'.$sheet.'.css');
9c4e6e21 3052 if ($sheetmodified > $lastmodified) {
3053 $lastmodified = $sheetmodified;
3054 }
3055 }
6535be85 3056 }
3057
6ba172fb 3058/// Get a list of all the files we want to include
3059 $files = array();
3060
3061 foreach ($THEME->sheets as $sheet) {
3062 $files[] = array($CFG->themedir, $themename.'/'.$sheet.'.css');
3063 }
3064
3065 if ($themename == 'standard') { // Add any standard styles included in any modules
3066 if (!empty($THEME->modsheets)) { // Search for styles.php within activity modules
3067 if ($mods = get_list_of_plugins('mod')) {
3068 foreach ($mods as $mod) {
3069 if (file_exists($CFG->dirroot.'/mod/'.$mod.'/styles.php')) {
3070 $files[] = array($CFG->dirroot, '/mod/'.$mod.'/styles.php');
3071 }
08396bb2 3072 }
3073 }
3074 }
a2b3f884 3075
6ba172fb 3076 if (!empty($THEME->blocksheets)) { // Search for styles.php within block modules
3077 if ($mods = get_list_of_plugins('blocks')) {
3078 foreach ($mods as $mod) {
3079 if (file_exists($CFG->dirroot.'/blocks/'.$mod.'/styles.php')) {
3080 $files[] = array($CFG->dirroot, '/blocks/'.$mod.'/styles.php');
3081 }
08396bb2 3082 }
3083 }
3084 }
a2b3f884 3085
ae628043 3086 if (!isset($THEME->courseformatsheets) || $THEME->courseformatsheets) { // Search for styles.php in course formats
3087 if ($mods = get_list_of_plugins('format','',$CFG->dirroot.'/course')) {
3088 foreach ($mods as $mod) {
3089 if (file_exists($CFG->dirroot.'/course/format/'.$mod.'/styles.php')) {
3090 $files[] = array($CFG->dirroot, '/course/format/'.$mod.'/styles.php');
3091 }
3092 }
3093 }
3094 }
3095
1273d7dd 3096 if (!isset($THEME->gradereportsheets) || $THEME->gradereportsheets) { // Search for styles.php in grade reports
3097 if ($reports = get_list_of_plugins('grade/report')) {
3098 foreach ($reports as $report) {
3099 if (file_exists($CFG->dirroot.'/grade/report/'.$report.'/styles.php')) {
3100 $files[] = array($CFG->dirroot, '/grade/report/'.$report.'/styles.php');
3101 }
3102 }
3103 }
3104 }
3105
6ba172fb 3106 if (!empty($THEME->langsheets)) { // Search for styles.php within the current language
6ba172fb 3107 if (file_exists($CFG->dirroot.'/lang/'.$lang.'/styles.php')) {
3108 $files[] = array($CFG->dirroot, '/lang/'.$lang.'/styles.php');
3109 }
3110 }
08396bb2 3111 }
3112
6ba172fb 3113 if ($files) {
3114 /// Produce a list of all the files first
3115 echo '/**************************************'."\n";
3116 echo ' * THEME NAME: '.$themename."\n *\n";
3117 echo ' * Files included in this sheet:'."\n *\n";
3118 foreach ($files as $file) {
3119 echo ' * '.$file[1]."\n";
08396bb2 3120 }
6ba172fb 3121 echo ' **************************************/'."\n\n";
08396bb2 3122
6ba172fb 3123
16f0af59 3124 /// check if csscobstants is set
3125 if (!empty($THEME->cssconstants)) {
3126 require_once("$CFG->libdir/cssconstants.php");
3127 /// Actually collect all the files in order.
3128 $css = '';
3129 foreach ($files as $file) {
3130 $css .= '/***** '.$file[1].' start *****/'."\n\n";
3131 $css .= file_get_contents($file[0].'/'.$file[1]);
3132 $ccs .= '/***** '.$file[1].' end *****/'."\n\n";
3133 }
3134 /// replace css_constants with their values
3135 echo replace_cssconstants($css);
3136 } else {
3137 /// Actually output all the files in order.
d0c92410 3138 if (empty($CFG->CSSEdit) && empty($THEME->CSSEdit)) {
3139 foreach ($files as $file) {
3140 echo '/***** '.$file[1].' start *****/'."\n\n";
3141 @include_once($file[0].'/'.$file[1]);
3142 echo '/***** '.$file[1].' end *****/'."\n\n";
3143 }
3144 } else {
3145 foreach ($files as $file) {
3146 echo '/* @group '.$file[1].' */'."\n\n";
3147 if (strstr($file[1], '.css') !== FALSE) {
3148 echo '@import url("'.$CFG->themewww.'/'.$file[1].'");'."\n\n";
3149 } else {
3150 @include_once($file[0].'/'.$file[1]);
3151 }
3152 echo '/* @end */'."\n\n";
3153 }
16f0af59 3154 }
6ba172fb 3155 }
9c4e6e21 3156 }
3157
a44091bf 3158 return $CFG->themewww.'/'.$themename; // Only to help old themes (1.4 and earlier)
6535be85 3159}
3160
9c4e6e21 3161
3162function theme_setup($theme = '', $params=NULL) {
d74d4f20 3163/// Sets up global variables related to themes
3164
c13a5e71 3165 global $CFG, $THEME, $SESSION, $USER, $HTTPSPAGEREQUIRED, $PAGE;
d74d4f20 3166
32462b2c 3167/// Do not mess with THEME if header already printed - this would break all the extra stuff in global $THEME from print_header()!!
c13a5e71 3168 if ($PAGE->headerprinted) {
32462b2c 3169 return;
3170 }
3171
d74d4f20 3172 if (empty($theme)) {
3173 $theme = current_theme();
3174 }
9c4e6e21 3175
09ad59dc 3176/// If the theme doesn't exist for some reason then revert to standardwhite
a44091bf 3177 if (!file_exists($CFG->themedir .'/'. $theme .'/config.php')) {
09ad59dc 3178 $CFG->theme = $theme = 'standardwhite';
3179 }
3180
55b734fb 3181/// Load up the theme config
3182 $THEME = NULL; // Just to be sure
a44091bf 3183 include($CFG->themedir .'/'. $theme .'/config.php'); // Main config for current theme
55b734fb 3184
9c4e6e21 3185/// Put together the parameters
3186 if (!$params) {
3187 $params = array();
3188 }
3572b8b1 3189
56766f85 3190 if ($theme != $CFG->theme) {
3191 $params[] = 'forceconfig='.$theme;
9c4e6e21 3192 }
55b734fb 3193
3194/// Force language too if required
3195 if (!empty($THEME->langsheets)) {
3196 $params[] = 'lang='.current_language();
3197 }
3198
3199/// Convert params to string
9c4e6e21 3200 if ($params) {
55b734fb 3201 $paramstring = '?'.implode('&', $params);
d74d4f20 3202 } else {
9c4e6e21 3203 $paramstring = '';
d74d4f20 3204 }
3205
9c4e6e21 3206/// Set up image paths
24c66531 3207 if(isset($CFG->smartpix) && $CFG->smartpix==1) {
3208 if($CFG->slasharguments) { // Use this method if possible for better caching
3209 $extra='';
3210 } else {
3211 $extra='?file=';
3212 }
84e3d2cc 3213
24c66531 3214 $CFG->pixpath = $CFG->wwwroot. '/pix/smartpix.php'.$extra.'/'.$theme;
3215 $CFG->modpixpath = $CFG->wwwroot .'/pix/smartpix.php'.$extra.'/'.$theme.'/mod';
3216 } else if (empty($THEME->custompix)) { // Could be set in the above file
d74d4f20 3217 $CFG->pixpath = $CFG->wwwroot .'/pix';
3218 $CFG->modpixpath = $CFG->wwwroot .'/mod';
3219 } else {
a44091bf 3220 $CFG->pixpath = $CFG->themewww .'/'. $theme .'/pix';
3221 $CFG->modpixpath = $CFG->themewww .'/'. $theme .'/pix/mod';
d74d4f20 3222 }
3223
9c4e6e21 3224/// Header and footer paths
a44091bf 3225 $CFG->header = $CFG->themedir .'/'. $theme .'/header.html';
3226 $CFG->footer = $CFG->themedir .'/'. $theme .'/footer.html';
d74d4f20 3227
9c4e6e21 3228/// Define stylesheet loading order
d74d4f20