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