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