MDL-15942 - separate data escaped for database entry from unescaped data
[moodle-linuxchix.git] / lib / weblib.php
blob9bd350f00ca81f2a80dcc30a35076ee29ff60073
1 <?php // $Id$
3 ///////////////////////////////////////////////////////////////////////////
4 // //
5 // NOTICE OF COPYRIGHT //
6 // //
7 // Moodle - Modular Object-Oriented Dynamic Learning Environment //
8 // http://moodle.com //
9 // //
10 // Copyright (C) 1999 onwards Martin Dougiamas http://dougiamas.com //
11 // //
12 // This program is free software; you can redistribute it and/or modify //
13 // it under the terms of the GNU General Public License as published by //
14 // the Free Software Foundation; either version 2 of the License, or //
15 // (at your option) any later version. //
16 // //
17 // This program is distributed in the hope that it will be useful, //
18 // but WITHOUT ANY WARRANTY; without even the implied warranty of //
19 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the //
20 // GNU General Public License for more details: //
21 // //
22 // http://www.gnu.org/copyleft/gpl.html //
23 // //
24 ///////////////////////////////////////////////////////////////////////////
26 /**
27 * Library of functions for web output
29 * Library of all general-purpose Moodle PHP functions and constants
30 * that produce HTML output
32 * Other main libraries:
33 * - datalib.php - functions that access the database.
34 * - moodlelib.php - general-purpose Moodle functions.
35 * @author Martin Dougiamas
36 * @version $Id$
37 * @license http://www.gnu.org/copyleft/gpl.html GNU Public License
38 * @package moodlecore
41 /// We are going to uses filterlib functions here
42 require_once("$CFG->libdir/filterlib.php");
44 require_once("$CFG->libdir/ajax/ajaxlib.php");
46 /// Constants
48 /// Define text formatting types ... eventually we can add Wiki, BBcode etc
50 /**
51 * Does all sorts of transformations and filtering
53 define('FORMAT_MOODLE', '0'); // Does all sorts of transformations and filtering
55 /**
56 * Plain HTML (with some tags stripped)
58 define('FORMAT_HTML', '1'); // Plain HTML (with some tags stripped)
60 /**
61 * Plain text (even tags are printed in full)
63 define('FORMAT_PLAIN', '2'); // Plain text (even tags are printed in full)
65 /**
66 * Wiki-formatted text
67 * Deprecated: left here just to note that '3' is not used (at the moment)
68 * and to catch any latent wiki-like text (which generates an error)
70 define('FORMAT_WIKI', '3'); // Wiki-formatted text
72 /**
73 * Markdown-formatted text http://daringfireball.net/projects/markdown/
75 define('FORMAT_MARKDOWN', '4'); // Markdown-formatted text http://daringfireball.net/projects/markdown/
77 /**
78 * TRUSTTEXT marker - if present in text, text cleaning should be bypassed
80 define('TRUSTTEXT', '#####TRUSTTEXT#####');
83 /**
84 * Javascript related defines
86 define('REQUIREJS_BEFOREHEADER', 0);
87 define('REQUIREJS_INHEADER', 1);
88 define('REQUIREJS_AFTERHEADER', 2);
90 /**
91 * Allowed tags - string of html tags that can be tested against for safe html tags
92 * @global string $ALLOWED_TAGS
94 global $ALLOWED_TAGS;
95 $ALLOWED_TAGS =
96 '<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>';
98 /**
99 * Allowed protocols - array of protocols that are safe to use in links and so on
100 * @global string $ALLOWED_PROTOCOLS
102 $ALLOWED_PROTOCOLS = array('http', 'https', 'ftp', 'news', 'mailto', 'rtsp', 'teamspeak', 'gopher', 'mms',
103 'color', 'callto', 'cursor', 'text-align', 'font-size', 'font-weight', 'font-style', 'font-family',
104 'border', 'margin', 'padding', 'background', 'text-decoration'); // CSS as well to get through kses
107 /// Functions
110 * Add quotes to HTML characters
112 * Returns $var with HTML characters (like "<", ">", etc.) properly quoted.
113 * This function is very similar to {@link p()}
115 * @param string $var the string potentially containing HTML characters
116 * @param boolean $strip to decide if we want to strip slashes or no. Default to false.
117 * true should be used to print data from forms and false for data from DB.
118 * @return string
120 function s($var, $strip=false) {
122 if ($var == '0') { // for integer 0, boolean false, string '0'
123 return '0';
126 if ($strip) {
127 return preg_replace("/&amp;(#\d+);/i", "&$1;", htmlspecialchars(stripslashes_safe($var)));
128 } else {
129 return preg_replace("/&amp;(#\d+);/i", "&$1;", htmlspecialchars($var));
134 * Add quotes to HTML characters
136 * Prints $var with HTML characters (like "<", ">", etc.) properly quoted.
137 * This function is very similar to {@link s()}
139 * @param string $var the string potentially containing HTML characters
140 * @param boolean $strip to decide if we want to strip slashes or no. Default to false.
141 * true should be used to print data from forms and false for data from DB.
142 * @return string
144 function p($var, $strip=false) {
145 echo s($var, $strip);
149 * Does proper javascript quoting.
150 * Do not use addslashes anymore, because it does not work when magic_quotes_sybase is enabled.
152 * @since 1.8 - 22/02/2007
153 * @param mixed value
154 * @return mixed quoted result
156 function addslashes_js($var) {
157 if (is_string($var)) {
158 $var = str_replace('\\', '\\\\', $var);
159 $var = str_replace(array('\'', '"', "\n", "\r", "\0"), array('\\\'', '\\"', '\\n', '\\r', '\\0'), $var);
160 $var = str_replace('</', '<\/', $var); // XHTML compliance
161 } else if (is_array($var)) {
162 $var = array_map('addslashes_js', $var);
163 } else if (is_object($var)) {
164 $a = get_object_vars($var);
165 foreach ($a as $key=>$value) {
166 $a[$key] = addslashes_js($value);
168 $var = (object)$a;
170 return $var;
174 * Remove query string from url
176 * Takes in a URL and returns it without the querystring portion
178 * @param string $url the url which may have a query string attached
179 * @return string
181 function strip_querystring($url) {
183 if ($commapos = strpos($url, '?')) {
184 return substr($url, 0, $commapos);
185 } else {
186 return $url;
191 * Returns the URL of the HTTP_REFERER, less the querystring portion if required
192 * @param boolean $stripquery if true, also removes the query part of the url.
193 * @return string
195 function get_referer($stripquery=true) {
196 if (isset($_SERVER['HTTP_REFERER'])) {
197 if ($stripquery) {
198 return strip_querystring($_SERVER['HTTP_REFERER']);
199 } else {
200 return $_SERVER['HTTP_REFERER'];
202 } else {
203 return '';
209 * Returns the name of the current script, WITH the querystring portion.
210 * this function is necessary because PHP_SELF and REQUEST_URI and SCRIPT_NAME
211 * return different things depending on a lot of things like your OS, Web
212 * server, and the way PHP is compiled (ie. as a CGI, module, ISAPI, etc.)
213 * <b>NOTE:</b> This function returns false if the global variables needed are not set.
215 * @return string
217 function me() {
219 if (!empty($_SERVER['REQUEST_URI'])) {
220 return $_SERVER['REQUEST_URI'];
222 } else if (!empty($_SERVER['PHP_SELF'])) {
223 if (!empty($_SERVER['QUERY_STRING'])) {
224 return $_SERVER['PHP_SELF'] .'?'. $_SERVER['QUERY_STRING'];
226 return $_SERVER['PHP_SELF'];
228 } else if (!empty($_SERVER['SCRIPT_NAME'])) {
229 if (!empty($_SERVER['QUERY_STRING'])) {
230 return $_SERVER['SCRIPT_NAME'] .'?'. $_SERVER['QUERY_STRING'];
232 return $_SERVER['SCRIPT_NAME'];
234 } else if (!empty($_SERVER['URL'])) { // May help IIS (not well tested)
235 if (!empty($_SERVER['QUERY_STRING'])) {
236 return $_SERVER['URL'] .'?'. $_SERVER['QUERY_STRING'];
238 return $_SERVER['URL'];
240 } else {
241 notify('Warning: Could not find any of these web server variables: $REQUEST_URI, $PHP_SELF, $SCRIPT_NAME or $URL');
242 return false;
247 * Like {@link me()} but returns a full URL
248 * @see me()
249 * @return string
251 function qualified_me() {
253 global $CFG;
255 if (!empty($CFG->wwwroot)) {
256 $url = parse_url($CFG->wwwroot);
259 if (!empty($url['host'])) {
260 $hostname = $url['host'];
261 } else if (!empty($_SERVER['SERVER_NAME'])) {
262 $hostname = $_SERVER['SERVER_NAME'];
263 } else if (!empty($_ENV['SERVER_NAME'])) {
264 $hostname = $_ENV['SERVER_NAME'];
265 } else if (!empty($_SERVER['HTTP_HOST'])) {
266 $hostname = $_SERVER['HTTP_HOST'];
267 } else if (!empty($_ENV['HTTP_HOST'])) {
268 $hostname = $_ENV['HTTP_HOST'];
269 } else {
270 notify('Warning: could not find the name of this server!');
271 return false;
274 if (!empty($url['port'])) {
275 $hostname .= ':'.$url['port'];
276 } else if (!empty($_SERVER['SERVER_PORT'])) {
277 if ($_SERVER['SERVER_PORT'] != 80 && $_SERVER['SERVER_PORT'] != 443) {
278 $hostname .= ':'.$_SERVER['SERVER_PORT'];
282 // TODO, this does not work in the situation described in MDL-11061, but
283 // I don't know how to fix it. Possibly believe $CFG->wwwroot ahead of what
284 // the server reports.
285 if (isset($_SERVER['HTTPS'])) {
286 $protocol = ($_SERVER['HTTPS'] == 'on') ? 'https://' : 'http://';
287 } else if (isset($_SERVER['SERVER_PORT'])) { # Apache2 does not export $_SERVER['HTTPS']
288 $protocol = ($_SERVER['SERVER_PORT'] == '443') ? 'https://' : 'http://';
289 } else {
290 $protocol = 'http://';
293 $url_prefix = $protocol.$hostname;
294 return $url_prefix . me();
299 * Class for creating and manipulating urls.
301 * See short write up here http://docs.moodle.org/en/Development:lib/weblib.php_moodle_url
303 class moodle_url {
304 var $scheme = '';// e.g. http
305 var $host = '';
306 var $port = '';
307 var $user = '';
308 var $pass = '';
309 var $path = '';
310 var $fragment = '';
311 var $params = array(); //associative array of query string params
314 * Pass no arguments to create a url that refers to this page. Use empty string to create empty url.
316 * @param string $url url default null means use this page url with no query string
317 * empty string means empty url.
318 * if you pass any other type of url it will be parsed into it's bits, including query string
319 * @param array $params these params override anything in the query string where params have the same name.
321 function moodle_url($url = null, $params = array()){
322 global $FULLME;
323 if ($url !== ''){
324 if ($url === null){
325 $url = strip_querystring($FULLME);
327 $parts = parse_url($url);
328 if ($parts === FALSE){
329 error('invalidurl');
331 if (isset($parts['query'])){
332 parse_str(str_replace('&amp;', '&', $parts['query']), $this->params);
334 unset($parts['query']);
335 foreach ($parts as $key => $value){
336 $this->$key = $value;
338 $this->params($params);
342 * Add an array of params to the params for this page. The added params override existing ones if they
343 * have the same name.
345 * @param array $params
347 function params($params){
348 $this->params = $params + $this->params;
352 * Remove all params if no arguments passed. Or else remove param $arg1, $arg2, etc.
354 * @param string $arg1
355 * @param string $arg2
356 * @param string $arg3
358 function remove_params(){
359 if ($thisargs = func_get_args()){
360 foreach ($thisargs as $arg){
361 if (isset($this->params[$arg])){
362 unset($this->params[$arg]);
365 } else { // no args
366 $this->params = array();
371 * Add a param to the params for this page. The added param overrides existing one if they
372 * have the same name.
374 * @param string $paramname name
375 * @param string $param value
377 function param($paramname, $param){
378 $this->params = array($paramname => $param) + $this->params;
382 function get_query_string($overrideparams = array()){
383 $arr = array();
384 $params = $overrideparams + $this->params;
385 foreach ($params as $key => $val){
386 $arr[] = urlencode($key)."=".urlencode($val);
388 return implode($arr, "&amp;");
391 * Outputs params as hidden form elements.
393 * @param array $exclude params to ignore
394 * @param integer $indent indentation
395 * @param array $overrideparams params to add to the output params, these
396 * override existing ones with the same name.
397 * @return string html for form elements.
399 function hidden_params_out($exclude = array(), $indent = 0, $overrideparams=array()){
400 $tabindent = str_repeat("\t", $indent);
401 $str = '';
402 $params = $overrideparams + $this->params;
403 foreach ($params as $key => $val){
404 if (FALSE === array_search($key, $exclude)) {
405 $val = s($val);
406 $str.= "$tabindent<input type=\"hidden\" name=\"$key\" value=\"$val\" />\n";
409 return $str;
412 * Output url
414 * @param boolean $noquerystring whether to output page params as a query string in the url.
415 * @param array $overrideparams params to add to the output url, these override existing ones with the same name.
416 * @return string url
418 function out($noquerystring = false, $overrideparams = array()) {
419 $uri = $this->scheme ? $this->scheme.':'.((strtolower($this->scheme) == 'mailto') ? '':'//'): '';
420 $uri .= $this->user ? $this->user.($this->pass? ':'.$this->pass:'').'@':'';
421 $uri .= $this->host ? $this->host : '';
422 $uri .= $this->port ? ':'.$this->port : '';
423 $uri .= $this->path ? $this->path : '';
424 if (!$noquerystring){
425 $uri .= (count($this->params)||count($overrideparams)) ? '?'.$this->get_query_string($overrideparams) : '';
427 $uri .= $this->fragment ? '#'.$this->fragment : '';
428 return $uri;
431 * Output action url with sesskey
433 * @param boolean $noquerystring whether to output page params as a query string in the url.
434 * @return string url
436 function out_action($overrideparams = array()) {
437 $overrideparams = array('sesskey'=> sesskey()) + $overrideparams;
438 return $this->out(false, $overrideparams);
443 * Determine if there is data waiting to be processed from a form
445 * Used on most forms in Moodle to check for data
446 * Returns the data as an object, if it's found.
447 * This object can be used in foreach loops without
448 * casting because it's cast to (array) automatically
450 * Checks that submitted POST data exists and returns it as object.
452 * @param string $url not used anymore
453 * @return mixed false or object
455 function data_submitted($url='') {
457 if (empty($_POST)) {
458 return false;
459 } else {
460 return (object)$_POST;
465 * Moodle replacement for php stripslashes() function,
466 * works also for objects and arrays.
468 * The standard php stripslashes() removes ALL backslashes
469 * even from strings - so C:\temp becomes C:temp - this isn't good.
470 * This function should work as a fairly safe replacement
471 * to be called on quoted AND unquoted strings (to be sure)
473 * @param mixed something to remove unsafe slashes from
474 * @return mixed
476 function stripslashes_safe($mixed) {
477 // there is no need to remove slashes from int, float and bool types
478 if (empty($mixed)) {
479 //nothing to do...
480 } else if (is_string($mixed)) {
481 if (ini_get_bool('magic_quotes_sybase')) { //only unescape single quotes
482 $mixed = str_replace("''", "'", $mixed);
483 } else { //the rest, simple and double quotes and backslashes
484 $mixed = str_replace("\\'", "'", $mixed);
485 $mixed = str_replace('\\"', '"', $mixed);
486 $mixed = str_replace('\\\\', '\\', $mixed);
488 } else if (is_array($mixed)) {
489 foreach ($mixed as $key => $value) {
490 $mixed[$key] = stripslashes_safe($value);
492 } else if (is_object($mixed)) {
493 $vars = get_object_vars($mixed);
494 foreach ($vars as $key => $value) {
495 $mixed->$key = stripslashes_safe($value);
499 return $mixed;
503 * Recursive implementation of stripslashes()
505 * This function will allow you to strip the slashes from a variable.
506 * If the variable is an array or object, slashes will be stripped
507 * from the items (or properties) it contains, even if they are arrays
508 * or objects themselves.
510 * @param mixed the variable to remove slashes from
511 * @return mixed
513 function stripslashes_recursive($var) {
514 if (is_object($var)) {
515 $new_var = new object();
516 $properties = get_object_vars($var);
517 foreach($properties as $property => $value) {
518 $new_var->$property = stripslashes_recursive($value);
521 } else if(is_array($var)) {
522 $new_var = array();
523 foreach($var as $property => $value) {
524 $new_var[$property] = stripslashes_recursive($value);
527 } else if(is_string($var)) {
528 $new_var = stripslashes($var);
530 } else {
531 $new_var = $var;
534 return $new_var;
538 * Recursive implementation of addslashes()
540 * This function will allow you to add the slashes from a variable.
541 * If the variable is an array or object, slashes will be added
542 * to the items (or properties) it contains, even if they are arrays
543 * or objects themselves.
545 * @param mixed the variable to add slashes from
546 * @return mixed
548 function addslashes_recursive($var) {
549 if (is_object($var)) {
550 $new_var = new object();
551 $properties = get_object_vars($var);
552 foreach($properties as $property => $value) {
553 $new_var->$property = addslashes_recursive($value);
556 } else if (is_array($var)) {
557 $new_var = array();
558 foreach($var as $property => $value) {
559 $new_var[$property] = addslashes_recursive($value);
562 } else if (is_string($var)) {
563 $new_var = addslashes($var);
565 } else { // nulls, integers, etc.
566 $new_var = $var;
569 return $new_var;
573 * Given some normal text this function will break up any
574 * long words to a given size by inserting the given character
576 * It's multibyte savvy and doesn't change anything inside html tags.
578 * @param string $string the string to be modified
579 * @param int $maxsize maximum length of the string to be returned
580 * @param string $cutchar the string used to represent word breaks
581 * @return string
583 function break_up_long_words($string, $maxsize=20, $cutchar=' ') {
585 /// Loading the textlib singleton instance. We are going to need it.
586 $textlib = textlib_get_instance();
588 /// First of all, save all the tags inside the text to skip them
589 $tags = array();
590 filter_save_tags($string,$tags);
592 /// Process the string adding the cut when necessary
593 $output = '';
594 $length = $textlib->strlen($string);
595 $wordlength = 0;
597 for ($i=0; $i<$length; $i++) {
598 $char = $textlib->substr($string, $i, 1);
599 if ($char == ' ' or $char == "\t" or $char == "\n" or $char == "\r" or $char == "<" or $char == ">") {
600 $wordlength = 0;
601 } else {
602 $wordlength++;
603 if ($wordlength > $maxsize) {
604 $output .= $cutchar;
605 $wordlength = 0;
608 $output .= $char;
611 /// Finally load the tags back again
612 if (!empty($tags)) {
613 $output = str_replace(array_keys($tags), $tags, $output);
616 return $output;
620 * This does a search and replace, ignoring case
621 * This function is only used for versions of PHP older than version 5
622 * which do not have a native version of this function.
623 * Taken from the PHP manual, by bradhuizenga @ softhome.net
625 * @param string $find the string to search for
626 * @param string $replace the string to replace $find with
627 * @param string $string the string to search through
628 * return string
630 if (!function_exists('str_ireplace')) { /// Only exists in PHP 5
631 function str_ireplace($find, $replace, $string) {
633 if (!is_array($find)) {
634 $find = array($find);
637 if(!is_array($replace)) {
638 if (!is_array($find)) {
639 $replace = array($replace);
640 } else {
641 // this will duplicate the string into an array the size of $find
642 $c = count($find);
643 $rString = $replace;
644 unset($replace);
645 for ($i = 0; $i < $c; $i++) {
646 $replace[$i] = $rString;
651 foreach ($find as $fKey => $fItem) {
652 $between = explode(strtolower($fItem),strtolower($string));
653 $pos = 0;
654 foreach($between as $bKey => $bItem) {
655 $between[$bKey] = substr($string,$pos,strlen($bItem));
656 $pos += strlen($bItem) + strlen($fItem);
658 $string = implode($replace[$fKey],$between);
660 return ($string);
665 * Locate the position of a string in another string
667 * This function is only used for versions of PHP older than version 5
668 * which do not have a native version of this function.
669 * Taken from the PHP manual, by dmarsh @ spscc.ctc.edu
671 * @param string $haystack The string to be searched
672 * @param string $needle The string to search for
673 * @param int $offset The position in $haystack where the search should begin.
675 if (!function_exists('stripos')) { /// Only exists in PHP 5
676 function stripos($haystack, $needle, $offset=0) {
678 return strpos(strtoupper($haystack), strtoupper($needle), $offset);
683 * This function will print a button/link/etc. form element
684 * that will work on both Javascript and non-javascript browsers.
685 * Relies on the Javascript function openpopup in javascript.php
687 * All parameters default to null, only $type and $url are mandatory.
689 * $url must be relative to home page eg /mod/survey/stuff.php
690 * @param string $url Web link relative to home page
691 * @param string $name Name to be assigned to the popup window (this is used by
692 * client-side scripts to "talk" to the popup window)
693 * @param string $linkname Text to be displayed as web link
694 * @param int $height Height to assign to popup window
695 * @param int $width Height to assign to popup window
696 * @param string $title Text to be displayed as popup page title
697 * @param string $options List of additional options for popup window
698 * @param string $return If true, return as a string, otherwise print
699 * @param string $id id added to the element
700 * @param string $class class added to the element
701 * @return string
702 * @uses $CFG
704 function element_to_popup_window ($type=null, $url=null, $name=null, $linkname=null,
705 $height=400, $width=500, $title=null,
706 $options=null, $return=false, $id=null, $class=null) {
708 if (is_null($url)) {
709 debugging('You must give the url to display in the popup. URL is missing - can\'t create popup window.', DEBUG_DEVELOPER);
712 global $CFG;
714 if ($options == 'none') { // 'none' is legacy, should be removed in v2.0
715 $options = null;
718 // add some sane default options for popup windows
719 if (!$options) {
720 $options = 'menubar=0,location=0,scrollbars,resizable';
722 if ($width) {
723 $options .= ',width='. $width;
725 if ($height) {
726 $options .= ',height='. $height;
728 if ($id) {
729 $id = ' id="'.$id.'" ';
731 if ($class) {
732 $class = ' class="'.$class.'" ';
734 if ($name) {
735 $_name = $name;
736 if (($name = preg_replace("/\s/", '_', $name)) != $_name) {
737 debugging('The $name of a popup window shouldn\'t contain spaces - string modified. '. $_name .' changed to '. $name, DEBUG_DEVELOPER);
739 } else {
740 $name = 'popup';
743 // get some default string, using the localized version of legacy defaults
744 if (is_null($linkname) || $linkname === '') {
745 $linkname = get_string('clickhere');
747 if (!$title) {
748 $title = get_string('popupwindowname');
751 $fullscreen = 0; // must be passed to openpopup
752 $element = '';
754 switch ($type) {
755 case 'button' :
756 $element = '<input type="button" name="'. $name .'" title="'. $title .'" value="'. $linkname .'" '. $id . $class .
757 "onclick=\"return openpopup('$url', '$name', '$options', $fullscreen);\" />\n";
758 break;
759 case 'link' :
760 // some log url entries contain _SERVER[HTTP_REFERRER] in which case wwwroot is already there.
761 if (!(strpos($url,$CFG->wwwroot) === false)) {
762 $url = substr($url, strlen($CFG->wwwroot));
764 $element = '<a title="'. s(strip_tags($title)) .'" href="'. $CFG->wwwroot . $url .'" '.
765 "onclick=\"this.target='$name'; return openpopup('$url', '$name', '$options', $fullscreen);\">$linkname</a>";
766 break;
767 default :
768 error('Undefined element - can\'t create popup window.');
769 break;
772 if ($return) {
773 return $element;
774 } else {
775 echo $element;
780 * Creates and displays (or returns) a link to a popup window, using element_to_popup_window function.
782 * @return string html code to display a link to a popup window.
783 * @see element_to_popup_window()
785 function link_to_popup_window ($url, $name=null, $linkname=null,
786 $height=400, $width=500, $title=null,
787 $options=null, $return=false) {
789 return element_to_popup_window('link', $url, $name, $linkname, $height, $width, $title, $options, $return, null, null);
793 * Creates and displays (or returns) a buttons to a popup window, using element_to_popup_window function.
795 * @return string html code to display a button to a popup window.
796 * @see element_to_popup_window()
798 function button_to_popup_window ($url, $name=null, $linkname=null,
799 $height=400, $width=500, $title=null, $options=null, $return=false,
800 $id=null, $class=null) {
802 return element_to_popup_window('button', $url, $name, $linkname, $height, $width, $title, $options, $return, $id, $class);
807 * Prints a simple button to close a window
808 * @param string $name name of the window to close
809 * @param boolean $return whether this function should return a string or output it
810 * @return string if $return is true, nothing otherwise
812 function close_window_button($name='closewindow', $return=false) {
813 global $CFG;
815 $output = '';
817 $output .= '<div class="closewindow">' . "\n";
818 $output .= '<form action="#"><div>';
819 $output .= '<input type="button" onclick="self.close();" value="'.get_string($name).'" />';
820 $output .= '</div></form>';
821 $output .= '</div>' . "\n";
823 if ($return) {
824 return $output;
825 } else {
826 echo $output;
831 * Try and close the current window immediately using Javascript
832 * @param int $delay the delay in seconds before closing the window
834 function close_window($delay=0) {
836 <script type="text/javascript">
837 //<![CDATA[
838 function close_this_window() {
839 self.close();
841 setTimeout("close_this_window()", <?php echo $delay * 1000 ?>);
842 //]]>
843 </script>
844 <noscript><center>
845 <?php print_string('pleaseclose') ?>
846 </center></noscript>
847 <?php
848 die;
853 * Given an array of values, output the HTML for a select element with those options.
854 * Normally, you only need to use the first few parameters.
856 * @param array $options The options to offer. An array of the form
857 * $options[{value}] = {text displayed for that option};
858 * @param string $name the name of this form control, as in &lt;select name="..." ...
859 * @param string $selected the option to select initially, default none.
860 * @param string $nothing The label for the 'nothing is selected' option. Defaults to get_string('choose').
861 * Set this to '' if you don't want a 'nothing is selected' option.
862 * @param string $script in not '', then this is added to the &lt;select> element as an onchange handler.
863 * @param string $nothingvalue The value corresponding to the $nothing option. Defaults to 0.
864 * @param boolean $return if false (the default) the the output is printed directly, If true, the
865 * generated HTML is returned as a string.
866 * @param boolean $disabled if true, the select is generated in a disabled state. Default, false.
867 * @param int $tabindex if give, sets the tabindex attribute on the &lt;select> element. Default none.
868 * @param string $id value to use for the id attribute of the &lt;select> element. If none is given,
869 * then a suitable one is constructed.
871 function choose_from_menu ($options, $name, $selected='', $nothing='choose', $script='',
872 $nothingvalue='0', $return=false, $disabled=false, $tabindex=0, $id='') {
874 if ($nothing == 'choose') {
875 $nothing = get_string('choose') .'...';
878 $attributes = ($script) ? 'onchange="'. $script .'"' : '';
879 if ($disabled) {
880 $attributes .= ' disabled="disabled"';
883 if ($tabindex) {
884 $attributes .= ' tabindex="'.$tabindex.'"';
887 if ($id ==='') {
888 $id = 'menu'.$name;
889 // name may contaion [], which would make an invalid id. e.g. numeric question type editing form, assignment quickgrading
890 $id = str_replace('[', '', $id);
891 $id = str_replace(']', '', $id);
894 $output = '<select id="'.$id.'" name="'. $name .'" '. $attributes .'>' . "\n";
895 if ($nothing) {
896 $output .= ' <option value="'. s($nothingvalue) .'"'. "\n";
897 if ($nothingvalue === $selected) {
898 $output .= ' selected="selected"';
900 $output .= '>'. $nothing .'</option>' . "\n";
902 if (!empty($options)) {
903 foreach ($options as $value => $label) {
904 $output .= ' <option value="'. s($value) .'"';
905 if ((string)$value == (string)$selected) {
906 $output .= ' selected="selected"';
908 if ($label === '') {
909 $output .= '>'. $value .'</option>' . "\n";
910 } else {
911 $output .= '>'. $label .'</option>' . "\n";
915 $output .= '</select>' . "\n";
917 if ($return) {
918 return $output;
919 } else {
920 echo $output;
925 * Choose value 0 or 1 from a menu with options 'No' and 'Yes'.
926 * Other options like choose_from_menu.
927 * @param string $name
928 * @param string $selected
929 * @param string $string (defaults to '')
930 * @param boolean $return whether this function should return a string or output it (defaults to false)
931 * @param boolean $disabled (defaults to false)
932 * @param int $tabindex
934 function choose_from_menu_yesno($name, $selected, $script = '',
935 $return = false, $disabled = false, $tabindex = 0) {
936 return choose_from_menu(array(get_string('no'), get_string('yes')), $name,
937 $selected, '', $script, '0', $return, $disabled, $tabindex);
941 * Just like choose_from_menu, but takes a nested array (2 levels) and makes a dropdown menu
942 * including option headings with the first level.
944 function choose_from_menu_nested($options,$name,$selected='',$nothing='choose',$script = '',
945 $nothingvalue=0,$return=false,$disabled=false,$tabindex=0) {
947 if ($nothing == 'choose') {
948 $nothing = get_string('choose') .'...';
951 $attributes = ($script) ? 'onchange="'. $script .'"' : '';
952 if ($disabled) {
953 $attributes .= ' disabled="disabled"';
956 if ($tabindex) {
957 $attributes .= ' tabindex="'.$tabindex.'"';
960 $output = '<select id="menu'.$name.'" name="'. $name .'" '. $attributes .'>' . "\n";
961 if ($nothing) {
962 $output .= ' <option value="'. $nothingvalue .'"'. "\n";
963 if ($nothingvalue === $selected) {
964 $output .= ' selected="selected"';
966 $output .= '>'. $nothing .'</option>' . "\n";
968 if (!empty($options)) {
969 foreach ($options as $section => $values) {
971 $output .= ' <optgroup label="'. s(format_string($section)) .'">'."\n";
972 foreach ($values as $value => $label) {
973 $output .= ' <option value="'. format_string($value) .'"';
974 if ((string)$value == (string)$selected) {
975 $output .= ' selected="selected"';
977 if ($label === '') {
978 $output .= '>'. $value .'</option>' . "\n";
979 } else {
980 $output .= '>'. $label .'</option>' . "\n";
983 $output .= ' </optgroup>'."\n";
986 $output .= '</select>' . "\n";
988 if ($return) {
989 return $output;
990 } else {
991 echo $output;
997 * Given an array of values, creates a group of radio buttons to be part of a form
999 * @param array $options An array of value-label pairs for the radio group (values as keys)
1000 * @param string $name Name of the radiogroup (unique in the form)
1001 * @param string $checked The value that is already checked
1003 function choose_from_radio ($options, $name, $checked='', $return=false) {
1005 static $idcounter = 0;
1007 if (!$name) {
1008 $name = 'unnamed';
1011 $output = '<span class="radiogroup '.$name."\">\n";
1013 if (!empty($options)) {
1014 $currentradio = 0;
1015 foreach ($options as $value => $label) {
1016 $htmlid = 'auto-rb'.sprintf('%04d', ++$idcounter);
1017 $output .= ' <span class="radioelement '.$name.' rb'.$currentradio."\">";
1018 $output .= '<input name="'.$name.'" id="'.$htmlid.'" type="radio" value="'.$value.'"';
1019 if ($value == $checked) {
1020 $output .= ' checked="checked"';
1022 if ($label === '') {
1023 $output .= ' /> <label for="'.$htmlid.'">'. $value .'</label></span>' . "\n";
1024 } else {
1025 $output .= ' /> <label for="'.$htmlid.'">'. $label .'</label></span>' . "\n";
1027 $currentradio = ($currentradio + 1) % 2;
1031 $output .= '</span>' . "\n";
1033 if ($return) {
1034 return $output;
1035 } else {
1036 echo $output;
1040 /** Display an standard html checkbox with an optional label
1042 * @param string $name The name of the checkbox
1043 * @param string $value The valus that the checkbox will pass when checked
1044 * @param boolean $checked The flag to tell the checkbox initial state
1045 * @param string $label The label to be showed near the checkbox
1046 * @param string $alt The info to be inserted in the alt tag
1048 function print_checkbox ($name, $value, $checked = true, $label = '', $alt = '', $script='',$return=false) {
1050 static $idcounter = 0;
1052 if (!$name) {
1053 $name = 'unnamed';
1056 if ($alt) {
1057 $alt = strip_tags($alt);
1058 } else {
1059 $alt = 'checkbox';
1062 if ($checked) {
1063 $strchecked = ' checked="checked"';
1064 } else {
1065 $strchecked = '';
1068 $htmlid = 'auto-cb'.sprintf('%04d', ++$idcounter);
1069 $output = '<span class="checkbox '.$name."\">";
1070 $output .= '<input name="'.$name.'" id="'.$htmlid.'" type="checkbox" value="'.$value.'" alt="'.$alt.'"'.$strchecked.' '.((!empty($script)) ? ' onclick="'.$script.'" ' : '').' />';
1071 if(!empty($label)) {
1072 $output .= ' <label for="'.$htmlid.'">'.$label.'</label>';
1074 $output .= '</span>'."\n";
1076 if (empty($return)) {
1077 echo $output;
1078 } else {
1079 return $output;
1084 /** Display an standard html text field with an optional label
1086 * @param string $name The name of the text field
1087 * @param string $value The value of the text field
1088 * @param string $label The label to be showed near the text field
1089 * @param string $alt The info to be inserted in the alt tag
1091 function print_textfield ($name, $value, $alt = '',$size=50,$maxlength=0, $return=false) {
1093 static $idcounter = 0;
1095 if (empty($name)) {
1096 $name = 'unnamed';
1099 if (empty($alt)) {
1100 $alt = 'textfield';
1103 if (!empty($maxlength)) {
1104 $maxlength = ' maxlength="'.$maxlength.'" ';
1107 $htmlid = 'auto-tf'.sprintf('%04d', ++$idcounter);
1108 $output = '<span class="textfield '.$name."\">";
1109 $output .= '<input name="'.$name.'" id="'.$htmlid.'" type="text" value="'.$value.'" size="'.$size.'" '.$maxlength.' alt="'.$alt.'" />';
1111 $output .= '</span>'."\n";
1113 if (empty($return)) {
1114 echo $output;
1115 } else {
1116 return $output;
1123 * Implements a complete little popup form
1125 * @uses $CFG
1126 * @param string $common The URL up to the point of the variable that changes
1127 * @param array $options Alist of value-label pairs for the popup list
1128 * @param string $formid Id must be unique on the page (originaly $formname)
1129 * @param string $selected The option that is already selected
1130 * @param string $nothing The label for the "no choice" option
1131 * @param string $help The name of a help page if help is required
1132 * @param string $helptext The name of the label for the help button
1133 * @param boolean $return Indicates whether the function should return the text
1134 * as a string or echo it directly to the page being rendered
1135 * @param string $targetwindow The name of the target page to open the linked page in.
1136 * @param string $selectlabel Text to place in a [label] element - preferred for accessibility.
1137 * @param array $optionsextra TODO, an array?
1138 * @return string If $return is true then the entire form is returned as a string.
1139 * @todo Finish documenting this function<br>
1141 function popup_form($common, $options, $formid, $selected='', $nothing='choose', $help='', $helptext='', $return=false,
1142 $targetwindow='self', $selectlabel='', $optionsextra=NULL) {
1144 global $CFG;
1145 static $go, $choose; /// Locally cached, in case there's lots on a page
1147 if (empty($options)) {
1148 return '';
1151 if (!isset($go)) {
1152 $go = get_string('go');
1155 if ($nothing == 'choose') {
1156 if (!isset($choose)) {
1157 $choose = get_string('choose');
1159 $nothing = $choose.'...';
1162 // changed reference to document.getElementById('id_abc') instead of document.abc
1163 // MDL-7861
1164 $output = '<form action="'.$CFG->wwwroot.'/course/jumpto.php"'.
1165 ' method="get" '.
1166 $CFG->frametarget.
1167 ' id="'.$formid.'"'.
1168 ' class="popupform">';
1169 if ($help) {
1170 $button = helpbutton($help, $helptext, 'moodle', true, false, '', true);
1171 } else {
1172 $button = '';
1175 if ($selectlabel) {
1176 $selectlabel = '<label for="'.$formid.'_jump">'.$selectlabel.'</label>';
1179 //IE and Opera fire the onchange when ever you move into a dropdwown list with the keyboard.
1180 //onfocus will call a function inside dropdown.js. It fixes this IE/Opera behavior.
1181 //Note: There is a bug on Opera+Linux with the javascript code (first mouse selection is inactive),
1182 //so we do not fix the Opera behavior on Linux
1183 if (check_browser_version('MSIE') || (check_browser_version('Opera') && !check_browser_operating_system("Linux"))) {
1184 $output .= '<div>'.$selectlabel.$button.'<select id="'.$formid.'_jump" onfocus="initSelect(\''.$formid.'\','.$targetwindow.')" name="jump">'."\n";
1186 //Other browser
1187 else {
1188 $output .= '<div>'.$selectlabel.$button.'<select id="'.$formid.'_jump" name="jump" onchange="'.$targetwindow.'.location=document.getElementById(\''.$formid.'\').jump.options[document.getElementById(\''.$formid.'\').jump.selectedIndex].value;">'."\n";
1191 if ($nothing != '') {
1192 $output .= " <option value=\"javascript:void(0)\">$nothing</option>\n";
1195 $inoptgroup = false;
1197 foreach ($options as $value => $label) {
1199 if ($label == '--') { /// we are ending previous optgroup
1200 /// Check to see if we already have a valid open optgroup
1201 /// XHTML demands that there be at least 1 option within an optgroup
1202 if ($inoptgroup and (count($optgr) > 1) ) {
1203 $output .= implode('', $optgr);
1204 $output .= ' </optgroup>';
1206 $optgr = array();
1207 $inoptgroup = false;
1208 continue;
1209 } else if (substr($label,0,2) == '--') { /// we are starting a new optgroup
1211 /// Check to see if we already have a valid open optgroup
1212 /// XHTML demands that there be at least 1 option within an optgroup
1213 if ($inoptgroup and (count($optgr) > 1) ) {
1214 $output .= implode('', $optgr);
1215 $output .= ' </optgroup>';
1218 unset($optgr);
1219 $optgr = array();
1221 $optgr[] = ' <optgroup label="'. s(format_string(substr($label,2))) .'">'; // Plain labels
1223 $inoptgroup = true; /// everything following will be in an optgroup
1224 continue;
1226 } else {
1227 if (!empty($CFG->usesid) && !isset($_COOKIE[session_name()]))
1229 $url=sid_process_url( $common . $value );
1230 } else
1232 $url=$common . $value;
1234 $optstr = ' <option value="' . $url . '"';
1236 if ($value == $selected) {
1237 $optstr .= ' selected="selected"';
1240 if (!empty($optionsextra[$value])) {
1241 $optstr .= ' '.$optionsextra[$value];
1244 if ($label) {
1245 $optstr .= '>'. $label .'</option>' . "\n";
1246 } else {
1247 $optstr .= '>'. $value .'</option>' . "\n";
1250 if ($inoptgroup) {
1251 $optgr[] = $optstr;
1252 } else {
1253 $output .= $optstr;
1259 /// catch the final group if not closed
1260 if ($inoptgroup and count($optgr) > 1) {
1261 $output .= implode('', $optgr);
1262 $output .= ' </optgroup>';
1265 $output .= '</select>';
1266 $output .= '<input type="hidden" name="sesskey" value="'.sesskey().'" />';
1267 $output .= '<div id="noscript'.$formid.'" style="display: inline;">';
1268 $output .= '<input type="submit" value="'.$go.'" /></div>';
1269 $output .= '<script type="text/javascript">'.
1270 "\n//<![CDATA[\n".
1271 'document.getElementById("noscript'.$formid.'").style.display = "none";'.
1272 "\n//]]>\n".'</script>';
1273 $output .= '</div>';
1274 $output .= '</form>';
1276 if ($return) {
1277 return $output;
1278 } else {
1279 echo $output;
1285 * Prints some red text
1287 * @param string $error The text to be displayed in red
1289 function formerr($error) {
1291 if (!empty($error)) {
1292 echo '<span class="error">'. $error .'</span>';
1297 * Validates an email to make sure it makes sense.
1299 * @param string $address The email address to validate.
1300 * @return boolean
1302 function validate_email($address) {
1304 return (ereg('^[-!#$%&\'*+\\/0-9=?A-Z^_`a-z{|}~]+'.
1305 '(\.[-!#$%&\'*+\\/0-9=?A-Z^_`a-z{|}~]+)*'.
1306 '@'.
1307 '[-!#$%&\'*+\\/0-9=?A-Z^_`a-z{|}~]+\.'.
1308 '[-!#$%&\'*+\\./0-9=?A-Z^_`a-z{|}~]+$',
1309 $address));
1313 * Extracts file argument either from file parameter or PATH_INFO
1315 * @param string $scriptname name of the calling script
1316 * @return string file path (only safe characters)
1318 function get_file_argument($scriptname) {
1319 global $_SERVER;
1321 $relativepath = FALSE;
1323 // first try normal parameter (compatible method == no relative links!)
1324 $relativepath = optional_param('file', FALSE, PARAM_PATH);
1325 if ($relativepath === '/testslasharguments') {
1326 echo 'test -1 : Incorrect use - try "file.php/testslasharguments" instead'; //indicate fopen/fread works for health center
1327 die;
1330 // then try extract file from PATH_INFO (slasharguments method)
1331 if (!$relativepath and !empty($_SERVER['PATH_INFO'])) {
1332 $path_info = $_SERVER['PATH_INFO'];
1333 // check that PATH_INFO works == must not contain the script name
1334 if (!strpos($path_info, $scriptname)) {
1335 $relativepath = clean_param(rawurldecode($path_info), PARAM_PATH);
1336 if ($relativepath === '/testslasharguments') {
1337 echo 'test 1 : Slasharguments test passed. Server confguration is compatible with file.php/1/pic.jpg slashargument setting.'; //indicate ok for health center
1338 die;
1343 // now if both fail try the old way
1344 // (for compatibility with misconfigured or older buggy php implementations)
1345 if (!$relativepath) {
1346 $arr = explode($scriptname, me());
1347 if (!empty($arr[1])) {
1348 $path_info = strip_querystring($arr[1]);
1349 $relativepath = clean_param(rawurldecode($path_info), PARAM_PATH);
1350 if ($relativepath === '/testslasharguments') {
1351 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
1352 die;
1357 return $relativepath;
1361 * Searches the current environment variables for some slash arguments
1363 * @param string $file ?
1364 * @todo Finish documenting this function
1366 function get_slash_arguments($file='file.php') {
1368 if (!$string = me()) {
1369 return false;
1372 $pathinfo = explode($file, $string);
1374 if (!empty($pathinfo[1])) {
1375 return addslashes($pathinfo[1]);
1376 } else {
1377 return false;
1382 * Extracts arguments from "/foo/bar/something"
1383 * eg http://mysite.com/script.php/foo/bar/something
1385 * @param string $string ?
1386 * @param int $i ?
1387 * @return array|string
1388 * @todo Finish documenting this function
1390 function parse_slash_arguments($string, $i=0) {
1392 if (detect_munged_arguments($string)) {
1393 return false;
1395 $args = explode('/', $string);
1397 if ($i) { // return just the required argument
1398 return $args[$i];
1400 } else { // return the whole array
1401 array_shift($args); // get rid of the empty first one
1402 return $args;
1407 * Just returns an array of text formats suitable for a popup menu
1409 * @uses FORMAT_MOODLE
1410 * @uses FORMAT_HTML
1411 * @uses FORMAT_PLAIN
1412 * @uses FORMAT_MARKDOWN
1413 * @return array
1415 function format_text_menu() {
1417 return array (FORMAT_MOODLE => get_string('formattext'),
1418 FORMAT_HTML => get_string('formathtml'),
1419 FORMAT_PLAIN => get_string('formatplain'),
1420 FORMAT_MARKDOWN => get_string('formatmarkdown'));
1424 * Given text in a variety of format codings, this function returns
1425 * the text as safe HTML.
1427 * This function should mainly be used for long strings like posts,
1428 * answers, glossary items etc. For short strings @see format_string().
1430 * @uses $CFG
1431 * @uses FORMAT_MOODLE
1432 * @uses FORMAT_HTML
1433 * @uses FORMAT_PLAIN
1434 * @uses FORMAT_WIKI
1435 * @uses FORMAT_MARKDOWN
1436 * @param string $text The text to be formatted. This is raw text originally from user input.
1437 * @param int $format Identifier of the text format to be used
1438 * (FORMAT_MOODLE, FORMAT_HTML, FORMAT_PLAIN, FORMAT_WIKI, FORMAT_MARKDOWN)
1439 * @param array $options ?
1440 * @param int $courseid ?
1441 * @return string
1442 * @todo Finish documenting this function
1444 function format_text($text, $format=FORMAT_MOODLE, $options=NULL, $courseid=NULL) {
1446 global $CFG, $COURSE;
1448 static $croncache = array();
1450 if ($text === '') {
1451 return ''; // no need to do any filters and cleaning
1454 if (!isset($options->trusttext)) {
1455 $options->trusttext = false;
1458 if (!isset($options->noclean)) {
1459 $options->noclean=false;
1461 if (!isset($options->nocache)) {
1462 $options->nocache=false;
1464 if (!isset($options->smiley)) {
1465 $options->smiley=true;
1467 if (!isset($options->filter)) {
1468 $options->filter=true;
1470 if (!isset($options->para)) {
1471 $options->para=true;
1473 if (!isset($options->newlines)) {
1474 $options->newlines=true;
1477 if (empty($courseid)) {
1478 $courseid = $COURSE->id;
1481 if (!empty($CFG->cachetext) and empty($options->nocache)) {
1482 $time = time() - $CFG->cachetext;
1483 $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);
1485 if (defined('FULLME') and FULLME == 'cron') {
1486 if (isset($croncache[$md5key])) {
1487 return $croncache[$md5key];
1491 if ($oldcacheitem = get_record_sql('SELECT * FROM '.$CFG->prefix.'cache_text WHERE md5key = \''.$md5key.'\'', true)) {
1492 if ($oldcacheitem->timemodified >= $time) {
1493 if (defined('FULLME') and FULLME == 'cron') {
1494 if (count($croncache) > 150) {
1495 reset($croncache);
1496 $key = key($croncache);
1497 unset($croncache[$key]);
1499 $croncache[$md5key] = $oldcacheitem->formattedtext;
1501 return $oldcacheitem->formattedtext;
1506 // trusttext overrides the noclean option!
1507 if ($options->trusttext) {
1508 if (trusttext_present($text)) {
1509 $text = trusttext_strip($text);
1510 if (!empty($CFG->enabletrusttext)) {
1511 $options->noclean = true;
1512 } else {
1513 $options->noclean = false;
1515 } else {
1516 $options->noclean = false;
1518 } else if (!debugging('', DEBUG_DEVELOPER)) {
1519 // strip any forgotten trusttext in non-developer mode
1520 // do not forget to disable text cache when debugging trusttext!!
1521 $text = trusttext_strip($text);
1524 $CFG->currenttextiscacheable = true; // Default status - can be changed by any filter
1526 switch ($format) {
1527 case FORMAT_HTML:
1528 if ($options->smiley) {
1529 replace_smilies($text);
1531 if (!$options->noclean) {
1532 $text = clean_text($text, FORMAT_HTML);
1534 if ($options->filter) {
1535 $text = filter_text($text, $courseid);
1537 break;
1539 case FORMAT_PLAIN:
1540 $text = s($text); // cleans dangerous JS
1541 $text = rebuildnolinktag($text);
1542 $text = str_replace(' ', '&nbsp; ', $text);
1543 $text = nl2br($text);
1544 break;
1546 case FORMAT_WIKI:
1547 // this format is deprecated
1548 $text = '<p>NOTICE: Wiki-like formatting has been removed from Moodle. You should not be seeing
1549 this message as all texts should have been converted to Markdown format instead.
1550 Please post a bug report to http://moodle.org/bugs with information about where you
1551 saw this message.</p>'.s($text);
1552 break;
1554 case FORMAT_MARKDOWN:
1555 $text = markdown_to_html($text);
1556 if ($options->smiley) {
1557 replace_smilies($text);
1559 if (!$options->noclean) {
1560 $text = clean_text($text, FORMAT_HTML);
1563 if ($options->filter) {
1564 $text = filter_text($text, $courseid);
1566 break;
1568 default: // FORMAT_MOODLE or anything else
1569 $text = text_to_html($text, $options->smiley, $options->para, $options->newlines);
1570 if (!$options->noclean) {
1571 $text = clean_text($text, FORMAT_HTML);
1574 if ($options->filter) {
1575 $text = filter_text($text, $courseid);
1577 break;
1580 if (empty($options->nocache) and !empty($CFG->cachetext) and $CFG->currenttextiscacheable) {
1581 if (defined('FULLME') and FULLME == 'cron') {
1582 // special static cron cache - no need to store it in db if its not already there
1583 if (count($croncache) > 150) {
1584 reset($croncache);
1585 $key = key($croncache);
1586 unset($croncache[$key]);
1588 $croncache[$md5key] = $text;
1589 return $text;
1592 $newcacheitem = new object();
1593 $newcacheitem->md5key = $md5key;
1594 $newcacheitem->formattedtext = addslashes($text);
1595 $newcacheitem->timemodified = time();
1596 if ($oldcacheitem) { // See bug 4677 for discussion
1597 $newcacheitem->id = $oldcacheitem->id;
1598 @update_record('cache_text', $newcacheitem); // Update existing record in the cache table
1599 // It's unlikely that the cron cache cleaner could have
1600 // deleted this entry in the meantime, as it allows
1601 // some extra time to cover these cases.
1602 } else {
1603 @insert_record('cache_text', $newcacheitem); // Insert a new record in the cache table
1604 // Again, it's possible that another user has caused this
1605 // record to be created already in the time that it took
1606 // to traverse this function. That's OK too, as the
1607 // call above handles duplicate entries, and eventually
1608 // the cron cleaner will delete them.
1612 return $text;
1615 /** Converts the text format from the value to the 'internal'
1616 * name or vice versa. $key can either be the value or the name
1617 * and you get the other back.
1619 * @param mixed int 0-4 or string one of 'moodle','html','plain','markdown'
1620 * @return mixed as above but the other way around!
1622 function text_format_name( $key ) {
1623 $lookup = array();
1624 $lookup[FORMAT_MOODLE] = 'moodle';
1625 $lookup[FORMAT_HTML] = 'html';
1626 $lookup[FORMAT_PLAIN] = 'plain';
1627 $lookup[FORMAT_MARKDOWN] = 'markdown';
1628 $value = "error";
1629 if (!is_numeric($key)) {
1630 $key = strtolower( $key );
1631 $value = array_search( $key, $lookup );
1633 else {
1634 if (isset( $lookup[$key] )) {
1635 $value = $lookup[ $key ];
1638 return $value;
1642 * Resets all data related to filters, called during upgrade or when filter settings change.
1643 * @return void
1645 function reset_text_filters_cache() {
1646 global $CFG;
1648 delete_records('cache_text');
1649 $purifdir = $CFG->dataroot.'/cache/htmlpurifier';
1650 remove_dir($purifdir, true);
1653 /** Given a simple string, this function returns the string
1654 * processed by enabled string filters if $CFG->filterall is enabled
1656 * This function should be used to print short strings (non html) that
1657 * need filter processing e.g. activity titles, post subjects,
1658 * glossary concepts.
1660 * @param string $string The string to be filtered.
1661 * @param boolean $striplinks To strip any link in the result text (Moodle 1.8 default changed from false to true! MDL-8713)
1662 * @param int $courseid Current course as filters can, potentially, use it
1663 * @return string
1665 function format_string ($string, $striplinks=true, $courseid=NULL ) {
1667 global $CFG, $COURSE;
1669 //We'll use a in-memory cache here to speed up repeated strings
1670 static $strcache = false;
1672 if ($strcache === false or count($strcache) > 2000 ) { // this number might need some tuning to limit memory usage in cron
1673 $strcache = array();
1676 //init course id
1677 if (empty($courseid)) {
1678 $courseid = $COURSE->id;
1681 //Calculate md5
1682 $md5 = md5($string.'<+>'.$striplinks.'<+>'.$courseid.'<+>'.current_language());
1684 //Fetch from cache if possible
1685 if (isset($strcache[$md5])) {
1686 return $strcache[$md5];
1689 // First replace all ampersands not followed by html entity code
1690 $string = preg_replace("/\&(?![a-zA-Z0-9#]{1,8};)/", "&amp;", $string);
1692 if (!empty($CFG->filterall)) {
1693 $string = filter_string($string, $courseid);
1696 // If the site requires it, strip ALL tags from this string
1697 if (!empty($CFG->formatstringstriptags)) {
1698 $string = strip_tags($string);
1700 } else {
1701 // Otherwise strip just links if that is required (default)
1702 if ($striplinks) { //strip links in string
1703 $string = preg_replace('/(<a\s[^>]+?>)(.+?)(<\/a>)/is','$2',$string);
1705 $string = clean_text($string);
1708 //Store to cache
1709 $strcache[$md5] = $string;
1711 return $string;
1715 * Given text in a variety of format codings, this function returns
1716 * the text as plain text suitable for plain email.
1718 * @uses FORMAT_MOODLE
1719 * @uses FORMAT_HTML
1720 * @uses FORMAT_PLAIN
1721 * @uses FORMAT_WIKI
1722 * @uses FORMAT_MARKDOWN
1723 * @param string $text The text to be formatted. This is raw text originally from user input.
1724 * @param int $format Identifier of the text format to be used
1725 * (FORMAT_MOODLE, FORMAT_HTML, FORMAT_PLAIN, FORMAT_WIKI, FORMAT_MARKDOWN)
1726 * @return string
1728 function format_text_email($text, $format) {
1730 switch ($format) {
1732 case FORMAT_PLAIN:
1733 return $text;
1734 break;
1736 case FORMAT_WIKI:
1737 $text = wiki_to_html($text);
1738 /// This expression turns links into something nice in a text format. (Russell Jungwirth)
1739 /// From: http://php.net/manual/en/function.eregi-replace.php and simplified
1740 $text = eregi_replace('(<a [^<]*href=["|\']?([^ "\']*)["|\']?[^>]*>([^<]*)</a>)','\\3 [ \\2 ]', $text);
1741 return strtr(strip_tags($text), array_flip(get_html_translation_table(HTML_ENTITIES)));
1742 break;
1744 case FORMAT_HTML:
1745 return html_to_text($text);
1746 break;
1748 case FORMAT_MOODLE:
1749 case FORMAT_MARKDOWN:
1750 default:
1751 $text = eregi_replace('(<a [^<]*href=["|\']?([^ "\']*)["|\']?[^>]*>([^<]*)</a>)','\\3 [ \\2 ]', $text);
1752 return strtr(strip_tags($text), array_flip(get_html_translation_table(HTML_ENTITIES)));
1753 break;
1758 * Given some text in HTML format, this function will pass it
1759 * through any filters that have been defined in $CFG->textfilterx
1760 * The variable defines a filepath to a file containing the
1761 * filter function. The file must contain a variable called
1762 * $textfilter_function which contains the name of the function
1763 * with $courseid and $text parameters
1765 * @param string $text The text to be passed through format filters
1766 * @param int $courseid ?
1767 * @return string
1768 * @todo Finish documenting this function
1770 function filter_text($text, $courseid=NULL) {
1771 global $CFG, $COURSE;
1773 if (empty($courseid)) {
1774 $courseid = $COURSE->id; // (copied from format_text)
1777 if (!empty($CFG->textfilters)) {
1778 require_once($CFG->libdir.'/filterlib.php');
1779 $textfilters = explode(',', $CFG->textfilters);
1780 foreach ($textfilters as $textfilter) {
1781 if (is_readable($CFG->dirroot .'/'. $textfilter .'/filter.php')) {
1782 include_once($CFG->dirroot .'/'. $textfilter .'/filter.php');
1783 $functionname = basename($textfilter).'_filter';
1784 if (function_exists($functionname)) {
1785 $text = $functionname($courseid, $text);
1791 /// <nolink> tags removed for XHTML compatibility
1792 $text = str_replace('<nolink>', '', $text);
1793 $text = str_replace('</nolink>', '', $text);
1795 return $text;
1800 * Given a string (short text) in HTML format, this function will pass it
1801 * through any filters that have been defined in $CFG->stringfilters
1802 * The variable defines a filepath to a file containing the
1803 * filter function. The file must contain a variable called
1804 * $textfilter_function which contains the name of the function
1805 * with $courseid and $text parameters
1807 * @param string $string The text to be passed through format filters
1808 * @param int $courseid The id of a course
1809 * @return string
1811 function filter_string($string, $courseid=NULL) {
1812 global $CFG, $COURSE;
1814 if (empty($CFG->textfilters)) { // All filters are disabled anyway so quit
1815 return $string;
1818 if (empty($courseid)) {
1819 $courseid = $COURSE->id;
1822 require_once($CFG->libdir.'/filterlib.php');
1824 if (isset($CFG->stringfilters)) { // We have a predefined list to use, great!
1825 if (empty($CFG->stringfilters)) { // but it's blank, so finish now
1826 return $string;
1828 $stringfilters = explode(',', $CFG->stringfilters); // ..use the list we have
1830 } else { // Otherwise try to derive a list from textfilters
1831 if (strpos($CFG->textfilters, 'filter/multilang') !== false) { // Multilang is here
1832 $stringfilters = array('filter/multilang'); // Let's use just that
1833 $CFG->stringfilters = 'filter/multilang'; // Save it for next time through
1834 } else {
1835 $CFG->stringfilters = ''; // Save the result and return
1836 return $string;
1841 foreach ($stringfilters as $stringfilter) {
1842 if (is_readable($CFG->dirroot .'/'. $stringfilter .'/filter.php')) {
1843 include_once($CFG->dirroot .'/'. $stringfilter .'/filter.php');
1844 $functionname = basename($stringfilter).'_filter';
1845 if (function_exists($functionname)) {
1846 $string = $functionname($courseid, $string);
1851 /// <nolink> tags removed for XHTML compatibility
1852 $string = str_replace('<nolink>', '', $string);
1853 $string = str_replace('</nolink>', '', $string);
1855 return $string;
1859 * Is the text marked as trusted?
1861 * @param string $text text to be searched for TRUSTTEXT marker
1862 * @return boolean
1864 function trusttext_present($text) {
1865 if (strpos($text, TRUSTTEXT) !== FALSE) {
1866 return true;
1867 } else {
1868 return false;
1873 * This funtion MUST be called before the cleaning or any other
1874 * function that modifies the data! We do not know the origin of trusttext
1875 * in database, if it gets there in tweaked form we must not convert it
1876 * to supported form!!!
1878 * Please be carefull not to use stripslashes on data from database
1879 * or twice stripslashes when processing data recieved from user.
1881 * @param string $text text that may contain TRUSTTEXT marker
1882 * @return text without any TRUSTTEXT marker
1884 function trusttext_strip($text) {
1885 global $CFG;
1887 while (true) { //removing nested TRUSTTEXT
1888 $orig = $text;
1889 $text = str_replace(TRUSTTEXT, '', $text);
1890 if (strcmp($orig, $text) === 0) {
1891 return $text;
1897 * Mark text as trusted, such text may contain any HTML tags because the
1898 * normal text cleaning will be bypassed.
1899 * Please make sure that the text comes from trusted user before storing
1900 * it into database!
1902 function trusttext_mark($text) {
1903 global $CFG;
1904 if (!empty($CFG->enabletrusttext) and (strpos($text, TRUSTTEXT) === FALSE)) {
1905 return TRUSTTEXT.$text;
1906 } else {
1907 return $text;
1910 function trusttext_after_edit(&$text, $context) {
1911 if (has_capability('moodle/site:trustcontent', $context)) {
1912 $text = trusttext_strip($text);
1913 $text = trusttext_mark($text);
1914 } else {
1915 $text = trusttext_strip($text);
1919 function trusttext_prepare_edit(&$text, &$format, $usehtmleditor, $context) {
1920 global $CFG;
1922 $options = new object();
1923 $options->smiley = false;
1924 $options->filter = false;
1925 if (!empty($CFG->enabletrusttext)
1926 and has_capability('moodle/site:trustcontent', $context)
1927 and trusttext_present($text)) {
1928 $options->noclean = true;
1929 } else {
1930 $options->noclean = false;
1932 $text = trusttext_strip($text);
1933 if ($usehtmleditor) {
1934 $text = format_text($text, $format, $options);
1935 $format = FORMAT_HTML;
1936 } else if (!$options->noclean){
1937 $text = clean_text($text, $format);
1942 * Given raw text (eg typed in by a user), this function cleans it up
1943 * and removes any nasty tags that could mess up Moodle pages.
1945 * @uses FORMAT_MOODLE
1946 * @uses FORMAT_PLAIN
1947 * @uses ALLOWED_TAGS
1948 * @param string $text The text to be cleaned
1949 * @param int $format Identifier of the text format to be used
1950 * (FORMAT_MOODLE, FORMAT_HTML, FORMAT_PLAIN, FORMAT_WIKI, FORMAT_MARKDOWN)
1951 * @return string The cleaned up text
1953 function clean_text($text, $format=FORMAT_MOODLE) {
1955 global $ALLOWED_TAGS, $CFG;
1957 if (empty($text) or is_numeric($text)) {
1958 return (string)$text;
1961 switch ($format) {
1962 case FORMAT_PLAIN:
1963 case FORMAT_MARKDOWN:
1964 return $text;
1966 default:
1968 if (!empty($CFG->enablehtmlpurifier)) {
1969 $text = purify_html($text);
1970 } else {
1971 /// Fix non standard entity notations
1972 $text = preg_replace('/(&#[0-9]+)(;?)/', "\\1;", $text);
1973 $text = preg_replace('/(&#x[0-9a-fA-F]+)(;?)/', "\\1;", $text);
1975 /// Remove tags that are not allowed
1976 $text = strip_tags($text, $ALLOWED_TAGS);
1978 /// Clean up embedded scripts and , using kses
1979 $text = cleanAttributes($text);
1981 /// Again remove tags that are not allowed
1982 $text = strip_tags($text, $ALLOWED_TAGS);
1986 /// Remove potential script events - some extra protection for undiscovered bugs in our code
1987 $text = eregi_replace("([^a-z])language([[:space:]]*)=", "\\1Xlanguage=", $text);
1988 $text = eregi_replace("([^a-z])on([a-z]+)([[:space:]]*)=", "\\1Xon\\2=", $text);
1990 return $text;
1995 * KSES replacement cleaning function - uses HTML Purifier.
1997 function purify_html($text) {
1998 global $CFG;
2000 // this can not be done only once because we sometimes need to reset the cache
2001 $cachedir = $CFG->dataroot.'/cache/htmlpurifier/';
2002 $status = check_dir_exists($cachedir, true, true);
2004 static $purifier = false;
2005 if ($purifier === false) {
2006 require_once $CFG->libdir.'/htmlpurifier/HTMLPurifier.auto.php';
2007 $config = HTMLPurifier_Config::createDefault();
2008 $config->set('Core', 'AcceptFullDocuments', false);
2009 $config->set('Core', 'Encoding', 'UTF-8');
2010 $config->set('HTML', 'Doctype', 'XHTML 1.0 Transitional');
2011 $config->set('Cache', 'SerializerPath', $cachedir);
2012 $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));
2013 $purifier = new HTMLPurifier($config);
2015 return $purifier->purify($text);
2019 * This function takes a string and examines it for HTML tags.
2020 * If tags are detected it passes the string to a helper function {@link cleanAttributes2()}
2021 * which checks for attributes and filters them for malicious content
2022 * 17/08/2004 :: Eamon DOT Costello AT dcu DOT ie
2024 * @param string $str The string to be examined for html tags
2025 * @return string
2027 function cleanAttributes($str){
2028 $result = preg_replace_callback(
2029 '%(<[^>]*(>|$)|>)%m', #search for html tags
2030 "cleanAttributes2",
2031 $str
2033 return $result;
2037 * This function takes a string with an html tag and strips out any unallowed
2038 * protocols e.g. javascript:
2039 * It calls ancillary functions in kses which are prefixed by kses
2040 * 17/08/2004 :: Eamon DOT Costello AT dcu DOT ie
2042 * @param array $htmlArray An array from {@link cleanAttributes()}, containing in its 1st
2043 * element the html to be cleared
2044 * @return string
2046 function cleanAttributes2($htmlArray){
2048 global $CFG, $ALLOWED_PROTOCOLS;
2049 require_once($CFG->libdir .'/kses.php');
2051 $htmlTag = $htmlArray[1];
2052 if (substr($htmlTag, 0, 1) != '<') {
2053 return '&gt;'; //a single character ">" detected
2055 if (!preg_match('%^<\s*(/\s*)?([a-zA-Z0-9]+)([^>]*)>?$%', $htmlTag, $matches)) {
2056 return ''; // It's seriously malformed
2058 $slash = trim($matches[1]); //trailing xhtml slash
2059 $elem = $matches[2]; //the element name
2060 $attrlist = $matches[3]; // the list of attributes as a string
2062 $attrArray = kses_hair($attrlist, $ALLOWED_PROTOCOLS);
2064 $attStr = '';
2065 foreach ($attrArray as $arreach) {
2066 $arreach['name'] = strtolower($arreach['name']);
2067 if ($arreach['name'] == 'style') {
2068 $value = $arreach['value'];
2069 while (true) {
2070 $prevvalue = $value;
2071 $value = kses_no_null($value);
2072 $value = preg_replace("/\/\*.*\*\//Us", '', $value);
2073 $value = kses_decode_entities($value);
2074 $value = preg_replace('/(&#[0-9]+)(;?)/', "\\1;", $value);
2075 $value = preg_replace('/(&#x[0-9a-fA-F]+)(;?)/', "\\1;", $value);
2076 if ($value === $prevvalue) {
2077 $arreach['value'] = $value;
2078 break;
2081 $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']);
2082 $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']);
2083 $arreach['value'] = preg_replace("/b\s*i\s*n\s*d\s*i\s*n\s*g/i", "Xbinding", $arreach['value']);
2084 } else if ($arreach['name'] == 'href') {
2085 //Adobe Acrobat Reader XSS protection
2086 $arreach['value'] = preg_replace('/(\.(pdf|fdf|xfdf|xdp|xfd))[^a-z0-9_\.\-].*$/i', '$1', $arreach['value']);
2088 $attStr .= ' '.$arreach['name'].'="'.$arreach['value'].'"';
2091 $xhtml_slash = '';
2092 if (preg_match('%/\s*$%', $attrlist)) {
2093 $xhtml_slash = ' /';
2095 return '<'. $slash . $elem . $attStr . $xhtml_slash .'>';
2099 * Replaces all known smileys in the text with image equivalents
2101 * @uses $CFG
2102 * @param string $text Passed by reference. The string to search for smily strings.
2103 * @return string
2105 function replace_smilies(&$text) {
2107 global $CFG;
2109 if (empty($CFG->emoticons)) { /// No emoticons defined, nothing to process here
2110 return;
2113 $lang = current_language();
2114 $emoticonstring = $CFG->emoticons;
2115 static $e = array();
2116 static $img = array();
2117 static $emoticons = null;
2119 if (is_null($emoticons)) {
2120 $emoticons = array();
2121 if ($emoticonstring) {
2122 $items = explode('{;}', $CFG->emoticons);
2123 foreach ($items as $item) {
2124 $item = explode('{:}', $item);
2125 $emoticons[$item[0]] = $item[1];
2131 if (empty($img[$lang])) { /// After the first time this is not run again
2132 $e[$lang] = array();
2133 $img[$lang] = array();
2134 foreach ($emoticons as $emoticon => $image){
2135 $alttext = get_string($image, 'pix');
2136 $e[$lang][] = $emoticon;
2137 $img[$lang][] = '<img alt="'. $alttext .'" width="15" height="15" src="'. $CFG->pixpath .'/s/'. $image .'.gif" />';
2141 // Exclude from transformations all the code inside <script> tags
2142 // Needed to solve Bug 1185. Thanks to jouse 2001 detecting it. :-)
2143 // Based on code from glossary fiter by Williams Castillo.
2144 // - Eloy
2146 // Detect all the <script> zones to take out
2147 $excludes = array();
2148 preg_match_all('/<script language(.+?)<\/script>/is',$text,$list_of_excludes);
2150 // Take out all the <script> zones from text
2151 foreach (array_unique($list_of_excludes[0]) as $key=>$value) {
2152 $excludes['<+'.$key.'+>'] = $value;
2154 if ($excludes) {
2155 $text = str_replace($excludes,array_keys($excludes),$text);
2158 /// this is the meat of the code - this is run every time
2159 $text = str_replace($e[$lang], $img[$lang], $text);
2161 // Recover all the <script> zones to text
2162 if ($excludes) {
2163 $text = str_replace(array_keys($excludes),$excludes,$text);
2168 * Given plain text, makes it into HTML as nicely as possible.
2169 * May contain HTML tags already
2171 * @uses $CFG
2172 * @param string $text The string to convert.
2173 * @param boolean $smiley Convert any smiley characters to smiley images?
2174 * @param boolean $para If true then the returned string will be wrapped in paragraph tags
2175 * @param boolean $newlines If true then lines newline breaks will be converted to HTML newline breaks.
2176 * @return string
2179 function text_to_html($text, $smiley=true, $para=true, $newlines=true) {
2182 global $CFG;
2184 /// Remove any whitespace that may be between HTML tags
2185 $text = eregi_replace(">([[:space:]]+)<", "><", $text);
2187 /// Remove any returns that precede or follow HTML tags
2188 $text = eregi_replace("([\n\r])<", " <", $text);
2189 $text = eregi_replace(">([\n\r])", "> ", $text);
2191 convert_urls_into_links($text);
2193 /// Make returns into HTML newlines.
2194 if ($newlines) {
2195 $text = nl2br($text);
2198 /// Turn smileys into images.
2199 if ($smiley) {
2200 replace_smilies($text);
2203 /// Wrap the whole thing in a paragraph tag if required
2204 if ($para) {
2205 return '<p>'.$text.'</p>';
2206 } else {
2207 return $text;
2212 * Given Markdown formatted text, make it into XHTML using external function
2214 * @uses $CFG
2215 * @param string $text The markdown formatted text to be converted.
2216 * @return string Converted text
2218 function markdown_to_html($text) {
2219 global $CFG;
2221 require_once($CFG->libdir .'/markdown.php');
2223 return Markdown($text);
2227 * Given HTML text, make it into plain text using external function
2229 * @uses $CFG
2230 * @param string $html The text to be converted.
2231 * @return string
2233 function html_to_text($html) {
2235 global $CFG;
2237 require_once($CFG->libdir .'/html2text.php');
2239 $result = html2text($html);
2241 // html2text does not fix numerical entities so handle those here.
2242 $tl=textlib_get_instance();
2243 $result = $tl->entities_to_utf8($result,false);
2245 return $result;
2249 * Given some text this function converts any URLs it finds into HTML links
2251 * @param string $text Passed in by reference. The string to be searched for urls.
2253 function convert_urls_into_links(&$text) {
2254 /// Make lone URLs into links. eg http://moodle.com/
2255 $text = eregi_replace("([[:space:]]|^|\(|\[)([[:alnum:]]+)://([^[:space:]]*)([[:alnum:]#?/&=])",
2256 "\\1<a href=\"\\2://\\3\\4\" target=\"_blank\">\\2://\\3\\4</a>", $text);
2258 /// eg www.moodle.com
2259 $text = eregi_replace("([[:space:]]|^|\(|\[)www\.([^[:space:]]*)([[:alnum:]#?/&=])",
2260 "\\1<a href=\"http://www.\\2\\3\" target=\"_blank\">www.\\2\\3</a>", $text);
2264 * This function will highlight search words in a given string
2265 * It cares about HTML and will not ruin links. It's best to use
2266 * this function after performing any conversions to HTML.
2267 * Function found here: http://forums.devshed.com/t67822/scdaa2d1c3d4bacb4671d075ad41f0854.html
2269 * @param string $needle The string to search for
2270 * @param string $haystack The string to search for $needle in
2271 * @param int $case whether to do case-sensitive or insensitive matching.
2272 * @return string
2273 * @todo Finish documenting this function
2275 function highlight($needle, $haystack, $case=0,
2276 $left_string='<span class="highlight">', $right_string='</span>') {
2278 if (empty($needle) or empty($haystack)) {
2279 return $haystack;
2282 //$list_of_words = eregi_replace("[^-a-zA-Z0-9&.']", " ", $needle); // bug 3101
2283 $list_of_words = $needle;
2284 $list_array = explode(' ', $list_of_words);
2285 for ($i=0; $i<sizeof($list_array); $i++) {
2286 if (strlen($list_array[$i]) == 1) {
2287 $list_array[$i] = '';
2290 $list_of_words = implode(' ', $list_array);
2291 $list_of_words_cp = $list_of_words;
2292 $final = array();
2293 preg_match_all('/<(.+?)>/is',$haystack,$list_of_words);
2295 foreach (array_unique($list_of_words[0]) as $key=>$value) {
2296 $final['<|'.$key.'|>'] = $value;
2299 $haystack = str_replace($final,array_keys($final),$haystack);
2300 $list_of_words_cp = eregi_replace(' +', '|', $list_of_words_cp);
2302 if ($list_of_words_cp{0}=='|') {
2303 $list_of_words_cp{0} = '';
2305 if ($list_of_words_cp{strlen($list_of_words_cp)-1}=='|') {
2306 $list_of_words_cp{strlen($list_of_words_cp)-1}='';
2309 $list_of_words_cp = trim($list_of_words_cp);
2311 if ($list_of_words_cp) {
2313 $list_of_words_cp = "(". $list_of_words_cp .")";
2315 if (!$case){
2316 $haystack = eregi_replace("$list_of_words_cp", "$left_string"."\\1"."$right_string", $haystack);
2317 } else {
2318 $haystack = ereg_replace("$list_of_words_cp", "$left_string"."\\1"."$right_string", $haystack);
2321 $haystack = str_replace(array_keys($final),$final,$haystack);
2323 return $haystack;
2327 * This function will highlight instances of $needle in $haystack
2328 * It's faster that the above function and doesn't care about
2329 * HTML or anything.
2331 * @param string $needle The string to search for
2332 * @param string $haystack The string to search for $needle in
2333 * @return string
2335 function highlightfast($needle, $haystack) {
2337 if (empty($needle) or empty($haystack)) {
2338 return $haystack;
2341 $parts = explode(moodle_strtolower($needle), moodle_strtolower($haystack));
2343 if (count($parts) === 1) {
2344 return $haystack;
2347 $pos = 0;
2349 foreach ($parts as $key => $part) {
2350 $parts[$key] = substr($haystack, $pos, strlen($part));
2351 $pos += strlen($part);
2353 $parts[$key] .= '<span class="highlight">'.substr($haystack, $pos, strlen($needle)).'</span>';
2354 $pos += strlen($needle);
2357 return str_replace('<span class="highlight"></span>', '', join('', $parts));
2361 * Return a string containing 'lang', xml:lang and optionally 'dir' HTML attributes.
2362 * Internationalisation, for print_header and backup/restorelib.
2363 * @param $dir Default false.
2364 * @return string Attributes.
2366 function get_html_lang($dir = false) {
2367 $direction = '';
2368 if ($dir) {
2369 if (get_string('thisdirection') == 'rtl') {
2370 $direction = ' dir="rtl"';
2371 } else {
2372 $direction = ' dir="ltr"';
2375 //Accessibility: added the 'lang' attribute to $direction, used in theme <html> tag.
2376 $language = str_replace('_', '-', str_replace('_utf8', '', current_language()));
2377 @header('Content-Language: '.$language);
2378 return ($direction.' lang="'.$language.'" xml:lang="'.$language.'"');
2382 * Return the markup for the destination of the 'Skip to main content' links.
2383 * Accessibility improvement for keyboard-only users.
2384 * Used in course formats, /index.php and /course/index.php
2385 * @return string HTML element.
2387 function skip_main_destination() {
2388 return '<span id="maincontent"></span>';
2392 /// STANDARD WEB PAGE PARTS ///////////////////////////////////////////////////
2395 * Print a standard header
2397 * @uses $USER
2398 * @uses $CFG
2399 * @uses $SESSION
2400 * @param string $title Appears at the top of the window
2401 * @param string $heading Appears at the top of the page
2402 * @param array $navigation Array of $navlinks arrays (keys: name, link, type) for use as breadcrumbs links
2403 * @param string $focus Indicates form element to get cursor focus on load eg inputform.password
2404 * @param string $meta Meta tags to be added to the header
2405 * @param boolean $cache Should this page be cacheable?
2406 * @param string $button HTML code for a button (usually for module editing)
2407 * @param string $menu HTML code for a popup menu
2408 * @param boolean $usexml use XML for this page
2409 * @param string $bodytags This text will be included verbatim in the <body> tag (useful for onload() etc)
2410 * @param bool $return If true, return the visible elements of the header instead of echoing them.
2412 function print_header ($title='', $heading='', $navigation='', $focus='',
2413 $meta='', $cache=true, $button='&nbsp;', $menu='',
2414 $usexml=false, $bodytags='', $return=false) {
2416 global $USER, $CFG, $THEME, $SESSION, $ME, $SITE, $COURSE;
2418 if (gettype($navigation) == 'string' && strlen($navigation) != 0 && $navigation != 'home') {
2419 debugging("print_header() was sent a string as 3rd ($navigation) parameter. "
2420 . "This is deprecated in favour of an array built by build_navigation(). Please upgrade your code.", DEBUG_DEVELOPER);
2423 $heading = format_string($heading); // Fix for MDL-8582
2425 /// This makes sure that the header is never repeated twice on a page
2426 if (defined('HEADER_PRINTED')) {
2427 debugging('print_header() was called more than once - this should not happen. Please check the code for this page closely. Note: error() and redirect() are now safe to call after print_header().');
2428 return;
2430 define('HEADER_PRINTED', 'true');
2433 /// Add the required stylesheets
2434 $stylesheetshtml = '';
2435 foreach ($CFG->stylesheets as $stylesheet) {
2436 $stylesheetshtml .= '<link rel="stylesheet" type="text/css" href="'.$stylesheet.'" />'."\n";
2438 $meta = $stylesheetshtml.$meta;
2441 /// Add the meta page from the themes if any were requested
2443 $metapage = '';
2445 if (!isset($THEME->standardmetainclude) || $THEME->standardmetainclude) {
2446 ob_start();
2447 include_once($CFG->dirroot.'/theme/standard/meta.php');
2448 $metapage .= ob_get_contents();
2449 ob_end_clean();
2452 if ($THEME->parent && (!isset($THEME->parentmetainclude) || $THEME->parentmetainclude)) {
2453 if (file_exists($CFG->dirroot.'/theme/'.$THEME->parent.'/meta.php')) {
2454 ob_start();
2455 include_once($CFG->dirroot.'/theme/'.$THEME->parent.'/meta.php');
2456 $metapage .= ob_get_contents();
2457 ob_end_clean();
2461 if (!isset($THEME->metainclude) || $THEME->metainclude) {
2462 if (file_exists($CFG->dirroot.'/theme/'.current_theme().'/meta.php')) {
2463 ob_start();
2464 include_once($CFG->dirroot.'/theme/'.current_theme().'/meta.php');
2465 $metapage .= ob_get_contents();
2466 ob_end_clean();
2470 $meta = $meta."\n".$metapage;
2472 $meta .= "\n".require_js('',1);
2474 /// Set up some navigation variables
2476 if (is_newnav($navigation)){
2477 $home = false;
2478 } else {
2479 if ($navigation == 'home') {
2480 $home = true;
2481 $navigation = '';
2482 } else {
2483 $home = false;
2487 /// This is another ugly hack to make navigation elements available to print_footer later
2488 $THEME->title = $title;
2489 $THEME->heading = $heading;
2490 $THEME->navigation = $navigation;
2491 $THEME->button = $button;
2492 $THEME->menu = $menu;
2493 $navmenulist = isset($THEME->navmenulist) ? $THEME->navmenulist : '';
2495 if ($button == '') {
2496 $button = '&nbsp;';
2499 if (file_exists($CFG->dataroot.'/'.SITEID.'/maintenance.html')) {
2500 $button = '<a href="'.$CFG->wwwroot.'/admin/maintenance.php">'.get_string('maintenancemode', 'admin').'</a> '.$button;
2501 if(!empty($title)) {
2502 $title .= ' - ';
2504 $title .= get_string('maintenancemode', 'admin');
2507 if (!$menu and $navigation) {
2508 if (empty($CFG->loginhttps)) {
2509 $wwwroot = $CFG->wwwroot;
2510 } else {
2512 $wwwroot = str_replace('http:','https:',$CFG->wwwroot);
2514 $menu = user_login_string($COURSE);
2517 if (isset($SESSION->justloggedin)) {
2518 unset($SESSION->justloggedin);
2519 if (!empty($CFG->displayloginfailures)) {
2520 if (!empty($USER->username) and $USER->username != 'guest') {
2521 if ($count = count_login_failures($CFG->displayloginfailures, $USER->username, $USER->lastlogin)) {
2522 $menu .= '&nbsp;<font size="1">';
2523 if (empty($count->accounts)) {
2524 $menu .= get_string('failedloginattempts', '', $count);
2525 } else {
2526 $menu .= get_string('failedloginattemptsall', '', $count);
2528 if (has_capability('moodle/site:viewreports', get_context_instance(CONTEXT_SYSTEM))) {
2529 $menu .= ' (<a href="'.$CFG->wwwroot.'/course/report/log/index.php'.
2530 '?chooselog=1&amp;id=1&amp;modid=site_errors">'.get_string('logs').'</a>)';
2532 $menu .= '</font>';
2539 $meta = '<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />' .
2540 "\n" . $meta . "\n";
2541 if (!$usexml) {
2542 @header('Content-Type: text/html; charset=utf-8');
2544 @header('Content-Script-Type: text/javascript');
2545 @header('Content-Style-Type: text/css');
2547 //Accessibility: added the 'lang' attribute to $direction, used in theme <html> tag.
2548 $direction = get_html_lang($dir=true);
2550 if ($cache) { // Allow caching on "back" (but not on normal clicks)
2551 @header('Cache-Control: private, pre-check=0, post-check=0, max-age=0');
2552 @header('Pragma: no-cache');
2553 @header('Expires: ');
2554 } else { // Do everything we can to always prevent clients and proxies caching
2555 @header('Cache-Control: no-store, no-cache, must-revalidate');
2556 @header('Cache-Control: post-check=0, pre-check=0', false);
2557 @header('Pragma: no-cache');
2558 @header('Expires: Mon, 20 Aug 1969 09:23:00 GMT');
2559 @header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
2561 $meta .= "\n<meta http-equiv=\"pragma\" content=\"no-cache\" />";
2562 $meta .= "\n<meta http-equiv=\"expires\" content=\"0\" />";
2564 @header('Accept-Ranges: none');
2566 $currentlanguage = current_language();
2568 if (empty($usexml)) {
2569 $direction = ' xmlns="http://www.w3.org/1999/xhtml"'. $direction; // See debug_header
2570 } else {
2571 $mathplayer = preg_match("/MathPlayer/i", $_SERVER['HTTP_USER_AGENT']);
2572 if(!$mathplayer) {
2573 header('Content-Type: application/xhtml+xml');
2575 echo '<?xml version="1.0" ?>'."\n";
2576 if (!empty($CFG->xml_stylesheets)) {
2577 $stylesheets = explode(';', $CFG->xml_stylesheets);
2578 foreach ($stylesheets as $stylesheet) {
2579 echo '<?xml-stylesheet type="text/xsl" href="'. $CFG->wwwroot .'/'. $stylesheet .'" ?>' . "\n";
2582 echo '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1';
2583 if (!empty($CFG->xml_doctype_extra)) {
2584 echo ' plus '. $CFG->xml_doctype_extra;
2586 echo '//' . strtoupper($currentlanguage) . '" "'. $CFG->xml_dtd .'">'."\n";
2587 $direction = " xmlns=\"http://www.w3.org/1999/xhtml\"
2588 xmlns:math=\"http://www.w3.org/1998/Math/MathML\"
2589 xmlns:xlink=\"http://www.w3.org/1999/xlink\"
2590 $direction";
2591 if($mathplayer) {
2592 $meta .= '<object id="mathplayer" classid="clsid:32F66A20-7614-11D4-BD11-00104BD3F987">' . "\n";
2593 $meta .= '<!--comment required to prevent this becoming an empty tag-->'."\n";
2594 $meta .= '</object>'."\n";
2595 $meta .= '<?import namespace="math" implementation="#mathplayer" ?>' . "\n";
2599 // Clean up the title
2601 $title = format_string($title); // fix for MDL-8582
2602 $title = str_replace('"', '&quot;', $title);
2604 // Create class and id for this page
2606 page_id_and_class($pageid, $pageclass);
2608 $pageclass .= ' course-'.$COURSE->id;
2610 if (!isloggedin()) {
2611 $pageclass .= ' notloggedin';
2614 if (!empty($USER->editing)) {
2615 $pageclass .= ' editing';
2618 if (!empty($CFG->blocksdrag)) {
2619 $pageclass .= ' drag';
2622 $pageclass .= ' dir-'.get_string('thisdirection');
2624 $pageclass .= ' lang-'.$currentlanguage;
2626 $bodytags .= ' class="'.$pageclass.'" id="'.$pageid.'"';
2628 ob_start();
2629 include($CFG->header);
2630 $output = ob_get_contents();
2631 ob_end_clean();
2633 // container debugging info
2634 $THEME->open_header_containers = open_containers();
2636 // Skip to main content, see skip_main_destination().
2637 if ($pageid=='course-view' or $pageid=='site-index' or $pageid=='course-index') {
2638 $skiplink = '<a class="skip" href="#maincontent">'.get_string('tocontent', 'access').'</a>';
2639 if (! preg_match('/(.*<div[^>]+id="page"[^>]*>)(.*)/s', $output, $matches)) {
2640 preg_match('/(.*<body.*?>)(.*)/s', $output, $matches);
2642 $output = $matches[1]."\n". $skiplink .$matches[2];
2645 $output = force_strict_header($output);
2647 if (!empty($CFG->messaging)) {
2648 $output .= message_popup_window();
2651 // Add in any extra JavaScript libraries that occurred during the header
2652 $output .= require_js('', 2);
2654 if ($return) {
2655 return $output;
2656 } else {
2657 echo $output;
2662 * Used to include JavaScript libraries.
2664 * When the $lib parameter is given, the function will ensure that the
2665 * named library is loaded onto the page - either in the HTML <head>,
2666 * just after the header, or at an arbitrary later point in the page,
2667 * depending on where this function is called.
2669 * Libraries will not be included more than once, so this works like
2670 * require_once in PHP.
2672 * There are two special-case calls to this function which are both used only
2673 * by weblib print_header:
2674 * $extracthtml = 1: this is used before printing the header.
2675 * It returns the script tag code that should go inside the <head>.
2676 * $extracthtml = 2: this is used after printing the header and handles any
2677 * require_js calls that occurred within the header itself.
2679 * @param mixed $lib - string or array of strings
2680 * string(s) should be the shortname for the library or the
2681 * full path to the library file.
2682 * @param int $extracthtml Do not set this parameter usually (leave 0), only
2683 * weblib should set this to 1 or 2 in print_header function.
2684 * @return mixed No return value, except when using $extracthtml it returns the html code.
2686 function require_js($lib,$extracthtml=0) {
2687 global $CFG;
2688 static $loadlibs = array();
2690 static $state = REQUIREJS_BEFOREHEADER;
2691 static $latecode = '';
2693 if (!empty($lib)) {
2694 // Add the lib to the list of libs to be loaded, if it isn't already
2695 // in the list.
2696 if (is_array($lib)) {
2697 foreach($lib as $singlelib) {
2698 require_js($singlelib);
2700 } else {
2701 $libpath = ajax_get_lib($lib);
2702 if (array_search($libpath, $loadlibs) === false) {
2703 $loadlibs[] = $libpath;
2705 // For state other than 0 we need to take action as well as just
2706 // adding it to loadlibs
2707 if($state != REQUIREJS_BEFOREHEADER) {
2708 // Get the script statement for this library
2709 $scriptstatement=get_require_js_code(array($libpath));
2711 if($state == REQUIREJS_AFTERHEADER) {
2712 // After the header, print it immediately
2713 print $scriptstatement;
2714 } else {
2715 // Haven't finished the header yet. Add it after the
2716 // header
2717 $latecode .= $scriptstatement;
2722 } else if($extracthtml==1) {
2723 if($state !== REQUIREJS_BEFOREHEADER) {
2724 debugging('Incorrect state in require_js (expected BEFOREHEADER): be careful not to call with empty $lib (except in print_header)');
2725 } else {
2726 $state = REQUIREJS_INHEADER;
2729 return get_require_js_code($loadlibs);
2730 } else if($extracthtml==2) {
2731 if($state !== REQUIREJS_INHEADER) {
2732 debugging('Incorrect state in require_js (expected INHEADER): be careful not to call with empty $lib (except in print_header)');
2733 return '';
2734 } else {
2735 $state = REQUIREJS_AFTERHEADER;
2736 return $latecode;
2738 } else {
2739 debugging('Unexpected value for $extracthtml');
2744 * Should not be called directly - use require_js. This function obtains the code
2745 * (script tags) needed to include JavaScript libraries.
2746 * @param array $loadlibs Array of library files to include
2747 * @return string HTML code to include them
2749 function get_require_js_code($loadlibs) {
2750 global $CFG;
2751 // Return the html needed to load the JavaScript files defined in
2752 // our list of libs to be loaded.
2753 $output = '';
2754 foreach ($loadlibs as $loadlib) {
2755 $output .= '<script type="text/javascript" ';
2756 $output .= " src=\"$loadlib\"></script>\n";
2757 if ($loadlib == $CFG->wwwroot.'/lib/yui/logger/logger-min.js') {
2758 // Special case, we need the CSS too.
2759 $output .= '<link type="text/css" rel="stylesheet" ';
2760 $output .= " href=\"{$CFG->wwwroot}/lib/yui/logger/assets/logger.css\" />\n";
2763 return $output;
2768 * Debugging aid: serve page as 'application/xhtml+xml' where possible,
2769 * and substitute the XHTML strict document type.
2770 * Note, requires the 'xmlns' fix in function print_header above.
2771 * See: http://tracker.moodle.org/browse/MDL-7883
2772 * TODO:
2774 function force_strict_header($output) {
2775 global $CFG;
2776 $strict = '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">';
2777 $xsl = '/lib/xhtml.xsl';
2779 if (!headers_sent() && !empty($CFG->xmlstrictheaders)) { // With xml strict headers, the browser will barf
2780 $ctype = 'Content-Type: ';
2781 $prolog= "<?xml version='1.0' encoding='utf-8'?>\n";
2783 if (isset($_SERVER['HTTP_ACCEPT'])
2784 && false !== strpos($_SERVER['HTTP_ACCEPT'], 'application/xhtml+xml')) {
2785 //|| false !== strpos($_SERVER['HTTP_USER_AGENT'], 'Safari') //Safari "Entity 'copy' not defined".
2786 // Firefox et al.
2787 $ctype .= 'application/xhtml+xml';
2788 $prolog .= "<!--\n DEBUG: $ctype \n-->\n";
2790 } else if (file_exists($CFG->dirroot.$xsl)
2791 && preg_match('/MSIE.*Windows NT/', $_SERVER['HTTP_USER_AGENT'])) {
2792 // XSL hack for IE 5+ on Windows.
2793 //$www_xsl = preg_replace('/(http:\/\/.+?\/).*/', '', $CFG->wwwroot) .$xsl;
2794 $www_xsl = $CFG->wwwroot .$xsl;
2795 $ctype .= 'application/xml';
2796 $prolog .= "<?xml-stylesheet type='text/xsl' href='$www_xsl'?>\n";
2797 $prolog .= "<!--\n DEBUG: $ctype \n-->\n";
2799 } else {
2800 //ELSE: Mac/IE, old/non-XML browsers.
2801 $ctype .= 'text/html';
2802 $prolog = '';
2804 @header($ctype.'; charset=utf-8');
2805 $output = $prolog . $output;
2807 // Test parser error-handling.
2808 if (isset($_GET['error'])) {
2809 $output .= "__ TEST: XML well-formed error < __\n";
2813 $output = preg_replace('/(<!DOCTYPE.+?>)/s', $strict, $output); // Always change the DOCTYPE to Strict 1.0
2815 return $output;
2821 * This version of print_header is simpler because the course name does not have to be
2822 * provided explicitly in the strings. It can be used on the site page as in courses
2823 * Eventually all print_header could be replaced by print_header_simple
2825 * @param string $title Appears at the top of the window
2826 * @param string $heading Appears at the top of the page
2827 * @param string $navigation Premade navigation string (for use as breadcrumbs links)
2828 * @param string $focus Indicates form element to get cursor focus on load eg inputform.password
2829 * @param string $meta Meta tags to be added to the header
2830 * @param boolean $cache Should this page be cacheable?
2831 * @param string $button HTML code for a button (usually for module editing)
2832 * @param string $menu HTML code for a popup menu
2833 * @param boolean $usexml use XML for this page
2834 * @param string $bodytags This text will be included verbatim in the <body> tag (useful for onload() etc)
2835 * @param bool $return If true, return the visible elements of the header instead of echoing them.
2837 function print_header_simple($title='', $heading='', $navigation='', $focus='', $meta='',
2838 $cache=true, $button='&nbsp;', $menu='', $usexml=false, $bodytags='', $return=false) {
2840 global $COURSE, $CFG;
2842 // if we have no navigation specified, build it
2843 if( empty($navigation) ){
2844 $navigation = build_navigation('');
2847 // If old style nav prepend course short name otherwise leave $navigation object alone
2848 if (!is_newnav($navigation)) {
2849 if ($COURSE->id != SITEID) {
2850 $shortname = '<a href="'.$CFG->wwwroot.'/course/view.php?id='. $COURSE->id .'">'. $COURSE->shortname .'</a> ->';
2851 $navigation = $shortname.' '.$navigation;
2855 $output = print_header($COURSE->shortname .': '. $title, $COURSE->fullname .' '. $heading, $navigation, $focus, $meta,
2856 $cache, $button, $menu, $usexml, $bodytags, true);
2858 if ($return) {
2859 return $output;
2860 } else {
2861 echo $output;
2867 * Can provide a course object to make the footer contain a link to
2868 * to the course home page, otherwise the link will go to the site home
2869 * @uses $USER
2870 * @param mixed $course course object, used for course link button or
2871 * 'none' means no user link, only docs link
2872 * 'empty' means nothing printed in footer
2873 * 'home' special frontpage footer
2874 * @param object $usercourse course used in user link
2875 * @param boolean $return output as string
2876 * @return mixed string or void
2878 function print_footer($course=NULL, $usercourse=NULL, $return=false) {
2879 global $USER, $CFG, $THEME, $COURSE;
2881 if (defined('ADMIN_EXT_HEADER_PRINTED') and !defined('ADMIN_EXT_FOOTER_PRINTED')) {
2882 admin_externalpage_print_footer();
2883 return;
2886 /// Course links or special footer
2887 if ($course) {
2888 if ($course === 'empty') {
2889 // special hack - sometimes we do not want even the docs link in footer
2890 $output = '';
2891 if (!empty($THEME->open_header_containers)) {
2892 for ($i=0; $i<$THEME->open_header_containers; $i++) {
2893 $output .= print_container_end_all(); // containers opened from header
2895 } else {
2896 //1.8 theme compatibility
2897 $output .= "\n</div>"; // content div
2899 $output .= "\n</div>\n</body>\n</html>"; // close page div started in header
2900 if ($return) {
2901 return $output;
2902 } else {
2903 echo $output;
2904 return;
2907 } else if ($course === 'none') { // Don't print any links etc
2908 $homelink = '';
2909 $loggedinas = '';
2910 $home = false;
2912 } else if ($course === 'home') { // special case for site home page - please do not remove
2913 $course = get_site();
2914 $homelink = '<div class="sitelink">'.
2915 '<a title="Moodle '. $CFG->release .'" href="http://moodle.org/">'.
2916 '<img style="width:100px;height:30px" src="pix/moodlelogo.gif" alt="moodlelogo" /></a></div>';
2917 $home = true;
2919 } else {
2920 $homelink = '<div class="homelink"><a '.$CFG->frametarget.' href="'.$CFG->wwwroot.
2921 '/course/view.php?id='.$course->id.'">'.format_string($course->shortname).'</a></div>';
2922 $home = false;
2925 } else {
2926 $course = get_site(); // Set course as site course by default
2927 $homelink = '<div class="homelink"><a '.$CFG->frametarget.' href="'.$CFG->wwwroot.'/">'.get_string('home').'</a></div>';
2928 $home = false;
2931 /// Set up some other navigation links (passed from print_header by ugly hack)
2932 $menu = isset($THEME->menu) ? str_replace('navmenu', 'navmenufooter', $THEME->menu) : '';
2933 $title = isset($THEME->title) ? $THEME->title : '';
2934 $button = isset($THEME->button) ? $THEME->button : '';
2935 $heading = isset($THEME->heading) ? $THEME->heading : '';
2936 $navigation = isset($THEME->navigation) ? $THEME->navigation : '';
2937 $navmenulist = isset($THEME->navmenulist) ? $THEME->navmenulist : '';
2940 /// Set the user link if necessary
2941 if (!$usercourse and is_object($course)) {
2942 $usercourse = $course;
2945 if (!isset($loggedinas)) {
2946 $loggedinas = user_login_string($usercourse, $USER);
2949 if ($loggedinas == $menu) {
2950 $menu = '';
2953 /// there should be exactly the same number of open containers as after the header
2954 if ($THEME->open_header_containers != open_containers()) {
2955 debugging('Unexpected number of open containers: '.open_containers().', expecting '.$THEME->open_header_containers, DEBUG_DEVELOPER);
2958 /// Provide some performance info if required
2959 $performanceinfo = '';
2960 if (defined('MDL_PERF') || (!empty($CFG->perfdebug) and $CFG->perfdebug > 7)) {
2961 $perf = get_performance_info();
2962 if (defined('MDL_PERFTOLOG') && !function_exists('register_shutdown_function')) {
2963 error_log("PERF: " . $perf['txt']);
2965 if (defined('MDL_PERFTOFOOT') || debugging() || $CFG->perfdebug > 7) {
2966 $performanceinfo = $perf['html'];
2970 /// Include the actual footer file
2972 ob_start();
2973 include($CFG->footer);
2974 $output = ob_get_contents();
2975 ob_end_clean();
2977 if ($return) {
2978 return $output;
2979 } else {
2980 echo $output;
2985 * Returns the name of the current theme
2987 * @uses $CFG
2988 * @uses $USER
2989 * @uses $SESSION
2990 * @uses $COURSE
2991 * @uses $FULLME
2992 * @return string
2994 function current_theme() {
2995 global $CFG, $USER, $SESSION, $COURSE, $FULLME;
2997 if (empty($CFG->themeorder)) {
2998 $themeorder = array('page', 'course', 'category', 'session', 'user', 'site');
2999 } else {
3000 $themeorder = $CFG->themeorder;
3003 if (isloggedin() and isset($CFG->mnet_localhost_id) and $USER->mnethostid != $CFG->mnet_localhost_id) {
3004 require_once($CFG->dirroot.'/mnet/peer.php');
3005 $mnet_peer = new mnet_peer();
3006 $mnet_peer->set_id($USER->mnethostid);
3009 $theme = '';
3010 foreach ($themeorder as $themetype) {
3012 if (!empty($theme)) continue;
3014 switch ($themetype) {
3015 case 'page': // Page theme is for special page-only themes set by code
3016 if (!empty($CFG->pagetheme)) {
3017 $theme = $CFG->pagetheme;
3019 break;
3020 case 'course':
3021 if (!empty($CFG->allowcoursethemes) and !empty($COURSE->theme)) {
3022 $theme = $COURSE->theme;
3024 break;
3025 case 'category':
3026 if (!empty($CFG->allowcategorythemes)) {
3027 /// Nasty hack to check if we're in a category page
3028 if (stripos($FULLME, 'course/category.php') !== false) {
3029 global $id;
3030 if (!empty($id)) {
3031 $theme = current_category_theme($id);
3033 /// Otherwise check if we're in a course that has a category theme set
3034 } else if (!empty($COURSE->category)) {
3035 $theme = current_category_theme($COURSE->category);
3038 break;
3039 case 'session':
3040 if (!empty($SESSION->theme)) {
3041 $theme = $SESSION->theme;
3043 break;
3044 case 'user':
3045 if (!empty($CFG->allowuserthemes) and !empty($USER->theme)) {
3046 if (isloggedin() and $USER->mnethostid != $CFG->mnet_localhost_id && $mnet_peer->force_theme == 1 && $mnet_peer->theme != '') {
3047 $theme = $mnet_peer->theme;
3048 } else {
3049 $theme = $USER->theme;
3052 break;
3053 case 'site':
3054 if (isloggedin() and isset($CFG->mnet_localhost_id) and $USER->mnethostid != $CFG->mnet_localhost_id && $mnet_peer->force_theme == 1 && $mnet_peer->theme != '') {
3055 $theme = $mnet_peer->theme;
3056 } else {
3057 $theme = $CFG->theme;
3059 break;
3060 default:
3061 /// do nothing
3065 /// A final check in case 'site' was not included in $CFG->themeorder
3066 if (empty($theme)) {
3067 $theme = $CFG->theme;
3070 return $theme;
3074 * Retrieves the category theme if one exists, otherwise checks the parent categories.
3075 * Recursive function.
3077 * @uses $COURSE
3078 * @param integer $categoryid id of the category to check
3079 * @return string theme name
3081 function current_category_theme($categoryid=0) {
3082 global $COURSE;
3084 /// Use the COURSE global if the categoryid not set
3085 if (empty($categoryid)) {
3086 if (!empty($COURSE->category)) {
3087 $categoryid = $COURSE->category;
3088 } else {
3089 return false;
3093 /// Retrieve the current category
3094 if ($category = get_record('course_categories', 'id', $categoryid)) {
3096 /// Return the category theme if it exists
3097 if (!empty($category->theme)) {
3098 return $category->theme;
3100 /// Otherwise try the parent category if one exists
3101 } else if (!empty($category->parent)) {
3102 return current_category_theme($category->parent);
3105 /// Return false if we can't find the category record
3106 } else {
3107 return false;
3112 * This function is called by stylesheets to set up the header
3113 * approriately as well as the current path
3115 * @uses $CFG
3116 * @param int $lastmodified ?
3117 * @param int $lifetime ?
3118 * @param string $thename ?
3120 function style_sheet_setup($lastmodified=0, $lifetime=300, $themename='', $forceconfig='', $lang='') {
3122 global $CFG, $THEME;
3124 // Fix for IE6 caching - we don't want the filemtime('styles.php'), instead use now.
3125 $lastmodified = time();
3127 header('Last-Modified: ' . gmdate("D, d M Y H:i:s", $lastmodified) . ' GMT');
3128 header('Expires: ' . gmdate("D, d M Y H:i:s", time() + $lifetime) . ' GMT');
3129 header('Cache-Control: max-age='. $lifetime);
3130 header('Pragma: ');
3131 header('Content-type: text/css'); // Correct MIME type
3133 $DEFAULT_SHEET_LIST = array('styles_layout', 'styles_fonts', 'styles_color');
3135 if (empty($themename)) {
3136 $themename = current_theme(); // So we have something. Normally not needed.
3137 } else {
3138 $themename = clean_param($themename, PARAM_SAFEDIR);
3141 if (!empty($forceconfig)) { // Page wants to use the config from this theme instead
3142 unset($THEME);
3143 include($CFG->themedir.'/'.$forceconfig.'/'.'config.php');
3146 /// If this is the standard theme calling us, then find out what sheets we need
3148 if ($themename == 'standard') {
3149 if (!isset($THEME->standardsheets) or $THEME->standardsheets === true) { // Use all the sheets we have
3150 $THEME->sheets = $DEFAULT_SHEET_LIST;
3151 } else if (empty($THEME->standardsheets)) { // We can stop right now!
3152 echo "/***** Nothing required from this stylesheet by main theme *****/\n\n";
3153 exit;
3154 } else { // Use the provided subset only
3155 $THEME->sheets = $THEME->standardsheets;
3158 /// If we are a parent theme, then check for parent definitions
3160 } else if (!empty($THEME->parent) && $themename == $THEME->parent) {
3161 if (!isset($THEME->parentsheets) or $THEME->parentsheets === true) { // Use all the sheets we have
3162 $THEME->sheets = $DEFAULT_SHEET_LIST;
3163 } else if (empty($THEME->parentsheets)) { // We can stop right now!
3164 echo "/***** Nothing required from this stylesheet by main theme *****/\n\n";
3165 exit;
3166 } else { // Use the provided subset only
3167 $THEME->sheets = $THEME->parentsheets;
3171 /// Work out the last modified date for this theme
3173 foreach ($THEME->sheets as $sheet) {
3174 if (file_exists($CFG->themedir.'/'.$themename.'/'.$sheet.'.css')) {
3175 $sheetmodified = filemtime($CFG->themedir.'/'.$themename.'/'.$sheet.'.css');
3176 if ($sheetmodified > $lastmodified) {
3177 $lastmodified = $sheetmodified;
3183 /// Get a list of all the files we want to include
3184 $files = array();
3186 foreach ($THEME->sheets as $sheet) {
3187 $files[] = array($CFG->themedir, $themename.'/'.$sheet.'.css');
3190 if ($themename == 'standard') { // Add any standard styles included in any modules
3191 if (!empty($THEME->modsheets)) { // Search for styles.php within activity modules
3192 if ($mods = get_list_of_plugins('mod')) {
3193 foreach ($mods as $mod) {
3194 if (file_exists($CFG->dirroot.'/mod/'.$mod.'/styles.php')) {
3195 $files[] = array($CFG->dirroot, '/mod/'.$mod.'/styles.php');
3201 if (!empty($THEME->blocksheets)) { // Search for styles.php within block modules
3202 if ($mods = get_list_of_plugins('blocks')) {
3203 foreach ($mods as $mod) {
3204 if (file_exists($CFG->dirroot.'/blocks/'.$mod.'/styles.php')) {
3205 $files[] = array($CFG->dirroot, '/blocks/'.$mod.'/styles.php');
3211 if (!isset($THEME->courseformatsheets) || $THEME->courseformatsheets) { // Search for styles.php in course formats
3212 if ($mods = get_list_of_plugins('format','',$CFG->dirroot.'/course')) {
3213 foreach ($mods as $mod) {
3214 if (file_exists($CFG->dirroot.'/course/format/'.$mod.'/styles.php')) {
3215 $files[] = array($CFG->dirroot, '/course/format/'.$mod.'/styles.php');
3221 if (!isset($THEME->gradereportsheets) || $THEME->gradereportsheets) { // Search for styles.php in grade reports
3222 if ($reports = get_list_of_plugins('grade/report')) {
3223 foreach ($reports as $report) {
3224 if (file_exists($CFG->dirroot.'/grade/report/'.$report.'/styles.php')) {
3225 $files[] = array($CFG->dirroot, '/grade/report/'.$report.'/styles.php');
3231 if (!empty($THEME->langsheets)) { // Search for styles.php within the current language
3232 if (file_exists($CFG->dirroot.'/lang/'.$lang.'/styles.php')) {
3233 $files[] = array($CFG->dirroot, '/lang/'.$lang.'/styles.php');
3238 if ($files) {
3239 /// Produce a list of all the files first
3240 echo '/**************************************'."\n";
3241 echo ' * THEME NAME: '.$themename."\n *\n";
3242 echo ' * Files included in this sheet:'."\n *\n";
3243 foreach ($files as $file) {
3244 echo ' * '.$file[1]."\n";
3246 echo ' **************************************/'."\n\n";
3249 /// check if csscobstants is set
3250 if (!empty($THEME->cssconstants)) {
3251 require_once("$CFG->libdir/cssconstants.php");
3252 /// Actually collect all the files in order.
3253 $css = '';
3254 foreach ($files as $file) {
3255 $css .= '/***** '.$file[1].' start *****/'."\n\n";
3256 $css .= file_get_contents($file[0].'/'.$file[1]);
3257 $ccs .= '/***** '.$file[1].' end *****/'."\n\n";
3259 /// replace css_constants with their values
3260 echo replace_cssconstants($css);
3261 } else {
3262 /// Actually output all the files in order.
3263 if (empty($CFG->CSSEdit) && empty($THEME->CSSEdit)) {
3264 foreach ($files as $file) {
3265 echo '/***** '.$file[1].' start *****/'."\n\n";
3266 @include_once($file[0].'/'.$file[1]);
3267 echo '/***** '.$file[1].' end *****/'."\n\n";
3269 } else {
3270 foreach ($files as $file) {
3271 echo '/* @group '.$file[1].' */'."\n\n";
3272 if (strstr($file[1], '.css') !== FALSE) {
3273 echo '@import url("'.$CFG->themewww.'/'.$file[1].'");'."\n\n";
3274 } else {
3275 @include_once($file[0].'/'.$file[1]);
3277 echo '/* @end */'."\n\n";
3283 return $CFG->themewww.'/'.$themename; // Only to help old themes (1.4 and earlier)
3287 function theme_setup($theme = '', $params=NULL) {
3288 /// Sets up global variables related to themes
3290 global $CFG, $THEME, $SESSION, $USER, $HTTPSPAGEREQUIRED;
3292 /// Do not mess with THEME if header already printed - this would break all the extra stuff in global $THEME from print_header()!!
3293 if (defined('HEADER_PRINTED')) {
3294 return;
3297 if (empty($theme)) {
3298 $theme = current_theme();
3301 /// If the theme doesn't exist for some reason then revert to standardwhite
3302 if (!file_exists($CFG->themedir .'/'. $theme .'/config.php')) {
3303 $CFG->theme = $theme = 'standardwhite';
3306 /// Load up the theme config
3307 $THEME = NULL; // Just to be sure
3308 include($CFG->themedir .'/'. $theme .'/config.php'); // Main config for current theme
3310 /// Put together the parameters
3311 if (!$params) {
3312 $params = array();
3315 if ($theme != $CFG->theme) {
3316 $params[] = 'forceconfig='.$theme;
3319 /// Force language too if required
3320 if (!empty($THEME->langsheets)) {
3321 $params[] = 'lang='.current_language();
3325 /// Convert params to string
3326 if ($params) {
3327 $paramstring = '?'.implode('&', $params);
3328 } else {
3329 $paramstring = '';
3332 /// Set up image paths
3333 if(isset($CFG->smartpix) && $CFG->smartpix==1) {
3334 if($CFG->slasharguments) { // Use this method if possible for better caching
3335 $extra='';
3336 } else {
3337 $extra='?file=';
3340 $CFG->pixpath = $CFG->wwwroot. '/pix/smartpix.php'.$extra.'/'.$theme;
3341 $CFG->modpixpath = $CFG->wwwroot .'/pix/smartpix.php'.$extra.'/'.$theme.'/mod';
3342 } else if (empty($THEME->custompix)) { // Could be set in the above file
3343 $CFG->pixpath = $CFG->wwwroot .'/pix';
3344 $CFG->modpixpath = $CFG->wwwroot .'/mod';
3345 } else {
3346 $CFG->pixpath = $CFG->themewww .'/'. $theme .'/pix';
3347 $CFG->modpixpath = $CFG->themewww .'/'. $theme .'/pix/mod';
3350 /// Header and footer paths
3351 $CFG->header = $CFG->themedir .'/'. $theme .'/header.html';
3352 $CFG->footer = $CFG->themedir .'/'. $theme .'/footer.html';
3354 /// Define stylesheet loading order
3355 $CFG->stylesheets = array();
3356 if ($theme != 'standard') { /// The standard sheet is always loaded first
3357 $CFG->stylesheets[] = $CFG->themewww.'/standard/styles.php'.$paramstring;
3359 if (!empty($THEME->parent)) { /// Parent stylesheets are loaded next
3360 $CFG->stylesheets[] = $CFG->themewww.'/'.$THEME->parent.'/styles.php'.$paramstring;
3362 $CFG->stylesheets[] = $CFG->themewww.'/'.$theme.'/styles.php'.$paramstring;
3364 /// We have to change some URLs in styles if we are in a $HTTPSPAGEREQUIRED page
3365 if (!empty($HTTPSPAGEREQUIRED)) {
3366 $CFG->themewww = str_replace('http:', 'https:', $CFG->themewww);
3367 $CFG->pixpath = str_replace('http:', 'https:', $CFG->pixpath);
3368 $CFG->modpixpath = str_replace('http:', 'https:', $CFG->modpixpath);
3369 foreach ($CFG->stylesheets as $key => $stylesheet) {
3370 $CFG->stylesheets[$key] = str_replace('http:', 'https:', $stylesheet);
3374 // RTL support - only for RTL languages, add RTL CSS
3375 if (get_string('thisdirection') == 'rtl') {
3376 $CFG->stylesheets[] = $CFG->themewww.'/standard/rtl.css'.$paramstring;
3377 $CFG->stylesheets[] = $CFG->themewww.'/'.$theme.'/rtl.css'.$paramstring;
3383 * Returns text to be displayed to the user which reflects their login status
3385 * @uses $CFG
3386 * @uses $USER
3387 * @param course $course {@link $COURSE} object containing course information
3388 * @param user $user {@link $USER} object containing user information
3389 * @return string
3391 function user_login_string($course=NULL, $user=NULL) {
3392 global $USER, $CFG, $SITE;
3394 if (empty($user) and !empty($USER->id)) {
3395 $user = $USER;
3398 if (empty($course)) {
3399 $course = $SITE;
3402 if (!empty($user->realuser)) {
3403 if ($realuser = get_record('user', 'id', $user->realuser)) {
3404 $fullname = fullname($realuser, true);
3405 $realuserinfo = " [<a $CFG->frametarget
3406 href=\"$CFG->wwwroot/course/loginas.php?id=$course->id&amp;return=1&amp;sesskey=".sesskey()."\">$fullname</a>] ";
3408 } else {
3409 $realuserinfo = '';
3412 if (empty($CFG->loginhttps)) {
3413 $wwwroot = $CFG->wwwroot;
3414 } else {
3415 $wwwroot = str_replace('http:','https:',$CFG->wwwroot);
3418 if (empty($course->id)) {
3419 // $course->id is not defined during installation
3420 return '';
3421 } else if (!empty($user->id)) {
3422 $context = get_context_instance(CONTEXT_COURSE, $course->id);
3424 $fullname = fullname($user, true);
3425 $username = "<a $CFG->frametarget href=\"$CFG->wwwroot/user/view.php?id=$user->id&amp;course=$course->id\">$fullname</a>";
3426 if (is_mnet_remote_user($user) and $idprovider = get_record('mnet_host', 'id', $user->mnethostid)) {
3427 $username .= " from <a $CFG->frametarget href=\"{$idprovider->wwwroot}\">{$idprovider->name}</a>";
3429 if (isset($user->username) && $user->username == 'guest') {
3430 $loggedinas = $realuserinfo.get_string('loggedinasguest').
3431 " (<a $CFG->frametarget href=\"$wwwroot/login/index.php\">".get_string('login').'</a>)';
3432 } else if (!empty($user->access['rsw'][$context->path])) {
3433 $rolename = '';
3434 if ($role = get_record('role', 'id', $user->access['rsw'][$context->path])) {
3435 $rolename = ': '.format_string($role->name);
3437 $loggedinas = get_string('loggedinas', 'moodle', $username).$rolename.
3438 " (<a $CFG->frametarget
3439 href=\"$CFG->wwwroot/course/view.php?id=$course->id&amp;switchrole=0&amp;sesskey=".sesskey()."\">".get_string('switchrolereturn').'</a>)';
3440 } else {
3441 $loggedinas = $realuserinfo.get_string('loggedinas', 'moodle', $username).' '.
3442 " (<a $CFG->frametarget href=\"$CFG->wwwroot/login/logout.php?sesskey=".sesskey()."\">".get_string('logout').'</a>)';
3444 } else {
3445 $loggedinas = get_string('loggedinnot', 'moodle').
3446 " (<a $CFG->frametarget href=\"$wwwroot/login/index.php\">".get_string('login').'</a>)';
3448 return '<div class="logininfo">'.$loggedinas.'</div>';
3452 * Tests whether $THEME->rarrow, $THEME->larrow have been set (theme/-/config.php).
3453 * If not it applies sensible defaults.
3455 * Accessibility: right and left arrow Unicode characters for breadcrumb, calendar,
3456 * search forum block, etc. Important: these are 'silent' in a screen-reader
3457 * (unlike &gt; &raquo;), and must be accompanied by text.
3458 * @uses $THEME
3460 function check_theme_arrows() {
3461 global $THEME;
3463 if (!isset($THEME->rarrow) and !isset($THEME->larrow)) {
3464 // Default, looks good in Win XP/IE 6, Win/Firefox 1.5, Win/Netscape 8...
3465 // Also OK in Win 9x/2K/IE 5.x
3466 $THEME->rarrow = '&#x25BA;';
3467 $THEME->larrow = '&#x25C4;';
3468 if (empty($_SERVER['HTTP_USER_AGENT'])) {
3469 $uagent = '';
3470 } else {
3471 $uagent = $_SERVER['HTTP_USER_AGENT'];
3473 if (false !== strpos($uagent, 'Opera')
3474 || false !== strpos($uagent, 'Mac')) {
3475 // Looks good in Win XP/Mac/Opera 8/9, Mac/Firefox 2, Camino, Safari.
3476 // Not broken in Mac/IE 5, Mac/Netscape 7 (?).
3477 $THEME->rarrow = '&#x25B6;';
3478 $THEME->larrow = '&#x25C0;';
3480 elseif (false !== strpos($uagent, 'Konqueror')) {
3481 $THEME->rarrow = '&rarr;';
3482 $THEME->larrow = '&larr;';
3484 elseif (isset($_SERVER['HTTP_ACCEPT_CHARSET'])
3485 && false === stripos($_SERVER['HTTP_ACCEPT_CHARSET'], 'utf-8')) {
3486 // (Win/IE 5 doesn't set ACCEPT_CHARSET, but handles Unicode.)
3487 // To be safe, non-Unicode browsers!
3488 $THEME->rarrow = '&gt;';
3489 $THEME->larrow = '&lt;';
3492 /// RTL support - in RTL languages, swap r and l arrows
3493 if (right_to_left()) {
3494 $t = $THEME->rarrow;
3495 $THEME->rarrow = $THEME->larrow;
3496 $THEME->larrow = $t;
3503 * Return the right arrow with text ('next'), and optionally embedded in a link.
3504 * See function above, check_theme_arrows.
3505 * @param string $text HTML/plain text label (set to blank only for breadcrumb separator cases).
3506 * @param string $url An optional link to use in a surrounding HTML anchor.
3507 * @param bool $accesshide True if text should be hidden (for screen readers only).
3508 * @param string $addclass Additional class names for the link, or the arrow character.
3509 * @return string HTML string.
3511 function link_arrow_right($text, $url='', $accesshide=false, $addclass='') {
3512 global $THEME;
3513 check_theme_arrows();
3514 $arrowclass = 'arrow ';
3515 if (! $url) {
3516 $arrowclass .= $addclass;
3518 $arrow = '<span class="'.$arrowclass.'">'.$THEME->rarrow.'</span>';
3519 $htmltext = '';
3520 if ($text) {
3521 $htmltext = $text.'&nbsp;';
3522 if ($accesshide) {
3523 $htmltext = get_accesshide($htmltext);
3526 if ($url) {
3527 $class = '';
3528 if ($addclass) {
3529 $class =" class=\"$addclass\"";
3531 return '<a'.$class.' href="'.$url.'" title="'.preg_replace('/<.*?>/','',$text).'">'.$htmltext.$arrow.'</a>';
3533 return $htmltext.$arrow;
3537 * Return the left arrow with text ('previous'), and optionally embedded in a link.
3538 * See function above, check_theme_arrows.
3539 * @param string $text HTML/plain text label (set to blank only for breadcrumb separator cases).
3540 * @param string $url An optional link to use in a surrounding HTML anchor.
3541 * @param bool $accesshide True if text should be hidden (for screen readers only).
3542 * @param string $addclass Additional class names for the link, or the arrow character.
3543 * @return string HTML string.
3545 function link_arrow_left($text, $url='', $accesshide=false, $addclass='') {
3546 global $THEME;
3547 check_theme_arrows();
3548 $arrowclass = 'arrow ';
3549 if (! $url) {
3550 $arrowclass .= $addclass;
3552 $arrow = '<span class="'.$arrowclass.'">'.$THEME->larrow.'</span>';
3553 $htmltext = '';
3554 if ($text) {
3555 $htmltext = '&nbsp;'.$text;
3556 if ($accesshide) {
3557 $htmltext = get_accesshide($htmltext);
3560 if ($url) {
3561 $class = '';
3562 if ($addclass) {
3563 $class =" class=\"$addclass\"";
3565 return '<a'.$class.' href="'.$url.'" title="'.preg_replace('/<.*?>/','',$text).'">'.$arrow.$htmltext.'</a>';
3567 return $arrow.$htmltext;
3571 * Return a HTML element with the class "accesshide", for accessibility.
3572 * Please use cautiously - where possible, text should be visible!
3573 * @param string $text Plain text.
3574 * @param string $elem Lowercase element name, default "span".
3575 * @param string $class Additional classes for the element.
3576 * @param string $attrs Additional attributes string in the form, "name='value' name2='value2'"
3577 * @return string HTML string.
3579 function get_accesshide($text, $elem='span', $class='', $attrs='') {
3580 return "<$elem class=\"accesshide $class\" $attrs>$text</$elem>";
3584 * Return the breadcrumb trail navigation separator.
3585 * @return string HTML string.
3587 function get_separator() {
3588 //Accessibility: the 'hidden' slash is preferred for screen readers.
3589 return ' '.link_arrow_right($text='/', $url='', $accesshide=true, 'sep').' ';
3593 * Prints breadcrumb trail of links, called in theme/-/header.html
3595 * @uses $CFG
3596 * @param mixed $navigation The breadcrumb navigation string to be printed
3597 * @param string $separator The breadcrumb trail separator. The default 0 leads to the use
3598 * of $THEME->rarrow, themes could use '&rarr;', '/', or '' for a style-sheet solution.
3599 * @param boolean $return False to echo the breadcrumb string (default), true to return it.
3601 function print_navigation ($navigation, $separator=0, $return=false) {
3602 global $CFG, $THEME;
3603 $output = '';
3605 if (0 === $separator) {
3606 $separator = get_separator();
3608 else {
3609 $separator = '<span class="sep">'. $separator .'</span>';
3612 if ($navigation) {
3614 if (is_newnav($navigation)) {
3615 if ($return) {
3616 return($navigation['navlinks']);
3617 } else {
3618 echo $navigation['navlinks'];
3619 return;
3621 } else {
3622 debugging('Navigation needs to be updated to use build_navigation()', DEBUG_DEVELOPER);
3625 if (!is_array($navigation)) {
3626 $ar = explode('->', $navigation);
3627 $navigation = array();
3629 foreach ($ar as $a) {
3630 if (strpos($a, '</a>') === false) {
3631 $navigation[] = array('title' => $a, 'url' => '');
3632 } else {
3633 if (preg_match('/<a.*href="([^"]*)">(.*)<\/a>/', $a, $matches)) {
3634 $navigation[] = array('title' => $matches[2], 'url' => $matches[1]);
3640 if (! $site = get_site()) {
3641 $site = new object();
3642 $site->shortname = get_string('home');
3645 //Accessibility: breadcrumb links now in a list, &raquo; replaced with a 'silent' character.
3646 $output .= get_accesshide(get_string('youarehere','access'), 'h2')."<ul>\n";
3648 $output .= '<li class="first">'."\n".'<a '.$CFG->frametarget.' onclick="this.target=\''.$CFG->framename.'\'" href="'
3649 .$CFG->wwwroot.((!has_capability('moodle/site:config', get_context_instance(CONTEXT_SYSTEM))
3650 && !empty($USER->id) && !empty($CFG->mymoodleredirect) && !isguest())
3651 ? '/my' : '') .'/">'. format_string($site->shortname) ."</a>\n</li>\n";
3654 foreach ($navigation as $navitem) {
3655 $title = trim(strip_tags(format_string($navitem['title'], false)));
3656 $url = $navitem['url'];
3658 if (empty($url)) {
3659 $output .= '<li class="first">'."$separator $title</li>\n";
3660 } else {
3661 $output .= '<li class="first">'."$separator\n<a ".$CFG->frametarget.' onclick="this.target=\''.$CFG->framename.'\'" href="'
3662 .$url.'">'."$title</a>\n</li>\n";
3666 $output .= "</ul>\n";
3669 if ($return) {
3670 return $output;
3671 } else {
3672 echo $output;
3677 * This function will build the navigation string to be used by print_header
3678 * and others.
3680 * It automatically generates the site and course level (if appropriate) links.
3682 * If you pass in a $cm object, the method will also generate the activity (e.g. 'Forums')
3683 * and activityinstances (e.g. 'General Developer Forum') navigation levels.
3685 * If you want to add any further navigation links after the ones this function generates,
3686 * the pass an array of extra link arrays like this:
3687 * array(
3688 * array('name' => $linktext1, 'link' => $url1, 'type' => $linktype1),
3689 * array('name' => $linktext2, 'link' => $url2, 'type' => $linktype2)
3691 * The normal case is to just add one further link, for example 'Editing forum' after
3692 * 'General Developer Forum', with no link.
3693 * To do that, you need to pass
3694 * array(array('name' => $linktext, 'link' => '', 'type' => 'title'))
3695 * However, becuase this is a very common case, you can use a shortcut syntax, and just
3696 * pass the string 'Editing forum', instead of an array as $extranavlinks.
3698 * At the moment, the link types only have limited significance. Type 'activity' is
3699 * recognised in order to implement the $CFG->hideactivitytypenavlink feature. Types
3700 * that are known to appear are 'home', 'course', 'activity', 'activityinstance' and 'title'.
3701 * This really needs to be documented better. In the mean time, try to be consistent, it will
3702 * enable people to customise the navigation more in future.
3704 * When passing a $cm object, the fields used are $cm->modname, $cm->name and $cm->course.
3705 * If you get the $cm object using the function get_coursemodule_from_instance or
3706 * get_coursemodule_from_id (as recommended) then this will be done for you automatically.
3707 * If you don't have $cm->modname or $cm->name, this fuction will attempt to find them using
3708 * the $cm->module and $cm->instance fields, but this takes extra database queries, so a
3709 * warning is printed in developer debug mode.
3711 * @uses $CFG
3712 * @uses $THEME
3714 * @param mixed $extranavlinks - Normally an array of arrays, keys: name, link, type. If you
3715 * only want one extra item with no link, you can pass a string instead. If you don't want
3716 * any extra links, pass an empty string.
3717 * @param mixed $cm - optionally the $cm object, if you want this function to generate the
3718 * activity and activityinstance levels of navigation too.
3720 * @return $navigation as an object so it can be differentiated from old style
3721 * navigation strings.
3723 function build_navigation($extranavlinks, $cm = null) {
3724 global $CFG, $COURSE;
3726 if (is_string($extranavlinks)) {
3727 if ($extranavlinks == '') {
3728 $extranavlinks = array();
3729 } else {
3730 $extranavlinks = array(array('name' => $extranavlinks, 'link' => '', 'type' => 'title'));
3734 $navlinks = array();
3736 //Site name
3737 if ($site = get_site()) {
3738 $navlinks[] = array(
3739 'name' => format_string($site->shortname),
3740 'link' => "$CFG->wwwroot/",
3741 'type' => 'home');
3744 // Course name, if appropriate.
3745 if (isset($COURSE) && $COURSE->id != SITEID) {
3746 $navlinks[] = array(
3747 'name' => format_string($COURSE->shortname),
3748 'link' => "$CFG->wwwroot/course/view.php?id=$COURSE->id",
3749 'type' => 'course');
3752 // Activity type and instance, if appropriate.
3753 if (is_object($cm)) {
3754 if (!isset($cm->modname)) {
3755 debugging('The field $cm->modname should be set if you call build_navigation with '.
3756 'a $cm parameter. If you get $cm using get_coursemodule_from_instance or '.
3757 'get_coursemodule_from_id, this will be done automatically.', DEBUG_DEVELOPER);
3758 if (!$cm->modname = get_field('modules', 'name', 'id', $cm->module)) {
3759 error('Cannot get the module type in build navigation.');
3762 if (!isset($cm->name)) {
3763 debugging('The field $cm->name should be set if you call build_navigation with '.
3764 'a $cm parameter. If you get $cm using get_coursemodule_from_instance or '.
3765 'get_coursemodule_from_id, this will be done automatically.', DEBUG_DEVELOPER);
3766 if (!$cm->name = get_field($cm->modname, 'name', 'id', $cm->instance)) {
3767 error('Cannot get the module name in build navigation.');
3770 $navlinks[] = array(
3771 'name' => get_string('modulenameplural', $cm->modname),
3772 'link' => $CFG->wwwroot . '/mod/' . $cm->modname . '/index.php?id=' . $cm->course,
3773 'type' => 'activity');
3774 $navlinks[] = array(
3775 'name' => format_string($cm->name),
3776 'link' => $CFG->wwwroot . '/mod/' . $cm->modname . '/view.php?id=' . $cm->id,
3777 'type' => 'activityinstance');
3780 //Merge in extra navigation links
3781 $navlinks = array_merge($navlinks, $extranavlinks);
3783 // Work out whether we should be showing the activity (e.g. Forums) link.
3784 // Note: build_navigation() is called from many places --
3785 // install & upgrade for example -- where we cannot count on the
3786 // roles infrastructure to be defined. Hence the $CFG->rolesactive check.
3787 if (!isset($CFG->hideactivitytypenavlink)) {
3788 $CFG->hideactivitytypenavlink = 0;
3790 if ($CFG->hideactivitytypenavlink == 2) {
3791 $hideactivitylink = true;
3792 } else if ($CFG->hideactivitytypenavlink == 1 && $CFG->rolesactive &&
3793 !empty($COURSE->id) && $COURSE->id != SITEID) {
3794 if (!isset($COURSE->context)) {
3795 $COURSE->context = get_context_instance(CONTEXT_COURSE, $COURSE->id);
3797 $hideactivitylink = !has_capability('moodle/course:manageactivities', $COURSE->context);
3798 } else {
3799 $hideactivitylink = false;
3802 //Construct an unordered list from $navlinks
3803 //Accessibility: heading hidden from visual browsers by default.
3804 $navigation = get_accesshide(get_string('youarehere','access'), 'h2')." <ul>\n";
3805 $lastindex = count($navlinks) - 1;
3806 $i = -1; // Used to count the times, so we know when we get to the last item.
3807 $first = true;
3808 foreach ($navlinks as $navlink) {
3809 $i++;
3810 $last = ($i == $lastindex);
3811 if (!is_array($navlink)) {
3812 continue;
3814 if ($navlink['type'] == 'activity' && !$last && $hideactivitylink) {
3815 continue;
3817 $navigation .= '<li class="first">';
3818 if (!$first) {
3819 $navigation .= get_separator();
3821 if ((!empty($navlink['link'])) && !$last) {
3822 $navigation .= "<a onclick=\"this.target='$CFG->framename'\" href=\"{$navlink['link']}\">";
3824 $navigation .= "{$navlink['name']}";
3825 if ((!empty($navlink['link'])) && !$last) {
3826 $navigation .= "</a>";
3829 $navigation .= "</li>";
3830 $first = false;
3832 $navigation .= "</ul>";
3834 return(array('newnav' => true, 'navlinks' => $navigation));
3839 * Prints a string in a specified size (retained for backward compatibility)
3841 * @param string $text The text to be displayed
3842 * @param int $size The size to set the font for text display.
3844 function print_headline($text, $size=2, $return=false) {
3845 $output = print_heading($text, '', $size, true);
3846 if ($return) {
3847 return $output;
3848 } else {
3849 echo $output;
3854 * Prints text in a format for use in headings.
3856 * @param string $text The text to be displayed
3857 * @param string $align The alignment of the printed paragraph of text
3858 * @param int $size The size to set the font for text display.
3860 function print_heading($text, $align='', $size=2, $class='main', $return=false) {
3861 if ($align) {
3862 $align = ' style="text-align:'.$align.';"';
3864 if ($class) {
3865 $class = ' class="'.$class.'"';
3867 $output = "<h$size $align $class>".stripslashes_safe($text)."</h$size>";
3869 if ($return) {
3870 return $output;
3871 } else {
3872 echo $output;
3877 * Centered heading with attached help button (same title text)
3878 * and optional icon attached
3880 * @param string $text The text to be displayed
3881 * @param string $helppage The help page to link to
3882 * @param string $module The module whose help should be linked to
3883 * @param string $icon Image to display if needed
3885 function print_heading_with_help($text, $helppage, $module='moodle', $icon='', $return=false) {
3886 $output = '';
3887 $output .= '<h2 class="main help">'.$icon.stripslashes_safe($text);
3888 $output .= helpbutton($helppage, $text, $module, true, false, '', true);
3889 $output .= '</h2>';
3891 if ($return) {
3892 return $output;
3893 } else {
3894 echo $output;
3899 function print_heading_block($heading, $class='', $return=false) {
3900 //Accessibility: 'headingblock' is now H1, see theme/standard/styles_*.css: ??
3901 $output = '<h2 class="headingblock header '.$class.'">'.stripslashes($heading).'</h2>';
3903 if ($return) {
3904 return $output;
3905 } else {
3906 echo $output;
3912 * Print a link to continue on to another page.
3914 * @uses $CFG
3915 * @param string $link The url to create a link to.
3917 function print_continue($link, $return=false) {
3919 global $CFG;
3921 // in case we are logging upgrade in admin/index.php stop it
3922 if (function_exists('upgrade_log_finish')) {
3923 upgrade_log_finish();
3926 $output = '';
3928 if ($link == '') {
3929 if (!empty($_SERVER['HTTP_REFERER'])) {
3930 $link = $_SERVER['HTTP_REFERER'];
3931 $link = str_replace('&', '&amp;', $link); // make it valid XHTML
3932 } else {
3933 $link = $CFG->wwwroot .'/';
3937 $options = array();
3938 $linkparts = parse_url(str_replace('&amp;', '&', $link));
3939 if (isset($linkparts['query'])) {
3940 parse_str($linkparts['query'], $options);
3943 $output .= '<div class="continuebutton">';
3945 $output .= print_single_button($link, $options, get_string('continue'), 'get', $CFG->framename, true);
3946 $output .= '</div>'."\n";
3948 if ($return) {
3949 return $output;
3950 } else {
3951 echo $output;
3957 * Print a message in a standard themed box.
3958 * Replaces print_simple_box (see deprecatedlib.php)
3960 * @param string $message, the content of the box
3961 * @param string $classes, space-separated class names.
3962 * @param string $idbase
3963 * @param boolean $return, return as string or just print it
3964 * @return mixed string or void
3966 function print_box($message, $classes='generalbox', $ids='', $return=false) {
3968 $output = print_box_start($classes, $ids, true);
3969 $output .= stripslashes_safe($message);
3970 $output .= print_box_end(true);
3972 if ($return) {
3973 return $output;
3974 } else {
3975 echo $output;
3980 * Starts a box using divs
3981 * Replaces print_simple_box_start (see deprecatedlib.php)
3983 * @param string $classes, space-separated class names.
3984 * @param string $idbase
3985 * @param boolean $return, return as string or just print it
3986 * @return mixed string or void
3988 function print_box_start($classes='generalbox', $ids='', $return=false) {
3989 global $THEME;
3991 if (strpos($classes, 'clearfix') !== false) {
3992 $clearfix = true;
3993 $classes = trim(str_replace('clearfix', '', $classes));
3994 } else {
3995 $clearfix = false;
3998 if (!empty($THEME->customcorners)) {
3999 $classes .= ' ccbox box';
4000 } else {
4001 $classes .= ' box';
4004 return print_container_start($clearfix, $classes, $ids, $return);
4008 * Simple function to end a box (see above)
4009 * Replaces print_simple_box_end (see deprecatedlib.php)
4011 * @param boolean $return, return as string or just print it
4013 function print_box_end($return=false) {
4014 return print_container_end($return);
4018 * Print a message in a standard themed container.
4020 * @param string $message, the content of the container
4021 * @param boolean $clearfix clear both sides
4022 * @param string $classes, space-separated class names.
4023 * @param string $idbase
4024 * @param boolean $return, return as string or just print it
4025 * @return string or void
4027 function print_container($message, $clearfix=false, $classes='', $idbase='', $return=false) {
4029 $output = print_container_start($clearfix, $classes, $idbase, true);
4030 $output .= stripslashes_safe($message);
4031 $output .= print_container_end(true);
4033 if ($return) {
4034 return $output;
4035 } else {
4036 echo $output;
4041 * Starts a container using divs
4043 * @param boolean $clearfix clear both sides
4044 * @param string $classes, space-separated class names.
4045 * @param string $idbase
4046 * @param boolean $return, return as string or just print it
4047 * @return mixed string or void
4049 function print_container_start($clearfix=false, $classes='', $idbase='', $return=false) {
4050 global $THEME;
4052 if (!isset($THEME->open_containers)) {
4053 $THEME->open_containers = array();
4055 $THEME->open_containers[] = $idbase;
4058 if (!empty($THEME->customcorners)) {
4059 $output = _print_custom_corners_start($clearfix, $classes, $idbase);
4060 } else {
4061 if ($idbase) {
4062 $id = ' id="'.$idbase.'"';
4063 } else {
4064 $id = '';
4066 if ($clearfix) {
4067 $clearfix = ' clearfix';
4068 } else {
4069 $clearfix = '';
4071 if ($classes or $clearfix) {
4072 $class = ' class="'.$classes.$clearfix.'"';
4073 } else {
4074 $class = '';
4076 $output = '<div'.$id.$class.'>';
4079 if ($return) {
4080 return $output;
4081 } else {
4082 echo $output;
4087 * Simple function to end a container (see above)
4088 * @param boolean $return, return as string or just print it
4089 * @return mixed string or void
4091 function print_container_end($return=false) {
4092 global $THEME;
4094 if (empty($THEME->open_containers)) {
4095 debugging('Incorrect request to end container - no more open containers.', DEBUG_DEVELOPER);
4096 $idbase = '';
4097 } else {
4098 $idbase = array_pop($THEME->open_containers);
4101 if (!empty($THEME->customcorners)) {
4102 $output = _print_custom_corners_end($idbase);
4103 } else {
4104 $output = '</div>';
4107 if ($return) {
4108 return $output;
4109 } else {
4110 echo $output;
4115 * Returns number of currently open containers
4116 * @return int number of open containers
4118 function open_containers() {
4119 global $THEME;
4121 if (!isset($THEME->open_containers)) {
4122 $THEME->open_containers = array();
4125 return count($THEME->open_containers);
4129 * Force closing of open containers
4130 * @param boolean $return, return as string or just print it
4131 * @param int $keep number of containers to be kept open - usually theme or page containers
4132 * @return mixed string or void
4134 function print_container_end_all($return=false, $keep=0) {
4135 $output = '';
4136 while (open_containers() > $keep) {
4137 $output .= print_container_end($return);
4140 if ($return) {
4141 return $output;
4142 } else {
4143 echo $output;
4148 * Internal function - do not use directly!
4149 * Starting part of the surrounding divs for custom corners
4151 * @param boolean $clearfix, add CLASS "clearfix" to the inner div against collapsing
4152 * @param string $classes
4153 * @param mixed $idbase, optionally, define one idbase to be added to all the elements in the corners
4154 * @return string
4156 function _print_custom_corners_start($clearfix=false, $classes='', $idbase='') {
4157 /// Analise if we want ids for the custom corner elements
4158 $id = '';
4159 $idbt = '';
4160 $idi1 = '';
4161 $idi2 = '';
4162 $idi3 = '';
4164 if ($idbase) {
4165 $id = 'id="'.$idbase.'" ';
4166 $idbt = 'id="'.$idbase.'-bt" ';
4167 $idi1 = 'id="'.$idbase.'-i1" ';
4168 $idi2 = 'id="'.$idbase.'-i2" ';
4169 $idi3 = 'id="'.$idbase.'-i3" ';
4172 /// Calculate current level
4173 $level = open_containers();
4175 /// Output begins
4176 $output = '<div '.$id.'class="wrap wraplevel'.$level.' '.$classes.'">'."\n";
4177 $output .= '<div '.$idbt.'class="bt"><div>&nbsp;</div></div>';
4178 $output .= "\n";
4179 $output .= '<div '.$idi1.'class="i1"><div '.$idi2.'class="i2">';
4180 $output .= (!empty($clearfix)) ? '<div '.$idi3.'class="i3 clearfix">' : '<div '.$idi3.'class="i3">';
4182 return $output;
4187 * Internal function - do not use directly!
4188 * Ending part of the surrounding divs for custom corners
4189 * @param string $idbase
4190 * @return string
4192 function _print_custom_corners_end($idbase) {
4193 /// Analise if we want ids for the custom corner elements
4194 $idbb = '';
4196 if ($idbase) {
4197 $idbb = 'id="' . $idbase . '-bb" ';
4200 /// Output begins
4201 $output = '</div></div></div>';
4202 $output .= "\n";
4203 $output .= '<div '.$idbb.'class="bb"><div>&nbsp;</div></div>'."\n";
4204 $output .= '</div>';
4206 return $output;
4211 * Print a self contained form with a single submit button.
4213 * @param string $link used as the action attribute on the form, so the URL that will be hit if the button is clicked.
4214 * @param array $options these become hidden form fields, so these options get passed to the script at $link.
4215 * @param string $label the caption that appears on the button.
4216 * @param string $method HTTP method used on the request of the button is clicked. 'get' or 'post'.
4217 * @param string $target no longer used.
4218 * @param boolean $return if false, output the form directly, otherwise return the HTML as a string.
4219 * @param string $tooltip a tooltip to add to the button as a title attribute.
4220 * @param boolean $disabled if true, the button will be disabled.
4221 * @param string $jsconfirmmessage if not empty then display a confirm dialogue with this string as the question.
4222 * @return string / nothing depending on the $return paramter.
4224 function print_single_button($link, $options, $label='OK', $method='get', $target='_self', $return=false, $tooltip='', $disabled = false, $jsconfirmmessage='') {
4225 $output = '';
4226 $link = str_replace('"', '&quot;', $link); //basic XSS protection
4227 $output .= '<div class="singlebutton">';
4228 // taking target out, will need to add later target="'.$target.'"
4229 $output .= '<form action="'. $link .'" method="'. $method .'">';
4230 $output .= '<div>';
4231 if ($options) {
4232 foreach ($options as $name => $value) {
4233 $output .= '<input type="hidden" name="'. $name .'" value="'. s($value) .'" />';
4236 if ($tooltip) {
4237 $tooltip = 'title="' . s($tooltip) . '"';
4238 } else {
4239 $tooltip = '';
4241 if ($disabled) {
4242 $disabled = 'disabled="disabled"';
4243 } else {
4244 $disabled = '';
4246 if ($jsconfirmmessage){
4247 $jsconfirmmessage = addslashes_js($jsconfirmmessage);
4248 $jsconfirmmessage = 'onclick="return confirm(\''. $jsconfirmmessage .'\');" ';
4250 $output .= '<input type="submit" value="'. s($label) ."\" $tooltip $disabled $jsconfirmmessage/></div></form></div>";
4252 if ($return) {
4253 return $output;
4254 } else {
4255 echo $output;
4261 * Print a spacer image with the option of including a line break.
4263 * @param int $height ?
4264 * @param int $width ?
4265 * @param boolean $br ?
4266 * @todo Finish documenting this function
4268 function print_spacer($height=1, $width=1, $br=true, $return=false) {
4269 global $CFG;
4270 $output = '';
4272 $output .= '<img class="spacer" height="'. $height .'" width="'. $width .'" src="'. $CFG->wwwroot .'/pix/spacer.gif" alt="" />';
4273 if ($br) {
4274 $output .= '<br />'."\n";
4277 if ($return) {
4278 return $output;
4279 } else {
4280 echo $output;
4285 * Given the path to a picture file in a course, or a URL,
4286 * this function includes the picture in the page.
4288 * @param string $path ?
4289 * @param int $courseid ?
4290 * @param int $height ?
4291 * @param int $width ?
4292 * @param string $link ?
4293 * @todo Finish documenting this function
4295 function print_file_picture($path, $courseid=0, $height='', $width='', $link='', $return=false) {
4296 global $CFG;
4297 $output = '';
4299 if ($height) {
4300 $height = 'height="'. $height .'"';
4302 if ($width) {
4303 $width = 'width="'. $width .'"';
4305 if ($link) {
4306 $output .= '<a href="'. $link .'">';
4308 if (substr(strtolower($path), 0, 7) == 'http://') {
4309 $output .= '<img style="height:'.$height.'px;width:'.$width.'px;" src="'. $path .'" />';
4311 } else if ($courseid) {
4312 $output .= '<img style="height:'.$height.'px;width:'.$width.'px;" src="';
4313 require_once($CFG->libdir.'/filelib.php');
4314 $output .= get_file_url("$courseid/$path");
4315 $output .= '" />';
4316 } else {
4317 $output .= 'Error: must pass URL or course';
4319 if ($link) {
4320 $output .= '</a>';
4323 if ($return) {
4324 return $output;
4325 } else {
4326 echo $output;
4331 * Print the specified user's avatar.
4333 * If you pass a $user object that has id, picture, imagealt, firstname, lastname
4334 * you save a DB query.
4336 * @param int $user takes a userid, or a userobj
4337 * @param int $courseid ?
4338 * @param boolean $picture Print the user picture?
4339 * @param int $size Size in pixels. Special values are (true/1 = 100px) and (false/0 = 35px) for backward compatability
4340 * @param boolean $return If false print picture to current page, otherwise return the output as string
4341 * @param boolean $link Enclose printed image in a link to view specified course?
4342 * @param string $target link target attribute
4343 * @param boolean $alttext use username or userspecified text in image alt attribute
4344 * return string
4345 * @todo Finish documenting this function
4347 function print_user_picture($user, $courseid, $picture=NULL, $size=0, $return=false, $link=true, $target='', $alttext=true) {
4348 global $CFG, $HTTPSPAGEREQUIRED;
4350 $needrec = false;
4351 // only touch the DB if we are missing data...
4352 if (is_object($user)) {
4353 // Note - both picture and imagealt _can_ be empty
4354 // what we are trying to see here is if they have been fetched
4355 // from the DB. We should use isset() _except_ that some installs
4356 // have those fields as nullable, and isset() will return false
4357 // on null. The only safe thing is to ask array_key_exists()
4358 // which works on objects. property_exists() isn't quite
4359 // what we want here...
4360 if (! (array_key_exists('picture', $user)
4361 && ($alttext && array_key_exists('imagealt', $user)
4362 || (isset($user->firstname) && isset($user->lastname)))) ) {
4363 $needrec = true;
4364 $user = $user->id;
4366 } else {
4367 if ($alttext) {
4368 // we need firstname, lastname, imagealt, can't escape...
4369 $needrec = true;
4370 } else {
4371 $userobj = new StdClass; // fake it to save DB traffic
4372 $userobj->id = $user;
4373 $userobj->picture = $picture;
4374 $user = clone($userobj);
4375 unset($userobj);
4378 if ($needrec) {
4379 $user = get_record('user','id',$user, '', '', '', '', 'id,firstname,lastname,imagealt');
4382 if ($link) {
4383 $url = '/user/view.php?id='. $user->id .'&amp;course='. $courseid ;
4384 if ($target) {
4385 $target='onclick="return openpopup(\''.$url.'\');"';
4387 $output = '<a '.$target.' href="'. $CFG->wwwroot . $url .'">';
4388 } else {
4389 $output = '';
4391 if (empty($size)) {
4392 $file = 'f2';
4393 $size = 35;
4394 } else if ($size === true or $size == 1) {
4395 $file = 'f1';
4396 $size = 100;
4397 } else if ($size >= 50) {
4398 $file = 'f1';
4399 } else {
4400 $file = 'f2';
4402 $class = "userpicture";
4403 if (!empty($HTTPSPAGEREQUIRED)) {
4404 $wwwroot = $CFG->httpswwwroot;
4405 } else {
4406 $wwwroot = $CFG->wwwroot;
4409 if (is_null($picture)) {
4410 $picture = $user->picture;
4413 if ($picture) { // Print custom user picture
4414 require_once($CFG->libdir.'/filelib.php');
4415 $src = get_file_url($user->id.'/'.$file.'.jpg', null, 'user');
4416 } else { // Print default user pictures (use theme version if available)
4417 $class .= " defaultuserpic";
4418 $src = "$CFG->pixpath/u/$file.png";
4420 $imagealt = '';
4421 if ($alttext) {
4422 if (!empty($user->imagealt)) {
4423 $imagealt = $user->imagealt;
4424 } else {
4425 $imagealt = get_string('pictureof','',fullname($user));
4429 $output .= '<img class="'.$class.'" src="'.$src.'" alt="'.s($imagealt).'" />';
4430 if ($link) {
4431 $output .= '</a>';
4434 if ($return) {
4435 return $output;
4436 } else {
4437 echo $output;
4442 * Prints a summary of a user in a nice little box.
4444 * @uses $CFG
4445 * @uses $USER
4446 * @param user $user A {@link $USER} object representing a user
4447 * @param course $course A {@link $COURSE} object representing a course
4449 function print_user($user, $course, $messageselect=false, $return=false) {
4451 global $CFG, $USER;
4453 $output = '';
4455 static $string;
4456 static $datestring;
4457 static $countries;
4459 $context = get_context_instance(CONTEXT_COURSE, $course->id);
4460 if (isset($user->context->id)) {
4461 $usercontext = get_context_instance_by_id($user->context->id);
4464 if (empty($string)) { // Cache all the strings for the rest of the page
4466 $string->email = get_string('email');
4467 $string->city = get_string('city');
4468 $string->lastaccess = get_string('lastaccess');
4469 $string->activity = get_string('activity');
4470 $string->unenrol = get_string('unenrol');
4471 $string->loginas = get_string('loginas');
4472 $string->fullprofile = get_string('fullprofile');
4473 $string->role = get_string('role');
4474 $string->name = get_string('name');
4475 $string->never = get_string('never');
4477 $datestring->day = get_string('day');
4478 $datestring->days = get_string('days');
4479 $datestring->hour = get_string('hour');
4480 $datestring->hours = get_string('hours');
4481 $datestring->min = get_string('min');
4482 $datestring->mins = get_string('mins');
4483 $datestring->sec = get_string('sec');
4484 $datestring->secs = get_string('secs');
4485 $datestring->year = get_string('year');
4486 $datestring->years = get_string('years');
4488 $countries = get_list_of_countries();
4491 /// Get the hidden field list
4492 if (has_capability('moodle/course:viewhiddenuserfields', $context)) {
4493 $hiddenfields = array();
4494 } else {
4495 $hiddenfields = array_flip(explode(',', $CFG->hiddenuserfields));
4498 $output .= '<table class="userinfobox">';
4499 $output .= '<tr>';
4500 $output .= '<td class="left side">';
4501 $output .= print_user_picture($user, $course->id, $user->picture, true, true);
4502 $output .= '</td>';
4503 $output .= '<td class="content">';
4504 $output .= '<div class="username">'.fullname($user, has_capability('moodle/site:viewfullnames', $context)).'</div>';
4505 $output .= '<div class="info">';
4506 if (!empty($user->role) and ($user->role <> $course->teacher)) {
4507 $output .= $string->role .': '. $user->role .'<br />';
4509 if ($user->maildisplay == 1 or ($user->maildisplay == 2 and ($course->id != SITEID) and !isguest()) or
4510 has_capability('moodle/course:viewhiddenuserfields', $context)) {
4511 $output .= $string->email .': <a href="mailto:'. $user->email .'">'. $user->email .'</a><br />';
4513 if (($user->city or $user->country) and (!isset($hiddenfields['city']) or !isset($hiddenfields['country']))) {
4514 $output .= $string->city .': ';
4515 if ($user->city && !isset($hiddenfields['city'])) {
4516 $output .= $user->city;
4518 if (!empty($countries[$user->country]) && !isset($hiddenfields['country'])) {
4519 if ($user->city && !isset($hiddenfields['city'])) {
4520 $output .= ', ';
4522 $output .= $countries[$user->country];
4524 $output .= '<br />';
4527 if (!isset($hiddenfields['lastaccess'])) {
4528 if ($user->lastaccess) {
4529 $output .= $string->lastaccess .': '. userdate($user->lastaccess);
4530 $output .= '&nbsp; ('. format_time(time() - $user->lastaccess, $datestring) .')';
4531 } else {
4532 $output .= $string->lastaccess .': '. $string->never;
4535 $output .= '</div></td><td class="links">';
4536 //link to blogs
4537 if ($CFG->bloglevel > 0) {
4538 $output .= '<a href="'.$CFG->wwwroot.'/blog/index.php?userid='.$user->id.'">'.get_string('blogs','blog').'</a><br />';
4540 //link to notes
4541 if (has_capability('moodle/notes:manage', $context) || has_capability('moodle/notes:view', $context)) {
4542 $output .= '<a href="'.$CFG->wwwroot.'/notes/index.php?course=' . $course->id. '&amp;user='.$user->id.'">'.get_string('notes','notes').'</a><br />';
4545 if (has_capability('moodle/user:viewuseractivitiesreport', $context) || (isset($usercontext) && has_capability('moodle/user:viewuseractivitiesreport', $usercontext))) {
4546 $timemidnight = usergetmidnight(time());
4547 $output .= '<a href="'. $CFG->wwwroot .'/course/user.php?id='. $course->id .'&amp;user='. $user->id .'">'. $string->activity .'</a><br />';
4549 if (has_capability('moodle/role:assign', $context, NULL)) { // Includes admins
4550 $output .= '<a href="'. $CFG->wwwroot .'/course/unenrol.php?id='. $course->id .'&amp;user='. $user->id .'">'. $string->unenrol .'</a><br />';
4552 if ($USER->id != $user->id && empty($USER->realuser) && has_capability('moodle/user:loginas', $context) &&
4553 ! has_capability('moodle/site:doanything', $context, $user->id, false)) {
4554 $output .= '<a href="'. $CFG->wwwroot .'/course/loginas.php?id='. $course->id .'&amp;user='. $user->id .'&amp;sesskey='. sesskey() .'">'. $string->loginas .'</a><br />';
4556 $output .= '<a href="'. $CFG->wwwroot .'/user/view.php?id='. $user->id .'&amp;course='. $course->id .'">'. $string->fullprofile .'...</a>';
4558 if (!empty($messageselect)) {
4559 $output .= '<br /><input type="checkbox" name="user'.$user->id.'" /> ';
4562 $output .= '</td></tr></table>';
4564 if ($return) {
4565 return $output;
4566 } else {
4567 echo $output;
4572 * Print a specified group's avatar.
4574 * @param group $group A single {@link group} object OR array of groups.
4575 * @param int $courseid The course ID.
4576 * @param boolean $large Default small picture, or large.
4577 * @param boolean $return If false print picture, otherwise return the output as string
4578 * @param boolean $link Enclose image in a link to view specified course?
4579 * @return string
4580 * @todo Finish documenting this function
4582 function print_group_picture($group, $courseid, $large=false, $return=false, $link=true) {
4583 global $CFG;
4585 if (is_array($group)) {
4586 $output = '';
4587 foreach($group as $g) {
4588 $output .= print_group_picture($g, $courseid, $large, true, $link);
4590 if ($return) {
4591 return $output;
4592 } else {
4593 echo $output;
4594 return;
4598 $context = get_context_instance(CONTEXT_COURSE, $courseid);
4600 if ($group->hidepicture and !has_capability('moodle/course:managegroups', $context)) {
4601 return '';
4604 if ($link or has_capability('moodle/site:accessallgroups', $context)) {
4605 $output = '<a href="'. $CFG->wwwroot .'/user/index.php?id='. $courseid .'&amp;group='. $group->id .'">';
4606 } else {
4607 $output = '';
4609 if ($large) {
4610 $file = 'f1';
4611 $size = 100;
4612 } else {
4613 $file = 'f2';
4614 $size = 35;
4616 if ($group->picture) { // Print custom group picture
4617 require_once($CFG->libdir.'/filelib.php');
4618 $grouppictureurl = get_file_url($group->id.'/'.$file.'.jpg', null, 'usergroup');
4619 $output .= '<img class="grouppicture" src="'.$grouppictureurl.'"'.
4620 ' style="width:'.$size.'px;height:'.$size.'px;" alt="'.s(get_string('group').' '.$group->name).'" title="'.s($group->name).'"/>';
4622 if ($link or has_capability('moodle/site:accessallgroups', $context)) {
4623 $output .= '</a>';
4626 if ($return) {
4627 return $output;
4628 } else {
4629 echo $output;
4634 * Print a png image.
4636 * @param string $url ?
4637 * @param int $sizex ?
4638 * @param int $sizey ?
4639 * @param boolean $return ?
4640 * @param string $parameters ?
4641 * @todo Finish documenting this function
4643 function print_png($url, $sizex, $sizey, $return, $parameters='alt=""') {
4644 global $CFG;
4645 static $recentIE;
4647 if (!isset($recentIE)) {
4648 $recentIE = check_browser_version('MSIE', '5.0');
4651 if ($recentIE) { // work around the HORRIBLE bug IE has with alpha transparencies
4652 $output .= '<img src="'. $CFG->pixpath .'/spacer.gif" width="'. $sizex .'" height="'. $sizey .'"'.
4653 ' class="png" style="width: '. $sizex .'px; height: '. $sizey .'px; '.
4654 ' filter: progid:DXImageTransform.Microsoft.AlphaImageLoader(src='.
4655 "'$url', sizingMethod='scale') ".
4656 ' '. $parameters .' />';
4657 } else {
4658 $output .= '<img src="'. $url .'" style="width: '. $sizex .'px; height: '. $sizey .'px; '. $parameters .' />';
4661 if ($return) {
4662 return $output;
4663 } else {
4664 echo $output;
4669 * Print a nicely formatted table.
4671 * @param array $table is an object with several properties.
4672 * <ul>
4673 * <li>$table->head - An array of heading names.
4674 * <li>$table->align - An array of column alignments
4675 * <li>$table->size - An array of column sizes
4676 * <li>$table->wrap - An array of "nowrap"s or nothing
4677 * <li>$table->data[] - An array of arrays containing the data.
4678 * <li>$table->width - A percentage of the page
4679 * <li>$table->tablealign - Align the whole table
4680 * <li>$table->cellpadding - Padding on each cell
4681 * <li>$table->cellspacing - Spacing between cells
4682 * <li>$table->class - class attribute to put on the table
4683 * <li>$table->id - id attribute to put on the table.
4684 * <li>$table->rowclass[] - classes to add to particular rows.
4685 * <li>$table->summary - Description of the contents for screen readers.
4686 * </ul>
4687 * @param bool $return whether to return an output string or echo now
4688 * @return boolean or $string
4689 * @todo Finish documenting this function
4691 function print_table($table, $return=false) {
4692 $output = '';
4694 if (isset($table->align)) {
4695 foreach ($table->align as $key => $aa) {
4696 if ($aa) {
4697 $align[$key] = ' text-align:'. fix_align_rtl($aa) .';'; // Fix for RTL languages
4698 } else {
4699 $align[$key] = '';
4703 if (isset($table->size)) {
4704 foreach ($table->size as $key => $ss) {
4705 if ($ss) {
4706 $size[$key] = ' width:'. $ss .';';
4707 } else {
4708 $size[$key] = '';
4712 if (isset($table->wrap)) {
4713 foreach ($table->wrap as $key => $ww) {
4714 if ($ww) {
4715 $wrap[$key] = ' white-space:nowrap;';
4716 } else {
4717 $wrap[$key] = '';
4722 if (empty($table->width)) {
4723 $table->width = '80%';
4726 if (empty($table->tablealign)) {
4727 $table->tablealign = 'center';
4730 if (!isset($table->cellpadding)) {
4731 $table->cellpadding = '5';
4734 if (!isset($table->cellspacing)) {
4735 $table->cellspacing = '1';
4738 if (empty($table->class)) {
4739 $table->class = 'generaltable';
4742 $tableid = empty($table->id) ? '' : 'id="'.$table->id.'"';
4744 $output .= '<table width="'.$table->width.'" ';
4745 if (!empty($table->summary)) {
4746 $output .= " summary=\"$table->summary\"";
4748 $output .= " cellpadding=\"$table->cellpadding\" cellspacing=\"$table->cellspacing\" class=\"$table->class boxalign$table->tablealign\" $tableid>\n";
4750 $countcols = 0;
4752 if (!empty($table->head)) {
4753 $countcols = count($table->head);
4754 $output .= '<tr>';
4755 $keys=array_keys($table->head);
4756 $lastkey = end($keys);
4757 foreach ($table->head as $key => $heading) {
4759 if (!isset($size[$key])) {
4760 $size[$key] = '';
4762 if (!isset($align[$key])) {
4763 $align[$key] = '';
4765 if ($key == $lastkey) {
4766 $extraclass = ' lastcol';
4767 } else {
4768 $extraclass = '';
4771 $output .= '<th style="vertical-align:top;'. $align[$key].$size[$key] .';white-space:nowrap;" class="header c'.$key.$extraclass.'" scope="col">'. $heading .'</th>';
4773 $output .= '</tr>'."\n";
4776 if (!empty($table->data)) {
4777 $oddeven = 1;
4778 $keys=array_keys($table->data);
4779 $lastrowkey = end($keys);
4780 foreach ($table->data as $key => $row) {
4781 $oddeven = $oddeven ? 0 : 1;
4782 if (!isset($table->rowclass[$key])) {
4783 $table->rowclass[$key] = '';
4785 if ($key == $lastrowkey) {
4786 $table->rowclass[$key] .= ' lastrow';
4788 $output .= '<tr class="r'.$oddeven.' '.$table->rowclass[$key].'">'."\n";
4789 if ($row == 'hr' and $countcols) {
4790 $output .= '<td colspan="'. $countcols .'"><div class="tabledivider"></div></td>';
4791 } else { /// it's a normal row of data
4792 $keys2=array_keys($row);
4793 $lastkey = end($keys2);
4794 foreach ($row as $key => $item) {
4795 if (!isset($size[$key])) {
4796 $size[$key] = '';
4798 if (!isset($align[$key])) {
4799 $align[$key] = '';
4801 if (!isset($wrap[$key])) {
4802 $wrap[$key] = '';
4804 if ($key == $lastkey) {
4805 $extraclass = ' lastcol';
4806 } else {
4807 $extraclass = '';
4809 $output .= '<td style="'. $align[$key].$size[$key].$wrap[$key] .'" class="cell c'.$key.$extraclass.'">'. $item .'</td>';
4812 $output .= '</tr>'."\n";
4815 $output .= '</table>'."\n";
4817 if ($return) {
4818 return $output;
4821 echo $output;
4822 return true;
4825 function print_recent_activity_note($time, $user, $text, $link, $return=false, $viewfullnames=null) {
4826 static $strftimerecent = null;
4827 $output = '';
4829 if (is_null($viewfullnames)) {
4830 $context = get_context_instance(CONTEXT_SYSTEM);
4831 $viewfullnames = has_capability('moodle/site:viewfullnames', $context);
4834 if (is_null($strftimerecent)) {
4835 $strftimerecent = get_string('strftimerecent');
4838 $output .= '<div class="head">';
4839 $output .= '<div class="date">'.userdate($time, $strftimerecent).'</div>';
4840 $output .= '<div class="name">'.fullname($user, $viewfullnames).'</div>';
4841 $output .= '</div>';
4842 $output .= '<div class="info"><a href="'.$link.'">'.format_string($text,true).'</a></div>';
4844 if ($return) {
4845 return $output;
4846 } else {
4847 echo $output;
4853 * Prints a basic textarea field.
4855 * @uses $CFG
4856 * @param boolean $usehtmleditor ?
4857 * @param int $rows ?
4858 * @param int $cols ?
4859 * @param null $width <b>Legacy field no longer used!</b> Set to zero to get control over mincols
4860 * @param null $height <b>Legacy field no longer used!</b> Set to zero to get control over minrows
4861 * @param string $name ?
4862 * @param string $value ?
4863 * @param int $courseid ?
4864 * @todo Finish documenting this function
4866 function print_textarea($usehtmleditor, $rows, $cols, $width, $height, $name, $value='', $courseid=0, $return=false, $id='') {
4867 /// $width and height are legacy fields and no longer used as pixels like they used to be.
4868 /// However, you can set them to zero to override the mincols and minrows values below.
4870 global $CFG, $COURSE, $HTTPSPAGEREQUIRED;
4871 static $scriptcount = 0; // For loading the htmlarea script only once.
4873 $mincols = 65;
4874 $minrows = 10;
4875 $str = '';
4877 if ($id === '') {
4878 $id = 'edit-'.$name;
4881 if ( empty($CFG->editorsrc) ) { // for backward compatibility.
4882 if (empty($courseid)) {
4883 $courseid = $COURSE->id;
4886 if ($usehtmleditor) {
4887 if (!empty($courseid) and has_capability('moodle/course:managefiles', get_context_instance(CONTEXT_COURSE, $courseid))) {
4888 $httpsrequired = empty($HTTPSPAGEREQUIRED) ? '' : '&amp;httpsrequired=1';
4889 // needed for course file area browsing in image insert plugin
4890 $str .= ($scriptcount < 1) ? '<script type="text/javascript" src="'.
4891 $CFG->httpswwwroot .'/lib/editor/htmlarea/htmlarea.php?id='.$courseid.$httpsrequired.'"></script>'."\n" : '';
4892 } else {
4893 $httpsrequired = empty($HTTPSPAGEREQUIRED) ? '' : '?httpsrequired=1';
4894 $str .= ($scriptcount < 1) ? '<script type="text/javascript" src="'.
4895 $CFG->httpswwwroot .'/lib/editor/htmlarea/htmlarea.php'.$httpsrequired.'"></script>'."\n" : '';
4898 $str .= ($scriptcount < 1) ? '<script type="text/javascript" src="'.
4899 $CFG->httpswwwroot .'/lib/editor/htmlarea/lang/en.php"></script>'."\n" : '';
4900 $scriptcount++;
4902 if ($height) { // Usually with legacy calls
4903 if ($rows < $minrows) {
4904 $rows = $minrows;
4907 if ($width) { // Usually with legacy calls
4908 if ($cols < $mincols) {
4909 $cols = $mincols;
4914 $str .= '<textarea class="form-textarea" id="'. $id .'" name="'. $name .'" rows="'. $rows .'" cols="'. $cols .'">';
4915 if ($usehtmleditor) {
4916 $str .= htmlspecialchars($value); // needed for editing of cleaned text!
4917 } else {
4918 $str .= s($value);
4920 $str .= '</textarea>'."\n";
4922 if ($usehtmleditor) {
4923 // Show shortcuts button if HTML editor is in use, but only if JavaScript is enabled (MDL-9556)
4924 $str .= '<script type="text/javascript">
4925 //<![CDATA[
4926 document.write(\''.addslashes_js(editorshortcutshelpbutton()).'\');
4927 //]]>
4928 </script>';
4931 if ($return) {
4932 return $str;
4934 echo $str;
4938 * Sets up the HTML editor on textareas in the current page.
4939 * If a field name is provided, then it will only be
4940 * applied to that field - otherwise it will be used
4941 * on every textarea in the page.
4943 * In most cases no arguments need to be supplied
4945 * @param string $name Form element to replace with HTMl editor by name
4947 function use_html_editor($name='', $editorhidebuttons='', $id='') {
4948 global $THEME;
4950 $editor = 'editor_'.md5($name); //name might contain illegal characters
4951 if ($id === '') {
4952 $id = 'edit-'.$name;
4954 echo "\n".'<script type="text/javascript" defer="defer">'."\n";
4955 echo '//<![CDATA['."\n\n"; // Extra \n is to fix odd wiki problem, MDL-8185
4956 echo "$editor = new HTMLArea('$id');\n";
4957 echo "var config = $editor.config;\n";
4959 echo print_editor_config($editorhidebuttons);
4961 if (empty($THEME->htmleditorpostprocess)) {
4962 if (empty($name)) {
4963 echo "\nHTMLArea.replaceAll($editor.config);\n";
4964 } else {
4965 echo "\n$editor.generate();\n";
4967 } else {
4968 if (empty($name)) {
4969 echo "\nvar HTML_name = '';";
4970 } else {
4971 echo "\nvar HTML_name = \"$name;\"";
4973 echo "\nvar HTML_editor = $editor;";
4975 echo '//]]>'."\n";
4976 echo '</script>'."\n";
4979 function print_editor_config($editorhidebuttons='', $return=false) {
4980 global $CFG;
4982 $str = "config.pageStyle = \"body {";
4984 if (!(empty($CFG->editorbackgroundcolor))) {
4985 $str .= " background-color: $CFG->editorbackgroundcolor;";
4988 if (!(empty($CFG->editorfontfamily))) {
4989 $str .= " font-family: $CFG->editorfontfamily;";
4992 if (!(empty($CFG->editorfontsize))) {
4993 $str .= " font-size: $CFG->editorfontsize;";
4996 $str .= " }\";\n";
4997 $str .= "config.killWordOnPaste = ";
4998 $str .= (empty($CFG->editorkillword)) ? "false":"true";
4999 $str .= ';'."\n";
5000 $str .= 'config.fontname = {'."\n";
5002 $fontlist = isset($CFG->editorfontlist) ? explode(';', $CFG->editorfontlist) : array();
5003 $i = 1; // Counter is used to get rid of the last comma.
5005 foreach ($fontlist as $fontline) {
5006 if (!empty($fontline)) {
5007 if ($i > 1) {
5008 $str .= ','."\n";
5010 list($fontkey, $fontvalue) = split(':', $fontline);
5011 $str .= '"'. $fontkey ."\":\t'". $fontvalue ."'";
5013 $i++;
5016 $str .= '};';
5018 if (!empty($editorhidebuttons)) {
5019 $str .= "\nconfig.hideSomeButtons(\" ". $editorhidebuttons ." \");\n";
5020 } else if (!empty($CFG->editorhidebuttons)) {
5021 $str .= "\nconfig.hideSomeButtons(\" ". $CFG->editorhidebuttons ." \");\n";
5024 if (!empty($CFG->editorspelling) && !empty($CFG->aspellpath)) {
5025 $str .= print_speller_code($CFG->htmleditor, true);
5028 if ($return) {
5029 return $str;
5031 echo $str;
5035 * Returns a turn edit on/off button for course in a self contained form.
5036 * Used to be an icon, but it's now a simple form button
5038 * Note that the caller is responsible for capchecks.
5040 * @uses $CFG
5041 * @uses $USER
5042 * @param int $courseid The course to update by id as found in 'course' table
5043 * @return string
5045 function update_course_icon($courseid) {
5046 global $CFG, $USER;
5048 if (!empty($USER->editing)) {
5049 $string = get_string('turneditingoff');
5050 $edit = '0';
5051 } else {
5052 $string = get_string('turneditingon');
5053 $edit = '1';
5056 return '<form '.$CFG->frametarget.' method="get" action="'.$CFG->wwwroot.'/course/view.php">'.
5057 '<div>'.
5058 '<input type="hidden" name="id" value="'.$courseid.'" />'.
5059 '<input type="hidden" name="edit" value="'.$edit.'" />'.
5060 '<input type="hidden" name="sesskey" value="'.sesskey().'" />'.
5061 '<input type="submit" value="'.$string.'" />'.
5062 '</div></form>';
5066 * Returns a little popup menu for switching roles
5068 * @uses $CFG
5069 * @uses $USER
5070 * @param int $courseid The course to update by id as found in 'course' table
5071 * @return string
5073 function switchroles_form($courseid) {
5075 global $CFG, $USER;
5078 if (!$context = get_context_instance(CONTEXT_COURSE, $courseid)) {
5079 return '';
5082 if (!empty($USER->access['rsw'][$context->path])){ // Just a button to return to normal
5083 $options = array();
5084 $options['id'] = $courseid;
5085 $options['sesskey'] = sesskey();
5086 $options['switchrole'] = 0;
5088 return print_single_button($CFG->wwwroot.'/course/view.php', $options,
5089 get_string('switchrolereturn'), 'post', '_self', true);
5092 if (has_capability('moodle/role:switchroles', $context)) {
5093 if (!$roles = get_assignable_roles_for_switchrole($context)) {
5094 return ''; // Nothing to show!
5096 // unset default user role - it would not work
5097 unset($roles[$CFG->guestroleid]);
5098 return popup_form($CFG->wwwroot.'/course/view.php?id='.$courseid.'&amp;sesskey='.sesskey().'&amp;switchrole=',
5099 $roles, 'switchrole', '', get_string('switchroleto'), 'switchrole', get_string('switchroleto'), true);
5102 return '';
5107 * Returns a turn edit on/off button for course in a self contained form.
5108 * Used to be an icon, but it's now a simple form button
5110 * @uses $CFG
5111 * @uses $USER
5112 * @param int $courseid The course to update by id as found in 'course' table
5113 * @return string
5115 function update_mymoodle_icon() {
5117 global $CFG, $USER;
5119 if (!empty($USER->editing)) {
5120 $string = get_string('updatemymoodleoff');
5121 $edit = '0';
5122 } else {
5123 $string = get_string('updatemymoodleon');
5124 $edit = '1';
5127 return "<form $CFG->frametarget method=\"get\" action=\"$CFG->wwwroot/my/index.php\">".
5128 "<div>".
5129 "<input type=\"hidden\" name=\"edit\" value=\"$edit\" />".
5130 "<input type=\"submit\" value=\"$string\" /></div></form>";
5134 * Returns a turn edit on/off button for tag in a self contained form.
5136 * @uses $CFG
5137 * @uses $USER
5138 * @return string
5140 function update_tag_button($tagid) {
5142 global $CFG, $USER;
5144 if (!empty($USER->editing)) {
5145 $string = get_string('turneditingoff');
5146 $edit = '0';
5147 } else {
5148 $string = get_string('turneditingon');
5149 $edit = '1';
5152 return "<form $CFG->frametarget method=\"get\" action=\"$CFG->wwwroot/tag/index.php\">".
5153 "<div>".
5154 "<input type=\"hidden\" name=\"edit\" value=\"$edit\" />".
5155 "<input type=\"hidden\" name=\"id\" value=\"$tagid\" />".
5156 "<input type=\"submit\" value=\"$string\" /></div></form>";
5160 * Prints the editing button on a module "view" page
5162 * @uses $CFG
5163 * @param type description
5164 * @todo Finish documenting this function
5166 function update_module_button($moduleid, $courseid, $string) {
5167 global $CFG, $USER;
5169 if (has_capability('moodle/course:manageactivities', get_context_instance(CONTEXT_MODULE, $moduleid))) {
5170 $string = get_string('updatethis', '', $string);
5172 return "<form $CFG->frametarget method=\"get\" action=\"$CFG->wwwroot/course/mod.php\" onsubmit=\"this.target='{$CFG->framename}'; return true\">".//hack to allow edit on framed resources
5173 "<div>".
5174 "<input type=\"hidden\" name=\"update\" value=\"$moduleid\" />".
5175 "<input type=\"hidden\" name=\"return\" value=\"true\" />".
5176 "<input type=\"hidden\" name=\"sesskey\" value=\"".sesskey()."\" />".
5177 "<input type=\"submit\" value=\"$string\" /></div></form>";
5178 } else {
5179 return '';
5184 * Prints the editing button on a category page
5186 * @uses $CFG
5187 * @uses $USER
5188 * @param int $categoryid ?
5189 * @return string
5190 * @todo Finish documenting this function
5192 function update_category_button($categoryid) {
5193 global $CFG, $USER;
5195 if (has_capability('moodle/category:update', get_context_instance(CONTEXT_COURSECAT, $categoryid))) {
5196 if (!empty($USER->categoryediting)) {
5197 $string = get_string('turneditingoff');
5198 $edit = 'off';
5199 } else {
5200 $string = get_string('turneditingon');
5201 $edit = 'on';
5204 return "<form $CFG->frametarget method=\"get\" action=\"$CFG->wwwroot/course/category.php\">".
5205 '<div>'.
5206 "<input type=\"hidden\" name=\"id\" value=\"$categoryid\" />".
5207 "<input type=\"hidden\" name=\"categoryedit\" value=\"$edit\" />".
5208 "<input type=\"hidden\" name=\"sesskey\" value=\"$USER->sesskey\" />".
5209 "<input type=\"submit\" value=\"$string\" /></div></form>";
5214 * Prints the editing button on categories listing
5216 * @uses $CFG
5217 * @uses $USER
5218 * @return string
5220 function update_categories_button() {
5221 global $CFG, $USER;
5223 if (has_capability('moodle/category:update', get_context_instance(CONTEXT_SYSTEM))) {
5224 if (!empty($USER->categoryediting)) {
5225 $string = get_string('turneditingoff');
5226 $categoryedit = 'off';
5227 } else {
5228 $string = get_string('turneditingon');
5229 $categoryedit = 'on';
5232 return "<form $CFG->frametarget method=\"get\" action=\"$CFG->wwwroot/course/index.php\">".
5233 '<div>'.
5234 '<input type="hidden" name="categoryedit" value="'. $categoryedit .'" />'.
5235 '<input type="hidden" name="sesskey" value="'.$USER->sesskey.'" />'.
5236 '<input type="submit" value="'. $string .'" /></div></form>';
5241 * Prints the editing button on search results listing
5242 * For bulk move courses to another category
5245 function update_categories_search_button($search,$page,$perpage) {
5246 global $CFG, $USER;
5248 // not sure if this capability is the best here
5249 if (has_capability('moodle/category:update', get_context_instance(CONTEXT_SYSTEM))) {
5250 if (!empty($USER->categoryediting)) {
5251 $string = get_string("turneditingoff");
5252 $edit = "off";
5253 $perpage = 30;
5254 } else {
5255 $string = get_string("turneditingon");
5256 $edit = "on";
5259 return "<form $CFG->frametarget method=\"get\" action=\"$CFG->wwwroot/course/search.php\">".
5260 '<div>'.
5261 "<input type=\"hidden\" name=\"edit\" value=\"$edit\" />".
5262 "<input type=\"hidden\" name=\"sesskey\" value=\"$USER->sesskey\" />".
5263 "<input type=\"hidden\" name=\"search\" value=\"".s($search, true)."\" />".
5264 "<input type=\"hidden\" name=\"page\" value=\"$page\" />".
5265 "<input type=\"hidden\" name=\"perpage\" value=\"$perpage\" />".
5266 "<input type=\"submit\" value=\"".s($string)."\" /></div></form>";
5271 * Given a course and a (current) coursemodule
5272 * This function returns a small popup menu with all the
5273 * course activity modules in it, as a navigation menu
5274 * The data is taken from the serialised array stored in
5275 * the course record
5277 * @param course $course A {@link $COURSE} object.
5278 * @param course $cm A {@link $COURSE} object.
5279 * @param string $targetwindow ?
5280 * @return string
5281 * @todo Finish documenting this function
5283 function navmenu($course, $cm=NULL, $targetwindow='self') {
5285 global $CFG, $THEME, $USER;
5287 if (empty($THEME->navmenuwidth)) {
5288 $width = 50;
5289 } else {
5290 $width = $THEME->navmenuwidth;
5293 if ($cm) {
5294 $cm = $cm->id;
5297 if ($course->format == 'weeks') {
5298 $strsection = get_string('week');
5299 } else {
5300 $strsection = get_string('topic');
5302 $strjumpto = get_string('jumpto');
5304 $modinfo = get_fast_modinfo($course);
5305 $context = get_context_instance(CONTEXT_COURSE, $course->id);
5307 $section = -1;
5308 $selected = '';
5309 $url = '';
5310 $previousmod = NULL;
5311 $backmod = NULL;
5312 $nextmod = NULL;
5313 $selectmod = NULL;
5314 $logslink = NULL;
5315 $flag = false;
5316 $menu = array();
5317 $menustyle = array();
5319 $sections = get_records('course_sections','course',$course->id,'section','section,visible,summary');
5321 if (!empty($THEME->makenavmenulist)) { /// A hack to produce an XHTML navmenu list for use in themes
5322 $THEME->navmenulist = navmenulist($course, $sections, $modinfo, $strsection, $strjumpto, $width, $cm);
5325 foreach ($modinfo->cms as $mod) {
5326 if ($mod->modname == 'label') {
5327 continue;
5330 if ($mod->sectionnum > $course->numsections) { /// Don't show excess hidden sections
5331 break;
5334 if (!$mod->uservisible) { // do not icnlude empty sections at all
5335 continue;
5338 if ($mod->sectionnum > 0 and $section != $mod->sectionnum) {
5339 $thissection = $sections[$mod->sectionnum];
5341 if ($thissection->visible or !$course->hiddensections or
5342 has_capability('moodle/course:viewhiddensections', $context)) {
5343 $thissection->summary = strip_tags(format_string($thissection->summary,true));
5344 if ($course->format == 'weeks' or empty($thissection->summary)) {
5345 $menu[] = '--'.$strsection ." ". $mod->sectionnum;
5346 } else {
5347 if (strlen($thissection->summary) < ($width-3)) {
5348 $menu[] = '--'.$thissection->summary;
5349 } else {
5350 $menu[] = '--'.substr($thissection->summary, 0, $width).'...';
5353 $section = $mod->sectionnum;
5354 } else {
5355 // no activities from this hidden section shown
5356 continue;
5360 $url = $mod->modname.'/view.php?id='. $mod->id;
5361 if ($flag) { // the current mod is the "next" mod
5362 $nextmod = $mod;
5363 $flag = false;
5365 $localname = $mod->name;
5366 if ($cm == $mod->id) {
5367 $selected = $url;
5368 $selectmod = $mod;
5369 $backmod = $previousmod;
5370 $flag = true; // set flag so we know to use next mod for "next"
5371 $localname = $strjumpto;
5372 $strjumpto = '';
5373 } else {
5374 $localname = strip_tags(format_string($localname,true));
5375 $tl=textlib_get_instance();
5376 if ($tl->strlen($localname) > ($width+5)) {
5377 $localname = $tl->substr($localname, 0, $width).'...';
5379 if (!$mod->visible) {
5380 $localname = '('.$localname.')';
5383 $menu[$url] = $localname;
5384 if (empty($THEME->navmenuiconshide)) {
5385 $menustyle[$url] = 'style="background-image: url('.$CFG->modpixpath.'/'.$mod->modname.'/icon.gif);"'; // Unfortunately necessary to do this here
5387 $previousmod = $mod;
5389 //Accessibility: added Alt text, replaced &gt; &lt; with 'silent' character and 'accesshide' text.
5391 if ($selectmod and has_capability('moodle/site:viewreports', $context)) {
5392 $logstext = get_string('alllogs');
5393 $logslink = '<li>'."\n".'<a title="'.$logstext.'" '.
5394 $CFG->frametarget.'onclick="this.target=\''.$CFG->framename.'\';"'.' href="'.
5395 $CFG->wwwroot.'/course/report/log/index.php?chooselog=1&amp;user=0&amp;date=0&amp;id='.
5396 $course->id.'&amp;modid='.$selectmod->id.'">'.
5397 '<img class="icon log" src="'.$CFG->pixpath.'/i/log.gif" alt="'.$logstext.'" /></a>'."\n".'</li>';
5400 if ($backmod) {
5401 $backtext= get_string('activityprev', 'access');
5402 $backmod = '<li><form action="'.$CFG->wwwroot.'/mod/'.$backmod->modname.'/view.php" '.
5403 'onclick="this.target=\''.$CFG->framename.'\';"'.'><fieldset class="invisiblefieldset">'.
5404 '<input type="hidden" name="id" value="'.$backmod->id.'" />'.
5405 '<button type="submit" title="'.$backtext.'">'.link_arrow_left($backtext, $url='', $accesshide=true).
5406 '</button></fieldset></form></li>';
5408 if ($nextmod) {
5409 $nexttext= get_string('activitynext', 'access');
5410 $nextmod = '<li><form action="'.$CFG->wwwroot.'/mod/'.$nextmod->modname.'/view.php" '.
5411 'onclick="this.target=\''.$CFG->framename.'\';"'.'><fieldset class="invisiblefieldset">'.
5412 '<input type="hidden" name="id" value="'.$nextmod->id.'" />'.
5413 '<button type="submit" title="'.$nexttext.'">'.link_arrow_right($nexttext, $url='', $accesshide=true).
5414 '</button></fieldset></form></li>';
5417 return '<div class="navigation">'."\n".'<ul>'.$logslink . $backmod .
5418 '<li>'.popup_form($CFG->wwwroot .'/mod/', $menu, 'navmenupopup', $selected, $strjumpto,
5419 '', '', true, $targetwindow, '', $menustyle).'</li>'.
5420 $nextmod . '</ul>'."\n".'</div>';
5424 * Given a course
5425 * This function returns a small popup menu with all the
5426 * course activity modules in it, as a navigation menu
5427 * outputs a simple list structure in XHTML
5428 * The data is taken from the serialised array stored in
5429 * the course record
5431 * @param course $course A {@link $COURSE} object.
5432 * @return string
5433 * @todo Finish documenting this function
5435 function navmenulist($course, $sections, $modinfo, $strsection, $strjumpto, $width=50, $cmid=0) {
5437 global $CFG;
5439 $section = -1;
5440 $url = '';
5441 $menu = array();
5442 $doneheading = false;
5444 $coursecontext = get_context_instance(CONTEXT_COURSE, $course->id);
5446 $menu[] = '<ul class="navmenulist"><li class="jumpto section"><span>'.$strjumpto.'</span><ul>';
5447 foreach ($modinfo->cms as $mod) {
5448 if ($mod->modname == 'label') {
5449 continue;
5452 if ($mod->sectionnum > $course->numsections) { /// Don't show excess hidden sections
5453 break;
5456 if (!$mod->uservisible) { // do not icnlude empty sections at all
5457 continue;
5460 if ($mod->sectionnum >= 0 and $section != $mod->sectionnum) {
5461 $thissection = $sections[$mod->sectionnum];
5463 if ($thissection->visible or !$course->hiddensections or
5464 has_capability('moodle/course:viewhiddensections', $coursecontext)) {
5465 $thissection->summary = strip_tags(format_string($thissection->summary,true));
5466 if (!$doneheading) {
5467 $menu[] = '</ul></li>';
5469 if ($course->format == 'weeks' or empty($thissection->summary)) {
5470 $item = $strsection ." ". $mod->sectionnum;
5471 } else {
5472 if (strlen($thissection->summary) < ($width-3)) {
5473 $item = $thissection->summary;
5474 } else {
5475 $item = substr($thissection->summary, 0, $width).'...';
5478 $menu[] = '<li class="section"><span>'.$item.'</span>';
5479 $menu[] = '<ul>';
5480 $doneheading = true;
5482 $section = $mod->sectionnum;
5483 } else {
5484 // no activities from this hidden section shown
5485 continue;
5489 $url = $mod->modname .'/view.php?id='. $mod->id;
5490 $mod->name = strip_tags(format_string(urldecode($mod->name),true));
5491 if (strlen($mod->name) > ($width+5)) {
5492 $mod->name = substr($mod->name, 0, $width).'...';
5494 if (!$mod->visible) {
5495 $mod->name = '('.$mod->name.')';
5497 $class = 'activity '.$mod->modname;
5498 $class .= ($cmid == $mod->cm) ? ' selected' : '';
5499 $menu[] = '<li class="'.$class.'">'.
5500 '<img src="'.$CFG->modpixpath.'/'.$mod->modname.'/icon.gif" alt="" />'.
5501 '<a href="'.$CFG->wwwroot.'/mod/'.$url.'">'.$mod->name.'</a></li>';
5504 if ($doneheading) {
5505 $menu[] = '</ul></li>';
5507 $menu[] = '</ul></li></ul>';
5509 return implode("\n", $menu);
5513 * Prints form items with the names $day, $month and $year
5515 * @param string $day fieldname
5516 * @param string $month fieldname
5517 * @param string $year fieldname
5518 * @param int $currenttime A default timestamp in GMT
5519 * @param boolean $return
5521 function print_date_selector($day, $month, $year, $currenttime=0, $return=false) {
5523 if (!$currenttime) {
5524 $currenttime = time();
5526 $currentdate = usergetdate($currenttime);
5528 for ($i=1; $i<=31; $i++) {
5529 $days[$i] = $i;
5531 for ($i=1; $i<=12; $i++) {
5532 $months[$i] = userdate(gmmktime(12,0,0,$i,15,2000), "%B");
5534 for ($i=1970; $i<=2020; $i++) {
5535 $years[$i] = $i;
5537 return choose_from_menu($days, $day, $currentdate['mday'], '', '', '0', $return)
5538 .choose_from_menu($months, $month, $currentdate['mon'], '', '', '0', $return)
5539 .choose_from_menu($years, $year, $currentdate['year'], '', '', '0', $return);
5544 *Prints form items with the names $hour and $minute
5546 * @param string $hour fieldname
5547 * @param string ? $minute fieldname
5548 * @param $currenttime A default timestamp in GMT
5549 * @param int $step minute spacing
5550 * @param boolean $return
5552 function print_time_selector($hour, $minute, $currenttime=0, $step=5, $return=false) {
5554 if (!$currenttime) {
5555 $currenttime = time();
5557 $currentdate = usergetdate($currenttime);
5558 if ($step != 1) {
5559 $currentdate['minutes'] = ceil($currentdate['minutes']/$step)*$step;
5561 for ($i=0; $i<=23; $i++) {
5562 $hours[$i] = sprintf("%02d",$i);
5564 for ($i=0; $i<=59; $i+=$step) {
5565 $minutes[$i] = sprintf("%02d",$i);
5568 return choose_from_menu($hours, $hour, $currentdate['hours'], '','','0',$return)
5569 .choose_from_menu($minutes, $minute, $currentdate['minutes'], '','','0',$return);
5573 * Prints time limit value selector
5575 * @uses $CFG
5576 * @param int $timelimit default
5577 * @param string $unit
5578 * @param string $name
5579 * @param boolean $return
5581 function print_timer_selector($timelimit = 0, $unit = '', $name = 'timelimit', $return=false) {
5583 global $CFG;
5585 if ($unit) {
5586 $unit = ' '.$unit;
5589 // Max timelimit is sessiontimeout - 10 minutes.
5590 $maxvalue = ($CFG->sessiontimeout / 60) - 10;
5592 for ($i=1; $i<=$maxvalue; $i++) {
5593 $minutes[$i] = $i.$unit;
5595 return choose_from_menu($minutes, $name, $timelimit, get_string('none'), '','','0',$return);
5599 * Prints a grade menu (as part of an existing form) with help
5600 * Showing all possible numerical grades and scales
5602 * @uses $CFG
5603 * @param int $courseid ?
5604 * @param string $name ?
5605 * @param string $current ?
5606 * @param boolean $includenograde ?
5607 * @todo Finish documenting this function
5609 function print_grade_menu($courseid, $name, $current, $includenograde=true, $return=false) {
5611 global $CFG;
5613 $output = '';
5614 $strscale = get_string('scale');
5615 $strscales = get_string('scales');
5617 $scales = get_scales_menu($courseid);
5618 foreach ($scales as $i => $scalename) {
5619 $grades[-$i] = $strscale .': '. $scalename;
5621 if ($includenograde) {
5622 $grades[0] = get_string('nograde');
5624 for ($i=100; $i>=1; $i--) {
5625 $grades[$i] = $i;
5627 $output .= choose_from_menu($grades, $name, $current, '', '', 0, true);
5629 $linkobject = '<span class="helplink"><img class="iconhelp" alt="'.$strscales.'" src="'.$CFG->pixpath .'/help.gif" /></span>';
5630 $output .= link_to_popup_window ('/course/scales.php?id='. $courseid .'&amp;list=true', 'ratingscales',
5631 $linkobject, 400, 500, $strscales, 'none', true);
5633 if ($return) {
5634 return $output;
5635 } else {
5636 echo $output;
5641 * Prints a scale menu (as part of an existing form) including help button
5642 * Just like {@link print_grade_menu()} but without the numeric grades
5644 * @param int $courseid ?
5645 * @param string $name ?
5646 * @param string $current ?
5647 * @todo Finish documenting this function
5649 function print_scale_menu($courseid, $name, $current, $return=false) {
5651 global $CFG;
5653 $output = '';
5654 $strscales = get_string('scales');
5655 $output .= choose_from_menu(get_scales_menu($courseid), $name, $current, '', '', 0, true);
5657 $linkobject = '<span class="helplink"><img class="iconhelp" alt="'.$strscales.'" src="'.$CFG->pixpath .'/help.gif" /></span>';
5658 $output .= link_to_popup_window ('/course/scales.php?id='. $courseid .'&amp;list=true', 'ratingscales',
5659 $linkobject, 400, 500, $strscales, 'none', true);
5660 if ($return) {
5661 return $output;
5662 } else {
5663 echo $output;
5668 * Prints a help button about a scale
5670 * @uses $CFG
5671 * @param id $courseid ?
5672 * @param object $scale ?
5673 * @todo Finish documenting this function
5675 function print_scale_menu_helpbutton($courseid, $scale, $return=false) {
5677 global $CFG;
5679 $output = '';
5680 $strscales = get_string('scales');
5682 $linkobject = '<span class="helplink"><img class="iconhelp" alt="'.$scale->name.'" src="'.$CFG->pixpath .'/help.gif" /></span>';
5683 $output .= link_to_popup_window ('/course/scales.php?id='. $courseid .'&amp;list=true&amp;scaleid='. $scale->id, 'ratingscale',
5684 $linkobject, 400, 500, $scale->name, 'none', true);
5685 if ($return) {
5686 return $output;
5687 } else {
5688 echo $output;
5693 * Print an error page displaying an error message. New method - use this for new code.
5695 * @uses $SESSION
5696 * @uses $CFG
5697 * @param string $errorcode The name of the string from error.php to print
5698 * @param string $link The url where the user will be prompted to continue. If no url is provided the user will be directed to the site index page.
5699 * @param object $a Extra words and phrases that might be required in the error string
5701 function print_error ($errorcode, $module='', $link='', $a=NULL) {
5703 global $CFG, $SESSION, $THEME;
5705 if (empty($module) || $module == 'moodle' || $module == 'core') {
5706 $module = 'error';
5707 $modulelink = 'moodle';
5708 } else {
5709 $modulelink = $module;
5712 if (empty($link) and !defined('ADMIN_EXT_HEADER_PRINTED')) {
5713 if ( !empty($SESSION->fromurl) ) {
5714 $link = $SESSION->fromurl;
5715 unset($SESSION->fromurl);
5716 } else {
5717 $link = $CFG->wwwroot .'/';
5721 if (!empty($CFG->errordocroot)) {
5722 $errordocroot = $CFG->errordocroot;
5723 } else if (!empty($CFG->docroot)) {
5724 $errordocroot = $CFG->docroot;
5725 } else {
5726 $errordocroot = 'http://docs.moodle.org';
5729 $message = get_string($errorcode, $module, $a);
5731 if (defined('FULLME') && FULLME == 'cron') {
5732 // Errors in cron should be mtrace'd.
5733 mtrace($message);
5734 die;
5737 $message = clean_text('<p class="errormessage">'.$message.'</p>'.
5738 '<p class="errorcode">'.
5739 '<a href="'.$errordocroot.'/en/error/'.$modulelink.'/'.$errorcode.'">'.
5740 get_string('moreinformation').'</a></p>');
5742 if (! defined('HEADER_PRINTED')) {
5743 //header not yet printed
5744 @header('HTTP/1.0 404 Not Found');
5745 print_header(get_string('error'));
5746 } else {
5747 print_container_end_all(false, $THEME->open_header_containers);
5750 echo '<br />';
5752 print_simple_box($message, '', '', '', '', 'errorbox');
5754 debugging('Stack trace:', DEBUG_DEVELOPER);
5756 // in case we are logging upgrade in admin/index.php stop it
5757 if (function_exists('upgrade_log_finish')) {
5758 upgrade_log_finish();
5761 if (!empty($link)) {
5762 print_continue($link);
5765 print_footer();
5767 for ($i=0;$i<512;$i++) { // Padding to help IE work with 404
5768 echo ' ';
5770 die;
5774 * Print an error to STDOUT and exit with a non-zero code. For commandline scripts.
5775 * Default errorcode is 1.
5777 * Very useful for perl-like error-handling:
5779 * do_somethting() or mdie("Something went wrong");
5781 * @param string $msg Error message
5782 * @param integer $errorcode Error code to emit
5784 function mdie($msg='', $errorcode=1) {
5785 trigger_error($msg);
5786 exit($errorcode);
5790 * Returns a string of html with an image of a help icon linked to a help page on a number of help topics.
5791 * Should be used only with htmleditor or textarea.
5792 * @param mixed $helptopics variable amount of params accepted. Each param may be a string or an array of arguments for
5793 * helpbutton.
5794 * @return string
5796 function editorhelpbutton(){
5797 global $CFG, $SESSION;
5798 $items = func_get_args();
5799 $i = 1;
5800 $urlparams = array();
5801 $titles = array();
5802 foreach ($items as $item){
5803 if (is_array($item)){
5804 $urlparams[] = "keyword$i=".urlencode($item[0]);
5805 $urlparams[] = "title$i=".urlencode($item[1]);
5806 if (isset($item[2])){
5807 $urlparams[] = "module$i=".urlencode($item[2]);
5809 $titles[] = trim($item[1], ". \t");
5810 }elseif (is_string($item)){
5811 $urlparams[] = "button$i=".urlencode($item);
5812 switch ($item){
5813 case 'reading' :
5814 $titles[] = get_string("helpreading");
5815 break;
5816 case 'writing' :
5817 $titles[] = get_string("helpwriting");
5818 break;
5819 case 'questions' :
5820 $titles[] = get_string("helpquestions");
5821 break;
5822 case 'emoticons' :
5823 $titles[] = get_string("helpemoticons");
5824 break;
5825 case 'richtext' :
5826 $titles[] = get_string('helprichtext');
5827 break;
5828 case 'text' :
5829 $titles[] = get_string('helptext');
5830 break;
5831 default :
5832 error('Unknown help topic '.$item);
5835 $i++;
5837 if (count($titles)>1){
5838 //join last two items with an 'and'
5839 $a = new object();
5840 $a->one = $titles[count($titles) - 2];
5841 $a->two = $titles[count($titles) - 1];
5842 $titles[count($titles) - 2] = get_string('and', '', $a);
5843 unset($titles[count($titles) - 1]);
5845 $alttag = join (', ', $titles);
5847 $paramstring = join('&', $urlparams);
5848 $linkobject = '<img alt="'.$alttag.'" class="iconhelp" src="'.$CFG->pixpath .'/help.gif" />';
5849 return link_to_popup_window(s('/lib/form/editorhelp.php?'.$paramstring), 'popup', $linkobject, 400, 500, $alttag, 'none', true);
5853 * Print a help button.
5855 * @uses $CFG
5856 * @param string $page The keyword that defines a help page
5857 * @param string $title The title of links, rollover tips, alt tags etc
5858 * 'Help with' (or the language equivalent) will be prefixed and '...' will be stripped.
5859 * @param string $module Which module is the page defined in
5860 * @param mixed $image Use a help image for the link? (true/false/"both")
5861 * @param boolean $linktext If true, display the title next to the help icon.
5862 * @param string $text If defined then this text is used in the page, and
5863 * the $page variable is ignored.
5864 * @param boolean $return If true then the output is returned as a string, if false it is printed to the current page.
5865 * @param string $imagetext The full text for the helpbutton icon. If empty use default help.gif
5866 * @return string
5867 * @todo Finish documenting this function
5869 function helpbutton ($page, $title, $module='moodle', $image=true, $linktext=false, $text='', $return=false,
5870 $imagetext='') {
5871 global $CFG, $COURSE;
5873 //warning if ever $text parameter is used
5874 //$text option won't work properly because the text needs to be always cleaned and,
5875 // when cleaned... html tags always break, so it's unusable.
5876 if ( isset($text) && $text!='') {
5877 debugging('Warning: it\'s not recommended to use $text parameter in helpbutton ($page=' . $page . ', $module=' . $module . ') function', DEBUG_DEVELOPER);
5880 // fix for MDL-7734
5881 if (!empty($COURSE->lang)) {
5882 $forcelang = $COURSE->lang;
5883 } else {
5884 $forcelang = '';
5887 if ($module == '') {
5888 $module = 'moodle';
5891 if ($title == '' && $linktext == '') {
5892 debugging('Error in call to helpbutton function: at least one of $title and $linktext is required');
5895 // Warn users about new window for Accessibility
5896 $tooltip = get_string('helpprefix2', '', trim($title, ". \t")) .' ('.get_string('newwindow').')';
5898 $linkobject = '';
5900 if ($image) {
5901 if ($linktext) {
5902 // MDL-7469 If text link is displayed with help icon, change to alt to "help with this".
5903 $linkobject .= $title.'&nbsp;';
5904 $tooltip = get_string('helpwiththis');
5906 if ($imagetext) {
5907 $linkobject .= $imagetext;
5908 } else {
5909 $linkobject .= '<img class="iconhelp" alt="'.s(strip_tags($tooltip)).'" src="'.
5910 $CFG->pixpath .'/help.gif" />';
5912 } else {
5913 $linkobject .= $tooltip;
5916 // fix for MDL-7734
5917 if ($text) {
5918 $url = '/help.php?module='. $module .'&amp;text='. s(urlencode($text).'&amp;forcelang='.$forcelang);
5919 } else {
5920 $url = '/help.php?module='. $module .'&amp;file='. $page .'.html&amp;forcelang='.$forcelang;
5923 $link = '<span class="helplink">'.
5924 link_to_popup_window ($url, 'popup', $linkobject, 400, 500, $tooltip, 'none', true).
5925 '</span>';
5927 if ($return) {
5928 return $link;
5929 } else {
5930 echo $link;
5935 * Print a help button.
5937 * Prints a special help button that is a link to the "live" emoticon popup
5938 * @uses $CFG
5939 * @uses $SESSION
5940 * @param string $form ?
5941 * @param string $field ?
5942 * @todo Finish documenting this function
5944 function emoticonhelpbutton($form, $field, $return = false) {
5946 global $CFG, $SESSION;
5948 $SESSION->inserttextform = $form;
5949 $SESSION->inserttextfield = $field;
5950 $imagetext = '<img src="' . $CFG->pixpath . '/s/smiley.gif" alt="" class="emoticon" style="margin-left:3px; padding-right:1px;width:15px;height:15px;" />';
5951 $help = helpbutton('emoticons', get_string('helpemoticons'), 'moodle', true, true, '', true, $imagetext);
5952 if (!$return){
5953 echo $help;
5954 } else {
5955 return $help;
5960 * Print a help button.
5962 * Prints a special help button for html editors (htmlarea in this case)
5963 * @uses $CFG
5965 function editorshortcutshelpbutton() {
5967 global $CFG;
5968 $imagetext = '<img src="' . $CFG->httpswwwroot . '/lib/editor/htmlarea/images/kbhelp.gif" alt="'.
5969 get_string('editorshortcutkeys').'" class="iconkbhelp" />';
5971 return helpbutton('editorshortcuts', get_string('editorshortcutkeys'), 'moodle', true, false, '', true, $imagetext);
5975 * Print a message and exit.
5977 * @uses $CFG
5978 * @param string $message ?
5979 * @param string $link ?
5980 * @todo Finish documenting this function
5982 function notice ($message, $link='', $course=NULL) {
5983 global $CFG, $SITE, $THEME, $COURSE;
5985 $message = clean_text($message); // In case nasties are in here
5987 if (defined('FULLME') && FULLME == 'cron') {
5988 // notices in cron should be mtrace'd.
5989 mtrace($message);
5990 die;
5993 if (! defined('HEADER_PRINTED')) {
5994 //header not yet printed
5995 print_header(get_string('notice'));
5996 } else {
5997 print_container_end_all(false, $THEME->open_header_containers);
6000 print_box($message, 'generalbox', 'notice');
6001 print_continue($link);
6003 if (empty($course)) {
6004 print_footer($COURSE);
6005 } else {
6006 print_footer($course);
6008 exit;
6012 * Print a message along with "Yes" and "No" links for the user to continue.
6014 * @param string $message The text to display
6015 * @param string $linkyes The link to take the user to if they choose "Yes"
6016 * @param string $linkno The link to take the user to if they choose "No"
6017 * TODO Document remaining arguments
6019 function notice_yesno ($message, $linkyes, $linkno, $optionsyes=NULL, $optionsno=NULL, $methodyes='post', $methodno='post') {
6021 global $CFG;
6023 $message = clean_text($message);
6024 $linkyes = clean_text($linkyes);
6025 $linkno = clean_text($linkno);
6027 print_box_start('generalbox', 'notice');
6028 echo '<p>'. $message .'</p>';
6029 echo '<div class="buttons">';
6030 print_single_button($linkyes, $optionsyes, get_string('yes'), $methodyes, $CFG->framename);
6031 print_single_button($linkno, $optionsno, get_string('no'), $methodno, $CFG->framename);
6032 echo '</div>';
6033 print_box_end();
6037 * Provide an definition of error_get_last for PHP before 5.2.0. This simply
6038 * returns NULL, since there is not way to get the right answer.
6040 if (!function_exists('error_get_last')) {
6041 // the eval is needed to prevent PHP 5.2+ from getting a parse error!
6042 eval('
6043 function error_get_last() {
6044 return NULL;
6050 * Redirects the user to another page, after printing a notice
6052 * @param string $url The url to take the user to
6053 * @param string $message The text message to display to the user about the redirect, if any
6054 * @param string $delay How long before refreshing to the new page at $url?
6055 * @todo '&' needs to be encoded into '&amp;' for XHTML compliance,
6056 * however, this is not true for javascript. Therefore we
6057 * first decode all entities in $url (since we cannot rely on)
6058 * the correct input) and then encode for where it's needed
6059 * echo "<script type='text/javascript'>alert('Redirect $url');</script>";
6061 function redirect($url, $message='', $delay=-1) {
6063 global $CFG, $THEME;
6065 if (!empty($CFG->usesid) && !isset($_COOKIE[session_name()])) {
6066 $url = sid_process_url($url);
6069 $message = clean_text($message);
6071 $encodedurl = preg_replace("/\&(?![a-zA-Z0-9#]{1,8};)/", "&amp;", $url);
6072 $encodedurl = preg_replace('/^.*href="([^"]*)".*$/', "\\1", clean_text('<a href="'.$encodedurl.'" />'));
6073 $url = str_replace('&amp;', '&', $encodedurl);
6075 /// At developer debug level. Don't redirect if errors have been printed on screen.
6076 /// Currenly only works in PHP 5.2+; we do not want strict PHP5 errors
6077 $lasterror = error_get_last();
6078 $error = defined('DEBUGGING_PRINTED') or (!empty($lasterror) && ($lasterror['type'] & DEBUG_DEVELOPER));
6079 $errorprinted = debugging('', DEBUG_ALL) && $CFG->debugdisplay && $error;
6080 if ($errorprinted) {
6081 $message = "<strong>Error output, so disabling automatic redirect.</strong></p><p>" . $message;
6084 $performanceinfo = '';
6085 if (defined('MDL_PERF') || (!empty($CFG->perfdebug) and $CFG->perfdebug > 7)) {
6086 if (defined('MDL_PERFTOLOG') && !function_exists('register_shutdown_function')) {
6087 $perf = get_performance_info();
6088 error_log("PERF: " . $perf['txt']);
6092 /// when no message and header printed yet, try to redirect
6093 if (empty($message) and !defined('HEADER_PRINTED')) {
6095 // Technically, HTTP/1.1 requires Location: header to contain
6096 // the absolute path. (In practice browsers accept relative
6097 // paths - but still, might as well do it properly.)
6098 // This code turns relative into absolute.
6099 if (!preg_match('|^[a-z]+:|', $url)) {
6100 // Get host name http://www.wherever.com
6101 $hostpart = preg_replace('|^(.*?[^:/])/.*$|', '$1', $CFG->wwwroot);
6102 if (preg_match('|^/|', $url)) {
6103 // URLs beginning with / are relative to web server root so we just add them in
6104 $url = $hostpart.$url;
6105 } else {
6106 // URLs not beginning with / are relative to path of current script, so add that on.
6107 $url = $hostpart.preg_replace('|\?.*$|','',me()).'/../'.$url;
6109 // Replace all ..s
6110 while (true) {
6111 $newurl = preg_replace('|/(?!\.\.)[^/]*/\.\./|', '/', $url);
6112 if ($newurl == $url) {
6113 break;
6115 $url = $newurl;
6119 $delay = 0;
6120 //try header redirection first
6121 @header($_SERVER['SERVER_PROTOCOL'] . ' 303 See Other'); //302 might not work for POST requests, 303 is ignored by obsolete clients
6122 @header('Location: '.$url);
6123 //another way for older browsers and already sent headers (eg trailing whitespace in config.php)
6124 echo '<meta http-equiv="refresh" content="'. $delay .'; url='. $encodedurl .'" />';
6125 echo '<script type="text/javascript">'. "\n" .'//<![CDATA['. "\n". "location.replace('".addslashes_js($url)."');". "\n". '//]]>'. "\n". '</script>'; // To cope with Mozilla bug
6126 die;
6129 if ($delay == -1) {
6130 $delay = 3; // if no delay specified wait 3 seconds
6132 if (! defined('HEADER_PRINTED')) {
6133 // this type of redirect might not be working in some browsers - such as lynx :-(
6134 print_header('', '', '', '', $errorprinted ? '' : ('<meta http-equiv="refresh" content="'. $delay .'; url='. $encodedurl .'" />'));
6135 $delay += 3; // double redirect prevention, it was sometimes breaking upgrades before 1.7
6136 } else {
6137 print_container_end_all(false, $THEME->open_header_containers);
6139 echo '<div id="redirect">';
6140 echo '<div id="message">' . $message . '</div>';
6141 echo '<div id="continue">( <a href="'. $encodedurl .'">'. get_string('continue') .'</a> )</div>';
6142 echo '</div>';
6144 if (!$errorprinted) {
6146 <script type="text/javascript">
6147 //<![CDATA[
6149 function redirect() {
6150 document.location.replace('<?php echo addslashes_js($url) ?>');
6152 setTimeout("redirect()", <?php echo ($delay * 1000) ?>);
6153 //]]>
6154 </script>
6155 <?php
6158 $CFG->docroot = false; // to prevent the link to moodle docs from being displayed on redirect page.
6159 print_footer('none');
6160 die;
6164 * Print a bold message in an optional color.
6166 * @param string $message The message to print out
6167 * @param string $style Optional style to display message text in
6168 * @param string $align Alignment option
6169 * @param bool $return whether to return an output string or echo now
6171 function notify($message, $style='notifyproblem', $align='center', $return=false) {
6172 if ($style == 'green') {
6173 $style = 'notifysuccess'; // backward compatible with old color system
6176 $message = clean_text($message);
6178 $output = '<div class="'.$style.'" style="text-align:'. $align .'">'. $message .'</div>'."\n";
6180 if ($return) {
6181 return $output;
6183 echo $output;
6188 * Given an email address, this function will return an obfuscated version of it
6190 * @param string $email The email address to obfuscate
6191 * @return string
6193 function obfuscate_email($email) {
6195 $i = 0;
6196 $length = strlen($email);
6197 $obfuscated = '';
6198 while ($i < $length) {
6199 if (rand(0,2)) {
6200 $obfuscated.='%'.dechex(ord($email{$i}));
6201 } else {
6202 $obfuscated.=$email{$i};
6204 $i++;
6206 return $obfuscated;
6210 * This function takes some text and replaces about half of the characters
6211 * with HTML entity equivalents. Return string is obviously longer.
6213 * @param string $plaintext The text to be obfuscated
6214 * @return string
6216 function obfuscate_text($plaintext) {
6218 $i=0;
6219 $length = strlen($plaintext);
6220 $obfuscated='';
6221 $prev_obfuscated = false;
6222 while ($i < $length) {
6223 $c = ord($plaintext{$i});
6224 $numerical = ($c >= ord('0')) && ($c <= ord('9'));
6225 if ($prev_obfuscated and $numerical ) {
6226 $obfuscated.='&#'.ord($plaintext{$i}).';';
6227 } else if (rand(0,2)) {
6228 $obfuscated.='&#'.ord($plaintext{$i}).';';
6229 $prev_obfuscated = true;
6230 } else {
6231 $obfuscated.=$plaintext{$i};
6232 $prev_obfuscated = false;
6234 $i++;
6236 return $obfuscated;
6240 * This function uses the {@link obfuscate_email()} and {@link obfuscate_text()}
6241 * to generate a fully obfuscated email link, ready to use.
6243 * @param string $email The email address to display
6244 * @param string $label The text to dispalyed as hyperlink to $email
6245 * @param boolean $dimmed If true then use css class 'dimmed' for hyperlink
6246 * @return string
6248 function obfuscate_mailto($email, $label='', $dimmed=false) {
6250 if (empty($label)) {
6251 $label = $email;
6253 if ($dimmed) {
6254 $title = get_string('emaildisable');
6255 $dimmed = ' class="dimmed"';
6256 } else {
6257 $title = '';
6258 $dimmed = '';
6260 return sprintf("<a href=\"%s:%s\" $dimmed title=\"$title\">%s</a>",
6261 obfuscate_text('mailto'), obfuscate_email($email),
6262 obfuscate_text($label));
6266 * Prints a single paging bar to provide access to other pages (usually in a search)
6268 * @param int $totalcount Thetotal number of entries available to be paged through
6269 * @param int $page The page you are currently viewing
6270 * @param int $perpage The number of entries that should be shown per page
6271 * @param mixed $baseurl If this is a string then it is the url which will be appended with $pagevar, an equals sign and the page number.
6272 * If this is a moodle_url object then the pagevar param will be replaced by the page no, for each page.
6273 * @param string $pagevar This is the variable name that you use for the page number in your code (ie. 'tablepage', 'blogpage', etc)
6274 * @param bool $nocurr do not display the current page as a link
6275 * @param bool $return whether to return an output string or echo now
6276 * @return bool or string
6278 function print_paging_bar($totalcount, $page, $perpage, $baseurl, $pagevar='page',$nocurr=false, $return=false) {
6279 $maxdisplay = 18;
6280 $output = '';
6282 if ($totalcount > $perpage) {
6283 $output .= '<div class="paging">';
6284 $output .= get_string('page') .':';
6285 if ($page > 0) {
6286 $pagenum = $page - 1;
6287 if (!is_a($baseurl, 'moodle_url')){
6288 $output .= '&nbsp;(<a href="'. $baseurl . $pagevar .'='. $pagenum .'">'. get_string('previous') .'</a>)&nbsp;';
6289 } else {
6290 $output .= '&nbsp;(<a href="'. $baseurl->out(false, array($pagevar => $pagenum)).'">'. get_string('previous') .'</a>)&nbsp;';
6293 if ($perpage > 0) {
6294 $lastpage = ceil($totalcount / $perpage);
6295 } else {
6296 $lastpage = 1;
6298 if ($page > 15) {
6299 $startpage = $page - 10;
6300 if (!is_a($baseurl, 'moodle_url')){
6301 $output .= '&nbsp;<a href="'. $baseurl . $pagevar .'=0">1</a>&nbsp;...';
6302 } else {
6303 $output .= '&nbsp;<a href="'. $baseurl->out(false, array($pagevar => 0)).'">1</a>&nbsp;...';
6305 } else {
6306 $startpage = 0;
6308 $currpage = $startpage;
6309 $displaycount = $displaypage = 0;
6310 while ($displaycount < $maxdisplay and $currpage < $lastpage) {
6311 $displaypage = $currpage+1;
6312 if ($page == $currpage && empty($nocurr)) {
6313 $output .= '&nbsp;&nbsp;'. $displaypage;
6314 } else {
6315 if (!is_a($baseurl, 'moodle_url')){
6316 $output .= '&nbsp;&nbsp;<a href="'. $baseurl . $pagevar .'='. $currpage .'">'. $displaypage .'</a>';
6317 } else {
6318 $output .= '&nbsp;&nbsp;<a href="'. $baseurl->out(false, array($pagevar => $currpage)).'">'. $displaypage .'</a>';
6322 $displaycount++;
6323 $currpage++;
6325 if ($currpage < $lastpage) {
6326 $lastpageactual = $lastpage - 1;
6327 if (!is_a($baseurl, 'moodle_url')){
6328 $output .= '&nbsp;...<a href="'. $baseurl . $pagevar .'='. $lastpageactual .'">'. $lastpage .'</a>&nbsp;';
6329 } else {
6330 $output .= '&nbsp;...<a href="'. $baseurl->out(false, array($pagevar => $lastpageactual)).'">'. $lastpage .'</a>&nbsp;';
6333 $pagenum = $page + 1;
6334 if ($pagenum != $displaypage) {
6335 if (!is_a($baseurl, 'moodle_url')){
6336 $output .= '&nbsp;&nbsp;(<a href="'. $baseurl . $pagevar .'='. $pagenum .'">'. get_string('next') .'</a>)';
6337 } else {
6338 $output .= '&nbsp;&nbsp;(<a href="'. $baseurl->out(false, array($pagevar => $pagenum)) .'">'. get_string('next') .'</a>)';
6341 $output .= '</div>';
6344 if ($return) {
6345 return $output;
6348 echo $output;
6349 return true;
6353 * This function is used to rebuild the <nolink> tag because some formats (PLAIN and WIKI)
6354 * will transform it to html entities
6356 * @param string $text Text to search for nolink tag in
6357 * @return string
6359 function rebuildnolinktag($text) {
6361 $text = preg_replace('/&lt;(\/*nolink)&gt;/i','<$1>',$text);
6363 return $text;
6367 * Prints a nice side block with an optional header. The content can either
6368 * be a block of HTML or a list of text with optional icons.
6370 * @param string $heading Block $title embedded in HTML tags, for example <h2>.
6371 * @param string $content ?
6372 * @param array $list ?
6373 * @param array $icons ?
6374 * @param string $footer ?
6375 * @param array $attributes ?
6376 * @param string $title Plain text title, as embedded in the $heading.
6377 * @todo Finish documenting this function. Show example of various attributes, etc.
6379 function print_side_block($heading='', $content='', $list=NULL, $icons=NULL, $footer='', $attributes = array(), $title='') {
6381 //Accessibility: skip block link, with title-text (or $block_id) to differentiate links.
6382 static $block_id = 0;
6383 $block_id++;
6384 if (empty($heading)) {
6385 $skip_text = get_string('skipblock', 'access').' '.$block_id;
6387 else {
6388 $skip_text = get_string('skipa', 'access', strip_tags($title));
6390 $skip_link = '<a href="#sb-'.$block_id.'" class="skip-block">'.$skip_text.'</a>';
6391 $skip_dest = '<span id="sb-'.$block_id.'" class="skip-block-to"></span>';
6393 if (! empty($heading)) {
6394 echo $skip_link;
6396 //ELSE: a single link on a page "Skip block 4" is too confusing - ignore.
6398 print_side_block_start($heading, $attributes);
6400 if ($content) {
6401 echo $content;
6402 if ($footer) {
6403 echo '<div class="footer">'. $footer .'</div>';
6405 } else {
6406 if ($list) {
6407 $row = 0;
6408 //Accessibility: replaced unnecessary table with list, see themes/standard/styles_layout.css
6409 echo "\n<ul class='list'>\n";
6410 foreach ($list as $key => $string) {
6411 echo '<li class="r'. $row .'">';
6412 if ($icons) {
6413 echo '<div class="icon column c0">'. $icons[$key] .'</div>';
6415 echo '<div class="column c1">'. $string .'</div>';
6416 echo "</li>\n";
6417 $row = $row ? 0:1;
6419 echo "</ul>\n";
6421 if ($footer) {
6422 echo '<div class="footer">'. $footer .'</div>';
6427 print_side_block_end($attributes, $title);
6428 echo $skip_dest;
6432 * Starts a nice side block with an optional header.
6434 * @param string $heading ?
6435 * @param array $attributes ?
6436 * @todo Finish documenting this function
6438 function print_side_block_start($heading='', $attributes = array()) {
6440 global $CFG, $THEME;
6442 // If there are no special attributes, give a default CSS class
6443 if (empty($attributes) || !is_array($attributes)) {
6444 $attributes = array('class' => 'sideblock');
6446 } else if(!isset($attributes['class'])) {
6447 $attributes['class'] = 'sideblock';
6449 } else if(!strpos($attributes['class'], 'sideblock')) {
6450 $attributes['class'] .= ' sideblock';
6453 // OK, the class is surely there and in addition to anything
6454 // else, it's tagged as a sideblock
6458 // IE misery: if I do it this way, blocks which start hidden cannot be "unhidden"
6460 // If there is a cookie to hide this thing, start it hidden
6461 if (!empty($attributes['id']) && isset($_COOKIE['hide:'.$attributes['id']])) {
6462 $attributes['class'] = 'hidden '.$attributes['class'];
6466 $attrtext = '';
6467 foreach ($attributes as $attr => $val) {
6468 $attrtext .= ' '.$attr.'="'.$val.'"';
6471 echo '<div '.$attrtext.'>';
6473 if (!empty($THEME->customcorners)) {
6474 echo '<div class="wrap">'."\n";
6476 if ($heading) {
6477 //Accessibility: H2 more appropriate in moodleblock.class.php: _title_html.
6478 echo '<div class="header">';
6479 if (!empty($THEME->customcorners)) {
6480 echo '<div class="bt"><div>&nbsp;</div></div>';
6481 echo '<div class="i1"><div class="i2">';
6482 echo '<div class="i3">';
6484 echo $heading;
6485 if (!empty($THEME->customcorners)) {
6486 echo '</div></div></div>';
6488 echo '</div>';
6489 } else {
6490 if (!empty($THEME->customcorners)) {
6491 echo '<div class="bt"><div>&nbsp;</div></div>';
6495 if (!empty($THEME->customcorners)) {
6496 echo '<div class="i1"><div class="i2">';
6497 echo '<div class="i3">';
6499 echo '<div class="content">';
6505 * Print table ending tags for a side block box.
6507 function print_side_block_end($attributes = array(), $title='') {
6508 global $CFG, $THEME;
6510 echo '</div>';
6512 if (!empty($THEME->customcorners)) {
6513 echo '</div></div></div><div class="bb"><div>&nbsp;</div></div></div>';
6516 echo '</div>';
6518 $strshow = addslashes_js(get_string('showblocka', 'access', strip_tags($title)));
6519 $strhide = addslashes_js(get_string('hideblocka', 'access', strip_tags($title)));
6521 // IE workaround: if I do it THIS way, it works! WTF?
6522 if (!empty($CFG->allowuserblockhiding) && isset($attributes['id'])) {
6523 echo '<script type="text/javascript">'."\n//<![CDATA[\n".'elementCookieHide("'.$attributes['id'].
6524 '","'.$strshow.'","'.$strhide."\");\n//]]>\n".'</script>';
6531 * Prints out code needed for spellchecking.
6532 * Original idea by Ludo (Marc Alier).
6534 * Opening CDATA and <script> are output by weblib::use_html_editor()
6535 * @uses $CFG
6536 * @param boolean $usehtmleditor Normally set by $CFG->htmleditor, can be overriden here
6537 * @param boolean $return If false, echos the code instead of returning it
6538 * @todo Find out if lib/editor/htmlarea/htmlarea.class.php::print_speller_code() is still used, and delete if not
6540 function print_speller_code ($usehtmleditor=false, $return=false) {
6541 global $CFG;
6542 $str = '';
6544 if(!$usehtmleditor) {
6545 $str .= 'function openSpellChecker() {'."\n";
6546 $str .= "\tvar speller = new spellChecker();\n";
6547 $str .= "\tspeller.popUpUrl = \"" . $CFG->httpswwwroot ."/lib/speller/spellchecker.html\";\n";
6548 $str .= "\tspeller.spellCheckScript = \"". $CFG->httpswwwroot ."/lib/speller/server-scripts/spellchecker.php\";\n";
6549 $str .= "\tspeller.spellCheckAll();\n";
6550 $str .= '}'."\n";
6551 } else {
6552 $str .= "function spellClickHandler(editor, buttonId) {\n";
6553 $str .= "\teditor._textArea.value = editor.getHTML();\n";
6554 $str .= "\tvar speller = new spellChecker( editor._textArea );\n";
6555 $str .= "\tspeller.popUpUrl = \"" . $CFG->httpswwwroot ."/lib/speller/spellchecker.html\";\n";
6556 $str .= "\tspeller.spellCheckScript = \"". $CFG->httpswwwroot ."/lib/speller/server-scripts/spellchecker.php\";\n";
6557 $str .= "\tspeller._moogle_edit=1;\n";
6558 $str .= "\tspeller._editor=editor;\n";
6559 $str .= "\tspeller.openChecker();\n";
6560 $str .= '}'."\n";
6563 if ($return) {
6564 return $str;
6566 echo $str;
6570 * Print button for spellchecking when editor is disabled
6572 function print_speller_button () {
6573 echo '<input type="button" value="Check spelling" onclick="openSpellChecker();" />'."\n";
6577 function page_id_and_class(&$getid, &$getclass) {
6578 // Create class and id for this page
6579 global $CFG, $ME;
6581 static $class = NULL;
6582 static $id = NULL;
6584 if (empty($CFG->pagepath)) {
6585 $CFG->pagepath = $ME;
6588 if (empty($class) || empty($id)) {
6589 $path = str_replace($CFG->httpswwwroot.'/', '', $CFG->pagepath); //Because the page could be HTTPSPAGEREQUIRED
6590 $path = str_replace('.php', '', $path);
6591 if (substr($path, -1) == '/') {
6592 $path .= 'index';
6594 if (empty($path) || $path == 'index') {
6595 $id = 'site-index';
6596 $class = 'course';
6597 } else if (substr($path, 0, 5) == 'admin') {
6598 $id = str_replace('/', '-', $path);
6599 $class = 'admin';
6600 } else {
6601 $id = str_replace('/', '-', $path);
6602 $class = explode('-', $id);
6603 array_pop($class);
6604 $class = implode('-', $class);
6608 $getid = $id;
6609 $getclass = $class;
6613 * Prints a maintenance message from /maintenance.html
6615 function print_maintenance_message () {
6616 global $CFG, $SITE;
6618 $CFG->pagepath = "index.php";
6619 print_header(strip_tags($SITE->fullname), $SITE->fullname, 'home');
6620 print_box_start();
6621 print_heading(get_string('sitemaintenance', 'admin'));
6622 @include($CFG->dataroot.'/1/maintenance.html');
6623 print_box_end();
6624 print_footer();
6628 * Adjust the list of allowed tags based on $CFG->allowobjectembed and user roles (admin)
6630 function adjust_allowed_tags() {
6632 global $CFG, $ALLOWED_TAGS;
6634 if (!empty($CFG->allowobjectembed)) {
6635 $ALLOWED_TAGS .= '<embed><object>';
6639 /// Some code to print tabs
6641 /// A class for tabs
6642 class tabobject {
6643 var $id;
6644 var $link;
6645 var $text;
6646 var $linkedwhenselected;
6648 /// A constructor just because I like constructors
6649 function tabobject ($id, $link='', $text='', $title='', $linkedwhenselected=false) {
6650 $this->id = $id;
6651 $this->link = $link;
6652 $this->text = $text;
6653 $this->title = $title ? $title : $text;
6654 $this->linkedwhenselected = $linkedwhenselected;
6661 * Returns a string containing a nested list, suitable for formatting into tabs with CSS.
6663 * @param array $tabrows An array of rows where each row is an array of tab objects
6664 * @param string $selected The id of the selected tab (whatever row it's on)
6665 * @param array $inactive An array of ids of inactive tabs that are not selectable.
6666 * @param array $activated An array of ids of other tabs that are currently activated
6668 function print_tabs($tabrows, $selected=NULL, $inactive=NULL, $activated=NULL, $return=false) {
6669 global $CFG;
6671 /// $inactive must be an array
6672 if (!is_array($inactive)) {
6673 $inactive = array();
6676 /// $activated must be an array
6677 if (!is_array($activated)) {
6678 $activated = array();
6681 /// Convert the tab rows into a tree that's easier to process
6682 if (!$tree = convert_tabrows_to_tree($tabrows, $selected, $inactive, $activated)) {
6683 return false;
6686 /// Print out the current tree of tabs (this function is recursive)
6688 $output = convert_tree_to_html($tree);
6690 $output = "\n\n".'<div class="tabtree">'.$output.'</div><div class="clearer"> </div>'."\n\n";
6692 /// We're done!
6694 if ($return) {
6695 return $output;
6697 echo $output;
6701 function convert_tree_to_html($tree, $row=0) {
6703 $str = "\n".'<ul class="tabrow'.$row.'">'."\n";
6705 $first = true;
6706 $count = count($tree);
6708 foreach ($tree as $tab) {
6709 $count--; // countdown to zero
6711 $liclass = '';
6713 if ($first && ($count == 0)) { // Just one in the row
6714 $liclass = 'first last';
6715 $first = false;
6716 } else if ($first) {
6717 $liclass = 'first';
6718 $first = false;
6719 } else if ($count == 0) {
6720 $liclass = 'last';
6723 if ((empty($tab->subtree)) && (!empty($tab->selected))) {
6724 $liclass .= (empty($liclass)) ? 'onerow' : ' onerow';
6727 if ($tab->inactive || $tab->active || $tab->selected) {
6728 if ($tab->selected) {
6729 $liclass .= (empty($liclass)) ? 'here selected' : ' here selected';
6730 } else if ($tab->active) {
6731 $liclass .= (empty($liclass)) ? 'here active' : ' here active';
6735 $str .= (!empty($liclass)) ? '<li class="'.$liclass.'">' : '<li>';
6737 if ($tab->inactive || $tab->active || ($tab->selected && !$tab->linkedwhenselected)) {
6738 // The a tag is used for styling
6739 $str .= '<a class="nolink"><span>'.$tab->text.'</span></a>';
6740 } else {
6741 $str .= '<a href="'.$tab->link.'" title="'.$tab->title.'"><span>'.$tab->text.'</span></a>';
6744 if (!empty($tab->subtree)) {
6745 $str .= convert_tree_to_html($tab->subtree, $row+1);
6746 } else if ($tab->selected) {
6747 $str .= '<div class="tabrow'.($row+1).' empty">&nbsp;</div>'."\n";
6750 $str .= ' </li>'."\n";
6752 $str .= '</ul>'."\n";
6754 return $str;
6758 function convert_tabrows_to_tree($tabrows, $selected, $inactive, $activated) {
6760 /// Work backwards through the rows (bottom to top) collecting the tree as we go.
6762 $tabrows = array_reverse($tabrows);
6764 $subtree = array();
6766 foreach ($tabrows as $row) {
6767 $tree = array();
6769 foreach ($row as $tab) {
6770 $tab->inactive = in_array((string)$tab->id, $inactive);
6771 $tab->active = in_array((string)$tab->id, $activated);
6772 $tab->selected = (string)$tab->id == $selected;
6774 if ($tab->active || $tab->selected) {
6775 if ($subtree) {
6776 $tab->subtree = $subtree;
6779 $tree[] = $tab;
6781 $subtree = $tree;
6784 return $subtree;
6789 * Returns a string containing a link to the user documentation for the current
6790 * page. Also contains an icon by default. Shown to teachers and admin only.
6792 * @param string $text The text to be displayed for the link
6793 * @param string $iconpath The path to the icon to be displayed
6795 function page_doc_link($text='', $iconpath='') {
6796 global $ME, $COURSE, $CFG;
6798 if (empty($CFG->docroot) or empty($CFG->rolesactive)) {
6799 return '';
6802 if (empty($COURSE->id)) {
6803 $context = get_context_instance(CONTEXT_SYSTEM);
6804 } else {
6805 $context = get_context_instance(CONTEXT_COURSE, $COURSE->id);
6808 if (!has_capability('moodle/site:doclinks', $context)) {
6809 return '';
6812 if (empty($CFG->pagepath)) {
6813 $CFG->pagepath = $ME;
6816 $path = str_replace($CFG->httpswwwroot.'/','', $CFG->pagepath); // Because the page could be HTTPSPAGEREQUIRED
6817 $path = str_replace('.php', '', $path);
6819 if (empty($path)) { // Not for home page
6820 return '';
6822 return doc_link($path, $text, $iconpath);
6826 * Returns a string containing a link to the user documentation.
6827 * Also contains an icon by default. Shown to teachers and admin only.
6829 * @param string $path The page link after doc root and language, no
6830 * leading slash.
6831 * @param string $text The text to be displayed for the link
6832 * @param string $iconpath The path to the icon to be displayed
6834 function doc_link($path='', $text='', $iconpath='') {
6835 global $CFG;
6837 if (empty($CFG->docroot)) {
6838 return '';
6841 $target = '';
6842 if (!empty($CFG->doctonewwindow)) {
6843 $target = ' target="_blank"';
6846 $lang = str_replace('_utf8', '', current_language());
6848 $str = '<a href="' .$CFG->docroot. '/' .$lang. '/' .$path. '"' .$target. '>';
6850 if (empty($iconpath)) {
6851 $iconpath = $CFG->httpswwwroot . '/pix/docs.gif';
6854 // alt left blank intentionally to prevent repetition in screenreaders
6855 $str .= '<img class="iconhelp" src="' .$iconpath. '" alt="" />' .$text. '</a>';
6857 return $str;
6862 * Returns true if the current site debugging settings are equal or above specified level.
6863 * If passed a parameter it will emit a debugging notice similar to trigger_error(). The
6864 * routing of notices is controlled by $CFG->debugdisplay
6865 * eg use like this:
6867 * 1) debugging('a normal debug notice');
6868 * 2) debugging('something really picky', DEBUG_ALL);
6869 * 3) debugging('annoying debug message only for develpers', DEBUG_DEVELOPER);
6870 * 4) if (debugging()) { perform extra debugging operations (do not use print or echo) }
6872 * In code blocks controlled by debugging() (such as example 4)
6873 * any output should be routed via debugging() itself, or the lower-level
6874 * trigger_error() or error_log(). Using echo or print will break XHTML
6875 * JS and HTTP headers.
6878 * @param string $message a message to print
6879 * @param int $level the level at which this debugging statement should show
6880 * @return bool
6882 function debugging($message='', $level=DEBUG_NORMAL) {
6884 global $CFG;
6886 if (empty($CFG->debug)) {
6887 return false;
6890 if ($CFG->debug >= $level) {
6891 if ($message) {
6892 $callers = debug_backtrace();
6893 $from = '<ul style="text-align: left">';
6894 foreach ($callers as $caller) {
6895 if (!isset($caller['line'])) {
6896 $caller['line'] = '?'; // probably call_user_func()
6898 if (!isset($caller['file'])) {
6899 $caller['file'] = $CFG->dirroot.'/unknownfile'; // probably call_user_func()
6901 $from .= '<li>line ' . $caller['line'] . ' of ' . substr($caller['file'], strlen($CFG->dirroot) + 1);
6902 if (isset($caller['function'])) {
6903 $from .= ': call to ';
6904 if (isset($caller['class'])) {
6905 $from .= $caller['class'] . $caller['type'];
6907 $from .= $caller['function'] . '()';
6909 $from .= '</li>';
6911 $from .= '</ul>';
6912 if (!isset($CFG->debugdisplay)) {
6913 $CFG->debugdisplay = ini_get_bool('display_errors');
6915 if ($CFG->debugdisplay) {
6916 if (!defined('DEBUGGING_PRINTED')) {
6917 define('DEBUGGING_PRINTED', 1); // indicates we have printed something
6919 notify($message . $from, 'notifytiny');
6920 } else {
6921 trigger_error($message . $from, E_USER_NOTICE);
6924 return true;
6926 return false;
6930 * Disable debug messages from debugging(), while keeping PHP error reporting level as is.
6932 function disable_debugging() {
6933 global $CFG;
6934 $CFG->debug = $CFG->debug | 0x80000000; // switch the sign bit in integer number ;-)
6939 * Returns string to add a frame attribute, if required
6941 function frametarget() {
6942 global $CFG;
6944 if (empty($CFG->framename) or ($CFG->framename == '_top')) {
6945 return '';
6946 } else {
6947 return ' target="'.$CFG->framename.'" ';
6952 * Outputs a HTML comment to the browser. This is used for those hard-to-debug
6953 * pages that use bits from many different files in very confusing ways (e.g. blocks).
6954 * @usage print_location_comment(__FILE__, __LINE__);
6955 * @param string $file
6956 * @param integer $line
6957 * @param boolean $return Whether to return or print the comment
6958 * @return mixed Void unless true given as third parameter
6960 function print_location_comment($file, $line, $return = false)
6962 if ($return) {
6963 return "<!-- $file at line $line -->\n";
6964 } else {
6965 echo "<!-- $file at line $line -->\n";
6971 * Returns an image of an up or down arrow, used for column sorting. To avoid unnecessary DB accesses, please
6972 * provide this function with the language strings for sortasc and sortdesc.
6973 * If no sort string is associated with the direction, an arrow with no alt text will be printed/returned.
6974 * @param string $direction 'up' or 'down'
6975 * @param string $strsort The language string used for the alt attribute of this image
6976 * @param bool $return Whether to print directly or return the html string
6977 * @return string HTML for the image
6979 * TODO See if this isn't already defined somewhere. If not, move this to weblib
6981 function print_arrow($direction='up', $strsort=null, $return=false) {
6982 global $CFG;
6984 if (!in_array($direction, array('up', 'down', 'right', 'left', 'move'))) {
6985 return null;
6988 $return = null;
6990 switch ($direction) {
6991 case 'up':
6992 $sortdir = 'asc';
6993 break;
6994 case 'down':
6995 $sortdir = 'desc';
6996 break;
6997 case 'move':
6998 $sortdir = 'asc';
6999 break;
7000 default:
7001 $sortdir = null;
7002 break;
7005 // Prepare language string
7006 $strsort = '';
7007 if (empty($strsort) && !empty($sortdir)) {
7008 $strsort = get_string('sort' . $sortdir, 'grades');
7011 $return = ' <img src="'.$CFG->pixpath.'/t/' . $direction . '.gif" alt="'.$strsort.'" /> ';
7013 if ($return) {
7014 return $return;
7015 } else {
7016 echo $return;
7021 * Returns boolean true if the current language is right-to-left (Hebrew, Arabic etc)
7024 function right_to_left() {
7025 static $result;
7027 if (isset($result)) {
7028 return $result;
7030 return $result = (get_string('thisdirection') == 'rtl');
7035 * Returns swapped left<=>right if in RTL environment.
7036 * part of RTL support
7038 * @param string $align align to check
7039 * @return string
7041 function fix_align_rtl($align) {
7042 if (!right_to_left()) {
7043 return $align;
7045 if ($align=='left') { return 'right'; }
7046 if ($align=='right') { return 'left'; }
7047 return $align;
7052 * Returns true if the page is displayed in a popup window.
7053 * Gets the information from the URL parameter inpopup.
7055 * @return boolean
7057 * TODO Use a central function to create the popup calls allover Moodle and
7058 * TODO In the moment only works with resources and probably questions.
7060 function is_in_popup() {
7061 $inpopup = optional_param('inpopup', '', PARAM_BOOL);
7063 return ($inpopup);
7067 // vim:autoindent:expandtab:shiftwidth=4:tabstop=4:tw=140: