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 * @param array $overrideparams params to add to the output params, these
396 * override existing ones with the same name.
397 * @return string html for form elements.
399 function hidden_params_out($exclude = array(), $indent = 0, $overrideparams=array()){
400 $tabindent = str_repeat("\t", $indent);
402 $params = $overrideparams +
$this->params
;
403 foreach ($params as $key => $val){
404 if (FALSE === array_search($key, $exclude)) {
406 $str.= "$tabindent<input type=\"hidden\" name=\"$key\" value=\"$val\" />\n";
414 * @param boolean $noquerystring whether to output page params as a query string in the url.
415 * @param array $overrideparams params to add to the output url, these override existing ones with the same name.
418 function out($noquerystring = false, $overrideparams = array()) {
419 $uri = $this->scheme ?
$this->scheme
.':'.((strtolower($this->scheme
) == 'mailto') ?
'':'//'): '';
420 $uri .= $this->user ?
$this->user
.($this->pass?
':'.$this->pass
:'').'@':'';
421 $uri .= $this->host ?
$this->host
: '';
422 $uri .= $this->port ?
':'.$this->port
: '';
423 $uri .= $this->path ?
$this->path
: '';
424 if (!$noquerystring){
425 $uri .= (count($this->params
)||
count($overrideparams)) ?
'?'.$this->get_query_string($overrideparams) : '';
427 $uri .= $this->fragment ?
'#'.$this->fragment
: '';
431 * Output action url with sesskey
433 * @param boolean $noquerystring whether to output page params as a query string in the url.
436 function out_action($overrideparams = array()) {
437 $overrideparams = array('sesskey'=> sesskey()) +
$overrideparams;
438 return $this->out(false, $overrideparams);
443 * Determine if there is data waiting to be processed from a form
445 * Used on most forms in Moodle to check for data
446 * Returns the data as an object, if it's found.
447 * This object can be used in foreach loops without
448 * casting because it's cast to (array) automatically
450 * Checks that submitted POST data exists and returns it as object.
452 * @param string $url not used anymore
453 * @return mixed false or object
455 function data_submitted($url='') {
460 return (object)$_POST;
465 * Moodle replacement for php stripslashes() function,
466 * works also for objects and arrays.
468 * The standard php stripslashes() removes ALL backslashes
469 * even from strings - so C:\temp becomes C:temp - this isn't good.
470 * This function should work as a fairly safe replacement
471 * to be called on quoted AND unquoted strings (to be sure)
473 * @param mixed something to remove unsafe slashes from
476 function stripslashes_safe($mixed) {
477 // there is no need to remove slashes from int, float and bool types
480 } else if (is_string($mixed)) {
481 if (ini_get_bool('magic_quotes_sybase')) { //only unescape single quotes
482 $mixed = str_replace("''", "'", $mixed);
483 } else { //the rest, simple and double quotes and backslashes
484 $mixed = str_replace("\\'", "'", $mixed);
485 $mixed = str_replace('\\"', '"', $mixed);
486 $mixed = str_replace('\\\\', '\\', $mixed);
488 } else if (is_array($mixed)) {
489 foreach ($mixed as $key => $value) {
490 $mixed[$key] = stripslashes_safe($value);
492 } else if (is_object($mixed)) {
493 $vars = get_object_vars($mixed);
494 foreach ($vars as $key => $value) {
495 $mixed->$key = stripslashes_safe($value);
503 * Recursive implementation of stripslashes()
505 * This function will allow you to strip the slashes from a variable.
506 * If the variable is an array or object, slashes will be stripped
507 * from the items (or properties) it contains, even if they are arrays
508 * or objects themselves.
510 * @param mixed the variable to remove slashes from
513 function stripslashes_recursive($var) {
514 if (is_object($var)) {
515 $new_var = new object();
516 $properties = get_object_vars($var);
517 foreach($properties as $property => $value) {
518 $new_var->$property = stripslashes_recursive($value);
521 } else if(is_array($var)) {
523 foreach($var as $property => $value) {
524 $new_var[$property] = stripslashes_recursive($value);
527 } else if(is_string($var)) {
528 $new_var = stripslashes($var);
538 * Recursive implementation of addslashes()
540 * This function will allow you to add the slashes from a variable.
541 * If the variable is an array or object, slashes will be added
542 * to the items (or properties) it contains, even if they are arrays
543 * or objects themselves.
545 * @param mixed the variable to add slashes from
548 function addslashes_recursive($var) {
549 if (is_object($var)) {
550 $new_var = new object();
551 $properties = get_object_vars($var);
552 foreach($properties as $property => $value) {
553 $new_var->$property = addslashes_recursive($value);
556 } else if (is_array($var)) {
558 foreach($var as $property => $value) {
559 $new_var[$property] = addslashes_recursive($value);
562 } else if (is_string($var)) {
563 $new_var = addslashes($var);
565 } else { // nulls, integers, etc.
573 * Given some normal text this function will break up any
574 * long words to a given size by inserting the given character
576 * It's multibyte savvy and doesn't change anything inside html tags.
578 * @param string $string the string to be modified
579 * @param int $maxsize maximum length of the string to be returned
580 * @param string $cutchar the string used to represent word breaks
583 function break_up_long_words($string, $maxsize=20, $cutchar=' ') {
585 /// Loading the textlib singleton instance. We are going to need it.
586 $textlib = textlib_get_instance();
588 /// First of all, save all the tags inside the text to skip them
590 filter_save_tags($string,$tags);
592 /// Process the string adding the cut when necessary
594 $length = $textlib->strlen($string);
597 for ($i=0; $i<$length; $i++
) {
598 $char = $textlib->substr($string, $i, 1);
599 if ($char == ' ' or $char == "\t" or $char == "\n" or $char == "\r" or $char == "<" or $char == ">") {
603 if ($wordlength > $maxsize) {
611 /// Finally load the tags back again
613 $output = str_replace(array_keys($tags), $tags, $output);
620 * This does a search and replace, ignoring case
621 * This function is only used for versions of PHP older than version 5
622 * which do not have a native version of this function.
623 * Taken from the PHP manual, by bradhuizenga @ softhome.net
625 * @param string $find the string to search for
626 * @param string $replace the string to replace $find with
627 * @param string $string the string to search through
630 if (!function_exists('str_ireplace')) { /// Only exists in PHP 5
631 function str_ireplace($find, $replace, $string) {
633 if (!is_array($find)) {
634 $find = array($find);
637 if(!is_array($replace)) {
638 if (!is_array($find)) {
639 $replace = array($replace);
641 // this will duplicate the string into an array the size of $find
645 for ($i = 0; $i < $c; $i++
) {
646 $replace[$i] = $rString;
651 foreach ($find as $fKey => $fItem) {
652 $between = explode(strtolower($fItem),strtolower($string));
654 foreach($between as $bKey => $bItem) {
655 $between[$bKey] = substr($string,$pos,strlen($bItem));
656 $pos +
= strlen($bItem) +
strlen($fItem);
658 $string = implode($replace[$fKey],$between);
665 * Locate the position of a string in another string
667 * This function is only used for versions of PHP older than version 5
668 * which do not have a native version of this function.
669 * Taken from the PHP manual, by dmarsh @ spscc.ctc.edu
671 * @param string $haystack The string to be searched
672 * @param string $needle The string to search for
673 * @param int $offset The position in $haystack where the search should begin.
675 if (!function_exists('stripos')) { /// Only exists in PHP 5
676 function stripos($haystack, $needle, $offset=0) {
678 return strpos(strtoupper($haystack), strtoupper($needle), $offset);
683 * This function will print a button/link/etc. form element
684 * that will work on both Javascript and non-javascript browsers.
685 * Relies on the Javascript function openpopup in javascript.php
687 * All parameters default to null, only $type and $url are mandatory.
689 * $url must be relative to home page eg /mod/survey/stuff.php
690 * @param string $url Web link relative to home page
691 * @param string $name Name to be assigned to the popup window (this is used by
692 * client-side scripts to "talk" to the popup window)
693 * @param string $linkname Text to be displayed as web link
694 * @param int $height Height to assign to popup window
695 * @param int $width Height to assign to popup window
696 * @param string $title Text to be displayed as popup page title
697 * @param string $options List of additional options for popup window
698 * @param string $return If true, return as a string, otherwise print
699 * @param string $id id added to the element
700 * @param string $class class added to the element
704 function element_to_popup_window ($type=null, $url=null, $name=null, $linkname=null,
705 $height=400, $width=500, $title=null,
706 $options=null, $return=false, $id=null, $class=null) {
709 debugging('You must give the url to display in the popup. URL is missing - can\'t create popup window.', DEBUG_DEVELOPER
);
714 if ($options == 'none') { // 'none' is legacy, should be removed in v2.0
718 // add some sane default options for popup windows
720 $options = 'menubar=0,location=0,scrollbars,resizable';
723 $options .= ',width='. $width;
726 $options .= ',height='. $height;
729 $id = ' id="'.$id.'" ';
732 $class = ' class="'.$class.'" ';
736 if (($name = preg_replace("/\s/", '_', $name)) != $_name) {
737 debugging('The $name of a popup window shouldn\'t contain spaces - string modified. '. $_name .' changed to '. $name, DEBUG_DEVELOPER
);
743 // get some default string, using the localized version of legacy defaults
744 if (is_null($linkname) ||
$linkname === '') {
745 $linkname = get_string('clickhere');
748 $title = get_string('popupwindowname');
751 $fullscreen = 0; // must be passed to openpopup
756 $element = '<input type="button" name="'. $name .'" title="'. $title .'" value="'. $linkname .'" '. $id . $class .
757 "onclick=\"return openpopup('$url', '$name', '$options', $fullscreen);\" />\n";
760 // some log url entries contain _SERVER[HTTP_REFERRER] in which case wwwroot is already there.
761 if (!(strpos($url,$CFG->wwwroot
) === false)) {
762 $url = substr($url, strlen($CFG->wwwroot
));
764 $element = '<a title="'. s(strip_tags($title)) .'" href="'. $CFG->wwwroot
. $url .'" '.
765 "onclick=\"this.target='$name'; return openpopup('$url', '$name', '$options', $fullscreen);\">$linkname</a>";
768 error('Undefined element - can\'t create popup window.');
780 * Creates and displays (or returns) a link to a popup window, using element_to_popup_window function.
782 * @return string html code to display a link to a popup window.
783 * @see element_to_popup_window()
785 function link_to_popup_window ($url, $name=null, $linkname=null,
786 $height=400, $width=500, $title=null,
787 $options=null, $return=false) {
789 return element_to_popup_window('link', $url, $name, $linkname, $height, $width, $title, $options, $return, null, null);
793 * Creates and displays (or returns) a buttons to a popup window, using element_to_popup_window function.
795 * @return string html code to display a button to a popup window.
796 * @see element_to_popup_window()
798 function button_to_popup_window ($url, $name=null, $linkname=null,
799 $height=400, $width=500, $title=null, $options=null, $return=false,
800 $id=null, $class=null) {
802 return element_to_popup_window('button', $url, $name, $linkname, $height, $width, $title, $options, $return, $id, $class);
807 * Prints a simple button to close a window
808 * @param string $name name of the window to close
809 * @param boolean $return whether this function should return a string or output it
810 * @return string if $return is true, nothing otherwise
812 function close_window_button($name='closewindow', $return=false) {
817 $output .= '<div class="closewindow">' . "\n";
818 $output .= '<form action="#"><div>';
819 $output .= '<input type="button" onclick="self.close();" value="'.get_string($name).'" />';
820 $output .= '</div></form>';
821 $output .= '</div>' . "\n";
831 * Try and close the current window immediately using Javascript
832 * @param int $delay the delay in seconds before closing the window
834 function close_window($delay=0) {
836 <script type
="text/javascript">
838 function close_this_window() {
841 setTimeout("close_this_window()", <?php
echo $delay * 1000 ?
>);
845 <?php
print_string('pleaseclose') ?
>
853 * Given an array of values, output the HTML for a select element with those options.
854 * Normally, you only need to use the first few parameters.
856 * @param array $options The options to offer. An array of the form
857 * $options[{value}] = {text displayed for that option};
858 * @param string $name the name of this form control, as in <select name="..." ...
859 * @param string $selected the option to select initially, default none.
860 * @param string $nothing The label for the 'nothing is selected' option. Defaults to get_string('choose').
861 * Set this to '' if you don't want a 'nothing is selected' option.
862 * @param string $script in not '', then this is added to the <select> element as an onchange handler.
863 * @param string $nothingvalue The value corresponding to the $nothing option. Defaults to 0.
864 * @param boolean $return if false (the default) the the output is printed directly, If true, the
865 * generated HTML is returned as a string.
866 * @param boolean $disabled if true, the select is generated in a disabled state. Default, false.
867 * @param int $tabindex if give, sets the tabindex attribute on the <select> element. Default none.
868 * @param string $id value to use for the id attribute of the <select> element. If none is given,
869 * then a suitable one is constructed.
871 function choose_from_menu ($options, $name, $selected='', $nothing='choose', $script='',
872 $nothingvalue='0', $return=false, $disabled=false, $tabindex=0, $id='') {
874 if ($nothing == 'choose') {
875 $nothing = get_string('choose') .'...';
878 $attributes = ($script) ?
'onchange="'. $script .'"' : '';
880 $attributes .= ' disabled="disabled"';
884 $attributes .= ' tabindex="'.$tabindex.'"';
889 // name may contaion [], which would make an invalid id. e.g. numeric question type editing form, assignment quickgrading
890 $id = str_replace('[', '', $id);
891 $id = str_replace(']', '', $id);
894 $output = '<select id="'.$id.'" name="'. $name .'" '. $attributes .'>' . "\n";
896 $output .= ' <option value="'. s($nothingvalue) .'"'. "\n";
897 if ($nothingvalue === $selected) {
898 $output .= ' selected="selected"';
900 $output .= '>'. $nothing .'</option>' . "\n";
902 if (!empty($options)) {
903 foreach ($options as $value => $label) {
904 $output .= ' <option value="'. s($value) .'"';
905 if ((string)$value == (string)$selected) {
906 $output .= ' selected="selected"';
909 $output .= '>'. $value .'</option>' . "\n";
911 $output .= '>'. $label .'</option>' . "\n";
915 $output .= '</select>' . "\n";
925 * Choose value 0 or 1 from a menu with options 'No' and 'Yes'.
926 * Other options like choose_from_menu.
927 * @param string $name
928 * @param string $selected
929 * @param string $string (defaults to '')
930 * @param boolean $return whether this function should return a string or output it (defaults to false)
931 * @param boolean $disabled (defaults to false)
932 * @param int $tabindex
934 function choose_from_menu_yesno($name, $selected, $script = '',
935 $return = false, $disabled = false, $tabindex = 0) {
936 return choose_from_menu(array(get_string('no'), get_string('yes')), $name,
937 $selected, '', $script, '0', $return, $disabled, $tabindex);
941 * Just like choose_from_menu, but takes a nested array (2 levels) and makes a dropdown menu
942 * including option headings with the first level.
944 function choose_from_menu_nested($options,$name,$selected='',$nothing='choose',$script = '',
945 $nothingvalue=0,$return=false,$disabled=false,$tabindex=0) {
947 if ($nothing == 'choose') {
948 $nothing = get_string('choose') .'...';
951 $attributes = ($script) ?
'onchange="'. $script .'"' : '';
953 $attributes .= ' disabled="disabled"';
957 $attributes .= ' tabindex="'.$tabindex.'"';
960 $output = '<select id="menu'.$name.'" name="'. $name .'" '. $attributes .'>' . "\n";
962 $output .= ' <option value="'. $nothingvalue .'"'. "\n";
963 if ($nothingvalue === $selected) {
964 $output .= ' selected="selected"';
966 $output .= '>'. $nothing .'</option>' . "\n";
968 if (!empty($options)) {
969 foreach ($options as $section => $values) {
971 $output .= ' <optgroup label="'. s(format_string($section)) .'">'."\n";
972 foreach ($values as $value => $label) {
973 $output .= ' <option value="'. format_string($value) .'"';
974 if ((string)$value == (string)$selected) {
975 $output .= ' selected="selected"';
978 $output .= '>'. $value .'</option>' . "\n";
980 $output .= '>'. $label .'</option>' . "\n";
983 $output .= ' </optgroup>'."\n";
986 $output .= '</select>' . "\n";
997 * Given an array of values, creates a group of radio buttons to be part of a form
999 * @param array $options An array of value-label pairs for the radio group (values as keys)
1000 * @param string $name Name of the radiogroup (unique in the form)
1001 * @param string $checked The value that is already checked
1003 function choose_from_radio ($options, $name, $checked='', $return=false) {
1005 static $idcounter = 0;
1011 $output = '<span class="radiogroup '.$name."\">\n";
1013 if (!empty($options)) {
1015 foreach ($options as $value => $label) {
1016 $htmlid = 'auto-rb'.sprintf('%04d', ++
$idcounter);
1017 $output .= ' <span class="radioelement '.$name.' rb'.$currentradio."\">";
1018 $output .= '<input name="'.$name.'" id="'.$htmlid.'" type="radio" value="'.$value.'"';
1019 if ($value == $checked) {
1020 $output .= ' checked="checked"';
1022 if ($label === '') {
1023 $output .= ' /> <label for="'.$htmlid.'">'. $value .'</label></span>' . "\n";
1025 $output .= ' /> <label for="'.$htmlid.'">'. $label .'</label></span>' . "\n";
1027 $currentradio = ($currentradio +
1) %
2;
1031 $output .= '</span>' . "\n";
1040 /** Display an standard html checkbox with an optional label
1042 * @param string $name The name of the checkbox
1043 * @param string $value The valus that the checkbox will pass when checked
1044 * @param boolean $checked The flag to tell the checkbox initial state
1045 * @param string $label The label to be showed near the checkbox
1046 * @param string $alt The info to be inserted in the alt tag
1048 function print_checkbox ($name, $value, $checked = true, $label = '', $alt = '', $script='',$return=false) {
1050 static $idcounter = 0;
1057 $alt = strip_tags($alt);
1063 $strchecked = ' checked="checked"';
1068 $htmlid = 'auto-cb'.sprintf('%04d', ++
$idcounter);
1069 $output = '<span class="checkbox '.$name."\">";
1070 $output .= '<input name="'.$name.'" id="'.$htmlid.'" type="checkbox" value="'.$value.'" alt="'.$alt.'"'.$strchecked.' '.((!empty($script)) ?
' onclick="'.$script.'" ' : '').' />';
1071 if(!empty($label)) {
1072 $output .= ' <label for="'.$htmlid.'">'.$label.'</label>';
1074 $output .= '</span>'."\n";
1076 if (empty($return)) {
1084 /** Display an standard html text field with an optional label
1086 * @param string $name The name of the text field
1087 * @param string $value The value of the text field
1088 * @param string $label The label to be showed near the text field
1089 * @param string $alt The info to be inserted in the alt tag
1091 function print_textfield ($name, $value, $alt = '',$size=50,$maxlength=0, $return=false) {
1093 static $idcounter = 0;
1103 if (!empty($maxlength)) {
1104 $maxlength = ' maxlength="'.$maxlength.'" ';
1107 $htmlid = 'auto-tf'.sprintf('%04d', ++
$idcounter);
1108 $output = '<span class="textfield '.$name."\">";
1109 $output .= '<input name="'.$name.'" id="'.$htmlid.'" type="text" value="'.$value.'" size="'.$size.'" '.$maxlength.' alt="'.$alt.'" />';
1111 $output .= '</span>'."\n";
1113 if (empty($return)) {
1123 * Implements a complete little popup form
1126 * @param string $common The URL up to the point of the variable that changes
1127 * @param array $options Alist of value-label pairs for the popup list
1128 * @param string $formid Id must be unique on the page (originaly $formname)
1129 * @param string $selected The option that is already selected
1130 * @param string $nothing The label for the "no choice" option
1131 * @param string $help The name of a help page if help is required
1132 * @param string $helptext The name of the label for the help button
1133 * @param boolean $return Indicates whether the function should return the text
1134 * as a string or echo it directly to the page being rendered
1135 * @param string $targetwindow The name of the target page to open the linked page in.
1136 * @param string $selectlabel Text to place in a [label] element - preferred for accessibility.
1137 * @param array $optionsextra TODO, an array?
1138 * @return string If $return is true then the entire form is returned as a string.
1139 * @todo Finish documenting this function<br>
1141 function popup_form($common, $options, $formid, $selected='', $nothing='choose', $help='', $helptext='', $return=false,
1142 $targetwindow='self', $selectlabel='', $optionsextra=NULL) {
1145 static $go, $choose; /// Locally cached, in case there's lots on a page
1147 if (empty($options)) {
1152 $go = get_string('go');
1155 if ($nothing == 'choose') {
1156 if (!isset($choose)) {
1157 $choose = get_string('choose');
1159 $nothing = $choose.'...';
1162 // changed reference to document.getElementById('id_abc') instead of document.abc
1164 $output = '<form action="'.$CFG->wwwroot
.'/course/jumpto.php"'.
1167 ' id="'.$formid.'"'.
1168 ' class="popupform">';
1170 $button = helpbutton($help, $helptext, 'moodle', true, false, '', true);
1176 $selectlabel = '<label for="'.$formid.'_jump">'.$selectlabel.'</label>';
1179 //IE and Opera fire the onchange when ever you move into a dropdwown list with the keyboard.
1180 //onfocus will call a function inside dropdown.js. It fixes this IE/Opera behavior.
1181 if (check_browser_version('MSIE') ||
check_browser_version('Opera')) {
1182 $output .= '<div>'.$selectlabel.$button.'<select id="'.$formid.'_jump" onfocus="initSelect(\''.$formid.'\','.$targetwindow.')" name="jump">'."\n";
1186 $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";
1189 if ($nothing != '') {
1190 $output .= " <option value=\"javascript:void(0)\">$nothing</option>\n";
1193 $inoptgroup = false;
1195 foreach ($options as $value => $label) {
1197 if ($label == '--') { /// we are ending previous optgroup
1198 /// Check to see if we already have a valid open optgroup
1199 /// XHTML demands that there be at least 1 option within an optgroup
1200 if ($inoptgroup and (count($optgr) > 1) ) {
1201 $output .= implode('', $optgr);
1202 $output .= ' </optgroup>';
1205 $inoptgroup = false;
1207 } else if (substr($label,0,2) == '--') { /// we are starting a new optgroup
1209 /// Check to see if we already have a valid open optgroup
1210 /// XHTML demands that there be at least 1 option within an optgroup
1211 if ($inoptgroup and (count($optgr) > 1) ) {
1212 $output .= implode('', $optgr);
1213 $output .= ' </optgroup>';
1219 $optgr[] = ' <optgroup label="'. s(format_string(substr($label,2))) .'">'; // Plain labels
1221 $inoptgroup = true; /// everything following will be in an optgroup
1225 if (!empty($CFG->usesid
) && !isset($_COOKIE[session_name()]))
1227 $url=sid_process_url( $common . $value );
1230 $url=$common . $value;
1232 $optstr = ' <option value="' . $url . '"';
1234 if ($value == $selected) {
1235 $optstr .= ' selected="selected"';
1238 if (!empty($optionsextra[$value])) {
1239 $optstr .= ' '.$optionsextra[$value];
1243 $optstr .= '>'. $label .'</option>' . "\n";
1245 $optstr .= '>'. $value .'</option>' . "\n";
1257 /// catch the final group if not closed
1258 if ($inoptgroup and count($optgr) > 1) {
1259 $output .= implode('', $optgr);
1260 $output .= ' </optgroup>';
1263 $output .= '</select>';
1264 $output .= '<input type="hidden" name="sesskey" value="'.sesskey().'" />';
1265 $output .= '<div id="noscript'.$formid.'" style="display: inline;">';
1266 $output .= '<input type="submit" value="'.$go.'" /></div>';
1267 $output .= '<script type="text/javascript">'.
1269 'document.getElementById("noscript'.$formid.'").style.display = "none";'.
1270 "\n//]]>\n".'</script>';
1271 $output .= '</div>';
1272 $output .= '</form>';
1283 * Prints some red text
1285 * @param string $error The text to be displayed in red
1287 function formerr($error) {
1289 if (!empty($error)) {
1290 echo '<span class="error">'. $error .'</span>';
1295 * Validates an email to make sure it makes sense.
1297 * @param string $address The email address to validate.
1300 function validate_email($address) {
1302 return (ereg('^[-!#$%&\'*+\\/0-9=?A-Z^_`a-z{|}~]+'.
1303 '(\.[-!#$%&\'*+\\/0-9=?A-Z^_`a-z{|}~]+)*'.
1305 '[-!#$%&\'*+\\/0-9=?A-Z^_`a-z{|}~]+\.'.
1306 '[-!#$%&\'*+\\./0-9=?A-Z^_`a-z{|}~]+$',
1311 * Extracts file argument either from file parameter or PATH_INFO
1313 * @param string $scriptname name of the calling script
1314 * @return string file path (only safe characters)
1316 function get_file_argument($scriptname) {
1319 $relativepath = FALSE;
1321 // first try normal parameter (compatible method == no relative links!)
1322 $relativepath = optional_param('file', FALSE, PARAM_PATH
);
1323 if ($relativepath === '/testslasharguments') {
1324 echo 'test -1 : Incorrect use - try "file.php/testslasharguments" instead'; //indicate fopen/fread works for health center
1328 // then try extract file from PATH_INFO (slasharguments method)
1329 if (!$relativepath and !empty($_SERVER['PATH_INFO'])) {
1330 $path_info = $_SERVER['PATH_INFO'];
1331 // check that PATH_INFO works == must not contain the script name
1332 if (!strpos($path_info, $scriptname)) {
1333 $relativepath = clean_param(rawurldecode($path_info), PARAM_PATH
);
1334 if ($relativepath === '/testslasharguments') {
1335 echo 'test 1 : Slasharguments test passed. Server confguration is compatible with file.php/1/pic.jpg slashargument setting.'; //indicate ok for health center
1341 // now if both fail try the old way
1342 // (for compatibility with misconfigured or older buggy php implementations)
1343 if (!$relativepath) {
1344 $arr = explode($scriptname, me());
1345 if (!empty($arr[1])) {
1346 $path_info = strip_querystring($arr[1]);
1347 $relativepath = clean_param(rawurldecode($path_info), PARAM_PATH
);
1348 if ($relativepath === '/testslasharguments') {
1349 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
1355 return $relativepath;
1359 * Searches the current environment variables for some slash arguments
1361 * @param string $file ?
1362 * @todo Finish documenting this function
1364 function get_slash_arguments($file='file.php') {
1366 if (!$string = me()) {
1370 $pathinfo = explode($file, $string);
1372 if (!empty($pathinfo[1])) {
1373 return addslashes($pathinfo[1]);
1380 * Extracts arguments from "/foo/bar/something"
1381 * eg http://mysite.com/script.php/foo/bar/something
1383 * @param string $string ?
1385 * @return array|string
1386 * @todo Finish documenting this function
1388 function parse_slash_arguments($string, $i=0) {
1390 if (detect_munged_arguments($string)) {
1393 $args = explode('/', $string);
1395 if ($i) { // return just the required argument
1398 } else { // return the whole array
1399 array_shift($args); // get rid of the empty first one
1405 * Just returns an array of text formats suitable for a popup menu
1407 * @uses FORMAT_MOODLE
1409 * @uses FORMAT_PLAIN
1410 * @uses FORMAT_MARKDOWN
1413 function format_text_menu() {
1415 return array (FORMAT_MOODLE
=> get_string('formattext'),
1416 FORMAT_HTML
=> get_string('formathtml'),
1417 FORMAT_PLAIN
=> get_string('formatplain'),
1418 FORMAT_MARKDOWN
=> get_string('formatmarkdown'));
1422 * Given text in a variety of format codings, this function returns
1423 * the text as safe HTML.
1425 * This function should mainly be used for long strings like posts,
1426 * answers, glossary items etc. For short strings @see format_string().
1429 * @uses FORMAT_MOODLE
1431 * @uses FORMAT_PLAIN
1433 * @uses FORMAT_MARKDOWN
1434 * @param string $text The text to be formatted. This is raw text originally from user input.
1435 * @param int $format Identifier of the text format to be used
1436 * (FORMAT_MOODLE, FORMAT_HTML, FORMAT_PLAIN, FORMAT_WIKI, FORMAT_MARKDOWN)
1437 * @param array $options ?
1438 * @param int $courseid ?
1440 * @todo Finish documenting this function
1442 function format_text($text, $format=FORMAT_MOODLE
, $options=NULL, $courseid=NULL) {
1444 global $CFG, $COURSE;
1446 static $croncache = array();
1449 return ''; // no need to do any filters and cleaning
1452 if (!isset($options->trusttext
)) {
1453 $options->trusttext
= false;
1456 if (!isset($options->noclean
)) {
1457 $options->noclean
=false;
1459 if (!isset($options->nocache
)) {
1460 $options->nocache
=false;
1462 if (!isset($options->smiley
)) {
1463 $options->smiley
=true;
1465 if (!isset($options->filter
)) {
1466 $options->filter
=true;
1468 if (!isset($options->para
)) {
1469 $options->para
=true;
1471 if (!isset($options->newlines
)) {
1472 $options->newlines
=true;
1475 if (empty($courseid)) {
1476 $courseid = $COURSE->id
;
1479 if (!empty($CFG->cachetext
) and empty($options->nocache
)) {
1480 $time = time() - $CFG->cachetext
;
1481 $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
);
1483 if (defined('FULLME') and FULLME
== 'cron') {
1484 if (isset($croncache[$md5key])) {
1485 return $croncache[$md5key];
1489 if ($oldcacheitem = get_record_sql('SELECT * FROM '.$CFG->prefix
.'cache_text WHERE md5key = \''.$md5key.'\'', true)) {
1490 if ($oldcacheitem->timemodified
>= $time) {
1491 if (defined('FULLME') and FULLME
== 'cron') {
1492 if (count($croncache) > 150) {
1494 $key = key($croncache);
1495 unset($croncache[$key]);
1497 $croncache[$md5key] = $oldcacheitem->formattedtext
;
1499 return $oldcacheitem->formattedtext
;
1504 // trusttext overrides the noclean option!
1505 if ($options->trusttext
) {
1506 if (trusttext_present($text)) {
1507 $text = trusttext_strip($text);
1508 if (!empty($CFG->enabletrusttext
)) {
1509 $options->noclean
= true;
1511 $options->noclean
= false;
1514 $options->noclean
= false;
1516 } else if (!debugging('', DEBUG_DEVELOPER
)) {
1517 // strip any forgotten trusttext in non-developer mode
1518 // do not forget to disable text cache when debugging trusttext!!
1519 $text = trusttext_strip($text);
1522 $CFG->currenttextiscacheable
= true; // Default status - can be changed by any filter
1526 if ($options->smiley
) {
1527 replace_smilies($text);
1529 if (!$options->noclean
) {
1530 $text = clean_text($text, FORMAT_HTML
);
1532 if ($options->filter
) {
1533 $text = filter_text($text, $courseid);
1538 $text = s($text); // cleans dangerous JS
1539 $text = rebuildnolinktag($text);
1540 $text = str_replace(' ', ' ', $text);
1541 $text = nl2br($text);
1545 // this format is deprecated
1546 $text = '<p>NOTICE: Wiki-like formatting has been removed from Moodle. You should not be seeing
1547 this message as all texts should have been converted to Markdown format instead.
1548 Please post a bug report to http://moodle.org/bugs with information about where you
1549 saw this message.</p>'.s($text);
1552 case FORMAT_MARKDOWN
:
1553 $text = markdown_to_html($text);
1554 if ($options->smiley
) {
1555 replace_smilies($text);
1557 if (!$options->noclean
) {
1558 $text = clean_text($text, FORMAT_HTML
);
1561 if ($options->filter
) {
1562 $text = filter_text($text, $courseid);
1566 default: // FORMAT_MOODLE or anything else
1567 $text = text_to_html($text, $options->smiley
, $options->para
, $options->newlines
);
1568 if (!$options->noclean
) {
1569 $text = clean_text($text, FORMAT_HTML
);
1572 if ($options->filter
) {
1573 $text = filter_text($text, $courseid);
1578 if (empty($options->nocache
) and !empty($CFG->cachetext
) and $CFG->currenttextiscacheable
) {
1579 if (defined('FULLME') and FULLME
== 'cron') {
1580 // special static cron cache - no need to store it in db if its not already there
1581 if (count($croncache) > 150) {
1583 $key = key($croncache);
1584 unset($croncache[$key]);
1586 $croncache[$md5key] = $text;
1590 $newcacheitem = new object();
1591 $newcacheitem->md5key
= $md5key;
1592 $newcacheitem->formattedtext
= addslashes($text);
1593 $newcacheitem->timemodified
= time();
1594 if ($oldcacheitem) { // See bug 4677 for discussion
1595 $newcacheitem->id
= $oldcacheitem->id
;
1596 @update_record
('cache_text', $newcacheitem); // Update existing record in the cache table
1597 // It's unlikely that the cron cache cleaner could have
1598 // deleted this entry in the meantime, as it allows
1599 // some extra time to cover these cases.
1601 @insert_record
('cache_text', $newcacheitem); // Insert a new record in the cache table
1602 // Again, it's possible that another user has caused this
1603 // record to be created already in the time that it took
1604 // to traverse this function. That's OK too, as the
1605 // call above handles duplicate entries, and eventually
1606 // the cron cleaner will delete them.
1613 /** Converts the text format from the value to the 'internal'
1614 * name or vice versa. $key can either be the value or the name
1615 * and you get the other back.
1617 * @param mixed int 0-4 or string one of 'moodle','html','plain','markdown'
1618 * @return mixed as above but the other way around!
1620 function text_format_name( $key ) {
1622 $lookup[FORMAT_MOODLE
] = 'moodle';
1623 $lookup[FORMAT_HTML
] = 'html';
1624 $lookup[FORMAT_PLAIN
] = 'plain';
1625 $lookup[FORMAT_MARKDOWN
] = 'markdown';
1627 if (!is_numeric($key)) {
1628 $key = strtolower( $key );
1629 $value = array_search( $key, $lookup );
1632 if (isset( $lookup[$key] )) {
1633 $value = $lookup[ $key ];
1640 * Resets all data related to filters, called during upgrade or when filter settings change.
1643 function reset_text_filters_cache() {
1646 delete_records('cache_text');
1647 $purifdir = $CFG->dataroot
.'/cache/htmlpurifier';
1648 remove_dir($purifdir, true);
1651 /** Given a simple string, this function returns the string
1652 * processed by enabled string filters if $CFG->filterall is enabled
1654 * This function should be used to print short strings (non html) that
1655 * need filter processing e.g. activity titles, post subjects,
1656 * glossary concepts.
1658 * @param string $string The string to be filtered.
1659 * @param boolean $striplinks To strip any link in the result text (Moodle 1.8 default changed from false to true! MDL-8713)
1660 * @param int $courseid Current course as filters can, potentially, use it
1663 function format_string ($string, $striplinks=true, $courseid=NULL ) {
1665 global $CFG, $COURSE;
1667 //We'll use a in-memory cache here to speed up repeated strings
1668 static $strcache = false;
1670 if ($strcache === false or count($strcache) > 2000 ) { // this number might need some tuning to limit memory usage in cron
1671 $strcache = array();
1675 if (empty($courseid)) {
1676 $courseid = $COURSE->id
;
1680 $md5 = md5($string.'<+>'.$striplinks.'<+>'.$courseid.'<+>'.current_language());
1682 //Fetch from cache if possible
1683 if (isset($strcache[$md5])) {
1684 return $strcache[$md5];
1687 // First replace all ampersands not followed by html entity code
1688 $string = preg_replace("/\&(?![a-zA-Z0-9#]{1,8};)/", "&", $string);
1690 if (!empty($CFG->filterall
)) {
1691 $string = filter_string($string, $courseid);
1694 // If the site requires it, strip ALL tags from this string
1695 if (!empty($CFG->formatstringstriptags
)) {
1696 $string = strip_tags($string);
1698 // Otherwise strip just links if that is required (default)
1699 } else if ($striplinks) { //strip links in string
1700 $string = preg_replace('/(<a[^>]+?>)(.+?)(<\/a>)/is','$2',$string);
1704 $strcache[$md5] = $string;
1710 * Given text in a variety of format codings, this function returns
1711 * the text as plain text suitable for plain email.
1713 * @uses FORMAT_MOODLE
1715 * @uses FORMAT_PLAIN
1717 * @uses FORMAT_MARKDOWN
1718 * @param string $text The text to be formatted. This is raw text originally from user input.
1719 * @param int $format Identifier of the text format to be used
1720 * (FORMAT_MOODLE, FORMAT_HTML, FORMAT_PLAIN, FORMAT_WIKI, FORMAT_MARKDOWN)
1723 function format_text_email($text, $format) {
1732 $text = wiki_to_html($text);
1733 /// This expression turns links into something nice in a text format. (Russell Jungwirth)
1734 /// From: http://php.net/manual/en/function.eregi-replace.php and simplified
1735 $text = eregi_replace('(<a [^<]*href=["|\']?([^ "\']*)["|\']?[^>]*>([^<]*)</a>)','\\3 [ \\2 ]', $text);
1736 return strtr(strip_tags($text), array_flip(get_html_translation_table(HTML_ENTITIES
)));
1740 return html_to_text($text);
1744 case FORMAT_MARKDOWN
:
1746 $text = eregi_replace('(<a [^<]*href=["|\']?([^ "\']*)["|\']?[^>]*>([^<]*)</a>)','\\3 [ \\2 ]', $text);
1747 return strtr(strip_tags($text), array_flip(get_html_translation_table(HTML_ENTITIES
)));
1753 * Given some text in HTML format, this function will pass it
1754 * through any filters that have been defined in $CFG->textfilterx
1755 * The variable defines a filepath to a file containing the
1756 * filter function. The file must contain a variable called
1757 * $textfilter_function which contains the name of the function
1758 * with $courseid and $text parameters
1760 * @param string $text The text to be passed through format filters
1761 * @param int $courseid ?
1763 * @todo Finish documenting this function
1765 function filter_text($text, $courseid=NULL) {
1766 global $CFG, $COURSE;
1768 if (empty($courseid)) {
1769 $courseid = $COURSE->id
; // (copied from format_text)
1772 if (!empty($CFG->textfilters
)) {
1773 require_once($CFG->libdir
.'/filterlib.php');
1774 $textfilters = explode(',', $CFG->textfilters
);
1775 foreach ($textfilters as $textfilter) {
1776 if (is_readable($CFG->dirroot
.'/'. $textfilter .'/filter.php')) {
1777 include_once($CFG->dirroot
.'/'. $textfilter .'/filter.php');
1778 $functionname = basename($textfilter).'_filter';
1779 if (function_exists($functionname)) {
1780 $text = $functionname($courseid, $text);
1786 /// <nolink> tags removed for XHTML compatibility
1787 $text = str_replace('<nolink>', '', $text);
1788 $text = str_replace('</nolink>', '', $text);
1795 * Given a string (short text) in HTML format, this function will pass it
1796 * through any filters that have been defined in $CFG->stringfilters
1797 * The variable defines a filepath to a file containing the
1798 * filter function. The file must contain a variable called
1799 * $textfilter_function which contains the name of the function
1800 * with $courseid and $text parameters
1802 * @param string $string The text to be passed through format filters
1803 * @param int $courseid The id of a course
1806 function filter_string($string, $courseid=NULL) {
1807 global $CFG, $COURSE;
1809 if (empty($CFG->textfilters
)) { // All filters are disabled anyway so quit
1813 if (empty($courseid)) {
1814 $courseid = $COURSE->id
;
1817 require_once($CFG->libdir
.'/filterlib.php');
1819 if (isset($CFG->stringfilters
)) { // We have a predefined list to use, great!
1820 if (empty($CFG->stringfilters
)) { // but it's blank, so finish now
1823 $stringfilters = explode(',', $CFG->stringfilters
); // ..use the list we have
1825 } else { // Otherwise try to derive a list from textfilters
1826 if (strpos($CFG->textfilters
, 'filter/multilang') !== false) { // Multilang is here
1827 $stringfilters = array('filter/multilang'); // Let's use just that
1828 $CFG->stringfilters
= 'filter/multilang'; // Save it for next time through
1830 $CFG->stringfilters
= ''; // Save the result and return
1836 foreach ($stringfilters as $stringfilter) {
1837 if (is_readable($CFG->dirroot
.'/'. $stringfilter .'/filter.php')) {
1838 include_once($CFG->dirroot
.'/'. $stringfilter .'/filter.php');
1839 $functionname = basename($stringfilter).'_filter';
1840 if (function_exists($functionname)) {
1841 $string = $functionname($courseid, $string);
1846 /// <nolink> tags removed for XHTML compatibility
1847 $string = str_replace('<nolink>', '', $string);
1848 $string = str_replace('</nolink>', '', $string);
1854 * Is the text marked as trusted?
1856 * @param string $text text to be searched for TRUSTTEXT marker
1859 function trusttext_present($text) {
1860 if (strpos($text, TRUSTTEXT
) !== FALSE) {
1868 * This funtion MUST be called before the cleaning or any other
1869 * function that modifies the data! We do not know the origin of trusttext
1870 * in database, if it gets there in tweaked form we must not convert it
1871 * to supported form!!!
1873 * Please be carefull not to use stripslashes on data from database
1874 * or twice stripslashes when processing data recieved from user.
1876 * @param string $text text that may contain TRUSTTEXT marker
1877 * @return text without any TRUSTTEXT marker
1879 function trusttext_strip($text) {
1882 while (true) { //removing nested TRUSTTEXT
1884 $text = str_replace(TRUSTTEXT
, '', $text);
1885 if (strcmp($orig, $text) === 0) {
1892 * Mark text as trusted, such text may contain any HTML tags because the
1893 * normal text cleaning will be bypassed.
1894 * Please make sure that the text comes from trusted user before storing
1897 function trusttext_mark($text) {
1899 if (!empty($CFG->enabletrusttext
) and (strpos($text, TRUSTTEXT
) === FALSE)) {
1900 return TRUSTTEXT
.$text;
1905 function trusttext_after_edit(&$text, $context) {
1906 if (has_capability('moodle/site:trustcontent', $context)) {
1907 $text = trusttext_strip($text);
1908 $text = trusttext_mark($text);
1910 $text = trusttext_strip($text);
1914 function trusttext_prepare_edit(&$text, &$format, $usehtmleditor, $context) {
1917 $options = new object();
1918 $options->smiley
= false;
1919 $options->filter
= false;
1920 if (!empty($CFG->enabletrusttext
)
1921 and has_capability('moodle/site:trustcontent', $context)
1922 and trusttext_present($text)) {
1923 $options->noclean
= true;
1925 $options->noclean
= false;
1927 $text = trusttext_strip($text);
1928 if ($usehtmleditor) {
1929 $text = format_text($text, $format, $options);
1930 $format = FORMAT_HTML
;
1931 } else if (!$options->noclean
){
1932 $text = clean_text($text, $format);
1937 * Given raw text (eg typed in by a user), this function cleans it up
1938 * and removes any nasty tags that could mess up Moodle pages.
1940 * @uses FORMAT_MOODLE
1941 * @uses FORMAT_PLAIN
1942 * @uses ALLOWED_TAGS
1943 * @param string $text The text to be cleaned
1944 * @param int $format Identifier of the text format to be used
1945 * (FORMAT_MOODLE, FORMAT_HTML, FORMAT_PLAIN, FORMAT_WIKI, FORMAT_MARKDOWN)
1946 * @return string The cleaned up text
1948 function clean_text($text, $format=FORMAT_MOODLE
) {
1950 global $ALLOWED_TAGS, $CFG;
1952 if (empty($text) or is_numeric($text)) {
1953 return (string)$text;
1958 case FORMAT_MARKDOWN
:
1963 if (!empty($CFG->enablehtmlpurifier
)) {
1964 $text = purify_html($text);
1966 /// Fix non standard entity notations
1967 $text = preg_replace('/(&#[0-9]+)(;?)/', "\\1;", $text);
1968 $text = preg_replace('/(&#x[0-9a-fA-F]+)(;?)/', "\\1;", $text);
1970 /// Remove tags that are not allowed
1971 $text = strip_tags($text, $ALLOWED_TAGS);
1973 /// Clean up embedded scripts and , using kses
1974 $text = cleanAttributes($text);
1976 /// Again remove tags that are not allowed
1977 $text = strip_tags($text, $ALLOWED_TAGS);
1981 /// Remove potential script events - some extra protection for undiscovered bugs in our code
1982 $text = eregi_replace("([^a-z])language([[:space:]]*)=", "\\1Xlanguage=", $text);
1983 $text = eregi_replace("([^a-z])on([a-z]+)([[:space:]]*)=", "\\1Xon\\2=", $text);
1990 * KSES replacement cleaning function - uses HTML Purifier.
1992 function purify_html($text) {
1995 // this can not be done only once because we sometimes need to reset the cache
1996 $cachedir = $CFG->dataroot
.'/cache/htmlpurifier/';
1997 $status = check_dir_exists($cachedir, true, true);
1999 static $purifier = false;
2000 if ($purifier === false) {
2001 require_once $CFG->libdir
.'/htmlpurifier/HTMLPurifier.auto.php';
2002 $config = HTMLPurifier_Config
::createDefault();
2003 $config->set('Core', 'AcceptFullDocuments', false);
2004 $config->set('Core', 'Encoding', 'UTF-8');
2005 $config->set('HTML', 'Doctype', 'XHTML 1.0 Transitional');
2006 $config->set('Cache', 'SerializerPath', $cachedir);
2007 $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));
2008 $purifier = new HTMLPurifier($config);
2010 return $purifier->purify($text);
2014 * This function takes a string and examines it for HTML tags.
2015 * If tags are detected it passes the string to a helper function {@link cleanAttributes2()}
2016 * which checks for attributes and filters them for malicious content
2017 * 17/08/2004 :: Eamon DOT Costello AT dcu DOT ie
2019 * @param string $str The string to be examined for html tags
2022 function cleanAttributes($str){
2023 $result = preg_replace_callback(
2024 '%(<[^>]*(>|$)|>)%m', #search for html tags
2032 * This function takes a string with an html tag and strips out any unallowed
2033 * protocols e.g. javascript:
2034 * It calls ancillary functions in kses which are prefixed by kses
2035 * 17/08/2004 :: Eamon DOT Costello AT dcu DOT ie
2037 * @param array $htmlArray An array from {@link cleanAttributes()}, containing in its 1st
2038 * element the html to be cleared
2041 function cleanAttributes2($htmlArray){
2043 global $CFG, $ALLOWED_PROTOCOLS;
2044 require_once($CFG->libdir
.'/kses.php');
2046 $htmlTag = $htmlArray[1];
2047 if (substr($htmlTag, 0, 1) != '<') {
2048 return '>'; //a single character ">" detected
2050 if (!preg_match('%^<\s*(/\s*)?([a-zA-Z0-9]+)([^>]*)>?$%', $htmlTag, $matches)) {
2051 return ''; // It's seriously malformed
2053 $slash = trim($matches[1]); //trailing xhtml slash
2054 $elem = $matches[2]; //the element name
2055 $attrlist = $matches[3]; // the list of attributes as a string
2057 $attrArray = kses_hair($attrlist, $ALLOWED_PROTOCOLS);
2060 foreach ($attrArray as $arreach) {
2061 $arreach['name'] = strtolower($arreach['name']);
2062 if ($arreach['name'] == 'style') {
2063 $value = $arreach['value'];
2065 $prevvalue = $value;
2066 $value = kses_no_null($value);
2067 $value = preg_replace("/\/\*.*\*\//Us", '', $value);
2068 $value = kses_decode_entities($value);
2069 $value = preg_replace('/(&#[0-9]+)(;?)/', "\\1;", $value);
2070 $value = preg_replace('/(&#x[0-9a-fA-F]+)(;?)/', "\\1;", $value);
2071 if ($value === $prevvalue) {
2072 $arreach['value'] = $value;
2076 $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']);
2077 $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']);
2078 $arreach['value'] = preg_replace("/b\s*i\s*n\s*d\s*i\s*n\s*g/i", "Xbinding", $arreach['value']);
2079 } else if ($arreach['name'] == 'href') {
2080 //Adobe Acrobat Reader XSS protection
2081 $arreach['value'] = preg_replace('/(\.(pdf|fdf|xfdf|xdp|xfd))[^a-z0-9_\.\-].*$/i', '$1', $arreach['value']);
2083 $attStr .= ' '.$arreach['name'].'="'.$arreach['value'].'"';
2087 if (preg_match('%/\s*$%', $attrlist)) {
2088 $xhtml_slash = ' /';
2090 return '<'. $slash . $elem . $attStr . $xhtml_slash .'>';
2094 * Replaces all known smileys in the text with image equivalents
2097 * @param string $text Passed by reference. The string to search for smily strings.
2100 function replace_smilies(&$text) {
2104 if (empty($CFG->emoticons
)) { /// No emoticons defined, nothing to process here
2108 $lang = current_language();
2109 $emoticonstring = $CFG->emoticons
;
2110 static $e = array();
2111 static $img = array();
2112 static $emoticons = null;
2114 if (is_null($emoticons)) {
2115 $emoticons = array();
2116 if ($emoticonstring) {
2117 $items = explode('{;}', $CFG->emoticons
);
2118 foreach ($items as $item) {
2119 $item = explode('{:}', $item);
2120 $emoticons[$item[0]] = $item[1];
2126 if (empty($img[$lang])) { /// After the first time this is not run again
2127 $e[$lang] = array();
2128 $img[$lang] = array();
2129 foreach ($emoticons as $emoticon => $image){
2130 $alttext = get_string($image, 'pix');
2131 $e[$lang][] = $emoticon;
2132 $img[$lang][] = '<img alt="'. $alttext .'" width="15" height="15" src="'. $CFG->pixpath
.'/s/'. $image .'.gif" />';
2136 // Exclude from transformations all the code inside <script> tags
2137 // Needed to solve Bug 1185. Thanks to jouse 2001 detecting it. :-)
2138 // Based on code from glossary fiter by Williams Castillo.
2141 // Detect all the <script> zones to take out
2142 $excludes = array();
2143 preg_match_all('/<script language(.+?)<\/script>/is',$text,$list_of_excludes);
2145 // Take out all the <script> zones from text
2146 foreach (array_unique($list_of_excludes[0]) as $key=>$value) {
2147 $excludes['<+'.$key.'+>'] = $value;
2150 $text = str_replace($excludes,array_keys($excludes),$text);
2153 /// this is the meat of the code - this is run every time
2154 $text = str_replace($e[$lang], $img[$lang], $text);
2156 // Recover all the <script> zones to text
2158 $text = str_replace(array_keys($excludes),$excludes,$text);
2163 * Given plain text, makes it into HTML as nicely as possible.
2164 * May contain HTML tags already
2167 * @param string $text The string to convert.
2168 * @param boolean $smiley Convert any smiley characters to smiley images?
2169 * @param boolean $para If true then the returned string will be wrapped in paragraph tags
2170 * @param boolean $newlines If true then lines newline breaks will be converted to HTML newline breaks.
2174 function text_to_html($text, $smiley=true, $para=true, $newlines=true) {
2179 /// Remove any whitespace that may be between HTML tags
2180 $text = eregi_replace(">([[:space:]]+)<", "><", $text);
2182 /// Remove any returns that precede or follow HTML tags
2183 $text = eregi_replace("([\n\r])<", " <", $text);
2184 $text = eregi_replace(">([\n\r])", "> ", $text);
2186 convert_urls_into_links($text);
2188 /// Make returns into HTML newlines.
2190 $text = nl2br($text);
2193 /// Turn smileys into images.
2195 replace_smilies($text);
2198 /// Wrap the whole thing in a paragraph tag if required
2200 return '<p>'.$text.'</p>';
2207 * Given Markdown formatted text, make it into XHTML using external function
2210 * @param string $text The markdown formatted text to be converted.
2211 * @return string Converted text
2213 function markdown_to_html($text) {
2216 require_once($CFG->libdir
.'/markdown.php');
2218 return Markdown($text);
2222 * Given HTML text, make it into plain text using external function
2225 * @param string $html The text to be converted.
2228 function html_to_text($html) {
2232 require_once($CFG->libdir
.'/html2text.php');
2234 $result = html2text($html);
2236 // html2text does not fix numerical entities so handle those here.
2237 $tl=textlib_get_instance();
2238 $result = $tl->entities_to_utf8($result,false);
2244 * Given some text this function converts any URLs it finds into HTML links
2246 * @param string $text Passed in by reference. The string to be searched for urls.
2248 function convert_urls_into_links(&$text) {
2249 /// Make lone URLs into links. eg http://moodle.com/
2250 $text = eregi_replace("([[:space:]]|^|\(|\[)([[:alnum:]]+)://([^[:space:]]*)([[:alnum:]#?/&=])",
2251 "\\1<a href=\"\\2://\\3\\4\" target=\"_blank\">\\2://\\3\\4</a>", $text);
2253 /// eg www.moodle.com
2254 $text = eregi_replace("([[:space:]]|^|\(|\[)www\.([^[:space:]]*)([[:alnum:]#?/&=])",
2255 "\\1<a href=\"http://www.\\2\\3\" target=\"_blank\">www.\\2\\3</a>", $text);
2259 * This function will highlight search words in a given string
2260 * It cares about HTML and will not ruin links. It's best to use
2261 * this function after performing any conversions to HTML.
2262 * Function found here: http://forums.devshed.com/t67822/scdaa2d1c3d4bacb4671d075ad41f0854.html
2264 * @param string $needle The string to search for
2265 * @param string $haystack The string to search for $needle in
2266 * @param int $case whether to do case-sensitive or insensitive matching.
2268 * @todo Finish documenting this function
2270 function highlight($needle, $haystack, $case=0,
2271 $left_string='<span class="highlight">', $right_string='</span>') {
2273 if (empty($needle) or empty($haystack)) {
2277 //$list_of_words = eregi_replace("[^-a-zA-Z0-9&.']", " ", $needle); // bug 3101
2278 $list_of_words = $needle;
2279 $list_array = explode(' ', $list_of_words);
2280 for ($i=0; $i<sizeof($list_array); $i++
) {
2281 if (strlen($list_array[$i]) == 1) {
2282 $list_array[$i] = '';
2285 $list_of_words = implode(' ', $list_array);
2286 $list_of_words_cp = $list_of_words;
2288 preg_match_all('/<(.+?)>/is',$haystack,$list_of_words);
2290 foreach (array_unique($list_of_words[0]) as $key=>$value) {
2291 $final['<|'.$key.'|>'] = $value;
2294 $haystack = str_replace($final,array_keys($final),$haystack);
2295 $list_of_words_cp = eregi_replace(' +', '|', $list_of_words_cp);
2297 if ($list_of_words_cp{0}=='|') {
2298 $list_of_words_cp{0} = '';
2300 if ($list_of_words_cp{strlen($list_of_words_cp)-1}=='|') {
2301 $list_of_words_cp{strlen($list_of_words_cp)-1}='';
2304 $list_of_words_cp = trim($list_of_words_cp);
2306 if ($list_of_words_cp) {
2308 $list_of_words_cp = "(". $list_of_words_cp .")";
2311 $haystack = eregi_replace("$list_of_words_cp", "$left_string"."\\1"."$right_string", $haystack);
2313 $haystack = ereg_replace("$list_of_words_cp", "$left_string"."\\1"."$right_string", $haystack);
2316 $haystack = str_replace(array_keys($final),$final,$haystack);
2322 * This function will highlight instances of $needle in $haystack
2323 * It's faster that the above function and doesn't care about
2326 * @param string $needle The string to search for
2327 * @param string $haystack The string to search for $needle in
2330 function highlightfast($needle, $haystack) {
2332 if (empty($needle) or empty($haystack)) {
2336 $parts = explode(moodle_strtolower($needle), moodle_strtolower($haystack));
2338 if (count($parts) === 1) {
2344 foreach ($parts as $key => $part) {
2345 $parts[$key] = substr($haystack, $pos, strlen($part));
2346 $pos +
= strlen($part);
2348 $parts[$key] .= '<span class="highlight">'.substr($haystack, $pos, strlen($needle)).'</span>';
2349 $pos +
= strlen($needle);
2352 return str_replace('<span class="highlight"></span>', '', join('', $parts));
2356 * Return a string containing 'lang', xml:lang and optionally 'dir' HTML attributes.
2357 * Internationalisation, for print_header and backup/restorelib.
2358 * @param $dir Default false.
2359 * @return string Attributes.
2361 function get_html_lang($dir = false) {
2364 if (get_string('thisdirection') == 'rtl') {
2365 $direction = ' dir="rtl"';
2367 $direction = ' dir="ltr"';
2370 //Accessibility: added the 'lang' attribute to $direction, used in theme <html> tag.
2371 $language = str_replace('_', '-', str_replace('_utf8', '', current_language()));
2372 @header
('Content-Language: '.$language);
2373 return ($direction.' lang="'.$language.'" xml:lang="'.$language.'"');
2377 * Return the markup for the destination of the 'Skip to main content' links.
2378 * Accessibility improvement for keyboard-only users.
2379 * Used in course formats, /index.php and /course/index.php
2380 * @return string HTML element.
2382 function skip_main_destination() {
2383 return '<span id="maincontent"></span>';
2387 /// STANDARD WEB PAGE PARTS ///////////////////////////////////////////////////
2390 * Print a standard header
2395 * @param string $title Appears at the top of the window
2396 * @param string $heading Appears at the top of the page
2397 * @param array $navigation Array of $navlinks arrays (keys: name, link, type) for use as breadcrumbs links
2398 * @param string $focus Indicates form element to get cursor focus on load eg inputform.password
2399 * @param string $meta Meta tags to be added to the header
2400 * @param boolean $cache Should this page be cacheable?
2401 * @param string $button HTML code for a button (usually for module editing)
2402 * @param string $menu HTML code for a popup menu
2403 * @param boolean $usexml use XML for this page
2404 * @param string $bodytags This text will be included verbatim in the <body> tag (useful for onload() etc)
2405 * @param bool $return If true, return the visible elements of the header instead of echoing them.
2407 function print_header ($title='', $heading='', $navigation='', $focus='',
2408 $meta='', $cache=true, $button=' ', $menu='',
2409 $usexml=false, $bodytags='', $return=false) {
2411 global $USER, $CFG, $THEME, $SESSION, $ME, $SITE, $COURSE;
2413 if (gettype($navigation) == 'string' && strlen($navigation) != 0 && $navigation != 'home') {
2414 debugging("print_header() was sent a string as 3rd ($navigation) parameter. "
2415 . "This is deprecated in favour of an array built by build_navigation(). Please upgrade your code.", DEBUG_DEVELOPER
);
2418 $heading = format_string($heading); // Fix for MDL-8582
2420 /// This makes sure that the header is never repeated twice on a page
2421 if (defined('HEADER_PRINTED')) {
2422 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().');
2425 define('HEADER_PRINTED', 'true');
2428 /// Add the required stylesheets
2429 $stylesheetshtml = '';
2430 foreach ($CFG->stylesheets
as $stylesheet) {
2431 $stylesheetshtml .= '<link rel="stylesheet" type="text/css" href="'.$stylesheet.'" />'."\n";
2433 $meta = $stylesheetshtml.$meta;
2436 /// Add the meta page from the themes if any were requested
2440 if (!isset($THEME->standardmetainclude
) ||
$THEME->standardmetainclude
) {
2442 include_once($CFG->dirroot
.'/theme/standard/meta.php');
2443 $metapage .= ob_get_contents();
2447 if ($THEME->parent
&& (!isset($THEME->parentmetainclude
) ||
$THEME->parentmetainclude
)) {
2448 if (file_exists($CFG->dirroot
.'/theme/'.$THEME->parent
.'/meta.php')) {
2450 include_once($CFG->dirroot
.'/theme/'.$THEME->parent
.'/meta.php');
2451 $metapage .= ob_get_contents();
2456 if (!isset($THEME->metainclude
) ||
$THEME->metainclude
) {
2457 if (file_exists($CFG->dirroot
.'/theme/'.current_theme().'/meta.php')) {
2459 include_once($CFG->dirroot
.'/theme/'.current_theme().'/meta.php');
2460 $metapage .= ob_get_contents();
2465 $meta = $meta."\n".$metapage;
2467 $meta .= "\n".require_js('',1);
2469 /// Set up some navigation variables
2471 if (is_newnav($navigation)){
2474 if ($navigation == 'home') {
2482 /// This is another ugly hack to make navigation elements available to print_footer later
2483 $THEME->title
= $title;
2484 $THEME->heading
= $heading;
2485 $THEME->navigation
= $navigation;
2486 $THEME->button
= $button;
2487 $THEME->menu
= $menu;
2488 $navmenulist = isset($THEME->navmenulist
) ?
$THEME->navmenulist
: '';
2490 if ($button == '') {
2494 if (!$menu and $navigation) {
2495 if (empty($CFG->loginhttps
)) {
2496 $wwwroot = $CFG->wwwroot
;
2498 $wwwroot = str_replace('http:','https:',$CFG->wwwroot
);
2500 $menu = user_login_string($COURSE);
2503 if (isset($SESSION->justloggedin
)) {
2504 unset($SESSION->justloggedin
);
2505 if (!empty($CFG->displayloginfailures
)) {
2506 if (!empty($USER->username
) and $USER->username
!= 'guest') {
2507 if ($count = count_login_failures($CFG->displayloginfailures
, $USER->username
, $USER->lastlogin
)) {
2508 $menu .= ' <font size="1">';
2509 if (empty($count->accounts
)) {
2510 $menu .= get_string('failedloginattempts', '', $count);
2512 $menu .= get_string('failedloginattemptsall', '', $count);
2514 if (has_capability('moodle/site:viewreports', get_context_instance(CONTEXT_SYSTEM
))) {
2515 $menu .= ' (<a href="'.$CFG->wwwroot
.'/course/report/log/index.php'.
2516 '?chooselog=1&id=1&modid=site_errors">'.get_string('logs').'</a>)';
2525 $meta = '<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />' .
2526 "\n" . $meta . "\n";
2528 @header
('Content-Type: text/html; charset=utf-8');
2530 @header
('Content-Script-Type: text/javascript');
2531 @header
('Content-Style-Type: text/css');
2533 //Accessibility: added the 'lang' attribute to $direction, used in theme <html> tag.
2534 $direction = get_html_lang($dir=true);
2536 if ($cache) { // Allow caching on "back" (but not on normal clicks)
2537 @header
('Cache-Control: private, pre-check=0, post-check=0, max-age=0');
2538 @header
('Pragma: no-cache');
2539 @header
('Expires: ');
2540 } else { // Do everything we can to always prevent clients and proxies caching
2541 @header
('Cache-Control: no-store, no-cache, must-revalidate');
2542 @header
('Cache-Control: post-check=0, pre-check=0', false);
2543 @header
('Pragma: no-cache');
2544 @header
('Expires: Mon, 20 Aug 1969 09:23:00 GMT');
2545 @header
('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
2547 $meta .= "\n<meta http-equiv=\"pragma\" content=\"no-cache\" />";
2548 $meta .= "\n<meta http-equiv=\"expires\" content=\"0\" />";
2550 @header
('Accept-Ranges: none');
2552 $currentlanguage = current_language();
2554 if (empty($usexml)) {
2555 $direction = ' xmlns="http://www.w3.org/1999/xhtml"'. $direction; // See debug_header
2557 $mathplayer = preg_match("/MathPlayer/i", $_SERVER['HTTP_USER_AGENT']);
2559 header('Content-Type: application/xhtml+xml');
2561 echo '<?xml version="1.0" ?>'."\n";
2562 if (!empty($CFG->xml_stylesheets
)) {
2563 $stylesheets = explode(';', $CFG->xml_stylesheets
);
2564 foreach ($stylesheets as $stylesheet) {
2565 echo '<?xml-stylesheet type="text/xsl" href="'. $CFG->wwwroot
.'/'. $stylesheet .'" ?>' . "\n";
2568 echo '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1';
2569 if (!empty($CFG->xml_doctype_extra
)) {
2570 echo ' plus '. $CFG->xml_doctype_extra
;
2572 echo '//' . strtoupper($currentlanguage) . '" "'. $CFG->xml_dtd
.'">'."\n";
2573 $direction = " xmlns=\"http://www.w3.org/1999/xhtml\"
2574 xmlns:math=\"http://www.w3.org/1998/Math/MathML\"
2575 xmlns:xlink=\"http://www.w3.org/1999/xlink\"
2578 $meta .= '<object id="mathplayer" classid="clsid:32F66A20-7614-11D4-BD11-00104BD3F987">' . "\n";
2579 $meta .= '<!--comment required to prevent this becoming an empty tag-->'."\n";
2580 $meta .= '</object>'."\n";
2581 $meta .= '<?import namespace="math" implementation="#mathplayer" ?>' . "\n";
2585 // Clean up the title
2587 $title = format_string($title); // fix for MDL-8582
2588 $title = str_replace('"', '"', $title);
2590 // Create class and id for this page
2592 page_id_and_class($pageid, $pageclass);
2594 $pageclass .= ' course-'.$COURSE->id
;
2596 if (!isloggedin()) {
2597 $pageclass .= ' notloggedin';
2600 if (!empty($USER->editing
)) {
2601 $pageclass .= ' editing';
2604 if (!empty($CFG->blocksdrag
)) {
2605 $pageclass .= ' drag';
2608 $pageclass .= ' dir-'.get_string('thisdirection');
2610 $pageclass .= ' lang-'.$currentlanguage;
2612 $bodytags .= ' class="'.$pageclass.'" id="'.$pageid.'"';
2615 include($CFG->header
);
2616 $output = ob_get_contents();
2619 // container debugging info
2620 $THEME->open_header_containers
= open_containers();
2622 // Skip to main content, see skip_main_destination().
2623 if ($pageid=='course-view' or $pageid=='site-index' or $pageid=='course-index') {
2624 $skiplink = '<a class="skip" href="#maincontent">'.get_string('tocontent', 'access').'</a>';
2625 if (! preg_match('/(.*<div[^>]+id="page"[^>]*>)(.*)/s', $output, $matches)) {
2626 preg_match('/(.*<body.*?>)(.*)/s', $output, $matches);
2628 $output = $matches[1]."\n". $skiplink .$matches[2];
2631 $output = force_strict_header($output);
2633 if (!empty($CFG->messaging
)) {
2634 $output .= message_popup_window();
2637 // Add in any extra JavaScript libraries that occurred during the header
2638 $output .= require_js('', 2);
2648 * Used to include JavaScript libraries.
2650 * When the $lib parameter is given, the function will ensure that the
2651 * named library is loaded onto the page - either in the HTML <head>,
2652 * just after the header, or at an arbitrary later point in the page,
2653 * depending on where this function is called.
2655 * Libraries will not be included more than once, so this works like
2656 * require_once in PHP.
2658 * There are two special-case calls to this function which are both used only
2659 * by weblib print_header:
2660 * $extracthtml = 1: this is used before printing the header.
2661 * It returns the script tag code that should go inside the <head>.
2662 * $extracthtml = 2: this is used after printing the header and handles any
2663 * require_js calls that occurred within the header itself.
2665 * @param mixed $lib - string or array of strings
2666 * string(s) should be the shortname for the library or the
2667 * full path to the library file.
2668 * @param int $extracthtml Do not set this parameter usually (leave 0), only
2669 * weblib should set this to 1 or 2 in print_header function.
2670 * @return mixed No return value, except when using $extracthtml it returns the html code.
2672 function require_js($lib,$extracthtml=0) {
2674 static $loadlibs = array();
2676 static $state = REQUIREJS_BEFOREHEADER
;
2677 static $latecode = '';
2680 // Add the lib to the list of libs to be loaded, if it isn't already
2682 if (is_array($lib)) {
2683 foreach($lib as $singlelib) {
2684 require_js($singlelib);
2687 $libpath = ajax_get_lib($lib);
2688 if (array_search($libpath, $loadlibs) === false) {
2689 $loadlibs[] = $libpath;
2691 // For state other than 0 we need to take action as well as just
2692 // adding it to loadlibs
2693 if($state != REQUIREJS_BEFOREHEADER
) {
2694 // Get the script statement for this library
2695 $scriptstatement=get_require_js_code(array($libpath));
2697 if($state == REQUIREJS_AFTERHEADER
) {
2698 // After the header, print it immediately
2699 print $scriptstatement;
2701 // Haven't finished the header yet. Add it after the
2703 $latecode .= $scriptstatement;
2708 } else if($extracthtml==1) {
2709 if($state !== REQUIREJS_BEFOREHEADER
) {
2710 debugging('Incorrect state in require_js (expected BEFOREHEADER): be careful not to call with empty $lib (except in print_header)');
2712 $state = REQUIREJS_INHEADER
;
2715 return get_require_js_code($loadlibs);
2716 } else if($extracthtml==2) {
2717 if($state !== REQUIREJS_INHEADER
) {
2718 debugging('Incorrect state in require_js (expected INHEADER): be careful not to call with empty $lib (except in print_header)');
2721 $state = REQUIREJS_AFTERHEADER
;
2725 debugging('Unexpected value for $extracthtml');
2730 * Should not be called directly - use require_js. This function obtains the code
2731 * (script tags) needed to include JavaScript libraries.
2732 * @param array $loadlibs Array of library files to include
2733 * @return string HTML code to include them
2735 function get_require_js_code($loadlibs) {
2737 // Return the html needed to load the JavaScript files defined in
2738 // our list of libs to be loaded.
2740 foreach ($loadlibs as $loadlib) {
2741 $output .= '<script type="text/javascript" ';
2742 $output .= " src=\"$loadlib\"></script>\n";
2743 if ($loadlib == $CFG->wwwroot
.'/lib/yui/logger/logger-min.js') {
2744 // Special case, we need the CSS too.
2745 $output .= '<link type="text/css" rel="stylesheet" ';
2746 $output .= " href=\"{$CFG->wwwroot}/lib/yui/logger/assets/logger.css\" />\n";
2754 * Debugging aid: serve page as 'application/xhtml+xml' where possible,
2755 * and substitute the XHTML strict document type.
2756 * Note, requires the 'xmlns' fix in function print_header above.
2757 * See: http://tracker.moodle.org/browse/MDL-7883
2760 function force_strict_header($output) {
2762 $strict = '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">';
2763 $xsl = '/lib/xhtml.xsl';
2765 if (!headers_sent() && !empty($CFG->xmlstrictheaders
)) { // With xml strict headers, the browser will barf
2766 $ctype = 'Content-Type: ';
2767 $prolog= "<?xml version='1.0' encoding='utf-8'?>\n";
2769 if (isset($_SERVER['HTTP_ACCEPT'])
2770 && false !== strpos($_SERVER['HTTP_ACCEPT'], 'application/xhtml+xml')) {
2771 //|| false !== strpos($_SERVER['HTTP_USER_AGENT'], 'Safari') //Safari "Entity 'copy' not defined".
2773 $ctype .= 'application/xhtml+xml';
2774 $prolog .= "<!--\n DEBUG: $ctype \n-->\n";
2776 } else if (file_exists($CFG->dirroot
.$xsl)
2777 && preg_match('/MSIE.*Windows NT/', $_SERVER['HTTP_USER_AGENT'])) {
2778 // XSL hack for IE 5+ on Windows.
2779 //$www_xsl = preg_replace('/(http:\/\/.+?\/).*/', '', $CFG->wwwroot) .$xsl;
2780 $www_xsl = $CFG->wwwroot
.$xsl;
2781 $ctype .= 'application/xml';
2782 $prolog .= "<?xml-stylesheet type='text/xsl' href='$www_xsl'?>\n";
2783 $prolog .= "<!--\n DEBUG: $ctype \n-->\n";
2786 //ELSE: Mac/IE, old/non-XML browsers.
2787 $ctype .= 'text/html';
2790 @header
($ctype.'; charset=utf-8');
2791 $output = $prolog . $output;
2793 // Test parser error-handling.
2794 if (isset($_GET['error'])) {
2795 $output .= "__ TEST: XML well-formed error < __\n";
2799 $output = preg_replace('/(<!DOCTYPE.+?>)/s', $strict, $output); // Always change the DOCTYPE to Strict 1.0
2807 * This version of print_header is simpler because the course name does not have to be
2808 * provided explicitly in the strings. It can be used on the site page as in courses
2809 * Eventually all print_header could be replaced by print_header_simple
2811 * @param string $title Appears at the top of the window
2812 * @param string $heading Appears at the top of the page
2813 * @param string $navigation Premade navigation string (for use as breadcrumbs links)
2814 * @param string $focus Indicates form element to get cursor focus on load eg inputform.password
2815 * @param string $meta Meta tags to be added to the header
2816 * @param boolean $cache Should this page be cacheable?
2817 * @param string $button HTML code for a button (usually for module editing)
2818 * @param string $menu HTML code for a popup menu
2819 * @param boolean $usexml use XML for this page
2820 * @param string $bodytags This text will be included verbatim in the <body> tag (useful for onload() etc)
2821 * @param bool $return If true, return the visible elements of the header instead of echoing them.
2823 function print_header_simple($title='', $heading='', $navigation='', $focus='', $meta='',
2824 $cache=true, $button=' ', $menu='', $usexml=false, $bodytags='', $return=false) {
2826 global $COURSE, $CFG;
2828 // if we have no navigation specified, build it
2829 if( empty($navigation) ){
2830 $navigation = build_navigation('');
2833 // If old style nav prepend course short name otherwise leave $navigation object alone
2834 if (!is_newnav($navigation)) {
2835 if ($COURSE->id
!= SITEID
) {
2836 $shortname = '<a href="'.$CFG->wwwroot
.'/course/view.php?id='. $COURSE->id
.'">'. $COURSE->shortname
.'</a> ->';
2837 $navigation = $shortname.' '.$navigation;
2841 $output = print_header($COURSE->shortname
.': '. $title, $COURSE->fullname
.' '. $heading, $navigation, $focus, $meta,
2842 $cache, $button, $menu, $usexml, $bodytags, true);
2853 * Can provide a course object to make the footer contain a link to
2854 * to the course home page, otherwise the link will go to the site home
2856 * @param mixed $course course object, used for course link button or
2857 * 'none' means no user link, only docs link
2858 * 'empty' means nothing printed in footer
2859 * 'home' special frontpage footer
2860 * @param object $usercourse course used in user link
2861 * @param boolean $return output as string
2862 * @return mixed string or void
2864 function print_footer($course=NULL, $usercourse=NULL, $return=false) {
2865 global $USER, $CFG, $THEME, $COURSE;
2867 if (defined('ADMIN_EXT_HEADER_PRINTED') and !defined('ADMIN_EXT_FOOTER_PRINTED')) {
2868 admin_externalpage_print_footer();
2872 /// Course links or special footer
2874 if ($course === 'empty') {
2875 // special hack - sometimes we do not want even the docs link in footer
2877 if (!empty($THEME->open_header_containers
)) {
2878 for ($i=0; $i<$THEME->open_header_containers
; $i++
) {
2879 $output .= print_container_end_all(); // containers opened from header
2882 //1.8 theme compatibility
2883 $output .= "\n</div>"; // content div
2885 $output .= "\n</div>\n</body>\n</html>"; // close page div started in header
2893 } else if ($course === 'none') { // Don't print any links etc
2898 } else if ($course === 'home') { // special case for site home page - please do not remove
2899 $course = get_site();
2900 $homelink = '<div class="sitelink">'.
2901 '<a title="Moodle '. $CFG->release
.'" href="http://moodle.org/">'.
2902 '<img style="width:100px;height:30px" src="pix/moodlelogo.gif" alt="moodlelogo" /></a></div>';
2906 $homelink = '<div class="homelink"><a '.$CFG->frametarget
.' href="'.$CFG->wwwroot
.
2907 '/course/view.php?id='.$course->id
.'">'.format_string($course->shortname
).'</a></div>';
2912 $course = get_site(); // Set course as site course by default
2913 $homelink = '<div class="homelink"><a '.$CFG->frametarget
.' href="'.$CFG->wwwroot
.'/">'.get_string('home').'</a></div>';
2917 /// Set up some other navigation links (passed from print_header by ugly hack)
2918 $menu = isset($THEME->menu
) ?
str_replace('navmenu', 'navmenufooter', $THEME->menu
) : '';
2919 $title = isset($THEME->title
) ?
$THEME->title
: '';
2920 $button = isset($THEME->button
) ?
$THEME->button
: '';
2921 $heading = isset($THEME->heading
) ?
$THEME->heading
: '';
2922 $navigation = isset($THEME->navigation
) ?
$THEME->navigation
: '';
2923 $navmenulist = isset($THEME->navmenulist
) ?
$THEME->navmenulist
: '';
2926 /// Set the user link if necessary
2927 if (!$usercourse and is_object($course)) {
2928 $usercourse = $course;
2931 if (!isset($loggedinas)) {
2932 $loggedinas = user_login_string($usercourse, $USER);
2935 if ($loggedinas == $menu) {
2939 /// there should be exactly the same number of open containers as after the header
2940 if ($THEME->open_header_containers
!= open_containers()) {
2941 debugging('Unexpected number of open containers: '.open_containers().', expecting '.$THEME->open_header_containers
, DEBUG_DEVELOPER
);
2944 /// Provide some performance info if required
2945 $performanceinfo = '';
2946 if (defined('MDL_PERF') ||
(!empty($CFG->perfdebug
) and $CFG->perfdebug
> 7)) {
2947 $perf = get_performance_info();
2948 if (defined('MDL_PERFTOLOG') && !function_exists('register_shutdown_function')) {
2949 error_log("PERF: " . $perf['txt']);
2951 if (defined('MDL_PERFTOFOOT') ||
debugging() ||
$CFG->perfdebug
> 7) {
2952 $performanceinfo = $perf['html'];
2956 /// Include the actual footer file
2959 include($CFG->footer
);
2960 $output = ob_get_contents();
2971 * Returns the name of the current theme
2980 function current_theme() {
2981 global $CFG, $USER, $SESSION, $COURSE, $FULLME;
2983 if (empty($CFG->themeorder
)) {
2984 $themeorder = array('page', 'course', 'category', 'session', 'user', 'site');
2986 $themeorder = $CFG->themeorder
;
2989 if (isloggedin() and $USER->mnethostid
!= $CFG->mnet_localhost_id
) {
2990 require_once($CFG->dirroot
.'/mnet/peer.php');
2991 $mnet_peer = new mnet_peer();
2992 $mnet_peer->set_id($USER->mnethostid
);
2996 foreach ($themeorder as $themetype) {
2998 if (!empty($theme)) continue;
3000 switch ($themetype) {
3001 case 'page': // Page theme is for special page-only themes set by code
3002 if (!empty($CFG->pagetheme
)) {
3003 $theme = $CFG->pagetheme
;
3007 if (!empty($CFG->allowcoursethemes
) and !empty($COURSE->theme
)) {
3008 $theme = $COURSE->theme
;
3012 if (!empty($CFG->allowcategorythemes
)) {
3013 /// Nasty hack to check if we're in a category page
3014 if (stripos($FULLME, 'course/category.php') !== false) {
3017 $theme = current_category_theme($id);
3019 /// Otherwise check if we're in a course that has a category theme set
3020 } else if (!empty($COURSE->category
)) {
3021 $theme = current_category_theme($COURSE->category
);
3026 if (!empty($SESSION->theme
)) {
3027 $theme = $SESSION->theme
;
3031 if (!empty($CFG->allowuserthemes
) and !empty($USER->theme
)) {
3032 if (isloggedin() and $USER->mnethostid
!= $CFG->mnet_localhost_id
&& $mnet_peer->force_theme
== 1 && $mnet_peer->theme
!= '') {
3033 $theme = $mnet_peer->theme
;
3035 $theme = $USER->theme
;
3040 if (isloggedin() and $USER->mnethostid
!= $CFG->mnet_localhost_id
&& $mnet_peer->force_theme
== 1 && $mnet_peer->theme
!= '') {
3041 $theme = $mnet_peer->theme
;
3043 $theme = $CFG->theme
;
3051 /// A final check in case 'site' was not included in $CFG->themeorder
3052 if (empty($theme)) {
3053 $theme = $CFG->theme
;
3060 * Retrieves the category theme if one exists, otherwise checks the parent categories.
3061 * Recursive function.
3064 * @param integer $categoryid id of the category to check
3065 * @return string theme name
3067 function current_category_theme($categoryid=0) {
3070 /// Use the COURSE global if the categoryid not set
3071 if (empty($categoryid)) {
3072 if (!empty($COURSE->category
)) {
3073 $categoryid = $COURSE->category
;
3079 /// Retrieve the current category
3080 if ($category = get_record('course_categories', 'id', $categoryid)) {
3082 /// Return the category theme if it exists
3083 if (!empty($category->theme
)) {
3084 return $category->theme
;
3086 /// Otherwise try the parent category if one exists
3087 } else if (!empty($category->parent
)) {
3088 return current_category_theme($category->parent
);
3091 /// Return false if we can't find the category record
3098 * This function is called by stylesheets to set up the header
3099 * approriately as well as the current path
3102 * @param int $lastmodified ?
3103 * @param int $lifetime ?
3104 * @param string $thename ?
3106 function style_sheet_setup($lastmodified=0, $lifetime=300, $themename='', $forceconfig='', $lang='') {
3108 global $CFG, $THEME;
3110 // Fix for IE6 caching - we don't want the filemtime('styles.php'), instead use now.
3111 $lastmodified = time();
3113 header('Last-Modified: ' . gmdate("D, d M Y H:i:s", $lastmodified) . ' GMT');
3114 header('Expires: ' . gmdate("D, d M Y H:i:s", time() +
$lifetime) . ' GMT');
3115 header('Cache-Control: max-age='. $lifetime);
3117 header('Content-type: text/css'); // Correct MIME type
3119 $DEFAULT_SHEET_LIST = array('styles_layout', 'styles_fonts', 'styles_color');
3121 if (empty($themename)) {
3122 $themename = current_theme(); // So we have something. Normally not needed.
3124 $themename = clean_param($themename, PARAM_SAFEDIR
);
3127 if (!empty($forceconfig)) { // Page wants to use the config from this theme instead
3129 include($CFG->themedir
.'/'.$forceconfig.'/'.'config.php');
3132 /// If this is the standard theme calling us, then find out what sheets we need
3134 if ($themename == 'standard') {
3135 if (!isset($THEME->standardsheets
) or $THEME->standardsheets
=== true) { // Use all the sheets we have
3136 $THEME->sheets
= $DEFAULT_SHEET_LIST;
3137 } else if (empty($THEME->standardsheets
)) { // We can stop right now!
3138 echo "/***** Nothing required from this stylesheet by main theme *****/\n\n";
3140 } else { // Use the provided subset only
3141 $THEME->sheets
= $THEME->standardsheets
;
3144 /// If we are a parent theme, then check for parent definitions
3146 } else if (!empty($THEME->parent
) && $themename == $THEME->parent
) {
3147 if (!isset($THEME->parentsheets
) or $THEME->parentsheets
=== true) { // Use all the sheets we have
3148 $THEME->sheets
= $DEFAULT_SHEET_LIST;
3149 } else if (empty($THEME->parentsheets
)) { // We can stop right now!
3150 echo "/***** Nothing required from this stylesheet by main theme *****/\n\n";
3152 } else { // Use the provided subset only
3153 $THEME->sheets
= $THEME->parentsheets
;
3157 /// Work out the last modified date for this theme
3159 foreach ($THEME->sheets
as $sheet) {
3160 if (file_exists($CFG->themedir
.'/'.$themename.'/'.$sheet.'.css')) {
3161 $sheetmodified = filemtime($CFG->themedir
.'/'.$themename.'/'.$sheet.'.css');
3162 if ($sheetmodified > $lastmodified) {
3163 $lastmodified = $sheetmodified;
3169 /// Get a list of all the files we want to include
3172 foreach ($THEME->sheets
as $sheet) {
3173 $files[] = array($CFG->themedir
, $themename.'/'.$sheet.'.css');
3176 if ($themename == 'standard') { // Add any standard styles included in any modules
3177 if (!empty($THEME->modsheets
)) { // Search for styles.php within activity modules
3178 if ($mods = get_list_of_plugins('mod')) {
3179 foreach ($mods as $mod) {
3180 if (file_exists($CFG->dirroot
.'/mod/'.$mod.'/styles.php')) {
3181 $files[] = array($CFG->dirroot
, '/mod/'.$mod.'/styles.php');
3187 if (!empty($THEME->blocksheets
)) { // Search for styles.php within block modules
3188 if ($mods = get_list_of_plugins('blocks')) {
3189 foreach ($mods as $mod) {
3190 if (file_exists($CFG->dirroot
.'/blocks/'.$mod.'/styles.php')) {
3191 $files[] = array($CFG->dirroot
, '/blocks/'.$mod.'/styles.php');
3197 if (!isset($THEME->courseformatsheets
) ||
$THEME->courseformatsheets
) { // Search for styles.php in course formats
3198 if ($mods = get_list_of_plugins('format','',$CFG->dirroot
.'/course')) {
3199 foreach ($mods as $mod) {
3200 if (file_exists($CFG->dirroot
.'/course/format/'.$mod.'/styles.php')) {
3201 $files[] = array($CFG->dirroot
, '/course/format/'.$mod.'/styles.php');
3207 if (!isset($THEME->gradereportsheets
) ||
$THEME->gradereportsheets
) { // Search for styles.php in grade reports
3208 if ($reports = get_list_of_plugins('grade/report')) {
3209 foreach ($reports as $report) {
3210 if (file_exists($CFG->dirroot
.'/grade/report/'.$report.'/styles.php')) {
3211 $files[] = array($CFG->dirroot
, '/grade/report/'.$report.'/styles.php');
3217 if (!empty($THEME->langsheets
)) { // Search for styles.php within the current language
3218 if (file_exists($CFG->dirroot
.'/lang/'.$lang.'/styles.php')) {
3219 $files[] = array($CFG->dirroot
, '/lang/'.$lang.'/styles.php');
3225 /// Produce a list of all the files first
3226 echo '/**************************************'."\n";
3227 echo ' * THEME NAME: '.$themename."\n *\n";
3228 echo ' * Files included in this sheet:'."\n *\n";
3229 foreach ($files as $file) {
3230 echo ' * '.$file[1]."\n";
3232 echo ' **************************************/'."\n\n";
3235 /// check if csscobstants is set
3236 if (!empty($THEME->cssconstants
)) {
3237 require_once("$CFG->libdir/cssconstants.php");
3238 /// Actually collect all the files in order.
3240 foreach ($files as $file) {
3241 $css .= '/***** '.$file[1].' start *****/'."\n\n";
3242 $css .= file_get_contents($file[0].'/'.$file[1]);
3243 $ccs .= '/***** '.$file[1].' end *****/'."\n\n";
3245 /// replace css_constants with their values
3246 echo replace_cssconstants($css);
3248 /// Actually output all the files in order.
3249 if (empty($CFG->CSSEdit
) && empty($THEME->CSSEdit
)) {
3250 foreach ($files as $file) {
3251 echo '/***** '.$file[1].' start *****/'."\n\n";
3252 @include_once
($file[0].'/'.$file[1]);
3253 echo '/***** '.$file[1].' end *****/'."\n\n";
3256 foreach ($files as $file) {
3257 echo '/* @group '.$file[1].' */'."\n\n";
3258 if (strstr($file[1], '.css') !== FALSE) {
3259 echo '@import url("'.$CFG->themewww
.'/'.$file[1].'");'."\n\n";
3261 @include_once
($file[0].'/'.$file[1]);
3263 echo '/* @end */'."\n\n";
3269 return $CFG->themewww
.'/'.$themename; // Only to help old themes (1.4 and earlier)
3273 function theme_setup($theme = '', $params=NULL) {
3274 /// Sets up global variables related to themes
3276 global $CFG, $THEME, $SESSION, $USER, $HTTPSPAGEREQUIRED;
3278 /// Do not mess with THEME if header already printed - this would break all the extra stuff in global $THEME from print_header()!!
3279 if (defined('HEADER_PRINTED')) {
3283 if (empty($theme)) {
3284 $theme = current_theme();
3287 /// If the theme doesn't exist for some reason then revert to standardwhite
3288 if (!file_exists($CFG->themedir
.'/'. $theme .'/config.php')) {
3289 $CFG->theme
= $theme = 'standardwhite';
3292 /// Load up the theme config
3293 $THEME = NULL; // Just to be sure
3294 include($CFG->themedir
.'/'. $theme .'/config.php'); // Main config for current theme
3296 /// Put together the parameters
3301 if ($theme != $CFG->theme
) {
3302 $params[] = 'forceconfig='.$theme;
3305 /// Force language too if required
3306 if (!empty($THEME->langsheets
)) {
3307 $params[] = 'lang='.current_language();
3311 /// Convert params to string
3313 $paramstring = '?'.implode('&', $params);
3318 /// Set up image paths
3319 if(isset($CFG->smartpix
) && $CFG->smartpix
==1) {
3320 if($CFG->slasharguments
) { // Use this method if possible for better caching
3326 $CFG->pixpath
= $CFG->wwwroot
. '/pix/smartpix.php'.$extra.'/'.$theme;
3327 $CFG->modpixpath
= $CFG->wwwroot
.'/pix/smartpix.php'.$extra.'/'.$theme.'/mod';
3328 } else if (empty($THEME->custompix
)) { // Could be set in the above file
3329 $CFG->pixpath
= $CFG->wwwroot
.'/pix';
3330 $CFG->modpixpath
= $CFG->wwwroot
.'/mod';
3332 $CFG->pixpath
= $CFG->themewww
.'/'. $theme .'/pix';
3333 $CFG->modpixpath
= $CFG->themewww
.'/'. $theme .'/pix/mod';
3336 /// Header and footer paths
3337 $CFG->header
= $CFG->themedir
.'/'. $theme .'/header.html';
3338 $CFG->footer
= $CFG->themedir
.'/'. $theme .'/footer.html';
3340 /// Define stylesheet loading order
3341 $CFG->stylesheets
= array();
3342 if ($theme != 'standard') { /// The standard sheet is always loaded first
3343 $CFG->stylesheets
[] = $CFG->themewww
.'/standard/styles.php'.$paramstring;
3345 if (!empty($THEME->parent
)) { /// Parent stylesheets are loaded next
3346 $CFG->stylesheets
[] = $CFG->themewww
.'/'.$THEME->parent
.'/styles.php'.$paramstring;
3348 $CFG->stylesheets
[] = $CFG->themewww
.'/'.$theme.'/styles.php'.$paramstring;
3350 /// We have to change some URLs in styles if we are in a $HTTPSPAGEREQUIRED page
3351 if (!empty($HTTPSPAGEREQUIRED)) {
3352 $CFG->themewww
= str_replace('http:', 'https:', $CFG->themewww
);
3353 $CFG->pixpath
= str_replace('http:', 'https:', $CFG->pixpath
);
3354 $CFG->modpixpath
= str_replace('http:', 'https:', $CFG->modpixpath
);
3355 foreach ($CFG->stylesheets
as $key => $stylesheet) {
3356 $CFG->stylesheets
[$key] = str_replace('http:', 'https:', $stylesheet);
3360 // RTL support - only for RTL languages, add RTL CSS
3361 if (get_string('thisdirection') == 'rtl') {
3362 $CFG->stylesheets
[] = $CFG->themewww
.'/standard/rtl.css'.$paramstring;
3363 $CFG->stylesheets
[] = $CFG->themewww
.'/'.$theme.'/rtl.css'.$paramstring;
3369 * Returns text to be displayed to the user which reflects their login status
3373 * @param course $course {@link $COURSE} object containing course information
3374 * @param user $user {@link $USER} object containing user information
3377 function user_login_string($course=NULL, $user=NULL) {
3378 global $USER, $CFG, $SITE;
3380 if (empty($user) and !empty($USER->id
)) {
3384 if (empty($course)) {
3388 if (!empty($user->realuser
)) {
3389 if ($realuser = get_record('user', 'id', $user->realuser
)) {
3390 $fullname = fullname($realuser, true);
3391 $realuserinfo = " [<a $CFG->frametarget
3392 href=\"$CFG->wwwroot/course/loginas.php?id=$course->id&return=1&sesskey=".sesskey()."\">$fullname</a>] ";
3398 if (empty($CFG->loginhttps
)) {
3399 $wwwroot = $CFG->wwwroot
;
3401 $wwwroot = str_replace('http:','https:',$CFG->wwwroot
);
3404 if (empty($course->id
)) {
3405 // $course->id is not defined during installation
3407 } else if (!empty($user->id
)) {
3408 $context = get_context_instance(CONTEXT_COURSE
, $course->id
);
3410 $fullname = fullname($user, true);
3411 $username = "<a $CFG->frametarget href=\"$CFG->wwwroot/user/view.php?id=$user->id&course=$course->id\">$fullname</a>";
3412 if (is_mnet_remote_user($user) and $idprovider = get_record('mnet_host', 'id', $user->mnethostid
)) {
3413 $username .= " from <a $CFG->frametarget href=\"{$idprovider->wwwroot}\">{$idprovider->name}</a>";
3415 if (isset($user->username
) && $user->username
== 'guest') {
3416 $loggedinas = $realuserinfo.get_string('loggedinasguest').
3417 " (<a $CFG->frametarget href=\"$wwwroot/login/index.php\">".get_string('login').'</a>)';
3418 } else if (!empty($user->access
['rsw'][$context->path
])) {
3420 if ($role = get_record('role', 'id', $user->access
['rsw'][$context->path
])) {
3421 $rolename = ': '.format_string($role->name
);
3423 $loggedinas = get_string('loggedinas', 'moodle', $username).$rolename.
3424 " (<a $CFG->frametarget
3425 href=\"$CFG->wwwroot/course/view.php?id=$course->id&switchrole=0&sesskey=".sesskey()."\">".get_string('switchrolereturn').'</a>)';
3427 $loggedinas = $realuserinfo.get_string('loggedinas', 'moodle', $username).' '.
3428 " (<a $CFG->frametarget href=\"$CFG->wwwroot/login/logout.php?sesskey=".sesskey()."\">".get_string('logout').'</a>)';
3431 $loggedinas = get_string('loggedinnot', 'moodle').
3432 " (<a $CFG->frametarget href=\"$wwwroot/login/index.php\">".get_string('login').'</a>)';
3434 return '<div class="logininfo">'.$loggedinas.'</div>';
3438 * Tests whether $THEME->rarrow, $THEME->larrow have been set (theme/-/config.php).
3439 * If not it applies sensible defaults.
3441 * Accessibility: right and left arrow Unicode characters for breadcrumb, calendar,
3442 * search forum block, etc. Important: these are 'silent' in a screen-reader
3443 * (unlike > »), and must be accompanied by text.
3446 function check_theme_arrows() {
3449 if (!isset($THEME->rarrow
) and !isset($THEME->larrow
)) {
3450 // Default, looks good in Win XP/IE 6, Win/Firefox 1.5, Win/Netscape 8...
3451 // Also OK in Win 9x/2K/IE 5.x
3452 $THEME->rarrow
= '►';
3453 $THEME->larrow
= '◄';
3454 $uagent = $_SERVER['HTTP_USER_AGENT'];
3455 if (false !== strpos($uagent, 'Opera')
3456 ||
false !== strpos($uagent, 'Mac')) {
3457 // Looks good in Win XP/Mac/Opera 8/9, Mac/Firefox 2, Camino, Safari.
3458 // Not broken in Mac/IE 5, Mac/Netscape 7 (?).
3459 $THEME->rarrow
= '▶';
3460 $THEME->larrow
= '◀';
3462 elseif (false !== strpos($uagent, 'Konqueror')) {
3463 $THEME->rarrow
= '→';
3464 $THEME->larrow
= '←';
3466 elseif (isset($_SERVER['HTTP_ACCEPT_CHARSET'])
3467 && false === stripos($_SERVER['HTTP_ACCEPT_CHARSET'], 'utf-8')) {
3468 // (Win/IE 5 doesn't set ACCEPT_CHARSET, but handles Unicode.)
3469 // To be safe, non-Unicode browsers!
3470 $THEME->rarrow
= '>';
3471 $THEME->larrow
= '<';
3474 /// RTL support - in RTL languages, swap r and l arrows
3475 if (right_to_left()) {
3476 $t = $THEME->rarrow
;
3477 $THEME->rarrow
= $THEME->larrow
;
3478 $THEME->larrow
= $t;
3485 * Return the right arrow with text ('next'), and optionally embedded in a link.
3486 * See function above, check_theme_arrows.
3487 * @param string $text HTML/plain text label (set to blank only for breadcrumb separator cases).
3488 * @param string $url An optional link to use in a surrounding HTML anchor.
3489 * @param bool $accesshide True if text should be hidden (for screen readers only).
3490 * @param string $addclass Additional class names for the link, or the arrow character.
3491 * @return string HTML string.
3493 function link_arrow_right($text, $url='', $accesshide=false, $addclass='') {
3495 check_theme_arrows();
3496 $arrowclass = 'arrow ';
3498 $arrowclass .= $addclass;
3500 $arrow = '<span class="'.$arrowclass.'">'.$THEME->rarrow
.'</span>';
3503 $htmltext = $text.' ';
3505 $htmltext = get_accesshide($htmltext);
3511 $class =" class=\"$addclass\"";
3513 return '<a'.$class.' href="'.$url.'" title="'.preg_replace('/<.*?>/','',$text).'">'.$htmltext.$arrow.'</a>';
3515 return $htmltext.$arrow;
3519 * Return the left arrow with text ('previous'), and optionally embedded in a link.
3520 * See function above, check_theme_arrows.
3521 * @param string $text HTML/plain text label (set to blank only for breadcrumb separator cases).
3522 * @param string $url An optional link to use in a surrounding HTML anchor.
3523 * @param bool $accesshide True if text should be hidden (for screen readers only).
3524 * @param string $addclass Additional class names for the link, or the arrow character.
3525 * @return string HTML string.
3527 function link_arrow_left($text, $url='', $accesshide=false, $addclass='') {
3529 check_theme_arrows();
3530 $arrowclass = 'arrow ';
3532 $arrowclass .= $addclass;
3534 $arrow = '<span class="'.$arrowclass.'">'.$THEME->larrow
.'</span>';
3537 $htmltext = ' '.$text;
3539 $htmltext = get_accesshide($htmltext);
3545 $class =" class=\"$addclass\"";
3547 return '<a'.$class.' href="'.$url.'" title="'.preg_replace('/<.*?>/','',$text).'">'.$arrow.$htmltext.'</a>';
3549 return $arrow.$htmltext;
3553 * Return a HTML element with the class "accesshide", for accessibility.
3554 * Please use cautiously - where possible, text should be visible!
3555 * @param string $text Plain text.
3556 * @param string $elem Lowercase element name, default "span".
3557 * @param string $class Additional classes for the element.
3558 * @param string $attrs Additional attributes string in the form, "name='value' name2='value2'"
3559 * @return string HTML string.
3561 function get_accesshide($text, $elem='span', $class='', $attrs='') {
3562 return "<$elem class=\"accesshide $class\" $attrs>$text</$elem>";
3566 * Return the breadcrumb trail navigation separator.
3567 * @return string HTML string.
3569 function get_separator() {
3570 //Accessibility: the 'hidden' slash is preferred for screen readers.
3571 return ' '.link_arrow_right($text='/', $url='', $accesshide=true, 'sep').' ';
3575 * Prints breadcrumb trail of links, called in theme/-/header.html
3578 * @param mixed $navigation The breadcrumb navigation string to be printed
3579 * @param string $separator The breadcrumb trail separator. The default 0 leads to the use
3580 * of $THEME->rarrow, themes could use '→', '/', or '' for a style-sheet solution.
3581 * @param boolean $return False to echo the breadcrumb string (default), true to return it.
3583 function print_navigation ($navigation, $separator=0, $return=false) {
3584 global $CFG, $THEME;
3587 if (0 === $separator) {
3588 $separator = get_separator();
3591 $separator = '<span class="sep">'. $separator .'</span>';
3596 if (is_newnav($navigation)) {
3598 return($navigation['navlinks']);
3600 echo $navigation['navlinks'];
3604 debugging('Navigation needs to be updated to use build_navigation()', DEBUG_DEVELOPER
);
3607 if (!is_array($navigation)) {
3608 $ar = explode('->', $navigation);
3609 $navigation = array();
3611 foreach ($ar as $a) {
3612 if (strpos($a, '</a>') === false) {
3613 $navigation[] = array('title' => $a, 'url' => '');
3615 if (preg_match('/<a.*href="([^"]*)">(.*)<\/a>/', $a, $matches)) {
3616 $navigation[] = array('title' => $matches[2], 'url' => $matches[1]);
3622 if (! $site = get_site()) {
3623 $site = new object();
3624 $site->shortname
= get_string('home');
3627 //Accessibility: breadcrumb links now in a list, » replaced with a 'silent' character.
3628 $output .= get_accesshide(get_string('youarehere','access'), 'h2')."<ul>\n";
3630 $output .= '<li class="first">'."\n".'<a '.$CFG->frametarget
.' onclick="this.target=\''.$CFG->framename
.'\'" href="'
3631 .$CFG->wwwroot
.((!has_capability('moodle/site:config', get_context_instance(CONTEXT_SYSTEM
))
3632 && !empty($USER->id
) && !empty($CFG->mymoodleredirect
) && !isguest())
3633 ?
'/my' : '') .'/">'. format_string($site->shortname
) ."</a>\n</li>\n";
3636 foreach ($navigation as $navitem) {
3637 $title = trim(strip_tags(format_string($navitem['title'], false)));
3638 $url = $navitem['url'];
3641 $output .= '<li class="first">'."$separator $title</li>\n";
3643 $output .= '<li class="first">'."$separator\n<a ".$CFG->frametarget
.' onclick="this.target=\''.$CFG->framename
.'\'" href="'
3644 .$url.'">'."$title</a>\n</li>\n";
3648 $output .= "</ul>\n";
3659 * This function will build the navigation string to be used by print_header
3662 * It automatically generates the site and course level (if appropriate) links.
3664 * If you pass in a $cm object, the method will also generate the activity (e.g. 'Forums')
3665 * and activityinstances (e.g. 'General Developer Forum') navigation levels.
3667 * If you want to add any further navigation links after the ones this function generates,
3668 * the pass an array of extra link arrays like this:
3670 * array('name' => $linktext1, 'link' => $url1, 'type' => $linktype1),
3671 * array('name' => $linktext2, 'link' => $url2, 'type' => $linktype2)
3673 * The normal case is to just add one further link, for example 'Editing forum' after
3674 * 'General Developer Forum', with no link.
3675 * To do that, you need to pass
3676 * array(array('name' => $linktext, 'link' => '', 'type' => 'title'))
3677 * However, becuase this is a very common case, you can use a shortcut syntax, and just
3678 * pass the string 'Editing forum', instead of an array as $extranavlinks.
3680 * At the moment, the link types only have limited significance. Type 'activity' is
3681 * recognised in order to implement the $CFG->hideactivitytypenavlink feature. Types
3682 * that are known to appear are 'home', 'course', 'activity', 'activityinstance' and 'title'.
3683 * This really needs to be documented better. In the mean time, try to be consistent, it will
3684 * enable people to customise the navigation more in future.
3686 * When passing a $cm object, the fields used are $cm->modname, $cm->name and $cm->course.
3687 * If you get the $cm object using the function get_coursemodule_from_instance or
3688 * get_coursemodule_from_id (as recommended) then this will be done for you automatically.
3689 * If you don't have $cm->modname or $cm->name, this fuction will attempt to find them using
3690 * the $cm->module and $cm->instance fields, but this takes extra database queries, so a
3691 * warning is printed in developer debug mode.
3696 * @param mixed $extranavlinks - Normally an array of arrays, keys: name, link, type. If you
3697 * only want one extra item with no link, you can pass a string instead. If you don't want
3698 * any extra links, pass an empty string.
3699 * @param mixed $cm - optionally the $cm object, if you want this function to generate the
3700 * activity and activityinstance levels of navigation too.
3702 * @return $navigation as an object so it can be differentiated from old style
3703 * navigation strings.
3705 function build_navigation($extranavlinks, $cm = null) {
3706 global $CFG, $COURSE;
3708 if (is_string($extranavlinks)) {
3709 if ($extranavlinks == '') {
3710 $extranavlinks = array();
3712 $extranavlinks = array(array('name' => $extranavlinks, 'link' => '', 'type' => 'title'));
3716 $navlinks = array();
3719 if ($site = get_site()) {
3720 $navlinks[] = array(
3721 'name' => format_string($site->shortname
),
3722 'link' => "$CFG->wwwroot/",
3726 // Course name, if appropriate.
3727 if (isset($COURSE) && $COURSE->id
!= SITEID
) {
3728 $navlinks[] = array(
3729 'name' => format_string($COURSE->shortname
),
3730 'link' => "$CFG->wwwroot/course/view.php?id=$COURSE->id",
3731 'type' => 'course');
3734 // Activity type and instance, if appropriate.
3735 if (is_object($cm)) {
3736 if (!isset($cm->modname
)) {
3737 debugging('The field $cm->modname should be set if you call build_navigation with '.
3738 'a $cm parameter. If you get $cm using get_coursemodule_from_instance or '.
3739 'get_coursemodule_from_id, this will be done automatically.', DEBUG_DEVELOPER
);
3740 if (!$cm->modname
= get_field('modules', 'name', 'id', $cm->module
)) {
3741 error('Cannot get the module type in build navigation.');
3744 if (!isset($cm->name
)) {
3745 debugging('The field $cm->name should be set if you call build_navigation with '.
3746 'a $cm parameter. If you get $cm using get_coursemodule_from_instance or '.
3747 'get_coursemodule_from_id, this will be done automatically.', DEBUG_DEVELOPER
);
3748 if (!$cm->name
= get_field($cm->modname
, 'name', 'id', $cm->instance
)) {
3749 error('Cannot get the module name in build navigation.');
3752 $navlinks[] = array(
3753 'name' => get_string('modulenameplural', $cm->modname
),
3754 'link' => $CFG->wwwroot
. '/mod/' . $cm->modname
. '/index.php?id=' . $cm->course
,
3755 'type' => 'activity');
3756 $navlinks[] = array(
3757 'name' => format_string($cm->name
),
3758 'link' => $CFG->wwwroot
. '/mod/' . $cm->modname
. '/view.php?id=' . $cm->id
,
3759 'type' => 'activityinstance');
3762 //Merge in extra navigation links
3763 $navlinks = array_merge($navlinks, $extranavlinks);
3765 // Work out whether we should be showing the activity (e.g. Forums) link.
3766 // Note: build_navigation() is called from many places --
3767 // install & upgrade for example -- where we cannot count on the
3768 // roles infrastructure to be defined. Hence the $CFG->rolesactive check.
3769 if (!isset($CFG->hideactivitytypenavlink
)) {
3770 $CFG->hideactivitytypenavlink
= 0;
3772 if ($CFG->hideactivitytypenavlink
== 2) {
3773 $hideactivitylink = true;
3774 } else if ($CFG->hideactivitytypenavlink
== 1 && $CFG->rolesactive
&&
3775 !empty($COURSE->id
) && $COURSE->id
!= SITEID
) {
3776 if (!isset($COURSE->context
)) {
3777 $COURSE->context
= get_context_instance(CONTEXT_COURSE
, $COURSE->id
);
3779 $hideactivitylink = !has_capability('moodle/course:manageactivities', $COURSE->context
);
3781 $hideactivitylink = false;
3784 //Construct an unordered list from $navlinks
3785 //Accessibility: heading hidden from visual browsers by default.
3786 $navigation = get_accesshide(get_string('youarehere','access'), 'h2')." <ul>\n";
3787 $lastindex = count($navlinks) - 1;
3788 $i = -1; // Used to count the times, so we know when we get to the last item.
3790 foreach ($navlinks as $navlink) {
3792 $last = ($i == $lastindex);
3793 if (!is_array($navlink)) {
3796 if ($navlink['type'] == 'activity' && !$last && $hideactivitylink) {
3799 $navigation .= '<li class="first">';
3801 $navigation .= get_separator();
3803 if ((!empty($navlink['link'])) && !$last) {
3804 $navigation .= "<a onclick=\"this.target='$CFG->framename'\" href=\"{$navlink['link']}\">";
3806 $navigation .= "{$navlink['name']}";
3807 if ((!empty($navlink['link'])) && !$last) {
3808 $navigation .= "</a>";
3811 $navigation .= "</li>";
3814 $navigation .= "</ul>";
3816 return(array('newnav' => true, 'navlinks' => $navigation));
3821 * Prints a string in a specified size (retained for backward compatibility)
3823 * @param string $text The text to be displayed
3824 * @param int $size The size to set the font for text display.
3826 function print_headline($text, $size=2, $return=false) {
3827 $output = print_heading($text, '', $size, true);
3836 * Prints text in a format for use in headings.
3838 * @param string $text The text to be displayed
3839 * @param string $align The alignment of the printed paragraph of text
3840 * @param int $size The size to set the font for text display.
3842 function print_heading($text, $align='', $size=2, $class='main', $return=false) {
3844 $align = ' style="text-align:'.$align.';"';
3847 $class = ' class="'.$class.'"';
3849 $output = "<h$size $align $class>".stripslashes_safe($text)."</h$size>";
3859 * Centered heading with attached help button (same title text)
3860 * and optional icon attached
3862 * @param string $text The text to be displayed
3863 * @param string $helppage The help page to link to
3864 * @param string $module The module whose help should be linked to
3865 * @param string $icon Image to display if needed
3867 function print_heading_with_help($text, $helppage, $module='moodle', $icon='', $return=false) {
3869 $output .= '<h2 class="main help">'.$icon.stripslashes_safe($text);
3870 $output .= helpbutton($helppage, $text, $module, true, false, '', true);
3881 function print_heading_block($heading, $class='', $return=false) {
3882 //Accessibility: 'headingblock' is now H1, see theme/standard/styles_*.css: ??
3883 $output = '<h2 class="headingblock header '.$class.'">'.stripslashes($heading).'</h2>';
3894 * Print a link to continue on to another page.
3897 * @param string $link The url to create a link to.
3899 function print_continue($link, $return=false) {
3903 // in case we are logging upgrade in admin/index.php stop it
3904 if (function_exists('upgrade_log_finish')) {
3905 upgrade_log_finish();
3911 if (!empty($_SERVER['HTTP_REFERER'])) {
3912 $link = $_SERVER['HTTP_REFERER'];
3913 $link = str_replace('&', '&', $link); // make it valid XHTML
3915 $link = $CFG->wwwroot
.'/';
3920 $linkparts = parse_url(str_replace('&', '&', $link));
3921 if (isset($linkparts['query'])) {
3922 parse_str($linkparts['query'], $options);
3925 $output .= '<div class="continuebutton">';
3927 $output .= print_single_button($link, $options, get_string('continue'), 'get', $CFG->framename
, true);
3928 $output .= '</div>'."\n";
3939 * Print a message in a standard themed box.
3940 * Replaces print_simple_box (see deprecatedlib.php)
3942 * @param string $message, the content of the box
3943 * @param string $classes, space-separated class names.
3944 * @param string $idbase
3945 * @param boolean $return, return as string or just print it
3946 * @return mixed string or void
3948 function print_box($message, $classes='generalbox', $ids='', $return=false) {
3950 $output = print_box_start($classes, $ids, true);
3951 $output .= stripslashes_safe($message);
3952 $output .= print_box_end(true);
3962 * Starts a box using divs
3963 * Replaces print_simple_box_start (see deprecatedlib.php)
3965 * @param string $classes, space-separated class names.
3966 * @param string $idbase
3967 * @param boolean $return, return as string or just print it
3968 * @return mixed string or void
3970 function print_box_start($classes='generalbox', $ids='', $return=false) {
3973 if (strpos($classes, 'clearfix') !== false) {
3975 $classes = trim(str_replace('clearfix', '', $classes));
3980 if (!empty($THEME->customcorners
)) {
3981 $classes .= ' ccbox box';
3986 return print_container_start($clearfix, $classes, $ids, $return);
3990 * Simple function to end a box (see above)
3991 * Replaces print_simple_box_end (see deprecatedlib.php)
3993 * @param boolean $return, return as string or just print it
3995 function print_box_end($return=false) {
3996 return print_container_end($return);
4000 * Print a message in a standard themed container.
4002 * @param string $message, the content of the container
4003 * @param boolean $clearfix clear both sides
4004 * @param string $classes, space-separated class names.
4005 * @param string $idbase
4006 * @param boolean $return, return as string or just print it
4007 * @return string or void
4009 function print_container($message, $clearfix=false, $classes='', $idbase='', $return=false) {
4011 $output = print_container_start($clearfix, $classes, $idbase, true);
4012 $output .= stripslashes_safe($message);
4013 $output .= print_container_end(true);
4023 * Starts a container using divs
4025 * @param boolean $clearfix clear both sides
4026 * @param string $classes, space-separated class names.
4027 * @param string $idbase
4028 * @param boolean $return, return as string or just print it
4029 * @return mixed string or void
4031 function print_container_start($clearfix=false, $classes='', $idbase='', $return=false) {
4034 if (!isset($THEME->open_containers
)) {
4035 $THEME->open_containers
= array();
4037 $THEME->open_containers
[] = $idbase;
4040 if (!empty($THEME->customcorners
)) {
4041 $output = _print_custom_corners_start($clearfix, $classes, $idbase);
4044 $id = ' id="'.$idbase.'"';
4049 $clearfix = ' clearfix';
4053 if ($classes or $clearfix) {
4054 $class = ' class="'.$classes.$clearfix.'"';
4058 $output = '<div'.$id.$class.'>';
4069 * Simple function to end a container (see above)
4070 * @param boolean $return, return as string or just print it
4071 * @return mixed string or void
4073 function print_container_end($return=false) {
4076 if (empty($THEME->open_containers
)) {
4077 debugging('Incorrect request to end container - no more open containers.', DEBUG_DEVELOPER
);
4080 $idbase = array_pop($THEME->open_containers
);
4083 if (!empty($THEME->customcorners
)) {
4084 $output = _print_custom_corners_end($idbase);
4097 * Returns number of currently open containers
4098 * @return int number of open containers
4100 function open_containers() {
4103 if (!isset($THEME->open_containers
)) {
4104 $THEME->open_containers
= array();
4107 return count($THEME->open_containers
);
4111 * Force closing of open containers
4112 * @param boolean $return, return as string or just print it
4113 * @param int $keep number of containers to be kept open - usually theme or page containers
4114 * @return mixed string or void
4116 function print_container_end_all($return=false, $keep=0) {
4118 while (open_containers() > $keep) {
4119 $output .= print_container_end($return);
4130 * Internal function - do not use directly!
4131 * Starting part of the surrounding divs for custom corners
4133 * @param boolean $clearfix, add CLASS "clearfix" to the inner div against collapsing
4134 * @param string $classes
4135 * @param mixed $idbase, optionally, define one idbase to be added to all the elements in the corners
4138 function _print_custom_corners_start($clearfix=false, $classes='', $idbase='') {
4139 /// Analise if we want ids for the custom corner elements
4147 $id = 'id="'.$idbase.'" ';
4148 $idbt = 'id="'.$idbase.'-bt" ';
4149 $idi1 = 'id="'.$idbase.'-i1" ';
4150 $idi2 = 'id="'.$idbase.'-i2" ';
4151 $idi3 = 'id="'.$idbase.'-i3" ';
4154 /// Calculate current level
4155 $level = open_containers();
4158 $output = '<div '.$id.'class="wrap wraplevel'.$level.' '.$classes.'">'."\n";
4159 $output .= '<div '.$idbt.'class="bt"><div> </div></div>';
4161 $output .= '<div '.$idi1.'class="i1"><div '.$idi2.'class="i2">';
4162 $output .= (!empty($clearfix)) ?
'<div '.$idi3.'class="i3 clearfix">' : '<div '.$idi3.'class="i3">';
4169 * Internal function - do not use directly!
4170 * Ending part of the surrounding divs for custom corners
4171 * @param string $idbase
4174 function _print_custom_corners_end($idbase) {
4175 /// Analise if we want ids for the custom corner elements
4179 $idbb = 'id="' . $idbase . '-bb" ';
4183 $output = '</div></div></div>';
4185 $output .= '<div '.$idbb.'class="bb"><div> </div></div>'."\n";
4186 $output .= '</div>';
4193 * Print a self contained form with a single submit button.
4195 * @param string $link used as the action attribute on the form, so the URL that will be hit if the button is clicked.
4196 * @param array $options these become hidden form fields, so these options get passed to the script at $link.
4197 * @param string $label the caption that appears on the button.
4198 * @param string $method HTTP method used on the request of the button is clicked. 'get' or 'post'.
4199 * @param string $target no longer used.
4200 * @param boolean $return if false, output the form directly, otherwise return the HTML as a string.
4201 * @param string $tooltip a tooltip to add to the button as a title attribute.
4202 * @param boolean $disabled if true, the button will be disabled.
4203 * @param string $jsconfirmmessage if not empty then display a confirm dialogue with this string as the question.
4204 * @return string / nothing depending on the $return paramter.
4206 function print_single_button($link, $options, $label='OK', $method='get', $target='_self', $return=false, $tooltip='', $disabled = false, $jsconfirmmessage='') {
4208 $link = str_replace('"', '"', $link); //basic XSS protection
4209 $output .= '<div class="singlebutton">';
4210 // taking target out, will need to add later target="'.$target.'"
4211 $output .= '<form action="'. $link .'" method="'. $method .'">';
4214 foreach ($options as $name => $value) {
4215 $output .= '<input type="hidden" name="'. $name .'" value="'. s($value) .'" />';
4219 $tooltip = 'title="' . s($tooltip) . '"';
4224 $disabled = 'disabled="disabled"';
4228 if ($jsconfirmmessage){
4229 $jsconfirmmessage = addslashes_js($jsconfirmmessage);
4230 $jsconfirmmessage = 'onclick="return confirm(\''. $jsconfirmmessage .'\');" ';
4232 $output .= '<input type="submit" value="'. s($label) ."\" $tooltip $disabled $jsconfirmmessage/></div></form></div>";
4243 * Print a spacer image with the option of including a line break.
4245 * @param int $height ?
4246 * @param int $width ?
4247 * @param boolean $br ?
4248 * @todo Finish documenting this function
4250 function print_spacer($height=1, $width=1, $br=true, $return=false) {
4254 $output .= '<img class="spacer" height="'. $height .'" width="'. $width .'" src="'. $CFG->wwwroot
.'/pix/spacer.gif" alt="" />';
4256 $output .= '<br />'."\n";
4267 * Given the path to a picture file in a course, or a URL,
4268 * this function includes the picture in the page.
4270 * @param string $path ?
4271 * @param int $courseid ?
4272 * @param int $height ?
4273 * @param int $width ?
4274 * @param string $link ?
4275 * @todo Finish documenting this function
4277 function print_file_picture($path, $courseid=0, $height='', $width='', $link='', $return=false) {
4282 $height = 'height="'. $height .'"';
4285 $width = 'width="'. $width .'"';
4288 $output .= '<a href="'. $link .'">';
4290 if (substr(strtolower($path), 0, 7) == 'http://') {
4291 $output .= '<img style="height:'.$height.'px;width:'.$width.'px;" src="'. $path .'" />';
4293 } else if ($courseid) {
4294 $output .= '<img style="height:'.$height.'px;width:'.$width.'px;" src="';
4295 if ($CFG->slasharguments
) { // Use this method if possible for better caching
4296 $output .= $CFG->wwwroot
.'/file.php/'. $courseid .'/'. $path;
4298 $output .= $CFG->wwwroot
.'/file.php?file=/'. $courseid .'/'. $path;
4302 $output .= 'Error: must pass URL or course';
4316 * Print the specified user's avatar.
4318 * If you pass a $user object that has id, picture, imagealt, firstname, lastname
4319 * you save a DB query.
4321 * @param int $user takes a userid, or a userobj
4322 * @param int $courseid ?
4323 * @param boolean $picture Print the user picture?
4324 * @param int $size Size in pixels. Special values are (true/1 = 100px) and (false/0 = 35px) for backward compatability
4325 * @param boolean $return If false print picture to current page, otherwise return the output as string
4326 * @param boolean $link Enclose printed image in a link to view specified course?
4327 * @param string $target link target attribute
4328 * @param boolean $alttext use username or userspecified text in image alt attribute
4330 * @todo Finish documenting this function
4332 function print_user_picture($user, $courseid, $picture=NULL, $size=0, $return=false, $link=true, $target='', $alttext=true) {
4333 global $CFG, $HTTPSPAGEREQUIRED;
4336 // only touch the DB if we are missing data...
4337 if (is_object($user)) {
4338 // Note - both picture and imagealt _can_ be empty
4339 // what we are trying to see here is if they have been fetched
4340 // from the DB. We should use isset() _except_ that some installs
4341 // have those fields as nullable, and isset() will return false
4342 // on null. The only safe thing is to ask array_key_exists()
4343 // which works on objects. property_exists() isn't quite
4344 // what we want here...
4345 if (! (array_key_exists('picture', $user)
4346 && ($alttext && array_key_exists('imagealt', $user)
4347 ||
(isset($user->firstname
) && isset($user->lastname
)))) ) {
4353 // we need firstname, lastname, imagealt, can't escape...
4356 $userobj = new StdClass
; // fake it to save DB traffic
4357 $userobj->id
= $user;
4358 $userobj->picture
= $picture;
4359 $user = clone($userobj);
4364 $user = get_record('user','id',$user, '', '', '', '', 'id,firstname,lastname,imagealt');
4368 $url = '/user/view.php?id='. $user->id
.'&course='. $courseid ;
4370 $target='onclick="return openpopup(\''.$url.'\');"';
4372 $output = '<a '.$target.' href="'. $CFG->wwwroot
. $url .'">';
4379 } else if ($size === true or $size == 1) {
4382 } else if ($size >= 50) {
4387 $class = "userpicture";
4388 if (!empty($HTTPSPAGEREQUIRED)) {
4389 $wwwroot = $CFG->httpswwwroot
;
4391 $wwwroot = $CFG->wwwroot
;
4394 if (is_null($picture)) {
4395 $picture = $user->picture
;
4398 if ($picture) { // Print custom user picture
4399 if ($CFG->slasharguments
) { // Use this method if possible for better caching
4400 $src = $wwwroot .'/user/pix.php/'. $user->id
.'/'. $file .'.jpg';
4402 $src = $wwwroot .'/user/pix.php?file=/'. $user->id
.'/'. $file .'.jpg';
4404 } else { // Print default user pictures (use theme version if available)
4405 $class .= " defaultuserpic";
4406 $src = "$CFG->pixpath/u/$file.png";
4410 if (!empty($user->imagealt
)) {
4411 $imagealt = $user->imagealt
;
4413 $imagealt = get_string('pictureof','',fullname($user));
4417 $output .= '<img class="'.$class.'" src="'.$src.'" alt="'.s($imagealt).'" />';
4430 * Prints a summary of a user in a nice little box.
4434 * @param user $user A {@link $USER} object representing a user
4435 * @param course $course A {@link $COURSE} object representing a course
4437 function print_user($user, $course, $messageselect=false, $return=false) {
4447 $context = get_context_instance(CONTEXT_COURSE
, $course->id
);
4448 if (isset($user->context
->id
)) {
4449 $usercontext = get_context_instance_by_id($user->context
->id
);
4452 if (empty($string)) { // Cache all the strings for the rest of the page
4454 $string->email
= get_string('email');
4455 $string->city
= get_string('city');
4456 $string->lastaccess
= get_string('lastaccess');
4457 $string->activity
= get_string('activity');
4458 $string->unenrol
= get_string('unenrol');
4459 $string->loginas
= get_string('loginas');
4460 $string->fullprofile
= get_string('fullprofile');
4461 $string->role
= get_string('role');
4462 $string->name
= get_string('name');
4463 $string->never
= get_string('never');
4465 $datestring->day
= get_string('day');
4466 $datestring->days
= get_string('days');
4467 $datestring->hour
= get_string('hour');
4468 $datestring->hours
= get_string('hours');
4469 $datestring->min
= get_string('min');
4470 $datestring->mins
= get_string('mins');
4471 $datestring->sec
= get_string('sec');
4472 $datestring->secs
= get_string('secs');
4473 $datestring->year
= get_string('year');
4474 $datestring->years
= get_string('years');
4476 $countries = get_list_of_countries();
4479 /// Get the hidden field list
4480 if (has_capability('moodle/course:viewhiddenuserfields', $context)) {
4481 $hiddenfields = array();
4483 $hiddenfields = array_flip(explode(',', $CFG->hiddenuserfields
));
4486 $output .= '<table class="userinfobox">';
4488 $output .= '<td class="left side">';
4489 $output .= print_user_picture($user, $course->id
, $user->picture
, true, true);
4491 $output .= '<td class="content">';
4492 $output .= '<div class="username">'.fullname($user, has_capability('moodle/site:viewfullnames', $context)).'</div>';
4493 $output .= '<div class="info">';
4494 if (!empty($user->role
) and ($user->role
<> $course->teacher
)) {
4495 $output .= $string->role
.': '. $user->role
.'<br />';
4497 if ($user->maildisplay
== 1 or ($user->maildisplay
== 2 and ($course->id
!= SITEID
) and !isguest()) or
4498 has_capability('moodle/course:viewhiddenuserfields', $context)) {
4499 $output .= $string->email
.': <a href="mailto:'. $user->email
.'">'. $user->email
.'</a><br />';
4501 if (($user->city
or $user->country
) and (!isset($hiddenfields['city']) or !isset($hiddenfields['country']))) {
4502 $output .= $string->city
.': ';
4503 if ($user->city
&& !isset($hiddenfields['city'])) {
4504 $output .= $user->city
;
4506 if (!empty($countries[$user->country
]) && !isset($hiddenfields['country'])) {
4507 if ($user->city
&& !isset($hiddenfields['city'])) {
4510 $output .= $countries[$user->country
];
4512 $output .= '<br />';
4515 if (!isset($hiddenfields['lastaccess'])) {
4516 if ($user->lastaccess
) {
4517 $output .= $string->lastaccess
.': '. userdate($user->lastaccess
);
4518 $output .= ' ('. format_time(time() - $user->lastaccess
, $datestring) .')';
4520 $output .= $string->lastaccess
.': '. $string->never
;
4523 $output .= '</div></td><td class="links">';
4525 if ($CFG->bloglevel
> 0) {
4526 $output .= '<a href="'.$CFG->wwwroot
.'/blog/index.php?userid='.$user->id
.'">'.get_string('blogs','blog').'</a><br />';
4529 if (has_capability('moodle/notes:manage', $context) ||
has_capability('moodle/notes:view', $context)) {
4530 $output .= '<a href="'.$CFG->wwwroot
.'/notes/index.php?course=' . $course->id
. '&user='.$user->id
.'">'.get_string('notes','notes').'</a><br />';
4533 if (has_capability('moodle/user:viewuseractivitiesreport', $context) ||
(isset($usercontext) && has_capability('moodle/user:viewuseractivitiesreport', $usercontext))) {
4534 $timemidnight = usergetmidnight(time());
4535 $output .= '<a href="'. $CFG->wwwroot
.'/course/user.php?id='. $course->id
.'&user='. $user->id
.'">'. $string->activity
.'</a><br />';
4537 if (has_capability('moodle/role:assign', $context, NULL)) { // Includes admins
4538 $output .= '<a href="'. $CFG->wwwroot
.'/course/unenrol.php?id='. $course->id
.'&user='. $user->id
.'">'. $string->unenrol
.'</a><br />';
4540 if ($USER->id
!= $user->id
&& empty($USER->realuser
) && has_capability('moodle/user:loginas', $context) &&
4541 ! has_capability('moodle/site:doanything', $context, $user->id
, false)) {
4542 $output .= '<a href="'. $CFG->wwwroot
.'/course/loginas.php?id='. $course->id
.'&user='. $user->id
.'&sesskey='. sesskey() .'">'. $string->loginas
.'</a><br />';
4544 $output .= '<a href="'. $CFG->wwwroot
.'/user/view.php?id='. $user->id
.'&course='. $course->id
.'">'. $string->fullprofile
.'...</a>';
4546 if (!empty($messageselect)) {
4547 $output .= '<br /><input type="checkbox" name="user'.$user->id
.'" /> ';
4550 $output .= '</td></tr></table>';
4560 * Print a specified group's avatar.
4562 * @param group $group A single {@link group} object OR array of groups.
4563 * @param int $courseid The course ID.
4564 * @param boolean $large Default small picture, or large.
4565 * @param boolean $return If false print picture, otherwise return the output as string
4566 * @param boolean $link Enclose image in a link to view specified course?
4568 * @todo Finish documenting this function
4570 function print_group_picture($group, $courseid, $large=false, $return=false, $link=true) {
4573 if (is_array($group)) {
4575 foreach($group as $g) {
4576 $output .= print_group_picture($g, $courseid, $large, true, $link);
4586 $context = get_context_instance(CONTEXT_COURSE
, $courseid);
4588 if ($group->hidepicture
and !has_capability('moodle/course:managegroups', $context)) {
4592 if ($link or has_capability('moodle/site:accessallgroups', $context)) {
4593 $output = '<a href="'. $CFG->wwwroot
.'/user/index.php?id='. $courseid .'&group='. $group->id
.'">';
4604 if ($group->picture
) { // Print custom group picture
4605 if ($CFG->slasharguments
) { // Use this method if possible for better caching
4606 $output .= '<img class="grouppicture" src="'.$CFG->wwwroot
.'/user/pixgroup.php/'.$group->id
.'/'.$file.'.jpg"'.
4607 ' style="width:'.$size.'px;height:'.$size.'px;" alt="'.s(get_string('group').' '.$group->name
).'" title="'.s($group->name
).'"/>';
4609 $output .= '<img class="grouppicture" src="'.$CFG->wwwroot
.'/user/pixgroup.php?file=/'.$group->id
.'/'.$file.'.jpg"'.
4610 ' style="width:'.$size.'px;height:'.$size.'px;" alt="'.s(get_string('group').' '.$group->name
).'" title="'.s($group->name
).'"/>';
4613 if ($link or has_capability('moodle/site:accessallgroups', $context)) {
4625 * Print a png image.
4627 * @param string $url ?
4628 * @param int $sizex ?
4629 * @param int $sizey ?
4630 * @param boolean $return ?
4631 * @param string $parameters ?
4632 * @todo Finish documenting this function
4634 function print_png($url, $sizex, $sizey, $return, $parameters='alt=""') {
4638 if (!isset($recentIE)) {
4639 $recentIE = check_browser_version('MSIE', '5.0');
4642 if ($recentIE) { // work around the HORRIBLE bug IE has with alpha transparencies
4643 $output .= '<img src="'. $CFG->pixpath
.'/spacer.gif" width="'. $sizex .'" height="'. $sizey .'"'.
4644 ' class="png" style="width: '. $sizex .'px; height: '. $sizey .'px; '.
4645 ' filter: progid:DXImageTransform.Microsoft.AlphaImageLoader(src='.
4646 "'$url', sizingMethod='scale') ".
4647 ' '. $parameters .' />';
4649 $output .= '<img src="'. $url .'" style="width: '. $sizex .'px; height: '. $sizey .'px; '. $parameters .' />';
4660 * Print a nicely formatted table.
4662 * @param array $table is an object with several properties.
4664 * <li>$table->head - An array of heading names.
4665 * <li>$table->align - An array of column alignments
4666 * <li>$table->size - An array of column sizes
4667 * <li>$table->wrap - An array of "nowrap"s or nothing
4668 * <li>$table->data[] - An array of arrays containing the data.
4669 * <li>$table->width - A percentage of the page
4670 * <li>$table->tablealign - Align the whole table
4671 * <li>$table->cellpadding - Padding on each cell
4672 * <li>$table->cellspacing - Spacing between cells
4673 * <li>$table->class - class attribute to put on the table
4674 * <li>$table->id - id attribute to put on the table.
4675 * <li>$table->rowclass[] - classes to add to particular rows.
4676 * <li>$table->summary - Description of the contents for screen readers.
4678 * @param bool $return whether to return an output string or echo now
4679 * @return boolean or $string
4680 * @todo Finish documenting this function
4682 function print_table($table, $return=false) {
4685 if (isset($table->align
)) {
4686 foreach ($table->align
as $key => $aa) {
4688 $align[$key] = ' text-align:'. fix_align_rtl($aa) .';'; // Fix for RTL languages
4694 if (isset($table->size
)) {
4695 foreach ($table->size
as $key => $ss) {
4697 $size[$key] = ' width:'. $ss .';';
4703 if (isset($table->wrap
)) {
4704 foreach ($table->wrap
as $key => $ww) {
4706 $wrap[$key] = ' white-space:nowrap;';
4713 if (empty($table->width
)) {
4714 $table->width
= '80%';
4717 if (empty($table->tablealign
)) {
4718 $table->tablealign
= 'center';
4721 if (!isset($table->cellpadding
)) {
4722 $table->cellpadding
= '5';
4725 if (!isset($table->cellspacing
)) {
4726 $table->cellspacing
= '1';
4729 if (empty($table->class)) {
4730 $table->class = 'generaltable';
4733 $tableid = empty($table->id
) ?
'' : 'id="'.$table->id
.'"';
4735 $output .= '<table width="'.$table->width
.'" ';
4736 if (!empty($table->summary
)) {
4737 $output .= " summary=\"$table->summary\"";
4739 $output .= " cellpadding=\"$table->cellpadding\" cellspacing=\"$table->cellspacing\" class=\"$table->class boxalign$table->tablealign\" $tableid>\n";
4743 if (!empty($table->head
)) {
4744 $countcols = count($table->head
);
4746 foreach ($table->head
as $key => $heading) {
4748 if (!isset($size[$key])) {
4751 if (!isset($align[$key])) {
4755 $output .= '<th style="vertical-align:top;'. $align[$key].$size[$key] .';white-space:nowrap;" class="header c'.$key.'" scope="col">'. $heading .'</th>';
4757 $output .= '</tr>'."\n";
4760 if (!empty($table->data
)) {
4762 foreach ($table->data
as $key => $row) {
4763 $oddeven = $oddeven ?
0 : 1;
4764 if (!isset($table->rowclass
[$key])) {
4765 $table->rowclass
[$key] = '';
4767 $output .= '<tr class="r'.$oddeven.' '.$table->rowclass
[$key].'">'."\n";
4768 if ($row == 'hr' and $countcols) {
4769 $output .= '<td colspan="'. $countcols .'"><div class="tabledivider"></div></td>';
4770 } else { /// it's a normal row of data
4771 foreach ($row as $key => $item) {
4772 if (!isset($size[$key])) {
4775 if (!isset($align[$key])) {
4778 if (!isset($wrap[$key])) {
4781 $output .= '<td style="'. $align[$key].$size[$key].$wrap[$key] .'" class="cell c'.$key.'">'. $item .'</td>';
4784 $output .= '</tr>'."\n";
4787 $output .= '</table>'."\n";
4797 function print_recent_activity_note($time, $user, $text, $link, $return=false, $viewfullnames=null) {
4798 static $strftimerecent = null;
4801 if (is_null($viewfullnames)) {
4802 $context = get_context_instance(CONTEXT_SYSTEM
);
4803 $viewfullnames = has_capability('moodle/site:viewfullnames', $context);
4806 if (is_null($strftimerecent)) {
4807 $strftimerecent = get_string('strftimerecent');
4810 $output .= '<div class="head">';
4811 $output .= '<div class="date">'.userdate($time, $strftimerecent).'</div>';
4812 $output .= '<div class="name">'.fullname($user, $viewfullnames).'</div>';
4813 $output .= '</div>';
4814 $output .= '<div class="info"><a href="'.$link.'">'.format_string($text,true).'</a></div>';
4825 * Prints a basic textarea field.
4828 * @param boolean $usehtmleditor ?
4829 * @param int $rows ?
4830 * @param int $cols ?
4831 * @param null $width <b>Legacy field no longer used!</b> Set to zero to get control over mincols
4832 * @param null $height <b>Legacy field no longer used!</b> Set to zero to get control over minrows
4833 * @param string $name ?
4834 * @param string $value ?
4835 * @param int $courseid ?
4836 * @todo Finish documenting this function
4838 function print_textarea($usehtmleditor, $rows, $cols, $width, $height, $name, $value='', $courseid=0, $return=false, $id='') {
4839 /// $width and height are legacy fields and no longer used as pixels like they used to be.
4840 /// However, you can set them to zero to override the mincols and minrows values below.
4842 global $CFG, $COURSE, $HTTPSPAGEREQUIRED;
4843 static $scriptcount = 0; // For loading the htmlarea script only once.
4850 $id = 'edit-'.$name;
4853 if ( empty($CFG->editorsrc
) ) { // for backward compatibility.
4854 if (empty($courseid)) {
4855 $courseid = $COURSE->id
;
4858 if ($usehtmleditor) {
4859 if (!empty($courseid) and has_capability('moodle/course:managefiles', get_context_instance(CONTEXT_COURSE
, $courseid))) {
4860 $httpsrequired = empty($HTTPSPAGEREQUIRED) ?
'' : '&httpsrequired=1';
4861 // needed for course file area browsing in image insert plugin
4862 $str .= ($scriptcount < 1) ?
'<script type="text/javascript" src="'.
4863 $CFG->httpswwwroot
.'/lib/editor/htmlarea/htmlarea.php?id='.$courseid.$httpsrequired.'"></script>'."\n" : '';
4865 $httpsrequired = empty($HTTPSPAGEREQUIRED) ?
'' : '?httpsrequired=1';
4866 $str .= ($scriptcount < 1) ?
'<script type="text/javascript" src="'.
4867 $CFG->httpswwwroot
.'/lib/editor/htmlarea/htmlarea.php'.$httpsrequired.'"></script>'."\n" : '';
4870 $str .= ($scriptcount < 1) ?
'<script type="text/javascript" src="'.
4871 $CFG->httpswwwroot
.'/lib/editor/htmlarea/lang/en.php"></script>'."\n" : '';
4874 if ($height) { // Usually with legacy calls
4875 if ($rows < $minrows) {
4879 if ($width) { // Usually with legacy calls
4880 if ($cols < $mincols) {
4886 $str .= '<textarea class="form-textarea" id="'. $id .'" name="'. $name .'" rows="'. $rows .'" cols="'. $cols .'">';
4887 if ($usehtmleditor) {
4888 $str .= htmlspecialchars($value); // needed for editing of cleaned text!
4892 $str .= '</textarea>'."\n";
4894 if ($usehtmleditor) {
4895 // Show shortcuts button if HTML editor is in use, but only if JavaScript is enabled (MDL-9556)
4896 $str .= '<script type="text/javascript">
4898 document.write(\''.addslashes_js(editorshortcutshelpbutton()).'\');
4910 * Sets up the HTML editor on textareas in the current page.
4911 * If a field name is provided, then it will only be
4912 * applied to that field - otherwise it will be used
4913 * on every textarea in the page.
4915 * In most cases no arguments need to be supplied
4917 * @param string $name Form element to replace with HTMl editor by name
4919 function use_html_editor($name='', $editorhidebuttons='', $id='') {
4922 $editor = 'editor_'.md5($name); //name might contain illegal characters
4924 $id = 'edit-'.$name;
4926 echo "\n".'<script type="text/javascript" defer="defer">'."\n";
4927 echo '//<![CDATA['."\n\n"; // Extra \n is to fix odd wiki problem, MDL-8185
4928 echo "$editor = new HTMLArea('$id');\n";
4929 echo "var config = $editor.config;\n";
4931 echo print_editor_config($editorhidebuttons);
4933 if (empty($THEME->htmleditorpostprocess
)) {
4935 echo "\nHTMLArea.replaceAll($editor.config);\n";
4937 echo "\n$editor.generate();\n";
4941 echo "\nvar HTML_name = '';";
4943 echo "\nvar HTML_name = \"$name;\"";
4945 echo "\nvar HTML_editor = $editor;";
4948 echo '</script>'."\n";
4951 function print_editor_config($editorhidebuttons='', $return=false) {
4954 $str = "config.pageStyle = \"body {";
4956 if (!(empty($CFG->editorbackgroundcolor
))) {
4957 $str .= " background-color: $CFG->editorbackgroundcolor;";
4960 if (!(empty($CFG->editorfontfamily
))) {
4961 $str .= " font-family: $CFG->editorfontfamily;";
4964 if (!(empty($CFG->editorfontsize
))) {
4965 $str .= " font-size: $CFG->editorfontsize;";
4969 $str .= "config.killWordOnPaste = ";
4970 $str .= (empty($CFG->editorkillword
)) ?
"false":"true";
4972 $str .= 'config.fontname = {'."\n";
4974 $fontlist = isset($CFG->editorfontlist
) ?
explode(';', $CFG->editorfontlist
) : array();
4975 $i = 1; // Counter is used to get rid of the last comma.
4977 foreach ($fontlist as $fontline) {
4978 if (!empty($fontline)) {
4982 list($fontkey, $fontvalue) = split(':', $fontline);
4983 $str .= '"'. $fontkey ."\":\t'". $fontvalue ."'";
4990 if (!empty($editorhidebuttons)) {
4991 $str .= "\nconfig.hideSomeButtons(\" ". $editorhidebuttons ." \");\n";
4992 } else if (!empty($CFG->editorhidebuttons
)) {
4993 $str .= "\nconfig.hideSomeButtons(\" ". $CFG->editorhidebuttons
." \");\n";
4996 if (!empty($CFG->editorspelling
) && !empty($CFG->aspellpath
)) {
4997 $str .= print_speller_code($CFG->htmleditor
, true);
5007 * Returns a turn edit on/off button for course in a self contained form.
5008 * Used to be an icon, but it's now a simple form button
5010 * Note that the caller is responsible for capchecks.
5014 * @param int $courseid The course to update by id as found in 'course' table
5017 function update_course_icon($courseid) {
5020 if (!empty($USER->editing
)) {
5021 $string = get_string('turneditingoff');
5024 $string = get_string('turneditingon');
5028 return '<form '.$CFG->frametarget
.' method="get" action="'.$CFG->wwwroot
.'/course/view.php">'.
5030 '<input type="hidden" name="id" value="'.$courseid.'" />'.
5031 '<input type="hidden" name="edit" value="'.$edit.'" />'.
5032 '<input type="hidden" name="sesskey" value="'.sesskey().'" />'.
5033 '<input type="submit" value="'.$string.'" />'.
5038 * Returns a little popup menu for switching roles
5042 * @param int $courseid The course to update by id as found in 'course' table
5045 function switchroles_form($courseid) {
5050 if (!$context = get_context_instance(CONTEXT_COURSE
, $courseid)) {
5054 if (!empty($USER->access
['rsw'][$context->path
])){ // Just a button to return to normal
5056 $options['id'] = $courseid;
5057 $options['sesskey'] = sesskey();
5058 $options['switchrole'] = 0;
5060 return print_single_button($CFG->wwwroot
.'/course/view.php', $options,
5061 get_string('switchrolereturn'), 'post', '_self', true);
5064 if (has_capability('moodle/role:switchroles', $context)) {
5065 if (!$roles = get_assignable_roles_for_switchrole($context)) {
5066 return ''; // Nothing to show!
5068 // unset default user role - it would not work
5069 unset($roles[$CFG->guestroleid
]);
5070 return popup_form($CFG->wwwroot
.'/course/view.php?id='.$courseid.'&sesskey='.sesskey().'&switchrole=',
5071 $roles, 'switchrole', '', get_string('switchroleto'), 'switchrole', get_string('switchroleto'), true);
5079 * Returns a turn edit on/off button for course in a self contained form.
5080 * Used to be an icon, but it's now a simple form button
5084 * @param int $courseid The course to update by id as found in 'course' table
5087 function update_mymoodle_icon() {
5091 if (!empty($USER->editing
)) {
5092 $string = get_string('updatemymoodleoff');
5095 $string = get_string('updatemymoodleon');
5099 return "<form $CFG->frametarget method=\"get\" action=\"$CFG->wwwroot/my/index.php\">".
5101 "<input type=\"hidden\" name=\"edit\" value=\"$edit\" />".
5102 "<input type=\"submit\" value=\"$string\" /></div></form>";
5106 * Returns a turn edit on/off button for tag in a self contained form.
5112 function update_tag_button($tagid) {
5116 if (!empty($USER->editing
)) {
5117 $string = get_string('turneditingoff');
5120 $string = get_string('turneditingon');
5124 return "<form $CFG->frametarget method=\"get\" action=\"$CFG->wwwroot/tag/index.php\">".
5126 "<input type=\"hidden\" name=\"edit\" value=\"$edit\" />".
5127 "<input type=\"hidden\" name=\"id\" value=\"$tagid\" />".
5128 "<input type=\"submit\" value=\"$string\" /></div></form>";
5132 * Prints the editing button on a module "view" page
5135 * @param type description
5136 * @todo Finish documenting this function
5138 function update_module_button($moduleid, $courseid, $string) {
5141 if (has_capability('moodle/course:manageactivities', get_context_instance(CONTEXT_MODULE
, $moduleid))) {
5142 $string = get_string('updatethis', '', $string);
5144 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
5146 "<input type=\"hidden\" name=\"update\" value=\"$moduleid\" />".
5147 "<input type=\"hidden\" name=\"return\" value=\"true\" />".
5148 "<input type=\"hidden\" name=\"sesskey\" value=\"".sesskey()."\" />".
5149 "<input type=\"submit\" value=\"$string\" /></div></form>";
5156 * Prints the editing button on a category page
5160 * @param int $categoryid ?
5162 * @todo Finish documenting this function
5164 function update_category_button($categoryid) {
5167 if (has_capability('moodle/category:update', get_context_instance(CONTEXT_COURSECAT
, $categoryid))) {
5168 if (!empty($USER->categoryediting
)) {
5169 $string = get_string('turneditingoff');
5172 $string = get_string('turneditingon');
5176 return "<form $CFG->frametarget method=\"get\" action=\"$CFG->wwwroot/course/category.php\">".
5178 "<input type=\"hidden\" name=\"id\" value=\"$categoryid\" />".
5179 "<input type=\"hidden\" name=\"categoryedit\" value=\"$edit\" />".
5180 "<input type=\"hidden\" name=\"sesskey\" value=\"$USER->sesskey\" />".
5181 "<input type=\"submit\" value=\"$string\" /></div></form>";
5186 * Prints the editing button on categories listing
5192 function update_categories_button() {
5195 if (has_capability('moodle/category:update', get_context_instance(CONTEXT_SYSTEM
))) {
5196 if (!empty($USER->categoryediting
)) {
5197 $string = get_string('turneditingoff');
5198 $categoryedit = 'off';
5200 $string = get_string('turneditingon');
5201 $categoryedit = 'on';
5204 return "<form $CFG->frametarget method=\"get\" action=\"$CFG->wwwroot/course/index.php\">".
5206 '<input type="hidden" name="categoryedit" value="'. $categoryedit .'" />'.
5207 '<input type="hidden" name="sesskey" value="'.$USER->sesskey
.'" />'.
5208 '<input type="submit" value="'. $string .'" /></div></form>';
5213 * Prints the editing button on search results listing
5214 * For bulk move courses to another category
5217 function update_categories_search_button($search,$page,$perpage) {
5220 // not sure if this capability is the best here
5221 if (has_capability('moodle/category:update', get_context_instance(CONTEXT_SYSTEM
))) {
5222 if (!empty($USER->categoryediting
)) {
5223 $string = get_string("turneditingoff");
5227 $string = get_string("turneditingon");
5231 return "<form $CFG->frametarget method=\"get\" action=\"$CFG->wwwroot/course/search.php\">".
5233 "<input type=\"hidden\" name=\"edit\" value=\"$edit\" />".
5234 "<input type=\"hidden\" name=\"sesskey\" value=\"$USER->sesskey\" />".
5235 "<input type=\"hidden\" name=\"search\" value=\"".s($search, true)."\" />".
5236 "<input type=\"hidden\" name=\"page\" value=\"$page\" />".
5237 "<input type=\"hidden\" name=\"perpage\" value=\"$perpage\" />".
5238 "<input type=\"submit\" value=\"".s($string)."\" /></div></form>";
5243 * Given a course and a (current) coursemodule
5244 * This function returns a small popup menu with all the
5245 * course activity modules in it, as a navigation menu
5246 * The data is taken from the serialised array stored in
5249 * @param course $course A {@link $COURSE} object.
5250 * @param course $cm A {@link $COURSE} object.
5251 * @param string $targetwindow ?
5253 * @todo Finish documenting this function
5255 function navmenu($course, $cm=NULL, $targetwindow='self') {
5257 global $CFG, $THEME, $USER;
5259 if (empty($THEME->navmenuwidth
)) {
5262 $width = $THEME->navmenuwidth
;
5269 if ($course->format
== 'weeks') {
5270 $strsection = get_string('week');
5272 $strsection = get_string('topic');
5274 $strjumpto = get_string('jumpto');
5276 $modinfo = get_fast_modinfo($course);
5277 $context = get_context_instance(CONTEXT_COURSE
, $course->id
);
5282 $previousmod = NULL;
5289 $menustyle = array();
5291 $sections = get_records('course_sections','course',$course->id
,'section','section,visible,summary');
5293 if (!empty($THEME->makenavmenulist
)) { /// A hack to produce an XHTML navmenu list for use in themes
5294 $THEME->navmenulist
= navmenulist($course, $sections, $modinfo, $strsection, $strjumpto, $width, $cm);
5297 foreach ($modinfo->cms
as $mod) {
5298 if ($mod->modname
== 'label') {
5302 if ($mod->sectionnum
> $course->numsections
) { /// Don't show excess hidden sections
5306 if (!$mod->uservisible
) { // do not icnlude empty sections at all
5310 if ($mod->sectionnum
> 0 and $section != $mod->sectionnum
) {
5311 $thissection = $sections[$mod->sectionnum
];
5313 if ($thissection->visible
or !$course->hiddensections
or
5314 has_capability('moodle/course:viewhiddensections', $context)) {
5315 $thissection->summary
= strip_tags(format_string($thissection->summary
,true));
5316 if ($course->format
== 'weeks' or empty($thissection->summary
)) {
5317 $menu[] = '--'.$strsection ." ". $mod->sectionnum
;
5319 if (strlen($thissection->summary
) < ($width-3)) {
5320 $menu[] = '--'.$thissection->summary
;
5322 $menu[] = '--'.substr($thissection->summary
, 0, $width).'...';
5325 $section = $mod->sectionnum
;
5327 // no activities from this hidden section shown
5332 $url = $mod->modname
.'/view.php?id='. $mod->id
;
5333 if ($flag) { // the current mod is the "next" mod
5337 $localname = $mod->name
;
5338 if ($cm == $mod->id
) {
5341 $backmod = $previousmod;
5342 $flag = true; // set flag so we know to use next mod for "next"
5343 $localname = $strjumpto;
5346 $localname = strip_tags(format_string($localname,true));
5347 $tl=textlib_get_instance();
5348 if ($tl->strlen($localname) > ($width+
5)) {
5349 $localname = $tl->substr($localname, 0, $width).'...';
5351 if (!$mod->visible
) {
5352 $localname = '('.$localname.')';
5355 $menu[$url] = $localname;
5356 if (empty($THEME->navmenuiconshide
)) {
5357 $menustyle[$url] = 'style="background-image: url('.$CFG->modpixpath
.'/'.$mod->modname
.'/icon.gif);"'; // Unfortunately necessary to do this here
5359 $previousmod = $mod;
5361 //Accessibility: added Alt text, replaced > < with 'silent' character and 'accesshide' text.
5363 if ($selectmod and has_capability('moodle/site:viewreports', $context)) {
5364 $logstext = get_string('alllogs');
5365 $logslink = '<li>'."\n".'<a title="'.$logstext.'" '.
5366 $CFG->frametarget
.'onclick="this.target=\''.$CFG->framename
.'\';"'.' href="'.
5367 $CFG->wwwroot
.'/course/report/log/index.php?chooselog=1&user=0&date=0&id='.
5368 $course->id
.'&modid='.$selectmod->id
.'">'.
5369 '<img class="icon log" src="'.$CFG->pixpath
.'/i/log.gif" alt="'.$logstext.'" /></a>'."\n".'</li>';
5373 $backtext= get_string('activityprev', 'access');
5374 $backmod = '<li><form action="'.$CFG->wwwroot
.'/mod/'.$backmod->modname
.'/view.php" '.
5375 'onclick="this.target=\''.$CFG->framename
.'\';"'.'><fieldset class="invisiblefieldset">'.
5376 '<input type="hidden" name="id" value="'.$backmod->id
.'" />'.
5377 '<button type="submit" title="'.$backtext.'">'.link_arrow_left($backtext, $url='', $accesshide=true).
5378 '</button></fieldset></form></li>';
5381 $nexttext= get_string('activitynext', 'access');
5382 $nextmod = '<li><form action="'.$CFG->wwwroot
.'/mod/'.$nextmod->modname
.'/view.php" '.
5383 'onclick="this.target=\''.$CFG->framename
.'\';"'.'><fieldset class="invisiblefieldset">'.
5384 '<input type="hidden" name="id" value="'.$nextmod->id
.'" />'.
5385 '<button type="submit" title="'.$nexttext.'">'.link_arrow_right($nexttext, $url='', $accesshide=true).
5386 '</button></fieldset></form></li>';
5389 return '<div class="navigation">'."\n".'<ul>'.$logslink . $backmod .
5390 '<li>'.popup_form($CFG->wwwroot
.'/mod/', $menu, 'navmenupopup', $selected, $strjumpto,
5391 '', '', true, $targetwindow, '', $menustyle).'</li>'.
5392 $nextmod . '</ul>'."\n".'</div>';
5397 * This function returns a small popup menu with all the
5398 * course activity modules in it, as a navigation menu
5399 * outputs a simple list structure in XHTML
5400 * The data is taken from the serialised array stored in
5403 * @param course $course A {@link $COURSE} object.
5405 * @todo Finish documenting this function
5407 function navmenulist($course, $sections, $modinfo, $strsection, $strjumpto, $width=50, $cmid=0) {
5414 $doneheading = false;
5416 $coursecontext = get_context_instance(CONTEXT_COURSE
, $course->id
);
5418 $menu[] = '<ul class="navmenulist"><li class="jumpto section"><span>'.$strjumpto.'</span><ul>';
5419 foreach ($modinfo->cms
as $mod) {
5420 if ($mod->modname
== 'label') {
5424 if ($mod->sectionnum
> $course->numsections
) { /// Don't show excess hidden sections
5428 if (!$mod->uservisible
) { // do not icnlude empty sections at all
5432 if ($mod->sectionnum
>= 0 and $section != $mod->sectionnum
) {
5433 $thissection = $sections[$mod->sectionnum
];
5435 if ($thissection->visible
or !$course->hiddensections
or
5436 has_capability('moodle/course:viewhiddensections', $coursecontext)) {
5437 $thissection->summary
= strip_tags(format_string($thissection->summary
,true));
5438 if (!$doneheading) {
5439 $menu[] = '</ul></li>';
5441 if ($course->format
== 'weeks' or empty($thissection->summary
)) {
5442 $item = $strsection ." ". $mod->sectionnum
;
5444 if (strlen($thissection->summary
) < ($width-3)) {
5445 $item = $thissection->summary
;
5447 $item = substr($thissection->summary
, 0, $width).'...';
5450 $menu[] = '<li class="section"><span>'.$item.'</span>';
5452 $doneheading = true;
5454 $section = $mod->sectionnum
;
5456 // no activities from this hidden section shown
5461 $url = $mod->modname
.'/view.php?id='. $mod->id
;
5462 $mod->name
= strip_tags(format_string(urldecode($mod->name
),true));
5463 if (strlen($mod->name
) > ($width+
5)) {
5464 $mod->name
= substr($mod->name
, 0, $width).'...';
5466 if (!$mod->visible
) {
5467 $mod->name
= '('.$mod->name
.')';
5469 $class = 'activity '.$mod->modname
;
5470 $class .= ($cmid == $mod->cm
) ?
' selected' : '';
5471 $menu[] = '<li class="'.$class.'">'.
5472 '<img src="'.$CFG->modpixpath
.'/'.$mod->modname
.'/icon.gif" alt="" />'.
5473 '<a href="'.$CFG->wwwroot
.'/mod/'.$url.'">'.$mod->name
.'</a></li>';
5477 $menu[] = '</ul></li>';
5479 $menu[] = '</ul></li></ul>';
5481 return implode("\n", $menu);
5485 * Prints form items with the names $day, $month and $year
5487 * @param string $day fieldname
5488 * @param string $month fieldname
5489 * @param string $year fieldname
5490 * @param int $currenttime A default timestamp in GMT
5491 * @param boolean $return
5493 function print_date_selector($day, $month, $year, $currenttime=0, $return=false) {
5495 if (!$currenttime) {
5496 $currenttime = time();
5498 $currentdate = usergetdate($currenttime);
5500 for ($i=1; $i<=31; $i++
) {
5503 for ($i=1; $i<=12; $i++
) {
5504 $months[$i] = userdate(gmmktime(12,0,0,$i,15,2000), "%B");
5506 for ($i=1970; $i<=2020; $i++
) {
5509 return choose_from_menu($days, $day, $currentdate['mday'], '', '', '0', $return)
5510 .choose_from_menu($months, $month, $currentdate['mon'], '', '', '0', $return)
5511 .choose_from_menu($years, $year, $currentdate['year'], '', '', '0', $return);
5516 *Prints form items with the names $hour and $minute
5518 * @param string $hour fieldname
5519 * @param string ? $minute fieldname
5520 * @param $currenttime A default timestamp in GMT
5521 * @param int $step minute spacing
5522 * @param boolean $return
5524 function print_time_selector($hour, $minute, $currenttime=0, $step=5, $return=false) {
5526 if (!$currenttime) {
5527 $currenttime = time();
5529 $currentdate = usergetdate($currenttime);
5531 $currentdate['minutes'] = ceil($currentdate['minutes']/$step)*$step;
5533 for ($i=0; $i<=23; $i++
) {
5534 $hours[$i] = sprintf("%02d",$i);
5536 for ($i=0; $i<=59; $i+
=$step) {
5537 $minutes[$i] = sprintf("%02d",$i);
5540 return choose_from_menu($hours, $hour, $currentdate['hours'], '','','0',$return)
5541 .choose_from_menu($minutes, $minute, $currentdate['minutes'], '','','0',$return);
5545 * Prints time limit value selector
5548 * @param int $timelimit default
5549 * @param string $unit
5550 * @param string $name
5551 * @param boolean $return
5553 function print_timer_selector($timelimit = 0, $unit = '', $name = 'timelimit', $return=false) {
5561 // Max timelimit is sessiontimeout - 10 minutes.
5562 $maxvalue = ($CFG->sessiontimeout
/ 60) - 10;
5564 for ($i=1; $i<=$maxvalue; $i++
) {
5565 $minutes[$i] = $i.$unit;
5567 return choose_from_menu($minutes, $name, $timelimit, get_string('none'), '','','0',$return);
5571 * Prints a grade menu (as part of an existing form) with help
5572 * Showing all possible numerical grades and scales
5575 * @param int $courseid ?
5576 * @param string $name ?
5577 * @param string $current ?
5578 * @param boolean $includenograde ?
5579 * @todo Finish documenting this function
5581 function print_grade_menu($courseid, $name, $current, $includenograde=true, $return=false) {
5586 $strscale = get_string('scale');
5587 $strscales = get_string('scales');
5589 $scales = get_scales_menu($courseid);
5590 foreach ($scales as $i => $scalename) {
5591 $grades[-$i] = $strscale .': '. $scalename;
5593 if ($includenograde) {
5594 $grades[0] = get_string('nograde');
5596 for ($i=100; $i>=1; $i--) {
5599 $output .= choose_from_menu($grades, $name, $current, '', '', 0, true);
5601 $linkobject = '<span class="helplink"><img class="iconhelp" alt="'.$strscales.'" src="'.$CFG->pixpath
.'/help.gif" /></span>';
5602 $output .= link_to_popup_window ('/course/scales.php?id='. $courseid .'&list=true', 'ratingscales',
5603 $linkobject, 400, 500, $strscales, 'none', true);
5613 * Prints a scale menu (as part of an existing form) including help button
5614 * Just like {@link print_grade_menu()} but without the numeric grades
5616 * @param int $courseid ?
5617 * @param string $name ?
5618 * @param string $current ?
5619 * @todo Finish documenting this function
5621 function print_scale_menu($courseid, $name, $current, $return=false) {
5626 $strscales = get_string('scales');
5627 $output .= choose_from_menu(get_scales_menu($courseid), $name, $current, '', '', 0, true);
5629 $linkobject = '<span class="helplink"><img class="iconhelp" alt="'.$strscales.'" src="'.$CFG->pixpath
.'/help.gif" /></span>';
5630 $output .= link_to_popup_window ('/course/scales.php?id='. $courseid .'&list=true', 'ratingscales',
5631 $linkobject, 400, 500, $strscales, 'none', true);
5640 * Prints a help button about a scale
5643 * @param id $courseid ?
5644 * @param object $scale ?
5645 * @todo Finish documenting this function
5647 function print_scale_menu_helpbutton($courseid, $scale, $return=false) {
5652 $strscales = get_string('scales');
5654 $linkobject = '<span class="helplink"><img class="iconhelp" alt="'.$scale->name
.'" src="'.$CFG->pixpath
.'/help.gif" /></span>';
5655 $output .= link_to_popup_window ('/course/scales.php?id='. $courseid .'&list=true&scaleid='. $scale->id
, 'ratingscale',
5656 $linkobject, 400, 500, $scale->name
, 'none', true);
5665 * Print an error page displaying an error message. New method - use this for new code.
5669 * @param string $errorcode The name of the string from error.php to print
5670 * @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.
5671 * @param object $a Extra words and phrases that might be required in the error string
5673 function print_error ($errorcode, $module='', $link='', $a=NULL) {
5675 global $CFG, $SESSION, $THEME;
5677 if (empty($module) ||
$module == 'moodle' ||
$module == 'core') {
5679 $modulelink = 'moodle';
5681 $modulelink = $module;
5684 if (empty($link) and !defined('ADMIN_EXT_HEADER_PRINTED')) {
5685 if ( !empty($SESSION->fromurl
) ) {
5686 $link = $SESSION->fromurl
;
5687 unset($SESSION->fromurl
);
5689 $link = $CFG->wwwroot
.'/';
5693 if (!empty($CFG->errordocroot
)) {
5694 $errordocroot = $CFG->errordocroot
;
5695 } else if (!empty($CFG->docroot
)) {
5696 $errordocroot = $CFG->docroot
;
5698 $errordocroot = 'http://docs.moodle.org';
5701 $message = get_string($errorcode, $module, $a);
5703 if (defined('FULLME') && FULLME
== 'cron') {
5704 // Errors in cron should be mtrace'd.
5709 $message = clean_text('<p class="errormessage">'.$message.'</p>'.
5710 '<p class="errorcode">'.
5711 '<a href="'.$errordocroot.'/en/error/'.$modulelink.'/'.$errorcode.'">'.
5712 get_string('moreinformation').'</a></p>');
5714 if (! defined('HEADER_PRINTED')) {
5715 //header not yet printed
5716 @header
('HTTP/1.0 404 Not Found');
5717 print_header(get_string('error'));
5719 print_container_end_all(false, $THEME->open_header_containers
);
5724 print_simple_box($message, '', '', '', '', 'errorbox');
5726 debugging('Stack trace:', DEBUG_DEVELOPER
);
5728 // in case we are logging upgrade in admin/index.php stop it
5729 if (function_exists('upgrade_log_finish')) {
5730 upgrade_log_finish();
5733 if (!empty($link)) {
5734 print_continue($link);
5739 for ($i=0;$i<512;$i++
) { // Padding to help IE work with 404
5746 * Print an error to STDOUT and exit with a non-zero code. For commandline scripts.
5747 * Default errorcode is 1.
5749 * Very useful for perl-like error-handling:
5751 * do_somethting() or mdie("Something went wrong");
5753 * @param string $msg Error message
5754 * @param integer $errorcode Error code to emit
5756 function mdie($msg='', $errorcode=1) {
5757 trigger_error($msg);
5762 * Returns a string of html with an image of a help icon linked to a help page on a number of help topics.
5763 * Should be used only with htmleditor or textarea.
5764 * @param mixed $helptopics variable amount of params accepted. Each param may be a string or an array of arguments for
5768 function editorhelpbutton(){
5769 global $CFG, $SESSION;
5770 $items = func_get_args();
5772 $urlparams = array();
5774 foreach ($items as $item){
5775 if (is_array($item)){
5776 $urlparams[] = "keyword$i=".urlencode($item[0]);
5777 $urlparams[] = "title$i=".urlencode($item[1]);
5778 if (isset($item[2])){
5779 $urlparams[] = "module$i=".urlencode($item[2]);
5781 $titles[] = trim($item[1], ". \t");
5782 }elseif (is_string($item)){
5783 $urlparams[] = "button$i=".urlencode($item);
5786 $titles[] = get_string("helpreading");
5789 $titles[] = get_string("helpwriting");
5792 $titles[] = get_string("helpquestions");
5795 $titles[] = get_string("helpemoticons");
5798 $titles[] = get_string('helprichtext');
5801 $titles[] = get_string('helptext');
5804 error('Unknown help topic '.$item);
5809 if (count($titles)>1){
5810 //join last two items with an 'and'
5812 $a->one
= $titles[count($titles) - 2];
5813 $a->two
= $titles[count($titles) - 1];
5814 $titles[count($titles) - 2] = get_string('and', '', $a);
5815 unset($titles[count($titles) - 1]);
5817 $alttag = join (', ', $titles);
5819 $paramstring = join('&', $urlparams);
5820 $linkobject = '<img alt="'.$alttag.'" class="iconhelp" src="'.$CFG->pixpath
.'/help.gif" />';
5821 return link_to_popup_window(s('/lib/form/editorhelp.php?'.$paramstring), 'popup', $linkobject, 400, 500, $alttag, 'none', true);
5825 * Print a help button.
5828 * @param string $page The keyword that defines a help page
5829 * @param string $title The title of links, rollover tips, alt tags etc
5830 * 'Help with' (or the language equivalent) will be prefixed and '...' will be stripped.
5831 * @param string $module Which module is the page defined in
5832 * @param mixed $image Use a help image for the link? (true/false/"both")
5833 * @param boolean $linktext If true, display the title next to the help icon.
5834 * @param string $text If defined then this text is used in the page, and
5835 * the $page variable is ignored.
5836 * @param boolean $return If true then the output is returned as a string, if false it is printed to the current page.
5837 * @param string $imagetext The full text for the helpbutton icon. If empty use default help.gif
5839 * @todo Finish documenting this function
5841 function helpbutton ($page, $title, $module='moodle', $image=true, $linktext=false, $text='', $return=false,
5843 global $CFG, $COURSE;
5846 if (!empty($COURSE->lang
)) {
5847 $forcelang = $COURSE->lang
;
5852 if ($module == '') {
5856 if ($title == '' && $linktext == '') {
5857 debugging('Error in call to helpbutton function: at least one of $title and $linktext is required');
5860 // Warn users about new window for Accessibility
5861 $tooltip = get_string('helpprefix2', '', trim($title, ". \t")) .' ('.get_string('newwindow').')';
5867 // MDL-7469 If text link is displayed with help icon, change to alt to "help with this".
5868 $linkobject .= $title.' ';
5869 $tooltip = get_string('helpwiththis');
5872 $linkobject .= $imagetext;
5874 $linkobject .= '<img class="iconhelp" alt="'.s(strip_tags($tooltip)).'" src="'.
5875 $CFG->pixpath
.'/help.gif" />';
5878 $linkobject .= $tooltip;
5883 $url = '/help.php?module='. $module .'&text='. s(urlencode($text).'&forcelang='.$forcelang);
5885 $url = '/help.php?module='. $module .'&file='. $page .'.html&forcelang='.$forcelang;
5888 $link = '<span class="helplink">'.
5889 link_to_popup_window ($url, 'popup', $linkobject, 400, 500, $tooltip, 'none', true).
5900 * Print a help button.
5902 * Prints a special help button that is a link to the "live" emoticon popup
5905 * @param string $form ?
5906 * @param string $field ?
5907 * @todo Finish documenting this function
5909 function emoticonhelpbutton($form, $field, $return = false) {
5911 global $CFG, $SESSION;
5913 $SESSION->inserttextform
= $form;
5914 $SESSION->inserttextfield
= $field;
5915 $imagetext = '<img src="' . $CFG->pixpath
. '/s/smiley.gif" alt="" class="emoticon" style="margin-left:3px; padding-right:1px;width:15px;height:15px;" />';
5916 $help = helpbutton('emoticons', get_string('helpemoticons'), 'moodle', true, true, '', true, $imagetext);
5925 * Print a help button.
5927 * Prints a special help button for html editors (htmlarea in this case)
5930 function editorshortcutshelpbutton() {
5933 $imagetext = '<img src="' . $CFG->httpswwwroot
. '/lib/editor/htmlarea/images/kbhelp.gif" alt="'.
5934 get_string('editorshortcutkeys').'" class="iconkbhelp" />';
5936 return helpbutton('editorshortcuts', get_string('editorshortcutkeys'), 'moodle', true, false, '', true, $imagetext);
5940 * Print a message and exit.
5943 * @param string $message ?
5944 * @param string $link ?
5945 * @todo Finish documenting this function
5947 function notice ($message, $link='', $course=NULL) {
5948 global $CFG, $SITE, $THEME, $COURSE;
5950 $message = clean_text($message); // In case nasties are in here
5952 if (defined('FULLME') && FULLME
== 'cron') {
5953 // notices in cron should be mtrace'd.
5958 if (! defined('HEADER_PRINTED')) {
5959 //header not yet printed
5960 print_header(get_string('notice'));
5962 print_container_end_all(false, $THEME->open_header_containers
);
5965 print_box($message, 'generalbox', 'notice');
5966 print_continue($link);
5968 if (empty($course)) {
5969 print_footer($COURSE);
5971 print_footer($course);
5977 * Print a message along with "Yes" and "No" links for the user to continue.
5979 * @param string $message The text to display
5980 * @param string $linkyes The link to take the user to if they choose "Yes"
5981 * @param string $linkno The link to take the user to if they choose "No"
5982 * TODO Document remaining arguments
5984 function notice_yesno ($message, $linkyes, $linkno, $optionsyes=NULL, $optionsno=NULL, $methodyes='post', $methodno='post') {
5988 $message = clean_text($message);
5989 $linkyes = clean_text($linkyes);
5990 $linkno = clean_text($linkno);
5992 print_box_start('generalbox', 'notice');
5993 echo '<p>'. $message .'</p>';
5994 echo '<div class="buttons">';
5995 print_single_button($linkyes, $optionsyes, get_string('yes'), $methodyes, $CFG->framename
);
5996 print_single_button($linkno, $optionsno, get_string('no'), $methodno, $CFG->framename
);
6002 * Provide an definition of error_get_last for PHP before 5.2.0. This simply
6003 * returns NULL, since there is not way to get the right answer.
6005 if (!function_exists('error_get_last')) {
6006 // the eval is needed to prevent PHP 5.2+ from getting a parse error!
6008 function error_get_last() {
6015 * Redirects the user to another page, after printing a notice
6017 * @param string $url The url to take the user to
6018 * @param string $message The text message to display to the user about the redirect, if any
6019 * @param string $delay How long before refreshing to the new page at $url?
6020 * @todo '&' needs to be encoded into '&' for XHTML compliance,
6021 * however, this is not true for javascript. Therefore we
6022 * first decode all entities in $url (since we cannot rely on)
6023 * the correct input) and then encode for where it's needed
6024 * echo "<script type='text/javascript'>alert('Redirect $url');</script>";
6026 function redirect($url, $message='', $delay=-1) {
6028 global $CFG, $THEME;
6030 if (!empty($CFG->usesid
) && !isset($_COOKIE[session_name()])) {
6031 $url = sid_process_url($url);
6034 $message = clean_text($message);
6036 $encodedurl = preg_replace("/\&(?![a-zA-Z0-9#]{1,8};)/", "&", $url);
6037 $encodedurl = preg_replace('/^.*href="([^"]*)".*$/', "\\1", clean_text('<a href="'.$encodedurl.'" />'));
6038 $url = str_replace('&', '&', $encodedurl);
6040 /// At developer debug level. Don't redirect if errors have been printed on screen.
6041 /// Currenly only works in PHP 5.2+; we do not want strict PHP5 errors
6042 $lasterror = error_get_last();
6043 $error = defined('DEBUGGING_PRINTED') or (!empty($lasterror) && ($lasterror['type'] & DEBUG_DEVELOPER
));
6044 $errorprinted = debugging('', DEBUG_ALL
) && $CFG->debugdisplay
&& $error;
6045 if ($errorprinted) {
6046 $message = "<strong>Error output, so disabling automatic redirect.</strong></p><p>" . $message;
6049 $performanceinfo = '';
6050 if (defined('MDL_PERF') ||
(!empty($CFG->perfdebug
) and $CFG->perfdebug
> 7)) {
6051 if (defined('MDL_PERFTOLOG') && !function_exists('register_shutdown_function')) {
6052 $perf = get_performance_info();
6053 error_log("PERF: " . $perf['txt']);
6057 /// when no message and header printed yet, try to redirect
6058 if (empty($message) and !defined('HEADER_PRINTED')) {
6060 // Technically, HTTP/1.1 requires Location: header to contain
6061 // the absolute path. (In practice browsers accept relative
6062 // paths - but still, might as well do it properly.)
6063 // This code turns relative into absolute.
6064 if (!preg_match('|^[a-z]+:|', $url)) {
6065 // Get host name http://www.wherever.com
6066 $hostpart = preg_replace('|^(.*?[^:/])/.*$|', '$1', $CFG->wwwroot
);
6067 if (preg_match('|^/|', $url)) {
6068 // URLs beginning with / are relative to web server root so we just add them in
6069 $url = $hostpart.$url;
6071 // URLs not beginning with / are relative to path of current script, so add that on.
6072 $url = $hostpart.preg_replace('|\?.*$|','',me()).'/../'.$url;
6076 $newurl = preg_replace('|/(?!\.\.)[^/]*/\.\./|', '/', $url);
6077 if ($newurl == $url) {
6085 //try header redirection first
6086 @header
($_SERVER['SERVER_PROTOCOL'] . ' 303 See Other'); //302 might not work for POST requests, 303 is ignored by obsolete clients
6087 @header
('Location: '.$url);
6088 //another way for older browsers and already sent headers (eg trailing whitespace in config.php)
6089 echo '<meta http-equiv="refresh" content="'. $delay .'; url='. $encodedurl .'" />';
6090 echo '<script type="text/javascript">'. "\n" .'//<![CDATA['. "\n". "location.replace('".addslashes_js($url)."');". "\n". '//]]>'. "\n". '</script>'; // To cope with Mozilla bug
6095 $delay = 3; // if no delay specified wait 3 seconds
6097 if (! defined('HEADER_PRINTED')) {
6098 // this type of redirect might not be working in some browsers - such as lynx :-(
6099 print_header('', '', '', '', $errorprinted ?
'' : ('<meta http-equiv="refresh" content="'. $delay .'; url='. $encodedurl .'" />'));
6100 $delay +
= 3; // double redirect prevention, it was sometimes breaking upgrades before 1.7
6102 print_container_end_all(false, $THEME->open_header_containers
);
6104 echo '<div id="redirect">';
6105 echo '<div id="message">' . $message . '</div>';
6106 echo '<div id="continue">( <a href="'. $encodedurl .'">'. get_string('continue') .'</a> )</div>';
6109 if (!$errorprinted) {
6111 <script type
="text/javascript">
6114 function redirect() {
6115 document
.location
.replace('<?php echo addslashes_js($url) ?>');
6117 setTimeout("redirect()", <?php
echo ($delay * 1000) ?
>);
6123 $CFG->docroot
= false; // to prevent the link to moodle docs from being displayed on redirect page.
6124 print_footer('none');
6129 * Print a bold message in an optional color.
6131 * @param string $message The message to print out
6132 * @param string $style Optional style to display message text in
6133 * @param string $align Alignment option
6134 * @param bool $return whether to return an output string or echo now
6136 function notify($message, $style='notifyproblem', $align='center', $return=false) {
6137 if ($style == 'green') {
6138 $style = 'notifysuccess'; // backward compatible with old color system
6141 $message = clean_text($message);
6143 $output = '<div class="'.$style.'" style="text-align:'. $align .'">'. $message .'</div>'."\n";
6153 * Given an email address, this function will return an obfuscated version of it
6155 * @param string $email The email address to obfuscate
6158 function obfuscate_email($email) {
6161 $length = strlen($email);
6163 while ($i < $length) {
6165 $obfuscated.='%'.dechex(ord($email{$i}));
6167 $obfuscated.=$email{$i};
6175 * This function takes some text and replaces about half of the characters
6176 * with HTML entity equivalents. Return string is obviously longer.
6178 * @param string $plaintext The text to be obfuscated
6181 function obfuscate_text($plaintext) {
6184 $length = strlen($plaintext);
6186 $prev_obfuscated = false;
6187 while ($i < $length) {
6188 $c = ord($plaintext{$i});
6189 $numerical = ($c >= ord('0')) && ($c <= ord('9'));
6190 if ($prev_obfuscated and $numerical ) {
6191 $obfuscated.='&#'.ord($plaintext{$i}).';';
6192 } else if (rand(0,2)) {
6193 $obfuscated.='&#'.ord($plaintext{$i}).';';
6194 $prev_obfuscated = true;
6196 $obfuscated.=$plaintext{$i};
6197 $prev_obfuscated = false;
6205 * This function uses the {@link obfuscate_email()} and {@link obfuscate_text()}
6206 * to generate a fully obfuscated email link, ready to use.
6208 * @param string $email The email address to display
6209 * @param string $label The text to dispalyed as hyperlink to $email
6210 * @param boolean $dimmed If true then use css class 'dimmed' for hyperlink
6213 function obfuscate_mailto($email, $label='', $dimmed=false) {
6215 if (empty($label)) {
6219 $title = get_string('emaildisable');
6220 $dimmed = ' class="dimmed"';
6225 return sprintf("<a href=\"%s:%s\" $dimmed title=\"$title\">%s</a>",
6226 obfuscate_text('mailto'), obfuscate_email($email),
6227 obfuscate_text($label));
6231 * Prints a single paging bar to provide access to other pages (usually in a search)
6233 * @param int $totalcount Thetotal number of entries available to be paged through
6234 * @param int $page The page you are currently viewing
6235 * @param int $perpage The number of entries that should be shown per page
6236 * @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.
6237 * If this is a moodle_url object then the pagevar param will be replaced by the page no, for each page.
6238 * @param string $pagevar This is the variable name that you use for the page number in your code (ie. 'tablepage', 'blogpage', etc)
6239 * @param bool $nocurr do not display the current page as a link
6240 * @param bool $return whether to return an output string or echo now
6241 * @return bool or string
6243 function print_paging_bar($totalcount, $page, $perpage, $baseurl, $pagevar='page',$nocurr=false, $return=false) {
6247 if ($totalcount > $perpage) {
6248 $output .= '<div class="paging">';
6249 $output .= get_string('page') .':';
6251 $pagenum = $page - 1;
6252 if (!is_a($baseurl, 'moodle_url')){
6253 $output .= ' (<a href="'. $baseurl . $pagevar .'='. $pagenum .'">'. get_string('previous') .'</a>) ';
6255 $output .= ' (<a href="'. $baseurl->out(false, array($pagevar => $pagenum)).'">'. get_string('previous') .'</a>) ';
6259 $lastpage = ceil($totalcount / $perpage);
6264 $startpage = $page - 10;
6265 if (!is_a($baseurl, 'moodle_url')){
6266 $output .= ' <a href="'. $baseurl . $pagevar .'=0">1</a> ...';
6268 $output .= ' <a href="'. $baseurl->out(false, array($pagevar => 0)).'">1</a> ...';
6273 $currpage = $startpage;
6274 $displaycount = $displaypage = 0;
6275 while ($displaycount < $maxdisplay and $currpage < $lastpage) {
6276 $displaypage = $currpage+
1;
6277 if ($page == $currpage && empty($nocurr)) {
6278 $output .= ' '. $displaypage;
6280 if (!is_a($baseurl, 'moodle_url')){
6281 $output .= ' <a href="'. $baseurl . $pagevar .'='. $currpage .'">'. $displaypage .'</a>';
6283 $output .= ' <a href="'. $baseurl->out(false, array($pagevar => $currpage)).'">'. $displaypage .'</a>';
6290 if ($currpage < $lastpage) {
6291 $lastpageactual = $lastpage - 1;
6292 if (!is_a($baseurl, 'moodle_url')){
6293 $output .= ' ...<a href="'. $baseurl . $pagevar .'='. $lastpageactual .'">'. $lastpage .'</a> ';
6295 $output .= ' ...<a href="'. $baseurl->out(false, array($pagevar => $lastpageactual)).'">'. $lastpage .'</a> ';
6298 $pagenum = $page +
1;
6299 if ($pagenum != $displaypage) {
6300 if (!is_a($baseurl, 'moodle_url')){
6301 $output .= ' (<a href="'. $baseurl . $pagevar .'='. $pagenum .'">'. get_string('next') .'</a>)';
6303 $output .= ' (<a href="'. $baseurl->out(false, array($pagevar => $pagenum)) .'">'. get_string('next') .'</a>)';
6306 $output .= '</div>';
6318 * This function is used to rebuild the <nolink> tag because some formats (PLAIN and WIKI)
6319 * will transform it to html entities
6321 * @param string $text Text to search for nolink tag in
6324 function rebuildnolinktag($text) {
6326 $text = preg_replace('/<(\/*nolink)>/i','<$1>',$text);
6332 * Prints a nice side block with an optional header. The content can either
6333 * be a block of HTML or a list of text with optional icons.
6335 * @param string $heading Block $title embedded in HTML tags, for example <h2>.
6336 * @param string $content ?
6337 * @param array $list ?
6338 * @param array $icons ?
6339 * @param string $footer ?
6340 * @param array $attributes ?
6341 * @param string $title Plain text title, as embedded in the $heading.
6342 * @todo Finish documenting this function. Show example of various attributes, etc.
6344 function print_side_block($heading='', $content='', $list=NULL, $icons=NULL, $footer='', $attributes = array(), $title='') {
6346 //Accessibility: skip block link, with title-text (or $block_id) to differentiate links.
6347 static $block_id = 0;
6349 if (empty($heading)) {
6350 $skip_text = get_string('skipblock', 'access').' '.$block_id;
6353 $skip_text = get_string('skipa', 'access', strip_tags($title));
6355 $skip_link = '<a href="#sb-'.$block_id.'" class="skip-block">'.$skip_text.'</a>';
6356 $skip_dest = '<span id="sb-'.$block_id.'" class="skip-block-to"></span>';
6358 if (! empty($heading)) {
6361 //ELSE: a single link on a page "Skip block 4" is too confusing - ignore.
6363 print_side_block_start($heading, $attributes);
6368 echo '<div class="footer">'. $footer .'</div>';
6373 //Accessibility: replaced unnecessary table with list, see themes/standard/styles_layout.css
6374 echo "\n<ul class='list'>\n";
6375 foreach ($list as $key => $string) {
6376 echo '<li class="r'. $row .'">';
6378 echo '<div class="icon column c0">'. $icons[$key] .'</div>';
6380 echo '<div class="column c1">'. $string .'</div>';
6387 echo '<div class="footer">'. $footer .'</div>';
6392 print_side_block_end($attributes, $title);
6397 * Starts a nice side block with an optional header.
6399 * @param string $heading ?
6400 * @param array $attributes ?
6401 * @todo Finish documenting this function
6403 function print_side_block_start($heading='', $attributes = array()) {
6405 global $CFG, $THEME;
6407 // If there are no special attributes, give a default CSS class
6408 if (empty($attributes) ||
!is_array($attributes)) {
6409 $attributes = array('class' => 'sideblock');
6411 } else if(!isset($attributes['class'])) {
6412 $attributes['class'] = 'sideblock';
6414 } else if(!strpos($attributes['class'], 'sideblock')) {
6415 $attributes['class'] .= ' sideblock';
6418 // OK, the class is surely there and in addition to anything
6419 // else, it's tagged as a sideblock
6423 // IE misery: if I do it this way, blocks which start hidden cannot be "unhidden"
6425 // If there is a cookie to hide this thing, start it hidden
6426 if (!empty($attributes['id']) && isset($_COOKIE['hide:'.$attributes['id']])) {
6427 $attributes['class'] = 'hidden '.$attributes['class'];
6432 foreach ($attributes as $attr => $val) {
6433 $attrtext .= ' '.$attr.'="'.$val.'"';
6436 echo '<div '.$attrtext.'>';
6438 if (!empty($THEME->customcorners
)) {
6439 echo '<div class="wrap">'."\n";
6442 //Accessibility: H2 more appropriate in moodleblock.class.php: _title_html.
6443 echo '<div class="header">';
6444 if (!empty($THEME->customcorners
)) {
6445 echo '<div class="bt"><div> </div></div>';
6446 echo '<div class="i1"><div class="i2">';
6447 echo '<div class="i3">';
6450 if (!empty($THEME->customcorners
)) {
6451 echo '</div></div></div>';
6455 if (!empty($THEME->customcorners
)) {
6456 echo '<div class="bt"><div> </div></div>';
6460 if (!empty($THEME->customcorners
)) {
6461 echo '<div class="i1"><div class="i2">';
6462 echo '<div class="i3">';
6464 echo '<div class="content">';
6470 * Print table ending tags for a side block box.
6472 function print_side_block_end($attributes = array(), $title='') {
6473 global $CFG, $THEME;
6477 if (!empty($THEME->customcorners
)) {
6478 echo '</div></div></div><div class="bb"><div> </div></div></div>';
6483 $strshow = addslashes_js(get_string('showblocka', 'access', strip_tags($title)));
6484 $strhide = addslashes_js(get_string('hideblocka', 'access', strip_tags($title)));
6486 // IE workaround: if I do it THIS way, it works! WTF?
6487 if (!empty($CFG->allowuserblockhiding
) && isset($attributes['id'])) {
6488 echo '<script type="text/javascript">'."\n//<![CDATA[\n".'elementCookieHide("'.$attributes['id'].
6489 '","'.$strshow.'","'.$strhide."\");\n//]]>\n".'</script>';
6496 * Prints out code needed for spellchecking.
6497 * Original idea by Ludo (Marc Alier).
6499 * Opening CDATA and <script> are output by weblib::use_html_editor()
6501 * @param boolean $usehtmleditor Normally set by $CFG->htmleditor, can be overriden here
6502 * @param boolean $return If false, echos the code instead of returning it
6503 * @todo Find out if lib/editor/htmlarea/htmlarea.class.php::print_speller_code() is still used, and delete if not
6505 function print_speller_code ($usehtmleditor=false, $return=false) {
6509 if(!$usehtmleditor) {
6510 $str .= 'function openSpellChecker() {'."\n";
6511 $str .= "\tvar speller = new spellChecker();\n";
6512 $str .= "\tspeller.popUpUrl = \"" . $CFG->httpswwwroot
."/lib/speller/spellchecker.html\";\n";
6513 $str .= "\tspeller.spellCheckScript = \"". $CFG->httpswwwroot
."/lib/speller/server-scripts/spellchecker.php\";\n";
6514 $str .= "\tspeller.spellCheckAll();\n";
6517 $str .= "function spellClickHandler(editor, buttonId) {\n";
6518 $str .= "\teditor._textArea.value = editor.getHTML();\n";
6519 $str .= "\tvar speller = new spellChecker( editor._textArea );\n";
6520 $str .= "\tspeller.popUpUrl = \"" . $CFG->httpswwwroot
."/lib/speller/spellchecker.html\";\n";
6521 $str .= "\tspeller.spellCheckScript = \"". $CFG->httpswwwroot
."/lib/speller/server-scripts/spellchecker.php\";\n";
6522 $str .= "\tspeller._moogle_edit=1;\n";
6523 $str .= "\tspeller._editor=editor;\n";
6524 $str .= "\tspeller.openChecker();\n";
6535 * Print button for spellchecking when editor is disabled
6537 function print_speller_button () {
6538 echo '<input type="button" value="Check spelling" onclick="openSpellChecker();" />'."\n";
6542 function page_id_and_class(&$getid, &$getclass) {
6543 // Create class and id for this page
6546 static $class = NULL;
6549 if (empty($CFG->pagepath
)) {
6550 $CFG->pagepath
= $ME;
6553 if (empty($class) ||
empty($id)) {
6554 $path = str_replace($CFG->httpswwwroot
.'/', '', $CFG->pagepath
); //Because the page could be HTTPSPAGEREQUIRED
6555 $path = str_replace('.php', '', $path);
6556 if (substr($path, -1) == '/') {
6559 if (empty($path) ||
$path == 'index') {
6562 } else if (substr($path, 0, 5) == 'admin') {
6563 $id = str_replace('/', '-', $path);
6566 $id = str_replace('/', '-', $path);
6567 $class = explode('-', $id);
6569 $class = implode('-', $class);
6578 * Prints a maintenance message from /maintenance.html
6580 function print_maintenance_message () {
6583 print_header(strip_tags($SITE->fullname
), $SITE->fullname
, 'home');
6584 print_simple_box_start('center');
6585 print_heading(get_string('sitemaintenance', 'admin'));
6586 @include
($CFG->dataroot
.'/1/maintenance.html');
6587 print_simple_box_end();
6592 * Adjust the list of allowed tags based on $CFG->allowobjectembed and user roles (admin)
6594 function adjust_allowed_tags() {
6596 global $CFG, $ALLOWED_TAGS;
6598 if (!empty($CFG->allowobjectembed
)) {
6599 $ALLOWED_TAGS .= '<embed><object>';
6603 /// Some code to print tabs
6605 /// A class for tabs
6610 var $linkedwhenselected;
6612 /// A constructor just because I like constructors
6613 function tabobject ($id, $link='', $text='', $title='', $linkedwhenselected=false) {
6615 $this->link
= $link;
6616 $this->text
= $text;
6617 $this->title
= $title ?
$title : $text;
6618 $this->linkedwhenselected
= $linkedwhenselected;
6625 * Returns a string containing a nested list, suitable for formatting into tabs with CSS.
6627 * @param array $tabrows An array of rows where each row is an array of tab objects
6628 * @param string $selected The id of the selected tab (whatever row it's on)
6629 * @param array $inactive An array of ids of inactive tabs that are not selectable.
6630 * @param array $activated An array of ids of other tabs that are currently activated
6632 function print_tabs($tabrows, $selected=NULL, $inactive=NULL, $activated=NULL, $return=false) {
6635 /// $inactive must be an array
6636 if (!is_array($inactive)) {
6637 $inactive = array();
6640 /// $activated must be an array
6641 if (!is_array($activated)) {
6642 $activated = array();
6645 /// Convert the tab rows into a tree that's easier to process
6646 if (!$tree = convert_tabrows_to_tree($tabrows, $selected, $inactive, $activated)) {
6650 /// Print out the current tree of tabs (this function is recursive)
6652 $output = convert_tree_to_html($tree);
6654 $output = "\n\n".'<div class="tabtree">'.$output.'</div><div class="clearer"> </div>'."\n\n";
6665 function convert_tree_to_html($tree, $row=0) {
6667 $str = "\n".'<ul class="tabrow'.$row.'">'."\n";
6670 $count = count($tree);
6672 foreach ($tree as $tab) {
6673 $count--; // countdown to zero
6677 if ($first && ($count == 0)) { // Just one in the row
6678 $liclass = 'first last';
6680 } else if ($first) {
6683 } else if ($count == 0) {
6687 if ((empty($tab->subtree
)) && (!empty($tab->selected
))) {
6688 $liclass .= (empty($liclass)) ?
'onerow' : ' onerow';
6691 if ($tab->inactive ||
$tab->active ||
$tab->selected
) {
6692 if ($tab->selected
) {
6693 $liclass .= (empty($liclass)) ?
'here selected' : ' here selected';
6694 } else if ($tab->active
) {
6695 $liclass .= (empty($liclass)) ?
'here active' : ' here active';
6699 $str .= (!empty($liclass)) ?
'<li class="'.$liclass.'">' : '<li>';
6701 if ($tab->inactive ||
$tab->active ||
($tab->selected
&& !$tab->linkedwhenselected
)) {
6702 // The a tag is used for styling
6703 $str .= '<a class="nolink"><span>'.$tab->text
.'</span></a>';
6705 $str .= '<a href="'.$tab->link
.'" title="'.$tab->title
.'"><span>'.$tab->text
.'</span></a>';
6708 if (!empty($tab->subtree
)) {
6709 $str .= convert_tree_to_html($tab->subtree
, $row+
1);
6710 } else if ($tab->selected
) {
6711 $str .= '<div class="tabrow'.($row+
1).' empty"> </div>'."\n";
6714 $str .= ' </li>'."\n";
6716 $str .= '</ul>'."\n";
6722 function convert_tabrows_to_tree($tabrows, $selected, $inactive, $activated) {
6724 /// Work backwards through the rows (bottom to top) collecting the tree as we go.
6726 $tabrows = array_reverse($tabrows);
6730 foreach ($tabrows as $row) {
6733 foreach ($row as $tab) {
6734 $tab->inactive
= in_array((string)$tab->id
, $inactive);
6735 $tab->active
= in_array((string)$tab->id
, $activated);
6736 $tab->selected
= (string)$tab->id
== $selected;
6738 if ($tab->active ||
$tab->selected
) {
6740 $tab->subtree
= $subtree;
6753 * Returns a string containing a link to the user documentation for the current
6754 * page. Also contains an icon by default. Shown to teachers and admin only.
6756 * @param string $text The text to be displayed for the link
6757 * @param string $iconpath The path to the icon to be displayed
6759 function page_doc_link($text='', $iconpath='') {
6760 global $ME, $COURSE, $CFG;
6762 if (empty($CFG->docroot
) or empty($CFG->rolesactive
)) {
6766 if (empty($COURSE->id
)) {
6767 $context = get_context_instance(CONTEXT_SYSTEM
);
6769 $context = get_context_instance(CONTEXT_COURSE
, $COURSE->id
);
6772 if (!has_capability('moodle/site:doclinks', $context)) {
6776 if (empty($CFG->pagepath
)) {
6777 $CFG->pagepath
= $ME;
6780 $path = str_replace($CFG->httpswwwroot
.'/','', $CFG->pagepath
); // Because the page could be HTTPSPAGEREQUIRED
6781 $path = str_replace('.php', '', $path);
6783 if (empty($path)) { // Not for home page
6786 return doc_link($path, $text, $iconpath);
6790 * Returns a string containing a link to the user documentation.
6791 * Also contains an icon by default. Shown to teachers and admin only.
6793 * @param string $path The page link after doc root and language, no
6795 * @param string $text The text to be displayed for the link
6796 * @param string $iconpath The path to the icon to be displayed
6798 function doc_link($path='', $text='', $iconpath='') {
6801 if (empty($CFG->docroot
)) {
6806 if (!empty($CFG->doctonewwindow
)) {
6807 $target = ' target="_blank"';
6810 $lang = str_replace('_utf8', '', current_language());
6812 $str = '<a href="' .$CFG->docroot
. '/' .$lang. '/' .$path. '"' .$target. '>';
6814 if (empty($iconpath)) {
6815 $iconpath = $CFG->httpswwwroot
. '/pix/docs.gif';
6818 // alt left blank intentionally to prevent repetition in screenreaders
6819 $str .= '<img class="iconhelp" src="' .$iconpath. '" alt="" />' .$text. '</a>';
6826 * Returns true if the current site debugging settings are equal or above specified level.
6827 * If passed a parameter it will emit a debugging notice similar to trigger_error(). The
6828 * routing of notices is controlled by $CFG->debugdisplay
6831 * 1) debugging('a normal debug notice');
6832 * 2) debugging('something really picky', DEBUG_ALL);
6833 * 3) debugging('annoying debug message only for develpers', DEBUG_DEVELOPER);
6834 * 4) if (debugging()) { perform extra debugging operations (do not use print or echo) }
6836 * In code blocks controlled by debugging() (such as example 4)
6837 * any output should be routed via debugging() itself, or the lower-level
6838 * trigger_error() or error_log(). Using echo or print will break XHTML
6839 * JS and HTTP headers.
6842 * @param string $message a message to print
6843 * @param int $level the level at which this debugging statement should show
6846 function debugging($message='', $level=DEBUG_NORMAL
) {
6850 if (empty($CFG->debug
)) {
6854 if ($CFG->debug
>= $level) {
6856 $callers = debug_backtrace();
6857 $from = '<ul style="text-align: left">';
6858 foreach ($callers as $caller) {
6859 if (!isset($caller['line'])) {
6860 $caller['line'] = '?'; // probably call_user_func()
6862 if (!isset($caller['file'])) {
6863 $caller['file'] = $CFG->dirroot
.'/unknownfile'; // probably call_user_func()
6865 $from .= '<li>line ' . $caller['line'] . ' of ' . substr($caller['file'], strlen($CFG->dirroot
) +
1);
6866 if (isset($caller['function'])) {
6867 $from .= ': call to ';
6868 if (isset($caller['class'])) {
6869 $from .= $caller['class'] . $caller['type'];
6871 $from .= $caller['function'] . '()';
6876 if (!isset($CFG->debugdisplay
)) {
6877 $CFG->debugdisplay
= ini_get('display_errors');
6879 if ($CFG->debugdisplay
) {
6880 if (!defined('DEBUGGING_PRINTED')) {
6881 define('DEBUGGING_PRINTED', 1); // indicates we have printed something
6883 notify($message . $from, 'notifytiny');
6885 trigger_error($message . $from, E_USER_NOTICE
);
6894 * Disable debug messages from debugging(), while keeping PHP error reporting level as is.
6896 function disable_debugging() {
6898 $CFG->debug
= $CFG->debug |
0x80000000; // switch the sign bit in integer number ;-)
6903 * Returns string to add a frame attribute, if required
6905 function frametarget() {
6908 if (empty($CFG->framename
) or ($CFG->framename
== '_top')) {
6911 return ' target="'.$CFG->framename
.'" ';
6916 * Outputs a HTML comment to the browser. This is used for those hard-to-debug
6917 * pages that use bits from many different files in very confusing ways (e.g. blocks).
6918 * @usage print_location_comment(__FILE__, __LINE__);
6919 * @param string $file
6920 * @param integer $line
6921 * @param boolean $return Whether to return or print the comment
6922 * @return mixed Void unless true given as third parameter
6924 function print_location_comment($file, $line, $return = false)
6927 return "<!-- $file at line $line -->\n";
6929 echo "<!-- $file at line $line -->\n";
6935 * Returns an image of an up or down arrow, used for column sorting. To avoid unnecessary DB accesses, please
6936 * provide this function with the language strings for sortasc and sortdesc.
6937 * If no sort string is associated with the direction, an arrow with no alt text will be printed/returned.
6938 * @param string $direction 'up' or 'down'
6939 * @param string $strsort The language string used for the alt attribute of this image
6940 * @param bool $return Whether to print directly or return the html string
6941 * @return string HTML for the image
6943 * TODO See if this isn't already defined somewhere. If not, move this to weblib
6945 function print_arrow($direction='up', $strsort=null, $return=false) {
6948 if (!in_array($direction, array('up', 'down', 'right', 'left', 'move'))) {
6954 switch ($direction) {
6969 // Prepare language string
6971 if (empty($strsort) && !empty($sortdir)) {
6972 $strsort = get_string('sort' . $sortdir, 'grades');
6975 $return = ' <img src="'.$CFG->pixpath
.'/t/' . $direction . '.gif" alt="'.$strsort.'" /> ';
6985 * Returns boolean true if the current language is right-to-left (Hebrew, Arabic etc)
6988 function right_to_left() {
6991 if (isset($result)) {
6994 return $result = (get_string('thisdirection') == 'rtl');
6999 * Returns swapped left<=>right if in RTL environment.
7000 * part of RTL support
7002 * @param string $align align to check
7005 function fix_align_rtl($align) {
7006 if (!right_to_left()) {
7009 if ($align=='left') { return 'right'; }
7010 if ($align=='right') { return 'left'; }
7016 * Returns true if the page is displayed in a popup window.
7017 * Gets the information from the URL parameter inpopup.
7021 * TODO Use a central function to create the popup calls allover Moodle and
7022 * TODO In the moment only works with resources and probably questions.
7024 function is_in_popup() {
7025 $inpopup = optional_param('inpopup', '', PARAM_BOOL
);
7031 // vim:autoindent:expandtab:shiftwidth=4:tabstop=4:tw=140: