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