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