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