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