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