Automatic installer.php lang files by installer_builder (20071129)
[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// //
b7064779 10// Copyright (C) 1999 onwards Martin Dougiamas http://dougiamas.com //
9fa49e22 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
a194510a 44require_once("$CFG->libdir/ajax/ajaxlib.php");
45
0095d5cd 46/// Constants
47
c1d57101 48/// Define text formatting types ... eventually we can add Wiki, BBcode etc
7cf1c7bd 49
50/**
51 * Does all sorts of transformations and filtering
52 */
b0ccd3fb 53define('FORMAT_MOODLE', '0'); // Does all sorts of transformations and filtering
7cf1c7bd 54
55/**
56 * Plain HTML (with some tags stripped)
57 */
b0ccd3fb 58define('FORMAT_HTML', '1'); // Plain HTML (with some tags stripped)
7cf1c7bd 59
60/**
61 * Plain text (even tags are printed in full)
62 */
b0ccd3fb 63define('FORMAT_PLAIN', '2'); // Plain text (even tags are printed in full)
7cf1c7bd 64
65/**
66 * Wiki-formatted text
6a6495ff 67 * Deprecated: left here just to note that '3' is not used (at the moment)
68 * and to catch any latent wiki-like text (which generates an error)
7cf1c7bd 69 */
b0ccd3fb 70define('FORMAT_WIKI', '3'); // Wiki-formatted text
7cf1c7bd 71
72/**
73 * Markdown-formatted text http://daringfireball.net/projects/markdown/
74 */
b0ccd3fb 75define('FORMAT_MARKDOWN', '4'); // Markdown-formatted text http://daringfireball.net/projects/markdown/
0095d5cd 76
7d8a3cb0 77/**
78 * TRUSTTEXT marker - if present in text, text cleaning should be bypassed
79 */
80define('TRUSTTEXT', '#####TRUSTTEXT#####');
81
7cf1c7bd 82
83/**
84 * Allowed tags - string of html tags that can be tested against for safe html tags
85 * @global string $ALLOWED_TAGS
86 */
5ea4af22 87global $ALLOWED_TAGS;
39dda0fc 88$ALLOWED_TAGS =
d046ae55 89'<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>';
90
037dcbb6 91/**
92 * Allowed protocols - array of protocols that are safe to use in links and so on
93 * @global string $ALLOWED_PROTOCOLS
94 */
f941df22 95$ALLOWED_PROTOCOLS = array('http', 'https', 'ftp', 'news', 'mailto', 'rtsp', 'teamspeak', 'gopher', 'mms',
c06c8492 96 'color', 'callto', 'cursor', 'text-align', 'font-size', 'font-weight', 'font-style',
016ffbd7 97 'border', 'margin', 'padding', 'background'); // CSS as well to get through kses
037dcbb6 98
99
0095d5cd 100/// Functions
101
7cf1c7bd 102/**
103 * Add quotes to HTML characters
104 *
105 * Returns $var with HTML characters (like "<", ">", etc.) properly quoted.
106 * This function is very similar to {@link p()}
107 *
108 * @param string $var the string potentially containing HTML characters
d4a42ff4 109 * @param boolean $strip to decide if we want to strip slashes or no. Default to false.
110 * true should be used to print data from forms and false for data from DB.
7cf1c7bd 111 * @return string
112 */
473d29eb 113function s($var, $strip=false) {
d4a42ff4 114
63e554d0 115 if ($var == '0') { // for integer 0, boolean false, string '0'
116 return '0';
3662bce5 117 }
d4a42ff4 118
119 if ($strip) {
473d29eb 120 return preg_replace("/&amp;(#\d+);/i", "&$1;", htmlspecialchars(stripslashes_safe($var)));
121 } else {
122 return preg_replace("/&amp;(#\d+);/i", "&$1;", htmlspecialchars($var));
d4a42ff4 123 }
f9903ed0 124}
125
7cf1c7bd 126/**
127 * Add quotes to HTML characters
128 *
d48b00b4 129 * Prints $var with HTML characters (like "<", ">", etc.) properly quoted.
7cf1c7bd 130 * This function is very similar to {@link s()}
131 *
132 * @param string $var the string potentially containing HTML characters
d4a42ff4 133 * @param boolean $strip to decide if we want to strip slashes or no. Default to false.
134 * true should be used to print data from forms and false for data from DB.
7cf1c7bd 135 * @return string
136 */
d4a42ff4 137function p($var, $strip=false) {
138 echo s($var, $strip);
f9903ed0 139}
140
0d1cd0ea 141/**
142 * Does proper javascript quoting.
5ce73257 143 * Do not use addslashes anymore, because it does not work when magic_quotes_sybase is enabled.
144 *
e2cd3ed0 145 * @since 1.8 - 22/02/2007
0d1cd0ea 146 * @param mixed value
147 * @return mixed quoted result
148 */
149function addslashes_js($var) {
150 if (is_string($var)) {
151 $var = str_replace('\\', '\\\\', $var);
152 $var = str_replace(array('\'', '"', "\n", "\r", "\0"), array('\\\'', '\\"', '\\n', '\\r', '\\0'), $var);
4702be4e 153 $var = str_replace('</', '<\/', $var); // XHTML compliance
0d1cd0ea 154 } else if (is_array($var)) {
155 $var = array_map('addslashes_js', $var);
156 } else if (is_object($var)) {
157 $a = get_object_vars($var);
158 foreach ($a as $key=>$value) {
159 $a[$key] = addslashes_js($value);
160 }
161 $var = (object)$a;
162 }
163 return $var;
164}
7cf1c7bd 165
7cf1c7bd 166/**
167 * Remove query string from url
168 *
169 * Takes in a URL and returns it without the querystring portion
170 *
171 * @param string $url the url which may have a query string attached
172 * @return string
173 */
174 function strip_querystring($url) {
f9903ed0 175
b9b8ab69 176 if ($commapos = strpos($url, '?')) {
177 return substr($url, 0, $commapos);
178 } else {
179 return $url;
180 }
f9903ed0 181}
182
7cf1c7bd 183/**
c8135a35 184 * Returns the URL of the HTTP_REFERER, less the querystring portion if required
7cf1c7bd 185 * @return string
186 */
c8135a35 187function get_referer($stripquery=true) {
d90ffc1f 188 if (isset($_SERVER['HTTP_REFERER'])) {
c8135a35 189 if ($stripquery) {
190 return strip_querystring($_SERVER['HTTP_REFERER']);
191 } else {
192 return $_SERVER['HTTP_REFERER'];
193 }
d90ffc1f 194 } else {
5ce73257 195 return '';
d90ffc1f 196 }
f9903ed0 197}
198
c1d57101 199
7cf1c7bd 200/**
201 * Returns the name of the current script, WITH the querystring portion.
202 * this function is necessary because PHP_SELF and REQUEST_URI and SCRIPT_NAME
203 * return different things depending on a lot of things like your OS, Web
204 * server, and the way PHP is compiled (ie. as a CGI, module, ISAPI, etc.)
d48b00b4 205 * <b>NOTE:</b> This function returns false if the global variables needed are not set.
206 *
7cf1c7bd 207 * @return string
208 */
209 function me() {
f9903ed0 210
b0ccd3fb 211 if (!empty($_SERVER['REQUEST_URI'])) {
212 return $_SERVER['REQUEST_URI'];
c1d57101 213
b0ccd3fb 214 } else if (!empty($_SERVER['PHP_SELF'])) {
215 if (!empty($_SERVER['QUERY_STRING'])) {
216 return $_SERVER['PHP_SELF'] .'?'. $_SERVER['QUERY_STRING'];
fced815c 217 }
b0ccd3fb 218 return $_SERVER['PHP_SELF'];
c1d57101 219
b0ccd3fb 220 } else if (!empty($_SERVER['SCRIPT_NAME'])) {
221 if (!empty($_SERVER['QUERY_STRING'])) {
222 return $_SERVER['SCRIPT_NAME'] .'?'. $_SERVER['QUERY_STRING'];
fced815c 223 }
b0ccd3fb 224 return $_SERVER['SCRIPT_NAME'];
fced815c 225
b0ccd3fb 226 } else if (!empty($_SERVER['URL'])) { // May help IIS (not well tested)
227 if (!empty($_SERVER['QUERY_STRING'])) {
228 return $_SERVER['URL'] .'?'. $_SERVER['QUERY_STRING'];
16c4d82a 229 }
b0ccd3fb 230 return $_SERVER['URL'];
16c4d82a 231
b9b8ab69 232 } else {
b0ccd3fb 233 notify('Warning: Could not find any of these web server variables: $REQUEST_URI, $PHP_SELF, $SCRIPT_NAME or $URL');
bcdfe14e 234 return false;
7fbd6b1c 235 }
f9903ed0 236}
237
7cf1c7bd 238/**
d48b00b4 239 * Like {@link me()} but returns a full URL
7cf1c7bd 240 * @see me()
7cf1c7bd 241 * @return string
242 */
f9903ed0 243function qualified_me() {
f9903ed0 244
b6e22603 245 global $CFG;
246
68796e6b 247 if (!empty($CFG->wwwroot)) {
248 $url = parse_url($CFG->wwwroot);
249 }
b6e22603 250
251 if (!empty($url['host'])) {
252 $hostname = $url['host'];
253 } else if (!empty($_SERVER['SERVER_NAME'])) {
b0ccd3fb 254 $hostname = $_SERVER['SERVER_NAME'];
255 } else if (!empty($_ENV['SERVER_NAME'])) {
256 $hostname = $_ENV['SERVER_NAME'];
257 } else if (!empty($_SERVER['HTTP_HOST'])) {
258 $hostname = $_SERVER['HTTP_HOST'];
259 } else if (!empty($_ENV['HTTP_HOST'])) {
260 $hostname = $_ENV['HTTP_HOST'];
39e018b3 261 } else {
b0ccd3fb 262 notify('Warning: could not find the name of this server!');
bcdfe14e 263 return false;
c1d57101 264 }
dc28eede 265
266 if (!empty($url['port'])) {
267 $hostname .= ':'.$url['port'];
268 } else if (!empty($_SERVER['SERVER_PORT'])) {
269 if ($_SERVER['SERVER_PORT'] != 80 && $_SERVER['SERVER_PORT'] != 443) {
270 $hostname .= ':'.$_SERVER['SERVER_PORT'];
271 }
272 }
273
93b2ed94 274 // TODO, this does not work in the situation described in MDL-11061, but
275 // I don't know how to fix it. Possibly believe $CFG->wwwroot ahead of what
276 // the server reports.
f77c261e 277 if (isset($_SERVER['HTTPS'])) {
278 $protocol = ($_SERVER['HTTPS'] == 'on') ? 'https://' : 'http://';
279 } else if (isset($_SERVER['SERVER_PORT'])) { # Apache2 does not export $_SERVER['HTTPS']
280 $protocol = ($_SERVER['SERVER_PORT'] == '443') ? 'https://' : 'http://';
281 } else {
282 $protocol = 'http://';
283 }
f9903ed0 284
39e018b3 285 $url_prefix = $protocol.$hostname;
b9b8ab69 286 return $url_prefix . me();
f9903ed0 287}
288
360e503e 289
290/**
291 * Class for creating and manipulating urls.
84e3d2cc 292 *
fae60ee3 293 * See short write up here http://docs.moodle.org/en/Development:lib/weblib.php_moodle_url
360e503e 294 */
295class moodle_url {
84e3d2cc 296 var $scheme = '';// e.g. http
297 var $host = '';
360e503e 298 var $port = '';
299 var $user = '';
84e3d2cc 300 var $pass = '';
360e503e 301 var $path = '';
302 var $fragment = '';
303 var $params = array(); //associative array of query string params
84e3d2cc 304
360e503e 305 /**
306 * Pass no arguments to create a url that refers to this page. Use empty string to create empty url.
84e3d2cc 307 *
e744ebba 308 * @param string $url url default null means use this page url with no query string
309 * empty string means empty url.
310 * if you pass any other type of url it will be parsed into it's bits, including query string
311 * @param array $params these params override anything in the query string where params have the same name.
360e503e 312 */
e744ebba 313 function moodle_url($url = null, $params = array()){
360e503e 314 global $FULLME;
315 if ($url !== ''){
316 if ($url === null){
317 $url = strip_querystring($FULLME);
318 }
319 $parts = parse_url($url);
320 if ($parts === FALSE){
321 error('invalidurl');
322 }
323 if (isset($parts['query'])){
24a905f9 324 parse_str(str_replace('&amp;', '&', $parts['query']), $this->params);
360e503e 325 }
326 unset($parts['query']);
327 foreach ($parts as $key => $value){
328 $this->$key = $value;
329 }
84e3d2cc 330 $this->params($params);
360e503e 331 }
84e3d2cc 332 }
360e503e 333 /**
84e3d2cc 334 * Add an array of params to the params for this page. The added params override existing ones if they
360e503e 335 * have the same name.
336 *
337 * @param array $params
338 */
339 function params($params){
340 $this->params = $params + $this->params;
341 }
84e3d2cc 342
360e503e 343 /**
84e3d2cc 344 * Remove all params if no arguments passed. Or else remove param $arg1, $arg2, etc.
360e503e 345 *
346 * @param string $arg1
347 * @param string $arg2
348 * @param string $arg3
349 */
350 function remove_params(){
351 if ($thisargs = func_get_args()){
352 foreach ($thisargs as $arg){
353 if (isset($this->params->$arg)){
354 unset($this->params->$arg);
355 }
356 }
357 } else { // no args
358 $this->params = array();
359 }
360 }
361
362 /**
84e3d2cc 363 * Add a param to the params for this page. The added param overrides existing one if they
360e503e 364 * have the same name.
365 *
366 * @param string $paramname name
367 * @param string $param value
368 */
369 function param($paramname, $param){
370 $this->params = array($paramname => $param) + $this->params;
371 }
372
84e3d2cc 373
dc1f7683 374 function get_query_string($overrideparams = array()){
360e503e 375 $arr = array();
376 $params = $overrideparams + $this->params;
377 foreach ($params as $key => $val){
378 $arr[] = urlencode($key)."=".urlencode($val);
379 }
dc1f7683 380 return implode($arr, "&amp;");
360e503e 381 }
382 /**
383 * Outputs params as hidden form elements.
fcdb06c4 384 *
fae60ee3 385 * @param array $exclude params to ignore
386 * @param integer $indent indentation
360e503e 387 * @return string html for form elements.
388 */
fcdb06c4 389 function hidden_params_out($exclude = array(), $indent = 0){
360e503e 390 $tabindent = str_repeat("\t", $indent);
391 $str = '';
392 foreach ($this->params as $key => $val){
fcdb06c4 393 if (FALSE === array_search($key, $exclude)) {
83bc64db 394 $val = s($val);
fcdb06c4 395 $str.= "$tabindent<input type=\"hidden\" name=\"$key\" value=\"$val\" />\n";
396 }
360e503e 397 }
398 return $str;
399 }
400 /**
401 * Output url
84e3d2cc 402 *
360e503e 403 * @param boolean $noquerystring whether to output page params as a query string in the url.
404 * @param array $overrideparams params to add to the output url, these override existing ones with the same name.
405 * @return string url
406 */
84e3d2cc 407 function out($noquerystring = false, $overrideparams = array()) {
360e503e 408 $uri = $this->scheme ? $this->scheme.':'.((strtolower($this->scheme) == 'mailto') ? '':'//'): '';
409 $uri .= $this->user ? $this->user.($this->pass? ':'.$this->pass:'').'@':'';
410 $uri .= $this->host ? $this->host : '';
411 $uri .= $this->port ? ':'.$this->port : '';
412 $uri .= $this->path ? $this->path : '';
413 if (!$noquerystring){
dc1f7683 414 $uri .= (count($this->params)||count($overrideparams)) ? '?'.$this->get_query_string($overrideparams) : '';
360e503e 415 }
416 $uri .= $this->fragment ? '#'.$this->fragment : '';
84e3d2cc 417 return $uri;
360e503e 418 }
419 /**
420 * Output action url with sesskey
84e3d2cc 421 *
360e503e 422 * @param boolean $noquerystring whether to output page params as a query string in the url.
423 * @return string url
424 */
84e3d2cc 425 function out_action($overrideparams = array()) {
360e503e 426 $overrideparams = array('sesskey'=> sesskey()) + $overrideparams;
dc1f7683 427 return $this->out(false, $overrideparams);
360e503e 428 }
429}
430
7cf1c7bd 431/**
432 * Determine if there is data waiting to be processed from a form
433 *
434 * Used on most forms in Moodle to check for data
435 * Returns the data as an object, if it's found.
436 * This object can be used in foreach loops without
437 * casting because it's cast to (array) automatically
772e78be 438 *
9c0f063b 439 * Checks that submitted POST data exists and returns it as object.
d48b00b4 440 *
9c0f063b 441 * @param string $url not used anymore
442 * @return mixed false or object
7cf1c7bd 443 */
b0ccd3fb 444function data_submitted($url='') {
d48b00b4 445
607809b3 446 if (empty($_POST)) {
36b4f985 447 return false;
448 } else {
9c0f063b 449 return (object)$_POST;
36b4f985 450 }
451}
452
7cf1c7bd 453/**
e8d1c9ed 454 * Moodle replacement for php stripslashes() function,
455 * works also for objects and arrays.
7cf1c7bd 456 *
772e78be 457 * The standard php stripslashes() removes ALL backslashes
7cf1c7bd 458 * even from strings - so C:\temp becomes C:temp - this isn't good.
459 * This function should work as a fairly safe replacement
460 * to be called on quoted AND unquoted strings (to be sure)
d48b00b4 461 *
e8d1c9ed 462 * @param mixed something to remove unsafe slashes from
463 * @return mixed
7cf1c7bd 464 */
e8d1c9ed 465function stripslashes_safe($mixed) {
466 // there is no need to remove slashes from int, float and bool types
467 if (empty($mixed)) {
468 //nothing to do...
469 } else if (is_string($mixed)) {
de64b6c6 470 if (ini_get_bool('magic_quotes_sybase')) { //only unescape single quotes
471 $mixed = str_replace("''", "'", $mixed);
472 } else { //the rest, simple and double quotes and backslashes
473 $mixed = str_replace("\\'", "'", $mixed);
474 $mixed = str_replace('\\"', '"', $mixed);
475 $mixed = str_replace('\\\\', '\\', $mixed);
476 }
e8d1c9ed 477 } else if (is_array($mixed)) {
478 foreach ($mixed as $key => $value) {
479 $mixed[$key] = stripslashes_safe($value);
480 }
481 } else if (is_object($mixed)) {
482 $vars = get_object_vars($mixed);
483 foreach ($vars as $key => $value) {
484 $mixed->$key = stripslashes_safe($value);
485 }
486 }
7d8f674d 487
e8d1c9ed 488 return $mixed;
7d8f674d 489}
f9903ed0 490
9b4b78fd 491/**
492 * Recursive implementation of stripslashes()
493 *
494 * This function will allow you to strip the slashes from a variable.
495 * If the variable is an array or object, slashes will be stripped
496 * from the items (or properties) it contains, even if they are arrays
497 * or objects themselves.
498 *
499 * @param mixed the variable to remove slashes from
500 * @return mixed
501 */
502function stripslashes_recursive($var) {
271c7a98 503 if (is_object($var)) {
504 $new_var = new object();
9b4b78fd 505 $properties = get_object_vars($var);
506 foreach($properties as $property => $value) {
271c7a98 507 $new_var->$property = stripslashes_recursive($value);
9b4b78fd 508 }
271c7a98 509
510 } else if(is_array($var)) {
511 $new_var = array();
9b4b78fd 512 foreach($var as $property => $value) {
271c7a98 513 $new_var[$property] = stripslashes_recursive($value);
9b4b78fd 514 }
271c7a98 515
516 } else if(is_string($var)) {
517 $new_var = stripslashes($var);
518
519 } else {
520 $new_var = $var;
9b4b78fd 521 }
271c7a98 522
523 return $new_var;
04480de3 524}
525
526/**
527 * Recursive implementation of addslashes()
528 *
529 * This function will allow you to add the slashes from a variable.
530 * If the variable is an array or object, slashes will be added
531 * to the items (or properties) it contains, even if they are arrays
532 * or objects themselves.
533 *
534 * @param mixed the variable to add slashes from
535 * @return mixed
536 */
537function addslashes_recursive($var) {
271c7a98 538 if (is_object($var)) {
539 $new_var = new object();
04480de3 540 $properties = get_object_vars($var);
541 foreach($properties as $property => $value) {
271c7a98 542 $new_var->$property = addslashes_recursive($value);
04480de3 543 }
271c7a98 544
545 } else if (is_array($var)) {
546 $new_var = array();
04480de3 547 foreach($var as $property => $value) {
271c7a98 548 $new_var[$property] = addslashes_recursive($value);
04480de3 549 }
271c7a98 550
551 } else if (is_string($var)) {
552 $new_var = addslashes($var);
553
f8e6e4db 554 } else { // nulls, integers, etc.
271c7a98 555 $new_var = $var;
04480de3 556 }
271c7a98 557
558 return $new_var;
9b4b78fd 559}
560
7cf1c7bd 561/**
d48b00b4 562 * Given some normal text this function will break up any
563 * long words to a given size by inserting the given character
564 *
6aaa17c7 565 * It's multibyte savvy and doesn't change anything inside html tags.
566 *
7cf1c7bd 567 * @param string $string the string to be modified
89dcb99d 568 * @param int $maxsize maximum length of the string to be returned
7cf1c7bd 569 * @param string $cutchar the string used to represent word breaks
570 * @return string
571 */
4a5644e5 572function break_up_long_words($string, $maxsize=20, $cutchar=' ') {
a2b3f884 573
6aaa17c7 574/// Loading the textlib singleton instance. We are going to need it.
575 $textlib = textlib_get_instance();
8f7dc7f1 576
6aaa17c7 577/// First of all, save all the tags inside the text to skip them
578 $tags = array();
579 filter_save_tags($string,$tags);
5b07d990 580
6aaa17c7 581/// Process the string adding the cut when necessary
4a5644e5 582 $output = '';
810944af 583 $length = $textlib->strlen($string);
4a5644e5 584 $wordlength = 0;
585
586 for ($i=0; $i<$length; $i++) {
810944af 587 $char = $textlib->substr($string, $i, 1);
6aaa17c7 588 if ($char == ' ' or $char == "\t" or $char == "\n" or $char == "\r" or $char == "<" or $char == ">") {
4a5644e5 589 $wordlength = 0;
590 } else {
591 $wordlength++;
592 if ($wordlength > $maxsize) {
593 $output .= $cutchar;
594 $wordlength = 0;
595 }
596 }
597 $output .= $char;
598 }
6aaa17c7 599
600/// Finally load the tags back again
601 if (!empty($tags)) {
602 $output = str_replace(array_keys($tags), $tags, $output);
603 }
604
4a5644e5 605 return $output;
606}
607
7cf1c7bd 608/**
609 * This does a search and replace, ignoring case
610 * This function is only used for versions of PHP older than version 5
611 * which do not have a native version of this function.
612 * Taken from the PHP manual, by bradhuizenga @ softhome.net
d48b00b4 613 *
7cf1c7bd 614 * @param string $find the string to search for
615 * @param string $replace the string to replace $find with
616 * @param string $string the string to search through
617 * return string
618 */
ce57cc79 619if (!function_exists('str_ireplace')) { /// Only exists in PHP 5
7ec2fc00 620 function str_ireplace($find, $replace, $string) {
7ec2fc00 621
622 if (!is_array($find)) {
623 $find = array($find);
624 }
625
626 if(!is_array($replace)) {
627 if (!is_array($find)) {
628 $replace = array($replace);
629 } else {
630 // this will duplicate the string into an array the size of $find
631 $c = count($find);
632 $rString = $replace;
633 unset($replace);
634 for ($i = 0; $i < $c; $i++) {
635 $replace[$i] = $rString;
636 }
637 }
638 }
639
640 foreach ($find as $fKey => $fItem) {
641 $between = explode(strtolower($fItem),strtolower($string));
642 $pos = 0;
643 foreach($between as $bKey => $bItem) {
644 $between[$bKey] = substr($string,$pos,strlen($bItem));
645 $pos += strlen($bItem) + strlen($fItem);
646 }
647 $string = implode($replace[$fKey],$between);
72e4eac6 648 }
7ec2fc00 649 return ($string);
3fe3851d 650 }
3fe3851d 651}
652
7cf1c7bd 653/**
654 * Locate the position of a string in another string
655 *
656 * This function is only used for versions of PHP older than version 5
657 * which do not have a native version of this function.
658 * Taken from the PHP manual, by dmarsh @ spscc.ctc.edu
d48b00b4 659 *
7cf1c7bd 660 * @param string $haystack The string to be searched
661 * @param string $needle The string to search for
89dcb99d 662 * @param int $offset The position in $haystack where the search should begin.
7cf1c7bd 663 */
ce57cc79 664if (!function_exists('stripos')) { /// Only exists in PHP 5
665 function stripos($haystack, $needle, $offset=0) {
d48b00b4 666
ce57cc79 667 return strpos(strtoupper($haystack), strtoupper($needle), $offset);
668 }
669}
670
7cf1c7bd 671/**
672 * This function will create a HTML link that will work on both
673 * Javascript and non-javascript browsers.
674 * Relies on the Javascript function openpopup in javascript.php
d48b00b4 675 *
7cf1c7bd 676 * $url must be relative to home page eg /mod/survey/stuff.php
677 * @param string $url Web link relative to home page
678 * @param string $name Name to be assigned to the popup window
679 * @param string $linkname Text to be displayed as web link
89dcb99d 680 * @param int $height Height to assign to popup window
681 * @param int $width Height to assign to popup window
7cf1c7bd 682 * @param string $title Text to be displayed as popup page title
683 * @param string $options List of additional options for popup window
684 * @todo Add code examples and list of some options that might be used.
685 * @param boolean $return Should the link to the popup window be returned as a string (true) or printed immediately (false)?
686 * @return string
687 * @uses $CFG
688 */
b0ccd3fb 689function link_to_popup_window ($url, $name='popup', $linkname='click here',
da4124be 690 $height=400, $width=500, $title='Popup window',
691 $options='none', $return=false) {
f9903ed0 692
ff80e012 693 global $CFG;
694
b0ccd3fb 695 if ($options == 'none') {
696 $options = 'menubar=0,location=0,scrollbars,resizable,width='. $width .',height='. $height;
b48f834c 697 }
86aa7ccf 698 $fullscreen = 0;
f9903ed0 699
c80b7585 700 if (!(strpos($url,$CFG->wwwroot) === false)) { // some log url entries contain _SERVER[HTTP_REFERRER] in which case wwwroot is already there.
d2fa35a8 701 $url = substr($url, strlen($CFG->wwwroot));
c80b7585 702 }
703
886c109d 704 $link = '<a title="'. s(strip_tags($title)) .'" href="'. $CFG->wwwroot . $url .'" '.
593bc22b 705 "onclick=\"this.target='$name'; return openpopup('$url', '$name', '$options', $fullscreen);\">$linkname</a>";
1f2eec7b 706 if ($return) {
707 return $link;
708 } else {
709 echo $link;
710 }
f9903ed0 711}
712
7cf1c7bd 713/**
714 * This function will print a button submit form element
715 * that will work on both Javascript and non-javascript browsers.
716 * Relies on the Javascript function openpopup in javascript.php
d48b00b4 717 *
7cf1c7bd 718 * $url must be relative to home page eg /mod/survey/stuff.php
719 * @param string $url Web link relative to home page
720 * @param string $name Name to be assigned to the popup window
721 * @param string $linkname Text to be displayed as web link
89dcb99d 722 * @param int $height Height to assign to popup window
723 * @param int $width Height to assign to popup window
7cf1c7bd 724 * @param string $title Text to be displayed as popup page title
725 * @param string $options List of additional options for popup window
dc28eede 726 * @param string $return If true, return as a string, otherwise print
7cf1c7bd 727 * @return string
728 * @uses $CFG
729 */
b0ccd3fb 730function button_to_popup_window ($url, $name='popup', $linkname='click here',
572fe9ab 731 $height=400, $width=500, $title='Popup window', $options='none', $return=false,
0f7d4e5e 732 $id='', $class='') {
52f1b496 733
734 global $CFG;
735
b0ccd3fb 736 if ($options == 'none') {
737 $options = 'menubar=0,location=0,scrollbars,resizable,width='. $width .',height='. $height;
52f1b496 738 }
0f7d4e5e 739
740 if ($id) {
741 $id = ' id="'.$id.'" ';
742 }
743 if ($class) {
744 $class = ' class="'.$class.'" ';
745 }
52f1b496 746 $fullscreen = 0;
747
0f7d4e5e 748 $button = '<input type="button" name="'.$name.'" title="'. $title .'" value="'. $linkname .' ..." '.$id.$class.
dc28eede 749 "onclick=\"return openpopup('$url', '$name', '$options', $fullscreen);\" />\n";
750 if ($return) {
751 return $button;
752 } else {
753 echo $button;
754 }
52f1b496 755}
756
757
7cf1c7bd 758/**
759 * Prints a simple button to close a window
760 */
eaeaf964 761function close_window_button($name='closewindow', $return=false) {
38d5ab86 762 global $CFG;
763
eaeaf964 764 $output = '';
765
4079b3d7 766 $output .= '<div class="closewindow">' . "\n";
38d5ab86 767 $output .= '<form action="'.$CFG->wwwroot.'"><div>'; // We don't use this
768 $output .= '<input type="button" onclick="self.close();" value="'.get_string($name).'" />';
769 $output .= '</div></form>';
4079b3d7 770 $output .= '</div>' . "\n";
eaeaf964 771
772 if ($return) {
773 return $output;
774 } else {
775 echo $output;
776 }
f9903ed0 777}
778
08396bb2 779/*
780 * Try and close the current window immediately using Javascript
781 */
782function close_window($delay=0) {
dfa924cc 783?>
784<script type="text/javascript">
4079b3d7 785//<![CDATA[
dfa924cc 786 function close_this_window() {
787 self.close();
788 }
789 setTimeout("close_this_window()", <?php echo $delay * 1000 ?>);
4079b3d7 790//]]>
dfa924cc 791</script>
792<noscript><center>
793<?php print_string('pleaseclose') ?>
794</center></noscript>
795<?php
796 die;
08396bb2 797}
798
799
d48b00b4 800/**
75afe0e7 801 * Given an array of values, output the HTML for a select element with those options.
802 * Normally, you only need to use the first few parameters.
d48b00b4 803 *
75afe0e7 804 * @param array $options The options to offer. An array of the form
805 * $options[{value}] = {text displayed for that option};
806 * @param string $name the name of this form control, as in &lt;select name="..." ...
807 * @param string $selected the option to select initially, default none.
808 * @param string $nothing The label for the 'nothing is selected' option. Defaults to get_string('choose').
809 * Set this to '' if you don't want a 'nothing is selected' option.
810 * @param string $script in not '', then this is added to the &lt;select> element as an onchange handler.
811 * @param string $nothingvalue The value corresponding to the $nothing option. Defaults to 0.
812 * @param boolean $return if false (the default) the the output is printed directly, If true, the
813 * generated HTML is returned as a string.
814 * @param boolean $disabled if true, the select is generated in a disabled state. Default, false.
815 * @param int $tabindex if give, sets the tabindex attribute on the &lt;select> element. Default none.
816 * @param string $id value to use for the id attribute of the &lt;select> element. If none is given,
817 * then a suitable one is constructed.
d48b00b4 818 */
c06c8492 819function choose_from_menu ($options, $name, $selected='', $nothing='choose', $script='',
7850588a 820 $nothingvalue='0', $return=false, $disabled=false, $tabindex=0, $id='') {
ab9f24ad 821
b0ccd3fb 822 if ($nothing == 'choose') {
823 $nothing = get_string('choose') .'...';
618b22c5 824 }
825
48e535bc 826 $attributes = ($script) ? 'onchange="'. $script .'"' : '';
827 if ($disabled) {
828 $attributes .= ' disabled="disabled"';
f9903ed0 829 }
9c9f7d77 830
25e5dbf9 831 if ($tabindex) {
832 $attributes .= ' tabindex="'.$tabindex.'"';
833 }
834
7850588a 835 if ($id ==='') {
a1c91f9a 836 $id = 'menu'.$name;
837 // name may contaion [], which would make an invalid id. e.g. numeric question type editing form, assignment quickgrading
838 $id = str_replace('[', '', $id);
839 $id = str_replace(']', '', $id);
7850588a 840 }
841
842 $output = '<select id="'.$id.'" name="'. $name .'" '. $attributes .'>' . "\n";
bda8d43a 843 if ($nothing) {
7850588a 844 $output .= ' <option value="'. s($nothingvalue) .'"'. "\n";
cec0a0fc 845 if ($nothingvalue === $selected) {
b0ccd3fb 846 $output .= ' selected="selected"';
bda8d43a 847 }
b0ccd3fb 848 $output .= '>'. $nothing .'</option>' . "\n";
873960de 849 }
607809b3 850 if (!empty($options)) {
851 foreach ($options as $value => $label) {
7850588a 852 $output .= ' <option value="'. s($value) .'"';
bd905b45 853 if ((string)$value == (string)$selected) {
b0ccd3fb 854 $output .= ' selected="selected"';
607809b3 855 }
b0ccd3fb 856 if ($label === '') {
857 $output .= '>'. $value .'</option>' . "\n";
a20c1090 858 } else {
b0ccd3fb 859 $output .= '>'. $label .'</option>' . "\n";
607809b3 860 }
f9903ed0 861 }
862 }
b0ccd3fb 863 $output .= '</select>' . "\n";
08056730 864
865 if ($return) {
866 return $output;
867 } else {
868 echo $output;
869 }
ab9f24ad 870}
f9903ed0 871
73d4db84 872/**
873 * Choose value 0 or 1 from a menu with options 'No' and 'Yes'.
874 * Other options like choose_from_menu.
875 */
876function choose_from_menu_yesno($name, $selected, $script = '',
877 $return = false, $disabled = false, $tabindex = 0) {
878 return choose_from_menu(array(get_string('no'), get_string('yes')), $name,
879 $selected, '', $script, '0', $return, $disabled, $tabindex);
880}
881
14040797 882/**
883 * Just like choose_from_menu, but takes a nested array (2 levels) and makes a dropdown menu
884 * including option headings with the first level.
885 */
886function choose_from_menu_nested($options,$name,$selected='',$nothing='choose',$script = '',
887 $nothingvalue=0,$return=false,$disabled=false,$tabindex=0) {
888
889 if ($nothing == 'choose') {
890 $nothing = get_string('choose') .'...';
891 }
892
893 $attributes = ($script) ? 'onchange="'. $script .'"' : '';
894 if ($disabled) {
895 $attributes .= ' disabled="disabled"';
896 }
897
898 if ($tabindex) {
899 $attributes .= ' tabindex="'.$tabindex.'"';
900 }
901
902 $output = '<select id="menu'.$name.'" name="'. $name .'" '. $attributes .'>' . "\n";
903 if ($nothing) {
904 $output .= ' <option value="'. $nothingvalue .'"'. "\n";
905 if ($nothingvalue === $selected) {
906 $output .= ' selected="selected"';
907 }
908 $output .= '>'. $nothing .'</option>' . "\n";
909 }
910 if (!empty($options)) {
911 foreach ($options as $section => $values) {
84e3d2cc 912
dacb47c0 913 $output .= ' <optgroup label="'. s(format_string($section)) .'">'."\n";
14040797 914 foreach ($values as $value => $label) {
dacb47c0 915 $output .= ' <option value="'. format_string($value) .'"';
f332bd02 916 if ((string)$value == (string)$selected) {
14040797 917 $output .= ' selected="selected"';
918 }
919 if ($label === '') {
920 $output .= '>'. $value .'</option>' . "\n";
921 } else {
922 $output .= '>'. $label .'</option>' . "\n";
923 }
924 }
925 $output .= ' </optgroup>'."\n";
926 }
927 }
928 $output .= '</select>' . "\n";
929
930 if ($return) {
931 return $output;
932 } else {
933 echo $output;
934 }
935}
936
937
531a3cb2 938/**
939 * Given an array of values, creates a group of radio buttons to be part of a form
c06c8492 940 *
531a3cb2 941 * @param array $options An array of value-label pairs for the radio group (values as keys)
942 * @param string $name Name of the radiogroup (unique in the form)
943 * @param string $checked The value that is already checked
944 */
eaeaf964 945function choose_from_radio ($options, $name, $checked='', $return=false) {
531a3cb2 946
20cbef63 947 static $idcounter = 0;
948
531a3cb2 949 if (!$name) {
950 $name = 'unnamed';
951 }
952
953 $output = '<span class="radiogroup '.$name."\">\n";
954
955 if (!empty($options)) {
956 $currentradio = 0;
957 foreach ($options as $value => $label) {
20cbef63 958 $htmlid = 'auto-rb'.sprintf('%04d', ++$idcounter);
959 $output .= ' <span class="radioelement '.$name.' rb'.$currentradio."\">";
960 $output .= '<input name="'.$name.'" id="'.$htmlid.'" type="radio" value="'.$value.'"';
531a3cb2 961 if ($value == $checked) {
962 $output .= ' checked="checked"';
963 }
964 if ($label === '') {
20cbef63 965 $output .= ' /> <label for="'.$htmlid.'">'. $value .'</label></span>' . "\n";
531a3cb2 966 } else {
20cbef63 967 $output .= ' /> <label for="'.$htmlid.'">'. $label .'</label></span>' . "\n";
531a3cb2 968 }
969 $currentradio = ($currentradio + 1) % 2;
970 }
971 }
972
973 $output .= '</span>' . "\n";
974
eaeaf964 975 if ($return) {
976 return $output;
977 } else {
978 echo $output;
979 }
531a3cb2 980}
981
2481037f 982/** Display an standard html checkbox with an optional label
983 *
984 * @param string $name The name of the checkbox
985 * @param string $value The valus that the checkbox will pass when checked
986 * @param boolean $checked The flag to tell the checkbox initial state
987 * @param string $label The label to be showed near the checkbox
988 * @param string $alt The info to be inserted in the alt tag
989 */
d0d272e7 990function print_checkbox ($name, $value, $checked = true, $label = '', $alt = '', $script='',$return=false) {
2481037f 991
20cbef63 992 static $idcounter = 0;
993
2481037f 994 if (!$name) {
995 $name = 'unnamed';
996 }
997
27f79fda 998 if ($alt) {
999 $alt = strip_tags($alt);
1000 } else {
2481037f 1001 $alt = 'checkbox';
1002 }
1003
1004 if ($checked) {
1005 $strchecked = ' checked="checked"';
f89f924e 1006 } else {
1007 $strchecked = '';
2481037f 1008 }
1009
20cbef63 1010 $htmlid = 'auto-cb'.sprintf('%04d', ++$idcounter);
2481037f 1011 $output = '<span class="checkbox '.$name."\">";
fbe31d22 1012 $output .= '<input name="'.$name.'" id="'.$htmlid.'" type="checkbox" value="'.$value.'" alt="'.$alt.'"'.$strchecked.' '.((!empty($script)) ? ' onclick="'.$script.'" ' : '').' />';
20cbef63 1013 if(!empty($label)) {
1014 $output .= ' <label for="'.$htmlid.'">'.$label.'</label>';
1015 }
2481037f 1016 $output .= '</span>'."\n";
1017
d0d272e7 1018 if (empty($return)) {
1019 echo $output;
1020 } else {
1021 return $output;
1022 }
2481037f 1023
1024}
1025
d0d272e7 1026/** Display an standard html text field with an optional label
1027 *
1028 * @param string $name The name of the text field
1029 * @param string $value The value of the text field
1030 * @param string $label The label to be showed near the text field
1031 * @param string $alt The info to be inserted in the alt tag
1032 */
eaeaf964 1033function print_textfield ($name, $value, $alt = '',$size=50,$maxlength=0, $return=false) {
d0d272e7 1034
1035 static $idcounter = 0;
1036
1037 if (empty($name)) {
1038 $name = 'unnamed';
1039 }
1040
1041 if (empty($alt)) {
1042 $alt = 'textfield';
1043 }
1044
1045 if (!empty($maxlength)) {
1046 $maxlength = ' maxlength="'.$maxlength.'" ';
1047 }
1048
ce432524 1049 $htmlid = 'auto-tf'.sprintf('%04d', ++$idcounter);
d0d272e7 1050 $output = '<span class="textfield '.$name."\">";
1051 $output .= '<input name="'.$name.'" id="'.$htmlid.'" type="text" value="'.$value.'" size="'.$size.'" '.$maxlength.' alt="'.$alt.'" />';
c06c8492 1052
d0d272e7 1053 $output .= '</span>'."\n";
1054
1055 if (empty($return)) {
1056 echo $output;
1057 } else {
1058 return $output;
1059 }
1060
1061}
1062
1063
d48b00b4 1064/**
1065 * Implements a complete little popup form
1066 *
89dcb99d 1067 * @uses $CFG
1068 * @param string $common The URL up to the point of the variable that changes
1069 * @param array $options Alist of value-label pairs for the popup list
ee5567d1 1070 * @param string $formid Id must be unique on the page (originaly $formname)
89dcb99d 1071 * @param string $selected The option that is already selected
1072 * @param string $nothing The label for the "no choice" option
1073 * @param string $help The name of a help page if help is required
1074 * @param string $helptext The name of the label for the help button
1075 * @param boolean $return Indicates whether the function should return the text
1076 * as a string or echo it directly to the page being rendered
772e78be 1077 * @param string $targetwindow The name of the target page to open the linked page in.
1d75edd0 1078 * @param string $selectlabel Text to place in a [label] element - preferred for accessibility.
1079 * @param array $optionsextra TODO, an array?
89dcb99d 1080 * @return string If $return is true then the entire form is returned as a string.
1081 * @todo Finish documenting this function<br>
89dcb99d 1082 */
b6b354e3 1083function popup_form($common, $options, $formid, $selected='', $nothing='choose', $help='', $helptext='', $return=false,
1084$targetwindow='self', $selectlabel='', $optionsextra=NULL) {
89dcb99d 1085
772e78be 1086 global $CFG;
b0542a1e 1087 static $go, $choose; /// Locally cached, in case there's lots on a page
87180677 1088
6f9f3b69 1089 if (empty($options)) {
1090 return '';
1091 }
0d0baabf 1092
b0542a1e 1093 if (!isset($go)) {
1094 $go = get_string('go');
037dcbb6 1095 }
1096
b0ccd3fb 1097 if ($nothing == 'choose') {
037dcbb6 1098 if (!isset($choose)) {
1099 $choose = get_string('choose');
1100 }
1101 $nothing = $choose.'...';
618b22c5 1102 }
1103
9d3c6ee5 1104 // changed reference to document.getElementById('id_abc') instead of document.abc
1105 // MDL-7861
4f24b3e3 1106 $output = '<form action="'.$CFG->wwwroot.'/course/jumpto.php"'.
fa738731 1107 ' method="get" '.
1108 $CFG->frametarget.
ee5567d1 1109 ' id="'.$formid.'"'.
c4d951e1 1110 ' class="popupform">';
4f24b3e3 1111 if ($help) {
1112 $button = helpbutton($help, $helptext, 'moodle', true, false, '', true);
1113 } else {
1114 $button = '';
1115 }
037dcbb6 1116
fcf9577a 1117 if ($selectlabel) {
1118 $selectlabel = '<label for="'.$formid.'_jump">'.$selectlabel.'</label>';
1119 }
1120
60ec23af 1121 $output .= '<div>'.$selectlabel.$button.'<select id="'.$formid.'_jump" name="jump" onchange="'.$targetwindow.'.location=document.getElementById(\''.$formid.'\').jump.options[document.getElementById(\''.$formid.'\').jump.selectedIndex].value;">'."\n";
f9903ed0 1122
b0ccd3fb 1123 if ($nothing != '') {
dfec7b01 1124 $output .= " <option value=\"javascript:void(0)\">$nothing</option>\n";
f9903ed0 1125 }
1126
72b4e283 1127 $inoptgroup = false;
89bfeee0 1128
f9903ed0 1129 foreach ($options as $value => $label) {
772e78be 1130
89bfeee0 1131 if ($label == '--') { /// we are ending previous optgroup
1132 /// Check to see if we already have a valid open optgroup
1133 /// XHTML demands that there be at least 1 option within an optgroup
1134 if ($inoptgroup and (count($optgr) > 1) ) {
1135 $output .= implode('', $optgr);
1136 $output .= ' </optgroup>';
1137 }
1138 $optgr = array();
1139 $inoptgroup = false;
1140 continue;
1141 } else if (substr($label,0,2) == '--') { /// we are starting a new optgroup
772e78be 1142
2a003a90 1143 /// Check to see if we already have a valid open optgroup
1144 /// XHTML demands that there be at least 1 option within an optgroup
1145 if ($inoptgroup and (count($optgr) > 1) ) {
1146 $output .= implode('', $optgr);
72b4e283 1147 $output .= ' </optgroup>';
72b4e283 1148 }
2a003a90 1149
1150 unset($optgr);
1151 $optgr = array();
1152
dacb47c0 1153 $optgr[] = ' <optgroup label="'. s(format_string(substr($label,2))) .'">'; // Plain labels
772e78be 1154
2a003a90 1155 $inoptgroup = true; /// everything following will be in an optgroup
3326450b 1156 continue;
772e78be 1157
d897cae4 1158 } else {
fd78420b 1159 if (!empty($CFG->usesid) && !isset($_COOKIE[session_name()]))
1160 {
1161 $url=sid_process_url( $common . $value );
1162 } else
1163 {
1164 $url=$common . $value;
1165 }
1166 $optstr = ' <option value="' . $url . '"';
772e78be 1167
d897cae4 1168 if ($value == $selected) {
2a003a90 1169 $optstr .= ' selected="selected"';
1170 }
772e78be 1171
b6b354e3 1172 if (!empty($optionsextra[$value])) {
1173 $optstr .= ' '.$optionsextra[$value];
1174 }
1175
2a003a90 1176 if ($label) {
1177 $optstr .= '>'. $label .'</option>' . "\n";
1178 } else {
1179 $optstr .= '>'. $value .'</option>' . "\n";
1180 }
772e78be 1181
2a003a90 1182 if ($inoptgroup) {
1183 $optgr[] = $optstr;
1184 } else {
1185 $output .= $optstr;
d897cae4 1186 }
f9903ed0 1187 }
772e78be 1188
f9903ed0 1189 }
2a003a90 1190
1191 /// catch the final group if not closed
1192 if ($inoptgroup and count($optgr) > 1) {
1193 $output .= implode('', $optgr);
72b4e283 1194 $output .= ' </optgroup>';
1195 }
2a003a90 1196
b0ccd3fb 1197 $output .= '</select>';
3435f39b 1198 $output .= '<input type="hidden" name="sesskey" value="'.sesskey().'" />';
ee5567d1 1199 $output .= '<div id="noscript'.$formid.'" style="display: inline;">';
929089e7 1200 $output .= '<input type="submit" value="'.$go.'" /></div>';
037dcbb6 1201 $output .= '<script type="text/javascript">'.
ce926cb8 1202 "\n//<![CDATA[\n".
ee5567d1 1203 'document.getElementById("noscript'.$formid.'").style.display = "none";'.
ce926cb8 1204 "\n//]]>\n".'</script>';
60ec23af 1205 $output .= '</div>';
3d621607 1206 $output .= '</form>';
d897cae4 1207
1208 if ($return) {
4f24b3e3 1209 return $output;
d897cae4 1210 } else {
4f24b3e3 1211 echo $output;
d897cae4 1212 }
f9903ed0 1213}
1214
1215
d48b00b4 1216/**
1217 * Prints some red text
1218 *
1219 * @param string $error The text to be displayed in red
1220 */
f9903ed0 1221function formerr($error) {
d48b00b4 1222
f9903ed0 1223 if (!empty($error)) {
7bc1c17f 1224 echo '<span class="error">'. $error .'</span>';
f9903ed0 1225 }
1226}
1227
d48b00b4 1228/**
1229 * Validates an email to make sure it makes sense.
1230 *
1231 * @param string $address The email address to validate.
1232 * @return boolean
1233 */
89dcb99d 1234function validate_email($address) {
d48b00b4 1235
78fbaeae 1236 return (ereg('^[-!#$%&\'*+\\/0-9=?A-Z^_`a-z{|}~]+'.
1237 '(\.[-!#$%&\'*+\\/0-9=?A-Z^_`a-z{|}~]+)*'.
f9903ed0 1238 '@'.
1239 '[-!#$%&\'*+\\/0-9=?A-Z^_`a-z{|}~]+\.'.
1240 '[-!#$%&\'*+\\./0-9=?A-Z^_`a-z{|}~]+$',
1241 $address));
1242}
1243
690f358b 1244/**
1245 * Extracts file argument either from file parameter or PATH_INFO
1246 *
1247 * @param string $scriptname name of the calling script
1248 * @return string file path (only safe characters)
1249 */
1250function get_file_argument($scriptname) {
1251 global $_SERVER;
1252
1253 $relativepath = FALSE;
1254
1255 // first try normal parameter (compatible method == no relative links!)
1256 $relativepath = optional_param('file', FALSE, PARAM_PATH);
48283ff6 1257 if ($relativepath === '/testslasharguments') {
9bbb40d6 1258 echo 'test -1 : Incorrect use - try "file.php/testslasharguments" instead'; //indicate fopen/fread works for health center
48283ff6 1259 die;
1260 }
690f358b 1261
1262 // then try extract file from PATH_INFO (slasharguments method)
1263 if (!$relativepath and !empty($_SERVER['PATH_INFO'])) {
1264 $path_info = $_SERVER['PATH_INFO'];
1265 // check that PATH_INFO works == must not contain the script name
1266 if (!strpos($path_info, $scriptname)) {
1267 $relativepath = clean_param(rawurldecode($path_info), PARAM_PATH);
48283ff6 1268 if ($relativepath === '/testslasharguments') {
9bbb40d6 1269 echo 'test 1 : Slasharguments test passed. Server confguration is compatible with file.php/1/pic.jpg slashargument setting.'; //indicate ok for health center
690f358b 1270 die;
1271 }
1272 }
1273 }
1274
1275 // now if both fail try the old way
1276 // (for compatibility with misconfigured or older buggy php implementations)
1277 if (!$relativepath) {
1278 $arr = explode($scriptname, me());
1279 if (!empty($arr[1])) {
1280 $path_info = strip_querystring($arr[1]);
1281 $relativepath = clean_param(rawurldecode($path_info), PARAM_PATH);
48283ff6 1282 if ($relativepath === '/testslasharguments') {
9bbb40d6 1283 echo 'test 2 : Slasharguments test passed (compatibility hack). Server confguration may be compatible with file.php/1/pic.jpg slashargument setting'; //indicate ok for health center
690f358b 1284 die;
1285 }
1286 }
1287 }
1288
1289 return $relativepath;
1290}
1291
d48b00b4 1292/**
1293 * Searches the current environment variables for some slash arguments
1294 *
1295 * @param string $file ?
1296 * @todo Finish documenting this function
1297 */
b0ccd3fb 1298function get_slash_arguments($file='file.php') {
f9903ed0 1299
eaa50dbc 1300 if (!$string = me()) {
f9903ed0 1301 return false;
1302 }
eaa50dbc 1303
6ed3da1d 1304 $pathinfo = explode($file, $string);
ab9f24ad 1305
bcdfe14e 1306 if (!empty($pathinfo[1])) {
9b74055f 1307 return addslashes($pathinfo[1]);
6ed3da1d 1308 } else {
1309 return false;
1310 }
1311}
1312
d48b00b4 1313/**
1314 * Extracts arguments from "/foo/bar/something"
1315 * eg http://mysite.com/script.php/foo/bar/something
1316 *
89dcb99d 1317 * @param string $string ?
1318 * @param int $i ?
1319 * @return array|string
d48b00b4 1320 * @todo Finish documenting this function
1321 */
6ed3da1d 1322function parse_slash_arguments($string, $i=0) {
f9903ed0 1323
6c8e8b5e 1324 if (detect_munged_arguments($string)) {
780db230 1325 return false;
1326 }
b0ccd3fb 1327 $args = explode('/', $string);
f9903ed0 1328
1329 if ($i) { // return just the required argument
1330 return $args[$i];
1331
1332 } else { // return the whole array
1333 array_shift($args); // get rid of the empty first one
1334 return $args;
1335 }
1336}
1337
d48b00b4 1338/**
89dcb99d 1339 * Just returns an array of text formats suitable for a popup menu
d48b00b4 1340 *
89dcb99d 1341 * @uses FORMAT_MOODLE
1342 * @uses FORMAT_HTML
1343 * @uses FORMAT_PLAIN
89dcb99d 1344 * @uses FORMAT_MARKDOWN
1345 * @return array
d48b00b4 1346 */
0095d5cd 1347function format_text_menu() {
d48b00b4 1348
b0ccd3fb 1349 return array (FORMAT_MOODLE => get_string('formattext'),
1350 FORMAT_HTML => get_string('formathtml'),
1351 FORMAT_PLAIN => get_string('formatplain'),
b0ccd3fb 1352 FORMAT_MARKDOWN => get_string('formatmarkdown'));
0095d5cd 1353}
1354
d48b00b4 1355/**
1356 * Given text in a variety of format codings, this function returns
772e78be 1357 * the text as safe HTML.
d48b00b4 1358 *
1359 * @uses $CFG
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 * @param array $options ?
1369 * @param int $courseid ?
1370 * @return string
d48b00b4 1371 * @todo Finish documenting this function
1372 */
7d8a3cb0 1373function format_text($text, $format=FORMAT_MOODLE, $options=NULL, $courseid=NULL) {
0095d5cd 1374
dcf6d93c 1375 global $CFG, $COURSE;
c4ae4fa1 1376
d53ca6ad 1377 if ($text === '') {
1378 return ''; // no need to do any filters and cleaning
1379 }
1380
7d8a3cb0 1381 if (!isset($options->trusttext)) {
1382 $options->trusttext = false;
1383 }
1384
e7a47153 1385 if (!isset($options->noclean)) {
1386 $options->noclean=false;
1387 }
a17c57b5 1388 if (!isset($options->nocache)) {
1389 $options->nocache=false;
1390 }
e7a47153 1391 if (!isset($options->smiley)) {
1392 $options->smiley=true;
1393 }
1394 if (!isset($options->filter)) {
1395 $options->filter=true;
1396 }
1397 if (!isset($options->para)) {
1398 $options->para=true;
1399 }
1400 if (!isset($options->newlines)) {
1401 $options->newlines=true;
f0aa2fed 1402 }
1403
c4ae4fa1 1404 if (empty($courseid)) {
dcf6d93c 1405 $courseid = $COURSE->id;
c4ae4fa1 1406 }
a751a4e5 1407
a17c57b5 1408 if (!empty($CFG->cachetext) and empty($options->nocache)) {
e7a47153 1409 $time = time() - $CFG->cachetext;
90bbe689 1410 $md5key = md5($text.'-'.(int)$courseid.'-'.current_language().'-'.(int)$format.(int)$options->trusttext.(int)$options->noclean.(int)$options->smiley.(int)$options->filter.(int)$options->para.(int)$options->newlines);
a9743837 1411 if ($oldcacheitem = get_record_sql('SELECT * FROM '.$CFG->prefix.'cache_text WHERE md5key = \''.$md5key.'\'', true)) {
1412 if ($oldcacheitem->timemodified >= $time) {
1413 return $oldcacheitem->formattedtext;
1414 }
e7a47153 1415 }
1416 }
1417
7d8a3cb0 1418 // trusttext overrides the noclean option!
1419 if ($options->trusttext) {
1420 if (trusttext_present($text)) {
1421 $text = trusttext_strip($text);
1422 if (!empty($CFG->enabletrusttext)) {
1423 $options->noclean = true;
1424 } else {
1425 $options->noclean = false;
1426 }
1427 } else {
1428 $options->noclean = false;
1429 }
d53ca6ad 1430 } else if (!debugging('', DEBUG_DEVELOPER)) {
1431 // strip any forgotten trusttext in non-developer mode
1432 // do not forget to disable text cache when debugging trusttext!!
1433 $text = trusttext_strip($text);
7d8a3cb0 1434 }
1435
8eaa4c61 1436 $CFG->currenttextiscacheable = true; // Default status - can be changed by any filter
c06c8492 1437
0095d5cd 1438 switch ($format) {
73f8658c 1439 case FORMAT_HTML:
7d8a3cb0 1440 if ($options->smiley) {
e7a47153 1441 replace_smilies($text);
1442 }
7d8a3cb0 1443 if (!$options->noclean) {
5c6347ce 1444 $text = clean_text($text, FORMAT_HTML);
9d40806d 1445 }
7d8a3cb0 1446 if ($options->filter) {
e7a47153 1447 $text = filter_text($text, $courseid);
1448 }
73f8658c 1449 break;
1450
6901fa79 1451 case FORMAT_PLAIN:
5c6347ce 1452 $text = s($text); // cleans dangerous JS
ab892a4f 1453 $text = rebuildnolinktag($text);
b0ccd3fb 1454 $text = str_replace(' ', '&nbsp; ', $text);
6901fa79 1455 $text = nl2br($text);
6901fa79 1456 break;
1457
d342c763 1458 case FORMAT_WIKI:
6a6495ff 1459 // this format is deprecated
572fe9ab 1460 $text = '<p>NOTICE: Wiki-like formatting has been removed from Moodle. You should not be seeing
1461 this message as all texts should have been converted to Markdown format instead.
ce50cc70 1462 Please post a bug report to http://moodle.org/bugs with information about where you
e7a47153 1463 saw this message.</p>'.s($text);
d342c763 1464 break;
1465
e7cdcd18 1466 case FORMAT_MARKDOWN:
1467 $text = markdown_to_html($text);
7d8a3cb0 1468 if ($options->smiley) {
e7a47153 1469 replace_smilies($text);
1470 }
7d8a3cb0 1471 if (!$options->noclean) {
5c6347ce 1472 $text = clean_text($text, FORMAT_HTML);
9d40806d 1473 }
c06c8492 1474
7d8a3cb0 1475 if ($options->filter) {
e7a47153 1476 $text = filter_text($text, $courseid);
1477 }
e7cdcd18 1478 break;
1479
73f8658c 1480 default: // FORMAT_MOODLE or anything else
b7a3d3b2 1481 $text = text_to_html($text, $options->smiley, $options->para, $options->newlines);
7d8a3cb0 1482 if (!$options->noclean) {
5c6347ce 1483 $text = clean_text($text, FORMAT_HTML);
9d40806d 1484 }
c06c8492 1485
7d8a3cb0 1486 if ($options->filter) {
e7a47153 1487 $text = filter_text($text, $courseid);
1488 }
0095d5cd 1489 break;
0095d5cd 1490 }
f0aa2fed 1491
f47f4659 1492 if (empty($options->nocache) and !empty($CFG->cachetext) and $CFG->currenttextiscacheable) {
1493 $newcacheitem = new object();
a9743837 1494 $newcacheitem->md5key = $md5key;
1495 $newcacheitem->formattedtext = addslashes($text);
1496 $newcacheitem->timemodified = time();
1497 if ($oldcacheitem) { // See bug 4677 for discussion
1498 $newcacheitem->id = $oldcacheitem->id;
1499 @update_record('cache_text', $newcacheitem); // Update existing record in the cache table
5ce73257 1500 // It's unlikely that the cron cache cleaner could have
a9743837 1501 // deleted this entry in the meantime, as it allows
1502 // some extra time to cover these cases.
1503 } else {
1504 @insert_record('cache_text', $newcacheitem); // Insert a new record in the cache table
1505 // Again, it's possible that another user has caused this
5ce73257 1506 // record to be created already in the time that it took
1507 // to traverse this function. That's OK too, as the
a9743837 1508 // call above handles duplicate entries, and eventually
1509 // the cron cleaner will delete them.
1510 }
f0aa2fed 1511 }
1512
1513 return $text;
0095d5cd 1514}
1515
4a28b5ca 1516/** Converts the text format from the value to the 'internal'
1517 * name or vice versa. $key can either be the value or the name
1518 * and you get the other back.
c06c8492 1519 *
4a28b5ca 1520 * @param mixed int 0-4 or string one of 'moodle','html','plain','markdown'
1521 * @return mixed as above but the other way around!
1522 */
1523function text_format_name( $key ) {
1524 $lookup = array();
1525 $lookup[FORMAT_MOODLE] = 'moodle';
1526 $lookup[FORMAT_HTML] = 'html';
1527 $lookup[FORMAT_PLAIN] = 'plain';
1528 $lookup[FORMAT_MARKDOWN] = 'markdown';
1529 $value = "error";
1530 if (!is_numeric($key)) {
1531 $key = strtolower( $key );
1532 $value = array_search( $key, $lookup );
1533 }
1534 else {
1535 if (isset( $lookup[$key] )) {
1536 $value = $lookup[ $key ];
1537 }
1538 }
1539 return $value;
1540}
1541
473d29eb 1542
7b2c5e72 1543/** Given a simple string, this function returns the string
1544 * processed by enabled filters if $CFG->filterall is enabled
1545 *
3e6691ee 1546 * @param string $string The string to be filtered.
fae83c8d 1547 * @param boolean $striplinks To strip any link in the result text (Moodle 1.8 default changed from false to true! MDL-8713)
3e6691ee 1548 * @param int $courseid Current course as filters can, potentially, use it
7b2c5e72 1549 * @return string
1550 */
fae83c8d 1551function format_string ($string, $striplinks=true, $courseid=NULL ) {
7b2c5e72 1552
65b0c132 1553 global $CFG, $COURSE;
38701b69 1554
2a3affe9 1555 //We'll use a in-memory cache here to speed up repeated strings
473d29eb 1556 static $strcache = false;
1557
38701b69 1558 if ($strcache === false or count($strcache) > 2000 ) { // this number might need some tuning to limit memory usage in cron
473d29eb 1559 $strcache = array();
1560 }
84e3d2cc 1561
38701b69 1562 //init course id
a97e0ccb 1563 if (empty($courseid)) {
38701b69 1564 $courseid = $COURSE->id;
1565 }
1566
2a3affe9 1567 //Calculate md5
38701b69 1568 $md5 = md5($string.'<+>'.$striplinks.'<+>'.$courseid.'<+>'.current_language());
2a3affe9 1569
1570 //Fetch from cache if possible
38701b69 1571 if (isset($strcache[$md5])) {
2a3affe9 1572 return $strcache[$md5];
1573 }
1574
dacb47c0 1575 // First replace all ampersands not followed by html entity code
cb6a4f09 1576 $string = preg_replace("/\&(?![a-zA-Z0-9#]{1,8};)/", "&amp;", $string);
268ddd50 1577
45daee10 1578 if (!empty($CFG->filterall)) {
037da74d 1579 $string = filter_string($string, $courseid);
7b2c5e72 1580 }
84e3d2cc 1581
9fbed9c9 1582 // If the site requires it, strip ALL tags from this string
1583 if (!empty($CFG->formatstringstriptags)) {
1584 $string = strip_tags($string);
1585
1586 // Otherwise strip just links if that is required (default)
1587 } else if ($striplinks) { //strip links in string
3e6691ee 1588 $string = preg_replace('/(<a[^>]+?>)(.+?)(<\/a>)/is','$2',$string);
1589 }
1590
2a3affe9 1591 //Store to cache
1592 $strcache[$md5] = $string;
84e3d2cc 1593
7b2c5e72 1594 return $string;
1595}
1596
d48b00b4 1597/**
1598 * Given text in a variety of format codings, this function returns
1599 * the text as plain text suitable for plain email.
d48b00b4 1600 *
89dcb99d 1601 * @uses FORMAT_MOODLE
1602 * @uses FORMAT_HTML
1603 * @uses FORMAT_PLAIN
1604 * @uses FORMAT_WIKI
1605 * @uses FORMAT_MARKDOWN
1606 * @param string $text The text to be formatted. This is raw text originally from user input.
772e78be 1607 * @param int $format Identifier of the text format to be used
89dcb99d 1608 * (FORMAT_MOODLE, FORMAT_HTML, FORMAT_PLAIN, FORMAT_WIKI, FORMAT_MARKDOWN)
1609 * @return string
d48b00b4 1610 */
d342c763 1611function format_text_email($text, $format) {
d342c763 1612
1613 switch ($format) {
1614
1615 case FORMAT_PLAIN:
1616 return $text;
1617 break;
1618
1619 case FORMAT_WIKI:
1620 $text = wiki_to_html($text);
5b472756 1621 /// This expression turns links into something nice in a text format. (Russell Jungwirth)
1622 /// From: http://php.net/manual/en/function.eregi-replace.php and simplified
76add072 1623 $text = eregi_replace('(<a [^<]*href=["|\']?([^ "\']*)["|\']?[^>]*>([^<]*)</a>)','\\3 [ \\2 ]', $text);
7c55a29b 1624 return strtr(strip_tags($text), array_flip(get_html_translation_table(HTML_ENTITIES)));
d342c763 1625 break;
1626
6ff45b59 1627 case FORMAT_HTML:
1628 return html_to_text($text);
1629 break;
1630
e7cdcd18 1631 case FORMAT_MOODLE:
1632 case FORMAT_MARKDOWN:
67ccec43 1633 default:
76add072 1634 $text = eregi_replace('(<a [^<]*href=["|\']?([^ "\']*)["|\']?[^>]*>([^<]*)</a>)','\\3 [ \\2 ]', $text);
7c55a29b 1635 return strtr(strip_tags($text), array_flip(get_html_translation_table(HTML_ENTITIES)));
d342c763 1636 break;
1637 }
1638}
0095d5cd 1639
d48b00b4 1640/**
1641 * Given some text in HTML format, this function will pass it
1642 * through any filters that have been defined in $CFG->textfilterx
1643 * The variable defines a filepath to a file containing the
1644 * filter function. The file must contain a variable called
1645 * $textfilter_function which contains the name of the function
1646 * with $courseid and $text parameters
1647 *
89dcb99d 1648 * @param string $text The text to be passed through format filters
1649 * @param int $courseid ?
d48b00b4 1650 * @return string
1651 * @todo Finish documenting this function
1652 */
c4ae4fa1 1653function filter_text($text, $courseid=NULL) {
dcf6d93c 1654 global $CFG, $COURSE;
1655
1656 if (empty($courseid)) {
1657 $courseid = $COURSE->id; // (copied from format_text)
1658 }
e67b9e31 1659
d523d2ea 1660 if (!empty($CFG->textfilters)) {
cbdfb929 1661 require_once($CFG->libdir.'/filterlib.php');
d523d2ea 1662 $textfilters = explode(',', $CFG->textfilters);
1663 foreach ($textfilters as $textfilter) {
b0ccd3fb 1664 if (is_readable($CFG->dirroot .'/'. $textfilter .'/filter.php')) {
1665 include_once($CFG->dirroot .'/'. $textfilter .'/filter.php');
df1c4611 1666 $functionname = basename($textfilter).'_filter';
1667 if (function_exists($functionname)) {
1668 $text = $functionname($courseid, $text);
1669 }
d523d2ea 1670 }
e67b9e31 1671 }
1672 }
d523d2ea 1673
c7444a36 1674 /// <nolink> tags removed for XHTML compatibility
1675 $text = str_replace('<nolink>', '', $text);
1676 $text = str_replace('</nolink>', '', $text);
1677
e67b9e31 1678 return $text;
1679}
1680
cbdfb929 1681
1682/**
1683 * Given a string (short text) in HTML format, this function will pass it
1684 * through any filters that have been defined in $CFG->stringfilters
1685 * The variable defines a filepath to a file containing the
1686 * filter function. The file must contain a variable called
1687 * $textfilter_function which contains the name of the function
1688 * with $courseid and $text parameters
1689 *
1690 * @param string $string The text to be passed through format filters
1691 * @param int $courseid The id of a course
1692 * @return string
1693 */
1694function filter_string($string, $courseid=NULL) {
1695 global $CFG, $COURSE;
1696
1697 if (empty($CFG->textfilters)) { // All filters are disabled anyway so quit
1698 return $string;
1699 }
1700
1701 if (empty($courseid)) {
84e3d2cc 1702 $courseid = $COURSE->id;
cbdfb929 1703 }
1704
1705 require_once($CFG->libdir.'/filterlib.php');
1706
1707 if (isset($CFG->stringfilters)) { // We have a predefined list to use, great!
1708 if (empty($CFG->stringfilters)) { // but it's blank, so finish now
1709 return $string;
1710 }
1711 $stringfilters = explode(',', $CFG->stringfilters); // ..use the list we have
1712
1713 } else { // Otherwise try to derive a list from textfilters
9fbed9c9 1714 if (strpos($CFG->textfilters, 'filter/multilang') !== false) { // Multilang is here
cbdfb929 1715 $stringfilters = array('filter/multilang'); // Let's use just that
1716 $CFG->stringfilters = 'filter/multilang'; // Save it for next time through
9fbed9c9 1717 } else {
1718 $CFG->stringfilters = ''; // Save the result and return
1719 return $string;
cbdfb929 1720 }
1721 }
1722
9fbed9c9 1723
cbdfb929 1724 foreach ($stringfilters as $stringfilter) {
1725 if (is_readable($CFG->dirroot .'/'. $stringfilter .'/filter.php')) {
1726 include_once($CFG->dirroot .'/'. $stringfilter .'/filter.php');
1727 $functionname = basename($stringfilter).'_filter';
1728 if (function_exists($functionname)) {
1729 $string = $functionname($courseid, $string);
1730 }
1731 }
1732 }
1733
1734 /// <nolink> tags removed for XHTML compatibility
1735 $string = str_replace('<nolink>', '', $string);
1736 $string = str_replace('</nolink>', '', $string);
1737
1738 return $string;
1739}
1740
7d8a3cb0 1741/**
1742 * Is the text marked as trusted?
1743 *
1744 * @param string $text text to be searched for TRUSTTEXT marker
1745 * @return boolean
1746 */
1747function trusttext_present($text) {
1748 if (strpos($text, TRUSTTEXT) !== FALSE) {
1749 return true;
1750 } else {
1751 return false;
1752 }
1753}
1754
1755/**
1756 * This funtion MUST be called before the cleaning or any other
1757 * function that modifies the data! We do not know the origin of trusttext
1758 * in database, if it gets there in tweaked form we must not convert it
1759 * to supported form!!!
1760 *
1761 * Please be carefull not to use stripslashes on data from database
1762 * or twice stripslashes when processing data recieved from user.
1763 *
5ce73257 1764 * @param string $text text that may contain TRUSTTEXT marker
7d8a3cb0 1765 * @return text without any TRUSTTEXT marker
1766 */
1767function trusttext_strip($text) {
1768 global $CFG;
1769
1770 while (true) { //removing nested TRUSTTEXT
5ce73257 1771 $orig = $text;
7d8a3cb0 1772 $text = str_replace(TRUSTTEXT, '', $text);
1773 if (strcmp($orig, $text) === 0) {
1774 return $text;
1775 }
1776 }
1777}
1778
1779/**
1780 * Mark text as trusted, such text may contain any HTML tags because the
1781 * normal text cleaning will be bypassed.
1782 * Please make sure that the text comes from trusted user before storing
1783 * it into database!
1784 */
1785function trusttext_mark($text) {
1786 global $CFG;
1787 if (!empty($CFG->enabletrusttext) and (strpos($text, TRUSTTEXT) === FALSE)) {
1788 return TRUSTTEXT.$text;
1789 } else {
1790 return $text;
1791 }
1792}
1793function trusttext_after_edit(&$text, $context) {
1794 if (has_capability('moodle/site:trustcontent', $context)) {
daed1a2f 1795 $text = trusttext_strip($text);
7d8a3cb0 1796 $text = trusttext_mark($text);
1797 } else {
1798 $text = trusttext_strip($text);
1799 }
1800}
1801
1802function trusttext_prepare_edit(&$text, &$format, $usehtmleditor, $context) {
1803 global $CFG;
1804
1805 $options = new object();
1806 $options->smiley = false;
1807 $options->filter = false;
1808 if (!empty($CFG->enabletrusttext)
1809 and has_capability('moodle/site:trustcontent', $context)
1810 and trusttext_present($text)) {
1811 $options->noclean = true;
1812 } else {
1813 $options->noclean = false;
1814 }
1815 $text = trusttext_strip($text);
1816 if ($usehtmleditor) {
1817 $text = format_text($text, $format, $options);
1818 $format = FORMAT_HTML;
1819 } else if (!$options->noclean){
1820 $text = clean_text($text, $format);
1821 }
1822}
1823
d48b00b4 1824/**
1825 * Given raw text (eg typed in by a user), this function cleans it up
1826 * and removes any nasty tags that could mess up Moodle pages.
1827 *
89dcb99d 1828 * @uses FORMAT_MOODLE
1829 * @uses FORMAT_PLAIN
1830 * @uses ALLOWED_TAGS
1831 * @param string $text The text to be cleaned
772e78be 1832 * @param int $format Identifier of the text format to be used
89dcb99d 1833 * (FORMAT_MOODLE, FORMAT_HTML, FORMAT_PLAIN, FORMAT_WIKI, FORMAT_MARKDOWN)
1834 * @return string The cleaned up text
d48b00b4 1835 */
3da47524 1836function clean_text($text, $format=FORMAT_MOODLE) {
b7a3cf49 1837
85fbf884 1838 global $ALLOWED_TAGS, $CFG;
1839
e0ac8448 1840 if (empty($text) or is_numeric($text)) {
84e3d2cc 1841 return (string)$text;
e0ac8448 1842 }
3fe3851d 1843
ab9f24ad 1844 switch ($format) {
e7cdcd18 1845 case FORMAT_PLAIN:
8f660562 1846 case FORMAT_MARKDOWN:
e7cdcd18 1847 return $text;
1848
1849 default:
1850
e0ac8448 1851 if (!empty($CFG->enablehtmlpurifier)) {
1852 $text = purify_html($text);
1853 } else {
1854 /// Fix non standard entity notations
1855 $text = preg_replace('/(&#[0-9]+)(;?)/', "\\1;", $text);
1856 $text = preg_replace('/(&#x[0-9a-fA-F]+)(;?)/', "\\1;", $text);
84e3d2cc 1857
e0ac8448 1858 /// Remove tags that are not allowed
1859 $text = strip_tags($text, $ALLOWED_TAGS);
84e3d2cc 1860
e0ac8448 1861 /// Clean up embedded scripts and , using kses
1862 $text = cleanAttributes($text);
a33c44c4 1863
1864 /// Again remove tags that are not allowed
1865 $text = strip_tags($text, $ALLOWED_TAGS);
1866
e0ac8448 1867 }
7789ffbf 1868
e0ac8448 1869 /// Remove potential script events - some extra protection for undiscovered bugs in our code
ab9f24ad 1870 $text = eregi_replace("([^a-z])language([[:space:]]*)=", "\\1Xlanguage=", $text);
1871 $text = eregi_replace("([^a-z])on([a-z]+)([[:space:]]*)=", "\\1Xon\\2=", $text);
6901fa79 1872
6901fa79 1873 return $text;
0095d5cd 1874 }
b7a3cf49 1875}
f9903ed0 1876
e0ac8448 1877/**
1878 * KSES replacement cleaning function - uses HTML Purifier.
1879 */
1880function purify_html($text) {
1881 global $CFG;
1882
1883 static $purifier = false;
1884 if (!$purifier) {
5adad310 1885 make_upload_directory('cache/htmlpurifier', false);
e0ac8448 1886 require_once $CFG->libdir.'/htmlpurifier/HTMLPurifier.auto.php';
1887 $config = HTMLPurifier_Config::createDefault();
1888 $config->set('Core', 'AcceptFullDocuments', false);
5adad310 1889 $config->set('Core', 'Encoding', 'UTF-8');
1890 $config->set('HTML', 'Doctype', 'XHTML 1.0 Transitional');
1891 $config->set('Cache', 'SerializerPath', $CFG->dataroot.'/cache/htmlpurifier');
e0ac8448 1892 $config->set('URI', 'AllowedSchemes', array('http'=>1, 'https'=>1, 'ftp'=>1, 'irc'=>1, 'nntp'=>1, 'news'=>1, 'rtsp'=>1, 'teamspeak'=>1, 'gopher'=>1, 'mms'=>1));
1893 $purifier = new HTMLPurifier($config);
1894 }
1895 return $purifier->purify($text);
1896}
1897
d48b00b4 1898/**
89dcb99d 1899 * This function takes a string and examines it for HTML tags.
d48b00b4 1900 * If tags are detected it passes the string to a helper function {@link cleanAttributes2()}
1901 * which checks for attributes and filters them for malicious content
1902 * 17/08/2004 :: Eamon DOT Costello AT dcu DOT ie
1903 *
1904 * @param string $str The string to be examined for html tags
1905 * @return string
1906 */
3bd7ffec 1907function cleanAttributes($str){
4e8f2e6b 1908 $result = preg_replace_callback(
1909 '%(<[^>]*(>|$)|>)%m', #search for html tags
1910 "cleanAttributes2",
3bd7ffec 1911 $str
67ccec43 1912 );
3bd7ffec 1913 return $result;
67ccec43 1914}
1915
d48b00b4 1916/**
1917 * This function takes a string with an html tag and strips out any unallowed
1918 * protocols e.g. javascript:
1919 * It calls ancillary functions in kses which are prefixed by kses
1920* 17/08/2004 :: Eamon DOT Costello AT dcu DOT ie
1921 *
4e8f2e6b 1922 * @param array $htmlArray An array from {@link cleanAttributes()}, containing in its 1st
1923 * element the html to be cleared
d48b00b4 1924 * @return string
1925 */
4e8f2e6b 1926function cleanAttributes2($htmlArray){
3bd7ffec 1927
037dcbb6 1928 global $CFG, $ALLOWED_PROTOCOLS;
b0ccd3fb 1929 require_once($CFG->libdir .'/kses.php');
3bd7ffec 1930
4e8f2e6b 1931 $htmlTag = $htmlArray[1];
037dcbb6 1932 if (substr($htmlTag, 0, 1) != '<') {
3bd7ffec 1933 return '&gt;'; //a single character ">" detected
1934 }
037dcbb6 1935 if (!preg_match('%^<\s*(/\s*)?([a-zA-Z0-9]+)([^>]*)>?$%', $htmlTag, $matches)) {
67ccec43 1936 return ''; // It's seriously malformed
1937 }
3bd7ffec 1938 $slash = trim($matches[1]); //trailing xhtml slash
67ccec43 1939 $elem = $matches[2]; //the element name
3bd7ffec 1940 $attrlist = $matches[3]; // the list of attributes as a string
1941
037dcbb6 1942 $attrArray = kses_hair($attrlist, $ALLOWED_PROTOCOLS);
3bd7ffec 1943
67ccec43 1944 $attStr = '';
037dcbb6 1945 foreach ($attrArray as $arreach) {
29939bea 1946 $arreach['name'] = strtolower($arreach['name']);
1947 if ($arreach['name'] == 'style') {
1948 $value = $arreach['value'];
1949 while (true) {
1950 $prevvalue = $value;
1951 $value = kses_no_null($value);
1952 $value = preg_replace("/\/\*.*\*\//Us", '', $value);
1953 $value = kses_decode_entities($value);
1954 $value = preg_replace('/(&#[0-9]+)(;?)/', "\\1;", $value);
1955 $value = preg_replace('/(&#x[0-9a-fA-F]+)(;?)/', "\\1;", $value);
1956 if ($value === $prevvalue) {
1957 $arreach['value'] = $value;
1958 break;
1959 }
1960 }
1961 $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']);
1962 $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']);
b8806ccc 1963 } else if ($arreach['name'] == 'href') {
ee7f231d 1964 //Adobe Acrobat Reader XSS protection
1965 $arreach['value'] = preg_replace('/(\.(pdf|fdf|xfdf|xdp|xfd))[^a-z0-9_\.\-].*$/i', '$1', $arreach['value']);
29939bea 1966 }
049bd7db 1967 $attStr .= ' '.$arreach['name'].'="'.$arreach['value'].'"';
3bd7ffec 1968 }
713126cd 1969
3bd7ffec 1970 $xhtml_slash = '';
037dcbb6 1971 if (preg_match('%/\s*$%', $attrlist)) {
67ccec43 1972 $xhtml_slash = ' /';
3bd7ffec 1973 }
b0ccd3fb 1974 return '<'. $slash . $elem . $attStr . $xhtml_slash .'>';
3bd7ffec 1975}
1976
d48b00b4 1977/**
1978 * Replaces all known smileys in the text with image equivalents
1979 *
1980 * @uses $CFG
1981 * @param string $text Passed by reference. The string to search for smily strings.
1982 * @return string
1983 */
5f350e8f 1984function replace_smilies(&$text) {
772e78be 1985///
2ea9027b 1986 global $CFG;
c1d57101 1987
5a144b3a 1988 $lang = current_language();
1989
5b472756 1990/// this builds the mapping array only once
69081931 1991 static $e = array();
1992 static $img = array();
617778f2 1993 static $emoticons = array(
fbfc2675 1994 ':-)' => 'smiley',
1995 ':)' => 'smiley',
1996 ':-D' => 'biggrin',
1997 ';-)' => 'wink',
1998 ':-/' => 'mixed',
1999 'V-.' => 'thoughtful',
2000 ':-P' => 'tongueout',
2001 'B-)' => 'cool',
2002 '^-)' => 'approve',
2003 '8-)' => 'wideeyes',
2004 ':o)' => 'clown',
2005 ':-(' => 'sad',
2006 ':(' => 'sad',
2007 '8-.' => 'shy',
2008 ':-I' => 'blush',
2009 ':-X' => 'kiss',
2010 '8-o' => 'surprise',
2011 'P-|' => 'blackeye',
2012 '8-[' => 'angry',
2013 'xx-P' => 'dead',
2014 '|-.' => 'sleepy',
2015 '}-]' => 'evil',
35cf8b79 2016 '(h)' => 'heart',
2017 '(heart)' => 'heart',
2018 '(y)' => 'yes',
2019 '(n)' => 'no',
2eb662d2 2020 '(martin)' => 'martin',
e84ea106 2021 '( )' => 'egg'
2ea9027b 2022 );
2023
5a144b3a 2024 if (empty($img[$lang])) { /// After the first time this is not run again
2025 $e[$lang] = array();
2026 $img[$lang] = array();
617778f2 2027 foreach ($emoticons as $emoticon => $image){
fbfc2675 2028 $alttext = get_string($image, 'pix');
2029
5a144b3a 2030 $e[$lang][] = $emoticon;
2031 $img[$lang][] = '<img alt="'. $alttext .'" width="15" height="15" src="'. $CFG->pixpath .'/s/'. $image .'.gif" />';
617778f2 2032 }
c0f728ba 2033 }
b7a3cf49 2034
8dcd43f3 2035 // Exclude from transformations all the code inside <script> tags
2036 // Needed to solve Bug 1185. Thanks to jouse 2001 detecting it. :-)
2037 // Based on code from glossary fiter by Williams Castillo.
2038 // - Eloy
2039
2040 // Detect all the <script> zones to take out
2041 $excludes = array();
2042 preg_match_all('/<script language(.+?)<\/script>/is',$text,$list_of_excludes);
2043
2044 // Take out all the <script> zones from text
2045 foreach (array_unique($list_of_excludes[0]) as $key=>$value) {
2046 $excludes['<+'.$key.'+>'] = $value;
2047 }
2048 if ($excludes) {
2049 $text = str_replace($excludes,array_keys($excludes),$text);
2050 }
2051
fbfc2675 2052/// this is the meat of the code - this is run every time
5a144b3a 2053 $text = str_replace($e[$lang], $img[$lang], $text);
8dcd43f3 2054
2055 // Recover all the <script> zones to text
2056 if ($excludes) {
2057 $text = str_replace(array_keys($excludes),$excludes,$text);
2058 }
1a072208 2059}
0095d5cd 2060
89dcb99d 2061/**
2062 * Given plain text, makes it into HTML as nicely as possible.
2063 * May contain HTML tags already
2064 *
2065 * @uses $CFG
2066 * @param string $text The string to convert.
2067 * @param boolean $smiley Convert any smiley characters to smiley images?
2068 * @param boolean $para If true then the returned string will be wrapped in paragraph tags
2069 * @param boolean $newlines If true then lines newline breaks will be converted to HTML newline breaks.
2070 * @return string
2071 */
2072
b7a3d3b2 2073function text_to_html($text, $smiley=true, $para=true, $newlines=true) {
772e78be 2074///
f9903ed0 2075
27326a3e 2076 global $CFG;
2077
c1d57101 2078/// Remove any whitespace that may be between HTML tags
7b3be1b1 2079 $text = eregi_replace(">([[:space:]]+)<", "><", $text);
2080
c1d57101 2081/// Remove any returns that precede or follow HTML tags
0eae8049 2082 $text = eregi_replace("([\n\r])<", " <", $text);
2083 $text = eregi_replace(">([\n\r])", "> ", $text);
7b3be1b1 2084
5f350e8f 2085 convert_urls_into_links($text);
f9903ed0 2086
c1d57101 2087/// Make returns into HTML newlines.
b7a3d3b2 2088 if ($newlines) {
2089 $text = nl2br($text);
2090 }
f9903ed0 2091
c1d57101 2092/// Turn smileys into images.
d69cb7f4 2093 if ($smiley) {
5f350e8f 2094 replace_smilies($text);
d69cb7f4 2095 }
f9903ed0 2096
c1d57101 2097/// Wrap the whole thing in a paragraph tag if required
909f539d 2098 if ($para) {
b0ccd3fb 2099 return '<p>'.$text.'</p>';
909f539d 2100 } else {
2101 return $text;
2102 }
f9903ed0 2103}
2104
d48b00b4 2105/**
2106 * Given Markdown formatted text, make it into XHTML using external function
2107 *
89dcb99d 2108 * @uses $CFG
2109 * @param string $text The markdown formatted text to be converted.
2110 * @return string Converted text
d48b00b4 2111 */
e7cdcd18 2112function markdown_to_html($text) {
e7cdcd18 2113 global $CFG;
2114
b0ccd3fb 2115 require_once($CFG->libdir .'/markdown.php');
e7cdcd18 2116
2117 return Markdown($text);
2118}
2119
d48b00b4 2120/**
89dcb99d 2121 * Given HTML text, make it into plain text using external function
d48b00b4 2122 *
2123 * @uses $CFG
2124 * @param string $html The text to be converted.
2125 * @return string
2126 */
6ff45b59 2127function html_to_text($html) {
89dcb99d 2128
428aaa29 2129 global $CFG;
6ff45b59 2130
b0ccd3fb 2131 require_once($CFG->libdir .'/html2text.php');
6ff45b59 2132
2133 return html2text($html);
2134}
2135
d48b00b4 2136/**
2137 * Given some text this function converts any URLs it finds into HTML links
2138 *
2139 * @param string $text Passed in by reference. The string to be searched for urls.
2140 */
5f350e8f 2141function convert_urls_into_links(&$text) {
5f350e8f 2142/// Make lone URLs into links. eg http://moodle.com/
3405b212 2143 $text = eregi_replace("([[:space:]]|^|\(|\[)([[:alnum:]]+)://([^[:space:]]*)([[:alnum:]#?/&=])",
bc01a2b8 2144 "\\1<a href=\"\\2://\\3\\4\" target=\"_blank\">\\2://\\3\\4</a>", $text);
5f350e8f 2145
2146/// eg www.moodle.com
ab9f24ad 2147 $text = eregi_replace("([[:space:]]|^|\(|\[)www\.([^[:space:]]*)([[:alnum:]#?/&=])",
bc01a2b8 2148 "\\1<a href=\"http://www.\\2\\3\" target=\"_blank\">www.\\2\\3</a>", $text);
5f350e8f 2149}
2150
d48b00b4 2151/**
2152 * This function will highlight search words in a given string
2153 * It cares about HTML and will not ruin links. It's best to use
2154 * this function after performing any conversions to HTML.
2155 * Function found here: http://forums.devshed.com/t67822/scdaa2d1c3d4bacb4671d075ad41f0854.html
2156 *
89dcb99d 2157 * @param string $needle The string to search for
2158 * @param string $haystack The string to search for $needle in
2e3987a9 2159 * @param int $case whether to do case-sensitive or insensitive matching.
89dcb99d 2160 * @return string
d48b00b4 2161 * @todo Finish documenting this function
2162 */
ab9f24ad 2163function highlight($needle, $haystack, $case=0,
b0ccd3fb 2164 $left_string='<span class="highlight">', $right_string='</span>') {
69d51d3a 2165 if (empty($needle)) {
2166 return $haystack;
2167 }
2168
5eecb8cb 2169 //$list_of_words = eregi_replace("[^-a-zA-Z0-9&.']", " ", $needle); // bug 3101
2170 $list_of_words = $needle;
b0ccd3fb 2171 $list_array = explode(' ', $list_of_words);
88438a58 2172 for ($i=0; $i<sizeof($list_array); $i++) {
2173 if (strlen($list_array[$i]) == 1) {
b0ccd3fb 2174 $list_array[$i] = '';
88438a58 2175 }
2176 }
b0ccd3fb 2177 $list_of_words = implode(' ', $list_array);
88438a58 2178 $list_of_words_cp = $list_of_words;
2179 $final = array();
2180 preg_match_all('/<(.+?)>/is',$haystack,$list_of_words);
2181
2182 foreach (array_unique($list_of_words[0]) as $key=>$value) {
2183 $final['<|'.$key.'|>'] = $value;
2184 }
2185
2186 $haystack = str_replace($final,array_keys($final),$haystack);
b0ccd3fb 2187 $list_of_words_cp = eregi_replace(' +', '|', $list_of_words_cp);
88438a58 2188
b0ccd3fb 2189 if ($list_of_words_cp{0}=='|') {
2190 $list_of_words_cp{0} = '';
88438a58 2191 }
b0ccd3fb 2192 if ($list_of_words_cp{strlen($list_of_words_cp)-1}=='|') {
2193 $list_of_words_cp{strlen($list_of_words_cp)-1}='';
88438a58 2194 }
88438a58 2195
9ccdcd97 2196 $list_of_words_cp = trim($list_of_words_cp);
2197
2198 if ($list_of_words_cp) {
2199
2200 $list_of_words_cp = "(". $list_of_words_cp .")";
2201
2202 if (!$case){
2203 $haystack = eregi_replace("$list_of_words_cp", "$left_string"."\\1"."$right_string", $haystack);
2204 } else {
2205 $haystack = ereg_replace("$list_of_words_cp", "$left_string"."\\1"."$right_string", $haystack);
2206 }
88438a58 2207 }
2208 $haystack = str_replace(array_keys($final),$final,$haystack);
2209
f60e7cfe 2210 return $haystack;
88438a58 2211}
2212
d48b00b4 2213/**
2214 * This function will highlight instances of $needle in $haystack
2215 * It's faster that the above function and doesn't care about
2216 * HTML or anything.
2217 *
2218 * @param string $needle The string to search for
2219 * @param string $haystack The string to search for $needle in
2220 * @return string
2221 */
88438a58 2222function highlightfast($needle, $haystack) {
5af78ed2 2223
57f1b914 2224 $parts = explode(moodle_strtolower($needle), moodle_strtolower($haystack));
5af78ed2 2225
2226 $pos = 0;
2227
2228 foreach ($parts as $key => $part) {
2229 $parts[$key] = substr($haystack, $pos, strlen($part));
2230 $pos += strlen($part);
2231
b0ccd3fb 2232 $parts[$key] .= '<span class="highlight">'.substr($haystack, $pos, strlen($needle)).'</span>';
5af78ed2 2233 $pos += strlen($needle);
ab9f24ad 2234 }
5af78ed2 2235
2236 return (join('', $parts));
2237}
2238
2ab4e4b8 2239/**
2240 * Return a string containing 'lang', xml:lang and optionally 'dir' HTML attributes.
2241 * Internationalisation, for print_header and backup/restorelib.
2242 * @param $dir Default false.
2243 * @return string Attributes.
2244 */
2245function get_html_lang($dir = false) {
2246 $direction = '';
2247 if ($dir) {
2248 if (get_string('thisdirection') == 'rtl') {
2249 $direction = ' dir="rtl"';
2250 } else {
2251 $direction = ' dir="ltr"';
2252 }
2253 }
2254 //Accessibility: added the 'lang' attribute to $direction, used in theme <html> tag.
2255 $language = str_replace('_', '-', str_replace('_utf8', '', current_language()));
0946fff4 2256 @header('Content-Language: '.$language);
84e3d2cc 2257 return ($direction.' lang="'.$language.'" xml:lang="'.$language.'"');
2ab4e4b8 2258}
2259
5c355019 2260/**
2261 * Return the markup for the destination of the 'Skip to main content' links.
317d5ddc 2262 * Accessibility improvement for keyboard-only users.
2263 * Used in course formats, /index.php and /course/index.php
2264 * @return string HTML element.
5c355019 2265 */
2266function skip_main_destination() {
2267 return '<span id="maincontent"></span>';
2268}
2269
f9903ed0 2270
9fa49e22 2271/// STANDARD WEB PAGE PARTS ///////////////////////////////////////////////////
2272
d48b00b4 2273/**
2274 * Print a standard header
2275 *
89dcb99d 2276 * @uses $USER
2277 * @uses $CFG
89dcb99d 2278 * @uses $SESSION
f1af7aaa 2279 * @param string $title Appears at the top of the window
2280 * @param string $heading Appears at the top of the page
2281 * @param array $navigation Array of $navlinks arrays (keys: name, link, type) for use as breadcrumbs links
2282 * @param string $focus Indicates form element to get cursor focus on load eg inputform.password
2283 * @param string $meta Meta tags to be added to the header
89dcb99d 2284 * @param boolean $cache Should this page be cacheable?
f1af7aaa 2285 * @param string $button HTML code for a button (usually for module editing)
2286 * @param string $menu HTML code for a popup menu
89dcb99d 2287 * @param boolean $usexml use XML for this page
f1af7aaa 2288 * @param string $bodytags This text will be included verbatim in the <body> tag (useful for onload() etc)
2289 * @param bool $return If true, return the visible elements of the header instead of echoing them.
d48b00b4 2290 */
36b6bcec 2291function print_header ($title='', $heading='', $navigation='', $focus='',
2292 $meta='', $cache=true, $button='&nbsp;', $menu='',
2293 $usexml=false, $bodytags='', $return=false) {
63f3cbbd 2294
dcf6d93c 2295 global $USER, $CFG, $THEME, $SESSION, $ME, $SITE, $COURSE;
84e3d2cc 2296
432038e0 2297 if (gettype($navigation) == 'string' && strlen($navigation) != 0 && $navigation != 'home') {
364fffda 2298 debugging("print_header() was sent a string as 3rd ($navigation) parameter. "
2299 . "This is deprecated in favour of an array built by build_navigation(). Please upgrade your code.");
2300 }
2301
6ba65fa0 2302 $heading = format_string($heading); // Fix for MDL-8582
84e3d2cc 2303
32613b50 2304/// This makes sure that the header is never repeated twice on a page
f231e867 2305 if (defined('HEADER_PRINTED')) {
ea82d6b6 2306 debugging('print_header() was called more than once - this should not happen. Please check the code for this page closely. Note: error() and redirect() are now safe to call after print_header().');
32613b50 2307 return;
32613b50 2308 }
f231e867 2309 define('HEADER_PRINTED', 'true');
2310
be933850 2311
c3f55692 2312/// Add the required stylesheets
d74d4f20 2313 $stylesheetshtml = '';
2314 foreach ($CFG->stylesheets as $stylesheet) {
2315 $stylesheetshtml .= '<link rel="stylesheet" type="text/css" href="'.$stylesheet.'" />'."\n";
c3f55692 2316 }
d74d4f20 2317 $meta = $stylesheetshtml.$meta;
e89fb61e 2318
84e3d2cc 2319
79f533c3 2320/// Add the meta page from the themes if any were requested
2321
2322 $metapage = '';
2323
2324 if (!isset($THEME->standardmetainclude) || $THEME->standardmetainclude) {
2325 ob_start();
2326 include_once($CFG->dirroot.'/theme/standard/meta.php');
2327 $metapage .= ob_get_contents();
2328 ob_end_clean();
2329 }
2330
2331 if ($THEME->parent && (!isset($THEME->parentmetainclude) || $THEME->parentmetainclude)) {
36e8c122 2332 if (file_exists($CFG->dirroot.'/theme/'.$THEME->parent.'/meta.php')) {
2333 ob_start();
2334 include_once($CFG->dirroot.'/theme/'.$THEME->parent.'/meta.php');
2335 $metapage .= ob_get_contents();
2336 ob_end_clean();
2337 }
79f533c3 2338 }
2339
2340 if (!isset($THEME->metainclude) || $THEME->metainclude) {
36e8c122 2341 if (file_exists($CFG->dirroot.'/theme/'.current_theme().'/meta.php')) {
2342 ob_start();
2343 include_once($CFG->dirroot.'/theme/'.current_theme().'/meta.php');
2344 $metapage .= ob_get_contents();
2345 ob_end_clean();
2346 }
79f533c3 2347 }
2348
2349 $meta = $meta."\n".$metapage;
2350
ca70075a 2351 $meta .= "\n".require_js('',1);
c77f9f07 2352
2353/// Set up some navigation variables
604c6341 2354
c77f9f07 2355 if (is_newnav($navigation)){
9d378732 2356 $home = false;
ac4feb59 2357 } else {
2358 if ($navigation == 'home') {
2359 $home = true;
2360 $navigation = '';
2361 } else {
2362 $home = false;
2363 }
9fa49e22 2364 }
2365
0d741155 2366/// This is another ugly hack to make navigation elements available to print_footer later
2367 $THEME->title = $title;
2368 $THEME->heading = $heading;
2369 $THEME->navigation = $navigation;
2370 $THEME->button = $button;
2371 $THEME->menu = $menu;
2507b2f5 2372 $navmenulist = isset($THEME->navmenulist) ? $THEME->navmenulist : '';
0d741155 2373
b0ccd3fb 2374 if ($button == '') {
2375 $button = '&nbsp;';
9fa49e22 2376 }
2377
2378 if (!$menu and $navigation) {
8a33e371 2379 if (empty($CFG->loginhttps)) {
2380 $wwwroot = $CFG->wwwroot;
2381 } else {
2c3432e6 2382 $wwwroot = str_replace('http:','https:',$CFG->wwwroot);
8a33e371 2383 }
60f9e36e 2384 $menu = user_login_string($COURSE);
9fa49e22 2385 }
67ccec43 2386
b4bac9b6 2387 if (isset($SESSION->justloggedin)) {
2388 unset($SESSION->justloggedin);
2389 if (!empty($CFG->displayloginfailures)) {
8f8ed475 2390 if (!empty($USER->username) and $USER->username != 'guest') {
b4bac9b6 2391 if ($count = count_login_failures($CFG->displayloginfailures, $USER->username, $USER->lastlogin)) {
2392 $menu .= '&nbsp;<font size="1">';
2393 if (empty($count->accounts)) {
2394 $menu .= get_string('failedloginattempts', '', $count);
2395 } else {
2396 $menu .= get_string('failedloginattemptsall', '', $count);
2397 }
51792df0 2398 if (has_capability('moodle/site:viewreports', get_context_instance(CONTEXT_SYSTEM, SITEID))) {
52af9a35 2399 $menu .= ' (<a href="'.$CFG->wwwroot.'/course/report/log/index.php'.
839f2456 2400 '?chooselog=1&amp;id=1&amp;modid=site_errors">'.get_string('logs').'</a>)';
b4bac9b6 2401 }
2402 $menu .= '</font>';
2403 }
2404 }
2405 }
2406 }
9fa49e22 2407
47037513 2408
bc1bbaf4 2409 $meta = '<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />' .
c6f9234c 2410 "\n" . $meta . "\n";
03fe48e7 2411 if (!$usexml) {
bc1bbaf4 2412 @header('Content-Type: text/html; charset=utf-8');
03fe48e7 2413 }
bc1bbaf4 2414 @header('Content-Script-Type: text/javascript');
2415 @header('Content-Style-Type: text/css');
9fa49e22 2416
6575bfd4 2417 //Accessibility: added the 'lang' attribute to $direction, used in theme <html> tag.
2ab4e4b8 2418 $direction = get_html_lang($dir=true);
ab9f24ad 2419
5debee2d 2420 if ($cache) { // Allow caching on "back" (but not on normal clicks)
2421 @header('Cache-Control: private, pre-check=0, post-check=0, max-age=0');
2422 @header('Pragma: no-cache');
772e78be 2423 @header('Expires: ');
5debee2d 2424 } else { // Do everything we can to always prevent clients and proxies caching
03fe48e7 2425 @header('Cache-Control: no-store, no-cache, must-revalidate');
2426 @header('Cache-Control: post-check=0, pre-check=0', false);
2427 @header('Pragma: no-cache');
5debee2d 2428 @header('Expires: Mon, 20 Aug 1969 09:23:00 GMT');
2429 @header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
03fe48e7 2430
5debee2d 2431 $meta .= "\n<meta http-equiv=\"pragma\" content=\"no-cache\" />";
2432 $meta .= "\n<meta http-equiv=\"expires\" content=\"0\" />";
66a51452 2433 }
5debee2d 2434 @header('Accept-Ranges: none');
66a51452 2435
b0b4ffe1 2436 $currentlanguage = current_language();
2437
5ce73257 2438 if (empty($usexml)) {
27f79fda 2439 $direction = ' xmlns="http://www.w3.org/1999/xhtml"'. $direction; // See debug_header
2440 } else {
8f0cd6ef 2441 $mathplayer = preg_match("/MathPlayer/i", $_SERVER['HTTP_USER_AGENT']);
2442 if(!$mathplayer) {
2443 header('Content-Type: application/xhtml+xml');
2444 }
b0ccd3fb 2445 echo '<?xml version="1.0" ?>'."\n";
66a51452 2446 if (!empty($CFG->xml_stylesheets)) {
b0ccd3fb 2447 $stylesheets = explode(';', $CFG->xml_stylesheets);
66a51452 2448 foreach ($stylesheets as $stylesheet) {
b0ccd3fb 2449 echo '<?xml-stylesheet type="text/xsl" href="'. $CFG->wwwroot .'/'. $stylesheet .'" ?>' . "\n";
66a51452 2450 }
2451 }
b0ccd3fb 2452 echo '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1';
e4576482 2453 if (!empty($CFG->xml_doctype_extra)) {
b0ccd3fb 2454 echo ' plus '. $CFG->xml_doctype_extra;
e4576482 2455 }
b0ccd3fb 2456 echo '//' . strtoupper($currentlanguage) . '" "'. $CFG->xml_dtd .'">'."\n";
8f0cd6ef 2457 $direction = " xmlns=\"http://www.w3.org/1999/xhtml\"
2458 xmlns:math=\"http://www.w3.org/1998/Math/MathML\"
8f0cd6ef 2459 xmlns:xlink=\"http://www.w3.org/1999/xlink\"
2460 $direction";
2461 if($mathplayer) {
2462 $meta .= '<object id="mathplayer" classid="clsid:32F66A20-7614-11D4-BD11-00104BD3F987">' . "\n";
b0ccd3fb 2463 $meta .= '<!--comment required to prevent this becoming an empty tag-->'."\n";
2464 $meta .= '</object>'."\n";
8f0cd6ef 2465 $meta .= '<?import namespace="math" implementation="#mathplayer" ?>' . "\n";
2466 }
9fa49e22 2467 }
2468
7bb6d80f 2469 // Clean up the title
2470
268ddd50 2471 $title = format_string($title); // fix for MDL-8582
2eea2cce 2472 $title = str_replace('"', '&quot;', $title);
2473
7bb6d80f 2474 // Create class and id for this page
2475
68d5f00a 2476 page_id_and_class($pageid, $pageclass);
7bb6d80f 2477
60f9e36e 2478 $pageclass .= ' course-'.$COURSE->id;
d6c66e12 2479
84e3d2cc 2480 if (($pageid != 'site-index') && ($pageid != 'course-view') &&
1d41dcd0 2481 (strstr($pageid, 'admin') === FALSE)) {
758027d0 2482 $pageclass .= ' nocoursepage';
2483 }
2484
367e23c2 2485 if (!isloggedin()) {
2486 $pageclass .= ' notloggedin';
2487 }
2488
e299f862 2489 if (!empty($USER->editing)) {
2490 $pageclass .= ' editing';
2491 }
2492
75c3849a 2493 if (!empty($CFG->blocksdrag)) {
2494 $pageclass .= ' drag';
2495 }
2496
70244cc2 2497 $pageclass .= ' dir-'.get_string('thisdirection');
84e3d2cc 2498
b0b4ffe1 2499 $pageclass .= ' lang-'.$currentlanguage;
2500
7bb6d80f 2501 $bodytags .= ' class="'.$pageclass.'" id="'.$pageid.'"';
772e78be 2502
36b6bcec 2503 ob_start();
ea35ab87 2504 include($CFG->header);
36b6bcec 2505 $output = ob_get_contents();
2506 ob_end_clean();
e608dddd 2507
317d5ddc 2508 // Skip to main content, see skip_main_destination().
2509 if ($pageid=='course-view' or $pageid=='site-index' or $pageid=='course-index') {
5c355019 2510 $skiplink = '<a class="skip" href="#maincontent">'.get_string('tocontent', 'access').'</a>';
2511 if (! preg_match('/(.*<div.*?page.>)(.*)/s', $output, $matches)) {
2512 preg_match('/(.*<body.*?>)(.*)/s', $output, $matches);
2513 }
2514 $output = $matches[1]."\n". $skiplink .$matches[2];
317d5ddc 2515 }
5c355019 2516
8af1b1ba 2517 $output = force_strict_header($output);
27f79fda 2518
cdf39255 2519 if (!empty($CFG->messaging)) {
36b6bcec 2520 $output .= message_popup_window();
2521 }
2522
ca70075a 2523 // Add in any extra JavaScript libraries that occurred during the header
2524 $output .= require_js('', 2);
2525
36b6bcec 2526 if ($return) {
2527 return $output;
2528 } else {
2529 echo $output;
cdf39255 2530 }
9fa49e22 2531}
2532
ca70075a 2533define('REQUIREJS_BEFOREHEADER',0);
2534define('REQUIREJS_INHEADER',1);
2535define('REQUIREJS_AFTERHEADER',2);
2536
2537/**
2538 * Used to include JavaScript libraries.
2539 *
2540 * When the $lib parameter is given, the function will ensure that the
2541 * named library is loaded onto the page - either in the HTML <head>,
2542 * just after the header, or at an arbitrary later point in the page,
2543 * depending on where this function is called.
2544 *
2545 * Libraries will not be included more than once, so this works like
2546 * require_once in PHP.
2547 *
2548 * There are two special-case calls to this function which are both used only
2549 * by weblib print_header:
2550 * $extracthtml = 1: this is used before printing the header.
2551 * It returns the script tag code that should go inside the <head>.
2552 * $extracthtml = 2: this is used after printing the header and handles any
2553 * require_js calls that occurred within the header itself.
2554 *
2555 * @param mixed $lib - string or array of strings
2556 * string(s) should be the shortname for the library or the
2557 * full path to the library file.
2558 * @param int $extracthtml Do not set this parameter usually (leave 0), only
2559 * weblib should set this to 1 or 2 in print_header function.
2560 * @return mixed No return value, except when using $extracthtml it returns the html code.
2561 */
2562function require_js($lib,$extracthtml=0) {
2563 global $CFG;
2564 static $loadlibs = array();
2565
2566 static $state = REQUIREJS_BEFOREHEADER;
2567 static $latecode = '';
2568
2569 if (!empty($lib)) {
2570 // Add the lib to the list of libs to be loaded, if it isn't already
2571 // in the list.
2572 if (is_array($lib)) {
2573 foreach($lib as $singlelib) {
2574 require_js($singlelib);
2575 }
2576 } else {
2577 $libpath = ajax_get_lib($lib);
2578 if (array_search($libpath, $loadlibs) === false) {
2579 $loadlibs[] = $libpath;
2580
2581 // For state other than 0 we need to take action as well as just
2582 // adding it to loadlibs
2583 if($state != REQUIREJS_BEFOREHEADER) {
2584 // Get the script statement for this library
2585 $scriptstatement=get_require_js_code(array($libpath));
2586
2587 if($state == REQUIREJS_AFTERHEADER) {
2588 // After the header, print it immediately
2589 print $scriptstatement;
2590 } else {
2591 // Haven't finished the header yet. Add it after the
2592 // header
2593 $latecode .= $scriptstatement;
2594 }
2595 }
2596 }
2597 }
2598 } else if($extracthtml==1) {
2599 if($state !== REQUIREJS_BEFOREHEADER) {
2600 debugging('Incorrect state in require_js (expected BEFOREHEADER): be careful not to call with empty $lib (except in print_header)');
2601 } else {
2602 $state = REQUIREJS_INHEADER;
2603 }
2604
2605 return get_require_js_code($loadlibs);
2606 } else if($extracthtml==2) {
2607 if($state !== REQUIREJS_INHEADER) {
2608 debugging('Incorrect state in require_js (expected INHEADER): be careful not to call with empty $lib (except in print_header)');
2609 return '';
2610 } else {
2611 $state = REQUIREJS_AFTERHEADER;
2612 return $latecode;
2613 }
2614 } else {
2615 debugging('Unexpected value for $extracthtml');
2616 }
2617}
2618
2619/**
2620 * Should not be called directly - use require_js. This function obtains the code
2621 * (script tags) needed to include JavaScript libraries.
2622 * @param array $loadlibs Array of library files to include
2623 * @return string HTML code to include them
2624 */
2625function get_require_js_code($loadlibs) {
2626 global $CFG;
2627 // Return the html needed to load the JavaScript files defined in
2628 // our list of libs to be loaded.
2629 $output = '';
2630 foreach ($loadlibs as $loadlib) {
2631 $output .= '<script type="text/javascript" ';
2632 $output .= " src=\"$loadlib\"></script>\n";
2633 if ($loadlib == $CFG->wwwroot.'/lib/yui/logger/logger-min.js') {
2634 // Special case, we need the CSS too.
2635 $output .= '<link type="text/css" rel="stylesheet" ';
2636 $output .= " href=\"{$CFG->wwwroot}/lib/yui/logger/assets/logger.css\" />\n";
2637 }
2638 }
2639 return $output;
2640}
2641
2642
27f79fda 2643/**
2644 * Debugging aid: serve page as 'application/xhtml+xml' where possible,
2645 * and substitute the XHTML strict document type.
2646 * Note, requires the 'xmlns' fix in function print_header above.
2647 * See: http://tracker.moodle.org/browse/MDL-7883
2648 * TODO:
2649 */
8af1b1ba 2650function force_strict_header($output) {
27f79fda 2651 global $CFG;
2652 $strict = '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">';
2653 $xsl = '/lib/xhtml.xsl';
2654
8cf6cb90 2655 if (!headers_sent() && !empty($CFG->xmlstrictheaders)) { // With xml strict headers, the browser will barf
27f79fda 2656 $ctype = 'Content-Type: ';
2657 $prolog= "<?xml version='1.0' encoding='utf-8'?>\n";
2658
5ce73257 2659 if (isset($_SERVER['HTTP_ACCEPT'])
27f79fda 2660 && false !== strpos($_SERVER['HTTP_ACCEPT'], 'application/xhtml+xml')) {
2661 //|| false !== strpos($_SERVER['HTTP_USER_AGENT'], 'Safari') //Safari "Entity 'copy' not defined".
2662 // Firefox et al.
2663 $ctype .= 'application/xhtml+xml';
2664 $prolog .= "<!--\n DEBUG: $ctype \n-->\n";
2665
2666 } else if (file_exists($CFG->dirroot.$xsl)
2667 && preg_match('/MSIE.*Windows NT/', $_SERVER['HTTP_USER_AGENT'])) {
2668 // XSL hack for IE 5+ on Windows.
2669 //$www_xsl = preg_replace('/(http:\/\/.+?\/).*/', '', $CFG->wwwroot) .$xsl;
2670 $www_xsl = $CFG->wwwroot .$xsl;
2671 $ctype .= 'application/xml';
2672 $prolog .= "<?xml-stylesheet type='text/xsl' href='$www_xsl'?>\n";
2673 $prolog .= "<!--\n DEBUG: $ctype \n-->\n";
2674
2675 } else {
2676 //ELSE: Mac/IE, old/non-XML browsers.
2677 $ctype .= 'text/html';
2678 $prolog = '';
2679 }
2680 @header($ctype.'; charset=utf-8');
2681 $output = $prolog . $output;
2682
2683 // Test parser error-handling.
2684 if (isset($_GET['error'])) {
2685 $output .= "__ TEST: XML well-formed error < __\n";
2686 }
2687 }
8af1b1ba 2688
84dec541 2689 $output = preg_replace('/(<!DOCTYPE.+?>)/s', $strict, $output); // Always change the DOCTYPE to Strict 1.0
8af1b1ba 2690
27f79fda 2691 return $output;
2692}
2693
2694
2695
d48b00b4 2696/**
2697 * This version of print_header is simpler because the course name does not have to be
2698 * provided explicitly in the strings. It can be used on the site page as in courses
2699 * Eventually all print_header could be replaced by print_header_simple
2700 *
89dcb99d 2701 * @param string $title Appears at the top of the window
2702 * @param string $heading Appears at the top of the page
2703 * @param string $navigation Premade navigation string (for use as breadcrumbs links)
2704 * @param string $focus Indicates form element to get cursor focus on load eg inputform.password
2705 * @param string $meta Meta tags to be added to the header
2706 * @param boolean $cache Should this page be cacheable?
2707 * @param string $button HTML code for a button (usually for module editing)
2708 * @param string $menu HTML code for a popup menu
2709 * @param boolean $usexml use XML for this page
2710 * @param string $bodytags This text will be included verbatim in the <body> tag (useful for onload() etc)
36b6bcec 2711 * @param bool $return If true, return the visible elements of the header instead of echoing them.
d48b00b4 2712 */
b0ccd3fb 2713function print_header_simple($title='', $heading='', $navigation='', $focus='', $meta='',
36b6bcec 2714 $cache=true, $button='&nbsp;', $menu='', $usexml=false, $bodytags='', $return=false) {
90fcc576 2715
5ce73257 2716 global $COURSE, $CFG;
90fcc576 2717
84e3d2cc 2718 // If old style nav prepend course short name otherwise leave $navigation object alone
ac4feb59 2719 if (!is_newnav($navigation)) {
7243c7c8 2720 if ($COURSE->id != SITEID) {
2721 $shortname = '<a href="'.$CFG->wwwroot.'/course/view.php?id='. $COURSE->id .'">'. $COURSE->shortname .'</a> ->';
2722 $navigation = $shortname.' '.$navigation;
2723 }
ac4feb59 2724 }
2725
2726 $output = print_header($COURSE->shortname .': '. $title, $COURSE->fullname .' '. $heading, $navigation, $focus, $meta,
da4124be 2727 $cache, $button, $menu, $usexml, $bodytags, true);
36b6bcec 2728
2729 if ($return) {
2730 return $output;
2731 } else {
2732 echo $output;
2733 }
90fcc576 2734}
629b5885 2735
2736
d48b00b4 2737/**
2738 * Can provide a course object to make the footer contain a link to
2739 * to the course home page, otherwise the link will go to the site home
2740 *
2741 * @uses $CFG
2742 * @uses $USER
89dcb99d 2743 * @param course $course {@link $COURSE} object containing course information
2744 * @param ? $usercourse ?
d48b00b4 2745 * @todo Finish documenting this function
2746 */
469b6501 2747function print_footer($course=NULL, $usercourse=NULL, $return=false) {
dcf6d93c 2748 global $USER, $CFG, $THEME, $COURSE;
9fa49e22 2749
1ae083e4 2750 if (defined('ADMIN_EXT_HEADER_PRINTED') and !defined('ADMIN_EXT_FOOTER_PRINTED')) {
635773c6 2751 admin_externalpage_print_footer();
2752 return;
1ae083e4 2753 }
2754
9fa49e22 2755/// Course links
2756 if ($course) {
a789577b 2757 if (is_string($course) && $course == 'none') { // Don't print any links etc
b3a2b9dd 2758 $homelink = '';
2759 $loggedinas = '';
0d741155 2760 $home = false;
a789577b 2761 } else if (is_string($course) && $course == 'home') { // special case for site home page - please do not remove
b3a2b9dd 2762 $course = get_site();
a77ac3dc 2763 $homelink = '<div class="sitelink">'.
244f6f32 2764 '<a title="moodle '. $CFG->release .' ('. $CFG->version .')" href="http://moodle.org/">'.
3572b8b1 2765 '<img style="width:100px;height:30px" src="pix/moodlelogo.gif" alt="moodlelogo" /></a></div>';
0d741155 2766 $home = true;
9fa49e22 2767 } else {
fa738731 2768 $homelink = '<div class="homelink"><a '.$CFG->frametarget.' href="'.$CFG->wwwroot.
6ba65fa0 2769 '/course/view.php?id='.$course->id.'">'.format_string($course->shortname).'</a></div>';
0d741155 2770 $home = false;
9fa49e22 2771 }
2772 } else {
b3a2b9dd 2773 $course = get_site(); // Set course as site course by default
fa738731 2774 $homelink = '<div class="homelink"><a '.$CFG->frametarget.' href="'.$CFG->wwwroot.'/">'.get_string('home').'</a></div>';
0d741155 2775 $home = false;
9fa49e22 2776 }
2777
0d741155 2778/// Set up some other navigation links (passed from print_header by ugly hack)
2507b2f5 2779 $menu = isset($THEME->menu) ? str_replace('navmenu', 'navmenufooter', $THEME->menu) : '';
2780 $title = isset($THEME->title) ? $THEME->title : '';
2781 $button = isset($THEME->button) ? $THEME->button : '';
2782 $heading = isset($THEME->heading) ? $THEME->heading : '';
2783 $navigation = isset($THEME->navigation) ? $THEME->navigation : '';
2784 $navmenulist = isset($THEME->navmenulist) ? $THEME->navmenulist : '';
0d741155 2785
f940ee41 2786
b3a2b9dd 2787/// Set the user link if necessary
2788 if (!$usercourse and is_object($course)) {
1f2eec7b 2789 $usercourse = $course;
2790 }
2791
b3a2b9dd 2792 if (!isset($loggedinas)) {
2793 $loggedinas = user_login_string($usercourse, $USER);
2794 }
2795
0d741155 2796 if ($loggedinas == $menu) {
9e0d1983 2797 $menu = '';
0d741155 2798 }
2799
0ad439bb 2800/// there should be exactly one open container 'content'
2801 if (open_containers() != 1) {
2802 debugging('Unexpected number of open containers: '.open_containers().', expecting 1.', DEBUG_DEVELOPER);
2803 }
2804
b8cea9b2 2805/// Provide some performance info if required
c2fd9e95 2806 $performanceinfo = '';
afd2b299 2807 if (defined('MDL_PERF') || (!empty($CFG->perfdebug) and $CFG->perfdebug > 7)) {
c2fd9e95 2808 $perf = get_performance_info();
cf1348ca 2809 if (defined('MDL_PERFTOLOG') && !function_exists('register_shutdown_function')) {
853df85e 2810 error_log("PERF: " . $perf['txt']);
2811 }
ea82d6b6 2812 if (defined('MDL_PERFTOFOOT') || debugging() || $CFG->perfdebug > 7) {
c2fd9e95 2813 $performanceinfo = $perf['html'];
2814 }
572fe9ab 2815 }
b8cea9b2 2816
b3a2b9dd 2817/// Include the actual footer file
a282d0ff 2818
469b6501 2819 ob_start();
ea35ab87 2820 include($CFG->footer);
469b6501 2821 $output = ob_get_contents();
2822 ob_end_clean();
a9a9bdba 2823
469b6501 2824 if ($return) {
2825 return $output;
2826 } else {
2827 echo $output;
2828 }
a282d0ff 2829}
2830
c3f55692 2831/**
2832 * Returns the name of the current theme
2833 *
2834 * @uses $CFG
8f8210b3 2835 * @uses $USER
2836 * @uses $SESSION
2837 * @uses $COURSE
2838 * @uses $FULLME
c3f55692 2839 * @return string
2840 */
2841function current_theme() {
8f8210b3 2842 global $CFG, $USER, $SESSION, $COURSE, $FULLME;
2843
2844 if (empty($CFG->themeorder)) {
2845 $themeorder = array('page', 'course', 'category', 'session', 'user', 'site');
2846 } else {
2847 $themeorder = $CFG->themeorder;
2848 }
2849
178bcb75 2850 if (isloggedin() and $USER->mnethostid != $CFG->mnet_localhost_id) {
1673e134 2851 require_once($CFG->dirroot.'/mnet/peer.php');
2852 $mnet_peer = new mnet_peer();
2853 $mnet_peer->set_id($USER->mnethostid);
2854 }
2855
8f8210b3 2856 $theme = '';
2857 foreach ($themeorder as $themetype) {
2858
2859 if (!empty($theme)) continue;
84e3d2cc 2860
8f8210b3 2861 switch ($themetype) {
2862 case 'page': // Page theme is for special page-only themes set by code
2863 if (!empty($CFG->pagetheme)) {
2864 $theme = $CFG->pagetheme;
2865 }
2866 break;
2867 case 'course':
2868 if (!empty($CFG->allowcoursethemes) and !empty($COURSE->theme)) {
2869 $theme = $COURSE->theme;
2870 }
2871 break;
2872 case 'category':
2873 if (!empty($CFG->allowcategorythemes)) {
2874 /// Nasty hack to check if we're in a category page
2875 if (stripos($FULLME, 'course/category.php') !== false) {
2876 global $id;
2877 if (!empty($id)) {
2878 $theme = current_category_theme($id);
2879 }
2880 /// Otherwise check if we're in a course that has a category theme set
2881 } else if (!empty($COURSE->category)) {
2882 $theme = current_category_theme($COURSE->category);
2883 }
2884 }
2885 break;
2886 case 'session':
2887 if (!empty($SESSION->theme)) {
2888 $theme = $SESSION->theme;
2889 }
2890 break;
2891 case 'user':
2892 if (!empty($CFG->allowuserthemes) and !empty($USER->theme)) {
178bcb75 2893 if (isloggedin() and $USER->mnethostid != $CFG->mnet_localhost_id && $mnet_peer->force_theme == 1 && $mnet_peer->theme != '') {
1673e134 2894 $theme = $mnet_peer->theme;
2895 } else {
2896 $theme = $USER->theme;
2897 }
8f8210b3 2898 }
2899 break;
2900 case 'site':
178bcb75 2901 if (isloggedin() and $USER->mnethostid != $CFG->mnet_localhost_id && $mnet_peer->force_theme == 1 && $mnet_peer->theme != '') {
1673e134 2902 $theme = $mnet_peer->theme;
2903 } else {
2904 $theme = $CFG->theme;
2905 }
8f8210b3 2906 break;
2907 default:
2908 /// do nothing
2909 }
2910 }
c3f55692 2911
8f8210b3 2912/// A final check in case 'site' was not included in $CFG->themeorder
2913 if (empty($theme)) {
2914 $theme = $CFG->theme;
2915 }
c3f55692 2916
8f8210b3 2917 return $theme;
2918}
c3f55692 2919
8f8210b3 2920/**
2921 * Retrieves the category theme if one exists, otherwise checks the parent categories.
2922 * Recursive function.
2923 *
2924 * @uses $COURSE
2925 * @param integer $categoryid id of the category to check
2926 * @return string theme name
2927 */
2928function current_category_theme($categoryid=0) {
2929 global $COURSE;
84e3d2cc 2930
8f8210b3 2931/// Use the COURSE global if the categoryid not set
2932 if (empty($categoryid)) {
2933 if (!empty($COURSE->category)) {
2934 $categoryid = $COURSE->category;
2935 } else {
2936 return false;
2937 }
2938 }
84e3d2cc 2939
8f8210b3 2940/// Retrieve the current category
2941 if ($category = get_record('course_categories', 'id', $categoryid)) {
84e3d2cc 2942
8f8210b3 2943 /// Return the category theme if it exists
2944 if (!empty($category->theme)) {
2945 return $category->theme;
c3f55692 2946
8f8210b3 2947 /// Otherwise try the parent category if one exists
2948 } else if (!empty($category->parent)) {
2949 return current_category_theme($category->parent);
2950 }
c3f55692 2951
8f8210b3 2952/// Return false if we can't find the category record
c3f55692 2953 } else {
8f8210b3 2954 return false;
c3f55692 2955 }
2956}
2957
d48b00b4 2958/**
2959 * This function is called by stylesheets to set up the header
2960 * approriately as well as the current path
2961 *
2962 * @uses $CFG
89dcb99d 2963 * @param int $lastmodified ?
2964 * @param int $lifetime ?
2965 * @param string $thename ?
d48b00b4 2966 */
f31701c4 2967function style_sheet_setup($lastmodified=0, $lifetime=300, $themename='', $forceconfig='', $lang='') {
6535be85 2968
9c4e6e21 2969 global $CFG, $THEME;
ab9f24ad 2970
a2e2bf64 2971 // Fix for IE6 caching - we don't want the filemtime('styles.php'), instead use now.
2972 $lastmodified = time();
2973
b0ccd3fb 2974 header('Last-Modified: ' . gmdate("D, d M Y H:i:s", $lastmodified) . ' GMT');
2975 header('Expires: ' . gmdate("D, d M Y H:i:s", time() + $lifetime) . ' GMT');
a2e2bf64 2976 header('Cache-Control: max-age='. $lifetime);
b0ccd3fb 2977 header('Pragma: ');
2978 header('Content-type: text/css'); // Correct MIME type
6535be85 2979
909ec807 2980 $DEFAULT_SHEET_LIST = array('styles_layout', 'styles_fonts', 'styles_color');
9c4e6e21 2981
2982 if (empty($themename)) {
2983 $themename = current_theme(); // So we have something. Normally not needed.
ab25ce31 2984 } else {
2985 $themename = clean_param($themename, PARAM_SAFEDIR);
9c4e6e21 2986 }
2987
2988 if (!empty($forceconfig)) { // Page wants to use the config from this theme instead
2989 unset($THEME);
a44091bf 2990 include($CFG->themedir.'/'.$forceconfig.'/'.'config.php');
9c4e6e21 2991 }
2992
2993/// If this is the standard theme calling us, then find out what sheets we need
2994
2995 if ($themename == 'standard') {
2996 if (!isset($THEME->standardsheets) or $THEME->standardsheets === true) { // Use all the sheets we have
2997 $THEME->sheets = $DEFAULT_SHEET_LIST;
2998 } else if (empty($THEME->standardsheets)) { // We can stop right now!
2999 echo "/***** Nothing required from this stylesheet by main theme *****/\n\n";
3000 exit;
3001 } else { // Use the provided subset only
3002 $THEME->sheets = $THEME->standardsheets;
3003 }
3004
3005/// If we are a parent theme, then check for parent definitions
3006
3007 } else if (!empty($THEME->parent) && $themename == $THEME->parent) {
3008 if (!isset($THEME->parentsheets) or $THEME->parentsheets === true) { // Use all the sheets we have
3009 $THEME->sheets = $DEFAULT_SHEET_LIST;
3010 } else if (empty($THEME->parentsheets)) { // We can stop right now!
3011 echo "/***** Nothing required from this stylesheet by main theme *****/\n\n";
3012 exit;
3013 } else { // Use the provided subset only
3014 $THEME->sheets = $THEME->parentsheets;
3015 }
3016 }
3017
3018/// Work out the last modified date for this theme
3019
3020 foreach ($THEME->sheets as $sheet) {
a44091bf 3021 if (file_exists($CFG->themedir.'/'.$themename.'/'.$sheet.'.css')) {
3022 $sheetmodified = filemtime($CFG->themedir.'/'.$themename.'/'.$sheet.'.css');
9c4e6e21 3023 if ($sheetmodified > $lastmodified) {
3024 $lastmodified = $sheetmodified;
3025 }
3026 }
6535be85 3027 }
3028
6535be85 3029
6ba172fb 3030/// Get a list of all the files we want to include
3031 $files = array();
3032
3033 foreach ($THEME->sheets as $sheet) {
3034 $files[] = array($CFG->themedir, $themename.'/'.$sheet.'.css');
3035 }
3036
3037 if ($themename == 'standard') { // Add any standard styles included in any modules
3038 if (!empty($THEME->modsheets)) { // Search for styles.php within activity modules
3039 if ($mods = get_list_of_plugins('mod')) {
3040 foreach ($mods as $mod) {
3041 if (file_exists($CFG->dirroot.'/mod/'.$mod.'/styles.php')) {
3042 $files[] = array($CFG->dirroot, '/mod/'.$mod.'/styles.php');
3043 }
08396bb2 3044 }
3045 }
3046 }
a2b3f884 3047
6ba172fb 3048 if (!empty($THEME->blocksheets)) { // Search for styles.php within block modules
3049 if ($mods = get_list_of_plugins('blocks')) {
3050 foreach ($mods as $mod) {
3051 if (file_exists($CFG->dirroot.'/blocks/'.$mod.'/styles.php')) {
3052 $files[] = array($CFG->dirroot, '/blocks/'.$mod.'/styles.php');
3053 }
08396bb2 3054 }
3055 }
3056 }
a2b3f884 3057
ae628043 3058 if (!isset($THEME->courseformatsheets) || $THEME->courseformatsheets) { // Search for styles.php in course formats
3059 if ($mods = get_list_of_plugins('format','',$CFG->dirroot.'/course')) {
3060 foreach ($mods as $mod) {
3061 if (file_exists($CFG->dirroot.'/course/format/'.$mod.'/styles.php')) {
3062 $files[] = array($CFG->dirroot, '/course/format/'.$mod.'/styles.php');
3063 }
3064 }
3065 }
3066 }
3067
1273d7dd 3068 if (!isset($THEME->gradereportsheets) || $THEME->gradereportsheets) { // Search for styles.php in grade reports
3069 if ($reports = get_list_of_plugins('grade/report')) {
3070 foreach ($reports as $report) {
3071 if (file_exists($CFG->dirroot.'/grade/report/'.$report.'/styles.php')) {
3072 $files[] = array($CFG->dirroot, '/grade/report/'.$report.'/styles.php');
3073 }
3074 }
3075 }
3076 }
3077
6ba172fb 3078 if (!empty($THEME->langsheets)) { // Search for styles.php within the current language
6ba172fb 3079 if (file_exists($CFG->dirroot.'/lang/'.$lang.'/styles.php')) {
3080 $files[] = array($CFG->dirroot, '/lang/'.$lang.'/styles.php');
3081 }
3082 }
08396bb2 3083 }
3084
6ba172fb 3085 if ($files) {
3086 /// Produce a list of all the files first
3087 echo '/**************************************'."\n";
3088 echo ' * THEME NAME: '.$themename."\n *\n";
3089 echo ' * Files included in this sheet:'."\n *\n";
3090 foreach ($files as $file) {
3091 echo ' * '.$file[1]."\n";
08396bb2 3092 }
6ba172fb 3093 echo ' **************************************/'."\n\n";
08396bb2 3094
6ba172fb 3095
16f0af59 3096 /// check if csscobstants is set
3097 if (!empty($THEME->cssconstants)) {
3098 require_once("$CFG->libdir/cssconstants.php");
3099 /// Actually collect all the files in order.
3100 $css = '';
3101 foreach ($files as $file) {
3102 $css .= '/***** '.$file[1].' start *****/'."\n\n";
3103 $css .= file_get_contents($file[0].'/'.$file[1]);
3104 $ccs .= '/***** '.$file[1].' end *****/'."\n\n";
3105 }
3106 /// replace css_constants with their values
3107 echo replace_cssconstants($css);
3108 } else {
3109 /// Actually output all the files in order.
d0c92410 3110 if (empty($CFG->CSSEdit) && empty($THEME->CSSEdit)) {
3111 foreach ($files as $file) {
3112 echo '/***** '.$file[1].' start *****/'."\n\n";
3113 @include_once($file[0].'/'.$file[1]);
3114 echo '/***** '.$file[1].' end *****/'."\n\n";
3115 }
3116 } else {
3117 foreach ($files as $file) {
3118 echo '/* @group '.$file[1].' */'."\n\n";
3119 if (strstr($file[1], '.css') !== FALSE) {
3120 echo '@import url("'.$CFG->themewww.'/'.$file[1].'");'."\n\n";
3121 } else {
3122 @include_once($file[0].'/'.$file[1]);
3123 }
3124 echo '/* @end */'."\n\n";
3125 }
16f0af59 3126 }
6ba172fb 3127 }
9c4e6e21 3128 }
3129
a44091bf 3130 return $CFG->themewww.'/'.$themename; // Only to help old themes (1.4 and earlier)
6535be85 3131}
3132
9c4e6e21 3133
3134function theme_setup($theme = '', $params=NULL) {
d74d4f20 3135/// Sets up global variables related to themes
3136
9152fc99 3137 global $CFG, $THEME, $SESSION, $USER, $HTTPSPAGEREQUIRED;
d74d4f20 3138
3139 if (empty($theme)) {
3140 $theme = current_theme();
3141 }
9c4e6e21 3142
09ad59dc 3143/// If the theme doesn't exist for some reason then revert to standardwhite
a44091bf 3144 if (!file_exists($CFG->themedir .'/'. $theme .'/config.php')) {
09ad59dc 3145 $CFG->theme = $theme = 'standardwhite';
3146 }
3147
55b734fb 3148/// Load up the theme config
3149 $THEME = NULL; // Just to be sure
a44091bf 3150 include($CFG->themedir .'/'. $theme .'/config.php'); // Main config for current theme
55b734fb 3151
9c4e6e21 3152/// Put together the parameters
3153 if (!$params) {
3154 $params = array();
3155 }
3572b8b1 3156
56766f85 3157 if ($theme != $CFG->theme) {
3158 $params[] = 'forceconfig='.$theme;
9c4e6e21 3159 }
55b734fb 3160
3161/// Force language too if required
3162 if (!empty($THEME->langsheets)) {
3163 $params[] = 'lang='.current_language();
3164 }
3165
3572b8b1 3166
55b734fb 3167/// Convert params to string
9c4e6e21 3168 if ($params) {
55b734fb 3169 $paramstring = '?'.implode('&', $params);
d74d4f20 3170 } else {
9c4e6e21 3171 $paramstring = '';
d74d4f20 3172 }
3173
9c4e6e21 3174/// Set up image paths
24c66531 3175 if(isset($CFG->smartpix) && $CFG->smartpix==1) {
3176 if($CFG->slasharguments) { // Use this method if possible for better caching
3177 $extra='';
3178 } else {
3179 $extra='?file=';
3180 }
84e3d2cc 3181
24c66531 3182 $CFG->pixpath = $CFG->wwwroot. '/pix/smartpix.php'.$extra.'/'.$theme;
3183 $CFG->modpixpath = $CFG->wwwroot .'/pix/smartpix.php'.$extra.'/'.$theme.'/mod';
3184 } else if (empty($THEME->custompix)) { // Could be set in the above file
d74d4f20 3185 $CFG->pixpath = $CFG->wwwroot .'/pix';
3186 $CFG->modpixpath = $CFG->wwwroot .'/mod';
3187 } else {
a44091bf 3188 $CFG->pixpath = $CFG->themewww .'/'. $theme .'/pix';
3189 $CFG->modpixpath = $CFG->themewww .'/'. $theme .'/pix/mod';
d74d4f20 3190 }
3191
9c4e6e21 3192/// Header and footer paths
a44091bf 3193 $CFG->header = $CFG->themedir .'/'. $theme .'/header.html';
3194 $CFG->footer = $CFG->themedir .'/'. $theme .'/footer.html';
d74d4f20 3195
9c4e6e21 3196/// Define stylesheet loading order
d74d4f20 3197 $CFG->stylesheets = array();
3198 if ($theme != 'standard') { /// The standard sheet is always loaded first
a44091bf 3199 $CFG->stylesheets[] = $CFG->themewww.'/standard/styles.php'.$paramstring;
d74d4f20 3200 }
3201 if (!empty($THEME->parent)) { /// Parent stylesheets are loaded next
a44091bf 3202 $CFG->stylesheets[] = $CFG->themewww.'/'.$THEME->parent.'/styles.php'.$paramstring;
d74d4f20 3203 }
a44091bf 3204 $CFG->stylesheets[] = $CFG->themewww.'/'.$theme.'/styles.php'.$paramstring;
d74d4f20 3205
9152fc99 3206/// We have to change some URLs in styles if we are in a $HTTPSPAGEREQUIRED page
3207 if (!empty($HTTPSPAGEREQUIRED)) {
3208 $CFG->themewww = str_replace('http:', 'https:', $CFG->themewww);
3209 $CFG->pixpath = str_replace('http:', 'https:', $CFG->pixpath);
3210 $CFG->modpixpath = str_replace('http:', 'https:', $CFG->modpixpath);
3211 foreach ($CFG->stylesheets as $key => $stylesheet) {
3212 $CFG->stylesheets[$key] = str_replace('http:', 'https:', $stylesheet);
3213 }
3214 }
3215
b2118095 3216// RTL support - only for RTL languages, add RTL CSS
3217 if (get_string('thisdirection') == 'rtl') {
3218 $CFG->stylesheets[] = $CFG->themewww.'/standard/rtl.css'.$paramstring;
f31701c4 3219 $CFG->stylesheets[] = $CFG->themewww.'/'.$theme.'/rtl.css'.$paramstring;
b2118095 3220 }
d74d4f20 3221}
3222
c3f55692 3223
d48b00b4 3224/**
3225 * Returns text to be displayed to the user which reflects their login status
3226 *
3227 * @uses $CFG
3228 * @uses $USER
89dcb99d 3229 * @param course $course {@link $COURSE} object containing course information
3230 * @param user $user {@link $USER} object containing user information
3231 * @return string
d48b00b4 3232 */
c44d5d42 3233function user_login_string($course=NULL, $user=NULL) {
3234 global $USER, $CFG, $SITE;
a282d0ff 3235
86a1ba04 3236 if (empty($user) and !empty($USER->id)) {
a282d0ff 3237 $user = $USER;
3238 }
3239
c44d5d42 3240 if (empty($course)) {
3241 $course = $SITE;
3242 }
3243
f6f66b03 3244 if (!empty($user->realuser)) {
b0ccd3fb 3245 if ($realuser = get_record('user', 'id', $user->realuser)) {
2d71e8ee 3246 $fullname = fullname($realuser, true);
fa738731 3247 $realuserinfo = " [<a $CFG->frametarget
f6f66b03 3248 href=\"$CFG->wwwroot/course/loginas.php?id=$course->id&amp;return=1&amp;sesskey=".sesskey()."\">$fullname</a>] ";
9fa49e22 3249 }
9d378732 3250 } else {
b0ccd3fb 3251 $realuserinfo = '';
9fa49e22 3252 }
3253
87180677 3254 if (empty($CFG->loginhttps)) {
3255 $wwwroot = $CFG->wwwroot;
3256 } else {
2c3432e6 3257 $wwwroot = str_replace('http:','https:',$CFG->wwwroot);
87180677 3258 }
3259
8743f4f3 3260 if (empty($course->id)) {
3261 // $course->id is not defined during installation
3262 return '';
f6f66b03 3263 } else if (!empty($user->id)) {
2d07587b 3264 $context = get_context_instance(CONTEXT_COURSE, $course->id);
3265
2d71e8ee 3266 $fullname = fullname($user, true);
fa738731 3267 $username = "<a $CFG->frametarget href=\"$CFG->wwwroot/user/view.php?id=$user->id&amp;course=$course->id\">$fullname</a>";
03d820c7 3268 if (is_mnet_remote_user($user) and $idprovider = get_record('mnet_host', 'id', $user->mnethostid)) {
fa738731 3269 $username .= " from <a $CFG->frametarget href=\"{$idprovider->wwwroot}\">{$idprovider->name}</a>";
03d820c7 3270 }
8f8ed475 3271 if (isset($user->username) && $user->username == 'guest') {
158de846 3272 $loggedinas = $realuserinfo.get_string('loggedinasguest').
fa738731 3273 " (<a $CFG->frametarget href=\"$wwwroot/login/index.php\">".get_string('login').'</a>)';
b1178725 3274 } else if (!empty($user->access['rsw'][$context->path])) {
91ea292e 3275 $rolename = '';
b1178725 3276 if ($role = get_record('role', 'id', $user->access['rsw'][$context->path])) {
91ea292e 3277 $rolename = ': '.format_string($role->name);
3278 }
3279 $loggedinas = get_string('loggedinas', 'moodle', $username).$rolename.
fa738731 3280 " (<a $CFG->frametarget
91ea292e 3281 href=\"$CFG->wwwroot/course/view.php?id=$course->id&amp;switchrole=0&amp;sesskey=".sesskey()."\">".get_string('switchrolereturn').'</a>)';
0ae7e6f4 3282 } else {
d5a01638 3283 $loggedinas = $realuserinfo.get_string('loggedinas', 'moodle', $username).' '.
18b07efa 3284 " (<a $CFG->frametarget href=\"$CFG->wwwroot/login/logout.php?sesskey=".sesskey()."\">".get_string('logout').'</a>)';
0ae7e6f4 3285 }
9fa49e22 3286 } else {
b0ccd3fb 3287 $loggedinas = get_string('loggedinnot', 'moodle').
fa738731 3288 " (<a $CFG->frametarget href=\"$wwwroot/login/index.php\">".get_string('login').'</a>)';
9fa49e22 3289 }
d3593a67 3290 return '<div class="logininfo">'.$loggedinas.'</div>';
9fa49e22 3291}
3292
d48b00b4 3293/**
57100a90 3294 * Tests whether $THEME->rarrow, $THEME->larrow have been set (theme/-/config.php).
3295 * If not it applies sensible defaults.
d48b00b4 3296 *
57100a90