MDL-8096 - user edit form splitting, refactoring, cleanup and fixing - work in progre...
[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
ab9f24ad 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)) {
8eaa4c61 1196 if (!empty($course->id)) { // An ugly hack for better compatibility
c4ae4fa1 1197 $courseid = $course->id;
1198 }
1199 }
a751a4e5 1200
a17c57b5 1201 if (!empty($CFG->cachetext) and empty($options->nocache)) {
e7a47153 1202 $time = time() - $CFG->cachetext;
90bbe689 1203 $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 1204 if ($oldcacheitem = get_record_sql('SELECT * FROM '.$CFG->prefix.'cache_text WHERE md5key = \''.$md5key.'\'', true)) {
1205 if ($oldcacheitem->timemodified >= $time) {
1206 return $oldcacheitem->formattedtext;
1207 }
e7a47153 1208 }
1209 }
1210
7d8a3cb0 1211 // trusttext overrides the noclean option!
1212 if ($options->trusttext) {
1213 if (trusttext_present($text)) {
1214 $text = trusttext_strip($text);
1215 if (!empty($CFG->enabletrusttext)) {
1216 $options->noclean = true;
1217 } else {
1218 $options->noclean = false;
1219 }
1220 } else {
1221 $options->noclean = false;
1222 }
d53ca6ad 1223 } else if (!debugging('', DEBUG_DEVELOPER)) {
1224 // strip any forgotten trusttext in non-developer mode
1225 // do not forget to disable text cache when debugging trusttext!!
1226 $text = trusttext_strip($text);
7d8a3cb0 1227 }
1228
8eaa4c61 1229 $CFG->currenttextiscacheable = true; // Default status - can be changed by any filter
c06c8492 1230
0095d5cd 1231 switch ($format) {
73f8658c 1232 case FORMAT_HTML:
7d8a3cb0 1233 if ($options->smiley) {
e7a47153 1234 replace_smilies($text);
1235 }
7d8a3cb0 1236 if (!$options->noclean) {
5c6347ce 1237 $text = clean_text($text, FORMAT_HTML);
9d40806d 1238 }
7d8a3cb0 1239 if ($options->filter) {
e7a47153 1240 $text = filter_text($text, $courseid);
1241 }
73f8658c 1242 break;
1243
6901fa79 1244 case FORMAT_PLAIN:
5c6347ce 1245 $text = s($text); // cleans dangerous JS
ab892a4f 1246 $text = rebuildnolinktag($text);
b0ccd3fb 1247 $text = str_replace(' ', '&nbsp; ', $text);
6901fa79 1248 $text = nl2br($text);
6901fa79 1249 break;
1250
d342c763 1251 case FORMAT_WIKI:
6a6495ff 1252 // this format is deprecated
572fe9ab 1253 $text = '<p>NOTICE: Wiki-like formatting has been removed from Moodle. You should not be seeing
1254 this message as all texts should have been converted to Markdown format instead.
ce50cc70 1255 Please post a bug report to http://moodle.org/bugs with information about where you
e7a47153 1256 saw this message.</p>'.s($text);
d342c763 1257 break;
1258
e7cdcd18 1259 case FORMAT_MARKDOWN:
1260 $text = markdown_to_html($text);
7d8a3cb0 1261 if ($options->smiley) {
e7a47153 1262 replace_smilies($text);
1263 }
7d8a3cb0 1264 if (!$options->noclean) {
5c6347ce 1265 $text = clean_text($text, FORMAT_HTML);
9d40806d 1266 }
c06c8492 1267
7d8a3cb0 1268 if ($options->filter) {
e7a47153 1269 $text = filter_text($text, $courseid);
1270 }
e7cdcd18 1271 break;
1272
73f8658c 1273 default: // FORMAT_MOODLE or anything else
b7a3d3b2 1274 $text = text_to_html($text, $options->smiley, $options->para, $options->newlines);
7d8a3cb0 1275 if (!$options->noclean) {
5c6347ce 1276 $text = clean_text($text, FORMAT_HTML);
9d40806d 1277 }
c06c8492 1278
7d8a3cb0 1279 if ($options->filter) {
e7a47153 1280 $text = filter_text($text, $courseid);
1281 }
0095d5cd 1282 break;
0095d5cd 1283 }
f0aa2fed 1284
f47f4659 1285 if (empty($options->nocache) and !empty($CFG->cachetext) and $CFG->currenttextiscacheable) {
1286 $newcacheitem = new object();
a9743837 1287 $newcacheitem->md5key = $md5key;
1288 $newcacheitem->formattedtext = addslashes($text);
1289 $newcacheitem->timemodified = time();
1290 if ($oldcacheitem) { // See bug 4677 for discussion
1291 $newcacheitem->id = $oldcacheitem->id;
1292 @update_record('cache_text', $newcacheitem); // Update existing record in the cache table
5ce73257 1293 // It's unlikely that the cron cache cleaner could have
a9743837 1294 // deleted this entry in the meantime, as it allows
1295 // some extra time to cover these cases.
1296 } else {
1297 @insert_record('cache_text', $newcacheitem); // Insert a new record in the cache table
1298 // Again, it's possible that another user has caused this
5ce73257 1299 // record to be created already in the time that it took
1300 // to traverse this function. That's OK too, as the
a9743837 1301 // call above handles duplicate entries, and eventually
1302 // the cron cleaner will delete them.
1303 }
f0aa2fed 1304 }
1305
1306 return $text;
0095d5cd 1307}
1308
4a28b5ca 1309/** Converts the text format from the value to the 'internal'
1310 * name or vice versa. $key can either be the value or the name
1311 * and you get the other back.
c06c8492 1312 *
4a28b5ca 1313 * @param mixed int 0-4 or string one of 'moodle','html','plain','markdown'
1314 * @return mixed as above but the other way around!
1315 */
1316function text_format_name( $key ) {
1317 $lookup = array();
1318 $lookup[FORMAT_MOODLE] = 'moodle';
1319 $lookup[FORMAT_HTML] = 'html';
1320 $lookup[FORMAT_PLAIN] = 'plain';
1321 $lookup[FORMAT_MARKDOWN] = 'markdown';
1322 $value = "error";
1323 if (!is_numeric($key)) {
1324 $key = strtolower( $key );
1325 $value = array_search( $key, $lookup );
1326 }
1327 else {
1328 if (isset( $lookup[$key] )) {
1329 $value = $lookup[ $key ];
1330 }
1331 }
1332 return $value;
1333}
1334
7b2c5e72 1335/** Given a simple string, this function returns the string
1336 * processed by enabled filters if $CFG->filterall is enabled
1337 *
3e6691ee 1338 * @param string $string The string to be filtered.
1339 * @param boolean $striplinks To strip any link in the result text.
1340 * @param int $courseid Current course as filters can, potentially, use it
7b2c5e72 1341 * @return string
1342 */
3e6691ee 1343function format_string ($string, $striplinks = false, $courseid=NULL ) {
7b2c5e72 1344
65b0c132 1345 global $CFG, $COURSE;
7b2c5e72 1346
2a3affe9 1347 //We'll use a in-memory cache here to speed up repeated strings
1348 static $strcache;
1349
1350 //Calculate md5
1c58f440 1351 $md5 = md5($string.'<+>'.$striplinks);
2a3affe9 1352
1353 //Fetch from cache if possible
1354 if(isset($strcache[$md5])) {
1355 return $strcache[$md5];
1356 }
1357
7b2c5e72 1358 if (empty($courseid)) {
65b0c132 1359 if (!empty($COURSE->id)) { // An ugly hack for better compatibility
1360 $courseid = $COURSE->id; // (copied from format_text)
7b2c5e72 1361 }
1362 }
1363
45daee10 1364 if (!empty($CFG->filterall)) {
7b2c5e72 1365 $string = filter_text($string, $courseid);
1366 }
1367
3e6691ee 1368 if ($striplinks) { //strip links in string
1369 $string = preg_replace('/(<a[^>]+?>)(.+?)(<\/a>)/is','$2',$string);
1370 }
1371
2a3affe9 1372 //Store to cache
1373 $strcache[$md5] = $string;
1374
7b2c5e72 1375 return $string;
1376}
1377
d48b00b4 1378/**
1379 * Given text in a variety of format codings, this function returns
1380 * the text as plain text suitable for plain email.
d48b00b4 1381 *
89dcb99d 1382 * @uses FORMAT_MOODLE
1383 * @uses FORMAT_HTML
1384 * @uses FORMAT_PLAIN
1385 * @uses FORMAT_WIKI
1386 * @uses FORMAT_MARKDOWN
1387 * @param string $text The text to be formatted. This is raw text originally from user input.
772e78be 1388 * @param int $format Identifier of the text format to be used
89dcb99d 1389 * (FORMAT_MOODLE, FORMAT_HTML, FORMAT_PLAIN, FORMAT_WIKI, FORMAT_MARKDOWN)
1390 * @return string
d48b00b4 1391 */
d342c763 1392function format_text_email($text, $format) {
d342c763 1393
1394 switch ($format) {
1395
1396 case FORMAT_PLAIN:
1397 return $text;
1398 break;
1399
1400 case FORMAT_WIKI:
1401 $text = wiki_to_html($text);
5b472756 1402 /// This expression turns links into something nice in a text format. (Russell Jungwirth)
1403 /// From: http://php.net/manual/en/function.eregi-replace.php and simplified
76add072 1404 $text = eregi_replace('(<a [^<]*href=["|\']?([^ "\']*)["|\']?[^>]*>([^<]*)</a>)','\\3 [ \\2 ]', $text);
7c55a29b 1405 return strtr(strip_tags($text), array_flip(get_html_translation_table(HTML_ENTITIES)));
d342c763 1406 break;
1407
6ff45b59 1408 case FORMAT_HTML:
1409 return html_to_text($text);
1410 break;
1411
e7cdcd18 1412 case FORMAT_MOODLE:
1413 case FORMAT_MARKDOWN:
67ccec43 1414 default:
76add072 1415 $text = eregi_replace('(<a [^<]*href=["|\']?([^ "\']*)["|\']?[^>]*>([^<]*)</a>)','\\3 [ \\2 ]', $text);
7c55a29b 1416 return strtr(strip_tags($text), array_flip(get_html_translation_table(HTML_ENTITIES)));
d342c763 1417 break;
1418 }
1419}
0095d5cd 1420
d48b00b4 1421/**
1422 * Given some text in HTML format, this function will pass it
1423 * through any filters that have been defined in $CFG->textfilterx
1424 * The variable defines a filepath to a file containing the
1425 * filter function. The file must contain a variable called
1426 * $textfilter_function which contains the name of the function
1427 * with $courseid and $text parameters
1428 *
89dcb99d 1429 * @param string $text The text to be passed through format filters
1430 * @param int $courseid ?
d48b00b4 1431 * @return string
1432 * @todo Finish documenting this function
1433 */
c4ae4fa1 1434function filter_text($text, $courseid=NULL) {
c4ae4fa1 1435 global $CFG;
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
be933850 1945 global $USER, $CFG, $THEME, $SESSION, $ME, $SITE, $HTTPSPAGEREQUIRED;
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
60f9e36e 1955 global $COURSE;
80acd6be 1956 if (!empty($COURSE->lang)) {
1957 $CFG->courselang = $COURSE->lang;
be933850 1958 moodle_setlocale();
b3153e4b 1959 }
80acd6be 1960 if (!empty($COURSE->theme)) {
32e2b302 1961 if (!empty($CFG->allowcoursethemes)) {
80acd6be 1962 $CFG->coursetheme = $COURSE->theme;
32e2b302 1963 theme_setup();
1964 }
1965 }
b3153e4b 1966
f78b1dad 1967/// We have to change some URLs in styles if we are in a $HTTPSPAGEREQUIRED page
1968 if (!empty($HTTPSPAGEREQUIRED)) {
2c3432e6 1969 $CFG->themewww = str_replace('http:', 'https:', $CFG->themewww);
1970 $CFG->pixpath = str_replace('http:', 'https:', $CFG->pixpath);
1971 $CFG->modpixpath = str_replace('http:', 'https:', $CFG->modpixpath);
f78b1dad 1972 foreach ($CFG->stylesheets as $key => $stylesheet) {
2c3432e6 1973 $CFG->stylesheets[$key] = str_replace('http:', 'https:', $stylesheet);
f78b1dad 1974 }
1975 }
0d741155 1976
c3f55692 1977/// Add the required stylesheets
d74d4f20 1978 $stylesheetshtml = '';
1979 foreach ($CFG->stylesheets as $stylesheet) {
1980 $stylesheetshtml .= '<link rel="stylesheet" type="text/css" href="'.$stylesheet.'" />'."\n";
c3f55692 1981 }
d74d4f20 1982 $meta = $stylesheetshtml.$meta;
e89fb61e 1983
79f533c3 1984
1985/// Add the meta page from the themes if any were requested
1986
1987 $metapage = '';
1988
1989 if (!isset($THEME->standardmetainclude) || $THEME->standardmetainclude) {
1990 ob_start();
1991 include_once($CFG->dirroot.'/theme/standard/meta.php');
1992 $metapage .= ob_get_contents();
1993 ob_end_clean();
1994 }
1995
1996 if ($THEME->parent && (!isset($THEME->parentmetainclude) || $THEME->parentmetainclude)) {
1997 ob_start();
1998 include_once($CFG->dirroot.'/theme/'.$THEME->parent.'/meta.php');
1999 $metapage .= ob_get_contents();
2000 ob_end_clean();
2001 }
2002
2003 if (!isset($THEME->metainclude) || $THEME->metainclude) {
2004 ob_start();
2005 include_once($CFG->dirroot.'/theme/'.current_theme().'/meta.php');
2006 $metapage .= ob_get_contents();
2007 ob_end_clean();
2008 }
2009
2010 $meta = $meta."\n".$metapage;
2011
2012
9fa49e22 2013
b0ccd3fb 2014 if ($navigation == 'home') {
9fa49e22 2015 $home = true;
b0ccd3fb 2016 $navigation = '';
9d378732 2017 } else {
2018 $home = false;
9fa49e22 2019 }
2020
0d741155 2021/// This is another ugly hack to make navigation elements available to print_footer later
2022 $THEME->title = $title;
2023 $THEME->heading = $heading;
2024 $THEME->navigation = $navigation;
2025 $THEME->button = $button;
2026 $THEME->menu = $menu;
2507b2f5 2027 $navmenulist = isset($THEME->navmenulist) ? $THEME->navmenulist : '';
0d741155 2028
b0ccd3fb 2029 if ($button == '') {
2030 $button = '&nbsp;';
9fa49e22 2031 }
2032
2033 if (!$menu and $navigation) {
8a33e371 2034 if (empty($CFG->loginhttps)) {
2035 $wwwroot = $CFG->wwwroot;
2036 } else {
2c3432e6 2037 $wwwroot = str_replace('http:','https:',$CFG->wwwroot);
8a33e371 2038 }
60f9e36e 2039 $menu = user_login_string($COURSE);
9fa49e22 2040 }
67ccec43 2041
b4bac9b6 2042 if (isset($SESSION->justloggedin)) {
2043 unset($SESSION->justloggedin);
2044 if (!empty($CFG->displayloginfailures)) {
8f8ed475 2045 if (!empty($USER->username) and $USER->username != 'guest') {
b4bac9b6 2046 if ($count = count_login_failures($CFG->displayloginfailures, $USER->username, $USER->lastlogin)) {
2047 $menu .= '&nbsp;<font size="1">';
2048 if (empty($count->accounts)) {
2049 $menu .= get_string('failedloginattempts', '', $count);
2050 } else {
2051 $menu .= get_string('failedloginattemptsall', '', $count);
2052 }
51792df0 2053 if (has_capability('moodle/site:viewreports', get_context_instance(CONTEXT_SYSTEM, SITEID))) {
52af9a35 2054 $menu .= ' (<a href="'.$CFG->wwwroot.'/course/report/log/index.php'.
839f2456 2055 '?chooselog=1&amp;id=1&amp;modid=site_errors">'.get_string('logs').'</a>)';
b4bac9b6 2056 }
2057 $menu .= '</font>';
2058 }
2059 }
2060 }
2061 }
9fa49e22 2062
47037513 2063
810944af 2064 $meta = '<meta http-equiv="content-type" content="text/html; charset=utf-8" />'. "\n". $meta ."\n";
03fe48e7 2065 if (!$usexml) {
810944af 2066 @header('Content-type: text/html; charset=utf-8');
03fe48e7 2067 }
9fa49e22 2068
b0ccd3fb 2069 if ( get_string('thisdirection') == 'rtl' ) {
2070 $direction = ' dir="rtl"';
9fa49e22 2071 } else {
b0ccd3fb 2072 $direction = ' dir="ltr"';
9fa49e22 2073 }
6575bfd4 2074 //Accessibility: added the 'lang' attribute to $direction, used in theme <html> tag.
2075 $language = str_replace('_utf8','',$CFG->lang);
2076 $direction .= ' lang="'.$language.'" xml:lang="'.$language.'"';
ab9f24ad 2077
5debee2d 2078 if ($cache) { // Allow caching on "back" (but not on normal clicks)
2079 @header('Cache-Control: private, pre-check=0, post-check=0, max-age=0');
2080 @header('Pragma: no-cache');
772e78be 2081 @header('Expires: ');
5debee2d 2082 } else { // Do everything we can to always prevent clients and proxies caching
03fe48e7 2083 @header('Cache-Control: no-store, no-cache, must-revalidate');
2084 @header('Cache-Control: post-check=0, pre-check=0', false);
2085 @header('Pragma: no-cache');
5debee2d 2086 @header('Expires: Mon, 20 Aug 1969 09:23:00 GMT');
2087 @header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
03fe48e7 2088
5debee2d 2089 $meta .= "\n<meta http-equiv=\"pragma\" content=\"no-cache\" />";
2090 $meta .= "\n<meta http-equiv=\"expires\" content=\"0\" />";
66a51452 2091 }
5debee2d 2092 @header('Accept-Ranges: none');
66a51452 2093
5ce73257 2094 if (empty($usexml)) {
27f79fda 2095 $direction = ' xmlns="http://www.w3.org/1999/xhtml"'. $direction; // See debug_header
2096 } else {
66a51452 2097 $currentlanguage = current_language();
8f0cd6ef 2098 $mathplayer = preg_match("/MathPlayer/i", $_SERVER['HTTP_USER_AGENT']);
2099 if(!$mathplayer) {
2100 header('Content-Type: application/xhtml+xml');
2101 }
b0ccd3fb 2102 echo '<?xml version="1.0" ?>'."\n";
66a51452 2103 if (!empty($CFG->xml_stylesheets)) {
b0ccd3fb 2104 $stylesheets = explode(';', $CFG->xml_stylesheets);
66a51452 2105 foreach ($stylesheets as $stylesheet) {
b0ccd3fb 2106 echo '<?xml-stylesheet type="text/xsl" href="'. $CFG->wwwroot .'/'. $stylesheet .'" ?>' . "\n";
66a51452 2107 }
2108 }
b0ccd3fb 2109 echo '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1';
e4576482 2110 if (!empty($CFG->xml_doctype_extra)) {
b0ccd3fb 2111 echo ' plus '. $CFG->xml_doctype_extra;
e4576482 2112 }
b0ccd3fb 2113 echo '//' . strtoupper($currentlanguage) . '" "'. $CFG->xml_dtd .'">'."\n";
8f0cd6ef 2114 $direction = " xmlns=\"http://www.w3.org/1999/xhtml\"
2115 xmlns:math=\"http://www.w3.org/1998/Math/MathML\"
8f0cd6ef 2116 xmlns:xlink=\"http://www.w3.org/1999/xlink\"
2117 $direction";
2118 if($mathplayer) {
2119 $meta .= '<object id="mathplayer" classid="clsid:32F66A20-7614-11D4-BD11-00104BD3F987">' . "\n";
b0ccd3fb 2120 $meta .= '<!--comment required to prevent this becoming an empty tag-->'."\n";
2121 $meta .= '</object>'."\n";
8f0cd6ef 2122 $meta .= '<?import namespace="math" implementation="#mathplayer" ?>' . "\n";
2123 }
9fa49e22 2124 }
2125
7bb6d80f 2126 // Clean up the title
2127
2eea2cce 2128 $title = str_replace('"', '&quot;', $title);
1d9fc417 2129 $title = strip_tags($title);
2eea2cce 2130
7bb6d80f 2131 // Create class and id for this page
2132
68d5f00a 2133 page_id_and_class($pageid, $pageclass);
7bb6d80f 2134
60f9e36e 2135 $pageclass .= ' course-'.$COURSE->id;
d6c66e12 2136
758027d0 2137 if (($pageid != 'site-index') && ($pageid != 'course-view') &&
2138 ($pageid != 'admin-settings')) {
2139 $pageclass .= ' nocoursepage';
2140 }
2141
367e23c2 2142 if (!isloggedin()) {
2143 $pageclass .= ' notloggedin';
2144 }
2145
e299f862 2146 if (!empty($USER->editing)) {
2147 $pageclass .= ' editing';
2148 }
2149
75c3849a 2150 if (!empty($CFG->blocksdrag)) {
2151 $pageclass .= ' drag';
2152 }
2153
7bb6d80f 2154 $bodytags .= ' class="'.$pageclass.'" id="'.$pageid.'"';
772e78be 2155
36b6bcec 2156 ob_start();
ea35ab87 2157 include($CFG->header);
36b6bcec 2158 $output = ob_get_contents();
2159 ob_end_clean();
e608dddd 2160
8af1b1ba 2161 $output = force_strict_header($output);
27f79fda 2162
cdf39255 2163 if (!empty($CFG->messaging)) {
36b6bcec 2164 $output .= message_popup_window();
2165 }
2166
2167 if ($return) {
2168 return $output;
2169 } else {
2170 echo $output;
cdf39255 2171 }
9fa49e22 2172}
2173
27f79fda 2174/**
2175 * Debugging aid: serve page as 'application/xhtml+xml' where possible,
2176 * and substitute the XHTML strict document type.
2177 * Note, requires the 'xmlns' fix in function print_header above.
2178 * See: http://tracker.moodle.org/browse/MDL-7883
2179 * TODO:
2180 */
8af1b1ba 2181function force_strict_header($output) {
27f79fda 2182 global $CFG;
2183 $strict = '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">';
2184 $xsl = '/lib/xhtml.xsl';
2185
8af1b1ba 2186 if (!headers_sent() && debugging(NULL, DEBUG_DEVELOPER)) { // In developer debugging, the browser will barf
27f79fda 2187 $ctype = 'Content-Type: ';
2188 $prolog= "<?xml version='1.0' encoding='utf-8'?>\n";
2189
5ce73257 2190 if (isset($_SERVER['HTTP_ACCEPT'])
27f79fda 2191 && false !== strpos($_SERVER['HTTP_ACCEPT'], 'application/xhtml+xml')) {
2192 //|| false !== strpos($_SERVER['HTTP_USER_AGENT'], 'Safari') //Safari "Entity 'copy' not defined".
2193 // Firefox et al.
2194 $ctype .= 'application/xhtml+xml';
2195 $prolog .= "<!--\n DEBUG: $ctype \n-->\n";
2196
2197 } else if (file_exists($CFG->dirroot.$xsl)
2198 && preg_match('/MSIE.*Windows NT/', $_SERVER['HTTP_USER_AGENT'])) {
2199 // XSL hack for IE 5+ on Windows.
2200 //$www_xsl = preg_replace('/(http:\/\/.+?\/).*/', '', $CFG->wwwroot) .$xsl;
2201 $www_xsl = $CFG->wwwroot .$xsl;
2202 $ctype .= 'application/xml';
2203 $prolog .= "<?xml-stylesheet type='text/xsl' href='$www_xsl'?>\n";
2204 $prolog .= "<!--\n DEBUG: $ctype \n-->\n";
2205
2206 } else {
2207 //ELSE: Mac/IE, old/non-XML browsers.
2208 $ctype .= 'text/html';
2209 $prolog = '';
2210 }
2211 @header($ctype.'; charset=utf-8');
2212 $output = $prolog . $output;
2213
2214 // Test parser error-handling.
2215 if (isset($_GET['error'])) {
2216 $output .= "__ TEST: XML well-formed error < __\n";
2217 }
2218 }
8af1b1ba 2219
84dec541 2220 $output = preg_replace('/(<!DOCTYPE.+?>)/s', $strict, $output); // Always change the DOCTYPE to Strict 1.0
8af1b1ba 2221
27f79fda 2222 return $output;
2223}
2224
2225
2226
d48b00b4 2227/**
2228 * This version of print_header is simpler because the course name does not have to be
2229 * provided explicitly in the strings. It can be used on the site page as in courses
2230 * Eventually all print_header could be replaced by print_header_simple
2231 *
89dcb99d 2232 * @param string $title Appears at the top of the window
2233 * @param string $heading Appears at the top of the page
2234 * @param string $navigation Premade navigation string (for use as breadcrumbs links)
2235 * @param string $focus Indicates form element to get cursor focus on load eg inputform.password
2236 * @param string $meta Meta tags to be added to the header
2237 * @param boolean $cache Should this page be cacheable?
2238 * @param string $button HTML code for a button (usually for module editing)
2239 * @param string $menu HTML code for a popup menu
2240 * @param boolean $usexml use XML for this page
2241 * @param string $bodytags This text will be included verbatim in the <body> tag (useful for onload() etc)
36b6bcec 2242 * @param bool $return If true, return the visible elements of the header instead of echoing them.
d48b00b4 2243 */
b0ccd3fb 2244function print_header_simple($title='', $heading='', $navigation='', $focus='', $meta='',
36b6bcec 2245 $cache=true, $button='&nbsp;', $menu='', $usexml=false, $bodytags='', $return=false) {
90fcc576 2246
5ce73257 2247 global $COURSE, $CFG;
90fcc576 2248
2249 $shortname ='';
c66c2c02 2250 if ($COURSE->id != SITEID) {
9103fd10 2251 $shortname = '<a href="'.$CFG->wwwroot.'/course/view.php?id='. $COURSE->id .'">'. $COURSE->shortname .'</a> ->';
90fcc576 2252 }
2253
050c78c4 2254 $output = print_header($COURSE->shortname .': '. $title, $COURSE->fullname .' '. $heading, $shortname .' '. $navigation, $focus, $meta,
da4124be 2255 $cache, $button, $menu, $usexml, $bodytags, true);
36b6bcec 2256
2257 if ($return) {
2258 return $output;
2259 } else {
2260 echo $output;
2261 }
90fcc576 2262}
629b5885 2263
2264
d48b00b4 2265/**
2266 * Can provide a course object to make the footer contain a link to
2267 * to the course home page, otherwise the link will go to the site home
2268 *
2269 * @uses $CFG
2270 * @uses $USER
89dcb99d 2271 * @param course $course {@link $COURSE} object containing course information
2272 * @param ? $usercourse ?
d48b00b4 2273 * @todo Finish documenting this function
2274 */
469b6501 2275function print_footer($course=NULL, $usercourse=NULL, $return=false) {
0d741155 2276 global $USER, $CFG, $THEME;
9fa49e22 2277
9fa49e22 2278/// Course links
2279 if ($course) {
a789577b 2280 if (is_string($course) && $course == 'none') { // Don't print any links etc
b3a2b9dd 2281 $homelink = '';
2282 $loggedinas = '';
0d741155 2283 $home = false;
a789577b 2284 } else if (is_string($course) && $course == 'home') { // special case for site home page - please do not remove
b3a2b9dd 2285 $course = get_site();
a77ac3dc 2286 $homelink = '<div class="sitelink">'.
244f6f32 2287 '<a title="moodle '. $CFG->release .' ('. $CFG->version .')" href="http://moodle.org/">'.
2288 '<br /><img style="width:100px;height:30px" src="pix/moodlelogo.gif" alt="moodlelogo" /></a></div>';
0d741155 2289 $home = true;
9fa49e22 2290 } else {
fa738731 2291 $homelink = '<div class="homelink"><a '.$CFG->frametarget.' href="'.$CFG->wwwroot.
a77ac3dc 2292 '/course/view.php?id='.$course->id.'">'.$course->shortname.'</a></div>';
0d741155 2293 $home = false;
9fa49e22 2294 }
2295 } else {
b3a2b9dd 2296 $course = get_site(); // Set course as site course by default
fa738731 2297 $homelink = '<div class="homelink"><a '.$CFG->frametarget.' href="'.$CFG->wwwroot.'/">'.get_string('home').'</a></div>';
0d741155 2298 $home = false;
9fa49e22 2299 }
2300
0d741155 2301/// Set up some other navigation links (passed from print_header by ugly hack)
2507b2f5 2302 $menu = isset($THEME->menu) ? str_replace('navmenu', 'navmenufooter', $THEME->menu) : '';
2303 $title = isset($THEME->title) ? $THEME->title : '';
2304 $button = isset($THEME->button) ? $THEME->button : '';
2305 $heading = isset($THEME->heading) ? $THEME->heading : '';
2306 $navigation = isset($THEME->navigation) ? $THEME->navigation : '';
2307 $navmenulist = isset($THEME->navmenulist) ? $THEME->navmenulist : '';
0d741155 2308
f940ee41 2309
b3a2b9dd 2310/// Set the user link if necessary
2311 if (!$usercourse and is_object($course)) {
1f2eec7b 2312 $usercourse = $course;
2313 }
2314
b3a2b9dd 2315 if (!isset($loggedinas)) {
2316 $loggedinas = user_login_string($usercourse, $USER);
2317 }
2318
0d741155 2319 if ($loggedinas == $menu) {
9e0d1983 2320 $menu = '';
0d741155 2321 }
2322
b8cea9b2 2323/// Provide some performance info if required
c2fd9e95 2324 $performanceinfo = '';
afd2b299 2325 if (defined('MDL_PERF') || (!empty($CFG->perfdebug) and $CFG->perfdebug > 7)) {
c2fd9e95 2326 $perf = get_performance_info();
853df85e 2327 if (defined('MDL_PERFTOLOG')) {
2328 error_log("PERF: " . $perf['txt']);
2329 }
ea82d6b6 2330 if (defined('MDL_PERFTOFOOT') || debugging() || $CFG->perfdebug > 7) {
c2fd9e95 2331 $performanceinfo = $perf['html'];
2332 }
572fe9ab 2333 }
b8cea9b2 2334
0d741155 2335
b3a2b9dd 2336/// Include the actual footer file
a282d0ff 2337
469b6501 2338 ob_start();
ea35ab87 2339 include($CFG->footer);
469b6501 2340 $output = ob_get_contents();
2341 ob_end_clean();
a9a9bdba 2342
469b6501 2343 if ($return) {
2344 return $output;
2345 } else {
2346 echo $output;
2347 }
a282d0ff 2348}
2349
c3f55692 2350/**
2351 * Returns the name of the current theme
2352 *
2353 * @uses $CFG
2354 * @param $USER
2355 * @param $SESSION
2356 * @return string
2357 */
2358function current_theme() {
32e2b302 2359 global $CFG, $USER, $SESSION, $course;
c3f55692 2360
417375b7 2361 if (!empty($CFG->pagetheme)) { // Page theme is for special page-only themes set by code
2362 return $CFG->pagetheme;
c3f55692 2363
59552aab 2364 } else if (!empty($CFG->coursetheme) and !empty($CFG->allowcoursethemes)) { // Course themes override others
c3f55692 2365 return $CFG->coursetheme;
2366
2367 } else if (!empty($SESSION->theme)) { // Session theme can override other settings
2368 return $SESSION->theme;
2369
32e2b302 2370 } else if (!empty($USER->theme) and !empty($CFG->allowuserthemes)) { // User theme can override site theme
c3f55692 2371 return $USER->theme;
2372
2373 } else {
2374 return $CFG->theme;
2375 }
2376}
2377
2378
d48b00b4 2379/**
2380 * This function is called by stylesheets to set up the header
2381 * approriately as well as the current path
2382 *
2383 * @uses $CFG
89dcb99d 2384 * @param int $lastmodified ?
2385 * @param int $lifetime ?
2386 * @param string $thename ?
d48b00b4 2387 */
55b734fb 2388function style_sheet_setup($lastmodified=0, $lifetime=300, $themename='', $forceconfig='', $lang='') {
6535be85 2389
9c4e6e21 2390 global $CFG, $THEME;
ab9f24ad 2391
a2e2bf64 2392 // Fix for IE6 caching - we don't want the filemtime('styles.php'), instead use now.
2393 $lastmodified = time();
2394
b0ccd3fb 2395 header('Last-Modified: ' . gmdate("D, d M Y H:i:s", $lastmodified) . ' GMT');
2396 header('Expires: ' . gmdate("D, d M Y H:i:s", time() + $lifetime) . ' GMT');
a2e2bf64 2397 header('Cache-Control: max-age='. $lifetime);
b0ccd3fb 2398 header('Pragma: ');
2399 header('Content-type: text/css'); // Correct MIME type
6535be85 2400
909ec807 2401 $DEFAULT_SHEET_LIST = array('styles_layout', 'styles_fonts', 'styles_color');
9c4e6e21 2402
2403 if (empty($themename)) {
2404 $themename = current_theme(); // So we have something. Normally not needed.
ab25ce31 2405 } else {
2406 $themename = clean_param($themename, PARAM_SAFEDIR);
9c4e6e21 2407 }
2408
2409 if (!empty($forceconfig)) { // Page wants to use the config from this theme instead
2410 unset($THEME);
a44091bf 2411 include($CFG->themedir.'/'.$forceconfig.'/'.'config.php');
9c4e6e21 2412 }
2413
2414/// If this is the standard theme calling us, then find out what sheets we need
2415
2416 if ($themename == 'standard') {
2417 if (!isset($THEME->standardsheets) or $THEME->standardsheets === true) { // Use all the sheets we have
2418 $THEME->sheets = $DEFAULT_SHEET_LIST;
2419 } else if (empty($THEME->standardsheets)) { // We can stop right now!
2420 echo "/***** Nothing required from this stylesheet by main theme *****/\n\n";
2421 exit;
2422 } else { // Use the provided subset only
2423 $THEME->sheets = $THEME->standardsheets;
2424 }
2425
2426/// If we are a parent theme, then check for parent definitions
2427
2428 } else if (!empty($THEME->parent) && $themename == $THEME->parent) {
2429 if (!isset($THEME->parentsheets) or $THEME->parentsheets === true) { // Use all the sheets we have
2430 $THEME->sheets = $DEFAULT_SHEET_LIST;
2431 } else if (empty($THEME->parentsheets)) { // We can stop right now!
2432 echo "/***** Nothing required from this stylesheet by main theme *****/\n\n";
2433 exit;
2434 } else { // Use the provided subset only
2435 $THEME->sheets = $THEME->parentsheets;
2436 }
2437 }
2438
2439/// Work out the last modified date for this theme
2440
2441 foreach ($THEME->sheets as $sheet) {
a44091bf 2442 if (file_exists($CFG->themedir.'/'.$themename.'/'.$sheet.'.css')) {
2443 $sheetmodified = filemtime($CFG->themedir.'/'.$themename.'/'.$sheet.'.css');
9c4e6e21 2444 if ($sheetmodified > $lastmodified) {
2445 $lastmodified = $sheetmodified;
2446 }
2447 }
6535be85 2448 }
2449
6535be85 2450
6ba172fb 2451/// Get a list of all the files we want to include
2452 $files = array();
2453
2454 foreach ($THEME->sheets as $sheet) {
2455 $files[] = array($CFG->themedir, $themename.'/'.$sheet.'.css');
2456 }
2457
2458 if ($themename == 'standard') { // Add any standard styles included in any modules
2459 if (!empty($THEME->modsheets)) { // Search for styles.php within activity modules
2460 if ($mods = get_list_of_plugins('mod')) {
2461 foreach ($mods as $mod) {
2462 if (file_exists($CFG->dirroot.'/mod/'.$mod.'/styles.php')) {
2463 $files[] = array($CFG->dirroot, '/mod/'.$mod.'/styles.php');
2464 }
08396bb2 2465 }
2466 }
2467 }
a2b3f884 2468
6ba172fb 2469 if (!empty($THEME->blocksheets)) { // Search for styles.php within block modules
2470 if ($mods = get_list_of_plugins('blocks')) {
2471 foreach ($mods as $mod) {
2472 if (file_exists($CFG->dirroot.'/blocks/'.$mod.'/styles.php')) {
2473 $files[] = array($CFG->dirroot, '/blocks/'.$mod.'/styles.php');
2474 }
08396bb2 2475 }
2476 }
2477 }
a2b3f884 2478
ae628043 2479 if (!isset($THEME->courseformatsheets) || $THEME->courseformatsheets) { // Search for styles.php in course formats
2480 if ($mods = get_list_of_plugins('format','',$CFG->dirroot.'/course')) {
2481 foreach ($mods as $mod) {
2482 if (file_exists($CFG->dirroot.'/course/format/'.$mod.'/styles.php')) {
2483 $files[] = array($CFG->dirroot, '/course/format/'.$mod.'/styles.php');
2484 }
2485 }
2486 }
2487 }
2488
6ba172fb 2489 if (!empty($THEME->langsheets)) { // Search for styles.php within the current language
6ba172fb 2490 if (file_exists($CFG->dirroot.'/lang/'.$lang.'/styles.php')) {
2491 $files[] = array($CFG->dirroot, '/lang/'.$lang.'/styles.php');
2492 }
2493 }
08396bb2 2494 }
2495
6ba172fb 2496
2497 if ($files) {
2498 /// Produce a list of all the files first
2499 echo '/**************************************'."\n";
2500 echo ' * THEME NAME: '.$themename."\n *\n";
2501 echo ' * Files included in this sheet:'."\n *\n";
2502 foreach ($files as $file) {
2503 echo ' * '.$file[1]."\n";
08396bb2 2504 }
6ba172fb 2505 echo ' **************************************/'."\n\n";
08396bb2 2506
6ba172fb 2507
16f0af59 2508 /// check if csscobstants is set
2509 if (!empty($THEME->cssconstants)) {
2510 require_once("$CFG->libdir/cssconstants.php");
2511 /// Actually collect all the files in order.
2512 $css = '';
2513 foreach ($files as $file) {
2514 $css .= '/***** '.$file[1].' start *****/'."\n\n";
2515 $css .= file_get_contents($file[0].'/'.$file[1]);
2516 $ccs .= '/***** '.$file[1].' end *****/'."\n\n";
2517 }
2518 /// replace css_constants with their values
2519 echo replace_cssconstants($css);
2520 } else {
2521 /// Actually output all the files in order.
2522 foreach ($files as $file) {
2523 echo '/***** '.$file[1].' start *****/'."\n\n";
2524 @include_once($file[0].'/'.$file[1]);
2525 echo '/***** '.$file[1].' end *****/'."\n\n";
2526 }
6ba172fb 2527 }
9c4e6e21 2528 }
2529
a44091bf 2530 return $CFG->themewww.'/'.$themename; // Only to help old themes (1.4 and earlier)
6535be85 2531}
2532
9c4e6e21 2533
2534function theme_setup($theme = '', $params=NULL) {
d74d4f20 2535/// Sets up global variables related to themes
2536
56766f85 2537 global $CFG, $THEME, $SESSION, $USER;
d74d4f20 2538
2539 if (empty($theme)) {
2540 $theme = current_theme();
2541 }
9c4e6e21 2542
09ad59dc 2543/// If the theme doesn't exist for some reason then revert to standardwhite
a44091bf 2544 if (!file_exists($CFG->themedir .'/'. $theme .'/config.php')) {
09ad59dc 2545 $CFG->theme = $theme = 'standardwhite';
2546 }
2547
55b734fb 2548/// Load up the theme config
2549 $THEME = NULL; // Just to be sure
a44091bf 2550 include($CFG->themedir .'/'. $theme .'/config.php'); // Main config for current theme
55b734fb 2551
9c4e6e21 2552/// Put together the parameters
2553 if (!$params) {
2554 $params = array();
2555 }
56766f85 2556 if ($theme != $CFG->theme) {
2557 $params[] = 'forceconfig='.$theme;
9c4e6e21 2558 }
55b734fb 2559
2560/// Force language too if required
2561 if (!empty($THEME->langsheets)) {
2562 $params[] = 'lang='.current_language();
2563 }
2564
2565/// Convert params to string
9c4e6e21 2566 if ($params) {
55b734fb 2567 $paramstring = '?'.implode('&', $params);
d74d4f20 2568 } else {
9c4e6e21 2569 $paramstring = '';
d74d4f20 2570 }
2571
9c4e6e21 2572/// Set up image paths
25580407 2573 if (empty($THEME->custompix)) { // Could be set in the above file
d74d4f20 2574 $CFG->pixpath = $CFG->wwwroot .'/pix';
2575 $CFG->modpixpath = $CFG->wwwroot .'/mod';
2576 } else {
a44091bf 2577 $CFG->pixpath = $CFG->themewww .'/'. $theme .'/pix';
2578 $CFG->modpixpath = $CFG->themewww .'/'. $theme .'/pix/mod';
d74d4f20 2579 }
2580
9c4e6e21 2581/// Header and footer paths
a44091bf 2582 $CFG->header = $CFG->themedir .'/'. $theme .'/header.html';
2583 $CFG->footer = $CFG->themedir .'/'. $theme .'/footer.html';
d74d4f20 2584
9c4e6e21 2585/// Define stylesheet loading order
d74d4f20 2586 $CFG->stylesheets = array();
2587 if ($theme != 'standard') { /// The standard sheet is always loaded first
a44091bf 2588 $CFG->stylesheets[] = $CFG->themewww.'/standard/styles.php'.$paramstring;
d74d4f20 2589 }
2590 if (!empty($THEME->parent)) { /// Parent stylesheets are loaded next
a44091bf 2591 $CFG->stylesheets[] = $CFG->themewww.'/'.$THEME->parent.'/styles.php'.$paramstring;
d74d4f20 2592 }
a44091bf 2593 $CFG->stylesheets[] = $CFG->themewww.'/'.$theme.'/styles.php'.$paramstring;
d74d4f20 2594
2595}
2596
c3f55692 2597
d48b00b4 2598/**
2599 * Returns text to be displayed to the user which reflects their login status
2600 *
2601 * @uses $CFG
2602 * @uses $USER
89dcb99d 2603 * @param course $course {@link $COURSE} object containing course information
2604 * @param user $user {@link $USER} object containing user information
2605 * @return string
d48b00b4 2606 */
c44d5d42 2607function user_login_string($course=NULL, $user=NULL) {
2608 global $USER, $CFG, $SITE;
a282d0ff 2609
86a1ba04 2610 if (empty($user) and !empty($USER->id)) {
a282d0ff 2611 $user = $USER;
2612 }
2613
c44d5d42 2614 if (empty($course)) {
2615 $course = $SITE;
2616 }
2617
a282d0ff 2618 if (isset($user->realuser)) {
b0ccd3fb 2619 if ($realuser = get_record('user', 'id', $user->realuser)) {
2d71e8ee 2620 $fullname = fullname($realuser, true);
fa738731 2621 $realuserinfo = " [<a $CFG->frametarget
01eb4f5f 2622 href=\"$CFG->wwwroot/course/loginas.php?id=$course->id&amp;return=1\">$fullname</a>] ";
9fa49e22 2623 }
9d378732 2624 } else {
b0ccd3fb 2625 $realuserinfo = '';
9fa49e22 2626 }
2627
87180677 2628 if (empty($CFG->loginhttps)) {
2629 $wwwroot = $CFG->wwwroot;
2630 } else {
2c3432e6 2631 $wwwroot = str_replace('http:','https:',$CFG->wwwroot);
87180677 2632 }
2633
8743f4f3 2634 if (empty($course->id)) {
2635 // $course->id is not defined during installation
2636 return '';
5ce73257 2637 } else if (isset($user->id) and $user->id) {
2d07587b 2638 $context = get_context_instance(CONTEXT_COURSE, $course->id);
2639
2d71e8ee 2640 $fullname = fullname($user, true);
fa738731 2641 $username = "<a $CFG->frametarget href=\"$CFG->wwwroot/user/view.php?id=$user->id&amp;course=$course->id\">$fullname</a>";
03d820c7 2642 if (is_mnet_remote_user($user) and $idprovider = get_record('mnet_host', 'id', $user->mnethostid)) {
fa738731 2643 $username .= " from <a $CFG->frametarget href=\"{$idprovider->wwwroot}\">{$idprovider->name}</a>";
03d820c7 2644 }
8f8ed475 2645 if (isset($user->username) && $user->username == 'guest') {
158de846 2646 $loggedinas = $realuserinfo.get_string('loggedinasguest').
fa738731 2647 " (<a $CFG->frametarget href=\"$wwwroot/login/index.php\">".get_string('login').'</a>)';
2d07587b 2648 } else if (!empty($user->switchrole[$context->id])) {
91ea292e 2649 $rolename = '';
2d07587b 2650 if ($role = get_record('role', 'id', $user->switchrole[$context->id])) {
91ea292e 2651 $rolename = ': '.format_string($role->name);
2652 }
2653 $loggedinas = get_string('loggedinas', 'moodle', $username).$rolename.
fa738731 2654 " (<a $CFG->frametarget
91ea292e 2655 href=\"$CFG->wwwroot/course/view.php?id=$course->id&amp;switchrole=0&amp;sesskey=".sesskey()."\">".get_string('switchrolereturn').'</a>)';
0ae7e6f4 2656 } else {
d5a01638 2657 $loggedinas = $realuserinfo.get_string('loggedinas', 'moodle', $username).' '.
fa738731 2658 " (<a $CFG->frametarget href=\"$CFG->wwwroot/login/logout.php\">".get_string('logout').'</a>)';
0ae7e6f4 2659 }
9fa49e22 2660 } else {
b0ccd3fb 2661 $loggedinas = get_string('loggedinnot', 'moodle').
fa738731 2662 " (<a $CFG->frametarget href=\"$wwwroot/login/index.php\">".get_string('login').'</a>)';
9fa49e22 2663 }
d3593a67 2664 return '<div class="logininfo">'.$loggedinas.'</div>';
9fa49e22 2665}
2666
d48b00b4 2667/**
57100a90 2668 * Tests whether $THEME->rarrow, $THEME->larrow have been set (theme/-/config.php).
2669 * If not it applies sensible defaults.
d48b00b4 2670 *
57100a90 2671 * Accessibility: right and left arrow Unicode characters for breadcrumb, calendar,
5ce73257 2672 * search forum block, etc. Important: these are 'silent' in a screen-reader
57100a90 2673 * (unlike &gt; &raquo;), and must be accompanied by text.
2674 * @uses $THEME
d48b00b4 2675 */
57100a90 2676function check_theme_arrows() {
2677 global $THEME;
5ce73257 2678
57100a90 2679 if (!isset($THEME->rarrow) and !isset($THEME->larrow)) {
ce27e6f4 2680 // Default, looks good in Win XP/IE 6, Win/Firefox 1.5, Win/Netscape 8...
2681 // Also OK in Win 9x/2K/IE 5.x
57100a90 2682 $THEME->rarrow = '&#x25BA;';
2683 $THEME->larrow = '&#x25C4;';
ce27e6f4 2684 $uagent = $_SERVER['HTTP_USER_AGENT'];
2685 if (false !== strpos($uagent, 'Opera')
2686 || false !== strpos($uagent, 'Mac')) {
2687 // Looks good in Win XP/Mac/Opera 8/9, Mac/Firefox 2, Camino, Safari.
2688 // Not broken in Mac/IE 5, Mac/Netscape 7 (?).
57100a90 2689 $THEME->rarrow = '&#x25B6;';
2690 $THEME->larrow = '&#x25C0;';
ce27e6f4 2691 }
2692 elseif (false !== strpos($uagent, 'Konqueror')) {
2693 $THEME->rarrow = '&rarr;';
2694 $THEME->larrow = '&larr;';
2695 }
2696 elseif (isset($_SERVER['HTTP_ACCEPT_CHARSET'])
2697 && false === stripos($_SERVER['HTTP_ACCEPT_CHARSET'], 'utf-8')) {
2698 // (Win/IE 5 doesn't set ACCEPT_CHARSET, but handles Unicode.)
2699 // To be safe, non-Unicode browsers!
2700 $THEME->rarrow = '&gt;';
2701 $THEME->larrow = '&lt;';
2702 }
57100a90 2703 }
2704}
da4124be 2705
57100a90 2706/**
2707 * Prints breadcrumb trail of links, called in theme/-/header.html
2708 *
2709 * @uses $CFG
2710 * @param string $navigation The breadcrumb navigation string to be printed
2711 * @param string $separator The breadcrumb trail separator. The default 0 leads to the use
2712 * of $THEME->rarrow, themes could use '&rarr;', '/', or '' for a style-sheet solution.
2713 * @param boolean $return False to echo the breadcrumb string (default), true to return it.
2714 */
2715function print_navigation ($navigation, $separator=0, $return=false) {
2716 global $CFG, $THEME;
da4124be 2717 $output = '';
5ce73257 2718
57100a90 2719 check_theme_arrows();
2720 if (0 === $separator) {
2721 $separator = $THEME->rarrow;
2722 }
2723 if (!empty($separator)) {
2724 $separator = '<span class="sep">'. $separator .'</span>';
2725 }
da4124be 2726
2727 if ($navigation) {
57100a90 2728 //Accessibility: breadcrumb links now in a list, &raquo; replaced with a 'silent' character.
da4124be 2729 $nav_text = get_string('youarehere','access');
57100a90 2730 $output .= '<h2 class="accesshide">'.$nav_text."</h2><ul>\n";
da4124be 2731 if (! $site = get_site()) {
2732 $site->shortname = get_string('home');
2733 }
57100a90 2734 $navigation = "<li>$separator ". str_replace('->', "</li>\n<li>$separator", $navigation) ."</li>\n";
fa738731 2735 $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 2736 ? '/my' : '') .'/">'. $site->shortname ."</a></li>\n". $navigation;
5ce73257 2737 $output .= "</ul>\n";
da4124be 2738 }
2739
2740 if ($return) {
2741 return $output;
2742 } else {
2743 echo $output;
2744 }
9fa49e22 2745}
2746
d48b00b4 2747/**
bfca0094 2748 * Prints a string in a specified size (retained for backward compatibility)
d48b00b4 2749 *
89dcb99d 2750 * @param string $text The text to be displayed
2751 * @param int $size The size to set the font for text display.
d48b00b4 2752 */
da4124be 2753function print_headline($text, $size=2, $return=false) {
593bc22b 2754 $output = print_heading($text, '', $size, true);
da4124be 2755 if ($return) {
2756 return $output;
2757 } else {
2758 echo $output;
2759 }
d4df9200 2760}
2761
d48b00b4 2762/**
2763 * Prints text in a format for use in headings.
2764 *
89dcb99d 2765 * @param string $text The text to be displayed
2766 * @param string $align The alignment of the printed paragraph of text
2767 * @param int $size The size to set the font for text display.
d48b00b4 2768 */
da4124be 2769function print_heading($text, $align='', $size=2, $class='main', $return=false) {
bfca0094 2770 if ($align) {
fc9cb24a 2771 $align = ' style="text-align:'.$align.';"';
bfca0094 2772 }
4419aa80 2773 if ($class) {
2774 $class = ' class="'.$class.'"';
2775 }
da4124be 2776 $output = "<h$size $align $class>".stripslashes_safe($text)."</h$size>";
2777
2778 if ($return) {
2779 return $output;
2780 } else {
2781 echo $output;
2782 }
9fa49e22 2783}
2784
d48b00b4 2785/**
2786 * Centered heading with attached help button (same title text)
2787 * and optional icon attached
2788 *
89dcb99d 2789 * @param string $text The text to be displayed
2790 * @param string $helppage The help page to link to
2791 * @param string $module The module whose help should be linked to
2792 * @param string $icon Image to display if needed
d48b00b4 2793 */
da4124be 2794function print_heading_with_help($text, $helppage, $module='moodle', $icon='', $return=false) {
2795 $output = '';
2796 $output .= '<h2 class="main help">'.$icon.stripslashes_safe($text);
2797 $output .= helpbutton($helppage, $text, $module, true, false, '', true);
2798 $output .= '</h2>';
2799
2800 if ($return) {
2801 return $output;
2802 } else {
2803 echo $output;
2804 }
9fa49e22 2805}
ab9f24ad 2806
6ee8277f 2807
da4124be 2808function print_heading_block($heading, $class='', $return=false) {
b6f30b18 2809 //Accessibility: 'headingblock' is now H1, see theme/standard/styles_*.css: ??
da4124be 2810 $output = '<h2 class="headingblock header '.$class.'">'.stripslashes($heading).'</h2>';
2811
2812 if ($return) {
2813 return $output;
2814 } else {
2815 echo $output;
2816 }
6ee8277f 2817}
2818
2819
d48b00b4 2820/**
2821 * Print a link to continue on to another page.
2822 *
2823 * @uses $CFG
2824 * @param string $link The url to create a link to.
2825 */
da4124be 2826function print_continue($link, $return=false) {
9fa49e22 2827
51a96819 2828 global $CFG;
2829
dedb2304 2830 // in case we are logging upgrade in admin/index.php stop it
2831 if (function_exists('upgrade_log_finish')) {
2832 upgrade_log_finish();
2833 }
2834
da4124be 2835 $output = '';
2836
e1968a8e 2837 if ($link == '') {
2838 if (!empty($_SERVER['HTTP_REFERER'])) {
2839 $link = $_SERVER['HTTP_REFERER'];
2840 $link = str_replace('&', '&amp;', $link); // make it valid XHTML
2841 } else {
2842 $link = $CFG->wwwroot .'/';
2843 }
9fa49e22 2844 }
2845
da4124be 2846 $output .= '<div class="continuebutton">';
c35e8b1c 2847
da4124be 2848 $output .= print_single_button($link, NULL, get_string('continue'), 'post', $CFG->framename, true);
2849 $output .= '</div>'."\n";
2850
2851 if ($return) {
2852 return $output;
2853 } else {
2854 echo $output;
2855 }
9fa49e22 2856}
2857
2123b644 2858
d48b00b4 2859/**
2860 * Print a message in a standard themed box.
2123b644 2861 * Replaces print_simple_box (see deprecatedlib.php)
d48b00b4 2862 *
2123b644 2863 * @param string $message, the content of the box
f79aa892 2864 * @param string $classes, space-separated class names.
2865 * @param string $ids, space-separated id names.
2123b644 2866 * @param boolean $return, return as string or just print it
d48b00b4 2867 */
f79aa892 2868function print_box($message, $classes='generalbox', $ids='', $return=false) {
2123b644 2869
f79aa892 2870 $output = print_box_start($classes, $ids, true);
da4124be 2871 $output .= stripslashes_safe($message);
2123b644 2872 $output .= print_box_end(true);
da4124be 2873
2874 if ($return) {
2875 return $output;
2876 } else {
2877 echo $output;
2878 }
9fa49e22 2879}
2880
e1968a8e 2881/**
2123b644 2882 * Starts a box using divs
2883 * Replaces print_simple_box_start (see deprecatedlib.php)
408b65dd 2884 *
f79aa892 2885 * @param string $classes, space-separated class names.
2886 * @param string $ids, space-separated id names.
2123b644 2887 * @param boolean $return, return as string or just print it
d48b00b4 2888 */
f79aa892 2889function print_box_start($classes='generalbox', $ids='', $return=false) {
da4124be 2890 $output = '';
9fa49e22 2891
f79aa892 2892 if ($ids) {
2893 $ids = ' id="'.$ids.'"';
30c9e694 2894 }
593bc22b 2895
8f36e33e 2896 $output .= '<div'.$ids.' class="box '.$classes.'">';
da4124be 2897
2898 if ($return) {
2899 return $output;
2900 } else {
2901 echo $output;
2902 }
9fa49e22 2903}
2904
2123b644 2905
e1968a8e 2906/**
2123b644 2907 * Simple function to end a box (see above)
2908 * Replaces print_simple_box_end (see deprecatedlib.php)
2909 *
2910 * @param boolean $return, return as string or just print it
d48b00b4 2911 */
2123b644 2912function print_box_end($return=false) {
df26dd34 2913 $output = '</div>';
da4124be 2914 if ($return) {
2915 return $output;
2916 } else {
2917 echo $output;
2918 }
9fa49e22 2919}
2920
30c9e694 2921
d48b00b4 2922/**
2923 * Print a self contained form with a single submit button.
2924 *
89dcb99d 2925 * @param string $link ?
2926 * @param array $options ?
2927 * @param string $label ?
2928 * @param string $method ?
d48b00b4 2929 * @todo Finish documenting this function
2930 */
da4124be 2931function print_single_button($link, $options, $label='OK', $method='get', $target='_self', $return=false) {
2932 $output = '';
2463ef81 2933 $link = str_replace('"', '&quot;', $link); //basic XSS protection
da4124be 2934 $output .= '<div class="singlebutton">';
64888fc1 2935 // taking target out, will need to add later target="'.$target.'"
2463ef81 2936 $output .= '<form action="'. $link .'" method="'. $method .'">';
64888fc1 2937 $output .= '<fieldset class="invisiblefieldset">';
9fa49e22 2938 if ($options) {
2939 foreach ($options as $name => $value) {
e1968a8e 2940 $output .= '<input type="hidden" name="'. $name .'" value="'. s($value) .'" />';
9fa49e22 2941 }
2942 }
e1968a8e 2943 $output .= '<input type="submit" value="'. s($label) .'" /></fieldset></form></div>';
da4124be 2944
2945 if ($return) {
2946 return $output;
2947 } else {
2948 echo $output;
2949 }
9fa49e22 2950}
2951
2123b644 2952
d48b00b4 2953/**
2954 * Print a spacer image with the option of including a line break.
2955 *
89dcb99d 2956 * @param int $height ?
2957 * @param int $width ?
2958 * @param boolean $br ?
d48b00b4 2959 * @todo Finish documenting this function
2960 */
da4124be 2961function print_spacer($height=1, $width=1, $br=true, $return=false) {
9fa49e22 2962 global $CFG;
da4124be 2963 $output = '';
2964
2965 $output .= '<img class="spacer" height="'. $height .'" width="'. $width .'" src="'. $CFG->wwwroot .'/pix/spacer.gif" alt="" />';
9fa49e22 2966 if ($br) {
da4124be 2967 $output .= '<br />'."\n";
2968 }
2969
2970 if ($return) {
2971 return $output;
2972 } else {
2973 echo $output;
9fa49e22 2974 }
2975}
2976
d48b00b4 2977/**
2978 * Given the path to a picture file in a course, or a URL,
2979 * this function includes the picture in the page.
2980 *
89dcb99d 2981 * @param string $path ?
2982 * @param int $courseid ?
2983 * @param int $height ?
2984 * @param int $width ?
2985 * @param string $link ?
d48b00b4 2986 * @todo Finish documenting this function
2987 */
da4124be 2988function print_file_picture($path, $courseid=0, $height='', $width='', $link='', $return=false) {
9fa49e22 2989 global $CFG;
da4124be 2990 $output = '';
9fa49e22 2991
2992 if ($height) {
b0ccd3fb 2993 $height = 'height="'. $height .'"';
9fa49e22 2994 }
2995 if ($width) {
b0ccd3fb 2996 $width = 'width="'. $width .'"';
9fa49e22 2997 }
2998 if ($link) {
da4124be 2999 $output .= '<a href="'. $link .'">';
9fa49e22 3000 }
b0ccd3fb 3001 if (substr(strtolower($path), 0, 7) == 'http://') {
7cd2f598 3002 $output .= '<img style="height:'.$height.'px;width:'.$width.'px;" src="'. $path .'" />';
9fa49e22 3003
3004 } else if ($courseid) {
7cd2f598 3005 $output .= '<img style="height:'.$height.'px;width:'.$width.'px;" src="';
9fa49e22 3006 if ($CFG->slasharguments) { // Use this method if possible for better caching
da4124be 3007 $output .= $CFG->wwwroot .'/file.php/'. $courseid .'/'. $path;
9fa49e22 3008 } else {
da4124be 3009 $output .= $CFG->wwwroot .'/file.php?file=/'. $courseid .'/'. $path;
9fa49e22 3010 }
da4124be 3011 $output .= '" />';
9fa49e22 3012 } else {
da4124be 3013 $output .= 'Error: must pass URL or course';
9fa49e22 3014 }
3015 if ($link) {
da4124be 3016 $output .= '</a>';
3017 }
3018
3019 if ($return) {
3020 return $output;
3021 } else {
3022 echo $output;
9fa49e22 3023 }
3024}
3025
d48b00b4 3026/**
3027 * Print the specified user's avatar.
3028 *
89dcb99d 3029 * @param int $userid ?
3030 * @param int $courseid ?
3031 * @param boolean $picture Print the user picture?
4c6c0e01 3032 * @param int $size Size in pixels. Special values are (true/1 = 100px) and (false/0 = 35px) for backward compatability
da4124be 3033 * @param boolean $return If false print picture to current page, otherwise return the output as string
89dcb99d 3034 * @param boolean $link Enclose printed image in a link to view specified course?
953eb6f3 3035 * @param string $target link target attribute
3036 * @param boolean $alttext use username or userspecified text in image alt attribute
89dcb99d 3037 * return string
d48b00b4 3038 * @todo Finish documenting this function
3039 */
953eb6f3 3040function print_user_picture($userid, $courseid, $picture, $size=0, $return=false, $link=true, $target='', $alttext=true) {
f374fb10 3041 global $CFG;
9fa49e22 3042
3043 if ($link) {
f66e1977 3044 if ($target) {
3045 $target=' target="_blank"';
3046 }
3047 $output = '<a '.$target.' href="'. $CFG->wwwroot .'/user/view.php?id='. $userid .'&amp;course='. $courseid .'">';
9fa49e22 3048 } else {
b0ccd3fb 3049 $output = '';
9fa49e22 3050 }
4c6c0e01 3051 if (empty($size)) {
3052 $file = 'f2';
da7a785b 3053 $size = 35;
4c6c0e01 3054 } else if ($size === true or $size == 1) {
b0ccd3fb 3055 $file = 'f1';
9fa49e22 3056 $size = 100;
4c6c0e01 3057 } else if ($size >= 50) {
3058 $file = 'f1';
9fa49e22 3059 } else {
b0ccd3fb 3060 $file = 'f2';
9fa49e22 3061 }
113a79e2 3062 $class = "userpicture";
67a63a30 3063 if ($picture) { // Print custom user picture
9fa49e22 3064 if ($CFG->slasharguments) { // Use this method if possible for better caching
c1138797 3065 $src = $CFG->wwwroot .'/user/pix.php/'. $userid .'/'. $file .'.jpg';
9fa49e22 3066 } else {
c1138797 3067 $src = $CFG->wwwroot .'/user/pix.php?file=/'. $userid .'/'. $file .'.jpg';
9fa49e22 3068 }
67a63a30 3069 } else { // Print default user pictures (use theme version if available)
113a79e2 3070 $class .= " defaultuserpic";
adc5f292 3071 $src = "$CFG->pixpath/u/$file.png";
9fa49e22 3072 }
ad6226fb 3073 $imagealt = '';
3074 if ($alttext and $user = get_record('user','id',$userid)) {
5a86df5e 3075 if (!empty($user->imagealt)) {
3076 $imagealt = $user->imagealt;
3077 } else {
3078 $imagealt = get_string('pictureof','',fullname($user));
5ce73257 3079 }
2bbaf749 3080 }
953eb6f3 3081
adc5f292 3082 $output .= '<img class="'.$class.'" src="'.$src.'" alt="'.s($imagealt).'" />';
9fa49e22 3083 if ($link) {
b0ccd3fb 3084 $output .= '</a>';
9fa49e22 3085 }
3086
da4124be 3087 if ($return) {
9fa49e22 3088 return $output;
3089 } else {
3090 echo $output;
3091 }
3092}
3093
d48b00b4 3094/**
3095 * Prints a summary of a user in a nice little box.
3096 *
89dcb99d 3097 * @uses $CFG
3098 * @uses $USER
3099 * @param user $user A {@link $USER} object representing a user
3100 * @param course $course A {@link $COURSE} object representing a course
d48b00b4 3101 */
da4124be 3102function print_user($user, $course, $messageselect=false, $return=false) {
951b22a8 3103
89dcb99d 3104 global $CFG, $USER;
499795e8 3105
da4124be 3106 $output = '';
3107
951b22a8 3108 static $string;
3109 static $datestring;
3110 static $countries;
951b22a8 3111
ec7a8b79 3112 $context = get_context_instance(CONTEXT_COURSE, $course->id);
04186cd9 3113
951b22a8 3114 if (empty($string)) { // Cache all the strings for the rest of the page
3115
b0ccd3fb 3116 $string->email = get_string('email');
3117 $string->location = get_string('location');
3118 $string->lastaccess = get_string('lastaccess');
3119 $string->activity = get_string('activity');
3120 $string->unenrol = get_string('unenrol');
3121 $string->loginas = get_string('loginas');
3122 $string->fullprofile = get_string('fullprofile');
3123 $string->role = get_string('role');
3124 $string->name = get_string('name');
3125 $string->never = get_string('never');
3126
3127 $datestring->day = get_string('day');
3128 $datestring->days = get_string('days');
3129 $datestring->hour = get_string('hour');
3130 $datestring->hours = get_string('hours');
3131 $datestring->min = get_string('min');
3132 $datestring->mins = get_string('mins');
3133 $datestring->sec = get_string('sec');
3134 $datestring->secs = get_string('secs');
951b22a8 3135
3136 $countries = get_list_of_countries();
951b22a8 3137 }
3138
3468d58a 3139/// Get the hidden field list
04186cd9 3140 if (has_capability('moodle/course:viewhiddenuserfields', $context)) {
3468d58a 3141 $hiddenfields = array();
3142 } else {
3143 $hiddenfields = array_flip(explode(',', $CFG->hiddenuserfields));
3144 }
3145
da4124be 3146 $output .= '<table class="userinfobox">';
3147 $output .= '<tr>';
3148 $output .= '<td class="left side">';
3149 $output .= print_user_picture($user->id, $course->id, $user->picture, true, true);
3150 $output .= '</td>';
3151 $output .= '<td class="content">';
ec7a8b79 3152 $output .= '<div class="username">'.fullname($user, has_capability('moodle/site:viewfullnames', $context)).'</div>';
da4124be 3153 $output .= '<div class="info">';
951b22a8 3154 if (!empty($user->role) and ($user->role <> $course->teacher)) {
da4124be 3155 $output .= $string->role .': '. $user->role .'<br />';
951b22a8 3156 }
1936c10e 3157 if ($user->maildisplay == 1 or ($user->maildisplay == 2 and ($course->id != SITEID) and !isguest()) or
04186cd9 3158has_capability('moodle/course:viewhiddenuserfields', $context)) {
da4124be 3159 $output .= $string->email .': <a href="mailto:'. $user->email .'">'. $user->email .'</a><br />';
951b22a8 3160 }
3468d58a 3161 if (($user->city or $user->country) and (!isset($hiddenfields['city']) or !isset($hiddenfields['country']))) {
da4124be 3162 $output .= $string->location .': ';
3468d58a 3163 if ($user->city && !isset($hiddenfields['city'])) {
da4124be 3164 $output .= $user->city;
b40bc478 3165 }
3468d58a 3166 if (!empty($countries[$user->country]) && !isset($hiddenfields['country'])) {
3167 if ($user->city && !isset($hiddenfields['city'])) {
da4124be 3168 $output .= ', ';
b40bc478 3169 }
da4124be 3170 $output .= $countries[$user->country];
b40bc478 3171 }
da4124be 3172 $output .= '<br />';
951b22a8 3173 }
ae8a5ff0 3174
3468d58a 3175 if (!isset($hiddenfields['lastaccess'])) {
3176 if ($user->lastaccess) {
da4124be 3177 $output .= $string->lastaccess .': '. userdate($user->lastaccess);
18894ee4 3178 $output .= '&nbsp; ('. format_time(time() - $user->lastaccess, $datestring) .')';
3468d58a 3179 } else {
da4124be 3180 $output .= $string->lastaccess .': '. $string->never;
3468d58a 3181 }
951b22a8 3182 }
da4124be 3183 $output .= '</div></td><td class="links">';
ae8a5ff0 3184 //link to blogs
b7425e2e 3185 if ($CFG->bloglevel > 0) {
da4124be 3186 $output .= '<a href="'.$CFG->wwwroot.'/blog/index.php?userid='.$user->id.'">'.get_string('blogs','blog').'</a><br />';
b7425e2e 3187 }
da4124be 3188
04186cd9 3189 if (has_capability('moodle/site:viewreports', $context)) {
951b22a8 3190 $timemidnight = usergetmidnight(time());
da4124be 3191 $output .= '<a href="'. $CFG->wwwroot .'/course/user.php?id='. $course->id .'&amp;user='. $user->id .'">'. $string->activity .'</a><br />';
04186cd9 3192 }
3193 if (has_capability('moodle/role:assign', $context, NULL)) { // Includes admins
3194 $output .= '<a href="'. $CFG->wwwroot .'/course/unenrol.php?id='. $course->id .'&amp;user='. $user->id .'">'. $string->unenrol .'</a><br />';
3195 }
3196 if ($USER->id != $user->id && has_capability('moodle/user:loginas', $context)) {
3197 $output .= '<a href="'. $CFG->wwwroot .'/course/loginas.php?id='. $course->id .'&amp;user='. $user->id .'">'. $string->loginas .'</a><br />';
ab9f24ad 3198 }
da4124be 3199 $output .= '<a href="'. $CFG->wwwroot .'/user/view.php?id='. $user->id .'&amp;course='. $course->id .'">'. $string->fullprofile .'...</a>';
951b22a8 3200
04186cd9 3201 if (!empty($messageselect)) {
3202 $output .= '<br /><input type="checkbox" name="user'.$user->id.'" /> ';
f19570d0 3203 }
3204
da4124be 3205 $output .= '</td></tr></table>';
3206
3207 if ($return) {
3208 return $output;
3209 } else {
3210 echo $output;
3211 }
951b22a8 3212}
3213
d48b00b4 3214/**
3215 * Print a specified group's avatar.
3216 *
fdcd0f05 3217 * @param group $group A {@link group} object representing a group or array of groups
89dcb99d 3218 * @param int $courseid ?
3219 * @param boolean $large ?
da4124be 3220 * @param boolean $return ?
89dcb99d 3221 * @param boolean $link ?
3222 * @return string
d48b00b4 3223 * @todo Finish documenting this function
3224 */
da4124be 3225function print_group_picture($group, $courseid, $large=false, $return=false, $link=true) {
f374fb10 3226 global $CFG;
3227
fdcd0f05 3228 if (is_array($group)) {
3229 $output = '';
3230 foreach($group as $g) {
3231 $output .= print_group_picture($g, $courseid, $large, true, $link);
3232 }
da4124be 3233 if ($return) {
fdcd0f05 3234 return $output;
3235 } else {
3236 echo $output;
3237 return;
3238 }
3239 }
3240
ec7a8b79 3241 $context = get_context_instance(CONTEXT_COURSE, $courseid);
97ea4833 3242
ec7a8b79 3243 if ($group->hidepicture and !has_capability('moodle/course:managegroups', $context)) {
3c0561cf 3244