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