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