Some improved XHTML
[moodle.git] / lib / weblib.php
CommitLineData
f9903ed0 1<?PHP // $Id$
2
9fa49e22 3///////////////////////////////////////////////////////////////////////////
4// weblib.php - functions for web output
f9903ed0 5//
9fa49e22 6// Library of all general-purpose Moodle PHP functions and constants
7// that produce HTML output
f9903ed0 8//
9fa49e22 9///////////////////////////////////////////////////////////////////////////
10// //
11// NOTICE OF COPYRIGHT //
12// //
13// Moodle - Modular Object-Oriented Dynamic Learning Environment //
14// http://moodle.com //
15// //
16// Copyright (C) 2001-2003 Martin Dougiamas http://dougiamas.com //
17// //
18// This program is free software; you can redistribute it and/or modify //
19// it under the terms of the GNU General Public License as published by //
20// the Free Software Foundation; either version 2 of the License, or //
21// (at your option) any later version. //
22// //
23// This program is distributed in the hope that it will be useful, //
24// but WITHOUT ANY WARRANTY; without even the implied warranty of //
25// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the //
26// GNU General Public License for more details: //
27// //
28// http://www.gnu.org/copyleft/gpl.html //
29// //
30///////////////////////////////////////////////////////////////////////////
f9903ed0 31
0095d5cd 32/// Constants
33
c1d57101 34/// Define text formatting types ... eventually we can add Wiki, BBcode etc
6901fa79 35define("FORMAT_MOODLE", "0"); // Does all sorts of transformations and filtering
d342c763 36define("FORMAT_HTML", "1"); // Plain HTML (with some tags stripped)
37define("FORMAT_PLAIN", "2"); // Plain text (even tags are printed in full)
38define("FORMAT_WIKI", "3"); // Wiki-formatted text
0095d5cd 39
ef5db724 40$ALLOWED_TAGS = "<p><br><b><i><u><font><table><tbody><span><div><tr><td><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>";
3fe3851d 41
42
0095d5cd 43/// Functions
44
3662bce5 45function s($var) {
c1d57101 46/// returns $var with HTML characters (like "<", ">", etc.) properly quoted,
f9903ed0 47
3662bce5 48 if (empty($var)) {
49 return "";
50 }
7d8f674d 51 return htmlSpecialChars(stripslashes_safe($var));
f9903ed0 52}
53
3662bce5 54function p($var) {
c1d57101 55/// prints $var with HTML characters (like "<", ">", etc.) properly quoted,
f9903ed0 56
3662bce5 57 if (empty($var)) {
58 echo "";
59 }
7d8f674d 60 echo htmlSpecialChars(stripslashes_safe($var));
f9903ed0 61}
62
8553b700 63function nvl(&$var, $default="") {
c1d57101 64/// if $var is undefined, return $default, otherwise return $var
8553b700 65
66 return isset($var) ? $var : $default;
67}
f9903ed0 68
69function strip_querystring($url) {
c1d57101 70/// takes a URL and returns it without the querystring portion
f9903ed0 71
b9b8ab69 72 if ($commapos = strpos($url, '?')) {
73 return substr($url, 0, $commapos);
74 } else {
75 return $url;
76 }
f9903ed0 77}
78
79function get_referer() {
c1d57101 80/// returns the URL of the HTTP_REFERER, less the querystring portion
f9903ed0 81
607809b3 82 return strip_querystring(nvl($_SERVER["HTTP_REFERER"]));
f9903ed0 83}
84
c1d57101 85
f9903ed0 86function me() {
c1d57101 87/// returns the name of the current script, WITH the querystring portion.
eaa50dbc 88/// this function is necessary because PHP_SELF and REQUEST_URI and SCRIPT_NAME
c1d57101 89/// return different things depending on a lot of things like your OS, Web
90/// server, and the way PHP is compiled (ie. as a CGI, module, ISAPI, etc.)
f9903ed0 91
607809b3 92 if (!empty($_SERVER["REQUEST_URI"])) {
93 return $_SERVER["REQUEST_URI"];
c1d57101 94
607809b3 95 } else if (!empty($_SERVER["PHP_SELF"])) {
fced815c 96 if (!empty($_SERVER["QUERY_STRING"])) {
97 return $_SERVER["PHP_SELF"]."?".$_SERVER["QUERY_STRING"];
98 }
607809b3 99 return $_SERVER["PHP_SELF"];
c1d57101 100
fced815c 101 } else if (!empty($_SERVER["SCRIPT_NAME"])) {
102 if (!empty($_SERVER["QUERY_STRING"])) {
103 return $_SERVER["SCRIPT_NAME"]."?".$_SERVER["QUERY_STRING"];
104 }
105 return $_SERVER["SCRIPT_NAME"];
106
b9b8ab69 107 } else {
fced815c 108 notify("Warning: Could not find any of these web server variables: \$REQUEST_URI, \$PHP_SELF or \$SCRIPT_NAME");
bcdfe14e 109 return false;
7fbd6b1c 110 }
f9903ed0 111}
112
113
f9903ed0 114function qualified_me() {
c1d57101 115/// like me() but returns a full URL
f9903ed0 116
39e018b3 117 if (!empty($_SERVER["HTTP_HOST"])) {
118 $hostname = $_SERVER["HTTP_HOST"];
119 } else if (!empty($_ENV["HTTP_HOST"])) {
120 $hostname = $_ENV["HTTP_HOST"];
df3fd249 121 } else if (!empty($_SERVER["SERVER_NAME"])) {
122 $hostname = $_SERVER["SERVER_NAME"];
39e018b3 123 } else if (!empty($_ENV["SERVER_NAME"])) {
124 $hostname = $_ENV["SERVER_NAME"];
125 } else {
126 notify("Warning: could not find the name of this server!");
bcdfe14e 127 return false;
c1d57101 128 }
f9903ed0 129
607809b3 130 $protocol = (isset($_SERVER["HTTPS"]) and $_SERVER["HTTPS"] == "on") ? "https://" : "http://";
39e018b3 131 $url_prefix = $protocol.$hostname;
b9b8ab69 132 return $url_prefix . me();
f9903ed0 133}
134
135
a0deb5db 136function match_referer($goodreferer = "") {
137/// returns true if the referer is the same as the goodreferer. If
138/// goodreferer is not specified, use qualified_me as the goodreferer
60f18531 139 global $CFG;
140
ae384ef1 141 if (empty($CFG->secureforms)) { // Don't bother checking referer
60f18531 142 return true;
143 }
f9903ed0 144
ae384ef1 145 if ($goodreferer == "nomatch") { // Don't bother checking referer
a0deb5db 146 return true;
147 }
148
149 if (empty($goodreferer)) {
150 $goodreferer = qualified_me();
c1d57101 151 }
a0deb5db 152 return $goodreferer == get_referer();
f9903ed0 153}
154
36b4f985 155function data_submitted($url="") {
156/// Used on most forms in Moodle to check for data
157/// Returns the data as an object, if it's found.
607809b3 158/// This object can be used in foreach loops without
159/// casting because it's cast to (array) automatically
36b4f985 160///
161/// Checks that submitted POST data exists, and also
162/// checks the referer against the given url (it uses
163/// the current page if none was specified.
164
37208cd2 165 global $CFG;
166
607809b3 167 if (empty($_POST)) {
36b4f985 168 return false;
607809b3 169
36b4f985 170 } else {
171 if (match_referer($url)) {
607809b3 172 return (object)$_POST;
36b4f985 173 } else {
174 if ($CFG->debug > 10) {
175 notice("The form did not come from this page! (referer = ".get_referer().")");
176 }
177 return false;
178 }
179 }
180}
181
7d8f674d 182function stripslashes_safe($string) {
183/// stripslashes() removes ALL backslashes even from strings
184/// so C:\temp becomes C:temp ... this isn't good.
185/// The following should work as a fairly safe replacement
186/// to be called on quoted AND unquoted strings (to be sure)
187
188 $string = str_replace("\\'", "'", $string);
189 $string = str_replace('\\"', '"', $string);
190 $string = str_replace('\\\\', '\\', $string);
191 return $string;
192}
f9903ed0 193
72e4eac6 194if (!function_exists('str_ireplace')) {
195 function str_ireplace($find, $replace, $string ) {
196 /// This does a search and replace, ignoring case
197 /// This function is only here because one doesn't exist yet in PHP
198 /// Unlike str_replace(), this only works on single values (not arrays)
199
200 $parts = explode(strtolower($find), strtolower($string));
201
202 $pos = 0;
203
204 foreach ($parts as $key => $part) {
205 $parts[$key] = substr($string, $pos, strlen($part));
206 $pos += strlen($part) + strlen($find);
207 }
208
209 return (join($replace, $parts));
3fe3851d 210 }
3fe3851d 211}
212
f9903ed0 213function read_template($filename, &$var) {
c1d57101 214/// return a (big) string containing the contents of a template file with all
215/// the variables interpolated. all the variables must be in the $var[] array or
216/// object (whatever you decide to use).
217///
218/// WARNING: do not use this on big files!!
f9903ed0 219
b9b8ab69 220 $temp = str_replace("\\", "\\\\", implode(file($filename), ""));
221 $temp = str_replace('"', '\"', $temp);
222 eval("\$template = \"$temp\";");
223 return $template;
f9903ed0 224}
225
226function checked(&$var, $set_value = 1, $unset_value = 0) {
c1d57101 227/// if variable is set, set it to the set_value otherwise set it to the
228/// unset_value. used to handle checkboxes when you are expecting them from
229/// a form
f9903ed0 230
b9b8ab69 231 if (empty($var)) {
232 $var = $unset_value;
233 } else {
234 $var = $set_value;
235 }
f9903ed0 236}
237
238function frmchecked(&$var, $true_value = "checked", $false_value = "") {
c1d57101 239/// prints the word "checked" if a variable is true, otherwise prints nothing,
240/// used for printing the word "checked" in a checkbox form input
f9903ed0 241
b9b8ab69 242 if ($var) {
243 echo $true_value;
244 } else {
245 echo $false_value;
246 }
f9903ed0 247}
248
249
86aa7ccf 250function link_to_popup_window ($url, $name="popup", $linkname="click here",
b48f834c 251 $height=400, $width=500, $title="Popup window", $options="none") {
c1d57101 252/// This will create a HTML link that will work on both
253/// Javascript and non-javascript browsers.
254/// Relies on the Javascript function openpopup in javascript.php
255/// $url must be relative to home page eg /mod/survey/stuff.php
f9903ed0 256
ff80e012 257 global $CFG;
258
b48f834c 259 if ($options == "none") {
260 $options = "menubar=0,location=0,scrollbars,resizable,width=$width,height=$height";
261 }
86aa7ccf 262 $fullscreen = 0;
f9903ed0 263
55e4b5f9 264 echo "<a target=\"$name\" title=\"$title\" href=\"$CFG->wwwroot$url\" ".
86aa7ccf 265 "onClick=\"return openpopup('$url', '$name', '$options', $fullscreen);\">$linkname</a>\n";
f9903ed0 266}
267
86aa7ccf 268
f9903ed0 269function close_window_button() {
c1d57101 270/// Prints a simple button to close a window
271
86aa7ccf 272 echo "<center>\n";
273 echo "<script>\n";
274 echo "<!--\n";
275 echo "document.write('<form>');\n";
276 echo "document.write('<input type=button onClick=\"self.close();\" value=\"".get_string("closewindow")."\">');\n";
277 echo "document.write('</form>');\n";
278 echo "-->\n";
279 echo "</script>\n";
280 echo "<noscript>\n";
281 echo "<a href=\"".$_SERVER['HTTP_REFERER']."\"><---</a>\n";
282 echo "</noscript>\n";
283 echo "</center>\n";
f9903ed0 284}
285
286
08056730 287function choose_from_menu ($options, $name, $selected="", $nothing="choose", $script="", $nothingvalue="0", $return=false) {
c1d57101 288/// Given an array of value, creates a popup menu to be part of a form
289/// $options["value"]["label"]
f9903ed0 290
618b22c5 291 if ($nothing == "choose") {
292 $nothing = get_string("choose")."...";
293 }
294
f9903ed0 295 if ($script) {
296 $javascript = "onChange=\"$script\"";
9c9f7d77 297 } else {
298 $javascript = "";
f9903ed0 299 }
9c9f7d77 300
76c1650d 301 $output = "<select name=$name $javascript>\n";
bda8d43a 302 if ($nothing) {
76c1650d 303 $output .= " <option value=\"$nothingvalue\"\n";
bda8d43a 304 if ($nothingvalue == $selected) {
76c1650d 305 $output .= " selected";
bda8d43a 306 }
76c1650d 307 $output .= ">$nothing</option>\n";
873960de 308 }
607809b3 309 if (!empty($options)) {
310 foreach ($options as $value => $label) {
76c1650d 311 $output .= " <option value=\"$value\"";
607809b3 312 if ($value == $selected) {
76c1650d 313 $output .= " selected";
607809b3 314 }
a20c1090 315 if ($label === "") {
76c1650d 316 $output .= ">$value</option>\n";
a20c1090 317 } else {
318 $output .= ">$label</option>\n";
607809b3 319 }
f9903ed0 320 }
321 }
76c1650d 322 $output .= "</select>\n";
08056730 323
324 if ($return) {
325 return $output;
326 } else {
327 echo $output;
328 }
f9903ed0 329}
330
16ef5e78 331function popup_form ($common, $options, $formname, $selected="", $nothing="choose", $help="", $helptext="", $return=false, $targetwindow="self") {
c1d57101 332/// Implements a complete little popup form
333/// $common = the URL up to the point of the variable that changes
334/// $options = A list of value-label pairs for the popup list
335/// $formname = name must be unique on the page
336/// $selected = the option that is already selected
337/// $nothing = The label for the "no choice" option
e5dfd0f3 338/// $help = The name of a help page if help is required
339/// $helptext = The name of the label for the help button
5b472756 340/// $return = Boolean indicating whether the function should return the text
341/// as a string or echo it directly to the page being rendered
f9903ed0 342
0d0baabf 343 global $CFG;
344
618b22c5 345 if ($nothing == "choose") {
346 $nothing = get_string("choose")."...";
347 }
348
dfec7b01 349 $startoutput = "<form target=\"{$CFG->framename}\" name=$formname>";
16ef5e78 350 $output = "<select name=popup onchange=\"$targetwindow.location=document.$formname.popup.options[document.$formname.popup.selectedIndex].value\">\n";
f9903ed0 351
352 if ($nothing != "") {
dfec7b01 353 $output .= " <option value=\"javascript:void(0)\">$nothing</option>\n";
f9903ed0 354 }
355
356 foreach ($options as $value => $label) {
d897cae4 357 if (substr($label,0,1) == "-") {
dfec7b01 358 $output .= " <option value=\"\"";
d897cae4 359 } else {
dfec7b01 360 $output .= " <option value=\"$common$value\"";
d897cae4 361 if ($value == $selected) {
dfec7b01 362 $output .= " selected";
d897cae4 363 }
f9903ed0 364 }
365 if ($label) {
dfec7b01 366 $output .= ">$label</option>\n";
f9903ed0 367 } else {
dfec7b01 368 $output .= ">$value</option>\n";
f9903ed0 369 }
370 }
dfec7b01 371 $output .= "</select>";
372 $output .= "</form>\n";
d897cae4 373
374 if ($return) {
dfec7b01 375 return $startoutput.$output;
d897cae4 376 } else {
dfec7b01 377 echo $startoutput;
9c9f7d77 378 if ($help) {
379 helpbutton($help, $helptext);
380 }
d897cae4 381 echo $output;
382 }
f9903ed0 383}
384
385
386
387function formerr($error) {
c1d57101 388/// Prints some red text
f9903ed0 389 if (!empty($error)) {
390 echo "<font color=#ff0000>$error</font>";
391 }
392}
393
394
395function validate_email ($address) {
c1d57101 396/// Validates an email to make it makes sense.
f9903ed0 397 return (ereg('^[-!#$%&\'*+\\./0-9=?A-Z^_`a-z{|}~]+'.
398 '@'.
399 '[-!#$%&\'*+\\/0-9=?A-Z^_`a-z{|}~]+\.'.
400 '[-!#$%&\'*+\\./0-9=?A-Z^_`a-z{|}~]+$',
401 $address));
402}
403
6c8e8b5e 404function detect_munged_arguments($string) {
393c9b4f 405 if (ereg('\.\.', $string)) { // check for parent URLs
6c8e8b5e 406 return true;
407 }
393c9b4f 408 if (ereg('[\|\`]', $string)) { // check for other bad characters
6c8e8b5e 409 return true;
410 }
411 return false;
412}
413
6ed3da1d 414function get_slash_arguments($file="file.php") {
415/// Searches the current environment variables for some slash arguments
f9903ed0 416
eaa50dbc 417 if (!$string = me()) {
f9903ed0 418 return false;
419 }
eaa50dbc 420
6ed3da1d 421 $pathinfo = explode($file, $string);
422
bcdfe14e 423 if (!empty($pathinfo[1])) {
424 return $pathinfo[1];
6ed3da1d 425 } else {
426 return false;
427 }
428}
429
430function parse_slash_arguments($string, $i=0) {
431/// Extracts arguments from "/foo/bar/something"
432/// eg http://mysite.com/script.php/foo/bar/something
f9903ed0 433
6c8e8b5e 434 if (detect_munged_arguments($string)) {
780db230 435 return false;
436 }
6ed3da1d 437 $args = explode("/", $string);
f9903ed0 438
439 if ($i) { // return just the required argument
440 return $args[$i];
441
442 } else { // return the whole array
443 array_shift($args); // get rid of the empty first one
444 return $args;
445 }
446}
447
0095d5cd 448function format_text_menu() {
c1d57101 449/// Just returns an array of formats suitable for a popup menu
0095d5cd 450 return array (FORMAT_MOODLE => get_string("formattext"),
6901fa79 451 FORMAT_HTML => get_string("formathtml"),
d342c763 452 FORMAT_PLAIN => get_string("formatplain"),
453 FORMAT_WIKI => get_string("formatwiki"));
0095d5cd 454}
455
60f18531 456function format_text($text, $format=FORMAT_MOODLE, $options=NULL) {
c1d57101 457/// Given text in a variety of format codings, this function returns
458/// the text as safe HTML.
459///
460/// $text is raw text (originally from a user)
461/// $format is one of the format constants, defined above
0095d5cd 462
a751a4e5 463 global $CFG;
464
0095d5cd 465 switch ($format) {
73f8658c 466 case FORMAT_HTML:
5f350e8f 467 replace_smilies($text);
73f8658c 468 return $text;
469 break;
470
6901fa79 471 case FORMAT_PLAIN:
472 $text = htmlentities($text);
3405b212 473 $text = str_replace(" ", "&nbsp; ", $text);
5f350e8f 474 replace_smilies($text);
6901fa79 475 $text = nl2br($text);
476 return $text;
477 break;
478
d342c763 479 case FORMAT_WIKI:
7f9bd7b9 480 return wiki_to_html($text);
d342c763 481 break;
482
73f8658c 483 default: // FORMAT_MOODLE or anything else
c9dda990 484 if (!isset($options->smiley)) {
485 $options->smiley=true;
486 }
487 if (!isset($options->para)) {
1a072208 488 $options->para=true;
c9dda990 489 }
0095d5cd 490 return text_to_html($text, $options->smiley, $options->para);
491 break;
0095d5cd 492 }
493}
494
d342c763 495function format_text_email($text, $format) {
496/// Given text in a variety of format codings, this function returns
497/// the text as plain text suitable for plain email.
498///
499/// $text is raw text (originally from a user)
500/// $format is one of the format constants, defined above
501
502 switch ($format) {
503
504 case FORMAT_PLAIN:
505 return $text;
506 break;
507
508 case FORMAT_WIKI:
509 $text = wiki_to_html($text);
5b472756 510 /// This expression turns links into something nice in a text format. (Russell Jungwirth)
511 /// From: http://php.net/manual/en/function.eregi-replace.php and simplified
512 $text = eregi_replace('(<a [^<]*href=["|\']?([^ "\']*)["|\']?[^>]*>([^<]*)</a>)','\\3 [\\2]', $text);
7c55a29b 513 return strtr(strip_tags($text), array_flip(get_html_translation_table(HTML_ENTITIES)));
d342c763 514 break;
515
516 default: // FORMAT_MOODLE or anything else
5b472756 517 $text = eregi_replace('(<a [^<]*href=["|\']?([^ "\']*)["|\']?[^>]*>([^<]*)</a>)','\\3 [\\2]', $text);
7c55a29b 518 return strtr(strip_tags($text), array_flip(get_html_translation_table(HTML_ENTITIES)));
d342c763 519 break;
520 }
521}
0095d5cd 522
523function clean_text($text, $format) {
c1d57101 524/// Given raw text (eg typed in by a user), this function cleans it up
525/// and removes any nasty tags that could mess up Moodle pages.
b7a3cf49 526
fc120758 527 global $ALLOWED_TAGS;
3fe3851d 528
d342c763 529 switch ($format) {
0095d5cd 530 case FORMAT_MOODLE:
0095d5cd 531 case FORMAT_HTML:
d342c763 532 case FORMAT_WIKI:
5b472756 533 /// Remove javascript: label
3fe3851d 534 $text = strip_tags($text, $ALLOWED_TAGS);
5b472756 535 /// Remove javascript/VBScript
536 $text = str_ireplace("javascript:", "xxx", $text);
537 /// Remove script events
538 $text = eregi_replace("([^a-z])language([[:space:]]*)=", "xxx", $text);
539 $text = eregi_replace("([^a-z])on([a-z]+)([[:space:]]*)=", "xxx", $text);
3fe3851d 540 return $text;
6901fa79 541
542 case FORMAT_PLAIN:
543 return $text;
0095d5cd 544 }
b7a3cf49 545}
f9903ed0 546
5f350e8f 547function replace_smilies(&$text) {
c1d57101 548/// Replaces all known smileys in the text with image equivalents
2ea9027b 549 global $CFG;
c1d57101 550
5b472756 551/// this builds the mapping array only once
617778f2 552 static $runonce = false;
69081931 553 static $e = array();
554 static $img = array();
617778f2 555 static $emoticons = array(
2ea9027b 556 ':-)' => 'smiley.gif',
557 ':)' => 'smiley.gif',
558 ':-D' => 'biggrin.gif',
559 ';-)' => 'wink.gif',
560 ':-/' => 'mixed.gif',
561 'V-.' => 'thoughtful.gif',
562 ':-P' => 'tongueout.gif',
563 'B-)' => 'cool.gif',
564 '^-)' => 'approve.gif',
565 '8-)' => 'wideeyes.gif',
566 ':o)' => 'clown.gif',
567 ':-(' => 'sad.gif',
568 ':(' => 'sad.gif',
569 '8-.' => 'shy.gif',
570 ':-I' => 'blush.gif',
571 ':-X' => 'kiss.gif',
572 '8-o' => 'surprise.gif',
573 'P-|' => 'blackeye.gif',
574 '8-[' => 'angry.gif',
575 'xx-P' => 'dead.gif',
576 '|-.' => 'sleepy.gif',
577 '}-]' => 'evil.gif',
578 );
579
5b472756 580 /// this is the meat of the code - this is run every time
581 if ($runonce == false){
617778f2 582 foreach ($emoticons as $emoticon => $image){
69081931 583 $e[] = $emoticon;
c9f6251e 584 $img[] = "<img alt=\"$emoticon\" width=15 height=15 src=\"$CFG->pixpath/s/$image\">";
617778f2 585 }
586 $runonce = true;
c0f728ba 587 }
b7a3cf49 588
5f350e8f 589 $text = str_replace($e, $img, $text);
1a072208 590}
0095d5cd 591
909f539d 592function text_to_html($text, $smiley=true, $para=true) {
c1d57101 593/// Given plain text, makes it into HTML as nicely as possible.
594/// May contain HTML tags already
f9903ed0 595
27326a3e 596 global $CFG;
597
c1d57101 598/// Remove any whitespace that may be between HTML tags
7b3be1b1 599 $text = eregi_replace(">([[:space:]]+)<", "><", $text);
600
c1d57101 601/// Remove any returns that precede or follow HTML tags
0eae8049 602 $text = eregi_replace("([\n\r])<", " <", $text);
603 $text = eregi_replace(">([\n\r])", "> ", $text);
7b3be1b1 604
5f350e8f 605 convert_urls_into_links($text);
f9903ed0 606
c1d57101 607/// Make returns into HTML newlines.
f9903ed0 608 $text = nl2br($text);
609
27326a3e 610/// Insert links to library pages if Library is being used
611 if (!empty($CFG->librarypath)) {
612 if (file_exists("$CFG->dirroot/$CFG->librarypath/librarylib.php")) {
613 include_once("$CFG->dirroot/$CFG->librarypath/librarylib.php");
614 $text = librarytexttohtml($text);
615 }
616 }
617
c1d57101 618/// Turn smileys into images.
d69cb7f4 619 if ($smiley) {
5f350e8f 620 replace_smilies($text);
d69cb7f4 621 }
f9903ed0 622
c1d57101 623/// Wrap the whole thing in a paragraph tag if required
909f539d 624 if ($para) {
01d79966 625 return "<p>".$text."</p>";
909f539d 626 } else {
627 return $text;
628 }
f9903ed0 629}
630
3e9ca9fb 631function wiki_to_html($text) {
01d79966 632/// Given Wiki formatted text, make it into XHTML using external function
43373804 633 global $CFG;
3e9ca9fb 634
43373804 635 require_once("$CFG->libdir/wiki.php");
3e9ca9fb 636
01d79966 637 $wiki = new Wiki;
638 return $wiki->format($text);
3e9ca9fb 639}
640
5f350e8f 641function convert_urls_into_links(&$text) {
642/// Given some text, it converts any URLs it finds into HTML links.
643
644/// Make lone URLs into links. eg http://moodle.com/
3405b212 645 $text = eregi_replace("([[:space:]]|^|\(|\[)([[:alnum:]]+)://([^[:space:]]*)([[:alnum:]#?/&=])",
88438a58 646 "\\1<a href=\"\\2://\\3\\4\" target=\"newpage\">\\2://\\3\\4</a>", $text);
5f350e8f 647
648/// eg www.moodle.com
3405b212 649 $text = eregi_replace("([[:space:]]|^|\(|\[)www\.([^[:space:]]*)([[:alnum:]#?/&=])",
88438a58 650 "\\1<a href=\"http://www.\\2\\3\" target=\"newpage\">www.\\2\\3</a>", $text);
5f350e8f 651}
652
88438a58 653function highlight($needle, $haystack, $case=0,
654 $left_string="<span class=\"highlight\">", $right_string="</span>") {
655/// This function will highlight search words in a given string
656/// It cares about HTML and will not ruin links. It's best to use
657/// this function after performing any conversions to HTML.
658/// Function found here: http://forums.devshed.com/t67822/scdaa2d1c3d4bacb4671d075ad41f0854.html
659
660 $list_of_words = eregi_replace("[^-a-zA-Z0-9&']", " ", $needle);
661 $list_array = explode(" ", $list_of_words);
662 for ($i=0; $i<sizeof($list_array); $i++) {
663 if (strlen($list_array[$i]) == 1) {
664 $list_array[$i] = "";
665 }
666 }
667 $list_of_words = implode(" ", $list_array);
668 $list_of_words_cp = $list_of_words;
669 $final = array();
670 preg_match_all('/<(.+?)>/is',$haystack,$list_of_words);
671
672 foreach (array_unique($list_of_words[0]) as $key=>$value) {
673 $final['<|'.$key.'|>'] = $value;
674 }
675
676 $haystack = str_replace($final,array_keys($final),$haystack);
677 $list_of_words_cp = eregi_replace(" +", "|", $list_of_words_cp);
678
679 if ($list_of_words_cp{0}=="|") {
680 $list_of_words_cp{0} = "";
681 }
682 if ($list_of_words_cp{strlen($list_of_words_cp)-1}=="|") {
683 $list_of_words_cp{strlen($list_of_words_cp)-1}="";
684 }
685 $list_of_words_cp = "(".trim($list_of_words_cp).")";
686
687 if (!$case){
688 $haystack = eregi_replace("$list_of_words_cp", "$left_string"."\\1"."$right_string", $haystack);
689 } else {
690 $haystack = ereg_replace("$list_of_words_cp", "$left_string"."\\1"."$right_string", $haystack);
691 }
692 $haystack = str_replace(array_keys($final),$final,$haystack);
693
694 return stripslashes($haystack);
695}
696
697function highlightfast($needle, $haystack) {
c1d57101 698/// This function will highlight instances of $needle in $haystack
88438a58 699/// It's faster that the above function and doesn't care about
700/// HTML or anything.
5af78ed2 701
702 $parts = explode(strtolower($needle), strtolower($haystack));
703
704 $pos = 0;
705
706 foreach ($parts as $key => $part) {
707 $parts[$key] = substr($haystack, $pos, strlen($part));
708 $pos += strlen($part);
709
88438a58 710 $parts[$key] .= "<span class=\"highlight\">".substr($haystack, $pos, strlen($needle))."</span>";
5af78ed2 711 $pos += strlen($needle);
712 }
713
714 return (join('', $parts));
715}
716
f9903ed0 717
9fa49e22 718/// STANDARD WEB PAGE PARTS ///////////////////////////////////////////////////
719
720function print_header ($title="", $heading="", $navigation="", $focus="", $meta="", $cache=true, $button="&nbsp;", $menu="") {
721// $title - appears top of window
722// $heading - appears top of page
723// $navigation - premade navigation string
724// $focus - indicates form element eg inputform.password
725// $meta - meta tags in the header
726// $cache - should this page be cacheable?
727// $button - HTML code for a button (usually for module editing)
728// $menu - HTML code for a popup menu
e825f279 729 global $USER, $CFG, $THEME, $SESSION;
9fa49e22 730
731 if (file_exists("$CFG->dirroot/theme/$CFG->theme/styles.php")) {
732 $styles = $CFG->stylesheet;
733 } else {
734 $styles = "$CFG->wwwroot/theme/standard/styles.php";
735 }
736
737 if ($navigation == "home") {
738 $home = true;
739 $navigation = "";
9d378732 740 } else {
741 $home = false;
9fa49e22 742 }
743
744 if ($button == "") {
745 $button = "&nbsp;";
746 }
747
748 if (!$menu and $navigation) {
749 if (isset($USER->id)) {
c6a0f9d5 750 $menu = "<font size=2><a target=\"$CFG->framename\" href=\"$CFG->wwwroot/login/logout.php\">".get_string("logout")."</a></font>";
9fa49e22 751 } else {
c6a0f9d5 752 $menu = "<font size=2><a target=\"$CFG->framename\" href=\"$CFG->wwwroot/login/index.php\">".get_string("login")."</a></font>";
9fa49e22 753 }
754 }
755
756 // Specify character set ... default is iso-8859-1 but some languages might need something else
757 // Could be optimised by carrying the charset variable around in $USER
758 if (current_language() == "en") {
107b010b 759 $meta = "<meta http-equiv=\"content-type\" content=\"text/html; charset=iso-8859-1\">\n$meta\n";
9fa49e22 760 } else {
107b010b 761 $meta = "<meta http-equiv=\"content-type\" content=\"text/html; charset=".get_string("thischarset")."\">\n$meta\n";
9fa49e22 762 }
763
3662bce5 764 if (!empty($CFG->langdir) and $CFG->langdir == "RTL") {
107b010b 765 $direction = " dir=\"rtl\"";
9fa49e22 766 } else {
107b010b 767 $direction = " dir=\"ltr\"";
9fa49e22 768 }
769
770 if (!$cache) { // Do everything we can to prevent clients and proxies caching
771 @header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
772 @header("Pragma: no-cache");
76c1650d 773 $meta .= "\n<meta http-equiv=\"pragma\" content=\"no-cache\">";
774 $meta .= "\n<meta http-equiv=\"expires\" content=\"0\">";
9fa49e22 775 }
776
777 include ("$CFG->dirroot/theme/$CFG->theme/header.html");
778}
779
780function print_footer ($course=NULL) {
781// Can provide a course object to make the footer contain a link to
782// to the course home page, otherwise the link will go to the site home
783 global $USER, $CFG, $THEME;
784
785
786/// Course links
787 if ($course) {
788 if ($course == "home") { // special case for site home page - please do not remove
76c1650d 789 $homelink = "<p align=\"center\"><a title=\"moodle $CFG->release ($CFG->version)\" href=\"http://moodle.org/\" target=\"_blank\">";
67a63a30 790 $homelink .= "<br><img width=\"130\" height=\"19\" src=\"pix/madewithmoodle.gif\" border=0></a></p>";
9fa49e22 791 $course = get_site();
792 $homepage = true;
793 } else {
76c1650d 794 $homelink = "<a target=\"{$CFG->framename}\" href=\"$CFG->wwwroot/course/view.php?id=$course->id\">$course->shortname</a>";
9fa49e22 795 }
796 } else {
c2cb4545 797 $homelink = "<a target=\"{$CFG->framename}\" href=\"$CFG->wwwroot/\">".get_string("home")."</a>";
9fa49e22 798 $course = get_site();
799 }
800
801/// User links
a282d0ff 802 $loggedinas = user_login_string($course, $USER);
803
804 include ("$CFG->dirroot/theme/$CFG->theme/footer.html");
805}
806
1ddf9329 807function style_sheet_setup($lastmodified=0, $lifetime=300, $themename="") {
808/// This function is called by stylesheets to set up the header
809/// approriately as well as the current path
6535be85 810
811 global $CFG;
812
813 header("Last-Modified: " . gmdate("D, d M Y H:i:s", $lastmodified) . " GMT");
814 header("Expires: " . gmdate("D, d M Y H:i:s", time() + $lifetime) . " GMT");
815 header("Cache-control: max_age = $lifetime");
816 header("Pragma: ");
817 header("Content-type: text/css"); // Correct MIME type
818
819 if (!empty($themename)) {
820 $CFG->theme = $themename;
821 }
822
823 return "$CFG->wwwroot/theme/$CFG->theme";
824
825}
826
a282d0ff 827
828function user_login_string($course, $user=NULL) {
829 global $USER, $CFG;
830
8d2accb6 831 if (empty($user)) {
a282d0ff 832 $user = $USER;
833 }
834
835 if (isset($user->realuser)) {
836 if ($realuser = get_record("user", "id", $user->realuser)) {
ca16eaeb 837 $realuserinfo = " [<a target=\"{$CFG->framename}\" href=\"$CFG->wwwroot/course/loginas.php?id=$course->id&return=$realuser->id\">$realuser->firstname $realuser->lastname</A>] ";
9fa49e22 838 }
9d378732 839 } else {
840 $realuserinfo = "";
9fa49e22 841 }
842
a282d0ff 843 if (isset($user->id) and $user->id) {
ca16eaeb 844 $username = "<a target=\"{$CFG->framename}\" href=\"$CFG->wwwroot/user/view.php?id=$user->id&course=$course->id\">$user->firstname $user->lastname</a>";
9fa49e22 845 $loggedinas = $realuserinfo.get_string("loggedinas", "moodle", "$username").
ca16eaeb 846 " (<a target=\"{$CFG->framename}\" href=\"$CFG->wwwroot/login/logout.php\">".get_string("logout")."</a>)";
9fa49e22 847 } else {
848 $loggedinas = get_string("loggedinnot", "moodle").
ca16eaeb 849 " (<a target=\"{$CFG->framename}\" href=\"$CFG->wwwroot/login/index.php\">".get_string("login")."</a>)";
9fa49e22 850 }
a282d0ff 851 return $loggedinas;
9fa49e22 852}
853
854
9fa49e22 855function print_navigation ($navigation) {
856 global $CFG;
857
858 if ($navigation) {
859 if (! $site = get_site()) {
860 $site->shortname = get_string("home");;
861 }
eb347b6b 862 echo "<a target=\"{$CFG->framename}\" href=\"$CFG->wwwroot/\">$site->shortname</a> -> $navigation";
9fa49e22 863 }
864}
865
d4df9200 866function print_headline($text, $size=2) {
867 echo "<b><font size=\"$size\">$text</font></b><br />\n";
868}
869
76c1650d 870function print_heading($text, $align="center", $size=3) {
871 echo "<p align=\"$align\"><font size=\"$size\"><b>".stripslashes_safe($text)."</b></font></p>";
9fa49e22 872}
873
c9f6251e 874function print_heading_with_help($text, $helppage, $module="moodle", $icon="") {
9fa49e22 875// Centered heading with attached help button (same title text)
c9f6251e 876// and optional icon attached
877 echo "<p align=\"center\"><font size=\"3\">$icon<b>".stripslashes_safe($text);
9fa49e22 878 helpbutton($helppage, $text, $module);
eb347b6b 879 echo "</b></font></p>";
9fa49e22 880}
881
882function print_continue($link) {
9fa49e22 883
884 if (!$link) {
607809b3 885 $link = $_SERVER["HTTP_REFERER"];
9fa49e22 886 }
887
eb347b6b 888 print_heading("<a href=\"$link\">".get_string("continue")."</a>");
9fa49e22 889}
890
891
892function print_simple_box($message, $align="", $width="", $color="#FFFFFF", $padding=5, $class="generalbox") {
893 print_simple_box_start($align, $width, $color, $padding, $class);
7d8f674d 894 echo stripslashes_safe($message);
9fa49e22 895 print_simple_box_end();
896}
897
898function print_simple_box_start($align="", $width="", $color="#FFFFFF", $padding=5, $class="generalbox") {
899 global $THEME;
900
901 if ($align) {
76c1650d 902 $align = "align=\"$align\"";
9fa49e22 903 }
904 if ($width) {
76c1650d 905 $width = "width=\"$width\"";
9fa49e22 906 }
9d378732 907 echo "<table $align $width class=\"$class\" border=\"0\" cellpadding=\"$padding\" cellspacing=\"0\"><tr><td bgcolor=\"$color\" class=\"$class"."content\">";
9fa49e22 908}
909
910function print_simple_box_end() {
911 echo "</td></tr></table>";
912}
913
cc7fa0dc 914function print_single_button($link, $options, $label="OK", $method="get") {
915 echo "<form action=\"$link\" method=\"$method\">";
9fa49e22 916 if ($options) {
917 foreach ($options as $name => $value) {
76c1650d 918 echo "<input type=hidden name=\"$name\" value=\"$value\">";
9fa49e22 919 }
920 }
76c1650d 921 echo "<input type=submit value=\"$label\"></form>";
9fa49e22 922}
923
924function print_spacer($height=1, $width=1, $br=true) {
925 global $CFG;
76c1650d 926 echo "<img height=\"$height\" width=\"$width\" src=\"$CFG->wwwroot/pix/spacer.gif\" alt=\"\">";
9fa49e22 927 if ($br) {
76c1650d 928 echo "<br />\n";
9fa49e22 929 }
930}
931
932function print_file_picture($path, $courseid=0, $height="", $width="", $link="") {
933// Given the path to a picture file in a course, or a URL,
934// this function includes the picture in the page.
935 global $CFG;
936
937 if ($height) {
76c1650d 938 $height = "height=\"$height\"";
9fa49e22 939 }
940 if ($width) {
76c1650d 941 $width = "width=\"$width\"";
9fa49e22 942 }
943 if ($link) {
76c1650d 944 echo "<a href=\"$link\">";
9fa49e22 945 }
946 if (substr(strtolower($path), 0, 7) == "http://") {
76c1650d 947 echo "<img border=0 $height $width src=\"$path\">";
9fa49e22 948
949 } else if ($courseid) {
76c1650d 950 echo "<img border=0 $height $width src=\"";
9fa49e22 951 if ($CFG->slasharguments) { // Use this method if possible for better caching
952 echo "$CFG->wwwroot/file.php/$courseid/$path";
953 } else {
3f396065 954 echo "$CFG->wwwroot/file.php?file=/$courseid/$path";
9fa49e22 955 }
956 echo "\">";
957 } else {
958 echo "Error: must pass URL or course";
959 }
960 if ($link) {
76c1650d 961 echo "</a>";
9fa49e22 962 }
963}
964
965function print_user_picture($userid, $courseid, $picture, $large=false, $returnstring=false, $link=true) {
67a63a30 966 global $CFG, $THEME;
9fa49e22 967
968 if ($link) {
76c1650d 969 $output = "<a href=\"$CFG->wwwroot/user/view.php?id=$userid&course=$courseid\">";
9fa49e22 970 } else {
971 $output = "";
972 }
973 if ($large) {
67a63a30 974 $file = "f1";
9fa49e22 975 $size = 100;
976 } else {
67a63a30 977 $file = "f2";
9fa49e22 978 $size = 35;
979 }
67a63a30 980 if ($picture) { // Print custom user picture
9fa49e22 981 if ($CFG->slasharguments) { // Use this method if possible for better caching
67a63a30 982 $output .= "<img align=\"absmiddle\" src=\"$CFG->wwwroot/user/pix.php/$userid/$file.jpg\"".
983 " border=\"0\" width=\"$size\" height=\"$size\" alt=\"\">";
9fa49e22 984 } else {
67a63a30 985 $output .= "<img align=\"absmiddle\" src=\"$CFG->wwwroot/user/pix.php?file=/$userid/$file.jpg\"".
986 " border=\"0\" width=\"$size\" height=\"$size\" alt=\"\">";
9fa49e22 987 }
67a63a30 988 } else { // Print default user pictures (use theme version if available)
c9f6251e 989 $output .= "<img align=\"absmiddle\" src=\"$CFG->pixpath/u/$file.png\"".
990 " border=\"0\" width=\"$size\" height=\"$size\" alt=\"\">";
9fa49e22 991 }
992 if ($link) {
76c1650d 993 $output .= "</a>";
9fa49e22 994 }
995
996 if ($returnstring) {
997 return $output;
998 } else {
999 echo $output;
1000 }
1001}
1002
1003function print_table($table) {
1004// Prints a nicely formatted table.
1005// $table is an object with several properties.
1006// $table->head is an array of heading names.
1007// $table->align is an array of column alignments
1008// $table->size is an array of column sizes
5867bfb5 1009// $table->wrap is an array of "nowrap"s or nothing
9fa49e22 1010// $table->data[] is an array of arrays containing the data.
1011// $table->width is an percentage of the page
1012// $table->cellpadding padding on each cell
1013// $table->cellspacing spacing between cells
1014
1015 if (isset($table->align)) {
1016 foreach ($table->align as $key => $aa) {
1017 if ($aa) {
76c1650d 1018 $align[$key] = " align=\"$aa\"";
9fa49e22 1019 } else {
1020 $align[$key] = "";
1021 }
1022 }
1023 }
1024 if (isset($table->size)) {
1025 foreach ($table->size as $key => $ss) {
1026 if ($ss) {
76c1650d 1027 $size[$key] = " width=\"$ss\"";
9fa49e22 1028 } else {
1029 $size[$key] = "";
1030 }
1031 }
1032 }
5867bfb5 1033 if (isset($table->wrap)) {
1034 foreach ($table->wrap as $key => $ww) {
1035 if ($ww) {
76c1650d 1036 $wrap[$key] = " nowrap ";
5867bfb5 1037 } else {
1038 $wrap[$key] = "";
1039 }
1040 }
1041 }
9fa49e22 1042
9d378732 1043 if (empty($table->width)) {
9fa49e22 1044 $table->width = "80%";
1045 }
1046
9d378732 1047 if (empty($table->cellpadding)) {
9fa49e22 1048 $table->cellpadding = "5";
1049 }
1050
9d378732 1051 if (empty($table->cellspacing)) {
9fa49e22 1052 $table->cellspacing = "1";
1053 }
1054
5867bfb5 1055 print_simple_box_start("center", "$table->width", "#ffffff", 0);
1056 echo "<table width=100% border=0 valign=top align=center ";
9fa49e22 1057 echo " cellpadding=\"$table->cellpadding\" cellspacing=\"$table->cellspacing\" class=\"generaltable\">\n";
1058
b79f41cd 1059 if (!empty($table->head)) {
5867bfb5 1060 echo "<tr>";
9fa49e22 1061 foreach ($table->head as $key => $heading) {
9d378732 1062 if (!isset($size[$key])) {
1063 $size[$key] = "";
1064 }
1065 if (!isset($align[$key])) {
1066 $align[$key] = "";
1067 }
5867bfb5 1068 echo "<th valign=top ".$align[$key].$size[$key]." nowrap class=\"generaltableheader\">$heading</th>";
9fa49e22 1069 }
1070 echo "</TR>\n";
1071 }
1072
1073 foreach ($table->data as $row) {
5867bfb5 1074 echo "<tr valign=top>";
9fa49e22 1075 foreach ($row as $key => $item) {
9d378732 1076 if (!isset($size[$key])) {
1077 $size[$key] = "";
1078 }
1079 if (!isset($align[$key])) {
1080 $align[$key] = "";
1081 }
5867bfb5 1082 if (!isset($wrap[$key])) {
1083 $wrap[$key] = "";
1084 }
1085 echo "<td ".$align[$key].$size[$key].$wrap[$key]." class=\"generaltablecell\">$item</td>";
9fa49e22 1086 }
5867bfb5 1087 echo "</tr>\n";
9fa49e22 1088 }
5867bfb5 1089 echo "</table>\n";
9fa49e22 1090 print_simple_box_end();
1091
1092 return true;
1093}
1094
2f4d324b 1095function make_table($table) {
1096// Creates a nicely formatted table and returns it
1097// $table is an object with several properties.
1098// $table->head is an array of heading names.
1099// $table->align is an array of column alignments
1100// $table->size is an array of column sizes
1101// $table->wrap is an array of "nowrap"s or nothing
1102// $table->data[] is an array of arrays containing the data.
1103// $table->width is an percentage of the page
1104// $table->class is a class
1105// $table->fontsize is the size of all the text
1106// $table->tablealign align the whole table
1107// $table->cellpadding padding on each cell
1108// $table->cellspacing spacing between cells
1109
1110 if (isset($table->align)) {
1111 foreach ($table->align as $key => $aa) {
1112 if ($aa) {
1113 $align[$key] = " align=\"$aa\"";
1114 } else {
1115 $align[$key] = "";
1116 }
1117 }
1118 }
1119 if (isset($table->size)) {
1120 foreach ($table->size as $key => $ss) {
1121 if ($ss) {
1122 $size[$key] = " width=\"$ss\"";
1123 } else {
1124 $size[$key] = "";
1125 }
1126 }
1127 }
1128 if (isset($table->wrap)) {
1129 foreach ($table->wrap as $key => $ww) {
1130 if ($ww) {
1131 $wrap[$key] = " nowrap ";
1132 } else {
1133 $wrap[$key] = "";
1134 }
1135 }
1136 }
1137
1138 if (empty($table->width)) {
1139 $table->width = "80%";
1140 }
1141
1142 if (empty($table->tablealign)) {
1143 $table->tablealign = "center";
1144 }
1145
1146 if (empty($table->cellpadding)) {
1147 $table->cellpadding = "5";
1148 }
1149
1150 if (empty($table->cellspacing)) {
1151 $table->cellspacing = "1";
1152 }
1153
1154 if (empty($table->class)) {
1155 $table->class = "generaltable";
1156 }
1157
1158 if (empty($table->fontsize)) {
1159 $fontsize = "";
1160 } else {
1161 $fontsize = "<font size=\"$table->fontsize\">";
1162 }
1163
1164 $output = "<table width=\"$table->width\" valign=top align=\"$table->tablealign\" ";
1165 $output .= " cellpadding=\"$table->cellpadding\" cellspacing=\"$table->cellspacing\" class=\"$table->class\">\n";
1166
1167 if (!empty($table->head)) {
1168 $output .= "<tr>";
1169 foreach ($table->head as $key => $heading) {
1170 if (!isset($size[$key])) {
1171 $size[$key] = "";
1172 }
1173 if (!isset($align[$key])) {
1174 $align[$key] = "";
1175 }
1176 $output .= "<th valign=top ".$align[$key].$size[$key]." nowrap class=\"{$table->class}header\">$fontsize$heading</th>";
1177 }
1178 $output .= "</tr>\n";
1179 }
1180
1181 foreach ($table->data as $row) {
1182 $output .= "<tr valign=top>";
1183 foreach ($row as $key => $item) {
1184 if (!isset($size[$key])) {
1185 $size[$key] = "";
1186 }
1187 if (!isset($align[$key])) {
1188 $align[$key] = "";
1189 }
1190 if (!isset($wrap[$key])) {
1191 $wrap[$key] = "";
1192 }
1193 $output .= "<td ".$align[$key].$size[$key].$wrap[$key]." class=\"{$table->class}cell\">$fontsize$item</td>";
1194 }
1195 $output .= "</tr>\n";
1196 }
1197 $output .= "</table>\n";
1198
1199 return $output;
1200}
1201
9fa49e22 1202function print_textarea($richedit, $rows, $cols, $width, $height, $name, $value="") {
7d8f674d 1203/// Prints a richtext field or a normal textarea
9fa49e22 1204 global $CFG, $THEME;
1205
1206 if ($richedit) {
76c1650d 1207 echo "<object id=richedit style=\"background-color: buttonface\"";
9fa49e22 1208 echo " data=\"$CFG->wwwroot/lib/rte/richedit.html\"";
1209 echo " width=\"$width\" height=\"$height\" ";
1210 echo " type=\"text/x-scriptlet\" VIEWASTEXT></object>\n";
76c1650d 1211 echo "<textarea style=\"display:none\" name=\"$name\" rows=1 cols=1>";
9fa49e22 1212 p($value);
76c1650d 1213 echo "</textarea>\n";
9fa49e22 1214 } else {
76c1650d 1215 echo "<textarea name=\"$name\" rows=\"$rows\" cols=\"$cols\" wrap=virtual>";
9fa49e22 1216 p($value);
76c1650d 1217 echo "</textarea>\n";
9fa49e22 1218 }
1219}
1220
1221function print_richedit_javascript($form, $name, $source="no") {
76c1650d 1222 echo "<script language=\"javascript\" event=\"onload\" for=\"window\">\n";
9fa49e22 1223 echo " document.richedit.options = \"history=no;source=$source\";";
1224 echo " document.richedit.docHtml = $form.$name.innerText;";
76c1650d 1225 echo "</script>";
9fa49e22 1226}
1227
1228
1229function update_course_icon($courseid) {
1230// Used to be an icon, but it's now a simple form button
1231 global $CFG, $USER;
1232
b6c12732 1233 if (isteacheredit($courseid)) {
9c9f7d77 1234 if (!empty($USER->editing)) {
9fa49e22 1235 $string = get_string("turneditingoff");
1236 $edit = "off";
1237 } else {
1238 $string = get_string("turneditingon");
1239 $edit = "on";
1240 }
76c1650d 1241 return "<form target=_parent method=get action=\"$CFG->wwwroot/course/view.php\">".
1242 "<input type=hidden name=id value=\"$courseid\">".
1243 "<input type=hidden name=edit value=\"$edit\">".
1244 "<input type=submit value=\"$string\"></form>";
9fa49e22 1245 }
1246}
1247
1248function update_module_button($moduleid, $courseid, $string) {
1249// Prints the editing button on a module "view" page
1250 global $CFG;
1251
b6c12732 1252 if (isteacheredit($courseid)) {
9fa49e22 1253 $string = get_string("updatethis", "", $string);
76c1650d 1254 return "<form target=_parent method=get action=\"$CFG->wwwroot/course/mod.php\">".
1255 "<input type=hidden name=update value=\"$moduleid\">".
1256 "<input type=hidden name=return value=\"true\">".
1257 "<input type=submit value=\"$string\"></form>";
b6c12732 1258 } else {
1259 return "";
9fa49e22 1260 }
1261}
1262
c2cb4545 1263function update_category_button($categoryid) {
d2b6ba70 1264// Prints the editing button on a category page
1265 global $CFG, $USER;
c2cb4545 1266
d2b6ba70 1267 if (iscreator()) {
1268 if (!empty($USER->editing)) {
1269 $string = get_string("turneditingoff");
1270 $edit = "off";
1271 } else {
1272 $string = get_string("turneditingon");
1273 $edit = "on";
9b16d1ea 1274 }
1275 return "<form method=get action=\"$CFG->wwwroot/course/category.php\">".
c2cb4545 1276 "<input type=hidden name=id value=\"$categoryid\">".
d2b6ba70 1277 "<input type=hidden name=edit value=\"$edit\">".
1278 "<input type=submit value=\"$string\"></form>";
1279 }
1280}
1281
1282function update_categories_button() {
1283// Prints the editing button on categories listing
1284 global $CFG, $USER;
1285
1286 if (isadmin()) {
1287 if (!empty($USER->editing)) {
1288 $string = get_string("turneditingoff");
1289 $edit = "off";
1290 } else {
1291 $string = get_string("turneditingon");
1292 $edit = "on";
1293 }
1294 return "<form target=_parent method=get action=\"$CFG->wwwroot/course/index.php\">".
1295 "<input type=hidden name=edit value=\"$edit\">".
c2cb4545 1296 "<input type=submit value=\"$string\"></form>";
1297 }
1298}
9fa49e22 1299
16ef5e78 1300function navmenu($course, $cm=NULL, $targetwindow="self") {
9fa49e22 1301// Given a course and a (current) coursemodule
1302// This function returns a small popup menu with all the
1303// course activity modules in it, as a navigation menu
1304// The data is taken from the serialised array stored in
1305// the course record
1306
1307 global $CFG;
1308
1309 if ($cm) {
1310 $cm = $cm->id;
1311 }
1312
1313 if ($course->format == 'weeks') {
1314 $strsection = get_string("week");
1315 } else {
1316 $strsection = get_string("topic");
1317 }
1318
1319 if (!$modinfo = unserialize($course->modinfo)) {
1320 return "";
1321 }
1322 $section = -1;
1323 $selected = "";
1324 foreach ($modinfo as $mod) {
ab2df10c 1325 if ($mod->mod == "label") {
1326 continue;
1327 }
9fa49e22 1328 if ($mod->section > 0 and $section <> $mod->section) {
1329 $menu[] = "-------------- $strsection $mod->section --------------";
1330 }
1331 $section = $mod->section;
cf055081 1332 //Only add visible or teacher mods to jumpmenu
1333 if ($mod->visible or isteacher($course->id)) {
1334 $url = "$mod->mod/view.php?id=$mod->cm";
1335 if ($cm == $mod->cm) {
1336 $selected = $url;
1337 }
1338 $mod->name = urldecode($mod->name);
1339 if (strlen($mod->name) > 55) {
1340 $mod->name = substr($mod->name, 0, 50)."...";
1341 }
2a409368 1342 if (!$mod->visible) {
1343 $mod->name = "(".$mod->name.")";
1344 }
cf055081 1345 $menu[$url] = $mod->name;
9fa49e22 1346 }
9fa49e22 1347 }
1348
16ef5e78 1349 return popup_form("$CFG->wwwroot/mod/", $menu, "navmenu", $selected, get_string("jumpto"),
1350 "", "", true, $targetwindow);
9fa49e22 1351}
1352
1353
1354
1355function print_date_selector($day, $month, $year, $currenttime=0) {
1356// Currenttime is a default timestamp in GMT
1357// Prints form items with the names $day, $month and $year
1358
1359 if (!$currenttime) {
1360 $currenttime = time();
1361 }
1362 $currentdate = usergetdate($currenttime);
1363
1364 for ($i=1; $i<=31; $i++) {
1365 $days[$i] = "$i";
1366 }
1367 for ($i=1; $i<=12; $i++) {
39e018b3 1368 $months[$i] = userdate(gmmktime(12,0,0,$i,1,2000), "%B");
9fa49e22 1369 }
1370 for ($i=2000; $i<=2010; $i++) {
1371 $years[$i] = $i;
1372 }
47f1da80 1373 choose_from_menu($days, $day, $currentdate['mday'], "");
1374 choose_from_menu($months, $month, $currentdate['mon'], "");
1375 choose_from_menu($years, $year, $currentdate['year'], "");
9fa49e22 1376}
1377
1378function print_time_selector($hour, $minute, $currenttime=0) {
1379// Currenttime is a default timestamp in GMT
1380// Prints form items with the names $hour and $minute
1381
1382 if (!$currenttime) {
1383 $currenttime = time();
1384 }
1385 $currentdate = usergetdate($currenttime);
1386 for ($i=0; $i<=23; $i++) {
1387 $hours[$i] = sprintf("%02d",$i);
1388 }
1389 for ($i=0; $i<=59; $i++) {
1390 $minutes[$i] = sprintf("%02d",$i);
1391 }
47f1da80 1392 choose_from_menu($hours, $hour, $currentdate['hours'], "");
1393 choose_from_menu($minutes, $minute, $currentdate['minutes'], "");
9fa49e22 1394}
1395
d6bdd9d5 1396function print_grade_menu($courseid, $name, $current, $includenograde=true) {
62ca135d 1397/// Prints a grade menu (as part of an existing form) with help
1398/// Showing all possible numerical grades and scales
1399
c9f6251e 1400 global $CFG;
62ca135d 1401
1402 $strscale = get_string("scale");
1403 $strscales = get_string("scales");
1404
1f7deef6 1405 $scales = get_scales_menu($courseid);
62ca135d 1406 foreach ($scales as $i => $scalename) {
1407 $grades[-$i] = "$strscale: $scalename";
1408 }
d6bdd9d5 1409 if ($includenograde) {
1410 $grades[0] = get_string("nograde");
1411 }
62ca135d 1412 for ($i=100; $i>=1; $i--) {
1413 $grades[$i] = $i;
1414 }
1415 choose_from_menu($grades, "$name", "$current", "");
1416
c9f6251e 1417 $helpicon = "$CFG->pixpath/help.gif";
62ca135d 1418 $linkobject = "<img align=\"absmiddle\" border=0 height=17 width=22 alt=\"$strscales\" src=\"$helpicon\">";
1419 link_to_popup_window ("/course/scales.php?id=$courseid&list=true", "ratingscales",
1420 $linkobject, 400, 500, $strscales);
1421}
1422
02ebf404 1423function print_scale_menu($courseid, $name, $current) {
1424/// Prints a scale menu (as part of an existing form) including help button
62ca135d 1425/// Just like print_grade_menu but without the numerical grades
02ebf404 1426
c9f6251e 1427 global $CFG;
02ebf404 1428
1429 $strscales = get_string("scales");
1430 choose_from_menu(get_scales_menu($courseid), "$name", $current, "");
c9f6251e 1431 $helpicon = "$CFG->pixpath/help.gif";
02ebf404 1432 $linkobject = "<img align=\"absmiddle\" border=0 height=17 width=22 alt=\"$strscales\" src=\"$helpicon\">";
1433 link_to_popup_window ("/course/scales.php?id=$courseid&list=true", "ratingscales",
1434 $linkobject, 400, 500, $strscales);
1435}
1436
fdc47ee6 1437
02ebf404 1438function print_scale_menu_helpbutton($courseid, $scale) {
1439/// Prints a help button about a scale
1440/// scale is an object
1441
c9f6251e 1442 global $CFG;
02ebf404 1443
1444 $strscales = get_string("scales");
c9f6251e 1445 $helpicon = "$CFG->pixpath/help.gif";
02ebf404 1446 $linkobject = "<img align=\"absmiddle\" border=0 height=17 width=22 alt=\"$scale->name\" src=\"$helpicon\">";
1447 link_to_popup_window ("/course/scales.php?id=$courseid&list=true&scale=$scale->id", "ratingscale",
1448 $linkobject, 400, 500, $scale->name);
1449}
1450
1451
9fa49e22 1452function error ($message, $link="") {
1453 global $CFG, $SESSION;
1454
1455 print_header(get_string("error"));
1456 echo "<BR>";
1457 print_simple_box($message, "center", "", "#FFBBBB");
1458
1459 if (!$link) {
1460 if ( !empty($SESSION->fromurl) ) {
1461 $link = "$SESSION->fromurl";
1462 unset($SESSION->fromurl);
9fa49e22 1463 } else {
c2cb4545 1464 $link = "$CFG->wwwroot/";
9fa49e22 1465 }
1466 }
1467 print_continue($link);
1468 print_footer();
1469 die;
1470}
1471
1472function helpbutton ($page, $title="", $module="moodle", $image=true, $linktext=false, $text="") {
1473 // $page = the keyword that defines a help page
1474 // $title = the title of links, rollover tips, alt tags etc
1475 // $module = which module is the page defined in
1476 // $image = use a help image for the link? (true/false/"both")
1477 // $text = if defined then this text is used in the page, and
1478 // the $page variable is ignored.
dc0dc7d5 1479 global $CFG, $THEME;
9fa49e22 1480
1481 if ($module == "") {
1482 $module = "moodle";
1483 }
1484
1485 if ($image) {
c9f6251e 1486 $icon = "$CFG->pixpath/help.gif";
9fa49e22 1487 if ($linktext) {
dc0dc7d5 1488 $linkobject = "$title<img align=\"absmiddle\" border=0 height=17 width=22 alt=\"\" src=\"$icon\">";
9fa49e22 1489 } else {
dc0dc7d5 1490 $linkobject = "<img align=\"absmiddle\" border=0 height=17 width=22 alt=\"$title\" src=\"$icon\">";
9fa49e22 1491 }
1492 } else {
1493 $linkobject = $title;
1494 }
1495 if ($text) {
1496 $url = "/help.php?module=$module&text=".htmlentities(urlencode($text));
1497 } else {
1498 $url = "/help.php?module=$module&file=$page.html";
1499 }
1500 link_to_popup_window ($url, "popup", $linkobject, 400, 500, $title);
1501}
1502
e825f279 1503function emoticonhelpbutton($form, $field) {
1504/// Prints a special help button that is a link to the "live" emoticon popup
1505 global $CFG, $SESSION;
1506
1507 $SESSION->inserttextform = $form;
1508 $SESSION->inserttextfield = $field;
1509 helpbutton("emoticons", get_string("helpemoticons"), "moodle", false, true);
c9f6251e 1510 echo "&nbsp;";
1511 link_to_popup_window ("/help.php?module=moodle&file=emoticons.html", "popup",
1512 "<img src=\"$CFG->pixpath/s/smiley.gif\" border=0 align=\"absmiddle\" width=15 height=15>",
1513 400, 500, get_string("helpemoticons"));
1514 echo "<br />";
e825f279 1515}
1516
9fa49e22 1517function notice ($message, $link="") {
750ab759 1518 global $CFG, $THEME;
9fa49e22 1519
1520 if (!$link) {
750ab759 1521 if (!empty($_SERVER["HTTP_REFERER"])) {
1522 $link = $_SERVER["HTTP_REFERER"];
1523 } else {
c2cb4545 1524 $link = "$CFG->wwwroot/";
750ab759 1525 }
9fa49e22 1526 }
1527
01d79966 1528 echo "<br />";
11a876e1 1529 print_simple_box($message, "center", "50%", "$THEME->cellheading", "20", "noticebox");
eb347b6b 1530 print_heading("<a href=\"$link\">".get_string("continue")."</a>");
9fa49e22 1531 print_footer(get_site());
1532 die;
1533}
1534
1535function notice_yesno ($message, $linkyes, $linkno) {
1536 global $THEME;
1537
eb347b6b 1538 print_simple_box_start("center", "60%", "$THEME->cellheading");
1539 echo "<p align=center><font size=3>$message</font></p>";
1540 echo "<p align=center><font size=3><b>";
1541 echo "<a href=\"$linkyes\">".get_string("yes")."</a>";
9fa49e22 1542 echo "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;";
eb347b6b 1543 echo "<a href=\"$linkno\">".get_string("no")."</a>";
1544 echo "</b></font></p>";
9fa49e22 1545 print_simple_box_end();
1546}
1547
559573a2 1548function redirect($url, $message="", $delay="0") {
9fa49e22 1549// Uses META tags to redirect the user, after printing a notice
1550
c9082a8c 1551 if (empty($message)) {
76c1650d 1552 echo "<meta http-equiv='refresh' content='$delay; url=$url'>";
c9082a8c 1553 } else {
05c19593 1554 if (empty($delay)) {
c9082a8c 1555 $delay = 3; // There's no point having a message with no delay
1556 }
76c1650d 1557 echo "<meta http-equiv='refresh' content='$delay; url=$url'>";
9fa49e22 1558 print_header();
76c1650d 1559 echo "<center>";
1560 echo "<p>$message</p>";
1561 echo "<p>( <a href=\"$url\">".get_string("continue")."</a> )</p>";
1562 echo "</center>";
9fa49e22 1563 }
1564 die;
1565}
1566
99988d1a 1567function notify ($message, $color="red", $align="center") {
1568 echo "<p align=\"$align\"><b><font color=\"$color\">$message</font></b></p>\n";
9fa49e22 1569}
1570
43373804 1571function obfuscate_email($email) {
1572/// Given an email address, this function will return an obfuscated version of it
1573 $i = 0;
1574 $length = strlen($email);
1575 $obfuscated = "";
1576 while ($i < $length) {
1577 if (rand(0,2)) {
1578 $obfuscated.='%'.dechex(ord($email{$i}));
1579 } else {
1580 $obfuscated.=$email{$i};
1581 }
1582 $i++;
1583 }
1584 return $obfuscated;
1585}
1586
1587function obfuscate_text($plaintext) {
1588/// This function takes some text and replaces about half of the characters
1589/// with HTML entity equivalents. Return string is obviously longer.
1590 $i=0;
1591 $length = strlen($plaintext);
1592 $obfuscated="";
2b09e377 1593 $prev_obfuscated = false;
43373804 1594 while ($i < $length) {
2b09e377 1595 $c = ord($plaintext{$i});
1596 $numerical = ($c >= ord('0')) && ($c <= ord('9'));
1597 if ($prev_obfuscated and $numerical ) {
1598 $obfuscated.='&#'.ord($plaintext{$i});
1599 } else if (rand(0,2)) {
43373804 1600 $obfuscated.='&#'.ord($plaintext{$i});
2b09e377 1601 $prev_obfuscated = true;
43373804 1602 } else {
1603 $obfuscated.=$plaintext{$i};
2b09e377 1604 $prev_obfuscated = false;
43373804 1605 }
2b09e377 1606 $i++;
43373804 1607 }
1608 return $obfuscated;
1609}
1610
1611function obfuscate_mailto($email, $label="") {
1612/// This function uses the above two functions to generate a fully
1613/// obfuscated email link, ready to use.
1614
1615 if (empty($label)) {
1616 $label = $email;
1617 }
1618 return sprintf('<a href="%s:%s" title="%s">%s</a>', obfuscate_text('mailto'),
1619 obfuscate_email($email),
1620 obfuscate_text($email),
1621 obfuscate_text($label));
1622}
1623
8b9c7aa0 1624function print_paging_bar($totalcount, $page, $perpage, $baseurl) {
1625/// Prints a single paging bar to provide access to other pages (usually in a search)
1626
519d369f 1627 $maxdisplay = 18;
8ef9cb56 1628
8b9c7aa0 1629 if ($totalcount > $perpage) {
f04dc61d 1630 echo "<center>";
1631 echo "<p>".get_string("page").":";
be20753e 1632 $lastpage = ceil($totalcount / $perpage);
1633 if ($page > 15) {
1634 $startpage = $page - 10;
519d369f 1635 echo "&nbsp<a href=\"{$baseurl}page=0\">1</a>&nbsp;...";
be20753e 1636 } else {
1637 $startpage = 0;
1638 }
be20753e 1639 $currpage = $startpage;
1640 $displaycount = 0;
1641 while ($displaycount < $maxdisplay and $currpage < $lastpage) {
1642 $displaypage = $currpage+1;
1643 if ($page == $currpage) {
8b9c7aa0 1644 echo "&nbsp;&nbsp;$displaypage";
1645 } else {
be20753e 1646 echo "&nbsp;&nbsp;<a href=\"{$baseurl}page=$currpage\">$displaypage</a>";
e27dbcc8 1647 }
be20753e 1648 $displaycount++;
1649 $currpage++;
8b9c7aa0 1650 }
924cef21 1651 if ($currpage < $lastpage) {
519d369f 1652 $lastpageactual = $lastpage - 1;
1653 echo "&nbsp;...<a href=\"{$baseurl}page=$lastpageactual\">$lastpage</a>&nbsp;";
924cef21 1654 }
8b9c7aa0 1655 $pagenum = $page + 1;
be20753e 1656 if ($pagenum != $displaypage) {
8b9c7aa0 1657 echo "&nbsp;&nbsp;(<a href=\"{$baseurl}page=$pagenum\">".get_string("next")."</a>)";
1658 }
1659 echo "</p>";
be20753e 1660 echo "</center>";
8b9c7aa0 1661 }
1662}
9fa49e22 1663
9d5b689c 1664// vim:autoindent:expandtab:shiftwidth=4:tabstop=4:tw=140:
f9903ed0 1665?>