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