Further work on Moodle 1.9 integration.
[moodle/mihaisucan.git] / lib / weblib.php
blob5e08a6c13a885b1f584c5197876b94844a251093
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', 'background-color', '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);
343 * Add an array of params to the params for this page.
345 * The added params override existing ones if they have the same name.
347 * @param array $params Defaults to null. If null then return value of param 'name'.
348 * @return array Array of Params for url.
350 function params($params = null) {
351 if (!is_null($params)) {
352 return $this->params = $params + $this->params;
353 } else {
354 return $this->params;
359 * Remove all params if no arguments passed. Or else remove param $arg1, $arg2, etc.
361 * @param string $arg1
362 * @param string $arg2
363 * @param string $arg3
365 function remove_params(){
366 if ($thisargs = func_get_args()){
367 foreach ($thisargs as $arg){
368 if (isset($this->params[$arg])){
369 unset($this->params[$arg]);
372 } else { // no args
373 $this->params = array();
378 * Add a param to the params for this page. The added param overrides existing one if they
379 * have the same name.
381 * @param string $paramname name
382 * @param string $param value
384 function param($paramname, $param){
385 $this->params = array($paramname => $param) + $this->params;
389 function get_query_string($overrideparams = array()){
390 $arr = array();
391 $params = $overrideparams + $this->params;
392 foreach ($params as $key => $val){
393 $arr[] = urlencode($key)."=".urlencode($val);
395 return implode($arr, "&amp;");
398 * Outputs params as hidden form elements.
400 * @param array $exclude params to ignore
401 * @param integer $indent indentation
402 * @param array $overrideparams params to add to the output params, these
403 * override existing ones with the same name.
404 * @return string html for form elements.
406 function hidden_params_out($exclude = array(), $indent = 0, $overrideparams=array()){
407 $tabindent = str_repeat("\t", $indent);
408 $str = '';
409 $params = $overrideparams + $this->params;
410 foreach ($params as $key => $val){
411 if (FALSE === array_search($key, $exclude)) {
412 $val = s($val);
413 $str.= "$tabindent<input type=\"hidden\" name=\"$key\" value=\"$val\" />\n";
416 return $str;
419 * Output url
421 * @param boolean $noquerystring whether to output page params as a query string in the url.
422 * @param array $overrideparams params to add to the output url, these override existing ones with the same name.
423 * @return string url
425 function out($noquerystring = false, $overrideparams = array()) {
426 $uri = $this->scheme ? $this->scheme.':'.((strtolower($this->scheme) == 'mailto') ? '':'//'): '';
427 $uri .= $this->user ? $this->user.($this->pass? ':'.$this->pass:'').'@':'';
428 $uri .= $this->host ? $this->host : '';
429 $uri .= $this->port ? ':'.$this->port : '';
430 $uri .= $this->path ? $this->path : '';
431 if (!$noquerystring){
432 $uri .= (count($this->params)||count($overrideparams)) ? '?'.$this->get_query_string($overrideparams) : '';
434 $uri .= $this->fragment ? '#'.$this->fragment : '';
435 return $uri;
438 * Output action url with sesskey
440 * @param boolean $noquerystring whether to output page params as a query string in the url.
441 * @return string url
443 function out_action($overrideparams = array()) {
444 $overrideparams = array('sesskey'=> sesskey()) + $overrideparams;
445 return $this->out(false, $overrideparams);
450 * Determine if there is data waiting to be processed from a form
452 * Used on most forms in Moodle to check for data
453 * Returns the data as an object, if it's found.
454 * This object can be used in foreach loops without
455 * casting because it's cast to (array) automatically
457 * Checks that submitted POST data exists and returns it as object.
459 * @param string $url not used anymore
460 * @return mixed false or object
462 function data_submitted($url='') {
464 if (empty($_POST)) {
465 return false;
466 } else {
467 return (object)$_POST;
472 * Moodle replacement for php stripslashes() function,
473 * works also for objects and arrays.
475 * The standard php stripslashes() removes ALL backslashes
476 * even from strings - so C:\temp becomes C:temp - this isn't good.
477 * This function should work as a fairly safe replacement
478 * to be called on quoted AND unquoted strings (to be sure)
480 * @param mixed something to remove unsafe slashes from
481 * @return mixed
483 function stripslashes_safe($mixed) {
484 // there is no need to remove slashes from int, float and bool types
485 if (empty($mixed)) {
486 //nothing to do...
487 } else if (is_string($mixed)) {
488 if (ini_get_bool('magic_quotes_sybase')) { //only unescape single quotes
489 $mixed = str_replace("''", "'", $mixed);
490 } else { //the rest, simple and double quotes and backslashes
491 $mixed = str_replace("\\'", "'", $mixed);
492 $mixed = str_replace('\\"', '"', $mixed);
493 $mixed = str_replace('\\\\', '\\', $mixed);
495 } else if (is_array($mixed)) {
496 foreach ($mixed as $key => $value) {
497 $mixed[$key] = stripslashes_safe($value);
499 } else if (is_object($mixed)) {
500 $vars = get_object_vars($mixed);
501 foreach ($vars as $key => $value) {
502 $mixed->$key = stripslashes_safe($value);
506 return $mixed;
510 * Recursive implementation of stripslashes()
512 * This function will allow you to strip the slashes from a variable.
513 * If the variable is an array or object, slashes will be stripped
514 * from the items (or properties) it contains, even if they are arrays
515 * or objects themselves.
517 * @param mixed the variable to remove slashes from
518 * @return mixed
520 function stripslashes_recursive($var) {
521 if (is_object($var)) {
522 $new_var = new object();
523 $properties = get_object_vars($var);
524 foreach($properties as $property => $value) {
525 $new_var->$property = stripslashes_recursive($value);
528 } else if(is_array($var)) {
529 $new_var = array();
530 foreach($var as $property => $value) {
531 $new_var[$property] = stripslashes_recursive($value);
534 } else if(is_string($var)) {
535 $new_var = stripslashes($var);
537 } else {
538 $new_var = $var;
541 return $new_var;
545 * Recursive implementation of addslashes()
547 * This function will allow you to add the slashes from a variable.
548 * If the variable is an array or object, slashes will be added
549 * to the items (or properties) it contains, even if they are arrays
550 * or objects themselves.
552 * @param mixed the variable to add slashes from
553 * @return mixed
555 function addslashes_recursive($var) {
556 if (is_object($var)) {
557 $new_var = new object();
558 $properties = get_object_vars($var);
559 foreach($properties as $property => $value) {
560 $new_var->$property = addslashes_recursive($value);
563 } else if (is_array($var)) {
564 $new_var = array();
565 foreach($var as $property => $value) {
566 $new_var[$property] = addslashes_recursive($value);
569 } else if (is_string($var)) {
570 $new_var = addslashes($var);
572 } else { // nulls, integers, etc.
573 $new_var = $var;
576 return $new_var;
580 * Given some normal text this function will break up any
581 * long words to a given size by inserting the given character
583 * It's multibyte savvy and doesn't change anything inside html tags.
585 * @param string $string the string to be modified
586 * @param int $maxsize maximum length of the string to be returned
587 * @param string $cutchar the string used to represent word breaks
588 * @return string
590 function break_up_long_words($string, $maxsize=20, $cutchar=' ') {
592 /// Loading the textlib singleton instance. We are going to need it.
593 $textlib = textlib_get_instance();
595 /// First of all, save all the tags inside the text to skip them
596 $tags = array();
597 filter_save_tags($string,$tags);
599 /// Process the string adding the cut when necessary
600 $output = '';
601 $length = $textlib->strlen($string);
602 $wordlength = 0;
604 for ($i=0; $i<$length; $i++) {
605 $char = $textlib->substr($string, $i, 1);
606 if ($char == ' ' or $char == "\t" or $char == "\n" or $char == "\r" or $char == "<" or $char == ">") {
607 $wordlength = 0;
608 } else {
609 $wordlength++;
610 if ($wordlength > $maxsize) {
611 $output .= $cutchar;
612 $wordlength = 0;
615 $output .= $char;
618 /// Finally load the tags back again
619 if (!empty($tags)) {
620 $output = str_replace(array_keys($tags), $tags, $output);
623 return $output;
627 * This does a search and replace, ignoring case
628 * This function is only used for versions of PHP older than version 5
629 * which do not have a native version of this function.
630 * Taken from the PHP manual, by bradhuizenga @ softhome.net
632 * @param string $find the string to search for
633 * @param string $replace the string to replace $find with
634 * @param string $string the string to search through
635 * return string
637 if (!function_exists('str_ireplace')) { /// Only exists in PHP 5
638 function str_ireplace($find, $replace, $string) {
640 if (!is_array($find)) {
641 $find = array($find);
644 if(!is_array($replace)) {
645 if (!is_array($find)) {
646 $replace = array($replace);
647 } else {
648 // this will duplicate the string into an array the size of $find
649 $c = count($find);
650 $rString = $replace;
651 unset($replace);
652 for ($i = 0; $i < $c; $i++) {
653 $replace[$i] = $rString;
658 foreach ($find as $fKey => $fItem) {
659 $between = explode(strtolower($fItem),strtolower($string));
660 $pos = 0;
661 foreach($between as $bKey => $bItem) {
662 $between[$bKey] = substr($string,$pos,strlen($bItem));
663 $pos += strlen($bItem) + strlen($fItem);
665 $string = implode($replace[$fKey],$between);
667 return ($string);
672 * Locate the position of a string in another string
674 * This function is only used for versions of PHP older than version 5
675 * which do not have a native version of this function.
676 * Taken from the PHP manual, by dmarsh @ spscc.ctc.edu
678 * @param string $haystack The string to be searched
679 * @param string $needle The string to search for
680 * @param int $offset The position in $haystack where the search should begin.
682 if (!function_exists('stripos')) { /// Only exists in PHP 5
683 function stripos($haystack, $needle, $offset=0) {
685 return strpos(strtoupper($haystack), strtoupper($needle), $offset);
690 * This function will print a button/link/etc. form element
691 * that will work on both Javascript and non-javascript browsers.
692 * Relies on the Javascript function openpopup in javascript.php
694 * All parameters default to null, only $type and $url are mandatory.
696 * $url must be relative to home page eg /mod/survey/stuff.php
697 * @param string $url Web link relative to home page
698 * @param string $name Name to be assigned to the popup window (this is used by
699 * client-side scripts to "talk" to the popup window)
700 * @param string $linkname Text to be displayed as web link
701 * @param int $height Height to assign to popup window
702 * @param int $width Height to assign to popup window
703 * @param string $title Text to be displayed as popup page title
704 * @param string $options List of additional options for popup window
705 * @param string $return If true, return as a string, otherwise print
706 * @param string $id id added to the element
707 * @param string $class class added to the element
708 * @return string
709 * @uses $CFG
711 function element_to_popup_window ($type=null, $url=null, $name=null, $linkname=null,
712 $height=400, $width=500, $title=null,
713 $options=null, $return=false, $id=null, $class=null) {
715 if (is_null($url)) {
716 debugging('You must give the url to display in the popup. URL is missing - can\'t create popup window.', DEBUG_DEVELOPER);
719 global $CFG;
721 if ($options == 'none') { // 'none' is legacy, should be removed in v2.0
722 $options = null;
725 // add some sane default options for popup windows
726 if (!$options) {
727 $options = 'menubar=0,location=0,scrollbars,resizable';
729 if ($width) {
730 $options .= ',width='. $width;
732 if ($height) {
733 $options .= ',height='. $height;
735 if ($id) {
736 $id = ' id="'.$id.'" ';
738 if ($class) {
739 $class = ' class="'.$class.'" ';
741 if ($name) {
742 $_name = $name;
743 if (($name = preg_replace("/\s/", '_', $name)) != $_name) {
744 debugging('The $name of a popup window shouldn\'t contain spaces - string modified. '. $_name .' changed to '. $name, DEBUG_DEVELOPER);
746 } else {
747 $name = 'popup';
750 // get some default string, using the localized version of legacy defaults
751 if (is_null($linkname) || $linkname === '') {
752 $linkname = get_string('clickhere');
754 if (!$title) {
755 $title = get_string('popupwindowname');
758 $fullscreen = 0; // must be passed to openpopup
759 $element = '';
761 switch ($type) {
762 case 'button' :
763 $element = '<input type="button" name="'. $name .'" title="'. $title .'" value="'. $linkname .'" '. $id . $class .
764 "onclick=\"return openpopup('$url', '$name', '$options', $fullscreen);\" />\n";
765 break;
766 case 'link' :
767 // some log url entries contain _SERVER[HTTP_REFERRER] in which case wwwroot is already there.
768 if (!(strpos($url,$CFG->wwwroot) === false)) {
769 $url = substr($url, strlen($CFG->wwwroot));
771 $element = '<a title="'. s(strip_tags($title)) .'" href="'. $CFG->wwwroot . $url .'" '.
772 "$CFG->frametarget onclick=\"this.target='$name'; return openpopup('$url', '$name', '$options', $fullscreen);\">$linkname</a>";
773 break;
774 default :
775 error('Undefined element - can\'t create popup window.');
776 break;
779 if ($return) {
780 return $element;
781 } else {
782 echo $element;
787 * Creates and displays (or returns) a link to a popup window, using element_to_popup_window function.
789 * @return string html code to display a link to a popup window.
790 * @see element_to_popup_window()
792 function link_to_popup_window ($url, $name=null, $linkname=null,
793 $height=400, $width=500, $title=null,
794 $options=null, $return=false) {
796 return element_to_popup_window('link', $url, $name, $linkname, $height, $width, $title, $options, $return, null, null);
800 * Creates and displays (or returns) a buttons to a popup window, using element_to_popup_window function.
802 * @return string html code to display a button to a popup window.
803 * @see element_to_popup_window()
805 function button_to_popup_window ($url, $name=null, $linkname=null,
806 $height=400, $width=500, $title=null, $options=null, $return=false,
807 $id=null, $class=null) {
809 return element_to_popup_window('button', $url, $name, $linkname, $height, $width, $title, $options, $return, $id, $class);
814 * Prints a simple button to close a window
815 * @param string $name name of the window to close
816 * @param boolean $return whether this function should return a string or output it
817 * @return string if $return is true, nothing otherwise
819 function close_window_button($name='closewindow', $return=false) {
820 global $CFG;
822 $output = '';
824 $output .= '<div class="closewindow">' . "\n";
825 $output .= '<form action="#"><div>';
826 $output .= '<input type="button" onclick="self.close();" value="'.get_string($name).'" />';
827 $output .= '</div></form>';
828 $output .= '</div>' . "\n";
830 if ($return) {
831 return $output;
832 } else {
833 echo $output;
838 * Try and close the current window immediately using Javascript
839 * @param int $delay the delay in seconds before closing the window
841 function close_window($delay=0) {
843 <script type="text/javascript">
844 //<![CDATA[
845 function close_this_window() {
846 self.close();
848 setTimeout("close_this_window()", <?php echo $delay * 1000 ?>);
849 //]]>
850 </script>
851 <noscript><center>
852 <?php print_string('pleaseclose') ?>
853 </center></noscript>
854 <?php
855 die;
859 * Given an array of values, output the HTML for a select element with those options.
860 * Normally, you only need to use the first few parameters.
862 * @param array $options The options to offer. An array of the form
863 * $options[{value}] = {text displayed for that option};
864 * @param string $name the name of this form control, as in &lt;select name="..." ...
865 * @param string $selected the option to select initially, default none.
866 * @param string $nothing The label for the 'nothing is selected' option. Defaults to get_string('choose').
867 * Set this to '' if you don't want a 'nothing is selected' option.
868 * @param string $script in not '', then this is added to the &lt;select> element as an onchange handler.
869 * @param string $nothingvalue The value corresponding to the $nothing option. Defaults to 0.
870 * @param boolean $return if false (the default) the the output is printed directly, If true, the
871 * generated HTML is returned as a string.
872 * @param boolean $disabled if true, the select is generated in a disabled state. Default, false.
873 * @param int $tabindex if give, sets the tabindex attribute on the &lt;select> element. Default none.
874 * @param string $id value to use for the id attribute of the &lt;select> element. If none is given,
875 * then a suitable one is constructed.
876 * @param mixed $listbox if false, display as a dropdown menu. If true, display as a list box.
877 * By default, the list box will have a number of rows equal to min(10, count($options)), but if
878 * $listbox is an integer, that number is used for size instead.
879 * @param boolean $multiple if true, enable multiple selections, else only 1 item can be selected. Used
880 * when $listbox display is enabled
881 * @param string $class value to use for the class attribute of the &lt;select> element. If none is given,
882 * then a suitable one is constructed.
884 function choose_from_menu ($options, $name, $selected='', $nothing='choose', $script='',
885 $nothingvalue='0', $return=false, $disabled=false, $tabindex=0,
886 $id='', $listbox=false, $multiple=false, $class='') {
888 if ($nothing == 'choose') {
889 $nothing = get_string('choose') .'...';
892 $attributes = ($script) ? 'onchange="'. $script .'"' : '';
893 if ($disabled) {
894 $attributes .= ' disabled="disabled"';
897 if ($tabindex) {
898 $attributes .= ' tabindex="'.$tabindex.'"';
901 if ($id ==='') {
902 $id = 'menu'.$name;
903 // name may contaion [], which would make an invalid id. e.g. numeric question type editing form, assignment quickgrading
904 $id = str_replace('[', '', $id);
905 $id = str_replace(']', '', $id);
908 if ($class ==='') {
909 $class = 'menu'.$name;
910 // name may contaion [], which would make an invalid class. e.g. numeric question type editing form, assignment quickgrading
911 $class = str_replace('[', '', $class);
912 $class = str_replace(']', '', $class);
914 $class = 'select ' . $class; /// Add 'select' selector always
916 if ($listbox) {
917 if (is_integer($listbox)) {
918 $size = $listbox;
919 } else {
920 $numchoices = count($options);
921 if ($nothing) {
922 $numchoices += 1;
924 $size = min(10, $numchoices);
926 $attributes .= ' size="' . $size . '"';
927 if ($multiple) {
928 $attributes .= ' multiple="multiple"';
932 $output = '<select id="'. $id .'" class="'. $class .'" name="'. $name .'" '. $attributes .'>' . "\n";
933 if ($nothing) {
934 $output .= ' <option value="'. s($nothingvalue) .'"'. "\n";
935 if ($nothingvalue === $selected) {
936 $output .= ' selected="selected"';
938 $output .= '>'. $nothing .'</option>' . "\n";
941 if (!empty($options)) {
942 foreach ($options as $value => $label) {
943 $output .= ' <option value="'. s($value) .'"';
944 if ((string)$value == (string)$selected ||
945 (is_array($selected) && in_array($value, $selected))) {
946 $output .= ' selected="selected"';
948 if ($label === '') {
949 $output .= '>'. $value .'</option>' . "\n";
950 } else {
951 $output .= '>'. $label .'</option>' . "\n";
955 $output .= '</select>' . "\n";
957 if ($return) {
958 return $output;
959 } else {
960 echo $output;
965 * Choose value 0 or 1 from a menu with options 'No' and 'Yes'.
966 * Other options like choose_from_menu.
967 * @param string $name
968 * @param string $selected
969 * @param string $string (defaults to '')
970 * @param boolean $return whether this function should return a string or output it (defaults to false)
971 * @param boolean $disabled (defaults to false)
972 * @param int $tabindex
974 function choose_from_menu_yesno($name, $selected, $script = '',
975 $return = false, $disabled = false, $tabindex = 0) {
976 return choose_from_menu(array(get_string('no'), get_string('yes')), $name,
977 $selected, '', $script, '0', $return, $disabled, $tabindex);
981 * Just like choose_from_menu, but takes a nested array (2 levels) and makes a dropdown menu
982 * including option headings with the first level.
984 function choose_from_menu_nested($options,$name,$selected='',$nothing='choose',$script = '',
985 $nothingvalue=0,$return=false,$disabled=false,$tabindex=0) {
987 if ($nothing == 'choose') {
988 $nothing = get_string('choose') .'...';
991 $attributes = ($script) ? 'onchange="'. $script .'"' : '';
992 if ($disabled) {
993 $attributes .= ' disabled="disabled"';
996 if ($tabindex) {
997 $attributes .= ' tabindex="'.$tabindex.'"';
1000 $output = '<select id="menu'.$name.'" name="'. $name .'" '. $attributes .'>' . "\n";
1001 if ($nothing) {
1002 $output .= ' <option value="'. $nothingvalue .'"'. "\n";
1003 if ($nothingvalue === $selected) {
1004 $output .= ' selected="selected"';
1006 $output .= '>'. $nothing .'</option>' . "\n";
1008 if (!empty($options)) {
1009 foreach ($options as $section => $values) {
1011 $output .= ' <optgroup label="'. s(format_string($section)) .'">'."\n";
1012 foreach ($values as $value => $label) {
1013 $output .= ' <option value="'. format_string($value) .'"';
1014 if ((string)$value == (string)$selected) {
1015 $output .= ' selected="selected"';
1017 if ($label === '') {
1018 $output .= '>'. $value .'</option>' . "\n";
1019 } else {
1020 $output .= '>'. $label .'</option>' . "\n";
1023 $output .= ' </optgroup>'."\n";
1026 $output .= '</select>' . "\n";
1028 if ($return) {
1029 return $output;
1030 } else {
1031 echo $output;
1037 * Given an array of values, creates a group of radio buttons to be part of a form
1039 * @param array $options An array of value-label pairs for the radio group (values as keys)
1040 * @param string $name Name of the radiogroup (unique in the form)
1041 * @param string $checked The value that is already checked
1043 function choose_from_radio ($options, $name, $checked='', $return=false) {
1045 static $idcounter = 0;
1047 if (!$name) {
1048 $name = 'unnamed';
1051 $output = '<span class="radiogroup '.$name."\">\n";
1053 if (!empty($options)) {
1054 $currentradio = 0;
1055 foreach ($options as $value => $label) {
1056 $htmlid = 'auto-rb'.sprintf('%04d', ++$idcounter);
1057 $output .= ' <span class="radioelement '.$name.' rb'.$currentradio."\">";
1058 $output .= '<input name="'.$name.'" id="'.$htmlid.'" type="radio" value="'.$value.'"';
1059 if ($value == $checked) {
1060 $output .= ' checked="checked"';
1062 if ($label === '') {
1063 $output .= ' /> <label for="'.$htmlid.'">'. $value .'</label></span>' . "\n";
1064 } else {
1065 $output .= ' /> <label for="'.$htmlid.'">'. $label .'</label></span>' . "\n";
1067 $currentradio = ($currentradio + 1) % 2;
1071 $output .= '</span>' . "\n";
1073 if ($return) {
1074 return $output;
1075 } else {
1076 echo $output;
1080 /** Display an standard html checkbox with an optional label
1082 * @param string $name The name of the checkbox
1083 * @param string $value The valus that the checkbox will pass when checked
1084 * @param boolean $checked The flag to tell the checkbox initial state
1085 * @param string $label The label to be showed near the checkbox
1086 * @param string $alt The info to be inserted in the alt tag
1088 function print_checkbox ($name, $value, $checked = true, $label = '', $alt = '', $script='',$return=false) {
1090 static $idcounter = 0;
1092 if (!$name) {
1093 $name = 'unnamed';
1096 if ($alt) {
1097 $alt = strip_tags($alt);
1098 } else {
1099 $alt = 'checkbox';
1102 if ($checked) {
1103 $strchecked = ' checked="checked"';
1104 } else {
1105 $strchecked = '';
1108 $htmlid = 'auto-cb'.sprintf('%04d', ++$idcounter);
1109 $output = '<span class="checkbox '.$name."\">";
1110 $output .= '<input name="'.$name.'" id="'.$htmlid.'" type="checkbox" value="'.$value.'" alt="'.$alt.'"'.$strchecked.' '.((!empty($script)) ? ' onclick="'.$script.'" ' : '').' />';
1111 if(!empty($label)) {
1112 $output .= ' <label for="'.$htmlid.'">'.$label.'</label>';
1114 $output .= '</span>'."\n";
1116 if (empty($return)) {
1117 echo $output;
1118 } else {
1119 return $output;
1124 /** Display an standard html text field with an optional label
1126 * @param string $name The name of the text field
1127 * @param string $value The value of the text field
1128 * @param string $label The label to be showed near the text field
1129 * @param string $alt The info to be inserted in the alt tag
1131 function print_textfield ($name, $value, $alt = '',$size=50,$maxlength=0, $return=false) {
1133 static $idcounter = 0;
1135 if (empty($name)) {
1136 $name = 'unnamed';
1139 if (empty($alt)) {
1140 $alt = 'textfield';
1143 if (!empty($maxlength)) {
1144 $maxlength = ' maxlength="'.$maxlength.'" ';
1147 $htmlid = 'auto-tf'.sprintf('%04d', ++$idcounter);
1148 $output = '<span class="textfield '.$name."\">";
1149 $output .= '<input name="'.$name.'" id="'.$htmlid.'" type="text" value="'.$value.'" size="'.$size.'" '.$maxlength.' alt="'.$alt.'" />';
1151 $output .= '</span>'."\n";
1153 if (empty($return)) {
1154 echo $output;
1155 } else {
1156 return $output;
1163 * Implements a complete little popup form
1165 * @uses $CFG
1166 * @param string $common The URL up to the point of the variable that changes
1167 * @param array $options Alist of value-label pairs for the popup list
1168 * @param string $formid Id must be unique on the page (originaly $formname)
1169 * @param string $selected The option that is already selected
1170 * @param string $nothing The label for the "no choice" option
1171 * @param string $help The name of a help page if help is required
1172 * @param string $helptext The name of the label for the help button
1173 * @param boolean $return Indicates whether the function should return the text
1174 * as a string or echo it directly to the page being rendered
1175 * @param string $targetwindow The name of the target page to open the linked page in.
1176 * @param string $selectlabel Text to place in a [label] element - preferred for accessibility.
1177 * @param array $optionsextra TODO, an array?
1178 * @param mixed $gobutton If set, this turns off the JavaScript and uses a 'go'
1179 * button instead (as is always included for JS-disabled users). Set to true
1180 * for a literal 'Go' button, or to a string to change the name of the button.
1181 * @return string If $return is true then the entire form is returned as a string.
1182 * @todo Finish documenting this function<br>
1184 function popup_form($common, $options, $formid, $selected='', $nothing='choose', $help='', $helptext='', $return=false,
1185 $targetwindow='self', $selectlabel='', $optionsextra=NULL, $gobutton=NULL) {
1187 global $CFG;
1188 static $go, $choose; /// Locally cached, in case there's lots on a page
1190 if (empty($options)) {
1191 return '';
1194 if (!isset($go)) {
1195 $go = get_string('go');
1198 if ($nothing == 'choose') {
1199 if (!isset($choose)) {
1200 $choose = get_string('choose');
1202 $nothing = $choose.'...';
1205 // changed reference to document.getElementById('id_abc') instead of document.abc
1206 // MDL-7861
1207 $output = '<form action="'.$CFG->wwwroot.'/course/jumpto.php"'.
1208 ' method="get" '.
1209 $CFG->frametarget.
1210 ' id="'.$formid.'"'.
1211 ' class="popupform">';
1212 if ($help) {
1213 $button = helpbutton($help, $helptext, 'moodle', true, false, '', true);
1214 } else {
1215 $button = '';
1218 if ($selectlabel) {
1219 $selectlabel = '<label for="'.$formid.'_jump">'.$selectlabel.'</label>';
1222 if ($gobutton) {
1223 // Using the no-JavaScript version
1224 $javascript = '';
1225 } else if (check_browser_version('MSIE') || (check_browser_version('Opera') && !check_browser_operating_system("Linux"))) {
1226 //IE and Opera fire the onchange when ever you move into a dropdown list with the keyboard.
1227 //onfocus will call a function inside dropdown.js. It fixes this IE/Opera behavior.
1228 //Note: There is a bug on Opera+Linux with the javascript code (first mouse selection is inactive),
1229 //so we do not fix the Opera behavior on Linux
1230 $javascript = ' onfocus="initSelect(\''.$formid.'\','.$targetwindow.')"';
1231 } else {
1232 //Other browser
1233 $javascript = ' onchange="'.$targetwindow.
1234 '.location=document.getElementById(\''.$formid.
1235 '\').jump.options[document.getElementById(\''.
1236 $formid.'\').jump.selectedIndex].value;"';
1239 $output .= '<div>'.$selectlabel.$button.'<select id="'.$formid.'_jump" name="jump"'.$javascript.'>'."\n";
1241 if ($nothing != '') {
1242 $output .= " <option value=\"javascript:void(0)\">$nothing</option>\n";
1245 $inoptgroup = false;
1247 foreach ($options as $value => $label) {
1249 if ($label == '--') { /// we are ending previous optgroup
1250 /// Check to see if we already have a valid open optgroup
1251 /// XHTML demands that there be at least 1 option within an optgroup
1252 if ($inoptgroup and (count($optgr) > 1) ) {
1253 $output .= implode('', $optgr);
1254 $output .= ' </optgroup>';
1256 $optgr = array();
1257 $inoptgroup = false;
1258 continue;
1259 } else if (substr($label,0,2) == '--') { /// we are starting a new optgroup
1261 /// Check to see if we already have a valid open optgroup
1262 /// XHTML demands that there be at least 1 option within an optgroup
1263 if ($inoptgroup and (count($optgr) > 1) ) {
1264 $output .= implode('', $optgr);
1265 $output .= ' </optgroup>';
1268 unset($optgr);
1269 $optgr = array();
1271 $optgr[] = ' <optgroup label="'. s(format_string(substr($label,2))) .'">'; // Plain labels
1273 $inoptgroup = true; /// everything following will be in an optgroup
1274 continue;
1276 } else {
1277 if (!empty($CFG->usesid) && !isset($_COOKIE[session_name()]))
1279 $url=sid_process_url( $common . $value );
1280 } else
1282 $url=$common . $value;
1284 $optstr = ' <option value="' . $url . '"';
1286 if ($value == $selected) {
1287 $optstr .= ' selected="selected"';
1290 if (!empty($optionsextra[$value])) {
1291 $optstr .= ' '.$optionsextra[$value];
1294 if ($label) {
1295 $optstr .= '>'. $label .'</option>' . "\n";
1296 } else {
1297 $optstr .= '>'. $value .'</option>' . "\n";
1300 if ($inoptgroup) {
1301 $optgr[] = $optstr;
1302 } else {
1303 $output .= $optstr;
1309 /// catch the final group if not closed
1310 if ($inoptgroup and count($optgr) > 1) {
1311 $output .= implode('', $optgr);
1312 $output .= ' </optgroup>';
1315 $output .= '</select>';
1316 $output .= '<input type="hidden" name="sesskey" value="'.sesskey().'" />';
1317 if ($gobutton) {
1318 $output .= '<input type="submit" value="'.
1319 ($gobutton===true ? $go : $gobutton).'" />';
1320 } else {
1321 $output .= '<div id="noscript'.$formid.'" style="display: inline;">';
1322 $output .= '<input type="submit" value="'.$go.'" /></div>';
1323 $output .= '<script type="text/javascript">'.
1324 "\n//<![CDATA[\n".
1325 'document.getElementById("noscript'.$formid.'").style.display = "none";'.
1326 "\n//]]>\n".'</script>';
1328 $output .= '</div></form>';
1330 if ($return) {
1331 return $output;
1332 } else {
1333 echo $output;
1339 * Prints some red text
1341 * @param string $error The text to be displayed in red
1343 function formerr($error) {
1345 if (!empty($error)) {
1346 echo '<span class="error">'. $error .'</span>';
1351 * Validates an email to make sure it makes sense.
1353 * @param string $address The email address to validate.
1354 * @return boolean
1356 function validate_email($address) {
1358 return (ereg('^[-!#$%&\'*+\\/0-9=?A-Z^_`a-z{|}~]+'.
1359 '(\.[-!#$%&\'*+\\/0-9=?A-Z^_`a-z{|}~]+)*'.
1360 '@'.
1361 '[-!#$%&\'*+\\/0-9=?A-Z^_`a-z{|}~]+\.'.
1362 '[-!#$%&\'*+\\./0-9=?A-Z^_`a-z{|}~]+$',
1363 $address));
1367 * Extracts file argument either from file parameter or PATH_INFO
1369 * @param string $scriptname name of the calling script
1370 * @return string file path (only safe characters)
1372 function get_file_argument($scriptname) {
1373 global $_SERVER;
1375 $relativepath = FALSE;
1377 // first try normal parameter (compatible method == no relative links!)
1378 $relativepath = optional_param('file', FALSE, PARAM_PATH);
1379 if ($relativepath === '/testslasharguments') {
1380 echo 'test -1 : Incorrect use - try "file.php/testslasharguments" instead'; //indicate fopen/fread works for health center
1381 die;
1384 // then try extract file from PATH_INFO (slasharguments method)
1385 if (!$relativepath and !empty($_SERVER['PATH_INFO'])) {
1386 $path_info = $_SERVER['PATH_INFO'];
1387 // check that PATH_INFO works == must not contain the script name
1388 if (!strpos($path_info, $scriptname)) {
1389 $relativepath = clean_param(rawurldecode($path_info), PARAM_PATH);
1390 if ($relativepath === '/testslasharguments') {
1391 echo 'test 1 : Slasharguments test passed. Server confguration is compatible with file.php/1/pic.jpg slashargument setting.'; //indicate ok for health center
1392 die;
1397 // now if both fail try the old way
1398 // (for compatibility with misconfigured or older buggy php implementations)
1399 if (!$relativepath) {
1400 $arr = explode($scriptname, me());
1401 if (!empty($arr[1])) {
1402 $path_info = strip_querystring($arr[1]);
1403 $relativepath = clean_param(rawurldecode($path_info), PARAM_PATH);
1404 if ($relativepath === '/testslasharguments') {
1405 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
1406 die;
1411 return $relativepath;
1415 * Searches the current environment variables for some slash arguments
1417 * @param string $file ?
1418 * @todo Finish documenting this function
1420 function get_slash_arguments($file='file.php') {
1422 if (!$string = me()) {
1423 return false;
1426 $pathinfo = explode($file, $string);
1428 if (!empty($pathinfo[1])) {
1429 return addslashes($pathinfo[1]);
1430 } else {
1431 return false;
1436 * Extracts arguments from "/foo/bar/something"
1437 * eg http://mysite.com/script.php/foo/bar/something
1439 * @param string $string ?
1440 * @param int $i ?
1441 * @return array|string
1442 * @todo Finish documenting this function
1444 function parse_slash_arguments($string, $i=0) {
1446 if (detect_munged_arguments($string)) {
1447 return false;
1449 $args = explode('/', $string);
1451 if ($i) { // return just the required argument
1452 return $args[$i];
1454 } else { // return the whole array
1455 array_shift($args); // get rid of the empty first one
1456 return $args;
1461 * Just returns an array of text formats suitable for a popup menu
1463 * @uses FORMAT_MOODLE
1464 * @uses FORMAT_HTML
1465 * @uses FORMAT_PLAIN
1466 * @uses FORMAT_MARKDOWN
1467 * @return array
1469 function format_text_menu() {
1471 return array (FORMAT_MOODLE => get_string('formattext'),
1472 FORMAT_HTML => get_string('formathtml'),
1473 FORMAT_PLAIN => get_string('formatplain'),
1474 FORMAT_MARKDOWN => get_string('formatmarkdown'));
1478 * Given text in a variety of format codings, this function returns
1479 * the text as safe HTML.
1481 * This function should mainly be used for long strings like posts,
1482 * answers, glossary items etc. For short strings @see format_string().
1484 * @uses $CFG
1485 * @uses FORMAT_MOODLE
1486 * @uses FORMAT_HTML
1487 * @uses FORMAT_PLAIN
1488 * @uses FORMAT_WIKI
1489 * @uses FORMAT_MARKDOWN
1490 * @param string $text The text to be formatted. This is raw text originally from user input.
1491 * @param int $format Identifier of the text format to be used
1492 * (FORMAT_MOODLE, FORMAT_HTML, FORMAT_PLAIN, FORMAT_WIKI, FORMAT_MARKDOWN)
1493 * @param array $options ?
1494 * @param int $courseid ?
1495 * @return string
1496 * @todo Finish documenting this function
1498 function format_text($text, $format=FORMAT_MOODLE, $options=NULL, $courseid=NULL) {
1500 global $CFG, $COURSE;
1502 static $croncache = array();
1504 if ($text === '') {
1505 return ''; // no need to do any filters and cleaning
1508 if (!isset($options->trusttext)) {
1509 $options->trusttext = false;
1512 if (!isset($options->noclean)) {
1513 $options->noclean=false;
1515 if (!isset($options->nocache)) {
1516 $options->nocache=false;
1518 if (!isset($options->smiley)) {
1519 $options->smiley=true;
1521 if (!isset($options->filter)) {
1522 $options->filter=true;
1524 if (!isset($options->para)) {
1525 $options->para=true;
1527 if (!isset($options->newlines)) {
1528 $options->newlines=true;
1531 if (empty($courseid)) {
1532 $courseid = $COURSE->id;
1535 if (!empty($CFG->cachetext) and empty($options->nocache)) {
1536 $time = time() - $CFG->cachetext;
1537 $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);
1539 if (defined('FULLME') and FULLME == 'cron') {
1540 if (isset($croncache[$md5key])) {
1541 return $croncache[$md5key];
1545 if ($oldcacheitem = get_record_sql('SELECT * FROM '.$CFG->prefix.'cache_text WHERE md5key = \''.$md5key.'\'', true)) {
1546 if ($oldcacheitem->timemodified >= $time) {
1547 if (defined('FULLME') and FULLME == 'cron') {
1548 if (count($croncache) > 150) {
1549 reset($croncache);
1550 $key = key($croncache);
1551 unset($croncache[$key]);
1553 $croncache[$md5key] = $oldcacheitem->formattedtext;
1555 return $oldcacheitem->formattedtext;
1560 // trusttext overrides the noclean option!
1561 if ($options->trusttext) {
1562 if (trusttext_present($text)) {
1563 $text = trusttext_strip($text);
1564 if (!empty($CFG->enabletrusttext)) {
1565 $options->noclean = true;
1566 } else {
1567 $options->noclean = false;
1569 } else {
1570 $options->noclean = false;
1572 } else if (!debugging('', DEBUG_DEVELOPER)) {
1573 // strip any forgotten trusttext in non-developer mode
1574 // do not forget to disable text cache when debugging trusttext!!
1575 $text = trusttext_strip($text);
1578 $CFG->currenttextiscacheable = true; // Default status - can be changed by any filter
1580 switch ($format) {
1581 case FORMAT_HTML:
1582 if ($options->smiley) {
1583 replace_smilies($text);
1585 if (!$options->noclean) {
1586 $text = clean_text($text, FORMAT_HTML);
1588 if ($options->filter) {
1589 $text = filter_text($text, $courseid);
1591 break;
1593 case FORMAT_PLAIN:
1594 $text = s($text); // cleans dangerous JS
1595 $text = rebuildnolinktag($text);
1596 $text = str_replace(' ', '&nbsp; ', $text);
1597 $text = nl2br($text);
1598 break;
1600 case FORMAT_WIKI:
1601 // this format is deprecated
1602 $text = '<p>NOTICE: Wiki-like formatting has been removed from Moodle. You should not be seeing
1603 this message as all texts should have been converted to Markdown format instead.
1604 Please post a bug report to http://moodle.org/bugs with information about where you
1605 saw this message.</p>'.s($text);
1606 break;
1608 case FORMAT_MARKDOWN:
1609 $text = markdown_to_html($text);
1610 if ($options->smiley) {
1611 replace_smilies($text);
1613 if (!$options->noclean) {
1614 $text = clean_text($text, FORMAT_HTML);
1617 if ($options->filter) {
1618 $text = filter_text($text, $courseid);
1620 break;
1622 default: // FORMAT_MOODLE or anything else
1623 $text = text_to_html($text, $options->smiley, $options->para, $options->newlines);
1624 if (!$options->noclean) {
1625 $text = clean_text($text, FORMAT_HTML);
1628 if ($options->filter) {
1629 $text = filter_text($text, $courseid);
1631 break;
1634 if (empty($options->nocache) and !empty($CFG->cachetext) and $CFG->currenttextiscacheable) {
1635 if (defined('FULLME') and FULLME == 'cron') {
1636 // special static cron cache - no need to store it in db if its not already there
1637 if (count($croncache) > 150) {
1638 reset($croncache);
1639 $key = key($croncache);
1640 unset($croncache[$key]);
1642 $croncache[$md5key] = $text;
1643 return $text;
1646 $newcacheitem = new object();
1647 $newcacheitem->md5key = $md5key;
1648 $newcacheitem->formattedtext = addslashes($text);
1649 $newcacheitem->timemodified = time();
1650 if ($oldcacheitem) { // See bug 4677 for discussion
1651 $newcacheitem->id = $oldcacheitem->id;
1652 @update_record('cache_text', $newcacheitem); // Update existing record in the cache table
1653 // It's unlikely that the cron cache cleaner could have
1654 // deleted this entry in the meantime, as it allows
1655 // some extra time to cover these cases.
1656 } else {
1657 @insert_record('cache_text', $newcacheitem); // Insert a new record in the cache table
1658 // Again, it's possible that another user has caused this
1659 // record to be created already in the time that it took
1660 // to traverse this function. That's OK too, as the
1661 // call above handles duplicate entries, and eventually
1662 // the cron cleaner will delete them.
1666 return $text;
1669 /** Converts the text format from the value to the 'internal'
1670 * name or vice versa. $key can either be the value or the name
1671 * and you get the other back.
1673 * @param mixed int 0-4 or string one of 'moodle','html','plain','markdown'
1674 * @return mixed as above but the other way around!
1676 function text_format_name( $key ) {
1677 $lookup = array();
1678 $lookup[FORMAT_MOODLE] = 'moodle';
1679 $lookup[FORMAT_HTML] = 'html';
1680 $lookup[FORMAT_PLAIN] = 'plain';
1681 $lookup[FORMAT_MARKDOWN] = 'markdown';
1682 $value = "error";
1683 if (!is_numeric($key)) {
1684 $key = strtolower( $key );
1685 $value = array_search( $key, $lookup );
1687 else {
1688 if (isset( $lookup[$key] )) {
1689 $value = $lookup[ $key ];
1692 return $value;
1696 * Resets all data related to filters, called during upgrade or when filter settings change.
1697 * @return void
1699 function reset_text_filters_cache() {
1700 global $CFG;
1702 delete_records('cache_text');
1703 $purifdir = $CFG->dataroot.'/cache/htmlpurifier';
1704 remove_dir($purifdir, true);
1707 /** Given a simple string, this function returns the string
1708 * processed by enabled string filters if $CFG->filterall is enabled
1710 * This function should be used to print short strings (non html) that
1711 * need filter processing e.g. activity titles, post subjects,
1712 * glossary concepts.
1714 * @param string $string The string to be filtered.
1715 * @param boolean $striplinks To strip any link in the result text (Moodle 1.8 default changed from false to true! MDL-8713)
1716 * @param int $courseid Current course as filters can, potentially, use it
1717 * @return string
1719 function format_string ($string, $striplinks=true, $courseid=NULL ) {
1721 global $CFG, $COURSE;
1723 //We'll use a in-memory cache here to speed up repeated strings
1724 static $strcache = false;
1726 if ($strcache === false or count($strcache) > 2000 ) { // this number might need some tuning to limit memory usage in cron
1727 $strcache = array();
1730 //init course id
1731 if (empty($courseid)) {
1732 $courseid = $COURSE->id;
1735 //Calculate md5
1736 $md5 = md5($string.'<+>'.$striplinks.'<+>'.$courseid.'<+>'.current_language());
1738 //Fetch from cache if possible
1739 if (isset($strcache[$md5])) {
1740 return $strcache[$md5];
1743 // First replace all ampersands not followed by html entity code
1744 $string = preg_replace("/\&(?![a-zA-Z0-9#]{1,8};)/", "&amp;", $string);
1746 if (!empty($CFG->filterall)) {
1747 $string = filter_string($string, $courseid);
1750 // If the site requires it, strip ALL tags from this string
1751 if (!empty($CFG->formatstringstriptags)) {
1752 $string = strip_tags($string);
1754 } else {
1755 // Otherwise strip just links if that is required (default)
1756 if ($striplinks) { //strip links in string
1757 $string = preg_replace('/(<a\s[^>]+?>)(.+?)(<\/a>)/is','$2',$string);
1759 $string = clean_text($string);
1762 //Store to cache
1763 $strcache[$md5] = $string;
1765 return $string;
1769 * Given text in a variety of format codings, this function returns
1770 * the text as plain text suitable for plain email.
1772 * @uses FORMAT_MOODLE
1773 * @uses FORMAT_HTML
1774 * @uses FORMAT_PLAIN
1775 * @uses FORMAT_WIKI
1776 * @uses FORMAT_MARKDOWN
1777 * @param string $text The text to be formatted. This is raw text originally from user input.
1778 * @param int $format Identifier of the text format to be used
1779 * (FORMAT_MOODLE, FORMAT_HTML, FORMAT_PLAIN, FORMAT_WIKI, FORMAT_MARKDOWN)
1780 * @return string
1782 function format_text_email($text, $format) {
1784 switch ($format) {
1786 case FORMAT_PLAIN:
1787 return $text;
1788 break;
1790 case FORMAT_WIKI:
1791 $text = wiki_to_html($text);
1792 /// This expression turns links into something nice in a text format. (Russell Jungwirth)
1793 /// From: http://php.net/manual/en/function.eregi-replace.php and simplified
1794 $text = eregi_replace('(<a [^<]*href=["|\']?([^ "\']*)["|\']?[^>]*>([^<]*)</a>)','\\3 [ \\2 ]', $text);
1795 return strtr(strip_tags($text), array_flip(get_html_translation_table(HTML_ENTITIES)));
1796 break;
1798 case FORMAT_HTML:
1799 return html_to_text($text);
1800 break;
1802 case FORMAT_MOODLE:
1803 case FORMAT_MARKDOWN:
1804 default:
1805 $text = eregi_replace('(<a [^<]*href=["|\']?([^ "\']*)["|\']?[^>]*>([^<]*)</a>)','\\3 [ \\2 ]', $text);
1806 return strtr(strip_tags($text), array_flip(get_html_translation_table(HTML_ENTITIES)));
1807 break;
1812 * Given some text in HTML format, this function will pass it
1813 * through any filters that have been defined in $CFG->textfilterx
1814 * The variable defines a filepath to a file containing the
1815 * filter function. The file must contain a variable called
1816 * $textfilter_function which contains the name of the function
1817 * with $courseid and $text parameters
1819 * @param string $text The text to be passed through format filters
1820 * @param int $courseid ?
1821 * @return string
1822 * @todo Finish documenting this function
1824 function filter_text($text, $courseid=NULL) {
1825 global $CFG, $COURSE;
1827 if (empty($courseid)) {
1828 $courseid = $COURSE->id; // (copied from format_text)
1831 if (!empty($CFG->textfilters)) {
1832 require_once($CFG->libdir.'/filterlib.php');
1833 $textfilters = explode(',', $CFG->textfilters);
1834 foreach ($textfilters as $textfilter) {
1835 if (is_readable($CFG->dirroot .'/'. $textfilter .'/filter.php')) {
1836 include_once($CFG->dirroot .'/'. $textfilter .'/filter.php');
1837 $functionname = basename($textfilter).'_filter';
1838 if (function_exists($functionname)) {
1839 $text = $functionname($courseid, $text);
1845 /// <nolink> tags removed for XHTML compatibility
1846 $text = str_replace('<nolink>', '', $text);
1847 $text = str_replace('</nolink>', '', $text);
1849 return $text;
1854 * Given a string (short text) in HTML format, this function will pass it
1855 * through any filters that have been defined in $CFG->stringfilters
1856 * The variable defines a filepath to a file containing the
1857 * filter function. The file must contain a variable called
1858 * $textfilter_function which contains the name of the function
1859 * with $courseid and $text parameters
1861 * @param string $string The text to be passed through format filters
1862 * @param int $courseid The id of a course
1863 * @return string
1865 function filter_string($string, $courseid=NULL) {
1866 global $CFG, $COURSE;
1868 if (empty($CFG->textfilters)) { // All filters are disabled anyway so quit
1869 return $string;
1872 if (empty($courseid)) {
1873 $courseid = $COURSE->id;
1876 require_once($CFG->libdir.'/filterlib.php');
1878 if (isset($CFG->stringfilters)) { // We have a predefined list to use, great!
1879 if (empty($CFG->stringfilters)) { // but it's blank, so finish now
1880 return $string;
1882 $stringfilters = explode(',', $CFG->stringfilters); // ..use the list we have
1884 } else { // Otherwise try to derive a list from textfilters
1885 if (strpos($CFG->textfilters, 'filter/multilang') !== false) { // Multilang is here
1886 $stringfilters = array('filter/multilang'); // Let's use just that
1887 $CFG->stringfilters = 'filter/multilang'; // Save it for next time through
1888 } else {
1889 $CFG->stringfilters = ''; // Save the result and return
1890 return $string;
1895 foreach ($stringfilters as $stringfilter) {
1896 if (is_readable($CFG->dirroot .'/'. $stringfilter .'/filter.php')) {
1897 include_once($CFG->dirroot .'/'. $stringfilter .'/filter.php');
1898 $functionname = basename($stringfilter).'_filter';
1899 if (function_exists($functionname)) {
1900 $string = $functionname($courseid, $string);
1905 /// <nolink> tags removed for XHTML compatibility
1906 $string = str_replace('<nolink>', '', $string);
1907 $string = str_replace('</nolink>', '', $string);
1909 return $string;
1913 * Is the text marked as trusted?
1915 * @param string $text text to be searched for TRUSTTEXT marker
1916 * @return boolean
1918 function trusttext_present($text) {
1919 if (strpos($text, TRUSTTEXT) !== FALSE) {
1920 return true;
1921 } else {
1922 return false;
1927 * This funtion MUST be called before the cleaning or any other
1928 * function that modifies the data! We do not know the origin of trusttext
1929 * in database, if it gets there in tweaked form we must not convert it
1930 * to supported form!!!
1932 * Please be carefull not to use stripslashes on data from database
1933 * or twice stripslashes when processing data recieved from user.
1935 * @param string $text text that may contain TRUSTTEXT marker
1936 * @return text without any TRUSTTEXT marker
1938 function trusttext_strip($text) {
1939 global $CFG;
1941 while (true) { //removing nested TRUSTTEXT
1942 $orig = $text;
1943 $text = str_replace(TRUSTTEXT, '', $text);
1944 if (strcmp($orig, $text) === 0) {
1945 return $text;
1951 * Mark text as trusted, such text may contain any HTML tags because the
1952 * normal text cleaning will be bypassed.
1953 * Please make sure that the text comes from trusted user before storing
1954 * it into database!
1956 function trusttext_mark($text) {
1957 global $CFG;
1958 if (!empty($CFG->enabletrusttext) and (strpos($text, TRUSTTEXT) === FALSE)) {
1959 return TRUSTTEXT.$text;
1960 } else {
1961 return $text;
1964 function trusttext_after_edit(&$text, $context) {
1965 if (has_capability('moodle/site:trustcontent', $context)) {
1966 $text = trusttext_strip($text);
1967 $text = trusttext_mark($text);
1968 } else {
1969 $text = trusttext_strip($text);
1973 function trusttext_prepare_edit(&$text, &$format, $usehtmleditor, $context) {
1974 global $CFG;
1976 $options = new object();
1977 $options->smiley = false;
1978 $options->filter = false;
1979 if (!empty($CFG->enabletrusttext)
1980 and has_capability('moodle/site:trustcontent', $context)
1981 and trusttext_present($text)) {
1982 $options->noclean = true;
1983 } else {
1984 $options->noclean = false;
1986 $text = trusttext_strip($text);
1987 if ($usehtmleditor) {
1988 $text = format_text($text, $format, $options);
1989 $format = FORMAT_HTML;
1990 } else if (!$options->noclean){
1991 $text = clean_text($text, $format);
1996 * Given raw text (eg typed in by a user), this function cleans it up
1997 * and removes any nasty tags that could mess up Moodle pages.
1999 * @uses FORMAT_MOODLE
2000 * @uses FORMAT_PLAIN
2001 * @uses ALLOWED_TAGS
2002 * @param string $text The text to be cleaned
2003 * @param int $format Identifier of the text format to be used
2004 * (FORMAT_MOODLE, FORMAT_HTML, FORMAT_PLAIN, FORMAT_WIKI, FORMAT_MARKDOWN)
2005 * @return string The cleaned up text
2007 function clean_text($text, $format=FORMAT_MOODLE) {
2009 global $ALLOWED_TAGS, $CFG;
2011 if (empty($text) or is_numeric($text)) {
2012 return (string)$text;
2015 switch ($format) {
2016 case FORMAT_PLAIN:
2017 case FORMAT_MARKDOWN:
2018 return $text;
2020 default:
2022 if (!empty($CFG->enablehtmlpurifier)) {
2023 $text = purify_html($text);
2024 } else {
2025 /// Fix non standard entity notations
2026 $text = preg_replace('/(&#[0-9]+)(;?)/', "\\1;", $text);
2027 $text = preg_replace('/(&#x[0-9a-fA-F]+)(;?)/', "\\1;", $text);
2029 /// Remove tags that are not allowed
2030 $text = strip_tags($text, $ALLOWED_TAGS);
2032 /// Clean up embedded scripts and , using kses
2033 $text = cleanAttributes($text);
2035 /// Again remove tags that are not allowed
2036 $text = strip_tags($text, $ALLOWED_TAGS);
2040 /// Remove potential script events - some extra protection for undiscovered bugs in our code
2041 $text = eregi_replace("([^a-z])language([[:space:]]*)=", "\\1Xlanguage=", $text);
2042 $text = eregi_replace("([^a-z])on([a-z]+)([[:space:]]*)=", "\\1Xon\\2=", $text);
2044 return $text;
2049 * KSES replacement cleaning function - uses HTML Purifier.
2051 function purify_html($text) {
2052 global $CFG;
2054 // this can not be done only once because we sometimes need to reset the cache
2055 $cachedir = $CFG->dataroot.'/cache/htmlpurifier/';
2056 $status = check_dir_exists($cachedir, true, true);
2058 static $purifier = false;
2059 if ($purifier === false) {
2060 require_once $CFG->libdir.'/htmlpurifier/HTMLPurifier.auto.php';
2061 $config = HTMLPurifier_Config::createDefault();
2062 $config->set('Core', 'AcceptFullDocuments', false);
2063 $config->set('Core', 'Encoding', 'UTF-8');
2064 $config->set('HTML', 'Doctype', 'XHTML 1.0 Transitional');
2065 $config->set('Cache', 'SerializerPath', $cachedir);
2066 $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));
2067 $config->set('Attr', 'AllowedFrameTargets', array('_blank'));
2068 $purifier = new HTMLPurifier($config);
2070 return $purifier->purify($text);
2074 * This function takes a string and examines it for HTML tags.
2075 * If tags are detected it passes the string to a helper function {@link cleanAttributes2()}
2076 * which checks for attributes and filters them for malicious content
2077 * 17/08/2004 :: Eamon DOT Costello AT dcu DOT ie
2079 * @param string $str The string to be examined for html tags
2080 * @return string
2082 function cleanAttributes($str){
2083 $result = preg_replace_callback(
2084 '%(<[^>]*(>|$)|>)%m', #search for html tags
2085 "cleanAttributes2",
2086 $str
2088 return $result;
2092 * This function takes a string with an html tag and strips out any unallowed
2093 * protocols e.g. javascript:
2094 * It calls ancillary functions in kses which are prefixed by kses
2095 * 17/08/2004 :: Eamon DOT Costello AT dcu DOT ie
2097 * @param array $htmlArray An array from {@link cleanAttributes()}, containing in its 1st
2098 * element the html to be cleared
2099 * @return string
2101 function cleanAttributes2($htmlArray){
2103 global $CFG, $ALLOWED_PROTOCOLS;
2104 require_once($CFG->libdir .'/kses.php');
2106 $htmlTag = $htmlArray[1];
2107 if (substr($htmlTag, 0, 1) != '<') {
2108 return '&gt;'; //a single character ">" detected
2110 if (!preg_match('%^<\s*(/\s*)?([a-zA-Z0-9]+)([^>]*)>?$%', $htmlTag, $matches)) {
2111 return ''; // It's seriously malformed
2113 $slash = trim($matches[1]); //trailing xhtml slash
2114 $elem = $matches[2]; //the element name
2115 $attrlist = $matches[3]; // the list of attributes as a string
2117 $attrArray = kses_hair($attrlist, $ALLOWED_PROTOCOLS);
2119 $attStr = '';
2120 foreach ($attrArray as $arreach) {
2121 $arreach['name'] = strtolower($arreach['name']);
2122 if ($arreach['name'] == 'style') {
2123 $value = $arreach['value'];
2124 while (true) {
2125 $prevvalue = $value;
2126 $value = kses_no_null($value);
2127 $value = preg_replace("/\/\*.*\*\//Us", '', $value);
2128 $value = kses_decode_entities($value);
2129 $value = preg_replace('/(&#[0-9]+)(;?)/', "\\1;", $value);
2130 $value = preg_replace('/(&#x[0-9a-fA-F]+)(;?)/', "\\1;", $value);
2131 if ($value === $prevvalue) {
2132 $arreach['value'] = $value;
2133 break;
2136 $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']);
2137 $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']);
2138 $arreach['value'] = preg_replace("/b\s*i\s*n\s*d\s*i\s*n\s*g/i", "Xbinding", $arreach['value']);
2139 } else if ($arreach['name'] == 'href') {
2140 //Adobe Acrobat Reader XSS protection
2141 $arreach['value'] = preg_replace('/(\.(pdf|fdf|xfdf|xdp|xfd)[^#]*)#.*$/i', '$1', $arreach['value']);
2143 $attStr .= ' '.$arreach['name'].'="'.$arreach['value'].'"';
2146 $xhtml_slash = '';
2147 if (preg_match('%/\s*$%', $attrlist)) {
2148 $xhtml_slash = ' /';
2150 return '<'. $slash . $elem . $attStr . $xhtml_slash .'>';
2154 * Replaces all known smileys in the text with image equivalents
2156 * @uses $CFG
2157 * @param string $text Passed by reference. The string to search for smily strings.
2158 * @return string
2160 function replace_smilies(&$text) {
2162 global $CFG;
2164 if (empty($CFG->emoticons)) { /// No emoticons defined, nothing to process here
2165 return;
2168 $lang = current_language();
2169 $emoticonstring = $CFG->emoticons;
2170 static $e = array();
2171 static $img = array();
2172 static $emoticons = null;
2174 if (is_null($emoticons)) {
2175 $emoticons = array();
2176 if ($emoticonstring) {
2177 $items = explode('{;}', $CFG->emoticons);
2178 foreach ($items as $item) {
2179 $item = explode('{:}', $item);
2180 $emoticons[$item[0]] = $item[1];
2186 if (empty($img[$lang])) { /// After the first time this is not run again
2187 $e[$lang] = array();
2188 $img[$lang] = array();
2189 foreach ($emoticons as $emoticon => $image){
2190 $alttext = get_string($image, 'pix');
2191 $alttext = preg_replace('/^\[\[(.*)\]\]$/', '$1', $alttext); /// Clean alttext in case there isn't lang string for it.
2192 $e[$lang][] = $emoticon;
2193 $img[$lang][] = '<img alt="'. $alttext .'" width="15" height="15" src="'. $CFG->pixpath .'/s/'. $image .'.gif" />';
2197 // Exclude from transformations all the code inside <script> tags
2198 // Needed to solve Bug 1185. Thanks to jouse 2001 detecting it. :-)
2199 // Based on code from glossary fiter by Williams Castillo.
2200 // - Eloy
2202 // Detect all the <script> zones to take out
2203 $excludes = array();
2204 preg_match_all('/<script language(.+?)<\/script>/is',$text,$list_of_excludes);
2206 // Take out all the <script> zones from text
2207 foreach (array_unique($list_of_excludes[0]) as $key=>$value) {
2208 $excludes['<+'.$key.'+>'] = $value;
2210 if ($excludes) {
2211 $text = str_replace($excludes,array_keys($excludes),$text);
2214 /// this is the meat of the code - this is run every time
2215 $text = str_replace($e[$lang], $img[$lang], $text);
2217 // Recover all the <script> zones to text
2218 if ($excludes) {
2219 $text = str_replace(array_keys($excludes),$excludes,$text);
2224 * Given plain text, makes it into HTML as nicely as possible.
2225 * May contain HTML tags already
2227 * @uses $CFG
2228 * @param string $text The string to convert.
2229 * @param boolean $smiley Convert any smiley characters to smiley images?
2230 * @param boolean $para If true then the returned string will be wrapped in paragraph tags
2231 * @param boolean $newlines If true then lines newline breaks will be converted to HTML newline breaks.
2232 * @return string
2235 function text_to_html($text, $smiley=true, $para=true, $newlines=true) {
2238 global $CFG;
2240 /// Remove any whitespace that may be between HTML tags
2241 $text = eregi_replace(">([[:space:]]+)<", "><", $text);
2243 /// Remove any returns that precede or follow HTML tags
2244 $text = eregi_replace("([\n\r])<", " <", $text);
2245 $text = eregi_replace(">([\n\r])", "> ", $text);
2247 convert_urls_into_links($text);
2249 /// Make returns into HTML newlines.
2250 if ($newlines) {
2251 $text = nl2br($text);
2254 /// Turn smileys into images.
2255 if ($smiley) {
2256 replace_smilies($text);
2259 /// Wrap the whole thing in a paragraph tag if required
2260 if ($para) {
2261 return '<p>'.$text.'</p>';
2262 } else {
2263 return $text;
2268 * Given Markdown formatted text, make it into XHTML using external function
2270 * @uses $CFG
2271 * @param string $text The markdown formatted text to be converted.
2272 * @return string Converted text
2274 function markdown_to_html($text) {
2275 global $CFG;
2277 require_once($CFG->libdir .'/markdown.php');
2279 return Markdown($text);
2283 * Given HTML text, make it into plain text using external function
2285 * @uses $CFG
2286 * @param string $html The text to be converted.
2287 * @return string
2289 function html_to_text($html) {
2291 global $CFG;
2293 require_once($CFG->libdir .'/html2text.php');
2295 $h2t = new html2text($html);
2296 $result = $h2t->get_text();
2298 return $result;
2302 * Given some text this function converts any URLs it finds into HTML links
2304 * @param string $text Passed in by reference. The string to be searched for urls.
2306 function convert_urls_into_links(&$text) {
2307 /// Make lone URLs into links. eg http://moodle.com/
2308 $text = eregi_replace("([[:space:]]|^|\(|\[)([[:alnum:]]+)://([^[:space:]]*)([[:alnum:]#?/&=])",
2309 "\\1<a href=\"\\2://\\3\\4\" target=\"_blank\">\\2://\\3\\4</a>", $text);
2311 /// eg www.moodle.com
2312 $text = eregi_replace("([[:space:]]|^|\(|\[)www\.([^[:space:]]*)([[:alnum:]#?/&=])",
2313 "\\1<a href=\"http://www.\\2\\3\" target=\"_blank\">www.\\2\\3</a>", $text);
2317 * This function will highlight search words in a given string
2318 * It cares about HTML and will not ruin links. It's best to use
2319 * this function after performing any conversions to HTML.
2321 * @param string $needle The search string. Syntax like "word1 +word2 -word3" is dealt with correctly.
2322 * @param string $haystack The string (HTML) within which to highlight the search terms.
2323 * @param boolean $matchcase whether to do case-sensitive. Default case-insensitive.
2324 * @param string $prefix the string to put before each search term found.
2325 * @param string $suffix the string to put after each search term found.
2326 * @return string The highlighted HTML.
2328 function highlight($needle, $haystack, $matchcase = false,
2329 $prefix = '<span class="highlight">', $suffix = '</span>') {
2331 /// Quick bail-out in trivial cases.
2332 if (empty($needle) or empty($haystack)) {
2333 return $haystack;
2336 /// Break up the search term into words, discard any -words and build a regexp.
2337 $words = preg_split('/ +/', trim($needle));
2338 foreach ($words as $index => $word) {
2339 if (strpos($word, '-') === 0) {
2340 unset($words[$index]);
2341 } else if (strpos($word, '+') === 0) {
2342 $words[$index] = '\b' . preg_quote(ltrim($word, '+'), '/') . '\b'; // Match only as a complete word.
2343 } else {
2344 $words[$index] = preg_quote($word, '/');
2347 $regexp = '/(' . implode('|', $words) . ')/u'; // u is do UTF-8 matching.
2348 if (!$matchcase) {
2349 $regexp .= 'i';
2352 /// Another chance to bail-out if $search was only -words
2353 if (empty($words)) {
2354 return $haystack;
2357 /// Find all the HTML tags in the input, and store them in a placeholders array.
2358 $placeholders = array();
2359 $matches = array();
2360 preg_match_all('/<[^>]*>/', $haystack, $matches);
2361 foreach (array_unique($matches[0]) as $key => $htmltag) {
2362 $placeholders['<|' . $key . '|>'] = $htmltag;
2365 /// In $hastack, replace each HTML tag with the corresponding placeholder.
2366 $haystack = str_replace($placeholders, array_keys($placeholders), $haystack);
2368 /// In the resulting string, Do the highlighting.
2369 $haystack = preg_replace($regexp, $prefix . '$1' . $suffix, $haystack);
2371 /// Turn the placeholders back into HTML tags.
2372 $haystack = str_replace(array_keys($placeholders), $placeholders, $haystack);
2374 return $haystack;
2378 * This function will highlight instances of $needle in $haystack
2379 * It's faster that the above function and doesn't care about
2380 * HTML or anything.
2382 * @param string $needle The string to search for
2383 * @param string $haystack The string to search for $needle in
2384 * @return string
2386 function highlightfast($needle, $haystack) {
2388 if (empty($needle) or empty($haystack)) {
2389 return $haystack;
2392 $parts = explode(moodle_strtolower($needle), moodle_strtolower($haystack));
2394 if (count($parts) === 1) {
2395 return $haystack;
2398 $pos = 0;
2400 foreach ($parts as $key => $part) {
2401 $parts[$key] = substr($haystack, $pos, strlen($part));
2402 $pos += strlen($part);
2404 $parts[$key] .= '<span class="highlight">'.substr($haystack, $pos, strlen($needle)).'</span>';
2405 $pos += strlen($needle);
2408 return str_replace('<span class="highlight"></span>', '', join('', $parts));
2412 * Return a string containing 'lang', xml:lang and optionally 'dir' HTML attributes.
2413 * Internationalisation, for print_header and backup/restorelib.
2414 * @param $dir Default false.
2415 * @return string Attributes.
2417 function get_html_lang($dir = false) {
2418 $direction = '';
2419 if ($dir) {
2420 if (get_string('thisdirection') == 'rtl') {
2421 $direction = ' dir="rtl"';
2422 } else {
2423 $direction = ' dir="ltr"';
2426 //Accessibility: added the 'lang' attribute to $direction, used in theme <html> tag.
2427 $language = str_replace('_', '-', str_replace('_utf8', '', current_language()));
2428 @header('Content-Language: '.$language);
2429 return ($direction.' lang="'.$language.'" xml:lang="'.$language.'"');
2433 * Return the markup for the destination of the 'Skip to main content' links.
2434 * Accessibility improvement for keyboard-only users.
2435 * Used in course formats, /index.php and /course/index.php
2436 * @return string HTML element.
2438 function skip_main_destination() {
2439 return '<span id="maincontent"></span>';
2443 /// STANDARD WEB PAGE PARTS ///////////////////////////////////////////////////
2446 * Print a standard header
2448 * @uses $USER
2449 * @uses $CFG
2450 * @uses $SESSION
2451 * @param string $title Appears at the top of the window
2452 * @param string $heading Appears at the top of the page
2453 * @param array $navigation Array of $navlinks arrays (keys: name, link, type) for use as breadcrumbs links
2454 * @param string $focus Indicates form element to get cursor focus on load eg inputform.password
2455 * @param string $meta Meta tags to be added to the header
2456 * @param boolean $cache Should this page be cacheable?
2457 * @param string $button HTML code for a button (usually for module editing)
2458 * @param string $menu HTML code for a popup menu
2459 * @param boolean $usexml use XML for this page
2460 * @param string $bodytags This text will be included verbatim in the <body> tag (useful for onload() etc)
2461 * @param bool $return If true, return the visible elements of the header instead of echoing them.
2463 function print_header ($title='', $heading='', $navigation='', $focus='',
2464 $meta='', $cache=true, $button='&nbsp;', $menu='',
2465 $usexml=false, $bodytags='', $return=false) {
2467 global $USER, $CFG, $THEME, $SESSION, $ME, $SITE, $COURSE;
2469 if (gettype($navigation) == 'string' && strlen($navigation) != 0 && $navigation != 'home') {
2470 debugging("print_header() was sent a string as 3rd ($navigation) parameter. "
2471 . "This is deprecated in favour of an array built by build_navigation(). Please upgrade your code.", DEBUG_DEVELOPER);
2474 $heading = format_string($heading); // Fix for MDL-8582
2476 /// This makes sure that the header is never repeated twice on a page
2477 if (defined('HEADER_PRINTED')) {
2478 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().');
2479 return;
2481 define('HEADER_PRINTED', 'true');
2484 /// Add the required stylesheets
2485 $stylesheetshtml = '';
2486 foreach ($CFG->stylesheets as $stylesheet) {
2487 $stylesheetshtml .= '<link rel="stylesheet" type="text/css" href="'.$stylesheet.'" />'."\n";
2489 $meta = $stylesheetshtml.$meta;
2492 /// Add the meta page from the themes if any were requested
2494 $metapage = '';
2496 if (!isset($THEME->standardmetainclude) || $THEME->standardmetainclude) {
2497 ob_start();
2498 include_once($CFG->dirroot.'/theme/standard/meta.php');
2499 $metapage .= ob_get_contents();
2500 ob_end_clean();
2503 if ($THEME->parent && (!isset($THEME->parentmetainclude) || $THEME->parentmetainclude)) {
2504 if (file_exists($CFG->dirroot.'/theme/'.$THEME->parent.'/meta.php')) {
2505 ob_start();
2506 include_once($CFG->dirroot.'/theme/'.$THEME->parent.'/meta.php');
2507 $metapage .= ob_get_contents();
2508 ob_end_clean();
2512 if (!isset($THEME->metainclude) || $THEME->metainclude) {
2513 if (file_exists($CFG->dirroot.'/theme/'.current_theme().'/meta.php')) {
2514 ob_start();
2515 include_once($CFG->dirroot.'/theme/'.current_theme().'/meta.php');
2516 $metapage .= ob_get_contents();
2517 ob_end_clean();
2521 $meta = $meta."\n".$metapage;
2523 $meta .= "\n".require_js('',1);
2525 /// Set up some navigation variables
2527 if (is_newnav($navigation)){
2528 $home = false;
2529 } else {
2530 if ($navigation == 'home') {
2531 $home = true;
2532 $navigation = '';
2533 } else {
2534 $home = false;
2538 /// This is another ugly hack to make navigation elements available to print_footer later
2539 $THEME->title = $title;
2540 $THEME->heading = $heading;
2541 $THEME->navigation = $navigation;
2542 $THEME->button = $button;
2543 $THEME->menu = $menu;
2544 $navmenulist = isset($THEME->navmenulist) ? $THEME->navmenulist : '';
2546 if ($button == '') {
2547 $button = '&nbsp;';
2550 if (file_exists($CFG->dataroot.'/'.SITEID.'/maintenance.html')) {
2551 $button = '<a href="'.$CFG->wwwroot.'/'.$CFG->admin.'/maintenance.php">'.get_string('maintenancemode', 'admin').'</a> '.$button;
2552 if(!empty($title)) {
2553 $title .= ' - ';
2555 $title .= get_string('maintenancemode', 'admin');
2558 if (!$menu and $navigation) {
2559 if (empty($CFG->loginhttps)) {
2560 $wwwroot = $CFG->wwwroot;
2561 } else {
2563 $wwwroot = str_replace('http:','https:',$CFG->wwwroot);
2565 $menu = user_login_string($COURSE);
2568 if (isset($SESSION->justloggedin)) {
2569 unset($SESSION->justloggedin);
2570 if (!empty($CFG->displayloginfailures)) {
2571 if (!empty($USER->username) and $USER->username != 'guest') {
2572 if ($count = count_login_failures($CFG->displayloginfailures, $USER->username, $USER->lastlogin)) {
2573 $menu .= '&nbsp;<font size="1">';
2574 if (empty($count->accounts)) {
2575 $menu .= get_string('failedloginattempts', '', $count);
2576 } else {
2577 $menu .= get_string('failedloginattemptsall', '', $count);
2579 if (has_capability('coursereport/log:view', get_context_instance(CONTEXT_SYSTEM))) {
2580 $menu .= ' (<a href="'.$CFG->wwwroot.'/course/report/log/index.php'.
2581 '?chooselog=1&amp;id=1&amp;modid=site_errors">'.get_string('logs').'</a>)';
2583 $menu .= '</font>';
2590 $meta = '<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />' .
2591 "\n" . $meta . "\n";
2592 if (!$usexml) {
2593 @header('Content-Type: text/html; charset=utf-8');
2595 @header('Content-Script-Type: text/javascript');
2596 @header('Content-Style-Type: text/css');
2598 //Accessibility: added the 'lang' attribute to $direction, used in theme <html> tag.
2599 $direction = get_html_lang($dir=true);
2601 if ($cache) { // Allow caching on "back" (but not on normal clicks)
2602 @header('Cache-Control: private, pre-check=0, post-check=0, max-age=0');
2603 @header('Pragma: no-cache');
2604 @header('Expires: ');
2605 } else { // Do everything we can to always prevent clients and proxies caching
2606 @header('Cache-Control: no-store, no-cache, must-revalidate');
2607 @header('Cache-Control: post-check=0, pre-check=0', false);
2608 @header('Pragma: no-cache');
2609 @header('Expires: Mon, 20 Aug 1969 09:23:00 GMT');
2610 @header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
2612 $meta .= "\n<meta http-equiv=\"pragma\" content=\"no-cache\" />";
2613 $meta .= "\n<meta http-equiv=\"expires\" content=\"0\" />";
2615 @header('Accept-Ranges: none');
2617 $currentlanguage = current_language();
2619 if (empty($usexml)) {
2620 $direction = ' xmlns="http://www.w3.org/1999/xhtml"'. $direction; // See debug_header
2621 } else {
2622 $mathplayer = preg_match("/MathPlayer/i", $_SERVER['HTTP_USER_AGENT']);
2623 if(!$mathplayer) {
2624 header('Content-Type: application/xhtml+xml');
2626 echo '<?xml version="1.0" ?>'."\n";
2627 if (!empty($CFG->xml_stylesheets)) {
2628 $stylesheets = explode(';', $CFG->xml_stylesheets);
2629 foreach ($stylesheets as $stylesheet) {
2630 echo '<?xml-stylesheet type="text/xsl" href="'. $CFG->wwwroot .'/'. $stylesheet .'" ?>' . "\n";
2633 echo '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1';
2634 if (!empty($CFG->xml_doctype_extra)) {
2635 echo ' plus '. $CFG->xml_doctype_extra;
2637 echo '//' . strtoupper($currentlanguage) . '" "'. $CFG->xml_dtd .'">'."\n";
2638 $direction = " xmlns=\"http://www.w3.org/1999/xhtml\"
2639 xmlns:math=\"http://www.w3.org/1998/Math/MathML\"
2640 xmlns:xlink=\"http://www.w3.org/1999/xlink\"
2641 $direction";
2642 if($mathplayer) {
2643 $meta .= '<object id="mathplayer" classid="clsid:32F66A20-7614-11D4-BD11-00104BD3F987">' . "\n";
2644 $meta .= '<!--comment required to prevent this becoming an empty tag-->'."\n";
2645 $meta .= '</object>'."\n";
2646 $meta .= '<?import namespace="math" implementation="#mathplayer" ?>' . "\n";
2650 // Clean up the title
2652 $title = format_string($title); // fix for MDL-8582
2653 $title = str_replace('"', '&quot;', $title);
2655 // Create class and id for this page
2657 page_id_and_class($pageid, $pageclass);
2659 $pageclass .= ' course-'.$COURSE->id;
2661 if (!isloggedin()) {
2662 $pageclass .= ' notloggedin';
2665 if (!empty($USER->editing)) {
2666 $pageclass .= ' editing';
2669 if (!empty($CFG->blocksdrag)) {
2670 $pageclass .= ' drag';
2673 $pageclass .= ' dir-'.get_string('thisdirection');
2675 $pageclass .= ' lang-'.$currentlanguage;
2677 $bodytags .= ' class="'.$pageclass.'" id="'.$pageid.'"';
2679 require_once($CFG->libdir .'/editor/htmlEditor.class.php');
2680 $htmlEditorObject = new htmlEditor();
2681 $htmlEditor = $htmlEditorObject->configure(NULL, $COURSE->id);
2683 ob_start();
2684 include($CFG->header);
2685 $output = ob_get_contents();
2686 ob_end_clean();
2688 // container debugging info
2689 $THEME->open_header_containers = open_containers();
2691 // Skip to main content, see skip_main_destination().
2692 if ($pageid=='course-view' or $pageid=='site-index' or $pageid=='course-index') {
2693 $skiplink = '<a class="skip" href="#maincontent">'.get_string('tocontent', 'access').'</a>';
2694 if (! preg_match('/(.*<div[^>]+id="page"[^>]*>)(.*)/s', $output, $matches)) {
2695 preg_match('/(.*<body.*?>)(.*)/s', $output, $matches);
2697 $output = $matches[1]."\n". $skiplink .$matches[2];
2700 $output = force_strict_header($output);
2702 if (!empty($CFG->messaging)) {
2703 $output .= message_popup_window();
2706 // Add in any extra JavaScript libraries that occurred during the header
2707 $output .= require_js('', 2);
2709 if ($return) {
2710 return $output;
2711 } else {
2712 echo $output;
2717 * Used to include JavaScript libraries.
2719 * When the $lib parameter is given, the function will ensure that the
2720 * named library is loaded onto the page - either in the HTML <head>,
2721 * just after the header, or at an arbitrary later point in the page,
2722 * depending on where this function is called.
2724 * Libraries will not be included more than once, so this works like
2725 * require_once in PHP.
2727 * There are two special-case calls to this function which are both used only
2728 * by weblib print_header:
2729 * $extracthtml = 1: this is used before printing the header.
2730 * It returns the script tag code that should go inside the <head>.
2731 * $extracthtml = 2: this is used after printing the header and handles any
2732 * require_js calls that occurred within the header itself.
2734 * @param mixed $lib - string or array of strings
2735 * string(s) should be the shortname for the library or the
2736 * full path to the library file.
2737 * @param int $extracthtml Do not set this parameter usually (leave 0), only
2738 * weblib should set this to 1 or 2 in print_header function.
2739 * @return mixed No return value, except when using $extracthtml it returns the html code.
2741 function require_js($lib,$extracthtml=0) {
2742 global $CFG;
2743 static $loadlibs = array();
2745 static $state = REQUIREJS_BEFOREHEADER;
2746 static $latecode = '';
2748 if (!empty($lib)) {
2749 // Add the lib to the list of libs to be loaded, if it isn't already
2750 // in the list.
2751 if (is_array($lib)) {
2752 foreach($lib as $singlelib) {
2753 require_js($singlelib);
2755 } else {
2756 $libpath = ajax_get_lib($lib);
2757 if (array_search($libpath, $loadlibs) === false) {
2758 $loadlibs[] = $libpath;
2760 // For state other than 0 we need to take action as well as just
2761 // adding it to loadlibs
2762 if($state != REQUIREJS_BEFOREHEADER) {
2763 // Get the script statement for this library
2764 $scriptstatement=get_require_js_code(array($libpath));
2766 if($state == REQUIREJS_AFTERHEADER) {
2767 // After the header, print it immediately
2768 print $scriptstatement;
2769 } else {
2770 // Haven't finished the header yet. Add it after the
2771 // header
2772 $latecode .= $scriptstatement;
2777 } else if($extracthtml==1) {
2778 if($state !== REQUIREJS_BEFOREHEADER) {
2779 debugging('Incorrect state in require_js (expected BEFOREHEADER): be careful not to call with empty $lib (except in print_header)');
2780 } else {
2781 $state = REQUIREJS_INHEADER;
2784 return get_require_js_code($loadlibs);
2785 } else if($extracthtml==2) {
2786 if($state !== REQUIREJS_INHEADER) {
2787 debugging('Incorrect state in require_js (expected INHEADER): be careful not to call with empty $lib (except in print_header)');
2788 return '';
2789 } else {
2790 $state = REQUIREJS_AFTERHEADER;
2791 return $latecode;
2793 } else {
2794 debugging('Unexpected value for $extracthtml');
2799 * Should not be called directly - use require_js. This function obtains the code
2800 * (script tags) needed to include JavaScript libraries.
2801 * @param array $loadlibs Array of library files to include
2802 * @return string HTML code to include them
2804 function get_require_js_code($loadlibs) {
2805 global $CFG;
2806 // Return the html needed to load the JavaScript files defined in
2807 // our list of libs to be loaded.
2808 $output = '';
2809 foreach ($loadlibs as $loadlib) {
2810 $output .= '<script type="text/javascript" ';
2811 $output .= " src=\"$loadlib\"></script>\n";
2812 if ($loadlib == $CFG->wwwroot.'/lib/yui/logger/logger-min.js') {
2813 // Special case, we need the CSS too.
2814 $output .= '<link type="text/css" rel="stylesheet" ';
2815 $output .= " href=\"{$CFG->wwwroot}/lib/yui/logger/assets/logger.css\" />\n";
2818 return $output;
2823 * Debugging aid: serve page as 'application/xhtml+xml' where possible,
2824 * and substitute the XHTML strict document type.
2825 * Note, requires the 'xmlns' fix in function print_header above.
2826 * See: http://tracker.moodle.org/browse/MDL-7883
2827 * TODO:
2829 function force_strict_header($output) {
2830 global $CFG;
2831 $strict = '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">';
2832 $xsl = '/lib/xhtml.xsl';
2834 if (!headers_sent() && !empty($CFG->xmlstrictheaders)) { // With xml strict headers, the browser will barf
2835 $ctype = 'Content-Type: ';
2836 $prolog= "<?xml version='1.0' encoding='utf-8'?>\n";
2838 if (isset($_SERVER['HTTP_ACCEPT'])
2839 && false !== strpos($_SERVER['HTTP_ACCEPT'], 'application/xhtml+xml')) {
2840 //|| false !== strpos($_SERVER['HTTP_USER_AGENT'], 'Safari') //Safari "Entity 'copy' not defined".
2841 // Firefox et al.
2842 $ctype .= 'application/xhtml+xml';
2843 $prolog .= "<!--\n DEBUG: $ctype \n-->\n";
2845 } else if (file_exists($CFG->dirroot.$xsl)
2846 && preg_match('/MSIE.*Windows NT/', $_SERVER['HTTP_USER_AGENT'])) {
2847 // XSL hack for IE 5+ on Windows.
2848 //$www_xsl = preg_replace('/(http:\/\/.+?\/).*/', '', $CFG->wwwroot) .$xsl;
2849 $www_xsl = $CFG->wwwroot .$xsl;
2850 $ctype .= 'application/xml';
2851 $prolog .= "<?xml-stylesheet type='text/xsl' href='$www_xsl'?>\n";
2852 $prolog .= "<!--\n DEBUG: $ctype \n-->\n";
2854 } else {
2855 //ELSE: Mac/IE, old/non-XML browsers.
2856 $ctype .= 'text/html';
2857 $prolog = '';
2859 @header($ctype.'; charset=utf-8');
2860 $output = $prolog . $output;
2862 // Test parser error-handling.
2863 if (isset($_GET['error'])) {
2864 $output .= "__ TEST: XML well-formed error < __\n";
2868 $output = preg_replace('/(<!DOCTYPE.+?>)/s', $strict, $output); // Always change the DOCTYPE to Strict 1.0
2870 return $output;
2876 * This version of print_header is simpler because the course name does not have to be
2877 * provided explicitly in the strings. It can be used on the site page as in courses
2878 * Eventually all print_header could be replaced by print_header_simple
2880 * @param string $title Appears at the top of the window
2881 * @param string $heading Appears at the top of the page
2882 * @param string $navigation Premade navigation string (for use as breadcrumbs links)
2883 * @param string $focus Indicates form element to get cursor focus on load eg inputform.password
2884 * @param string $meta Meta tags to be added to the header
2885 * @param boolean $cache Should this page be cacheable?
2886 * @param string $button HTML code for a button (usually for module editing)
2887 * @param string $menu HTML code for a popup menu
2888 * @param boolean $usexml use XML for this page
2889 * @param string $bodytags This text will be included verbatim in the <body> tag (useful for onload() etc)
2890 * @param bool $return If true, return the visible elements of the header instead of echoing them.
2892 function print_header_simple($title='', $heading='', $navigation='', $focus='', $meta='',
2893 $cache=true, $button='&nbsp;', $menu='', $usexml=false, $bodytags='', $return=false) {
2895 global $COURSE, $CFG;
2897 // if we have no navigation specified, build it
2898 if( empty($navigation) ){
2899 $navigation = build_navigation('');
2902 // If old style nav prepend course short name otherwise leave $navigation object alone
2903 if (!is_newnav($navigation)) {
2904 if ($COURSE->id != SITEID) {
2905 $shortname = '<a href="'.$CFG->wwwroot.'/course/view.php?id='. $COURSE->id .'">'. $COURSE->shortname .'</a> ->';
2906 $navigation = $shortname.' '.$navigation;
2910 $output = print_header($COURSE->shortname .': '. $title, $COURSE->fullname .' '. $heading, $navigation, $focus, $meta,
2911 $cache, $button, $menu, $usexml, $bodytags, true);
2913 if ($return) {
2914 return $output;
2915 } else {
2916 echo $output;
2922 * Can provide a course object to make the footer contain a link to
2923 * to the course home page, otherwise the link will go to the site home
2924 * @uses $USER
2925 * @param mixed $course course object, used for course link button or
2926 * 'none' means no user link, only docs link
2927 * 'empty' means nothing printed in footer
2928 * 'home' special frontpage footer
2929 * @param object $usercourse course used in user link
2930 * @param boolean $return output as string
2931 * @return mixed string or void
2933 function print_footer($course=NULL, $usercourse=NULL, $return=false) {
2934 global $USER, $CFG, $THEME, $COURSE;
2936 if (defined('ADMIN_EXT_HEADER_PRINTED') and !defined('ADMIN_EXT_FOOTER_PRINTED')) {
2937 admin_externalpage_print_footer();
2938 return;
2941 /// Course links or special footer
2942 if ($course) {
2943 if ($course === 'empty') {
2944 // special hack - sometimes we do not want even the docs link in footer
2945 $output = '';
2946 if (!empty($THEME->open_header_containers)) {
2947 for ($i=0; $i<$THEME->open_header_containers; $i++) {
2948 $output .= print_container_end_all(); // containers opened from header
2950 } else {
2951 //1.8 theme compatibility
2952 $output .= "\n</div>"; // content div
2954 $output .= "\n</div>\n</body>\n</html>"; // close page div started in header
2955 if ($return) {
2956 return $output;
2957 } else {
2958 echo $output;
2959 return;
2962 } else if ($course === 'none') { // Don't print any links etc
2963 $homelink = '';
2964 $loggedinas = '';
2965 $home = false;
2967 } else if ($course === 'home') { // special case for site home page - please do not remove
2968 $course = get_site();
2969 $homelink = '<div class="sitelink">'.
2970 '<a title="Moodle '. $CFG->release .'" href="http://moodle.org/">'.
2971 '<img style="width:100px;height:30px" src="pix/moodlelogo.gif" alt="moodlelogo" /></a></div>';
2972 $home = true;
2974 } else {
2975 $homelink = '<div class="homelink"><a '.$CFG->frametarget.' href="'.$CFG->wwwroot.
2976 '/course/view.php?id='.$course->id.'">'.format_string($course->shortname).'</a></div>';
2977 $home = false;
2980 } else {
2981 $course = get_site(); // Set course as site course by default
2982 $homelink = '<div class="homelink"><a '.$CFG->frametarget.' href="'.$CFG->wwwroot.'/">'.get_string('home').'</a></div>';
2983 $home = false;
2986 /// Set up some other navigation links (passed from print_header by ugly hack)
2987 $menu = isset($THEME->menu) ? str_replace('navmenu', 'navmenufooter', $THEME->menu) : '';
2988 $title = isset($THEME->title) ? $THEME->title : '';
2989 $button = isset($THEME->button) ? $THEME->button : '';
2990 $heading = isset($THEME->heading) ? $THEME->heading : '';
2991 $navigation = isset($THEME->navigation) ? $THEME->navigation : '';
2992 $navmenulist = isset($THEME->navmenulist) ? $THEME->navmenulist : '';
2995 /// Set the user link if necessary
2996 if (!$usercourse and is_object($course)) {
2997 $usercourse = $course;
3000 if (!isset($loggedinas)) {
3001 $loggedinas = user_login_string($usercourse, $USER);
3004 if ($loggedinas == $menu) {
3005 $menu = '';
3008 /// there should be exactly the same number of open containers as after the header
3009 if ($THEME->open_header_containers != open_containers()) {
3010 debugging('Unexpected number of open containers: '.open_containers().', expecting '.$THEME->open_header_containers, DEBUG_DEVELOPER);
3013 /// Provide some performance info if required
3014 $performanceinfo = '';
3015 if (defined('MDL_PERF') || (!empty($CFG->perfdebug) and $CFG->perfdebug > 7)) {
3016 $perf = get_performance_info();
3017 if (defined('MDL_PERFTOLOG') && !function_exists('register_shutdown_function')) {
3018 error_log("PERF: " . $perf['txt']);
3020 if (defined('MDL_PERFTOFOOT') || debugging() || $CFG->perfdebug > 7) {
3021 $performanceinfo = $perf['html'];
3025 /// Include the actual footer file
3027 ob_start();
3028 include($CFG->footer);
3029 $output = ob_get_contents();
3030 ob_end_clean();
3032 if ($return) {
3033 return $output;
3034 } else {
3035 echo $output;
3040 * Returns the name of the current theme
3042 * @uses $CFG
3043 * @uses $USER
3044 * @uses $SESSION
3045 * @uses $COURSE
3046 * @uses $FULLME
3047 * @return string
3049 function current_theme() {
3050 global $CFG, $USER, $SESSION, $COURSE, $FULLME;
3052 if (empty($CFG->themeorder)) {
3053 $themeorder = array('page', 'course', 'category', 'session', 'user', 'site');
3054 } else {
3055 $themeorder = $CFG->themeorder;
3058 if (isloggedin() and isset($CFG->mnet_localhost_id) and $USER->mnethostid != $CFG->mnet_localhost_id) {
3059 require_once($CFG->dirroot.'/mnet/peer.php');
3060 $mnet_peer = new mnet_peer();
3061 $mnet_peer->set_id($USER->mnethostid);
3064 $theme = '';
3065 foreach ($themeorder as $themetype) {
3067 if (!empty($theme)) continue;
3069 switch ($themetype) {
3070 case 'page': // Page theme is for special page-only themes set by code
3071 if (!empty($CFG->pagetheme)) {
3072 $theme = $CFG->pagetheme;
3074 break;
3075 case 'course':
3076 if (!empty($CFG->allowcoursethemes) and !empty($COURSE->theme)) {
3077 $theme = $COURSE->theme;
3079 break;
3080 case 'category':
3081 if (!empty($CFG->allowcategorythemes)) {
3082 /// Nasty hack to check if we're in a category page
3083 if (stripos($FULLME, 'course/category.php') !== false) {
3084 global $id;
3085 if (!empty($id)) {
3086 $theme = current_category_theme($id);
3088 /// Otherwise check if we're in a course that has a category theme set
3089 } else if (!empty($COURSE->category)) {
3090 $theme = current_category_theme($COURSE->category);
3093 break;
3094 case 'session':
3095 if (!empty($SESSION->theme)) {
3096 $theme = $SESSION->theme;
3098 break;
3099 case 'user':
3100 if (!empty($CFG->allowuserthemes) and !empty($USER->theme)) {
3101 if (isloggedin() and $USER->mnethostid != $CFG->mnet_localhost_id && $mnet_peer->force_theme == 1 && $mnet_peer->theme != '') {
3102 $theme = $mnet_peer->theme;
3103 } else {
3104 $theme = $USER->theme;
3107 break;
3108 case 'site':
3109 if (isloggedin() and isset($CFG->mnet_localhost_id) and $USER->mnethostid != $CFG->mnet_localhost_id && $mnet_peer->force_theme == 1 && $mnet_peer->theme != '') {
3110 $theme = $mnet_peer->theme;
3111 } else {
3112 $theme = $CFG->theme;
3114 break;
3115 default:
3116 /// do nothing
3120 /// A final check in case 'site' was not included in $CFG->themeorder
3121 if (empty($theme)) {
3122 $theme = $CFG->theme;
3125 return $theme;
3129 * Retrieves the category theme if one exists, otherwise checks the parent categories.
3130 * Recursive function.
3132 * @uses $COURSE
3133 * @param integer $categoryid id of the category to check
3134 * @return string theme name
3136 function current_category_theme($categoryid=0) {
3137 global $COURSE;
3139 /// Use the COURSE global if the categoryid not set
3140 if (empty($categoryid)) {
3141 if (!empty($COURSE->category)) {
3142 $categoryid = $COURSE->category;
3143 } else {
3144 return false;
3148 /// Retrieve the current category
3149 if ($category = get_record('course_categories', 'id', $categoryid)) {
3151 /// Return the category theme if it exists
3152 if (!empty($category->theme)) {
3153 return $category->theme;
3155 /// Otherwise try the parent category if one exists
3156 } else if (!empty($category->parent)) {
3157 return current_category_theme($category->parent);
3160 /// Return false if we can't find the category record
3161 } else {
3162 return false;
3167 * This function is called by stylesheets to set up the header
3168 * approriately as well as the current path
3170 * @uses $CFG
3171 * @param int $lastmodified ?
3172 * @param int $lifetime ?
3173 * @param string $thename ?
3175 function style_sheet_setup($lastmodified=0, $lifetime=300, $themename='', $forceconfig='', $lang='') {
3177 global $CFG, $THEME;
3179 // Fix for IE6 caching - we don't want the filemtime('styles.php'), instead use now.
3180 $lastmodified = time();
3182 header('Last-Modified: ' . gmdate("D, d M Y H:i:s", $lastmodified) . ' GMT');
3183 header('Expires: ' . gmdate("D, d M Y H:i:s", time() + $lifetime) . ' GMT');
3184 header('Cache-Control: max-age='. $lifetime);
3185 header('Pragma: ');
3186 header('Content-type: text/css'); // Correct MIME type
3188 $DEFAULT_SHEET_LIST = array('styles_layout', 'styles_fonts', 'styles_color');
3190 if (empty($themename)) {
3191 $themename = current_theme(); // So we have something. Normally not needed.
3192 } else {
3193 $themename = clean_param($themename, PARAM_SAFEDIR);
3196 if (!empty($forceconfig)) { // Page wants to use the config from this theme instead
3197 unset($THEME);
3198 include($CFG->themedir.'/'.$forceconfig.'/'.'config.php');
3201 /// If this is the standard theme calling us, then find out what sheets we need
3203 if ($themename == 'standard') {
3204 if (!isset($THEME->standardsheets) or $THEME->standardsheets === true) { // Use all the sheets we have
3205 $THEME->sheets = $DEFAULT_SHEET_LIST;
3206 } else if (empty($THEME->standardsheets)) { // We can stop right now!
3207 echo "/***** Nothing required from this stylesheet by main theme *****/\n\n";
3208 exit;
3209 } else { // Use the provided subset only
3210 $THEME->sheets = $THEME->standardsheets;
3213 /// If we are a parent theme, then check for parent definitions
3215 } else if (!empty($THEME->parent) && $themename == $THEME->parent) {
3216 if (!isset($THEME->parentsheets) or $THEME->parentsheets === true) { // Use all the sheets we have
3217 $THEME->sheets = $DEFAULT_SHEET_LIST;
3218 } else if (empty($THEME->parentsheets)) { // We can stop right now!
3219 echo "/***** Nothing required from this stylesheet by main theme *****/\n\n";
3220 exit;
3221 } else { // Use the provided subset only
3222 $THEME->sheets = $THEME->parentsheets;
3226 /// Work out the last modified date for this theme
3228 foreach ($THEME->sheets as $sheet) {
3229 if (file_exists($CFG->themedir.'/'.$themename.'/'.$sheet.'.css')) {
3230 $sheetmodified = filemtime($CFG->themedir.'/'.$themename.'/'.$sheet.'.css');
3231 if ($sheetmodified > $lastmodified) {
3232 $lastmodified = $sheetmodified;
3238 /// Get a list of all the files we want to include
3239 $files = array();
3241 foreach ($THEME->sheets as $sheet) {
3242 $files[] = array($CFG->themedir, $themename.'/'.$sheet.'.css');
3245 if ($themename == 'standard') { // Add any standard styles included in any modules
3246 if (!empty($THEME->modsheets)) { // Search for styles.php within activity modules
3247 if ($mods = get_list_of_plugins('mod')) {
3248 foreach ($mods as $mod) {
3249 if (file_exists($CFG->dirroot.'/mod/'.$mod.'/styles.php')) {
3250 $files[] = array($CFG->dirroot, '/mod/'.$mod.'/styles.php');
3256 if (!empty($THEME->blocksheets)) { // Search for styles.php within block modules
3257 if ($mods = get_list_of_plugins('blocks')) {
3258 foreach ($mods as $mod) {
3259 if (file_exists($CFG->dirroot.'/blocks/'.$mod.'/styles.php')) {
3260 $files[] = array($CFG->dirroot, '/blocks/'.$mod.'/styles.php');
3266 if (!isset($THEME->courseformatsheets) || $THEME->courseformatsheets) { // Search for styles.php in course formats
3267 if ($mods = get_list_of_plugins('format','',$CFG->dirroot.'/course')) {
3268 foreach ($mods as $mod) {
3269 if (file_exists($CFG->dirroot.'/course/format/'.$mod.'/styles.php')) {
3270 $files[] = array($CFG->dirroot, '/course/format/'.$mod.'/styles.php');
3276 if (!isset($THEME->gradereportsheets) || $THEME->gradereportsheets) { // Search for styles.php in grade reports
3277 if ($reports = get_list_of_plugins('grade/report')) {
3278 foreach ($reports as $report) {
3279 if (file_exists($CFG->dirroot.'/grade/report/'.$report.'/styles.php')) {
3280 $files[] = array($CFG->dirroot, '/grade/report/'.$report.'/styles.php');
3286 if (!empty($THEME->langsheets)) { // Search for styles.php within the current language
3287 if (file_exists($CFG->dirroot.'/lang/'.$lang.'/styles.php')) {
3288 $files[] = array($CFG->dirroot, '/lang/'.$lang.'/styles.php');
3293 if ($files) {
3294 /// Produce a list of all the files first
3295 echo '/**************************************'."\n";
3296 echo ' * THEME NAME: '.$themename."\n *\n";
3297 echo ' * Files included in this sheet:'."\n *\n";
3298 foreach ($files as $file) {
3299 echo ' * '.$file[1]."\n";
3301 echo ' **************************************/'."\n\n";
3304 /// check if csscobstants is set
3305 if (!empty($THEME->cssconstants)) {
3306 require_once("$CFG->libdir/cssconstants.php");
3307 /// Actually collect all the files in order.
3308 $css = '';
3309 foreach ($files as $file) {
3310 $css .= '/***** '.$file[1].' start *****/'."\n\n";
3311 $css .= file_get_contents($file[0].'/'.$file[1]);
3312 $ccs .= '/***** '.$file[1].' end *****/'."\n\n";
3314 /// replace css_constants with their values
3315 echo replace_cssconstants($css);
3316 } else {
3317 /// Actually output all the files in order.
3318 if (empty($CFG->CSSEdit) && empty($THEME->CSSEdit)) {
3319 foreach ($files as $file) {
3320 echo '/***** '.$file[1].' start *****/'."\n\n";
3321 @include_once($file[0].'/'.$file[1]);
3322 echo '/***** '.$file[1].' end *****/'."\n\n";
3324 } else {
3325 foreach ($files as $file) {
3326 echo '/* @group '.$file[1].' */'."\n\n";
3327 if (strstr($file[1], '.css') !== FALSE) {
3328 echo '@import url("'.$CFG->themewww.'/'.$file[1].'");'."\n\n";
3329 } else {
3330 @include_once($file[0].'/'.$file[1]);
3332 echo '/* @end */'."\n\n";
3338 return $CFG->themewww.'/'.$themename; // Only to help old themes (1.4 and earlier)
3342 function theme_setup($theme = '', $params=NULL) {
3343 /// Sets up global variables related to themes
3345 global $CFG, $THEME, $SESSION, $USER, $HTTPSPAGEREQUIRED;
3347 /// Do not mess with THEME if header already printed - this would break all the extra stuff in global $THEME from print_header()!!
3348 if (defined('HEADER_PRINTED')) {
3349 return;
3352 if (empty($theme)) {
3353 $theme = current_theme();
3356 /// If the theme doesn't exist for some reason then revert to standardwhite
3357 if (!file_exists($CFG->themedir .'/'. $theme .'/config.php')) {
3358 $CFG->theme = $theme = 'standardwhite';
3361 /// Load up the theme config
3362 $THEME = NULL; // Just to be sure
3363 include($CFG->themedir .'/'. $theme .'/config.php'); // Main config for current theme
3365 /// Put together the parameters
3366 if (!$params) {
3367 $params = array();
3370 if ($theme != $CFG->theme) {
3371 $params[] = 'forceconfig='.$theme;
3374 /// Force language too if required
3375 if (!empty($THEME->langsheets)) {
3376 $params[] = 'lang='.current_language();
3380 /// Convert params to string
3381 if ($params) {
3382 $paramstring = '?'.implode('&', $params);
3383 } else {
3384 $paramstring = '';
3387 /// Set up image paths
3388 if(isset($CFG->smartpix) && $CFG->smartpix==1) {
3389 if($CFG->slasharguments) { // Use this method if possible for better caching
3390 $extra='';
3391 } else {
3392 $extra='?file=';
3395 $CFG->pixpath = $CFG->wwwroot. '/pix/smartpix.php'.$extra.'/'.$theme;
3396 $CFG->modpixpath = $CFG->wwwroot .'/pix/smartpix.php'.$extra.'/'.$theme.'/mod';
3397 } else if (empty($THEME->custompix)) { // Could be set in the above file
3398 $CFG->pixpath = $CFG->wwwroot .'/pix';
3399 $CFG->modpixpath = $CFG->wwwroot .'/mod';
3400 } else {
3401 $CFG->pixpath = $CFG->themewww .'/'. $theme .'/pix';
3402 $CFG->modpixpath = $CFG->themewww .'/'. $theme .'/pix/mod';
3405 /// Header and footer paths
3406 $CFG->header = $CFG->themedir .'/'. $theme .'/header.html';
3407 $CFG->footer = $CFG->themedir .'/'. $theme .'/footer.html';
3409 /// Define stylesheet loading order
3410 $CFG->stylesheets = array();
3411 if ($theme != 'standard') { /// The standard sheet is always loaded first
3412 $CFG->stylesheets[] = $CFG->themewww.'/standard/styles.php'.$paramstring;
3414 if (!empty($THEME->parent)) { /// Parent stylesheets are loaded next
3415 $CFG->stylesheets[] = $CFG->themewww.'/'.$THEME->parent.'/styles.php'.$paramstring;
3417 $CFG->stylesheets[] = $CFG->themewww.'/'.$theme.'/styles.php'.$paramstring;
3419 /// We have to change some URLs in styles if we are in a $HTTPSPAGEREQUIRED page
3420 if (!empty($HTTPSPAGEREQUIRED)) {
3421 $CFG->themewww = str_replace('http:', 'https:', $CFG->themewww);
3422 $CFG->pixpath = str_replace('http:', 'https:', $CFG->pixpath);
3423 $CFG->modpixpath = str_replace('http:', 'https:', $CFG->modpixpath);
3424 foreach ($CFG->stylesheets as $key => $stylesheet) {
3425 $CFG->stylesheets[$key] = str_replace('http:', 'https:', $stylesheet);
3429 // RTL support - only for RTL languages, add RTL CSS
3430 if (get_string('thisdirection') == 'rtl') {
3431 $CFG->stylesheets[] = $CFG->themewww.'/standard/rtl.css'.$paramstring;
3432 $CFG->stylesheets[] = $CFG->themewww.'/'.$theme.'/rtl.css'.$paramstring;
3438 * Returns text to be displayed to the user which reflects their login status
3440 * @uses $CFG
3441 * @uses $USER
3442 * @param course $course {@link $COURSE} object containing course information
3443 * @param user $user {@link $USER} object containing user information
3444 * @return string
3446 function user_login_string($course=NULL, $user=NULL) {
3447 global $USER, $CFG, $SITE;
3449 if (empty($user) and !empty($USER->id)) {
3450 $user = $USER;
3453 if (empty($course)) {
3454 $course = $SITE;
3457 if (!empty($user->realuser)) {
3458 if ($realuser = get_record('user', 'id', $user->realuser)) {
3459 $fullname = fullname($realuser, true);
3460 $realuserinfo = " [<a $CFG->frametarget
3461 href=\"$CFG->wwwroot/course/loginas.php?id=$course->id&amp;return=1&amp;sesskey=".sesskey()."\">$fullname</a>] ";
3463 } else {
3464 $realuserinfo = '';
3467 if (empty($CFG->loginhttps)) {
3468 $wwwroot = $CFG->wwwroot;
3469 } else {
3470 $wwwroot = str_replace('http:','https:',$CFG->wwwroot);
3473 if (empty($course->id)) {
3474 // $course->id is not defined during installation
3475 return '';
3476 } else if (!empty($user->id)) {
3477 $context = get_context_instance(CONTEXT_COURSE, $course->id);
3479 $fullname = fullname($user, true);
3480 $username = "<a $CFG->frametarget href=\"$CFG->wwwroot/user/view.php?id=$user->id&amp;course=$course->id\">$fullname</a>";
3481 if (is_mnet_remote_user($user) and $idprovider = get_record('mnet_host', 'id', $user->mnethostid)) {
3482 $username .= " from <a $CFG->frametarget href=\"{$idprovider->wwwroot}\">{$idprovider->name}</a>";
3484 if (isset($user->username) && $user->username == 'guest') {
3485 $loggedinas = $realuserinfo.get_string('loggedinasguest').
3486 " (<a $CFG->frametarget href=\"$wwwroot/login/index.php\">".get_string('login').'</a>)';
3487 } else if (!empty($user->access['rsw'][$context->path])) {
3488 $rolename = '';
3489 if ($role = get_record('role', 'id', $user->access['rsw'][$context->path])) {
3490 $rolename = ': '.format_string($role->name);
3492 $loggedinas = get_string('loggedinas', 'moodle', $username).$rolename.
3493 " (<a $CFG->frametarget
3494 href=\"$CFG->wwwroot/course/view.php?id=$course->id&amp;switchrole=0&amp;sesskey=".sesskey()."\">".get_string('switchrolereturn').'</a>)';
3495 } else {
3496 $loggedinas = $realuserinfo.get_string('loggedinas', 'moodle', $username).' '.
3497 " (<a $CFG->frametarget href=\"$CFG->wwwroot/login/logout.php?sesskey=".sesskey()."\">".get_string('logout').'</a>)';
3499 } else {
3500 $loggedinas = get_string('loggedinnot', 'moodle').
3501 " (<a $CFG->frametarget href=\"$wwwroot/login/index.php\">".get_string('login').'</a>)';
3503 return '<div class="logininfo">'.$loggedinas.'</div>';
3507 * Tests whether $THEME->rarrow, $THEME->larrow have been set (theme/-/config.php).
3508 * If not it applies sensible defaults.
3510 * Accessibility: right and left arrow Unicode characters for breadcrumb, calendar,
3511 * search forum block, etc. Important: these are 'silent' in a screen-reader
3512 * (unlike &gt; &raquo;), and must be accompanied by text.
3513 * @uses $THEME
3515 function check_theme_arrows() {
3516 global $THEME;
3518 if (!isset($THEME->rarrow) and !isset($THEME->larrow)) {
3519 // Default, looks good in Win XP/IE 6, Win/Firefox 1.5, Win/Netscape 8...
3520 // Also OK in Win 9x/2K/IE 5.x
3521 $THEME->rarrow = '&#x25BA;';
3522 $THEME->larrow = '&#x25C4;';
3523 if (empty($_SERVER['HTTP_USER_AGENT'])) {
3524 $uagent = '';
3525 } else {
3526 $uagent = $_SERVER['HTTP_USER_AGENT'];
3528 if (false !== strpos($uagent, 'Opera')
3529 || false !== strpos($uagent, 'Mac')) {
3530 // Looks good in Win XP/Mac/Opera 8/9, Mac/Firefox 2, Camino, Safari.
3531 // Not broken in Mac/IE 5, Mac/Netscape 7 (?).
3532 $THEME->rarrow = '&#x25B6;';
3533 $THEME->larrow = '&#x25C0;';
3535 elseif (false !== strpos($uagent, 'Konqueror')) {
3536 $THEME->rarrow = '&rarr;';
3537 $THEME->larrow = '&larr;';
3539 elseif (isset($_SERVER['HTTP_ACCEPT_CHARSET'])
3540 && false === stripos($_SERVER['HTTP_ACCEPT_CHARSET'], 'utf-8')) {
3541 // (Win/IE 5 doesn't set ACCEPT_CHARSET, but handles Unicode.)
3542 // To be safe, non-Unicode browsers!
3543 $THEME->rarrow = '&gt;';
3544 $THEME->larrow = '&lt;';
3547 /// RTL support - in RTL languages, swap r and l arrows
3548 if (right_to_left()) {
3549 $t = $THEME->rarrow;
3550 $THEME->rarrow = $THEME->larrow;
3551 $THEME->larrow = $t;
3558 * Return the right arrow with text ('next'), and optionally embedded in a link.
3559 * See function above, check_theme_arrows.
3560 * @param string $text HTML/plain text label (set to blank only for breadcrumb separator cases).
3561 * @param string $url An optional link to use in a surrounding HTML anchor.
3562 * @param bool $accesshide True if text should be hidden (for screen readers only).
3563 * @param string $addclass Additional class names for the link, or the arrow character.
3564 * @return string HTML string.
3566 function link_arrow_right($text, $url='', $accesshide=false, $addclass='') {
3567 global $THEME;
3568 check_theme_arrows();
3569 $arrowclass = 'arrow ';
3570 if (! $url) {
3571 $arrowclass .= $addclass;
3573 $arrow = '<span class="'.$arrowclass.'">'.$THEME->rarrow.'</span>';
3574 $htmltext = '';
3575 if ($text) {
3576 $htmltext = $text.'&nbsp;';
3577 if ($accesshide) {
3578 $htmltext = get_accesshide($htmltext);
3581 if ($url) {
3582 $class = '';
3583 if ($addclass) {
3584 $class =" class=\"$addclass\"";
3586 return '<a'.$class.' href="'.$url.'" title="'.preg_replace('/<.*?>/','',$text).'">'.$htmltext.$arrow.'</a>';
3588 return $htmltext.$arrow;
3592 * Return the left arrow with text ('previous'), and optionally embedded in a link.
3593 * See function above, check_theme_arrows.
3594 * @param string $text HTML/plain text label (set to blank only for breadcrumb separator cases).
3595 * @param string $url An optional link to use in a surrounding HTML anchor.
3596 * @param bool $accesshide True if text should be hidden (for screen readers only).
3597 * @param string $addclass Additional class names for the link, or the arrow character.
3598 * @return string HTML string.
3600 function link_arrow_left($text, $url='', $accesshide=false, $addclass='') {
3601 global $THEME;
3602 check_theme_arrows();
3603 $arrowclass = 'arrow ';
3604 if (! $url) {
3605 $arrowclass .= $addclass;
3607 $arrow = '<span class="'.$arrowclass.'">'.$THEME->larrow.'</span>';
3608 $htmltext = '';
3609 if ($text) {
3610 $htmltext = '&nbsp;'.$text;
3611 if ($accesshide) {
3612 $htmltext = get_accesshide($htmltext);
3615 if ($url) {
3616 $class = '';
3617 if ($addclass) {
3618 $class =" class=\"$addclass\"";
3620 return '<a'.$class.' href="'.$url.'" title="'.preg_replace('/<.*?>/','',$text).'">'.$arrow.$htmltext.'</a>';
3622 return $arrow.$htmltext;
3626 * Return a HTML element with the class "accesshide", for accessibility.
3627 * Please use cautiously - where possible, text should be visible!
3628 * @param string $text Plain text.
3629 * @param string $elem Lowercase element name, default "span".
3630 * @param string $class Additional classes for the element.
3631 * @param string $attrs Additional attributes string in the form, "name='value' name2='value2'"
3632 * @return string HTML string.
3634 function get_accesshide($text, $elem='span', $class='', $attrs='') {
3635 return "<$elem class=\"accesshide $class\" $attrs>$text</$elem>";
3639 * Return the breadcrumb trail navigation separator.
3640 * @return string HTML string.
3642 function get_separator() {
3643 //Accessibility: the 'hidden' slash is preferred for screen readers.
3644 return ' '.link_arrow_right($text='/', $url='', $accesshide=true, 'sep').' ';
3648 * Prints breadcrumb trail of links, called in theme/-/header.html
3650 * @uses $CFG
3651 * @param mixed $navigation The breadcrumb navigation string to be printed
3652 * @param string $separator OBSOLETE, mostly not used any more. See build_navigation instead.
3653 * @param boolean $return False to echo the breadcrumb string (default), true to return it.
3654 * @return string or null, depending on $return.
3656 function print_navigation ($navigation, $separator=0, $return=false) {
3657 global $CFG, $THEME;
3658 $output = '';
3660 if (0 === $separator) {
3661 $separator = get_separator();
3663 else {
3664 $separator = '<span class="sep">'. $separator .'</span>';
3667 if ($navigation) {
3669 if (is_newnav($navigation)) {
3670 if ($return) {
3671 return($navigation['navlinks']);
3672 } else {
3673 echo $navigation['navlinks'];
3674 return;
3676 } else {
3677 debugging('Navigation needs to be updated to use build_navigation()', DEBUG_DEVELOPER);
3680 if (!is_array($navigation)) {
3681 $ar = explode('->', $navigation);
3682 $navigation = array();
3684 foreach ($ar as $a) {
3685 if (strpos($a, '</a>') === false) {
3686 $navigation[] = array('title' => $a, 'url' => '');
3687 } else {
3688 if (preg_match('/<a.*href="([^"]*)">(.*)<\/a>/', $a, $matches)) {
3689 $navigation[] = array('title' => $matches[2], 'url' => $matches[1]);
3695 if (! $site = get_site()) {
3696 $site = new object();
3697 $site->shortname = get_string('home');
3700 //Accessibility: breadcrumb links now in a list, &raquo; replaced with a 'silent' character.
3701 $output .= get_accesshide(get_string('youarehere','access'), 'h2')."<ul>\n";
3703 $output .= '<li class="first">'."\n".'<a '.$CFG->frametarget.' onclick="this.target=\''.$CFG->framename.'\'" href="'
3704 .$CFG->wwwroot.((!has_capability('moodle/site:config', get_context_instance(CONTEXT_SYSTEM))
3705 && !empty($USER->id) && !empty($CFG->mymoodleredirect) && !isguest())
3706 ? '/my' : '') .'/">'. format_string($site->shortname) ."</a>\n</li>\n";
3709 foreach ($navigation as $navitem) {
3710 $title = trim(strip_tags(format_string($navitem['title'], false)));
3711 $url = $navitem['url'];
3713 if (empty($url)) {
3714 $output .= '<li>'."$separator $title</li>\n";
3715 } else {
3716 $output .= '<li>'."$separator\n<a ".$CFG->frametarget.' onclick="this.target=\''.$CFG->framename.'\'" href="'
3717 .$url.'">'."$title</a>\n</li>\n";
3721 $output .= "</ul>\n";
3724 if ($return) {
3725 return $output;
3726 } else {
3727 echo $output;
3732 * This function will build the navigation string to be used by print_header
3733 * and others.
3735 * It automatically generates the site and course level (if appropriate) links.
3737 * If you pass in a $cm object, the method will also generate the activity (e.g. 'Forums')
3738 * and activityinstances (e.g. 'General Developer Forum') navigation levels.
3740 * If you want to add any further navigation links after the ones this function generates,
3741 * the pass an array of extra link arrays like this:
3742 * array(
3743 * array('name' => $linktext1, 'link' => $url1, 'type' => $linktype1),
3744 * array('name' => $linktext2, 'link' => $url2, 'type' => $linktype2)
3746 * The normal case is to just add one further link, for example 'Editing forum' after
3747 * 'General Developer Forum', with no link.
3748 * To do that, you need to pass
3749 * array(array('name' => $linktext, 'link' => '', 'type' => 'title'))
3750 * However, becuase this is a very common case, you can use a shortcut syntax, and just
3751 * pass the string 'Editing forum', instead of an array as $extranavlinks.
3753 * At the moment, the link types only have limited significance. Type 'activity' is
3754 * recognised in order to implement the $CFG->hideactivitytypenavlink feature. Types
3755 * that are known to appear are 'home', 'course', 'activity', 'activityinstance' and 'title'.
3756 * This really needs to be documented better. In the mean time, try to be consistent, it will
3757 * enable people to customise the navigation more in future.
3759 * When passing a $cm object, the fields used are $cm->modname, $cm->name and $cm->course.
3760 * If you get the $cm object using the function get_coursemodule_from_instance or
3761 * get_coursemodule_from_id (as recommended) then this will be done for you automatically.
3762 * If you don't have $cm->modname or $cm->name, this fuction will attempt to find them using
3763 * the $cm->module and $cm->instance fields, but this takes extra database queries, so a
3764 * warning is printed in developer debug mode.
3766 * @uses $CFG
3767 * @uses $THEME
3769 * @param mixed $extranavlinks - Normally an array of arrays, keys: name, link, type. If you
3770 * only want one extra item with no link, you can pass a string instead. If you don't want
3771 * any extra links, pass an empty string.
3772 * @param mixed $cm - optionally the $cm object, if you want this function to generate the
3773 * activity and activityinstance levels of navigation too.
3775 * @return $navigation as an object so it can be differentiated from old style
3776 * navigation strings.
3778 function build_navigation($extranavlinks, $cm = null) {
3779 global $CFG, $COURSE;
3781 if (is_string($extranavlinks)) {
3782 if ($extranavlinks == '') {
3783 $extranavlinks = array();
3784 } else {
3785 $extranavlinks = array(array('name' => $extranavlinks, 'link' => '', 'type' => 'title'));
3789 $navlinks = array();
3791 //Site name
3792 if ($site = get_site()) {
3793 $navlinks[] = array(
3794 'name' => format_string($site->shortname),
3795 'link' => "$CFG->wwwroot/",
3796 'type' => 'home');
3799 // Course name, if appropriate.
3800 if (isset($COURSE) && $COURSE->id != SITEID) {
3801 $navlinks[] = array(
3802 'name' => format_string($COURSE->shortname),
3803 'link' => "$CFG->wwwroot/course/view.php?id=$COURSE->id",
3804 'type' => 'course');
3807 // Activity type and instance, if appropriate.
3808 if (is_object($cm)) {
3809 if (!isset($cm->modname)) {
3810 debugging('The field $cm->modname should be set if you call build_navigation with '.
3811 'a $cm parameter. If you get $cm using get_coursemodule_from_instance or '.
3812 'get_coursemodule_from_id, this will be done automatically.', DEBUG_DEVELOPER);
3813 if (!$cm->modname = get_field('modules', 'name', 'id', $cm->module)) {
3814 error('Cannot get the module type in build navigation.');
3817 if (!isset($cm->name)) {
3818 debugging('The field $cm->name should be set if you call build_navigation with '.
3819 'a $cm parameter. If you get $cm using get_coursemodule_from_instance or '.
3820 'get_coursemodule_from_id, this will be done automatically.', DEBUG_DEVELOPER);
3821 if (!$cm->name = get_field($cm->modname, 'name', 'id', $cm->instance)) {
3822 error('Cannot get the module name in build navigation.');
3825 $navlinks[] = array(
3826 'name' => get_string('modulenameplural', $cm->modname),
3827 'link' => $CFG->wwwroot . '/mod/' . $cm->modname . '/index.php?id=' . $cm->course,
3828 'type' => 'activity');
3829 $navlinks[] = array(
3830 'name' => format_string($cm->name),
3831 'link' => $CFG->wwwroot . '/mod/' . $cm->modname . '/view.php?id=' . $cm->id,
3832 'type' => 'activityinstance');
3835 //Merge in extra navigation links
3836 $navlinks = array_merge($navlinks, $extranavlinks);
3838 // Work out whether we should be showing the activity (e.g. Forums) link.
3839 // Note: build_navigation() is called from many places --
3840 // install & upgrade for example -- where we cannot count on the
3841 // roles infrastructure to be defined. Hence the $CFG->rolesactive check.
3842 if (!isset($CFG->hideactivitytypenavlink)) {
3843 $CFG->hideactivitytypenavlink = 0;
3845 if ($CFG->hideactivitytypenavlink == 2) {
3846 $hideactivitylink = true;
3847 } else if ($CFG->hideactivitytypenavlink == 1 && $CFG->rolesactive &&
3848 !empty($COURSE->id) && $COURSE->id != SITEID) {
3849 if (!isset($COURSE->context)) {
3850 $COURSE->context = get_context_instance(CONTEXT_COURSE, $COURSE->id);
3852 $hideactivitylink = !has_capability('moodle/course:manageactivities', $COURSE->context);
3853 } else {
3854 $hideactivitylink = false;
3857 //Construct an unordered list from $navlinks
3858 //Accessibility: heading hidden from visual browsers by default.
3859 $navigation = get_accesshide(get_string('youarehere','access'), 'h2')." <ul>\n";
3860 $lastindex = count($navlinks) - 1;
3861 $i = -1; // Used to count the times, so we know when we get to the last item.
3862 $first = true;
3863 foreach ($navlinks as $navlink) {
3864 $i++;
3865 $last = ($i == $lastindex);
3866 if (!is_array($navlink)) {
3867 continue;
3869 if (!empty($navlink['type']) && $navlink['type'] == 'activity' && !$last && $hideactivitylink) {
3870 continue;
3872 if ($first) {
3873 $navigation .= '<li class="first">';
3874 } else {
3875 $navigation .= '<li>';
3877 if (!$first) {
3878 $navigation .= get_separator();
3880 if ((!empty($navlink['link'])) && !$last) {
3881 $navigation .= "<a $CFG->frametarget onclick=\"this.target='$CFG->framename'\" href=\"{$navlink['link']}\">";
3883 $navigation .= "{$navlink['name']}";
3884 if ((!empty($navlink['link'])) && !$last) {
3885 $navigation .= "</a>";
3888 $navigation .= "</li>";
3889 $first = false;
3891 $navigation .= "</ul>";
3893 return(array('newnav' => true, 'navlinks' => $navigation));
3898 * Prints a string in a specified size (retained for backward compatibility)
3900 * @param string $text The text to be displayed
3901 * @param int $size The size to set the font for text display.
3903 function print_headline($text, $size=2, $return=false) {
3904 $output = print_heading($text, '', $size, true);
3905 if ($return) {
3906 return $output;
3907 } else {
3908 echo $output;
3913 * Prints text in a format for use in headings.
3915 * @param string $text The text to be displayed
3916 * @param string $align The alignment of the printed paragraph of text
3917 * @param int $size The size to set the font for text display.
3919 function print_heading($text, $align='', $size=2, $class='main', $return=false) {
3920 if ($align) {
3921 $align = ' style="text-align:'.$align.';"';
3923 if ($class) {
3924 $class = ' class="'.$class.'"';
3926 $output = "<h$size $align $class>".stripslashes_safe($text)."</h$size>";
3928 if ($return) {
3929 return $output;
3930 } else {
3931 echo $output;
3936 * Centered heading with attached help button (same title text)
3937 * and optional icon attached
3939 * @param string $text The text to be displayed
3940 * @param string $helppage The help page to link to
3941 * @param string $module The module whose help should be linked to
3942 * @param string $icon Image to display if needed
3944 function print_heading_with_help($text, $helppage, $module='moodle', $icon='', $return=false) {
3945 $output = '';
3946 $output .= '<h2 class="main help">'.$icon.stripslashes_safe($text);
3947 $output .= helpbutton($helppage, $text, $module, true, false, '', true);
3948 $output .= '</h2>';
3950 if ($return) {
3951 return $output;
3952 } else {
3953 echo $output;
3958 function print_heading_block($heading, $class='', $return=false) {
3959 //Accessibility: 'headingblock' is now H1, see theme/standard/styles_*.css: ??
3960 $output = '<h2 class="headingblock header '.$class.'">'.stripslashes($heading).'</h2>';
3962 if ($return) {
3963 return $output;
3964 } else {
3965 echo $output;
3971 * Print a link to continue on to another page.
3973 * @uses $CFG
3974 * @param string $link The url to create a link to.
3976 function print_continue($link, $return=false) {
3978 global $CFG;
3980 // in case we are logging upgrade in admin/index.php stop it
3981 if (function_exists('upgrade_log_finish')) {
3982 upgrade_log_finish();
3985 $output = '';
3987 if ($link == '') {
3988 if (!empty($_SERVER['HTTP_REFERER'])) {
3989 $link = $_SERVER['HTTP_REFERER'];
3990 $link = str_replace('&', '&amp;', $link); // make it valid XHTML
3991 } else {
3992 $link = $CFG->wwwroot .'/';
3996 $options = array();
3997 $linkparts = parse_url(str_replace('&amp;', '&', $link));
3998 if (isset($linkparts['query'])) {
3999 parse_str($linkparts['query'], $options);
4002 $output .= '<div class="continuebutton">';
4004 $output .= print_single_button($link, $options, get_string('continue'), 'get', $CFG->framename, true);
4005 $output .= '</div>'."\n";
4007 if ($return) {
4008 return $output;
4009 } else {
4010 echo $output;
4016 * Print a message in a standard themed box.
4017 * Replaces print_simple_box (see deprecatedlib.php)
4019 * @param string $message, the content of the box
4020 * @param string $classes, space-separated class names.
4021 * @param string $idbase
4022 * @param boolean $return, return as string or just print it
4023 * @return mixed string or void
4025 function print_box($message, $classes='generalbox', $ids='', $return=false) {
4027 $output = print_box_start($classes, $ids, true);
4028 $output .= stripslashes_safe($message);
4029 $output .= print_box_end(true);
4031 if ($return) {
4032 return $output;
4033 } else {
4034 echo $output;
4039 * Starts a box using divs
4040 * Replaces print_simple_box_start (see deprecatedlib.php)
4042 * @param string $classes, space-separated class names.
4043 * @param string $idbase
4044 * @param boolean $return, return as string or just print it
4045 * @return mixed string or void
4047 function print_box_start($classes='generalbox', $ids='', $return=false) {
4048 global $THEME;
4050 if (strpos($classes, 'clearfix') !== false) {
4051 $clearfix = true;
4052 $classes = trim(str_replace('clearfix', '', $classes));
4053 } else {
4054 $clearfix = false;
4057 if (!empty($THEME->customcorners)) {
4058 $classes .= ' ccbox box';
4059 } else {
4060 $classes .= ' box';
4063 return print_container_start($clearfix, $classes, $ids, $return);
4067 * Simple function to end a box (see above)
4068 * Replaces print_simple_box_end (see deprecatedlib.php)
4070 * @param boolean $return, return as string or just print it
4072 function print_box_end($return=false) {
4073 return print_container_end($return);
4077 * Print a message in a standard themed container.
4079 * @param string $message, the content of the container
4080 * @param boolean $clearfix clear both sides
4081 * @param string $classes, space-separated class names.
4082 * @param string $idbase
4083 * @param boolean $return, return as string or just print it
4084 * @return string or void
4086 function print_container($message, $clearfix=false, $classes='', $idbase='', $return=false) {
4088 $output = print_container_start($clearfix, $classes, $idbase, true);
4089 $output .= stripslashes_safe($message);
4090 $output .= print_container_end(true);
4092 if ($return) {
4093 return $output;
4094 } else {
4095 echo $output;
4100 * Starts a container using divs
4102 * @param boolean $clearfix clear both sides
4103 * @param string $classes, space-separated class names.
4104 * @param string $idbase
4105 * @param boolean $return, return as string or just print it
4106 * @return mixed string or void
4108 function print_container_start($clearfix=false, $classes='', $idbase='', $return=false) {
4109 global $THEME;
4111 if (!isset($THEME->open_containers)) {
4112 $THEME->open_containers = array();
4114 $THEME->open_containers[] = $idbase;
4117 if (!empty($THEME->customcorners)) {
4118 $output = _print_custom_corners_start($clearfix, $classes, $idbase);
4119 } else {
4120 if ($idbase) {
4121 $id = ' id="'.$idbase.'"';
4122 } else {
4123 $id = '';
4125 if ($clearfix) {
4126 $clearfix = ' clearfix';
4127 } else {
4128 $clearfix = '';
4130 if ($classes or $clearfix) {
4131 $class = ' class="'.$classes.$clearfix.'"';
4132 } else {
4133 $class = '';
4135 $output = '<div'.$id.$class.'>';
4138 if ($return) {
4139 return $output;
4140 } else {
4141 echo $output;
4146 * Simple function to end a container (see above)
4147 * @param boolean $return, return as string or just print it
4148 * @return mixed string or void
4150 function print_container_end($return=false) {
4151 global $THEME;
4153 if (empty($THEME->open_containers)) {
4154 debugging('Incorrect request to end container - no more open containers.', DEBUG_DEVELOPER);
4155 $idbase = '';
4156 } else {
4157 $idbase = array_pop($THEME->open_containers);
4160 if (!empty($THEME->customcorners)) {
4161 $output = _print_custom_corners_end($idbase);
4162 } else {
4163 $output = '</div>';
4166 if ($return) {
4167 return $output;
4168 } else {
4169 echo $output;
4174 * Returns number of currently open containers
4175 * @return int number of open containers
4177 function open_containers() {
4178 global $THEME;
4180 if (!isset($THEME->open_containers)) {
4181 $THEME->open_containers = array();
4184 return count($THEME->open_containers);
4188 * Force closing of open containers
4189 * @param boolean $return, return as string or just print it
4190 * @param int $keep number of containers to be kept open - usually theme or page containers
4191 * @return mixed string or void
4193 function print_container_end_all($return=false, $keep=0) {
4194 $output = '';
4195 while (open_containers() > $keep) {
4196 $output .= print_container_end($return);
4199 if ($return) {
4200 return $output;
4201 } else {
4202 echo $output;
4207 * Internal function - do not use directly!
4208 * Starting part of the surrounding divs for custom corners
4210 * @param boolean $clearfix, add CLASS "clearfix" to the inner div against collapsing
4211 * @param string $classes
4212 * @param mixed $idbase, optionally, define one idbase to be added to all the elements in the corners
4213 * @return string
4215 function _print_custom_corners_start($clearfix=false, $classes='', $idbase='') {
4216 /// Analise if we want ids for the custom corner elements
4217 $id = '';
4218 $idbt = '';
4219 $idi1 = '';
4220 $idi2 = '';
4221 $idi3 = '';
4223 if ($idbase) {
4224 $id = 'id="'.$idbase.'" ';
4225 $idbt = 'id="'.$idbase.'-bt" ';
4226 $idi1 = 'id="'.$idbase.'-i1" ';
4227 $idi2 = 'id="'.$idbase.'-i2" ';
4228 $idi3 = 'id="'.$idbase.'-i3" ';
4231 /// Calculate current level
4232 $level = open_containers();
4234 /// Output begins
4235 $output = '<div '.$id.'class="wrap wraplevel'.$level.' '.$classes.'">'."\n";
4236 $output .= '<div '.$idbt.'class="bt"><div>&nbsp;</div></div>';
4237 $output .= "\n";
4238 $output .= '<div '.$idi1.'class="i1"><div '.$idi2.'class="i2">';
4239 $output .= (!empty($clearfix)) ? '<div '.$idi3.'class="i3 clearfix">' : '<div '.$idi3.'class="i3">';
4241 return $output;
4246 * Internal function - do not use directly!
4247 * Ending part of the surrounding divs for custom corners
4248 * @param string $idbase
4249 * @return string
4251 function _print_custom_corners_end($idbase) {
4252 /// Analise if we want ids for the custom corner elements
4253 $idbb = '';
4255 if ($idbase) {
4256 $idbb = 'id="' . $idbase . '-bb" ';
4259 /// Output begins
4260 $output = '</div></div></div>';
4261 $output .= "\n";
4262 $output .= '<div '.$idbb.'class="bb"><div>&nbsp;</div></div>'."\n";
4263 $output .= '</div>';
4265 return $output;
4270 * Print a self contained form with a single submit button.
4272 * @param string $link used as the action attribute on the form, so the URL that will be hit if the button is clicked.
4273 * @param array $options these become hidden form fields, so these options get passed to the script at $link.
4274 * @param string $label the caption that appears on the button.
4275 * @param string $method HTTP method used on the request of the button is clicked. 'get' or 'post'.
4276 * @param string $target no longer used.
4277 * @param boolean $return if false, output the form directly, otherwise return the HTML as a string.
4278 * @param string $tooltip a tooltip to add to the button as a title attribute.
4279 * @param boolean $disabled if true, the button will be disabled.
4280 * @param string $jsconfirmmessage if not empty then display a confirm dialogue with this string as the question.
4281 * @return string / nothing depending on the $return paramter.
4283 function print_single_button($link, $options, $label='OK', $method='get', $target='_self', $return=false, $tooltip='', $disabled = false, $jsconfirmmessage='') {
4284 $output = '';
4285 $link = str_replace('"', '&quot;', $link); //basic XSS protection
4286 $output .= '<div class="singlebutton">';
4287 // taking target out, will need to add later target="'.$target.'"
4288 $output .= '<form action="'. $link .'" method="'. $method .'">';
4289 $output .= '<div>';
4290 if ($options) {
4291 foreach ($options as $name => $value) {
4292 $output .= '<input type="hidden" name="'. $name .'" value="'. s($value) .'" />';
4295 if ($tooltip) {
4296 $tooltip = 'title="' . s($tooltip) . '"';
4297 } else {
4298 $tooltip = '';
4300 if ($disabled) {
4301 $disabled = 'disabled="disabled"';
4302 } else {
4303 $disabled = '';
4305 if ($jsconfirmmessage){
4306 $jsconfirmmessage = addslashes_js($jsconfirmmessage);
4307 $jsconfirmmessage = 'onclick="return confirm(\''. $jsconfirmmessage .'\');" ';
4309 $output .= '<input type="submit" value="'. s($label) ."\" $tooltip $disabled $jsconfirmmessage/></div></form></div>";
4311 if ($return) {
4312 return $output;
4313 } else {
4314 echo $output;
4320 * Print a spacer image with the option of including a line break.
4322 * @param int $height ?
4323 * @param int $width ?
4324 * @param boolean $br ?
4325 * @todo Finish documenting this function
4327 function print_spacer($height=1, $width=1, $br=true, $return=false) {
4328 global $CFG;
4329 $output = '';
4331 $output .= '<img class="spacer" height="'. $height .'" width="'. $width .'" src="'. $CFG->wwwroot .'/pix/spacer.gif" alt="" />';
4332 if ($br) {
4333 $output .= '<br />'."\n";
4336 if ($return) {
4337 return $output;
4338 } else {
4339 echo $output;
4344 * Given the path to a picture file in a course, or a URL,
4345 * this function includes the picture in the page.
4347 * @param string $path ?
4348 * @param int $courseid ?
4349 * @param int $height ?
4350 * @param int $width ?
4351 * @param string $link ?
4352 * @todo Finish documenting this function
4354 function print_file_picture($path, $courseid=0, $height='', $width='', $link='', $return=false) {
4355 global $CFG;
4356 $output = '';
4358 if ($height) {
4359 $height = 'height="'. $height .'"';
4361 if ($width) {
4362 $width = 'width="'. $width .'"';
4364 if ($link) {
4365 $output .= '<a href="'. $link .'">';
4367 if (substr(strtolower($path), 0, 7) == 'http://') {
4368 $output .= '<img style="height:'.$height.'px;width:'.$width.'px;" src="'. $path .'" />';
4370 } else if ($courseid) {
4371 $output .= '<img style="height:'.$height.'px;width:'.$width.'px;" src="';
4372 require_once($CFG->libdir.'/filelib.php');
4373 $output .= get_file_url("$courseid/$path");
4374 $output .= '" />';
4375 } else {
4376 $output .= 'Error: must pass URL or course';
4378 if ($link) {
4379 $output .= '</a>';
4382 if ($return) {
4383 return $output;
4384 } else {
4385 echo $output;
4390 * Print the specified user's avatar.
4392 * @param mixed $user Should be a $user object with at least fields id, picture, imagealt, firstname, lastname
4393 * If any of these are missing, or if a userid is passed, the the database is queried. Avoid this
4394 * if at all possible, particularly for reports. It is very bad for performance.
4395 * @param int $courseid The course id. Used when constructing the link to the user's profile.
4396 * @param boolean $picture The picture to print. By default (or if NULL is passed) $user->picture is used.
4397 * @param int $size Size in pixels. Special values are (true/1 = 100px) and (false/0 = 35px) for backward compatability
4398 * @param boolean $return If false print picture to current page, otherwise return the output as string
4399 * @param boolean $link enclose printed image in a link the user's profile (default true).
4400 * @param string $target link target attribute. Makes the profile open in a popup window.
4401 * @param boolean $alttext add non-blank alt-text to the image. (Default true, set to false for purely
4402 * decorative images, or where the username will be printed anyway.)
4403 * @return string or nothing, depending on $return.
4405 function print_user_picture($user, $courseid, $picture=NULL, $size=0, $return=false, $link=true, $target='', $alttext=true) {
4406 global $CFG;
4408 $needrec = false;
4409 // only touch the DB if we are missing data...
4410 if (is_object($user)) {
4411 // Note - both picture and imagealt _can_ be empty
4412 // what we are trying to see here is if they have been fetched
4413 // from the DB. We should use isset() _except_ that some installs
4414 // have those fields as nullable, and isset() will return false
4415 // on null. The only safe thing is to ask array_key_exists()
4416 // which works on objects. property_exists() isn't quite
4417 // what we want here...
4418 if (! (array_key_exists('picture', $user)
4419 && ($alttext && array_key_exists('imagealt', $user)
4420 || (isset($user->firstname) && isset($user->lastname)))) ) {
4421 $needrec = true;
4422 $user = $user->id;
4424 } else {
4425 if ($alttext) {
4426 // we need firstname, lastname, imagealt, can't escape...
4427 $needrec = true;
4428 } else {
4429 $userobj = new StdClass; // fake it to save DB traffic
4430 $userobj->id = $user;
4431 $userobj->picture = $picture;
4432 $user = clone($userobj);
4433 unset($userobj);
4436 if ($needrec) {
4437 $user = get_record('user','id',$user, '', '', '', '', 'id,firstname,lastname,imagealt');
4440 if ($link) {
4441 $url = '/user/view.php?id='. $user->id .'&amp;course='. $courseid ;
4442 if ($target) {
4443 $target='onclick="return openpopup(\''.$url.'\');"';
4445 $output = '<a '.$target.' href="'. $CFG->wwwroot . $url .'">';
4446 } else {
4447 $output = '';
4449 if (empty($size)) {
4450 $file = 'f2';
4451 $size = 35;
4452 } else if ($size === true or $size == 1) {
4453 $file = 'f1';
4454 $size = 100;
4455 } else if ($size >= 50) {
4456 $file = 'f1';
4457 } else {
4458 $file = 'f2';
4460 $class = "userpicture";
4462 if (is_null($picture) and !empty($user->picture)) {
4463 $picture = $user->picture;
4466 if ($picture) { // Print custom user picture
4467 require_once($CFG->libdir.'/filelib.php');
4468 $src = get_file_url($user->id.'/'.$file.'.jpg', null, 'user');
4469 } else { // Print default user pictures (use theme version if available)
4470 $class .= " defaultuserpic";
4471 $src = "$CFG->pixpath/u/$file.png";
4473 $imagealt = '';
4474 if ($alttext) {
4475 if (!empty($user->imagealt)) {
4476 $imagealt = $user->imagealt;
4477 } else {
4478 $imagealt = get_string('pictureof','',fullname($user));
4482 $output .= "<img class=\"$class\" src=\"$src\" height=\"$size\" width=\"$size\" alt=\"".s($imagealt).'" />';
4483 if ($link) {
4484 $output .= '</a>';
4487 if ($return) {
4488 return $output;
4489 } else {
4490 echo $output;
4495 * Prints a summary of a user in a nice little box.
4497 * @uses $CFG
4498 * @uses $USER
4499 * @param user $user A {@link $USER} object representing a user
4500 * @param course $course A {@link $COURSE} object representing a course
4502 function print_user($user, $course, $messageselect=false, $return=false) {
4504 global $CFG, $USER;
4506 $output = '';
4508 static $string;
4509 static $datestring;
4510 static $countries;
4512 $context = get_context_instance(CONTEXT_COURSE, $course->id);
4513 if (isset($user->context->id)) {
4514 $usercontext = $user->context;
4515 } else {
4516 $usercontext = get_context_instance(CONTEXT_USER, $user->id);
4519 if (empty($string)) { // Cache all the strings for the rest of the page
4521 $string->email = get_string('email');
4522 $string->city = get_string('city');
4523 $string->lastaccess = get_string('lastaccess');
4524 $string->activity = get_string('activity');
4525 $string->unenrol = get_string('unenrol');
4526 $string->loginas = get_string('loginas');
4527 $string->fullprofile = get_string('fullprofile');
4528 $string->role = get_string('role');
4529 $string->name = get_string('name');
4530 $string->never = get_string('never');
4532 $datestring->day = get_string('day');
4533 $datestring->days = get_string('days');
4534 $datestring->hour = get_string('hour');
4535 $datestring->hours = get_string('hours');
4536 $datestring->min = get_string('min');
4537 $datestring->mins = get_string('mins');
4538 $datestring->sec = get_string('sec');
4539 $datestring->secs = get_string('secs');
4540 $datestring->year = get_string('year');
4541 $datestring->years = get_string('years');
4543 $countries = get_list_of_countries();
4546 /// Get the hidden field list
4547 if (has_capability('moodle/course:viewhiddenuserfields', $context)) {
4548 $hiddenfields = array();
4549 } else {
4550 $hiddenfields = array_flip(explode(',', $CFG->hiddenuserfields));
4553 $output .= '<table class="userinfobox">';
4554 $output .= '<tr>';
4555 $output .= '<td class="left side">';
4556 $output .= print_user_picture($user, $course->id, $user->picture, true, true);
4557 $output .= '</td>';
4558 $output .= '<td class="content">';
4559 $output .= '<div class="username">'.fullname($user, has_capability('moodle/site:viewfullnames', $context)).'</div>';
4560 $output .= '<div class="info">';
4561 if (!empty($user->role) and ($user->role <> $course->teacher)) {
4562 $output .= $string->role .': '. $user->role .'<br />';
4564 if ($user->maildisplay == 1 or ($user->maildisplay == 2 and ($course->id != SITEID) and !isguest()) or
4565 has_capability('moodle/course:viewhiddenuserfields', $context)) {
4566 $output .= $string->email .': <a href="mailto:'. $user->email .'">'. $user->email .'</a><br />';
4568 if (($user->city or $user->country) and (!isset($hiddenfields['city']) or !isset($hiddenfields['country']))) {
4569 $output .= $string->city .': ';
4570 if ($user->city && !isset($hiddenfields['city'])) {
4571 $output .= $user->city;
4573 if (!empty($countries[$user->country]) && !isset($hiddenfields['country'])) {
4574 if ($user->city && !isset($hiddenfields['city'])) {
4575 $output .= ', ';
4577 $output .= $countries[$user->country];
4579 $output .= '<br />';
4582 if (!isset($hiddenfields['lastaccess'])) {
4583 if ($user->lastaccess) {
4584 $output .= $string->lastaccess .': '. userdate($user->lastaccess);
4585 $output .= '&nbsp; ('. format_time(time() - $user->lastaccess, $datestring) .')';
4586 } else {
4587 $output .= $string->lastaccess .': '. $string->never;
4590 $output .= '</div></td><td class="links">';
4591 //link to blogs
4592 if ($CFG->bloglevel > 0) {
4593 $output .= '<a href="'.$CFG->wwwroot.'/blog/index.php?userid='.$user->id.'">'.get_string('blogs','blog').'</a><br />';
4595 //link to notes
4596 if (!empty($CFG->enablenotes) and (has_capability('moodle/notes:manage', $context) || has_capability('moodle/notes:view', $context))) {
4597 $output .= '<a href="'.$CFG->wwwroot.'/notes/index.php?course=' . $course->id. '&amp;user='.$user->id.'">'.get_string('notes','notes').'</a><br />';
4600 if (has_capability('moodle/site:viewreports', $context) or has_capability('moodle/user:viewuseractivitiesreport', $usercontext)) {
4601 $output .= '<a href="'. $CFG->wwwroot .'/course/user.php?id='. $course->id .'&amp;user='. $user->id .'">'. $string->activity .'</a><br />';
4603 if (has_capability('moodle/role:assign', $context) and get_user_roles($context, $user->id, false)) { // I can unassing and user has some role
4604 $output .= '<a href="'. $CFG->wwwroot .'/course/unenrol.php?id='. $course->id .'&amp;user='. $user->id .'">'. $string->unenrol .'</a><br />';
4606 if ($USER->id != $user->id && empty($USER->realuser) && has_capability('moodle/user:loginas', $context) &&
4607 ! has_capability('moodle/site:doanything', $context, $user->id, false)) {
4608 $output .= '<a href="'. $CFG->wwwroot .'/course/loginas.php?id='. $course->id .'&amp;user='. $user->id .'&amp;sesskey='. sesskey() .'">'. $string->loginas .'</a><br />';
4610 $output .= '<a href="'. $CFG->wwwroot .'/user/view.php?id='. $user->id .'&amp;course='. $course->id .'">'. $string->fullprofile .'...</a>';
4612 if (!empty($messageselect)) {
4613 $output .= '<br /><input type="checkbox" name="user'.$user->id.'" /> ';
4616 $output .= '</td></tr></table>';
4618 if ($return) {
4619 return $output;
4620 } else {
4621 echo $output;
4626 * Print a specified group's avatar.
4628 * @param group $group A single {@link group} object OR array of groups.
4629 * @param int $courseid The course ID.
4630 * @param boolean $large Default small picture, or large.
4631 * @param boolean $return If false print picture, otherwise return the output as string
4632 * @param boolean $link Enclose image in a link to view specified course?
4633 * @return string
4634 * @todo Finish documenting this function
4636 function print_group_picture($group, $courseid, $large=false, $return=false, $link=true) {
4637 global $CFG;
4639 if (is_array($group)) {
4640 $output = '';
4641 foreach($group as $g) {
4642 $output .= print_group_picture($g, $courseid, $large, true, $link);
4644 if ($return) {
4645 return $output;
4646 } else {
4647 echo $output;
4648 return;
4652 $context = get_context_instance(CONTEXT_COURSE, $courseid);
4654 if ($group->hidepicture and !has_capability('moodle/course:managegroups', $context)) {
4655 return '';
4658 if ($link or has_capability('moodle/site:accessallgroups', $context)) {
4659 $output = '<a href="'. $CFG->wwwroot .'/user/index.php?id='. $courseid .'&amp;group='. $group->id .'">';
4660 } else {
4661 $output = '';
4663 if ($large) {
4664 $file = 'f1';
4665 } else {
4666 $file = 'f2';
4668 if ($group->picture) { // Print custom group picture
4669 require_once($CFG->libdir.'/filelib.php');
4670 $grouppictureurl = get_file_url($group->id.'/'.$file.'.jpg', null, 'usergroup');
4671 $output .= '<img class="grouppicture" src="'.$grouppictureurl.'"'.
4672 ' alt="'.s(get_string('group').' '.$group->name).'" title="'.s($group->name).'"/>';
4674 if ($link or has_capability('moodle/site:accessallgroups', $context)) {
4675 $output .= '</a>';
4678 if ($return) {
4679 return $output;
4680 } else {
4681 echo $output;
4686 * Print a png image.
4688 * @param string $url ?
4689 * @param int $sizex ?
4690 * @param int $sizey ?
4691 * @param boolean $return ?
4692 * @param string $parameters ?
4693 * @todo Finish documenting this function
4695 function print_png($url, $sizex, $sizey, $return, $parameters='alt=""') {
4696 global $CFG;
4697 static $recentIE;
4699 if (!isset($recentIE)) {
4700 $recentIE = check_browser_version('MSIE', '5.0');
4703 if ($recentIE) { // work around the HORRIBLE bug IE has with alpha transparencies
4704 $output .= '<img src="'. $CFG->pixpath .'/spacer.gif" width="'. $sizex .'" height="'. $sizey .'"'.
4705 ' class="png" style="width: '. $sizex .'px; height: '. $sizey .'px; '.
4706 ' filter: progid:DXImageTransform.Microsoft.AlphaImageLoader(src='.
4707 "'$url', sizingMethod='scale') ".
4708 ' '. $parameters .' />';
4709 } else {
4710 $output .= '<img src="'. $url .'" style="width: '. $sizex .'px; height: '. $sizey .'px; '. $parameters .' />';
4713 if ($return) {
4714 return $output;
4715 } else {
4716 echo $output;
4721 * Print a nicely formatted table.
4723 * @param array $table is an object with several properties.
4724 * <ul>
4725 * <li>$table->head - An array of heading names.
4726 * <li>$table->align - An array of column alignments
4727 * <li>$table->size - An array of column sizes
4728 * <li>$table->wrap - An array of "nowrap"s or nothing
4729 * <li>$table->data[] - An array of arrays containing the data.
4730 * <li>$table->width - A percentage of the page
4731 * <li>$table->tablealign - Align the whole table
4732 * <li>$table->cellpadding - Padding on each cell
4733 * <li>$table->cellspacing - Spacing between cells
4734 * <li>$table->class - class attribute to put on the table
4735 * <li>$table->id - id attribute to put on the table.
4736 * <li>$table->rowclass[] - classes to add to particular rows.
4737 * <li>$table->summary - Description of the contents for screen readers.
4738 * </ul>
4739 * @param bool $return whether to return an output string or echo now
4740 * @return boolean or $string
4741 * @todo Finish documenting this function
4743 function print_table($table, $return=false) {
4744 $output = '';
4746 if (isset($table->align)) {
4747 foreach ($table->align as $key => $aa) {
4748 if ($aa) {
4749 $align[$key] = ' text-align:'. fix_align_rtl($aa) .';'; // Fix for RTL languages
4750 } else {
4751 $align[$key] = '';
4755 if (isset($table->size)) {
4756 foreach ($table->size as $key => $ss) {
4757 if ($ss) {
4758 $size[$key] = ' width:'. $ss .';';
4759 } else {
4760 $size[$key] = '';
4764 if (isset($table->wrap)) {
4765 foreach ($table->wrap as $key => $ww) {
4766 if ($ww) {
4767 $wrap[$key] = ' white-space:nowrap;';
4768 } else {
4769 $wrap[$key] = '';
4774 if (empty($table->width)) {
4775 $table->width = '80%';
4778 if (empty($table->tablealign)) {
4779 $table->tablealign = 'center';
4782 if (!isset($table->cellpadding)) {
4783 $table->cellpadding = '5';
4786 if (!isset($table->cellspacing)) {
4787 $table->cellspacing = '1';
4790 if (empty($table->class)) {
4791 $table->class = 'generaltable';
4794 $tableid = empty($table->id) ? '' : 'id="'.$table->id.'"';
4796 $output .= '<table width="'.$table->width.'" ';
4797 if (!empty($table->summary)) {
4798 $output .= " summary=\"$table->summary\"";
4800 $output .= " cellpadding=\"$table->cellpadding\" cellspacing=\"$table->cellspacing\" class=\"$table->class boxalign$table->tablealign\" $tableid>\n";
4802 $countcols = 0;
4804 if (!empty($table->head)) {
4805 $countcols = count($table->head);
4806 $output .= '<tr>';
4807 $keys=array_keys($table->head);
4808 $lastkey = end($keys);
4809 foreach ($table->head as $key => $heading) {
4811 if (!isset($size[$key])) {
4812 $size[$key] = '';
4814 if (!isset($align[$key])) {
4815 $align[$key] = '';
4817 if ($key == $lastkey) {
4818 $extraclass = ' lastcol';
4819 } else {
4820 $extraclass = '';
4823 $output .= '<th style="vertical-align:top;'. $align[$key].$size[$key] .';white-space:nowrap;" class="header c'.$key.$extraclass.'" scope="col">'. $heading .'</th>';
4825 $output .= '</tr>'."\n";
4828 if (!empty($table->data)) {
4829 $oddeven = 1;
4830 $keys=array_keys($table->data);
4831 $lastrowkey = end($keys);
4832 foreach ($table->data as $key => $row) {
4833 $oddeven = $oddeven ? 0 : 1;
4834 if (!isset($table->rowclass[$key])) {
4835 $table->rowclass[$key] = '';
4837 if ($key == $lastrowkey) {
4838 $table->rowclass[$key] .= ' lastrow';
4840 $output .= '<tr class="r'.$oddeven.' '.$table->rowclass[$key].'">'."\n";
4841 if ($row == 'hr' and $countcols) {
4842 $output .= '<td colspan="'. $countcols .'"><div class="tabledivider"></div></td>';
4843 } else { /// it's a normal row of data
4844 $keys2=array_keys($row);
4845 $lastkey = end($keys2);
4846 foreach ($row as $key => $item) {
4847 if (!isset($size[$key])) {
4848 $size[$key] = '';
4850 if (!isset($align[$key])) {
4851 $align[$key] = '';
4853 if (!isset($wrap[$key])) {
4854 $wrap[$key] = '';
4856 if ($key == $lastkey) {
4857 $extraclass = ' lastcol';
4858 } else {
4859 $extraclass = '';
4861 $output .= '<td style="'. $align[$key].$size[$key].$wrap[$key] .'" class="cell c'.$key.$extraclass.'">'. $item .'</td>';
4864 $output .= '</tr>'."\n";
4867 $output .= '</table>'."\n";
4869 if ($return) {
4870 return $output;
4873 echo $output;
4874 return true;
4877 function print_recent_activity_note($time, $user, $text, $link, $return=false, $viewfullnames=null) {
4878 static $strftimerecent = null;
4879 $output = '';
4881 if (is_null($viewfullnames)) {
4882 $context = get_context_instance(CONTEXT_SYSTEM);
4883 $viewfullnames = has_capability('moodle/site:viewfullnames', $context);
4886 if (is_null($strftimerecent)) {
4887 $strftimerecent = get_string('strftimerecent');
4890 $output .= '<div class="head">';
4891 $output .= '<div class="date">'.userdate($time, $strftimerecent).'</div>';
4892 $output .= '<div class="name">'.fullname($user, $viewfullnames).'</div>';
4893 $output .= '</div>';
4894 $output .= '<div class="info"><a href="'.$link.'">'.format_string($text,true).'</a></div>';
4896 if ($return) {
4897 return $output;
4898 } else {
4899 echo $output;
4905 * Prints a basic textarea field.
4907 * When using this function, you should
4909 * @uses $CFG
4910 * @param bool $usehtmleditor Enables the use of the htmleditor for this field.
4911 * @param int $rows Number of rows to display (minimum of 10 when $height is non-null)
4912 * @param int $cols Number of columns to display (minimum of 65 when $width is non-null)
4913 * @param null $width (Deprecated) Width of the element; if a value is passed, the minimum value for $cols will be 65. Value is otherwise ignored.
4914 * @param null $height (Deprecated) Height of the element; if a value is passe, the minimum value for $rows will be 10. Value is otherwise ignored.
4915 * @param string $name Name to use for the textarea element.
4916 * @param string $value Initial content to display in the textarea.
4917 * @param int $obsolete deprecated
4918 * @param bool $return If false, will output string. If true, will return string value.
4919 * @param string $id CSS ID to add to the textarea element.
4920 * @param string $editorclass CSS classes to add to the textarea element when using the htmleditor. Use 'form-textarea-simple' to get a basic editor. Defaults to 'form-textarea-advanced' (complete editor). If this is null or invalid, the htmleditor will not show for this field.
4922 function print_textarea($usehtmleditor, $rows, $cols, $width, $height, $name, $value='', $obsolete=0, $return=false, $id='', $editorclass='form-textarea-advanced') {
4923 /// $width and height are legacy fields and no longer used as pixels like they used to be.
4924 /// However, you can set them to zero to override the mincols and minrows values below.
4926 global $CFG, $COURSE, $HTTPSPAGEREQUIRED, $THEME;
4928 $mincols = 65;
4929 $minrows = 10;
4930 $str = '';
4932 if ($id === '') {
4933 $id = 'edit-'.$name;
4936 if ( empty($CFG->editorsrc) && $usehtmleditor ) { // for backward compatibility.
4937 if ($height && ($rows < $minrows)) {
4938 $rows = $minrows;
4940 if ($width && ($cols < $mincols)) {
4941 $cols = $mincols;
4945 if ($usehtmleditor) {
4946 $THEME->htmleditors[] = $id;
4947 } else {
4948 $editorclass = '';
4951 $str .= "\n".'<textarea class="form-textarea '. $editorclass .'" id="'. $id .'" name="'. $name .'" rows="'. $rows .'" cols="'. $cols .'">'."\n";
4952 if ($usehtmleditor) {
4953 $str .= htmlspecialchars($value); // needed for editing of cleaned text!
4954 } else {
4955 $str .= s($value);
4957 $str .= '</textarea>'."\n";
4959 if ($usehtmleditor) {
4960 $str_toggle = '<span class="helplink"><a href="javascript:mce_toggleEditor(\''. $id .'\');"><img width="50" height="17" src="'. $CFG->httpswwwroot .'/lib/editor/tinymce/images/toggle.gif" alt="'. get_string('editortoggle') .'" title="'. get_string('editortoggle') .'" class="icontoggle" /></a></span>';
4961 // Show shortcuts button if HTML editor is in use, but only if JavaScript is enabled (MDL-9556)
4962 $str .= '<div class="textareaicons">';
4963 $str .= '<script type="text/javascript">
4964 //<![CDATA[
4965 if (window.mce_saveOnSubmit && window.mce_toggleEditor) {
4966 mce_saveOnSubmit(\''.addslashes_js($id).'\');
4967 document.write(\''.addslashes_js($str_toggle).'\');
4968 document.write(\''.addslashes_js(editorshortcutshelpbutton()).'\');
4970 //]]>
4971 </script>';
4972 $str .= '</div>';
4975 if ($return) {
4976 return $str;
4978 echo $str;
4982 * Returns a turn edit on/off button for course in a self contained form.
4983 * Used to be an icon, but it's now a simple form button
4985 * Note that the caller is responsible for capchecks.
4987 * @uses $CFG
4988 * @uses $USER
4989 * @param int $courseid The course to update by id as found in 'course' table
4990 * @return string
4992 function update_course_icon($courseid) {
4993 global $CFG, $USER;
4995 if (!empty($USER->editing)) {
4996 $string = get_string('turneditingoff');
4997 $edit = '0';
4998 } else {
4999 $string = get_string('turneditingon');
5000 $edit = '1';
5003 return '<form '.$CFG->frametarget.' method="get" action="'.$CFG->wwwroot.'/course/view.php">'.
5004 '<div>'.
5005 '<input type="hidden" name="id" value="'.$courseid.'" />'.
5006 '<input type="hidden" name="edit" value="'.$edit.'" />'.
5007 '<input type="hidden" name="sesskey" value="'.sesskey().'" />'.
5008 '<input type="submit" value="'.$string.'" />'.
5009 '</div></form>';
5013 * Returns a little popup menu for switching roles
5015 * @uses $CFG
5016 * @uses $USER
5017 * @param int $courseid The course to update by id as found in 'course' table
5018 * @return string
5020 function switchroles_form($courseid) {
5022 global $CFG, $USER;
5025 if (!$context = get_context_instance(CONTEXT_COURSE, $courseid)) {
5026 return '';
5029 if (!empty($USER->access['rsw'][$context->path])){ // Just a button to return to normal
5030 $options = array();
5031 $options['id'] = $courseid;
5032 $options['sesskey'] = sesskey();
5033 $options['switchrole'] = 0;
5035 return print_single_button($CFG->wwwroot.'/course/view.php', $options,
5036 get_string('switchrolereturn'), 'post', '_self', true);
5039 if (has_capability('moodle/role:switchroles', $context)) {
5040 if (!$roles = get_assignable_roles_for_switchrole($context)) {
5041 return ''; // Nothing to show!
5043 // unset default user role - it would not work
5044 unset($roles[$CFG->guestroleid]);
5045 return popup_form($CFG->wwwroot.'/course/view.php?id='.$courseid.'&amp;sesskey='.sesskey().'&amp;switchrole=',
5046 $roles, 'switchrole', '', get_string('switchroleto'), 'switchrole', get_string('switchroleto'), true);
5049 return '';
5054 * Returns a turn edit on/off button for course in a self contained form.
5055 * Used to be an icon, but it's now a simple form button
5057 * @uses $CFG
5058 * @uses $USER
5059 * @param int $courseid The course to update by id as found in 'course' table
5060 * @return string
5062 function update_mymoodle_icon() {
5064 global $CFG, $USER;
5066 if (!empty($USER->editing)) {
5067 $string = get_string('updatemymoodleoff');
5068 $edit = '0';
5069 } else {
5070 $string = get_string('updatemymoodleon');
5071 $edit = '1';
5074 return "<form $CFG->frametarget method=\"get\" action=\"$CFG->wwwroot/my/index.php\">".
5075 "<div>".
5076 "<input type=\"hidden\" name=\"edit\" value=\"$edit\" />".
5077 "<input type=\"submit\" value=\"$string\" /></div></form>";
5081 * Returns a turn edit on/off button for tag in a self contained form.
5083 * @uses $CFG
5084 * @uses $USER
5085 * @return string
5087 function update_tag_button($tagid) {
5089 global $CFG, $USER;
5091 if (!empty($USER->editing)) {
5092 $string = get_string('turneditingoff');
5093 $edit = '0';
5094 } else {
5095 $string = get_string('turneditingon');
5096 $edit = '1';
5099 return "<form $CFG->frametarget method=\"get\" action=\"$CFG->wwwroot/tag/index.php\">".
5100 "<div>".
5101 "<input type=\"hidden\" name=\"edit\" value=\"$edit\" />".
5102 "<input type=\"hidden\" name=\"id\" value=\"$tagid\" />".
5103 "<input type=\"submit\" value=\"$string\" /></div></form>";
5107 * Prints the editing button on a module "view" page
5109 * @uses $CFG
5110 * @param type description
5111 * @todo Finish documenting this function
5113 function update_module_button($moduleid, $courseid, $string) {
5114 global $CFG, $USER;
5116 if (has_capability('moodle/course:manageactivities', get_context_instance(CONTEXT_MODULE, $moduleid))) {
5117 $string = get_string('updatethis', '', $string);
5119 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
5120 "<div>".
5121 "<input type=\"hidden\" name=\"update\" value=\"$moduleid\" />".
5122 "<input type=\"hidden\" name=\"return\" value=\"true\" />".
5123 "<input type=\"hidden\" name=\"sesskey\" value=\"".sesskey()."\" />".
5124 "<input type=\"submit\" value=\"$string\" /></div></form>";
5125 } else {
5126 return '';
5131 * Prints the editing button on search results listing
5132 * For bulk move courses to another category
5135 function update_categories_search_button($search,$page,$perpage) {
5136 global $CFG, $USER;
5138 // not sure if this capability is the best here
5139 if (has_capability('moodle/category:manage', get_context_instance(CONTEXT_SYSTEM))) {
5140 if (!empty($USER->categoryediting)) {
5141 $string = get_string("turneditingoff");
5142 $edit = "off";
5143 $perpage = 30;
5144 } else {
5145 $string = get_string("turneditingon");
5146 $edit = "on";
5149 return "<form $CFG->frametarget method=\"get\" action=\"$CFG->wwwroot/course/search.php\">".
5150 '<div>'.
5151 "<input type=\"hidden\" name=\"edit\" value=\"$edit\" />".
5152 "<input type=\"hidden\" name=\"sesskey\" value=\"$USER->sesskey\" />".
5153 "<input type=\"hidden\" name=\"search\" value=\"".s($search, true)."\" />".
5154 "<input type=\"hidden\" name=\"page\" value=\"$page\" />".
5155 "<input type=\"hidden\" name=\"perpage\" value=\"$perpage\" />".
5156 "<input type=\"submit\" value=\"".s($string)."\" /></div></form>";
5161 * Given a course and a (current) coursemodule
5162 * This function returns a small popup menu with all the
5163 * course activity modules in it, as a navigation menu
5164 * The data is taken from the serialised array stored in
5165 * the course record
5167 * @param course $course A {@link $COURSE} object.
5168 * @param course $cm A {@link $COURSE} object.
5169 * @param string $targetwindow ?
5170 * @return string
5171 * @todo Finish documenting this function
5173 function navmenu($course, $cm=NULL, $targetwindow='self') {
5175 global $CFG, $THEME, $USER;
5177 if (empty($THEME->navmenuwidth)) {
5178 $width = 50;
5179 } else {
5180 $width = $THEME->navmenuwidth;
5183 if ($cm) {
5184 $cm = $cm->id;
5187 if ($course->format == 'weeks') {
5188 $strsection = get_string('week');
5189 } else {
5190 $strsection = get_string('topic');
5192 $strjumpto = get_string('jumpto');
5194 $modinfo = get_fast_modinfo($course);
5195 $context = get_context_instance(CONTEXT_COURSE, $course->id);
5197 $section = -1;
5198 $selected = '';
5199 $url = '';
5200 $previousmod = NULL;
5201 $backmod = NULL;
5202 $nextmod = NULL;
5203 $selectmod = NULL;
5204 $logslink = NULL;
5205 $flag = false;
5206 $menu = array();
5207 $menustyle = array();
5209 $sections = get_records('course_sections','course',$course->id,'section','section,visible,summary');
5211 if (!empty($THEME->makenavmenulist)) { /// A hack to produce an XHTML navmenu list for use in themes
5212 $THEME->navmenulist = navmenulist($course, $sections, $modinfo, $strsection, $strjumpto, $width, $cm);
5215 foreach ($modinfo->cms as $mod) {
5216 if ($mod->modname == 'label') {
5217 continue;
5220 if ($mod->sectionnum > $course->numsections) { /// Don't show excess hidden sections
5221 break;
5224 if (!$mod->uservisible) { // do not icnlude empty sections at all
5225 continue;
5228 if ($mod->sectionnum > 0 and $section != $mod->sectionnum) {
5229 $thissection = $sections[$mod->sectionnum];
5231 if ($thissection->visible or !$course->hiddensections or
5232 has_capability('moodle/course:viewhiddensections', $context)) {
5233 $thissection->summary = strip_tags(format_string($thissection->summary,true));
5234 if ($course->format == 'weeks' or empty($thissection->summary)) {
5235 $menu[] = '--'.$strsection ." ". $mod->sectionnum;
5236 } else {
5237 if (strlen($thissection->summary) < ($width-3)) {
5238 $menu[] = '--'.$thissection->summary;
5239 } else {
5240 $menu[] = '--'.substr($thissection->summary, 0, $width).'...';
5243 $section = $mod->sectionnum;
5244 } else {
5245 // no activities from this hidden section shown
5246 continue;
5250 $url = $mod->modname.'/view.php?id='. $mod->id;
5251 if ($flag) { // the current mod is the "next" mod
5252 $nextmod = $mod;
5253 $flag = false;
5255 $localname = $mod->name;
5256 if ($cm == $mod->id) {
5257 $selected = $url;
5258 $selectmod = $mod;
5259 $backmod = $previousmod;
5260 $flag = true; // set flag so we know to use next mod for "next"
5261 $localname = $strjumpto;
5262 $strjumpto = '';
5263 } else {
5264 $localname = strip_tags(format_string($localname,true));
5265 $tl=textlib_get_instance();
5266 if ($tl->strlen($localname) > ($width+5)) {
5267 $localname = $tl->substr($localname, 0, $width).'...';
5269 if (!$mod->visible) {
5270 $localname = '('.$localname.')';
5273 $menu[$url] = $localname;
5274 if (empty($THEME->navmenuiconshide)) {
5275 $menustyle[$url] = 'style="background-image: url('.$CFG->modpixpath.'/'.$mod->modname.'/icon.gif);"'; // Unfortunately necessary to do this here
5277 $previousmod = $mod;
5279 //Accessibility: added Alt text, replaced &gt; &lt; with 'silent' character and 'accesshide' text.
5281 if ($selectmod and has_capability('coursereport/log:view', $context)) {
5282 $logstext = get_string('alllogs');
5283 $logslink = '<li>'."\n".'<a title="'.$logstext.'" '.
5284 $CFG->frametarget.' onclick="this.target=\''.$CFG->framename.'\';"'.' href="'.
5285 $CFG->wwwroot.'/course/report/log/index.php?chooselog=1&amp;user=0&amp;date=0&amp;id='.
5286 $course->id.'&amp;modid='.$selectmod->id.'">'.
5287 '<img class="icon log" src="'.$CFG->pixpath.'/i/log.gif" alt="'.$logstext.'" /></a>'."\n".'</li>';
5290 if ($backmod) {
5291 $backtext= get_string('activityprev', 'access');
5292 $backmod = '<li><form action="'.$CFG->wwwroot.'/mod/'.$backmod->modname.'/view.php" '.$CFG->frametarget.' '.
5293 'onclick="this.target=\''.$CFG->framename.'\';"'.'><fieldset class="invisiblefieldset">'.
5294 '<input type="hidden" name="id" value="'.$backmod->id.'" />'.
5295 '<button type="submit" title="'.$backtext.'">'.link_arrow_left($backtext, $url='', $accesshide=true).
5296 '</button></fieldset></form></li>';
5298 if ($nextmod) {
5299 $nexttext= get_string('activitynext', 'access');
5300 $nextmod = '<li><form action="'.$CFG->wwwroot.'/mod/'.$nextmod->modname.'/view.php" '.$CFG->frametarget.' '.
5301 'onclick="this.target=\''.$CFG->framename.'\';"'.'><fieldset class="invisiblefieldset">'.
5302 '<input type="hidden" name="id" value="'.$nextmod->id.'" />'.
5303 '<button type="submit" title="'.$nexttext.'">'.link_arrow_right($nexttext, $url='', $accesshide=true).
5304 '</button></fieldset></form></li>';
5307 return '<div class="navigation">'."\n".'<ul>'.$logslink . $backmod .
5308 '<li>'.popup_form($CFG->wwwroot .'/mod/', $menu, 'navmenupopup', $selected, $strjumpto,
5309 '', '', true, $targetwindow, '', $menustyle).'</li>'.
5310 $nextmod . '</ul>'."\n".'</div>';
5314 * Given a course
5315 * This function returns a small popup menu with all the
5316 * course activity modules in it, as a navigation menu
5317 * outputs a simple list structure in XHTML
5318 * The data is taken from the serialised array stored in
5319 * the course record
5321 * @param course $course A {@link $COURSE} object.
5322 * @return string
5323 * @todo Finish documenting this function
5325 function navmenulist($course, $sections, $modinfo, $strsection, $strjumpto, $width=50, $cmid=0) {
5327 global $CFG;
5329 $section = -1;
5330 $url = '';
5331 $menu = array();
5332 $doneheading = false;
5334 $coursecontext = get_context_instance(CONTEXT_COURSE, $course->id);
5336 $menu[] = '<ul class="navmenulist"><li class="jumpto section"><span>'.$strjumpto.'</span><ul>';
5337 foreach ($modinfo->cms as $mod) {
5338 if ($mod->modname == 'label') {
5339 continue;
5342 if ($mod->sectionnum > $course->numsections) { /// Don't show excess hidden sections
5343 break;
5346 if (!$mod->uservisible) { // do not icnlude empty sections at all
5347 continue;
5350 if ($mod->sectionnum >= 0 and $section != $mod->sectionnum) {
5351 $thissection = $sections[$mod->sectionnum];
5353 if ($thissection->visible or !$course->hiddensections or
5354 has_capability('moodle/course:viewhiddensections', $coursecontext)) {
5355 $thissection->summary = strip_tags(format_string($thissection->summary,true));
5356 if (!$doneheading) {
5357 $menu[] = '</ul></li>';
5359 if ($course->format == 'weeks' or empty($thissection->summary)) {
5360 $item = $strsection ." ". $mod->sectionnum;
5361 } else {
5362 if (strlen($thissection->summary) < ($width-3)) {
5363 $item = $thissection->summary;
5364 } else {
5365 $item = substr($thissection->summary, 0, $width).'...';
5368 $menu[] = '<li class="section"><span>'.$item.'</span>';
5369 $menu[] = '<ul>';
5370 $doneheading = true;
5372 $section = $mod->sectionnum;
5373 } else {
5374 // no activities from this hidden section shown
5375 continue;
5379 $url = $mod->modname .'/view.php?id='. $mod->id;
5380 $mod->name = strip_tags(format_string(urldecode($mod->name),true));
5381 if (strlen($mod->name) > ($width+5)) {
5382 $mod->name = substr($mod->name, 0, $width).'...';
5384 if (!$mod->visible) {
5385 $mod->name = '('.$mod->name.')';
5387 $class = 'activity '.$mod->modname;
5388 $class .= ($cmid == $mod->id) ? ' selected' : '';
5389 $menu[] = '<li class="'.$class.'">'.
5390 '<img src="'.$CFG->modpixpath.'/'.$mod->modname.'/icon.gif" alt="" />'.
5391 '<a href="'.$CFG->wwwroot.'/mod/'.$url.'">'.$mod->name.'</a></li>';
5394 if ($doneheading) {
5395 $menu[] = '</ul></li>';
5397 $menu[] = '</ul></li></ul>';
5399 return implode("\n", $menu);
5403 * Prints form items with the names $day, $month and $year
5405 * @param string $day fieldname
5406 * @param string $month fieldname
5407 * @param string $year fieldname
5408 * @param int $currenttime A default timestamp in GMT
5409 * @param boolean $return
5411 function print_date_selector($day, $month, $year, $currenttime=0, $return=false) {
5413 if (!$currenttime) {
5414 $currenttime = time();
5416 $currentdate = usergetdate($currenttime);
5418 for ($i=1; $i<=31; $i++) {
5419 $days[$i] = $i;
5421 for ($i=1; $i<=12; $i++) {
5422 $months[$i] = userdate(gmmktime(12,0,0,$i,15,2000), "%B");
5424 for ($i=1970; $i<=2020; $i++) {
5425 $years[$i] = $i;
5428 // Build or print result
5429 $result='';
5430 // Note: There should probably be a fieldset around these fields as they are
5431 // clearly grouped. However this causes problems with display. See Mozilla
5432 // bug 474415
5433 $result.='<label class="accesshide" for="menu'.$day.'">'.get_string('day','form').'</label>';
5434 $result.=choose_from_menu($days, $day, $currentdate['mday'], '', '', '0', true);
5435 $result.='<label class="accesshide" for="menu'.$month.'">'.get_string('month','form').'</label>';
5436 $result.=choose_from_menu($months, $month, $currentdate['mon'], '', '', '0', true);
5437 $result.='<label class="accesshide" for="menu'.$year.'">'.get_string('year','form').'</label>';
5438 $result.=choose_from_menu($years, $year, $currentdate['year'], '', '', '0', true);
5440 if ($return) {
5441 return $result;
5442 } else {
5443 echo $result;
5448 *Prints form items with the names $hour and $minute
5450 * @param string $hour fieldname
5451 * @param string ? $minute fieldname
5452 * @param $currenttime A default timestamp in GMT
5453 * @param int $step minute spacing
5454 * @param boolean $return
5456 function print_time_selector($hour, $minute, $currenttime=0, $step=5, $return=false) {
5458 if (!$currenttime) {
5459 $currenttime = time();
5461 $currentdate = usergetdate($currenttime);
5462 if ($step != 1) {
5463 $currentdate['minutes'] = ceil($currentdate['minutes']/$step)*$step;
5465 for ($i=0; $i<=23; $i++) {
5466 $hours[$i] = sprintf("%02d",$i);
5468 for ($i=0; $i<=59; $i+=$step) {
5469 $minutes[$i] = sprintf("%02d",$i);
5472 // Build or print result
5473 $result='';
5474 // Note: There should probably be a fieldset around these fields as they are
5475 // clearly grouped. However this causes problems with display. See Mozilla
5476 // bug 474415
5477 $result.='<label class="accesshide" for="menu'.$hour.'">'.get_string('hour','form').'</label>';
5478 $result.=choose_from_menu($hours, $hour, $currentdate['hours'], '','','0',true);
5479 $result.='<label class="accesshide" for="menu'.$minute.'">'.get_string('minute','form').'</label>';
5480 $result.=choose_from_menu($minutes, $minute, $currentdate['minutes'], '','','0',true);
5482 if ($return) {
5483 return $result;
5484 } else {
5485 echo $result;
5490 * Prints time limit value selector
5492 * @uses $CFG
5493 * @param int $timelimit default
5494 * @param string $unit
5495 * @param string $name
5496 * @param boolean $return
5498 function print_timer_selector($timelimit = 0, $unit = '', $name = 'timelimit', $return=false) {
5500 global $CFG;
5502 if ($unit) {
5503 $unit = ' '.$unit;
5506 // Max timelimit is sessiontimeout - 10 minutes.
5507 $maxvalue = ($CFG->sessiontimeout / 60) - 10;
5509 for ($i=1; $i<=$maxvalue; $i++) {
5510 $minutes[$i] = $i.$unit;
5512 return choose_from_menu($minutes, $name, $timelimit, get_string('none'), '','','0',$return);
5516 * Prints a grade menu (as part of an existing form) with help
5517 * Showing all possible numerical grades and scales
5519 * @uses $CFG
5520 * @param int $courseid ?
5521 * @param string $name ?
5522 * @param string $current ?
5523 * @param boolean $includenograde ?
5524 * @todo Finish documenting this function
5526 function print_grade_menu($courseid, $name, $current, $includenograde=true, $return=false) {
5528 global $CFG;
5530 $output = '';
5531 $strscale = get_string('scale');
5532 $strscales = get_string('scales');
5534 $scales = get_scales_menu($courseid);
5535 foreach ($scales as $i => $scalename) {
5536 $grades[-$i] = $strscale .': '. $scalename;
5538 if ($includenograde) {
5539 $grades[0] = get_string('nograde');
5541 for ($i=100; $i>=1; $i--) {
5542 $grades[$i] = $i;
5544 $output .= choose_from_menu($grades, $name, $current, '', '', 0, true);
5546 $linkobject = '<span class="helplink"><img class="iconhelp" alt="'.$strscales.'" src="'.$CFG->pixpath .'/help.gif" /></span>';
5547 $output .= link_to_popup_window ('/course/scales.php?id='. $courseid .'&amp;list=true', 'ratingscales',
5548 $linkobject, 400, 500, $strscales, 'none', true);
5550 if ($return) {
5551 return $output;
5552 } else {
5553 echo $output;
5558 * Prints a scale menu (as part of an existing form) including help button
5559 * Just like {@link print_grade_menu()} but without the numeric grades
5561 * @param int $courseid ?
5562 * @param string $name ?
5563 * @param string $current ?
5564 * @todo Finish documenting this function
5566 function print_scale_menu($courseid, $name, $current, $return=false) {
5568 global $CFG;
5570 $output = '';
5571 $strscales = get_string('scales');
5572 $output .= choose_from_menu(get_scales_menu($courseid), $name, $current, '', '', 0, true);
5574 $linkobject = '<span class="helplink"><img class="iconhelp" alt="'.$strscales.'" src="'.$CFG->pixpath .'/help.gif" /></span>';
5575 $output .= link_to_popup_window ('/course/scales.php?id='. $courseid .'&amp;list=true', 'ratingscales',
5576 $linkobject, 400, 500, $strscales, 'none', true);
5577 if ($return) {
5578 return $output;
5579 } else {
5580 echo $output;
5585 * Prints a help button about a scale
5587 * @uses $CFG
5588 * @param id $courseid ?
5589 * @param object $scale ?
5590 * @todo Finish documenting this function
5592 function print_scale_menu_helpbutton($courseid, $scale, $return=false) {
5594 global $CFG;
5596 $output = '';
5597 $strscales = get_string('scales');
5599 $linkobject = '<span class="helplink"><img class="iconhelp" alt="'.$scale->name.'" src="'.$CFG->pixpath .'/help.gif" /></span>';
5600 $output .= link_to_popup_window ('/course/scales.php?id='. $courseid .'&amp;list=true&amp;scaleid='. $scale->id, 'ratingscale',
5601 $linkobject, 400, 500, $scale->name, 'none', true);
5602 if ($return) {
5603 return $output;
5604 } else {
5605 echo $output;
5610 * Print an error page displaying an error message. New method - use this for new code.
5612 * @uses $SESSION
5613 * @uses $CFG
5614 * @param string $errorcode The name of the string from error.php (or other specified file) to print
5615 * @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.
5616 * @param object $a Extra words and phrases that might be required in the error string
5617 * @param array $extralocations An array of strings with other locations to look for string files
5618 * @return does not return, terminates script
5620 function print_error($errorcode, $module='error', $link='', $a=NULL, $extralocations=NULL) {
5621 global $CFG, $SESSION, $THEME;
5623 if (empty($module) || $module === 'moodle' || $module === 'core') {
5624 $module = 'error';
5627 $message = get_string($errorcode, $module, $a, $extralocations);
5628 if ($module === 'error' and strpos($message, '[[') === 0) {
5629 //search in moodle file if error specified - needed for backwards compatibility
5630 $message = get_string($errorcode, 'moodle', $a, $extralocations);
5633 if (empty($link) and !defined('ADMIN_EXT_HEADER_PRINTED')) {
5634 if ( !empty($SESSION->fromurl) ) {
5635 $link = $SESSION->fromurl;
5636 unset($SESSION->fromurl);
5637 } else {
5638 $link = $CFG->wwwroot .'/';
5642 if (!empty($CFG->errordocroot)) {
5643 $errordocroot = $CFG->errordocroot;
5644 } else if (!empty($CFG->docroot)) {
5645 $errordocroot = $CFG->docroot;
5646 } else {
5647 $errordocroot = 'http://docs.moodle.org';
5650 if (defined('FULLME') && FULLME == 'cron') {
5651 // Errors in cron should be mtrace'd.
5652 mtrace($message);
5653 die;
5656 if ($module === 'error') {
5657 $modulelink = 'moodle';
5658 } else {
5659 $modulelink = $module;
5662 $message = clean_text('<p class="errormessage">'.$message.'</p>'.
5663 '<p class="errorcode">'.
5664 '<a href="'.$errordocroot.'/en/error/'.$modulelink.'/'.$errorcode.'">'.
5665 get_string('moreinformation').'</a></p>');
5667 if (! defined('HEADER_PRINTED')) {
5668 //header not yet printed
5669 @header('HTTP/1.0 404 Not Found');
5670 print_header(get_string('error'));
5671 } else {
5672 print_container_end_all(false, $THEME->open_header_containers);
5675 echo '<br />';
5677 print_simple_box($message, '', '', '', '', 'errorbox');
5679 debugging('Stack trace:', DEBUG_DEVELOPER);
5681 // in case we are logging upgrade in admin/index.php stop it
5682 if (function_exists('upgrade_log_finish')) {
5683 upgrade_log_finish();
5686 if (!empty($link)) {
5687 print_continue($link);
5690 print_footer();
5692 for ($i=0;$i<512;$i++) { // Padding to help IE work with 404
5693 echo ' ';
5695 die;
5699 * Print an error to STDOUT and exit with a non-zero code. For commandline scripts.
5700 * Default errorcode is 1.
5702 * Very useful for perl-like error-handling:
5704 * do_somethting() or mdie("Something went wrong");
5706 * @param string $msg Error message
5707 * @param integer $errorcode Error code to emit
5709 function mdie($msg='', $errorcode=1) {
5710 trigger_error($msg);
5711 exit($errorcode);
5715 * Returns a string of html with an image of a help icon linked to a help page on a number of help topics.
5716 * Should be used only with htmleditor or textarea.
5717 * @param mixed $helptopics variable amount of params accepted. Each param may be a string or an array of arguments for
5718 * helpbutton.
5719 * @return string
5721 function editorhelpbutton(){
5722 global $CFG, $SESSION;
5723 $items = func_get_args();
5724 $i = 1;
5725 $urlparams = array();
5726 $titles = array();
5727 foreach ($items as $item){
5728 if (is_array($item)){
5729 $urlparams[] = "keyword$i=".urlencode($item[0]);
5730 $urlparams[] = "title$i=".urlencode($item[1]);
5731 if (isset($item[2])){
5732 $urlparams[] = "module$i=".urlencode($item[2]);
5734 $titles[] = trim($item[1], ". \t");
5735 }elseif (is_string($item)){
5736 $urlparams[] = "button$i=".urlencode($item);
5737 switch ($item){
5738 case 'reading' :
5739 $titles[] = get_string("helpreading");
5740 break;
5741 case 'writing' :
5742 $titles[] = get_string("helpwriting");
5743 break;
5744 case 'questions' :
5745 $titles[] = get_string("helpquestions");
5746 break;
5747 case 'emoticons' :
5748 $titles[] = get_string("helpemoticons");
5749 break;
5750 case 'richtext' :
5751 $titles[] = get_string('helprichtext');
5752 break;
5753 case 'text' :
5754 $titles[] = get_string('helptext');
5755 break;
5756 default :
5757 error('Unknown help topic '.$item);
5760 $i++;
5762 if (count($titles)>1){
5763 //join last two items with an 'and'
5764 $a = new object();
5765 $a->one = $titles[count($titles) - 2];
5766 $a->two = $titles[count($titles) - 1];
5767 $titles[count($titles) - 2] = get_string('and', '', $a);
5768 unset($titles[count($titles) - 1]);
5770 $alttag = join (', ', $titles);
5772 $paramstring = join('&', $urlparams);
5773 $linkobject = '<img alt="'.$alttag.'" class="iconhelp" src="'.$CFG->pixpath .'/help.gif" />';
5774 return link_to_popup_window(s('/lib/form/editorhelp.php?'.$paramstring), 'popup', $linkobject, 400, 500, $alttag, 'none', true);
5778 * Print a help button.
5780 * @uses $CFG
5781 * @param string $page The keyword that defines a help page
5782 * @param string $title The title of links, rollover tips, alt tags etc
5783 * 'Help with' (or the language equivalent) will be prefixed and '...' will be stripped.
5784 * @param string $module Which module is the page defined in
5785 * @param mixed $image Use a help image for the link? (true/false/"both")
5786 * @param boolean $linktext If true, display the title next to the help icon.
5787 * @param string $text If defined then this text is used in the page, and
5788 * the $page variable is ignored.
5789 * @param boolean $return If true then the output is returned as a string, if false it is printed to the current page.
5790 * @param string $imagetext The full text for the helpbutton icon. If empty use default help.gif
5791 * @return string
5792 * @todo Finish documenting this function
5794 function helpbutton ($page, $title, $module='moodle', $image=true, $linktext=false, $text='', $return=false,
5795 $imagetext='') {
5796 global $CFG, $COURSE;
5798 //warning if ever $text parameter is used
5799 //$text option won't work properly because the text needs to be always cleaned and,
5800 // when cleaned... html tags always break, so it's unusable.
5801 if ( isset($text) && $text!='') {
5802 debugging('Warning: it\'s not recommended to use $text parameter in helpbutton ($page=' . $page . ', $module=' . $module . ') function', DEBUG_DEVELOPER);
5805 // fix for MDL-7734
5806 if (!empty($COURSE->lang)) {
5807 $forcelang = $COURSE->lang;
5808 } else {
5809 $forcelang = '';
5812 if ($module == '') {
5813 $module = 'moodle';
5816 if ($title == '' && $linktext == '') {
5817 debugging('Error in call to helpbutton function: at least one of $title and $linktext is required');
5820 // Warn users about new window for Accessibility
5821 $tooltip = get_string('helpprefix2', '', trim($title, ". \t")) .' ('.get_string('newwindow').')';
5823 $linkobject = '';
5825 if ($image) {
5826 if ($linktext) {
5827 // MDL-7469 If text link is displayed with help icon, change to alt to "help with this".
5828 $linkobject .= $title.'&nbsp;';
5829 $tooltip = get_string('helpwiththis');
5831 if ($imagetext) {
5832 $linkobject .= $imagetext;
5833 } else {
5834 $linkobject .= '<img class="iconhelp" alt="'.s(strip_tags($tooltip)).'" src="'.
5835 $CFG->pixpath .'/help.gif" />';
5837 } else {
5838 $linkobject .= $tooltip;
5841 // fix for MDL-7734
5842 if ($text) {
5843 $url = '/help.php?module='. $module .'&amp;text='. s(urlencode($text).'&amp;forcelang='.$forcelang);
5844 } else {
5845 $url = '/help.php?module='. $module .'&amp;file='. $page .'.html&amp;forcelang='.$forcelang;
5848 $link = '<span class="helplink">'.
5849 link_to_popup_window ($url, 'popup', $linkobject, 400, 500, $tooltip, 'none', true).
5850 '</span>';
5852 if ($return) {
5853 return $link;
5854 } else {
5855 echo $link;
5860 * Print a help button.
5862 * Prints a special help button that is a link to the "live" emoticon popup
5863 * @uses $CFG
5864 * @uses $SESSION
5865 * @param string $form ?
5866 * @param string $field ?
5867 * @todo Finish documenting this function
5869 function emoticonhelpbutton($form, $field, $return = false) {
5871 global $CFG, $SESSION;
5873 $SESSION->inserttextform = $form;
5874 $SESSION->inserttextfield = $field;
5875 $imagetext = '<img src="' . $CFG->pixpath . '/s/smiley.gif" alt="" class="emoticon" style="margin-left:3px; padding-right:1px;width:15px;height:15px;" />';
5876 $help = helpbutton('emoticons', get_string('helpemoticons'), 'moodle', true, true, '', true, $imagetext);
5877 if (!$return){
5878 echo $help;
5879 } else {
5880 return $help;
5885 * Print a help button.
5887 * Prints a special help button for html editors (htmlarea in this case)
5888 * @uses $CFG
5890 function editorshortcutshelpbutton() {
5892 global $CFG;
5893 $imagetext = '<img src="' . $CFG->httpswwwroot . '/lib/editor/htmlarea/images/kbhelp.gif" alt="'.
5894 get_string('editorshortcutkeys').'" class="iconkbhelp" />';
5896 return helpbutton('editorshortcuts', get_string('editorshortcutkeys'), 'moodle', true, false, '', true, $imagetext);
5900 * Print a message and exit.
5902 * @uses $CFG
5903 * @param string $message ?
5904 * @param string $link ?
5905 * @todo Finish documenting this function
5907 function notice ($message, $link='', $course=NULL) {
5908 global $CFG, $SITE, $THEME, $COURSE;
5910 $message = clean_text($message); // In case nasties are in here
5912 if (defined('FULLME') && FULLME == 'cron') {
5913 // notices in cron should be mtrace'd.
5914 mtrace($message);
5915 die;
5918 if (! defined('HEADER_PRINTED')) {
5919 //header not yet printed
5920 print_header(get_string('notice'));
5921 } else {
5922 print_container_end_all(false, $THEME->open_header_containers);
5925 print_box($message, 'generalbox', 'notice');
5926 print_continue($link);
5928 if (empty($course)) {
5929 print_footer($COURSE);
5930 } else {
5931 print_footer($course);
5933 exit;
5937 * Print a message along with "Yes" and "No" links for the user to continue.
5939 * @param string $message The text to display
5940 * @param string $linkyes The link to take the user to if they choose "Yes"
5941 * @param string $linkno The link to take the user to if they choose "No"
5942 * TODO Document remaining arguments
5944 function notice_yesno ($message, $linkyes, $linkno, $optionsyes=NULL, $optionsno=NULL, $methodyes='post', $methodno='post') {
5946 global $CFG;
5948 $message = clean_text($message);
5949 $linkyes = clean_text($linkyes);
5950 $linkno = clean_text($linkno);
5952 print_box_start('generalbox', 'notice');
5953 echo '<p>'. $message .'</p>';
5954 echo '<div class="buttons">';
5955 print_single_button($linkyes, $optionsyes, get_string('yes'), $methodyes, $CFG->framename);
5956 print_single_button($linkno, $optionsno, get_string('no'), $methodno, $CFG->framename);
5957 echo '</div>';
5958 print_box_end();
5962 * Provide an definition of error_get_last for PHP before 5.2.0. This simply
5963 * returns NULL, since there is not way to get the right answer.
5965 if (!function_exists('error_get_last')) {
5966 // the eval is needed to prevent PHP 5.2+ from getting a parse error!
5967 eval('
5968 function error_get_last() {
5969 return NULL;
5975 * Redirects the user to another page, after printing a notice
5977 * @param string $url The url to take the user to
5978 * @param string $message The text message to display to the user about the redirect, if any
5979 * @param string $delay How long before refreshing to the new page at $url?
5980 * @todo '&' needs to be encoded into '&amp;' for XHTML compliance,
5981 * however, this is not true for javascript. Therefore we
5982 * first decode all entities in $url (since we cannot rely on)
5983 * the correct input) and then encode for where it's needed
5984 * echo "<script type='text/javascript'>alert('Redirect $url');</script>";
5986 function redirect($url, $message='', $delay=-1) {
5988 global $CFG, $THEME;
5990 if (!empty($CFG->usesid) && !isset($_COOKIE[session_name()])) {
5991 $url = sid_process_url($url);
5994 $message = clean_text($message);
5996 $encodedurl = preg_replace("/\&(?![a-zA-Z0-9#]{1,8};)/", "&amp;", $url);
5997 $encodedurl = preg_replace('/^.*href="([^"]*)".*$/', "\\1", clean_text('<a href="'.$encodedurl.'" />'));
5998 $url = str_replace('&amp;', '&', $encodedurl);
6000 /// At developer debug level. Don't redirect if errors have been printed on screen.
6001 /// Currenly only works in PHP 5.2+; we do not want strict PHP5 errors
6002 $lasterror = error_get_last();
6003 $error = defined('DEBUGGING_PRINTED') or (!empty($lasterror) && ($lasterror['type'] & DEBUG_DEVELOPER));
6004 $errorprinted = debugging('', DEBUG_ALL) && $CFG->debugdisplay && $error;
6005 if ($errorprinted) {
6006 $message = "<strong>Error output, so disabling automatic redirect.</strong></p><p>" . $message;
6009 $performanceinfo = '';
6010 if (defined('MDL_PERF') || (!empty($CFG->perfdebug) and $CFG->perfdebug > 7)) {
6011 if (defined('MDL_PERFTOLOG') && !function_exists('register_shutdown_function')) {
6012 $perf = get_performance_info();
6013 error_log("PERF: " . $perf['txt']);
6017 /// when no message and header printed yet, try to redirect
6018 if (empty($message) and !defined('HEADER_PRINTED')) {
6020 // Technically, HTTP/1.1 requires Location: header to contain
6021 // the absolute path. (In practice browsers accept relative
6022 // paths - but still, might as well do it properly.)
6023 // This code turns relative into absolute.
6024 if (!preg_match('|^[a-z]+:|', $url)) {
6025 // Get host name http://www.wherever.com
6026 $hostpart = preg_replace('|^(.*?[^:/])/.*$|', '$1', $CFG->wwwroot);
6027 if (preg_match('|^/|', $url)) {
6028 // URLs beginning with / are relative to web server root so we just add them in
6029 $url = $hostpart.$url;
6030 } else {
6031 // URLs not beginning with / are relative to path of current script, so add that on.
6032 $url = $hostpart.preg_replace('|\?.*$|','',me()).'/../'.$url;
6034 // Replace all ..s
6035 while (true) {
6036 $newurl = preg_replace('|/(?!\.\.)[^/]*/\.\./|', '/', $url);
6037 if ($newurl == $url) {
6038 break;
6040 $url = $newurl;
6044 $delay = 0;
6045 //try header redirection first
6046 @header($_SERVER['SERVER_PROTOCOL'] . ' 303 See Other'); //302 might not work for POST requests, 303 is ignored by obsolete clients
6047 @header('Location: '.$url);
6048 //another way for older browsers and already sent headers (eg trailing whitespace in config.php)
6049 echo '<meta http-equiv="refresh" content="'. $delay .'; url='. $encodedurl .'" />';
6050 echo '<script type="text/javascript">'. "\n" .'//<![CDATA['. "\n". "location.replace('".addslashes_js($url)."');". "\n". '//]]>'. "\n". '</script>'; // To cope with Mozilla bug
6051 die;
6054 if ($delay == -1) {
6055 $delay = 3; // if no delay specified wait 3 seconds
6057 if (! defined('HEADER_PRINTED')) {
6058 // this type of redirect might not be working in some browsers - such as lynx :-(
6059 print_header('', '', '', '', $errorprinted ? '' : ('<meta http-equiv="refresh" content="'. $delay .'; url='. $encodedurl .'" />'));
6060 $delay += 3; // double redirect prevention, it was sometimes breaking upgrades before 1.7
6061 } else {
6062 print_container_end_all(false, $THEME->open_header_containers);
6064 echo '<div id="redirect">';
6065 echo '<div id="message">' . $message . '</div>';
6066 echo '<div id="continue">( <a href="'. $encodedurl .'">'. get_string('continue') .'</a> )</div>';
6067 echo '</div>';
6069 if (!$errorprinted) {
6071 <script type="text/javascript">
6072 //<![CDATA[
6074 function redirect() {
6075 document.location.replace('<?php echo addslashes_js($url) ?>');
6077 setTimeout("redirect()", <?php echo ($delay * 1000) ?>);
6078 //]]>
6079 </script>
6080 <?php
6083 $CFG->docroot = false; // to prevent the link to moodle docs from being displayed on redirect page.
6084 print_footer('none');
6085 die;
6089 * Print a bold message in an optional color.
6091 * @param string $message The message to print out
6092 * @param string $style Optional style to display message text in
6093 * @param string $align Alignment option
6094 * @param bool $return whether to return an output string or echo now
6096 function notify($message, $style='notifyproblem', $align='center', $return=false) {
6097 if ($style == 'green') {
6098 $style = 'notifysuccess'; // backward compatible with old color system
6101 $message = clean_text($message);
6103 $output = '<div class="'.$style.'" style="text-align:'. $align .'">'. $message .'</div>'."\n";
6105 if ($return) {
6106 return $output;
6108 echo $output;
6113 * Given an email address, this function will return an obfuscated version of it
6115 * @param string $email The email address to obfuscate
6116 * @return string
6118 function obfuscate_email($email) {
6120 $i = 0;
6121 $length = strlen($email);
6122 $obfuscated = '';
6123 while ($i < $length) {
6124 if (rand(0,2)) {
6125 $obfuscated.='%'.dechex(ord($email{$i}));
6126 } else {
6127 $obfuscated.=$email{$i};
6129 $i++;
6131 return $obfuscated;
6135 * This function takes some text and replaces about half of the characters
6136 * with HTML entity equivalents. Return string is obviously longer.
6138 * @param string $plaintext The text to be obfuscated
6139 * @return string
6141 function obfuscate_text($plaintext) {
6143 $i=0;
6144 $length = strlen($plaintext);
6145 $obfuscated='';
6146 $prev_obfuscated = false;
6147 while ($i < $length) {
6148 $c = ord($plaintext{$i});
6149 $numerical = ($c >= ord('0')) && ($c <= ord('9'));
6150 if ($prev_obfuscated and $numerical ) {
6151 $obfuscated.='&#'.ord($plaintext{$i}).';';
6152 } else if (rand(0,2)) {
6153 $obfuscated.='&#'.ord($plaintext{$i}).';';
6154 $prev_obfuscated = true;
6155 } else {
6156 $obfuscated.=$plaintext{$i};
6157 $prev_obfuscated = false;
6159 $i++;
6161 return $obfuscated;
6165 * This function uses the {@link obfuscate_email()} and {@link obfuscate_text()}
6166 * to generate a fully obfuscated email link, ready to use.
6168 * @param string $email The email address to display
6169 * @param string $label The text to dispalyed as hyperlink to $email
6170 * @param boolean $dimmed If true then use css class 'dimmed' for hyperlink
6171 * @return string
6173 function obfuscate_mailto($email, $label='', $dimmed=false) {
6175 if (empty($label)) {
6176 $label = $email;
6178 if ($dimmed) {
6179 $title = get_string('emaildisable');
6180 $dimmed = ' class="dimmed"';
6181 } else {
6182 $title = '';
6183 $dimmed = '';
6185 return sprintf("<a href=\"%s:%s\" $dimmed title=\"$title\">%s</a>",
6186 obfuscate_text('mailto'), obfuscate_email($email),
6187 obfuscate_text($label));
6191 * Prints a single paging bar to provide access to other pages (usually in a search)
6193 * @param int $totalcount Thetotal number of entries available to be paged through
6194 * @param int $page The page you are currently viewing
6195 * @param int $perpage The number of entries that should be shown per page
6196 * @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.
6197 * If this is a moodle_url object then the pagevar param will be replaced by the page no, for each page.
6198 * @param string $pagevar This is the variable name that you use for the page number in your code (ie. 'tablepage', 'blogpage', etc)
6199 * @param bool $nocurr do not display the current page as a link
6200 * @param bool $return whether to return an output string or echo now
6201 * @return bool or string
6203 function print_paging_bar($totalcount, $page, $perpage, $baseurl, $pagevar='page',$nocurr=false, $return=false) {
6204 $maxdisplay = 18;
6205 $output = '';
6207 if ($totalcount > $perpage) {
6208 $output .= '<div class="paging">';
6209 $output .= get_string('page') .':';
6210 if ($page > 0) {
6211 $pagenum = $page - 1;
6212 if (!is_a($baseurl, 'moodle_url')){
6213 $output .= '&nbsp;(<a class="previous" href="'. $baseurl . $pagevar .'='. $pagenum .'">'. get_string('previous') .'</a>)&nbsp;';
6214 } else {
6215 $output .= '&nbsp;(<a class="previous" href="'. $baseurl->out(false, array($pagevar => $pagenum)).'">'. get_string('previous') .'</a>)&nbsp;';
6218 if ($perpage > 0) {
6219 $lastpage = ceil($totalcount / $perpage);
6220 } else {
6221 $lastpage = 1;
6223 if ($page > 15) {
6224 $startpage = $page - 10;
6225 if (!is_a($baseurl, 'moodle_url')){
6226 $output .= '&nbsp;<a href="'. $baseurl . $pagevar .'=0">1</a>&nbsp;...';
6227 } else {
6228 $output .= '&nbsp;<a href="'. $baseurl->out(false, array($pagevar => 0)).'">1</a>&nbsp;...';
6230 } else {
6231 $startpage = 0;
6233 $currpage = $startpage;
6234 $displaycount = $displaypage = 0;
6235 while ($displaycount < $maxdisplay and $currpage < $lastpage) {
6236 $displaypage = $currpage+1;
6237 if ($page == $currpage && empty($nocurr)) {
6238 $output .= '&nbsp;&nbsp;'. $displaypage;
6239 } else {
6240 if (!is_a($baseurl, 'moodle_url')){
6241 $output .= '&nbsp;&nbsp;<a href="'. $baseurl . $pagevar .'='. $currpage .'">'. $displaypage .'</a>';
6242 } else {
6243 $output .= '&nbsp;&nbsp;<a href="'. $baseurl->out(false, array($pagevar => $currpage)).'">'. $displaypage .'</a>';
6247 $displaycount++;
6248 $currpage++;
6250 if ($currpage < $lastpage) {
6251 $lastpageactual = $lastpage - 1;
6252 if (!is_a($baseurl, 'moodle_url')){
6253 $output .= '&nbsp;...<a href="'. $baseurl . $pagevar .'='. $lastpageactual .'">'. $lastpage .'</a>&nbsp;';
6254 } else {
6255 $output .= '&nbsp;...<a href="'. $baseurl->out(false, array($pagevar => $lastpageactual)).'">'. $lastpage .'</a>&nbsp;';
6258 $pagenum = $page + 1;
6259 if ($pagenum != $displaypage) {
6260 if (!is_a($baseurl, 'moodle_url')){
6261 $output .= '&nbsp;&nbsp;(<a class="next" href="'. $baseurl . $pagevar .'='. $pagenum .'">'. get_string('next') .'</a>)';
6262 } else {
6263 $output .= '&nbsp;&nbsp;(<a class="next" href="'. $baseurl->out(false, array($pagevar => $pagenum)) .'">'. get_string('next') .'</a>)';
6266 $output .= '</div>';
6269 if ($return) {
6270 return $output;
6273 echo $output;
6274 return true;
6278 * This function is used to rebuild the <nolink> tag because some formats (PLAIN and WIKI)
6279 * will transform it to html entities
6281 * @param string $text Text to search for nolink tag in
6282 * @return string
6284 function rebuildnolinktag($text) {
6286 $text = preg_replace('/&lt;(\/*nolink)&gt;/i','<$1>',$text);
6288 return $text;
6292 * Prints a nice side block with an optional header. The content can either
6293 * be a block of HTML or a list of text with optional icons.
6295 * @param string $heading Block $title embedded in HTML tags, for example <h2>.
6296 * @param string $content ?
6297 * @param array $list ?
6298 * @param array $icons ?
6299 * @param string $footer ?
6300 * @param array $attributes ?
6301 * @param string $title Plain text title, as embedded in the $heading.
6302 * @todo Finish documenting this function. Show example of various attributes, etc.
6304 function print_side_block($heading='', $content='', $list=NULL, $icons=NULL, $footer='', $attributes = array(), $title='') {
6306 //Accessibility: skip block link, with title-text (or $block_id) to differentiate links.
6307 static $block_id = 0;
6308 $block_id++;
6309 $skip_text = get_string('skipa', 'access', strip_tags($title));
6310 $skip_link = '<a href="#sb-'.$block_id.'" class="skip-block">'.$skip_text.'</a>';
6311 $skip_dest = '<span id="sb-'.$block_id.'" class="skip-block-to"></span>';
6313 $strip_title = strip_tags($title);
6314 if (! empty($strip_title)) {
6315 echo $skip_link;
6317 //ELSE: a single link on a page "Skip block 4" is too confusing - ignore.
6319 print_side_block_start($heading, $attributes);
6321 if ($content) {
6322 echo $content;
6323 if ($footer) {
6324 echo '<div class="footer">'. $footer .'</div>';
6326 } else {
6327 if ($list) {
6328 $row = 0;
6329 //Accessibility: replaced unnecessary table with list, see themes/standard/styles_layout.css
6330 echo "\n<ul class='list'>\n";
6331 foreach ($list as $key => $string) {
6332 echo '<li class="r'. $row .'">';
6333 if ($icons) {
6334 echo '<div class="icon column c0">'. $icons[$key] .'</div>';
6336 echo '<div class="column c1">'. $string .'</div>';
6337 echo "</li>\n";
6338 $row = $row ? 0:1;
6340 echo "</ul>\n";
6342 if ($footer) {
6343 echo '<div class="footer">'. $footer .'</div>';
6348 print_side_block_end($attributes, $title);
6349 echo $skip_dest;
6353 * Starts a nice side block with an optional header.
6355 * @param string $heading ?
6356 * @param array $attributes ?
6357 * @todo Finish documenting this function
6359 function print_side_block_start($heading='', $attributes = array()) {
6361 global $CFG, $THEME;
6363 // If there are no special attributes, give a default CSS class
6364 if (empty($attributes) || !is_array($attributes)) {
6365 $attributes = array('class' => 'sideblock');
6367 } else if(!isset($attributes['class'])) {
6368 $attributes['class'] = 'sideblock';
6370 } else if(!strpos($attributes['class'], 'sideblock')) {
6371 $attributes['class'] .= ' sideblock';
6374 // OK, the class is surely there and in addition to anything
6375 // else, it's tagged as a sideblock
6379 // IE misery: if I do it this way, blocks which start hidden cannot be "unhidden"
6381 // If there is a cookie to hide this thing, start it hidden
6382 if (!empty($attributes['id']) && isset($_COOKIE['hide:'.$attributes['id']])) {
6383 $attributes['class'] = 'hidden '.$attributes['class'];
6387 $attrtext = '';
6388 foreach ($attributes as $attr => $val) {
6389 $attrtext .= ' '.$attr.'="'.$val.'"';
6392 echo '<div '.$attrtext.'>';
6394 if (!empty($THEME->customcorners)) {
6395 echo '<div class="wrap">'."\n";
6397 if ($heading) {
6398 //Accessibility: H2 more appropriate in moodleblock.class.php: _title_html.
6399 echo '<div class="header">';
6400 if (!empty($THEME->customcorners)) {
6401 echo '<div class="bt"><div>&nbsp;</div></div>';
6402 echo '<div class="i1"><div class="i2">';
6403 echo '<div class="i3">';
6405 echo $heading;
6406 if (!empty($THEME->customcorners)) {
6407 echo '</div></div></div>';
6409 echo '</div>';
6410 } else {
6411 if (!empty($THEME->customcorners)) {
6412 echo '<div class="bt"><div>&nbsp;</div></div>';
6416 if (!empty($THEME->customcorners)) {
6417 echo '<div class="i1"><div class="i2">';
6418 echo '<div class="i3">';
6420 echo '<div class="content">';
6426 * Print table ending tags for a side block box.
6428 function print_side_block_end($attributes = array(), $title='') {
6429 global $CFG, $THEME;
6431 echo '</div>';
6433 if (!empty($THEME->customcorners)) {
6434 echo '</div></div></div><div class="bb"><div>&nbsp;</div></div></div>';
6437 echo '</div>';
6439 $strshow = addslashes_js(get_string('showblocka', 'access', strip_tags($title)));
6440 $strhide = addslashes_js(get_string('hideblocka', 'access', strip_tags($title)));
6442 // IE workaround: if I do it THIS way, it works! WTF?
6443 if (!empty($CFG->allowuserblockhiding) && isset($attributes['id'])) {
6444 echo '<script type="text/javascript">'."\n//<![CDATA[\n".'elementCookieHide("'.$attributes['id'].
6445 '","'.$strshow.'","'.$strhide."\");\n//]]>\n".'</script>';
6452 * Prints out code needed for spellchecking.
6453 * Original idea by Ludo (Marc Alier).
6455 * Opening CDATA and <script> are output by weblib::use_html_editor()
6456 * @uses $CFG
6457 * @param boolean $usehtmleditor Normally set by $CFG->htmleditor, can be overriden here
6458 * @param boolean $return If false, echos the code instead of returning it
6459 * @todo Find out if lib/editor/htmlarea/htmlarea.class.php::print_speller_code() is still used, and delete if not
6461 function print_speller_code ($usehtmleditor=false, $return=false) {
6462 global $CFG;
6463 $str = '';
6465 if(!$usehtmleditor) {
6466 $str .= 'function openSpellChecker() {'."\n";
6467 $str .= "\tvar speller = new spellChecker();\n";
6468 $str .= "\tspeller.popUpUrl = \"" . $CFG->httpswwwroot ."/lib/speller/spellchecker.html\";\n";
6469 $str .= "\tspeller.spellCheckScript = \"". $CFG->httpswwwroot ."/lib/speller/server-scripts/spellchecker.php\";\n";
6470 $str .= "\tspeller.spellCheckAll();\n";
6471 $str .= '}'."\n";
6472 } else {
6473 $str .= "function spellClickHandler(editor, buttonId) {\n";
6474 $str .= "\teditor._textArea.value = editor.getHTML();\n";
6475 $str .= "\tvar speller = new spellChecker( editor._textArea );\n";
6476 $str .= "\tspeller.popUpUrl = \"" . $CFG->httpswwwroot ."/lib/speller/spellchecker.html\";\n";
6477 $str .= "\tspeller.spellCheckScript = \"". $CFG->httpswwwroot ."/lib/speller/server-scripts/spellchecker.php\";\n";
6478 $str .= "\tspeller._moogle_edit=1;\n";
6479 $str .= "\tspeller._editor=editor;\n";
6480 $str .= "\tspeller.openChecker();\n";
6481 $str .= '}'."\n";
6484 if ($return) {
6485 return $str;
6487 echo $str;
6491 * Print button for spellchecking when editor is disabled
6493 function print_speller_button () {
6494 echo '<input type="button" value="Check spelling" onclick="openSpellChecker();" />'."\n";
6498 function page_id_and_class(&$getid, &$getclass) {
6499 // Create class and id for this page
6500 global $CFG, $ME;
6502 static $class = NULL;
6503 static $id = NULL;
6505 if (empty($CFG->pagepath)) {
6506 $CFG->pagepath = $ME;
6509 if (empty($class) || empty($id)) {
6510 $path = str_replace($CFG->httpswwwroot.'/', '', $CFG->pagepath); //Because the page could be HTTPSPAGEREQUIRED
6511 $path = str_replace('.php', '', $path);
6512 if (substr($path, -1) == '/') {
6513 $path .= 'index';
6515 if (empty($path) || $path == 'index') {
6516 $id = 'site-index';
6517 $class = 'course';
6518 } else if (substr($path, 0, 5) == 'admin') {
6519 $id = str_replace('/', '-', $path);
6520 $class = 'admin';
6521 } else {
6522 $id = str_replace('/', '-', $path);
6523 $class = explode('-', $id);
6524 array_pop($class);
6525 $class = implode('-', $class);
6529 $getid = $id;
6530 $getclass = $class;
6534 * Prints a maintenance message from /maintenance.html
6536 function print_maintenance_message () {
6537 global $CFG, $SITE;
6539 $CFG->pagepath = "index.php";
6540 print_header(strip_tags($SITE->fullname), $SITE->fullname, 'home');
6541 print_box_start();
6542 print_heading(get_string('sitemaintenance', 'admin'));
6543 @include($CFG->dataroot.'/'.SITEID.'/maintenance.html');
6544 print_box_end();
6545 print_footer();
6549 * Adjust the list of allowed tags based on $CFG->allowobjectembed and user roles (admin)
6551 function adjust_allowed_tags() {
6553 global $CFG, $ALLOWED_TAGS;
6555 if (!empty($CFG->allowobjectembed)) {
6556 $ALLOWED_TAGS .= '<embed><object>';
6560 /// Some code to print tabs
6562 /// A class for tabs
6563 class tabobject {
6564 var $id;
6565 var $link;
6566 var $text;
6567 var $linkedwhenselected;
6569 /// A constructor just because I like constructors
6570 function tabobject ($id, $link='', $text='', $title='', $linkedwhenselected=false) {
6571 $this->id = $id;
6572 $this->link = $link;
6573 $this->text = $text;
6574 $this->title = $title ? $title : $text;
6575 $this->linkedwhenselected = $linkedwhenselected;
6582 * Returns a string containing a nested list, suitable for formatting into tabs with CSS.
6584 * @param array $tabrows An array of rows where each row is an array of tab objects
6585 * @param string $selected The id of the selected tab (whatever row it's on)
6586 * @param array $inactive An array of ids of inactive tabs that are not selectable.
6587 * @param array $activated An array of ids of other tabs that are currently activated
6589 function print_tabs($tabrows, $selected=NULL, $inactive=NULL, $activated=NULL, $return=false) {
6590 global $CFG;
6592 /// $inactive must be an array
6593 if (!is_array($inactive)) {
6594 $inactive = array();
6597 /// $activated must be an array
6598 if (!is_array($activated)) {
6599 $activated = array();
6602 /// Convert the tab rows into a tree that's easier to process
6603 if (!$tree = convert_tabrows_to_tree($tabrows, $selected, $inactive, $activated)) {
6604 return false;
6607 /// Print out the current tree of tabs (this function is recursive)
6609 $output = convert_tree_to_html($tree);
6611 $output = "\n\n".'<div class="tabtree">'.$output.'</div><div class="clearer"> </div>'."\n\n";
6613 /// We're done!
6615 if ($return) {
6616 return $output;
6618 echo $output;
6622 function convert_tree_to_html($tree, $row=0) {
6624 $str = "\n".'<ul class="tabrow'.$row.'">'."\n";
6626 $first = true;
6627 $count = count($tree);
6629 foreach ($tree as $tab) {
6630 $count--; // countdown to zero
6632 $liclass = '';
6634 if ($first && ($count == 0)) { // Just one in the row
6635 $liclass = 'first last';
6636 $first = false;
6637 } else if ($first) {
6638 $liclass = 'first';
6639 $first = false;
6640 } else if ($count == 0) {
6641 $liclass = 'last';
6644 if ((empty($tab->subtree)) && (!empty($tab->selected))) {
6645 $liclass .= (empty($liclass)) ? 'onerow' : ' onerow';
6648 if ($tab->inactive || $tab->active || $tab->selected) {
6649 if ($tab->selected) {
6650 $liclass .= (empty($liclass)) ? 'here selected' : ' here selected';
6651 } else if ($tab->active) {
6652 $liclass .= (empty($liclass)) ? 'here active' : ' here active';
6656 $str .= (!empty($liclass)) ? '<li class="'.$liclass.'">' : '<li>';
6658 if ($tab->inactive || $tab->active || ($tab->selected && !$tab->linkedwhenselected)) {
6659 // The a tag is used for styling
6660 $str .= '<a class="nolink"><span>'.$tab->text.'</span></a>';
6661 } else {
6662 $str .= '<a href="'.$tab->link.'" title="'.$tab->title.'"><span>'.$tab->text.'</span></a>';
6665 if (!empty($tab->subtree)) {
6666 $str .= convert_tree_to_html($tab->subtree, $row+1);
6667 } else if ($tab->selected) {
6668 $str .= '<div class="tabrow'.($row+1).' empty">&nbsp;</div>'."\n";
6671 $str .= ' </li>'."\n";
6673 $str .= '</ul>'."\n";
6675 return $str;
6679 function convert_tabrows_to_tree($tabrows, $selected, $inactive, $activated) {
6681 /// Work backwards through the rows (bottom to top) collecting the tree as we go.
6683 $tabrows = array_reverse($tabrows);
6685 $subtree = array();
6687 foreach ($tabrows as $row) {
6688 $tree = array();
6690 foreach ($row as $tab) {
6691 $tab->inactive = in_array((string)$tab->id, $inactive);
6692 $tab->active = in_array((string)$tab->id, $activated);
6693 $tab->selected = (string)$tab->id == $selected;
6695 if ($tab->active || $tab->selected) {
6696 if ($subtree) {
6697 $tab->subtree = $subtree;
6700 $tree[] = $tab;
6702 $subtree = $tree;
6705 return $subtree;
6710 * Returns a string containing a link to the user documentation for the current
6711 * page. Also contains an icon by default. Shown to teachers and admin only.
6713 * @param string $text The text to be displayed for the link
6714 * @param string $iconpath The path to the icon to be displayed
6716 function page_doc_link($text='', $iconpath='') {
6717 global $ME, $COURSE, $CFG;
6719 if (empty($CFG->docroot) or empty($CFG->rolesactive)) {
6720 return '';
6723 if (empty($COURSE->id)) {
6724 $context = get_context_instance(CONTEXT_SYSTEM);
6725 } else {
6726 $context = get_context_instance(CONTEXT_COURSE, $COURSE->id);
6729 if (!has_capability('moodle/site:doclinks', $context)) {
6730 return '';
6733 if (empty($CFG->pagepath)) {
6734 $CFG->pagepath = $ME;
6737 $path = str_replace($CFG->httpswwwroot.'/','', $CFG->pagepath); // Because the page could be HTTPSPAGEREQUIRED
6738 $path = str_replace('.php', '', $path);
6740 if (empty($path)) { // Not for home page
6741 return '';
6743 return doc_link($path, $text, $iconpath);
6747 * Returns a string containing a link to the user documentation.
6748 * Also contains an icon by default. Shown to teachers and admin only.
6750 * @param string $path The page link after doc root and language, no
6751 * leading slash.
6752 * @param string $text The text to be displayed for the link
6753 * @param string $iconpath The path to the icon to be displayed
6755 function doc_link($path='', $text='', $iconpath='') {
6756 global $CFG;
6758 if (empty($CFG->docroot)) {
6759 return '';
6762 $target = '';
6763 if (!empty($CFG->doctonewwindow)) {
6764 $target = ' target="_blank"';
6767 $lang = str_replace('_utf8', '', current_language());
6769 $str = '<a href="' .$CFG->docroot. '/' .$lang. '/' .$path. '"' .$target. '>';
6771 if (empty($iconpath)) {
6772 $iconpath = $CFG->httpswwwroot . '/pix/docs.gif';
6775 // alt left blank intentionally to prevent repetition in screenreaders
6776 $str .= '<img class="iconhelp" src="' .$iconpath. '" alt="" />' .$text. '</a>';
6778 return $str;
6783 * Returns true if the current site debugging settings are equal or above specified level.
6784 * If passed a parameter it will emit a debugging notice similar to trigger_error(). The
6785 * routing of notices is controlled by $CFG->debugdisplay
6786 * eg use like this:
6788 * 1) debugging('a normal debug notice');
6789 * 2) debugging('something really picky', DEBUG_ALL);
6790 * 3) debugging('annoying debug message only for develpers', DEBUG_DEVELOPER);
6791 * 4) if (debugging()) { perform extra debugging operations (do not use print or echo) }
6793 * In code blocks controlled by debugging() (such as example 4)
6794 * any output should be routed via debugging() itself, or the lower-level
6795 * trigger_error() or error_log(). Using echo or print will break XHTML
6796 * JS and HTTP headers.
6799 * @param string $message a message to print
6800 * @param int $level the level at which this debugging statement should show
6801 * @return bool
6803 function debugging($message='', $level=DEBUG_NORMAL) {
6805 global $CFG;
6807 if (empty($CFG->debug)) {
6808 return false;
6811 if ($CFG->debug >= $level) {
6812 if ($message) {
6813 $callers = debug_backtrace();
6814 $from = '<ul style="text-align: left">';
6815 foreach ($callers as $caller) {
6816 if (!isset($caller['line'])) {
6817 $caller['line'] = '?'; // probably call_user_func()
6819 if (!isset($caller['file'])) {
6820 $caller['file'] = $CFG->dirroot.'/unknownfile'; // probably call_user_func()
6822 $from .= '<li>line ' . $caller['line'] . ' of ' . substr($caller['file'], strlen($CFG->dirroot) + 1);
6823 if (isset($caller['function'])) {
6824 $from .= ': call to ';
6825 if (isset($caller['class'])) {
6826 $from .= $caller['class'] . $caller['type'];
6828 $from .= $caller['function'] . '()';
6830 $from .= '</li>';
6832 $from .= '</ul>';
6833 if (!isset($CFG->debugdisplay)) {
6834 $CFG->debugdisplay = ini_get_bool('display_errors');
6836 if ($CFG->debugdisplay) {
6837 if (!defined('DEBUGGING_PRINTED')) {
6838 define('DEBUGGING_PRINTED', 1); // indicates we have printed something
6840 notify($message . $from, 'notifytiny');
6841 } else {
6842 trigger_error($message . $from, E_USER_NOTICE);
6845 return true;
6847 return false;
6851 * Disable debug messages from debugging(), while keeping PHP error reporting level as is.
6853 function disable_debugging() {
6854 global $CFG;
6855 $CFG->debug = $CFG->debug | 0x80000000; // switch the sign bit in integer number ;-)
6860 * Returns string to add a frame attribute, if required
6862 function frametarget() {
6863 global $CFG;
6865 if (empty($CFG->framename) or ($CFG->framename == '_top')) {
6866 return '';
6867 } else {
6868 return ' target="'.$CFG->framename.'" ';
6873 * Outputs a HTML comment to the browser. This is used for those hard-to-debug
6874 * pages that use bits from many different files in very confusing ways (e.g. blocks).
6875 * @usage print_location_comment(__FILE__, __LINE__);
6876 * @param string $file
6877 * @param integer $line
6878 * @param boolean $return Whether to return or print the comment
6879 * @return mixed Void unless true given as third parameter
6881 function print_location_comment($file, $line, $return = false)
6883 if ($return) {
6884 return "<!-- $file at line $line -->\n";
6885 } else {
6886 echo "<!-- $file at line $line -->\n";
6892 * Returns an image of an up or down arrow, used for column sorting. To avoid unnecessary DB accesses, please
6893 * provide this function with the language strings for sortasc and sortdesc.
6894 * If no sort string is associated with the direction, an arrow with no alt text will be printed/returned.
6895 * @param string $direction 'up' or 'down'
6896 * @param string $strsort The language string used for the alt attribute of this image
6897 * @param bool $return Whether to print directly or return the html string
6898 * @return string HTML for the image
6900 * TODO See if this isn't already defined somewhere. If not, move this to weblib
6902 function print_arrow($direction='up', $strsort=null, $return=false) {
6903 global $CFG;
6905 if (!in_array($direction, array('up', 'down', 'right', 'left', 'move'))) {
6906 return null;
6909 $return = null;
6911 switch ($direction) {
6912 case 'up':
6913 $sortdir = 'asc';
6914 break;
6915 case 'down':
6916 $sortdir = 'desc';
6917 break;
6918 case 'move':
6919 $sortdir = 'asc';
6920 break;
6921 default:
6922 $sortdir = null;
6923 break;
6926 // Prepare language string
6927 $strsort = '';
6928 if (empty($strsort) && !empty($sortdir)) {
6929 $strsort = get_string('sort' . $sortdir, 'grades');
6932 $return = ' <img src="'.$CFG->pixpath.'/t/' . $direction . '.gif" alt="'.$strsort.'" /> ';
6934 if ($return) {
6935 return $return;
6936 } else {
6937 echo $return;
6942 * Returns boolean true if the current language is right-to-left (Hebrew, Arabic etc)
6945 function right_to_left() {
6946 static $result;
6948 if (isset($result)) {
6949 return $result;
6951 return $result = (get_string('thisdirection') == 'rtl');
6956 * Returns swapped left<=>right if in RTL environment.
6957 * part of RTL support
6959 * @param string $align align to check
6960 * @return string
6962 function fix_align_rtl($align) {
6963 if (!right_to_left()) {
6964 return $align;
6966 if ($align=='left') { return 'right'; }
6967 if ($align=='right') { return 'left'; }
6968 return $align;
6973 * Returns true if the page is displayed in a popup window.
6974 * Gets the information from the URL parameter inpopup.
6976 * @return boolean
6978 * TODO Use a central function to create the popup calls allover Moodle and
6979 * TODO In the moment only works with resources and probably questions.
6981 function is_in_popup() {
6982 $inpopup = optional_param('inpopup', '', PARAM_BOOL);
6984 return ($inpopup);
6988 * Return the authentication plugin title
6989 * @param string $authtype plugin type
6990 * @return string
6992 function auth_get_plugin_title ($authtype) {
6993 $authtitle = get_string("auth_{$authtype}title", "auth");
6994 if ($authtitle == "[[auth_{$authtype}title]]") {
6995 $authtitle = get_string("auth_{$authtype}title", "auth_{$authtype}");
6997 return $authtitle;
7000 // vim:autoindent:expandtab:shiftwidth=4:tabstop=4:tw=140: