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