MDL-8323 finished full conversion to proper $COURSE global - no more $CFG->coursethem...
[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// //
10// Copyright (C) 2001-2003 Martin Dougiamas http://dougiamas.com //
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
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
0095d5cd 44/// Constants
45
c1d57101 46/// Define text formatting types ... eventually we can add Wiki, BBcode etc
7cf1c7bd 47
48/**
49 * Does all sorts of transformations and filtering
50 */
b0ccd3fb 51define('FORMAT_MOODLE', '0'); // Does all sorts of transformations and filtering
7cf1c7bd 52
53/**
54 * Plain HTML (with some tags stripped)
55 */
b0ccd3fb 56define('FORMAT_HTML', '1'); // Plain HTML (with some tags stripped)
7cf1c7bd 57
58/**
59 * Plain text (even tags are printed in full)
60 */
b0ccd3fb 61define('FORMAT_PLAIN', '2'); // Plain text (even tags are printed in full)
7cf1c7bd 62
63/**
64 * Wiki-formatted text
6a6495ff 65 * Deprecated: left here just to note that '3' is not used (at the moment)
66 * and to catch any latent wiki-like text (which generates an error)
7cf1c7bd 67 */
b0ccd3fb 68define('FORMAT_WIKI', '3'); // Wiki-formatted text
7cf1c7bd 69
70/**
71 * Markdown-formatted text http://daringfireball.net/projects/markdown/
72 */
b0ccd3fb 73define('FORMAT_MARKDOWN', '4'); // Markdown-formatted text http://daringfireball.net/projects/markdown/
0095d5cd 74
7d8a3cb0 75/**
76 * TRUSTTEXT marker - if present in text, text cleaning should be bypassed
77 */
78define('TRUSTTEXT', '#####TRUSTTEXT#####');
79
7cf1c7bd 80
81/**
82 * Allowed tags - string of html tags that can be tested against for safe html tags
83 * @global string $ALLOWED_TAGS
84 */
39dda0fc 85$ALLOWED_TAGS =
d046ae55 86'<p><br><b><i><u><font><table><tbody><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>';
87
037dcbb6 88/**
89 * Allowed protocols - array of protocols that are safe to use in links and so on
90 * @global string $ALLOWED_PROTOCOLS
91 */
f941df22 92$ALLOWED_PROTOCOLS = array('http', 'https', 'ftp', 'news', 'mailto', 'rtsp', 'teamspeak', 'gopher', 'mms',
c06c8492 93 'color', 'callto', 'cursor', 'text-align', 'font-size', 'font-weight', 'font-style',
016ffbd7 94 'border', 'margin', 'padding', 'background'); // CSS as well to get through kses
037dcbb6 95
96
0095d5cd 97/// Functions
98
7cf1c7bd 99/**
100 * Add quotes to HTML characters
101 *
102 * Returns $var with HTML characters (like "<", ">", etc.) properly quoted.
103 * This function is very similar to {@link p()}
104 *
105 * @param string $var the string potentially containing HTML characters
d4a42ff4 106 * @param boolean $strip to decide if we want to strip slashes or no. Default to false.
107 * true should be used to print data from forms and false for data from DB.
7cf1c7bd 108 * @return string
109 */
d4a42ff4 110function s($var, $strip=false) {
111
63e554d0 112 if ($var == '0') { // for integer 0, boolean false, string '0'
113 return '0';
3662bce5 114 }
d4a42ff4 115
116 if ($strip) {
117 return preg_replace("/&amp;(#\d+);/i", "&$1;", htmlspecialchars(stripslashes_safe($var)));
118 } else {
119 return preg_replace("/&amp;(#\d+);/i", "&$1;", htmlspecialchars($var));
120 }
f9903ed0 121}
122
7cf1c7bd 123/**
124 * Add quotes to HTML characters
125 *
d48b00b4 126 * Prints $var with HTML characters (like "<", ">", etc.) properly quoted.
7cf1c7bd 127 * This function is very similar to {@link s()}
128 *
129 * @param string $var the string potentially containing HTML characters
d4a42ff4 130 * @param boolean $strip to decide if we want to strip slashes or no. Default to false.
131 * true should be used to print data from forms and false for data from DB.
7cf1c7bd 132 * @return string
133 */
d4a42ff4 134function p($var, $strip=false) {
135 echo s($var, $strip);
f9903ed0 136}
137
0d1cd0ea 138/**
139 * Does proper javascript quoting.
5ce73257 140 * Do not use addslashes anymore, because it does not work when magic_quotes_sybase is enabled.
141 *
0d1cd0ea 142 * @param mixed value
143 * @return mixed quoted result
144 */
145function addslashes_js($var) {
146 if (is_string($var)) {
147 $var = str_replace('\\', '\\\\', $var);
148 $var = str_replace(array('\'', '"', "\n", "\r", "\0"), array('\\\'', '\\"', '\\n', '\\r', '\\0'), $var);
4702be4e 149 $var = str_replace('</', '<\/', $var); // XHTML compliance
0d1cd0ea 150 } else if (is_array($var)) {
151 $var = array_map('addslashes_js', $var);
152 } else if (is_object($var)) {
153 $a = get_object_vars($var);
154 foreach ($a as $key=>$value) {
155 $a[$key] = addslashes_js($value);
156 }
157 $var = (object)$a;
158 }
159 return $var;
160}
7cf1c7bd 161
7cf1c7bd 162/**
163 * Remove query string from url
164 *
165 * Takes in a URL and returns it without the querystring portion
166 *
167 * @param string $url the url which may have a query string attached
168 * @return string
169 */
170 function strip_querystring($url) {
f9903ed0 171
b9b8ab69 172 if ($commapos = strpos($url, '?')) {
173 return substr($url, 0, $commapos);
174 } else {
175 return $url;
176 }
f9903ed0 177}
178
7cf1c7bd 179/**
180 * Returns the URL of the HTTP_REFERER, less the querystring portion
181 * @return string
182 */
f9903ed0 183function get_referer() {
d90ffc1f 184 if (isset($_SERVER['HTTP_REFERER'])) {
185 return strip_querystring($_SERVER['HTTP_REFERER']);
186 } else {
5ce73257 187 return '';
d90ffc1f 188 }
f9903ed0 189}
190
c1d57101 191
7cf1c7bd 192/**
193 * Returns the name of the current script, WITH the querystring portion.
194 * this function is necessary because PHP_SELF and REQUEST_URI and SCRIPT_NAME
195 * return different things depending on a lot of things like your OS, Web
196 * server, and the way PHP is compiled (ie. as a CGI, module, ISAPI, etc.)
d48b00b4 197 * <b>NOTE:</b> This function returns false if the global variables needed are not set.
198 *
7cf1c7bd 199 * @return string
200 */
201 function me() {
f9903ed0 202
b0ccd3fb 203 if (!empty($_SERVER['REQUEST_URI'])) {
204 return $_SERVER['REQUEST_URI'];
c1d57101 205
b0ccd3fb 206 } else if (!empty($_SERVER['PHP_SELF'])) {
207 if (!empty($_SERVER['QUERY_STRING'])) {
208 return $_SERVER['PHP_SELF'] .'?'. $_SERVER['QUERY_STRING'];
fced815c 209 }
b0ccd3fb 210 return $_SERVER['PHP_SELF'];
c1d57101 211
b0ccd3fb 212 } else if (!empty($_SERVER['SCRIPT_NAME'])) {
213 if (!empty($_SERVER['QUERY_STRING'])) {
214 return $_SERVER['SCRIPT_NAME'] .'?'. $_SERVER['QUERY_STRING'];
fced815c 215 }
b0ccd3fb 216 return $_SERVER['SCRIPT_NAME'];
fced815c 217
b0ccd3fb 218 } else if (!empty($_SERVER['URL'])) { // May help IIS (not well tested)
219 if (!empty($_SERVER['QUERY_STRING'])) {
220 return $_SERVER['URL'] .'?'. $_SERVER['QUERY_STRING'];
16c4d82a 221 }
b0ccd3fb 222 return $_SERVER['URL'];
16c4d82a 223
b9b8ab69 224 } else {
b0ccd3fb 225 notify('Warning: Could not find any of these web server variables: $REQUEST_URI, $PHP_SELF, $SCRIPT_NAME or $URL');
bcdfe14e 226 return false;
7fbd6b1c 227 }
f9903ed0 228}
229
7cf1c7bd 230/**
d48b00b4 231 * Like {@link me()} but returns a full URL
7cf1c7bd 232 * @see me()
7cf1c7bd 233 * @return string
234 */
f9903ed0 235function qualified_me() {
f9903ed0 236
b6e22603 237 global $CFG;
238
68796e6b 239 if (!empty($CFG->wwwroot)) {
240 $url = parse_url($CFG->wwwroot);
241 }
b6e22603 242
243 if (!empty($url['host'])) {
244 $hostname = $url['host'];
245 } else if (!empty($_SERVER['SERVER_NAME'])) {
b0ccd3fb 246 $hostname = $_SERVER['SERVER_NAME'];
247 } else if (!empty($_ENV['SERVER_NAME'])) {
248 $hostname = $_ENV['SERVER_NAME'];
249 } else if (!empty($_SERVER['HTTP_HOST'])) {
250 $hostname = $_SERVER['HTTP_HOST'];
251 } else if (!empty($_ENV['HTTP_HOST'])) {
252 $hostname = $_ENV['HTTP_HOST'];
39e018b3 253 } else {
b0ccd3fb 254 notify('Warning: could not find the name of this server!');
bcdfe14e 255 return false;
c1d57101 256 }
dc28eede 257
258 if (!empty($url['port'])) {
259 $hostname .= ':'.$url['port'];
260 } else if (!empty($_SERVER['SERVER_PORT'])) {
261 if ($_SERVER['SERVER_PORT'] != 80 && $_SERVER['SERVER_PORT'] != 443) {
262 $hostname .= ':'.$_SERVER['SERVER_PORT'];
263 }
264 }
265
f77c261e 266 if (isset($_SERVER['HTTPS'])) {
267 $protocol = ($_SERVER['HTTPS'] == 'on') ? 'https://' : 'http://';
268 } else if (isset($_SERVER['SERVER_PORT'])) { # Apache2 does not export $_SERVER['HTTPS']
269 $protocol = ($_SERVER['SERVER_PORT'] == '443') ? 'https://' : 'http://';
270 } else {
271 $protocol = 'http://';
272 }
f9903ed0 273
39e018b3 274 $url_prefix = $protocol.$hostname;
b9b8ab69 275 return $url_prefix . me();
f9903ed0 276}
277
7cf1c7bd 278/**
279 * Determine if there is data waiting to be processed from a form
280 *
281 * Used on most forms in Moodle to check for data
282 * Returns the data as an object, if it's found.
283 * This object can be used in foreach loops without
284 * casting because it's cast to (array) automatically
772e78be 285 *
9c0f063b 286 * Checks that submitted POST data exists and returns it as object.
d48b00b4 287 *
9c0f063b 288 * @param string $url not used anymore
289 * @return mixed false or object
7cf1c7bd 290 */
b0ccd3fb 291function data_submitted($url='') {
d48b00b4 292
607809b3 293 if (empty($_POST)) {
36b4f985 294 return false;
295 } else {
9c0f063b 296 return (object)$_POST;
36b4f985 297 }
298}
299
7cf1c7bd 300/**
e8d1c9ed 301 * Moodle replacement for php stripslashes() function,
302 * works also for objects and arrays.
7cf1c7bd 303 *
772e78be 304 * The standard php stripslashes() removes ALL backslashes
7cf1c7bd 305 * even from strings - so C:\temp becomes C:temp - this isn't good.
306 * This function should work as a fairly safe replacement
307 * to be called on quoted AND unquoted strings (to be sure)
d48b00b4 308 *
e8d1c9ed 309 * @param mixed something to remove unsafe slashes from
310 * @return mixed
7cf1c7bd 311 */
e8d1c9ed 312function stripslashes_safe($mixed) {
313 // there is no need to remove slashes from int, float and bool types
314 if (empty($mixed)) {
315 //nothing to do...
316 } else if (is_string($mixed)) {
de64b6c6 317 if (ini_get_bool('magic_quotes_sybase')) { //only unescape single quotes
318 $mixed = str_replace("''", "'", $mixed);
319 } else { //the rest, simple and double quotes and backslashes
320 $mixed = str_replace("\\'", "'", $mixed);
321 $mixed = str_replace('\\"', '"', $mixed);
322 $mixed = str_replace('\\\\', '\\', $mixed);
323 }
e8d1c9ed 324 } else if (is_array($mixed)) {
325 foreach ($mixed as $key => $value) {
326 $mixed[$key] = stripslashes_safe($value);
327 }
328 } else if (is_object($mixed)) {
329 $vars = get_object_vars($mixed);
330 foreach ($vars as $key => $value) {
331 $mixed->$key = stripslashes_safe($value);
332 }
333 }
7d8f674d 334
e8d1c9ed 335 return $mixed;
7d8f674d 336}
f9903ed0 337
9b4b78fd 338/**
339 * Recursive implementation of stripslashes()
340 *
341 * This function will allow you to strip the slashes from a variable.
342 * If the variable is an array or object, slashes will be stripped
343 * from the items (or properties) it contains, even if they are arrays
344 * or objects themselves.
345 *
346 * @param mixed the variable to remove slashes from
347 * @return mixed
348 */
349function stripslashes_recursive($var) {
350 if(is_object($var)) {
351 $properties = get_object_vars($var);
352 foreach($properties as $property => $value) {
353 $var->$property = stripslashes_recursive($value);
354 }
355 }
356 else if(is_array($var)) {
357 foreach($var as $property => $value) {
358 $var[$property] = stripslashes_recursive($value);
359 }
360 }
361 else if(is_string($var)) {
362 $var = stripslashes($var);
363 }
364 return $var;
365}
366
7cf1c7bd 367/**
d48b00b4 368 * Given some normal text this function will break up any
369 * long words to a given size by inserting the given character
370 *
6aaa17c7 371 * It's multibyte savvy and doesn't change anything inside html tags.
372 *
7cf1c7bd 373 * @param string $string the string to be modified
89dcb99d 374 * @param int $maxsize maximum length of the string to be returned
7cf1c7bd 375 * @param string $cutchar the string used to represent word breaks
376 * @return string
377 */
4a5644e5 378function break_up_long_words($string, $maxsize=20, $cutchar=' ') {
a2b3f884 379
6aaa17c7 380/// Loading the textlib singleton instance. We are going to need it.
381 $textlib = textlib_get_instance();
8f7dc7f1 382
6aaa17c7 383/// First of all, save all the tags inside the text to skip them
384 $tags = array();
385 filter_save_tags($string,$tags);
5b07d990 386
6aaa17c7 387/// Process the string adding the cut when necessary
4a5644e5 388 $output = '';
810944af 389 $length = $textlib->strlen($string);
4a5644e5 390 $wordlength = 0;
391
392 for ($i=0; $i<$length; $i++) {
810944af 393 $char = $textlib->substr($string, $i, 1);
6aaa17c7 394 if ($char == ' ' or $char == "\t" or $char == "\n" or $char == "\r" or $char == "<" or $char == ">") {
4a5644e5 395 $wordlength = 0;
396 } else {
397 $wordlength++;
398 if ($wordlength > $maxsize) {
399 $output .= $cutchar;
400 $wordlength = 0;
401 }
402 }
403 $output .= $char;
404 }
6aaa17c7 405
406/// Finally load the tags back again
407 if (!empty($tags)) {
408 $output = str_replace(array_keys($tags), $tags, $output);
409 }
410
4a5644e5 411 return $output;
412}
413
7cf1c7bd 414/**
415 * This does a search and replace, ignoring case
416 * This function is only used for versions of PHP older than version 5
417 * which do not have a native version of this function.
418 * Taken from the PHP manual, by bradhuizenga @ softhome.net
d48b00b4 419 *
7cf1c7bd 420 * @param string $find the string to search for
421 * @param string $replace the string to replace $find with
422 * @param string $string the string to search through
423 * return string
424 */
ce57cc79 425if (!function_exists('str_ireplace')) { /// Only exists in PHP 5
7ec2fc00 426 function str_ireplace($find, $replace, $string) {
7ec2fc00 427
428 if (!is_array($find)) {
429 $find = array($find);
430 }
431
432 if(!is_array($replace)) {
433 if (!is_array($find)) {
434 $replace = array($replace);
435 } else {
436 // this will duplicate the string into an array the size of $find
437 $c = count($find);
438 $rString = $replace;
439 unset($replace);
440 for ($i = 0; $i < $c; $i++) {
441 $replace[$i] = $rString;
442 }
443 }
444 }
445
446 foreach ($find as $fKey => $fItem) {
447 $between = explode(strtolower($fItem),strtolower($string));
448 $pos = 0;
449 foreach($between as $bKey => $bItem) {
450 $between[$bKey] = substr($string,$pos,strlen($bItem));
451 $pos += strlen($bItem) + strlen($fItem);
452 }
453 $string = implode($replace[$fKey],$between);
72e4eac6 454 }
7ec2fc00 455 return ($string);
3fe3851d 456 }
3fe3851d 457}
458
7cf1c7bd 459/**
460 * Locate the position of a string in another string
461 *
462 * This function is only used for versions of PHP older than version 5
463 * which do not have a native version of this function.
464 * Taken from the PHP manual, by dmarsh @ spscc.ctc.edu
d48b00b4 465 *
7cf1c7bd 466 * @param string $haystack The string to be searched
467 * @param string $needle The string to search for
89dcb99d 468 * @param int $offset The position in $haystack where the search should begin.
7cf1c7bd 469 */
ce57cc79 470if (!function_exists('stripos')) { /// Only exists in PHP 5
471 function stripos($haystack, $needle, $offset=0) {
d48b00b4 472
ce57cc79 473 return strpos(strtoupper($haystack), strtoupper($needle), $offset);
474 }
475}
476
7cf1c7bd 477/**
478 * This function will create a HTML link that will work on both
479 * Javascript and non-javascript browsers.
480 * Relies on the Javascript function openpopup in javascript.php
d48b00b4 481 *
7cf1c7bd 482 * $url must be relative to home page eg /mod/survey/stuff.php
483 * @param string $url Web link relative to home page
484 * @param string $name Name to be assigned to the popup window
485 * @param string $linkname Text to be displayed as web link
89dcb99d 486 * @param int $height Height to assign to popup window
487 * @param int $width Height to assign to popup window
7cf1c7bd 488 * @param string $title Text to be displayed as popup page title
489 * @param string $options List of additional options for popup window
490 * @todo Add code examples and list of some options that might be used.
491 * @param boolean $return Should the link to the popup window be returned as a string (true) or printed immediately (false)?
492 * @return string
493 * @uses $CFG
494 */
b0ccd3fb 495function link_to_popup_window ($url, $name='popup', $linkname='click here',
da4124be 496 $height=400, $width=500, $title='Popup window',
497 $options='none', $return=false) {
f9903ed0 498
ff80e012 499 global $CFG;
500
b0ccd3fb 501 if ($options == 'none') {
502 $options = 'menubar=0,location=0,scrollbars,resizable,width='. $width .',height='. $height;
b48f834c 503 }
86aa7ccf 504 $fullscreen = 0;
f9903ed0 505
c80b7585 506 if (!(strpos($url,$CFG->wwwroot) === false)) { // some log url entries contain _SERVER[HTTP_REFERRER] in which case wwwroot is already there.
d2fa35a8 507 $url = substr($url, strlen($CFG->wwwroot));
c80b7585 508 }
509
593bc22b 510 $link = '<a title="'. s($title) .'" href="'. $CFG->wwwroot . $url .'" '.
511 "onclick=\"this.target='$name'; return openpopup('$url', '$name', '$options', $fullscreen);\">$linkname</a>";
1f2eec7b 512 if ($return) {
513 return $link;
514 } else {
515 echo $link;
516 }
f9903ed0 517}
518
7cf1c7bd 519/**
520 * This function will print a button submit form element
521 * that will work on both Javascript and non-javascript browsers.
522 * Relies on the Javascript function openpopup in javascript.php
d48b00b4 523 *
7cf1c7bd 524 * $url must be relative to home page eg /mod/survey/stuff.php
525 * @param string $url Web link relative to home page
526 * @param string $name Name to be assigned to the popup window
527 * @param string $linkname Text to be displayed as web link
89dcb99d 528 * @param int $height Height to assign to popup window
529 * @param int $width Height to assign to popup window
7cf1c7bd 530 * @param string $title Text to be displayed as popup page title
531 * @param string $options List of additional options for popup window
dc28eede 532 * @param string $return If true, return as a string, otherwise print
7cf1c7bd 533 * @return string
534 * @uses $CFG
535 */
b0ccd3fb 536function button_to_popup_window ($url, $name='popup', $linkname='click here',
572fe9ab 537 $height=400, $width=500, $title='Popup window', $options='none', $return=false,
0f7d4e5e 538 $id='', $class='') {
52f1b496 539
540 global $CFG;
541
b0ccd3fb 542 if ($options == 'none') {
543 $options = 'menubar=0,location=0,scrollbars,resizable,width='. $width .',height='. $height;
52f1b496 544 }
0f7d4e5e 545
546 if ($id) {
547 $id = ' id="'.$id.'" ';
548 }
549 if ($class) {
550 $class = ' class="'.$class.'" ';
551 }
52f1b496 552 $fullscreen = 0;
553
0f7d4e5e 554 $button = '<input type="button" name="'.$name.'" title="'. $title .'" value="'. $linkname .' ..." '.$id.$class.
dc28eede 555 "onclick=\"return openpopup('$url', '$name', '$options', $fullscreen);\" />\n";
556 if ($return) {
557 return $button;
558 } else {
559 echo $button;
560 }
52f1b496 561}
562
563
7cf1c7bd 564/**
565 * Prints a simple button to close a window
566 */
eaeaf964 567function close_window_button($name='closewindow', $return=false) {
568 $output = '';
569
4079b3d7 570 $output .= '<div class="closewindow">' . "\n";
eaeaf964 571 $output .= '<script type="text/javascript">' . "\n";
4079b3d7 572 $output .= '//<![CDATA[' . "\n";
eaeaf964 573 $output .= "document.write('<form>');\n";
574 $output .= "document.write('<input type=\"button\" onclick=\"self.close();\" value=\"".get_string("closewindow")."\" />');\n";
575 $output .= "document.write('<\/form>');\n";
4079b3d7 576 $output .= '//]]>' . "\n";
eaeaf964 577 $output .= '</script>' . "\n";
84d04c3e 578 $output .= '<noscript><p>' . "\n";
eaeaf964 579 $output .= get_string($name);
84d04c3e 580 $output .= '</p></noscript>' . "\n";
4079b3d7 581 $output .= '</div>' . "\n";
eaeaf964 582
583 if ($return) {
584 return $output;
585 } else {
586 echo $output;
587 }
f9903ed0 588}
589
08396bb2 590/*
591 * Try and close the current window immediately using Javascript
592 */
593function close_window($delay=0) {
dfa924cc 594?>
595<script type="text/javascript">
4079b3d7 596//<![CDATA[
dfa924cc 597 function close_this_window() {
598 self.close();
599 }
600 setTimeout("close_this_window()", <?php echo $delay * 1000 ?>);
4079b3d7 601//]]>
dfa924cc 602</script>
603<noscript><center>
604<?php print_string('pleaseclose') ?>
605</center></noscript>
606<?php
607 die;
08396bb2 608}
609
610
d48b00b4 611/**
612 * Given an array of value, creates a popup menu to be part of a form
613 * $options["value"]["label"]
614 *
615 * @param type description
616 * @todo Finish documenting this function
617 */
c06c8492 618function choose_from_menu ($options, $name, $selected='', $nothing='choose', $script='',
7850588a 619 $nothingvalue='0', $return=false, $disabled=false, $tabindex=0, $id='') {
ab9f24ad 620
b0ccd3fb 621 if ($nothing == 'choose') {
622 $nothing = get_string('choose') .'...';
618b22c5 623 }
624
48e535bc 625 $attributes = ($script) ? 'onchange="'. $script .'"' : '';
626 if ($disabled) {
627 $attributes .= ' disabled="disabled"';
f9903ed0 628 }
9c9f7d77 629
25e5dbf9 630 if ($tabindex) {
631 $attributes .= ' tabindex="'.$tabindex.'"';
632 }
633
7850588a 634 if ($id ==='') {
a1c91f9a 635 $id = 'menu'.$name;
636 // name may contaion [], which would make an invalid id. e.g. numeric question type editing form, assignment quickgrading
637 $id = str_replace('[', '', $id);
638 $id = str_replace(']', '', $id);
7850588a 639 }
640
641 $output = '<select id="'.$id.'" name="'. $name .'" '. $attributes .'>' . "\n";
bda8d43a 642 if ($nothing) {
7850588a 643 $output .= ' <option value="'. s($nothingvalue) .'"'. "\n";
cec0a0fc 644 if ($nothingvalue === $selected) {
b0ccd3fb 645 $output .= ' selected="selected"';
bda8d43a 646 }
b0ccd3fb 647 $output .= '>'. $nothing .'</option>' . "\n";
873960de 648 }
607809b3 649 if (!empty($options)) {
650 foreach ($options as $value => $label) {
7850588a 651 $output .= ' <option value="'. s($value) .'"';
bd905b45 652 if ((string)$value == (string)$selected) {
b0ccd3fb 653 $output .= ' selected="selected"';
607809b3 654 }
b0ccd3fb 655 if ($label === '') {
656 $output .= '>'. $value .'</option>' . "\n";
a20c1090 657 } else {
b0ccd3fb 658 $output .= '>'. $label .'</option>' . "\n";
607809b3 659 }
f9903ed0 660 }
661 }
b0ccd3fb 662 $output .= '</select>' . "\n";
08056730 663
664 if ($return) {
665 return $output;
666 } else {
667 echo $output;
668 }
ab9f24ad 669}
f9903ed0 670
73d4db84 671/**
672 * Choose value 0 or 1 from a menu with options 'No' and 'Yes'.
673 * Other options like choose_from_menu.
674 */
675function choose_from_menu_yesno($name, $selected, $script = '',
676 $return = false, $disabled = false, $tabindex = 0) {
677 return choose_from_menu(array(get_string('no'), get_string('yes')), $name,
678 $selected, '', $script, '0', $return, $disabled, $tabindex);
679}
680
14040797 681/**
682 * Just like choose_from_menu, but takes a nested array (2 levels) and makes a dropdown menu
683 * including option headings with the first level.
684 */
685function choose_from_menu_nested($options,$name,$selected='',$nothing='choose',$script = '',
686 $nothingvalue=0,$return=false,$disabled=false,$tabindex=0) {
687
688 if ($nothing == 'choose') {
689 $nothing = get_string('choose') .'...';
690 }
691
692 $attributes = ($script) ? 'onchange="'. $script .'"' : '';
693 if ($disabled) {
694 $attributes .= ' disabled="disabled"';
695 }
696
697 if ($tabindex) {
698 $attributes .= ' tabindex="'.$tabindex.'"';
699 }
700
701 $output = '<select id="menu'.$name.'" name="'. $name .'" '. $attributes .'>' . "\n";
702 if ($nothing) {
703 $output .= ' <option value="'. $nothingvalue .'"'. "\n";
704 if ($nothingvalue === $selected) {
705 $output .= ' selected="selected"';
706 }
707 $output .= '>'. $nothing .'</option>' . "\n";
708 }
709 if (!empty($options)) {
710 foreach ($options as $section => $values) {
711 $output .= ' <optgroup label="'.$section.'">'."\n";
712 foreach ($values as $value => $label) {
713 $output .= ' <option value="'. $value .'"';
f332bd02 714 if ((string)$value == (string)$selected) {
14040797 715 $output .= ' selected="selected"';
716 }
717 if ($label === '') {
718 $output .= '>'. $value .'</option>' . "\n";
719 } else {
720 $output .= '>'. $label .'</option>' . "\n";
721 }
722 }
723 $output .= ' </optgroup>'."\n";
724 }
725 }
726 $output .= '</select>' . "\n";
727
728 if ($return) {
729 return $output;
730 } else {
731 echo $output;
732 }
733}
734
735
531a3cb2 736/**
737 * Given an array of values, creates a group of radio buttons to be part of a form
c06c8492 738 *
531a3cb2 739 * @param array $options An array of value-label pairs for the radio group (values as keys)
740 * @param string $name Name of the radiogroup (unique in the form)
741 * @param string $checked The value that is already checked
742 */
eaeaf964 743function choose_from_radio ($options, $name, $checked='', $return=false) {
531a3cb2 744
20cbef63 745 static $idcounter = 0;
746
531a3cb2 747 if (!$name) {
748 $name = 'unnamed';
749 }
750
751 $output = '<span class="radiogroup '.$name."\">\n";
752
753 if (!empty($options)) {
754 $currentradio = 0;
755 foreach ($options as $value => $label) {
20cbef63 756 $htmlid = 'auto-rb'.sprintf('%04d', ++$idcounter);
757 $output .= ' <span class="radioelement '.$name.' rb'.$currentradio."\">";
758 $output .= '<input name="'.$name.'" id="'.$htmlid.'" type="radio" value="'.$value.'"';
531a3cb2 759 if ($value == $checked) {
760 $output .= ' checked="checked"';
761 }
762 if ($label === '') {
20cbef63 763 $output .= ' /> <label for="'.$htmlid.'">'. $value .'</label></span>' . "\n";
531a3cb2 764 } else {
20cbef63 765 $output .= ' /> <label for="'.$htmlid.'">'. $label .'</label></span>' . "\n";
531a3cb2 766 }
767 $currentradio = ($currentradio + 1) % 2;
768 }
769 }
770
771 $output .= '</span>' . "\n";
772
eaeaf964 773 if ($return) {
774 return $output;
775 } else {
776 echo $output;
777 }
531a3cb2 778}
779
2481037f 780/** Display an standard html checkbox with an optional label
781 *
782 * @param string $name The name of the checkbox
783 * @param string $value The valus that the checkbox will pass when checked
784 * @param boolean $checked The flag to tell the checkbox initial state
785 * @param string $label The label to be showed near the checkbox
786 * @param string $alt The info to be inserted in the alt tag
787 */
d0d272e7 788function print_checkbox ($name, $value, $checked = true, $label = '', $alt = '', $script='',$return=false) {
2481037f 789
20cbef63 790 static $idcounter = 0;
791
2481037f 792 if (!$name) {
793 $name = 'unnamed';
794 }
795
27f79fda 796 if ($alt) {
797 $alt = strip_tags($alt);
798 } else {
2481037f 799 $alt = 'checkbox';
800 }
801
802 if ($checked) {
803 $strchecked = ' checked="checked"';
f89f924e 804 } else {
805 $strchecked = '';
2481037f 806 }
807
20cbef63 808 $htmlid = 'auto-cb'.sprintf('%04d', ++$idcounter);
2481037f 809 $output = '<span class="checkbox '.$name."\">";
d0d272e7 810 $output .= '<input name="'.$name.'" id="'.$htmlid.'" type="checkbox" value="'.$value.'" alt="'.$alt.'"'.$strchecked.' '.((!empty($script)) ? ' onClick="'.$script.'" ' : '').' />';
20cbef63 811 if(!empty($label)) {
812 $output .= ' <label for="'.$htmlid.'">'.$label.'</label>';
813 }
2481037f 814 $output .= '</span>'."\n";
815
d0d272e7 816 if (empty($return)) {
817 echo $output;
818 } else {
819 return $output;
820 }
2481037f 821
822}
823
d0d272e7 824/** Display an standard html text field with an optional label
825 *
826 * @param string $name The name of the text field
827 * @param string $value The value of the text field
828 * @param string $label The label to be showed near the text field
829 * @param string $alt The info to be inserted in the alt tag
830 */
eaeaf964 831function print_textfield ($name, $value, $alt = '',$size=50,$maxlength=0, $return=false) {
d0d272e7 832
833 static $idcounter = 0;
834
835 if (empty($name)) {
836 $name = 'unnamed';
837 }
838
839 if (empty($alt)) {
840 $alt = 'textfield';
841 }
842
843 if (!empty($maxlength)) {
844 $maxlength = ' maxlength="'.$maxlength.'" ';
845 }
846
ce432524 847 $htmlid = 'auto-tf'.sprintf('%04d', ++$idcounter);
d0d272e7 848 $output = '<span class="textfield '.$name."\">";
849 $output .= '<input name="'.$name.'" id="'.$htmlid.'" type="text" value="'.$value.'" size="'.$size.'" '.$maxlength.' alt="'.$alt.'" />';
c06c8492 850
d0d272e7 851 $output .= '</span>'."\n";
852
853 if (empty($return)) {
854 echo $output;
855 } else {
856 return $output;
857 }
858
859}
860
861
d48b00b4 862/**
863 * Implements a complete little popup form
864 *
89dcb99d 865 * @uses $CFG
866 * @param string $common The URL up to the point of the variable that changes
867 * @param array $options Alist of value-label pairs for the popup list
ee5567d1 868 * @param string $formid Id must be unique on the page (originaly $formname)
89dcb99d 869 * @param string $selected The option that is already selected
870 * @param string $nothing The label for the "no choice" option
871 * @param string $help The name of a help page if help is required
872 * @param string $helptext The name of the label for the help button
873 * @param boolean $return Indicates whether the function should return the text
874 * as a string or echo it directly to the page being rendered
772e78be 875 * @param string $targetwindow The name of the target page to open the linked page in.
89dcb99d 876 * @return string If $return is true then the entire form is returned as a string.
877 * @todo Finish documenting this function<br>
89dcb99d 878 */
4609c6f0 879function popup_form($common, $options, $formid, $selected='', $nothing='choose', $help='', $helptext='', $return=false, $targetwindow='self', $selectlabel='') {
89dcb99d 880
772e78be 881 global $CFG;
b0542a1e 882 static $go, $choose; /// Locally cached, in case there's lots on a page
87180677 883
6f9f3b69 884 if (empty($options)) {
885 return '';
886 }
0d0baabf 887
b0542a1e 888 if (!isset($go)) {
889 $go = get_string('go');
037dcbb6 890 }
891
b0ccd3fb 892 if ($nothing == 'choose') {
037dcbb6 893 if (!isset($choose)) {
894 $choose = get_string('choose');
895 }
896 $nothing = $choose.'...';
618b22c5 897 }
898
9d3c6ee5 899 // changed reference to document.getElementById('id_abc') instead of document.abc
900 // MDL-7861
4f24b3e3 901 $output = '<form action="'.$CFG->wwwroot.'/course/jumpto.php"'.
fa738731 902 ' method="get" '.
903 $CFG->frametarget.
ee5567d1 904 ' id="'.$formid.'"'.
c4d951e1 905 ' class="popupform">';
4f24b3e3 906 if ($help) {
907 $button = helpbutton($help, $helptext, 'moodle', true, false, '', true);
908 } else {
909 $button = '';
910 }
037dcbb6 911
fcf9577a 912 if ($selectlabel) {
913 $selectlabel = '<label for="'.$formid.'_jump">'.$selectlabel.'</label>';
914 }
915
916 $output .= '<fieldset class="invisiblefieldset">'.$selectlabel.$button.'<select id="'.$formid.'_jump" name="jump" onchange="'.$targetwindow.'.location=document.getElementById(\''.$formid.'\').jump.options[document.getElementById(\''.$formid.'\').jump.selectedIndex].value;">'."\n";
f9903ed0 917
b0ccd3fb 918 if ($nothing != '') {
dfec7b01 919 $output .= " <option value=\"javascript:void(0)\">$nothing</option>\n";
f9903ed0 920 }
921
72b4e283 922 $inoptgroup = false;
89bfeee0 923
f9903ed0 924 foreach ($options as $value => $label) {
772e78be 925
89bfeee0 926 if ($label == '--') { /// we are ending previous optgroup
927 /// Check to see if we already have a valid open optgroup
928 /// XHTML demands that there be at least 1 option within an optgroup
929 if ($inoptgroup and (count($optgr) > 1) ) {
930 $output .= implode('', $optgr);
931 $output .= ' </optgroup>';
932 }
933 $optgr = array();
934 $inoptgroup = false;
935 continue;
936 } else if (substr($label,0,2) == '--') { /// we are starting a new optgroup
772e78be 937
2a003a90 938 /// Check to see if we already have a valid open optgroup
939 /// XHTML demands that there be at least 1 option within an optgroup
940 if ($inoptgroup and (count($optgr) > 1) ) {
941 $output .= implode('', $optgr);
72b4e283 942 $output .= ' </optgroup>';
72b4e283 943 }
2a003a90 944
945 unset($optgr);
946 $optgr = array();
947
948 $optgr[] = ' <optgroup label="'. substr($label,2) .'">'; // Plain labels
772e78be 949
2a003a90 950 $inoptgroup = true; /// everything following will be in an optgroup
3326450b 951 continue;
772e78be 952
d897cae4 953 } else {
fd78420b 954 if (!empty($CFG->usesid) && !isset($_COOKIE[session_name()]))
955 {
956 $url=sid_process_url( $common . $value );
957 } else
958 {
959 $url=$common . $value;
960 }
961 $optstr = ' <option value="' . $url . '"';
772e78be 962
d897cae4 963 if ($value == $selected) {
2a003a90 964 $optstr .= ' selected="selected"';
965 }
772e78be 966
2a003a90 967 if ($label) {
968 $optstr .= '>'. $label .'</option>' . "\n";
969 } else {
970 $optstr .= '>'. $value .'</option>' . "\n";
971 }
772e78be 972
2a003a90 973 if ($inoptgroup) {
974 $optgr[] = $optstr;
975 } else {
976 $output .= $optstr;
d897cae4 977 }
f9903ed0 978 }
772e78be 979
f9903ed0 980 }
2a003a90 981
982 /// catch the final group if not closed
983 if ($inoptgroup and count($optgr) > 1) {
984 $output .= implode('', $optgr);
72b4e283 985 $output .= ' </optgroup>';
986 }
2a003a90 987
b0ccd3fb 988 $output .= '</select>';
3435f39b 989 $output .= '<input type="hidden" name="sesskey" value="'.sesskey().'" />';
ee5567d1 990 $output .= '<div id="noscript'.$formid.'" style="display: inline;">';
929089e7 991 $output .= '<input type="submit" value="'.$go.'" /></div>';
037dcbb6 992 $output .= '<script type="text/javascript">'.
ce926cb8 993 "\n//<![CDATA[\n".
ee5567d1 994 'document.getElementById("noscript'.$formid.'").style.display = "none";'.
ce926cb8 995 "\n//]]>\n".'</script>';
fcf9577a 996 $output .= '</fieldset>';
3d621607 997 $output .= '</form>';
d897cae4 998
999 if ($return) {
4f24b3e3 1000 return $output;
d897cae4 1001 } else {
4f24b3e3 1002 echo $output;
d897cae4 1003 }
f9903ed0 1004}
1005
1006
d48b00b4 1007/**
1008 * Prints some red text
1009 *
1010 * @param string $error The text to be displayed in red
1011 */
f9903ed0 1012function formerr($error) {
d48b00b4 1013
f9903ed0 1014 if (!empty($error)) {
7bc1c17f 1015 echo '<span class="error">'. $error .'</span>';
f9903ed0 1016 }
1017}
1018
d48b00b4 1019/**
1020 * Validates an email to make sure it makes sense.
1021 *
1022 * @param string $address The email address to validate.
1023 * @return boolean
1024 */
89dcb99d 1025function validate_email($address) {
d48b00b4 1026
78fbaeae 1027 return (ereg('^[-!#$%&\'*+\\/0-9=?A-Z^_`a-z{|}~]+'.
1028 '(\.[-!#$%&\'*+\\/0-9=?A-Z^_`a-z{|}~]+)*'.
f9903ed0 1029 '@'.
1030 '[-!#$%&\'*+\\/0-9=?A-Z^_`a-z{|}~]+\.'.
1031 '[-!#$%&\'*+\\./0-9=?A-Z^_`a-z{|}~]+$',
1032 $address));
1033}
1034
690f358b 1035/**
1036 * Extracts file argument either from file parameter or PATH_INFO
1037 *
1038 * @param string $scriptname name of the calling script
1039 * @return string file path (only safe characters)
1040 */
1041function get_file_argument($scriptname) {
1042 global $_SERVER;
1043
1044 $relativepath = FALSE;
1045
1046 // first try normal parameter (compatible method == no relative links!)
1047 $relativepath = optional_param('file', FALSE, PARAM_PATH);
48283ff6 1048 if ($relativepath === '/testslasharguments') {
9bbb40d6 1049 echo 'test -1 : Incorrect use - try "file.php/testslasharguments" instead'; //indicate fopen/fread works for health center
48283ff6 1050 die;
1051 }
690f358b 1052
1053 // then try extract file from PATH_INFO (slasharguments method)
1054 if (!$relativepath and !empty($_SERVER['PATH_INFO'])) {
1055 $path_info = $_SERVER['PATH_INFO'];
1056 // check that PATH_INFO works == must not contain the script name
1057 if (!strpos($path_info, $scriptname)) {
1058 $relativepath = clean_param(rawurldecode($path_info), PARAM_PATH);
48283ff6 1059 if ($relativepath === '/testslasharguments') {
9bbb40d6 1060 echo 'test 1 : Slasharguments test passed. Server confguration is compatible with file.php/1/pic.jpg slashargument setting.'; //indicate ok for health center
690f358b 1061 die;
1062 }
1063 }
1064 }
1065
1066 // now if both fail try the old way
1067 // (for compatibility with misconfigured or older buggy php implementations)
1068 if (!$relativepath) {
1069 $arr = explode($scriptname, me());
1070 if (!empty($arr[1])) {
1071 $path_info = strip_querystring($arr[1]);
1072 $relativepath = clean_param(rawurldecode($path_info), PARAM_PATH);
48283ff6 1073 if ($relativepath === '/testslasharguments') {
9bbb40d6 1074 echo 'test 2 : Slasharguments test passed (compatibility hack). Server confguration may be compatible with file.php/1/pic.jpg slashargument setting'; //indicate ok for health center
690f358b 1075 die;
1076 }
1077 }
1078 }
1079
1080 return $relativepath;
1081}
1082
d48b00b4 1083/**
1084 * Searches the current environment variables for some slash arguments
1085 *
1086 * @param string $file ?
1087 * @todo Finish documenting this function
1088 */
b0ccd3fb 1089function get_slash_arguments($file='file.php') {
f9903ed0 1090
eaa50dbc 1091 if (!$string = me()) {
f9903ed0 1092 return false;
1093 }
eaa50dbc 1094
6ed3da1d 1095 $pathinfo = explode($file, $string);
ab9f24ad 1096
bcdfe14e 1097 if (!empty($pathinfo[1])) {
9b74055f 1098 return addslashes($pathinfo[1]);
6ed3da1d 1099 } else {
1100 return false;
1101 }
1102}
1103
d48b00b4 1104/**
1105 * Extracts arguments from "/foo/bar/something"
1106 * eg http://mysite.com/script.php/foo/bar/something
1107 *
89dcb99d 1108 * @param string $string ?
1109 * @param int $i ?
1110 * @return array|string
d48b00b4 1111 * @todo Finish documenting this function
1112 */
6ed3da1d 1113function parse_slash_arguments($string, $i=0) {
f9903ed0 1114
6c8e8b5e 1115 if (detect_munged_arguments($string)) {
780db230 1116 return false;
1117 }
b0ccd3fb 1118 $args = explode('/', $string);
f9903ed0 1119
1120 if ($i) { // return just the required argument
1121 return $args[$i];
1122
1123 } else { // return the whole array
1124 array_shift($args); // get rid of the empty first one
1125 return $args;
1126 }
1127}
1128
d48b00b4 1129/**
89dcb99d 1130 * Just returns an array of text formats suitable for a popup menu
d48b00b4 1131 *
89dcb99d 1132 * @uses FORMAT_MOODLE
1133 * @uses FORMAT_HTML
1134 * @uses FORMAT_PLAIN
89dcb99d 1135 * @uses FORMAT_MARKDOWN
1136 * @return array
d48b00b4 1137 */
0095d5cd 1138function format_text_menu() {
d48b00b4 1139
b0ccd3fb 1140 return array (FORMAT_MOODLE => get_string('formattext'),
1141 FORMAT_HTML => get_string('formathtml'),
1142 FORMAT_PLAIN => get_string('formatplain'),
b0ccd3fb 1143 FORMAT_MARKDOWN => get_string('formatmarkdown'));
0095d5cd 1144}
1145
d48b00b4 1146/**
1147 * Given text in a variety of format codings, this function returns
772e78be 1148 * the text as safe HTML.
d48b00b4 1149 *
1150 * @uses $CFG
89dcb99d 1151 * @uses FORMAT_MOODLE
1152 * @uses FORMAT_HTML
1153 * @uses FORMAT_PLAIN
1154 * @uses FORMAT_WIKI
1155 * @uses FORMAT_MARKDOWN
1156 * @param string $text The text to be formatted. This is raw text originally from user input.
772e78be 1157 * @param int $format Identifier of the text format to be used
89dcb99d 1158 * (FORMAT_MOODLE, FORMAT_HTML, FORMAT_PLAIN, FORMAT_WIKI, FORMAT_MARKDOWN)
1159 * @param array $options ?
1160 * @param int $courseid ?
1161 * @return string
d48b00b4 1162 * @todo Finish documenting this function
1163 */
7d8a3cb0 1164function format_text($text, $format=FORMAT_MOODLE, $options=NULL, $courseid=NULL) {
0095d5cd 1165
dcf6d93c 1166 global $CFG, $COURSE;
c4ae4fa1 1167
d53ca6ad 1168 if ($text === '') {
1169 return ''; // no need to do any filters and cleaning
1170 }
1171
7d8a3cb0 1172 if (!isset($options->trusttext)) {
1173 $options->trusttext = false;
1174 }
1175
e7a47153 1176 if (!isset($options->noclean)) {
1177 $options->noclean=false;
1178 }
a17c57b5 1179 if (!isset($options->nocache)) {
1180 $options->nocache=false;
1181 }
e7a47153 1182 if (!isset($options->smiley)) {
1183 $options->smiley=true;
1184 }
1185 if (!isset($options->filter)) {
1186 $options->filter=true;
1187 }
1188 if (!isset($options->para)) {
1189 $options->para=true;
1190 }
1191 if (!isset($options->newlines)) {
1192 $options->newlines=true;
f0aa2fed 1193 }
1194
c4ae4fa1 1195 if (empty($courseid)) {
dcf6d93c 1196 $courseid = $COURSE->id;
c4ae4fa1 1197 }
a751a4e5 1198
a17c57b5 1199 if (!empty($CFG->cachetext) and empty($options->nocache)) {
e7a47153 1200 $time = time() - $CFG->cachetext;
90bbe689 1201 $md5key = md5($text.'-'.(int)$courseid.'-'.current_language().'-'.(int)$format.(int)$options->trusttext.(int)$options->noclean.(int)$options->smiley.(int)$options->filter.(int)$options->para.(int)$options->newlines);
a9743837 1202 if ($oldcacheitem = get_record_sql('SELECT * FROM '.$CFG->prefix.'cache_text WHERE md5key = \''.$md5key.'\'', true)) {
1203 if ($oldcacheitem->timemodified >= $time) {
1204 return $oldcacheitem->formattedtext;
1205 }
e7a47153 1206 }
1207 }
1208
7d8a3cb0 1209 // trusttext overrides the noclean option!
1210 if ($options->trusttext) {
1211 if (trusttext_present($text)) {
1212 $text = trusttext_strip($text);
1213 if (!empty($CFG->enabletrusttext)) {
1214 $options->noclean = true;
1215 } else {
1216 $options->noclean = false;
1217 }
1218 } else {
1219 $options->noclean = false;
1220 }
d53ca6ad 1221 } else if (!debugging('', DEBUG_DEVELOPER)) {
1222 // strip any forgotten trusttext in non-developer mode
1223 // do not forget to disable text cache when debugging trusttext!!
1224 $text = trusttext_strip($text);
7d8a3cb0 1225 }
1226
8eaa4c61 1227 $CFG->currenttextiscacheable = true; // Default status - can be changed by any filter
c06c8492 1228
0095d5cd 1229 switch ($format) {
73f8658c 1230 case FORMAT_HTML:
7d8a3cb0 1231 if ($options->smiley) {
e7a47153 1232 replace_smilies($text);
1233 }
7d8a3cb0 1234 if (!$options->noclean) {
5c6347ce 1235 $text = clean_text($text, FORMAT_HTML);
9d40806d 1236 }
7d8a3cb0 1237 if ($options->filter) {
e7a47153 1238 $text = filter_text($text, $courseid);
1239 }
73f8658c 1240 break;
1241
6901fa79 1242 case FORMAT_PLAIN:
5c6347ce 1243 $text = s($text); // cleans dangerous JS
ab892a4f 1244 $text = rebuildnolinktag($text);
b0ccd3fb 1245 $text = str_replace(' ', '&nbsp; ', $text);
6901fa79 1246 $text = nl2br($text);
6901fa79 1247 break;
1248
d342c763 1249 case FORMAT_WIKI:
6a6495ff 1250 // this format is deprecated
572fe9ab 1251 $text = '<p>NOTICE: Wiki-like formatting has been removed from Moodle. You should not be seeing
1252 this message as all texts should have been converted to Markdown format instead.
ce50cc70 1253 Please post a bug report to http://moodle.org/bugs with information about where you
e7a47153 1254 saw this message.</p>'.s($text);
d342c763 1255 break;
1256
e7cdcd18 1257 case FORMAT_MARKDOWN:
1258 $text = markdown_to_html($text);
7d8a3cb0 1259 if ($options->smiley) {
e7a47153 1260 replace_smilies($text);
1261 }
7d8a3cb0 1262 if (!$options->noclean) {
5c6347ce 1263 $text = clean_text($text, FORMAT_HTML);
9d40806d 1264 }
c06c8492 1265
7d8a3cb0 1266 if ($options->filter) {
e7a47153 1267 $text = filter_text($text, $courseid);
1268 }
e7cdcd18 1269 break;
1270
73f8658c 1271 default: // FORMAT_MOODLE or anything else
b7a3d3b2 1272 $text = text_to_html($text, $options->smiley, $options->para, $options->newlines);
7d8a3cb0 1273 if (!$options->noclean) {
5c6347ce 1274 $text = clean_text($text, FORMAT_HTML);
9d40806d 1275 }
c06c8492 1276
7d8a3cb0 1277 if ($options->filter) {
e7a47153 1278 $text = filter_text($text, $courseid);
1279 }
0095d5cd 1280 break;
0095d5cd 1281 }
f0aa2fed 1282
f47f4659 1283 if (empty($options->nocache) and !empty($CFG->cachetext) and $CFG->currenttextiscacheable) {
1284 $newcacheitem = new object();
a9743837 1285 $newcacheitem->md5key = $md5key;
1286 $newcacheitem->formattedtext = addslashes($text);
1287 $newcacheitem->timemodified = time();
1288 if ($oldcacheitem) { // See bug 4677 for discussion
1289 $newcacheitem->id = $oldcacheitem->id;
1290 @update_record('cache_text', $newcacheitem); // Update existing record in the cache table
5ce73257 1291 // It's unlikely that the cron cache cleaner could have
a9743837 1292 // deleted this entry in the meantime, as it allows
1293 // some extra time to cover these cases.
1294 } else {
1295 @insert_record('cache_text', $newcacheitem); // Insert a new record in the cache table
1296 // Again, it's possible that another user has caused this
5ce73257 1297 // record to be created already in the time that it took
1298 // to traverse this function. That's OK too, as the
a9743837 1299 // call above handles duplicate entries, and eventually
1300 // the cron cleaner will delete them.
1301 }
f0aa2fed 1302 }
1303
1304 return $text;
0095d5cd 1305}
1306
4a28b5ca 1307/** Converts the text format from the value to the 'internal'
1308 * name or vice versa. $key can either be the value or the name
1309 * and you get the other back.
c06c8492 1310 *
4a28b5ca 1311 * @param mixed int 0-4 or string one of 'moodle','html','plain','markdown'
1312 * @return mixed as above but the other way around!
1313 */
1314function text_format_name( $key ) {
1315 $lookup = array();
1316 $lookup[FORMAT_MOODLE] = 'moodle';
1317 $lookup[FORMAT_HTML] = 'html';
1318 $lookup[FORMAT_PLAIN] = 'plain';
1319 $lookup[FORMAT_MARKDOWN] = 'markdown';
1320 $value = "error";
1321 if (!is_numeric($key)) {
1322 $key = strtolower( $key );
1323 $value = array_search( $key, $lookup );
1324 }
1325 else {
1326 if (isset( $lookup[$key] )) {
1327 $value = $lookup[ $key ];
1328 }
1329 }
1330 return $value;
1331}
1332
7b2c5e72 1333/** Given a simple string, this function returns the string
1334 * processed by enabled filters if $CFG->filterall is enabled
1335 *
3e6691ee 1336 * @param string $string The string to be filtered.
1337 * @param boolean $striplinks To strip any link in the result text.
1338 * @param int $courseid Current course as filters can, potentially, use it
7b2c5e72 1339 * @return string
1340 */
3e6691ee 1341function format_string ($string, $striplinks = false, $courseid=NULL ) {
7b2c5e72 1342
65b0c132 1343 global $CFG, $COURSE;
7b2c5e72 1344
2a3affe9 1345 //We'll use a in-memory cache here to speed up repeated strings
1346 static $strcache;
1347
1348 //Calculate md5
1c58f440 1349 $md5 = md5($string.'<+>'.$striplinks);
2a3affe9 1350
1351 //Fetch from cache if possible
1352 if(isset($strcache[$md5])) {
1353 return $strcache[$md5];
1354 }
1355
7b2c5e72 1356 if (empty($courseid)) {
dcf6d93c 1357 $courseid = $COURSE->id; // (copied from format_text)
7b2c5e72 1358 }
1359
45daee10 1360 if (!empty($CFG->filterall)) {
7b2c5e72 1361 $string = filter_text($string, $courseid);
1362 }
1363
3e6691ee 1364 if ($striplinks) { //strip links in string
1365 $string = preg_replace('/(<a[^>]+?>)(.+?)(<\/a>)/is','$2',$string);
1366 }
1367
2a3affe9 1368 //Store to cache
1369 $strcache[$md5] = $string;
1370
7b2c5e72 1371 return $string;
1372}
1373
d48b00b4 1374/**
1375 * Given text in a variety of format codings, this function returns
1376 * the text as plain text suitable for plain email.
d48b00b4 1377 *
89dcb99d 1378 * @uses FORMAT_MOODLE
1379 * @uses FORMAT_HTML
1380 * @uses FORMAT_PLAIN
1381 * @uses FORMAT_WIKI
1382 * @uses FORMAT_MARKDOWN
1383 * @param string $text The text to be formatted. This is raw text originally from user input.
772e78be 1384 * @param int $format Identifier of the text format to be used
89dcb99d 1385 * (FORMAT_MOODLE, FORMAT_HTML, FORMAT_PLAIN, FORMAT_WIKI, FORMAT_MARKDOWN)
1386 * @return string
d48b00b4 1387 */
d342c763 1388function format_text_email($text, $format) {
d342c763 1389
1390 switch ($format) {
1391
1392 case FORMAT_PLAIN:
1393 return $text;
1394 break;
1395
1396 case FORMAT_WIKI:
1397 $text = wiki_to_html($text);
5b472756 1398 /// This expression turns links into something nice in a text format. (Russell Jungwirth)
1399 /// From: http://php.net/manual/en/function.eregi-replace.php and simplified
76add072 1400 $text = eregi_replace('(<a [^<]*href=["|\']?([^ "\']*)["|\']?[^>]*>([^<]*)</a>)','\\3 [ \\2 ]', $text);
7c55a29b 1401 return strtr(strip_tags($text), array_flip(get_html_translation_table(HTML_ENTITIES)));
d342c763 1402 break;
1403
6ff45b59 1404 case FORMAT_HTML:
1405 return html_to_text($text);
1406 break;
1407
e7cdcd18 1408 case FORMAT_MOODLE:
1409 case FORMAT_MARKDOWN:
67ccec43 1410 default:
76add072 1411 $text = eregi_replace('(<a [^<]*href=["|\']?([^ "\']*)["|\']?[^>]*>([^<]*)</a>)','\\3 [ \\2 ]', $text);
7c55a29b 1412 return strtr(strip_tags($text), array_flip(get_html_translation_table(HTML_ENTITIES)));
d342c763 1413 break;
1414 }
1415}
0095d5cd 1416
d48b00b4 1417/**
1418 * Given some text in HTML format, this function will pass it
1419 * through any filters that have been defined in $CFG->textfilterx
1420 * The variable defines a filepath to a file containing the
1421 * filter function. The file must contain a variable called
1422 * $textfilter_function which contains the name of the function
1423 * with $courseid and $text parameters
1424 *
89dcb99d 1425 * @param string $text The text to be passed through format filters
1426 * @param int $courseid ?
d48b00b4 1427 * @return string
1428 * @todo Finish documenting this function
1429 */
c4ae4fa1 1430function filter_text($text, $courseid=NULL) {
dcf6d93c 1431 global $CFG, $COURSE;
1432
1433 if (empty($courseid)) {
1434 $courseid = $COURSE->id; // (copied from format_text)
1435 }
e67b9e31 1436
01af49bb 1437 require_once($CFG->libdir.'/filterlib.php');
d523d2ea 1438 if (!empty($CFG->textfilters)) {
1439 $textfilters = explode(',', $CFG->textfilters);
1440 foreach ($textfilters as $textfilter) {
b0ccd3fb 1441 if (is_readable($CFG->dirroot .'/'. $textfilter .'/filter.php')) {
1442 include_once($CFG->dirroot .'/'. $textfilter .'/filter.php');
df1c4611 1443 $functionname = basename($textfilter).'_filter';
1444 if (function_exists($functionname)) {
1445 $text = $functionname($courseid, $text);
1446 }
d523d2ea 1447 }
e67b9e31 1448 }
1449 }
d523d2ea 1450
c7444a36 1451 /// <nolink> tags removed for XHTML compatibility
1452 $text = str_replace('<nolink>', '', $text);
1453 $text = str_replace('</nolink>', '', $text);
1454
e67b9e31 1455 return $text;
1456}
1457
7d8a3cb0 1458/**
1459 * Is the text marked as trusted?
1460 *
1461 * @param string $text text to be searched for TRUSTTEXT marker
1462 * @return boolean
1463 */
1464function trusttext_present($text) {
1465 if (strpos($text, TRUSTTEXT) !== FALSE) {
1466 return true;
1467 } else {
1468 return false;
1469 }
1470}
1471
1472/**
1473 * This funtion MUST be called before the cleaning or any other
1474 * function that modifies the data! We do not know the origin of trusttext
1475 * in database, if it gets there in tweaked form we must not convert it
1476 * to supported form!!!
1477 *
1478 * Please be carefull not to use stripslashes on data from database
1479 * or twice stripslashes when processing data recieved from user.
1480 *
5ce73257 1481 * @param string $text text that may contain TRUSTTEXT marker
7d8a3cb0 1482 * @return text without any TRUSTTEXT marker
1483 */
1484function trusttext_strip($text) {
1485 global $CFG;
1486
1487 while (true) { //removing nested TRUSTTEXT
5ce73257 1488 $orig = $text;
7d8a3cb0 1489 $text = str_replace(TRUSTTEXT, '', $text);
1490 if (strcmp($orig, $text) === 0) {
1491 return $text;
1492 }
1493 }
1494}
1495
1496/**
1497 * Mark text as trusted, such text may contain any HTML tags because the
1498 * normal text cleaning will be bypassed.
1499 * Please make sure that the text comes from trusted user before storing
1500 * it into database!
1501 */
1502function trusttext_mark($text) {
1503 global $CFG;
1504 if (!empty($CFG->enabletrusttext) and (strpos($text, TRUSTTEXT) === FALSE)) {
1505 return TRUSTTEXT.$text;
1506 } else {
1507 return $text;
1508 }
1509}
1510function trusttext_after_edit(&$text, $context) {
1511 if (has_capability('moodle/site:trustcontent', $context)) {
daed1a2f 1512 $text = trusttext_strip($text);
7d8a3cb0 1513 $text = trusttext_mark($text);
1514 } else {
1515 $text = trusttext_strip($text);
1516 }
1517}
1518
1519function trusttext_prepare_edit(&$text, &$format, $usehtmleditor, $context) {
1520 global $CFG;
1521
1522 $options = new object();
1523 $options->smiley = false;
1524 $options->filter = false;
1525 if (!empty($CFG->enabletrusttext)
1526 and has_capability('moodle/site:trustcontent', $context)
1527 and trusttext_present($text)) {
1528 $options->noclean = true;
1529 } else {
1530 $options->noclean = false;
1531 }
1532 $text = trusttext_strip($text);
1533 if ($usehtmleditor) {
1534 $text = format_text($text, $format, $options);
1535 $format = FORMAT_HTML;
1536 } else if (!$options->noclean){
1537 $text = clean_text($text, $format);
1538 }
1539}
1540
d48b00b4 1541/**
1542 * Given raw text (eg typed in by a user), this function cleans it up
1543 * and removes any nasty tags that could mess up Moodle pages.
1544 *
89dcb99d 1545 * @uses FORMAT_MOODLE
1546 * @uses FORMAT_PLAIN
1547 * @uses ALLOWED_TAGS
1548 * @param string $text The text to be cleaned
772e78be 1549 * @param int $format Identifier of the text format to be used
89dcb99d 1550 * (FORMAT_MOODLE, FORMAT_HTML, FORMAT_PLAIN, FORMAT_WIKI, FORMAT_MARKDOWN)
1551 * @return string The cleaned up text
d48b00b4 1552 */
3da47524 1553function clean_text($text, $format=FORMAT_MOODLE) {
b7a3cf49 1554
fc120758 1555 global $ALLOWED_TAGS;
3fe3851d 1556
ab9f24ad 1557 switch ($format) {
e7cdcd18 1558 case FORMAT_PLAIN:
1559 return $text;
1560
1561 default:
1562
29939bea 1563 /// Fix non standard entity notations
1564 $text = preg_replace('/(&#[0-9]+)(;?)/', "\\1;", $text);
1565 $text = preg_replace('/(&#x[0-9a-fA-F]+)(;?)/', "\\1;", $text);
1566
09cbeb40 1567 /// Remove tags that are not allowed
3fe3851d 1568 $text = strip_tags($text, $ALLOWED_TAGS);
e7cdcd18 1569
7789ffbf 1570 /// Clean up embedded scripts and , using kses
1571 $text = cleanAttributes($text);
1572
5b472756 1573 /// Remove script events
ab9f24ad 1574 $text = eregi_replace("([^a-z])language([[:space:]]*)=", "\\1Xlanguage=", $text);
1575 $text = eregi_replace("([^a-z])on([a-z]+)([[:space:]]*)=", "\\1Xon\\2=", $text);
6901fa79 1576
6901fa79 1577 return $text;
0095d5cd 1578 }
b7a3cf49 1579}
f9903ed0 1580
d48b00b4 1581/**
89dcb99d 1582 * This function takes a string and examines it for HTML tags.
d48b00b4 1583 * If tags are detected it passes the string to a helper function {@link cleanAttributes2()}
1584 * which checks for attributes and filters them for malicious content
1585 * 17/08/2004 :: Eamon DOT Costello AT dcu DOT ie
1586 *
1587 * @param string $str The string to be examined for html tags
1588 * @return string
1589 */
3bd7ffec 1590function cleanAttributes($str){
4e8f2e6b 1591 $result = preg_replace_callback(
1592 '%(<[^>]*(>|$)|>)%m', #search for html tags
1593 "cleanAttributes2",
3bd7ffec 1594 $str
67ccec43 1595 );
3bd7ffec 1596 return $result;
67ccec43 1597}
1598
d48b00b4 1599/**
1600 * This function takes a string with an html tag and strips out any unallowed
1601 * protocols e.g. javascript:
1602 * It calls ancillary functions in kses which are prefixed by kses
1603* 17/08/2004 :: Eamon DOT Costello AT dcu DOT ie
1604 *
4e8f2e6b 1605 * @param array $htmlArray An array from {@link cleanAttributes()}, containing in its 1st
1606 * element the html to be cleared
d48b00b4 1607 * @return string
1608 */
4e8f2e6b 1609function cleanAttributes2($htmlArray){
3bd7ffec 1610
037dcbb6 1611 global $CFG, $ALLOWED_PROTOCOLS;
b0ccd3fb 1612 require_once($CFG->libdir .'/kses.php');
3bd7ffec 1613
4e8f2e6b 1614 $htmlTag = $htmlArray[1];
037dcbb6 1615 if (substr($htmlTag, 0, 1) != '<') {
3bd7ffec 1616 return '&gt;'; //a single character ">" detected
1617 }
037dcbb6 1618 if (!preg_match('%^<\s*(/\s*)?([a-zA-Z0-9]+)([^>]*)>?$%', $htmlTag, $matches)) {
67ccec43 1619 return ''; // It's seriously malformed
1620 }
3bd7ffec 1621 $slash = trim($matches[1]); //trailing xhtml slash
67ccec43 1622 $elem = $matches[2]; //the element name
3bd7ffec 1623 $attrlist = $matches[3]; // the list of attributes as a string
1624
037dcbb6 1625 $attrArray = kses_hair($attrlist, $ALLOWED_PROTOCOLS);
3bd7ffec 1626
67ccec43 1627 $attStr = '';
037dcbb6 1628 foreach ($attrArray as $arreach) {
29939bea 1629 $arreach['name'] = strtolower($arreach['name']);
1630 if ($arreach['name'] == 'style') {
1631 $value = $arreach['value'];
1632 while (true) {
1633 $prevvalue = $value;
1634 $value = kses_no_null($value);
1635 $value = preg_replace("/\/\*.*\*\//Us", '', $value);
1636 $value = kses_decode_entities($value);
1637 $value = preg_replace('/(&#[0-9]+)(;?)/', "\\1;", $value);
1638 $value = preg_replace('/(&#x[0-9a-fA-F]+)(;?)/', "\\1;", $value);
1639 if ($value === $prevvalue) {
1640 $arreach['value'] = $value;
1641 break;
1642 }
1643 }
1644 $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']);
1645 $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']);
b8806ccc 1646 } else if ($arreach['name'] == 'href') {
ee7f231d 1647 //Adobe Acrobat Reader XSS protection
1648 $arreach['value'] = preg_replace('/(\.(pdf|fdf|xfdf|xdp|xfd))[^a-z0-9_\.\-].*$/i', '$1', $arreach['value']);
29939bea 1649 }
049bd7db 1650 $attStr .= ' '.$arreach['name'].'="'.$arreach['value'].'"';
3bd7ffec 1651 }
713126cd 1652
3bd7ffec 1653 $xhtml_slash = '';
037dcbb6 1654 if (preg_match('%/\s*$%', $attrlist)) {
67ccec43 1655 $xhtml_slash = ' /';
3bd7ffec 1656 }
b0ccd3fb 1657 return '<'. $slash . $elem . $attStr . $xhtml_slash .'>';
3bd7ffec 1658}
1659
d48b00b4 1660/**
1661 * Replaces all known smileys in the text with image equivalents
1662 *
1663 * @uses $CFG
1664 * @param string $text Passed by reference. The string to search for smily strings.
1665 * @return string
1666 */
5f350e8f 1667function replace_smilies(&$text) {
772e78be 1668///
2ea9027b 1669 global $CFG;
c1d57101 1670
5b472756 1671/// this builds the mapping array only once
617778f2 1672 static $runonce = false;
69081931 1673 static $e = array();
1674 static $img = array();
617778f2 1675 static $emoticons = array(
fbfc2675 1676 ':-)' => 'smiley',
1677 ':)' => 'smiley',
1678 ':-D' => 'biggrin',
1679 ';-)' => 'wink',
1680 ':-/' => 'mixed',
1681 'V-.' => 'thoughtful',
1682 ':-P' => 'tongueout',
1683 'B-)' => 'cool',
1684 '^-)' => 'approve',
1685 '8-)' => 'wideeyes',
1686 ':o)' => 'clown',
1687 ':-(' => 'sad',
1688 ':(' => 'sad',
1689 '8-.' => 'shy',
1690 ':-I' => 'blush',
1691 ':-X' => 'kiss',
1692 '8-o' => 'surprise',
1693 'P-|' => 'blackeye',
1694 '8-[' => 'angry',
1695 'xx-P' => 'dead',
1696 '|-.' => 'sleepy',
1697 '}-]' => 'evil',
35cf8b79 1698 '(h)' => 'heart',
1699 '(heart)' => 'heart',
1700 '(y)' => 'yes',
1701 '(n)' => 'no',
2eb662d2 1702 '(martin)' => 'martin',
e84ea106 1703 '( )' => 'egg'
2ea9027b 1704 );
1705
fbfc2675 1706 if ($runonce == false) { /// After the first time this is not run again
617778f2 1707 foreach ($emoticons as $emoticon => $image){
fbfc2675 1708 $alttext = get_string($image, 'pix');
1709
69081931 1710 $e[] = $emoticon;
d48b00b4 1711 $img[] = '<img alt="'. $alttext .'" width="15" height="15" src="'. $CFG->pixpath .'/s/'. $image .'.gif" />';
617778f2 1712 }
1713 $runonce = true;
c0f728ba 1714 }
b7a3cf49 1715
8dcd43f3 1716 // Exclude from transformations all the code inside <script> tags
1717 // Needed to solve Bug 1185. Thanks to jouse 2001 detecting it. :-)
1718 // Based on code from glossary fiter by Williams Castillo.
1719 // - Eloy
1720
1721 // Detect all the <script> zones to take out
1722 $excludes = array();
1723 preg_match_all('/<script language(.+?)<\/script>/is',$text,$list_of_excludes);
1724
1725 // Take out all the <script> zones from text
1726 foreach (array_unique($list_of_excludes[0]) as $key=>$value) {
1727 $excludes['<+'.$key.'+>'] = $value;
1728 }
1729 if ($excludes) {
1730 $text = str_replace($excludes,array_keys($excludes),$text);
1731 }
1732
fbfc2675 1733/// this is the meat of the code - this is run every time
5f350e8f 1734 $text = str_replace($e, $img, $text);
8dcd43f3 1735
1736 // Recover all the <script> zones to text
1737 if ($excludes) {
1738 $text = str_replace(array_keys($excludes),$excludes,$text);
1739 }
1a072208 1740}
0095d5cd 1741
89dcb99d 1742/**
1743 * Given plain text, makes it into HTML as nicely as possible.
1744 * May contain HTML tags already
1745 *
1746 * @uses $CFG
1747 * @param string $text The string to convert.
1748 * @param boolean $smiley Convert any smiley characters to smiley images?
1749 * @param boolean $para If true then the returned string will be wrapped in paragraph tags
1750 * @param boolean $newlines If true then lines newline breaks will be converted to HTML newline breaks.
1751 * @return string
1752 */
1753
b7a3d3b2 1754function text_to_html($text, $smiley=true, $para=true, $newlines=true) {
772e78be 1755///
f9903ed0 1756
27326a3e 1757 global $CFG;
1758
c1d57101 1759/// Remove any whitespace that may be between HTML tags
7b3be1b1 1760 $text = eregi_replace(">([[:space:]]+)<", "><", $text);
1761
c1d57101 1762/// Remove any returns that precede or follow HTML tags
0eae8049 1763 $text = eregi_replace("([\n\r])<", " <", $text);
1764 $text = eregi_replace(">([\n\r])", "> ", $text);
7b3be1b1 1765
5f350e8f 1766 convert_urls_into_links($text);
f9903ed0 1767
c1d57101 1768/// Make returns into HTML newlines.
b7a3d3b2 1769 if ($newlines) {
1770 $text = nl2br($text);
1771 }
f9903ed0 1772
c1d57101 1773/// Turn smileys into images.
d69cb7f4 1774 if ($smiley) {
5f350e8f 1775 replace_smilies($text);
d69cb7f4 1776 }
f9903ed0 1777
c1d57101 1778/// Wrap the whole thing in a paragraph tag if required
909f539d 1779 if ($para) {
b0ccd3fb 1780 return '<p>'.$text.'</p>';
909f539d 1781 } else {
1782 return $text;
1783 }
f9903ed0 1784}
1785
d48b00b4 1786/**
1787 * Given Markdown formatted text, make it into XHTML using external function
1788 *
89dcb99d 1789 * @uses $CFG
1790 * @param string $text The markdown formatted text to be converted.
1791 * @return string Converted text
d48b00b4 1792 */
e7cdcd18 1793function markdown_to_html($text) {
e7cdcd18 1794 global $CFG;
1795
b0ccd3fb 1796 require_once($CFG->libdir .'/markdown.php');
e7cdcd18 1797
1798 return Markdown($text);
1799}
1800
d48b00b4 1801/**
89dcb99d 1802 * Given HTML text, make it into plain text using external function
d48b00b4 1803 *
1804 * @uses $CFG
1805 * @param string $html The text to be converted.
1806 * @return string
1807 */
6ff45b59 1808function html_to_text($html) {
89dcb99d 1809
428aaa29 1810 global $CFG;
6ff45b59 1811
b0ccd3fb 1812 require_once($CFG->libdir .'/html2text.php');
6ff45b59 1813
1814 return html2text($html);
1815}
1816
d48b00b4 1817/**
1818 * Given some text this function converts any URLs it finds into HTML links
1819 *
1820 * @param string $text Passed in by reference. The string to be searched for urls.
1821 */
5f350e8f 1822function convert_urls_into_links(&$text) {
5f350e8f 1823/// Make lone URLs into links. eg http://moodle.com/
3405b212 1824 $text = eregi_replace("([[:space:]]|^|\(|\[)([[:alnum:]]+)://([^[:space:]]*)([[:alnum:]#?/&=])",
bc01a2b8 1825 "\\1<a href=\"\\2://\\3\\4\" target=\"_blank\">\\2://\\3\\4</a>", $text);
5f350e8f 1826
1827/// eg www.moodle.com
ab9f24ad 1828 $text = eregi_replace("([[:space:]]|^|\(|\[)www\.([^[:space:]]*)([[:alnum:]#?/&=])",
bc01a2b8 1829 "\\1<a href=\"http://www.\\2\\3\" target=\"_blank\">www.\\2\\3</a>", $text);
5f350e8f 1830}
1831
d48b00b4 1832/**
1833 * This function will highlight search words in a given string
1834 * It cares about HTML and will not ruin links. It's best to use
1835 * this function after performing any conversions to HTML.
1836 * Function found here: http://forums.devshed.com/t67822/scdaa2d1c3d4bacb4671d075ad41f0854.html
1837 *
89dcb99d 1838 * @param string $needle The string to search for
1839 * @param string $haystack The string to search for $needle in
1840 * @param int $case ?
1841 * @return string
d48b00b4 1842 * @todo Finish documenting this function
1843 */
ab9f24ad 1844function highlight($needle, $haystack, $case=0,
b0ccd3fb 1845 $left_string='<span class="highlight">', $right_string='</span>') {
69d51d3a 1846 if (empty($needle)) {
1847 return $haystack;
1848 }
1849
5eecb8cb 1850 //$list_of_words = eregi_replace("[^-a-zA-Z0-9&.']", " ", $needle); // bug 3101
1851 $list_of_words = $needle;
b0ccd3fb 1852 $list_array = explode(' ', $list_of_words);
88438a58 1853 for ($i=0; $i<sizeof($list_array); $i++) {
1854 if (strlen($list_array[$i]) == 1) {
b0ccd3fb 1855 $list_array[$i] = '';
88438a58 1856 }
1857 }
b0ccd3fb 1858 $list_of_words = implode(' ', $list_array);
88438a58 1859 $list_of_words_cp = $list_of_words;
1860 $final = array();
1861 preg_match_all('/<(.+?)>/is',$haystack,$list_of_words);
1862
1863 foreach (array_unique($list_of_words[0]) as $key=>$value) {
1864 $final['<|'.$key.'|>'] = $value;
1865 }
1866
1867 $haystack = str_replace($final,array_keys($final),$haystack);
b0ccd3fb 1868 $list_of_words_cp = eregi_replace(' +', '|', $list_of_words_cp);
88438a58 1869
b0ccd3fb 1870 if ($list_of_words_cp{0}=='|') {
1871 $list_of_words_cp{0} = '';
88438a58 1872 }
b0ccd3fb 1873 if ($list_of_words_cp{strlen($list_of_words_cp)-1}=='|') {
1874 $list_of_words_cp{strlen($list_of_words_cp)-1}='';
88438a58 1875 }
88438a58 1876
9ccdcd97 1877 $list_of_words_cp = trim($list_of_words_cp);
1878
1879 if ($list_of_words_cp) {
1880
1881 $list_of_words_cp = "(". $list_of_words_cp .")";
1882
1883 if (!$case){
1884 $haystack = eregi_replace("$list_of_words_cp", "$left_string"."\\1"."$right_string", $haystack);
1885 } else {
1886 $haystack = ereg_replace("$list_of_words_cp", "$left_string"."\\1"."$right_string", $haystack);
1887 }
88438a58 1888 }
1889 $haystack = str_replace(array_keys($final),$final,$haystack);
1890
f60e7cfe 1891 return $haystack;
88438a58 1892}
1893
d48b00b4 1894/**
1895 * This function will highlight instances of $needle in $haystack
1896 * It's faster that the above function and doesn't care about
1897 * HTML or anything.
1898 *
1899 * @param string $needle The string to search for
1900 * @param string $haystack The string to search for $needle in
1901 * @return string
1902 */
88438a58 1903function highlightfast($needle, $haystack) {
5af78ed2 1904
57f1b914 1905 $parts = explode(moodle_strtolower($needle), moodle_strtolower($haystack));
5af78ed2 1906
1907 $pos = 0;
1908
1909 foreach ($parts as $key => $part) {
1910 $parts[$key] = substr($haystack, $pos, strlen($part));
1911 $pos += strlen($part);
1912
b0ccd3fb 1913 $parts[$key] .= '<span class="highlight">'.substr($haystack, $pos, strlen($needle)).'</span>';
5af78ed2 1914 $pos += strlen($needle);
ab9f24ad 1915 }
5af78ed2 1916
1917 return (join('', $parts));
1918}
1919
f9903ed0 1920
9fa49e22 1921/// STANDARD WEB PAGE PARTS ///////////////////////////////////////////////////
1922
d48b00b4 1923/**
1924 * Print a standard header
1925 *
89dcb99d 1926 * @uses $USER
1927 * @uses $CFG
89dcb99d 1928 * @uses $SESSION
1929 * @param string $title Appears at the top of the window
1930 * @param string $heading Appears at the top of the page
1931 * @param string $navigation Premade navigation string (for use as breadcrumbs links)
1932 * @param string $focus Indicates form element to get cursor focus on load eg inputform.password
1933 * @param string $meta Meta tags to be added to the header
1934 * @param boolean $cache Should this page be cacheable?
1935 * @param string $button HTML code for a button (usually for module editing)
1936 * @param string $menu HTML code for a popup menu
1937 * @param boolean $usexml use XML for this page
1938 * @param string $bodytags This text will be included verbatim in the <body> tag (useful for onload() etc)
36b6bcec 1939 * @param bool $return If true, return the visible elements of the header instead of echoing them.
d48b00b4 1940 */
36b6bcec 1941function print_header ($title='', $heading='', $navigation='', $focus='',
1942 $meta='', $cache=true, $button='&nbsp;', $menu='',
1943 $usexml=false, $bodytags='', $return=false) {
63f3cbbd 1944
dcf6d93c 1945 global $USER, $CFG, $THEME, $SESSION, $ME, $SITE, $COURSE;
c06c8492 1946
32613b50 1947/// This makes sure that the header is never repeated twice on a page
f231e867 1948 if (defined('HEADER_PRINTED')) {
ea82d6b6 1949 debugging('print_header() was called more than once - this should not happen. Please check the code for this page closely. Note: error() and redirect() are now safe to call after print_header().');
32613b50 1950 return;
32613b50 1951 }
f231e867 1952 define('HEADER_PRINTED', 'true');
1953
be933850 1954
c3f55692 1955/// Add the required stylesheets
d74d4f20 1956 $stylesheetshtml = '';
1957 foreach ($CFG->stylesheets as $stylesheet) {
1958 $stylesheetshtml .= '<link rel="stylesheet" type="text/css" href="'.$stylesheet.'" />'."\n";
c3f55692 1959 }
d74d4f20 1960 $meta = $stylesheetshtml.$meta;
e89fb61e 1961
79f533c3 1962
1963/// Add the meta page from the themes if any were requested
1964
1965 $metapage = '';
1966
1967 if (!isset($THEME->standardmetainclude) || $THEME->standardmetainclude) {
1968 ob_start();
1969 include_once($CFG->dirroot.'/theme/standard/meta.php');
1970 $metapage .= ob_get_contents();
1971 ob_end_clean();
1972 }
1973
1974 if ($THEME->parent && (!isset($THEME->parentmetainclude) || $THEME->parentmetainclude)) {
36e8c122 1975 if (file_exists($CFG->dirroot.'/theme/'.$THEME->parent.'/meta.php')) {
1976 ob_start();
1977 include_once($CFG->dirroot.'/theme/'.$THEME->parent.'/meta.php');
1978 $metapage .= ob_get_contents();
1979 ob_end_clean();
1980 }
79f533c3 1981 }
1982
1983 if (!isset($THEME->metainclude) || $THEME->metainclude) {
36e8c122 1984 if (file_exists($CFG->dirroot.'/theme/'.current_theme().'/meta.php')) {
1985 ob_start();
1986 include_once($CFG->dirroot.'/theme/'.current_theme().'/meta.php');
1987 $metapage .= ob_get_contents();
1988 ob_end_clean();
1989 }
79f533c3 1990 }
1991
1992 $meta = $meta."\n".$metapage;
1993
1994
9fa49e22 1995
b0ccd3fb 1996 if ($navigation == 'home') {
9fa49e22 1997 $home = true;
b0ccd3fb 1998 $navigation = '';
9d378732 1999 } else {
2000 $home = false;
9fa49e22 2001 }
2002
0d741155 2003/// This is another ugly hack to make navigation elements available to print_footer later
2004 $THEME->title = $title;
2005 $THEME->heading = $heading;
2006 $THEME->navigation = $navigation;
2007 $THEME->button = $button;
2008 $THEME->menu = $menu;
2507b2f5 2009 $navmenulist = isset($THEME->navmenulist) ? $THEME->navmenulist : '';
0d741155 2010
b0ccd3fb 2011 if ($button == '') {
2012 $button = '&nbsp;';
9fa49e22 2013 }
2014
2015 if (!$menu and $navigation) {
8a33e371 2016 if (empty($CFG->loginhttps)) {
2017 $wwwroot = $CFG->wwwroot;
2018 } else {
2c3432e6 2019 $wwwroot = str_replace('http:','https:',$CFG->wwwroot);
8a33e371 2020 }
60f9e36e 2021 $menu = user_login_string($COURSE);
9fa49e22 2022 }
67ccec43 2023
b4bac9b6 2024 if (isset($SESSION->justloggedin)) {
2025 unset($SESSION->justloggedin);
2026 if (!empty($CFG->displayloginfailures)) {
8f8ed475 2027 if (!empty($USER->username) and $USER->username != 'guest') {
b4bac9b6 2028 if ($count = count_login_failures($CFG->displayloginfailures, $USER->username, $USER->lastlogin)) {
2029 $menu .= '&nbsp;<font size="1">';
2030 if (empty($count->accounts)) {
2031 $menu .= get_string('failedloginattempts', '', $count);
2032 } else {
2033 $menu .= get_string('failedloginattemptsall', '', $count);
2034 }
51792df0 2035 if (has_capability('moodle/site:viewreports', get_context_instance(CONTEXT_SYSTEM, SITEID))) {
52af9a35 2036 $menu .= ' (<a href="'.$CFG->wwwroot.'/course/report/log/index.php'.
839f2456 2037 '?chooselog=1&amp;id=1&amp;modid=site_errors">'.get_string('logs').'</a>)';
b4bac9b6 2038 }
2039 $menu .= '</font>';
2040 }
2041 }
2042 }
2043 }
9fa49e22 2044
47037513 2045
810944af 2046 $meta = '<meta http-equiv="content-type" content="text/html; charset=utf-8" />'. "\n". $meta ."\n";
03fe48e7 2047 if (!$usexml) {
810944af 2048 @header('Content-type: text/html; charset=utf-8');
03fe48e7 2049 }
9fa49e22 2050
b0ccd3fb 2051 if ( get_string('thisdirection') == 'rtl' ) {
2052 $direction = ' dir="rtl"';
9fa49e22 2053 } else {
b0ccd3fb 2054 $direction = ' dir="ltr"';
9fa49e22 2055 }
6575bfd4 2056 //Accessibility: added the 'lang' attribute to $direction, used in theme <html> tag.
2057 $language = str_replace('_utf8','',$CFG->lang);
2058 $direction .= ' lang="'.$language.'" xml:lang="'.$language.'"';
ab9f24ad 2059
5debee2d 2060 if ($cache) { // Allow caching on "back" (but not on normal clicks)
2061 @header('Cache-Control: private, pre-check=0, post-check=0, max-age=0');
2062 @header('Pragma: no-cache');
772e78be 2063 @header('Expires: ');
5debee2d 2064 } else { // Do everything we can to always prevent clients and proxies caching
03fe48e7 2065 @header('Cache-Control: no-store, no-cache, must-revalidate');
2066 @header('Cache-Control: post-check=0, pre-check=0', false);
2067 @header('Pragma: no-cache');
5debee2d 2068 @header('Expires: Mon, 20 Aug 1969 09:23:00 GMT');
2069 @header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
03fe48e7 2070
5debee2d 2071 $meta .= "\n<meta http-equiv=\"pragma\" content=\"no-cache\" />";
2072 $meta .= "\n<meta http-equiv=\"expires\" content=\"0\" />";
66a51452 2073 }
5debee2d 2074 @header('Accept-Ranges: none');
66a51452 2075
5ce73257 2076 if (empty($usexml)) {
27f79fda 2077 $direction = ' xmlns="http://www.w3.org/1999/xhtml"'. $direction; // See debug_header
2078 } else {
66a51452 2079 $currentlanguage = current_language();
8f0cd6ef 2080 $mathplayer = preg_match("/MathPlayer/i", $_SERVER['HTTP_USER_AGENT']);
2081 if(!$mathplayer) {
2082 header('Content-Type: application/xhtml+xml');
2083 }
b0ccd3fb 2084 echo '<?xml version="1.0" ?>'."\n";
66a51452 2085 if (!empty($CFG->xml_stylesheets)) {
b0ccd3fb 2086 $stylesheets = explode(';', $CFG->xml_stylesheets);
66a51452 2087 foreach ($stylesheets as $stylesheet) {
b0ccd3fb 2088 echo '<?xml-stylesheet type="text/xsl" href="'. $CFG->wwwroot .'/'. $stylesheet .'" ?>' . "\n";
66a51452 2089 }
2090 }
b0ccd3fb 2091 echo '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1';
e4576482 2092 if (!empty($CFG->xml_doctype_extra)) {
b0ccd3fb 2093 echo ' plus '. $CFG->xml_doctype_extra;
e4576482 2094 }
b0ccd3fb 2095 echo '//' . strtoupper($currentlanguage) . '" "'. $CFG->xml_dtd .'">'."\n";
8f0cd6ef 2096 $direction = " xmlns=\"http://www.w3.org/1999/xhtml\"
2097 xmlns:math=\"http://www.w3.org/1998/Math/MathML\"
8f0cd6ef 2098 xmlns:xlink=\"http://www.w3.org/1999/xlink\"
2099 $direction";
2100 if($mathplayer) {
2101 $meta .= '<object id="mathplayer" classid="clsid:32F66A20-7614-11D4-BD11-00104BD3F987">' . "\n";
b0ccd3fb 2102 $meta .= '<!--comment required to prevent this becoming an empty tag-->'."\n";
2103 $meta .= '</object>'."\n";
8f0cd6ef 2104 $meta .= '<?import namespace="math" implementation="#mathplayer" ?>' . "\n";
2105 }
9fa49e22 2106 }
2107
7bb6d80f 2108 // Clean up the title
2109
2eea2cce 2110 $title = str_replace('"', '&quot;', $title);
1d9fc417 2111 $title = strip_tags($title);
2eea2cce 2112
7bb6d80f 2113 // Create class and id for this page
2114
68d5f00a 2115 page_id_and_class($pageid, $pageclass);
7bb6d80f 2116
60f9e36e 2117 $pageclass .= ' course-'.$COURSE->id;
d6c66e12 2118
758027d0 2119 if (($pageid != 'site-index') && ($pageid != 'course-view') &&
2120 ($pageid != 'admin-settings')) {
2121 $pageclass .= ' nocoursepage';
2122 }
2123
367e23c2 2124 if (!isloggedin()) {
2125 $pageclass .= ' notloggedin';
2126 }
2127
e299f862 2128 if (!empty($USER->editing)) {
2129 $pageclass .= ' editing';
2130 }
2131
75c3849a 2132 if (!empty($CFG->blocksdrag)) {
2133 $pageclass .= ' drag';
2134 }
2135
7bb6d80f 2136 $bodytags .= ' class="'.$pageclass.'" id="'.$pageid.'"';
772e78be 2137
36b6bcec 2138 ob_start();
ea35ab87 2139 include($CFG->header);
36b6bcec 2140 $output = ob_get_contents();
2141 ob_end_clean();
e608dddd 2142
8af1b1ba 2143 $output = force_strict_header($output);
27f79fda 2144
cdf39255 2145 if (!empty($CFG->messaging)) {
36b6bcec 2146 $output .= message_popup_window();
2147 }
2148
2149 if ($return) {
2150 return $output;
2151 } else {
2152 echo $output;
cdf39255 2153 }
9fa49e22 2154}
2155
27f79fda 2156/**
2157 * Debugging aid: serve page as 'application/xhtml+xml' where possible,
2158 * and substitute the XHTML strict document type.
2159 * Note, requires the 'xmlns' fix in function print_header above.
2160 * See: http://tracker.moodle.org/browse/MDL-7883
2161 * TODO:
2162 */
8af1b1ba 2163function force_strict_header($output) {
27f79fda 2164 global $CFG;
2165 $strict = '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">';
2166 $xsl = '/lib/xhtml.xsl';
2167
8af1b1ba 2168 if (!headers_sent() && debugging(NULL, DEBUG_DEVELOPER)) { // In developer debugging, the browser will barf
27f79fda 2169 $ctype = 'Content-Type: ';
2170 $prolog= "<?xml version='1.0' encoding='utf-8'?>\n";
2171
5ce73257 2172 if (isset($_SERVER['HTTP_ACCEPT'])
27f79fda 2173 && false !== strpos($_SERVER['HTTP_ACCEPT'], 'application/xhtml+xml')) {
2174 //|| false !== strpos($_SERVER['HTTP_USER_AGENT'], 'Safari') //Safari "Entity 'copy' not defined".
2175 // Firefox et al.
2176 $ctype .= 'application/xhtml+xml';
2177 $prolog .= "<!--\n DEBUG: $ctype \n-->\n";
2178
2179 } else if (file_exists($CFG->dirroot.$xsl)
2180 && preg_match('/MSIE.*Windows NT/', $_SERVER['HTTP_USER_AGENT'])) {
2181 // XSL hack for IE 5+ on Windows.
2182 //$www_xsl = preg_replace('/(http:\/\/.+?\/).*/', '', $CFG->wwwroot) .$xsl;
2183 $www_xsl = $CFG->wwwroot .$xsl;
2184 $ctype .= 'application/xml';
2185 $prolog .= "<?xml-stylesheet type='text/xsl' href='$www_xsl'?>\n";
2186 $prolog .= "<!--\n DEBUG: $ctype \n-->\n";
2187
2188 } else {
2189 //ELSE: Mac/IE, old/non-XML browsers.
2190 $ctype .= 'text/html';
2191 $prolog = '';
2192 }
2193 @header($ctype.'; charset=utf-8');
2194 $output = $prolog . $output;
2195
2196 // Test parser error-handling.
2197 if (isset($_GET['error'])) {
2198 $output .= "__ TEST: XML well-formed error < __\n";
2199 }
2200 }
8af1b1ba 2201
84dec541 2202 $output = preg_replace('/(<!DOCTYPE.+?>)/s', $strict, $output); // Always change the DOCTYPE to Strict 1.0
8af1b1ba 2203
27f79fda 2204 return $output;
2205}
2206
2207
2208
d48b00b4 2209/**
2210 * This version of print_header is simpler because the course name does not have to be
2211 * provided explicitly in the strings. It can be used on the site page as in courses
2212 * Eventually all print_header could be replaced by print_header_simple
2213 *
89dcb99d 2214 * @param string $title Appears at the top of the window
2215 * @param string $heading Appears at the top of the page
2216 * @param string $navigation Premade navigation string (for use as breadcrumbs links)
2217 * @param string $focus Indicates form element to get cursor focus on load eg inputform.password
2218 * @param string $meta Meta tags to be added to the header
2219 * @param boolean $cache Should this page be cacheable?
2220 * @param string $button HTML code for a button (usually for module editing)
2221 * @param string $menu HTML code for a popup menu
2222 * @param boolean $usexml use XML for this page
2223 * @param string $bodytags This text will be included verbatim in the <body> tag (useful for onload() etc)
36b6bcec 2224 * @param bool $return If true, return the visible elements of the header instead of echoing them.
d48b00b4 2225 */
b0ccd3fb 2226function print_header_simple($title='', $heading='', $navigation='', $focus='', $meta='',
36b6bcec 2227 $cache=true, $button='&nbsp;', $menu='', $usexml=false, $bodytags='', $return=false) {
90fcc576 2228
5ce73257 2229 global $COURSE, $CFG;
90fcc576 2230
2231 $shortname ='';
c66c2c02 2232 if ($COURSE->id != SITEID) {
9103fd10 2233 $shortname = '<a href="'.$CFG->wwwroot.'/course/view.php?id='. $COURSE->id .'">'. $COURSE->shortname .'</a> ->';
90fcc576 2234 }
2235
050c78c4 2236 $output = print_header($COURSE->shortname .': '. $title, $COURSE->fullname .' '. $heading, $shortname .' '. $navigation, $focus, $meta,
da4124be 2237 $cache, $button, $menu, $usexml, $bodytags, true);
36b6bcec 2238
2239 if ($return) {
2240 return $output;
2241 } else {
2242 echo $output;
2243 }
90fcc576 2244}
629b5885 2245
2246
d48b00b4 2247/**
2248 * Can provide a course object to make the footer contain a link to
2249 * to the course home page, otherwise the link will go to the site home
2250 *
2251 * @uses $CFG
2252 * @uses $USER
89dcb99d 2253 * @param course $course {@link $COURSE} object containing course information
2254 * @param ? $usercourse ?
d48b00b4 2255 * @todo Finish documenting this function
2256 */
469b6501 2257function print_footer($course=NULL, $usercourse=NULL, $return=false) {
dcf6d93c 2258 global $USER, $CFG, $THEME, $COURSE;
9fa49e22 2259
9fa49e22 2260/// Course links
2261 if ($course) {
a789577b 2262 if (is_string($course) && $course == 'none') { // Don't print any links etc
b3a2b9dd 2263 $homelink = '';
2264 $loggedinas = '';
0d741155 2265 $home = false;
a789577b 2266 } else if (is_string($course) && $course == 'home') { // special case for site home page - please do not remove
b3a2b9dd 2267 $course = get_site();
a77ac3dc 2268 $homelink = '<div class="sitelink">'.
244f6f32 2269 '<a title="moodle '. $CFG->release .' ('. $CFG->version .')" href="http://moodle.org/">'.
2270 '<br /><img style="width:100px;height:30px" src="pix/moodlelogo.gif" alt="moodlelogo" /></a></div>';
0d741155 2271 $home = true;
9fa49e22 2272 } else {
fa738731 2273 $homelink = '<div class="homelink"><a '.$CFG->frametarget.' href="'.$CFG->wwwroot.
a77ac3dc 2274 '/course/view.php?id='.$course->id.'">'.$course->shortname.'</a></div>';
0d741155 2275 $home = false;
9fa49e22 2276 }
2277 } else {
b3a2b9dd 2278 $course = get_site(); // Set course as site course by default
fa738731 2279 $homelink = '<div class="homelink"><a '.$CFG->frametarget.' href="'.$CFG->wwwroot.'/">'.get_string('home').'</a></div>';
0d741155 2280 $home = false;
9fa49e22 2281 }
2282
0d741155 2283/// Set up some other navigation links (passed from print_header by ugly hack)
2507b2f5 2284 $menu = isset($THEME->menu) ? str_replace('navmenu', 'navmenufooter', $THEME->menu) : '';
2285 $title = isset($THEME->title) ? $THEME->title : '';
2286 $button = isset($THEME->button) ? $THEME->button : '';
2287 $heading = isset($THEME->heading) ? $THEME->heading : '';
2288 $navigation = isset($THEME->navigation) ? $THEME->navigation : '';
2289 $navmenulist = isset($THEME->navmenulist) ? $THEME->navmenulist : '';
0d741155 2290
f940ee41 2291
b3a2b9dd 2292/// Set the user link if necessary
2293 if (!$usercourse and is_object($course)) {
1f2eec7b 2294 $usercourse = $course;
2295 }
2296
b3a2b9dd 2297 if (!isset($loggedinas)) {
2298 $loggedinas = user_login_string($usercourse, $USER);
2299 }
2300
0d741155 2301 if ($loggedinas == $menu) {
9e0d1983 2302 $menu = '';
0d741155 2303 }
2304
b8cea9b2 2305/// Provide some performance info if required
c2fd9e95 2306 $performanceinfo = '';
afd2b299 2307 if (defined('MDL_PERF') || (!empty($CFG->perfdebug) and $CFG->perfdebug > 7)) {
c2fd9e95 2308 $perf = get_performance_info();
853df85e 2309 if (defined('MDL_PERFTOLOG')) {
2310 error_log("PERF: " . $perf['txt']);
2311 }
ea82d6b6 2312 if (defined('MDL_PERFTOFOOT') || debugging() || $CFG->perfdebug > 7) {
c2fd9e95 2313 $performanceinfo = $perf['html'];
2314 }
572fe9ab 2315 }
b8cea9b2 2316
0d741155 2317
b3a2b9dd 2318/// Include the actual footer file
a282d0ff 2319
469b6501 2320 ob_start();
ea35ab87 2321 include($CFG->footer);
469b6501 2322 $output = ob_get_contents();
2323 ob_end_clean();
a9a9bdba 2324
469b6501 2325 if ($return) {
2326 return $output;
2327 } else {
2328 echo $output;
2329 }
a282d0ff 2330}
2331
c3f55692 2332/**
2333 * Returns the name of the current theme
2334 *
2335 * @uses $CFG
2336 * @param $USER
2337 * @param $SESSION
2338 * @return string
2339 */
2340function current_theme() {
9152fc99 2341 global $CFG, $USER, $SESSION, $COURSE;
c3f55692 2342
417375b7 2343 if (!empty($CFG->pagetheme)) { // Page theme is for special page-only themes set by code
2344 return $CFG->pagetheme;
c3f55692 2345
9152fc99 2346 } else if (!empty($CFG->allowcoursethemes) and !empty($COURSE->theme)) { // Course themes override others
2347 return $COURSE->theme;
c3f55692 2348
2349 } else if (!empty($SESSION->theme)) { // Session theme can override other settings
2350 return $SESSION->theme;
2351
9152fc99 2352 } else if (!empty($CFG->allowuserthemes) and !empty($USER->theme)) { // User theme can override site theme
c3f55692 2353 return $USER->theme;
2354
2355 } else {
2356 return $CFG->theme;
2357 }
2358}
2359
2360
d48b00b4 2361/**
2362 * This function is called by stylesheets to set up the header
2363 * approriately as well as the current path
2364 *
2365 * @uses $CFG
89dcb99d 2366 * @param int $lastmodified ?
2367 * @param int $lifetime ?
2368 * @param string $thename ?
d48b00b4 2369 */
55b734fb 2370function style_sheet_setup($lastmodified=0, $lifetime=300, $themename='', $forceconfig='', $lang='') {
6535be85 2371
9c4e6e21 2372 global $CFG, $THEME;
ab9f24ad 2373
a2e2bf64 2374 // Fix for IE6 caching - we don't want the filemtime('styles.php'), instead use now.
2375 $lastmodified = time();
2376
b0ccd3fb 2377 header('Last-Modified: ' . gmdate("D, d M Y H:i:s", $lastmodified) . ' GMT');
2378 header('Expires: ' . gmdate("D, d M Y H:i:s", time() + $lifetime) . ' GMT');
a2e2bf64 2379 header('Cache-Control: max-age='. $lifetime);
b0ccd3fb 2380 header('Pragma: ');
2381 header('Content-type: text/css'); // Correct MIME type
6535be85 2382
909ec807 2383 $DEFAULT_SHEET_LIST = array('styles_layout', 'styles_fonts', 'styles_color');
9c4e6e21 2384
2385 if (empty($themename)) {
2386 $themename = current_theme(); // So we have something. Normally not needed.
ab25ce31 2387 } else {
2388 $themename = clean_param($themename, PARAM_SAFEDIR);
9c4e6e21 2389 }
2390
2391 if (!empty($forceconfig)) { // Page wants to use the config from this theme instead
2392 unset($THEME);
a44091bf 2393 include($CFG->themedir.'/'.$forceconfig.'/'.'config.php');
9c4e6e21 2394 }
2395
2396/// If this is the standard theme calling us, then find out what sheets we need
2397
2398 if ($themename == 'standard') {
2399 if (!isset($THEME->standardsheets) or $THEME->standardsheets === true) { // Use all the sheets we have
2400 $THEME->sheets = $DEFAULT_SHEET_LIST;
2401 } else if (empty($THEME->standardsheets)) { // We can stop right now!
2402 echo "/***** Nothing required from this stylesheet by main theme *****/\n\n";
2403 exit;
2404 } else { // Use the provided subset only
2405 $THEME->sheets = $THEME->standardsheets;
2406 }
2407
2408/// If we are a parent theme, then check for parent definitions
2409
2410 } else if (!empty($THEME->parent) && $themename == $THEME->parent) {
2411 if (!isset($THEME->parentsheets) or $THEME->parentsheets === true) { // Use all the sheets we have
2412 $THEME->sheets = $DEFAULT_SHEET_LIST;
2413 } else if (empty($THEME->parentsheets)) { // We can stop right now!
2414 echo "/***** Nothing required from this stylesheet by main theme *****/\n\n";
2415 exit;
2416 } else { // Use the provided subset only
2417 $THEME->sheets = $THEME->parentsheets;
2418 }
2419 }
2420
2421/// Work out the last modified date for this theme
2422
2423 foreach ($THEME->sheets as $sheet) {
a44091bf 2424 if (file_exists($CFG->themedir.'/'.$themename.'/'.$sheet.'.css')) {
2425 $sheetmodified = filemtime($CFG->themedir.'/'.$themename.'/'.$sheet.'.css');
9c4e6e21 2426 if ($sheetmodified > $lastmodified) {
2427 $lastmodified = $sheetmodified;
2428 }
2429 }
6535be85 2430 }
2431
6535be85 2432
6ba172fb 2433/// Get a list of all the files we want to include
2434 $files = array();
2435
2436 foreach ($THEME->sheets as $sheet) {
2437 $files[] = array($CFG->themedir, $themename.'/'.$sheet.'.css');
2438 }
2439
2440 if ($themename == 'standard') { // Add any standard styles included in any modules
2441 if (!empty($THEME->modsheets)) { // Search for styles.php within activity modules
2442 if ($mods = get_list_of_plugins('mod')) {
2443 foreach ($mods as $mod) {
2444 if (file_exists($CFG->dirroot.'/mod/'.$mod.'/styles.php')) {
2445 $files[] = array($CFG->dirroot, '/mod/'.$mod.'/styles.php');
2446 }
08396bb2 2447 }
2448 }
2449 }
a2b3f884 2450
6ba172fb 2451 if (!empty($THEME->blocksheets)) { // Search for styles.php within block modules
2452 if ($mods = get_list_of_plugins('blocks')) {
2453 foreach ($mods as $mod) {
2454 if (file_exists($CFG->dirroot.'/blocks/'.$mod.'/styles.php')) {
2455 $files[] = array($CFG->dirroot, '/blocks/'.$mod.'/styles.php');
2456 }
08396bb2 2457 }
2458 }
2459 }
a2b3f884 2460
ae628043 2461 if (!isset($THEME->courseformatsheets) || $THEME->courseformatsheets) { // Search for styles.php in course formats
2462 if ($mods = get_list_of_plugins('format','',$CFG->dirroot.'/course')) {
2463 foreach ($mods as $mod) {
2464 if (file_exists($CFG->dirroot.'/course/format/'.$mod.'/styles.php')) {
2465 $files[] = array($CFG->dirroot, '/course/format/'.$mod.'/styles.php');
2466 }
2467 }
2468 }
2469 }
2470
6ba172fb 2471 if (!empty($THEME->langsheets)) { // Search for styles.php within the current language
6ba172fb 2472 if (file_exists($CFG->dirroot.'/lang/'.$lang.'/styles.php')) {
2473 $files[] = array($CFG->dirroot, '/lang/'.$lang.'/styles.php');
2474 }
2475 }
08396bb2 2476 }
2477
6ba172fb 2478
2479 if ($files) {
2480 /// Produce a list of all the files first
2481 echo '/**************************************'."\n";
2482 echo ' * THEME NAME: '.$themename."\n *\n";
2483 echo ' * Files included in this sheet:'."\n *\n";
2484 foreach ($files as $file) {
2485 echo ' * '.$file[1]."\n";
08396bb2 2486 }
6ba172fb 2487 echo ' **************************************/'."\n\n";
08396bb2 2488
6ba172fb 2489
16f0af59 2490 /// check if csscobstants is set
2491 if (!empty($THEME->cssconstants)) {
2492 require_once("$CFG->libdir/cssconstants.php");
2493 /// Actually collect all the files in order.
2494 $css = '';
2495 foreach ($files as $file) {
2496 $css .= '/***** '.$file[1].' start *****/'."\n\n";
2497 $css .= file_get_contents($file[0].'/'.$file[1]);
2498 $ccs .= '/***** '.$file[1].' end *****/'."\n\n";
2499 }
2500 /// replace css_constants with their values
2501 echo replace_cssconstants($css);
2502 } else {
2503 /// Actually output all the files in order.
2504 foreach ($files as $file) {
2505 echo '/***** '.$file[1].' start *****/'."\n\n";
2506 @include_once($file[0].'/'.$file[1]);
2507 echo '/***** '.$file[1].' end *****/'."\n\n";
2508 }
6ba172fb 2509 }
9c4e6e21 2510 }
2511
a44091bf 2512 return $CFG->themewww.'/'.$themename; // Only to help old themes (1.4 and earlier)
6535be85 2513}
2514
9c4e6e21 2515
2516function theme_setup($theme = '', $params=NULL) {
d74d4f20 2517/// Sets up global variables related to themes
2518
9152fc99 2519 global $CFG, $THEME, $SESSION, $USER, $HTTPSPAGEREQUIRED;
d74d4f20 2520
2521 if (empty($theme)) {
2522 $theme = current_theme();
2523 }
9c4e6e21 2524
09ad59dc 2525/// If the theme doesn't exist for some reason then revert to standardwhite
a44091bf 2526 if (!file_exists($CFG->themedir .'/'. $theme .'/config.php')) {
09ad59dc 2527 $CFG->theme = $theme = 'standardwhite';
2528 }
2529
55b734fb 2530/// Load up the theme config
2531 $THEME = NULL; // Just to be sure
a44091bf 2532 include($CFG->themedir .'/'. $theme .'/config.php'); // Main config for current theme
55b734fb 2533
9c4e6e21 2534/// Put together the parameters
2535 if (!$params) {
2536 $params = array();
2537 }
56766f85 2538 if ($theme != $CFG->theme) {
2539 $params[] = 'forceconfig='.$theme;
9c4e6e21 2540 }
55b734fb 2541
2542/// Force language too if required
2543 if (!empty($THEME->langsheets)) {
2544 $params[] = 'lang='.current_language();
2545 }
2546
2547/// Convert params to string
9c4e6e21 2548 if ($params) {
55b734fb 2549 $paramstring = '?'.implode('&', $params);
d74d4f20 2550 } else {
9c4e6e21 2551 $paramstring = '';
d74d4f20 2552 }
2553
9c4e6e21 2554/// Set up image paths
25580407 2555 if (empty($THEME->custompix)) { // Could be set in the above file
d74d4f20 2556 $CFG->pixpath = $CFG->wwwroot .'/pix';
2557 $CFG->modpixpath = $CFG->wwwroot .'/mod';
2558 } else {
a44091bf 2559 $CFG->pixpath = $CFG->themewww .'/'. $theme .'/pix';
2560 $CFG->modpixpath = $CFG->themewww .'/'. $theme .'/pix/mod';
d74d4f20 2561 }
2562
9c4e6e21 2563/// Header and footer paths
a44091bf 2564 $CFG->header = $CFG->themedir .'/'. $theme .'/header.html';
2565 $CFG->footer = $CFG->themedir .'/'. $theme .'/footer.html';
d74d4f20 2566
9c4e6e21 2567/// Define stylesheet loading order
d74d4f20 2568 $CFG->stylesheets = array();
2569 if ($theme != 'standard') { /// The standard sheet is always loaded first
a44091bf 2570 $CFG->stylesheets[] = $CFG->themewww.'/standard/styles.php'.$paramstring;
d74d4f20 2571 }
2572 if (!empty($THEME->parent)) { /// Parent stylesheets are loaded next
a44091bf 2573 $CFG->stylesheets[] = $CFG->themewww.'/'.$THEME->parent.'/styles.php'.$paramstring;
d74d4f20 2574 }
a44091bf 2575 $CFG->stylesheets[] = $CFG->themewww.'/'.$theme.'/styles.php'.$paramstring;
d74d4f20 2576
9152fc99 2577/// We have to change some URLs in styles if we are in a $HTTPSPAGEREQUIRED page
2578 if (!empty($HTTPSPAGEREQUIRED)) {
2579 $CFG->themewww = str_replace('http:', 'https:', $CFG->themewww);
2580 $CFG->pixpath = str_replace('http:', 'https:', $CFG->pixpath);
2581 $CFG->modpixpath = str_replace('http:', 'https:', $CFG->modpixpath);
2582 foreach ($CFG->stylesheets as $key => $stylesheet) {
2583 $CFG->stylesheets[$key] = str_replace('http:', 'https:', $stylesheet);
2584 }
2585 }
2586
d74d4f20 2587}
2588
c3f55692 2589
d48b00b4 2590/**
2591 * Returns text to be displayed to the user which reflects their login status
2592 *
2593 * @uses $CFG
2594 * @uses $USER
89dcb99d 2595 * @param course $course {@link $COURSE} object containing course information
2596 * @param user $user {@link $USER} object containing user information
2597 * @return string
d48b00b4 2598 */
c44d5d42 2599function user_login_string($course=NULL, $user=NULL) {
2600 global $USER, $CFG, $SITE;
a282d0ff 2601
86a1ba04 2602 if (empty($user) and !empty($USER->id)) {
a282d0ff 2603 $user = $USER;
2604 }
2605
c44d5d42 2606 if (empty($course)) {
2607 $course = $SITE;
2608 }
2609
a282d0ff 2610 if (isset($user->realuser)) {
b0ccd3fb 2611 if ($realuser = get_record('user', 'id', $user->realuser)) {
2d71e8ee 2612 $fullname = fullname($realuser, true);
fa738731 2613 $realuserinfo = " [<a $CFG->frametarget
01eb4f5f 2614 href=\"$CFG->wwwroot/course/loginas.php?id=$course->id&amp;return=1\">$fullname</a>] ";
9fa49e22 2615 }
9d378732 2616 } else {
b0ccd3fb 2617 $realuserinfo = '';
9fa49e22 2618 }
2619
87180677 2620 if (empty($CFG->loginhttps)) {
2621 $wwwroot = $CFG->wwwroot;
2622 } else {
2c3432e6 2623 $wwwroot = str_replace('http:','https:',$CFG->wwwroot);
87180677 2624 }
2625
8743f4f3 2626 if (empty($course->id)) {
2627 // $course->id is not defined during installation
2628 return '';
5ce73257 2629 } else if (isset($user->id) and $user->id) {
2d07587b 2630 $context = get_context_instance(CONTEXT_COURSE, $course->id);
2631
2d71e8ee 2632 $fullname = fullname($user, true);
fa738731 2633 $username = "<a $CFG->frametarget href=\"$CFG->wwwroot/user/view.php?id=$user->id&amp;course=$course->id\">$fullname</a>";
03d820c7 2634 if (is_mnet_remote_user($user) and $idprovider = get_record('mnet_host', 'id', $user->mnethostid)) {
fa738731 2635 $username .= " from <a $CFG->frametarget href=\"{$idprovider->wwwroot}\">{$idprovider->name}</a>";
03d820c7 2636 }
8f8ed475 2637 if (isset($user->username) && $user->username == 'guest') {
158de846 2638 $loggedinas = $realuserinfo.get_string('loggedinasguest').
fa738731 2639 " (<a $CFG->frametarget href=\"$wwwroot/login/index.php\">".get_string('login').'</a>)';
2d07587b 2640 } else if (!empty($user->switchrole[$context->id])) {
91ea292e 2641 $rolename = '';
2d07587b 2642 if ($role = get_record('role', 'id', $user->switchrole[$context->id])) {
91ea292e 2643 $rolename = ': '.format_string($role->name);
2644 }
2645 $loggedinas = get_string('loggedinas', 'moodle', $username).$rolename.
fa738731 2646 " (<a $CFG->frametarget
91ea292e 2647 href=\"$CFG->wwwroot/course/view.php?id=$course->id&amp;switchrole=0&amp;sesskey=".sesskey()."\">".get_string('switchrolereturn').'</a>)';
0ae7e6f4 2648 } else {
d5a01638 2649 $loggedinas = $realuserinfo.get_string('loggedinas', 'moodle', $username).' '.
fa738731 2650 " (<a $CFG->frametarget href=\"$CFG->wwwroot/login/logout.php\">".get_string('logout').'</a>)';
0ae7e6f4 2651 }
9fa49e22 2652 } else {
b0ccd3fb 2653 $loggedinas = get_string('loggedinnot', 'moodle').
fa738731 2654 " (<a $CFG->frametarget href=\"$wwwroot/login/index.php\">".get_string('login').'</a>)';
9fa49e22 2655 }
d3593a67 2656 return '<div class="logininfo">'.$loggedinas.'</div>';
9fa49e22 2657}
2658
d48b00b4 2659/**
57100a90 2660 * Tests whether $THEME->rarrow, $THEME->larrow have been set (theme/-/config.php).
2661 * If not it applies sensible defaults.
d48b00b4 2662 *
57100a90 2663 * Accessibility: right and left arrow Unicode characters for breadcrumb, calendar,
5ce73257 2664 * search forum block, etc. Important: these are 'silent' in a screen-reader
57100a90 2665 * (unlike &gt; &raquo;), and must be accompanied by text.
2666 * @uses $THEME
d48b00b4 2667 */
57100a90 2668function check_theme_arrows() {
2669 global $THEME;
5ce73257 2670
57100a90 2671 if (!isset($THEME->rarrow) and !isset($THEME->larrow)) {
ce27e6f4 2672 // Default, looks good in Win XP/IE 6, Win/Firefox 1.5, Win/Netscape 8...
2673 // Also OK in Win 9x/2K/IE 5.x
57100a90 2674 $THEME->rarrow = '&#x25BA;';
2675 $THEME->larrow = '&#x25C4;';
ce27e6f4 2676 $uagent = $_SERVER['HTTP_USER_AGENT'];
2677 if (false !== strpos($uagent, 'Opera')
2678 || false !== strpos($uagent, 'Mac')) {
2679 // Looks good in Win XP/Mac/Opera 8/9, Mac/Firefox 2, Camino, Safari.
2680 // Not broken in Mac/IE 5, Mac/Netscape 7 (?).
57100a90 2681 $THEME->rarrow = '&#x25B6;';
2682 $THEME->larrow = '&#x25C0;';
ce27e6f4 2683 }
2684 elseif (false !== strpos($uagent, 'Konqueror')) {
2685 $THEME->rarrow = '&rarr;';
2686 $THEME->larrow = '&larr;';
2687 }
2688 elseif (isset($_SERVER['HTTP_ACCEPT_CHARSET'])
2689 && false === stripos($_SERVER['HTTP_ACCEPT_CHARSET'], 'utf-8')) {
2690 // (Win/IE 5 doesn't set ACCEPT_CHARSET, but handles Unicode.)
2691 // To be safe, non-Unicode browsers!
2692 $THEME->rarrow = '&gt;';
2693 $THEME->larrow = '&lt;';
2694 }
57100a90 2695 }
2696}
da4124be 2697
57100a90 2698/**
2699 * Prints breadcrumb trail of links, called in theme/-/header.html
2700 *
2701 * @uses $CFG
2702 * @param string $navigation The breadcrumb navigation string to be printed
2703 * @param string $separator The breadcrumb trail separator. The default 0 leads to the use
2704 * of $THEME->rarrow, themes could use '&rarr;', '/', or '' for a style-sheet solution.
2705 * @param boolean $return False to echo the breadcrumb string (default), true to return it.
2706 */
2707function print_navigation ($navigation, $separator=0, $return=false) {
2708 global $CFG, $THEME;
da4124be 2709 $output = '';
5ce73257 2710
57100a90 2711 check_theme_arrows();
2712 if (0 === $separator) {
2713 $separator = $THEME->rarrow;
2714 }
2715 if (!empty($separator)) {
2716 $separator = '<span class="sep">'. $separator .'</span>';
2717 }
da4124be 2718
2719 if ($navigation) {
57100a90 2720 //Accessibility: breadcrumb links now in a list, &raquo; replaced with a 'silent' character.
da4124be 2721 $nav_text = get_string('youarehere','access');
57100a90 2722 $output .= '<h2 class="accesshide">'.$nav_text."</h2><ul>\n";
da4124be 2723 if (! $site = get_site()) {
2724 $site->shortname = get_string('home');
2725 }
57100a90 2726 $navigation = "<li>$separator ". str_replace('->', "</li>\n<li>$separator", $navigation) ."</li>\n";
fa738731 2727 $output .= '<li class="first"><a '.$CFG->frametarget.' href="'. $CFG->wwwroot.((!has_capability('moodle/site:config', get_context_instance(CONTEXT_SYSTEM, SITEID)) && !empty($USER->id) && !empty($CFG->mymoodleredirect) && !isguest())
9a477f90 2728 ? '/my' : '') .'/">'. $site->shortname ."</a></li>\n". $navigation;
5ce73257 2729 $output .= "</ul>\n";
da4124be 2730 }
2731
2732 if ($return) {
2733 return $output;
2734 } else {
2735 echo $output;
2736 }
9fa49e22 2737}
2738
d48b00b4 2739/**
bfca0094 2740 * Prints a string in a specified size (retained for backward compatibility)
d48b00b4 2741 *
89dcb99d 2742 * @param string $text The text to be displayed
2743 * @param int $size The size to set the font for text display.
d48b00b4 2744 */
da4124be 2745function print_headline($text, $size=2, $return=false) {
593bc22b 2746 $output = print_heading($text, '', $size, true);
da4124be 2747 if ($return) {
2748 return $output;
2749 } else {
2750 echo $output;
2751 }
d4df9200 2752}
2753
d48b00b4 2754/**
2755 * Prints text in a format for use in headings.
2756 *
89dcb99d 2757 * @param string $text The text to be displayed
2758 * @param string $align The alignment of the printed paragraph of text
2759 * @param int $size The size to set the font for text display.
d48b00b4 2760 */
da4124be 2761function print_heading($text, $align='', $size=2, $class='main', $return=false) {
bfca0094 2762 if ($align) {
fc9cb24a 2763 $align = ' style="text-align:'.$align.';"';
bfca0094 2764 }
4419aa80 2765 if ($class) {
2766 $class = ' class="'.$class.'"';
2767 }
da4124be 2768 $output = "<h$size $align $class>".stripslashes_safe($text)."</h$size>";
2769
2770 if ($return) {
2771 return $output;
2772 } else {
2773 echo $output;
2774 }
9fa49e22 2775}
2776
d48b00b4 2777/**
2778 * Centered heading with attached help button (same title text)
2779 * and optional icon attached
2780 *
89dcb99d 2781 * @param string $text The text to be displayed
2782 * @param string $helppage The help page to link to
2783 * @param string $module The module whose help should be linked to
2784 * @param string $icon Image to display if needed
d48b00b4 2785 */
da4124be 2786function print_heading_with_help($text, $helppage, $module='moodle', $icon='', $return=false) {
2787 $output = '';
2788 $output .= '<h2 class="main help">'.$icon.stripslashes_safe($text);
2789 $output .= helpbutton($helppage, $text, $module, true, false, '', true);
2790 $output .= '</h2>';
2791
2792 if ($return) {
2793 return $output;
2794 } else {
2795 echo $output;
2796 }
9fa49e22 2797}
ab9f24ad 2798
6ee8277f 2799
da4124be 2800function print_heading_block($heading, $class='', $return=false) {
b6f30b18 2801 //Accessibility: 'headingblock' is now H1, see theme/standard/styles_*.css: ??
da4124be 2802 $output = '<h2 class="headingblock header '.$class.'">'.stripslashes($heading).'</h2>';
2803
2804 if ($return) {
2805 return $output;
2806 } else {
2807 echo $output;
2808 }
6ee8277f 2809}
2810
2811
d48b00b4 2812/**
2813 * Print a link to continue on to another page.
2814 *
2815 * @uses $CFG
2816 * @param string $link The url to create a link to.
2817 */
da4124be 2818function print_continue($link, $return=false) {
9fa49e22 2819
51a96819 2820 global $CFG;
2821
dedb2304 2822 // in case we are logging upgrade in admin/index.php stop it
2823 if (function_exists('upgrade_log_finish')) {
2824 upgrade_log_finish();
2825 }
2826
da4124be 2827 $output = '';
2828
e1968a8e 2829 if ($link == '') {
2830 if (!empty($_SERVER['HTTP_REFERER'])) {
2831 $link = $_SERVER['HTTP_REFERER'];
2832 $link = str_replace('&', '&amp;', $link); // make it valid XHTML
2833 } else {
2834 $link = $CFG->wwwroot .'/';
2835 }
9fa49e22 2836 }
2837
da4124be 2838 $output .= '<div class="continuebutton">';
c35e8b1c 2839
da4124be 2840 $output .= print_single_button($link, NULL, get_string('continue'), 'post', $CFG->framename, true);
2841 $output .= '</div>'."\n";
2842
2843 if ($return) {
2844 return $output;
2845 } else {
2846 echo $output;
2847 }
9fa49e22 2848}
2849
2123b644 2850
d48b00b4 2851/**
2852 * Print a message in a standard themed box.
2123b644 2853 * Replaces print_simple_box (see deprecatedlib.php)
d48b00b4 2854 *
2123b644 2855 * @param string $message, the content of the box
f79aa892 2856 * @param string $classes, space-separated class names.
2857 * @param string $ids, space-separated id names.
2123b644 2858 * @param boolean $return, return as string or just print it
d48b00b4 2859 */
f79aa892 2860function print_box($message, $classes='generalbox', $ids='', $return=false) {
2123b644 2861
f79aa892 2862 $output = print_box_start($classes, $ids, true);
da4124be 2863 $output .= stripslashes_safe($message);
2123b644 2864 $output .= print_box_end(true);
da4124be 2865
2866 if ($return) {
2867 return $output;
2868 } else {
2869 echo $output;
2870 }
9fa49e22 2871}
2872
e1968a8e 2873/**
2123b644 2874 * Starts a box using divs
2875 * Replaces print_simple_box_start (see deprecatedlib.php)
408b65dd 2876 *
f79aa892 2877 * @param string $classes, space-separated class names.
2878 * @param string $ids, space-separated id names.
2123b644 2879 * @param boolean $return, return as string or just print it
d48b00b4 2880 */
f79aa892 2881function print_box_start($classes='generalbox', $ids='', $return=false) {
da4124be 2882 $output = '';
9fa49e22 2883
f79aa892 2884 if ($ids) {
2885 $ids = ' id="'.$ids.'"';
30c9e694 2886 }
593bc22b 2887
8f36e33e 2888 $output .= '<div'.$ids.' class="box '.$classes.'">';
da4124be 2889
2890 if ($return) {
2891 return $output;
2892 } else {
2893 echo $output;
2894 }
9fa49e22 2895}
2896
2123b644 2897
e1968a8e 2898/**
2123b644 2899 * Simple function to end a box (see above)
2900 * Replaces print_simple_box_end (see deprecatedlib.php)
2901 *
2902 * @param boolean $return, return as string or just print it
d48b00b4 2903 */
2123b644 2904function print_box_end($return=false) {
df26dd34 2905 $output = '</div>';
da4124be 2906 if ($return) {
2907 return $output;
2908 } else {
2909 echo $output;
2910 }
9fa49e22 2911}
2912
30c9e694 2913
d48b00b4 2914/**
2915 * Print a self contained form with a single submit button.
2916 *
89dcb99d 2917 * @param string $link ?
2918 * @param array $options ?
2919 * @param string $label ?
2920 * @param string $method ?
d48b00b4 2921 * @todo Finish documenting this function
2922 */
da4124be 2923function print_single_button($link, $options, $label='OK', $method='get', $target='_self', $return=false) {
2924 $output = '';
2463ef81 2925 $link = str_replace('"', '&quot;', $link); //basic XSS protection
da4124be 2926 $output .= '<div class="singlebutton">';
64888fc1 2927 // taking target out, will need to add later target="'.$target.'"
2463ef81 2928 $output .= '<form action="'. $link .'" method="'. $method .'">';
64888fc1 2929 $output .= '<fieldset class="invisiblefieldset">';
9fa49e22 2930 if ($options) {
2931 foreach ($options as $name => $value) {
e1968a8e 2932 $output .= '<input type="hidden" name="'. $name .'" value="'. s($value) .'" />';
9fa49e22 2933 }
2934 }
e1968a8e 2935 $output .= '<input type="submit" value="'. s($label) .'" /></fieldset></form></div>';
da4124be 2936
2937 if ($return) {
2938 return $output;
2939 } else {
2940 echo $output;
2941 }
9fa49e22 2942}
2943
2123b644 2944
d48b00b4 2945/**
2946 * Print a spacer image with the option of including a line break.
2947 *
89dcb99d 2948 * @param int $height ?
2949 * @param int $width ?
2950 * @param boolean $br ?
d48b00b4 2951 * @todo Finish documenting this function
2952 */
da4124be 2953function print_spacer($height=1, $width=1, $br=true, $return=false) {
9fa49e22 2954 global $CFG;
da4124be 2955 $output = '';
2956
2957 $output .= '<img class="spacer" height="'. $height .'" width="'. $width .'" src="'. $CFG->wwwroot .'/pix/spacer.gif" alt="" />';
9fa49e22 2958 if ($br) {
da4124be 2959 $output .= '<br />'."\n";
2960 }
2961
2962 if ($return) {
2963 return $output;
2964 } else {
2965 echo $output;
9fa49e22 2966 }
2967}
2968
d48b00b4 2969/**
2970 * Given the path to a picture file in a course, or a URL,
2971 * this function includes the picture in the page.
2972 *
89dcb99d 2973 * @param string $path ?
2974 * @param int $courseid ?
2975 * @param int $height ?
2976 * @param int $width ?
2977 * @param string $link ?
d48b00b4 2978 * @todo Finish documenting this function
2979 */
da4124be 2980function print_file_picture($path, $courseid=0, $height='', $width='', $link='', $return=false) {
9fa49e22 2981 global $CFG;
da4124be 2982 $output = '';
9fa49e22 2983
2984 if ($height) {
b0ccd3fb 2985 $height = 'height="'. $height .'"';
9fa49e22 2986 }
2987 if ($width) {
b0ccd3fb 2988 $width = 'width="'. $width .'"';
9fa49e22 2989 }
2990 if ($link) {
da4124be 2991 $output .= '<a href="'. $link .'">';
9fa49e22 2992 }
b0ccd3fb 2993 if (substr(strtolower($path), 0, 7) == 'http://') {
7cd2f598 2994 $output .= '<img style="height:'.$height.'px;width:'.$width.'px;" src="'. $path .'" />';
9fa49e22 2995
2996 } else if ($courseid) {
7cd2f598 2997 $output .= '<img style="height:'.$height.'px;width:'.$width.'px;" src="';
9fa49e22 2998 if ($CFG->slasharguments) { // Use this method if possible for better caching
da4124be 2999 $output .= $CFG->wwwroot .'/file.php/'. $courseid .'/'. $path;
9fa49e22 3000 } else {
da4124be 3001 $output .= $CFG->wwwroot .'/file.php?file=/'. $courseid .'/'. $path;
9fa49e22 3002 }
da4124be 3003 $output .= '" />';
9fa49e22 3004 } else {
da4124be 3005 $output .= 'Error: must pass URL or course';
9fa49e22 3006 }
3007 if ($link) {
da4124be 3008 $output .= '</a>';
3009 }
3010
3011 if ($return) {
3012 return $output;
3013 } else {
3014 echo $output;
9fa49e22 3015 }
3016}
3017
d48b00b4 3018/**
3019 * Print the specified user's avatar.
3020 *
89dcb99d 3021 * @param int $userid ?
3022 * @param int $courseid ?
3023 * @param boolean $picture Print the user picture?
4c6c0e01 3024 * @param int $size Size in pixels. Special values are (true/1 = 100px) and (false/0 = 35px) for backward compatability
da4124be 3025 * @param boolean $return If false print picture to current page, otherwise return the output as string
89dcb99d 3026 * @param boolean $link Enclose printed image in a link to view specified course?
953eb6f3 3027 * @param string $target link target attribute
3028 * @param boolean $alttext use username or userspecified text in image alt attribute
89dcb99d 3029 * return string
d48b00b4 3030 * @todo Finish documenting this function
3031 */
953eb6f3 3032function print_user_picture($userid, $courseid, $picture, $size=0, $return=false, $link=true, $target='', $alttext=true) {
f374fb10 3033 global $CFG;
9fa49e22 3034
3035 if ($link) {
f66e1977 3036 if ($target) {
3037 $target=' target="_blank"';
3038 }
3039 $output = '<a '.$target.' href="'. $CFG->wwwroot .'/user/view.php?id='. $userid .'&amp;course='. $courseid .'">';
9fa49e22 3040 } else {
b0ccd3fb 3041 $output = '';
9fa49e22 3042 }
4c6c0e01 3043 if (empty($size)) {
3044 $file = 'f2';
da7a785b 3045 $size = 35;
4c6c0e01 3046 } else if ($size === true or $size == 1) {
b0ccd3fb 3047 $file = 'f1';
9fa49e22 3048 $size = 100;
4c6c0e01 3049 } else if ($size >= 50) {
3050 $file = 'f1';
9fa49e22 3051 } else {
b0ccd3fb 3052 $file = 'f2';
9fa49e22 3053 }
113a79e2 3054 $class = "userpicture";
67a63a30 3055 if ($picture) { // Print custom user picture
9fa49e22 3056 if ($CFG->slasharguments) { // Use this method if possible for better caching
c1138797 3057 $src = $CFG->wwwroot .'/user/pix.php/'. $userid .'/'. $file .'.jpg';
9fa49e22 3058 } else {
c1138797 3059 $src = $CFG->wwwroot .'/user/pix.php?file=/'. $userid .'/'. $file .'.jpg';
9fa49e22 3060 }
67a63a30 3061 } else { // Print default user pictures (use theme version if available)
113a79e2 3062 $class .= " defaultuserpic";
adc5f292 3063 $src = "$CFG->pixpath/u/$file.png";
9fa49e22 3064 }
ad6226fb 3065 $imagealt = '';
3066 if ($alttext and $user = get_record('user','id',$userid)) {
5a86df5e 3067 if (!empty($user->imagealt)) {
3068 $imagealt = $user->imagealt;
3069 } else {
3070 $imagealt = get_string('pictureof','',fullname($user));
5ce73257 3071 }
2bbaf749 3072 }
953eb6f3 3073
adc5f292 3074 $output .= '<img class="'.$class.'" src="'.$src.'" alt="'.s($imagealt).'" />';
9fa49e22 3075 if ($link) {
b0ccd3fb 3076 $output .= '</a>';
9fa49e22 3077 }
3078
da4124be 3079 if ($return) {
9fa49e22 3080 return $output;
3081 } else {
3082 echo $output;
3083 }
3084}
3085
d48b00b4 3086/**
3087 * Prints a summary of a user in a nice little box.
3088 *
89dcb99d 3089 * @uses $CFG
3090 * @uses $USER
3091 * @param user $user A {@link $USER} object representing a user
3092 * @param course $course A {@link $COURSE} object representing a course
d48b00b4 3093 */
da4124be 3094function print_user($user, $course, $messageselect=false, $return=false) {
951b22a8 3095
89dcb99d 3096 global $CFG, $USER;
499795e8 3097
da4124be 3098 $output = '';
3099
951b22a8 3100 static $string;
3101 static $datestring;
3102 static $countries;
951b22a8 3103
ec7a8b79 3104 $context = get_context_instance(CONTEXT_COURSE, $course->id);
04186cd9 3105
951b22a8 3106 if (empty($string)) { // Cache all the strings for the rest of the page
3107
b0ccd3fb 3108 $string->email = get_string('email');
3109 $string->location = get_string('location');
3110 $string->lastaccess = get_string('lastaccess');
3111 $string->activity = get_string('activity');
3112 $string->unenrol = get_string('unenrol');
3113 $string->loginas = get_string('loginas');
3114 $string->fullprofile = get_string('fullprofile');
3115 $string->role = get_string('role');
3116 $string->name = get_string('name');
3117 $string->never = get_string('never');
3118
3119 $datestring->day = get_string('day');
3120 $datestring->days = get_string('days');
3121 $datestring->hour = get_string('hour');
3122 $datestring->hours = get_string('hours');
3123 $datestring->min = get_string('min');
3124 $datestring->mins = get_string('mins');
3125 $datestring->sec = get_string('sec');
3126 $datestring->secs = get_string('secs');
951b22a8 3127
3128 $countries = get_list_of_countries();
951b22a8 3129 }
3130
3468d58a 3131/// Get the hidden field list
04186cd9 3132 if (has_capability('moodle/course:viewhiddenuserfields', $context)) {
3468d58a 3133 $hiddenfields = array();
3134 } else {
3135 $hiddenfields = array_flip(explode(',', $CFG->hiddenuserfields));
3136 }
3137
da4124be 3138 $output .= '<table class="userinfobox">';
3139 $output .= '<tr>';
3140 $output .= '<td class="left side">';
3141 $output .= print_user_picture($user->id, $course->id, $user->picture, true, true);
3142 $output .= '</td>';
3143 $output .= '<td class="content">';
ec7a8b79 3144 $output .= '<div class="username">'.fullname($user, has_capability('moodle/site:viewfullnames', $context)).'</div>';
da4124be 3145 $output .= '<div class="info">';
951b22a8 3146 if (!empty($user->role) and ($user->role <> $course->teacher)) {
da4124be 3147 $output .= $string->role .': '. $user->role .'<br />';
951b22a8 3148 }
1936c10e 3149 if ($user->maildisplay == 1 or ($user->maildisplay == 2 and ($course->id != SITEID) and !isguest()) or
04186cd9 3150has_capability('moodle/course:viewhiddenuserfields', $context)) {
da4124be 3151 $output .= $string->email .': <a href="mailto:'. $user->email .'">'. $user->email .'</a><br />';
951b22a8 3152 }
3468d58a 3153 if (($user->city or $user->country) and (!isset($hiddenfields['city']) or !isset($hiddenfields['country']))) {
da4124be 3154 $output .= $string->location .': ';
3468d58a 3155 if ($user->city && !isset($hiddenfields['city'])) {
da4124be 3156 $output .= $user->city;
b40bc478 3157 }
3468d58a 3158 if (!empty($countries[$user->country]) && !isset($hiddenfields['country'])) {
3159 if ($user->city && !isset($hiddenfields['city'])) {
da4124be 3160 $output .= ', ';
b40bc478 3161 }
da4124be 3162 $output .= $countries[$user->country];
b40bc478 3163 }
da4124be 3164 $output .= '<br />';
951b22a8 3165 }
ae8a5ff0 3166
3468d58a 3167 if (!isset($hiddenfields['lastaccess'])) {
3168 if ($user->lastaccess) {
da4124be 3169 $output .= $string->lastaccess .': '. userdate($user->lastaccess);
18894ee4 3170 $output .= '&nbsp; ('. format_time(time() - $user->lastaccess, $datestring) .')';
3468d58a 3171 } else {
da4124be 3172 $output .= $string->lastaccess .': '. $string->never;
3468d58a 3173 }
951b22a8 3174 }
da4124be 3175 $output .= '</div></td><td class="links">';
ae8a5ff0 3176 //link to blogs
b7425e2e 3177 if ($CFG->bloglevel > 0) {
da4124be 3178 $output .= '<a href="'.$CFG->wwwroot.'/blog/index.php?userid='.$user->id.'">'.get_string('blogs','blog').'</a><br />';
b7425e2e 3179 }
da4124be 3180
04186cd9 3181 if (has_capability('moodle/site:viewreports', $context)) {
951b22a8 3182 $timemidnight = usergetmidnight(time());
da4124be 3183 $output .= '<a href="'. $CFG->wwwroot .'/course/user.php?id='. $course->id .'&amp;user='. $user->id .'">'. $string->activity .'</a><br />';
04186cd9 3184 }
3185 if (has_capability('moodle/role:assign', $context, NULL)) { // Includes admins
3186 $output .= '<a href="'. $CFG->wwwroot .'/course/unenrol.php?id='. $course->id .'&amp;user='. $user->id .'">'. $string->unenrol .'</a><br />';
3187 }
3188 if ($USER->id != $user->id && has_capability('moodle/user:loginas', $context)) {
3189 $output .= '<a href="'. $CFG->wwwroot .'/course/loginas.php?id='. $course->id .'&amp;user='. $user->id .'">'. $string->loginas .'</a><br />';
ab9f24ad 3190 }
da4124be 3191 $output .= '<a href="'. $CFG->wwwroot .'/user/view.php?id='. $user->id .'&amp;course='. $course->id .'">'. $string->fullprofile .'...</a>';
951b22a8 3192
04186cd9 3193 if (!empty($messageselect)) {
3194 $output .= '<br /><input type="checkbox" name="user'.$user->id.'" /> ';
f19570d0 3195 }
3196
da4124be 3197 $output .= '</td></tr></table>';
3198
3199 if ($return) {
3200 return $output;
3201 } else {
3202 echo $output;
3203 }
951b22a8 3204}
3205
d48b00b4 3206/**
3207 * Print a specified group's avatar.
3208 *
fdcd0f05 3209 * @param group $group A {@link group} object representing a group or array of groups
89dcb99d 3210 * @param int $courseid ?
3211 * @param boolean $large ?
da4124be 3212 * @param boolean $return ?
89dcb99d 3213 * @param boolean $link ?
3214 * @return string
d48b00b4 3215 * @todo Finish documenting this function
3216 */
da4124be 3217function print_group_picture($group, $courseid, $large=false, $return=false, $link=true) {
f374fb10 3218 global $CFG;
3219
fdcd0f05 3220 if (is_array($group)) {
3221 $output = '';
3222 foreach($group as $g) {
3223 $output .= print_group_picture($g, $courseid, $large, true, $link);
3224 }
da4124be 3225 if ($return) {
fdcd0f05 3226 return $output;
3227 } else {
3228 echo $output;
3229 return;
3230 }
3231 }
3232
ec7a8b79 3233 $context = get_context_instance(CONTEXT_COURSE, $courseid);
97ea4833 3234
ec7a8b79 3235 if ($group->hidepicture and !has_capability('moodle/course:managegroups', $context)) {
3c0561cf 3236 return '';
3237 }
c3cbfe7f 3238
ec7a8b79 3239 if ($link or has_capability('moodle/site:accessallgroups', $context)) {
a756cf1d 3240 $output = '<a href="'. $CFG->wwwroot .'/user/index.php?id='. $courseid .'&amp;group='. $group->id .'">';
3c0561cf 3241 } else {
3242 $output = '';
3243 }
3244 if ($large) {
b0ccd3fb 3245 $file = 'f1';
3c0561cf