SOme fixes for formatting from Koen in bug 1183
[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
39dda0fc 40$ALLOWED_TAGS =
36268d02 41"<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><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>";
3fe3851d 42
43
0095d5cd 44/// Functions
45
3662bce5 46function s($var) {
c1d57101 47/// returns $var with HTML characters (like "<", ">", etc.) properly quoted,
f9903ed0 48
3662bce5 49 if (empty($var)) {
50 return "";
51 }
7d8f674d 52 return htmlSpecialChars(stripslashes_safe($var));
f9903ed0 53}
54
3662bce5 55function p($var) {
c1d57101 56/// prints $var with HTML characters (like "<", ">", etc.) properly quoted,
f9903ed0 57
3662bce5 58 if (empty($var)) {
59 echo "";
60 }
7d8f674d 61 echo htmlSpecialChars(stripslashes_safe($var));
f9903ed0 62}
63
8553b700 64function nvl(&$var, $default="") {
c1d57101 65/// if $var is undefined, return $default, otherwise return $var
8553b700 66
67 return isset($var) ? $var : $default;
68}
f9903ed0 69
70function strip_querystring($url) {
c1d57101 71/// takes a URL and returns it without the querystring portion
f9903ed0 72
b9b8ab69 73 if ($commapos = strpos($url, '?')) {
74 return substr($url, 0, $commapos);
75 } else {
76 return $url;
77 }
f9903ed0 78}
79
80function get_referer() {
c1d57101 81/// returns the URL of the HTTP_REFERER, less the querystring portion
f9903ed0 82
607809b3 83 return strip_querystring(nvl($_SERVER["HTTP_REFERER"]));
f9903ed0 84}
85
c1d57101 86
f9903ed0 87function me() {
c1d57101 88/// returns the name of the current script, WITH the querystring portion.
eaa50dbc 89/// this function is necessary because PHP_SELF and REQUEST_URI and SCRIPT_NAME
c1d57101 90/// return different things depending on a lot of things like your OS, Web
91/// server, and the way PHP is compiled (ie. as a CGI, module, ISAPI, etc.)
f9903ed0 92
607809b3 93 if (!empty($_SERVER["REQUEST_URI"])) {
94 return $_SERVER["REQUEST_URI"];
c1d57101 95
607809b3 96 } else if (!empty($_SERVER["PHP_SELF"])) {
fced815c 97 if (!empty($_SERVER["QUERY_STRING"])) {
98 return $_SERVER["PHP_SELF"]."?".$_SERVER["QUERY_STRING"];
99 }
607809b3 100 return $_SERVER["PHP_SELF"];
c1d57101 101
fced815c 102 } else if (!empty($_SERVER["SCRIPT_NAME"])) {
103 if (!empty($_SERVER["QUERY_STRING"])) {
104 return $_SERVER["SCRIPT_NAME"]."?".$_SERVER["QUERY_STRING"];
105 }
106 return $_SERVER["SCRIPT_NAME"];
107
b9b8ab69 108 } else {
fced815c 109 notify("Warning: Could not find any of these web server variables: \$REQUEST_URI, \$PHP_SELF or \$SCRIPT_NAME");
bcdfe14e 110 return false;
7fbd6b1c 111 }
f9903ed0 112}
113
114
f9903ed0 115function qualified_me() {
c1d57101 116/// like me() but returns a full URL
f9903ed0 117
39e018b3 118 if (!empty($_SERVER["HTTP_HOST"])) {
119 $hostname = $_SERVER["HTTP_HOST"];
120 } else if (!empty($_ENV["HTTP_HOST"])) {
121 $hostname = $_ENV["HTTP_HOST"];
df3fd249 122 } else if (!empty($_SERVER["SERVER_NAME"])) {
123 $hostname = $_SERVER["SERVER_NAME"];
39e018b3 124 } else if (!empty($_ENV["SERVER_NAME"])) {
125 $hostname = $_ENV["SERVER_NAME"];
126 } else {
127 notify("Warning: could not find the name of this server!");
bcdfe14e 128 return false;
c1d57101 129 }
f9903ed0 130
607809b3 131 $protocol = (isset($_SERVER["HTTPS"]) and $_SERVER["HTTPS"] == "on") ? "https://" : "http://";
39e018b3 132 $url_prefix = $protocol.$hostname;
b9b8ab69 133 return $url_prefix . me();
f9903ed0 134}
135
136
a0deb5db 137function match_referer($goodreferer = "") {
138/// returns true if the referer is the same as the goodreferer. If
139/// goodreferer is not specified, use qualified_me as the goodreferer
60f18531 140 global $CFG;
141
ae384ef1 142 if (empty($CFG->secureforms)) { // Don't bother checking referer
60f18531 143 return true;
144 }
f9903ed0 145
ae384ef1 146 if ($goodreferer == "nomatch") { // Don't bother checking referer
a0deb5db 147 return true;
148 }
149
150 if (empty($goodreferer)) {
151 $goodreferer = qualified_me();
c1d57101 152 }
a0deb5db 153 return $goodreferer == get_referer();
f9903ed0 154}
155
36b4f985 156function data_submitted($url="") {
157/// Used on most forms in Moodle to check for data
158/// Returns the data as an object, if it's found.
607809b3 159/// This object can be used in foreach loops without
160/// casting because it's cast to (array) automatically
36b4f985 161///
162/// Checks that submitted POST data exists, and also
163/// checks the referer against the given url (it uses
164/// the current page if none was specified.
165
37208cd2 166 global $CFG;
167
607809b3 168 if (empty($_POST)) {
36b4f985 169 return false;
607809b3 170
36b4f985 171 } else {
172 if (match_referer($url)) {
607809b3 173 return (object)$_POST;
36b4f985 174 } else {
175 if ($CFG->debug > 10) {
176 notice("The form did not come from this page! (referer = ".get_referer().")");
177 }
178 return false;
179 }
180 }
181}
182
7d8f674d 183function stripslashes_safe($string) {
184/// stripslashes() removes ALL backslashes even from strings
185/// so C:\temp becomes C:temp ... this isn't good.
186/// The following should work as a fairly safe replacement
187/// to be called on quoted AND unquoted strings (to be sure)
188
189 $string = str_replace("\\'", "'", $string);
190 $string = str_replace('\\"', '"', $string);
191 $string = str_replace('\\\\', '\\', $string);
192 return $string;
193}
f9903ed0 194
4a5644e5 195
196function break_up_long_words($string, $maxsize=20, $cutchar=' ') {
197/// Given some normal text, this function will break up any
198/// long words to a given size, by inserting the given character
199
200 $output = '';
201 $length = strlen($string);
202 $wordlength = 0;
203
204 for ($i=0; $i<$length; $i++) {
205 $char = $string[$i];
206 if ($char == ' ' or $char == "\t" or $char == "\n" or $char == "\r") {
207 $wordlength = 0;
208 } else {
209 $wordlength++;
210 if ($wordlength > $maxsize) {
211 $output .= $cutchar;
212 $wordlength = 0;
213 }
214 }
215 $output .= $char;
216 }
217 return $output;
218}
219
220
ce57cc79 221if (!function_exists('str_ireplace')) { /// Only exists in PHP 5
7ec2fc00 222 function str_ireplace($find, $replace, $string) {
72e4eac6 223 /// This does a search and replace, ignoring case
ce57cc79 224 /// This function is only used for versions of PHP older than version 5
225 /// which do not have a native version of this function.
226 /// Taken from the PHP manual, by bradhuizenga @ softhome.net
7ec2fc00 227
228 if (!is_array($find)) {
229 $find = array($find);
230 }
231
232 if(!is_array($replace)) {
233 if (!is_array($find)) {
234 $replace = array($replace);
235 } else {
236 // this will duplicate the string into an array the size of $find
237 $c = count($find);
238 $rString = $replace;
239 unset($replace);
240 for ($i = 0; $i < $c; $i++) {
241 $replace[$i] = $rString;
242 }
243 }
244 }
245
246 foreach ($find as $fKey => $fItem) {
247 $between = explode(strtolower($fItem),strtolower($string));
248 $pos = 0;
249 foreach($between as $bKey => $bItem) {
250 $between[$bKey] = substr($string,$pos,strlen($bItem));
251 $pos += strlen($bItem) + strlen($fItem);
252 }
253 $string = implode($replace[$fKey],$between);
72e4eac6 254 }
7ec2fc00 255 return ($string);
3fe3851d 256 }
3fe3851d 257}
258
ce57cc79 259if (!function_exists('stripos')) { /// Only exists in PHP 5
260 function stripos($haystack, $needle, $offset=0) {
261 /// This function is only used for versions of PHP older than version 5
262 /// which do not have a native version of this function.
263 /// Taken from the PHP manual, by dmarsh @ spscc.ctc.edu
264 return strpos(strtoupper($haystack), strtoupper($needle), $offset);
265 }
266}
267
f9903ed0 268function read_template($filename, &$var) {
c1d57101 269/// return a (big) string containing the contents of a template file with all
270/// the variables interpolated. all the variables must be in the $var[] array or
271/// object (whatever you decide to use).
272///
273/// WARNING: do not use this on big files!!
f9903ed0 274
b9b8ab69 275 $temp = str_replace("\\", "\\\\", implode(file($filename), ""));
276 $temp = str_replace('"', '\"', $temp);
277 eval("\$template = \"$temp\";");
278 return $template;
f9903ed0 279}
280
281function checked(&$var, $set_value = 1, $unset_value = 0) {
c1d57101 282/// if variable is set, set it to the set_value otherwise set it to the
283/// unset_value. used to handle checkboxes when you are expecting them from
284/// a form
f9903ed0 285
b9b8ab69 286 if (empty($var)) {
287 $var = $unset_value;
288 } else {
289 $var = $set_value;
290 }
f9903ed0 291}
292
293function frmchecked(&$var, $true_value = "checked", $false_value = "") {
c1d57101 294/// prints the word "checked" if a variable is true, otherwise prints nothing,
295/// used for printing the word "checked" in a checkbox form input
f9903ed0 296
b9b8ab69 297 if ($var) {
298 echo $true_value;
299 } else {
300 echo $false_value;
301 }
f9903ed0 302}
303
304
86aa7ccf 305function link_to_popup_window ($url, $name="popup", $linkname="click here",
b48f834c 306 $height=400, $width=500, $title="Popup window", $options="none") {
c1d57101 307/// This will create a HTML link that will work on both
308/// Javascript and non-javascript browsers.
309/// Relies on the Javascript function openpopup in javascript.php
310/// $url must be relative to home page eg /mod/survey/stuff.php
f9903ed0 311
ff80e012 312 global $CFG;
313
b48f834c 314 if ($options == "none") {
315 $options = "menubar=0,location=0,scrollbars,resizable,width=$width,height=$height";
316 }
86aa7ccf 317 $fullscreen = 0;
f9903ed0 318
55e4b5f9 319 echo "<a target=\"$name\" title=\"$title\" href=\"$CFG->wwwroot$url\" ".
86aa7ccf 320 "onClick=\"return openpopup('$url', '$name', '$options', $fullscreen);\">$linkname</a>\n";
f9903ed0 321}
322
86aa7ccf 323
52f1b496 324function button_to_popup_window ($url, $name="popup", $linkname="click here",
325 $height=400, $width=500, $title="Popup window", $options="none") {
326/// This will create a HTML link that will work on both
327/// Javascript and non-javascript browsers.
328/// Relies on the Javascript function openpopup in javascript.php
329/// $url must be relative to home page eg /mod/survey/stuff.php
330
331 global $CFG;
332
333 if ($options == "none") {
334 $options = "menubar=0,location=0,scrollbars,resizable,width=$width,height=$height";
335 }
336 $fullscreen = 0;
337
338 echo "<input type=\"button\" name=\"popupwindow\" title=\"$title\" value=\"$linkname ...\" ".
339 "onClick=\"return openpopup('$url', '$name', '$options', $fullscreen);\">\n";
340}
341
342
f9903ed0 343function close_window_button() {
c1d57101 344/// Prints a simple button to close a window
345
86aa7ccf 346 echo "<center>\n";
347 echo "<script>\n";
348 echo "<!--\n";
349 echo "document.write('<form>');\n";
66a51452 350 echo "document.write('<input type=\"button\" onClick=\"self.close();\" value=\"".get_string("closewindow")."\" />');\n";
86aa7ccf 351 echo "document.write('</form>');\n";
352 echo "-->\n";
353 echo "</script>\n";
354 echo "<noscript>\n";
355 echo "<a href=\"".$_SERVER['HTTP_REFERER']."\"><---</a>\n";
356 echo "</noscript>\n";
357 echo "</center>\n";
f9903ed0 358}
359
360
08056730 361function choose_from_menu ($options, $name, $selected="", $nothing="choose", $script="", $nothingvalue="0", $return=false) {
c1d57101 362/// Given an array of value, creates a popup menu to be part of a form
363/// $options["value"]["label"]
f9903ed0 364
618b22c5 365 if ($nothing == "choose") {
366 $nothing = get_string("choose")."...";
367 }
368
f9903ed0 369 if ($script) {
370 $javascript = "onChange=\"$script\"";
9c9f7d77 371 } else {
372 $javascript = "";
f9903ed0 373 }
9c9f7d77 374
66a51452 375 $output = "<select name=\"$name\" $javascript>\n";
bda8d43a 376 if ($nothing) {
76c1650d 377 $output .= " <option value=\"$nothingvalue\"\n";
bda8d43a 378 if ($nothingvalue == $selected) {
66a51452 379 $output .= " selected=\"true\"";
bda8d43a 380 }
76c1650d 381 $output .= ">$nothing</option>\n";
873960de 382 }
607809b3 383 if (!empty($options)) {
384 foreach ($options as $value => $label) {
76c1650d 385 $output .= " <option value=\"$value\"";
607809b3 386 if ($value == $selected) {
66a51452 387 $output .= " selected=\"true\"";
607809b3 388 }
a20c1090 389 if ($label === "") {
76c1650d 390 $output .= ">$value</option>\n";
a20c1090 391 } else {
392 $output .= ">$label</option>\n";
607809b3 393 }
f9903ed0 394 }
395 }
76c1650d 396 $output .= "</select>\n";
08056730 397
398 if ($return) {
399 return $output;
400 } else {
401 echo $output;
402 }
f9903ed0 403}
404
16ef5e78 405function popup_form ($common, $options, $formname, $selected="", $nothing="choose", $help="", $helptext="", $return=false, $targetwindow="self") {
c1d57101 406/// Implements a complete little popup form
407/// $common = the URL up to the point of the variable that changes
408/// $options = A list of value-label pairs for the popup list
409/// $formname = name must be unique on the page
410/// $selected = the option that is already selected
411/// $nothing = The label for the "no choice" option
e5dfd0f3 412/// $help = The name of a help page if help is required
413/// $helptext = The name of the label for the help button
5b472756 414/// $return = Boolean indicating whether the function should return the text
415/// as a string or echo it directly to the page being rendered
f9903ed0 416
0d0baabf 417 global $CFG;
418
618b22c5 419 if ($nothing == "choose") {
420 $nothing = get_string("choose")."...";
421 }
422
66a51452 423 $startoutput = "<form target=\"{$CFG->framename}\" name=\"$formname\">";
424 $output = "<select name=\"popup\" onchange=\"$targetwindow.location=document.$formname.popup.options[document.$formname.popup.selectedIndex].value\">\n";
f9903ed0 425
426 if ($nothing != "") {
dfec7b01 427 $output .= " <option value=\"javascript:void(0)\">$nothing</option>\n";
f9903ed0 428 }
429
430 foreach ($options as $value => $label) {
d897cae4 431 if (substr($label,0,1) == "-") {
dfec7b01 432 $output .= " <option value=\"\"";
d897cae4 433 } else {
dfec7b01 434 $output .= " <option value=\"$common$value\"";
d897cae4 435 if ($value == $selected) {
66a51452 436 $output .= " selected=\"true\"";
d897cae4 437 }
f9903ed0 438 }
439 if ($label) {
dfec7b01 440 $output .= ">$label</option>\n";
f9903ed0 441 } else {
dfec7b01 442 $output .= ">$value</option>\n";
f9903ed0 443 }
444 }
dfec7b01 445 $output .= "</select>";
446 $output .= "</form>\n";
d897cae4 447
448 if ($return) {
dfec7b01 449 return $startoutput.$output;
d897cae4 450 } else {
dfec7b01 451 echo $startoutput;
9c9f7d77 452 if ($help) {
453 helpbutton($help, $helptext);
454 }
d897cae4 455 echo $output;
456 }
f9903ed0 457}
458
459
460
461function formerr($error) {
c1d57101 462/// Prints some red text
f9903ed0 463 if (!empty($error)) {
66a51452 464 echo "<font color=\"#ff0000\">$error</font>";
f9903ed0 465 }
466}
467
468
469function validate_email ($address) {
66a51452 470/// Validates an email to make sure it makes sense.
f9903ed0 471 return (ereg('^[-!#$%&\'*+\\./0-9=?A-Z^_`a-z{|}~]+'.
472 '@'.
473 '[-!#$%&\'*+\\/0-9=?A-Z^_`a-z{|}~]+\.'.
474 '[-!#$%&\'*+\\./0-9=?A-Z^_`a-z{|}~]+$',
475 $address));
476}
477
6c8e8b5e 478function detect_munged_arguments($string) {
393c9b4f 479 if (ereg('\.\.', $string)) { // check for parent URLs
6c8e8b5e 480 return true;
481 }
393c9b4f 482 if (ereg('[\|\`]', $string)) { // check for other bad characters
6c8e8b5e 483 return true;
484 }
f038d9a3 485 if (empty($string) or $string == '/') {
486 return true;
487 }
488
6c8e8b5e 489 return false;
490}
491
6ed3da1d 492function get_slash_arguments($file="file.php") {
493/// Searches the current environment variables for some slash arguments
f9903ed0 494
eaa50dbc 495 if (!$string = me()) {
f9903ed0 496 return false;
497 }
eaa50dbc 498
6ed3da1d 499 $pathinfo = explode($file, $string);
500
bcdfe14e 501 if (!empty($pathinfo[1])) {
502 return $pathinfo[1];
6ed3da1d 503 } else {
504 return false;
505 }
506}
507
508function parse_slash_arguments($string, $i=0) {
509/// Extracts arguments from "/foo/bar/something"
510/// eg http://mysite.com/script.php/foo/bar/something
f9903ed0 511
6c8e8b5e 512 if (detect_munged_arguments($string)) {
780db230 513 return false;
514 }
6ed3da1d 515 $args = explode("/", $string);
f9903ed0 516
517 if ($i) { // return just the required argument
518 return $args[$i];
519
520 } else { // return the whole array
521 array_shift($args); // get rid of the empty first one
522 return $args;
523 }
524}
525
0095d5cd 526function format_text_menu() {
c1d57101 527/// Just returns an array of formats suitable for a popup menu
0095d5cd 528 return array (FORMAT_MOODLE => get_string("formattext"),
6901fa79 529 FORMAT_HTML => get_string("formathtml"),
d342c763 530 FORMAT_PLAIN => get_string("formatplain"),
531 FORMAT_WIKI => get_string("formatwiki"));
0095d5cd 532}
533
c4ae4fa1 534function format_text($text, $format=FORMAT_MOODLE, $options=NULL, $courseid=NULL ) {
c1d57101 535/// Given text in a variety of format codings, this function returns
536/// the text as safe HTML.
537///
538/// $text is raw text (originally from a user)
539/// $format is one of the format constants, defined above
0095d5cd 540
c4ae4fa1 541 global $CFG, $course;
542
f0aa2fed 543 if (!empty($CFG->cachetext)) {
544 $time = time() - $CFG->cachetext;
545 $md5key = md5($text);
45121ffb 546 if ($cacheitem = get_record_select('cache_text', "md5key = '$md5key' AND timemodified > '$time'")) {
f0aa2fed 547 return $cacheitem->formattedtext;
548 }
549 }
550
c4ae4fa1 551 if (empty($courseid)) {
8eaa4c61 552 if (!empty($course->id)) { // An ugly hack for better compatibility
c4ae4fa1 553 $courseid = $course->id;
554 }
555 }
a751a4e5 556
8eaa4c61 557 $CFG->currenttextiscacheable = true; // Default status - can be changed by any filter
558
0095d5cd 559 switch ($format) {
73f8658c 560 case FORMAT_HTML:
5f350e8f 561 replace_smilies($text);
f0aa2fed 562 $text = filter_text($text, $courseid);
73f8658c 563 break;
564
6901fa79 565 case FORMAT_PLAIN:
566 $text = htmlentities($text);
3405b212 567 $text = str_replace(" ", "&nbsp; ", $text);
5f350e8f 568 replace_smilies($text);
6901fa79 569 $text = nl2br($text);
6901fa79 570 break;
571
d342c763 572 case FORMAT_WIKI:
e67b9e31 573 $text = wiki_to_html($text);
f0aa2fed 574 $text = filter_text($text, $courseid);
d342c763 575 break;
576
73f8658c 577 default: // FORMAT_MOODLE or anything else
c9dda990 578 if (!isset($options->smiley)) {
579 $options->smiley=true;
580 }
581 if (!isset($options->para)) {
1a072208 582 $options->para=true;
c9dda990 583 }
b7a3d3b2 584 if (!isset($options->newlines)) {
585 $options->newlines=true;
586 }
587 $text = text_to_html($text, $options->smiley, $options->para, $options->newlines);
f0aa2fed 588 $text = filter_text($text, $courseid);
0095d5cd 589 break;
0095d5cd 590 }
f0aa2fed 591
8eaa4c61 592 if (!empty($CFG->cachetext) and $CFG->currenttextiscacheable) {
f0aa2fed 593 $newrecord->md5key = $md5key;
594 $newrecord->formattedtext = addslashes($text);
595 $newrecord->timemodified = time();
45121ffb 596 insert_record('cache_text', $newrecord);
f0aa2fed 597 }
598
599 return $text;
0095d5cd 600}
601
d342c763 602function format_text_email($text, $format) {
603/// Given text in a variety of format codings, this function returns
604/// the text as plain text suitable for plain email.
605///
606/// $text is raw text (originally from a user)
607/// $format is one of the format constants, defined above
608
609 switch ($format) {
610
611 case FORMAT_PLAIN:
612 return $text;
613 break;
614
615 case FORMAT_WIKI:
616 $text = wiki_to_html($text);
5b472756 617 /// This expression turns links into something nice in a text format. (Russell Jungwirth)
618 /// From: http://php.net/manual/en/function.eregi-replace.php and simplified
619 $text = eregi_replace('(<a [^<]*href=["|\']?([^ "\']*)["|\']?[^>]*>([^<]*)</a>)','\\3 [\\2]', $text);
7c55a29b 620 return strtr(strip_tags($text), array_flip(get_html_translation_table(HTML_ENTITIES)));
d342c763 621 break;
622
6ff45b59 623 case FORMAT_HTML:
624 return html_to_text($text);
625 break;
626
d342c763 627 default: // FORMAT_MOODLE or anything else
5b472756 628 $text = eregi_replace('(<a [^<]*href=["|\']?([^ "\']*)["|\']?[^>]*>([^<]*)</a>)','\\3 [\\2]', $text);
7c55a29b 629 return strtr(strip_tags($text), array_flip(get_html_translation_table(HTML_ENTITIES)));
d342c763 630 break;
631 }
632}
0095d5cd 633
e67b9e31 634
c4ae4fa1 635function filter_text($text, $courseid=NULL) {
e67b9e31 636/// Given some text in HTML format, this function will pass it
637/// through any filters that have been defined in $CFG->textfilterx
638/// The variable defines a filepath to a file containing the
639/// filter function. The file must contain a variable called
640/// $textfilter_function which contains the name of the function
c4ae4fa1 641/// with $courseid and $text parameters
e67b9e31 642
c4ae4fa1 643 global $CFG;
e67b9e31 644
d523d2ea 645 if (!empty($CFG->textfilters)) {
646 $textfilters = explode(',', $CFG->textfilters);
647 foreach ($textfilters as $textfilter) {
828aeff2 648 if (is_readable("$CFG->dirroot/$textfilter/filter.php")) {
649 include("$CFG->dirroot/$textfilter/filter.php");
d523d2ea 650 $text = $textfilter_function($courseid, $text);
651 }
e67b9e31 652 }
653 }
d523d2ea 654
e67b9e31 655 return $text;
656}
657
658
3da47524 659function clean_text($text, $format=FORMAT_MOODLE) {
c1d57101 660/// Given raw text (eg typed in by a user), this function cleans it up
661/// and removes any nasty tags that could mess up Moodle pages.
b7a3cf49 662
fc120758 663 global $ALLOWED_TAGS;
3fe3851d 664
d342c763 665 switch ($format) {
0095d5cd 666 case FORMAT_MOODLE:
0095d5cd 667 case FORMAT_HTML:
d342c763 668 case FORMAT_WIKI:
5b472756 669 /// Remove javascript: label
3fe3851d 670 $text = strip_tags($text, $ALLOWED_TAGS);
5b472756 671 /// Remove javascript/VBScript
672 $text = str_ireplace("javascript:", "xxx", $text);
673 /// Remove script events
674 $text = eregi_replace("([^a-z])language([[:space:]]*)=", "xxx", $text);
675 $text = eregi_replace("([^a-z])on([a-z]+)([[:space:]]*)=", "xxx", $text);
3fe3851d 676 return $text;
6901fa79 677
678 case FORMAT_PLAIN:
679 return $text;
0095d5cd 680 }
b7a3cf49 681}
f9903ed0 682
5f350e8f 683function replace_smilies(&$text) {
c1d57101 684/// Replaces all known smileys in the text with image equivalents
2ea9027b 685 global $CFG;
c1d57101 686
5b472756 687/// this builds the mapping array only once
617778f2 688 static $runonce = false;
69081931 689 static $e = array();
690 static $img = array();
617778f2 691 static $emoticons = array(
fbfc2675 692 ':-)' => 'smiley',
693 ':)' => 'smiley',
694 ':-D' => 'biggrin',
695 ';-)' => 'wink',
696 ':-/' => 'mixed',
697 'V-.' => 'thoughtful',
698 ':-P' => 'tongueout',
699 'B-)' => 'cool',
700 '^-)' => 'approve',
701 '8-)' => 'wideeyes',
702 ':o)' => 'clown',
703 ':-(' => 'sad',
704 ':(' => 'sad',
705 '8-.' => 'shy',
706 ':-I' => 'blush',
707 ':-X' => 'kiss',
708 '8-o' => 'surprise',
709 'P-|' => 'blackeye',
710 '8-[' => 'angry',
711 'xx-P' => 'dead',
712 '|-.' => 'sleepy',
713 '}-]' => 'evil',
2ea9027b 714 );
715
fbfc2675 716 if ($runonce == false) { /// After the first time this is not run again
617778f2 717 foreach ($emoticons as $emoticon => $image){
fbfc2675 718 $alttext = get_string($image, 'pix');
719
69081931 720 $e[] = $emoticon;
fbfc2675 721 $img[] = "<img alt=\"$alttext\" width=\"15\" height=\"15\" src=\"$CFG->pixpath/s/$image.gif\" />";
617778f2 722 }
723 $runonce = true;
c0f728ba 724 }
b7a3cf49 725
fbfc2675 726/// this is the meat of the code - this is run every time
5f350e8f 727 $text = str_replace($e, $img, $text);
1a072208 728}
0095d5cd 729
b7a3d3b2 730function text_to_html($text, $smiley=true, $para=true, $newlines=true) {
c1d57101 731/// Given plain text, makes it into HTML as nicely as possible.
732/// May contain HTML tags already
f9903ed0 733
27326a3e 734 global $CFG;
735
c1d57101 736/// Remove any whitespace that may be between HTML tags
7b3be1b1 737 $text = eregi_replace(">([[:space:]]+)<", "><", $text);
738
c1d57101 739/// Remove any returns that precede or follow HTML tags
0eae8049 740 $text = eregi_replace("([\n\r])<", " <", $text);
741 $text = eregi_replace(">([\n\r])", "> ", $text);
7b3be1b1 742
5f350e8f 743 convert_urls_into_links($text);
f9903ed0 744
c1d57101 745/// Make returns into HTML newlines.
b7a3d3b2 746 if ($newlines) {
747 $text = nl2br($text);
748 }
f9903ed0 749
c1d57101 750/// Turn smileys into images.
d69cb7f4 751 if ($smiley) {
5f350e8f 752 replace_smilies($text);
d69cb7f4 753 }
f9903ed0 754
c1d57101 755/// Wrap the whole thing in a paragraph tag if required
909f539d 756 if ($para) {
01d79966 757 return "<p>".$text."</p>";
909f539d 758 } else {
759 return $text;
760 }
f9903ed0 761}
762
3e9ca9fb 763function wiki_to_html($text) {
01d79966 764/// Given Wiki formatted text, make it into XHTML using external function
43373804 765 global $CFG;
3e9ca9fb 766
43373804 767 require_once("$CFG->libdir/wiki.php");
3e9ca9fb 768
01d79966 769 $wiki = new Wiki;
770 return $wiki->format($text);
3e9ca9fb 771}
772
6ff45b59 773function html_to_text($html) {
774/// Given HTML text, make it into plain text using external function
428aaa29 775 global $CFG;
6ff45b59 776
777 require_once("$CFG->libdir/html2text.php");
778
779 return html2text($html);
780}
781
782
5f350e8f 783function convert_urls_into_links(&$text) {
784/// Given some text, it converts any URLs it finds into HTML links.
785
786/// Make lone URLs into links. eg http://moodle.com/
3405b212 787 $text = eregi_replace("([[:space:]]|^|\(|\[)([[:alnum:]]+)://([^[:space:]]*)([[:alnum:]#?/&=])",
88438a58 788 "\\1<a href=\"\\2://\\3\\4\" target=\"newpage\">\\2://\\3\\4</a>", $text);
5f350e8f 789
790/// eg www.moodle.com
3405b212 791 $text = eregi_replace("([[:space:]]|^|\(|\[)www\.([^[:space:]]*)([[:alnum:]#?/&=])",
88438a58 792 "\\1<a href=\"http://www.\\2\\3\" target=\"newpage\">www.\\2\\3</a>", $text);
5f350e8f 793}
794
88438a58 795function highlight($needle, $haystack, $case=0,
796 $left_string="<span class=\"highlight\">", $right_string="</span>") {
797/// This function will highlight search words in a given string
798/// It cares about HTML and will not ruin links. It's best to use
799/// this function after performing any conversions to HTML.
800/// Function found here: http://forums.devshed.com/t67822/scdaa2d1c3d4bacb4671d075ad41f0854.html
801
69d51d3a 802 if (empty($needle)) {
803 return $haystack;
804 }
805
88438a58 806 $list_of_words = eregi_replace("[^-a-zA-Z0-9&']", " ", $needle);
807 $list_array = explode(" ", $list_of_words);
808 for ($i=0; $i<sizeof($list_array); $i++) {
809 if (strlen($list_array[$i]) == 1) {
810 $list_array[$i] = "";
811 }
812 }
813 $list_of_words = implode(" ", $list_array);
814 $list_of_words_cp = $list_of_words;
815 $final = array();
816 preg_match_all('/<(.+?)>/is',$haystack,$list_of_words);
817
818 foreach (array_unique($list_of_words[0]) as $key=>$value) {
819 $final['<|'.$key.'|>'] = $value;
820 }
821
822 $haystack = str_replace($final,array_keys($final),$haystack);
823 $list_of_words_cp = eregi_replace(" +", "|", $list_of_words_cp);
824
825 if ($list_of_words_cp{0}=="|") {
826 $list_of_words_cp{0} = "";
827 }
828 if ($list_of_words_cp{strlen($list_of_words_cp)-1}=="|") {
829 $list_of_words_cp{strlen($list_of_words_cp)-1}="";
830 }
831 $list_of_words_cp = "(".trim($list_of_words_cp).")";
832
833 if (!$case){
834 $haystack = eregi_replace("$list_of_words_cp", "$left_string"."\\1"."$right_string", $haystack);
835 } else {
836 $haystack = ereg_replace("$list_of_words_cp", "$left_string"."\\1"."$right_string", $haystack);
837 }
838 $haystack = str_replace(array_keys($final),$final,$haystack);
839
840 return stripslashes($haystack);
841}
842
843function highlightfast($needle, $haystack) {
c1d57101 844/// This function will highlight instances of $needle in $haystack
88438a58 845/// It's faster that the above function and doesn't care about
846/// HTML or anything.
5af78ed2 847
848 $parts = explode(strtolower($needle), strtolower($haystack));
849
850 $pos = 0;
851
852 foreach ($parts as $key => $part) {
853 $parts[$key] = substr($haystack, $pos, strlen($part));
854 $pos += strlen($part);
855
88438a58 856 $parts[$key] .= "<span class=\"highlight\">".substr($haystack, $pos, strlen($needle))."</span>";
5af78ed2 857 $pos += strlen($needle);
858 }
859
860 return (join('', $parts));
861}
862
f9903ed0 863
9fa49e22 864/// STANDARD WEB PAGE PARTS ///////////////////////////////////////////////////
865
66a51452 866function print_header ($title="", $heading="", $navigation="", $focus="", $meta="",
867 $cache=true, $button="&nbsp;", $menu="", $usexml=false) {
9fa49e22 868// $title - appears top of window
869// $heading - appears top of page
870// $navigation - premade navigation string
871// $focus - indicates form element eg inputform.password
872// $meta - meta tags in the header
873// $cache - should this page be cacheable?
874// $button - HTML code for a button (usually for module editing)
66a51452 875// $menu - HTML code for a popup menu
876// $usexml - use XML for this page
e825f279 877 global $USER, $CFG, $THEME, $SESSION;
9fa49e22 878
b3153e4b 879 global $course; // This is a bit of an ugly hack to be gotten rid of later
880 if (!empty($course->lang)) {
881 $CFG->courselang = $course->lang;
882 }
883
9fa49e22 884 if (file_exists("$CFG->dirroot/theme/$CFG->theme/styles.php")) {
885 $styles = $CFG->stylesheet;
886 } else {
887 $styles = "$CFG->wwwroot/theme/standard/styles.php";
888 }
889
890 if ($navigation == "home") {
891 $home = true;
892 $navigation = "";
9d378732 893 } else {
894 $home = false;
9fa49e22 895 }
896
897 if ($button == "") {
898 $button = "&nbsp;";
899 }
900
901 if (!$menu and $navigation) {
902 if (isset($USER->id)) {
66a51452 903 $menu = "<font size=\"2\"><a target=\"$CFG->framename\" href=\"$CFG->wwwroot/login/logout.php\">".get_string("logout")."</a></font>";
9fa49e22 904 } else {
66a51452 905 $menu = "<font size=\"2\"><a target=\"$CFG->framename\" href=\"$CFG->wwwroot/login/index.php\">".get_string("login")."</a></font>";
9fa49e22 906 }
907 }
908
47037513 909 // Add a stylesheet for the HTML editor
910 $meta = "<style type=\"text/css\">@import url($CFG->wwwroot/lib/editor/htmlarea.css);</style>\n$meta\n";
911
9fa49e22 912 // Specify character set ... default is iso-8859-1 but some languages might need something else
913 // Could be optimised by carrying the charset variable around in $USER
914 if (current_language() == "en") {
66a51452 915 $meta = "<meta http-equiv=\"content-type\" content=\"text/html; charset=iso-8859-1\" />\n$meta\n";
9fa49e22 916 } else {
66a51452 917 $meta = "<meta http-equiv=\"content-type\" content=\"text/html; charset=".get_string("thischarset")."\" />\n$meta\n";
9fa49e22 918 }
919
d8152d04 920 if ( get_string("thisdirection") == "rtl" ) {
107b010b 921 $direction = " dir=\"rtl\"";
9fa49e22 922 } else {
107b010b 923 $direction = " dir=\"ltr\"";
9fa49e22 924 }
925
926 if (!$cache) { // Do everything we can to prevent clients and proxies caching
927 @header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
928 @header("Pragma: no-cache");
66a51452 929 $meta .= "\n<meta http-equiv=\"pragma\" content=\"no-cache\" />";
930 $meta .= "\n<meta http-equiv=\"expires\" content=\"0\" />";
931 }
932
933 if ($usexml) { // Added by Gustav Delius / Mad Alex for MathML output
934 $currentlanguage = current_language();
935
936 @header("Content-type: text/xml");
937 echo "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\" ?>\n";
938 if (!empty($CFG->xml_stylesheets)) {
939 $stylesheets = explode(";", $CFG->xml_stylesheets);
940 foreach ($stylesheets as $stylesheet) {
941 echo "<?xml-stylesheet type=\"text/xsl\" href=\"$CFG->wwwroot/$stylesheet\" ?>\n";
942 }
943 }
944 echo "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.1";
e4576482 945 if (!empty($CFG->xml_doctype_extra)) {
66a51452 946 echo " plus $CFG->xml_doctype_extra";
e4576482 947 }
66a51452 948 echo "//" . strtoupper($currentlanguage) . "\" \"$CFG->xml_dtd\">\n";
949 $direction = " xmlns=\"http://www.w3.org/1999/xhtml\" xml:lang=\"$currentlanguage\" $direction";
9fa49e22 950 }
951
2eea2cce 952 $title = str_replace('"', '&quot;', $title);
1d9fc417 953 $title = strip_tags($title);
2eea2cce 954
9fa49e22 955 include ("$CFG->dirroot/theme/$CFG->theme/header.html");
956}
957
958function print_footer ($course=NULL) {
959// Can provide a course object to make the footer contain a link to
960// to the course home page, otherwise the link will go to the site home
961 global $USER, $CFG, $THEME;
962
963
964/// Course links
965 if ($course) {
966 if ($course == "home") { // special case for site home page - please do not remove
76c1650d 967 $homelink = "<p align=\"center\"><a title=\"moodle $CFG->release ($CFG->version)\" href=\"http://moodle.org/\" target=\"_blank\">";
2d8b2369 968 $homelink .= "<br /><img width=\"100\" height=\"30\" src=\"pix/moodlelogo.gif\" border=\"0\" /></a></p>";
9fa49e22 969 $course = get_site();
970 $homepage = true;
971 } else {
76c1650d 972 $homelink = "<a target=\"{$CFG->framename}\" href=\"$CFG->wwwroot/course/view.php?id=$course->id\">$course->shortname</a>";
9fa49e22 973 }
974 } else {
c2cb4545 975 $homelink = "<a target=\"{$CFG->framename}\" href=\"$CFG->wwwroot/\">".get_string("home")."</a>";
9fa49e22 976 $course = get_site();
977 }
978
979/// User links
a282d0ff 980 $loggedinas = user_login_string($course, $USER);
981
982 include ("$CFG->dirroot/theme/$CFG->theme/footer.html");
983}
984
1ddf9329 985function style_sheet_setup($lastmodified=0, $lifetime=300, $themename="") {
986/// This function is called by stylesheets to set up the header
987/// approriately as well as the current path
6535be85 988
989 global $CFG;
e3b343e0 990
6535be85 991 header("Last-Modified: " . gmdate("D, d M Y H:i:s", $lastmodified) . " GMT");
992 header("Expires: " . gmdate("D, d M Y H:i:s", time() + $lifetime) . " GMT");
993 header("Cache-control: max_age = $lifetime");
994 header("Pragma: ");
995 header("Content-type: text/css"); // Correct MIME type
996
997 if (!empty($themename)) {
998 $CFG->theme = $themename;
999 }
1000
1001 return "$CFG->wwwroot/theme/$CFG->theme";
1002
1003}
1004
a282d0ff 1005
1006function user_login_string($course, $user=NULL) {
1007 global $USER, $CFG;
1008
8d2accb6 1009 if (empty($user)) {
a282d0ff 1010 $user = $USER;
1011 }
1012
1013 if (isset($user->realuser)) {
1014 if ($realuser = get_record("user", "id", $user->realuser)) {
2d71e8ee 1015 $fullname = fullname($realuser, true);
1016 $realuserinfo = " [<a target=\"{$CFG->framename}\"
1017 href=\"$CFG->wwwroot/course/loginas.php?id=$course->id&amp;return=$realuser->id\">$fullname</a>] ";
9fa49e22 1018 }
9d378732 1019 } else {
1020 $realuserinfo = "";
9fa49e22 1021 }
1022
a282d0ff 1023 if (isset($user->id) and $user->id) {
2d71e8ee 1024 $fullname = fullname($user, true);
1025 $username = "<a target=\"{$CFG->framename}\" href=\"$CFG->wwwroot/user/view.php?id=$user->id&amp;course=$course->id\">$fullname</a>";
9fa49e22 1026 $loggedinas = $realuserinfo.get_string("loggedinas", "moodle", "$username").
ca16eaeb 1027 " (<a target=\"{$CFG->framename}\" href=\"$CFG->wwwroot/login/logout.php\">".get_string("logout")."</a>)";
9fa49e22 1028 } else {
1029 $loggedinas = get_string("loggedinnot", "moodle").
ca16eaeb 1030 " (<a target=\"{$CFG->framename}\" href=\"$CFG->wwwroot/login/index.php\">".get_string("login")."</a>)";
9fa49e22 1031 }
a282d0ff 1032 return $loggedinas;
9fa49e22 1033}
1034
1035
9fa49e22 1036function print_navigation ($navigation) {
1037 global $CFG;
1038
1039 if ($navigation) {
1040 if (! $site = get_site()) {
1041 $site->shortname = get_string("home");;
1042 }
eb347b6b 1043 echo "<a target=\"{$CFG->framename}\" href=\"$CFG->wwwroot/\">$site->shortname</a> -> $navigation";
9fa49e22 1044 }
1045}
1046
d4df9200 1047function print_headline($text, $size=2) {
1048 echo "<b><font size=\"$size\">$text</font></b><br />\n";
1049}
1050
76c1650d 1051function print_heading($text, $align="center", $size=3) {
1052 echo "<p align=\"$align\"><font size=\"$size\"><b>".stripslashes_safe($text)."</b></font></p>";
9fa49e22 1053}
1054
c9f6251e 1055function print_heading_with_help($text, $helppage, $module="moodle", $icon="") {
9fa49e22 1056// Centered heading with attached help button (same title text)
c9f6251e 1057// and optional icon attached
1058 echo "<p align=\"center\"><font size=\"3\">$icon<b>".stripslashes_safe($text);
9fa49e22 1059 helpbutton($helppage, $text, $module);
eb347b6b 1060 echo "</b></font></p>";
9fa49e22 1061}
1062
1063function print_continue($link) {
9fa49e22 1064
1065 if (!$link) {
607809b3 1066 $link = $_SERVER["HTTP_REFERER"];
9fa49e22 1067 }
1068
eb347b6b 1069 print_heading("<a href=\"$link\">".get_string("continue")."</a>");
9fa49e22 1070}
1071
1072
1073function print_simple_box($message, $align="", $width="", $color="#FFFFFF", $padding=5, $class="generalbox") {
1074 print_simple_box_start($align, $width, $color, $padding, $class);
7d8f674d 1075 echo stripslashes_safe($message);
9fa49e22 1076 print_simple_box_end();
1077}
1078
1079function print_simple_box_start($align="", $width="", $color="#FFFFFF", $padding=5, $class="generalbox") {
1080 global $THEME;
1081
1082 if ($align) {
76c1650d 1083 $align = "align=\"$align\"";
9fa49e22 1084 }
1085 if ($width) {
76c1650d 1086 $width = "width=\"$width\"";
9fa49e22 1087 }
9d378732 1088 echo "<table $align $width class=\"$class\" border=\"0\" cellpadding=\"$padding\" cellspacing=\"0\"><tr><td bgcolor=\"$color\" class=\"$class"."content\">";
9fa49e22 1089}
1090
1091function print_simple_box_end() {
1092 echo "</td></tr></table>";
1093}
1094
cc7fa0dc 1095function print_single_button($link, $options, $label="OK", $method="get") {
1096 echo "<form action=\"$link\" method=\"$method\">";
9fa49e22 1097 if ($options) {
1098 foreach ($options as $name => $value) {
66a51452 1099 echo "<input type=\"hidden\" name=\"$name\" value=\"$value\" />";
9fa49e22 1100 }
1101 }
66a51452 1102 echo "<input type=\"submit\" value=\"$label\" /></form>";
9fa49e22 1103}
1104
1105function print_spacer($height=1, $width=1, $br=true) {
1106 global $CFG;
66a51452 1107 echo "<img height=\"$height\" width=\"$width\" src=\"$CFG->wwwroot/pix/spacer.gif\" alt=\"\" />";
9fa49e22 1108 if ($br) {
76c1650d 1109 echo "<br />\n";
9fa49e22 1110 }
1111}
1112
1113function print_file_picture($path, $courseid=0, $height="", $width="", $link="") {
1114// Given the path to a picture file in a course, or a URL,
1115// this function includes the picture in the page.
1116 global $CFG;
1117
1118 if ($height) {
76c1650d 1119 $height = "height=\"$height\"";
9fa49e22 1120 }
1121 if ($width) {
76c1650d 1122 $width = "width=\"$width\"";
9fa49e22 1123 }
1124 if ($link) {
76c1650d 1125 echo "<a href=\"$link\">";
9fa49e22 1126 }
1127 if (substr(strtolower($path), 0, 7) == "http://") {
66a51452 1128 echo "<img border=\"0\" $height $width src=\"$path\" />";
9fa49e22 1129
1130 } else if ($courseid) {
66a51452 1131 echo "<img border=\"0\" $height $width src=\"";
9fa49e22 1132 if ($CFG->slasharguments) { // Use this method if possible for better caching
1133 echo "$CFG->wwwroot/file.php/$courseid/$path";
1134 } else {
3f396065 1135 echo "$CFG->wwwroot/file.php?file=/$courseid/$path";
9fa49e22 1136 }
66a51452 1137 echo "\" />";
9fa49e22 1138 } else {
1139 echo "Error: must pass URL or course";
1140 }
1141 if ($link) {
76c1650d 1142 echo "</a>";
9fa49e22 1143 }
1144}
1145
1146function print_user_picture($userid, $courseid, $picture, $large=false, $returnstring=false, $link=true) {
f374fb10 1147 global $CFG;
9fa49e22 1148
1149 if ($link) {
66a51452 1150 $output = "<a href=\"$CFG->wwwroot/user/view.php?id=$userid&amp;course=$courseid\">";
9fa49e22 1151 } else {
1152 $output = "";
1153 }
1154 if ($large) {
67a63a30 1155 $file = "f1";
9fa49e22 1156 $size = 100;
1157 } else {
67a63a30 1158 $file = "f2";
9fa49e22 1159 $size = 35;
1160 }
67a63a30 1161 if ($picture) { // Print custom user picture
9fa49e22 1162 if ($CFG->slasharguments) { // Use this method if possible for better caching
67a63a30 1163 $output .= "<img align=\"absmiddle\" src=\"$CFG->wwwroot/user/pix.php/$userid/$file.jpg\"".
66a51452 1164 " border=\"0\" width=\"$size\" height=\"$size\" alt=\"\" />";
9fa49e22 1165 } else {
67a63a30 1166 $output .= "<img align=\"absmiddle\" src=\"$CFG->wwwroot/user/pix.php?file=/$userid/$file.jpg\"".
66a51452 1167 " border=\"0\" width=\"$size\" height=\"$size\" alt=\"\" />";
9fa49e22 1168 }
67a63a30 1169 } else { // Print default user pictures (use theme version if available)
c9f6251e 1170 $output .= "<img align=\"absmiddle\" src=\"$CFG->pixpath/u/$file.png\"".
66a51452 1171 " border=\"0\" width=\"$size\" height=\"$size\" alt=\"\" />";
9fa49e22 1172 }
1173 if ($link) {
76c1650d 1174 $output .= "</a>";
9fa49e22 1175 }
1176
1177 if ($returnstring) {
1178 return $output;
1179 } else {
1180 echo $output;
1181 }
1182}
1183
951b22a8 1184function print_user($user, $course) {
1185/// Prints a summary of a user in a nice little box
1186
54be24ec 1187 global $CFG,$USER;
499795e8 1188
951b22a8 1189 static $string;
1190 static $datestring;
1191 static $countries;
1192 static $isteacher;
1193
1194 if (empty($string)) { // Cache all the strings for the rest of the page
1195
1196 $string->email = get_string("email");
1197 $string->location = get_string("location");
1198 $string->lastaccess = get_string("lastaccess");
1199 $string->activity = get_string("activity");
1200 $string->unenrol = get_string("unenrol");
1201 $string->loginas = get_string("loginas");
1202 $string->fullprofile = get_string("fullprofile");
1203 $string->role = get_string("role");
1204 $string->name = get_string("name");
1205 $string->never = get_string("never");
1206
1207 $datestring->day = get_string("day");
1208 $datestring->days = get_string("days");
1209 $datestring->hour = get_string("hour");
1210 $datestring->hours = get_string("hours");
1211 $datestring->min = get_string("min");
1212 $datestring->mins = get_string("mins");
1213 $datestring->sec = get_string("sec");
1214 $datestring->secs = get_string("secs");
1215
1216 $countries = get_list_of_countries();
1217
1218 $isteacher = isteacher($course->id);
1219 }
1220
1221 echo '<table width="80%" align="center" border="0" cellpadding="10" cellspacing="0" class="userinfobox">';
1222 echo '<tr>';
1223 echo '<td width="100" bgcolor="#ffffff" valign="top" class="userinfoboxside">';
1224 print_user_picture($user->id, $course->id, $user->picture, true);
1225 echo '</td>';
1226 echo '<td width="100%" bgcolor="#ffffff" valign="top" class="userinfoboxsummary">';
1227 echo '<font size="-1">';
1228 echo '<font size="3"><b>'.fullname($user, $isteacher).'</b></font>';
1229 echo '<p>';
1230 if (!empty($user->role) and ($user->role <> $course->teacher)) {
1231 echo "$string->role: $user->role<br />";
1232 }
d0ec93fb 1233 if ($user->maildisplay == 1 or ($user->maildisplay == 2 and $course->category and !isguest()) or $isteacher) {
951b22a8 1234 echo "$string->email: <a href=\"mailto:$user->email\">$user->email</a><br />";
1235 }
1236 if ($user->city or $user->country) {
1237 echo "$string->location: $user->city, ".$countries["$user->country"]."<br />";
1238 }
1239 if ($user->lastaccess) {
1240 echo "$string->lastaccess: ".userdate($user->lastaccess);
1241 echo "&nbsp (".format_time(time() - $user->lastaccess, $datestring).")";
1242 } else {
1243 echo "$string->lastaccess: $string->never";
1244 }
1245 echo '</td><td valign="bottom" bgcolor="#ffffff" nowrap="nowrap" class="userinfoboxlinkcontent">';
1246
1247 echo '<font size="1">';
1248 if ($isteacher) {
1249 $timemidnight = usergetmidnight(time());
499795e8 1250 echo "<a href=\"$CFG->wwwroot/course/user.php?id=$course->id&user=$user->id\">$string->activity</a><br>";
4e3a6092 1251 if (!iscreator($user->id)) { // Includes admins
1252 if (isstudent($course->id, $user->id)) { // Includes admins
1253 echo "<a href=\"$CFG->wwwroot/course/unenrol.php?id=$course->id&user=$user->id\">$string->unenrol</a><br />";
1254 }
1255 if ($USER->id != $user->id) {
1256 echo "<a href=\"$CFG->wwwroot/course/loginas.php?id=$course->id&user=$user->id\">$string->loginas</a><br />";
1257 }
951b22a8 1258 }
1259 }
499795e8 1260 echo "<a href=\"$CFG->wwwroot/user/view.php?id=$user->id&course=$course->id\">$string->fullprofile...</a>";
951b22a8 1261 echo '</font>';
1262
1263 echo '</td></tr></table>';
1264}
1265
1266
f2c80965 1267function print_group_picture($group, $courseid, $large=false, $returnstring=false, $link=true) {
f374fb10 1268 global $CFG;
1269
97ea4833 1270 static $isteacheredit;
1271
1272 if (!isset($isteacheredit)) {
1273 $isteacheredit = isteacheredit($courseid);
1274 }
1275
1276 if ($group->hidepicture and !$isteacheredit) {
3c0561cf 1277 return '';
1278 }
c3cbfe7f 1279
97ea4833 1280 if ($link or $isteacheredit) {
1281 $output = "<a href=\"$CFG->wwwroot/course/group.php?id=$courseid&amp;group=$group->id\">";
3c0561cf 1282 } else {
1283 $output = '';
1284 }
1285 if ($large) {
1286 $file = "f1";
1287 $size = 100;
1288 } else {
1289 $file = "f2";
1290 $size = 35;
1291 }
1292 if ($group->picture) { // Print custom group picture
1293 if ($CFG->slasharguments) { // Use this method if possible for better caching
1294 $output .= "<img align=\"absmiddle\" src=\"$CFG->wwwroot/user/pixgroup.php/$group->id/$file.jpg\"".
97ea4833 1295 " border=\"0\" width=\"$size\" height=\"$size\" alt=\"\" title=\"$group->name\"/>";
f2c80965 1296 } else {
3c0561cf 1297 $output .= "<img align=\"absmiddle\" src=\"$CFG->wwwroot/user/pixgroup.php?file=/$group->id/$file.jpg\"".
97ea4833 1298 " border=\"0\" width=\"$size\" height=\"$size\" alt=\"\" title=\"$group->name\"/>";
f2c80965 1299 }
f374fb10 1300 }
97ea4833 1301 if ($link or $isteacheredit) {
3c0561cf 1302 $output .= "</a>";
1303 }
f374fb10 1304
1305 if ($returnstring) {
1306 return $output;
1307 } else {
1308 echo $output;
1309 }
1310}
1311
35067c43 1312
1313function print_png($url, $sizex, $sizey, $returnstring, $parameters='alt=""') {
1314 global $CFG;
1315 static $recentIE;
1316
1317 if (!isset($recentIE)) {
1318 $recentIE = check_browser_version('MSIE', '5.0');
1319 }
1320
1321 if ($recentIE) { // work around the HORRIBLE bug IE has with alpha transparencies
1322 $output .= "<img src=\"$CFG->pixpath/spacer.gif\" width=\"$sizex\" height=\"$sizey\"".
1323 " border=\"0\" style=\"width: {$sizex}px; height: {$sizey}px; ".
1324 " filter: progid:DXImageTransform.Microsoft.AlphaImageLoader(src='$url', sizingMethod='scale') ".
1325 " $parameters />";
1326 } else {
1327 $output .= "<img src=\"$url\" border=\"0\" width=\"$sizex\" height=\"$sizey\" ".
1328 " $parameters />";
1329 }
1330
1331 if ($returnstring) {
1332 return $output;
1333 } else {
1334 echo $output;
1335 }
1336}
1337
1338
9fa49e22 1339function print_table($table) {
1340// Prints a nicely formatted table.
1341// $table is an object with several properties.
1342// $table->head is an array of heading names.
1343// $table->align is an array of column alignments
1344// $table->size is an array of column sizes
5867bfb5 1345// $table->wrap is an array of "nowrap"s or nothing
9fa49e22 1346// $table->data[] is an array of arrays containing the data.
1347// $table->width is an percentage of the page
1348// $table->cellpadding padding on each cell
1349// $table->cellspacing spacing between cells
1350
e21e20cf 1351 global $THEME;
1352
9fa49e22 1353 if (isset($table->align)) {
1354 foreach ($table->align as $key => $aa) {
1355 if ($aa) {
76c1650d 1356 $align[$key] = " align=\"$aa\"";
9fa49e22 1357 } else {
1358 $align[$key] = "";
1359 }
1360 }
1361 }
1362 if (isset($table->size)) {
1363 foreach ($table->size as $key => $ss) {
1364 if ($ss) {
76c1650d 1365 $size[$key] = " width=\"$ss\"";
9fa49e22 1366 } else {
1367 $size[$key] = "";
1368 }
1369 }
1370 }
5867bfb5 1371 if (isset($table->wrap)) {
1372 foreach ($table->wrap as $key => $ww) {
1373 if ($ww) {
66a51452 1374 $wrap[$key] = " nowrap=\"nowrap\" ";
5867bfb5 1375 } else {
1376 $wrap[$key] = "";
1377 }
1378 }
1379 }
9fa49e22 1380
9d378732 1381 if (empty($table->width)) {
9fa49e22 1382 $table->width = "80%";
1383 }
1384
9d378732 1385 if (empty($table->cellpadding)) {
9fa49e22 1386 $table->cellpadding = "5";
1387 }
1388
9d378732 1389 if (empty($table->cellspacing)) {
9fa49e22 1390 $table->cellspacing = "1";
1391 }
1392
5867bfb5 1393 print_simple_box_start("center", "$table->width", "#ffffff", 0);
66a51452 1394 echo "<table width=\"100%\" border=\"0\" valign=\"top\" align=\"center\" ";
9fa49e22 1395 echo " cellpadding=\"$table->cellpadding\" cellspacing=\"$table->cellspacing\" class=\"generaltable\">\n";
1396
e21e20cf 1397 $countcols = 0;
1398
b79f41cd 1399 if (!empty($table->head)) {
e21e20cf 1400 $countcols = count($table->head);;
5867bfb5 1401 echo "<tr>";
9fa49e22 1402 foreach ($table->head as $key => $heading) {
e21e20cf 1403
9d378732 1404 if (!isset($size[$key])) {
1405 $size[$key] = "";
1406 }
1407 if (!isset($align[$key])) {
1408 $align[$key] = "";
1409 }
66a51452 1410 echo "<th valign=\"top\" ".$align[$key].$size[$key]." nowrap=\"nowrap\" class=\"generaltableheader\">$heading</th>";
9fa49e22 1411 }
66a51452 1412 echo "</tr>\n";
9fa49e22 1413 }
1414
a1f8ff87 1415 if (!empty($table->data)) {
1416 foreach ($table->data as $row) {
1417 echo "<tr valign=\"top\">";
e21e20cf 1418 if ($row == "hr" and $countcols) {
6a903e0e 1419 echo "<td colspan=\"$countcols\"><div class=\"tabledivider\"></div></td>";
e21e20cf 1420 } else { /// it's a normal row of data
1421 foreach ($row as $key => $item) {
1422 if (!isset($size[$key])) {
1423 $size[$key] = "";
1424 }
1425 if (!isset($align[$key])) {
1426 $align[$key] = "";
1427 }
1428 if (!isset($wrap[$key])) {
1429 $wrap[$key] = "";
1430 }
1431 echo "<td ".$align[$key].$size[$key].$wrap[$key]." class=\"generaltablecell\">$item</td>";
1432 }
a1f8ff87 1433 }
1434 echo "</tr>\n";
9fa49e22 1435 }
9fa49e22 1436 }
5867bfb5 1437 echo "</table>\n";
9fa49e22 1438 print_simple_box_end();
1439
1440 return true;
1441}
1442
2f4d324b 1443function make_table($table) {
1444// Creates a nicely formatted table and returns it
1445// $table is an object with several properties.
1446// $table->head is an array of heading names.
1447// $table->align is an array of column alignments
1448// $table->size is an array of column sizes
1449// $table->wrap is an array of "nowrap"s or nothing
1450// $table->data[] is an array of arrays containing the data.
1451// $table->width is an percentage of the page
1452// $table->class is a class
1453// $table->fontsize is the size of all the text
1454// $table->tablealign align the whole table
1455// $table->cellpadding padding on each cell
1456// $table->cellspacing spacing between cells
1457
1458 if (isset($table->align)) {
1459 foreach ($table->align as $key => $aa) {
1460 if ($aa) {
1461 $align[$key] = " align=\"$aa\"";
1462 } else {
1463 $align[$key] = "";
1464 }
1465 }
1466 }
1467 if (isset($table->size)) {
1468 foreach ($table->size as $key => $ss) {
1469 if ($ss) {
1470 $size[$key] = " width=\"$ss\"";
1471 } else {
1472 $size[$key] = "";
1473 }
1474 }
1475 }
1476 if (isset($table->wrap)) {
1477 foreach ($table->wrap as $key => $ww) {
1478 if ($ww) {
66a51452 1479 $wrap[$key] = " nowrap=\"nowrap\" ";
2f4d324b 1480 } else {
1481 $wrap[$key] = "";
1482 }
1483 }
1484 }
1485
1486 if (empty($table->width)) {
1487 $table->width = "80%";
1488 }
1489
1490 if (empty($table->tablealign)) {
1491 $table->tablealign = "center";
1492 }
1493
1494 if (empty($table->cellpadding)) {
1495 $table->cellpadding = "5";
1496 }
1497
1498 if (empty($table->cellspacing)) {
1499 $table->cellspacing = "1";
1500 }
1501
1502 if (empty($table->class)) {
1503 $table->class = "generaltable";
1504 }
1505
1506 if (empty($table->fontsize)) {
1507 $fontsize = "";
1508 } else {
1509 $fontsize = "<font size=\"$table->fontsize\">";
1510 }
1511
66a51452 1512 $output = "<table width=\"$table->width\" valign=\"top\" align=\"$table->tablealign\" ";
2f4d324b 1513 $output .= " cellpadding=\"$table->cellpadding\" cellspacing=\"$table->cellspacing\" class=\"$table->class\">\n";
1514
1515 if (!empty($table->head)) {
1516 $output .= "<tr>";
1517 foreach ($table->head as $key => $heading) {
1518 if (!isset($size[$key])) {
1519 $size[$key] = "";
1520 }
1521 if (!isset($align[$key])) {
1522 $align[$key] = "";
1523 }
66a51452 1524 $output .= "<th valign=\"top\" ".$align[$key].$size[$key]." nowrap=\"nowrap\" class=\"{$table->class}header\">$fontsize$heading</th>";
2f4d324b 1525 }
1526 $output .= "</tr>\n";
1527 }
1528
1529 foreach ($table->data as $row) {
66a51452 1530 $output .= "<tr valign=\"top\">";
2f4d324b 1531 foreach ($row as $key => $item) {
1532 if (!isset($size[$key])) {
1533 $size[$key] = "";
1534 }
1535 if (!isset($align[$key])) {
1536 $align[$key] = "";
1537 }
1538 if (!isset($wrap[$key])) {
1539 $wrap[$key] = "";
1540 }
1541 $output .= "<td ".$align[$key].$size[$key].$wrap[$key]." class=\"{$table->class}cell\">$fontsize$item</td>";
1542 }
1543 $output .= "</tr>\n";
1544 }
1545 $output .= "</table>\n";
1546
1547 return $output;
1548}
1549
47037513 1550function print_textarea($usehtmleditor, $rows, $cols, $width, $height, $name, $value="", $courseid=0) {
1551/// Prints a basic textarea field
1552/// $width and height are legacy fields and no longer used
4c46c425 1553
47037513 1554 global $CFG, $course;
50bdc74d 1555
408e62f8 1556 if (empty($courseid)) {
50bdc74d 1557 if (!empty($course->id)) { // search for it in global context
1558 $courseid = $course->id;
1559 }
1560 }
9fa49e22 1561
47037513 1562 if ($usehtmleditor) {
1563 if (!empty($courseid) and isteacher($courseid)) {
1564 echo "<script type=\"text/javascript\" src=\"$CFG->wwwroot/lib/editor/htmlarea.php?id=$courseid\"></script>\n";
1565 } else {
1566 echo "<script type=\"text/javascript\" src=\"$CFG->wwwroot/lib/editor/htmlarea.php\"></script>\n";
1567 }
1568 echo "<script type=\"text/javascript\" src=\"$CFG->wwwroot/lib/editor/dialog.js\"></script>\n";
1569 echo "<script type=\"text/javascript\" src=\"$CFG->wwwroot/lib/editor/lang/en.php\"></script>\n";
1570 echo "<script type=\"text/javascript\" src=\"$CFG->wwwroot/lib/editor/popupwin.js\"></script>\n";
50bdc74d 1571
47037513 1572 if ($rows < 20) {
1573 $rows = 20;
1574 }
1575 if ($cols < 65) {
1576 $cols = 65;
4c46c425 1577 }
9fa49e22 1578 }
47037513 1579
1580 echo "<textarea id=\"$name\" name=\"$name\" rows=\"$rows\" cols=\"$cols\" wrap=\"virtual\">";
1581 p($value);
1582 echo "</textarea>\n";
9fa49e22 1583}
1584
1585function print_richedit_javascript($form, $name, $source="no") {
47037513 1586/// Legacy function, provided for backward compatability
1587 use_html_editor($name);
1588}
1589
1590function use_html_editor($name="") {
1591/// Sets up the HTML editor on textareas in the current page.
1592/// If a field name is provided, then it will only be
1593/// applied to that field - otherwise it will be used
1594/// on every textarea in the page.
1595///
1596/// In most cases no arguments need to be supplied
4c46c425 1597
47037513 1598 echo "<script language=\"javascript\" type=\"text/javascript\" defer=\"1\">\n";
1599 if (empty($name)) {
1600 echo "HTMLArea.replaceAll();";
1601 } else {
1602 echo "HTMLArea.replace('$name')";
4c46c425 1603 }
47037513 1604 echo "</script>";
9fa49e22 1605}
1606
1607
1608function update_course_icon($courseid) {
1609// Used to be an icon, but it's now a simple form button
1610 global $CFG, $USER;
1611
b6c12732 1612 if (isteacheredit($courseid)) {
9c9f7d77 1613 if (!empty($USER->editing)) {
9fa49e22 1614 $string = get_string("turneditingoff");
1615 $edit = "off";
1616 } else {
1617 $string = get_string("turneditingon");
1618 $edit = "on";
1619 }
60b9a565 1620 return "<form target=\"$CFG->framename\" method=\"get\" action=\"$CFG->wwwroot/course/view.php\">".
66a51452 1621 "<input type=\"hidden\" name=\"id\" value=\"$courseid\" />".
1622 "<input type=\"hidden\" name=\"edit\" value=\"$edit\" />".
1623 "<input type=\"submit\" value=\"$string\" /></form>";
9fa49e22 1624 }
1625}
1626
1627function update_module_button($moduleid, $courseid, $string) {
1628// Prints the editing button on a module "view" page
1629 global $CFG;
1630
b6c12732 1631 if (isteacheredit($courseid)) {
9fa49e22 1632 $string = get_string("updatethis", "", $string);
60b9a565 1633 return "<form target=\"$CFG->framename\" method=\"get\" action=\"$CFG->wwwroot/course/mod.php\">".
66a51452 1634 "<input type=\"hidden\" name=\"update\" value=\"$moduleid\" />".
1635 "<input type=\"hidden\" name=\"return\" value=\"true\" />".
1636 "<input type=\"submit\" value=\"$string\" /></form>";
b6c12732 1637 } else {
1638 return "";
9fa49e22 1639 }
1640}
1641
c2cb4545 1642function update_category_button($categoryid) {
d2b6ba70 1643// Prints the editing button on a category page
1644 global $CFG, $USER;
c2cb4545 1645
d2b6ba70 1646 if (iscreator()) {
f374fb10 1647 if (!empty($USER->categoryediting)) {
d2b6ba70 1648 $string = get_string("turneditingoff");
1649 $edit = "off";
1650 } else {
1651 $string = get_string("turneditingon");
1652 $edit = "on";
9b16d1ea 1653 }
60b9a565 1654 return "<form target=\"$CFG->framename\" method=\"get\" action=\"$CFG->wwwroot/course/category.php\">".
66a51452 1655 "<input type=\"hidden\" name=\"id\" value=\"$categoryid\" />".
1656 "<input type=\"hidden\" name=\"edit\" value=\"$edit\" />".
1657 "<input type=\"submit\" value=\"$string\" /></form>";
d2b6ba70 1658 }
1659}
1660
1661function update_categories_button() {
1662// Prints the editing button on categories listing
1663 global $CFG, $USER;
1664
1665 if (isadmin()) {
f374fb10 1666 if (!empty($USER->categoriesediting)) {
d2b6ba70 1667 $string = get_string("turneditingoff");
1668 $edit = "off";
1669 } else {
1670 $string = get_string("turneditingon");
1671 $edit = "on";
1672 }
60b9a565 1673 return "<form target=\"$CFG->framename\" method=\"get\" action=\"$CFG->wwwroot/course/index.php\">".
66a51452 1674 "<input type=\"hidden\" name=\"edit\" value=\"$edit\" />".
1675 "<input type=\"submit\" value=\"$string\" /></form>";
c2cb4545 1676 }
1677}
9fa49e22 1678
b3153e4b 1679function update_group_button($courseid, $groupid) {
f374fb10 1680// Prints the editing button on group page
1681 global $CFG, $USER;
1682
1683 if (isteacheredit($courseid)) {
b3153e4b 1684 $string = get_string('editgroupprofile');
f374fb10 1685 return "<form target=\"$CFG->framename\" method=\"get\" action=\"$CFG->wwwroot/course/group.php\">".
1686 "<input type=\"hidden\" name=\"id\" value=\"$courseid\" />".
b3153e4b 1687 "<input type=\"hidden\" name=\"group\" value=\"$groupid\" />".
1688 "<input type=\"hidden\" name=\"edit\" value=\"on\" />".
f374fb10 1689 "<input type=\"submit\" value=\"$string\" /></form>";
1690 }
1691}
1692
1693function update_groups_button($courseid) {
1694// Prints the editing button on groups page
1695 global $CFG, $USER;
1696
1697 if (isteacheredit($courseid)) {
1698 if (!empty($USER->groupsediting)) {
1699 $string = get_string("turneditingoff");
1700 $edit = "off";
1701 } else {
1702 $string = get_string("turneditingon");
1703 $edit = "on";
1704 }
1705 return "<form target=\"$CFG->framename\" method=\"get\" action=\"$CFG->wwwroot/course/groups.php\">".
1706 "<input type=\"hidden\" name=\"id\" value=\"$courseid\" />".
1707 "<input type=\"hidden\" name=\"edit\" value=\"$edit\" />".
1708 "<input type=\"submit\" value=\"$string\" /></form>";
1709 }
1710}
1711
c3cbfe7f 1712function print_group_menu($groups, $groupmode, $currentgroup, $urlroot) {
1713/// Prints an appropriate group selection menu
1714
1d9fc417 1715/// Add an "All groups" to the start of the menu
743a92ff 1716 $groupsmenu[0] = get_string("allparticipants");
1d9fc417 1717 foreach ($groups as $key => $groupname) {
1718 $groupsmenu[$key] = $groupname;
1719 }
1720
e9a551b3 1721 echo '<table><tr><td align="right">';
c3cbfe7f 1722 if ($groupmode == VISIBLEGROUPS) {
1723 print_string('groupsvisible');
1724 } else {
1725 print_string('groupsseparate');
1726 }
1727 echo ':';
e9a551b3 1728 echo '</td><td nowrap="nowrap" align="left">';
1d9fc417 1729 popup_form($urlroot.'&group=', $groupsmenu, 'selectgroup', $currentgroup, "", "", "", false, "self");
c3cbfe7f 1730 echo '</tr></table>';
1731
1732}
1733
f2d91421 1734
16ef5e78 1735function navmenu($course, $cm=NULL, $targetwindow="self") {
9fa49e22 1736// Given a course and a (current) coursemodule
f2d91421 1737// This function returns a small popup menu with all the
9fa49e22 1738// course activity modules in it, as a navigation menu
f2d91421 1739// The data is taken from the serialised array stored in
9fa49e22 1740// the course record
1741
1742 global $CFG;
1743
1744 if ($cm) {
f2d91421 1745 $cm = $cm->id;
9fa49e22 1746 }
1747
1748 if ($course->format == 'weeks') {
1749 $strsection = get_string("week");
1750 } else {
1751 $strsection = get_string("topic");
1752 }
1753
1754 if (!$modinfo = unserialize($course->modinfo)) {
1755 return "";
1756 }
f2d91421 1757 $isteacher = isteacher($course->id);
9fa49e22 1758 $section = -1;
1759 $selected = "";
f2d91421 1760 $url = "";
1761 $previousmod = NULL;
1762 $backmod = NULL;
1763 $nextmod = NULL;
4866a367 1764 $selectmod = NULL;
3da47524 1765 $logslink = NULL;
f2d91421 1766 $flag = false;
1767
9fa49e22 1768 foreach ($modinfo as $mod) {
ab2df10c 1769 if ($mod->mod == "label") {
1770 continue;
1771 }
9fa49e22 1772 if ($mod->section > 0 and $section <> $mod->section) {
1773 $menu[] = "-------------- $strsection $mod->section --------------";
1774 }
1775 $section = $mod->section;
cf055081 1776 //Only add visible or teacher mods to jumpmenu
f2d91421 1777 if ($mod->visible or $isteacher) {
cf055081 1778 $url = "$mod->mod/view.php?id=$mod->cm";
f2d91421 1779 if ($flag) { // the current mod is the "next" mod
1780 $nextmod = $mod;
1781 $flag = false;
1782 }
cf055081 1783 if ($cm == $mod->cm) {
1784 $selected = $url;
3da47524 1785 $selectmod = $mod;
f2d91421 1786 $backmod = $previousmod;
1787 $flag = true; // set flag so we know to use next mod for "next"
cf055081 1788 }
1789 $mod->name = urldecode($mod->name);
1790 if (strlen($mod->name) > 55) {
1791 $mod->name = substr($mod->name, 0, 50)."...";
1792 }
2a409368 1793 if (!$mod->visible) {
1794 $mod->name = "(".$mod->name.")";
1795 }
f2d91421 1796 $menu[$url] = $mod->name;
db0d0337 1797 $previousmod = $mod;
9fa49e22 1798 }
f2d91421 1799 }
69d79bc3 1800 if ($selectmod and $isteacher) {
791b42ee 1801 $logslink = "<td><a target=\"$CFG->framename\" href=".
69d79bc3 1802 "\"$CFG->wwwroot/course/log.php?chooselog=1&user=0&date=0&id=$course->id&modid=$selectmod->cm\">".
1803 "<img border=\"0\" height=\"16\" width=\"16\" src=\"$CFG->pixpath/i/log.gif\"></a></td>";
3da47524 1804
1805 }
f2d91421 1806 if ($backmod) {
1807 $backmod = "<form action=\"$CFG->wwwroot/mod/$backmod->mod/view.php\" target=\"$CFG->framename\">".
1808 "<input type=\"hidden\" name=\"id\" value=\"$backmod->cm\">".
1809 "<input type=\"submit\" value=\"&lt;\"></form>";
1810 }
1811 if ($nextmod) {
1812 $nextmod = "<form action=\"$CFG->wwwroot/mod/$nextmod->mod/view.php\" target=\"$CFG->framename\">".
1813 "<input type=\"hidden\" name=\"id\" value=\"$nextmod->cm\">".
1814 "<input type=\"submit\" value=\"&gt;\"></form>";
1815 }
3da47524 1816 return "<table><tr>$logslink<td>$backmod</td><td>" .
f2d91421 1817 popup_form("$CFG->wwwroot/mod/", $menu, "navmenu", $selected, get_string("jumpto"),
1818 "", "", true, $targetwindow).
1819 "</td><td>$nextmod</td></tr></table>";
1820}
9fa49e22 1821
1822
1823function print_date_selector($day, $month, $year, $currenttime=0) {
1824// Currenttime is a default timestamp in GMT
1825// Prints form items with the names $day, $month and $year
1826
1827 if (!$currenttime) {
1828 $currenttime = time();
1829 }
1830 $currentdate = usergetdate($currenttime);
1831
1832 for ($i=1; $i<=31; $i++) {
1833 $days[$i] = "$i";
1834 }
1835 for ($i=1; $i<=12; $i++) {
39e018b3 1836 $months[$i] = userdate(gmmktime(12,0,0,$i,1,2000), "%B");
9fa49e22 1837 }
1838 for ($i=2000; $i<=2010; $i++) {
1839 $years[$i] = $i;
1840 }
47f1da80 1841 choose_from_menu($days, $day, $currentdate['mday'], "");
1842 choose_from_menu($months, $month, $currentdate['mon'], "");
1843 choose_from_menu($years, $year, $currentdate['year'], "");
9fa49e22 1844}
1845
6942583e 1846function print_time_selector($hour, $minute, $currenttime=0, $step=5) {
9fa49e22 1847// Currenttime is a default timestamp in GMT
1848// Prints form items with the names $hour and $minute
1849
1850 if (!$currenttime) {
1851 $currenttime = time();
1852 }
1853 $currentdate = usergetdate($currenttime);
6942583e 1854 if ($step != 1) {
1855 $currentdate['minutes'] = ceil($currentdate['minutes']/$step)*$step;
1856 }
9fa49e22 1857 for ($i=0; $i<=23; $i++) {
1858 $hours[$i] = sprintf("%02d",$i);
1859 }
6942583e 1860 for ($i=0; $i<=59; $i+=$step) {
9fa49e22 1861 $minutes[$i] = sprintf("%02d",$i);
1862 }
47f1da80 1863 choose_from_menu($hours, $hour, $currentdate['hours'], "");
1864 choose_from_menu($minutes, $minute, $currentdate['minutes'], "");
9fa49e22 1865}
1866
d6bdd9d5 1867function print_grade_menu($courseid, $name, $current, $includenograde=true) {
62ca135d 1868/// Prints a grade menu (as part of an existing form) with help
1869/// Showing all possible numerical grades and scales
1870
c9f6251e 1871 global $CFG;
62ca135d 1872
1873 $strscale = get_string("scale");
1874 $strscales = get_string("scales");
1875
1f7deef6 1876 $scales = get_scales_menu($courseid);
62ca135d 1877 foreach ($scales as $i => $scalename) {
1878 $grades[-$i] = "$strscale: $scalename";
1879 }
d6bdd9d5 1880 if ($includenograde) {
1881 $grades[0] = get_string("nograde");
1882 }
62ca135d 1883 for ($i=100; $i>=1; $i--) {
1884 $grades[$i] = $i;
1885 }
1886 choose_from_menu($grades, "$name", "$current", "");
1887
c9f6251e 1888 $helpicon = "$CFG->pixpath/help.gif";
66a51452 1889 $linkobject = "<img align=\"absmiddle\" border=\"0\" height=\"17\" width=\"22\" alt=\"$strscales\" src=\"$helpicon\" />";
1890 link_to_popup_window ("/course/scales.php?id=$courseid&amp;list=true", "ratingscales",
62ca135d 1891 $linkobject, 400, 500, $strscales);
1892}
1893
02ebf404 1894function print_scale_menu($courseid, $name, $current) {
1895/// Prints a scale menu (as part of an existing form) including help button
62ca135d 1896/// Just like print_grade_menu but without the numerical grades
02ebf404 1897
c9f6251e 1898 global $CFG;
02ebf404 1899
1900 $strscales = get_string("scales");
1901 choose_from_menu(get_scales_menu($courseid), "$name", $current, "");
c9f6251e 1902 $helpicon = "$CFG->pixpath/help.gif";
66a51452 1903 $linkobject = "<img align=\"absmiddle\" border=\"0\" height=\"17\" width=\"22\" alt=\"$strscales\" src=\"$helpicon\" />";
1904 link_to_popup_window ("/course/scales.php?id=$courseid&amp;list=true", "ratingscales",
02ebf404 1905 $linkobject, 400, 500, $strscales);
1906}
1907
fdc47ee6 1908
02ebf404 1909function print_scale_menu_helpbutton($courseid, $scale) {
1910/// Prints a help button about a scale
1911/// scale is an object
1912
c9f6251e 1913 global $CFG;
02ebf404 1914
1915 $strscales = get_string("scales");
c9f6251e 1916 $helpicon = "$CFG->pixpath/help.gif";
66a51452 1917 $linkobject = "<img align=\"absmiddle\" border=\"0\" height=\"17\" width=\"22\" alt=\"$scale->name\" src=\"$helpicon\" />";
1918 link_to_popup_window ("/course/scales.php?id=$courseid&amp;list=true&amp;scale=$scale->id", "ratingscale",
02ebf404 1919 $linkobject, 400, 500, $scale->name);
1920}
1921
1922
9fa49e22 1923function error ($message, $link="") {
1924 global $CFG, $SESSION;
1925
1926 print_header(get_string("error"));
66a51452 1927 echo "<br />";
9fa49e22 1928 print_simple_box($message, "center", "", "#FFBBBB");
1929
1930 if (!$link) {
1931 if ( !empty($SESSION->fromurl) ) {
1932 $link = "$SESSION->fromurl";
1933 unset($SESSION->fromurl);
9fa49e22 1934 } else {
c2cb4545 1935 $link = "$CFG->wwwroot/";
9fa49e22 1936 }
1937 }
1938 print_continue($link);
1939 print_footer();
1940 die;
1941}
1942
1943function helpbutton ($page, $title="", $module="moodle", $image=true, $linktext=false, $text="") {
1944 // $page = the keyword that defines a help page
1945 // $title = the title of links, rollover tips, alt tags etc
1946 // $module = which module is the page defined in
1947 // $image = use a help image for the link? (true/false/"both")
1948 // $text = if defined then this text is used in the page, and
1949 // the $page variable is ignored.
dc0dc7d5 1950 global $CFG, $THEME;
9fa49e22 1951
1952 if ($module == "") {
1953 $module = "moodle";
1954 }
1955
1956 if ($image) {
c9f6251e 1957 $icon = "$CFG->pixpath/help.gif";
9fa49e22 1958 if ($linktext) {
7fc0f9e5 1959 $linkobject = "<span style=\"cursor:help;\">$title<img align=\"absmiddle\" border=\"0\" ".
1960 " height=\"17\" width=\"22\" alt=\"\" src=\"$icon\" /></span>";
9fa49e22 1961 } else {
7fc0f9e5 1962 $linkobject = "<img align=\"absmiddle\" border=\"0\" height=\"17\" width=\"22\" ".
1963 " alt=\"$title\" style=\"cursor:help;\" src=\"$icon\" />";
9fa49e22 1964 }
1965 } else {
7fc0f9e5 1966 $linkobject = "<span style=\"cursor:help;\">$title</span>";
9fa49e22 1967 }
1968 if ($text) {
66a51452 1969 $url = "/help.php?module=$module&amp;text=".htmlentities(urlencode($text));
9fa49e22 1970 } else {
66a51452 1971 $url = "/help.php?module=$module&amp;file=$page.html";
9fa49e22 1972 }
1973 link_to_popup_window ($url, "popup", $linkobject, 400, 500, $title);
1974}
1975
e825f279 1976function emoticonhelpbutton($form, $field) {
1977/// Prints a special help button that is a link to the "live" emoticon popup
1978 global $CFG, $SESSION;
1979
1980 $SESSION->inserttextform = $form;
1981 $SESSION->inserttextfield = $field;
1982 helpbutton("emoticons", get_string("helpemoticons"), "moodle", false, true);
c9f6251e 1983 echo "&nbsp;";
66a51452 1984 link_to_popup_window ("/help.php?module=moodle&amp;file=emoticons.html", "popup",
1985 "<img src=\"$CFG->pixpath/s/smiley.gif\" border=\"0\" align=\"absmiddle\" width=\"15\" height=\"15\" />",
c9f6251e 1986 400, 500, get_string("helpemoticons"));
1987 echo "<br />";
e825f279 1988}
1989
9fa49e22 1990function notice ($message, $link="") {
750ab759 1991 global $CFG, $THEME;
9fa49e22 1992
1993 if (!$link) {
750ab759 1994 if (!empty($_SERVER["HTTP_REFERER"])) {
1995 $link = $_SERVER["HTTP_REFERER"];
1996 } else {
c2cb4545 1997 $link = "$CFG->wwwroot/";
750ab759 1998 }
9fa49e22 1999 }
2000
01d79966 2001 echo "<br />";
11a876e1 2002 print_simple_box($message, "center", "50%", "$THEME->cellheading", "20", "noticebox");
eb347b6b 2003 print_heading("<a href=\"$link\">".get_string("continue")."</a>");
9fa49e22 2004 print_footer(get_site());
2005 die;
2006}
2007
2008function notice_yesno ($message, $linkyes, $linkno) {
2009 global $THEME;
2010
eb347b6b 2011 print_simple_box_start("center", "60%", "$THEME->cellheading");
66a51452 2012 echo "<p align=\"center\"><font size=\"3\">$message</font></p>";
2013 echo "<p align=\"center\"><font size=\"3\"><b>";
eb347b6b 2014 echo "<a href=\"$linkyes\">".get_string("yes")."</a>";
9fa49e22 2015 echo "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;";
eb347b6b 2016 echo "<a href=\"$linkno\">".get_string("no")."</a>";
2017 echo "</b></font></p>";
9fa49e22 2018 print_simple_box_end();
2019}
2020
559573a2 2021function redirect($url, $message="", $delay="0") {
5d6c043a 2022// Redirects the user to another page, after printing a notice
9fa49e22 2023
c9082a8c 2024 if (empty($message)) {
2b23eea3 2025 echo "<meta http-equiv=\"refresh\" content=\"$delay; url=$url\" />";
8a55c984 2026 echo "<script>location.replace('$url');</script>"; // To cope with Mozilla bug
c9082a8c 2027 } else {
05c19593 2028 if (empty($delay)) {
c9082a8c 2029 $delay = 3; // There's no point having a message with no delay
2030 }
5f546a46 2031 print_header("", "", "", "", "<meta http-equiv=\"refresh\" content=\"$delay; url=$url\" />");
76c1650d 2032 echo "<center>";
2033 echo "<p>$message</p>";
2034 echo "<p>( <a href=\"$url\">".get_string("continue")."</a> )</p>";
2035 echo "</center>";
ff019455 2036 flush();
2037 sleep($delay);
2038 echo "<script>location.replace('$url');</script>"; // To cope with Mozilla bug
9fa49e22 2039 }
2040 die;
2041}
2042
99988d1a 2043function notify ($message, $color="red", $align="center") {
2044 echo "<p align=\"$align\"><b><font color=\"$color\">$message</font></b></p>\n";
9fa49e22 2045}
2046
43373804 2047function obfuscate_email($email) {
2048/// Given an email address, this function will return an obfuscated version of it
2049 $i = 0;
2050 $length = strlen($email);
2051 $obfuscated = "";
2052 while ($i < $length) {
2053 if (rand(0,2)) {
2054 $obfuscated.='%'.dechex(ord($email{$i}));
2055 } else {
2056 $obfuscated.=$email{$i};
2057 }
2058 $i++;
2059 }
2060 return $obfuscated;
2061}
2062
2063function obfuscate_text($plaintext) {
2064/// This function takes some text and replaces about half of the characters
2065/// with HTML entity equivalents. Return string is obviously longer.
2066 $i=0;
2067 $length = strlen($plaintext);
2068 $obfuscated="";
2b09e377 2069 $prev_obfuscated = false;
43373804 2070 while ($i < $length) {
2b09e377 2071 $c = ord($plaintext{$i});
2072 $numerical = ($c >= ord('0')) && ($c <= ord('9'));
2073 if ($prev_obfuscated and $numerical ) {
2074 $obfuscated.='&#'.ord($plaintext{$i});
2075 } else if (rand(0,2)) {
43373804 2076 $obfuscated.='&#'.ord($plaintext{$i});
2b09e377 2077 $prev_obfuscated = true;
43373804 2078 } else {
2079 $obfuscated.=$plaintext{$i};
2b09e377 2080 $prev_obfuscated = false;
43373804 2081 }
2b09e377 2082 $i++;
43373804 2083 }
2084 return $obfuscated;
2085}
2086
cadb96f2 2087function obfuscate_mailto($email, $label="", $dimmed=false) {
43373804 2088/// This function uses the above two functions to generate a fully
2089/// obfuscated email link, ready to use.
2090
2091 if (empty($label)) {
2092 $label = $email;
2093 }
cadb96f2 2094 if ($dimmed) {
2095 $title = get_string('emaildisable');
2096 $dimmed = ' class="dimmed"';
2097 } else {
2098 $title = '';
2099 $dimmed = '';
2100 }
2101 return sprintf("<a href=\"%s:%s\" $dimmed title=\"$title\">%s</a>",
2102 obfuscate_text('mailto'), obfuscate_email($email),
2103 obfuscate_text($label));
43373804 2104}
2105
8b9c7aa0 2106function print_paging_bar($totalcount, $page, $perpage, $baseurl) {
2107/// Prints a single paging bar to provide access to other pages (usually in a search)
2108
519d369f 2109 $maxdisplay = 18;
8ef9cb56 2110
8b9c7aa0 2111 if ($totalcount > $perpage) {
f04dc61d 2112 echo "<center>";
2113 echo "<p>".get_string("page").":";
f374fb10 2114 if ($page > 0) {
2115 $pagenum=$page-1;
2116 echo "&nbsp;(<a href=\"{$baseurl}page=$pagenum\">".get_string("previous")."</a>)&nbsp;";
2117 }
be20753e 2118 $lastpage = ceil($totalcount / $perpage);
2119 if ($page > 15) {
2120 $startpage = $page - 10;
519d369f 2121 echo "&nbsp<a href=\"{$baseurl}page=0\">1</a>&nbsp;...";
be20753e 2122 } else {
2123 $startpage = 0;
2124 }
be20753e 2125 $currpage = $startpage;
2126 $displaycount = 0;
2127 while ($displaycount < $maxdisplay and $currpage < $lastpage) {
2128 $displaypage = $currpage+1;
2129 if ($page == $currpage) {
8b9c7aa0 2130 echo "&nbsp;&nbsp;$displaypage";
2131 } else {
be20753e 2132 echo "&nbsp;&nbsp;<a href=\"{$baseurl}page=$currpage\">$displaypage</a>";
e27dbcc8 2133 }
be20753e 2134 $displaycount++;
2135 $currpage++;
8b9c7aa0 2136 }
924cef21 2137 if ($currpage < $lastpage) {
519d369f 2138 $lastpageactual = $lastpage - 1;
2139 echo "&nbsp;...<a href=\"{$baseurl}page=$lastpageactual\">$lastpage</a>&nbsp;";
924cef21 2140 }
8b9c7aa0 2141 $pagenum = $page + 1;
be20753e 2142 if ($pagenum != $displaypage) {
8b9c7aa0 2143 echo "&nbsp;&nbsp;(<a href=\"{$baseurl}page=$pagenum\">".get_string("next")."</a>)";
2144 }
2145 echo "</p>";
be20753e 2146 echo "</center>";
8b9c7aa0 2147 }
2148}
9fa49e22 2149
9d5b689c 2150// vim:autoindent:expandtab:shiftwidth=4:tabstop=4:tw=140:
f9903ed0 2151?>