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