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