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