3 ///////////////////////////////////////////////////////////////////////////
5 // NOTICE OF COPYRIGHT //
7 // Moodle - Modular Object-Oriented Dynamic Learning Environment //
8 // http://moodle.com //
10 // Copyright (C) 1999 onwards Martin Dougiamas http://dougiamas.com //
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. //
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: //
22 // http://www.gnu.org/copyleft/gpl.html //
24 ///////////////////////////////////////////////////////////////////////////
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
37 * @license http://www.gnu.org/copyleft/gpl.html GNU Public License
41 /// We are going to uses filterlib functions here
42 require_once("$CFG->libdir/filterlib.php");
44 require_once("$CFG->libdir/ajax/ajaxlib.php");
48 /// Define text formatting types ... eventually we can add Wiki, BBcode etc
51 * Does all sorts of transformations and filtering
53 define('FORMAT_MOODLE', '0'); // Does all sorts of transformations and filtering
56 * Plain HTML (with some tags stripped)
58 define('FORMAT_HTML', '1'); // Plain HTML (with some tags stripped)
61 * Plain text (even tags are printed in full)
63 define('FORMAT_PLAIN', '2'); // Plain text (even tags are printed in full)
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
73 * Markdown-formatted text http://daringfireball.net/projects/markdown/
75 define('FORMAT_MARKDOWN', '4'); // Markdown-formatted text http://daringfireball.net/projects/markdown/
78 * TRUSTTEXT marker - if present in text, text cleaning should be bypassed
80 define('TRUSTTEXT', '#####TRUSTTEXT#####');
84 * Javascript related defines
86 define('REQUIREJS_BEFOREHEADER', 0);
87 define('REQUIREJS_INHEADER', 1);
88 define('REQUIREJS_AFTERHEADER', 2);
91 * Allowed tags - string of html tags that can be tested against for safe html tags
92 * @global string $ALLOWED_TAGS
96 '<p><br><b><i><u><font><table><tbody><span><div><tr><td><th><ol><ul><dl><li><dt><dd><h1><h2><h3><h4><h5><h6><hr><img><a><strong><emphasis><em><sup><sub><address><cite><blockquote><pre><strike><param><acronym><nolink><lang><tex><algebra><math><mi><mn><mo><mtext><mspace><ms><mrow><mfrac><msqrt><mroot><mstyle><merror><mpadded><mphantom><mfenced><msub><msup><msubsup><munder><mover><munderover><mmultiscripts><mtable><mtr><mtd><maligngroup><malignmark><maction><cn><ci><apply><reln><fn><interval><inverse><sep><condition><declare><lambda><compose><ident><quotient><exp><factorial><divide><max><min><minus><plus><power><rem><times><root><gcd><and><or><xor><not><implies><forall><exists><abs><conjugate><eq><neq><gt><lt><geq><leq><ln><log><int><diff><partialdiff><lowlimit><uplimit><bvar><degree><set><list><union><intersect><in><notin><subset><prsubset><notsubset><notprsubset><setdiff><sum><product><limit><tendsto><mean><sdev><variance><median><mode><moment><vector><matrix><matrixrow><determinant><transpose><selector><annotation><semantics><annotation-xml><tt><code>';
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',
104 'border', 'margin', 'padding', 'background', 'text-decoration'); // CSS as well to get through kses
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.
120 function s($var, $strip=false) {
122 if ($var == '0') { // for integer 0, boolean false, string '0'
127 return preg_replace("/&(#\d+);/i", "&$1;", htmlspecialchars(stripslashes_safe($var)));
129 return preg_replace("/&(#\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.
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
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);
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
181 function strip_querystring($url) {
183 if ($commapos = strpos($url, '?')) {
184 return substr($url, 0, $commapos);
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.
195 function get_referer($stripquery=true) {
196 if (isset($_SERVER['HTTP_REFERER'])) {
198 return strip_querystring($_SERVER['HTTP_REFERER']);
200 return $_SERVER['HTTP_REFERER'];
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.
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'];
241 notify('Warning: Could not find any of these web server variables: $REQUEST_URI, $PHP_SELF, $SCRIPT_NAME or $URL');
247 * Like {@link me()} but returns a full URL
251 function qualified_me() {
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'];
270 notify('Warning: could not find the name of this server!');
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://';
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
304 var $scheme = '';// e.g. http
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()){
325 $url = strip_querystring($FULLME);
327 $parts = parse_url($url);
328 if ($parts === FALSE){
331 if (isset($parts['query'])){
332 parse_str(str_replace('&', '&', $parts['query']), $this->params
);
334 unset($parts['query']);
335 foreach ($parts as $key => $value){
336 $this->$key = $value;
338 $this->params($params);
342 * Add an array of params to the params for this page. The added params override existing ones if they
343 * have the same name.
345 * @param array $params
347 function params($params){
348 $this->params
= $params +
$this->params
;
352 * Remove all params if no arguments passed. Or else remove param $arg1, $arg2, etc.
354 * @param string $arg1
355 * @param string $arg2
356 * @param string $arg3
358 function remove_params(){
359 if ($thisargs = func_get_args()){
360 foreach ($thisargs as $arg){
361 if (isset($this->params
->$arg)){
362 unset($this->params
->$arg);
366 $this->params
= array();
371 * Add a param to the params for this page. The added param overrides existing one if they
372 * have the same name.
374 * @param string $paramname name
375 * @param string $param value
377 function param($paramname, $param){
378 $this->params
= array($paramname => $param) +
$this->params
;
382 function get_query_string($overrideparams = array()){
384 $params = $overrideparams +
$this->params
;
385 foreach ($params as $key => $val){
386 $arr[] = urlencode($key)."=".urlencode($val);
388 return implode($arr, "&");
391 * Outputs params as hidden form elements.
393 * @param array $exclude params to ignore
394 * @param integer $indent indentation
395 * @return string html for form elements.
397 function hidden_params_out($exclude = array(), $indent = 0){
398 $tabindent = str_repeat("\t", $indent);
400 foreach ($this->params
as $key => $val){
401 if (FALSE === array_search($key, $exclude)) {
403 $str.= "$tabindent<input type=\"hidden\" name=\"$key\" value=\"$val\" />\n";
411 * @param boolean $noquerystring whether to output page params as a query string in the url.
412 * @param array $overrideparams params to add to the output url, these override existing ones with the same name.
415 function out($noquerystring = false, $overrideparams = array()) {
416 $uri = $this->scheme ?
$this->scheme
.':'.((strtolower($this->scheme
) == 'mailto') ?
'':'//'): '';
417 $uri .= $this->user ?
$this->user
.($this->pass?
':'.$this->pass
:'').'@':'';
418 $uri .= $this->host ?
$this->host
: '';
419 $uri .= $this->port ?
':'.$this->port
: '';
420 $uri .= $this->path ?
$this->path
: '';
421 if (!$noquerystring){
422 $uri .= (count($this->params
)||
count($overrideparams)) ?
'?'.$this->get_query_string($overrideparams) : '';
424 $uri .= $this->fragment ?
'#'.$this->fragment
: '';
428 * Output action url with sesskey
430 * @param boolean $noquerystring whether to output page params as a query string in the url.
433 function out_action($overrideparams = array()) {
434 $overrideparams = array('sesskey'=> sesskey()) +
$overrideparams;
435 return $this->out(false, $overrideparams);
440 * Determine if there is data waiting to be processed from a form
442 * Used on most forms in Moodle to check for data
443 * Returns the data as an object, if it's found.
444 * This object can be used in foreach loops without
445 * casting because it's cast to (array) automatically
447 * Checks that submitted POST data exists and returns it as object.
449 * @param string $url not used anymore
450 * @return mixed false or object
452 function data_submitted($url='') {
457 return (object)$_POST;
462 * Moodle replacement for php stripslashes() function,
463 * works also for objects and arrays.
465 * The standard php stripslashes() removes ALL backslashes
466 * even from strings - so C:\temp becomes C:temp - this isn't good.
467 * This function should work as a fairly safe replacement
468 * to be called on quoted AND unquoted strings (to be sure)
470 * @param mixed something to remove unsafe slashes from
473 function stripslashes_safe($mixed) {
474 // there is no need to remove slashes from int, float and bool types
477 } else if (is_string($mixed)) {
478 if (ini_get_bool('magic_quotes_sybase')) { //only unescape single quotes
479 $mixed = str_replace("''", "'", $mixed);
480 } else { //the rest, simple and double quotes and backslashes
481 $mixed = str_replace("\\'", "'", $mixed);
482 $mixed = str_replace('\\"', '"', $mixed);
483 $mixed = str_replace('\\\\', '\\', $mixed);
485 } else if (is_array($mixed)) {
486 foreach ($mixed as $key => $value) {
487 $mixed[$key] = stripslashes_safe($value);
489 } else if (is_object($mixed)) {
490 $vars = get_object_vars($mixed);
491 foreach ($vars as $key => $value) {
492 $mixed->$key = stripslashes_safe($value);
500 * Recursive implementation of stripslashes()
502 * This function will allow you to strip the slashes from a variable.
503 * If the variable is an array or object, slashes will be stripped
504 * from the items (or properties) it contains, even if they are arrays
505 * or objects themselves.
507 * @param mixed the variable to remove slashes from
510 function stripslashes_recursive($var) {
511 if (is_object($var)) {
512 $new_var = new object();
513 $properties = get_object_vars($var);
514 foreach($properties as $property => $value) {
515 $new_var->$property = stripslashes_recursive($value);
518 } else if(is_array($var)) {
520 foreach($var as $property => $value) {
521 $new_var[$property] = stripslashes_recursive($value);
524 } else if(is_string($var)) {
525 $new_var = stripslashes($var);
535 * Recursive implementation of addslashes()
537 * This function will allow you to add the slashes from a variable.
538 * If the variable is an array or object, slashes will be added
539 * to the items (or properties) it contains, even if they are arrays
540 * or objects themselves.
542 * @param mixed the variable to add slashes from
545 function addslashes_recursive($var) {
546 if (is_object($var)) {
547 $new_var = new object();
548 $properties = get_object_vars($var);
549 foreach($properties as $property => $value) {
550 $new_var->$property = addslashes_recursive($value);
553 } else if (is_array($var)) {
555 foreach($var as $property => $value) {
556 $new_var[$property] = addslashes_recursive($value);
559 } else if (is_string($var)) {
560 $new_var = addslashes($var);
562 } else { // nulls, integers, etc.
570 * Given some normal text this function will break up any
571 * long words to a given size by inserting the given character
573 * It's multibyte savvy and doesn't change anything inside html tags.
575 * @param string $string the string to be modified
576 * @param int $maxsize maximum length of the string to be returned
577 * @param string $cutchar the string used to represent word breaks
580 function break_up_long_words($string, $maxsize=20, $cutchar=' ') {
582 /// Loading the textlib singleton instance. We are going to need it.
583 $textlib = textlib_get_instance();
585 /// First of all, save all the tags inside the text to skip them
587 filter_save_tags($string,$tags);
589 /// Process the string adding the cut when necessary
591 $length = $textlib->strlen($string);
594 for ($i=0; $i<$length; $i++
) {
595 $char = $textlib->substr($string, $i, 1);
596 if ($char == ' ' or $char == "\t" or $char == "\n" or $char == "\r" or $char == "<" or $char == ">") {
600 if ($wordlength > $maxsize) {
608 /// Finally load the tags back again
610 $output = str_replace(array_keys($tags), $tags, $output);
617 * This does a search and replace, ignoring case
618 * This function is only used for versions of PHP older than version 5
619 * which do not have a native version of this function.
620 * Taken from the PHP manual, by bradhuizenga @ softhome.net
622 * @param string $find the string to search for
623 * @param string $replace the string to replace $find with
624 * @param string $string the string to search through
627 if (!function_exists('str_ireplace')) { /// Only exists in PHP 5
628 function str_ireplace($find, $replace, $string) {
630 if (!is_array($find)) {
631 $find = array($find);
634 if(!is_array($replace)) {
635 if (!is_array($find)) {
636 $replace = array($replace);
638 // this will duplicate the string into an array the size of $find
642 for ($i = 0; $i < $c; $i++
) {
643 $replace[$i] = $rString;
648 foreach ($find as $fKey => $fItem) {
649 $between = explode(strtolower($fItem),strtolower($string));
651 foreach($between as $bKey => $bItem) {
652 $between[$bKey] = substr($string,$pos,strlen($bItem));
653 $pos +
= strlen($bItem) +
strlen($fItem);
655 $string = implode($replace[$fKey],$between);
662 * Locate the position of a string in another string
664 * This function is only used for versions of PHP older than version 5
665 * which do not have a native version of this function.
666 * Taken from the PHP manual, by dmarsh @ spscc.ctc.edu
668 * @param string $haystack The string to be searched
669 * @param string $needle The string to search for
670 * @param int $offset The position in $haystack where the search should begin.
672 if (!function_exists('stripos')) { /// Only exists in PHP 5
673 function stripos($haystack, $needle, $offset=0) {
675 return strpos(strtoupper($haystack), strtoupper($needle), $offset);
680 * This function will print a button/link/etc. form element
681 * that will work on both Javascript and non-javascript browsers.
682 * Relies on the Javascript function openpopup in javascript.php
684 * All parameters default to null, only $type and $url are mandatory.
686 * $url must be relative to home page eg /mod/survey/stuff.php
687 * @param string $url Web link relative to home page
688 * @param string $name Name to be assigned to the popup window (this is used by
689 * client-side scripts to "talk" to the popup window)
690 * @param string $linkname Text to be displayed as web link
691 * @param int $height Height to assign to popup window
692 * @param int $width Height to assign to popup window
693 * @param string $title Text to be displayed as popup page title
694 * @param string $options List of additional options for popup window
695 * @param string $return If true, return as a string, otherwise print
696 * @param string $id id added to the element
697 * @param string $class class added to the element
701 function element_to_popup_window ($type=null, $url=null, $name=null, $linkname=null,
702 $height=400, $width=500, $title=null,
703 $options=null, $return=false, $id=null, $class=null) {
706 debugging('You must give the url to display in the popup. URL is missing - can\'t create popup window.', DEBUG_DEVELOPER
);
711 if ($options == 'none') { // 'none' is legacy, should be removed in v2.0
715 // add some sane default options for popup windows
717 $options = 'menubar=0,location=0,scrollbars,resizable';
720 $options .= ',width='. $width;
723 $options .= ',height='. $height;
726 $id = ' id="'.$id.'" ';
729 $class = ' class="'.$class.'" ';
733 if (($name = preg_replace("/\s/", '_', $name)) != $_name) {
734 debugging('The $name of a popup window shouldn\'t contain spaces - string modified. '. $_name .' changed to '. $name, DEBUG_DEVELOPER
);
740 // get some default string, using the localized version of legacy defaults
742 $linkname = get_string('clickhere');
745 $title = get_string('popupwindowname');
748 $fullscreen = 0; // must be passed to openpopup
753 $element = '<input type="button" name="'. $name .'" title="'. $title .'" value="'. $linkname .'" '. $id . $class .
754 "onclick=\"return openpopup('$url', '$name', '$options', $fullscreen);\" />\n";
757 // some log url entries contain _SERVER[HTTP_REFERRER] in which case wwwroot is already there.
758 if (!(strpos($url,$CFG->wwwroot
) === false)) {
759 $url = substr($url, strlen($CFG->wwwroot
));
761 $element = '<a title="'. s(strip_tags($title)) .'" href="'. $CFG->wwwroot
. $url .'" '.
762 "onclick=\"this.target='$name'; return openpopup('$url', '$name', '$options', $fullscreen);\">$linkname</a>";
765 error('Undefined element - can\'t create popup window.');
777 * Creates and displays (or returns) a link to a popup window, using element_to_popup_window function.
779 * @return string html code to display a link to a popup window.
780 * @see element_to_popup_window()
782 function link_to_popup_window ($url, $name=null, $linkname=null,
783 $height=400, $width=500, $title=null,
784 $options=null, $return=false) {
786 return element_to_popup_window('link', $url, $name, $linkname, $height, $width, $title, $options, $return, null, null);
790 * Creates and displays (or returns) a buttons to a popup window, using element_to_popup_window function.
792 * @return string html code to display a button to a popup window.
793 * @see element_to_popup_window()
795 function button_to_popup_window ($url, $name=null, $linkname=null,
796 $height=400, $width=500, $title=null, $options=null, $return=false,
797 $id=null, $class=null) {
799 return element_to_popup_window('button', $url, $name, $linkname, $height, $width, $title, $options, $return, $id, $class);
804 * Prints a simple button to close a window
805 * @param string $name name of the window to close
806 * @param boolean $return whether this function should return a string or output it
807 * @return string if $return is true, nothing otherwise
809 function close_window_button($name='closewindow', $return=false) {
814 $output .= '<div class="closewindow">' . "\n";
815 $output .= '<form action="'.$CFG->wwwroot
.'"><div>'; // We don't use this
816 $output .= '<input type="button" onclick="self.close();" value="'.get_string($name).'" />';
817 $output .= '</div></form>';
818 $output .= '</div>' . "\n";
828 * Try and close the current window immediately using Javascript
829 * @param int $delay the delay in seconds before closing the window
831 function close_window($delay=0) {
833 <script type
="text/javascript">
835 function close_this_window() {
838 setTimeout("close_this_window()", <?php
echo $delay * 1000 ?
>);
842 <?php
print_string('pleaseclose') ?
>
850 * Given an array of values, output the HTML for a select element with those options.
851 * Normally, you only need to use the first few parameters.
853 * @param array $options The options to offer. An array of the form
854 * $options[{value}] = {text displayed for that option};
855 * @param string $name the name of this form control, as in <select name="..." ...
856 * @param string $selected the option to select initially, default none.
857 * @param string $nothing The label for the 'nothing is selected' option. Defaults to get_string('choose').
858 * Set this to '' if you don't want a 'nothing is selected' option.
859 * @param string $script in not '', then this is added to the <select> element as an onchange handler.
860 * @param string $nothingvalue The value corresponding to the $nothing option. Defaults to 0.
861 * @param boolean $return if false (the default) the the output is printed directly, If true, the
862 * generated HTML is returned as a string.
863 * @param boolean $disabled if true, the select is generated in a disabled state. Default, false.
864 * @param int $tabindex if give, sets the tabindex attribute on the <select> element. Default none.
865 * @param string $id value to use for the id attribute of the <select> element. If none is given,
866 * then a suitable one is constructed.
868 function choose_from_menu ($options, $name, $selected='', $nothing='choose', $script='',
869 $nothingvalue='0', $return=false, $disabled=false, $tabindex=0, $id='') {
871 if ($nothing == 'choose') {
872 $nothing = get_string('choose') .'...';
875 $attributes = ($script) ?
'onchange="'. $script .'"' : '';
877 $attributes .= ' disabled="disabled"';
881 $attributes .= ' tabindex="'.$tabindex.'"';
886 // name may contaion [], which would make an invalid id. e.g. numeric question type editing form, assignment quickgrading
887 $id = str_replace('[', '', $id);
888 $id = str_replace(']', '', $id);
891 $output = '<select id="'.$id.'" name="'. $name .'" '. $attributes .'>' . "\n";
893 $output .= ' <option value="'. s($nothingvalue) .'"'. "\n";
894 if ($nothingvalue === $selected) {
895 $output .= ' selected="selected"';
897 $output .= '>'. $nothing .'</option>' . "\n";
899 if (!empty($options)) {
900 foreach ($options as $value => $label) {
901 $output .= ' <option value="'. s($value) .'"';
902 if ((string)$value == (string)$selected) {
903 $output .= ' selected="selected"';
906 $output .= '>'. $value .'</option>' . "\n";
908 $output .= '>'. $label .'</option>' . "\n";
912 $output .= '</select>' . "\n";
922 * Choose value 0 or 1 from a menu with options 'No' and 'Yes'.
923 * Other options like choose_from_menu.
924 * @param string $name
925 * @param string $selected
926 * @param string $string (defaults to '')
927 * @param boolean $return whether this function should return a string or output it (defaults to false)
928 * @param boolean $disabled (defaults to false)
929 * @param int $tabindex
931 function choose_from_menu_yesno($name, $selected, $script = '',
932 $return = false, $disabled = false, $tabindex = 0) {
933 return choose_from_menu(array(get_string('no'), get_string('yes')), $name,
934 $selected, '', $script, '0', $return, $disabled, $tabindex);
938 * Just like choose_from_menu, but takes a nested array (2 levels) and makes a dropdown menu
939 * including option headings with the first level.
941 function choose_from_menu_nested($options,$name,$selected='',$nothing='choose',$script = '',
942 $nothingvalue=0,$return=false,$disabled=false,$tabindex=0) {
944 if ($nothing == 'choose') {
945 $nothing = get_string('choose') .'...';
948 $attributes = ($script) ?
'onchange="'. $script .'"' : '';
950 $attributes .= ' disabled="disabled"';
954 $attributes .= ' tabindex="'.$tabindex.'"';
957 $output = '<select id="menu'.$name.'" name="'. $name .'" '. $attributes .'>' . "\n";
959 $output .= ' <option value="'. $nothingvalue .'"'. "\n";
960 if ($nothingvalue === $selected) {
961 $output .= ' selected="selected"';
963 $output .= '>'. $nothing .'</option>' . "\n";
965 if (!empty($options)) {
966 foreach ($options as $section => $values) {
968 $output .= ' <optgroup label="'. s(format_string($section)) .'">'."\n";
969 foreach ($values as $value => $label) {
970 $output .= ' <option value="'. format_string($value) .'"';
971 if ((string)$value == (string)$selected) {
972 $output .= ' selected="selected"';
975 $output .= '>'. $value .'</option>' . "\n";
977 $output .= '>'. $label .'</option>' . "\n";
980 $output .= ' </optgroup>'."\n";
983 $output .= '</select>' . "\n";
994 * Given an array of values, creates a group of radio buttons to be part of a form
996 * @param array $options An array of value-label pairs for the radio group (values as keys)
997 * @param string $name Name of the radiogroup (unique in the form)
998 * @param string $checked The value that is already checked
1000 function choose_from_radio ($options, $name, $checked='', $return=false) {
1002 static $idcounter = 0;
1008 $output = '<span class="radiogroup '.$name."\">\n";
1010 if (!empty($options)) {
1012 foreach ($options as $value => $label) {
1013 $htmlid = 'auto-rb'.sprintf('%04d', ++
$idcounter);
1014 $output .= ' <span class="radioelement '.$name.' rb'.$currentradio."\">";
1015 $output .= '<input name="'.$name.'" id="'.$htmlid.'" type="radio" value="'.$value.'"';
1016 if ($value == $checked) {
1017 $output .= ' checked="checked"';
1019 if ($label === '') {
1020 $output .= ' /> <label for="'.$htmlid.'">'. $value .'</label></span>' . "\n";
1022 $output .= ' /> <label for="'.$htmlid.'">'. $label .'</label></span>' . "\n";
1024 $currentradio = ($currentradio +
1) %
2;
1028 $output .= '</span>' . "\n";
1037 /** Display an standard html checkbox with an optional label
1039 * @param string $name The name of the checkbox
1040 * @param string $value The valus that the checkbox will pass when checked
1041 * @param boolean $checked The flag to tell the checkbox initial state
1042 * @param string $label The label to be showed near the checkbox
1043 * @param string $alt The info to be inserted in the alt tag
1045 function print_checkbox ($name, $value, $checked = true, $label = '', $alt = '', $script='',$return=false) {
1047 static $idcounter = 0;
1054 $alt = strip_tags($alt);
1060 $strchecked = ' checked="checked"';
1065 $htmlid = 'auto-cb'.sprintf('%04d', ++
$idcounter);
1066 $output = '<span class="checkbox '.$name."\">";
1067 $output .= '<input name="'.$name.'" id="'.$htmlid.'" type="checkbox" value="'.$value.'" alt="'.$alt.'"'.$strchecked.' '.((!empty($script)) ?
' onclick="'.$script.'" ' : '').' />';
1068 if(!empty($label)) {
1069 $output .= ' <label for="'.$htmlid.'">'.$label.'</label>';
1071 $output .= '</span>'."\n";
1073 if (empty($return)) {
1081 /** Display an standard html text field with an optional label
1083 * @param string $name The name of the text field
1084 * @param string $value The value of the text field
1085 * @param string $label The label to be showed near the text field
1086 * @param string $alt The info to be inserted in the alt tag
1088 function print_textfield ($name, $value, $alt = '',$size=50,$maxlength=0, $return=false) {
1090 static $idcounter = 0;
1100 if (!empty($maxlength)) {
1101 $maxlength = ' maxlength="'.$maxlength.'" ';
1104 $htmlid = 'auto-tf'.sprintf('%04d', ++
$idcounter);
1105 $output = '<span class="textfield '.$name."\">";
1106 $output .= '<input name="'.$name.'" id="'.$htmlid.'" type="text" value="'.$value.'" size="'.$size.'" '.$maxlength.' alt="'.$alt.'" />';
1108 $output .= '</span>'."\n";
1110 if (empty($return)) {
1120 * Implements a complete little popup form
1123 * @param string $common The URL up to the point of the variable that changes
1124 * @param array $options Alist of value-label pairs for the popup list
1125 * @param string $formid Id must be unique on the page (originaly $formname)
1126 * @param string $selected The option that is already selected
1127 * @param string $nothing The label for the "no choice" option
1128 * @param string $help The name of a help page if help is required
1129 * @param string $helptext The name of the label for the help button
1130 * @param boolean $return Indicates whether the function should return the text
1131 * as a string or echo it directly to the page being rendered
1132 * @param string $targetwindow The name of the target page to open the linked page in.
1133 * @param string $selectlabel Text to place in a [label] element - preferred for accessibility.
1134 * @param array $optionsextra TODO, an array?
1135 * @return string If $return is true then the entire form is returned as a string.
1136 * @todo Finish documenting this function<br>
1138 function popup_form($common, $options, $formid, $selected='', $nothing='choose', $help='', $helptext='', $return=false,
1139 $targetwindow='self', $selectlabel='', $optionsextra=NULL) {
1142 static $go, $choose; /// Locally cached, in case there's lots on a page
1144 if (empty($options)) {
1149 $go = get_string('go');
1152 if ($nothing == 'choose') {
1153 if (!isset($choose)) {
1154 $choose = get_string('choose');
1156 $nothing = $choose.'...';
1159 // changed reference to document.getElementById('id_abc') instead of document.abc
1161 $output = '<form action="'.$CFG->wwwroot
.'/course/jumpto.php"'.
1164 ' id="'.$formid.'"'.
1165 ' class="popupform">';
1167 $button = helpbutton($help, $helptext, 'moodle', true, false, '', true);
1173 $selectlabel = '<label for="'.$formid.'_jump">'.$selectlabel.'</label>';
1176 //IE and Opera fire the onchange when ever you move into a dropdwown list with the keyboard.
1177 //onfocus will call a function inside dropdown.js. It fixes this IE/Opera behavior.
1178 if (check_browser_version('MSIE') ||
check_browser_version('Opera')) {
1179 $output .= '<div>'.$selectlabel.$button.'<select id="'.$formid.'_jump" onfocus="initSelect(\''.$formid.'\','.$targetwindow.')" name="jump">'."\n";
1183 $output .= '<div>'.$selectlabel.$button.'<select id="'.$formid.'_jump" name="jump" onchange="'.$targetwindow.'.location=document.getElementById(\''.$formid.'\').jump.options[document.getElementById(\''.$formid.'\').jump.selectedIndex].value;">'."\n";
1186 if ($nothing != '') {
1187 $output .= " <option value=\"javascript:void(0)\">$nothing</option>\n";
1190 $inoptgroup = false;
1192 foreach ($options as $value => $label) {
1194 if ($label == '--') { /// we are ending previous optgroup
1195 /// Check to see if we already have a valid open optgroup
1196 /// XHTML demands that there be at least 1 option within an optgroup
1197 if ($inoptgroup and (count($optgr) > 1) ) {
1198 $output .= implode('', $optgr);
1199 $output .= ' </optgroup>';
1202 $inoptgroup = false;
1204 } else if (substr($label,0,2) == '--') { /// we are starting a new optgroup
1206 /// Check to see if we already have a valid open optgroup
1207 /// XHTML demands that there be at least 1 option within an optgroup
1208 if ($inoptgroup and (count($optgr) > 1) ) {
1209 $output .= implode('', $optgr);
1210 $output .= ' </optgroup>';
1216 $optgr[] = ' <optgroup label="'. s(format_string(substr($label,2))) .'">'; // Plain labels
1218 $inoptgroup = true; /// everything following will be in an optgroup
1222 if (!empty($CFG->usesid
) && !isset($_COOKIE[session_name()]))
1224 $url=sid_process_url( $common . $value );
1227 $url=$common . $value;
1229 $optstr = ' <option value="' . $url . '"';
1231 if ($value == $selected) {
1232 $optstr .= ' selected="selected"';
1235 if (!empty($optionsextra[$value])) {
1236 $optstr .= ' '.$optionsextra[$value];
1240 $optstr .= '>'. $label .'</option>' . "\n";
1242 $optstr .= '>'. $value .'</option>' . "\n";
1254 /// catch the final group if not closed
1255 if ($inoptgroup and count($optgr) > 1) {
1256 $output .= implode('', $optgr);
1257 $output .= ' </optgroup>';
1260 $output .= '</select>';
1261 $output .= '<input type="hidden" name="sesskey" value="'.sesskey().'" />';
1262 $output .= '<div id="noscript'.$formid.'" style="display: inline;">';
1263 $output .= '<input type="submit" value="'.$go.'" /></div>';
1264 $output .= '<script type="text/javascript">'.
1266 'document.getElementById("noscript'.$formid.'").style.display = "none";'.
1267 "\n//]]>\n".'</script>';
1268 $output .= '</div>';
1269 $output .= '</form>';
1280 * Prints some red text
1282 * @param string $error The text to be displayed in red
1284 function formerr($error) {
1286 if (!empty($error)) {
1287 echo '<span class="error">'. $error .'</span>';
1292 * Validates an email to make sure it makes sense.
1294 * @param string $address The email address to validate.
1297 function validate_email($address) {
1299 return (ereg('^[-!#$%&\'*+\\/0-9=?A-Z^_`a-z{|}~]+'.
1300 '(\.[-!#$%&\'*+\\/0-9=?A-Z^_`a-z{|}~]+)*'.
1302 '[-!#$%&\'*+\\/0-9=?A-Z^_`a-z{|}~]+\.'.
1303 '[-!#$%&\'*+\\./0-9=?A-Z^_`a-z{|}~]+$',
1308 * Extracts file argument either from file parameter or PATH_INFO
1310 * @param string $scriptname name of the calling script
1311 * @return string file path (only safe characters)
1313 function get_file_argument($scriptname) {
1316 $relativepath = FALSE;
1318 // first try normal parameter (compatible method == no relative links!)
1319 $relativepath = optional_param('file', FALSE, PARAM_PATH
);
1320 if ($relativepath === '/testslasharguments') {
1321 echo 'test -1 : Incorrect use - try "file.php/testslasharguments" instead'; //indicate fopen/fread works for health center
1325 // then try extract file from PATH_INFO (slasharguments method)
1326 if (!$relativepath and !empty($_SERVER['PATH_INFO'])) {
1327 $path_info = $_SERVER['PATH_INFO'];
1328 // check that PATH_INFO works == must not contain the script name
1329 if (!strpos($path_info, $scriptname)) {
1330 $relativepath = clean_param(rawurldecode($path_info), PARAM_PATH
);
1331 if ($relativepath === '/testslasharguments') {
1332 echo 'test 1 : Slasharguments test passed. Server confguration is compatible with file.php/1/pic.jpg slashargument setting.'; //indicate ok for health center
1338 // now if both fail try the old way
1339 // (for compatibility with misconfigured or older buggy php implementations)
1340 if (!$relativepath) {
1341 $arr = explode($scriptname, me());
1342 if (!empty($arr[1])) {
1343 $path_info = strip_querystring($arr[1]);
1344 $relativepath = clean_param(rawurldecode($path_info), PARAM_PATH
);
1345 if ($relativepath === '/testslasharguments') {
1346 echo 'test 2 : Slasharguments test passed (compatibility hack). Server confguration may be compatible with file.php/1/pic.jpg slashargument setting'; //indicate ok for health center
1352 return $relativepath;
1356 * Searches the current environment variables for some slash arguments
1358 * @param string $file ?
1359 * @todo Finish documenting this function
1361 function get_slash_arguments($file='file.php') {
1363 if (!$string = me()) {
1367 $pathinfo = explode($file, $string);
1369 if (!empty($pathinfo[1])) {
1370 return addslashes($pathinfo[1]);
1377 * Extracts arguments from "/foo/bar/something"
1378 * eg http://mysite.com/script.php/foo/bar/something
1380 * @param string $string ?
1382 * @return array|string
1383 * @todo Finish documenting this function
1385 function parse_slash_arguments($string, $i=0) {
1387 if (detect_munged_arguments($string)) {
1390 $args = explode('/', $string);
1392 if ($i) { // return just the required argument
1395 } else { // return the whole array
1396 array_shift($args); // get rid of the empty first one
1402 * Just returns an array of text formats suitable for a popup menu
1404 * @uses FORMAT_MOODLE
1406 * @uses FORMAT_PLAIN
1407 * @uses FORMAT_MARKDOWN
1410 function format_text_menu() {
1412 return array (FORMAT_MOODLE
=> get_string('formattext'),
1413 FORMAT_HTML
=> get_string('formathtml'),
1414 FORMAT_PLAIN
=> get_string('formatplain'),
1415 FORMAT_MARKDOWN
=> get_string('formatmarkdown'));
1419 * Given text in a variety of format codings, this function returns
1420 * the text as safe HTML.
1422 * This function should mainly be used for long strings like posts,
1423 * answers, glossary items etc. For short strings @see format_string().
1426 * @uses FORMAT_MOODLE
1428 * @uses FORMAT_PLAIN
1430 * @uses FORMAT_MARKDOWN
1431 * @param string $text The text to be formatted. This is raw text originally from user input.
1432 * @param int $format Identifier of the text format to be used
1433 * (FORMAT_MOODLE, FORMAT_HTML, FORMAT_PLAIN, FORMAT_WIKI, FORMAT_MARKDOWN)
1434 * @param array $options ?
1435 * @param int $courseid ?
1437 * @todo Finish documenting this function
1439 function format_text($text, $format=FORMAT_MOODLE
, $options=NULL, $courseid=NULL) {
1441 global $CFG, $COURSE;
1443 static $croncache = array();
1446 return ''; // no need to do any filters and cleaning
1449 if (!isset($options->trusttext
)) {
1450 $options->trusttext
= false;
1453 if (!isset($options->noclean
)) {
1454 $options->noclean
=false;
1456 if (!isset($options->nocache
)) {
1457 $options->nocache
=false;
1459 if (!isset($options->smiley
)) {
1460 $options->smiley
=true;
1462 if (!isset($options->filter
)) {
1463 $options->filter
=true;
1465 if (!isset($options->para
)) {
1466 $options->para
=true;
1468 if (!isset($options->newlines
)) {
1469 $options->newlines
=true;
1472 if (empty($courseid)) {
1473 $courseid = $COURSE->id
;
1476 if (!empty($CFG->cachetext
) and empty($options->nocache
)) {
1477 $time = time() - $CFG->cachetext
;
1478 $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
);
1480 if (defined('FULLME') and FULLME
== 'cron') {
1481 if (isset($croncache[$md5key])) {
1482 return $croncache[$md5key];
1486 if ($oldcacheitem = get_record_sql('SELECT * FROM '.$CFG->prefix
.'cache_text WHERE md5key = \''.$md5key.'\'', true)) {
1487 if ($oldcacheitem->timemodified
>= $time) {
1488 if (defined('FULLME') and FULLME
== 'cron') {
1489 if (count($croncache) > 150) {
1491 $key = key($croncache);
1492 unset($croncache[$key]);
1494 $croncache[$md5key] = $oldcacheitem->formattedtext
;
1496 return $oldcacheitem->formattedtext
;
1501 // trusttext overrides the noclean option!
1502 if ($options->trusttext
) {
1503 if (trusttext_present($text)) {
1504 $text = trusttext_strip($text);
1505 if (!empty($CFG->enabletrusttext
)) {
1506 $options->noclean
= true;
1508 $options->noclean
= false;
1511 $options->noclean
= false;
1513 } else if (!debugging('', DEBUG_DEVELOPER
)) {
1514 // strip any forgotten trusttext in non-developer mode
1515 // do not forget to disable text cache when debugging trusttext!!
1516 $text = trusttext_strip($text);
1519 $CFG->currenttextiscacheable
= true; // Default status - can be changed by any filter
1523 if ($options->smiley
) {
1524 replace_smilies($text);
1526 if (!$options->noclean
) {
1527 $text = clean_text($text, FORMAT_HTML
);
1529 if ($options->filter
) {
1530 $text = filter_text($text, $courseid);
1535 $text = s($text); // cleans dangerous JS
1536 $text = rebuildnolinktag($text);
1537 $text = str_replace(' ', ' ', $text);
1538 $text = nl2br($text);
1542 // this format is deprecated
1543 $text = '<p>NOTICE: Wiki-like formatting has been removed from Moodle. You should not be seeing
1544 this message as all texts should have been converted to Markdown format instead.
1545 Please post a bug report to http://moodle.org/bugs with information about where you
1546 saw this message.</p>'.s($text);
1549 case FORMAT_MARKDOWN
:
1550 $text = markdown_to_html($text);
1551 if ($options->smiley
) {
1552 replace_smilies($text);
1554 if (!$options->noclean
) {
1555 $text = clean_text($text, FORMAT_HTML
);
1558 if ($options->filter
) {
1559 $text = filter_text($text, $courseid);
1563 default: // FORMAT_MOODLE or anything else
1564 $text = text_to_html($text, $options->smiley
, $options->para
, $options->newlines
);
1565 if (!$options->noclean
) {
1566 $text = clean_text($text, FORMAT_HTML
);
1569 if ($options->filter
) {
1570 $text = filter_text($text, $courseid);
1575 if (empty($options->nocache
) and !empty($CFG->cachetext
) and $CFG->currenttextiscacheable
) {
1576 if (defined('FULLME') and FULLME
== 'cron') {
1577 // special static cron cache - no need to store it in db if its not already there
1578 if (count($croncache) > 150) {
1580 $key = key($croncache);
1581 unset($croncache[$key]);
1583 $croncache[$md5key] = $text;
1587 $newcacheitem = new object();
1588 $newcacheitem->md5key
= $md5key;
1589 $newcacheitem->formattedtext
= addslashes($text);
1590 $newcacheitem->timemodified
= time();
1591 if ($oldcacheitem) { // See bug 4677 for discussion
1592 $newcacheitem->id
= $oldcacheitem->id
;
1593 @update_record
('cache_text', $newcacheitem); // Update existing record in the cache table
1594 // It's unlikely that the cron cache cleaner could have
1595 // deleted this entry in the meantime, as it allows
1596 // some extra time to cover these cases.
1598 @insert_record
('cache_text', $newcacheitem); // Insert a new record in the cache table
1599 // Again, it's possible that another user has caused this
1600 // record to be created already in the time that it took
1601 // to traverse this function. That's OK too, as the
1602 // call above handles duplicate entries, and eventually
1603 // the cron cleaner will delete them.
1610 /** Converts the text format from the value to the 'internal'
1611 * name or vice versa. $key can either be the value or the name
1612 * and you get the other back.
1614 * @param mixed int 0-4 or string one of 'moodle','html','plain','markdown'
1615 * @return mixed as above but the other way around!
1617 function text_format_name( $key ) {
1619 $lookup[FORMAT_MOODLE
] = 'moodle';
1620 $lookup[FORMAT_HTML
] = 'html';
1621 $lookup[FORMAT_PLAIN
] = 'plain';
1622 $lookup[FORMAT_MARKDOWN
] = 'markdown';
1624 if (!is_numeric($key)) {
1625 $key = strtolower( $key );
1626 $value = array_search( $key, $lookup );
1629 if (isset( $lookup[$key] )) {
1630 $value = $lookup[ $key ];
1637 * Resets all data related to filters, called during upgrade or when filter settings change.
1640 function reset_text_filters_cache() {
1643 delete_records('cache_text');
1644 $purifdir = $CFG->dataroot
.'/cache/htmlpurifier';
1645 remove_dir($purifdir, true);
1648 /** Given a simple string, this function returns the string
1649 * processed by enabled string filters if $CFG->filterall is enabled
1651 * This function should be used to print short strings (non html) that
1652 * need filter processing e.g. activity titles, post subjects,
1653 * glossary concepts.
1655 * @param string $string The string to be filtered.
1656 * @param boolean $striplinks To strip any link in the result text (Moodle 1.8 default changed from false to true! MDL-8713)
1657 * @param int $courseid Current course as filters can, potentially, use it
1660 function format_string ($string, $striplinks=true, $courseid=NULL ) {
1662 global $CFG, $COURSE;
1664 //We'll use a in-memory cache here to speed up repeated strings
1665 static $strcache = false;
1667 if ($strcache === false or count($strcache) > 2000 ) { // this number might need some tuning to limit memory usage in cron
1668 $strcache = array();
1672 if (empty($courseid)) {
1673 $courseid = $COURSE->id
;
1677 $md5 = md5($string.'<+>'.$striplinks.'<+>'.$courseid.'<+>'.current_language());
1679 //Fetch from cache if possible
1680 if (isset($strcache[$md5])) {
1681 return $strcache[$md5];
1684 // First replace all ampersands not followed by html entity code
1685 $string = preg_replace("/\&(?![a-zA-Z0-9#]{1,8};)/", "&", $string);
1687 if (!empty($CFG->filterall
)) {
1688 $string = filter_string($string, $courseid);
1691 // If the site requires it, strip ALL tags from this string
1692 if (!empty($CFG->formatstringstriptags
)) {
1693 $string = strip_tags($string);
1695 // Otherwise strip just links if that is required (default)
1696 } else if ($striplinks) { //strip links in string
1697 $string = preg_replace('/(<a[^>]+?>)(.+?)(<\/a>)/is','$2',$string);
1701 $strcache[$md5] = $string;
1707 * Given text in a variety of format codings, this function returns
1708 * the text as plain text suitable for plain email.
1710 * @uses FORMAT_MOODLE
1712 * @uses FORMAT_PLAIN
1714 * @uses FORMAT_MARKDOWN
1715 * @param string $text The text to be formatted. This is raw text originally from user input.
1716 * @param int $format Identifier of the text format to be used
1717 * (FORMAT_MOODLE, FORMAT_HTML, FORMAT_PLAIN, FORMAT_WIKI, FORMAT_MARKDOWN)
1720 function format_text_email($text, $format) {
1729 $text = wiki_to_html($text);
1730 /// This expression turns links into something nice in a text format. (Russell Jungwirth)
1731 /// From: http://php.net/manual/en/function.eregi-replace.php and simplified
1732 $text = eregi_replace('(<a [^<]*href=["|\']?([^ "\']*)["|\']?[^>]*>([^<]*)</a>)','\\3 [ \\2 ]', $text);
1733 return strtr(strip_tags($text), array_flip(get_html_translation_table(HTML_ENTITIES
)));
1737 return html_to_text($text);
1741 case FORMAT_MARKDOWN
:
1743 $text = eregi_replace('(<a [^<]*href=["|\']?([^ "\']*)["|\']?[^>]*>([^<]*)</a>)','\\3 [ \\2 ]', $text);
1744 return strtr(strip_tags($text), array_flip(get_html_translation_table(HTML_ENTITIES
)));
1750 * Given some text in HTML format, this function will pass it
1751 * through any filters that have been defined in $CFG->textfilterx
1752 * The variable defines a filepath to a file containing the
1753 * filter function. The file must contain a variable called
1754 * $textfilter_function which contains the name of the function
1755 * with $courseid and $text parameters
1757 * @param string $text The text to be passed through format filters
1758 * @param int $courseid ?
1760 * @todo Finish documenting this function
1762 function filter_text($text, $courseid=NULL) {
1763 global $CFG, $COURSE;
1765 if (empty($courseid)) {
1766 $courseid = $COURSE->id
; // (copied from format_text)
1769 if (!empty($CFG->textfilters
)) {
1770 require_once($CFG->libdir
.'/filterlib.php');
1771 $textfilters = explode(',', $CFG->textfilters
);
1772 foreach ($textfilters as $textfilter) {
1773 if (is_readable($CFG->dirroot
.'/'. $textfilter .'/filter.php')) {
1774 include_once($CFG->dirroot
.'/'. $textfilter .'/filter.php');
1775 $functionname = basename($textfilter).'_filter';
1776 if (function_exists($functionname)) {
1777 $text = $functionname($courseid, $text);
1783 /// <nolink> tags removed for XHTML compatibility
1784 $text = str_replace('<nolink>', '', $text);
1785 $text = str_replace('</nolink>', '', $text);
1792 * Given a string (short text) in HTML format, this function will pass it
1793 * through any filters that have been defined in $CFG->stringfilters
1794 * The variable defines a filepath to a file containing the
1795 * filter function. The file must contain a variable called
1796 * $textfilter_function which contains the name of the function
1797 * with $courseid and $text parameters
1799 * @param string $string The text to be passed through format filters
1800 * @param int $courseid The id of a course
1803 function filter_string($string, $courseid=NULL) {
1804 global $CFG, $COURSE;
1806 if (empty($CFG->textfilters
)) { // All filters are disabled anyway so quit
1810 if (empty($courseid)) {
1811 $courseid = $COURSE->id
;
1814 require_once($CFG->libdir
.'/filterlib.php');
1816 if (isset($CFG->stringfilters
)) { // We have a predefined list to use, great!
1817 if (empty($CFG->stringfilters
)) { // but it's blank, so finish now
1820 $stringfilters = explode(',', $CFG->stringfilters
); // ..use the list we have
1822 } else { // Otherwise try to derive a list from textfilters
1823 if (strpos($CFG->textfilters
, 'filter/multilang') !== false) { // Multilang is here
1824 $stringfilters = array('filter/multilang'); // Let's use just that
1825 $CFG->stringfilters
= 'filter/multilang'; // Save it for next time through
1827 $CFG->stringfilters
= ''; // Save the result and return
1833 foreach ($stringfilters as $stringfilter) {
1834 if (is_readable($CFG->dirroot
.'/'. $stringfilter .'/filter.php')) {
1835 include_once($CFG->dirroot
.'/'. $stringfilter .'/filter.php');
1836 $functionname = basename($stringfilter).'_filter';
1837 if (function_exists($functionname)) {
1838 $string = $functionname($courseid, $string);
1843 /// <nolink> tags removed for XHTML compatibility
1844 $string = str_replace('<nolink>', '', $string);
1845 $string = str_replace('</nolink>', '', $string);
1851 * Is the text marked as trusted?
1853 * @param string $text text to be searched for TRUSTTEXT marker
1856 function trusttext_present($text) {
1857 if (strpos($text, TRUSTTEXT
) !== FALSE) {
1865 * This funtion MUST be called before the cleaning or any other
1866 * function that modifies the data! We do not know the origin of trusttext
1867 * in database, if it gets there in tweaked form we must not convert it
1868 * to supported form!!!
1870 * Please be carefull not to use stripslashes on data from database
1871 * or twice stripslashes when processing data recieved from user.
1873 * @param string $text text that may contain TRUSTTEXT marker
1874 * @return text without any TRUSTTEXT marker
1876 function trusttext_strip($text) {
1879 while (true) { //removing nested TRUSTTEXT
1881 $text = str_replace(TRUSTTEXT
, '', $text);
1882 if (strcmp($orig, $text) === 0) {
1889 * Mark text as trusted, such text may contain any HTML tags because the
1890 * normal text cleaning will be bypassed.
1891 * Please make sure that the text comes from trusted user before storing
1894 function trusttext_mark($text) {
1896 if (!empty($CFG->enabletrusttext
) and (strpos($text, TRUSTTEXT
) === FALSE)) {
1897 return TRUSTTEXT
.$text;
1902 function trusttext_after_edit(&$text, $context) {
1903 if (has_capability('moodle/site:trustcontent', $context)) {
1904 $text = trusttext_strip($text);
1905 $text = trusttext_mark($text);
1907 $text = trusttext_strip($text);
1911 function trusttext_prepare_edit(&$text, &$format, $usehtmleditor, $context) {
1914 $options = new object();
1915 $options->smiley
= false;
1916 $options->filter
= false;
1917 if (!empty($CFG->enabletrusttext
)
1918 and has_capability('moodle/site:trustcontent', $context)
1919 and trusttext_present($text)) {
1920 $options->noclean
= true;
1922 $options->noclean
= false;
1924 $text = trusttext_strip($text);
1925 if ($usehtmleditor) {
1926 $text = format_text($text, $format, $options);
1927 $format = FORMAT_HTML
;
1928 } else if (!$options->noclean
){
1929 $text = clean_text($text, $format);
1934 * Given raw text (eg typed in by a user), this function cleans it up
1935 * and removes any nasty tags that could mess up Moodle pages.
1937 * @uses FORMAT_MOODLE
1938 * @uses FORMAT_PLAIN
1939 * @uses ALLOWED_TAGS
1940 * @param string $text The text to be cleaned
1941 * @param int $format Identifier of the text format to be used
1942 * (FORMAT_MOODLE, FORMAT_HTML, FORMAT_PLAIN, FORMAT_WIKI, FORMAT_MARKDOWN)
1943 * @return string The cleaned up text
1945 function clean_text($text, $format=FORMAT_MOODLE
) {
1947 global $ALLOWED_TAGS, $CFG;
1949 if (empty($text) or is_numeric($text)) {
1950 return (string)$text;
1955 case FORMAT_MARKDOWN
:
1960 if (!empty($CFG->enablehtmlpurifier
)) {
1961 $text = purify_html($text);
1963 /// Fix non standard entity notations
1964 $text = preg_replace('/(&#[0-9]+)(;?)/', "\\1;", $text);
1965 $text = preg_replace('/(&#x[0-9a-fA-F]+)(;?)/', "\\1;", $text);
1967 /// Remove tags that are not allowed
1968 $text = strip_tags($text, $ALLOWED_TAGS);
1970 /// Clean up embedded scripts and , using kses
1971 $text = cleanAttributes($text);
1973 /// Again remove tags that are not allowed
1974 $text = strip_tags($text, $ALLOWED_TAGS);
1978 /// Remove potential script events - some extra protection for undiscovered bugs in our code
1979 $text = eregi_replace("([^a-z])language([[:space:]]*)=", "\\1Xlanguage=", $text);
1980 $text = eregi_replace("([^a-z])on([a-z]+)([[:space:]]*)=", "\\1Xon\\2=", $text);
1987 * KSES replacement cleaning function - uses HTML Purifier.
1989 function purify_html($text) {
1992 // this can not be done only once because we sometimes need to reset the cache
1993 $cachedir = $CFG->dataroot
.'/cache/htmlpurifier/';
1994 $status = check_dir_exists($cachedir, true, true);
1996 static $purifier = false;
1997 if ($purifier === false) {
1998 require_once $CFG->libdir
.'/htmlpurifier/HTMLPurifier.auto.php';
1999 $config = HTMLPurifier_Config
::createDefault();
2000 $config->set('Core', 'AcceptFullDocuments', false);
2001 $config->set('Core', 'Encoding', 'UTF-8');
2002 $config->set('HTML', 'Doctype', 'XHTML 1.0 Transitional');
2003 $config->set('Cache', 'SerializerPath', $cachedir);
2004 $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));
2005 $purifier = new HTMLPurifier($config);
2007 return $purifier->purify($text);
2011 * This function takes a string and examines it for HTML tags.
2012 * If tags are detected it passes the string to a helper function {@link cleanAttributes2()}
2013 * which checks for attributes and filters them for malicious content
2014 * 17/08/2004 :: Eamon DOT Costello AT dcu DOT ie
2016 * @param string $str The string to be examined for html tags
2019 function cleanAttributes($str){
2020 $result = preg_replace_callback(
2021 '%(<[^>]*(>|$)|>)%m', #search for html tags
2029 * This function takes a string with an html tag and strips out any unallowed
2030 * protocols e.g. javascript:
2031 * It calls ancillary functions in kses which are prefixed by kses
2032 * 17/08/2004 :: Eamon DOT Costello AT dcu DOT ie
2034 * @param array $htmlArray An array from {@link cleanAttributes()}, containing in its 1st
2035 * element the html to be cleared
2038 function cleanAttributes2($htmlArray){
2040 global $CFG, $ALLOWED_PROTOCOLS;
2041 require_once($CFG->libdir
.'/kses.php');
2043 $htmlTag = $htmlArray[1];
2044 if (substr($htmlTag, 0, 1) != '<') {
2045 return '>'; //a single character ">" detected
2047 if (!preg_match('%^<\s*(/\s*)?([a-zA-Z0-9]+)([^>]*)>?$%', $htmlTag, $matches)) {
2048 return ''; // It's seriously malformed
2050 $slash = trim($matches[1]); //trailing xhtml slash
2051 $elem = $matches[2]; //the element name
2052 $attrlist = $matches[3]; // the list of attributes as a string
2054 $attrArray = kses_hair($attrlist, $ALLOWED_PROTOCOLS);
2057 foreach ($attrArray as $arreach) {
2058 $arreach['name'] = strtolower($arreach['name']);
2059 if ($arreach['name'] == 'style') {
2060 $value = $arreach['value'];
2062 $prevvalue = $value;
2063 $value = kses_no_null($value);
2064 $value = preg_replace("/\/\*.*\*\//Us", '', $value);
2065 $value = kses_decode_entities($value);
2066 $value = preg_replace('/(&#[0-9]+)(;?)/', "\\1;", $value);
2067 $value = preg_replace('/(&#x[0-9a-fA-F]+)(;?)/', "\\1;", $value);
2068 if ($value === $prevvalue) {
2069 $arreach['value'] = $value;
2073 $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']);
2074 $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']);
2075 $arreach['value'] = preg_replace("/b\s*i\s*n\s*d\s*i\s*n\s*g/i", "Xbinding", $arreach['value']);
2076 } else if ($arreach['name'] == 'href') {
2077 //Adobe Acrobat Reader XSS protection
2078 $arreach['value'] = preg_replace('/(\.(pdf|fdf|xfdf|xdp|xfd))[^a-z0-9_\.\-].*$/i', '$1', $arreach['value']);
2080 $attStr .= ' '.$arreach['name'].'="'.$arreach['value'].'"';
2084 if (preg_match('%/\s*$%', $attrlist)) {
2085 $xhtml_slash = ' /';
2087 return '<'. $slash . $elem . $attStr . $xhtml_slash .'>';
2091 * Replaces all known smileys in the text with image equivalents
2094 * @param string $text Passed by reference. The string to search for smily strings.
2097 function replace_smilies(&$text) {
2100 $lang = current_language();
2101 $emoticonstring = $CFG->emoticons
;
2102 static $e = array();
2103 static $img = array();
2104 static $emoticons = null;
2106 if (is_null($emoticons)) {
2107 $emoticons = array();
2108 if ($emoticonstring) {
2109 $items = explode('{;}', $CFG->emoticons
);
2110 foreach ($items as $item) {
2111 $item = explode('{:}', $item);
2112 $emoticons[$item[0]] = $item[1];
2118 if (empty($img[$lang])) { /// After the first time this is not run again
2119 $e[$lang] = array();
2120 $img[$lang] = array();
2121 foreach ($emoticons as $emoticon => $image){
2122 $alttext = get_string($image, 'pix');
2123 $e[$lang][] = $emoticon;
2124 $img[$lang][] = '<img alt="'. $alttext .'" width="15" height="15" src="'. $CFG->pixpath
.'/s/'. $image .'.gif" />';
2128 // Exclude from transformations all the code inside <script> tags
2129 // Needed to solve Bug 1185. Thanks to jouse 2001 detecting it. :-)
2130 // Based on code from glossary fiter by Williams Castillo.
2133 // Detect all the <script> zones to take out
2134 $excludes = array();
2135 preg_match_all('/<script language(.+?)<\/script>/is',$text,$list_of_excludes);
2137 // Take out all the <script> zones from text
2138 foreach (array_unique($list_of_excludes[0]) as $key=>$value) {
2139 $excludes['<+'.$key.'+>'] = $value;
2142 $text = str_replace($excludes,array_keys($excludes),$text);
2145 /// this is the meat of the code - this is run every time
2146 $text = str_replace($e[$lang], $img[$lang], $text);
2148 // Recover all the <script> zones to text
2150 $text = str_replace(array_keys($excludes),$excludes,$text);
2155 * Given plain text, makes it into HTML as nicely as possible.
2156 * May contain HTML tags already
2159 * @param string $text The string to convert.
2160 * @param boolean $smiley Convert any smiley characters to smiley images?
2161 * @param boolean $para If true then the returned string will be wrapped in paragraph tags
2162 * @param boolean $newlines If true then lines newline breaks will be converted to HTML newline breaks.
2166 function text_to_html($text, $smiley=true, $para=true, $newlines=true) {
2171 /// Remove any whitespace that may be between HTML tags
2172 $text = eregi_replace(">([[:space:]]+)<", "><", $text);
2174 /// Remove any returns that precede or follow HTML tags
2175 $text = eregi_replace("([\n\r])<", " <", $text);
2176 $text = eregi_replace(">([\n\r])", "> ", $text);
2178 convert_urls_into_links($text);
2180 /// Make returns into HTML newlines.
2182 $text = nl2br($text);
2185 /// Turn smileys into images.
2187 replace_smilies($text);
2190 /// Wrap the whole thing in a paragraph tag if required
2192 return '<p>'.$text.'</p>';
2199 * Given Markdown formatted text, make it into XHTML using external function
2202 * @param string $text The markdown formatted text to be converted.
2203 * @return string Converted text
2205 function markdown_to_html($text) {
2208 require_once($CFG->libdir
.'/markdown.php');
2210 return Markdown($text);
2214 * Given HTML text, make it into plain text using external function
2217 * @param string $html The text to be converted.
2220 function html_to_text($html) {
2224 require_once($CFG->libdir
.'/html2text.php');
2226 return html2text($html);
2230 * Given some text this function converts any URLs it finds into HTML links
2232 * @param string $text Passed in by reference. The string to be searched for urls.
2234 function convert_urls_into_links(&$text) {
2235 /// Make lone URLs into links. eg http://moodle.com/
2236 $text = eregi_replace("([[:space:]]|^|\(|\[)([[:alnum:]]+)://([^[:space:]]*)([[:alnum:]#?/&=])",
2237 "\\1<a href=\"\\2://\\3\\4\" target=\"_blank\">\\2://\\3\\4</a>", $text);
2239 /// eg www.moodle.com
2240 $text = eregi_replace("([[:space:]]|^|\(|\[)www\.([^[:space:]]*)([[:alnum:]#?/&=])",
2241 "\\1<a href=\"http://www.\\2\\3\" target=\"_blank\">www.\\2\\3</a>", $text);
2245 * This function will highlight search words in a given string
2246 * It cares about HTML and will not ruin links. It's best to use
2247 * this function after performing any conversions to HTML.
2248 * Function found here: http://forums.devshed.com/t67822/scdaa2d1c3d4bacb4671d075ad41f0854.html
2250 * @param string $needle The string to search for
2251 * @param string $haystack The string to search for $needle in
2252 * @param int $case whether to do case-sensitive or insensitive matching.
2254 * @todo Finish documenting this function
2256 function highlight($needle, $haystack, $case=0,
2257 $left_string='<span class="highlight">', $right_string='</span>') {
2259 if (empty($needle) or empty($haystack)) {
2263 //$list_of_words = eregi_replace("[^-a-zA-Z0-9&.']", " ", $needle); // bug 3101
2264 $list_of_words = $needle;
2265 $list_array = explode(' ', $list_of_words);
2266 for ($i=0; $i<sizeof($list_array); $i++
) {
2267 if (strlen($list_array[$i]) == 1) {
2268 $list_array[$i] = '';
2271 $list_of_words = implode(' ', $list_array);
2272 $list_of_words_cp = $list_of_words;
2274 preg_match_all('/<(.+?)>/is',$haystack,$list_of_words);
2276 foreach (array_unique($list_of_words[0]) as $key=>$value) {
2277 $final['<|'.$key.'|>'] = $value;
2280 $haystack = str_replace($final,array_keys($final),$haystack);
2281 $list_of_words_cp = eregi_replace(' +', '|', $list_of_words_cp);
2283 if ($list_of_words_cp{0}=='|') {
2284 $list_of_words_cp{0} = '';
2286 if ($list_of_words_cp{strlen($list_of_words_cp)-1}=='|') {
2287 $list_of_words_cp{strlen($list_of_words_cp)-1}='';
2290 $list_of_words_cp = trim($list_of_words_cp);
2292 if ($list_of_words_cp) {
2294 $list_of_words_cp = "(". $list_of_words_cp .")";
2297 $haystack = eregi_replace("$list_of_words_cp", "$left_string"."\\1"."$right_string", $haystack);
2299 $haystack = ereg_replace("$list_of_words_cp", "$left_string"."\\1"."$right_string", $haystack);
2302 $haystack = str_replace(array_keys($final),$final,$haystack);
2308 * This function will highlight instances of $needle in $haystack
2309 * It's faster that the above function and doesn't care about
2312 * @param string $needle The string to search for
2313 * @param string $haystack The string to search for $needle in
2316 function highlightfast($needle, $haystack) {
2318 if (empty($needle) or empty($haystack)) {
2322 $parts = explode(moodle_strtolower($needle), moodle_strtolower($haystack));
2324 if (count($parts) === 1) {
2330 foreach ($parts as $key => $part) {
2331 $parts[$key] = substr($haystack, $pos, strlen($part));
2332 $pos +
= strlen($part);
2334 $parts[$key] .= '<span class="highlight">'.substr($haystack, $pos, strlen($needle)).'</span>';
2335 $pos +
= strlen($needle);
2338 return str_replace('<span class="highlight"></span>', '', join('', $parts));
2342 * Return a string containing 'lang', xml:lang and optionally 'dir' HTML attributes.
2343 * Internationalisation, for print_header and backup/restorelib.
2344 * @param $dir Default false.
2345 * @return string Attributes.
2347 function get_html_lang($dir = false) {
2350 if (get_string('thisdirection') == 'rtl') {
2351 $direction = ' dir="rtl"';
2353 $direction = ' dir="ltr"';
2356 //Accessibility: added the 'lang' attribute to $direction, used in theme <html> tag.
2357 $language = str_replace('_', '-', str_replace('_utf8', '', current_language()));
2358 @header
('Content-Language: '.$language);
2359 return ($direction.' lang="'.$language.'" xml:lang="'.$language.'"');
2363 * Return the markup for the destination of the 'Skip to main content' links.
2364 * Accessibility improvement for keyboard-only users.
2365 * Used in course formats, /index.php and /course/index.php
2366 * @return string HTML element.
2368 function skip_main_destination() {
2369 return '<span id="maincontent"></span>';
2373 /// STANDARD WEB PAGE PARTS ///////////////////////////////////////////////////
2376 * Print a standard header
2381 * @param string $title Appears at the top of the window
2382 * @param string $heading Appears at the top of the page
2383 * @param array $navigation Array of $navlinks arrays (keys: name, link, type) for use as breadcrumbs links
2384 * @param string $focus Indicates form element to get cursor focus on load eg inputform.password
2385 * @param string $meta Meta tags to be added to the header
2386 * @param boolean $cache Should this page be cacheable?
2387 * @param string $button HTML code for a button (usually for module editing)
2388 * @param string $menu HTML code for a popup menu
2389 * @param boolean $usexml use XML for this page
2390 * @param string $bodytags This text will be included verbatim in the <body> tag (useful for onload() etc)
2391 * @param bool $return If true, return the visible elements of the header instead of echoing them.
2393 function print_header ($title='', $heading='', $navigation='', $focus='',
2394 $meta='', $cache=true, $button=' ', $menu='',
2395 $usexml=false, $bodytags='', $return=false) {
2397 global $USER, $CFG, $THEME, $SESSION, $ME, $SITE, $COURSE;
2399 if (gettype($navigation) == 'string' && strlen($navigation) != 0 && $navigation != 'home') {
2400 debugging("print_header() was sent a string as 3rd ($navigation) parameter. "
2401 . "This is deprecated in favour of an array built by build_navigation(). Please upgrade your code.", DEBUG_DEVELOPER
);
2404 $heading = format_string($heading); // Fix for MDL-8582
2406 /// This makes sure that the header is never repeated twice on a page
2407 if (defined('HEADER_PRINTED')) {
2408 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().');
2411 define('HEADER_PRINTED', 'true');
2414 /// Add the required stylesheets
2415 $stylesheetshtml = '';
2416 foreach ($CFG->stylesheets
as $stylesheet) {
2417 $stylesheetshtml .= '<link rel="stylesheet" type="text/css" href="'.$stylesheet.'" />'."\n";
2419 $meta = $stylesheetshtml.$meta;
2422 /// Add the meta page from the themes if any were requested
2426 if (!isset($THEME->standardmetainclude
) ||
$THEME->standardmetainclude
) {
2428 include_once($CFG->dirroot
.'/theme/standard/meta.php');
2429 $metapage .= ob_get_contents();
2433 if ($THEME->parent
&& (!isset($THEME->parentmetainclude
) ||
$THEME->parentmetainclude
)) {
2434 if (file_exists($CFG->dirroot
.'/theme/'.$THEME->parent
.'/meta.php')) {
2436 include_once($CFG->dirroot
.'/theme/'.$THEME->parent
.'/meta.php');
2437 $metapage .= ob_get_contents();
2442 if (!isset($THEME->metainclude
) ||
$THEME->metainclude
) {
2443 if (file_exists($CFG->dirroot
.'/theme/'.current_theme().'/meta.php')) {
2445 include_once($CFG->dirroot
.'/theme/'.current_theme().'/meta.php');
2446 $metapage .= ob_get_contents();
2451 $meta = $meta."\n".$metapage;
2453 $meta .= "\n".require_js('',1);
2455 /// Set up some navigation variables
2457 if (is_newnav($navigation)){
2460 if ($navigation == 'home') {
2468 /// This is another ugly hack to make navigation elements available to print_footer later
2469 $THEME->title
= $title;
2470 $THEME->heading
= $heading;
2471 $THEME->navigation
= $navigation;
2472 $THEME->button
= $button;
2473 $THEME->menu
= $menu;
2474 $navmenulist = isset($THEME->navmenulist
) ?
$THEME->navmenulist
: '';
2476 if ($button == '') {
2480 if (!$menu and $navigation) {
2481 if (empty($CFG->loginhttps
)) {
2482 $wwwroot = $CFG->wwwroot
;
2484 $wwwroot = str_replace('http:','https:',$CFG->wwwroot
);
2486 $menu = user_login_string($COURSE);
2489 if (isset($SESSION->justloggedin
)) {
2490 unset($SESSION->justloggedin
);
2491 if (!empty($CFG->displayloginfailures
)) {
2492 if (!empty($USER->username
) and $USER->username
!= 'guest') {
2493 if ($count = count_login_failures($CFG->displayloginfailures
, $USER->username
, $USER->lastlogin
)) {
2494 $menu .= ' <font size="1">';
2495 if (empty($count->accounts
)) {
2496 $menu .= get_string('failedloginattempts', '', $count);
2498 $menu .= get_string('failedloginattemptsall', '', $count);
2500 if (has_capability('moodle/site:viewreports', get_context_instance(CONTEXT_SYSTEM
))) {
2501 $menu .= ' (<a href="'.$CFG->wwwroot
.'/course/report/log/index.php'.
2502 '?chooselog=1&id=1&modid=site_errors">'.get_string('logs').'</a>)';
2511 $meta = '<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />' .
2512 "\n" . $meta . "\n";
2514 @header
('Content-Type: text/html; charset=utf-8');
2516 @header
('Content-Script-Type: text/javascript');
2517 @header
('Content-Style-Type: text/css');
2519 //Accessibility: added the 'lang' attribute to $direction, used in theme <html> tag.
2520 $direction = get_html_lang($dir=true);
2522 if ($cache) { // Allow caching on "back" (but not on normal clicks)
2523 @header
('Cache-Control: private, pre-check=0, post-check=0, max-age=0');
2524 @header
('Pragma: no-cache');
2525 @header
('Expires: ');
2526 } else { // Do everything we can to always prevent clients and proxies caching
2527 @header
('Cache-Control: no-store, no-cache, must-revalidate');
2528 @header
('Cache-Control: post-check=0, pre-check=0', false);
2529 @header
('Pragma: no-cache');
2530 @header
('Expires: Mon, 20 Aug 1969 09:23:00 GMT');
2531 @header
('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
2533 $meta .= "\n<meta http-equiv=\"pragma\" content=\"no-cache\" />";
2534 $meta .= "\n<meta http-equiv=\"expires\" content=\"0\" />";
2536 @header
('Accept-Ranges: none');
2538 $currentlanguage = current_language();
2540 if (empty($usexml)) {
2541 $direction = ' xmlns="http://www.w3.org/1999/xhtml"'. $direction; // See debug_header
2543 $mathplayer = preg_match("/MathPlayer/i", $_SERVER['HTTP_USER_AGENT']);
2545 header('Content-Type: application/xhtml+xml');
2547 echo '<?xml version="1.0" ?>'."\n";
2548 if (!empty($CFG->xml_stylesheets
)) {
2549 $stylesheets = explode(';', $CFG->xml_stylesheets
);
2550 foreach ($stylesheets as $stylesheet) {
2551 echo '<?xml-stylesheet type="text/xsl" href="'. $CFG->wwwroot
.'/'. $stylesheet .'" ?>' . "\n";
2554 echo '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1';
2555 if (!empty($CFG->xml_doctype_extra
)) {
2556 echo ' plus '. $CFG->xml_doctype_extra
;
2558 echo '//' . strtoupper($currentlanguage) . '" "'. $CFG->xml_dtd
.'">'."\n";
2559 $direction = " xmlns=\"http://www.w3.org/1999/xhtml\"
2560 xmlns:math=\"http://www.w3.org/1998/Math/MathML\"
2561 xmlns:xlink=\"http://www.w3.org/1999/xlink\"
2564 $meta .= '<object id="mathplayer" classid="clsid:32F66A20-7614-11D4-BD11-00104BD3F987">' . "\n";
2565 $meta .= '<!--comment required to prevent this becoming an empty tag-->'."\n";
2566 $meta .= '</object>'."\n";
2567 $meta .= '<?import namespace="math" implementation="#mathplayer" ?>' . "\n";
2571 // Clean up the title
2573 $title = format_string($title); // fix for MDL-8582
2574 $title = str_replace('"', '"', $title);
2576 // Create class and id for this page
2578 page_id_and_class($pageid, $pageclass);
2580 $pageclass .= ' course-'.$COURSE->id
;
2582 if (!isloggedin()) {
2583 $pageclass .= ' notloggedin';
2586 if (!empty($USER->editing
)) {
2587 $pageclass .= ' editing';
2590 if (!empty($CFG->blocksdrag
)) {
2591 $pageclass .= ' drag';
2594 $pageclass .= ' dir-'.get_string('thisdirection');
2596 $pageclass .= ' lang-'.$currentlanguage;
2598 $bodytags .= ' class="'.$pageclass.'" id="'.$pageid.'"';
2601 include($CFG->header
);
2602 $output = ob_get_contents();
2605 // container debugging info
2606 $THEME->open_header_containers
= open_containers();
2608 // Skip to main content, see skip_main_destination().
2609 if ($pageid=='course-view' or $pageid=='site-index' or $pageid=='course-index') {
2610 $skiplink = '<a class="skip" href="#maincontent">'.get_string('tocontent', 'access').'</a>';
2611 if (! preg_match('/(.*<div[^>]+id="page"[^>]*>)(.*)/s', $output, $matches)) {
2612 preg_match('/(.*<body.*?>)(.*)/s', $output, $matches);
2614 $output = $matches[1]."\n". $skiplink .$matches[2];
2617 $output = force_strict_header($output);
2619 if (!empty($CFG->messaging
)) {
2620 $output .= message_popup_window();
2623 // Add in any extra JavaScript libraries that occurred during the header
2624 $output .= require_js('', 2);
2634 * Used to include JavaScript libraries.
2636 * When the $lib parameter is given, the function will ensure that the
2637 * named library is loaded onto the page - either in the HTML <head>,
2638 * just after the header, or at an arbitrary later point in the page,
2639 * depending on where this function is called.
2641 * Libraries will not be included more than once, so this works like
2642 * require_once in PHP.
2644 * There are two special-case calls to this function which are both used only
2645 * by weblib print_header:
2646 * $extracthtml = 1: this is used before printing the header.
2647 * It returns the script tag code that should go inside the <head>.
2648 * $extracthtml = 2: this is used after printing the header and handles any
2649 * require_js calls that occurred within the header itself.
2651 * @param mixed $lib - string or array of strings
2652 * string(s) should be the shortname for the library or the
2653 * full path to the library file.
2654 * @param int $extracthtml Do not set this parameter usually (leave 0), only
2655 * weblib should set this to 1 or 2 in print_header function.
2656 * @return mixed No return value, except when using $extracthtml it returns the html code.
2658 function require_js($lib,$extracthtml=0) {
2660 static $loadlibs = array();
2662 static $state = REQUIREJS_BEFOREHEADER
;
2663 static $latecode = '';
2666 // Add the lib to the list of libs to be loaded, if it isn't already
2668 if (is_array($lib)) {
2669 foreach($lib as $singlelib) {
2670 require_js($singlelib);
2673 $libpath = ajax_get_lib($lib);
2674 if (array_search($libpath, $loadlibs) === false) {
2675 $loadlibs[] = $libpath;
2677 // For state other than 0 we need to take action as well as just
2678 // adding it to loadlibs
2679 if($state != REQUIREJS_BEFOREHEADER
) {
2680 // Get the script statement for this library
2681 $scriptstatement=get_require_js_code(array($libpath));
2683 if($state == REQUIREJS_AFTERHEADER
) {
2684 // After the header, print it immediately
2685 print $scriptstatement;
2687 // Haven't finished the header yet. Add it after the
2689 $latecode .= $scriptstatement;
2694 } else if($extracthtml==1) {
2695 if($state !== REQUIREJS_BEFOREHEADER
) {
2696 debugging('Incorrect state in require_js (expected BEFOREHEADER): be careful not to call with empty $lib (except in print_header)');
2698 $state = REQUIREJS_INHEADER
;
2701 return get_require_js_code($loadlibs);
2702 } else if($extracthtml==2) {
2703 if($state !== REQUIREJS_INHEADER
) {
2704 debugging('Incorrect state in require_js (expected INHEADER): be careful not to call with empty $lib (except in print_header)');
2707 $state = REQUIREJS_AFTERHEADER
;
2711 debugging('Unexpected value for $extracthtml');
2716 * Should not be called directly - use require_js. This function obtains the code
2717 * (script tags) needed to include JavaScript libraries.
2718 * @param array $loadlibs Array of library files to include
2719 * @return string HTML code to include them
2721 function get_require_js_code($loadlibs) {
2723 // Return the html needed to load the JavaScript files defined in
2724 // our list of libs to be loaded.
2726 foreach ($loadlibs as $loadlib) {
2727 $output .= '<script type="text/javascript" ';
2728 $output .= " src=\"$loadlib\"></script>\n";
2729 if ($loadlib == $CFG->wwwroot
.'/lib/yui/logger/logger-min.js') {
2730 // Special case, we need the CSS too.
2731 $output .= '<link type="text/css" rel="stylesheet" ';
2732 $output .= " href=\"{$CFG->wwwroot}/lib/yui/logger/assets/logger.css\" />\n";
2740 * Debugging aid: serve page as 'application/xhtml+xml' where possible,
2741 * and substitute the XHTML strict document type.
2742 * Note, requires the 'xmlns' fix in function print_header above.
2743 * See: http://tracker.moodle.org/browse/MDL-7883
2746 function force_strict_header($output) {
2748 $strict = '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">';
2749 $xsl = '/lib/xhtml.xsl';
2751 if (!headers_sent() && !empty($CFG->xmlstrictheaders
)) { // With xml strict headers, the browser will barf
2752 $ctype = 'Content-Type: ';
2753 $prolog= "<?xml version='1.0' encoding='utf-8'?>\n";
2755 if (isset($_SERVER['HTTP_ACCEPT'])
2756 && false !== strpos($_SERVER['HTTP_ACCEPT'], 'application/xhtml+xml')) {
2757 //|| false !== strpos($_SERVER['HTTP_USER_AGENT'], 'Safari') //Safari "Entity 'copy' not defined".
2759 $ctype .= 'application/xhtml+xml';
2760 $prolog .= "<!--\n DEBUG: $ctype \n-->\n";
2762 } else if (file_exists($CFG->dirroot
.$xsl)
2763 && preg_match('/MSIE.*Windows NT/', $_SERVER['HTTP_USER_AGENT'])) {
2764 // XSL hack for IE 5+ on Windows.
2765 //$www_xsl = preg_replace('/(http:\/\/.+?\/).*/', '', $CFG->wwwroot) .$xsl;
2766 $www_xsl = $CFG->wwwroot
.$xsl;
2767 $ctype .= 'application/xml';
2768 $prolog .= "<?xml-stylesheet type='text/xsl' href='$www_xsl'?>\n";
2769 $prolog .= "<!--\n DEBUG: $ctype \n-->\n";
2772 //ELSE: Mac/IE, old/non-XML browsers.
2773 $ctype .= 'text/html';
2776 @header
($ctype.'; charset=utf-8');
2777 $output = $prolog . $output;
2779 // Test parser error-handling.
2780 if (isset($_GET['error'])) {
2781 $output .= "__ TEST: XML well-formed error < __\n";
2785 $output = preg_replace('/(<!DOCTYPE.+?>)/s', $strict, $output); // Always change the DOCTYPE to Strict 1.0
2793 * This version of print_header is simpler because the course name does not have to be
2794 * provided explicitly in the strings. It can be used on the site page as in courses
2795 * Eventually all print_header could be replaced by print_header_simple
2797 * @param string $title Appears at the top of the window
2798 * @param string $heading Appears at the top of the page
2799 * @param string $navigation Premade navigation string (for use as breadcrumbs links)
2800 * @param string $focus Indicates form element to get cursor focus on load eg inputform.password
2801 * @param string $meta Meta tags to be added to the header
2802 * @param boolean $cache Should this page be cacheable?
2803 * @param string $button HTML code for a button (usually for module editing)
2804 * @param string $menu HTML code for a popup menu
2805 * @param boolean $usexml use XML for this page
2806 * @param string $bodytags This text will be included verbatim in the <body> tag (useful for onload() etc)
2807 * @param bool $return If true, return the visible elements of the header instead of echoing them.
2809 function print_header_simple($title='', $heading='', $navigation='', $focus='', $meta='',
2810 $cache=true, $button=' ', $menu='', $usexml=false, $bodytags='', $return=false) {
2812 global $COURSE, $CFG;
2814 // if we have no navigation specified, build it
2815 if( empty($navigation) ){
2816 $navigation = build_navigation('');
2819 // If old style nav prepend course short name otherwise leave $navigation object alone
2820 if (!is_newnav($navigation)) {
2821 if ($COURSE->id
!= SITEID
) {
2822 $shortname = '<a href="'.$CFG->wwwroot
.'/course/view.php?id='. $COURSE->id
.'">'. $COURSE->shortname
.'</a> ->';
2823 $navigation = $shortname.' '.$navigation;
2827 $output = print_header($COURSE->shortname
.': '. $title, $COURSE->fullname
.' '. $heading, $navigation, $focus, $meta,
2828 $cache, $button, $menu, $usexml, $bodytags, true);
2839 * Can provide a course object to make the footer contain a link to
2840 * to the course home page, otherwise the link will go to the site home
2842 * @param mixed $course course object, used for course link button or
2843 * 'none' means no user link, only docs link
2844 * 'empty' means nothing printed in footer
2845 * 'home' special frontpage footer
2846 * @param object $usercourse course used in user link
2847 * @param boolean $return output as string
2848 * @return mixed string or void
2850 function print_footer($course=NULL, $usercourse=NULL, $return=false) {
2851 global $USER, $CFG, $THEME, $COURSE;
2853 if (defined('ADMIN_EXT_HEADER_PRINTED') and !defined('ADMIN_EXT_FOOTER_PRINTED')) {
2854 admin_externalpage_print_footer();
2858 /// Course links or special footer
2860 if ($course === 'empty') {
2861 // special hack - sometimes we do not want even the docs link in footer
2863 if (!empty($THEME->open_header_containers
)) {
2864 for ($i=0; $i<$THEME->open_header_containers
; $i++
) {
2865 $output .= print_container_end_all(); // containers opened from header
2868 //1.8 theme compatibility
2869 $output .= "\n</div>"; // content div
2871 $output .= "\n</div>\n</body>\n</html>"; // close page div started in header
2879 } else if ($course === 'none') { // Don't print any links etc
2884 } else if ($course === 'home') { // special case for site home page - please do not remove
2885 $course = get_site();
2886 $homelink = '<div class="sitelink">'.
2887 '<a title="Moodle '. $CFG->release
.'" href="http://moodle.org/">'.
2888 '<img style="width:100px;height:30px" src="pix/moodlelogo.gif" alt="moodlelogo" /></a></div>';
2892 $homelink = '<div class="homelink"><a '.$CFG->frametarget
.' href="'.$CFG->wwwroot
.
2893 '/course/view.php?id='.$course->id
.'">'.format_string($course->shortname
).'</a></div>';
2898 $course = get_site(); // Set course as site course by default
2899 $homelink = '<div class="homelink"><a '.$CFG->frametarget
.' href="'.$CFG->wwwroot
.'/">'.get_string('home').'</a></div>';
2903 /// Set up some other navigation links (passed from print_header by ugly hack)
2904 $menu = isset($THEME->menu
) ?
str_replace('navmenu', 'navmenufooter', $THEME->menu
) : '';
2905 $title = isset($THEME->title
) ?
$THEME->title
: '';
2906 $button = isset($THEME->button
) ?
$THEME->button
: '';
2907 $heading = isset($THEME->heading
) ?
$THEME->heading
: '';
2908 $navigation = isset($THEME->navigation
) ?
$THEME->navigation
: '';
2909 $navmenulist = isset($THEME->navmenulist
) ?
$THEME->navmenulist
: '';
2912 /// Set the user link if necessary
2913 if (!$usercourse and is_object($course)) {
2914 $usercourse = $course;
2917 if (!isset($loggedinas)) {
2918 $loggedinas = user_login_string($usercourse, $USER);
2921 if ($loggedinas == $menu) {
2925 /// there should be exactly the same number of open containers as after the header
2926 if ($THEME->open_header_containers
!= open_containers()) {
2927 debugging('Unexpected number of open containers: '.open_containers().', expecting '.$THEME->open_header_containers
, DEBUG_DEVELOPER
);
2930 /// Provide some performance info if required
2931 $performanceinfo = '';
2932 if (defined('MDL_PERF') ||
(!empty($CFG->perfdebug
) and $CFG->perfdebug
> 7)) {
2933 $perf = get_performance_info();
2934 if (defined('MDL_PERFTOLOG') && !function_exists('register_shutdown_function')) {
2935 error_log("PERF: " . $perf['txt']);
2937 if (defined('MDL_PERFTOFOOT') ||
debugging() ||
$CFG->perfdebug
> 7) {
2938 $performanceinfo = $perf['html'];
2942 /// Include the actual footer file
2945 include($CFG->footer
);
2946 $output = ob_get_contents();
2957 * Returns the name of the current theme
2966 function current_theme() {
2967 global $CFG, $USER, $SESSION, $COURSE, $FULLME;
2969 if (empty($CFG->themeorder
)) {
2970 $themeorder = array('page', 'course', 'category', 'session', 'user', 'site');
2972 $themeorder = $CFG->themeorder
;
2975 if (isloggedin() and $USER->mnethostid
!= $CFG->mnet_localhost_id
) {
2976 require_once($CFG->dirroot
.'/mnet/peer.php');
2977 $mnet_peer = new mnet_peer();
2978 $mnet_peer->set_id($USER->mnethostid
);
2982 foreach ($themeorder as $themetype) {
2984 if (!empty($theme)) continue;
2986 switch ($themetype) {
2987 case 'page': // Page theme is for special page-only themes set by code
2988 if (!empty($CFG->pagetheme
)) {
2989 $theme = $CFG->pagetheme
;
2993 if (!empty($CFG->allowcoursethemes
) and !empty($COURSE->theme
)) {
2994 $theme = $COURSE->theme
;
2998 if (!empty($CFG->allowcategorythemes
)) {
2999 /// Nasty hack to check if we're in a category page
3000 if (stripos($FULLME, 'course/category.php') !== false) {
3003 $theme = current_category_theme($id);
3005 /// Otherwise check if we're in a course that has a category theme set
3006 } else if (!empty($COURSE->category
)) {
3007 $theme = current_category_theme($COURSE->category
);
3012 if (!empty($SESSION->theme
)) {
3013 $theme = $SESSION->theme
;
3017 if (!empty($CFG->allowuserthemes
) and !empty($USER->theme
)) {
3018 if (isloggedin() and $USER->mnethostid
!= $CFG->mnet_localhost_id
&& $mnet_peer->force_theme
== 1 && $mnet_peer->theme
!= '') {
3019 $theme = $mnet_peer->theme
;
3021 $theme = $USER->theme
;
3026 if (isloggedin() and $USER->mnethostid
!= $CFG->mnet_localhost_id
&& $mnet_peer->force_theme
== 1 && $mnet_peer->theme
!= '') {
3027 $theme = $mnet_peer->theme
;
3029 $theme = $CFG->theme
;
3037 /// A final check in case 'site' was not included in $CFG->themeorder
3038 if (empty($theme)) {
3039 $theme = $CFG->theme
;
3046 * Retrieves the category theme if one exists, otherwise checks the parent categories.
3047 * Recursive function.
3050 * @param integer $categoryid id of the category to check
3051 * @return string theme name
3053 function current_category_theme($categoryid=0) {
3056 /// Use the COURSE global if the categoryid not set
3057 if (empty($categoryid)) {
3058 if (!empty($COURSE->category
)) {
3059 $categoryid = $COURSE->category
;
3065 /// Retrieve the current category
3066 if ($category = get_record('course_categories', 'id', $categoryid)) {
3068 /// Return the category theme if it exists
3069 if (!empty($category->theme
)) {
3070 return $category->theme
;
3072 /// Otherwise try the parent category if one exists
3073 } else if (!empty($category->parent
)) {
3074 return current_category_theme($category->parent
);
3077 /// Return false if we can't find the category record
3084 * This function is called by stylesheets to set up the header
3085 * approriately as well as the current path
3088 * @param int $lastmodified ?
3089 * @param int $lifetime ?
3090 * @param string $thename ?
3092 function style_sheet_setup($lastmodified=0, $lifetime=300, $themename='', $forceconfig='', $lang='') {
3094 global $CFG, $THEME;
3096 // Fix for IE6 caching - we don't want the filemtime('styles.php'), instead use now.
3097 $lastmodified = time();
3099 header('Last-Modified: ' . gmdate("D, d M Y H:i:s", $lastmodified) . ' GMT');
3100 header('Expires: ' . gmdate("D, d M Y H:i:s", time() +
$lifetime) . ' GMT');
3101 header('Cache-Control: max-age='. $lifetime);
3103 header('Content-type: text/css'); // Correct MIME type
3105 $DEFAULT_SHEET_LIST = array('styles_layout', 'styles_fonts', 'styles_color');
3107 if (empty($themename)) {
3108 $themename = current_theme(); // So we have something. Normally not needed.
3110 $themename = clean_param($themename, PARAM_SAFEDIR
);
3113 if (!empty($forceconfig)) { // Page wants to use the config from this theme instead
3115 include($CFG->themedir
.'/'.$forceconfig.'/'.'config.php');
3118 /// If this is the standard theme calling us, then find out what sheets we need
3120 if ($themename == 'standard') {
3121 if (!isset($THEME->standardsheets
) or $THEME->standardsheets
=== true) { // Use all the sheets we have
3122 $THEME->sheets
= $DEFAULT_SHEET_LIST;
3123 } else if (empty($THEME->standardsheets
)) { // We can stop right now!
3124 echo "/***** Nothing required from this stylesheet by main theme *****/\n\n";
3126 } else { // Use the provided subset only
3127 $THEME->sheets
= $THEME->standardsheets
;
3130 /// If we are a parent theme, then check for parent definitions
3132 } else if (!empty($THEME->parent
) && $themename == $THEME->parent
) {
3133 if (!isset($THEME->parentsheets
) or $THEME->parentsheets
=== true) { // Use all the sheets we have
3134 $THEME->sheets
= $DEFAULT_SHEET_LIST;
3135 } else if (empty($THEME->parentsheets
)) { // We can stop right now!
3136 echo "/***** Nothing required from this stylesheet by main theme *****/\n\n";
3138 } else { // Use the provided subset only
3139 $THEME->sheets
= $THEME->parentsheets
;
3143 /// Work out the last modified date for this theme
3145 foreach ($THEME->sheets
as $sheet) {
3146 if (file_exists($CFG->themedir
.'/'.$themename.'/'.$sheet.'.css')) {
3147 $sheetmodified = filemtime($CFG->themedir
.'/'.$themename.'/'.$sheet.'.css');
3148 if ($sheetmodified > $lastmodified) {
3149 $lastmodified = $sheetmodified;
3155 /// Get a list of all the files we want to include
3158 foreach ($THEME->sheets
as $sheet) {
3159 $files[] = array($CFG->themedir
, $themename.'/'.$sheet.'.css');
3162 if ($themename == 'standard') { // Add any standard styles included in any modules
3163 if (!empty($THEME->modsheets
)) { // Search for styles.php within activity modules
3164 if ($mods = get_list_of_plugins('mod')) {
3165 foreach ($mods as $mod) {
3166 if (file_exists($CFG->dirroot
.'/mod/'.$mod.'/styles.php')) {
3167 $files[] = array($CFG->dirroot
, '/mod/'.$mod.'/styles.php');
3173 if (!empty($THEME->blocksheets
)) { // Search for styles.php within block modules
3174 if ($mods = get_list_of_plugins('blocks')) {
3175 foreach ($mods as $mod) {
3176 if (file_exists($CFG->dirroot
.'/blocks/'.$mod.'/styles.php')) {
3177 $files[] = array($CFG->dirroot
, '/blocks/'.$mod.'/styles.php');
3183 if (!isset($THEME->courseformatsheets
) ||
$THEME->courseformatsheets
) { // Search for styles.php in course formats
3184 if ($mods = get_list_of_plugins('format','',$CFG->dirroot
.'/course')) {
3185 foreach ($mods as $mod) {
3186 if (file_exists($CFG->dirroot
.'/course/format/'.$mod.'/styles.php')) {
3187 $files[] = array($CFG->dirroot
, '/course/format/'.$mod.'/styles.php');
3193 if (!isset($THEME->gradereportsheets
) ||
$THEME->gradereportsheets
) { // Search for styles.php in grade reports
3194 if ($reports = get_list_of_plugins('grade/report')) {
3195 foreach ($reports as $report) {
3196 if (file_exists($CFG->dirroot
.'/grade/report/'.$report.'/styles.php')) {
3197 $files[] = array($CFG->dirroot
, '/grade/report/'.$report.'/styles.php');
3203 if (!empty($THEME->langsheets
)) { // Search for styles.php within the current language
3204 if (file_exists($CFG->dirroot
.'/lang/'.$lang.'/styles.php')) {
3205 $files[] = array($CFG->dirroot
, '/lang/'.$lang.'/styles.php');
3211 /// Produce a list of all the files first
3212 echo '/**************************************'."\n";
3213 echo ' * THEME NAME: '.$themename."\n *\n";
3214 echo ' * Files included in this sheet:'."\n *\n";
3215 foreach ($files as $file) {
3216 echo ' * '.$file[1]."\n";
3218 echo ' **************************************/'."\n\n";
3221 /// check if csscobstants is set
3222 if (!empty($THEME->cssconstants
)) {
3223 require_once("$CFG->libdir/cssconstants.php");
3224 /// Actually collect all the files in order.
3226 foreach ($files as $file) {
3227 $css .= '/***** '.$file[1].' start *****/'."\n\n";
3228 $css .= file_get_contents($file[0].'/'.$file[1]);
3229 $ccs .= '/***** '.$file[1].' end *****/'."\n\n";
3231 /// replace css_constants with their values
3232 echo replace_cssconstants($css);
3234 /// Actually output all the files in order.
3235 if (empty($CFG->CSSEdit
) && empty($THEME->CSSEdit
)) {
3236 foreach ($files as $file) {
3237 echo '/***** '.$file[1].' start *****/'."\n\n";
3238 @include_once
($file[0].'/'.$file[1]);
3239 echo '/***** '.$file[1].' end *****/'."\n\n";
3242 foreach ($files as $file) {
3243 echo '/* @group '.$file[1].' */'."\n\n";
3244 if (strstr($file[1], '.css') !== FALSE) {
3245 echo '@import url("'.$CFG->themewww
.'/'.$file[1].'");'."\n\n";
3247 @include_once
($file[0].'/'.$file[1]);
3249 echo '/* @end */'."\n\n";
3255 return $CFG->themewww
.'/'.$themename; // Only to help old themes (1.4 and earlier)
3259 function theme_setup($theme = '', $params=NULL) {
3260 /// Sets up global variables related to themes
3262 global $CFG, $THEME, $SESSION, $USER, $HTTPSPAGEREQUIRED;
3264 /// Do not mess with THEME if header already printed - this would break all the extra stuff in global $THEME from print_header()!!
3265 if (defined('HEADER_PRINTED')) {
3269 if (empty($theme)) {
3270 $theme = current_theme();
3273 /// If the theme doesn't exist for some reason then revert to standardwhite
3274 if (!file_exists($CFG->themedir
.'/'. $theme .'/config.php')) {
3275 $CFG->theme
= $theme = 'standardwhite';
3278 /// Load up the theme config
3279 $THEME = NULL; // Just to be sure
3280 include($CFG->themedir
.'/'. $theme .'/config.php'); // Main config for current theme
3282 /// Put together the parameters
3287 if ($theme != $CFG->theme
) {
3288 $params[] = 'forceconfig='.$theme;
3291 /// Force language too if required
3292 if (!empty($THEME->langsheets
)) {
3293 $params[] = 'lang='.current_language();
3297 /// Convert params to string
3299 $paramstring = '?'.implode('&', $params);
3304 /// Set up image paths
3305 if(isset($CFG->smartpix
) && $CFG->smartpix
==1) {
3306 if($CFG->slasharguments
) { // Use this method if possible for better caching
3312 $CFG->pixpath
= $CFG->wwwroot
. '/pix/smartpix.php'.$extra.'/'.$theme;
3313 $CFG->modpixpath
= $CFG->wwwroot
.'/pix/smartpix.php'.$extra.'/'.$theme.'/mod';
3314 } else if (empty($THEME->custompix
)) { // Could be set in the above file
3315 $CFG->pixpath
= $CFG->wwwroot
.'/pix';
3316 $CFG->modpixpath
= $CFG->wwwroot
.'/mod';
3318 $CFG->pixpath
= $CFG->themewww
.'/'. $theme .'/pix';
3319 $CFG->modpixpath
= $CFG->themewww
.'/'. $theme .'/pix/mod';
3322 /// Header and footer paths
3323 $CFG->header
= $CFG->themedir
.'/'. $theme .'/header.html';
3324 $CFG->footer
= $CFG->themedir
.'/'. $theme .'/footer.html';
3326 /// Define stylesheet loading order
3327 $CFG->stylesheets
= array();
3328 if ($theme != 'standard') { /// The standard sheet is always loaded first
3329 $CFG->stylesheets
[] = $CFG->themewww
.'/standard/styles.php'.$paramstring;
3331 if (!empty($THEME->parent
)) { /// Parent stylesheets are loaded next
3332 $CFG->stylesheets
[] = $CFG->themewww
.'/'.$THEME->parent
.'/styles.php'.$paramstring;
3334 $CFG->stylesheets
[] = $CFG->themewww
.'/'.$theme.'/styles.php'.$paramstring;
3336 /// We have to change some URLs in styles if we are in a $HTTPSPAGEREQUIRED page
3337 if (!empty($HTTPSPAGEREQUIRED)) {
3338 $CFG->themewww
= str_replace('http:', 'https:', $CFG->themewww
);
3339 $CFG->pixpath
= str_replace('http:', 'https:', $CFG->pixpath
);
3340 $CFG->modpixpath
= str_replace('http:', 'https:', $CFG->modpixpath
);
3341 foreach ($CFG->stylesheets
as $key => $stylesheet) {
3342 $CFG->stylesheets
[$key] = str_replace('http:', 'https:', $stylesheet);
3346 // RTL support - only for RTL languages, add RTL CSS
3347 if (get_string('thisdirection') == 'rtl') {
3348 $CFG->stylesheets
[] = $CFG->themewww
.'/standard/rtl.css'.$paramstring;
3349 $CFG->stylesheets
[] = $CFG->themewww
.'/'.$theme.'/rtl.css'.$paramstring;
3355 * Returns text to be displayed to the user which reflects their login status
3359 * @param course $course {@link $COURSE} object containing course information
3360 * @param user $user {@link $USER} object containing user information
3363 function user_login_string($course=NULL, $user=NULL) {
3364 global $USER, $CFG, $SITE;
3366 if (empty($user) and !empty($USER->id
)) {
3370 if (empty($course)) {
3374 if (!empty($user->realuser
)) {
3375 if ($realuser = get_record('user', 'id', $user->realuser
)) {
3376 $fullname = fullname($realuser, true);
3377 $realuserinfo = " [<a $CFG->frametarget
3378 href=\"$CFG->wwwroot/course/loginas.php?id=$course->id&return=1&sesskey=".sesskey()."\">$fullname</a>] ";
3384 if (empty($CFG->loginhttps
)) {
3385 $wwwroot = $CFG->wwwroot
;
3387 $wwwroot = str_replace('http:','https:',$CFG->wwwroot
);
3390 if (empty($course->id
)) {
3391 // $course->id is not defined during installation
3393 } else if (!empty($user->id
)) {
3394 $context = get_context_instance(CONTEXT_COURSE
, $course->id
);
3396 $fullname = fullname($user, true);
3397 $username = "<a $CFG->frametarget href=\"$CFG->wwwroot/user/view.php?id=$user->id&course=$course->id\">$fullname</a>";
3398 if (is_mnet_remote_user($user) and $idprovider = get_record('mnet_host', 'id', $user->mnethostid
)) {
3399 $username .= " from <a $CFG->frametarget href=\"{$idprovider->wwwroot}\">{$idprovider->name}</a>";
3401 if (isset($user->username
) && $user->username
== 'guest') {
3402 $loggedinas = $realuserinfo.get_string('loggedinasguest').
3403 " (<a $CFG->frametarget href=\"$wwwroot/login/index.php\">".get_string('login').'</a>)';
3404 } else if (!empty($user->access
['rsw'][$context->path
])) {
3406 if ($role = get_record('role', 'id', $user->access
['rsw'][$context->path
])) {
3407 $rolename = ': '.format_string($role->name
);
3409 $loggedinas = get_string('loggedinas', 'moodle', $username).$rolename.
3410 " (<a $CFG->frametarget
3411 href=\"$CFG->wwwroot/course/view.php?id=$course->id&switchrole=0&sesskey=".sesskey()."\">".get_string('switchrolereturn').'</a>)';
3413 $loggedinas = $realuserinfo.get_string('loggedinas', 'moodle', $username).' '.
3414 " (<a $CFG->frametarget href=\"$CFG->wwwroot/login/logout.php?sesskey=".sesskey()."\">".get_string('logout').'</a>)';
3417 $loggedinas = get_string('loggedinnot', 'moodle').
3418 " (<a $CFG->frametarget href=\"$wwwroot/login/index.php\">".get_string('login').'</a>)';
3420 return '<div class="logininfo">'.$loggedinas.'</div>';
3424 * Tests whether $THEME->rarrow, $THEME->larrow have been set (theme/-/config.php).
3425 * If not it applies sensible defaults.
3427 * Accessibility: right and left arrow Unicode characters for breadcrumb, calendar,
3428 * search forum block, etc. Important: these are 'silent' in a screen-reader
3429 * (unlike > »), and must be accompanied by text.
3432 function check_theme_arrows() {
3435 if (!isset($THEME->rarrow
) and !isset($THEME->larrow
)) {
3436 // Default, looks good in Win XP/IE 6, Win/Firefox 1.5, Win/Netscape 8...
3437 // Also OK in Win 9x/2K/IE 5.x
3438 $THEME->rarrow
= '►';
3439 $THEME->larrow
= '◄';
3440 $uagent = $_SERVER['HTTP_USER_AGENT'];
3441 if (false !== strpos($uagent, 'Opera')
3442 ||
false !== strpos($uagent, 'Mac')) {
3443 // Looks good in Win XP/Mac/Opera 8/9, Mac/Firefox 2, Camino, Safari.
3444 // Not broken in Mac/IE 5, Mac/Netscape 7 (?).
3445 $THEME->rarrow
= '▶';
3446 $THEME->larrow
= '◀';
3448 elseif (false !== strpos($uagent, 'Konqueror')) {
3449 $THEME->rarrow
= '→';
3450 $THEME->larrow
= '←';
3452 elseif (isset($_SERVER['HTTP_ACCEPT_CHARSET'])
3453 && false === stripos($_SERVER['HTTP_ACCEPT_CHARSET'], 'utf-8')) {
3454 // (Win/IE 5 doesn't set ACCEPT_CHARSET, but handles Unicode.)
3455 // To be safe, non-Unicode browsers!
3456 $THEME->rarrow
= '>';
3457 $THEME->larrow
= '<';
3460 /// RTL support - in RTL languages, swap r and l arrows
3461 if (right_to_left()) {
3462 $t = $THEME->rarrow
;
3463 $THEME->rarrow
= $THEME->larrow
;
3464 $THEME->larrow
= $t;
3471 * Return the right arrow with text ('next'), and optionally embedded in a link.
3472 * See function above, check_theme_arrows.
3473 * @param string $text HTML/plain text label (set to blank only for breadcrumb separator cases).
3474 * @param string $url An optional link to use in a surrounding HTML anchor.
3475 * @param bool $accesshide True if text should be hidden (for screen readers only).
3476 * @param string $addclass Additional class names for the link, or the arrow character.
3477 * @return string HTML string.
3479 function link_arrow_right($text, $url='', $accesshide=false, $addclass='') {
3481 check_theme_arrows();
3482 $arrowclass = 'arrow ';
3484 $arrowclass .= $addclass;
3486 $arrow = '<span class="'.$arrowclass.'">'.$THEME->rarrow
.'</span>';
3489 $htmltext = $text.' ';
3491 $htmltext = get_accesshide($htmltext);
3497 $class =" class=\"$addclass\"";
3499 return '<a'.$class.' href="'.$url.'" title="'.preg_replace('/<.*?>/','',$text).'">'.$htmltext.$arrow.'</a>';
3501 return $htmltext.$arrow;
3505 * Return the left arrow with text ('previous'), and optionally embedded in a link.
3506 * See function above, check_theme_arrows.
3507 * @param string $text HTML/plain text label (set to blank only for breadcrumb separator cases).
3508 * @param string $url An optional link to use in a surrounding HTML anchor.
3509 * @param bool $accesshide True if text should be hidden (for screen readers only).
3510 * @param string $addclass Additional class names for the link, or the arrow character.
3511 * @return string HTML string.
3513 function link_arrow_left($text, $url='', $accesshide=false, $addclass='') {
3515 check_theme_arrows();
3516 $arrowclass = 'arrow ';
3518 $arrowclass .= $addclass;
3520 $arrow = '<span class="'.$arrowclass.'">'.$THEME->larrow
.'</span>';
3523 $htmltext = ' '.$text;
3525 $htmltext = get_accesshide($htmltext);
3531 $class =" class=\"$addclass\"";
3533 return '<a'.$class.' href="'.$url.'" title="'.preg_replace('/<.*?>/','',$text).'">'.$arrow.$htmltext.'</a>';
3535 return $arrow.$htmltext;
3539 * Return a HTML element with the class "accesshide", for accessibility.
3540 * Please use cautiously - where possible, text should be visible!
3541 * @param string $text Plain text.
3542 * @param string $elem Lowercase element name, default "span".
3543 * @param string $class Additional classes for the element.
3544 * @param string $attrs Additional attributes string in the form, "name='value' name2='value2'"
3545 * @return string HTML string.
3547 function get_accesshide($text, $elem='span', $class='', $attrs='') {
3548 return "<$elem class=\"accesshide $class\" $attrs>$text</$elem>";
3552 * Return the breadcrumb trail navigation separator.
3553 * @return string HTML string.
3555 function get_separator() {
3556 //Accessibility: the 'hidden' slash is preferred for screen readers.
3557 return ' '.link_arrow_right($text='/', $url='', $accesshide=true, 'sep').' ';
3561 * Prints breadcrumb trail of links, called in theme/-/header.html
3564 * @param mixed $navigation The breadcrumb navigation string to be printed
3565 * @param string $separator The breadcrumb trail separator. The default 0 leads to the use
3566 * of $THEME->rarrow, themes could use '→', '/', or '' for a style-sheet solution.
3567 * @param boolean $return False to echo the breadcrumb string (default), true to return it.
3569 function print_navigation ($navigation, $separator=0, $return=false) {
3570 global $CFG, $THEME;
3573 if (0 === $separator) {
3574 $separator = get_separator();
3577 $separator = '<span class="sep">'. $separator .'</span>';
3582 if (is_newnav($navigation)) {
3584 return($navigation['navlinks']);
3586 echo $navigation['navlinks'];
3590 debugging('Navigation needs to be updated to use build_navigation()', DEBUG_DEVELOPER
);
3593 if (!is_array($navigation)) {
3594 $ar = explode('->', $navigation);
3595 $navigation = array();
3597 foreach ($ar as $a) {
3598 if (strpos($a, '</a>') === false) {
3599 $navigation[] = array('title' => $a, 'url' => '');
3601 if (preg_match('/<a.*href="([^"]*)">(.*)<\/a>/', $a, $matches)) {
3602 $navigation[] = array('title' => $matches[2], 'url' => $matches[1]);
3608 if (! $site = get_site()) {
3609 $site = new object();
3610 $site->shortname
= get_string('home');
3613 //Accessibility: breadcrumb links now in a list, » replaced with a 'silent' character.
3614 $output .= get_accesshide(get_string('youarehere','access'), 'h2')."<ul>\n";
3616 $output .= '<li class="first">'."\n".'<a '.$CFG->frametarget
.' onclick="this.target=\''.$CFG->framename
.'\'" href="'
3617 .$CFG->wwwroot
.((!has_capability('moodle/site:config', get_context_instance(CONTEXT_SYSTEM
))
3618 && !empty($USER->id
) && !empty($CFG->mymoodleredirect
) && !isguest())
3619 ?
'/my' : '') .'/">'. format_string($site->shortname
) ."</a>\n</li>\n";
3622 foreach ($navigation as $navitem) {
3623 $title = trim(strip_tags(format_string($navitem['title'], false)));
3624 $url = $navitem['url'];
3627 $output .= '<li class="first">'."$separator $title</li>\n";
3629 $output .= '<li class="first">'."$separator\n<a ".$CFG->frametarget
.' onclick="this.target=\''.$CFG->framename
.'\'" href="'
3630 .$url.'">'."$title</a>\n</li>\n";
3634 $output .= "</ul>\n";
3645 * This function will build the navigation string to be used by print_header
3648 * It automatically generates the site and course level (if appropriate) links.
3650 * If you pass in a $cm object, the method will also generate the activity (e.g. 'Forums')
3651 * and activityinstances (e.g. 'General Developer Forum') navigation levels.
3653 * If you want to add any further navigation links after the ones this function generates,
3654 * the pass an array of extra link arrays like this:
3656 * array('name' => $linktext1, 'link' => $url1, 'type' => $linktype1),
3657 * array('name' => $linktext2, 'link' => $url2, 'type' => $linktype2)
3659 * The normal case is to just add one further link, for example 'Editing forum' after
3660 * 'General Developer Forum', with no link.
3661 * To do that, you need to pass
3662 * array(array('name' => $linktext, 'link' => '', 'type' => 'title'))
3663 * However, becuase this is a very common case, you can use a shortcut syntax, and just
3664 * pass the string 'Editing forum', instead of an array as $extranavlinks.
3666 * At the moment, the link types only have limited significance. Type 'activity' is
3667 * recognised in order to implement the $CFG->hideactivitytypenavlink feature. Types
3668 * that are known to appear are 'home', 'course', 'activity', 'activityinstance' and 'title'.
3669 * This really needs to be documented better. In the mean time, try to be consistent, it will
3670 * enable people to customise the navigation more in future.
3672 * When passing a $cm object, the fields used are $cm->modname, $cm->name and $cm->course.
3673 * If you get the $cm object using the function get_coursemodule_from_instance or
3674 * get_coursemodule_from_id (as recommended) then this will be done for you automatically.
3675 * If you don't have $cm->modname or $cm->name, this fuction will attempt to find them using
3676 * the $cm->module and $cm->instance fields, but this takes extra database queries, so a
3677 * warning is printed in developer debug mode.
3682 * @param mixed $extranavlinks - Normally an array of arrays, keys: name, link, type. If you
3683 * only want one extra item with no link, you can pass a string instead. If you don't want
3684 * any extra links, pass an empty string.
3685 * @param mixed $cm - optionally the $cm object, if you want this function to generate the
3686 * activity and activityinstance levels of navigation too.
3688 * @return $navigation as an object so it can be differentiated from old style
3689 * navigation strings.
3691 function build_navigation($extranavlinks, $cm = null) {
3692 global $CFG, $COURSE;
3694 if (is_string($extranavlinks)) {
3695 if ($extranavlinks == '') {
3696 $extranavlinks = array();
3698 $extranavlinks = array(array('name' => $extranavlinks, 'link' => '', 'type' => 'title'));
3702 $navlinks = array();
3705 if ($site = get_site()) {
3706 $navlinks[] = array(
3707 'name' => format_string($site->shortname
),
3708 'link' => "$CFG->wwwroot/",
3712 // Course name, if appropriate.
3713 if (isset($COURSE) && $COURSE->id
!= SITEID
) {
3714 $navlinks[] = array(
3715 'name' => format_string($COURSE->shortname
),
3716 'link' => "$CFG->wwwroot/course/view.php?id=$COURSE->id",
3717 'type' => 'course');
3720 // Activity type and instance, if appropriate.
3721 if (is_object($cm)) {
3722 if (!isset($cm->modname
)) {
3723 debugging('The field $cm->modname should be set if you call build_navigation with '.
3724 'a $cm parameter. If you get $cm using get_coursemodule_from_instance or '.
3725 'get_coursemodule_from_id, this will be done automatically.', DEBUG_DEVELOPER
);
3726 if (!$cm->modname
= get_field('modules', 'name', 'id', $cm->module
)) {
3727 error('Cannot get the module type in build navigation.');
3730 if (!isset($cm->name
)) {
3731 debugging('The field $cm->name should be set if you call build_navigation with '.
3732 'a $cm parameter. If you get $cm using get_coursemodule_from_instance or '.
3733 'get_coursemodule_from_id, this will be done automatically.', DEBUG_DEVELOPER
);
3734 if (!$cm->name
= get_field($cm->modname
, 'name', 'id', $cm->instance
)) {
3735 error('Cannot get the module name in build navigation.');
3738 $navlinks[] = array(
3739 'name' => get_string('modulenameplural', $cm->modname
),
3740 'link' => $CFG->wwwroot
. '/mod/' . $cm->modname
. '/index.php?id=' . $cm->course
,
3741 'type' => 'activity');
3742 $navlinks[] = array(
3743 'name' => format_string($cm->name
),
3744 'link' => $CFG->wwwroot
. '/mod/' . $cm->modname
. '/view.php?id=' . $cm->id
,
3745 'type' => 'activityinstance');
3748 //Merge in extra navigation links
3749 $navlinks = array_merge($navlinks, $extranavlinks);
3751 // Work out whether we should be showing the activity (e.g. Forums) link.
3752 // Note: build_navigation() is called from many places --
3753 // install & upgrade for example -- where we cannot count on the
3754 // roles infrastructure to be defined. Hence the $CFG->rolesactive check.
3755 if (!isset($CFG->hideactivitytypenavlink
)) {
3756 $CFG->hideactivitytypenavlink
= 0;
3758 if ($CFG->hideactivitytypenavlink
== 2) {
3759 $hideactivitylink = true;
3760 } else if ($CFG->hideactivitytypenavlink
== 1 && $CFG->rolesactive
&&
3761 !empty($COURSE->id
) && $COURSE->id
!= SITEID
) {
3762 if (!isset($COURSE->context
)) {
3763 $COURSE->context
= get_context_instance(CONTEXT_COURSE
, $COURSE->id
);
3765 $hideactivitylink = !has_capability('moodle/course:manageactivities', $COURSE->context
);
3767 $hideactivitylink = false;
3770 //Construct an unordered list from $navlinks
3771 //Accessibility: heading hidden from visual browsers by default.
3772 $navigation = get_accesshide(get_string('youarehere','access'), 'h2')." <ul>\n";
3773 $lastindex = count($navlinks) - 1;
3774 $i = -1; // Used to count the times, so we know when we get to the last item.
3776 foreach ($navlinks as $navlink) {
3778 $last = ($i == $lastindex);
3779 if (!is_array($navlink)) {
3782 if ($navlink['type'] == 'activity' && !$last && $hideactivitylink) {
3785 $navigation .= '<li class="first">';
3787 $navigation .= get_separator();
3789 if ((!empty($navlink['link'])) && !$last) {
3790 $navigation .= "<a onclick=\"this.target='$CFG->framename'\" href=\"{$navlink['link']}\">";
3792 $navigation .= "{$navlink['name']}";
3793 if ((!empty($navlink['link'])) && !$last) {
3794 $navigation .= "</a>";
3797 $navigation .= "</li>";
3800 $navigation .= "</ul>";
3802 return(array('newnav' => true, 'navlinks' => $navigation));
3807 * Prints a string in a specified size (retained for backward compatibility)
3809 * @param string $text The text to be displayed
3810 * @param int $size The size to set the font for text display.
3812 function print_headline($text, $size=2, $return=false) {
3813 $output = print_heading($text, '', $size, true);
3822 * Prints text in a format for use in headings.
3824 * @param string $text The text to be displayed
3825 * @param string $align The alignment of the printed paragraph of text
3826 * @param int $size The size to set the font for text display.
3828 function print_heading($text, $align='', $size=2, $class='main', $return=false) {
3830 $align = ' style="text-align:'.$align.';"';
3833 $class = ' class="'.$class.'"';
3835 $output = "<h$size $align $class>".stripslashes_safe($text)."</h$size>";
3845 * Centered heading with attached help button (same title text)
3846 * and optional icon attached
3848 * @param string $text The text to be displayed
3849 * @param string $helppage The help page to link to
3850 * @param string $module The module whose help should be linked to
3851 * @param string $icon Image to display if needed
3853 function print_heading_with_help($text, $helppage, $module='moodle', $icon='', $return=false) {
3855 $output .= '<h2 class="main help">'.$icon.stripslashes_safe($text);
3856 $output .= helpbutton($helppage, $text, $module, true, false, '', true);
3867 function print_heading_block($heading, $class='', $return=false) {
3868 //Accessibility: 'headingblock' is now H1, see theme/standard/styles_*.css: ??
3869 $output = '<h2 class="headingblock header '.$class.'">'.stripslashes($heading).'</h2>';
3880 * Print a link to continue on to another page.
3883 * @param string $link The url to create a link to.
3885 function print_continue($link, $return=false) {
3889 // in case we are logging upgrade in admin/index.php stop it
3890 if (function_exists('upgrade_log_finish')) {
3891 upgrade_log_finish();
3897 if (!empty($_SERVER['HTTP_REFERER'])) {
3898 $link = $_SERVER['HTTP_REFERER'];
3899 $link = str_replace('&', '&', $link); // make it valid XHTML
3901 $link = $CFG->wwwroot
.'/';
3906 $linkparts = parse_url(str_replace('&', '&', $link));
3907 if (isset($linkparts['query'])) {
3908 parse_str($linkparts['query'], $options);
3911 $output .= '<div class="continuebutton">';
3913 $output .= print_single_button($link, $options, get_string('continue'), 'get', $CFG->framename
, true);
3914 $output .= '</div>'."\n";
3925 * Print a message in a standard themed box.
3926 * Replaces print_simple_box (see deprecatedlib.php)
3928 * @param string $message, the content of the box
3929 * @param string $classes, space-separated class names.
3930 * @param string $idbase
3931 * @param boolean $return, return as string or just print it
3932 * @return mixed string or void
3934 function print_box($message, $classes='generalbox', $ids='', $return=false) {
3936 $output = print_box_start($classes, $ids, true);
3937 $output .= stripslashes_safe($message);
3938 $output .= print_box_end(true);
3948 * Starts a box using divs
3949 * Replaces print_simple_box_start (see deprecatedlib.php)
3951 * @param string $classes, space-separated class names.
3952 * @param string $idbase
3953 * @param boolean $return, return as string or just print it
3954 * @return mixed string or void
3956 function print_box_start($classes='generalbox', $ids='', $return=false) {
3959 if (strpos($classes, 'clearfix') !== false) {
3961 $classes = trim(str_replace('clearfix', '', $classes));
3966 if (!empty($THEME->customcorners
)) {
3967 $classes .= ' ccbox box';
3972 return print_container_start($clearfix, $classes, $ids, $return);
3976 * Simple function to end a box (see above)
3977 * Replaces print_simple_box_end (see deprecatedlib.php)
3979 * @param boolean $return, return as string or just print it
3981 function print_box_end($return=false) {
3982 return print_container_end($return);
3986 * Print a message in a standard themed container.
3988 * @param string $message, the content of the container
3989 * @param boolean $clearfix clear both sides
3990 * @param string $classes, space-separated class names.
3991 * @param string $idbase
3992 * @param boolean $return, return as string or just print it
3993 * @return string or void
3995 function print_container($message, $clearfix=false, $classes='', $idbase='', $return=false) {
3997 $output = print_container_start($clearfix, $classes, $idbase, true);
3998 $output .= stripslashes_safe($message);
3999 $output .= print_container_end(true);
4009 * Starts a container using divs
4011 * @param boolean $clearfix clear both sides
4012 * @param string $classes, space-separated class names.
4013 * @param string $idbase
4014 * @param boolean $return, return as string or just print it
4015 * @return mixed string or void
4017 function print_container_start($clearfix=false, $classes='', $idbase='', $return=false) {
4020 if (!isset($THEME->open_containers
)) {
4021 $THEME->open_containers
= array();
4023 $THEME->open_containers
[] = $idbase;
4026 if (!empty($THEME->customcorners
)) {
4027 $output = _print_custom_corners_start($clearfix, $classes, $idbase);
4030 $id = ' id="'.$idbase.'"';
4035 $clearfix = ' clearfix';
4039 if ($classes or $clearfix) {
4040 $class = ' class="'.$classes.$clearfix.'"';
4044 $output = '<div'.$id.$class.'>';
4055 * Simple function to end a container (see above)
4056 * @param boolean $return, return as string or just print it
4057 * @return mixed string or void
4059 function print_container_end($return=false) {
4062 if (empty($THEME->open_containers
)) {
4063 debugging('Incorrect request to end container - no more open containers.', DEBUG_DEVELOPER
);
4066 $idbase = array_pop($THEME->open_containers
);
4069 if (!empty($THEME->customcorners
)) {
4070 $output = _print_custom_corners_end($idbase);
4083 * Returns number of currently open containers
4084 * @return int number of open containers
4086 function open_containers() {
4089 if (!isset($THEME->open_containers
)) {
4090 $THEME->open_containers
= array();
4093 return count($THEME->open_containers
);
4097 * Force closing of open containers
4098 * @param boolean $return, return as string or just print it
4099 * @param int $keep number of containers to be kept open - usually theme or page containers
4100 * @return mixed string or void
4102 function print_container_end_all($return=false, $keep=0) {
4104 while (open_containers() > $keep) {
4105 $output .= print_container_end($return);
4116 * Internal function - do not use directly!
4117 * Starting part of the surrounding divs for custom corners
4119 * @param boolean $clearfix, add CLASS "clearfix" to the inner div against collapsing
4120 * @param string $classes
4121 * @param mixed $idbase, optionally, define one idbase to be added to all the elements in the corners
4124 function _print_custom_corners_start($clearfix=false, $classes='', $idbase='') {
4125 /// Analise if we want ids for the custom corner elements
4133 $id = 'id="'.$idbase.'" ';
4134 $idbt = 'id="'.$idbase.'-bt" ';
4135 $idi1 = 'id="'.$idbase.'-i1" ';
4136 $idi2 = 'id="'.$idbase.'-i2" ';
4137 $idi3 = 'id="'.$idbase.'-i3" ';
4140 /// Calculate current level
4141 $level = open_containers();
4144 $output = '<div '.$id.'class="wrap wraplevel'.$level.' '.$classes.'">'."\n";
4145 $output .= '<div '.$idbt.'class="bt"><div> </div></div>';
4147 $output .= '<div '.$idi1.'class="i1"><div '.$idi2.'class="i2">';
4148 $output .= (!empty($clearfix)) ?
'<div '.$idi3.'class="i3 clearfix">' : '<div '.$idi3.'class="i3">';
4155 * Internal function - do not use directly!
4156 * Ending part of the surrounding divs for custom corners
4157 * @param string $idbase
4160 function _print_custom_corners_end($idbase) {
4161 /// Analise if we want ids for the custom corner elements
4165 $idbb = 'id="' . $idbase . '-bb" ';
4169 $output = '</div></div></div>';
4171 $output .= '<div '.$idbb.'class="bb"><div> </div></div>'."\n";
4172 $output .= '</div>';
4179 * Print a self contained form with a single submit button.
4181 * @param string $link used as the action attribute on the form, so the URL that will be hit if the button is clicked.
4182 * @param array $options these become hidden form fields, so these options get passed to the script at $link.
4183 * @param string $label the caption that appears on the button.
4184 * @param string $method HTTP method used on the request of the button is clicked. 'get' or 'post'.
4185 * @param string $target no longer used.
4186 * @param boolean $return if false, output the form directly, otherwise return the HTML as a string.
4187 * @param string $tooltip a tooltip to add to the button as a title attribute.
4188 * @param boolean $disabled if true, the button will be disabled.
4189 * @param string $jsconfirmmessage if not empty then display a confirm dialogue with this string as the question.
4190 * @return string / nothing depending on the $return paramter.
4192 function print_single_button($link, $options, $label='OK', $method='get', $target='_self', $return=false, $tooltip='', $disabled = false, $jsconfirmmessage='') {
4194 $link = str_replace('"', '"', $link); //basic XSS protection
4195 $output .= '<div class="singlebutton">';
4196 // taking target out, will need to add later target="'.$target.'"
4197 $output .= '<form action="'. $link .'" method="'. $method .'">';
4200 foreach ($options as $name => $value) {
4201 $output .= '<input type="hidden" name="'. $name .'" value="'. s($value) .'" />';
4205 $tooltip = 'title="' . s($tooltip) . '"';
4210 $disabled = 'disabled="disabled"';
4214 if ($jsconfirmmessage){
4215 $jsconfirmmessage = addslashes_js($jsconfirmmessage);
4216 $jsconfirmmessage = 'onclick="return confirm(\''. $jsconfirmmessage .'\');" ';
4218 $output .= '<input type="submit" value="'. s($label) ."\" $tooltip $disabled $jsconfirmmessage/></div></form></div>";
4229 * Print a spacer image with the option of including a line break.
4231 * @param int $height ?
4232 * @param int $width ?
4233 * @param boolean $br ?
4234 * @todo Finish documenting this function
4236 function print_spacer($height=1, $width=1, $br=true, $return=false) {
4240 $output .= '<img class="spacer" height="'. $height .'" width="'. $width .'" src="'. $CFG->wwwroot
.'/pix/spacer.gif" alt="" />';
4242 $output .= '<br />'."\n";
4253 * Given the path to a picture file in a course, or a URL,
4254 * this function includes the picture in the page.
4256 * @param string $path ?
4257 * @param int $courseid ?
4258 * @param int $height ?
4259 * @param int $width ?
4260 * @param string $link ?
4261 * @todo Finish documenting this function
4263 function print_file_picture($path, $courseid=0, $height='', $width='', $link='', $return=false) {
4268 $height = 'height="'. $height .'"';
4271 $width = 'width="'. $width .'"';
4274 $output .= '<a href="'. $link .'">';
4276 if (substr(strtolower($path), 0, 7) == 'http://') {
4277 $output .= '<img style="height:'.$height.'px;width:'.$width.'px;" src="'. $path .'" />';
4279 } else if ($courseid) {
4280 $output .= '<img style="height:'.$height.'px;width:'.$width.'px;" src="';
4281 if ($CFG->slasharguments
) { // Use this method if possible for better caching
4282 $output .= $CFG->wwwroot
.'/file.php/'. $courseid .'/'. $path;
4284 $output .= $CFG->wwwroot
.'/file.php?file=/'. $courseid .'/'. $path;
4288 $output .= 'Error: must pass URL or course';
4302 * Print the specified user's avatar.
4304 * If you pass a $user object that has id, picture, imagealt, firstname, lastname
4305 * you save a DB query.
4307 * @param int $user takes a userid, or a userobj
4308 * @param int $courseid ?
4309 * @param boolean $picture Print the user picture?
4310 * @param int $size Size in pixels. Special values are (true/1 = 100px) and (false/0 = 35px) for backward compatability
4311 * @param boolean $return If false print picture to current page, otherwise return the output as string
4312 * @param boolean $link Enclose printed image in a link to view specified course?
4313 * @param string $target link target attribute
4314 * @param boolean $alttext use username or userspecified text in image alt attribute
4316 * @todo Finish documenting this function
4318 function print_user_picture($user, $courseid, $picture=NULL, $size=0, $return=false, $link=true, $target='', $alttext=true) {
4319 global $CFG, $HTTPSPAGEREQUIRED;
4322 // only touch the DB if we are missing data...
4323 if (is_object($user)) {
4324 // Note - both picture and imagealt _can_ be empty
4325 // what we are trying to see here is if they have been fetched
4326 // from the DB. We should use isset() _except_ that some installs
4327 // have those fields as nullable, and isset() will return false
4328 // on null. The only safe thing is to ask array_key_exists()
4329 // which works on objects. property_exists() isn't quite
4330 // what we want here...
4331 if (! (array_key_exists('picture', $user)
4332 && ($alttext && array_key_exists('imagealt', $user)
4333 ||
(isset($user->firstname
) && isset($user->lastname
)))) ) {
4339 // we need firstname, lastname, imagealt, can't escape...
4342 $userobj = new StdClass
; // fake it to save DB traffic
4343 $userobj->id
= $user;
4344 $userobj->picture
= $picture;
4345 $user = clone($userobj);
4350 $user = get_record('user','id',$user, '', '', '', '', 'id,firstname,lastname,imagealt');
4355 $target=' target="_blank"';
4357 $output = '<a '.$target.' href="'. $CFG->wwwroot
.'/user/view.php?id='. $user->id
.'&course='. $courseid .'">';
4364 } else if ($size === true or $size == 1) {
4367 } else if ($size >= 50) {
4372 $class = "userpicture";
4373 if (!empty($HTTPSPAGEREQUIRED)) {
4374 $wwwroot = $CFG->httpswwwroot
;
4376 $wwwroot = $CFG->wwwroot
;
4379 if (is_null($picture)) {
4380 $picture = $user->picture
;
4383 if ($picture) { // Print custom user picture
4384 if ($CFG->slasharguments
) { // Use this method if possible for better caching
4385 $src = $wwwroot .'/user/pix.php/'. $user->id
.'/'. $file .'.jpg';
4387 $src = $wwwroot .'/user/pix.php?file=/'. $user->id
.'/'. $file .'.jpg';
4389 } else { // Print default user pictures (use theme version if available)
4390 $class .= " defaultuserpic";
4391 $src = "$CFG->pixpath/u/$file.png";
4395 if (!empty($user->imagealt
)) {
4396 $imagealt = $user->imagealt
;
4398 $imagealt = get_string('pictureof','',fullname($user));
4402 $output .= '<img class="'.$class.'" src="'.$src.'" alt="'.s($imagealt).'" />';
4415 * Prints a summary of a user in a nice little box.
4419 * @param user $user A {@link $USER} object representing a user
4420 * @param course $course A {@link $COURSE} object representing a course
4422 function print_user($user, $course, $messageselect=false, $return=false) {
4432 $context = get_context_instance(CONTEXT_COURSE
, $course->id
);
4433 if (isset($user->context
->id
)) {
4434 $usercontext = get_context_instance_by_id($user->context
->id
);
4437 if (empty($string)) { // Cache all the strings for the rest of the page
4439 $string->email
= get_string('email');
4440 $string->city
= get_string('city');
4441 $string->lastaccess
= get_string('lastaccess');
4442 $string->activity
= get_string('activity');
4443 $string->unenrol
= get_string('unenrol');
4444 $string->loginas
= get_string('loginas');
4445 $string->fullprofile
= get_string('fullprofile');
4446 $string->role
= get_string('role');
4447 $string->name
= get_string('name');
4448 $string->never
= get_string('never');
4450 $datestring->day
= get_string('day');
4451 $datestring->days
= get_string('days');
4452 $datestring->hour
= get_string('hour');
4453 $datestring->hours
= get_string('hours');
4454 $datestring->min
= get_string('min');
4455 $datestring->mins
= get_string('mins');
4456 $datestring->sec
= get_string('sec');
4457 $datestring->secs
= get_string('secs');
4458 $datestring->year
= get_string('year');
4459 $datestring->years
= get_string('years');
4461 $countries = get_list_of_countries();
4464 /// Get the hidden field list
4465 if (has_capability('moodle/course:viewhiddenuserfields', $context)) {
4466 $hiddenfields = array();
4468 $hiddenfields = array_flip(explode(',', $CFG->hiddenuserfields
));
4471 $output .= '<table class="userinfobox">';
4473 $output .= '<td class="left side">';
4474 $output .= print_user_picture($user, $course->id
, $user->picture
, true, true);
4476 $output .= '<td class="content">';
4477 $output .= '<div class="username">'.fullname($user, has_capability('moodle/site:viewfullnames', $context)).'</div>';
4478 $output .= '<div class="info">';
4479 if (!empty($user->role
) and ($user->role
<> $course->teacher
)) {
4480 $output .= $string->role
.': '. $user->role
.'<br />';
4482 if ($user->maildisplay
== 1 or ($user->maildisplay
== 2 and ($course->id
!= SITEID
) and !isguest()) or
4483 has_capability('moodle/course:viewhiddenuserfields', $context)) {
4484 $output .= $string->email
.': <a href="mailto:'. $user->email
.'">'. $user->email
.'</a><br />';
4486 if (($user->city
or $user->country
) and (!isset($hiddenfields['city']) or !isset($hiddenfields['country']))) {
4487 $output .= $string->city
.': ';
4488 if ($user->city
&& !isset($hiddenfields['city'])) {
4489 $output .= $user->city
;
4491 if (!empty($countries[$user->country
]) && !isset($hiddenfields['country'])) {
4492 if ($user->city
&& !isset($hiddenfields['city'])) {
4495 $output .= $countries[$user->country
];
4497 $output .= '<br />';
4500 if (!isset($hiddenfields['lastaccess'])) {
4501 if ($user->lastaccess
) {
4502 $output .= $string->lastaccess
.': '. userdate($user->lastaccess
);
4503 $output .= ' ('. format_time(time() - $user->lastaccess
, $datestring) .')';
4505 $output .= $string->lastaccess
.': '. $string->never
;
4508 $output .= '</div></td><td class="links">';
4510 if ($CFG->bloglevel
> 0) {
4511 $output .= '<a href="'.$CFG->wwwroot
.'/blog/index.php?userid='.$user->id
.'">'.get_string('blogs','blog').'</a><br />';
4514 if (has_capability('moodle/notes:manage', $context) ||
has_capability('moodle/notes:view', $context)) {
4515 $output .= '<a href="'.$CFG->wwwroot
.'/notes/index.php?course=' . $course->id
. '&user='.$user->id
.'">'.get_string('notes','notes').'</a><br />';
4518 if (has_capability('moodle/user:viewuseractivitiesreport', $context) ||
(isset($usercontext) && has_capability('moodle/user:viewuseractivitiesreport', $usercontext))) {
4519 $timemidnight = usergetmidnight(time());
4520 $output .= '<a href="'. $CFG->wwwroot
.'/course/user.php?id='. $course->id
.'&user='. $user->id
.'">'. $string->activity
.'</a><br />';
4522 if (has_capability('moodle/role:assign', $context, NULL)) { // Includes admins
4523 $output .= '<a href="'. $CFG->wwwroot
.'/course/unenrol.php?id='. $course->id
.'&user='. $user->id
.'">'. $string->unenrol
.'</a><br />';
4525 if ($USER->id
!= $user->id
&& empty($USER->realuser
) && has_capability('moodle/user:loginas', $context) &&
4526 ! has_capability('moodle/site:doanything', $context, $user->id
, false)) {
4527 $output .= '<a href="'. $CFG->wwwroot
.'/course/loginas.php?id='. $course->id
.'&user='. $user->id
.'&sesskey='. sesskey() .'">'. $string->loginas
.'</a><br />';
4529 $output .= '<a href="'. $CFG->wwwroot
.'/user/view.php?id='. $user->id
.'&course='. $course->id
.'">'. $string->fullprofile
.'...</a>';
4531 if (!empty($messageselect)) {
4532 $output .= '<br /><input type="checkbox" name="user'.$user->id
.'" /> ';
4535 $output .= '</td></tr></table>';
4545 * Print a specified group's avatar.
4547 * @param group $group A single {@link group} object OR array of groups.
4548 * @param int $courseid The course ID.
4549 * @param boolean $large Default small picture, or large.
4550 * @param boolean $return If false print picture, otherwise return the output as string
4551 * @param boolean $link Enclose image in a link to view specified course?
4553 * @todo Finish documenting this function
4555 function print_group_picture($group, $courseid, $large=false, $return=false, $link=true) {
4558 if (is_array($group)) {
4560 foreach($group as $g) {
4561 $output .= print_group_picture($g, $courseid, $large, true, $link);
4571 $context = get_context_instance(CONTEXT_COURSE
, $courseid);
4573 if ($group->hidepicture
and !has_capability('moodle/course:managegroups', $context)) {
4577 if ($link or has_capability('moodle/site:accessallgroups', $context)) {
4578 $output = '<a href="'. $CFG->wwwroot
.'/user/index.php?id='. $courseid .'&group='. $group->id
.'">';
4589 if ($group->picture
) { // Print custom group picture
4590 if ($CFG->slasharguments
) { // Use this method if possible for better caching
4591 $output .= '<img class="grouppicture" src="'.$CFG->wwwroot
.'/user/pixgroup.php/'.$group->id
.'/'.$file.'.jpg"'.
4592 ' style="width:'.$size.'px;height:'.$size.'px;" alt="'.s(get_string('group').' '.$group->name
).'" title="'.s($group->name
).'"/>';
4594 $output .= '<img class="grouppicture" src="'.$CFG->wwwroot
.'/user/pixgroup.php?file=/'.$group->id
.'/'.$file.'.jpg"'.
4595 ' style="width:'.$size.'px;height:'.$size.'px;" alt="'.s(get_string('group').' '.$group->name
).'" title="'.s($group->name
).'"/>';
4598 if ($link or has_capability('moodle/site:accessallgroups', $context)) {
4610 * Print a png image.
4612 * @param string $url ?
4613 * @param int $sizex ?
4614 * @param int $sizey ?
4615 * @param boolean $return ?
4616 * @param string $parameters ?
4617 * @todo Finish documenting this function
4619 function print_png($url, $sizex, $sizey, $return, $parameters='alt=""') {
4623 if (!isset($recentIE)) {
4624 $recentIE = check_browser_version('MSIE', '5.0');
4627 if ($recentIE) { // work around the HORRIBLE bug IE has with alpha transparencies
4628 $output .= '<img src="'. $CFG->pixpath
.'/spacer.gif" width="'. $sizex .'" height="'. $sizey .'"'.
4629 ' class="png" style="width: '. $sizex .'px; height: '. $sizey .'px; '.
4630 ' filter: progid:DXImageTransform.Microsoft.AlphaImageLoader(src='.
4631 "'$url', sizingMethod='scale') ".
4632 ' '. $parameters .' />';
4634 $output .= '<img src="'. $url .'" style="width: '. $sizex .'px; height: '. $sizey .'px; '. $parameters .' />';
4645 * Print a nicely formatted table.
4647 * @param array $table is an object with several properties.
4649 * <li>$table->head - An array of heading names.
4650 * <li>$table->align - An array of column alignments
4651 * <li>$table->size - An array of column sizes
4652 * <li>$table->wrap - An array of "nowrap"s or nothing
4653 * <li>$table->data[] - An array of arrays containing the data.
4654 * <li>$table->width - A percentage of the page
4655 * <li>$table->tablealign - Align the whole table
4656 * <li>$table->cellpadding - Padding on each cell
4657 * <li>$table->cellspacing - Spacing between cells
4658 * <li>$table->class - class attribute to put on the table
4659 * <li>$table->id - id attribute to put on the table.
4660 * <li>$table->rowclass[] - classes to add to particular rows.
4661 * <li>$table->summary - Description of the contents for screen readers.
4663 * @param bool $return whether to return an output string or echo now
4664 * @return boolean or $string
4665 * @todo Finish documenting this function
4667 function print_table($table, $return=false) {
4670 if (isset($table->align
)) {
4671 foreach ($table->align
as $key => $aa) {
4673 $align[$key] = ' text-align:'. fix_align_rtl($aa) .';'; // Fix for RTL languages
4679 if (isset($table->size
)) {
4680 foreach ($table->size
as $key => $ss) {
4682 $size[$key] = ' width:'. $ss .';';
4688 if (isset($table->wrap
)) {
4689 foreach ($table->wrap
as $key => $ww) {
4691 $wrap[$key] = ' white-space:nowrap;';
4698 if (empty($table->width
)) {
4699 $table->width
= '80%';
4702 if (empty($table->tablealign
)) {
4703 $table->tablealign
= 'center';
4706 if (!isset($table->cellpadding
)) {
4707 $table->cellpadding
= '5';
4710 if (!isset($table->cellspacing
)) {
4711 $table->cellspacing
= '1';
4714 if (empty($table->class)) {
4715 $table->class = 'generaltable';
4718 $tableid = empty($table->id
) ?
'' : 'id="'.$table->id
.'"';
4720 $output .= '<table width="'.$table->width
.'" ';
4721 if (!empty($table->summary
)) {
4722 $output .= " summary=\"$table->summary\"";
4724 $output .= " cellpadding=\"$table->cellpadding\" cellspacing=\"$table->cellspacing\" class=\"$table->class boxalign$table->tablealign\" $tableid>\n";
4728 if (!empty($table->head
)) {
4729 $countcols = count($table->head
);
4731 foreach ($table->head
as $key => $heading) {
4733 if (!isset($size[$key])) {
4736 if (!isset($align[$key])) {
4740 $output .= '<th style="vertical-align:top;'. $align[$key].$size[$key] .';white-space:nowrap;" class="header c'.$key.'" scope="col">'. $heading .'</th>';
4742 $output .= '</tr>'."\n";
4745 if (!empty($table->data
)) {
4747 foreach ($table->data
as $key => $row) {
4748 $oddeven = $oddeven ?
0 : 1;
4749 if (!isset($table->rowclass
[$key])) {
4750 $table->rowclass
[$key] = '';
4752 $output .= '<tr class="r'.$oddeven.' '.$table->rowclass
[$key].'">'."\n";
4753 if ($row == 'hr' and $countcols) {
4754 $output .= '<td colspan="'. $countcols .'"><div class="tabledivider"></div></td>';
4755 } else { /// it's a normal row of data
4756 foreach ($row as $key => $item) {
4757 if (!isset($size[$key])) {
4760 if (!isset($align[$key])) {
4763 if (!isset($wrap[$key])) {
4766 $output .= '<td style="'. $align[$key].$size[$key].$wrap[$key] .'" class="cell c'.$key.'">'. $item .'</td>';
4769 $output .= '</tr>'."\n";
4772 $output .= '</table>'."\n";
4782 function print_recent_activity_note($time, $user, $text, $link, $return=false, $viewfullnames=null) {
4783 static $strftimerecent = null;
4786 if (is_null($viewfullnames)) {
4787 $context = get_context_instance(CONTEXT_SYSTEM
);
4788 $viewfullnames = has_capability('moodle/site:viewfullnames', $context);
4791 if (is_null($strftimerecent)) {
4792 $strftimerecent = get_string('strftimerecent');
4795 $output .= '<div class="head">';
4796 $output .= '<div class="date">'.userdate($time, $strftimerecent).'</div>';
4797 $output .= '<div class="name">'.fullname($user, $viewfullnames).'</div>';
4798 $output .= '</div>';
4799 $output .= '<div class="info"><a href="'.$link.'">'.format_string($text,true).'</a></div>';
4810 * Prints a basic textarea field.
4813 * @param boolean $usehtmleditor ?
4814 * @param int $rows ?
4815 * @param int $cols ?
4816 * @param null $width <b>Legacy field no longer used!</b> Set to zero to get control over mincols
4817 * @param null $height <b>Legacy field no longer used!</b> Set to zero to get control over minrows
4818 * @param string $name ?
4819 * @param string $value ?
4820 * @param int $courseid ?
4821 * @todo Finish documenting this function
4823 function print_textarea($usehtmleditor, $rows, $cols, $width, $height, $name, $value='', $courseid=0, $return=false, $id='') {
4824 /// $width and height are legacy fields and no longer used as pixels like they used to be.
4825 /// However, you can set them to zero to override the mincols and minrows values below.
4827 global $CFG, $COURSE, $HTTPSPAGEREQUIRED;
4828 static $scriptcount = 0; // For loading the htmlarea script only once.
4835 $id = 'edit-'.$name;
4838 if ( empty($CFG->editorsrc
) ) { // for backward compatibility.
4839 if (empty($courseid)) {
4840 $courseid = $COURSE->id
;
4843 if ($usehtmleditor) {
4844 if (!empty($courseid) and has_capability('moodle/course:managefiles', get_context_instance(CONTEXT_COURSE
, $courseid))) {
4845 $httpsrequired = empty($HTTPSPAGEREQUIRED) ?
'' : '&httpsrequired=1';
4846 // needed for course file area browsing in image insert plugin
4847 $str .= ($scriptcount < 1) ?
'<script type="text/javascript" src="'.
4848 $CFG->httpswwwroot
.'/lib/editor/htmlarea/htmlarea.php?id='.$courseid.$httpsrequired.'"></script>'."\n" : '';
4850 $httpsrequired = empty($HTTPSPAGEREQUIRED) ?
'' : '?httpsrequired=1';
4851 $str .= ($scriptcount < 1) ?
'<script type="text/javascript" src="'.
4852 $CFG->httpswwwroot
.'/lib/editor/htmlarea/htmlarea.php'.$httpsrequired.'"></script>'."\n" : '';
4855 $str .= ($scriptcount < 1) ?
'<script type="text/javascript" src="'.
4856 $CFG->httpswwwroot
.'/lib/editor/htmlarea/lang/en.php"></script>'."\n" : '';
4859 if ($height) { // Usually with legacy calls
4860 if ($rows < $minrows) {
4864 if ($width) { // Usually with legacy calls
4865 if ($cols < $mincols) {
4871 $str .= '<textarea class="form-textarea" id="'. $id .'" name="'. $name .'" rows="'. $rows .'" cols="'. $cols .'">';
4872 if ($usehtmleditor) {
4873 $str .= htmlspecialchars($value); // needed for editing of cleaned text!
4877 $str .= '</textarea>'."\n";
4879 if ($usehtmleditor) {
4880 // Show shortcuts button if HTML editor is in use, but only if JavaScript is enabled (MDL-9556)
4881 $str .= '<script type="text/javascript">
4883 document.write(\''.addslashes_js(editorshortcutshelpbutton()).'\');
4895 * Sets up the HTML editor on textareas in the current page.
4896 * If a field name is provided, then it will only be
4897 * applied to that field - otherwise it will be used
4898 * on every textarea in the page.
4900 * In most cases no arguments need to be supplied
4902 * @param string $name Form element to replace with HTMl editor by name
4904 function use_html_editor($name='', $editorhidebuttons='', $id='') {
4907 $editor = 'editor_'.md5($name); //name might contain illegal characters
4909 $id = 'edit-'.$name;
4911 echo "\n".'<script type="text/javascript" defer="defer">'."\n";
4912 echo '//<![CDATA['."\n\n"; // Extra \n is to fix odd wiki problem, MDL-8185
4913 echo "$editor = new HTMLArea('$id');\n";
4914 echo "var config = $editor.config;\n";
4916 echo print_editor_config($editorhidebuttons);
4918 if (empty($THEME->htmleditorpostprocess
)) {
4920 echo "\nHTMLArea.replaceAll($editor.config);\n";
4922 echo "\n$editor.generate();\n";
4926 echo "\nvar HTML_name = '';";
4928 echo "\nvar HTML_name = \"$name;\"";
4930 echo "\nvar HTML_editor = $editor;";
4933 echo '</script>'."\n";
4936 function print_editor_config($editorhidebuttons='', $return=false) {
4939 $str = "config.pageStyle = \"body {";
4941 if (!(empty($CFG->editorbackgroundcolor
))) {
4942 $str .= " background-color: $CFG->editorbackgroundcolor;";
4945 if (!(empty($CFG->editorfontfamily
))) {
4946 $str .= " font-family: $CFG->editorfontfamily;";
4949 if (!(empty($CFG->editorfontsize
))) {
4950 $str .= " font-size: $CFG->editorfontsize;";
4954 $str .= "config.killWordOnPaste = ";
4955 $str .= (empty($CFG->editorkillword
)) ?
"false":"true";
4957 $str .= 'config.fontname = {'."\n";
4959 $fontlist = isset($CFG->editorfontlist
) ?
explode(';', $CFG->editorfontlist
) : array();
4960 $i = 1; // Counter is used to get rid of the last comma.
4962 foreach ($fontlist as $fontline) {
4963 if (!empty($fontline)) {
4967 list($fontkey, $fontvalue) = split(':', $fontline);
4968 $str .= '"'. $fontkey ."\":\t'". $fontvalue ."'";
4975 if (!empty($editorhidebuttons)) {
4976 $str .= "\nconfig.hideSomeButtons(\" ". $editorhidebuttons ." \");\n";
4977 } else if (!empty($CFG->editorhidebuttons
)) {
4978 $str .= "\nconfig.hideSomeButtons(\" ". $CFG->editorhidebuttons
." \");\n";
4981 if (!empty($CFG->editorspelling
) && !empty($CFG->aspellpath
)) {
4982 $str .= print_speller_code($CFG->htmleditor
, true);
4992 * Returns a turn edit on/off button for course in a self contained form.
4993 * Used to be an icon, but it's now a simple form button
4995 * Note that the caller is responsible for capchecks.
4999 * @param int $courseid The course to update by id as found in 'course' table
5002 function update_course_icon($courseid) {
5005 if (!empty($USER->editing
)) {
5006 $string = get_string('turneditingoff');
5009 $string = get_string('turneditingon');
5013 return '<form '.$CFG->frametarget
.' method="get" action="'.$CFG->wwwroot
.'/course/view.php">'.
5015 '<input type="hidden" name="id" value="'.$courseid.'" />'.
5016 '<input type="hidden" name="edit" value="'.$edit.'" />'.
5017 '<input type="hidden" name="sesskey" value="'.sesskey().'" />'.
5018 '<input type="submit" value="'.$string.'" />'.
5023 * Returns a little popup menu for switching roles
5027 * @param int $courseid The course to update by id as found in 'course' table
5030 function switchroles_form($courseid) {
5035 if (!$context = get_context_instance(CONTEXT_COURSE
, $courseid)) {
5039 if (!empty($USER->access
['rsw'][$context->path
])){ // Just a button to return to normal
5041 $options['id'] = $courseid;
5042 $options['sesskey'] = sesskey();
5043 $options['switchrole'] = 0;
5045 return print_single_button($CFG->wwwroot
.'/course/view.php', $options,
5046 get_string('switchrolereturn'), 'post', '_self', true);
5049 if (has_capability('moodle/role:switchroles', $context)) {
5050 if (!$roles = get_assignable_roles_for_switchrole($context)) {
5051 return ''; // Nothing to show!
5053 // unset default user role - it would not work
5054 unset($roles[$CFG->guestroleid
]);
5055 return popup_form($CFG->wwwroot
.'/course/view.php?id='.$courseid.'&sesskey='.sesskey().'&switchrole=',
5056 $roles, 'switchrole', '', get_string('switchroleto'), 'switchrole', get_string('switchroleto'), true);
5064 * Returns a turn edit on/off button for course in a self contained form.
5065 * Used to be an icon, but it's now a simple form button
5069 * @param int $courseid The course to update by id as found in 'course' table
5072 function update_mymoodle_icon() {
5076 if (!empty($USER->editing
)) {
5077 $string = get_string('updatemymoodleoff');
5080 $string = get_string('updatemymoodleon');
5084 return "<form $CFG->frametarget method=\"get\" action=\"$CFG->wwwroot/my/index.php\">".
5086 "<input type=\"hidden\" name=\"edit\" value=\"$edit\" />".
5087 "<input type=\"submit\" value=\"$string\" /></div></form>";
5091 * Returns a turn edit on/off button for tag in a self contained form.
5097 function update_tag_button($tagid) {
5101 if (!empty($USER->editing
)) {
5102 $string = get_string('turneditingoff');
5105 $string = get_string('turneditingon');
5109 return "<form $CFG->frametarget method=\"get\" action=\"$CFG->wwwroot/tag/index.php\">".
5111 "<input type=\"hidden\" name=\"edit\" value=\"$edit\" />".
5112 "<input type=\"hidden\" name=\"id\" value=\"$tagid\" />".
5113 "<input type=\"submit\" value=\"$string\" /></div></form>";
5117 * Prints the editing button on a module "view" page
5120 * @param type description
5121 * @todo Finish documenting this function
5123 function update_module_button($moduleid, $courseid, $string) {
5126 if (has_capability('moodle/course:manageactivities', get_context_instance(CONTEXT_MODULE
, $moduleid))) {
5127 $string = get_string('updatethis', '', $string);
5129 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
5131 "<input type=\"hidden\" name=\"update\" value=\"$moduleid\" />".
5132 "<input type=\"hidden\" name=\"return\" value=\"true\" />".
5133 "<input type=\"hidden\" name=\"sesskey\" value=\"".sesskey()."\" />".
5134 "<input type=\"submit\" value=\"$string\" /></div></form>";
5141 * Prints the editing button on a category page
5145 * @param int $categoryid ?
5147 * @todo Finish documenting this function
5149 function update_category_button($categoryid) {
5152 if (has_capability('moodle/category:update', get_context_instance(CONTEXT_COURSECAT
, $categoryid))) {
5153 if (!empty($USER->categoryediting
)) {
5154 $string = get_string('turneditingoff');
5157 $string = get_string('turneditingon');
5161 return "<form $CFG->frametarget method=\"get\" action=\"$CFG->wwwroot/course/category.php\">".
5163 "<input type=\"hidden\" name=\"id\" value=\"$categoryid\" />".
5164 "<input type=\"hidden\" name=\"categoryedit\" value=\"$edit\" />".
5165 "<input type=\"hidden\" name=\"sesskey\" value=\"$USER->sesskey\" />".
5166 "<input type=\"submit\" value=\"$string\" /></div></form>";
5171 * Prints the editing button on categories listing
5177 function update_categories_button() {
5180 if (has_capability('moodle/category:update', get_context_instance(CONTEXT_SYSTEM
))) {
5181 if (!empty($USER->categoryediting
)) {
5182 $string = get_string('turneditingoff');
5183 $categoryedit = 'off';
5185 $string = get_string('turneditingon');
5186 $categoryedit = 'on';
5189 return "<form $CFG->frametarget method=\"get\" action=\"$CFG->wwwroot/course/index.php\">".
5191 '<input type="hidden" name="categoryedit" value="'. $categoryedit .'" />'.
5192 '<input type="hidden" name="sesskey" value="'.$USER->sesskey
.'" />'.
5193 '<input type="submit" value="'. $string .'" /></div></form>';
5198 * Prints the editing button on search results listing
5199 * For bulk move courses to another category
5202 function update_categories_search_button($search,$page,$perpage) {
5205 // not sure if this capability is the best here
5206 if (has_capability('moodle/category:update', get_context_instance(CONTEXT_SYSTEM
))) {
5207 if (!empty($USER->categoryediting
)) {
5208 $string = get_string("turneditingoff");
5212 $string = get_string("turneditingon");
5216 return "<form $CFG->frametarget method=\"get\" action=\"$CFG->wwwroot/course/search.php\">".
5218 "<input type=\"hidden\" name=\"edit\" value=\"$edit\" />".
5219 "<input type=\"hidden\" name=\"sesskey\" value=\"$USER->sesskey\" />".
5220 "<input type=\"hidden\" name=\"search\" value=\"".s($search, true)."\" />".
5221 "<input type=\"hidden\" name=\"page\" value=\"$page\" />".
5222 "<input type=\"hidden\" name=\"perpage\" value=\"$perpage\" />".
5223 "<input type=\"submit\" value=\"".s($string)."\" /></div></form>";
5228 * Given a course and a (current) coursemodule
5229 * This function returns a small popup menu with all the
5230 * course activity modules in it, as a navigation menu
5231 * The data is taken from the serialised array stored in
5234 * @param course $course A {@link $COURSE} object.
5235 * @param course $cm A {@link $COURSE} object.
5236 * @param string $targetwindow ?
5238 * @todo Finish documenting this function
5240 function navmenu($course, $cm=NULL, $targetwindow='self') {
5242 global $CFG, $THEME, $USER;
5244 if (empty($THEME->navmenuwidth
)) {
5247 $width = $THEME->navmenuwidth
;
5254 if ($course->format
== 'weeks') {
5255 $strsection = get_string('week');
5257 $strsection = get_string('topic');
5259 $strjumpto = get_string('jumpto');
5261 $modinfo = get_fast_modinfo($course);
5262 $context = get_context_instance(CONTEXT_COURSE
, $course->id
);
5267 $previousmod = NULL;
5274 $menustyle = array();
5276 $sections = get_records('course_sections','course',$course->id
,'section','section,visible,summary');
5278 if (!empty($THEME->makenavmenulist
)) { /// A hack to produce an XHTML navmenu list for use in themes
5279 $THEME->navmenulist
= navmenulist($course, $sections, $modinfo, $strsection, $strjumpto, $width, $cm);
5282 foreach ($modinfo->cms
as $mod) {
5283 if ($mod->modname
== 'label') {
5287 if ($mod->sectionnum
> $course->numsections
) { /// Don't show excess hidden sections
5291 if (!$mod->uservisible
) { // do not icnlude empty sections at all
5295 if ($mod->sectionnum
> 0 and $section != $mod->sectionnum
) {
5296 $thissection = $sections[$mod->sectionnum
];
5298 if ($thissection->visible
or !$course->hiddensections
or
5299 has_capability('moodle/course:viewhiddensections', $context)) {
5300 $thissection->summary
= strip_tags(format_string($thissection->summary
,true));
5301 if ($course->format
== 'weeks' or empty($thissection->summary
)) {
5302 $menu[] = '--'.$strsection ." ". $mod->sectionnum
;
5304 if (strlen($thissection->summary
) < ($width-3)) {
5305 $menu[] = '--'.$thissection->summary
;
5307 $menu[] = '--'.substr($thissection->summary
, 0, $width).'...';
5310 $section = $mod->sectionnum
;
5312 // no activities from this hidden section shown
5317 $url = $mod->modname
.'/view.php?id='. $mod->id
;
5318 if ($flag) { // the current mod is the "next" mod
5322 $localname = $mod->name
;
5323 if ($cm == $mod->id
) {
5326 $backmod = $previousmod;
5327 $flag = true; // set flag so we know to use next mod for "next"
5328 $localname = $strjumpto;
5331 $localname = strip_tags(format_string($localname,true));
5332 $tl=textlib_get_instance();
5333 if ($tl->strlen($localname) > ($width+
5)) {
5334 $localname = $tl->substr($localname, 0, $width).'...';
5336 if (!$mod->visible
) {
5337 $localname = '('.$localname.')';
5340 $menu[$url] = $localname;
5341 if (empty($THEME->navmenuiconshide
)) {
5342 $menustyle[$url] = 'style="background-image: url('.$CFG->modpixpath
.'/'.$mod->modname
.'/icon.gif);"'; // Unfortunately necessary to do this here
5344 $previousmod = $mod;
5346 //Accessibility: added Alt text, replaced > < with 'silent' character and 'accesshide' text.
5348 if ($selectmod and has_capability('moodle/site:viewreports', $context)) {
5349 $logstext = get_string('alllogs');
5350 $logslink = '<li>'."\n".'<a title="'.$logstext.'" '.
5351 $CFG->frametarget
.'onclick="this.target=\''.$CFG->framename
.'\';"'.' href="'.
5352 $CFG->wwwroot
.'/course/report/log/index.php?chooselog=1&user=0&date=0&id='.
5353 $course->id
.'&modid='.$selectmod->id
.'">'.
5354 '<img class="icon log" src="'.$CFG->pixpath
.'/i/log.gif" alt="'.$logstext.'" /></a>'."\n".'</li>';
5358 $backtext= get_string('activityprev', 'access');
5359 $backmod = '<li><form action="'.$CFG->wwwroot
.'/mod/'.$backmod->modname
.'/view.php" '.
5360 'onclick="this.target=\''.$CFG->framename
.'\';"'.'><fieldset class="invisiblefieldset">'.
5361 '<input type="hidden" name="id" value="'.$backmod->id
.'" />'.
5362 '<button type="submit" title="'.$backtext.'">'.link_arrow_left($backtext, $url='', $accesshide=true).
5363 '</button></fieldset></form></li>';
5366 $nexttext= get_string('activitynext', 'access');
5367 $nextmod = '<li><form action="'.$CFG->wwwroot
.'/mod/'.$nextmod->modname
.'/view.php" '.
5368 'onclick="this.target=\''.$CFG->framename
.'\';"'.'><fieldset class="invisiblefieldset">'.
5369 '<input type="hidden" name="id" value="'.$nextmod->id
.'" />'.
5370 '<button type="submit" title="'.$nexttext.'">'.link_arrow_right($nexttext, $url='', $accesshide=true).
5371 '</button></fieldset></form></li>';
5374 return '<div class="navigation">'."\n".'<ul>'.$logslink . $backmod .
5375 '<li>'.popup_form($CFG->wwwroot
.'/mod/', $menu, 'navmenupopup', $selected, $strjumpto,
5376 '', '', true, $targetwindow, '', $menustyle).'</li>'.
5377 $nextmod . '</ul>'."\n".'</div>';
5382 * This function returns a small popup menu with all the
5383 * course activity modules in it, as a navigation menu
5384 * outputs a simple list structure in XHTML
5385 * The data is taken from the serialised array stored in
5388 * @param course $course A {@link $COURSE} object.
5390 * @todo Finish documenting this function
5392 function navmenulist($course, $sections, $modinfo, $strsection, $strjumpto, $width=50, $cmid=0) {
5399 $doneheading = false;
5401 $coursecontext = get_context_instance(CONTEXT_COURSE
, $course->id
);
5403 $menu[] = '<ul class="navmenulist"><li class="jumpto section"><span>'.$strjumpto.'</span><ul>';
5404 foreach ($modinfo->cms
as $mod) {
5405 if ($mod->modname
== 'label') {
5409 if ($mod->sectionnum
> $course->numsections
) { /// Don't show excess hidden sections
5413 if (!$mod->uservisible
) { // do not icnlude empty sections at all
5417 if ($mod->sectionnum
>= 0 and $section != $mod->sectionnum
) {
5418 $thissection = $sections[$mod->sectionnum
];
5420 if ($thissection->visible
or !$course->hiddensections
or
5421 has_capability('moodle/course:viewhiddensections', $coursecontext)) {
5422 $thissection->summary
= strip_tags(format_string($thissection->summary
,true));
5423 if (!$doneheading) {
5424 $menu[] = '</ul></li>';
5426 if ($course->format
== 'weeks' or empty($thissection->summary
)) {
5427 $item = $strsection ." ". $mod->sectionnum
;
5429 if (strlen($thissection->summary
) < ($width-3)) {
5430 $item = $thissection->summary
;
5432 $item = substr($thissection->summary
, 0, $width).'...';
5435 $menu[] = '<li class="section"><span>'.$item.'</span>';
5437 $doneheading = true;
5439 $section = $mod->sectionnum
;
5441 // no activities from this hidden section shown
5446 $url = $mod->modname
.'/view.php?id='. $mod->id
;
5447 $mod->name
= strip_tags(format_string(urldecode($mod->name
),true));
5448 if (strlen($mod->name
) > ($width+
5)) {
5449 $mod->name
= substr($mod->name
, 0, $width).'...';
5451 if (!$mod->visible
) {
5452 $mod->name
= '('.$mod->name
.')';
5454 $class = 'activity '.$mod->modname
;
5455 $class .= ($cmid == $mod->cm
) ?
' selected' : '';
5456 $menu[] = '<li class="'.$class.'">'.
5457 '<img src="'.$CFG->modpixpath
.'/'.$mod->modname
.'/icon.gif" alt="" />'.
5458 '<a href="'.$CFG->wwwroot
.'/mod/'.$url.'">'.$mod->name
.'</a></li>';
5462 $menu[] = '</ul></li>';
5464 $menu[] = '</ul></li></ul>';
5466 return implode("\n", $menu);
5470 * Prints form items with the names $day, $month and $year
5472 * @param string $day fieldname
5473 * @param string $month fieldname
5474 * @param string $year fieldname
5475 * @param int $currenttime A default timestamp in GMT
5476 * @param boolean $return
5478 function print_date_selector($day, $month, $year, $currenttime=0, $return=false) {
5480 if (!$currenttime) {
5481 $currenttime = time();
5483 $currentdate = usergetdate($currenttime);
5485 for ($i=1; $i<=31; $i++
) {
5488 for ($i=1; $i<=12; $i++
) {
5489 $months[$i] = userdate(gmmktime(12,0,0,$i,15,2000), "%B");
5491 for ($i=1970; $i<=2020; $i++
) {
5494 return choose_from_menu($days, $day, $currentdate['mday'], '', '', '0', $return)
5495 .choose_from_menu($months, $month, $currentdate['mon'], '', '', '0', $return)
5496 .choose_from_menu($years, $year, $currentdate['year'], '', '', '0', $return);
5501 *Prints form items with the names $hour and $minute
5503 * @param string $hour fieldname
5504 * @param string ? $minute fieldname
5505 * @param $currenttime A default timestamp in GMT
5506 * @param int $step minute spacing
5507 * @param boolean $return
5509 function print_time_selector($hour, $minute, $currenttime=0, $step=5, $return=false) {
5511 if (!$currenttime) {
5512 $currenttime = time();
5514 $currentdate = usergetdate($currenttime);
5516 $currentdate['minutes'] = ceil($currentdate['minutes']/$step)*$step;
5518 for ($i=0; $i<=23; $i++
) {
5519 $hours[$i] = sprintf("%02d",$i);
5521 for ($i=0; $i<=59; $i+
=$step) {
5522 $minutes[$i] = sprintf("%02d",$i);
5525 return choose_from_menu($hours, $hour, $currentdate['hours'], '','','0',$return)
5526 .choose_from_menu($minutes, $minute, $currentdate['minutes'], '','','0',$return);
5530 * Prints time limit value selector
5533 * @param int $timelimit default
5534 * @param string $unit
5535 * @param string $name
5536 * @param boolean $return
5538 function print_timer_selector($timelimit = 0, $unit = '', $name = 'timelimit', $return=false) {
5546 // Max timelimit is sessiontimeout - 10 minutes.
5547 $maxvalue = ($CFG->sessiontimeout
/ 60) - 10;
5549 for ($i=1; $i<=$maxvalue; $i++
) {
5550 $minutes[$i] = $i.$unit;
5552 return choose_from_menu($minutes, $name, $timelimit, get_string('none'), '','','0',$return);
5556 * Prints a grade menu (as part of an existing form) with help
5557 * Showing all possible numerical grades and scales
5560 * @param int $courseid ?
5561 * @param string $name ?
5562 * @param string $current ?
5563 * @param boolean $includenograde ?
5564 * @todo Finish documenting this function
5566 function print_grade_menu($courseid, $name, $current, $includenograde=true, $return=false) {
5571 $strscale = get_string('scale');
5572 $strscales = get_string('scales');
5574 $scales = get_scales_menu($courseid);
5575 foreach ($scales as $i => $scalename) {
5576 $grades[-$i] = $strscale .': '. $scalename;
5578 if ($includenograde) {
5579 $grades[0] = get_string('nograde');
5581 for ($i=100; $i>=1; $i--) {
5584 $output .= choose_from_menu($grades, $name, $current, '', '', 0, true);
5586 $linkobject = '<span class="helplink"><img class="iconhelp" alt="'.$strscales.'" src="'.$CFG->pixpath
.'/help.gif" /></span>';
5587 $output .= link_to_popup_window ('/course/scales.php?id='. $courseid .'&list=true', 'ratingscales',
5588 $linkobject, 400, 500, $strscales, 'none', true);
5598 * Prints a scale menu (as part of an existing form) including help button
5599 * Just like {@link print_grade_menu()} but without the numeric grades
5601 * @param int $courseid ?
5602 * @param string $name ?
5603 * @param string $current ?
5604 * @todo Finish documenting this function
5606 function print_scale_menu($courseid, $name, $current, $return=false) {
5611 $strscales = get_string('scales');
5612 $output .= choose_from_menu(get_scales_menu($courseid), $name, $current, '', '', 0, true);
5614 $linkobject = '<span class="helplink"><img class="iconhelp" alt="'.$strscales.'" src="'.$CFG->pixpath
.'/help.gif" /></span>';
5615 $output .= link_to_popup_window ('/course/scales.php?id='. $courseid .'&list=true', 'ratingscales',
5616 $linkobject, 400, 500, $strscales, 'none', true);
5625 * Prints a help button about a scale
5628 * @param id $courseid ?
5629 * @param object $scale ?
5630 * @todo Finish documenting this function
5632 function print_scale_menu_helpbutton($courseid, $scale, $return=false) {
5637 $strscales = get_string('scales');
5639 $linkobject = '<span class="helplink"><img class="iconhelp" alt="'.$scale->name
.'" src="'.$CFG->pixpath
.'/help.gif" /></span>';
5640 $output .= link_to_popup_window ('/course/scales.php?id='. $courseid .'&list=true&scaleid='. $scale->id
, 'ratingscale',
5641 $linkobject, 400, 500, $scale->name
, 'none', true);
5650 * Print an error page displaying an error message. New method - use this for new code.
5654 * @param string $errorcode The name of the string from error.php to print
5655 * @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.
5656 * @param object $a Extra words and phrases that might be required in the error string
5658 function print_error ($errorcode, $module='', $link='', $a=NULL) {
5660 global $CFG, $SESSION, $THEME;
5662 if (empty($module) ||
$module == 'moodle' ||
$module == 'core') {
5664 $modulelink = 'moodle';
5666 $modulelink = $module;
5669 if (empty($link) and !defined('ADMIN_EXT_HEADER_PRINTED')) {
5670 if ( !empty($SESSION->fromurl
) ) {
5671 $link = $SESSION->fromurl
;
5672 unset($SESSION->fromurl
);
5674 $link = $CFG->wwwroot
.'/';
5678 if (!empty($CFG->errordocroot
)) {
5679 $errordocroot = $CFG->errordocroot
;
5680 } else if (!empty($CFG->docroot
)) {
5681 $errordocroot = $CFG->docroot
;
5683 $errordocroot = 'http://docs.moodle.org';
5686 $message = get_string($errorcode, $module, $a);
5688 if (defined('FULLME') && FULLME
== 'cron') {
5689 // Errors in cron should be mtrace'd.
5694 $message = clean_text('<p class="errormessage">'.$message.'</p>'.
5695 '<p class="errorcode">'.
5696 '<a href="'.$errordocroot.'/en/error/'.$modulelink.'/'.$errorcode.'">'.
5697 get_string('moreinformation').'</a></p>');
5699 if (! defined('HEADER_PRINTED')) {
5700 //header not yet printed
5701 @header
('HTTP/1.0 404 Not Found');
5702 print_header(get_string('error'));
5704 print_container_end_all(false, $THEME->open_header_containers
);
5709 print_simple_box($message, '', '', '', '', 'errorbox');
5711 debugging('Stack trace:', DEBUG_DEVELOPER
);
5713 // in case we are logging upgrade in admin/index.php stop it
5714 if (function_exists('upgrade_log_finish')) {
5715 upgrade_log_finish();
5718 if (!empty($link)) {
5719 print_continue($link);
5724 for ($i=0;$i<512;$i++
) { // Padding to help IE work with 404
5731 * Print an error to STDOUT and exit with a non-zero code. For commandline scripts.
5732 * Default errorcode is 1.
5734 * Very useful for perl-like error-handling:
5736 * do_somethting() or mdie("Something went wrong");
5738 * @param string $msg Error message
5739 * @param integer $errorcode Error code to emit
5741 function mdie($msg='', $errorcode=1) {
5742 trigger_error($msg);
5747 * Returns a string of html with an image of a help icon linked to a help page on a number of help topics.
5748 * Should be used only with htmleditor or textarea.
5749 * @param mixed $helptopics variable amount of params accepted. Each param may be a string or an array of arguments for
5753 function editorhelpbutton(){
5754 global $CFG, $SESSION;
5755 $items = func_get_args();
5757 $urlparams = array();
5759 foreach ($items as $item){
5760 if (is_array($item)){
5761 $urlparams[] = "keyword$i=".urlencode($item[0]);
5762 $urlparams[] = "title$i=".urlencode($item[1]);
5763 if (isset($item[2])){
5764 $urlparams[] = "module$i=".urlencode($item[2]);
5766 $titles[] = trim($item[1], ". \t");
5767 }elseif (is_string($item)){
5768 $urlparams[] = "button$i=".urlencode($item);
5771 $titles[] = get_string("helpreading");
5774 $titles[] = get_string("helpwriting");
5777 $titles[] = get_string("helpquestions");
5780 $titles[] = get_string("helpemoticons");
5783 $titles[] = get_string('helprichtext');
5786 $titles[] = get_string('helptext');
5789 error('Unknown help topic '.$item);
5794 if (count($titles)>1){
5795 //join last two items with an 'and'
5797 $a->one
= $titles[count($titles) - 2];
5798 $a->two
= $titles[count($titles) - 1];
5799 $titles[count($titles) - 2] = get_string('and', '', $a);
5800 unset($titles[count($titles) - 1]);
5802 $alttag = join (', ', $titles);
5804 $paramstring = join('&', $urlparams);
5805 $linkobject = '<img alt="'.$alttag.'" class="iconhelp" src="'.$CFG->pixpath
.'/help.gif" />';
5806 return link_to_popup_window(s('/lib/form/editorhelp.php?'.$paramstring), $alttag, $linkobject, 400, 500, $alttag, 'none', true);
5810 * Print a help button.
5813 * @param string $page The keyword that defines a help page
5814 * @param string $title The title of links, rollover tips, alt tags etc
5815 * 'Help with' (or the language equivalent) will be prefixed and '...' will be stripped.
5816 * @param string $module Which module is the page defined in
5817 * @param mixed $image Use a help image for the link? (true/false/"both")
5818 * @param boolean $linktext If true, display the title next to the help icon.
5819 * @param string $text If defined then this text is used in the page, and
5820 * the $page variable is ignored.
5821 * @param boolean $return If true then the output is returned as a string, if false it is printed to the current page.
5822 * @param string $imagetext The full text for the helpbutton icon. If empty use default help.gif
5824 * @todo Finish documenting this function
5826 function helpbutton ($page, $title, $module='moodle', $image=true, $linktext=false, $text='', $return=false,
5828 global $CFG, $COURSE;
5831 if (!empty($COURSE->lang
)) {
5832 $forcelang = $COURSE->lang
;
5837 if ($module == '') {
5841 if ($title == '' && $linktext == '') {
5842 debugging('Error in call to helpbutton function: at least one of $title and $linktext is required');
5845 // Warn users about new window for Accessibility
5846 $tooltip = get_string('helpprefix2', '', trim($title, ". \t")) .' ('.get_string('newwindow').')';
5852 // MDL-7469 If text link is displayed with help icon, change to alt to "help with this".
5853 $linkobject .= $title.' ';
5854 $tooltip = get_string('helpwiththis');
5857 $linkobject .= $imagetext;
5859 $linkobject .= '<img class="iconhelp" alt="'.s(strip_tags($tooltip)).'" src="'.
5860 $CFG->pixpath
.'/help.gif" />';
5863 $linkobject .= $tooltip;
5868 $url = '/help.php?module='. $module .'&text='. s(urlencode($text).'&forcelang='.$forcelang);
5870 $url = '/help.php?module='. $module .'&file='. $page .'.html&forcelang='.$forcelang;
5873 $link = '<span class="helplink">'.
5874 link_to_popup_window ($url, 'popup', $linkobject, 400, 500, $tooltip, 'none', true).
5885 * Print a help button.
5887 * Prints a special help button that is a link to the "live" emoticon popup
5890 * @param string $form ?
5891 * @param string $field ?
5892 * @todo Finish documenting this function
5894 function emoticonhelpbutton($form, $field, $return = false) {
5896 global $CFG, $SESSION;
5898 $SESSION->inserttextform
= $form;
5899 $SESSION->inserttextfield
= $field;
5900 $imagetext = '<img src="' . $CFG->pixpath
. '/s/smiley.gif" alt="" class="emoticon" style="margin-left:3px; padding-right:1px;width:15px;height:15px;" />';
5901 $help = helpbutton('emoticons', get_string('helpemoticons'), 'moodle', true, true, '', true, $imagetext);
5910 * Print a help button.
5912 * Prints a special help button for html editors (htmlarea in this case)
5915 function editorshortcutshelpbutton() {
5918 $imagetext = '<img src="' . $CFG->httpswwwroot
. '/lib/editor/htmlarea/images/kbhelp.gif" alt="'.
5919 get_string('editorshortcutkeys').'" class="iconkbhelp" />';
5921 return helpbutton('editorshortcuts', get_string('editorshortcutkeys'), 'moodle', true, false, '', true, $imagetext);
5925 * Print a message and exit.
5928 * @param string $message ?
5929 * @param string $link ?
5930 * @todo Finish documenting this function
5932 function notice ($message, $link='', $course=NULL) {
5933 global $CFG, $SITE, $THEME, $COURSE;
5935 $message = clean_text($message); // In case nasties are in here
5937 if (defined('FULLME') && FULLME
== 'cron') {
5938 // notices in cron should be mtrace'd.
5943 if (! defined('HEADER_PRINTED')) {
5944 //header not yet printed
5945 print_header(get_string('notice'));
5947 print_container_end_all(false, $THEME->open_header_containers
);
5950 print_box($message, 'generalbox', 'notice');
5951 print_continue($link);
5953 if (empty($course)) {
5954 print_footer($COURSE);
5956 print_footer($course);
5962 * Print a message along with "Yes" and "No" links for the user to continue.
5964 * @param string $message The text to display
5965 * @param string $linkyes The link to take the user to if they choose "Yes"
5966 * @param string $linkno The link to take the user to if they choose "No"
5967 * TODO Document remaining arguments
5969 function notice_yesno ($message, $linkyes, $linkno, $optionsyes=NULL, $optionsno=NULL, $methodyes='post', $methodno='post') {
5973 $message = clean_text($message);
5974 $linkyes = clean_text($linkyes);
5975 $linkno = clean_text($linkno);
5977 print_box_start('generalbox', 'notice');
5978 echo '<p>'. $message .'</p>';
5979 echo '<div class="buttons">';
5980 print_single_button($linkyes, $optionsyes, get_string('yes'), $methodyes, $CFG->framename
);
5981 print_single_button($linkno, $optionsno, get_string('no'), $methodno, $CFG->framename
);
5987 * Provide an definition of error_get_last for PHP before 5.2.0. This simply
5988 * returns NULL, since there is not way to get the right answer.
5990 if (!function_exists('error_get_last')) {
5991 // the eval is needed to prevent PHP 5.2+ from getting a parse error!
5993 function error_get_last() {
6000 * Redirects the user to another page, after printing a notice
6002 * @param string $url The url to take the user to
6003 * @param string $message The text message to display to the user about the redirect, if any
6004 * @param string $delay How long before refreshing to the new page at $url?
6005 * @todo '&' needs to be encoded into '&' for XHTML compliance,
6006 * however, this is not true for javascript. Therefore we
6007 * first decode all entities in $url (since we cannot rely on)
6008 * the correct input) and then encode for where it's needed
6009 * echo "<script type='text/javascript'>alert('Redirect $url');</script>";
6011 function redirect($url, $message='', $delay=-1) {
6013 global $CFG, $THEME;
6015 if (!empty($CFG->usesid
) && !isset($_COOKIE[session_name()])) {
6016 $url = sid_process_url($url);
6019 $message = clean_text($message);
6021 $encodedurl = preg_replace("/\&(?![a-zA-Z0-9#]{1,8};)/", "&", $url);
6022 $encodedurl = preg_replace('/^.*href="([^"]*)".*$/', "\\1", clean_text('<a href="'.$encodedurl.'" />'));
6023 $url = str_replace('&', '&', $encodedurl);
6025 /// At developer debug level. Don't redirect if errors have been printed on screen.
6026 /// Currenly only works in PHP 5.2+; we do not want strict PHP5 errors
6027 $lasterror = error_get_last();
6028 $error = defined('DEBUGGING_PRINTED') or (!empty($lasterror) && ($lasterror['type'] & DEBUG_DEVELOPER
));
6029 $errorprinted = debugging('', DEBUG_ALL
) && $CFG->debugdisplay
&& $error;
6030 if ($errorprinted) {
6031 $message = "<strong>Error output, so disabling automatic redirect.</strong></p><p>" . $message;
6034 $performanceinfo = '';
6035 if (defined('MDL_PERF') ||
(!empty($CFG->perfdebug
) and $CFG->perfdebug
> 7)) {
6036 if (defined('MDL_PERFTOLOG') && !function_exists('register_shutdown_function')) {
6037 $perf = get_performance_info();
6038 error_log("PERF: " . $perf['txt']);
6042 /// when no message and header printed yet, try to redirect
6043 if (empty($message) and !defined('HEADER_PRINTED')) {
6045 // Technically, HTTP/1.1 requires Location: header to contain
6046 // the absolute path. (In practice browsers accept relative
6047 // paths - but still, might as well do it properly.)
6048 // This code turns relative into absolute.
6049 if (!preg_match('|^[a-z]+:|', $url)) {
6050 // Get host name http://www.wherever.com
6051 $hostpart = preg_replace('|^(.*?[^:/])/.*$|', '$1', $CFG->wwwroot
);
6052 if (preg_match('|^/|', $url)) {
6053 // URLs beginning with / are relative to web server root so we just add them in
6054 $url = $hostpart.$url;
6056 // URLs not beginning with / are relative to path of current script, so add that on.
6057 $url = $hostpart.preg_replace('|\?.*$|','',me()).'/../'.$url;
6061 $newurl = preg_replace('|/(?!\.\.)[^/]*/\.\./|', '/', $url);
6062 if ($newurl == $url) {
6070 //try header redirection first
6071 @header
($_SERVER['SERVER_PROTOCOL'] . ' 303 See Other'); //302 might not work for POST requests, 303 is ignored by obsolete clients
6072 @header
('Location: '.$url);
6073 //another way for older browsers and already sent headers (eg trailing whitespace in config.php)
6074 echo '<meta http-equiv="refresh" content="'. $delay .'; url='. $encodedurl .'" />';
6075 echo '<script type="text/javascript">'. "\n" .'//<![CDATA['. "\n". "location.replace('".addslashes_js($url)."');". "\n". '//]]>'. "\n". '</script>'; // To cope with Mozilla bug
6080 $delay = 3; // if no delay specified wait 3 seconds
6082 if (! defined('HEADER_PRINTED')) {
6083 // this type of redirect might not be working in some browsers - such as lynx :-(
6084 print_header('', '', '', '', $errorprinted ?
'' : ('<meta http-equiv="refresh" content="'. $delay .'; url='. $encodedurl .'" />'));
6085 $delay +
= 3; // double redirect prevention, it was sometimes breaking upgrades before 1.7
6087 print_container_end_all(false, $THEME->open_header_containers
);
6089 echo '<div id="redirect">';
6090 echo '<div id="message">' . $message . '</div>';
6091 echo '<div id="continue">( <a href="'. $encodedurl .'">'. get_string('continue') .'</a> )</div>';
6094 if (!$errorprinted) {
6096 <script type
="text/javascript">
6099 function redirect() {
6100 document
.location
.replace('<?php echo addslashes_js($url) ?>');
6102 setTimeout("redirect()", <?php
echo ($delay * 1000) ?
>);
6108 $CFG->docroot
= false; // to prevent the link to moodle docs from being displayed on redirect page.
6109 print_footer('none');
6114 * Print a bold message in an optional color.
6116 * @param string $message The message to print out
6117 * @param string $style Optional style to display message text in
6118 * @param string $align Alignment option
6119 * @param bool $return whether to return an output string or echo now
6121 function notify($message, $style='notifyproblem', $align='center', $return=false) {
6122 if ($style == 'green') {
6123 $style = 'notifysuccess'; // backward compatible with old color system
6126 $message = clean_text($message);
6128 $output = '<div class="'.$style.'" style="text-align:'. $align .'">'. $message .'</div>'."\n";
6138 * Given an email address, this function will return an obfuscated version of it
6140 * @param string $email The email address to obfuscate
6143 function obfuscate_email($email) {
6146 $length = strlen($email);
6148 while ($i < $length) {
6150 $obfuscated.='%'.dechex(ord($email{$i}));
6152 $obfuscated.=$email{$i};
6160 * This function takes some text and replaces about half of the characters
6161 * with HTML entity equivalents. Return string is obviously longer.
6163 * @param string $plaintext The text to be obfuscated
6166 function obfuscate_text($plaintext) {
6169 $length = strlen($plaintext);
6171 $prev_obfuscated = false;
6172 while ($i < $length) {
6173 $c = ord($plaintext{$i});
6174 $numerical = ($c >= ord('0')) && ($c <= ord('9'));
6175 if ($prev_obfuscated and $numerical ) {
6176 $obfuscated.='&#'.ord($plaintext{$i}).';';
6177 } else if (rand(0,2)) {
6178 $obfuscated.='&#'.ord($plaintext{$i}).';';
6179 $prev_obfuscated = true;
6181 $obfuscated.=$plaintext{$i};
6182 $prev_obfuscated = false;
6190 * This function uses the {@link obfuscate_email()} and {@link obfuscate_text()}
6191 * to generate a fully obfuscated email link, ready to use.
6193 * @param string $email The email address to display
6194 * @param string $label The text to dispalyed as hyperlink to $email
6195 * @param boolean $dimmed If true then use css class 'dimmed' for hyperlink
6198 function obfuscate_mailto($email, $label='', $dimmed=false) {
6200 if (empty($label)) {
6204 $title = get_string('emaildisable');
6205 $dimmed = ' class="dimmed"';
6210 return sprintf("<a href=\"%s:%s\" $dimmed title=\"$title\">%s</a>",
6211 obfuscate_text('mailto'), obfuscate_email($email),
6212 obfuscate_text($label));
6216 * Prints a single paging bar to provide access to other pages (usually in a search)
6218 * @param int $totalcount Thetotal number of entries available to be paged through
6219 * @param int $page The page you are currently viewing
6220 * @param int $perpage The number of entries that should be shown per page
6221 * @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.
6222 * If this is a moodle_url object then the pagevar param will be replaced by the page no, for each page.
6223 * @param string $pagevar This is the variable name that you use for the page number in your code (ie. 'tablepage', 'blogpage', etc)
6224 * @param bool $nocurr do not display the current page as a link
6225 * @param bool $return whether to return an output string or echo now
6226 * @return bool or string
6228 function print_paging_bar($totalcount, $page, $perpage, $baseurl, $pagevar='page',$nocurr=false, $return=false) {
6232 if ($totalcount > $perpage) {
6233 $output .= '<div class="paging">';
6234 $output .= get_string('page') .':';
6236 $pagenum = $page - 1;
6237 if (!is_a($baseurl, 'moodle_url')){
6238 $output .= ' (<a href="'. $baseurl . $pagevar .'='. $pagenum .'">'. get_string('previous') .'</a>) ';
6240 $output .= ' (<a href="'. $baseurl->out(false, array($pagevar => $pagenum)).'">'. get_string('previous') .'</a>) ';
6244 $lastpage = ceil($totalcount / $perpage);
6249 $startpage = $page - 10;
6250 if (!is_a($baseurl, 'moodle_url')){
6251 $output .= ' <a href="'. $baseurl . $pagevar .'=0">1</a> ...';
6253 $output .= ' <a href="'. $baseurl->out(false, array($pagevar => 0)).'">1</a> ...';
6258 $currpage = $startpage;
6259 $displaycount = $displaypage = 0;
6260 while ($displaycount < $maxdisplay and $currpage < $lastpage) {
6261 $displaypage = $currpage+
1;
6262 if ($page == $currpage && empty($nocurr)) {
6263 $output .= ' '. $displaypage;
6265 if (!is_a($baseurl, 'moodle_url')){
6266 $output .= ' <a href="'. $baseurl . $pagevar .'='. $currpage .'">'. $displaypage .'</a>';
6268 $output .= ' <a href="'. $baseurl->out(false, array($pagevar => $currpage)).'">'. $displaypage .'</a>';
6275 if ($currpage < $lastpage) {
6276 $lastpageactual = $lastpage - 1;
6277 if (!is_a($baseurl, 'moodle_url')){
6278 $output .= ' ...<a href="'. $baseurl . $pagevar .'='. $lastpageactual .'">'. $lastpage .'</a> ';
6280 $output .= ' ...<a href="'. $baseurl->out(false, array($pagevar => $lastpageactual)).'">'. $lastpage .'</a> ';
6283 $pagenum = $page +
1;
6284 if ($pagenum != $displaypage) {
6285 if (!is_a($baseurl, 'moodle_url')){
6286 $output .= ' (<a href="'. $baseurl . $pagevar .'='. $pagenum .'">'. get_string('next') .'</a>)';
6288 $output .= ' (<a href="'. $baseurl->out(false, array($pagevar => $pagenum)) .'">'. get_string('next') .'</a>)';
6291 $output .= '</div>';
6303 * This function is used to rebuild the <nolink> tag because some formats (PLAIN and WIKI)
6304 * will transform it to html entities
6306 * @param string $text Text to search for nolink tag in
6309 function rebuildnolinktag($text) {
6311 $text = preg_replace('/<(\/*nolink)>/i','<$1>',$text);
6317 * Prints a nice side block with an optional header. The content can either
6318 * be a block of HTML or a list of text with optional icons.
6320 * @param string $heading Block $title embedded in HTML tags, for example <h2>.
6321 * @param string $content ?
6322 * @param array $list ?
6323 * @param array $icons ?
6324 * @param string $footer ?
6325 * @param array $attributes ?
6326 * @param string $title Plain text title, as embedded in the $heading.
6327 * @todo Finish documenting this function. Show example of various attributes, etc.
6329 function print_side_block($heading='', $content='', $list=NULL, $icons=NULL, $footer='', $attributes = array(), $title='') {
6331 //Accessibility: skip block link, with title-text (or $block_id) to differentiate links.
6332 static $block_id = 0;
6334 if (empty($heading)) {
6335 $skip_text = get_string('skipblock', 'access').' '.$block_id;
6338 $skip_text = get_string('skipa', 'access', strip_tags($title));
6340 $skip_link = '<a href="#sb-'.$block_id.'" class="skip-block">'.$skip_text.'</a>';
6341 $skip_dest = '<span id="sb-'.$block_id.'" class="skip-block-to"></span>';
6343 if (! empty($heading)) {
6346 //ELSE: a single link on a page "Skip block 4" is too confusing - ignore.
6348 print_side_block_start($heading, $attributes);
6353 echo '<div class="footer">'. $footer .'</div>';
6358 //Accessibility: replaced unnecessary table with list, see themes/standard/styles_layout.css
6359 echo "\n<ul class='list'>\n";
6360 foreach ($list as $key => $string) {
6361 echo '<li class="r'. $row .'">';
6363 echo '<div class="icon column c0">'. $icons[$key] .'</div>';
6365 echo '<div class="column c1">'. $string .'</div>';
6372 echo '<div class="footer">'. $footer .'</div>';
6377 print_side_block_end($attributes, $title);
6382 * Starts a nice side block with an optional header.
6384 * @param string $heading ?
6385 * @param array $attributes ?
6386 * @todo Finish documenting this function
6388 function print_side_block_start($heading='', $attributes = array()) {
6390 global $CFG, $THEME;
6392 // If there are no special attributes, give a default CSS class
6393 if (empty($attributes) ||
!is_array($attributes)) {
6394 $attributes = array('class' => 'sideblock');
6396 } else if(!isset($attributes['class'])) {
6397 $attributes['class'] = 'sideblock';
6399 } else if(!strpos($attributes['class'], 'sideblock')) {
6400 $attributes['class'] .= ' sideblock';
6403 // OK, the class is surely there and in addition to anything
6404 // else, it's tagged as a sideblock
6408 // IE misery: if I do it this way, blocks which start hidden cannot be "unhidden"
6410 // If there is a cookie to hide this thing, start it hidden
6411 if (!empty($attributes['id']) && isset($_COOKIE['hide:'.$attributes['id']])) {
6412 $attributes['class'] = 'hidden '.$attributes['class'];
6417 foreach ($attributes as $attr => $val) {
6418 $attrtext .= ' '.$attr.'="'.$val.'"';
6421 echo '<div '.$attrtext.'>';
6423 if (!empty($THEME->customcorners
)) {
6424 echo '<div class="wrap">'."\n";
6427 //Accessibility: H2 more appropriate in moodleblock.class.php: _title_html.
6428 echo '<div class="header">';
6429 if (!empty($THEME->customcorners
)) {
6430 echo '<div class="bt"><div> </div></div>';
6431 echo '<div class="i1"><div class="i2">';
6432 echo '<div class="i3">';
6435 if (!empty($THEME->customcorners
)) {
6436 echo '</div></div></div>';
6440 if (!empty($THEME->customcorners
)) {
6441 echo '<div class="bt"><div> </div></div>';
6445 if (!empty($THEME->customcorners
)) {
6446 echo '<div class="i1"><div class="i2">';
6447 echo '<div class="i3">';
6449 echo '<div class="content">';
6455 * Print table ending tags for a side block box.
6457 function print_side_block_end($attributes = array(), $title='') {
6458 global $CFG, $THEME;
6462 if (!empty($THEME->customcorners
)) {
6463 echo '</div></div></div><div class="bb"><div> </div></div></div>';
6468 $strshow = addslashes_js(get_string('showblocka', 'access', strip_tags($title)));
6469 $strhide = addslashes_js(get_string('hideblocka', 'access', strip_tags($title)));
6471 // IE workaround: if I do it THIS way, it works! WTF?
6472 if (!empty($CFG->allowuserblockhiding
) && isset($attributes['id'])) {
6473 echo '<script type="text/javascript">'."\n//<![CDATA[\n".'elementCookieHide("'.$attributes['id'].
6474 '","'.$strshow.'","'.$strhide."\");\n//]]>\n".'</script>';
6481 * Prints out code needed for spellchecking.
6482 * Original idea by Ludo (Marc Alier).
6484 * Opening CDATA and <script> are output by weblib::use_html_editor()
6486 * @param boolean $usehtmleditor Normally set by $CFG->htmleditor, can be overriden here
6487 * @param boolean $return If false, echos the code instead of returning it
6488 * @todo Find out if lib/editor/htmlarea/htmlarea.class.php::print_speller_code() is still used, and delete if not
6490 function print_speller_code ($usehtmleditor=false, $return=false) {
6494 if(!$usehtmleditor) {
6495 $str .= 'function openSpellChecker() {'."\n";
6496 $str .= "\tvar speller = new spellChecker();\n";
6497 $str .= "\tspeller.popUpUrl = \"" . $CFG->wwwroot
."/lib/speller/spellchecker.html\";\n";
6498 $str .= "\tspeller.spellCheckScript = \"". $CFG->wwwroot
."/lib/speller/server-scripts/spellchecker.php\";\n";
6499 $str .= "\tspeller.spellCheckAll();\n";
6502 $str .= "function spellClickHandler(editor, buttonId) {\n";
6503 $str .= "\teditor._textArea.value = editor.getHTML();\n";
6504 $str .= "\tvar speller = new spellChecker( editor._textArea );\n";
6505 $str .= "\tspeller.popUpUrl = \"" . $CFG->wwwroot
."/lib/speller/spellchecker.html\";\n";
6506 $str .= "\tspeller.spellCheckScript = \"". $CFG->wwwroot
."/lib/speller/server-scripts/spellchecker.php\";\n";
6507 $str .= "\tspeller._moogle_edit=1;\n";
6508 $str .= "\tspeller._editor=editor;\n";
6509 $str .= "\tspeller.openChecker();\n";
6520 * Print button for spellchecking when editor is disabled
6522 function print_speller_button () {
6523 echo '<input type="button" value="Check spelling" onclick="openSpellChecker();" />'."\n";
6527 function page_id_and_class(&$getid, &$getclass) {
6528 // Create class and id for this page
6531 static $class = NULL;
6534 if (empty($CFG->pagepath
)) {
6535 $CFG->pagepath
= $ME;
6538 if (empty($class) ||
empty($id)) {
6539 $path = str_replace($CFG->httpswwwroot
.'/', '', $CFG->pagepath
); //Because the page could be HTTPSPAGEREQUIRED
6540 $path = str_replace('.php', '', $path);
6541 if (substr($path, -1) == '/') {
6544 if (empty($path) ||
$path == 'index') {
6547 } else if (substr($path, 0, 5) == 'admin') {
6548 $id = str_replace('/', '-', $path);
6551 $id = str_replace('/', '-', $path);
6552 $class = explode('-', $id);
6554 $class = implode('-', $class);
6563 * Prints a maintenance message from /maintenance.html
6565 function print_maintenance_message () {
6568 print_header(strip_tags($SITE->fullname
), $SITE->fullname
, 'home');
6569 print_simple_box_start('center');
6570 print_heading(get_string('sitemaintenance', 'admin'));
6571 @include
($CFG->dataroot
.'/1/maintenance.html');
6572 print_simple_box_end();
6577 * Adjust the list of allowed tags based on $CFG->allowobjectembed and user roles (admin)
6579 function adjust_allowed_tags() {
6581 global $CFG, $ALLOWED_TAGS;
6583 if (!empty($CFG->allowobjectembed
)) {
6584 $ALLOWED_TAGS .= '<embed><object>';
6588 /// Some code to print tabs
6590 /// A class for tabs
6595 var $linkedwhenselected;
6597 /// A constructor just because I like constructors
6598 function tabobject ($id, $link='', $text='', $title='', $linkedwhenselected=false) {
6600 $this->link
= $link;
6601 $this->text
= $text;
6602 $this->title
= $title ?
$title : $text;
6603 $this->linkedwhenselected
= $linkedwhenselected;
6610 * Returns a string containing a nested list, suitable for formatting into tabs with CSS.
6612 * @param array $tabrows An array of rows where each row is an array of tab objects
6613 * @param string $selected The id of the selected tab (whatever row it's on)
6614 * @param array $inactive An array of ids of inactive tabs that are not selectable.
6615 * @param array $activated An array of ids of other tabs that are currently activated
6617 function print_tabs($tabrows, $selected=NULL, $inactive=NULL, $activated=NULL, $return=false) {
6620 /// $inactive must be an array
6621 if (!is_array($inactive)) {
6622 $inactive = array();
6625 /// $activated must be an array
6626 if (!is_array($activated)) {
6627 $activated = array();
6630 /// Convert the tab rows into a tree that's easier to process
6631 if (!$tree = convert_tabrows_to_tree($tabrows, $selected, $inactive, $activated)) {
6635 /// Print out the current tree of tabs (this function is recursive)
6637 $output = convert_tree_to_html($tree);
6639 $output = "\n\n".'<div class="tabtree">'.$output.'</div><div class="clearer"> </div>'."\n\n";
6650 function convert_tree_to_html($tree, $row=0) {
6652 $str = "\n".'<ul class="tabrow'.$row.'">'."\n";
6655 $count = count($tree);
6657 foreach ($tree as $tab) {
6658 $count--; // countdown to zero
6662 if ($first && ($count == 0)) { // Just one in the row
6663 $liclass = 'first last';
6665 } else if ($first) {
6668 } else if ($count == 0) {
6672 if ((empty($tab->subtree
)) && (!empty($tab->selected
))) {
6673 $liclass .= (empty($liclass)) ?
'onerow' : ' onerow';
6676 if ($tab->inactive ||
$tab->active ||
$tab->selected
) {
6677 if ($tab->selected
) {
6678 $liclass .= (empty($liclass)) ?
'here selected' : ' here selected';
6679 } else if ($tab->active
) {
6680 $liclass .= (empty($liclass)) ?
'here active' : ' here active';
6684 $str .= (!empty($liclass)) ?
'<li class="'.$liclass.'">' : '<li>';
6686 if ($tab->inactive ||
$tab->active ||
($tab->selected
&& !$tab->linkedwhenselected
)) {
6687 // The a tag is used for styling
6688 $str .= '<a class="nolink"><span>'.$tab->text
.'</span></a>';
6690 $str .= '<a href="'.$tab->link
.'" title="'.$tab->title
.'"><span>'.$tab->text
.'</span></a>';
6693 if (!empty($tab->subtree
)) {
6694 $str .= convert_tree_to_html($tab->subtree
, $row+
1);
6695 } else if ($tab->selected
) {
6696 $str .= '<div class="tabrow'.($row+
1).' empty"> </div>'."\n";
6699 $str .= ' </li>'."\n";
6701 $str .= '</ul>'."\n";
6707 function convert_tabrows_to_tree($tabrows, $selected, $inactive, $activated) {
6709 /// Work backwards through the rows (bottom to top) collecting the tree as we go.
6711 $tabrows = array_reverse($tabrows);
6715 foreach ($tabrows as $row) {
6718 foreach ($row as $tab) {
6719 $tab->inactive
= in_array((string)$tab->id
, $inactive);
6720 $tab->active
= in_array((string)$tab->id
, $activated);
6721 $tab->selected
= (string)$tab->id
== $selected;
6723 if ($tab->active ||
$tab->selected
) {
6725 $tab->subtree
= $subtree;
6738 * Returns a string containing a link to the user documentation for the current
6739 * page. Also contains an icon by default. Shown to teachers and admin only.
6741 * @param string $text The text to be displayed for the link
6742 * @param string $iconpath The path to the icon to be displayed
6744 function page_doc_link($text='', $iconpath='') {
6745 global $ME, $COURSE, $CFG;
6747 if (empty($CFG->docroot
) or empty($CFG->rolesactive
)) {
6751 if (empty($COURSE->id
)) {
6752 $context = get_context_instance(CONTEXT_SYSTEM
);
6754 $context = get_context_instance(CONTEXT_COURSE
, $COURSE->id
);
6757 if (!has_capability('moodle/site:doclinks', $context)) {
6761 if (empty($CFG->pagepath
)) {
6762 $CFG->pagepath
= $ME;
6765 $path = str_replace($CFG->httpswwwroot
.'/','', $CFG->pagepath
); // Because the page could be HTTPSPAGEREQUIRED
6766 $path = str_replace('.php', '', $path);
6768 if (empty($path)) { // Not for home page
6771 return doc_link($path, $text, $iconpath);
6775 * Returns a string containing a link to the user documentation.
6776 * Also contains an icon by default. Shown to teachers and admin only.
6778 * @param string $path The page link after doc root and language, no
6780 * @param string $text The text to be displayed for the link
6781 * @param string $iconpath The path to the icon to be displayed
6783 function doc_link($path='', $text='', $iconpath='') {
6786 if (empty($CFG->docroot
)) {
6791 if (!empty($CFG->doctonewwindow
)) {
6792 $target = ' target="_blank"';
6795 $lang = str_replace('_utf8', '', current_language());
6797 $str = '<a href="' .$CFG->docroot
. '/' .$lang. '/' .$path. '"' .$target. '>';
6799 if (empty($iconpath)) {
6800 $iconpath = $CFG->httpswwwroot
. '/pix/docs.gif';
6803 // alt left blank intentionally to prevent repetition in screenreaders
6804 $str .= '<img class="iconhelp" src="' .$iconpath. '" alt="" />' .$text. '</a>';
6811 * Returns true if the current site debugging settings are equal or above specified level.
6812 * If passed a parameter it will emit a debugging notice similar to trigger_error(). The
6813 * routing of notices is controlled by $CFG->debugdisplay
6816 * 1) debugging('a normal debug notice');
6817 * 2) debugging('something really picky', DEBUG_ALL);
6818 * 3) debugging('annoying debug message only for develpers', DEBUG_DEVELOPER);
6819 * 4) if (debugging()) { perform extra debugging operations (do not use print or echo) }
6821 * In code blocks controlled by debugging() (such as example 4)
6822 * any output should be routed via debugging() itself, or the lower-level
6823 * trigger_error() or error_log(). Using echo or print will break XHTML
6824 * JS and HTTP headers.
6827 * @param string $message a message to print
6828 * @param int $level the level at which this debugging statement should show
6831 function debugging($message='', $level=DEBUG_NORMAL
) {
6835 if (empty($CFG->debug
)) {
6839 if ($CFG->debug
>= $level) {
6841 $callers = debug_backtrace();
6842 $from = '<ul style="text-align: left">';
6843 foreach ($callers as $caller) {
6844 if (!isset($caller['line'])) {
6845 $caller['line'] = '?'; // probably call_user_func()
6847 if (!isset($caller['file'])) {
6848 $caller['file'] = $CFG->dirroot
.'/unknownfile'; // probably call_user_func()
6850 $from .= '<li>line ' . $caller['line'] . ' of ' . substr($caller['file'], strlen($CFG->dirroot
) +
1);
6851 if (isset($caller['function'])) {
6852 $from .= ': call to ';
6853 if (isset($caller['class'])) {
6854 $from .= $caller['class'] . $caller['type'];
6856 $from .= $caller['function'] . '()';
6861 if (!isset($CFG->debugdisplay
)) {
6862 $CFG->debugdisplay
= ini_get('display_errors');
6864 if ($CFG->debugdisplay
) {
6865 if (!defined('DEBUGGING_PRINTED')) {
6866 define('DEBUGGING_PRINTED', 1); // indicates we have printed something
6868 notify($message . $from, 'notifytiny');
6870 trigger_error($message . $from, E_USER_NOTICE
);
6879 * Disable debug messages from debugging(), while keeping PHP error reporting level as is.
6881 function disable_debugging() {
6883 $CFG->debug
= $CFG->debug |
0x80000000; // switch the sign bit in integer number ;-)
6888 * Returns string to add a frame attribute, if required
6890 function frametarget() {
6893 if (empty($CFG->framename
) or ($CFG->framename
== '_top')) {
6896 return ' target="'.$CFG->framename
.'" ';
6901 * Outputs a HTML comment to the browser. This is used for those hard-to-debug
6902 * pages that use bits from many different files in very confusing ways (e.g. blocks).
6903 * @usage print_location_comment(__FILE__, __LINE__);
6904 * @param string $file
6905 * @param integer $line
6906 * @param boolean $return Whether to return or print the comment
6907 * @return mixed Void unless true given as third parameter
6909 function print_location_comment($file, $line, $return = false)
6912 return "<!-- $file at line $line -->\n";
6914 echo "<!-- $file at line $line -->\n";
6920 * Returns an image of an up or down arrow, used for column sorting. To avoid unnecessary DB accesses, please
6921 * provide this function with the language strings for sortasc and sortdesc.
6922 * If no sort string is associated with the direction, an arrow with no alt text will be printed/returned.
6923 * @param string $direction 'up' or 'down'
6924 * @param string $strsort The language string used for the alt attribute of this image
6925 * @param bool $return Whether to print directly or return the html string
6926 * @return string HTML for the image
6928 * TODO See if this isn't already defined somewhere. If not, move this to weblib
6930 function print_arrow($direction='up', $strsort=null, $return=false) {
6933 if (!in_array($direction, array('up', 'down', 'right', 'left', 'move'))) {
6939 switch ($direction) {
6954 // Prepare language string
6956 if (empty($strsort) && !empty($sortdir)) {
6957 $strsort = get_string('sort' . $sortdir, 'grades');
6960 $return = ' <img src="'.$CFG->pixpath
.'/t/' . $direction . '.gif" alt="'.$strsort.'" /> ';
6970 * Returns boolean true if the current language is right-to-left (Hebrew, Arabic etc)
6973 function right_to_left() {
6976 if (isset($result)) {
6979 return $result = (get_string('thisdirection') == 'rtl');
6984 * Returns swapped left<=>right if in RTL environment.
6985 * part of RTL support
6987 * @param string $align align to check
6990 function fix_align_rtl($align) {
6991 if (!right_to_left()) {
6994 if ($align=='left') { return 'right'; }
6995 if ($align=='right') { return 'left'; }
7001 * Returns true if the page is displayed in a popup window.
7002 * Gets the information from the URL parameter inpopup.
7006 * TODO Use a central function to create the popup calls allover Moodle and
7007 * TODO In the moment only works with resources and probably questions.
7009 function is_in_popup() {
7010 $inpopup = optional_param('inpopup', '', PARAM_BOOL
);
7016 // vim:autoindent:expandtab:shiftwidth=4:tabstop=4:tw=140: